blob: d36967fdcfe1f996c26ca0644e96593be5df9f7e [file] [log] [blame]
Chris Lattner9bc02a42003-05-13 21:37:02 +00001//===-- Constants.cpp - Implement Constant nodes --------------------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner00950542001-06-06 20:29:01 +00009//
Chris Lattnereb59ca92011-02-07 20:03:14 +000010// This file implements the Constant* classes.
Chris Lattner00950542001-06-06 20:29:01 +000011//
12//===----------------------------------------------------------------------===//
13
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000014#include "llvm/IR/Constants.h"
Chris Lattner92f6fea2007-02-27 03:05:06 +000015#include "ConstantFold.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000016#include "LLVMContextImpl.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000017#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/SmallVector.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000019#include "llvm/ADT/StringMap.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000020#include "llvm/IR/DerivedTypes.h"
Chandler Carruthbd7cba02014-03-04 10:40:04 +000021#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000022#include "llvm/IR/GlobalValue.h"
23#include "llvm/IR/Instructions.h"
24#include "llvm/IR/Module.h"
25#include "llvm/IR/Operator.h"
Bill Wendling2e3def12006-11-17 08:03:48 +000026#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000027#include "llvm/Support/ErrorHandling.h"
Chris Lattner8a94bf12006-09-28 00:35:06 +000028#include "llvm/Support/ManagedStatic.h"
Bill Wendling2e3def12006-11-17 08:03:48 +000029#include "llvm/Support/MathExtras.h"
Chris Lattner37f077a2009-08-23 04:02:03 +000030#include "llvm/Support/raw_ostream.h"
Chris Lattner00950542001-06-06 20:29:01 +000031#include <algorithm>
Serge Gueltond35f86e2017-05-09 19:31:13 +000032
Chris Lattner31f84992003-11-21 20:23:48 +000033using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000034
Chris Lattner00950542001-06-06 20:29:01 +000035//===----------------------------------------------------------------------===//
Chris Lattnere9bb2df2001-12-03 22:26:30 +000036// Constant Class
Chris Lattner00950542001-06-06 20:29:01 +000037//===----------------------------------------------------------------------===//
38
Chris Lattnerb4473872011-07-15 05:58:04 +000039bool Constant::isNegativeZeroValue() const {
40 // Floating point values have an explicit -0.0 value.
41 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
42 return CFP->isZero() && CFP->isNegative();
Galina Kistanovaa46517e2012-07-13 01:25:27 +000043
David Tweedec7eb552013-03-18 11:54:44 +000044 // Equivalent for a vector of -0.0's.
45 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
Craig Topperfce91792017-07-15 22:06:19 +000046 if (CV->getElementType()->isFloatingPointTy() && CV->isSplat())
47 if (CV->getElementAsAPFloat(0).isNegZero())
David Tweedec7eb552013-03-18 11:54:44 +000048 return true;
49
Owen Anderson108258a2015-11-20 22:34:48 +000050 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
51 if (ConstantFP *SplatCFP = dyn_cast_or_null<ConstantFP>(CV->getSplatValue()))
52 if (SplatCFP && SplatCFP->isZero() && SplatCFP->isNegative())
53 return true;
54
David Tweed974cdfb2013-03-19 10:16:40 +000055 // We've already handled true FP case; any other FP vectors can't represent -0.0.
56 if (getType()->isFPOrFPVectorTy())
57 return false;
David Tweedec7eb552013-03-18 11:54:44 +000058
Chris Lattnerb4473872011-07-15 05:58:04 +000059 // Otherwise, just use +0.0.
60 return isNullValue();
61}
62
Shuxin Yangc3d6de22013-01-09 00:53:25 +000063// Return true iff this constant is positive zero (floating point), negative
64// zero (floating point), or a null value.
Shuxin Yang935e35d2013-01-09 00:13:41 +000065bool Constant::isZeroValue() const {
66 // Floating point values have an explicit -0.0 value.
67 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
68 return CFP->isZero();
69
Owen Anderson3f9c2902015-11-20 08:16:13 +000070 // Equivalent for a vector of -0.0's.
71 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
Craig Topperfce91792017-07-15 22:06:19 +000072 if (CV->getElementType()->isFloatingPointTy() && CV->isSplat())
73 if (CV->getElementAsAPFloat(0).isZero())
Owen Anderson3f9c2902015-11-20 08:16:13 +000074 return true;
75
Owen Anderson108258a2015-11-20 22:34:48 +000076 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
77 if (ConstantFP *SplatCFP = dyn_cast_or_null<ConstantFP>(CV->getSplatValue()))
78 if (SplatCFP && SplatCFP->isZero())
79 return true;
80
Shuxin Yang935e35d2013-01-09 00:13:41 +000081 // Otherwise, just use +0.0.
82 return isNullValue();
83}
84
Chris Lattner032c6eb2011-07-15 06:14:08 +000085bool Constant::isNullValue() const {
86 // 0 is null.
87 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
88 return CI->isZero();
Galina Kistanovaa46517e2012-07-13 01:25:27 +000089
Chris Lattner032c6eb2011-07-15 06:14:08 +000090 // +0.0 is null.
91 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
92 return CFP->isZero() && !CFP->isNegative();
93
David Majnemer83fc12a2015-11-11 21:57:16 +000094 // constant zero is zero for aggregates, cpnull is null for pointers, none for
95 // tokens.
96 return isa<ConstantAggregateZero>(this) || isa<ConstantPointerNull>(this) ||
97 isa<ConstantTokenNone>(this);
Chris Lattner032c6eb2011-07-15 06:14:08 +000098}
99
Nadav Rotem4c7c0f22011-08-24 20:18:38 +0000100bool Constant::isAllOnesValue() const {
101 // Check for -1 integers
102 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
103 return CI->isMinusOne();
104
105 // Check for FP which are bitcasted from -1 integers
106 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
107 return CFP->getValueAPF().bitcastToAPInt().isAllOnesValue();
108
Benjamin Kramerb518cae2011-11-14 19:12:20 +0000109 // Check for constant vectors which are splats of -1 values.
Nadav Rotem4c7c0f22011-08-24 20:18:38 +0000110 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
Benjamin Kramerb518cae2011-11-14 19:12:20 +0000111 if (Constant *Splat = CV->getSplatValue())
112 return Splat->isAllOnesValue();
Nadav Rotem4c7c0f22011-08-24 20:18:38 +0000113
Chris Lattnere150e2d2012-01-26 02:31:22 +0000114 // Check for constant vectors which are splats of -1 values.
Craig Topperfce91792017-07-15 22:06:19 +0000115 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this)) {
116 if (CV->isSplat()) {
117 if (CV->getElementType()->isFloatingPointTy())
118 return CV->getElementAsAPFloat(0).bitcastToAPInt().isAllOnesValue();
119 return CV->getElementAsAPInt(0).isAllOnesValue();
120 }
121 }
Chris Lattnere150e2d2012-01-26 02:31:22 +0000122
Nadav Rotem4c7c0f22011-08-24 20:18:38 +0000123 return false;
124}
Benjamin Kramerb518cae2011-11-14 19:12:20 +0000125
David Majnemer3bbb4b12014-08-16 09:23:42 +0000126bool Constant::isOneValue() const {
127 // Check for 1 integers
128 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
129 return CI->isOne();
130
131 // Check for FP which are bitcasted from 1 integers
132 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
Craig Topperc68553c2017-06-07 00:58:02 +0000133 return CFP->getValueAPF().bitcastToAPInt().isOneValue();
David Majnemer3bbb4b12014-08-16 09:23:42 +0000134
135 // Check for constant vectors which are splats of 1 values.
136 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
137 if (Constant *Splat = CV->getSplatValue())
138 return Splat->isOneValue();
139
140 // Check for constant vectors which are splats of 1 values.
Craig Topperfce91792017-07-15 22:06:19 +0000141 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this)) {
142 if (CV->isSplat()) {
143 if (CV->getElementType()->isFloatingPointTy())
144 return CV->getElementAsAPFloat(0).bitcastToAPInt().isOneValue();
145 return CV->getElementAsAPInt(0).isOneValue();
146 }
147 }
David Majnemer3bbb4b12014-08-16 09:23:42 +0000148
149 return false;
150}
151
David Majnemer5f5939c2014-07-02 06:07:09 +0000152bool Constant::isMinSignedValue() const {
153 // Check for INT_MIN integers
154 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
155 return CI->isMinValue(/*isSigned=*/true);
156
157 // Check for FP which are bitcasted from INT_MIN integers
158 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
159 return CFP->getValueAPF().bitcastToAPInt().isMinSignedValue();
160
161 // Check for constant vectors which are splats of INT_MIN values.
162 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
163 if (Constant *Splat = CV->getSplatValue())
164 return Splat->isMinSignedValue();
165
166 // Check for constant vectors which are splats of INT_MIN values.
Craig Topperfce91792017-07-15 22:06:19 +0000167 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this)) {
168 if (CV->isSplat()) {
169 if (CV->getElementType()->isFloatingPointTy())
170 return CV->getElementAsAPFloat(0).bitcastToAPInt().isMinSignedValue();
171 return CV->getElementAsAPInt(0).isMinSignedValue();
172 }
173 }
David Majnemer5f5939c2014-07-02 06:07:09 +0000174
175 return false;
176}
177
David Majnemer0e4fc412014-08-22 16:41:23 +0000178bool Constant::isNotMinSignedValue() const {
179 // Check for INT_MIN integers
180 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
181 return !CI->isMinValue(/*isSigned=*/true);
182
183 // Check for FP which are bitcasted from INT_MIN integers
184 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
185 return !CFP->getValueAPF().bitcastToAPInt().isMinSignedValue();
186
Nikita Popov9ecb9082018-12-01 10:58:34 +0000187 // Check that vectors don't contain INT_MIN
188 if (this->getType()->isVectorTy()) {
189 unsigned NumElts = this->getType()->getVectorNumElements();
190 for (unsigned i = 0; i != NumElts; ++i) {
191 Constant *Elt = this->getAggregateElement(i);
192 if (!Elt || !Elt->isNotMinSignedValue())
193 return false;
Craig Topperfce91792017-07-15 22:06:19 +0000194 }
Nikita Popov9ecb9082018-12-01 10:58:34 +0000195 return true;
Craig Topperfce91792017-07-15 22:06:19 +0000196 }
David Majnemer0e4fc412014-08-22 16:41:23 +0000197
198 // It *may* contain INT_MIN, we can't tell.
199 return false;
200}
201
Sanjay Patel8afcfc32018-02-16 22:32:54 +0000202bool Constant::isFiniteNonZeroFP() const {
203 if (auto *CFP = dyn_cast<ConstantFP>(this))
204 return CFP->getValueAPF().isFiniteNonZero();
205 if (!getType()->isVectorTy())
206 return false;
207 for (unsigned i = 0, e = getType()->getVectorNumElements(); i != e; ++i) {
208 auto *CFP = dyn_cast_or_null<ConstantFP>(this->getAggregateElement(i));
209 if (!CFP || !CFP->getValueAPF().isFiniteNonZero())
210 return false;
211 }
212 return true;
213}
214
215bool Constant::isNormalFP() const {
216 if (auto *CFP = dyn_cast<ConstantFP>(this))
217 return CFP->getValueAPF().isNormal();
218 if (!getType()->isVectorTy())
219 return false;
220 for (unsigned i = 0, e = getType()->getVectorNumElements(); i != e; ++i) {
221 auto *CFP = dyn_cast_or_null<ConstantFP>(this->getAggregateElement(i));
222 if (!CFP || !CFP->getValueAPF().isNormal())
223 return false;
224 }
225 return true;
226}
227
Sanjay Patelc1de3c62018-02-20 16:08:15 +0000228bool Constant::hasExactInverseFP() const {
229 if (auto *CFP = dyn_cast<ConstantFP>(this))
230 return CFP->getValueAPF().getExactInverse(nullptr);
231 if (!getType()->isVectorTy())
232 return false;
233 for (unsigned i = 0, e = getType()->getVectorNumElements(); i != e; ++i) {
234 auto *CFP = dyn_cast_or_null<ConstantFP>(this->getAggregateElement(i));
235 if (!CFP || !CFP->getValueAPF().getExactInverse(nullptr))
236 return false;
237 }
238 return true;
239}
240
Sanjay Patel1629c232018-03-02 18:36:08 +0000241bool Constant::isNaN() const {
242 if (auto *CFP = dyn_cast<ConstantFP>(this))
243 return CFP->isNaN();
244 if (!getType()->isVectorTy())
245 return false;
246 for (unsigned i = 0, e = getType()->getVectorNumElements(); i != e; ++i) {
247 auto *CFP = dyn_cast_or_null<ConstantFP>(this->getAggregateElement(i));
248 if (!CFP || !CFP->isNaN())
249 return false;
250 }
251 return true;
252}
253
Sanjay Patel58b0c382018-07-06 14:52:36 +0000254bool Constant::containsUndefElement() const {
255 if (!getType()->isVectorTy())
256 return false;
257 for (unsigned i = 0, e = getType()->getVectorNumElements(); i != e; ++i)
258 if (isa<UndefValue>(getAggregateElement(i)))
259 return true;
260
261 return false;
262}
263
Sanjay Patel0ac37a42016-04-29 22:03:27 +0000264/// Constructor to create a '0' constant of arbitrary type.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000265Constant *Constant::getNullValue(Type *Ty) {
Owen Andersona7235ea2009-07-31 20:28:14 +0000266 switch (Ty->getTypeID()) {
267 case Type::IntegerTyID:
268 return ConstantInt::get(Ty, 0);
Dan Gohmance163392011-12-17 00:04:22 +0000269 case Type::HalfTyID:
270 return ConstantFP::get(Ty->getContext(),
Stephan Bergmann20a600c2016-12-14 11:57:17 +0000271 APFloat::getZero(APFloat::IEEEhalf()));
Owen Andersona7235ea2009-07-31 20:28:14 +0000272 case Type::FloatTyID:
Benjamin Kramer98383962010-12-04 14:22:24 +0000273 return ConstantFP::get(Ty->getContext(),
Stephan Bergmann20a600c2016-12-14 11:57:17 +0000274 APFloat::getZero(APFloat::IEEEsingle()));
Owen Andersona7235ea2009-07-31 20:28:14 +0000275 case Type::DoubleTyID:
Benjamin Kramer98383962010-12-04 14:22:24 +0000276 return ConstantFP::get(Ty->getContext(),
Stephan Bergmann20a600c2016-12-14 11:57:17 +0000277 APFloat::getZero(APFloat::IEEEdouble()));
Owen Andersona7235ea2009-07-31 20:28:14 +0000278 case Type::X86_FP80TyID:
Benjamin Kramer98383962010-12-04 14:22:24 +0000279 return ConstantFP::get(Ty->getContext(),
Stephan Bergmann20a600c2016-12-14 11:57:17 +0000280 APFloat::getZero(APFloat::x87DoubleExtended()));
Owen Andersona7235ea2009-07-31 20:28:14 +0000281 case Type::FP128TyID:
282 return ConstantFP::get(Ty->getContext(),
Stephan Bergmann20a600c2016-12-14 11:57:17 +0000283 APFloat::getZero(APFloat::IEEEquad()));
Owen Andersona7235ea2009-07-31 20:28:14 +0000284 case Type::PPC_FP128TyID:
Benjamin Kramer98383962010-12-04 14:22:24 +0000285 return ConstantFP::get(Ty->getContext(),
Stephan Bergmann20a600c2016-12-14 11:57:17 +0000286 APFloat(APFloat::PPCDoubleDouble(),
Tim Northover0a29cb02013-01-22 09:46:31 +0000287 APInt::getNullValue(128)));
Owen Andersona7235ea2009-07-31 20:28:14 +0000288 case Type::PointerTyID:
289 return ConstantPointerNull::get(cast<PointerType>(Ty));
290 case Type::StructTyID:
291 case Type::ArrayTyID:
292 case Type::VectorTyID:
293 return ConstantAggregateZero::get(Ty);
David Majnemer83fc12a2015-11-11 21:57:16 +0000294 case Type::TokenTyID:
295 return ConstantTokenNone::get(Ty->getContext());
Owen Andersona7235ea2009-07-31 20:28:14 +0000296 default:
297 // Function, Label, or Opaque type?
Craig Topper50bee422012-02-05 22:14:15 +0000298 llvm_unreachable("Cannot create a null constant of that type!");
Owen Andersona7235ea2009-07-31 20:28:14 +0000299 }
300}
301
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000302Constant *Constant::getIntegerValue(Type *Ty, const APInt &V) {
303 Type *ScalarTy = Ty->getScalarType();
Dan Gohman43ee5f72009-08-03 22:07:33 +0000304
305 // Create the base integer constant.
306 Constant *C = ConstantInt::get(Ty->getContext(), V);
307
308 // Convert an integer to a pointer, if necessary.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000309 if (PointerType *PTy = dyn_cast<PointerType>(ScalarTy))
Dan Gohman43ee5f72009-08-03 22:07:33 +0000310 C = ConstantExpr::getIntToPtr(C, PTy);
311
312 // Broadcast a scalar to a vector, if necessary.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000313 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattner3c2c9542012-01-25 05:19:54 +0000314 C = ConstantVector::getSplat(VTy->getNumElements(), C);
Dan Gohman43ee5f72009-08-03 22:07:33 +0000315
316 return C;
317}
318
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000319Constant *Constant::getAllOnesValue(Type *Ty) {
320 if (IntegerType *ITy = dyn_cast<IntegerType>(Ty))
Owen Andersona7235ea2009-07-31 20:28:14 +0000321 return ConstantInt::get(Ty->getContext(),
322 APInt::getAllOnesValue(ITy->getBitWidth()));
Nadav Rotem093399c2011-02-17 21:22:27 +0000323
324 if (Ty->isFloatingPointTy()) {
325 APFloat FL = APFloat::getAllOnesValue(Ty->getPrimitiveSizeInBits(),
326 !Ty->isPPC_FP128Ty());
327 return ConstantFP::get(Ty->getContext(), FL);
328 }
329
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000330 VectorType *VTy = cast<VectorType>(Ty);
Chris Lattner3c2c9542012-01-25 05:19:54 +0000331 return ConstantVector::getSplat(VTy->getNumElements(),
332 getAllOnesValue(VTy->getElementType()));
Owen Andersona7235ea2009-07-31 20:28:14 +0000333}
334
Chris Lattner3d5ed222012-01-25 06:16:32 +0000335Constant *Constant::getAggregateElement(unsigned Elt) const {
Duncan P. N. Exon Smithd7773c02016-04-05 21:10:45 +0000336 if (const ConstantAggregate *CC = dyn_cast<ConstantAggregate>(this))
337 return Elt < CC->getNumOperands() ? CC->getOperand(Elt) : nullptr;
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000338
David Majnemer6de0a122015-02-16 04:02:09 +0000339 if (const ConstantAggregateZero *CAZ = dyn_cast<ConstantAggregateZero>(this))
340 return Elt < CAZ->getNumElements() ? CAZ->getElementValue(Elt) : nullptr;
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000341
Chris Lattner3d5ed222012-01-25 06:16:32 +0000342 if (const UndefValue *UV = dyn_cast<UndefValue>(this))
David Majnemer6de0a122015-02-16 04:02:09 +0000343 return Elt < UV->getNumElements() ? UV->getElementValue(Elt) : nullptr;
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000344
Chris Lattner230cdab2012-01-26 00:42:34 +0000345 if (const ConstantDataSequential *CDS =dyn_cast<ConstantDataSequential>(this))
Craig Topperec0f0bc2014-04-09 06:08:46 +0000346 return Elt < CDS->getNumElements() ? CDS->getElementAsConstant(Elt)
347 : nullptr;
348 return nullptr;
Chris Lattner3d5ed222012-01-25 06:16:32 +0000349}
350
351Constant *Constant::getAggregateElement(Constant *Elt) const {
352 assert(isa<IntegerType>(Elt->getType()) && "Index must be an integer");
Florian Hahn41d83af2018-12-12 02:22:12 +0000353 if (ConstantInt *CI = dyn_cast<ConstantInt>(Elt)) {
354 // Check if the constant fits into an uint64_t.
355 if (CI->getValue().getActiveBits() > 64)
356 return nullptr;
Chris Lattner3d5ed222012-01-25 06:16:32 +0000357 return getAggregateElement(CI->getZExtValue());
Florian Hahn41d83af2018-12-12 02:22:12 +0000358 }
Craig Topperec0f0bc2014-04-09 06:08:46 +0000359 return nullptr;
Chris Lattner3d5ed222012-01-25 06:16:32 +0000360}
361
Pete Cooperd6218122015-06-23 21:55:11 +0000362void Constant::destroyConstant() {
363 /// First call destroyConstantImpl on the subclass. This gives the subclass
364 /// a chance to remove the constant from any maps/pools it's contained in.
365 switch (getValueID()) {
366 default:
367 llvm_unreachable("Not a constant!");
368#define HANDLE_CONSTANT(Name) \
369 case Value::Name##Val: \
370 cast<Name>(this)->destroyConstantImpl(); \
371 break;
372#include "llvm/IR/Value.def"
373 }
Chris Lattner3d5ed222012-01-25 06:16:32 +0000374
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000375 // When a Constant is destroyed, there may be lingering
Chris Lattnerf5ec48d2001-10-13 06:57:33 +0000376 // references to the constant by other constants in the constant pool. These
Misha Brukmanef6a6a62003-08-21 22:14:26 +0000377 // constants are implicitly dependent on the module that is being deleted,
Chris Lattnerf5ec48d2001-10-13 06:57:33 +0000378 // but they don't know that. Because we only find out when the CPV is
379 // deleted, we must now notify all of our users (that should only be
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000380 // Constants) that they are, in fact, invalid now and should be deleted.
Chris Lattnerf5ec48d2001-10-13 06:57:33 +0000381 //
382 while (!use_empty()) {
Chandler Carruth36b699f2014-03-09 03:16:01 +0000383 Value *V = user_back();
Pete Cooperd6218122015-06-23 21:55:11 +0000384#ifndef NDEBUG // Only in -g mode...
Chris Lattner37f077a2009-08-23 04:02:03 +0000385 if (!isa<Constant>(V)) {
David Greened2e63b72010-01-05 01:29:19 +0000386 dbgs() << "While deleting: " << *this
Pete Cooperd6218122015-06-23 21:55:11 +0000387 << "\n\nUse still stuck around after Def is destroyed: " << *V
388 << "\n\n";
Chris Lattner37f077a2009-08-23 04:02:03 +0000389 }
Chris Lattnerf5ec48d2001-10-13 06:57:33 +0000390#endif
Vikram S. Adve345e0cf2002-07-14 23:13:17 +0000391 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
Chris Lattner230cdab2012-01-26 00:42:34 +0000392 cast<Constant>(V)->destroyConstant();
Chris Lattnerf5ec48d2001-10-13 06:57:33 +0000393
394 // The constant should remove itself from our use list...
Chandler Carruth36b699f2014-03-09 03:16:01 +0000395 assert((use_empty() || user_back() != V) && "Constant not removed!");
Chris Lattnerf5ec48d2001-10-13 06:57:33 +0000396 }
397
398 // Value has no outstanding references it is safe to delete it now...
399 delete this;
Chris Lattner1d87bcf2001-10-01 20:11:19 +0000400}
Chris Lattner00950542001-06-06 20:29:01 +0000401
Benjamin Kramer88486802013-04-13 12:53:18 +0000402static bool canTrapImpl(const Constant *C,
Craig Topper431bdfc2014-08-21 05:55:13 +0000403 SmallPtrSetImpl<const ConstantExpr *> &NonTrappingOps) {
Benjamin Kramer88486802013-04-13 12:53:18 +0000404 assert(C->getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
Chris Lattner35b89fa2006-10-20 00:27:06 +0000405 // The only thing that could possibly trap are constant exprs.
Benjamin Kramer88486802013-04-13 12:53:18 +0000406 const ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
407 if (!CE)
408 return false;
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000409
410 // ConstantExpr traps if any operands can trap.
Benjamin Kramer88486802013-04-13 12:53:18 +0000411 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
412 if (ConstantExpr *Op = dyn_cast<ConstantExpr>(CE->getOperand(i))) {
David Blaikie5401ba72014-11-19 07:49:26 +0000413 if (NonTrappingOps.insert(Op).second && canTrapImpl(Op, NonTrappingOps))
Benjamin Kramer88486802013-04-13 12:53:18 +0000414 return true;
415 }
416 }
Chris Lattner35b89fa2006-10-20 00:27:06 +0000417
418 // Otherwise, only specific operations can trap.
419 switch (CE->getOpcode()) {
420 default:
421 return false;
Reid Spencer1628cec2006-10-26 06:15:43 +0000422 case Instruction::UDiv:
423 case Instruction::SDiv:
Reid Spencer0a783f72006-11-02 01:53:59 +0000424 case Instruction::URem:
425 case Instruction::SRem:
Chris Lattner35b89fa2006-10-20 00:27:06 +0000426 // Div and rem can trap if the RHS is not known to be non-zero.
Chris Lattner0eeb9132009-10-28 05:14:34 +0000427 if (!isa<ConstantInt>(CE->getOperand(1)) ||CE->getOperand(1)->isNullValue())
Chris Lattner35b89fa2006-10-20 00:27:06 +0000428 return true;
429 return false;
430 }
431}
432
Benjamin Kramer88486802013-04-13 12:53:18 +0000433bool Constant::canTrap() const {
434 SmallPtrSet<const ConstantExpr *, 4> NonTrappingOps;
435 return canTrapImpl(this, NonTrappingOps);
436}
437
Hans Wennborg160dcf52014-06-20 00:38:12 +0000438/// Check if C contains a GlobalValue for which Predicate is true.
439static bool
440ConstHasGlobalValuePredicate(const Constant *C,
441 bool (*Predicate)(const GlobalValue *)) {
442 SmallPtrSet<const Constant *, 8> Visited;
443 SmallVector<const Constant *, 8> WorkList;
444 WorkList.push_back(C);
445 Visited.insert(C);
Hans Wennborg18398582012-11-15 11:40:00 +0000446
447 while (!WorkList.empty()) {
Hans Wennborg160dcf52014-06-20 00:38:12 +0000448 const Constant *WorkItem = WorkList.pop_back_val();
449 if (const auto *GV = dyn_cast<GlobalValue>(WorkItem))
450 if (Predicate(GV))
Hans Wennborg18398582012-11-15 11:40:00 +0000451 return true;
Hans Wennborg160dcf52014-06-20 00:38:12 +0000452 for (const Value *Op : WorkItem->operands()) {
453 const Constant *ConstOp = dyn_cast<Constant>(Op);
454 if (!ConstOp)
Hans Wennborgfbeb9562012-11-16 10:33:25 +0000455 continue;
David Blaikie5401ba72014-11-19 07:49:26 +0000456 if (Visited.insert(ConstOp).second)
Hans Wennborg160dcf52014-06-20 00:38:12 +0000457 WorkList.push_back(ConstOp);
Hans Wennborg18398582012-11-15 11:40:00 +0000458 }
459 }
Hans Wennborg18398582012-11-15 11:40:00 +0000460 return false;
461}
462
Hans Wennborg160dcf52014-06-20 00:38:12 +0000463bool Constant::isThreadDependent() const {
464 auto DLLImportPredicate = [](const GlobalValue *GV) {
465 return GV->isThreadLocal();
466 };
467 return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
468}
469
470bool Constant::isDLLImportDependent() const {
471 auto DLLImportPredicate = [](const GlobalValue *GV) {
472 return GV->hasDLLImportStorageClass();
473 };
474 return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
475}
476
Chris Lattner4a7642e2009-11-01 18:11:50 +0000477bool Constant::isConstantUsed() const {
Chandler Carruth36b699f2014-03-09 03:16:01 +0000478 for (const User *U : users()) {
479 const Constant *UC = dyn_cast<Constant>(U);
Craig Topperec0f0bc2014-04-09 06:08:46 +0000480 if (!UC || isa<GlobalValue>(UC))
Chris Lattner4a7642e2009-11-01 18:11:50 +0000481 return true;
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000482
Chris Lattner4a7642e2009-11-01 18:11:50 +0000483 if (UC->isConstantUsed())
484 return true;
485 }
486 return false;
487}
488
Rafael Espindola8dcaa9f2015-11-17 00:51:23 +0000489bool Constant::needsRelocation() const {
490 if (isa<GlobalValue>(this))
491 return true; // Global reference.
492
Chris Lattner5d81bef2009-10-28 04:12:16 +0000493 if (const BlockAddress *BA = dyn_cast<BlockAddress>(this))
Rafael Espindola8dcaa9f2015-11-17 00:51:23 +0000494 return BA->getFunction()->needsRelocation();
495
Chris Lattner5099b312010-01-03 18:09:40 +0000496 // While raw uses of blockaddress need to be relocated, differences between
497 // two of them don't when they are for labels in the same function. This is a
498 // common idiom when creating a table for the indirect goto extension, so we
499 // handle it efficiently here.
500 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(this))
501 if (CE->getOpcode() == Instruction::Sub) {
502 ConstantExpr *LHS = dyn_cast<ConstantExpr>(CE->getOperand(0));
503 ConstantExpr *RHS = dyn_cast<ConstantExpr>(CE->getOperand(1));
Rafael Espindola8dcaa9f2015-11-17 00:51:23 +0000504 if (LHS && RHS && LHS->getOpcode() == Instruction::PtrToInt &&
Chris Lattner5099b312010-01-03 18:09:40 +0000505 RHS->getOpcode() == Instruction::PtrToInt &&
506 isa<BlockAddress>(LHS->getOperand(0)) &&
507 isa<BlockAddress>(RHS->getOperand(0)) &&
508 cast<BlockAddress>(LHS->getOperand(0))->getFunction() ==
Rafael Espindola8dcaa9f2015-11-17 00:51:23 +0000509 cast<BlockAddress>(RHS->getOperand(0))->getFunction())
510 return false;
Chris Lattner5099b312010-01-03 18:09:40 +0000511 }
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000512
Rafael Espindola8dcaa9f2015-11-17 00:51:23 +0000513 bool Result = false;
Evan Chengafe15812007-03-08 00:59:12 +0000514 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
Rafael Espindola8dcaa9f2015-11-17 00:51:23 +0000515 Result |= cast<Constant>(getOperand(i))->needsRelocation();
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000516
Chris Lattner7cf12c72009-07-22 00:05:44 +0000517 return Result;
Evan Chengafe15812007-03-08 00:59:12 +0000518}
519
Sanjay Patel0ac37a42016-04-29 22:03:27 +0000520/// If the specified constantexpr is dead, remove it. This involves recursively
521/// eliminating any dead users of the constantexpr.
Chris Lattner13fb0db2011-02-18 04:41:42 +0000522static bool removeDeadUsersOfConstant(const Constant *C) {
523 if (isa<GlobalValue>(C)) return false; // Cannot remove this
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000524
Chris Lattner13fb0db2011-02-18 04:41:42 +0000525 while (!C->use_empty()) {
Chandler Carruth36b699f2014-03-09 03:16:01 +0000526 const Constant *User = dyn_cast<Constant>(C->user_back());
Chris Lattner13fb0db2011-02-18 04:41:42 +0000527 if (!User) return false; // Non-constant usage;
528 if (!removeDeadUsersOfConstant(User))
529 return false; // Constant wasn't dead
530 }
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000531
Chris Lattner13fb0db2011-02-18 04:41:42 +0000532 const_cast<Constant*>(C)->destroyConstant();
533 return true;
534}
535
536
Chris Lattner13fb0db2011-02-18 04:41:42 +0000537void Constant::removeDeadConstantUsers() const {
Chandler Carruth36b699f2014-03-09 03:16:01 +0000538 Value::const_user_iterator I = user_begin(), E = user_end();
539 Value::const_user_iterator LastNonDeadUser = E;
Chris Lattner13fb0db2011-02-18 04:41:42 +0000540 while (I != E) {
541 const Constant *User = dyn_cast<Constant>(*I);
Craig Topperec0f0bc2014-04-09 06:08:46 +0000542 if (!User) {
Chris Lattner13fb0db2011-02-18 04:41:42 +0000543 LastNonDeadUser = I;
544 ++I;
545 continue;
546 }
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000547
Chris Lattner13fb0db2011-02-18 04:41:42 +0000548 if (!removeDeadUsersOfConstant(User)) {
549 // If the constant wasn't dead, remember that this was the last live use
550 // and move on to the next constant.
551 LastNonDeadUser = I;
552 ++I;
553 continue;
554 }
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000555
Chris Lattner13fb0db2011-02-18 04:41:42 +0000556 // If the constant was dead, then the iterator is invalidated.
557 if (LastNonDeadUser == E) {
Chandler Carruth36b699f2014-03-09 03:16:01 +0000558 I = user_begin();
Chris Lattner13fb0db2011-02-18 04:41:42 +0000559 if (I == E) break;
560 } else {
561 I = LastNonDeadUser;
562 ++I;
563 }
564 }
565}
566
567
Chris Lattner86381442008-07-10 00:28:11 +0000568
Chris Lattner00950542001-06-06 20:29:01 +0000569//===----------------------------------------------------------------------===//
Chris Lattner6b6f6ba2007-02-20 06:39:57 +0000570// ConstantInt
Chris Lattner00950542001-06-06 20:29:01 +0000571//===----------------------------------------------------------------------===//
572
Duncan P. N. Exon Smith34cfdde2016-02-21 02:39:49 +0000573ConstantInt::ConstantInt(IntegerType *Ty, const APInt &V)
574 : ConstantData(Ty, ConstantIntVal), Val(V) {
Reid Spencer532d0ce2007-02-26 23:54:03 +0000575 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
Chris Lattner00950542001-06-06 20:29:01 +0000576}
577
Nick Lewyckyd01f50f2011-03-06 03:36:19 +0000578ConstantInt *ConstantInt::getTrue(LLVMContext &Context) {
Owen Anderson5defacc2009-07-31 17:39:07 +0000579 LLVMContextImpl *pImpl = Context.pImpl;
Benjamin Kramerf601d6d2010-11-20 18:43:35 +0000580 if (!pImpl->TheTrueVal)
581 pImpl->TheTrueVal = ConstantInt::get(Type::getInt1Ty(Context), 1);
582 return pImpl->TheTrueVal;
Owen Anderson5defacc2009-07-31 17:39:07 +0000583}
584
Nick Lewyckyd01f50f2011-03-06 03:36:19 +0000585ConstantInt *ConstantInt::getFalse(LLVMContext &Context) {
Owen Anderson5defacc2009-07-31 17:39:07 +0000586 LLVMContextImpl *pImpl = Context.pImpl;
Benjamin Kramerf601d6d2010-11-20 18:43:35 +0000587 if (!pImpl->TheFalseVal)
588 pImpl->TheFalseVal = ConstantInt::get(Type::getInt1Ty(Context), 0);
589 return pImpl->TheFalseVal;
Owen Anderson5defacc2009-07-31 17:39:07 +0000590}
591
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000592Constant *ConstantInt::getTrue(Type *Ty) {
Craig Toppereb41f6a2017-07-09 07:04:03 +0000593 assert(Ty->isIntOrIntVectorTy(1) && "Type not i1 or vector of i1.");
Sanjay Patel997ed302017-04-16 17:00:21 +0000594 ConstantInt *TrueC = ConstantInt::getTrue(Ty->getContext());
595 if (auto *VTy = dyn_cast<VectorType>(Ty))
596 return ConstantVector::getSplat(VTy->getNumElements(), TrueC);
597 return TrueC;
Nick Lewyckyd01f50f2011-03-06 03:36:19 +0000598}
599
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000600Constant *ConstantInt::getFalse(Type *Ty) {
Craig Toppereb41f6a2017-07-09 07:04:03 +0000601 assert(Ty->isIntOrIntVectorTy(1) && "Type not i1 or vector of i1.");
Sanjay Patel997ed302017-04-16 17:00:21 +0000602 ConstantInt *FalseC = ConstantInt::getFalse(Ty->getContext());
603 if (auto *VTy = dyn_cast<VectorType>(Ty))
604 return ConstantVector::getSplat(VTy->getNumElements(), FalseC);
605 return FalseC;
Nick Lewyckyd01f50f2011-03-06 03:36:19 +0000606}
607
Benjamin Kramer51df2c22014-12-06 13:12:56 +0000608// Get a ConstantInt from an APInt.
Nick Lewyckyd01f50f2011-03-06 03:36:19 +0000609ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt &V) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000610 // get an existing value or the insertion position
Benjamin Kramer6dd56e62013-06-01 17:51:03 +0000611 LLVMContextImpl *pImpl = Context.pImpl;
Justin Lebara2e3c5a2016-10-10 16:26:13 +0000612 std::unique_ptr<ConstantInt> &Slot = pImpl->IntConstants[V];
Benjamin Kramer51df2c22014-12-06 13:12:56 +0000613 if (!Slot) {
614 // Get the corresponding integer type for the bit width of the value.
615 IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
Justin Lebara2e3c5a2016-10-10 16:26:13 +0000616 Slot.reset(new ConstantInt(ITy, V));
Benjamin Kramer51df2c22014-12-06 13:12:56 +0000617 }
618 assert(Slot->getType() == IntegerType::get(Context, V.getBitWidth()));
Justin Lebara2e3c5a2016-10-10 16:26:13 +0000619 return Slot.get();
Owen Andersoneed707b2009-07-24 23:12:02 +0000620}
621
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000622Constant *ConstantInt::get(Type *Ty, uint64_t V, bool isSigned) {
Nick Lewyckyd01f50f2011-03-06 03:36:19 +0000623 Constant *C = get(cast<IntegerType>(Ty->getScalarType()), V, isSigned);
Owen Andersoneed707b2009-07-24 23:12:02 +0000624
625 // For vectors, broadcast the value.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000626 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattner3c2c9542012-01-25 05:19:54 +0000627 return ConstantVector::getSplat(VTy->getNumElements(), C);
Owen Andersoneed707b2009-07-24 23:12:02 +0000628
629 return C;
630}
631
Sanjay Patel7aae44e2016-05-18 22:05:28 +0000632ConstantInt *ConstantInt::get(IntegerType *Ty, uint64_t V, bool isSigned) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000633 return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned));
634}
635
Chris Lattnera78fa8c2012-01-27 03:08:05 +0000636ConstantInt *ConstantInt::getSigned(IntegerType *Ty, int64_t V) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000637 return get(Ty, V, true);
638}
639
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000640Constant *ConstantInt::getSigned(Type *Ty, int64_t V) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000641 return get(Ty, V, true);
642}
643
Chris Lattnera78fa8c2012-01-27 03:08:05 +0000644Constant *ConstantInt::get(Type *Ty, const APInt& V) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000645 ConstantInt *C = get(Ty->getContext(), V);
646 assert(C->getType() == Ty->getScalarType() &&
647 "ConstantInt type doesn't match the type implied by its value!");
648
649 // For vectors, broadcast the value.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000650 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattner3c2c9542012-01-25 05:19:54 +0000651 return ConstantVector::getSplat(VTy->getNumElements(), C);
Owen Andersoneed707b2009-07-24 23:12:02 +0000652
653 return C;
654}
655
Sanjay Patel7aae44e2016-05-18 22:05:28 +0000656ConstantInt *ConstantInt::get(IntegerType* Ty, StringRef Str, uint8_t radix) {
Erick Tryzelaar0e81f662009-08-16 23:36:33 +0000657 return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
658}
659
Pete Cooperd6218122015-06-23 21:55:11 +0000660/// Remove the constant from the constant table.
661void ConstantInt::destroyConstantImpl() {
662 llvm_unreachable("You can't ConstantInt->destroyConstantImpl()!");
663}
664
Chris Lattner6b6f6ba2007-02-20 06:39:57 +0000665//===----------------------------------------------------------------------===//
Chris Lattner9b4ee0c2007-02-20 07:17:17 +0000666// ConstantFP
Chris Lattner6b6f6ba2007-02-20 06:39:57 +0000667//===----------------------------------------------------------------------===//
668
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000669static const fltSemantics *TypeToFloatSemantics(Type *Ty) {
Dan Gohmance163392011-12-17 00:04:22 +0000670 if (Ty->isHalfTy())
Stephan Bergmann20a600c2016-12-14 11:57:17 +0000671 return &APFloat::IEEEhalf();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000672 if (Ty->isFloatTy())
Stephan Bergmann20a600c2016-12-14 11:57:17 +0000673 return &APFloat::IEEEsingle();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000674 if (Ty->isDoubleTy())
Stephan Bergmann20a600c2016-12-14 11:57:17 +0000675 return &APFloat::IEEEdouble();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000676 if (Ty->isX86_FP80Ty())
Stephan Bergmann20a600c2016-12-14 11:57:17 +0000677 return &APFloat::x87DoubleExtended();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000678 else if (Ty->isFP128Ty())
Stephan Bergmann20a600c2016-12-14 11:57:17 +0000679 return &APFloat::IEEEquad();
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000680
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000681 assert(Ty->isPPC_FP128Ty() && "Unknown FP format");
Stephan Bergmann20a600c2016-12-14 11:57:17 +0000682 return &APFloat::PPCDoubleDouble();
Rafael Espindola87d1f472009-07-15 17:40:42 +0000683}
684
Chris Lattnera78fa8c2012-01-27 03:08:05 +0000685Constant *ConstantFP::get(Type *Ty, double V) {
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000686 LLVMContext &Context = Ty->getContext();
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000687
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000688 APFloat FV(V);
689 bool ignored;
690 FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
691 APFloat::rmNearestTiesToEven, &ignored);
692 Constant *C = get(Context, FV);
693
694 // For vectors, broadcast the value.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000695 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattner3c2c9542012-01-25 05:19:54 +0000696 return ConstantVector::getSplat(VTy->getNumElements(), C);
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000697
698 return C;
699}
700
Sanjay Patel0e9e7442018-02-15 13:55:52 +0000701Constant *ConstantFP::get(Type *Ty, const APFloat &V) {
702 ConstantFP *C = get(Ty->getContext(), V);
703 assert(C->getType() == Ty->getScalarType() &&
704 "ConstantFP type doesn't match the type implied by its value!");
705
706 // For vectors, broadcast the value.
707 if (auto *VTy = dyn_cast<VectorType>(Ty))
708 return ConstantVector::getSplat(VTy->getNumElements(), C);
709
710 return C;
711}
Erick Tryzelaar0e81f662009-08-16 23:36:33 +0000712
Chris Lattnera78fa8c2012-01-27 03:08:05 +0000713Constant *ConstantFP::get(Type *Ty, StringRef Str) {
Erick Tryzelaar0e81f662009-08-16 23:36:33 +0000714 LLVMContext &Context = Ty->getContext();
715
716 APFloat FV(*TypeToFloatSemantics(Ty->getScalarType()), Str);
717 Constant *C = get(Context, FV);
718
719 // For vectors, broadcast the value.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000720 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattner3c2c9542012-01-25 05:19:54 +0000721 return ConstantVector::getSplat(VTy->getNumElements(), C);
Erick Tryzelaar0e81f662009-08-16 23:36:33 +0000722
Bjorn Petterssona1ff84e2018-07-03 12:39:52 +0000723 return C;
Erick Tryzelaar0e81f662009-08-16 23:36:33 +0000724}
725
JF Bastiene3796d32018-12-10 19:27:38 +0000726Constant *ConstantFP::getNaN(Type *Ty, bool Negative, uint64_t Payload) {
Tom Stellardeb963a52015-04-20 19:38:24 +0000727 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
JF Bastiene3796d32018-12-10 19:27:38 +0000728 APFloat NaN = APFloat::getNaN(Semantics, Negative, Payload);
Tom Stellardeb963a52015-04-20 19:38:24 +0000729 Constant *C = get(Ty->getContext(), NaN);
730
731 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
732 return ConstantVector::getSplat(VTy->getNumElements(), C);
733
734 return C;
735}
736
JF Bastiene3796d32018-12-10 19:27:38 +0000737Constant *ConstantFP::getQNaN(Type *Ty, bool Negative, APInt *Payload) {
738 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
739 APFloat NaN = APFloat::getQNaN(Semantics, Negative, Payload);
740 Constant *C = get(Ty->getContext(), NaN);
741
742 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
743 return ConstantVector::getSplat(VTy->getNumElements(), C);
744
745 return C;
746}
747
748Constant *ConstantFP::getSNaN(Type *Ty, bool Negative, APInt *Payload) {
749 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
750 APFloat NaN = APFloat::getSNaN(Semantics, Negative, Payload);
751 Constant *C = get(Ty->getContext(), NaN);
752
753 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
754 return ConstantVector::getSplat(VTy->getNumElements(), C);
755
756 return C;
757}
758
Benjamin Kramerbedf8422014-01-18 16:43:06 +0000759Constant *ConstantFP::getNegativeZero(Type *Ty) {
760 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
761 APFloat NegZero = APFloat::getZero(Semantics, /*Negative=*/true);
762 Constant *C = get(Ty->getContext(), NegZero);
Erick Tryzelaar0e81f662009-08-16 23:36:33 +0000763
Benjamin Kramerbedf8422014-01-18 16:43:06 +0000764 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
765 return ConstantVector::getSplat(VTy->getNumElements(), C);
766
767 return C;
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000768}
769
770
Chris Lattner3c2c9542012-01-25 05:19:54 +0000771Constant *ConstantFP::getZeroValueForNegation(Type *Ty) {
Benjamin Kramerbedf8422014-01-18 16:43:06 +0000772 if (Ty->isFPOrFPVectorTy())
773 return getNegativeZero(Ty);
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000774
Owen Andersona7235ea2009-07-31 20:28:14 +0000775 return Constant::getNullValue(Ty);
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000776}
777
778
779// ConstantFP accessors.
780ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000781 LLVMContextImpl* pImpl = Context.pImpl;
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000782
Justin Lebara2e3c5a2016-10-10 16:26:13 +0000783 std::unique_ptr<ConstantFP> &Slot = pImpl->FPConstants[V];
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000784
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000785 if (!Slot) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000786 Type *Ty;
Stephan Bergmann20a600c2016-12-14 11:57:17 +0000787 if (&V.getSemantics() == &APFloat::IEEEhalf())
Dan Gohmance163392011-12-17 00:04:22 +0000788 Ty = Type::getHalfTy(Context);
Stephan Bergmann20a600c2016-12-14 11:57:17 +0000789 else if (&V.getSemantics() == &APFloat::IEEEsingle())
Owen Anderson59d5aac2009-10-19 20:11:52 +0000790 Ty = Type::getFloatTy(Context);
Stephan Bergmann20a600c2016-12-14 11:57:17 +0000791 else if (&V.getSemantics() == &APFloat::IEEEdouble())
Owen Anderson59d5aac2009-10-19 20:11:52 +0000792 Ty = Type::getDoubleTy(Context);
Stephan Bergmann20a600c2016-12-14 11:57:17 +0000793 else if (&V.getSemantics() == &APFloat::x87DoubleExtended())
Owen Anderson59d5aac2009-10-19 20:11:52 +0000794 Ty = Type::getX86_FP80Ty(Context);
Stephan Bergmann20a600c2016-12-14 11:57:17 +0000795 else if (&V.getSemantics() == &APFloat::IEEEquad())
Owen Anderson59d5aac2009-10-19 20:11:52 +0000796 Ty = Type::getFP128Ty(Context);
797 else {
Bjorn Petterssona1ff84e2018-07-03 12:39:52 +0000798 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble() &&
Owen Anderson59d5aac2009-10-19 20:11:52 +0000799 "Unknown FP format");
800 Ty = Type::getPPC_FP128Ty(Context);
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000801 }
Justin Lebara2e3c5a2016-10-10 16:26:13 +0000802 Slot.reset(new ConstantFP(Ty, V));
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000803 }
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000804
Justin Lebara2e3c5a2016-10-10 16:26:13 +0000805 return Slot.get();
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000806}
807
Benjamin Kramerbedf8422014-01-18 16:43:06 +0000808Constant *ConstantFP::getInfinity(Type *Ty, bool Negative) {
809 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
810 Constant *C = get(Ty->getContext(), APFloat::getInf(Semantics, Negative));
811
812 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
813 return ConstantVector::getSplat(VTy->getNumElements(), C);
814
815 return C;
Dan Gohmanf344f7f2009-09-25 23:00:48 +0000816}
817
Duncan P. N. Exon Smith34cfdde2016-02-21 02:39:49 +0000818ConstantFP::ConstantFP(Type *Ty, const APFloat &V)
819 : ConstantData(Ty, ConstantFPVal), Val(V) {
Chris Lattner288e78f2008-04-09 06:38:30 +0000820 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
821 "FP type Mismatch");
Chris Lattner00950542001-06-06 20:29:01 +0000822}
823
Chris Lattner032c6eb2011-07-15 06:14:08 +0000824bool ConstantFP::isExactlyValue(const APFloat &V) const {
Dale Johannesenf04afdb2007-08-30 00:23:21 +0000825 return Val.bitwiseIsEqual(V);
Chris Lattner9b4ee0c2007-02-20 07:17:17 +0000826}
827
Pete Cooperd6218122015-06-23 21:55:11 +0000828/// Remove the constant from the constant table.
829void ConstantFP::destroyConstantImpl() {
Craig Topperaa9b8232017-06-27 19:57:51 +0000830 llvm_unreachable("You can't ConstantFP->destroyConstantImpl()!");
Pete Cooperd6218122015-06-23 21:55:11 +0000831}
832
Chris Lattner9b4ee0c2007-02-20 07:17:17 +0000833//===----------------------------------------------------------------------===//
Chris Lattnerff2b7f32012-01-24 05:42:11 +0000834// ConstantAggregateZero Implementation
835//===----------------------------------------------------------------------===//
836
Chris Lattner3d5ed222012-01-25 06:16:32 +0000837Constant *ConstantAggregateZero::getSequentialElement() const {
Chris Lattner230cdab2012-01-26 00:42:34 +0000838 return Constant::getNullValue(getType()->getSequentialElementType());
Chris Lattnerff2b7f32012-01-24 05:42:11 +0000839}
840
Chris Lattner3d5ed222012-01-25 06:16:32 +0000841Constant *ConstantAggregateZero::getStructElement(unsigned Elt) const {
Chris Lattner230cdab2012-01-26 00:42:34 +0000842 return Constant::getNullValue(getType()->getStructElementType(Elt));
Chris Lattnerff2b7f32012-01-24 05:42:11 +0000843}
844
Chris Lattner3d5ed222012-01-25 06:16:32 +0000845Constant *ConstantAggregateZero::getElementValue(Constant *C) const {
Chris Lattnerff2b7f32012-01-24 05:42:11 +0000846 if (isa<SequentialType>(getType()))
847 return getSequentialElement();
848 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
849}
850
Chris Lattner3d5ed222012-01-25 06:16:32 +0000851Constant *ConstantAggregateZero::getElementValue(unsigned Idx) const {
Chris Lattnerdf390282012-01-24 07:54:10 +0000852 if (isa<SequentialType>(getType()))
853 return getSequentialElement();
854 return getStructElement(Idx);
855}
856
David Majnemer6de0a122015-02-16 04:02:09 +0000857unsigned ConstantAggregateZero::getNumElements() const {
Craig Topper84bbcfe2015-08-01 22:20:21 +0000858 Type *Ty = getType();
859 if (auto *AT = dyn_cast<ArrayType>(Ty))
David Majnemer6de0a122015-02-16 04:02:09 +0000860 return AT->getNumElements();
Craig Topper84bbcfe2015-08-01 22:20:21 +0000861 if (auto *VT = dyn_cast<VectorType>(Ty))
David Majnemer6de0a122015-02-16 04:02:09 +0000862 return VT->getNumElements();
863 return Ty->getStructNumElements();
864}
Chris Lattnerdf390282012-01-24 07:54:10 +0000865
Chris Lattnerff2b7f32012-01-24 05:42:11 +0000866//===----------------------------------------------------------------------===//
867// UndefValue Implementation
868//===----------------------------------------------------------------------===//
869
Chris Lattner3d5ed222012-01-25 06:16:32 +0000870UndefValue *UndefValue::getSequentialElement() const {
Chris Lattner230cdab2012-01-26 00:42:34 +0000871 return UndefValue::get(getType()->getSequentialElementType());
Chris Lattnerff2b7f32012-01-24 05:42:11 +0000872}
873
Chris Lattner3d5ed222012-01-25 06:16:32 +0000874UndefValue *UndefValue::getStructElement(unsigned Elt) const {
Chris Lattner230cdab2012-01-26 00:42:34 +0000875 return UndefValue::get(getType()->getStructElementType(Elt));
Chris Lattnerff2b7f32012-01-24 05:42:11 +0000876}
877
Chris Lattner3d5ed222012-01-25 06:16:32 +0000878UndefValue *UndefValue::getElementValue(Constant *C) const {
Chris Lattnerff2b7f32012-01-24 05:42:11 +0000879 if (isa<SequentialType>(getType()))
880 return getSequentialElement();
881 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
882}
883
Chris Lattner3d5ed222012-01-25 06:16:32 +0000884UndefValue *UndefValue::getElementValue(unsigned Idx) const {
Chris Lattnerdf390282012-01-24 07:54:10 +0000885 if (isa<SequentialType>(getType()))
886 return getSequentialElement();
887 return getStructElement(Idx);
888}
889
David Majnemer6de0a122015-02-16 04:02:09 +0000890unsigned UndefValue::getNumElements() const {
Craig Topper84bbcfe2015-08-01 22:20:21 +0000891 Type *Ty = getType();
Peter Collingbournea705e0e2016-12-02 03:20:58 +0000892 if (auto *ST = dyn_cast<SequentialType>(Ty))
893 return ST->getNumElements();
David Majnemer6de0a122015-02-16 04:02:09 +0000894 return Ty->getStructNumElements();
895}
Chris Lattnerff2b7f32012-01-24 05:42:11 +0000896
897//===----------------------------------------------------------------------===//
Chris Lattner9b4ee0c2007-02-20 07:17:17 +0000898// ConstantXXX Classes
899//===----------------------------------------------------------------------===//
900
Chris Lattner18c7f802012-02-05 02:29:43 +0000901template <typename ItTy, typename EltTy>
902static bool rangeOnlyContains(ItTy Start, ItTy End, EltTy Elt) {
903 for (; Start != End; ++Start)
904 if (*Start != Elt)
905 return false;
906 return true;
907}
Chris Lattner9b4ee0c2007-02-20 07:17:17 +0000908
Justin Bognerfc161532015-12-01 20:20:49 +0000909template <typename SequentialTy, typename ElementTy>
910static Constant *getIntSequenceIfElementsMatch(ArrayRef<Constant *> V) {
911 assert(!V.empty() && "Cannot get empty int sequence.");
912
913 SmallVector<ElementTy, 16> Elts;
914 for (Constant *C : V)
915 if (auto *CI = dyn_cast<ConstantInt>(C))
916 Elts.push_back(CI->getZExtValue());
917 else
918 return nullptr;
919 return SequentialTy::get(V[0]->getContext(), Elts);
920}
921
922template <typename SequentialTy, typename ElementTy>
923static Constant *getFPSequenceIfElementsMatch(ArrayRef<Constant *> V) {
924 assert(!V.empty() && "Cannot get empty FP sequence.");
925
926 SmallVector<ElementTy, 16> Elts;
927 for (Constant *C : V)
928 if (auto *CFP = dyn_cast<ConstantFP>(C))
929 Elts.push_back(CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
930 else
931 return nullptr;
932 return SequentialTy::getFP(V[0]->getContext(), Elts);
933}
934
935template <typename SequenceTy>
936static Constant *getSequenceIfElementsMatch(Constant *C,
937 ArrayRef<Constant *> V) {
938 // We speculatively build the elements here even if it turns out that there is
939 // a constantexpr or something else weird, since it is so uncommon for that to
940 // happen.
941 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
942 if (CI->getType()->isIntegerTy(8))
943 return getIntSequenceIfElementsMatch<SequenceTy, uint8_t>(V);
944 else if (CI->getType()->isIntegerTy(16))
945 return getIntSequenceIfElementsMatch<SequenceTy, uint16_t>(V);
946 else if (CI->getType()->isIntegerTy(32))
947 return getIntSequenceIfElementsMatch<SequenceTy, uint32_t>(V);
948 else if (CI->getType()->isIntegerTy(64))
949 return getIntSequenceIfElementsMatch<SequenceTy, uint64_t>(V);
950 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
Justin Bognere32f0e22015-12-08 03:01:16 +0000951 if (CFP->getType()->isHalfTy())
952 return getFPSequenceIfElementsMatch<SequenceTy, uint16_t>(V);
953 else if (CFP->getType()->isFloatTy())
Justin Bognerfc161532015-12-01 20:20:49 +0000954 return getFPSequenceIfElementsMatch<SequenceTy, uint32_t>(V);
955 else if (CFP->getType()->isDoubleTy())
956 return getFPSequenceIfElementsMatch<SequenceTy, uint64_t>(V);
957 }
958
959 return nullptr;
960}
961
Duncan P. N. Exon Smithd7773c02016-04-05 21:10:45 +0000962ConstantAggregate::ConstantAggregate(CompositeType *T, ValueTy VT,
963 ArrayRef<Constant *> V)
964 : Constant(T, VT, OperandTraits<ConstantAggregate>::op_end(this) - V.size(),
965 V.size()) {
Fangrui Song53a62242018-11-17 01:44:25 +0000966 llvm::copy(V, op_begin());
Duncan P. N. Exon Smithd7773c02016-04-05 21:10:45 +0000967
968 // Check that types match, unless this is an opaque struct.
969 if (auto *ST = dyn_cast<StructType>(T))
970 if (ST->isOpaque())
971 return;
972 for (unsigned I = 0, E = V.size(); I != E; ++I)
973 assert(V[I]->getType() == T->getTypeAtIndex(I) &&
974 "Initializer for composite element doesn't match!");
975}
976
977ConstantArray::ConstantArray(ArrayType *T, ArrayRef<Constant *> V)
978 : ConstantAggregate(T, ConstantArrayVal, V) {
979 assert(V.size() == T->getNumElements() &&
980 "Invalid initializer for constant array");
Chris Lattner00950542001-06-06 20:29:01 +0000981}
982
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000983Constant *ConstantArray::get(ArrayType *Ty, ArrayRef<Constant*> V) {
Duncan P. N. Exon Smith7116af62014-08-19 16:39:58 +0000984 if (Constant *C = getImpl(Ty, V))
985 return C;
986 return Ty->getContext().pImpl->ArrayConstants.getOrCreate(Ty, V);
987}
Justin Bognerfc161532015-12-01 20:20:49 +0000988
Duncan P. N. Exon Smith7116af62014-08-19 16:39:58 +0000989Constant *ConstantArray::getImpl(ArrayType *Ty, ArrayRef<Constant*> V) {
Chris Lattner18c7f802012-02-05 02:29:43 +0000990 // Empty arrays are canonicalized to ConstantAggregateZero.
991 if (V.empty())
992 return ConstantAggregateZero::get(Ty);
993
Jeffrey Yasskin1fb613c2009-09-30 21:08:08 +0000994 for (unsigned i = 0, e = V.size(); i != e; ++i) {
995 assert(V[i]->getType() == Ty->getElementType() &&
996 "Wrong type in array element initializer");
997 }
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000998
Chris Lattner18c7f802012-02-05 02:29:43 +0000999 // If this is an all-zero array, return a ConstantAggregateZero object. If
1000 // all undef, return an UndefValue, if "all simple", then return a
1001 // ConstantDataArray.
1002 Constant *C = V[0];
1003 if (isa<UndefValue>(C) && rangeOnlyContains(V.begin(), V.end(), C))
1004 return UndefValue::get(Ty);
Chris Lattnere150e2d2012-01-26 02:31:22 +00001005
Chris Lattner18c7f802012-02-05 02:29:43 +00001006 if (C->isNullValue() && rangeOnlyContains(V.begin(), V.end(), C))
1007 return ConstantAggregateZero::get(Ty);
1008
1009 // Check to see if all of the elements are ConstantFP or ConstantInt and if
1010 // the element type is compatible with ConstantDataVector. If so, use it.
Justin Bognerfc161532015-12-01 20:20:49 +00001011 if (ConstantDataSequential::isElementTypeCompatible(C->getType()))
1012 return getSequenceIfElementsMatch<ConstantDataArray>(C, V);
Chris Lattnere150e2d2012-01-26 02:31:22 +00001013
Chris Lattner18c7f802012-02-05 02:29:43 +00001014 // Otherwise, we really do want to create a ConstantArray.
Duncan P. N. Exon Smith7116af62014-08-19 16:39:58 +00001015 return nullptr;
Owen Anderson1fd70962009-07-28 18:32:17 +00001016}
1017
Chris Lattnerb065b062011-06-20 04:01:31 +00001018StructType *ConstantStruct::getTypeForElements(LLVMContext &Context,
1019 ArrayRef<Constant*> V,
1020 bool Packed) {
Bill Wendlinga7a3f042012-02-07 01:27:51 +00001021 unsigned VecSize = V.size();
1022 SmallVector<Type*, 16> EltTypes(VecSize);
1023 for (unsigned i = 0; i != VecSize; ++i)
1024 EltTypes[i] = V[i]->getType();
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001025
Chris Lattnerb065b062011-06-20 04:01:31 +00001026 return StructType::get(Context, EltTypes, Packed);
1027}
1028
1029
1030StructType *ConstantStruct::getTypeForElements(ArrayRef<Constant*> V,
1031 bool Packed) {
1032 assert(!V.empty() &&
1033 "ConstantStruct::getTypeForElements cannot be called on empty list");
1034 return getTypeForElements(V[0]->getContext(), V, Packed);
1035}
1036
Jay Foad166579e2011-07-25 10:14:44 +00001037ConstantStruct::ConstantStruct(StructType *T, ArrayRef<Constant *> V)
Duncan P. N. Exon Smithd7773c02016-04-05 21:10:45 +00001038 : ConstantAggregate(T, ConstantStructVal, V) {
1039 assert((T->isOpaque() || V.size() == T->getNumElements()) &&
1040 "Invalid initializer for constant struct");
Chris Lattner00950542001-06-06 20:29:01 +00001041}
1042
Owen Anderson8fa33382009-07-27 22:29:26 +00001043// ConstantStruct accessors.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001044Constant *ConstantStruct::get(StructType *ST, ArrayRef<Constant*> V) {
Chris Lattner1afcace2011-07-09 17:41:24 +00001045 assert((ST->isOpaque() || ST->getNumElements() == V.size()) &&
1046 "Incorrect # elements specified to ConstantStruct::get");
Chris Lattnere150e2d2012-01-26 02:31:22 +00001047
1048 // Create a ConstantAggregateZero value if all elements are zeros.
1049 bool isZero = true;
1050 bool isUndef = false;
Bjorn Petterssona1ff84e2018-07-03 12:39:52 +00001051
Chris Lattnere150e2d2012-01-26 02:31:22 +00001052 if (!V.empty()) {
1053 isUndef = isa<UndefValue>(V[0]);
1054 isZero = V[0]->isNullValue();
1055 if (isUndef || isZero) {
1056 for (unsigned i = 0, e = V.size(); i != e; ++i) {
1057 if (!V[i]->isNullValue())
1058 isZero = false;
1059 if (!isa<UndefValue>(V[i]))
1060 isUndef = false;
1061 }
1062 }
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001063 }
Chris Lattnere150e2d2012-01-26 02:31:22 +00001064 if (isZero)
1065 return ConstantAggregateZero::get(ST);
1066 if (isUndef)
1067 return UndefValue::get(ST);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001068
Chris Lattnere150e2d2012-01-26 02:31:22 +00001069 return ST->getContext().pImpl->StructConstants.getOrCreate(ST, V);
Owen Anderson8fa33382009-07-27 22:29:26 +00001070}
1071
Jay Foad166579e2011-07-25 10:14:44 +00001072ConstantVector::ConstantVector(VectorType *T, ArrayRef<Constant *> V)
Duncan P. N. Exon Smithd7773c02016-04-05 21:10:45 +00001073 : ConstantAggregate(T, ConstantVectorVal, V) {
Duncan P. N. Exon Smithef940292016-04-05 20:53:47 +00001074 assert(V.size() == T->getNumElements() &&
Duncan P. N. Exon Smithd7773c02016-04-05 21:10:45 +00001075 "Invalid initializer for constant vector");
Brian Gaeke715c90b2004-08-20 06:00:58 +00001076}
1077
Owen Andersonaf7ec972009-07-28 21:19:26 +00001078// ConstantVector accessors.
Jay Foada0c13842011-06-22 09:10:19 +00001079Constant *ConstantVector::get(ArrayRef<Constant*> V) {
Duncan P. N. Exon Smith7116af62014-08-19 16:39:58 +00001080 if (Constant *C = getImpl(V))
1081 return C;
1082 VectorType *Ty = VectorType::get(V.front()->getType(), V.size());
1083 return Ty->getContext().pImpl->VectorConstants.getOrCreate(Ty, V);
1084}
Justin Bognerfc161532015-12-01 20:20:49 +00001085
Duncan P. N. Exon Smith7116af62014-08-19 16:39:58 +00001086Constant *ConstantVector::getImpl(ArrayRef<Constant*> V) {
Jay Foad9afc5272011-01-27 14:44:55 +00001087 assert(!V.empty() && "Vectors can't be empty");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001088 VectorType *T = VectorType::get(V.front()->getType(), V.size());
Jay Foad9afc5272011-01-27 14:44:55 +00001089
Chris Lattner2ca5c862011-02-15 00:14:00 +00001090 // If this is an all-undef or all-zero vector, return a
Owen Andersonaf7ec972009-07-28 21:19:26 +00001091 // ConstantAggregateZero or UndefValue.
1092 Constant *C = V[0];
1093 bool isZero = C->isNullValue();
1094 bool isUndef = isa<UndefValue>(C);
1095
1096 if (isZero || isUndef) {
1097 for (unsigned i = 1, e = V.size(); i != e; ++i)
1098 if (V[i] != C) {
1099 isZero = isUndef = false;
1100 break;
1101 }
1102 }
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001103
Owen Andersonaf7ec972009-07-28 21:19:26 +00001104 if (isZero)
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001105 return ConstantAggregateZero::get(T);
Owen Andersonaf7ec972009-07-28 21:19:26 +00001106 if (isUndef)
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001107 return UndefValue::get(T);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001108
Chris Lattner36c744f2012-01-30 06:21:21 +00001109 // Check to see if all of the elements are ConstantFP or ConstantInt and if
1110 // the element type is compatible with ConstantDataVector. If so, use it.
Justin Bognerfc161532015-12-01 20:20:49 +00001111 if (ConstantDataSequential::isElementTypeCompatible(C->getType()))
1112 return getSequenceIfElementsMatch<ConstantDataVector>(C, V);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001113
Chris Lattner36c744f2012-01-30 06:21:21 +00001114 // Otherwise, the element type isn't compatible with ConstantDataVector, or
Craig Toppercd0241d2017-04-11 06:41:55 +00001115 // the operand list contains a ConstantExpr or something else strange.
Duncan P. N. Exon Smith7116af62014-08-19 16:39:58 +00001116 return nullptr;
Owen Andersonaf7ec972009-07-28 21:19:26 +00001117}
1118
Chris Lattner3c2c9542012-01-25 05:19:54 +00001119Constant *ConstantVector::getSplat(unsigned NumElts, Constant *V) {
Chris Lattner36c744f2012-01-30 06:21:21 +00001120 // If this splat is compatible with ConstantDataVector, use it instead of
1121 // ConstantVector.
1122 if ((isa<ConstantFP>(V) || isa<ConstantInt>(V)) &&
1123 ConstantDataSequential::isElementTypeCompatible(V->getType()))
1124 return ConstantDataVector::getSplat(NumElts, V);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001125
Chris Lattner3c2c9542012-01-25 05:19:54 +00001126 SmallVector<Constant*, 32> Elts(NumElts, V);
1127 return get(Elts);
1128}
1129
David Majnemer83fc12a2015-11-11 21:57:16 +00001130ConstantTokenNone *ConstantTokenNone::get(LLVMContext &Context) {
1131 LLVMContextImpl *pImpl = Context.pImpl;
1132 if (!pImpl->TheNoneToken)
David Majnemer3ee61b82015-11-16 20:55:57 +00001133 pImpl->TheNoneToken.reset(new ConstantTokenNone(Context));
1134 return pImpl->TheNoneToken.get();
David Majnemer83fc12a2015-11-11 21:57:16 +00001135}
1136
1137/// Remove the constant from the constant table.
1138void ConstantTokenNone::destroyConstantImpl() {
1139 llvm_unreachable("You can't ConstantTokenNone->destroyConstantImpl()!");
1140}
Chris Lattner3c2c9542012-01-25 05:19:54 +00001141
Reid Spencer3da59db2006-11-27 01:05:10 +00001142// Utility function for determining if a ConstantExpr is a CastOp or not. This
1143// can't be inline because we don't want to #include Instruction.h into
1144// Constant.h
1145bool ConstantExpr::isCast() const {
1146 return Instruction::isCast(getOpcode());
1147}
1148
Reid Spencer077d0eb2006-12-04 05:19:50 +00001149bool ConstantExpr::isCompare() const {
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00001150 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
Reid Spencer077d0eb2006-12-04 05:19:50 +00001151}
1152
Dan Gohmane6992f72009-09-10 23:37:55 +00001153bool ConstantExpr::isGEPWithNoNotionalOverIndexing() const {
1154 if (getOpcode() != Instruction::GetElementPtr) return false;
1155
1156 gep_type_iterator GEPI = gep_type_begin(this), E = gep_type_end(this);
Benjamin Kramerd628f192014-03-02 12:27:27 +00001157 User::const_op_iterator OI = std::next(this->op_begin());
Dan Gohmane6992f72009-09-10 23:37:55 +00001158
Sanjay Patel587c78e2016-12-11 20:07:02 +00001159 // The remaining indices may be compile-time known integers within the bounds
1160 // of the corresponding notional static array types.
Dan Gohmane6992f72009-09-10 23:37:55 +00001161 for (; GEPI != E; ++GEPI, ++OI) {
Sanjay Patel587c78e2016-12-11 20:07:02 +00001162 if (isa<UndefValue>(*OI))
1163 continue;
1164 auto *CI = dyn_cast<ConstantInt>(*OI);
1165 if (!CI || (GEPI.isBoundedSequential() &&
1166 (CI->getValue().getActiveBits() > 64 ||
1167 CI->getZExtValue() >= GEPI.getSequentialNumElements())))
Peter Collingbourne06115802016-12-02 02:24:42 +00001168 return false;
Dan Gohmane6992f72009-09-10 23:37:55 +00001169 }
1170
1171 // All the indices checked out.
1172 return true;
1173}
1174
Dan Gohman81a0c0b2008-05-31 00:58:22 +00001175bool ConstantExpr::hasIndices() const {
1176 return getOpcode() == Instruction::ExtractValue ||
1177 getOpcode() == Instruction::InsertValue;
1178}
1179
Jay Foadd30aa5a2011-04-13 15:22:40 +00001180ArrayRef<unsigned> ConstantExpr::getIndices() const {
Dan Gohman81a0c0b2008-05-31 00:58:22 +00001181 if (const ExtractValueConstantExpr *EVCE =
1182 dyn_cast<ExtractValueConstantExpr>(this))
1183 return EVCE->Indices;
Dan Gohman1a203572008-06-23 16:39:44 +00001184
1185 return cast<InsertValueConstantExpr>(this)->Indices;
Dan Gohman81a0c0b2008-05-31 00:58:22 +00001186}
1187
Reid Spencer728b6db2006-12-03 05:48:19 +00001188unsigned ConstantExpr::getPredicate() const {
Craig Topper07e8f882015-12-15 06:11:36 +00001189 return cast<CompareConstantExpr>(this)->predicate;
Reid Spencer728b6db2006-12-03 05:48:19 +00001190}
Chris Lattnerf4ba6c72001-10-03 06:12:09 +00001191
Reid Spencer3da59db2006-11-27 01:05:10 +00001192Constant *
1193ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
Chris Lattner1fe8f6b2006-07-14 19:37:40 +00001194 assert(Op->getType() == getOperand(OpNo)->getType() &&
1195 "Replacing operand with value of different type!");
Chris Lattnerb88a7fb2006-07-14 22:20:01 +00001196 if (getOperand(OpNo) == Op)
1197 return const_cast<ConstantExpr*>(this);
Chris Lattner1a8def62012-01-26 20:37:11 +00001198
1199 SmallVector<Constant*, 8> NewOps;
1200 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1201 NewOps.push_back(i == OpNo ? Op : getOperand(i));
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001202
Chris Lattner1a8def62012-01-26 20:37:11 +00001203 return getWithOperands(NewOps);
Chris Lattnerb88a7fb2006-07-14 22:20:01 +00001204}
1205
Duncan P. N. Exon Smithe2215572014-08-19 19:45:37 +00001206Constant *ConstantExpr::getWithOperands(ArrayRef<Constant *> Ops, Type *Ty,
David Blaikie81e467d2015-08-21 20:16:51 +00001207 bool OnlyIfReduced, Type *SrcTy) const {
Jay Foadb81e4572011-04-13 13:46:01 +00001208 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001209
Benjamin Kramerf94a2932015-03-02 11:57:04 +00001210 // If no operands changed return self.
1211 if (Ty == getType() && std::equal(Ops.begin(), Ops.end(), op_begin()))
Chris Lattnerb88a7fb2006-07-14 22:20:01 +00001212 return const_cast<ConstantExpr*>(this);
1213
Duncan P. N. Exon Smithe2215572014-08-19 19:45:37 +00001214 Type *OnlyIfReducedTy = OnlyIfReduced ? Ty : nullptr;
Chris Lattnerb88a7fb2006-07-14 22:20:01 +00001215 switch (getOpcode()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001216 case Instruction::Trunc:
1217 case Instruction::ZExt:
1218 case Instruction::SExt:
1219 case Instruction::FPTrunc:
1220 case Instruction::FPExt:
1221 case Instruction::UIToFP:
1222 case Instruction::SIToFP:
1223 case Instruction::FPToUI:
1224 case Instruction::FPToSI:
1225 case Instruction::PtrToInt:
1226 case Instruction::IntToPtr:
1227 case Instruction::BitCast:
Matt Arsenault59d3ae62013-11-15 01:34:59 +00001228 case Instruction::AddrSpaceCast:
Duncan P. N. Exon Smithe2215572014-08-19 19:45:37 +00001229 return ConstantExpr::getCast(getOpcode(), Ops[0], Ty, OnlyIfReduced);
Chris Lattnerb88a7fb2006-07-14 22:20:01 +00001230 case Instruction::Select:
Duncan P. N. Exon Smithe2215572014-08-19 19:45:37 +00001231 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2], OnlyIfReducedTy);
Chris Lattnerb88a7fb2006-07-14 22:20:01 +00001232 case Instruction::InsertElement:
Duncan P. N. Exon Smithe2215572014-08-19 19:45:37 +00001233 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2],
1234 OnlyIfReducedTy);
Chris Lattnerb88a7fb2006-07-14 22:20:01 +00001235 case Instruction::ExtractElement:
Duncan P. N. Exon Smithe2215572014-08-19 19:45:37 +00001236 return ConstantExpr::getExtractElement(Ops[0], Ops[1], OnlyIfReducedTy);
Chris Lattner1a8def62012-01-26 20:37:11 +00001237 case Instruction::InsertValue:
Duncan P. N. Exon Smithe2215572014-08-19 19:45:37 +00001238 return ConstantExpr::getInsertValue(Ops[0], Ops[1], getIndices(),
1239 OnlyIfReducedTy);
Chris Lattner1a8def62012-01-26 20:37:11 +00001240 case Instruction::ExtractValue:
Duncan P. N. Exon Smithe2215572014-08-19 19:45:37 +00001241 return ConstantExpr::getExtractValue(Ops[0], getIndices(), OnlyIfReducedTy);
Chris Lattnerb88a7fb2006-07-14 22:20:01 +00001242 case Instruction::ShuffleVector:
Duncan P. N. Exon Smithe2215572014-08-19 19:45:37 +00001243 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2],
1244 OnlyIfReducedTy);
David Blaikie81e467d2015-08-21 20:16:51 +00001245 case Instruction::GetElementPtr: {
1246 auto *GEPO = cast<GEPOperator>(this);
1247 assert(SrcTy || (Ops[0]->getType() == getOperand(0)->getType()));
1248 return ConstantExpr::getGetElementPtr(
1249 SrcTy ? SrcTy : GEPO->getSourceElementType(), Ops[0], Ops.slice(1),
Peter Collingbourneca668e12016-11-10 22:34:55 +00001250 GEPO->isInBounds(), GEPO->getInRangeIndex(), OnlyIfReducedTy);
David Blaikie81e467d2015-08-21 20:16:51 +00001251 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00001252 case Instruction::ICmp:
1253 case Instruction::FCmp:
Duncan P. N. Exon Smithe2215572014-08-19 19:45:37 +00001254 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1],
1255 OnlyIfReducedTy);
Chris Lattnerb88a7fb2006-07-14 22:20:01 +00001256 default:
1257 assert(getNumOperands() == 2 && "Must be binary operator?");
Duncan P. N. Exon Smithe2215572014-08-19 19:45:37 +00001258 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1], SubclassOptionalData,
1259 OnlyIfReducedTy);
Chris Lattner1fe8f6b2006-07-14 19:37:40 +00001260 }
1261}
1262
Chris Lattner00950542001-06-06 20:29:01 +00001263
1264//===----------------------------------------------------------------------===//
Chris Lattner00950542001-06-06 20:29:01 +00001265// isValueValidForType implementations
1266
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001267bool ConstantInt::isValueValidForType(Type *Ty, uint64_t Val) {
Chris Lattner230cdab2012-01-26 00:42:34 +00001268 unsigned NumBits = Ty->getIntegerBitWidth(); // assert okay
1269 if (Ty->isIntegerTy(1))
Reid Spencera54b7cb2007-01-12 07:05:14 +00001270 return Val == 0 || Val == 1;
Craig Toppera26780d2017-06-07 00:58:05 +00001271 return isUIntN(NumBits, Val);
Reid Spencer9b11d512006-12-19 01:28:19 +00001272}
1273
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001274bool ConstantInt::isValueValidForType(Type *Ty, int64_t Val) {
Chris Lattner230cdab2012-01-26 00:42:34 +00001275 unsigned NumBits = Ty->getIntegerBitWidth();
1276 if (Ty->isIntegerTy(1))
Reid Spencerc1030572007-01-19 21:13:56 +00001277 return Val == 0 || Val == 1 || Val == -1;
Craig Toppera26780d2017-06-07 00:58:05 +00001278 return isIntN(NumBits, Val);
Chris Lattner00950542001-06-06 20:29:01 +00001279}
1280
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001281bool ConstantFP::isValueValidForType(Type *Ty, const APFloat& Val) {
Dale Johannesenf04afdb2007-08-30 00:23:21 +00001282 // convert modifies in place, so make a copy.
1283 APFloat Val2 = APFloat(Val);
Dale Johannesen23a98552008-10-09 23:00:39 +00001284 bool losesInfo;
Chris Lattnerf70c22b2004-06-17 18:19:28 +00001285 switch (Ty->getTypeID()) {
Chris Lattner00950542001-06-06 20:29:01 +00001286 default:
1287 return false; // These can't be represented as floating point!
1288
Dale Johannesenf04afdb2007-08-30 00:23:21 +00001289 // FIXME rounding mode needs to be more flexible
Dan Gohmance163392011-12-17 00:04:22 +00001290 case Type::HalfTyID: {
Stephan Bergmann20a600c2016-12-14 11:57:17 +00001291 if (&Val2.getSemantics() == &APFloat::IEEEhalf())
Dan Gohmance163392011-12-17 00:04:22 +00001292 return true;
Stephan Bergmann20a600c2016-12-14 11:57:17 +00001293 Val2.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven, &losesInfo);
Dan Gohmance163392011-12-17 00:04:22 +00001294 return !losesInfo;
1295 }
Dale Johannesen23a98552008-10-09 23:00:39 +00001296 case Type::FloatTyID: {
Stephan Bergmann20a600c2016-12-14 11:57:17 +00001297 if (&Val2.getSemantics() == &APFloat::IEEEsingle())
Dale Johannesen23a98552008-10-09 23:00:39 +00001298 return true;
Stephan Bergmann20a600c2016-12-14 11:57:17 +00001299 Val2.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, &losesInfo);
Dale Johannesen23a98552008-10-09 23:00:39 +00001300 return !losesInfo;
1301 }
1302 case Type::DoubleTyID: {
Stephan Bergmann20a600c2016-12-14 11:57:17 +00001303 if (&Val2.getSemantics() == &APFloat::IEEEhalf() ||
1304 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1305 &Val2.getSemantics() == &APFloat::IEEEdouble())
Dale Johannesen23a98552008-10-09 23:00:39 +00001306 return true;
Stephan Bergmann20a600c2016-12-14 11:57:17 +00001307 Val2.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, &losesInfo);
Dale Johannesen23a98552008-10-09 23:00:39 +00001308 return !losesInfo;
1309 }
Dale Johannesenebbc95d2007-08-09 22:51:36 +00001310 case Type::X86_FP80TyID:
Stephan Bergmann20a600c2016-12-14 11:57:17 +00001311 return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
Bjorn Petterssona1ff84e2018-07-03 12:39:52 +00001312 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
Stephan Bergmann20a600c2016-12-14 11:57:17 +00001313 &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1314 &Val2.getSemantics() == &APFloat::x87DoubleExtended();
Dale Johannesenebbc95d2007-08-09 22:51:36 +00001315 case Type::FP128TyID:
Stephan Bergmann20a600c2016-12-14 11:57:17 +00001316 return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
Bjorn Petterssona1ff84e2018-07-03 12:39:52 +00001317 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
Stephan Bergmann20a600c2016-12-14 11:57:17 +00001318 &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1319 &Val2.getSemantics() == &APFloat::IEEEquad();
Dale Johannesena471c2e2007-10-11 18:07:22 +00001320 case Type::PPC_FP128TyID:
Stephan Bergmann20a600c2016-12-14 11:57:17 +00001321 return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
Bjorn Petterssona1ff84e2018-07-03 12:39:52 +00001322 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
Stephan Bergmann20a600c2016-12-14 11:57:17 +00001323 &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1324 &Val2.getSemantics() == &APFloat::PPCDoubleDouble();
Chris Lattner00950542001-06-06 20:29:01 +00001325 }
Chris Lattnerd74ea2b2006-05-24 17:04:05 +00001326}
Chris Lattner37bf6302001-07-20 19:16:02 +00001327
Chris Lattnerff2b7f32012-01-24 05:42:11 +00001328
Chris Lattner531daef2001-09-07 16:46:31 +00001329//===----------------------------------------------------------------------===//
Chris Lattner531daef2001-09-07 16:46:31 +00001330// Factory Function Implementation
1331
Chris Lattner9df0fb42012-01-23 15:20:12 +00001332ConstantAggregateZero *ConstantAggregateZero::get(Type *Ty) {
Chris Lattner61c70e92010-08-28 04:09:24 +00001333 assert((Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()) &&
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001334 "Cannot create an aggregate zero of non-aggregate type!");
David Blaikiebf3afab2014-11-25 02:13:54 +00001335
Justin Lebara2e3c5a2016-10-10 16:26:13 +00001336 std::unique_ptr<ConstantAggregateZero> &Entry =
1337 Ty->getContext().pImpl->CAZConstants[Ty];
1338 if (!Entry)
1339 Entry.reset(new ConstantAggregateZero(Ty));
1340
1341 return Entry.get();
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001342}
1343
Sanjay Patel0ac37a42016-04-29 22:03:27 +00001344/// Remove the constant from the constant table.
Pete Cooperd6218122015-06-23 21:55:11 +00001345void ConstantAggregateZero::destroyConstantImpl() {
Chris Lattner9df0fb42012-01-23 15:20:12 +00001346 getContext().pImpl->CAZConstants.erase(getType());
Chris Lattner40bbeb52004-02-15 05:53:04 +00001347}
1348
Sanjay Patel0ac37a42016-04-29 22:03:27 +00001349/// Remove the constant from the constant table.
Pete Cooperd6218122015-06-23 21:55:11 +00001350void ConstantArray::destroyConstantImpl() {
Chris Lattner1afcace2011-07-09 17:41:24 +00001351 getType()->getContext().pImpl->ArrayConstants.remove(this);
Chris Lattner02ec5ed2003-05-23 20:03:32 +00001352}
1353
Chris Lattner93aeea32002-08-26 17:53:56 +00001354
Chris Lattnere9bb2df2001-12-03 22:26:30 +00001355//---- ConstantStruct::get() implementation...
Chris Lattner531daef2001-09-07 16:46:31 +00001356//
Chris Lattnered468e372003-10-05 00:17:43 +00001357
Sanjay Patel0ac37a42016-04-29 22:03:27 +00001358/// Remove the constant from the constant table.
Pete Cooperd6218122015-06-23 21:55:11 +00001359void ConstantStruct::destroyConstantImpl() {
Chris Lattner1afcace2011-07-09 17:41:24 +00001360 getType()->getContext().pImpl->StructConstants.remove(this);
Chris Lattnerf5ec48d2001-10-13 06:57:33 +00001361}
Chris Lattner6a57baa2001-10-03 15:39:36 +00001362
Sanjay Patel0ac37a42016-04-29 22:03:27 +00001363/// Remove the constant from the constant table.
Pete Cooperd6218122015-06-23 21:55:11 +00001364void ConstantVector::destroyConstantImpl() {
Chris Lattner1afcace2011-07-09 17:41:24 +00001365 getType()->getContext().pImpl->VectorConstants.remove(this);
Brian Gaeke715c90b2004-08-20 06:00:58 +00001366}
1367
Duncan Sands2333e292012-11-13 12:59:33 +00001368Constant *Constant::getSplatValue() const {
1369 assert(this->getType()->isVectorTy() && "Only valid for vectors!");
1370 if (isa<ConstantAggregateZero>(this))
1371 return getNullValue(this->getType()->getVectorElementType());
1372 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
1373 return CV->getSplatValue();
1374 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
1375 return CV->getSplatValue();
Craig Topperec0f0bc2014-04-09 06:08:46 +00001376 return nullptr;
Duncan Sands2333e292012-11-13 12:59:33 +00001377}
1378
Duncan Sands7681c6d2011-02-01 08:39:12 +00001379Constant *ConstantVector::getSplatValue() const {
Dan Gohman3b7cf0a2007-10-17 17:51:30 +00001380 // Check out first element.
1381 Constant *Elt = getOperand(0);
1382 // Then make sure all remaining elements point to the same value.
1383 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
Chris Lattner3e194732011-07-17 06:01:30 +00001384 if (getOperand(I) != Elt)
Craig Topperec0f0bc2014-04-09 06:08:46 +00001385 return nullptr;
Dan Gohman3b7cf0a2007-10-17 17:51:30 +00001386 return Elt;
1387}
1388
Duncan Sands2333e292012-11-13 12:59:33 +00001389const APInt &Constant::getUniqueInteger() const {
1390 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
1391 return CI->getValue();
1392 assert(this->getSplatValue() && "Doesn't contain a unique integer!");
1393 const Constant *C = this->getAggregateElement(0U);
1394 assert(C && isa<ConstantInt>(C) && "Not a vector of numbers!");
1395 return cast<ConstantInt>(C)->getValue();
1396}
1397
Chris Lattner2ee11ec2009-10-28 00:01:44 +00001398//---- ConstantPointerNull::get() implementation.
Chris Lattnerf5ec48d2001-10-13 06:57:33 +00001399//
Chris Lattner02ec5ed2003-05-23 20:03:32 +00001400
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001401ConstantPointerNull *ConstantPointerNull::get(PointerType *Ty) {
Justin Lebara2e3c5a2016-10-10 16:26:13 +00001402 std::unique_ptr<ConstantPointerNull> &Entry =
1403 Ty->getContext().pImpl->CPNConstants[Ty];
Craig Topperec0f0bc2014-04-09 06:08:46 +00001404 if (!Entry)
Justin Lebara2e3c5a2016-10-10 16:26:13 +00001405 Entry.reset(new ConstantPointerNull(Ty));
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001406
Justin Lebara2e3c5a2016-10-10 16:26:13 +00001407 return Entry.get();
Chris Lattner6a57baa2001-10-03 15:39:36 +00001408}
1409
Sanjay Patel0ac37a42016-04-29 22:03:27 +00001410/// Remove the constant from the constant table.
Pete Cooperd6218122015-06-23 21:55:11 +00001411void ConstantPointerNull::destroyConstantImpl() {
Chris Lattner9df0fb42012-01-23 15:20:12 +00001412 getContext().pImpl->CPNConstants.erase(getType());
Chris Lattner41661fd2002-08-18 00:40:04 +00001413}
1414
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001415UndefValue *UndefValue::get(Type *Ty) {
Justin Lebara2e3c5a2016-10-10 16:26:13 +00001416 std::unique_ptr<UndefValue> &Entry = Ty->getContext().pImpl->UVConstants[Ty];
Craig Topperec0f0bc2014-04-09 06:08:46 +00001417 if (!Entry)
Justin Lebara2e3c5a2016-10-10 16:26:13 +00001418 Entry.reset(new UndefValue(Ty));
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001419
Justin Lebara2e3c5a2016-10-10 16:26:13 +00001420 return Entry.get();
Chris Lattnerb9f18592004-10-16 18:07:16 +00001421}
1422
Sanjay Patel0ac37a42016-04-29 22:03:27 +00001423/// Remove the constant from the constant table.
Pete Cooperd6218122015-06-23 21:55:11 +00001424void UndefValue::destroyConstantImpl() {
Chris Lattner9df0fb42012-01-23 15:20:12 +00001425 // Free the constant and any dangling references to it.
1426 getContext().pImpl->UVConstants.erase(getType());
Chris Lattnerb9f18592004-10-16 18:07:16 +00001427}
1428
Chris Lattner2ee11ec2009-10-28 00:01:44 +00001429BlockAddress *BlockAddress::get(BasicBlock *BB) {
Craig Topper0b6cb712014-04-15 06:32:26 +00001430 assert(BB->getParent() && "Block must have a parent");
Chris Lattner2ee11ec2009-10-28 00:01:44 +00001431 return get(BB->getParent(), BB);
1432}
1433
1434BlockAddress *BlockAddress::get(Function *F, BasicBlock *BB) {
1435 BlockAddress *&BA =
1436 F->getContext().pImpl->BlockAddresses[std::make_pair(F, BB)];
Craig Topperec0f0bc2014-04-09 06:08:46 +00001437 if (!BA)
Chris Lattner2ee11ec2009-10-28 00:01:44 +00001438 BA = new BlockAddress(F, BB);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001439
Chris Lattner2ee11ec2009-10-28 00:01:44 +00001440 assert(BA->getFunction() == F && "Basic block moved between functions");
1441 return BA;
1442}
1443
1444BlockAddress::BlockAddress(Function *F, BasicBlock *BB)
1445: Constant(Type::getInt8PtrTy(F->getContext()), Value::BlockAddressVal,
1446 &Op<0>(), 2) {
Chris Lattnerd0ec2352009-11-01 03:03:03 +00001447 setOperand(0, F);
1448 setOperand(1, BB);
Chris Lattnercdfc9402009-11-01 01:27:45 +00001449 BB->AdjustBlockAddressRefCount(1);
Chris Lattner2ee11ec2009-10-28 00:01:44 +00001450}
1451
Chandler Carruth60e425e2014-01-19 02:13:50 +00001452BlockAddress *BlockAddress::lookup(const BasicBlock *BB) {
1453 if (!BB->hasAddressTaken())
Craig Topperec0f0bc2014-04-09 06:08:46 +00001454 return nullptr;
Chandler Carruth60e425e2014-01-19 02:13:50 +00001455
1456 const Function *F = BB->getParent();
Craig Topper0b6cb712014-04-15 06:32:26 +00001457 assert(F && "Block must have a parent");
Chandler Carruth60e425e2014-01-19 02:13:50 +00001458 BlockAddress *BA =
1459 F->getContext().pImpl->BlockAddresses.lookup(std::make_pair(F, BB));
1460 assert(BA && "Refcount and block address map disagree!");
1461 return BA;
1462}
Chris Lattner2ee11ec2009-10-28 00:01:44 +00001463
Sanjay Patel0ac37a42016-04-29 22:03:27 +00001464/// Remove the constant from the constant table.
Pete Cooperd6218122015-06-23 21:55:11 +00001465void BlockAddress::destroyConstantImpl() {
Chris Lattner1afcace2011-07-09 17:41:24 +00001466 getFunction()->getType()->getContext().pImpl
Chris Lattner2ee11ec2009-10-28 00:01:44 +00001467 ->BlockAddresses.erase(std::make_pair(getFunction(), getBasicBlock()));
Chris Lattnercdfc9402009-11-01 01:27:45 +00001468 getBasicBlock()->AdjustBlockAddressRefCount(-1);
Chris Lattner2ee11ec2009-10-28 00:01:44 +00001469}
1470
Mehdi Amini4c696962016-02-10 22:47:15 +00001471Value *BlockAddress::handleOperandChangeImpl(Value *From, Value *To) {
Chris Lattner2ee11ec2009-10-28 00:01:44 +00001472 // This could be replacing either the Basic Block or the Function. In either
1473 // case, we have to remove the map entry.
1474 Function *NewF = getFunction();
1475 BasicBlock *NewBB = getBasicBlock();
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001476
Mehdi Amini4c696962016-02-10 22:47:15 +00001477 if (From == NewF)
Derek Schuffc06e5cf2013-06-13 19:51:17 +00001478 NewF = cast<Function>(To->stripPointerCasts());
Mehdi Amini4c696962016-02-10 22:47:15 +00001479 else {
1480 assert(From == NewBB && "From does not match any operand");
Chris Lattner2ee11ec2009-10-28 00:01:44 +00001481 NewBB = cast<BasicBlock>(To);
Mehdi Amini4c696962016-02-10 22:47:15 +00001482 }
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001483
Chris Lattner2ee11ec2009-10-28 00:01:44 +00001484 // See if the 'new' entry already exists, if not, just update this in place
1485 // and return early.
1486 BlockAddress *&NewBA =
1487 getContext().pImpl->BlockAddresses[std::make_pair(NewF, NewBB)];
Pete Cooper234c5892015-06-24 18:55:24 +00001488 if (NewBA)
1489 return NewBA;
Chris Lattner2ee11ec2009-10-28 00:01:44 +00001490
Duncan P. N. Exon Smith7116af62014-08-19 16:39:58 +00001491 getBasicBlock()->AdjustBlockAddressRefCount(-1);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001492
Duncan P. N. Exon Smith7116af62014-08-19 16:39:58 +00001493 // Remove the old entry, this can't cause the map to rehash (just a
1494 // tombstone will get added).
1495 getContext().pImpl->BlockAddresses.erase(std::make_pair(getFunction(),
1496 getBasicBlock()));
1497 NewBA = this;
1498 setOperand(0, NewF);
1499 setOperand(1, NewBB);
1500 getBasicBlock()->AdjustBlockAddressRefCount(1);
Pete Cooper234c5892015-06-24 18:55:24 +00001501
1502 // If we just want to keep the existing value, then return null.
1503 // Callers know that this means we shouldn't delete this value.
1504 return nullptr;
Chris Lattner2ee11ec2009-10-28 00:01:44 +00001505}
1506
1507//---- ConstantExpr::get() implementations.
Vikram S. Adve345e0cf2002-07-14 23:13:17 +00001508//
Reid Spencer79e21d32006-12-31 05:26:44 +00001509
Reid Spencer3da59db2006-11-27 01:05:10 +00001510/// This is a utility function to handle folding of casts and lookup of the
Duncan Sands66a1a052008-03-30 19:38:55 +00001511/// cast in the ExprConstants map. It is used by the various get* methods below.
Duncan P. N. Exon Smithe2215572014-08-19 19:45:37 +00001512static Constant *getFoldedCast(Instruction::CastOps opc, Constant *C, Type *Ty,
1513 bool OnlyIfReduced = false) {
Chris Lattner9eacf8a2003-10-07 22:19:19 +00001514 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
Reid Spencer3da59db2006-11-27 01:05:10 +00001515 // Fold a few common cases
Chris Lattnerb29d5962010-02-01 20:48:08 +00001516 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
Reid Spencer3da59db2006-11-27 01:05:10 +00001517 return FC;
Chris Lattnerd628f6a2003-04-17 19:24:48 +00001518
Duncan P. N. Exon Smithe2215572014-08-19 19:45:37 +00001519 if (OnlyIfReduced)
1520 return nullptr;
1521
Owen Andersond03eecd2009-08-04 20:25:11 +00001522 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
1523
Nadav Rotem82e905a2013-03-07 01:30:40 +00001524 // Look up the constant in the table first to ensure uniqueness.
Duncan P. N. Exon Smith7116af62014-08-19 16:39:58 +00001525 ConstantExprKeyType Key(opc, C);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001526
Owen Andersond03eecd2009-08-04 20:25:11 +00001527 return pImpl->ExprConstants.getOrCreate(Ty, Key);
Vikram S. Adve345e0cf2002-07-14 23:13:17 +00001528}
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001529
Duncan P. N. Exon Smithe2215572014-08-19 19:45:37 +00001530Constant *ConstantExpr::getCast(unsigned oc, Constant *C, Type *Ty,
1531 bool OnlyIfReduced) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001532 Instruction::CastOps opc = Instruction::CastOps(oc);
1533 assert(Instruction::isCast(opc) && "opcode out of range");
1534 assert(C && Ty && "Null arguments to getCast");
Chris Lattner0b68a002010-01-26 21:51:43 +00001535 assert(CastInst::castIsValid(opc, C, Ty) && "Invalid constantexpr cast!");
Reid Spencer3da59db2006-11-27 01:05:10 +00001536
1537 switch (opc) {
Chris Lattner0b68a002010-01-26 21:51:43 +00001538 default:
1539 llvm_unreachable("Invalid cast opcode");
Duncan P. N. Exon Smithe2215572014-08-19 19:45:37 +00001540 case Instruction::Trunc:
1541 return getTrunc(C, Ty, OnlyIfReduced);
1542 case Instruction::ZExt:
1543 return getZExt(C, Ty, OnlyIfReduced);
1544 case Instruction::SExt:
1545 return getSExt(C, Ty, OnlyIfReduced);
1546 case Instruction::FPTrunc:
1547 return getFPTrunc(C, Ty, OnlyIfReduced);
1548 case Instruction::FPExt:
1549 return getFPExtend(C, Ty, OnlyIfReduced);
1550 case Instruction::UIToFP:
1551 return getUIToFP(C, Ty, OnlyIfReduced);
1552 case Instruction::SIToFP:
1553 return getSIToFP(C, Ty, OnlyIfReduced);
1554 case Instruction::FPToUI:
1555 return getFPToUI(C, Ty, OnlyIfReduced);
1556 case Instruction::FPToSI:
1557 return getFPToSI(C, Ty, OnlyIfReduced);
1558 case Instruction::PtrToInt:
1559 return getPtrToInt(C, Ty, OnlyIfReduced);
1560 case Instruction::IntToPtr:
1561 return getIntToPtr(C, Ty, OnlyIfReduced);
1562 case Instruction::BitCast:
1563 return getBitCast(C, Ty, OnlyIfReduced);
1564 case Instruction::AddrSpaceCast:
1565 return getAddrSpaceCast(C, Ty, OnlyIfReduced);
Chris Lattnerf5ac6c22005-01-01 15:59:57 +00001566 }
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001567}
Reid Spencer7858b332006-12-05 19:14:13 +00001568
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001569Constant *ConstantExpr::getZExtOrBitCast(Constant *C, Type *Ty) {
Dan Gohman6de29f82009-06-15 22:12:54 +00001570 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
Dan Gohman3b490632010-04-12 22:12:29 +00001571 return getBitCast(C, Ty);
1572 return getZExt(C, Ty);
Reid Spencer848414e2006-12-04 20:17:56 +00001573}
1574
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001575Constant *ConstantExpr::getSExtOrBitCast(Constant *C, Type *Ty) {
Dan Gohman6de29f82009-06-15 22:12:54 +00001576 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
Dan Gohman3b490632010-04-12 22:12:29 +00001577 return getBitCast(C, Ty);
1578 return getSExt(C, Ty);
Reid Spencer848414e2006-12-04 20:17:56 +00001579}
1580
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001581Constant *ConstantExpr::getTruncOrBitCast(Constant *C, Type *Ty) {
Dan Gohman6de29f82009-06-15 22:12:54 +00001582 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
Dan Gohman3b490632010-04-12 22:12:29 +00001583 return getBitCast(C, Ty);
1584 return getTrunc(C, Ty);
Reid Spencer848414e2006-12-04 20:17:56 +00001585}
1586
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001587Constant *ConstantExpr::getPointerCast(Constant *S, Type *Ty) {
Evgeniy Stepanov655578f2013-01-16 14:41:46 +00001588 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
1589 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
1590 "Invalid cast");
Reid Spencerc0459fb2006-12-05 03:25:26 +00001591
Evgeniy Stepanov655578f2013-01-16 14:41:46 +00001592 if (Ty->isIntOrIntVectorTy())
Dan Gohman3b490632010-04-12 22:12:29 +00001593 return getPtrToInt(S, Ty);
Matt Arsenault59d3ae62013-11-15 01:34:59 +00001594
1595 unsigned SrcAS = S->getType()->getPointerAddressSpace();
1596 if (Ty->isPtrOrPtrVectorTy() && SrcAS != Ty->getPointerAddressSpace())
1597 return getAddrSpaceCast(S, Ty);
1598
Dan Gohman3b490632010-04-12 22:12:29 +00001599 return getBitCast(S, Ty);
Reid Spencerc0459fb2006-12-05 03:25:26 +00001600}
1601
Matt Arsenault47172e82013-12-07 02:58:41 +00001602Constant *ConstantExpr::getPointerBitCastOrAddrSpaceCast(Constant *S,
1603 Type *Ty) {
1604 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
1605 assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
1606
1607 if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
1608 return getAddrSpaceCast(S, Ty);
1609
1610 return getBitCast(S, Ty);
1611}
1612
Sanjay Patel7aae44e2016-05-18 22:05:28 +00001613Constant *ConstantExpr::getIntegerCast(Constant *C, Type *Ty, bool isSigned) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001614 assert(C->getType()->isIntOrIntVectorTy() &&
1615 Ty->isIntOrIntVectorTy() && "Invalid cast");
Dan Gohman6de29f82009-06-15 22:12:54 +00001616 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1617 unsigned DstBits = Ty->getScalarSizeInBits();
Reid Spencer84f3eab2006-12-12 00:51:07 +00001618 Instruction::CastOps opcode =
1619 (SrcBits == DstBits ? Instruction::BitCast :
1620 (SrcBits > DstBits ? Instruction::Trunc :
1621 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1622 return getCast(opcode, C, Ty);
1623}
1624
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001625Constant *ConstantExpr::getFPCast(Constant *C, Type *Ty) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001626 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
Reid Spencer84f3eab2006-12-12 00:51:07 +00001627 "Invalid cast");
Dan Gohman6de29f82009-06-15 22:12:54 +00001628 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1629 unsigned DstBits = Ty->getScalarSizeInBits();
Reid Spencerf25212a2006-12-12 05:38:50 +00001630 if (SrcBits == DstBits)
1631 return C; // Avoid a useless cast
Reid Spencer84f3eab2006-12-12 00:51:07 +00001632 Instruction::CastOps opcode =
Jay Foad9afc5272011-01-27 14:44:55 +00001633 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
Reid Spencer84f3eab2006-12-12 00:51:07 +00001634 return getCast(opcode, C, Ty);
1635}
1636
Duncan P. N. Exon Smithe2215572014-08-19 19:45:37 +00001637Constant *ConstantExpr::getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) {
Dan Gohman6de29f82009-06-15 22:12:54 +00001638#ifndef NDEBUG
1639 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1640 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1641#endif
1642 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001643 assert(C->getType()->isIntOrIntVectorTy() && "Trunc operand must be integer");
1644 assert(Ty->isIntOrIntVectorTy() && "Trunc produces only integral");
Dan Gohman6de29f82009-06-15 22:12:54 +00001645 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
Reid Spencer3da59db2006-11-27 01:05:10 +00001646 "SrcTy must be larger than DestTy for Trunc!");
1647
Duncan P. N. Exon Smithe2215572014-08-19 19:45:37 +00001648 return getFoldedCast(Instruction::Trunc, C, Ty, OnlyIfReduced);
Reid Spencer3da59db2006-11-27 01:05:10 +00001649}
1650
Duncan P. N. Exon Smithe2215572014-08-19 19:45:37 +00001651Constant *ConstantExpr::getSExt(Constant *C, Type *Ty, bool OnlyIfReduced) {
Dan Gohman6de29f82009-06-15 22:12:54 +00001652#ifndef NDEBUG
1653 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1654 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1655#endif
1656 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001657 assert(C->getType()->isIntOrIntVectorTy() && "SExt operand must be integral");
1658 assert(Ty->isIntOrIntVectorTy() && "SExt produces only integer");
Dan Gohman6de29f82009-06-15 22:12:54 +00001659 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
Reid Spencer3da59db2006-11-27 01:05:10 +00001660 "SrcTy must be smaller than DestTy for SExt!");
1661
Duncan P. N. Exon Smithe2215572014-08-19 19:45:37 +00001662 return getFoldedCast(Instruction::SExt, C, Ty, OnlyIfReduced);
Chris Lattnerd144f422004-04-04 23:20:30 +00001663}
1664
Duncan P. N. Exon Smithe2215572014-08-19 19:45:37 +00001665Constant *ConstantExpr::getZExt(Constant *C, Type *Ty, bool OnlyIfReduced) {
Dan Gohman6de29f82009-06-15 22:12:54 +00001666#ifndef NDEBUG
1667 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1668 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1669#endif
1670 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001671 assert(C->getType()->isIntOrIntVectorTy() && "ZEXt operand must be integral");
1672 assert(Ty->isIntOrIntVectorTy() && "ZExt produces only integer");
Dan Gohman6de29f82009-06-15 22:12:54 +00001673 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
Reid Spencer3da59db2006-11-27 01:05:10 +00001674 "SrcTy must be smaller than DestTy for ZExt!");
1675
Duncan P. N. Exon Smithe2215572014-08-19 19:45:37 +00001676 return getFoldedCast(Instruction::ZExt, C, Ty, OnlyIfReduced);
Reid Spencer3da59db2006-11-27 01:05:10 +00001677}
1678
Duncan P. N. Exon Smithe2215572014-08-19 19:45:37 +00001679Constant *ConstantExpr::getFPTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) {
Dan Gohman6de29f82009-06-15 22:12:54 +00001680#ifndef NDEBUG
1681 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1682 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1683#endif
1684 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001685 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00001686 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
Reid Spencer3da59db2006-11-27 01:05:10 +00001687 "This is an illegal floating point truncation!");
Duncan P. N. Exon Smithe2215572014-08-19 19:45:37 +00001688 return getFoldedCast(Instruction::FPTrunc, C, Ty, OnlyIfReduced);
Reid Spencer3da59db2006-11-27 01:05:10 +00001689}
1690
Duncan P. N. Exon Smithe2215572014-08-19 19:45:37 +00001691Constant *ConstantExpr::getFPExtend(Constant *C, Type *Ty, bool OnlyIfReduced) {
Dan Gohman6de29f82009-06-15 22:12:54 +00001692#ifndef NDEBUG
1693 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1694 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1695#endif
1696 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001697 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00001698 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
Reid Spencer3da59db2006-11-27 01:05:10 +00001699 "This is an illegal floating point extension!");
Duncan P. N. Exon Smithe2215572014-08-19 19:45:37 +00001700 return getFoldedCast(Instruction::FPExt, C, Ty, OnlyIfReduced);
Reid Spencer3da59db2006-11-27 01:05:10 +00001701}
1702
Duncan P. N. Exon Smithe2215572014-08-19 19:45:37 +00001703Constant *ConstantExpr::getUIToFP(Constant *C, Type *Ty, bool OnlyIfReduced) {
Devang Patelb6dc9352008-11-03 23:20:04 +00001704#ifndef NDEBUG
Nate Begemanb348d182007-11-17 03:58:34 +00001705 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1706 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Patelb6dc9352008-11-03 23:20:04 +00001707#endif
Nate Begemanb348d182007-11-17 03:58:34 +00001708 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001709 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
Nate Begemanb348d182007-11-17 03:58:34 +00001710 "This is an illegal uint to floating point cast!");
Duncan P. N. Exon Smithe2215572014-08-19 19:45:37 +00001711 return getFoldedCast(Instruction::UIToFP, C, Ty, OnlyIfReduced);
Reid Spencer3da59db2006-11-27 01:05:10 +00001712}
1713
Duncan P. N. Exon Smithe2215572014-08-19 19:45:37 +00001714Constant *ConstantExpr::getSIToFP(Constant *C, Type *Ty, bool OnlyIfReduced) {
Devang Patelb6dc9352008-11-03 23:20:04 +00001715#ifndef NDEBUG
Nate Begemanb348d182007-11-17 03:58:34 +00001716 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1717 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Patelb6dc9352008-11-03 23:20:04 +00001718#endif
Nate Begemanb348d182007-11-17 03:58:34 +00001719 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001720 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
Reid Spencer3da59db2006-11-27 01:05:10 +00001721 "This is an illegal sint to floating point cast!");
Duncan P. N. Exon Smithe2215572014-08-19 19:45:37 +00001722 return getFoldedCast(Instruction::SIToFP, C, Ty, OnlyIfReduced);
Reid Spencer3da59db2006-11-27 01:05:10 +00001723}
1724
Duncan P. N. Exon Smithe2215572014-08-19 19:45:37 +00001725Constant *ConstantExpr::getFPToUI(Constant *C, Type *Ty, bool OnlyIfReduced) {
Devang Patelb6dc9352008-11-03 23:20:04 +00001726#ifndef NDEBUG
Nate Begemanb348d182007-11-17 03:58:34 +00001727 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1728 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Patelb6dc9352008-11-03 23:20:04 +00001729#endif
Nate Begemanb348d182007-11-17 03:58:34 +00001730 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001731 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
Nate Begemanb348d182007-11-17 03:58:34 +00001732 "This is an illegal floating point to uint cast!");
Duncan P. N. Exon Smithe2215572014-08-19 19:45:37 +00001733 return getFoldedCast(Instruction::FPToUI, C, Ty, OnlyIfReduced);
Reid Spencer3da59db2006-11-27 01:05:10 +00001734}
1735
Duncan P. N. Exon Smithe2215572014-08-19 19:45:37 +00001736Constant *ConstantExpr::getFPToSI(Constant *C, Type *Ty, bool OnlyIfReduced) {
Devang Patelb6dc9352008-11-03 23:20:04 +00001737#ifndef NDEBUG
Nate Begemanb348d182007-11-17 03:58:34 +00001738 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1739 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Patelb6dc9352008-11-03 23:20:04 +00001740#endif
Nate Begemanb348d182007-11-17 03:58:34 +00001741 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001742 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
Nate Begemanb348d182007-11-17 03:58:34 +00001743 "This is an illegal floating point to sint cast!");
Duncan P. N. Exon Smithe2215572014-08-19 19:45:37 +00001744 return getFoldedCast(Instruction::FPToSI, C, Ty, OnlyIfReduced);
Reid Spencer3da59db2006-11-27 01:05:10 +00001745}
1746
Duncan P. N. Exon Smithe2215572014-08-19 19:45:37 +00001747Constant *ConstantExpr::getPtrToInt(Constant *C, Type *DstTy,
1748 bool OnlyIfReduced) {
Craig Topper10600822017-07-09 07:04:00 +00001749 assert(C->getType()->isPtrOrPtrVectorTy() &&
Nadav Rotem16087692011-12-05 06:29:09 +00001750 "PtrToInt source must be pointer or pointer vector");
Craig Topper10600822017-07-09 07:04:00 +00001751 assert(DstTy->isIntOrIntVectorTy() &&
Nadav Rotem16087692011-12-05 06:29:09 +00001752 "PtrToInt destination must be integer or integer vector");
Chris Lattneraf7b4fb2012-01-25 01:32:59 +00001753 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
Nick Lewycky1486ae62012-01-25 03:20:12 +00001754 if (isa<VectorType>(C->getType()))
Chris Lattner230cdab2012-01-26 00:42:34 +00001755 assert(C->getType()->getVectorNumElements()==DstTy->getVectorNumElements()&&
Chris Lattneraf7b4fb2012-01-25 01:32:59 +00001756 "Invalid cast between a different number of vector elements");
Duncan P. N. Exon Smithe2215572014-08-19 19:45:37 +00001757 return getFoldedCast(Instruction::PtrToInt, C, DstTy, OnlyIfReduced);
Reid Spencer3da59db2006-11-27 01:05:10 +00001758}
1759
Duncan P. N. Exon Smithe2215572014-08-19 19:45:37 +00001760Constant *ConstantExpr::getIntToPtr(Constant *C, Type *DstTy,
1761 bool OnlyIfReduced) {
Craig Topper10600822017-07-09 07:04:00 +00001762 assert(C->getType()->isIntOrIntVectorTy() &&
Nadav Rotem16087692011-12-05 06:29:09 +00001763 "IntToPtr source must be integer or integer vector");
Craig Topper10600822017-07-09 07:04:00 +00001764 assert(DstTy->isPtrOrPtrVectorTy() &&
Nadav Rotem16087692011-12-05 06:29:09 +00001765 "IntToPtr destination must be a pointer or pointer vector");
Chris Lattneraf7b4fb2012-01-25 01:32:59 +00001766 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
Nick Lewycky1486ae62012-01-25 03:20:12 +00001767 if (isa<VectorType>(C->getType()))
Chris Lattner230cdab2012-01-26 00:42:34 +00001768 assert(C->getType()->getVectorNumElements()==DstTy->getVectorNumElements()&&
Chris Lattneraf7b4fb2012-01-25 01:32:59 +00001769 "Invalid cast between a different number of vector elements");
Duncan P. N. Exon Smithe2215572014-08-19 19:45:37 +00001770 return getFoldedCast(Instruction::IntToPtr, C, DstTy, OnlyIfReduced);
Reid Spencer3da59db2006-11-27 01:05:10 +00001771}
1772
Duncan P. N. Exon Smithe2215572014-08-19 19:45:37 +00001773Constant *ConstantExpr::getBitCast(Constant *C, Type *DstTy,
1774 bool OnlyIfReduced) {
Chris Lattner0b68a002010-01-26 21:51:43 +00001775 assert(CastInst::castIsValid(Instruction::BitCast, C, DstTy) &&
1776 "Invalid constantexpr bitcast!");
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001777
Chris Lattner8c7f24a2009-03-21 06:55:54 +00001778 // It is common to ask for a bitcast of a value to its own type, handle this
1779 // speedily.
1780 if (C->getType() == DstTy) return C;
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001781
Duncan P. N. Exon Smithe2215572014-08-19 19:45:37 +00001782 return getFoldedCast(Instruction::BitCast, C, DstTy, OnlyIfReduced);
Chris Lattnerd144f422004-04-04 23:20:30 +00001783}
1784
Duncan P. N. Exon Smithe2215572014-08-19 19:45:37 +00001785Constant *ConstantExpr::getAddrSpaceCast(Constant *C, Type *DstTy,
1786 bool OnlyIfReduced) {
Matt Arsenault59d3ae62013-11-15 01:34:59 +00001787 assert(CastInst::castIsValid(Instruction::AddrSpaceCast, C, DstTy) &&
1788 "Invalid constantexpr addrspacecast!");
1789
Jingyue Wuf6eb7e32014-06-15 21:40:57 +00001790 // Canonicalize addrspacecasts between different pointer types by first
1791 // bitcasting the pointer type and then converting the address space.
1792 PointerType *SrcScalarTy = cast<PointerType>(C->getType()->getScalarType());
1793 PointerType *DstScalarTy = cast<PointerType>(DstTy->getScalarType());
1794 Type *DstElemTy = DstScalarTy->getElementType();
1795 if (SrcScalarTy->getElementType() != DstElemTy) {
1796 Type *MidTy = PointerType::get(DstElemTy, SrcScalarTy->getAddressSpace());
1797 if (VectorType *VT = dyn_cast<VectorType>(DstTy)) {
1798 // Handle vectors of pointers.
1799 MidTy = VectorType::get(MidTy, VT->getNumElements());
1800 }
1801 C = getBitCast(C, MidTy);
1802 }
Duncan P. N. Exon Smithe2215572014-08-19 19:45:37 +00001803 return getFoldedCast(Instruction::AddrSpaceCast, C, DstTy, OnlyIfReduced);
Matt Arsenault59d3ae62013-11-15 01:34:59 +00001804}
1805
Cameron McInallyca8cb682018-11-13 18:15:47 +00001806Constant *ConstantExpr::get(unsigned Opcode, Constant *C, unsigned Flags,
1807 Type *OnlyIfReducedTy) {
1808 // Check the operands for consistency first.
1809 assert(Instruction::isUnaryOp(Opcode) &&
1810 "Invalid opcode in unary constant expression");
1811
1812#ifndef NDEBUG
1813 switch (Opcode) {
1814 case Instruction::FNeg:
1815 assert(C->getType()->isFPOrFPVectorTy() &&
1816 "Tried to create a floating-point operation on a "
1817 "non-floating-point type!");
1818 break;
1819 default:
1820 break;
1821 }
1822#endif
1823
1824 // TODO: Try to constant fold operation.
1825
1826 if (OnlyIfReducedTy == C->getType())
1827 return nullptr;
1828
1829 Constant *ArgVec[] = { C };
1830 ConstantExprKeyType Key(Opcode, ArgVec, 0, Flags);
1831
1832 LLVMContextImpl *pImpl = C->getContext().pImpl;
1833 return pImpl->ExprConstants.getOrCreate(C->getType(), Key);
1834}
1835
Chris Lattnereaf79802011-07-09 18:23:52 +00001836Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2,
Duncan P. N. Exon Smithe2215572014-08-19 19:45:37 +00001837 unsigned Flags, Type *OnlyIfReducedTy) {
Chris Lattnereaf79802011-07-09 18:23:52 +00001838 // Check the operands for consistency first.
Simon Pilgrim0b0278f2018-06-22 10:48:02 +00001839 assert(Instruction::isBinaryOp(Opcode) &&
Chris Lattnerf31f5832003-05-21 17:49:25 +00001840 "Invalid opcode in binary constant expression");
1841 assert(C1->getType() == C2->getType() &&
1842 "Operand types in binary constant expression should match");
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001843
Chris Lattner91b362b2004-08-17 17:28:46 +00001844#ifndef NDEBUG
1845 switch (Opcode) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001846 case Instruction::Add:
Reid Spencer0a783f72006-11-02 01:53:59 +00001847 case Instruction::Sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001848 case Instruction::Mul:
Chris Lattner91b362b2004-08-17 17:28:46 +00001849 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001850 assert(C1->getType()->isIntOrIntVectorTy() &&
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001851 "Tried to create an integer operation on a non-integer type!");
1852 break;
1853 case Instruction::FAdd:
1854 case Instruction::FSub:
1855 case Instruction::FMul:
1856 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001857 assert(C1->getType()->isFPOrFPVectorTy() &&
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001858 "Tried to create a floating-point operation on a "
1859 "non-floating-point type!");
Chris Lattner91b362b2004-08-17 17:28:46 +00001860 break;
Bjorn Petterssona1ff84e2018-07-03 12:39:52 +00001861 case Instruction::UDiv:
1862 case Instruction::SDiv:
Reid Spencer1628cec2006-10-26 06:15:43 +00001863 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001864 assert(C1->getType()->isIntOrIntVectorTy() &&
Reid Spencer1628cec2006-10-26 06:15:43 +00001865 "Tried to create an arithmetic operation on a non-arithmetic type!");
1866 break;
1867 case Instruction::FDiv:
1868 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001869 assert(C1->getType()->isFPOrFPVectorTy() &&
Dan Gohmanf57478f2009-06-15 22:25:12 +00001870 "Tried to create an arithmetic operation on a non-arithmetic type!");
Reid Spencer1628cec2006-10-26 06:15:43 +00001871 break;
Bjorn Petterssona1ff84e2018-07-03 12:39:52 +00001872 case Instruction::URem:
1873 case Instruction::SRem:
Reid Spencer0a783f72006-11-02 01:53:59 +00001874 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001875 assert(C1->getType()->isIntOrIntVectorTy() &&
Reid Spencer0a783f72006-11-02 01:53:59 +00001876 "Tried to create an arithmetic operation on a non-arithmetic type!");
1877 break;
1878 case Instruction::FRem:
1879 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001880 assert(C1->getType()->isFPOrFPVectorTy() &&
Dan Gohmanf57478f2009-06-15 22:25:12 +00001881 "Tried to create an arithmetic operation on a non-arithmetic type!");
Reid Spencer0a783f72006-11-02 01:53:59 +00001882 break;
Chris Lattner91b362b2004-08-17 17:28:46 +00001883 case Instruction::And:
1884 case Instruction::Or:
1885 case Instruction::Xor:
1886 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001887 assert(C1->getType()->isIntOrIntVectorTy() &&
Misha Brukman1bae2912005-01-27 06:46:38 +00001888 "Tried to create a logical operation on a non-integral type!");
Chris Lattner91b362b2004-08-17 17:28:46 +00001889 break;
Chris Lattner91b362b2004-08-17 17:28:46 +00001890 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00001891 case Instruction::LShr:
1892 case Instruction::AShr:
Reid Spencer832254e2007-02-02 02:16:23 +00001893 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001894 assert(C1->getType()->isIntOrIntVectorTy() &&
Chris Lattner91b362b2004-08-17 17:28:46 +00001895 "Tried to create a shift operation on a non-integer type!");
1896 break;
1897 default:
1898 break;
1899 }
1900#endif
1901
Chris Lattnereaf79802011-07-09 18:23:52 +00001902 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1903 return FC; // Fold a few common cases.
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001904
Duncan P. N. Exon Smithe2215572014-08-19 19:45:37 +00001905 if (OnlyIfReducedTy == C1->getType())
1906 return nullptr;
1907
Benjamin Kramer4e4cc7d2013-03-07 20:53:34 +00001908 Constant *ArgVec[] = { C1, C2 };
Duncan P. N. Exon Smith7116af62014-08-19 16:39:58 +00001909 ConstantExprKeyType Key(Opcode, ArgVec, 0, Flags);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001910
Chris Lattnereaf79802011-07-09 18:23:52 +00001911 LLVMContextImpl *pImpl = C1->getContext().pImpl;
1912 return pImpl->ExprConstants.getOrCreate(C1->getType(), Key);
Reid Spencer67263fe2006-12-04 21:35:24 +00001913}
1914
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001915Constant *ConstantExpr::getSizeOf(Type* Ty) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00001916 // sizeof is implemented as: (i64) gep (Ty*)null, 1
1917 // Note that a non-inbounds gep is used, as null isn't within any object.
Owen Anderson1d0be152009-08-13 21:58:54 +00001918 Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001919 Constant *GEP = getGetElementPtr(
David Blaikie19443c12015-04-02 18:55:32 +00001920 Ty, Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
Bjorn Petterssona1ff84e2018-07-03 12:39:52 +00001921 return getPtrToInt(GEP,
Dan Gohman3b490632010-04-12 22:12:29 +00001922 Type::getInt64Ty(Ty->getContext()));
Owen Andersonbaf3c402009-07-29 18:55:55 +00001923}
1924
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001925Constant *ConstantExpr::getAlignOf(Type* Ty) {
Dan Gohman0f5efe52010-01-28 02:15:55 +00001926 // alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1
Dan Gohmane2574d32009-08-11 17:57:01 +00001927 // Note that a non-inbounds gep is used, as null isn't within any object.
Serge Gueltond35f86e2017-05-09 19:31:13 +00001928 Type *AligningTy = StructType::get(Type::getInt1Ty(Ty->getContext()), Ty);
Matt Arsenaultb5a391a2014-04-23 20:58:57 +00001929 Constant *NullPtr = Constant::getNullValue(AligningTy->getPointerTo(0));
Dan Gohman06ed3e72010-01-28 02:43:22 +00001930 Constant *Zero = ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0);
Owen Anderson1d0be152009-08-13 21:58:54 +00001931 Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001932 Constant *Indices[2] = { Zero, One };
David Blaikie19443c12015-04-02 18:55:32 +00001933 Constant *GEP = getGetElementPtr(AligningTy, NullPtr, Indices);
Dan Gohman3b490632010-04-12 22:12:29 +00001934 return getPtrToInt(GEP,
1935 Type::getInt64Ty(Ty->getContext()));
Owen Andersonbaf3c402009-07-29 18:55:55 +00001936}
1937
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001938Constant *ConstantExpr::getOffsetOf(StructType* STy, unsigned FieldNo) {
Dan Gohman2544a1d2010-02-01 16:37:38 +00001939 return getOffsetOf(STy, ConstantInt::get(Type::getInt32Ty(STy->getContext()),
1940 FieldNo));
1941}
1942
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001943Constant *ConstantExpr::getOffsetOf(Type* Ty, Constant *FieldNo) {
Dan Gohman3778f212009-08-16 21:26:11 +00001944 // offsetof is implemented as: (i64) gep (Ty*)null, 0, FieldNo
1945 // Note that a non-inbounds gep is used, as null isn't within any object.
1946 Constant *GEPIdx[] = {
Dan Gohman2544a1d2010-02-01 16:37:38 +00001947 ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0),
1948 FieldNo
Dan Gohman3778f212009-08-16 21:26:11 +00001949 };
1950 Constant *GEP = getGetElementPtr(
David Blaikie19443c12015-04-02 18:55:32 +00001951 Ty, Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
Dan Gohman3b490632010-04-12 22:12:29 +00001952 return getPtrToInt(GEP,
1953 Type::getInt64Ty(Ty->getContext()));
Dan Gohman3778f212009-08-16 21:26:11 +00001954}
Owen Andersonbaf3c402009-07-29 18:55:55 +00001955
Duncan P. N. Exon Smithe2215572014-08-19 19:45:37 +00001956Constant *ConstantExpr::getCompare(unsigned short Predicate, Constant *C1,
1957 Constant *C2, bool OnlyIfReduced) {
Reid Spencer67263fe2006-12-04 21:35:24 +00001958 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001959
Chris Lattnereaf79802011-07-09 18:23:52 +00001960 switch (Predicate) {
1961 default: llvm_unreachable("Invalid CmpInst predicate");
1962 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
1963 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
1964 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
1965 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
1966 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
1967 case CmpInst::FCMP_TRUE:
Duncan P. N. Exon Smithe2215572014-08-19 19:45:37 +00001968 return getFCmp(Predicate, C1, C2, OnlyIfReduced);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001969
Chris Lattnereaf79802011-07-09 18:23:52 +00001970 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
1971 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
1972 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
1973 case CmpInst::ICMP_SLE:
Duncan P. N. Exon Smithe2215572014-08-19 19:45:37 +00001974 return getICmp(Predicate, C1, C2, OnlyIfReduced);
Chris Lattnereaf79802011-07-09 18:23:52 +00001975 }
Chris Lattnerc3d12f02004-08-04 18:50:09 +00001976}
1977
Duncan P. N. Exon Smithe2215572014-08-19 19:45:37 +00001978Constant *ConstantExpr::getSelect(Constant *C, Constant *V1, Constant *V2,
1979 Type *OnlyIfReducedTy) {
Chris Lattner9ace0cd2008-12-29 00:16:12 +00001980 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
Chris Lattner08a45cc2004-03-12 05:54:04 +00001981
Chris Lattnereaf79802011-07-09 18:23:52 +00001982 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1983 return SC; // Fold common cases
Chris Lattner08a45cc2004-03-12 05:54:04 +00001984
Duncan P. N. Exon Smithe2215572014-08-19 19:45:37 +00001985 if (OnlyIfReducedTy == V1->getType())
1986 return nullptr;
1987
Benjamin Kramer4e4cc7d2013-03-07 20:53:34 +00001988 Constant *ArgVec[] = { C, V1, V2 };
Duncan P. N. Exon Smith7116af62014-08-19 16:39:58 +00001989 ConstantExprKeyType Key(Instruction::Select, ArgVec);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001990
Chris Lattnereaf79802011-07-09 18:23:52 +00001991 LLVMContextImpl *pImpl = C->getContext().pImpl;
1992 return pImpl->ExprConstants.getOrCreate(V1->getType(), Key);
Chris Lattner08a45cc2004-03-12 05:54:04 +00001993}
1994
David Blaikie19443c12015-04-02 18:55:32 +00001995Constant *ConstantExpr::getGetElementPtr(Type *Ty, Constant *C,
1996 ArrayRef<Value *> Idxs, bool InBounds,
Peter Collingbourneca668e12016-11-10 22:34:55 +00001997 Optional<unsigned> InRangeIndex,
David Blaikie19443c12015-04-02 18:55:32 +00001998 Type *OnlyIfReducedTy) {
David Blaikie19443c12015-04-02 18:55:32 +00001999 if (!Ty)
2000 Ty = cast<PointerType>(C->getType()->getScalarType())->getElementType();
2001 else
James Y Knight719df2e2019-01-10 16:07:20 +00002002 assert(Ty ==
2003 cast<PointerType>(C->getType()->getScalarType())->getElementType());
David Blaikiead80c2d2015-05-07 17:28:58 +00002004
Peter Collingbourneca668e12016-11-10 22:34:55 +00002005 if (Constant *FC =
2006 ConstantFoldGetElementPtr(Ty, C, InBounds, InRangeIndex, Idxs))
David Blaikiead80c2d2015-05-07 17:28:58 +00002007 return FC; // Fold a few common cases.
2008
Chris Lattnereaf79802011-07-09 18:23:52 +00002009 // Get the result type of the getelementptr!
David Blaikie19443c12015-04-02 18:55:32 +00002010 Type *DestTy = GetElementPtrInst::getIndexedType(Ty, Idxs);
2011 assert(DestTy && "GEP indices invalid!");
Chris Lattner230cdab2012-01-26 00:42:34 +00002012 unsigned AS = C->getType()->getPointerAddressSpace();
David Blaikie19443c12015-04-02 18:55:32 +00002013 Type *ReqTy = DestTy->getPointerTo(AS);
Elena Demikhovsky746e3ce2016-05-15 12:30:25 +00002014
2015 unsigned NumVecElts = 0;
2016 if (C->getType()->isVectorTy())
2017 NumVecElts = C->getType()->getVectorNumElements();
2018 else for (auto Idx : Idxs)
2019 if (Idx->getType()->isVectorTy())
2020 NumVecElts = Idx->getType()->getVectorNumElements();
2021
2022 if (NumVecElts)
2023 ReqTy = VectorType::get(ReqTy, NumVecElts);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002024
Duncan P. N. Exon Smithe2215572014-08-19 19:45:37 +00002025 if (OnlyIfReducedTy == ReqTy)
2026 return nullptr;
2027
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002028 // Look up the constant in the table first to ensure uniqueness
2029 std::vector<Constant*> ArgVec;
Jay Foaddab3d292011-07-21 14:31:17 +00002030 ArgVec.reserve(1 + Idxs.size());
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002031 ArgVec.push_back(C);
Duncan Sands2333e292012-11-13 12:59:33 +00002032 for (unsigned i = 0, e = Idxs.size(); i != e; ++i) {
Duncan Sands2333e292012-11-13 12:59:33 +00002033 assert((!Idxs[i]->getType()->isVectorTy() ||
Elena Demikhovsky746e3ce2016-05-15 12:30:25 +00002034 Idxs[i]->getType()->getVectorNumElements() == NumVecElts) &&
Duncan Sands2333e292012-11-13 12:59:33 +00002035 "getelementptr index type missmatch");
Elena Demikhovsky746e3ce2016-05-15 12:30:25 +00002036
2037 Constant *Idx = cast<Constant>(Idxs[i]);
2038 if (NumVecElts && !Idxs[i]->getType()->isVectorTy())
2039 Idx = ConstantVector::getSplat(NumVecElts, Idx);
2040 ArgVec.push_back(Idx);
Duncan Sands2333e292012-11-13 12:59:33 +00002041 }
Peter Collingbourneca668e12016-11-10 22:34:55 +00002042
2043 unsigned SubClassOptionalData = InBounds ? GEPOperator::IsInBounds : 0;
2044 if (InRangeIndex && *InRangeIndex < 63)
2045 SubClassOptionalData |= (*InRangeIndex + 1) << 1;
Duncan P. N. Exon Smith7116af62014-08-19 16:39:58 +00002046 const ConstantExprKeyType Key(Instruction::GetElementPtr, ArgVec, 0,
Peter Collingbourneca668e12016-11-10 22:34:55 +00002047 SubClassOptionalData, None, Ty);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002048
Chris Lattnereaf79802011-07-09 18:23:52 +00002049 LLVMContextImpl *pImpl = C->getContext().pImpl;
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002050 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2051}
2052
Duncan P. N. Exon Smithe2215572014-08-19 19:45:37 +00002053Constant *ConstantExpr::getICmp(unsigned short pred, Constant *LHS,
2054 Constant *RHS, bool OnlyIfReduced) {
Reid Spencer077d0eb2006-12-04 05:19:50 +00002055 assert(LHS->getType() == RHS->getType());
Craig Topper3208bb22017-07-05 23:35:46 +00002056 assert(CmpInst::isIntPredicate((CmpInst::Predicate)pred) &&
2057 "Invalid ICmp Predicate");
Reid Spencer077d0eb2006-12-04 05:19:50 +00002058
Chris Lattnerb29d5962010-02-01 20:48:08 +00002059 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
Reid Spencer077d0eb2006-12-04 05:19:50 +00002060 return FC; // Fold a few common cases...
2061
Duncan P. N. Exon Smithe2215572014-08-19 19:45:37 +00002062 if (OnlyIfReduced)
2063 return nullptr;
2064
Reid Spencer077d0eb2006-12-04 05:19:50 +00002065 // Look up the constant in the table first to ensure uniqueness
Benjamin Kramer4e4cc7d2013-03-07 20:53:34 +00002066 Constant *ArgVec[] = { LHS, RHS };
Reid Spencer4fa021a2006-12-24 18:42:29 +00002067 // Get the key type with both the opcode and predicate
Duncan P. N. Exon Smith7116af62014-08-19 16:39:58 +00002068 const ConstantExprKeyType Key(Instruction::ICmp, ArgVec, pred);
Owen Anderson31c36f02009-06-17 20:10:08 +00002069
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002070 Type *ResultTy = Type::getInt1Ty(LHS->getContext());
2071 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
Nick Lewycky401f3252010-01-21 07:03:21 +00002072 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
2073
Owen Andersond03eecd2009-08-04 20:25:11 +00002074 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
Nick Lewycky401f3252010-01-21 07:03:21 +00002075 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
Reid Spencer077d0eb2006-12-04 05:19:50 +00002076}
2077
Duncan P. N. Exon Smithe2215572014-08-19 19:45:37 +00002078Constant *ConstantExpr::getFCmp(unsigned short pred, Constant *LHS,
2079 Constant *RHS, bool OnlyIfReduced) {
Reid Spencer077d0eb2006-12-04 05:19:50 +00002080 assert(LHS->getType() == RHS->getType());
Craig Topper3208bb22017-07-05 23:35:46 +00002081 assert(CmpInst::isFPPredicate((CmpInst::Predicate)pred) &&
2082 "Invalid FCmp Predicate");
Reid Spencer077d0eb2006-12-04 05:19:50 +00002083
Chris Lattnerb29d5962010-02-01 20:48:08 +00002084 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
Reid Spencer077d0eb2006-12-04 05:19:50 +00002085 return FC; // Fold a few common cases...
2086
Duncan P. N. Exon Smithe2215572014-08-19 19:45:37 +00002087 if (OnlyIfReduced)
2088 return nullptr;
2089
Reid Spencer077d0eb2006-12-04 05:19:50 +00002090 // Look up the constant in the table first to ensure uniqueness
Benjamin Kramer4e4cc7d2013-03-07 20:53:34 +00002091 Constant *ArgVec[] = { LHS, RHS };
Reid Spencer4fa021a2006-12-24 18:42:29 +00002092 // Get the key type with both the opcode and predicate
Duncan P. N. Exon Smith7116af62014-08-19 16:39:58 +00002093 const ConstantExprKeyType Key(Instruction::FCmp, ArgVec, pred);
Nick Lewycky401f3252010-01-21 07:03:21 +00002094
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002095 Type *ResultTy = Type::getInt1Ty(LHS->getContext());
2096 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
Nick Lewycky401f3252010-01-21 07:03:21 +00002097 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
2098
Owen Andersond03eecd2009-08-04 20:25:11 +00002099 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
Nick Lewycky401f3252010-01-21 07:03:21 +00002100 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
Reid Spencer077d0eb2006-12-04 05:19:50 +00002101}
2102
Duncan P. N. Exon Smithe2215572014-08-19 19:45:37 +00002103Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx,
2104 Type *OnlyIfReducedTy) {
Duncan Sands1df98592010-02-16 11:11:14 +00002105 assert(Val->getType()->isVectorTy() &&
Reid Spencerac9dcb92007-02-15 03:39:18 +00002106 "Tried to create extractelement operation on non-vector type!");
Michael J. Spencerd4b4f2d2014-05-01 22:12:39 +00002107 assert(Idx->getType()->isIntegerTy() &&
2108 "Extractelement index must be an integer type!");
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002109
Chris Lattnereaf79802011-07-09 18:23:52 +00002110 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
Chris Lattner83738a22009-12-30 20:25:09 +00002111 return FC; // Fold a few common cases.
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002112
Duncan P. N. Exon Smithe2215572014-08-19 19:45:37 +00002113 Type *ReqTy = Val->getType()->getVectorElementType();
2114 if (OnlyIfReducedTy == ReqTy)
2115 return nullptr;
2116
Robert Bocchinoc152f9c2006-01-17 20:07:22 +00002117 // Look up the constant in the table first to ensure uniqueness
Benjamin Kramer4e4cc7d2013-03-07 20:53:34 +00002118 Constant *ArgVec[] = { Val, Idx };
Duncan P. N. Exon Smith7116af62014-08-19 16:39:58 +00002119 const ConstantExprKeyType Key(Instruction::ExtractElement, ArgVec);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002120
Chris Lattnereaf79802011-07-09 18:23:52 +00002121 LLVMContextImpl *pImpl = Val->getContext().pImpl;
Owen Andersond03eecd2009-08-04 20:25:11 +00002122 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
Robert Bocchinoc152f9c2006-01-17 20:07:22 +00002123}
2124
Duncan P. N. Exon Smithe2215572014-08-19 19:45:37 +00002125Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
2126 Constant *Idx, Type *OnlyIfReducedTy) {
Duncan Sands1df98592010-02-16 11:11:14 +00002127 assert(Val->getType()->isVectorTy() &&
Reid Spencerac9dcb92007-02-15 03:39:18 +00002128 "Tried to create insertelement operation on non-vector type!");
Chris Lattner230cdab2012-01-26 00:42:34 +00002129 assert(Elt->getType() == Val->getType()->getVectorElementType() &&
2130 "Insertelement types must match!");
Michael J. Spencerd4b4f2d2014-05-01 22:12:39 +00002131 assert(Idx->getType()->isIntegerTy() &&
Reid Spencer3d10b0b2007-01-26 07:37:34 +00002132 "Insertelement index must be i32 type!");
Robert Bocchinoc152f9c2006-01-17 20:07:22 +00002133
Chris Lattnereaf79802011-07-09 18:23:52 +00002134 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
2135 return FC; // Fold a few common cases.
Duncan P. N. Exon Smithe2215572014-08-19 19:45:37 +00002136
2137 if (OnlyIfReducedTy == Val->getType())
2138 return nullptr;
2139
Chris Lattner00f10232006-04-08 01:18:18 +00002140 // Look up the constant in the table first to ensure uniqueness
Benjamin Kramer4e4cc7d2013-03-07 20:53:34 +00002141 Constant *ArgVec[] = { Val, Elt, Idx };
Duncan P. N. Exon Smith7116af62014-08-19 16:39:58 +00002142 const ConstantExprKeyType Key(Instruction::InsertElement, ArgVec);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002143
Chris Lattnereaf79802011-07-09 18:23:52 +00002144 LLVMContextImpl *pImpl = Val->getContext().pImpl;
2145 return pImpl->ExprConstants.getOrCreate(Val->getType(), Key);
Chris Lattner00f10232006-04-08 01:18:18 +00002146}
2147
Duncan P. N. Exon Smithe2215572014-08-19 19:45:37 +00002148Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
2149 Constant *Mask, Type *OnlyIfReducedTy) {
Chris Lattner00f10232006-04-08 01:18:18 +00002150 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
2151 "Invalid shuffle vector constant expr operands!");
Nate Begeman0f123cf2009-02-12 21:28:33 +00002152
Chris Lattnereaf79802011-07-09 18:23:52 +00002153 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
2154 return FC; // Fold a few common cases.
2155
Chris Lattner230cdab2012-01-26 00:42:34 +00002156 unsigned NElts = Mask->getType()->getVectorNumElements();
2157 Type *EltTy = V1->getType()->getVectorElementType();
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002158 Type *ShufTy = VectorType::get(EltTy, NElts);
Chris Lattnereaf79802011-07-09 18:23:52 +00002159
Duncan P. N. Exon Smithe2215572014-08-19 19:45:37 +00002160 if (OnlyIfReducedTy == ShufTy)
2161 return nullptr;
2162
Chris Lattnereaf79802011-07-09 18:23:52 +00002163 // Look up the constant in the table first to ensure uniqueness
Benjamin Kramer4e4cc7d2013-03-07 20:53:34 +00002164 Constant *ArgVec[] = { V1, V2, Mask };
Duncan P. N. Exon Smith7116af62014-08-19 16:39:58 +00002165 const ConstantExprKeyType Key(Instruction::ShuffleVector, ArgVec);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002166
Chris Lattnereaf79802011-07-09 18:23:52 +00002167 LLVMContextImpl *pImpl = ShufTy->getContext().pImpl;
2168 return pImpl->ExprConstants.getOrCreate(ShufTy, Key);
Chris Lattner00f10232006-04-08 01:18:18 +00002169}
2170
Chris Lattnereaf79802011-07-09 18:23:52 +00002171Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
Duncan P. N. Exon Smithe2215572014-08-19 19:45:37 +00002172 ArrayRef<unsigned> Idxs,
2173 Type *OnlyIfReducedTy) {
Hal Finkel10050d12013-07-10 22:51:01 +00002174 assert(Agg->getType()->isFirstClassType() &&
2175 "Non-first-class type for constant insertvalue expression");
2176
Jay Foadfc6d3a42011-07-13 10:26:04 +00002177 assert(ExtractValueInst::getIndexedType(Agg->getType(),
2178 Idxs) == Val->getType() &&
Dan Gohman041e2eb2008-05-15 19:50:34 +00002179 "insertvalue indices invalid!");
Hal Finkel10050d12013-07-10 22:51:01 +00002180 Type *ReqTy = Val->getType();
2181
2182 if (Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs))
2183 return FC;
2184
Duncan P. N. Exon Smithe2215572014-08-19 19:45:37 +00002185 if (OnlyIfReducedTy == ReqTy)
2186 return nullptr;
2187
Hal Finkel10050d12013-07-10 22:51:01 +00002188 Constant *ArgVec[] = { Agg, Val };
Duncan P. N. Exon Smith7116af62014-08-19 16:39:58 +00002189 const ConstantExprKeyType Key(Instruction::InsertValue, ArgVec, 0, 0, Idxs);
Hal Finkel10050d12013-07-10 22:51:01 +00002190
2191 LLVMContextImpl *pImpl = Agg->getContext().pImpl;
2192 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
Dan Gohman041e2eb2008-05-15 19:50:34 +00002193}
2194
Duncan P. N. Exon Smithe2215572014-08-19 19:45:37 +00002195Constant *ConstantExpr::getExtractValue(Constant *Agg, ArrayRef<unsigned> Idxs,
2196 Type *OnlyIfReducedTy) {
Dan Gohmane4569942008-05-23 00:36:11 +00002197 assert(Agg->getType()->isFirstClassType() &&
Chris Lattnereaf79802011-07-09 18:23:52 +00002198 "Tried to create extractelement operation on non-first-class type!");
Dan Gohman041e2eb2008-05-15 19:50:34 +00002199
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002200 Type *ReqTy = ExtractValueInst::getIndexedType(Agg->getType(), Idxs);
Chandler Carruthdc770fc2011-07-10 09:45:35 +00002201 (void)ReqTy;
Chris Lattnereaf79802011-07-09 18:23:52 +00002202 assert(ReqTy && "extractvalue indices invalid!");
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002203
Dan Gohmane4569942008-05-23 00:36:11 +00002204 assert(Agg->getType()->isFirstClassType() &&
2205 "Non-first-class type for constant extractvalue expression");
Hal Finkel10050d12013-07-10 22:51:01 +00002206 if (Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs))
2207 return FC;
2208
Duncan P. N. Exon Smithe2215572014-08-19 19:45:37 +00002209 if (OnlyIfReducedTy == ReqTy)
2210 return nullptr;
2211
Hal Finkel10050d12013-07-10 22:51:01 +00002212 Constant *ArgVec[] = { Agg };
Duncan P. N. Exon Smith7116af62014-08-19 16:39:58 +00002213 const ConstantExprKeyType Key(Instruction::ExtractValue, ArgVec, 0, 0, Idxs);
Hal Finkel10050d12013-07-10 22:51:01 +00002214
2215 LLVMContextImpl *pImpl = Agg->getContext().pImpl;
2216 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
Dan Gohman041e2eb2008-05-15 19:50:34 +00002217}
2218
Chris Lattner81baf142011-02-10 07:01:55 +00002219Constant *ConstantExpr::getNeg(Constant *C, bool HasNUW, bool HasNSW) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002220 assert(C->getType()->isIntOrIntVectorTy() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002221 "Cannot NEG a nonintegral value!");
Chris Lattner81baf142011-02-10 07:01:55 +00002222 return getSub(ConstantFP::getZeroValueForNegation(C->getType()),
2223 C, HasNUW, HasNSW);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002224}
2225
Chris Lattnerf067d582011-02-07 16:40:21 +00002226Constant *ConstantExpr::getFNeg(Constant *C) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002227 assert(C->getType()->isFPOrFPVectorTy() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002228 "Cannot FNEG a non-floating-point value!");
Chris Lattner81baf142011-02-10 07:01:55 +00002229 return getFSub(ConstantFP::getZeroValueForNegation(C->getType()), C);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002230}
2231
Chris Lattnerf067d582011-02-07 16:40:21 +00002232Constant *ConstantExpr::getNot(Constant *C) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002233 assert(C->getType()->isIntOrIntVectorTy() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002234 "Cannot NOT a nonintegral value!");
Owen Andersona7235ea2009-07-31 20:28:14 +00002235 return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
Owen Andersonbaf3c402009-07-29 18:55:55 +00002236}
2237
Chris Lattner81baf142011-02-10 07:01:55 +00002238Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2,
2239 bool HasNUW, bool HasNSW) {
2240 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2241 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2242 return get(Instruction::Add, C1, C2, Flags);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002243}
2244
Chris Lattnerf067d582011-02-07 16:40:21 +00002245Constant *ConstantExpr::getFAdd(Constant *C1, Constant *C2) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002246 return get(Instruction::FAdd, C1, C2);
2247}
2248
Chris Lattner81baf142011-02-10 07:01:55 +00002249Constant *ConstantExpr::getSub(Constant *C1, Constant *C2,
2250 bool HasNUW, bool HasNSW) {
2251 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2252 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2253 return get(Instruction::Sub, C1, C2, Flags);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002254}
2255
Chris Lattnerf067d582011-02-07 16:40:21 +00002256Constant *ConstantExpr::getFSub(Constant *C1, Constant *C2) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002257 return get(Instruction::FSub, C1, C2);
2258}
2259
Chris Lattner81baf142011-02-10 07:01:55 +00002260Constant *ConstantExpr::getMul(Constant *C1, Constant *C2,
2261 bool HasNUW, bool HasNSW) {
2262 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2263 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2264 return get(Instruction::Mul, C1, C2, Flags);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002265}
2266
Chris Lattnerf067d582011-02-07 16:40:21 +00002267Constant *ConstantExpr::getFMul(Constant *C1, Constant *C2) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002268 return get(Instruction::FMul, C1, C2);
2269}
2270
Chris Lattner74f5c5a2011-02-09 16:43:07 +00002271Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2, bool isExact) {
2272 return get(Instruction::UDiv, C1, C2,
2273 isExact ? PossiblyExactOperator::IsExact : 0);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002274}
2275
Chris Lattner74f5c5a2011-02-09 16:43:07 +00002276Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2, bool isExact) {
2277 return get(Instruction::SDiv, C1, C2,
2278 isExact ? PossiblyExactOperator::IsExact : 0);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002279}
2280
Chris Lattnerf067d582011-02-07 16:40:21 +00002281Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002282 return get(Instruction::FDiv, C1, C2);
2283}
2284
Chris Lattnerf067d582011-02-07 16:40:21 +00002285Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002286 return get(Instruction::URem, C1, C2);
2287}
2288
Chris Lattnerf067d582011-02-07 16:40:21 +00002289Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002290 return get(Instruction::SRem, C1, C2);
2291}
2292
Chris Lattnerf067d582011-02-07 16:40:21 +00002293Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002294 return get(Instruction::FRem, C1, C2);
2295}
2296
Chris Lattnerf067d582011-02-07 16:40:21 +00002297Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002298 return get(Instruction::And, C1, C2);
2299}
2300
Chris Lattnerf067d582011-02-07 16:40:21 +00002301Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002302 return get(Instruction::Or, C1, C2);
2303}
2304
Chris Lattnerf067d582011-02-07 16:40:21 +00002305Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002306 return get(Instruction::Xor, C1, C2);
2307}
2308
Chris Lattner81baf142011-02-10 07:01:55 +00002309Constant *ConstantExpr::getShl(Constant *C1, Constant *C2,
2310 bool HasNUW, bool HasNSW) {
2311 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2312 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2313 return get(Instruction::Shl, C1, C2, Flags);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002314}
2315
Chris Lattner74f5c5a2011-02-09 16:43:07 +00002316Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2, bool isExact) {
2317 return get(Instruction::LShr, C1, C2,
2318 isExact ? PossiblyExactOperator::IsExact : 0);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002319}
2320
Chris Lattner74f5c5a2011-02-09 16:43:07 +00002321Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2, bool isExact) {
2322 return get(Instruction::AShr, C1, C2,
2323 isExact ? PossiblyExactOperator::IsExact : 0);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002324}
2325
Sanjay Patel79da1642018-07-06 15:18:58 +00002326Constant *ConstantExpr::getBinOpIdentity(unsigned Opcode, Type *Ty,
2327 bool AllowRHSConstant) {
2328 assert(Instruction::isBinaryOp(Opcode) && "Only binops allowed");
2329
2330 // Commutative opcodes: it does not matter if AllowRHSConstant is set.
2331 if (Instruction::isCommutative(Opcode)) {
2332 switch (Opcode) {
2333 case Instruction::Add: // X + 0 = X
2334 case Instruction::Or: // X | 0 = X
2335 case Instruction::Xor: // X ^ 0 = X
2336 return Constant::getNullValue(Ty);
2337 case Instruction::Mul: // X * 1 = X
2338 return ConstantInt::get(Ty, 1);
2339 case Instruction::And: // X & -1 = X
2340 return Constant::getAllOnesValue(Ty);
2341 case Instruction::FAdd: // X + -0.0 = X
2342 // TODO: If the fadd has 'nsz', should we return +0.0?
2343 return ConstantFP::getNegativeZero(Ty);
2344 case Instruction::FMul: // X * 1.0 = X
2345 return ConstantFP::get(Ty, 1.0);
2346 default:
2347 llvm_unreachable("Every commutative binop has an identity constant");
2348 }
2349 }
2350
2351 // Non-commutative opcodes: AllowRHSConstant must be set.
2352 if (!AllowRHSConstant)
Craig Topperec0f0bc2014-04-09 06:08:46 +00002353 return nullptr;
Duncan Sandsee5a0942012-06-13 09:42:13 +00002354
Sanjay Patel79da1642018-07-06 15:18:58 +00002355 switch (Opcode) {
2356 case Instruction::Sub: // X - 0 = X
2357 case Instruction::Shl: // X << 0 = X
2358 case Instruction::LShr: // X >>u 0 = X
2359 case Instruction::AShr: // X >> 0 = X
2360 case Instruction::FSub: // X - 0.0 = X
2361 return Constant::getNullValue(Ty);
2362 case Instruction::SDiv: // X / 1 = X
2363 case Instruction::UDiv: // X /u 1 = X
2364 return ConstantInt::get(Ty, 1);
2365 case Instruction::FDiv: // X / 1.0 = X
2366 return ConstantFP::get(Ty, 1.0);
2367 default:
2368 return nullptr;
Duncan Sandsc038a782012-06-12 14:33:56 +00002369 }
2370}
2371
Duncan Sandsee5a0942012-06-13 09:42:13 +00002372Constant *ConstantExpr::getBinOpAbsorber(unsigned Opcode, Type *Ty) {
2373 switch (Opcode) {
2374 default:
2375 // Doesn't have an absorber.
Craig Topperec0f0bc2014-04-09 06:08:46 +00002376 return nullptr;
Duncan Sandsee5a0942012-06-13 09:42:13 +00002377
2378 case Instruction::Or:
2379 return Constant::getAllOnesValue(Ty);
2380
2381 case Instruction::And:
2382 case Instruction::Mul:
2383 return Constant::getNullValue(Ty);
2384 }
2385}
2386
Sanjay Patel0ac37a42016-04-29 22:03:27 +00002387/// Remove the constant from the constant table.
Pete Cooperd6218122015-06-23 21:55:11 +00002388void ConstantExpr::destroyConstantImpl() {
Chris Lattner1afcace2011-07-09 17:41:24 +00002389 getType()->getContext().pImpl->ExprConstants.remove(this);
Vikram S. Adve345e0cf2002-07-14 23:13:17 +00002390}
2391
Chris Lattnerc188eeb2002-07-30 18:54:25 +00002392const char *ConstantExpr::getOpcodeName() const {
2393 return Instruction::getOpcodeName(getOpcode());
Vikram S. Adve345e0cf2002-07-14 23:13:17 +00002394}
Reid Spencer1c9c8e62004-07-17 23:48:33 +00002395
David Blaikie66583e42015-05-08 00:42:26 +00002396GetElementPtrConstantExpr::GetElementPtrConstantExpr(
2397 Type *SrcElementTy, Constant *C, ArrayRef<Constant *> IdxList, Type *DestTy)
2398 : ConstantExpr(DestTy, Instruction::GetElementPtr,
2399 OperandTraits<GetElementPtrConstantExpr>::op_end(this) -
2400 (IdxList.size() + 1),
2401 IdxList.size() + 1),
Eduard Burtescuf70dc422016-01-19 17:28:00 +00002402 SrcElementTy(SrcElementTy),
2403 ResElementTy(GetElementPtrInst::getIndexedType(SrcElementTy, IdxList)) {
Pete Cooper10520422015-05-21 22:48:54 +00002404 Op<0>() = C;
Pete Coopercff40fc2015-06-12 17:48:05 +00002405 Use *OperandList = getOperandList();
Chris Lattner04e3b1e2010-03-30 20:48:48 +00002406 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
2407 OperandList[i+1] = IdxList[i];
2408}
2409
David Blaikie66583e42015-05-08 00:42:26 +00002410Type *GetElementPtrConstantExpr::getSourceElementType() const {
2411 return SrcElementTy;
2412}
2413
Eduard Burtescuf70dc422016-01-19 17:28:00 +00002414Type *GetElementPtrConstantExpr::getResultElementType() const {
2415 return ResElementTy;
2416}
2417
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002418//===----------------------------------------------------------------------===//
2419// ConstantData* implementations
2420
Chris Lattner45bb5c52012-01-24 04:43:41 +00002421Type *ConstantDataSequential::getElementType() const {
2422 return getType()->getElementType();
2423}
2424
Chris Lattner9e631da2012-01-24 09:31:43 +00002425StringRef ConstantDataSequential::getRawDataValues() const {
Chris Lattner1ee0ecf2012-01-24 13:41:11 +00002426 return StringRef(DataElements, getNumElements()*getElementByteSize());
Chris Lattner9e631da2012-01-24 09:31:43 +00002427}
2428
Craig Topper84bbcfe2015-08-01 22:20:21 +00002429bool ConstantDataSequential::isElementTypeCompatible(Type *Ty) {
Justin Bognere32f0e22015-12-08 03:01:16 +00002430 if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) return true;
Craig Topper84bbcfe2015-08-01 22:20:21 +00002431 if (auto *IT = dyn_cast<IntegerType>(Ty)) {
Chris Lattner45bb5c52012-01-24 04:43:41 +00002432 switch (IT->getBitWidth()) {
2433 case 8:
2434 case 16:
2435 case 32:
2436 case 64:
2437 return true;
2438 default: break;
2439 }
2440 }
2441 return false;
2442}
2443
Chris Lattner1ee0ecf2012-01-24 13:41:11 +00002444unsigned ConstantDataSequential::getNumElements() const {
Chris Lattneraf7b4fb2012-01-25 01:32:59 +00002445 if (ArrayType *AT = dyn_cast<ArrayType>(getType()))
2446 return AT->getNumElements();
Chris Lattner230cdab2012-01-26 00:42:34 +00002447 return getType()->getVectorNumElements();
Chris Lattner1ee0ecf2012-01-24 13:41:11 +00002448}
2449
2450
Chris Lattner45bb5c52012-01-24 04:43:41 +00002451uint64_t ConstantDataSequential::getElementByteSize() const {
2452 return getElementType()->getPrimitiveSizeInBits()/8;
2453}
2454
Sanjay Patel0ac37a42016-04-29 22:03:27 +00002455/// Return the start of the specified element.
Chris Lattner45bb5c52012-01-24 04:43:41 +00002456const char *ConstantDataSequential::getElementPointer(unsigned Elt) const {
Chris Lattner1ee0ecf2012-01-24 13:41:11 +00002457 assert(Elt < getNumElements() && "Invalid Elt");
Chris Lattner45bb5c52012-01-24 04:43:41 +00002458 return DataElements+Elt*getElementByteSize();
2459}
2460
2461
Sanjay Patel0ac37a42016-04-29 22:03:27 +00002462/// Return true if the array is empty or all zeros.
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002463static bool isAllZeros(StringRef Arr) {
Benjamin Kramere96e21f2016-06-26 14:10:56 +00002464 for (char I : Arr)
2465 if (I != 0)
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002466 return false;
2467 return true;
2468}
Chris Lattnerff2b7f32012-01-24 05:42:11 +00002469
Sanjay Patel0ac37a42016-04-29 22:03:27 +00002470/// This is the underlying implementation of all of the
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002471/// ConstantDataSequential::get methods. They all thunk down to here, providing
Chris Lattner8cf27ef2012-01-30 18:19:30 +00002472/// the correct element type. We take the bytes in as a StringRef because
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002473/// we *want* an underlying "char*" to avoid TBAA type punning violations.
2474Constant *ConstantDataSequential::getImpl(StringRef Elements, Type *Ty) {
Chris Lattner230cdab2012-01-26 00:42:34 +00002475 assert(isElementTypeCompatible(Ty->getSequentialElementType()));
Chris Lattner29cc6cb2012-01-24 14:17:05 +00002476 // If the elements are all zero or there are no elements, return a CAZ, which
2477 // is more dense and canonical.
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002478 if (isAllZeros(Elements))
2479 return ConstantAggregateZero::get(Ty);
2480
2481 // Do a lookup to see if we have already formed one of these.
David Blaikie1d4f28c2014-11-19 05:49:42 +00002482 auto &Slot =
2483 *Ty->getContext()
2484 .pImpl->CDSConstants.insert(std::make_pair(Elements, nullptr))
2485 .first;
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002486
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002487 // The bucket can point to a linked list of different CDS's that have the same
2488 // body but different types. For example, 0,0,0,1 could be a 4 element array
2489 // of i8, or a 1-element array of i32. They'll both end up in the same
2490 /// StringMap bucket, linked up by their Next pointers. Walk the list.
David Blaikie1d4f28c2014-11-19 05:49:42 +00002491 ConstantDataSequential **Entry = &Slot.second;
Craig Topperec0f0bc2014-04-09 06:08:46 +00002492 for (ConstantDataSequential *Node = *Entry; Node;
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002493 Entry = &Node->Next, Node = *Entry)
2494 if (Node->getType() == Ty)
2495 return Node;
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002496
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002497 // Okay, we didn't get a hit. Create a node of the right class, link it in,
2498 // and return it.
2499 if (isa<ArrayType>(Ty))
David Blaikie1d4f28c2014-11-19 05:49:42 +00002500 return *Entry = new ConstantDataArray(Ty, Slot.first().data());
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002501
2502 assert(isa<VectorType>(Ty));
David Blaikie1d4f28c2014-11-19 05:49:42 +00002503 return *Entry = new ConstantDataVector(Ty, Slot.first().data());
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002504}
2505
Pete Cooperd6218122015-06-23 21:55:11 +00002506void ConstantDataSequential::destroyConstantImpl() {
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002507 // Remove the constant from the StringMap.
Bjorn Petterssona1ff84e2018-07-03 12:39:52 +00002508 StringMap<ConstantDataSequential*> &CDSConstants =
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002509 getType()->getContext().pImpl->CDSConstants;
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002510
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002511 StringMap<ConstantDataSequential*>::iterator Slot =
Chris Lattner9e631da2012-01-24 09:31:43 +00002512 CDSConstants.find(getRawDataValues());
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002513
2514 assert(Slot != CDSConstants.end() && "CDS not found in uniquing table");
2515
2516 ConstantDataSequential **Entry = &Slot->getValue();
2517
2518 // Remove the entry from the hash table.
Craig Topperec0f0bc2014-04-09 06:08:46 +00002519 if (!(*Entry)->Next) {
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002520 // If there is only one value in the bucket (common case) it must be this
2521 // entry, and removing the entry should remove the bucket completely.
2522 assert((*Entry) == this && "Hash mismatch in ConstantDataSequential");
2523 getContext().pImpl->CDSConstants.erase(Slot);
2524 } else {
Bjorn Petterssona1ff84e2018-07-03 12:39:52 +00002525 // Otherwise, there are multiple entries linked off the bucket, unlink the
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002526 // node we care about but keep the bucket around.
2527 for (ConstantDataSequential *Node = *Entry; ;
2528 Entry = &Node->Next, Node = *Entry) {
2529 assert(Node && "Didn't find entry in its uniquing hash table!");
2530 // If we found our entry, unlink it from the list and we're done.
2531 if (Node == this) {
2532 *Entry = Node->Next;
2533 break;
2534 }
2535 }
2536 }
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002537
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002538 // If we were part of a list, make sure that we don't delete the list that is
2539 // still owned by the uniquing map.
Craig Topperec0f0bc2014-04-09 06:08:46 +00002540 Next = nullptr;
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002541}
2542
Rafael Espindola1b4da6c2015-02-19 16:08:20 +00002543/// getFP() constructors - Return a constant with array type with an element
2544/// count and element type of float with precision matching the number of
2545/// bits in the ArrayRef passed in. (i.e. half for 16bits, float for 32bits,
2546/// double for 64bits) Note that this can return a ConstantAggregateZero
2547/// object.
2548Constant *ConstantDataArray::getFP(LLVMContext &Context,
2549 ArrayRef<uint16_t> Elts) {
Justin Bogner43812842015-12-09 21:21:07 +00002550 Type *Ty = ArrayType::get(Type::getHalfTy(Context), Elts.size());
Rafael Espindola1b4da6c2015-02-19 16:08:20 +00002551 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper04955762017-07-11 15:52:21 +00002552 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
Rafael Espindola1b4da6c2015-02-19 16:08:20 +00002553}
2554Constant *ConstantDataArray::getFP(LLVMContext &Context,
2555 ArrayRef<uint32_t> Elts) {
2556 Type *Ty = ArrayType::get(Type::getFloatTy(Context), Elts.size());
2557 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper04955762017-07-11 15:52:21 +00002558 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
Rafael Espindola1b4da6c2015-02-19 16:08:20 +00002559}
2560Constant *ConstantDataArray::getFP(LLVMContext &Context,
2561 ArrayRef<uint64_t> Elts) {
2562 Type *Ty = ArrayType::get(Type::getDoubleTy(Context), Elts.size());
2563 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper04955762017-07-11 15:52:21 +00002564 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002565}
2566
Chris Lattner32100602012-01-24 14:04:40 +00002567Constant *ConstantDataArray::getString(LLVMContext &Context,
2568 StringRef Str, bool AddNull) {
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002569 if (!AddNull) {
2570 const uint8_t *Data = reinterpret_cast<const uint8_t *>(Str.data());
Craig Topper04955762017-07-11 15:52:21 +00002571 return get(Context, makeArrayRef(Data, Str.size()));
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002572 }
2573
Chris Lattner32100602012-01-24 14:04:40 +00002574 SmallVector<uint8_t, 64> ElementVals;
2575 ElementVals.append(Str.begin(), Str.end());
2576 ElementVals.push_back(0);
2577 return get(Context, ElementVals);
2578}
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002579
2580/// get() constructors - Return a constant with vector type with an element
2581/// count and element type matching the ArrayRef passed in. Note that this
2582/// can return a ConstantAggregateZero object.
Chris Lattner32100602012-01-24 14:04:40 +00002583Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint8_t> Elts){
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002584 Type *Ty = VectorType::get(Type::getInt8Ty(Context), Elts.size());
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002585 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper04955762017-07-11 15:52:21 +00002586 return getImpl(StringRef(Data, Elts.size() * 1), Ty);
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002587}
Chris Lattner32100602012-01-24 14:04:40 +00002588Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint16_t> Elts){
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002589 Type *Ty = VectorType::get(Type::getInt16Ty(Context), Elts.size());
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002590 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper04955762017-07-11 15:52:21 +00002591 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002592}
Chris Lattner32100602012-01-24 14:04:40 +00002593Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint32_t> Elts){
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002594 Type *Ty = VectorType::get(Type::getInt32Ty(Context), Elts.size());
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002595 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper04955762017-07-11 15:52:21 +00002596 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002597}
Chris Lattner32100602012-01-24 14:04:40 +00002598Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint64_t> Elts){
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002599 Type *Ty = VectorType::get(Type::getInt64Ty(Context), Elts.size());
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002600 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper04955762017-07-11 15:52:21 +00002601 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002602}
Chris Lattner32100602012-01-24 14:04:40 +00002603Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<float> Elts) {
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002604 Type *Ty = VectorType::get(Type::getFloatTy(Context), Elts.size());
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002605 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper04955762017-07-11 15:52:21 +00002606 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002607}
Chris Lattner32100602012-01-24 14:04:40 +00002608Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<double> Elts) {
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002609 Type *Ty = VectorType::get(Type::getDoubleTy(Context), Elts.size());
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002610 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper04955762017-07-11 15:52:21 +00002611 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
Rafael Espindola1b4da6c2015-02-19 16:08:20 +00002612}
2613
2614/// getFP() constructors - Return a constant with vector type with an element
2615/// count and element type of float with the precision matching the number of
2616/// bits in the ArrayRef passed in. (i.e. half for 16bits, float for 32bits,
2617/// double for 64bits) Note that this can return a ConstantAggregateZero
2618/// object.
2619Constant *ConstantDataVector::getFP(LLVMContext &Context,
2620 ArrayRef<uint16_t> Elts) {
2621 Type *Ty = VectorType::get(Type::getHalfTy(Context), Elts.size());
2622 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper04955762017-07-11 15:52:21 +00002623 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
Rafael Espindola1b4da6c2015-02-19 16:08:20 +00002624}
2625Constant *ConstantDataVector::getFP(LLVMContext &Context,
2626 ArrayRef<uint32_t> Elts) {
2627 Type *Ty = VectorType::get(Type::getFloatTy(Context), Elts.size());
2628 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper04955762017-07-11 15:52:21 +00002629 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
Rafael Espindola1b4da6c2015-02-19 16:08:20 +00002630}
2631Constant *ConstantDataVector::getFP(LLVMContext &Context,
2632 ArrayRef<uint64_t> Elts) {
2633 Type *Ty = VectorType::get(Type::getDoubleTy(Context), Elts.size());
2634 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper04955762017-07-11 15:52:21 +00002635 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002636}
2637
Chris Lattner3c2c9542012-01-25 05:19:54 +00002638Constant *ConstantDataVector::getSplat(unsigned NumElts, Constant *V) {
2639 assert(isElementTypeCompatible(V->getType()) &&
2640 "Element type not compatible with ConstantData");
2641 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
2642 if (CI->getType()->isIntegerTy(8)) {
2643 SmallVector<uint8_t, 16> Elts(NumElts, CI->getZExtValue());
2644 return get(V->getContext(), Elts);
2645 }
2646 if (CI->getType()->isIntegerTy(16)) {
2647 SmallVector<uint16_t, 16> Elts(NumElts, CI->getZExtValue());
2648 return get(V->getContext(), Elts);
2649 }
2650 if (CI->getType()->isIntegerTy(32)) {
2651 SmallVector<uint32_t, 16> Elts(NumElts, CI->getZExtValue());
2652 return get(V->getContext(), Elts);
2653 }
2654 assert(CI->getType()->isIntegerTy(64) && "Unsupported ConstantData type");
2655 SmallVector<uint64_t, 16> Elts(NumElts, CI->getZExtValue());
2656 return get(V->getContext(), Elts);
2657 }
2658
Chris Lattner36c744f2012-01-30 06:21:21 +00002659 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
Justin Bognere32f0e22015-12-08 03:01:16 +00002660 if (CFP->getType()->isHalfTy()) {
2661 SmallVector<uint16_t, 16> Elts(
2662 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
2663 return getFP(V->getContext(), Elts);
2664 }
Chris Lattner36c744f2012-01-30 06:21:21 +00002665 if (CFP->getType()->isFloatTy()) {
Rafael Espindola1b4da6c2015-02-19 16:08:20 +00002666 SmallVector<uint32_t, 16> Elts(
2667 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
2668 return getFP(V->getContext(), Elts);
Chris Lattner36c744f2012-01-30 06:21:21 +00002669 }
2670 if (CFP->getType()->isDoubleTy()) {
Rafael Espindola1b4da6c2015-02-19 16:08:20 +00002671 SmallVector<uint64_t, 16> Elts(
2672 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
2673 return getFP(V->getContext(), Elts);
Chris Lattner36c744f2012-01-30 06:21:21 +00002674 }
Chris Lattner3c2c9542012-01-25 05:19:54 +00002675 }
Chris Lattner36c744f2012-01-30 06:21:21 +00002676 return ConstantVector::getSplat(NumElts, V);
Chris Lattner3c2c9542012-01-25 05:19:54 +00002677}
2678
2679
Chris Lattner45bb5c52012-01-24 04:43:41 +00002680uint64_t ConstantDataSequential::getElementAsInteger(unsigned Elt) const {
2681 assert(isa<IntegerType>(getElementType()) &&
2682 "Accessor can only be used when element is an integer");
2683 const char *EltPtr = getElementPointer(Elt);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002684
Chris Lattner45bb5c52012-01-24 04:43:41 +00002685 // The data is stored in host byte order, make sure to cast back to the right
2686 // type to load with the right endianness.
Chris Lattner230cdab2012-01-26 00:42:34 +00002687 switch (getElementType()->getIntegerBitWidth()) {
Craig Topper50bee422012-02-05 22:14:15 +00002688 default: llvm_unreachable("Invalid bitwidth for CDS");
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002689 case 8:
Craig Topper04955762017-07-11 15:52:21 +00002690 return *reinterpret_cast<const uint8_t *>(EltPtr);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002691 case 16:
Craig Topper04955762017-07-11 15:52:21 +00002692 return *reinterpret_cast<const uint16_t *>(EltPtr);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002693 case 32:
Craig Topper04955762017-07-11 15:52:21 +00002694 return *reinterpret_cast<const uint32_t *>(EltPtr);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002695 case 64:
Craig Topper04955762017-07-11 15:52:21 +00002696 return *reinterpret_cast<const uint64_t *>(EltPtr);
Chris Lattner45bb5c52012-01-24 04:43:41 +00002697 }
2698}
2699
Craig Topperfce91792017-07-15 22:06:19 +00002700APInt ConstantDataSequential::getElementAsAPInt(unsigned Elt) const {
2701 assert(isa<IntegerType>(getElementType()) &&
2702 "Accessor can only be used when element is an integer");
2703 const char *EltPtr = getElementPointer(Elt);
2704
2705 // The data is stored in host byte order, make sure to cast back to the right
2706 // type to load with the right endianness.
2707 switch (getElementType()->getIntegerBitWidth()) {
2708 default: llvm_unreachable("Invalid bitwidth for CDS");
2709 case 8: {
2710 auto EltVal = *reinterpret_cast<const uint8_t *>(EltPtr);
2711 return APInt(8, EltVal);
2712 }
2713 case 16: {
2714 auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
2715 return APInt(16, EltVal);
2716 }
2717 case 32: {
2718 auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr);
2719 return APInt(32, EltVal);
2720 }
2721 case 64: {
2722 auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr);
2723 return APInt(64, EltVal);
2724 }
2725 }
2726}
2727
Chris Lattner45bb5c52012-01-24 04:43:41 +00002728APFloat ConstantDataSequential::getElementAsAPFloat(unsigned Elt) const {
2729 const char *EltPtr = getElementPointer(Elt);
2730
2731 switch (getElementType()->getTypeID()) {
Nick Lewycky1486ae62012-01-25 03:20:12 +00002732 default:
Craig Topper50bee422012-02-05 22:14:15 +00002733 llvm_unreachable("Accessor can only be used when element is float/double!");
Justin Bognere32f0e22015-12-08 03:01:16 +00002734 case Type::HalfTyID: {
2735 auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
Stephan Bergmann20a600c2016-12-14 11:57:17 +00002736 return APFloat(APFloat::IEEEhalf(), APInt(16, EltVal));
Justin Bognere32f0e22015-12-08 03:01:16 +00002737 }
Benjamin Kramer5c251162015-02-20 15:11:55 +00002738 case Type::FloatTyID: {
2739 auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr);
Stephan Bergmann20a600c2016-12-14 11:57:17 +00002740 return APFloat(APFloat::IEEEsingle(), APInt(32, EltVal));
Benjamin Kramer5c251162015-02-20 15:11:55 +00002741 }
2742 case Type::DoubleTyID: {
2743 auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr);
Stephan Bergmann20a600c2016-12-14 11:57:17 +00002744 return APFloat(APFloat::IEEEdouble(), APInt(64, EltVal));
Chris Lattner45bb5c52012-01-24 04:43:41 +00002745 }
Benjamin Kramer5c251162015-02-20 15:11:55 +00002746 }
Chris Lattner45bb5c52012-01-24 04:43:41 +00002747}
2748
Chris Lattner45bb5c52012-01-24 04:43:41 +00002749float ConstantDataSequential::getElementAsFloat(unsigned Elt) const {
2750 assert(getElementType()->isFloatTy() &&
2751 "Accessor can only be used when element is a 'float'");
Craig Topper04955762017-07-11 15:52:21 +00002752 return *reinterpret_cast<const float *>(getElementPointer(Elt));
Chris Lattner45bb5c52012-01-24 04:43:41 +00002753}
2754
Chris Lattner45bb5c52012-01-24 04:43:41 +00002755double ConstantDataSequential::getElementAsDouble(unsigned Elt) const {
2756 assert(getElementType()->isDoubleTy() &&
2757 "Accessor can only be used when element is a 'float'");
Craig Topper04955762017-07-11 15:52:21 +00002758 return *reinterpret_cast<const double *>(getElementPointer(Elt));
Chris Lattner45bb5c52012-01-24 04:43:41 +00002759}
2760
Chris Lattner45bb5c52012-01-24 04:43:41 +00002761Constant *ConstantDataSequential::getElementAsConstant(unsigned Elt) const {
Justin Bognere32f0e22015-12-08 03:01:16 +00002762 if (getElementType()->isHalfTy() || getElementType()->isFloatTy() ||
2763 getElementType()->isDoubleTy())
Chris Lattner45bb5c52012-01-24 04:43:41 +00002764 return ConstantFP::get(getContext(), getElementAsAPFloat(Elt));
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002765
Chris Lattner45bb5c52012-01-24 04:43:41 +00002766 return ConstantInt::get(getElementType(), getElementAsInteger(Elt));
2767}
2768
Matthias Braun708626d2017-05-19 22:37:09 +00002769bool ConstantDataSequential::isString(unsigned CharSize) const {
2770 return isa<ArrayType>(getType()) && getElementType()->isIntegerTy(CharSize);
Chris Lattner62339072012-01-24 09:01:07 +00002771}
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002772
Chris Lattner62339072012-01-24 09:01:07 +00002773bool ConstantDataSequential::isCString() const {
2774 if (!isString())
2775 return false;
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002776
Chris Lattner62339072012-01-24 09:01:07 +00002777 StringRef Str = getAsString();
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002778
Chris Lattner62339072012-01-24 09:01:07 +00002779 // The last value must be nul.
2780 if (Str.back() != 0) return false;
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002781
Chris Lattner62339072012-01-24 09:01:07 +00002782 // Other elements must be non-nul.
2783 return Str.drop_back().find(0) == StringRef::npos;
2784}
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002785
Craig Topperfce91792017-07-15 22:06:19 +00002786bool ConstantDataVector::isSplat() const {
Chris Lattnere150e2d2012-01-26 02:31:22 +00002787 const char *Base = getRawDataValues().data();
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002788
Chris Lattnere150e2d2012-01-26 02:31:22 +00002789 // Compare elements 1+ to the 0'th element.
2790 unsigned EltSize = getElementByteSize();
2791 for (unsigned i = 1, e = getNumElements(); i != e; ++i)
2792 if (memcmp(Base, Base+i*EltSize, EltSize))
Craig Topperfce91792017-07-15 22:06:19 +00002793 return false;
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002794
Craig Topperfce91792017-07-15 22:06:19 +00002795 return true;
2796}
2797
2798Constant *ConstantDataVector::getSplatValue() const {
Chris Lattnere150e2d2012-01-26 02:31:22 +00002799 // If they're all the same, return the 0th one as a representative.
Craig Topperfce91792017-07-15 22:06:19 +00002800 return isSplat() ? getElementAsConstant(0) : nullptr;
Chris Lattnere150e2d2012-01-26 02:31:22 +00002801}
Chris Lattner04e3b1e2010-03-30 20:48:48 +00002802
Chris Lattner5cbade92005-10-03 21:58:36 +00002803//===----------------------------------------------------------------------===//
Pete Cooper234c5892015-06-24 18:55:24 +00002804// handleOperandChange implementations
Chris Lattner5cbade92005-10-03 21:58:36 +00002805
Pete Cooper234c5892015-06-24 18:55:24 +00002806/// Update this constant array to change uses of
Chris Lattner54984052007-08-21 00:55:23 +00002807/// 'From' to be uses of 'To'. This must update the uniquing data structures
2808/// etc.
2809///
2810/// Note that we intentionally replace all uses of From with To here. Consider
2811/// a large array that uses 'From' 1000 times. By handling this case all here,
Pete Cooper234c5892015-06-24 18:55:24 +00002812/// ConstantArray::handleOperandChange is only invoked once, and that
Chris Lattner54984052007-08-21 00:55:23 +00002813/// single invocation handles all 1000 uses. Handling them one at a time would
2814/// work, but would be really slow because it would have to unique each updated
2815/// array instance.
Chris Lattner2ee11ec2009-10-28 00:01:44 +00002816///
Mehdi Amini4c696962016-02-10 22:47:15 +00002817void Constant::handleOperandChange(Value *From, Value *To) {
Pete Cooper234c5892015-06-24 18:55:24 +00002818 Value *Replacement = nullptr;
2819 switch (getValueID()) {
2820 default:
2821 llvm_unreachable("Not a constant!");
2822#define HANDLE_CONSTANT(Name) \
2823 case Value::Name##Val: \
Mehdi Amini4c696962016-02-10 22:47:15 +00002824 Replacement = cast<Name>(this)->handleOperandChangeImpl(From, To); \
Pete Cooper234c5892015-06-24 18:55:24 +00002825 break;
2826#include "llvm/IR/Value.def"
2827 }
2828
2829 // If handleOperandChangeImpl returned nullptr, then it handled
2830 // replacing itself and we don't want to delete or replace anything else here.
2831 if (!Replacement)
2832 return;
2833
Duncan P. N. Exon Smith7116af62014-08-19 16:39:58 +00002834 // I do need to replace this with an existing value.
2835 assert(Replacement != this && "I didn't contain From!");
2836
2837 // Everyone using this now uses the replacement.
2838 replaceAllUsesWith(Replacement);
2839
2840 // Delete the old constant!
2841 destroyConstant();
2842}
2843
Mehdi Amini4c696962016-02-10 22:47:15 +00002844Value *ConstantArray::handleOperandChangeImpl(Value *From, Value *To) {
Owen Anderson1fd70962009-07-28 18:32:17 +00002845 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2846 Constant *ToC = cast<Constant>(To);
2847
Talin2cb395e2012-02-05 20:54:10 +00002848 SmallVector<Constant*, 8> Values;
Owen Anderson1fd70962009-07-28 18:32:17 +00002849 Values.reserve(getNumOperands()); // Build replacement array.
2850
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002851 // Fill values with the modified operands of the constant array. Also,
Owen Anderson1fd70962009-07-28 18:32:17 +00002852 // compute whether this turns into an all-zeros array.
Owen Anderson1fd70962009-07-28 18:32:17 +00002853 unsigned NumUpdated = 0;
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002854
Chris Lattnere150e2d2012-01-26 02:31:22 +00002855 // Keep track of whether all the values in the array are "ToC".
2856 bool AllSame = true;
Pete Coopercff40fc2015-06-12 17:48:05 +00002857 Use *OperandList = getOperandList();
Mehdi Amini4c696962016-02-10 22:47:15 +00002858 unsigned OperandNo = 0;
Chris Lattnere150e2d2012-01-26 02:31:22 +00002859 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2860 Constant *Val = cast<Constant>(O->get());
2861 if (Val == From) {
Mehdi Amini4c696962016-02-10 22:47:15 +00002862 OperandNo = (O - OperandList);
Chris Lattnere150e2d2012-01-26 02:31:22 +00002863 Val = ToC;
2864 ++NumUpdated;
Owen Anderson1fd70962009-07-28 18:32:17 +00002865 }
Chris Lattnere150e2d2012-01-26 02:31:22 +00002866 Values.push_back(Val);
Talin2cb395e2012-02-05 20:54:10 +00002867 AllSame &= Val == ToC;
Owen Anderson1fd70962009-07-28 18:32:17 +00002868 }
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002869
Pete Cooper234c5892015-06-24 18:55:24 +00002870 if (AllSame && ToC->isNullValue())
2871 return ConstantAggregateZero::get(getType());
2872
2873 if (AllSame && isa<UndefValue>(ToC))
2874 return UndefValue::get(getType());
Aaron Ballman93710f02014-08-19 14:59:02 +00002875
Duncan P. N. Exon Smith7116af62014-08-19 16:39:58 +00002876 // Check for any other type of constant-folding.
Pete Cooper234c5892015-06-24 18:55:24 +00002877 if (Constant *C = getImpl(getType(), Values))
2878 return C;
Aaron Ballman93710f02014-08-19 14:59:02 +00002879
Duncan P. N. Exon Smithbb69ce82014-08-19 19:13:30 +00002880 // Update to the new value.
Pete Cooper234c5892015-06-24 18:55:24 +00002881 return getContext().pImpl->ArrayConstants.replaceOperandsInPlace(
Mehdi Amini4c696962016-02-10 22:47:15 +00002882 Values, this, From, ToC, NumUpdated, OperandNo);
Chris Lattner5cbade92005-10-03 21:58:36 +00002883}
2884
Mehdi Amini4c696962016-02-10 22:47:15 +00002885Value *ConstantStruct::handleOperandChangeImpl(Value *From, Value *To) {
Owen Anderson8fa33382009-07-27 22:29:26 +00002886 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2887 Constant *ToC = cast<Constant>(To);
2888
Pete Coopercff40fc2015-06-12 17:48:05 +00002889 Use *OperandList = getOperandList();
Owen Anderson8fa33382009-07-27 22:29:26 +00002890
Talin2cb395e2012-02-05 20:54:10 +00002891 SmallVector<Constant*, 8> Values;
Owen Anderson8fa33382009-07-27 22:29:26 +00002892 Values.reserve(getNumOperands()); // Build replacement struct.
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002893
2894 // Fill values with the modified operands of the constant struct. Also,
Owen Anderson8fa33382009-07-27 22:29:26 +00002895 // compute whether this turns into an all-zeros struct.
Mehdi Amini4c696962016-02-10 22:47:15 +00002896 unsigned NumUpdated = 0;
2897 bool AllSame = true;
2898 unsigned OperandNo = 0;
2899 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O) {
2900 Constant *Val = cast<Constant>(O->get());
2901 if (Val == From) {
2902 OperandNo = (O - OperandList);
2903 Val = ToC;
2904 ++NumUpdated;
Owen Anderson8fa33382009-07-27 22:29:26 +00002905 }
Mehdi Amini4c696962016-02-10 22:47:15 +00002906 Values.push_back(Val);
2907 AllSame &= Val == ToC;
Owen Anderson8fa33382009-07-27 22:29:26 +00002908 }
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002909
Mehdi Amini4c696962016-02-10 22:47:15 +00002910 if (AllSame && ToC->isNullValue())
Pete Cooper234c5892015-06-24 18:55:24 +00002911 return ConstantAggregateZero::get(getType());
2912
Mehdi Amini4c696962016-02-10 22:47:15 +00002913 if (AllSame && isa<UndefValue>(ToC))
Pete Cooper234c5892015-06-24 18:55:24 +00002914 return UndefValue::get(getType());
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002915
Duncan P. N. Exon Smith7116af62014-08-19 16:39:58 +00002916 // Update to the new value.
Pete Cooper234c5892015-06-24 18:55:24 +00002917 return getContext().pImpl->StructConstants.replaceOperandsInPlace(
Mehdi Amini4c696962016-02-10 22:47:15 +00002918 Values, this, From, ToC, NumUpdated, OperandNo);
Chris Lattner5cbade92005-10-03 21:58:36 +00002919}
2920
Mehdi Amini4c696962016-02-10 22:47:15 +00002921Value *ConstantVector::handleOperandChangeImpl(Value *From, Value *To) {
Chris Lattner5cbade92005-10-03 21:58:36 +00002922 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
Duncan P. N. Exon Smith7116af62014-08-19 16:39:58 +00002923 Constant *ToC = cast<Constant>(To);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002924
Chris Lattnera7c69882012-01-26 20:40:56 +00002925 SmallVector<Constant*, 8> Values;
Chris Lattner5cbade92005-10-03 21:58:36 +00002926 Values.reserve(getNumOperands()); // Build replacement array...
Duncan P. N. Exon Smith7116af62014-08-19 16:39:58 +00002927 unsigned NumUpdated = 0;
Mehdi Amini4c696962016-02-10 22:47:15 +00002928 unsigned OperandNo = 0;
Chris Lattner5cbade92005-10-03 21:58:36 +00002929 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2930 Constant *Val = getOperand(i);
Duncan P. N. Exon Smith7116af62014-08-19 16:39:58 +00002931 if (Val == From) {
Mehdi Amini4c696962016-02-10 22:47:15 +00002932 OperandNo = i;
Duncan P. N. Exon Smith7116af62014-08-19 16:39:58 +00002933 ++NumUpdated;
2934 Val = ToC;
2935 }
Chris Lattner5cbade92005-10-03 21:58:36 +00002936 Values.push_back(Val);
2937 }
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002938
Pete Cooper234c5892015-06-24 18:55:24 +00002939 if (Constant *C = getImpl(Values))
2940 return C;
Duncan P. N. Exon Smith4d48c3f22014-08-19 02:24:46 +00002941
Duncan P. N. Exon Smithbb69ce82014-08-19 19:13:30 +00002942 // Update to the new value.
Pete Cooper234c5892015-06-24 18:55:24 +00002943 return getContext().pImpl->VectorConstants.replaceOperandsInPlace(
Mehdi Amini4c696962016-02-10 22:47:15 +00002944 Values, this, From, ToC, NumUpdated, OperandNo);
Chris Lattner5cbade92005-10-03 21:58:36 +00002945}
2946
Mehdi Amini4c696962016-02-10 22:47:15 +00002947Value *ConstantExpr::handleOperandChangeImpl(Value *From, Value *ToV) {
Chris Lattner5cbade92005-10-03 21:58:36 +00002948 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2949 Constant *To = cast<Constant>(ToV);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002950
Chris Lattner1a8def62012-01-26 20:37:11 +00002951 SmallVector<Constant*, 8> NewOps;
Duncan P. N. Exon Smithb03916a2014-08-19 20:03:35 +00002952 unsigned NumUpdated = 0;
Mehdi Amini4c696962016-02-10 22:47:15 +00002953 unsigned OperandNo = 0;
Chris Lattner1a8def62012-01-26 20:37:11 +00002954 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2955 Constant *Op = getOperand(i);
Duncan P. N. Exon Smithb03916a2014-08-19 20:03:35 +00002956 if (Op == From) {
Mehdi Amini4c696962016-02-10 22:47:15 +00002957 OperandNo = i;
Duncan P. N. Exon Smithb03916a2014-08-19 20:03:35 +00002958 ++NumUpdated;
2959 Op = To;
2960 }
2961 NewOps.push_back(Op);
Chris Lattner5cbade92005-10-03 21:58:36 +00002962 }
Duncan P. N. Exon Smithb03916a2014-08-19 20:03:35 +00002963 assert(NumUpdated && "I didn't contain From!");
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002964
Pete Cooper234c5892015-06-24 18:55:24 +00002965 if (Constant *C = getWithOperands(NewOps, getType(), true))
2966 return C;
Duncan P. N. Exon Smith7116af62014-08-19 16:39:58 +00002967
Duncan P. N. Exon Smithb03916a2014-08-19 20:03:35 +00002968 // Update to the new value.
Pete Cooper234c5892015-06-24 18:55:24 +00002969 return getContext().pImpl->ExprConstants.replaceOperandsInPlace(
Mehdi Amini4c696962016-02-10 22:47:15 +00002970 NewOps, this, From, To, NumUpdated, OperandNo);
Duncan P. N. Exon Smith7116af62014-08-19 16:39:58 +00002971}
2972
James Molloyb9478c22012-11-17 17:56:30 +00002973Instruction *ConstantExpr::getAsInstruction() {
Benjamin Kramerbac8d0e2015-02-28 13:20:15 +00002974 SmallVector<Value *, 4> ValueOperands(op_begin(), op_end());
James Molloyb9478c22012-11-17 17:56:30 +00002975 ArrayRef<Value*> Ops(ValueOperands);
2976
2977 switch (getOpcode()) {
2978 case Instruction::Trunc:
2979 case Instruction::ZExt:
2980 case Instruction::SExt:
2981 case Instruction::FPTrunc:
2982 case Instruction::FPExt:
2983 case Instruction::UIToFP:
2984 case Instruction::SIToFP:
2985 case Instruction::FPToUI:
2986 case Instruction::FPToSI:
2987 case Instruction::PtrToInt:
2988 case Instruction::IntToPtr:
2989 case Instruction::BitCast:
Eli Benderskye952af72014-01-18 22:54:33 +00002990 case Instruction::AddrSpaceCast:
James Molloyb9478c22012-11-17 17:56:30 +00002991 return CastInst::Create((Instruction::CastOps)getOpcode(),
2992 Ops[0], getType());
2993 case Instruction::Select:
2994 return SelectInst::Create(Ops[0], Ops[1], Ops[2]);
2995 case Instruction::InsertElement:
2996 return InsertElementInst::Create(Ops[0], Ops[1], Ops[2]);
2997 case Instruction::ExtractElement:
2998 return ExtractElementInst::Create(Ops[0], Ops[1]);
2999 case Instruction::InsertValue:
3000 return InsertValueInst::Create(Ops[0], Ops[1], getIndices());
3001 case Instruction::ExtractValue:
3002 return ExtractValueInst::Create(Ops[0], getIndices());
3003 case Instruction::ShuffleVector:
3004 return new ShuffleVectorInst(Ops[0], Ops[1], Ops[2]);
3005
David Blaikiefb5115d2015-03-14 01:53:18 +00003006 case Instruction::GetElementPtr: {
3007 const auto *GO = cast<GEPOperator>(this);
3008 if (GO->isInBounds())
3009 return GetElementPtrInst::CreateInBounds(GO->getSourceElementType(),
3010 Ops[0], Ops.slice(1));
3011 return GetElementPtrInst::Create(GO->getSourceElementType(), Ops[0],
3012 Ops.slice(1));
3013 }
James Molloyb9478c22012-11-17 17:56:30 +00003014 case Instruction::ICmp:
3015 case Instruction::FCmp:
3016 return CmpInst::Create((Instruction::OtherOps)getOpcode(),
Craig Topper240b0e12015-12-15 06:11:33 +00003017 (CmpInst::Predicate)getPredicate(), Ops[0], Ops[1]);
James Molloyb9478c22012-11-17 17:56:30 +00003018
3019 default:
3020 assert(getNumOperands() == 2 && "Must be binary operator?");
3021 BinaryOperator *BO =
3022 BinaryOperator::Create((Instruction::BinaryOps)getOpcode(),
3023 Ops[0], Ops[1]);
3024 if (isa<OverflowingBinaryOperator>(BO)) {
3025 BO->setHasNoUnsignedWrap(SubclassOptionalData &
3026 OverflowingBinaryOperator::NoUnsignedWrap);
3027 BO->setHasNoSignedWrap(SubclassOptionalData &
3028 OverflowingBinaryOperator::NoSignedWrap);
3029 }
3030 if (isa<PossiblyExactOperator>(BO))
3031 BO->setIsExact(SubclassOptionalData & PossiblyExactOperator::IsExact);
3032 return BO;
3033 }
3034}