blob: 22ffc811511c6daf213649efbe156580eb443380 [file] [log] [blame]
Chris Lattner2b383d2e2003-05-13 21:37:02 +00001//===-- Constants.cpp - Implement Constant nodes --------------------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-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 Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner2f7c9632001-06-06 20:29:01 +00009//
Chris Lattnere17322b2011-02-07 20:03:14 +000010// This file implements the Constant* classes.
Chris Lattner2f7c9632001-06-06 20:29:01 +000011//
12//===----------------------------------------------------------------------===//
13
Chandler Carruth9fb823b2013-01-02 11:36:10 +000014#include "llvm/IR/Constants.h"
Chris Lattner33e93b82007-02-27 03:05:06 +000015#include "ConstantFold.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "LLVMContextImpl.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000017#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/SmallVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/ADT/StringMap.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000020#include "llvm/IR/DerivedTypes.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000021#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-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 Wendling6a462f12006-11-17 08:03:48 +000026#include "llvm/Support/Debug.h"
Torok Edwinccb29cd2009-07-11 13:10:19 +000027#include "llvm/Support/ErrorHandling.h"
Chris Lattner69edc982006-09-28 00:35:06 +000028#include "llvm/Support/ManagedStatic.h"
Bill Wendling6a462f12006-11-17 08:03:48 +000029#include "llvm/Support/MathExtras.h"
Chris Lattner78683a72009-08-23 04:02:03 +000030#include "llvm/Support/raw_ostream.h"
Chris Lattner2f7c9632001-06-06 20:29:01 +000031#include <algorithm>
Serge Gueltone38003f2017-05-09 19:31:13 +000032
Chris Lattner189d19f2003-11-21 20:23:48 +000033using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000034
Chris Lattner2f7c9632001-06-06 20:29:01 +000035//===----------------------------------------------------------------------===//
Chris Lattner3462ae32001-12-03 22:26:30 +000036// Constant Class
Chris Lattner2f7c9632001-06-06 20:29:01 +000037//===----------------------------------------------------------------------===//
38
Chris Lattnerac5fb562011-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 Kistanovafc259902012-07-13 01:25:27 +000043
David Tweed5493fee2013-03-18 11:54:44 +000044 // Equivalent for a vector of -0.0's.
45 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
Craig Topper0b4b4e32017-07-15 22:06:19 +000046 if (CV->getElementType()->isFloatingPointTy() && CV->isSplat())
47 if (CV->getElementAsAPFloat(0).isNegZero())
David Tweed5493fee2013-03-18 11:54:44 +000048 return true;
49
Owen Anderson8e851302015-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 Tweed298e4192013-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 Tweed5493fee2013-03-18 11:54:44 +000058
Chris Lattnerac5fb562011-07-15 05:58:04 +000059 // Otherwise, just use +0.0.
60 return isNullValue();
61}
62
Shuxin Yang9ca562e2013-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 Yangf0537ab2013-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 Anderson630077e2015-11-20 08:16:13 +000070 // Equivalent for a vector of -0.0's.
71 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
Craig Topper0b4b4e32017-07-15 22:06:19 +000072 if (CV->getElementType()->isFloatingPointTy() && CV->isSplat())
73 if (CV->getElementAsAPFloat(0).isZero())
Owen Anderson630077e2015-11-20 08:16:13 +000074 return true;
75
Owen Anderson8e851302015-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 Yangf0537ab2013-01-09 00:13:41 +000081 // Otherwise, just use +0.0.
82 return isNullValue();
83}
84
Chris Lattnerbe6610c2011-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 Kistanovafc259902012-07-13 01:25:27 +000089
Chris Lattnerbe6610c2011-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 Majnemerf0f224d2015-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 Lattnerbe6610c2011-07-15 06:14:08 +000098}
99
Nadav Rotem365af6f2011-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 Kramer42d098e2011-11-14 19:12:20 +0000109 // Check for constant vectors which are splats of -1 values.
Nadav Rotem365af6f2011-08-24 20:18:38 +0000110 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
Benjamin Kramer42d098e2011-11-14 19:12:20 +0000111 if (Constant *Splat = CV->getSplatValue())
112 return Splat->isAllOnesValue();
Nadav Rotem365af6f2011-08-24 20:18:38 +0000113
Chris Lattnerf14a67f2012-01-26 02:31:22 +0000114 // Check for constant vectors which are splats of -1 values.
Craig Topper0b4b4e32017-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 Lattnerf14a67f2012-01-26 02:31:22 +0000122
Nadav Rotem365af6f2011-08-24 20:18:38 +0000123 return false;
124}
Benjamin Kramer42d098e2011-11-14 19:12:20 +0000125
David Majnemer1a0bbc82014-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 Topper93ac6e12017-06-07 00:58:02 +0000133 return CFP->getValueAPF().bitcastToAPInt().isOneValue();
David Majnemer1a0bbc82014-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 Topper0b4b4e32017-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 Majnemer1a0bbc82014-08-16 09:23:42 +0000148
149 return false;
150}
151
David Majnemerbdeef602014-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 Topper0b4b4e32017-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 Majnemerbdeef602014-07-02 06:07:09 +0000174
175 return false;
176}
177
David Majnemer0e6c9862014-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 Popov0c5d6cc2018-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 Topper0b4b4e32017-07-15 22:06:19 +0000194 }
Nikita Popov0c5d6cc2018-12-01 10:58:34 +0000195 return true;
Craig Topper0b4b4e32017-07-15 22:06:19 +0000196 }
David Majnemer0e6c9862014-08-22 16:41:23 +0000197
198 // It *may* contain INT_MIN, we can't tell.
199 return false;
200}
201
Sanjay Patel08868e4942018-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 Patel90f4c8e2018-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 Patel46b083e2018-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 Patele6dda2f2018-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 Patel1d0ac7c2016-04-29 22:03:27 +0000264/// Constructor to create a '0' constant of arbitrary type.
Chris Lattner229907c2011-07-18 04:54:35 +0000265Constant *Constant::getNullValue(Type *Ty) {
Owen Anderson5a1acd92009-07-31 20:28:14 +0000266 switch (Ty->getTypeID()) {
267 case Type::IntegerTyID:
268 return ConstantInt::get(Ty, 0);
Dan Gohman518cda42011-12-17 00:04:22 +0000269 case Type::HalfTyID:
270 return ConstantFP::get(Ty->getContext(),
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000271 APFloat::getZero(APFloat::IEEEhalf()));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000272 case Type::FloatTyID:
Benjamin Kramer8ceebfa2010-12-04 14:22:24 +0000273 return ConstantFP::get(Ty->getContext(),
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000274 APFloat::getZero(APFloat::IEEEsingle()));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000275 case Type::DoubleTyID:
Benjamin Kramer8ceebfa2010-12-04 14:22:24 +0000276 return ConstantFP::get(Ty->getContext(),
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000277 APFloat::getZero(APFloat::IEEEdouble()));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000278 case Type::X86_FP80TyID:
Benjamin Kramer8ceebfa2010-12-04 14:22:24 +0000279 return ConstantFP::get(Ty->getContext(),
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000280 APFloat::getZero(APFloat::x87DoubleExtended()));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000281 case Type::FP128TyID:
282 return ConstantFP::get(Ty->getContext(),
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000283 APFloat::getZero(APFloat::IEEEquad()));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000284 case Type::PPC_FP128TyID:
Benjamin Kramer8ceebfa2010-12-04 14:22:24 +0000285 return ConstantFP::get(Ty->getContext(),
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000286 APFloat(APFloat::PPCDoubleDouble(),
Tim Northover29178a32013-01-22 09:46:31 +0000287 APInt::getNullValue(128)));
Owen Anderson5a1acd92009-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 Majnemerf0f224d2015-11-11 21:57:16 +0000294 case Type::TokenTyID:
295 return ConstantTokenNone::get(Ty->getContext());
Owen Anderson5a1acd92009-07-31 20:28:14 +0000296 default:
297 // Function, Label, or Opaque type?
Craig Topperc514b542012-02-05 22:14:15 +0000298 llvm_unreachable("Cannot create a null constant of that type!");
Owen Anderson5a1acd92009-07-31 20:28:14 +0000299 }
300}
301
Chris Lattner229907c2011-07-18 04:54:35 +0000302Constant *Constant::getIntegerValue(Type *Ty, const APInt &V) {
303 Type *ScalarTy = Ty->getScalarType();
Dan Gohmanf011f5a2009-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 Lattner229907c2011-07-18 04:54:35 +0000309 if (PointerType *PTy = dyn_cast<PointerType>(ScalarTy))
Dan Gohmanf011f5a2009-08-03 22:07:33 +0000310 C = ConstantExpr::getIntToPtr(C, PTy);
311
312 // Broadcast a scalar to a vector, if necessary.
Chris Lattner229907c2011-07-18 04:54:35 +0000313 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattnere9eed292012-01-25 05:19:54 +0000314 C = ConstantVector::getSplat(VTy->getNumElements(), C);
Dan Gohmanf011f5a2009-08-03 22:07:33 +0000315
316 return C;
317}
318
Chris Lattner229907c2011-07-18 04:54:35 +0000319Constant *Constant::getAllOnesValue(Type *Ty) {
320 if (IntegerType *ITy = dyn_cast<IntegerType>(Ty))
Owen Anderson5a1acd92009-07-31 20:28:14 +0000321 return ConstantInt::get(Ty->getContext(),
322 APInt::getAllOnesValue(ITy->getBitWidth()));
Nadav Rotem7cc6d122011-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 Lattner229907c2011-07-18 04:54:35 +0000330 VectorType *VTy = cast<VectorType>(Ty);
Chris Lattnere9eed292012-01-25 05:19:54 +0000331 return ConstantVector::getSplat(VTy->getNumElements(),
332 getAllOnesValue(VTy->getElementType()));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000333}
334
Chris Lattner7e683d12012-01-25 06:16:32 +0000335Constant *Constant::getAggregateElement(unsigned Elt) const {
Duncan P. N. Exon Smith1de3c7e2016-04-05 21:10:45 +0000336 if (const ConstantAggregate *CC = dyn_cast<ConstantAggregate>(this))
337 return Elt < CC->getNumOperands() ? CC->getOperand(Elt) : nullptr;
Galina Kistanovafc259902012-07-13 01:25:27 +0000338
David Majnemer9b529a72015-02-16 04:02:09 +0000339 if (const ConstantAggregateZero *CAZ = dyn_cast<ConstantAggregateZero>(this))
340 return Elt < CAZ->getNumElements() ? CAZ->getElementValue(Elt) : nullptr;
Galina Kistanovafc259902012-07-13 01:25:27 +0000341
Chris Lattner7e683d12012-01-25 06:16:32 +0000342 if (const UndefValue *UV = dyn_cast<UndefValue>(this))
David Majnemer9b529a72015-02-16 04:02:09 +0000343 return Elt < UV->getNumElements() ? UV->getElementValue(Elt) : nullptr;
Galina Kistanovafc259902012-07-13 01:25:27 +0000344
Chris Lattner8326bd82012-01-26 00:42:34 +0000345 if (const ConstantDataSequential *CDS =dyn_cast<ConstantDataSequential>(this))
Craig Topperc6207612014-04-09 06:08:46 +0000346 return Elt < CDS->getNumElements() ? CDS->getElementAsConstant(Elt)
347 : nullptr;
348 return nullptr;
Chris Lattner7e683d12012-01-25 06:16:32 +0000349}
350
351Constant *Constant::getAggregateElement(Constant *Elt) const {
352 assert(isa<IntegerType>(Elt->getType()) && "Index must be an integer");
353 if (ConstantInt *CI = dyn_cast<ConstantInt>(Elt))
354 return getAggregateElement(CI->getZExtValue());
Craig Topperc6207612014-04-09 06:08:46 +0000355 return nullptr;
Chris Lattner7e683d12012-01-25 06:16:32 +0000356}
357
Pete Cooper86dd4cf2015-06-23 21:55:11 +0000358void Constant::destroyConstant() {
359 /// First call destroyConstantImpl on the subclass. This gives the subclass
360 /// a chance to remove the constant from any maps/pools it's contained in.
361 switch (getValueID()) {
362 default:
363 llvm_unreachable("Not a constant!");
364#define HANDLE_CONSTANT(Name) \
365 case Value::Name##Val: \
366 cast<Name>(this)->destroyConstantImpl(); \
367 break;
368#include "llvm/IR/Value.def"
369 }
Chris Lattner7e683d12012-01-25 06:16:32 +0000370
Chris Lattner3462ae32001-12-03 22:26:30 +0000371 // When a Constant is destroyed, there may be lingering
Chris Lattnerd7a73302001-10-13 06:57:33 +0000372 // references to the constant by other constants in the constant pool. These
Misha Brukmanbe372b92003-08-21 22:14:26 +0000373 // constants are implicitly dependent on the module that is being deleted,
Chris Lattnerd7a73302001-10-13 06:57:33 +0000374 // but they don't know that. Because we only find out when the CPV is
375 // deleted, we must now notify all of our users (that should only be
Chris Lattner3462ae32001-12-03 22:26:30 +0000376 // Constants) that they are, in fact, invalid now and should be deleted.
Chris Lattnerd7a73302001-10-13 06:57:33 +0000377 //
378 while (!use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000379 Value *V = user_back();
Pete Cooper86dd4cf2015-06-23 21:55:11 +0000380#ifndef NDEBUG // Only in -g mode...
Chris Lattner78683a72009-08-23 04:02:03 +0000381 if (!isa<Constant>(V)) {
David Greene1e27a132010-01-05 01:29:19 +0000382 dbgs() << "While deleting: " << *this
Pete Cooper86dd4cf2015-06-23 21:55:11 +0000383 << "\n\nUse still stuck around after Def is destroyed: " << *V
384 << "\n\n";
Chris Lattner78683a72009-08-23 04:02:03 +0000385 }
Chris Lattnerd7a73302001-10-13 06:57:33 +0000386#endif
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000387 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
Chris Lattner8326bd82012-01-26 00:42:34 +0000388 cast<Constant>(V)->destroyConstant();
Chris Lattnerd7a73302001-10-13 06:57:33 +0000389
390 // The constant should remove itself from our use list...
Chandler Carruthcdf47882014-03-09 03:16:01 +0000391 assert((use_empty() || user_back() != V) && "Constant not removed!");
Chris Lattnerd7a73302001-10-13 06:57:33 +0000392 }
393
394 // Value has no outstanding references it is safe to delete it now...
395 delete this;
Chris Lattner38569342001-10-01 20:11:19 +0000396}
Chris Lattner2f7c9632001-06-06 20:29:01 +0000397
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000398static bool canTrapImpl(const Constant *C,
Craig Topper71b7b682014-08-21 05:55:13 +0000399 SmallPtrSetImpl<const ConstantExpr *> &NonTrappingOps) {
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000400 assert(C->getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
Chris Lattner23dd1f62006-10-20 00:27:06 +0000401 // The only thing that could possibly trap are constant exprs.
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000402 const ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
403 if (!CE)
404 return false;
Galina Kistanovafc259902012-07-13 01:25:27 +0000405
406 // ConstantExpr traps if any operands can trap.
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000407 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
408 if (ConstantExpr *Op = dyn_cast<ConstantExpr>(CE->getOperand(i))) {
David Blaikie70573dc2014-11-19 07:49:26 +0000409 if (NonTrappingOps.insert(Op).second && canTrapImpl(Op, NonTrappingOps))
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000410 return true;
411 }
412 }
Chris Lattner23dd1f62006-10-20 00:27:06 +0000413
414 // Otherwise, only specific operations can trap.
415 switch (CE->getOpcode()) {
416 default:
417 return false;
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000418 case Instruction::UDiv:
419 case Instruction::SDiv:
Reid Spencer7eb55b32006-11-02 01:53:59 +0000420 case Instruction::URem:
421 case Instruction::SRem:
Chris Lattner23dd1f62006-10-20 00:27:06 +0000422 // Div and rem can trap if the RHS is not known to be non-zero.
Chris Lattnera91a5632009-10-28 05:14:34 +0000423 if (!isa<ConstantInt>(CE->getOperand(1)) ||CE->getOperand(1)->isNullValue())
Chris Lattner23dd1f62006-10-20 00:27:06 +0000424 return true;
425 return false;
426 }
427}
428
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000429bool Constant::canTrap() const {
430 SmallPtrSet<const ConstantExpr *, 4> NonTrappingOps;
431 return canTrapImpl(this, NonTrappingOps);
432}
433
Hans Wennborg4dc89512014-06-20 00:38:12 +0000434/// Check if C contains a GlobalValue for which Predicate is true.
435static bool
436ConstHasGlobalValuePredicate(const Constant *C,
437 bool (*Predicate)(const GlobalValue *)) {
438 SmallPtrSet<const Constant *, 8> Visited;
439 SmallVector<const Constant *, 8> WorkList;
440 WorkList.push_back(C);
441 Visited.insert(C);
Hans Wennborg709e0152012-11-15 11:40:00 +0000442
443 while (!WorkList.empty()) {
Hans Wennborg4dc89512014-06-20 00:38:12 +0000444 const Constant *WorkItem = WorkList.pop_back_val();
445 if (const auto *GV = dyn_cast<GlobalValue>(WorkItem))
446 if (Predicate(GV))
Hans Wennborg709e0152012-11-15 11:40:00 +0000447 return true;
Hans Wennborg4dc89512014-06-20 00:38:12 +0000448 for (const Value *Op : WorkItem->operands()) {
449 const Constant *ConstOp = dyn_cast<Constant>(Op);
450 if (!ConstOp)
Hans Wennborg18aa12402012-11-16 10:33:25 +0000451 continue;
David Blaikie70573dc2014-11-19 07:49:26 +0000452 if (Visited.insert(ConstOp).second)
Hans Wennborg4dc89512014-06-20 00:38:12 +0000453 WorkList.push_back(ConstOp);
Hans Wennborg709e0152012-11-15 11:40:00 +0000454 }
455 }
Hans Wennborg709e0152012-11-15 11:40:00 +0000456 return false;
457}
458
Hans Wennborg4dc89512014-06-20 00:38:12 +0000459bool Constant::isThreadDependent() const {
460 auto DLLImportPredicate = [](const GlobalValue *GV) {
461 return GV->isThreadLocal();
462 };
463 return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
464}
465
466bool Constant::isDLLImportDependent() const {
467 auto DLLImportPredicate = [](const GlobalValue *GV) {
468 return GV->hasDLLImportStorageClass();
469 };
470 return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
471}
472
Chris Lattner253bc772009-11-01 18:11:50 +0000473bool Constant::isConstantUsed() const {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000474 for (const User *U : users()) {
475 const Constant *UC = dyn_cast<Constant>(U);
Craig Topperc6207612014-04-09 06:08:46 +0000476 if (!UC || isa<GlobalValue>(UC))
Chris Lattner253bc772009-11-01 18:11:50 +0000477 return true;
Galina Kistanovafc259902012-07-13 01:25:27 +0000478
Chris Lattner253bc772009-11-01 18:11:50 +0000479 if (UC->isConstantUsed())
480 return true;
481 }
482 return false;
483}
484
Rafael Espindola65e49022015-11-17 00:51:23 +0000485bool Constant::needsRelocation() const {
486 if (isa<GlobalValue>(this))
487 return true; // Global reference.
488
Chris Lattner2cb85b42009-10-28 04:12:16 +0000489 if (const BlockAddress *BA = dyn_cast<BlockAddress>(this))
Rafael Espindola65e49022015-11-17 00:51:23 +0000490 return BA->getFunction()->needsRelocation();
491
Chris Lattnera7cfc432010-01-03 18:09:40 +0000492 // While raw uses of blockaddress need to be relocated, differences between
493 // two of them don't when they are for labels in the same function. This is a
494 // common idiom when creating a table for the indirect goto extension, so we
495 // handle it efficiently here.
496 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(this))
497 if (CE->getOpcode() == Instruction::Sub) {
498 ConstantExpr *LHS = dyn_cast<ConstantExpr>(CE->getOperand(0));
499 ConstantExpr *RHS = dyn_cast<ConstantExpr>(CE->getOperand(1));
Rafael Espindola65e49022015-11-17 00:51:23 +0000500 if (LHS && RHS && LHS->getOpcode() == Instruction::PtrToInt &&
Chris Lattnera7cfc432010-01-03 18:09:40 +0000501 RHS->getOpcode() == Instruction::PtrToInt &&
502 isa<BlockAddress>(LHS->getOperand(0)) &&
503 isa<BlockAddress>(RHS->getOperand(0)) &&
504 cast<BlockAddress>(LHS->getOperand(0))->getFunction() ==
Rafael Espindola65e49022015-11-17 00:51:23 +0000505 cast<BlockAddress>(RHS->getOperand(0))->getFunction())
506 return false;
Chris Lattnera7cfc432010-01-03 18:09:40 +0000507 }
Galina Kistanovafc259902012-07-13 01:25:27 +0000508
Rafael Espindola65e49022015-11-17 00:51:23 +0000509 bool Result = false;
Evan Chengf9e003b2007-03-08 00:59:12 +0000510 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
Rafael Espindola65e49022015-11-17 00:51:23 +0000511 Result |= cast<Constant>(getOperand(i))->needsRelocation();
Galina Kistanovafc259902012-07-13 01:25:27 +0000512
Chris Lattner4565ef52009-07-22 00:05:44 +0000513 return Result;
Evan Chengf9e003b2007-03-08 00:59:12 +0000514}
515
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +0000516/// If the specified constantexpr is dead, remove it. This involves recursively
517/// eliminating any dead users of the constantexpr.
Chris Lattner84886402011-02-18 04:41:42 +0000518static bool removeDeadUsersOfConstant(const Constant *C) {
519 if (isa<GlobalValue>(C)) return false; // Cannot remove this
Galina Kistanovafc259902012-07-13 01:25:27 +0000520
Chris Lattner84886402011-02-18 04:41:42 +0000521 while (!C->use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000522 const Constant *User = dyn_cast<Constant>(C->user_back());
Chris Lattner84886402011-02-18 04:41:42 +0000523 if (!User) return false; // Non-constant usage;
524 if (!removeDeadUsersOfConstant(User))
525 return false; // Constant wasn't dead
526 }
Galina Kistanovafc259902012-07-13 01:25:27 +0000527
Chris Lattner84886402011-02-18 04:41:42 +0000528 const_cast<Constant*>(C)->destroyConstant();
529 return true;
530}
531
532
Chris Lattner84886402011-02-18 04:41:42 +0000533void Constant::removeDeadConstantUsers() const {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000534 Value::const_user_iterator I = user_begin(), E = user_end();
535 Value::const_user_iterator LastNonDeadUser = E;
Chris Lattner84886402011-02-18 04:41:42 +0000536 while (I != E) {
537 const Constant *User = dyn_cast<Constant>(*I);
Craig Topperc6207612014-04-09 06:08:46 +0000538 if (!User) {
Chris Lattner84886402011-02-18 04:41:42 +0000539 LastNonDeadUser = I;
540 ++I;
541 continue;
542 }
Galina Kistanovafc259902012-07-13 01:25:27 +0000543
Chris Lattner84886402011-02-18 04:41:42 +0000544 if (!removeDeadUsersOfConstant(User)) {
545 // If the constant wasn't dead, remember that this was the last live use
546 // and move on to the next constant.
547 LastNonDeadUser = I;
548 ++I;
549 continue;
550 }
Galina Kistanovafc259902012-07-13 01:25:27 +0000551
Chris Lattner84886402011-02-18 04:41:42 +0000552 // If the constant was dead, then the iterator is invalidated.
553 if (LastNonDeadUser == E) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000554 I = user_begin();
Chris Lattner84886402011-02-18 04:41:42 +0000555 if (I == E) break;
556 } else {
557 I = LastNonDeadUser;
558 ++I;
559 }
560 }
561}
562
563
Chris Lattner2105d662008-07-10 00:28:11 +0000564
Chris Lattner2f7c9632001-06-06 20:29:01 +0000565//===----------------------------------------------------------------------===//
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000566// ConstantInt
Chris Lattner2f7c9632001-06-06 20:29:01 +0000567//===----------------------------------------------------------------------===//
568
Duncan P. N. Exon Smithb6452792016-02-21 02:39:49 +0000569ConstantInt::ConstantInt(IntegerType *Ty, const APInt &V)
570 : ConstantData(Ty, ConstantIntVal), Val(V) {
Reid Spencerb31bffe2007-02-26 23:54:03 +0000571 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
Chris Lattner2f7c9632001-06-06 20:29:01 +0000572}
573
Nick Lewycky92db8e82011-03-06 03:36:19 +0000574ConstantInt *ConstantInt::getTrue(LLVMContext &Context) {
Owen Anderson23a204d2009-07-31 17:39:07 +0000575 LLVMContextImpl *pImpl = Context.pImpl;
Benjamin Kramerddd1b7b2010-11-20 18:43:35 +0000576 if (!pImpl->TheTrueVal)
577 pImpl->TheTrueVal = ConstantInt::get(Type::getInt1Ty(Context), 1);
578 return pImpl->TheTrueVal;
Owen Anderson23a204d2009-07-31 17:39:07 +0000579}
580
Nick Lewycky92db8e82011-03-06 03:36:19 +0000581ConstantInt *ConstantInt::getFalse(LLVMContext &Context) {
Owen Anderson23a204d2009-07-31 17:39:07 +0000582 LLVMContextImpl *pImpl = Context.pImpl;
Benjamin Kramerddd1b7b2010-11-20 18:43:35 +0000583 if (!pImpl->TheFalseVal)
584 pImpl->TheFalseVal = ConstantInt::get(Type::getInt1Ty(Context), 0);
585 return pImpl->TheFalseVal;
Owen Anderson23a204d2009-07-31 17:39:07 +0000586}
587
Chris Lattner229907c2011-07-18 04:54:35 +0000588Constant *ConstantInt::getTrue(Type *Ty) {
Craig Topperfde47232017-07-09 07:04:03 +0000589 assert(Ty->isIntOrIntVectorTy(1) && "Type not i1 or vector of i1.");
Sanjay Patel70a575a2017-04-16 17:00:21 +0000590 ConstantInt *TrueC = ConstantInt::getTrue(Ty->getContext());
591 if (auto *VTy = dyn_cast<VectorType>(Ty))
592 return ConstantVector::getSplat(VTy->getNumElements(), TrueC);
593 return TrueC;
Nick Lewycky92db8e82011-03-06 03:36:19 +0000594}
595
Chris Lattner229907c2011-07-18 04:54:35 +0000596Constant *ConstantInt::getFalse(Type *Ty) {
Craig Topperfde47232017-07-09 07:04:03 +0000597 assert(Ty->isIntOrIntVectorTy(1) && "Type not i1 or vector of i1.");
Sanjay Patel70a575a2017-04-16 17:00:21 +0000598 ConstantInt *FalseC = ConstantInt::getFalse(Ty->getContext());
599 if (auto *VTy = dyn_cast<VectorType>(Ty))
600 return ConstantVector::getSplat(VTy->getNumElements(), FalseC);
601 return FalseC;
Nick Lewycky92db8e82011-03-06 03:36:19 +0000602}
603
Benjamin Kramer8e5dc532014-12-06 13:12:56 +0000604// Get a ConstantInt from an APInt.
Nick Lewycky92db8e82011-03-06 03:36:19 +0000605ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt &V) {
Owen Andersonedb4a702009-07-24 23:12:02 +0000606 // get an existing value or the insertion position
Benjamin Kramer320682f2013-06-01 17:51:03 +0000607 LLVMContextImpl *pImpl = Context.pImpl;
Justin Lebar611c5c22016-10-10 16:26:13 +0000608 std::unique_ptr<ConstantInt> &Slot = pImpl->IntConstants[V];
Benjamin Kramer8e5dc532014-12-06 13:12:56 +0000609 if (!Slot) {
610 // Get the corresponding integer type for the bit width of the value.
611 IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
Justin Lebar611c5c22016-10-10 16:26:13 +0000612 Slot.reset(new ConstantInt(ITy, V));
Benjamin Kramer8e5dc532014-12-06 13:12:56 +0000613 }
614 assert(Slot->getType() == IntegerType::get(Context, V.getBitWidth()));
Justin Lebar611c5c22016-10-10 16:26:13 +0000615 return Slot.get();
Owen Andersonedb4a702009-07-24 23:12:02 +0000616}
617
Chris Lattner229907c2011-07-18 04:54:35 +0000618Constant *ConstantInt::get(Type *Ty, uint64_t V, bool isSigned) {
Nick Lewycky92db8e82011-03-06 03:36:19 +0000619 Constant *C = get(cast<IntegerType>(Ty->getScalarType()), V, isSigned);
Owen Andersonedb4a702009-07-24 23:12:02 +0000620
621 // For vectors, broadcast the value.
Chris Lattner229907c2011-07-18 04:54:35 +0000622 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattnere9eed292012-01-25 05:19:54 +0000623 return ConstantVector::getSplat(VTy->getNumElements(), C);
Owen Andersonedb4a702009-07-24 23:12:02 +0000624
625 return C;
626}
627
Sanjay Patelf3587ec2016-05-18 22:05:28 +0000628ConstantInt *ConstantInt::get(IntegerType *Ty, uint64_t V, bool isSigned) {
Owen Andersonedb4a702009-07-24 23:12:02 +0000629 return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned));
630}
631
Chris Lattner0256be92012-01-27 03:08:05 +0000632ConstantInt *ConstantInt::getSigned(IntegerType *Ty, int64_t V) {
Owen Andersonedb4a702009-07-24 23:12:02 +0000633 return get(Ty, V, true);
634}
635
Chris Lattner229907c2011-07-18 04:54:35 +0000636Constant *ConstantInt::getSigned(Type *Ty, int64_t V) {
Owen Andersonedb4a702009-07-24 23:12:02 +0000637 return get(Ty, V, true);
638}
639
Chris Lattner0256be92012-01-27 03:08:05 +0000640Constant *ConstantInt::get(Type *Ty, const APInt& V) {
Owen Andersonedb4a702009-07-24 23:12:02 +0000641 ConstantInt *C = get(Ty->getContext(), V);
642 assert(C->getType() == Ty->getScalarType() &&
643 "ConstantInt type doesn't match the type implied by its value!");
644
645 // For vectors, broadcast the value.
Chris Lattner229907c2011-07-18 04:54:35 +0000646 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattnere9eed292012-01-25 05:19:54 +0000647 return ConstantVector::getSplat(VTy->getNumElements(), C);
Owen Andersonedb4a702009-07-24 23:12:02 +0000648
649 return C;
650}
651
Sanjay Patelf3587ec2016-05-18 22:05:28 +0000652ConstantInt *ConstantInt::get(IntegerType* Ty, StringRef Str, uint8_t radix) {
Erick Tryzelaarfc2280d2009-08-16 23:36:33 +0000653 return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
654}
655
Pete Cooper86dd4cf2015-06-23 21:55:11 +0000656/// Remove the constant from the constant table.
657void ConstantInt::destroyConstantImpl() {
658 llvm_unreachable("You can't ConstantInt->destroyConstantImpl()!");
659}
660
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000661//===----------------------------------------------------------------------===//
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000662// ConstantFP
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000663//===----------------------------------------------------------------------===//
664
Chris Lattner229907c2011-07-18 04:54:35 +0000665static const fltSemantics *TypeToFloatSemantics(Type *Ty) {
Dan Gohman518cda42011-12-17 00:04:22 +0000666 if (Ty->isHalfTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000667 return &APFloat::IEEEhalf();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000668 if (Ty->isFloatTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000669 return &APFloat::IEEEsingle();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000670 if (Ty->isDoubleTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000671 return &APFloat::IEEEdouble();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000672 if (Ty->isX86_FP80Ty())
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000673 return &APFloat::x87DoubleExtended();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000674 else if (Ty->isFP128Ty())
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000675 return &APFloat::IEEEquad();
Galina Kistanovafc259902012-07-13 01:25:27 +0000676
Chris Lattnerfdd87902009-10-05 05:54:46 +0000677 assert(Ty->isPPC_FP128Ty() && "Unknown FP format");
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000678 return &APFloat::PPCDoubleDouble();
Rafael Espindolaf5d53d42009-07-15 17:40:42 +0000679}
680
Chris Lattner0256be92012-01-27 03:08:05 +0000681Constant *ConstantFP::get(Type *Ty, double V) {
Owen Anderson69c464d2009-07-27 20:59:43 +0000682 LLVMContext &Context = Ty->getContext();
Galina Kistanovafc259902012-07-13 01:25:27 +0000683
Owen Anderson69c464d2009-07-27 20:59:43 +0000684 APFloat FV(V);
685 bool ignored;
686 FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
687 APFloat::rmNearestTiesToEven, &ignored);
688 Constant *C = get(Context, FV);
689
690 // For vectors, broadcast the value.
Chris Lattner229907c2011-07-18 04:54:35 +0000691 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattnere9eed292012-01-25 05:19:54 +0000692 return ConstantVector::getSplat(VTy->getNumElements(), C);
Owen Anderson69c464d2009-07-27 20:59:43 +0000693
694 return C;
695}
696
Sanjay Patel6a0f6672018-02-15 13:55:52 +0000697Constant *ConstantFP::get(Type *Ty, const APFloat &V) {
698 ConstantFP *C = get(Ty->getContext(), V);
699 assert(C->getType() == Ty->getScalarType() &&
700 "ConstantFP type doesn't match the type implied by its value!");
701
702 // For vectors, broadcast the value.
703 if (auto *VTy = dyn_cast<VectorType>(Ty))
704 return ConstantVector::getSplat(VTy->getNumElements(), C);
705
706 return C;
707}
Erick Tryzelaarfc2280d2009-08-16 23:36:33 +0000708
Chris Lattner0256be92012-01-27 03:08:05 +0000709Constant *ConstantFP::get(Type *Ty, StringRef Str) {
Erick Tryzelaarfc2280d2009-08-16 23:36:33 +0000710 LLVMContext &Context = Ty->getContext();
711
712 APFloat FV(*TypeToFloatSemantics(Ty->getScalarType()), Str);
713 Constant *C = get(Context, FV);
714
715 // For vectors, broadcast the value.
Chris Lattner229907c2011-07-18 04:54:35 +0000716 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattnere9eed292012-01-25 05:19:54 +0000717 return ConstantVector::getSplat(VTy->getNumElements(), C);
Erick Tryzelaarfc2280d2009-08-16 23:36:33 +0000718
Bjorn Petterssonaa025802018-07-03 12:39:52 +0000719 return C;
Erick Tryzelaarfc2280d2009-08-16 23:36:33 +0000720}
721
JF Bastien69f60982018-12-10 19:27:38 +0000722Constant *ConstantFP::getNaN(Type *Ty, bool Negative, uint64_t Payload) {
Tom Stellard67246d12015-04-20 19:38:24 +0000723 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
JF Bastien69f60982018-12-10 19:27:38 +0000724 APFloat NaN = APFloat::getNaN(Semantics, Negative, Payload);
Tom Stellard67246d12015-04-20 19:38:24 +0000725 Constant *C = get(Ty->getContext(), NaN);
726
727 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
728 return ConstantVector::getSplat(VTy->getNumElements(), C);
729
730 return C;
731}
732
JF Bastien69f60982018-12-10 19:27:38 +0000733Constant *ConstantFP::getQNaN(Type *Ty, bool Negative, APInt *Payload) {
734 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
735 APFloat NaN = APFloat::getQNaN(Semantics, Negative, Payload);
736 Constant *C = get(Ty->getContext(), NaN);
737
738 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
739 return ConstantVector::getSplat(VTy->getNumElements(), C);
740
741 return C;
742}
743
744Constant *ConstantFP::getSNaN(Type *Ty, bool Negative, APInt *Payload) {
745 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
746 APFloat NaN = APFloat::getSNaN(Semantics, Negative, Payload);
747 Constant *C = get(Ty->getContext(), NaN);
748
749 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
750 return ConstantVector::getSplat(VTy->getNumElements(), C);
751
752 return C;
753}
754
Benjamin Kramer5d2ff222014-01-18 16:43:06 +0000755Constant *ConstantFP::getNegativeZero(Type *Ty) {
756 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
757 APFloat NegZero = APFloat::getZero(Semantics, /*Negative=*/true);
758 Constant *C = get(Ty->getContext(), NegZero);
Erick Tryzelaarfc2280d2009-08-16 23:36:33 +0000759
Benjamin Kramer5d2ff222014-01-18 16:43:06 +0000760 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
761 return ConstantVector::getSplat(VTy->getNumElements(), C);
762
763 return C;
Owen Anderson69c464d2009-07-27 20:59:43 +0000764}
765
766
Chris Lattnere9eed292012-01-25 05:19:54 +0000767Constant *ConstantFP::getZeroValueForNegation(Type *Ty) {
Benjamin Kramer5d2ff222014-01-18 16:43:06 +0000768 if (Ty->isFPOrFPVectorTy())
769 return getNegativeZero(Ty);
Owen Anderson69c464d2009-07-27 20:59:43 +0000770
Owen Anderson5a1acd92009-07-31 20:28:14 +0000771 return Constant::getNullValue(Ty);
Owen Anderson69c464d2009-07-27 20:59:43 +0000772}
773
774
775// ConstantFP accessors.
776ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
Owen Anderson69c464d2009-07-27 20:59:43 +0000777 LLVMContextImpl* pImpl = Context.pImpl;
Galina Kistanovafc259902012-07-13 01:25:27 +0000778
Justin Lebar611c5c22016-10-10 16:26:13 +0000779 std::unique_ptr<ConstantFP> &Slot = pImpl->FPConstants[V];
Galina Kistanovafc259902012-07-13 01:25:27 +0000780
Owen Anderson69c464d2009-07-27 20:59:43 +0000781 if (!Slot) {
Chris Lattner229907c2011-07-18 04:54:35 +0000782 Type *Ty;
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000783 if (&V.getSemantics() == &APFloat::IEEEhalf())
Dan Gohman518cda42011-12-17 00:04:22 +0000784 Ty = Type::getHalfTy(Context);
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000785 else if (&V.getSemantics() == &APFloat::IEEEsingle())
Owen Anderson5dab84c2009-10-19 20:11:52 +0000786 Ty = Type::getFloatTy(Context);
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000787 else if (&V.getSemantics() == &APFloat::IEEEdouble())
Owen Anderson5dab84c2009-10-19 20:11:52 +0000788 Ty = Type::getDoubleTy(Context);
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000789 else if (&V.getSemantics() == &APFloat::x87DoubleExtended())
Owen Anderson5dab84c2009-10-19 20:11:52 +0000790 Ty = Type::getX86_FP80Ty(Context);
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000791 else if (&V.getSemantics() == &APFloat::IEEEquad())
Owen Anderson5dab84c2009-10-19 20:11:52 +0000792 Ty = Type::getFP128Ty(Context);
793 else {
Bjorn Petterssonaa025802018-07-03 12:39:52 +0000794 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble() &&
Owen Anderson5dab84c2009-10-19 20:11:52 +0000795 "Unknown FP format");
796 Ty = Type::getPPC_FP128Ty(Context);
Owen Anderson69c464d2009-07-27 20:59:43 +0000797 }
Justin Lebar611c5c22016-10-10 16:26:13 +0000798 Slot.reset(new ConstantFP(Ty, V));
Owen Anderson69c464d2009-07-27 20:59:43 +0000799 }
Galina Kistanovafc259902012-07-13 01:25:27 +0000800
Justin Lebar611c5c22016-10-10 16:26:13 +0000801 return Slot.get();
Owen Anderson69c464d2009-07-27 20:59:43 +0000802}
803
Benjamin Kramer5d2ff222014-01-18 16:43:06 +0000804Constant *ConstantFP::getInfinity(Type *Ty, bool Negative) {
805 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
806 Constant *C = get(Ty->getContext(), APFloat::getInf(Semantics, Negative));
807
808 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
809 return ConstantVector::getSplat(VTy->getNumElements(), C);
810
811 return C;
Dan Gohmanfeb50212009-09-25 23:00:48 +0000812}
813
Duncan P. N. Exon Smithb6452792016-02-21 02:39:49 +0000814ConstantFP::ConstantFP(Type *Ty, const APFloat &V)
815 : ConstantData(Ty, ConstantFPVal), Val(V) {
Chris Lattner98bd9392008-04-09 06:38:30 +0000816 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
817 "FP type Mismatch");
Chris Lattner2f7c9632001-06-06 20:29:01 +0000818}
819
Chris Lattnerbe6610c2011-07-15 06:14:08 +0000820bool ConstantFP::isExactlyValue(const APFloat &V) const {
Dale Johannesend246b2c2007-08-30 00:23:21 +0000821 return Val.bitwiseIsEqual(V);
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000822}
823
Pete Cooper86dd4cf2015-06-23 21:55:11 +0000824/// Remove the constant from the constant table.
825void ConstantFP::destroyConstantImpl() {
Craig Topperccbb8102017-06-27 19:57:51 +0000826 llvm_unreachable("You can't ConstantFP->destroyConstantImpl()!");
Pete Cooper86dd4cf2015-06-23 21:55:11 +0000827}
828
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000829//===----------------------------------------------------------------------===//
Chris Lattner030af792012-01-24 05:42:11 +0000830// ConstantAggregateZero Implementation
831//===----------------------------------------------------------------------===//
832
Chris Lattner7e683d12012-01-25 06:16:32 +0000833Constant *ConstantAggregateZero::getSequentialElement() const {
Chris Lattner8326bd82012-01-26 00:42:34 +0000834 return Constant::getNullValue(getType()->getSequentialElementType());
Chris Lattner030af792012-01-24 05:42:11 +0000835}
836
Chris Lattner7e683d12012-01-25 06:16:32 +0000837Constant *ConstantAggregateZero::getStructElement(unsigned Elt) const {
Chris Lattner8326bd82012-01-26 00:42:34 +0000838 return Constant::getNullValue(getType()->getStructElementType(Elt));
Chris Lattner030af792012-01-24 05:42:11 +0000839}
840
Chris Lattner7e683d12012-01-25 06:16:32 +0000841Constant *ConstantAggregateZero::getElementValue(Constant *C) const {
Chris Lattner030af792012-01-24 05:42:11 +0000842 if (isa<SequentialType>(getType()))
843 return getSequentialElement();
844 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
845}
846
Chris Lattner7e683d12012-01-25 06:16:32 +0000847Constant *ConstantAggregateZero::getElementValue(unsigned Idx) const {
Chris Lattnerf7eb5432012-01-24 07:54:10 +0000848 if (isa<SequentialType>(getType()))
849 return getSequentialElement();
850 return getStructElement(Idx);
851}
852
David Majnemer9b529a72015-02-16 04:02:09 +0000853unsigned ConstantAggregateZero::getNumElements() const {
Craig Toppere3dcce92015-08-01 22:20:21 +0000854 Type *Ty = getType();
855 if (auto *AT = dyn_cast<ArrayType>(Ty))
David Majnemer9b529a72015-02-16 04:02:09 +0000856 return AT->getNumElements();
Craig Toppere3dcce92015-08-01 22:20:21 +0000857 if (auto *VT = dyn_cast<VectorType>(Ty))
David Majnemer9b529a72015-02-16 04:02:09 +0000858 return VT->getNumElements();
859 return Ty->getStructNumElements();
860}
Chris Lattnerf7eb5432012-01-24 07:54:10 +0000861
Chris Lattner030af792012-01-24 05:42:11 +0000862//===----------------------------------------------------------------------===//
863// UndefValue Implementation
864//===----------------------------------------------------------------------===//
865
Chris Lattner7e683d12012-01-25 06:16:32 +0000866UndefValue *UndefValue::getSequentialElement() const {
Chris Lattner8326bd82012-01-26 00:42:34 +0000867 return UndefValue::get(getType()->getSequentialElementType());
Chris Lattner030af792012-01-24 05:42:11 +0000868}
869
Chris Lattner7e683d12012-01-25 06:16:32 +0000870UndefValue *UndefValue::getStructElement(unsigned Elt) const {
Chris Lattner8326bd82012-01-26 00:42:34 +0000871 return UndefValue::get(getType()->getStructElementType(Elt));
Chris Lattner030af792012-01-24 05:42:11 +0000872}
873
Chris Lattner7e683d12012-01-25 06:16:32 +0000874UndefValue *UndefValue::getElementValue(Constant *C) const {
Chris Lattner030af792012-01-24 05:42:11 +0000875 if (isa<SequentialType>(getType()))
876 return getSequentialElement();
877 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
878}
879
Chris Lattner7e683d12012-01-25 06:16:32 +0000880UndefValue *UndefValue::getElementValue(unsigned Idx) const {
Chris Lattnerf7eb5432012-01-24 07:54:10 +0000881 if (isa<SequentialType>(getType()))
882 return getSequentialElement();
883 return getStructElement(Idx);
884}
885
David Majnemer9b529a72015-02-16 04:02:09 +0000886unsigned UndefValue::getNumElements() const {
Craig Toppere3dcce92015-08-01 22:20:21 +0000887 Type *Ty = getType();
Peter Collingbournebc070522016-12-02 03:20:58 +0000888 if (auto *ST = dyn_cast<SequentialType>(Ty))
889 return ST->getNumElements();
David Majnemer9b529a72015-02-16 04:02:09 +0000890 return Ty->getStructNumElements();
891}
Chris Lattner030af792012-01-24 05:42:11 +0000892
893//===----------------------------------------------------------------------===//
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000894// ConstantXXX Classes
895//===----------------------------------------------------------------------===//
896
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000897template <typename ItTy, typename EltTy>
898static bool rangeOnlyContains(ItTy Start, ItTy End, EltTy Elt) {
899 for (; Start != End; ++Start)
900 if (*Start != Elt)
901 return false;
902 return true;
903}
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000904
Justin Bogner909e1c02015-12-01 20:20:49 +0000905template <typename SequentialTy, typename ElementTy>
906static Constant *getIntSequenceIfElementsMatch(ArrayRef<Constant *> V) {
907 assert(!V.empty() && "Cannot get empty int sequence.");
908
909 SmallVector<ElementTy, 16> Elts;
910 for (Constant *C : V)
911 if (auto *CI = dyn_cast<ConstantInt>(C))
912 Elts.push_back(CI->getZExtValue());
913 else
914 return nullptr;
915 return SequentialTy::get(V[0]->getContext(), Elts);
916}
917
918template <typename SequentialTy, typename ElementTy>
919static Constant *getFPSequenceIfElementsMatch(ArrayRef<Constant *> V) {
920 assert(!V.empty() && "Cannot get empty FP sequence.");
921
922 SmallVector<ElementTy, 16> Elts;
923 for (Constant *C : V)
924 if (auto *CFP = dyn_cast<ConstantFP>(C))
925 Elts.push_back(CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
926 else
927 return nullptr;
928 return SequentialTy::getFP(V[0]->getContext(), Elts);
929}
930
931template <typename SequenceTy>
932static Constant *getSequenceIfElementsMatch(Constant *C,
933 ArrayRef<Constant *> V) {
934 // We speculatively build the elements here even if it turns out that there is
935 // a constantexpr or something else weird, since it is so uncommon for that to
936 // happen.
937 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
938 if (CI->getType()->isIntegerTy(8))
939 return getIntSequenceIfElementsMatch<SequenceTy, uint8_t>(V);
940 else if (CI->getType()->isIntegerTy(16))
941 return getIntSequenceIfElementsMatch<SequenceTy, uint16_t>(V);
942 else if (CI->getType()->isIntegerTy(32))
943 return getIntSequenceIfElementsMatch<SequenceTy, uint32_t>(V);
944 else if (CI->getType()->isIntegerTy(64))
945 return getIntSequenceIfElementsMatch<SequenceTy, uint64_t>(V);
946 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
Justin Bogner0ebc8602015-12-08 03:01:16 +0000947 if (CFP->getType()->isHalfTy())
948 return getFPSequenceIfElementsMatch<SequenceTy, uint16_t>(V);
949 else if (CFP->getType()->isFloatTy())
Justin Bogner909e1c02015-12-01 20:20:49 +0000950 return getFPSequenceIfElementsMatch<SequenceTy, uint32_t>(V);
951 else if (CFP->getType()->isDoubleTy())
952 return getFPSequenceIfElementsMatch<SequenceTy, uint64_t>(V);
953 }
954
955 return nullptr;
956}
957
Duncan P. N. Exon Smith1de3c7e2016-04-05 21:10:45 +0000958ConstantAggregate::ConstantAggregate(CompositeType *T, ValueTy VT,
959 ArrayRef<Constant *> V)
960 : Constant(T, VT, OperandTraits<ConstantAggregate>::op_end(this) - V.size(),
961 V.size()) {
Fangrui Song75709322018-11-17 01:44:25 +0000962 llvm::copy(V, op_begin());
Duncan P. N. Exon Smith1de3c7e2016-04-05 21:10:45 +0000963
964 // Check that types match, unless this is an opaque struct.
965 if (auto *ST = dyn_cast<StructType>(T))
966 if (ST->isOpaque())
967 return;
968 for (unsigned I = 0, E = V.size(); I != E; ++I)
969 assert(V[I]->getType() == T->getTypeAtIndex(I) &&
970 "Initializer for composite element doesn't match!");
971}
972
973ConstantArray::ConstantArray(ArrayType *T, ArrayRef<Constant *> V)
974 : ConstantAggregate(T, ConstantArrayVal, V) {
975 assert(V.size() == T->getNumElements() &&
976 "Invalid initializer for constant array");
Chris Lattner2f7c9632001-06-06 20:29:01 +0000977}
978
Chris Lattner229907c2011-07-18 04:54:35 +0000979Constant *ConstantArray::get(ArrayType *Ty, ArrayRef<Constant*> V) {
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +0000980 if (Constant *C = getImpl(Ty, V))
981 return C;
982 return Ty->getContext().pImpl->ArrayConstants.getOrCreate(Ty, V);
983}
Justin Bogner909e1c02015-12-01 20:20:49 +0000984
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +0000985Constant *ConstantArray::getImpl(ArrayType *Ty, ArrayRef<Constant*> V) {
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000986 // Empty arrays are canonicalized to ConstantAggregateZero.
987 if (V.empty())
988 return ConstantAggregateZero::get(Ty);
989
Jeffrey Yasskin8ce67f82009-09-30 21:08:08 +0000990 for (unsigned i = 0, e = V.size(); i != e; ++i) {
991 assert(V[i]->getType() == Ty->getElementType() &&
992 "Wrong type in array element initializer");
993 }
Galina Kistanovafc259902012-07-13 01:25:27 +0000994
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000995 // If this is an all-zero array, return a ConstantAggregateZero object. If
996 // all undef, return an UndefValue, if "all simple", then return a
997 // ConstantDataArray.
998 Constant *C = V[0];
999 if (isa<UndefValue>(C) && rangeOnlyContains(V.begin(), V.end(), C))
1000 return UndefValue::get(Ty);
Chris Lattnerf14a67f2012-01-26 02:31:22 +00001001
Chris Lattnercf9e8f62012-02-05 02:29:43 +00001002 if (C->isNullValue() && rangeOnlyContains(V.begin(), V.end(), C))
1003 return ConstantAggregateZero::get(Ty);
1004
1005 // Check to see if all of the elements are ConstantFP or ConstantInt and if
1006 // the element type is compatible with ConstantDataVector. If so, use it.
Justin Bogner909e1c02015-12-01 20:20:49 +00001007 if (ConstantDataSequential::isElementTypeCompatible(C->getType()))
1008 return getSequenceIfElementsMatch<ConstantDataArray>(C, V);
Chris Lattnerf14a67f2012-01-26 02:31:22 +00001009
Chris Lattnercf9e8f62012-02-05 02:29:43 +00001010 // Otherwise, we really do want to create a ConstantArray.
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001011 return nullptr;
Owen Andersonc2c79322009-07-28 18:32:17 +00001012}
1013
Chris Lattnercc19efa2011-06-20 04:01:31 +00001014StructType *ConstantStruct::getTypeForElements(LLVMContext &Context,
1015 ArrayRef<Constant*> V,
1016 bool Packed) {
Bill Wendling3ae7dd32012-02-07 01:27:51 +00001017 unsigned VecSize = V.size();
1018 SmallVector<Type*, 16> EltTypes(VecSize);
1019 for (unsigned i = 0; i != VecSize; ++i)
1020 EltTypes[i] = V[i]->getType();
Galina Kistanovafc259902012-07-13 01:25:27 +00001021
Chris Lattnercc19efa2011-06-20 04:01:31 +00001022 return StructType::get(Context, EltTypes, Packed);
1023}
1024
1025
1026StructType *ConstantStruct::getTypeForElements(ArrayRef<Constant*> V,
1027 bool Packed) {
1028 assert(!V.empty() &&
1029 "ConstantStruct::getTypeForElements cannot be called on empty list");
1030 return getTypeForElements(V[0]->getContext(), V, Packed);
1031}
1032
Jay Foad89d9b812011-07-25 10:14:44 +00001033ConstantStruct::ConstantStruct(StructType *T, ArrayRef<Constant *> V)
Duncan P. N. Exon Smith1de3c7e2016-04-05 21:10:45 +00001034 : ConstantAggregate(T, ConstantStructVal, V) {
1035 assert((T->isOpaque() || V.size() == T->getNumElements()) &&
1036 "Invalid initializer for constant struct");
Chris Lattner2f7c9632001-06-06 20:29:01 +00001037}
1038
Owen Anderson45308b52009-07-27 22:29:26 +00001039// ConstantStruct accessors.
Chris Lattner229907c2011-07-18 04:54:35 +00001040Constant *ConstantStruct::get(StructType *ST, ArrayRef<Constant*> V) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001041 assert((ST->isOpaque() || ST->getNumElements() == V.size()) &&
1042 "Incorrect # elements specified to ConstantStruct::get");
Chris Lattnerf14a67f2012-01-26 02:31:22 +00001043
1044 // Create a ConstantAggregateZero value if all elements are zeros.
1045 bool isZero = true;
1046 bool isUndef = false;
Bjorn Petterssonaa025802018-07-03 12:39:52 +00001047
Chris Lattnerf14a67f2012-01-26 02:31:22 +00001048 if (!V.empty()) {
1049 isUndef = isa<UndefValue>(V[0]);
1050 isZero = V[0]->isNullValue();
1051 if (isUndef || isZero) {
1052 for (unsigned i = 0, e = V.size(); i != e; ++i) {
1053 if (!V[i]->isNullValue())
1054 isZero = false;
1055 if (!isa<UndefValue>(V[i]))
1056 isUndef = false;
1057 }
1058 }
Galina Kistanovafc259902012-07-13 01:25:27 +00001059 }
Chris Lattnerf14a67f2012-01-26 02:31:22 +00001060 if (isZero)
1061 return ConstantAggregateZero::get(ST);
1062 if (isUndef)
1063 return UndefValue::get(ST);
Galina Kistanovafc259902012-07-13 01:25:27 +00001064
Chris Lattnerf14a67f2012-01-26 02:31:22 +00001065 return ST->getContext().pImpl->StructConstants.getOrCreate(ST, V);
Owen Anderson45308b52009-07-27 22:29:26 +00001066}
1067
Jay Foad89d9b812011-07-25 10:14:44 +00001068ConstantVector::ConstantVector(VectorType *T, ArrayRef<Constant *> V)
Duncan P. N. Exon Smith1de3c7e2016-04-05 21:10:45 +00001069 : ConstantAggregate(T, ConstantVectorVal, V) {
Duncan P. N. Exon Smithdb63bda2016-04-05 20:53:47 +00001070 assert(V.size() == T->getNumElements() &&
Duncan P. N. Exon Smith1de3c7e2016-04-05 21:10:45 +00001071 "Invalid initializer for constant vector");
Brian Gaeke02209042004-08-20 06:00:58 +00001072}
1073
Owen Anderson4aa32952009-07-28 21:19:26 +00001074// ConstantVector accessors.
Jay Foadb8a8bed32011-06-22 09:10:19 +00001075Constant *ConstantVector::get(ArrayRef<Constant*> V) {
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001076 if (Constant *C = getImpl(V))
1077 return C;
1078 VectorType *Ty = VectorType::get(V.front()->getType(), V.size());
1079 return Ty->getContext().pImpl->VectorConstants.getOrCreate(Ty, V);
1080}
Justin Bogner909e1c02015-12-01 20:20:49 +00001081
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001082Constant *ConstantVector::getImpl(ArrayRef<Constant*> V) {
Jay Foad9f32cfd2011-01-27 14:44:55 +00001083 assert(!V.empty() && "Vectors can't be empty");
Chris Lattner229907c2011-07-18 04:54:35 +00001084 VectorType *T = VectorType::get(V.front()->getType(), V.size());
Jay Foad9f32cfd2011-01-27 14:44:55 +00001085
Chris Lattner69229312011-02-15 00:14:00 +00001086 // If this is an all-undef or all-zero vector, return a
Owen Anderson4aa32952009-07-28 21:19:26 +00001087 // ConstantAggregateZero or UndefValue.
1088 Constant *C = V[0];
1089 bool isZero = C->isNullValue();
1090 bool isUndef = isa<UndefValue>(C);
1091
1092 if (isZero || isUndef) {
1093 for (unsigned i = 1, e = V.size(); i != e; ++i)
1094 if (V[i] != C) {
1095 isZero = isUndef = false;
1096 break;
1097 }
1098 }
Galina Kistanovafc259902012-07-13 01:25:27 +00001099
Owen Anderson4aa32952009-07-28 21:19:26 +00001100 if (isZero)
Owen Andersonb292b8c2009-07-30 23:03:37 +00001101 return ConstantAggregateZero::get(T);
Owen Anderson4aa32952009-07-28 21:19:26 +00001102 if (isUndef)
Owen Andersonb292b8c2009-07-30 23:03:37 +00001103 return UndefValue::get(T);
Galina Kistanovafc259902012-07-13 01:25:27 +00001104
Chris Lattner978fe0c2012-01-30 06:21:21 +00001105 // Check to see if all of the elements are ConstantFP or ConstantInt and if
1106 // the element type is compatible with ConstantDataVector. If so, use it.
Justin Bogner909e1c02015-12-01 20:20:49 +00001107 if (ConstantDataSequential::isElementTypeCompatible(C->getType()))
1108 return getSequenceIfElementsMatch<ConstantDataVector>(C, V);
Galina Kistanovafc259902012-07-13 01:25:27 +00001109
Chris Lattner978fe0c2012-01-30 06:21:21 +00001110 // Otherwise, the element type isn't compatible with ConstantDataVector, or
Craig Topperdf907262017-04-11 06:41:55 +00001111 // the operand list contains a ConstantExpr or something else strange.
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001112 return nullptr;
Owen Anderson4aa32952009-07-28 21:19:26 +00001113}
1114
Chris Lattnere9eed292012-01-25 05:19:54 +00001115Constant *ConstantVector::getSplat(unsigned NumElts, Constant *V) {
Chris Lattner978fe0c2012-01-30 06:21:21 +00001116 // If this splat is compatible with ConstantDataVector, use it instead of
1117 // ConstantVector.
1118 if ((isa<ConstantFP>(V) || isa<ConstantInt>(V)) &&
1119 ConstantDataSequential::isElementTypeCompatible(V->getType()))
1120 return ConstantDataVector::getSplat(NumElts, V);
Galina Kistanovafc259902012-07-13 01:25:27 +00001121
Chris Lattnere9eed292012-01-25 05:19:54 +00001122 SmallVector<Constant*, 32> Elts(NumElts, V);
1123 return get(Elts);
1124}
1125
David Majnemerf0f224d2015-11-11 21:57:16 +00001126ConstantTokenNone *ConstantTokenNone::get(LLVMContext &Context) {
1127 LLVMContextImpl *pImpl = Context.pImpl;
1128 if (!pImpl->TheNoneToken)
David Majnemer2dd41c52015-11-16 20:55:57 +00001129 pImpl->TheNoneToken.reset(new ConstantTokenNone(Context));
1130 return pImpl->TheNoneToken.get();
David Majnemerf0f224d2015-11-11 21:57:16 +00001131}
1132
1133/// Remove the constant from the constant table.
1134void ConstantTokenNone::destroyConstantImpl() {
1135 llvm_unreachable("You can't ConstantTokenNone->destroyConstantImpl()!");
1136}
Chris Lattnere9eed292012-01-25 05:19:54 +00001137
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001138// Utility function for determining if a ConstantExpr is a CastOp or not. This
1139// can't be inline because we don't want to #include Instruction.h into
1140// Constant.h
1141bool ConstantExpr::isCast() const {
1142 return Instruction::isCast(getOpcode());
1143}
1144
Reid Spenceree3c9912006-12-04 05:19:50 +00001145bool ConstantExpr::isCompare() const {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00001146 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
Reid Spenceree3c9912006-12-04 05:19:50 +00001147}
1148
Dan Gohman7190d482009-09-10 23:37:55 +00001149bool ConstantExpr::isGEPWithNoNotionalOverIndexing() const {
1150 if (getOpcode() != Instruction::GetElementPtr) return false;
1151
1152 gep_type_iterator GEPI = gep_type_begin(this), E = gep_type_end(this);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001153 User::const_op_iterator OI = std::next(this->op_begin());
Dan Gohman7190d482009-09-10 23:37:55 +00001154
Sanjay Patel81ed3492016-12-11 20:07:02 +00001155 // The remaining indices may be compile-time known integers within the bounds
1156 // of the corresponding notional static array types.
Dan Gohman7190d482009-09-10 23:37:55 +00001157 for (; GEPI != E; ++GEPI, ++OI) {
Sanjay Patel81ed3492016-12-11 20:07:02 +00001158 if (isa<UndefValue>(*OI))
1159 continue;
1160 auto *CI = dyn_cast<ConstantInt>(*OI);
1161 if (!CI || (GEPI.isBoundedSequential() &&
1162 (CI->getValue().getActiveBits() > 64 ||
1163 CI->getZExtValue() >= GEPI.getSequentialNumElements())))
Peter Collingbourneab85225b2016-12-02 02:24:42 +00001164 return false;
Dan Gohman7190d482009-09-10 23:37:55 +00001165 }
1166
1167 // All the indices checked out.
1168 return true;
1169}
1170
Dan Gohman1ecaf452008-05-31 00:58:22 +00001171bool ConstantExpr::hasIndices() const {
1172 return getOpcode() == Instruction::ExtractValue ||
1173 getOpcode() == Instruction::InsertValue;
1174}
1175
Jay Foad0091fe82011-04-13 15:22:40 +00001176ArrayRef<unsigned> ConstantExpr::getIndices() const {
Dan Gohman1ecaf452008-05-31 00:58:22 +00001177 if (const ExtractValueConstantExpr *EVCE =
1178 dyn_cast<ExtractValueConstantExpr>(this))
1179 return EVCE->Indices;
Dan Gohmana469bdb2008-06-23 16:39:44 +00001180
1181 return cast<InsertValueConstantExpr>(this)->Indices;
Dan Gohman1ecaf452008-05-31 00:58:22 +00001182}
1183
Reid Spencer10fbf0e2006-12-03 05:48:19 +00001184unsigned ConstantExpr::getPredicate() const {
Craig Toppercc03b492015-12-15 06:11:36 +00001185 return cast<CompareConstantExpr>(this)->predicate;
Reid Spencer10fbf0e2006-12-03 05:48:19 +00001186}
Chris Lattner60e0dd72001-10-03 06:12:09 +00001187
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001188Constant *
1189ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
Chris Lattner7c1018a2006-07-14 19:37:40 +00001190 assert(Op->getType() == getOperand(OpNo)->getType() &&
1191 "Replacing operand with value of different type!");
Chris Lattner227816342006-07-14 22:20:01 +00001192 if (getOperand(OpNo) == Op)
1193 return const_cast<ConstantExpr*>(this);
Chris Lattner37e38352012-01-26 20:37:11 +00001194
1195 SmallVector<Constant*, 8> NewOps;
1196 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1197 NewOps.push_back(i == OpNo ? Op : getOperand(i));
Galina Kistanovafc259902012-07-13 01:25:27 +00001198
Chris Lattner37e38352012-01-26 20:37:11 +00001199 return getWithOperands(NewOps);
Chris Lattner227816342006-07-14 22:20:01 +00001200}
1201
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001202Constant *ConstantExpr::getWithOperands(ArrayRef<Constant *> Ops, Type *Ty,
David Blaikie88208842015-08-21 20:16:51 +00001203 bool OnlyIfReduced, Type *SrcTy) const {
Jay Foad5c984e562011-04-13 13:46:01 +00001204 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
Galina Kistanovafc259902012-07-13 01:25:27 +00001205
Benjamin Kramer8008e9f2015-03-02 11:57:04 +00001206 // If no operands changed return self.
1207 if (Ty == getType() && std::equal(Ops.begin(), Ops.end(), op_begin()))
Chris Lattner227816342006-07-14 22:20:01 +00001208 return const_cast<ConstantExpr*>(this);
1209
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001210 Type *OnlyIfReducedTy = OnlyIfReduced ? Ty : nullptr;
Chris Lattner227816342006-07-14 22:20:01 +00001211 switch (getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001212 case Instruction::Trunc:
1213 case Instruction::ZExt:
1214 case Instruction::SExt:
1215 case Instruction::FPTrunc:
1216 case Instruction::FPExt:
1217 case Instruction::UIToFP:
1218 case Instruction::SIToFP:
1219 case Instruction::FPToUI:
1220 case Instruction::FPToSI:
1221 case Instruction::PtrToInt:
1222 case Instruction::IntToPtr:
1223 case Instruction::BitCast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00001224 case Instruction::AddrSpaceCast:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001225 return ConstantExpr::getCast(getOpcode(), Ops[0], Ty, OnlyIfReduced);
Chris Lattner227816342006-07-14 22:20:01 +00001226 case Instruction::Select:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001227 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2], OnlyIfReducedTy);
Chris Lattner227816342006-07-14 22:20:01 +00001228 case Instruction::InsertElement:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001229 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2],
1230 OnlyIfReducedTy);
Chris Lattner227816342006-07-14 22:20:01 +00001231 case Instruction::ExtractElement:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001232 return ConstantExpr::getExtractElement(Ops[0], Ops[1], OnlyIfReducedTy);
Chris Lattner37e38352012-01-26 20:37:11 +00001233 case Instruction::InsertValue:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001234 return ConstantExpr::getInsertValue(Ops[0], Ops[1], getIndices(),
1235 OnlyIfReducedTy);
Chris Lattner37e38352012-01-26 20:37:11 +00001236 case Instruction::ExtractValue:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001237 return ConstantExpr::getExtractValue(Ops[0], getIndices(), OnlyIfReducedTy);
Chris Lattner227816342006-07-14 22:20:01 +00001238 case Instruction::ShuffleVector:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001239 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2],
1240 OnlyIfReducedTy);
David Blaikie88208842015-08-21 20:16:51 +00001241 case Instruction::GetElementPtr: {
1242 auto *GEPO = cast<GEPOperator>(this);
1243 assert(SrcTy || (Ops[0]->getType() == getOperand(0)->getType()));
1244 return ConstantExpr::getGetElementPtr(
1245 SrcTy ? SrcTy : GEPO->getSourceElementType(), Ops[0], Ops.slice(1),
Peter Collingbourned93620b2016-11-10 22:34:55 +00001246 GEPO->isInBounds(), GEPO->getInRangeIndex(), OnlyIfReducedTy);
David Blaikie88208842015-08-21 20:16:51 +00001247 }
Reid Spencer266e42b2006-12-23 06:05:41 +00001248 case Instruction::ICmp:
1249 case Instruction::FCmp:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001250 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1],
1251 OnlyIfReducedTy);
Chris Lattner227816342006-07-14 22:20:01 +00001252 default:
1253 assert(getNumOperands() == 2 && "Must be binary operator?");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001254 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1], SubclassOptionalData,
1255 OnlyIfReducedTy);
Chris Lattner7c1018a2006-07-14 19:37:40 +00001256 }
1257}
1258
Chris Lattner2f7c9632001-06-06 20:29:01 +00001259
1260//===----------------------------------------------------------------------===//
Chris Lattner2f7c9632001-06-06 20:29:01 +00001261// isValueValidForType implementations
1262
Chris Lattner229907c2011-07-18 04:54:35 +00001263bool ConstantInt::isValueValidForType(Type *Ty, uint64_t Val) {
Chris Lattner8326bd82012-01-26 00:42:34 +00001264 unsigned NumBits = Ty->getIntegerBitWidth(); // assert okay
1265 if (Ty->isIntegerTy(1))
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001266 return Val == 0 || Val == 1;
Craig Topper50b1e512017-06-07 00:58:05 +00001267 return isUIntN(NumBits, Val);
Reid Spencere7334722006-12-19 01:28:19 +00001268}
1269
Chris Lattner229907c2011-07-18 04:54:35 +00001270bool ConstantInt::isValueValidForType(Type *Ty, int64_t Val) {
Chris Lattner8326bd82012-01-26 00:42:34 +00001271 unsigned NumBits = Ty->getIntegerBitWidth();
1272 if (Ty->isIntegerTy(1))
Reid Spencera94d3942007-01-19 21:13:56 +00001273 return Val == 0 || Val == 1 || Val == -1;
Craig Topper50b1e512017-06-07 00:58:05 +00001274 return isIntN(NumBits, Val);
Chris Lattner2f7c9632001-06-06 20:29:01 +00001275}
1276
Chris Lattner229907c2011-07-18 04:54:35 +00001277bool ConstantFP::isValueValidForType(Type *Ty, const APFloat& Val) {
Dale Johannesend246b2c2007-08-30 00:23:21 +00001278 // convert modifies in place, so make a copy.
1279 APFloat Val2 = APFloat(Val);
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001280 bool losesInfo;
Chris Lattner6b727592004-06-17 18:19:28 +00001281 switch (Ty->getTypeID()) {
Chris Lattner2f7c9632001-06-06 20:29:01 +00001282 default:
1283 return false; // These can't be represented as floating point!
1284
Dale Johannesend246b2c2007-08-30 00:23:21 +00001285 // FIXME rounding mode needs to be more flexible
Dan Gohman518cda42011-12-17 00:04:22 +00001286 case Type::HalfTyID: {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001287 if (&Val2.getSemantics() == &APFloat::IEEEhalf())
Dan Gohman518cda42011-12-17 00:04:22 +00001288 return true;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001289 Val2.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven, &losesInfo);
Dan Gohman518cda42011-12-17 00:04:22 +00001290 return !losesInfo;
1291 }
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001292 case Type::FloatTyID: {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001293 if (&Val2.getSemantics() == &APFloat::IEEEsingle())
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001294 return true;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001295 Val2.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, &losesInfo);
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001296 return !losesInfo;
1297 }
1298 case Type::DoubleTyID: {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001299 if (&Val2.getSemantics() == &APFloat::IEEEhalf() ||
1300 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1301 &Val2.getSemantics() == &APFloat::IEEEdouble())
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001302 return true;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001303 Val2.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, &losesInfo);
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001304 return !losesInfo;
1305 }
Dale Johannesenbdad8092007-08-09 22:51:36 +00001306 case Type::X86_FP80TyID:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001307 return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
Bjorn Petterssonaa025802018-07-03 12:39:52 +00001308 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001309 &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1310 &Val2.getSemantics() == &APFloat::x87DoubleExtended();
Dale Johannesenbdad8092007-08-09 22:51:36 +00001311 case Type::FP128TyID:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001312 return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
Bjorn Petterssonaa025802018-07-03 12:39:52 +00001313 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001314 &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1315 &Val2.getSemantics() == &APFloat::IEEEquad();
Dale Johannesen007aa372007-10-11 18:07:22 +00001316 case Type::PPC_FP128TyID:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001317 return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
Bjorn Petterssonaa025802018-07-03 12:39:52 +00001318 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001319 &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1320 &Val2.getSemantics() == &APFloat::PPCDoubleDouble();
Chris Lattner2f7c9632001-06-06 20:29:01 +00001321 }
Chris Lattneraa2372562006-05-24 17:04:05 +00001322}
Chris Lattner9655e542001-07-20 19:16:02 +00001323
Chris Lattner030af792012-01-24 05:42:11 +00001324
Chris Lattner49d855c2001-09-07 16:46:31 +00001325//===----------------------------------------------------------------------===//
Chris Lattner49d855c2001-09-07 16:46:31 +00001326// Factory Function Implementation
1327
Chris Lattnerc7f9fd42012-01-23 15:20:12 +00001328ConstantAggregateZero *ConstantAggregateZero::get(Type *Ty) {
Chris Lattner13ee7952010-08-28 04:09:24 +00001329 assert((Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()) &&
Owen Andersonb292b8c2009-07-30 23:03:37 +00001330 "Cannot create an aggregate zero of non-aggregate type!");
David Blaikie899b85a2014-11-25 02:13:54 +00001331
Justin Lebar611c5c22016-10-10 16:26:13 +00001332 std::unique_ptr<ConstantAggregateZero> &Entry =
1333 Ty->getContext().pImpl->CAZConstants[Ty];
1334 if (!Entry)
1335 Entry.reset(new ConstantAggregateZero(Ty));
1336
1337 return Entry.get();
Owen Andersonb292b8c2009-07-30 23:03:37 +00001338}
1339
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00001340/// Remove the constant from the constant table.
Pete Cooper86dd4cf2015-06-23 21:55:11 +00001341void ConstantAggregateZero::destroyConstantImpl() {
Chris Lattnerc7f9fd42012-01-23 15:20:12 +00001342 getContext().pImpl->CAZConstants.erase(getType());
Chris Lattner9fba3da2004-02-15 05:53:04 +00001343}
1344
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00001345/// Remove the constant from the constant table.
Pete Cooper86dd4cf2015-06-23 21:55:11 +00001346void ConstantArray::destroyConstantImpl() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001347 getType()->getContext().pImpl->ArrayConstants.remove(this);
Chris Lattner98fa07b2003-05-23 20:03:32 +00001348}
1349
Chris Lattner81fabb02002-08-26 17:53:56 +00001350
Chris Lattner3462ae32001-12-03 22:26:30 +00001351//---- ConstantStruct::get() implementation...
Chris Lattner49d855c2001-09-07 16:46:31 +00001352//
Chris Lattnerb50d1352003-10-05 00:17:43 +00001353
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00001354/// Remove the constant from the constant table.
Pete Cooper86dd4cf2015-06-23 21:55:11 +00001355void ConstantStruct::destroyConstantImpl() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001356 getType()->getContext().pImpl->StructConstants.remove(this);
Chris Lattnerd7a73302001-10-13 06:57:33 +00001357}
Chris Lattner883ad0b2001-10-03 15:39:36 +00001358
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00001359/// Remove the constant from the constant table.
Pete Cooper86dd4cf2015-06-23 21:55:11 +00001360void ConstantVector::destroyConstantImpl() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001361 getType()->getContext().pImpl->VectorConstants.remove(this);
Brian Gaeke02209042004-08-20 06:00:58 +00001362}
1363
Duncan Sandse6beec62012-11-13 12:59:33 +00001364Constant *Constant::getSplatValue() const {
1365 assert(this->getType()->isVectorTy() && "Only valid for vectors!");
1366 if (isa<ConstantAggregateZero>(this))
1367 return getNullValue(this->getType()->getVectorElementType());
1368 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
1369 return CV->getSplatValue();
1370 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
1371 return CV->getSplatValue();
Craig Topperc6207612014-04-09 06:08:46 +00001372 return nullptr;
Duncan Sandse6beec62012-11-13 12:59:33 +00001373}
1374
Duncan Sandscf0ff032011-02-01 08:39:12 +00001375Constant *ConstantVector::getSplatValue() const {
Dan Gohman07159202007-10-17 17:51:30 +00001376 // Check out first element.
1377 Constant *Elt = getOperand(0);
1378 // Then make sure all remaining elements point to the same value.
1379 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
Chris Lattnerd04e32d2011-07-17 06:01:30 +00001380 if (getOperand(I) != Elt)
Craig Topperc6207612014-04-09 06:08:46 +00001381 return nullptr;
Dan Gohman07159202007-10-17 17:51:30 +00001382 return Elt;
1383}
1384
Duncan Sandse6beec62012-11-13 12:59:33 +00001385const APInt &Constant::getUniqueInteger() const {
1386 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
1387 return CI->getValue();
1388 assert(this->getSplatValue() && "Doesn't contain a unique integer!");
1389 const Constant *C = this->getAggregateElement(0U);
1390 assert(C && isa<ConstantInt>(C) && "Not a vector of numbers!");
1391 return cast<ConstantInt>(C)->getValue();
1392}
1393
Chris Lattner31b132c2009-10-28 00:01:44 +00001394//---- ConstantPointerNull::get() implementation.
Chris Lattnerd7a73302001-10-13 06:57:33 +00001395//
Chris Lattner98fa07b2003-05-23 20:03:32 +00001396
Chris Lattner229907c2011-07-18 04:54:35 +00001397ConstantPointerNull *ConstantPointerNull::get(PointerType *Ty) {
Justin Lebar611c5c22016-10-10 16:26:13 +00001398 std::unique_ptr<ConstantPointerNull> &Entry =
1399 Ty->getContext().pImpl->CPNConstants[Ty];
Craig Topperc6207612014-04-09 06:08:46 +00001400 if (!Entry)
Justin Lebar611c5c22016-10-10 16:26:13 +00001401 Entry.reset(new ConstantPointerNull(Ty));
Galina Kistanovafc259902012-07-13 01:25:27 +00001402
Justin Lebar611c5c22016-10-10 16:26:13 +00001403 return Entry.get();
Chris Lattner883ad0b2001-10-03 15:39:36 +00001404}
1405
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00001406/// Remove the constant from the constant table.
Pete Cooper86dd4cf2015-06-23 21:55:11 +00001407void ConstantPointerNull::destroyConstantImpl() {
Chris Lattnerc7f9fd42012-01-23 15:20:12 +00001408 getContext().pImpl->CPNConstants.erase(getType());
Chris Lattner0c6e0b92002-08-18 00:40:04 +00001409}
1410
Chris Lattner229907c2011-07-18 04:54:35 +00001411UndefValue *UndefValue::get(Type *Ty) {
Justin Lebar611c5c22016-10-10 16:26:13 +00001412 std::unique_ptr<UndefValue> &Entry = Ty->getContext().pImpl->UVConstants[Ty];
Craig Topperc6207612014-04-09 06:08:46 +00001413 if (!Entry)
Justin Lebar611c5c22016-10-10 16:26:13 +00001414 Entry.reset(new UndefValue(Ty));
Galina Kistanovafc259902012-07-13 01:25:27 +00001415
Justin Lebar611c5c22016-10-10 16:26:13 +00001416 return Entry.get();
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001417}
1418
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00001419/// Remove the constant from the constant table.
Pete Cooper86dd4cf2015-06-23 21:55:11 +00001420void UndefValue::destroyConstantImpl() {
Chris Lattnerc7f9fd42012-01-23 15:20:12 +00001421 // Free the constant and any dangling references to it.
1422 getContext().pImpl->UVConstants.erase(getType());
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001423}
1424
Chris Lattner31b132c2009-10-28 00:01:44 +00001425BlockAddress *BlockAddress::get(BasicBlock *BB) {
Craig Topper2617dcc2014-04-15 06:32:26 +00001426 assert(BB->getParent() && "Block must have a parent");
Chris Lattner31b132c2009-10-28 00:01:44 +00001427 return get(BB->getParent(), BB);
1428}
1429
1430BlockAddress *BlockAddress::get(Function *F, BasicBlock *BB) {
1431 BlockAddress *&BA =
1432 F->getContext().pImpl->BlockAddresses[std::make_pair(F, BB)];
Craig Topperc6207612014-04-09 06:08:46 +00001433 if (!BA)
Chris Lattner31b132c2009-10-28 00:01:44 +00001434 BA = new BlockAddress(F, BB);
Galina Kistanovafc259902012-07-13 01:25:27 +00001435
Chris Lattner31b132c2009-10-28 00:01:44 +00001436 assert(BA->getFunction() == F && "Basic block moved between functions");
1437 return BA;
1438}
1439
1440BlockAddress::BlockAddress(Function *F, BasicBlock *BB)
1441: Constant(Type::getInt8PtrTy(F->getContext()), Value::BlockAddressVal,
1442 &Op<0>(), 2) {
Chris Lattnerc559a9f2009-11-01 03:03:03 +00001443 setOperand(0, F);
1444 setOperand(1, BB);
Chris Lattneraa99c942009-11-01 01:27:45 +00001445 BB->AdjustBlockAddressRefCount(1);
Chris Lattner31b132c2009-10-28 00:01:44 +00001446}
1447
Chandler Carruth6a936922014-01-19 02:13:50 +00001448BlockAddress *BlockAddress::lookup(const BasicBlock *BB) {
1449 if (!BB->hasAddressTaken())
Craig Topperc6207612014-04-09 06:08:46 +00001450 return nullptr;
Chandler Carruth6a936922014-01-19 02:13:50 +00001451
1452 const Function *F = BB->getParent();
Craig Topper2617dcc2014-04-15 06:32:26 +00001453 assert(F && "Block must have a parent");
Chandler Carruth6a936922014-01-19 02:13:50 +00001454 BlockAddress *BA =
1455 F->getContext().pImpl->BlockAddresses.lookup(std::make_pair(F, BB));
1456 assert(BA && "Refcount and block address map disagree!");
1457 return BA;
1458}
Chris Lattner31b132c2009-10-28 00:01:44 +00001459
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00001460/// Remove the constant from the constant table.
Pete Cooper86dd4cf2015-06-23 21:55:11 +00001461void BlockAddress::destroyConstantImpl() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001462 getFunction()->getType()->getContext().pImpl
Chris Lattner31b132c2009-10-28 00:01:44 +00001463 ->BlockAddresses.erase(std::make_pair(getFunction(), getBasicBlock()));
Chris Lattneraa99c942009-11-01 01:27:45 +00001464 getBasicBlock()->AdjustBlockAddressRefCount(-1);
Chris Lattner31b132c2009-10-28 00:01:44 +00001465}
1466
Mehdi Amini8914d292016-02-10 22:47:15 +00001467Value *BlockAddress::handleOperandChangeImpl(Value *From, Value *To) {
Chris Lattner31b132c2009-10-28 00:01:44 +00001468 // This could be replacing either the Basic Block or the Function. In either
1469 // case, we have to remove the map entry.
1470 Function *NewF = getFunction();
1471 BasicBlock *NewBB = getBasicBlock();
Galina Kistanovafc259902012-07-13 01:25:27 +00001472
Mehdi Amini8914d292016-02-10 22:47:15 +00001473 if (From == NewF)
Derek Schuffec9dc012013-06-13 19:51:17 +00001474 NewF = cast<Function>(To->stripPointerCasts());
Mehdi Amini8914d292016-02-10 22:47:15 +00001475 else {
1476 assert(From == NewBB && "From does not match any operand");
Chris Lattner31b132c2009-10-28 00:01:44 +00001477 NewBB = cast<BasicBlock>(To);
Mehdi Amini8914d292016-02-10 22:47:15 +00001478 }
Galina Kistanovafc259902012-07-13 01:25:27 +00001479
Chris Lattner31b132c2009-10-28 00:01:44 +00001480 // See if the 'new' entry already exists, if not, just update this in place
1481 // and return early.
1482 BlockAddress *&NewBA =
1483 getContext().pImpl->BlockAddresses[std::make_pair(NewF, NewBB)];
Pete Cooper5815b1f2015-06-24 18:55:24 +00001484 if (NewBA)
1485 return NewBA;
Chris Lattner31b132c2009-10-28 00:01:44 +00001486
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001487 getBasicBlock()->AdjustBlockAddressRefCount(-1);
Galina Kistanovafc259902012-07-13 01:25:27 +00001488
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001489 // Remove the old entry, this can't cause the map to rehash (just a
1490 // tombstone will get added).
1491 getContext().pImpl->BlockAddresses.erase(std::make_pair(getFunction(),
1492 getBasicBlock()));
1493 NewBA = this;
1494 setOperand(0, NewF);
1495 setOperand(1, NewBB);
1496 getBasicBlock()->AdjustBlockAddressRefCount(1);
Pete Cooper5815b1f2015-06-24 18:55:24 +00001497
1498 // If we just want to keep the existing value, then return null.
1499 // Callers know that this means we shouldn't delete this value.
1500 return nullptr;
Chris Lattner31b132c2009-10-28 00:01:44 +00001501}
1502
1503//---- ConstantExpr::get() implementations.
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001504//
Reid Spencer8d9336d2006-12-31 05:26:44 +00001505
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001506/// This is a utility function to handle folding of casts and lookup of the
Duncan Sands7d6c8ae2008-03-30 19:38:55 +00001507/// cast in the ExprConstants map. It is used by the various get* methods below.
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001508static Constant *getFoldedCast(Instruction::CastOps opc, Constant *C, Type *Ty,
1509 bool OnlyIfReduced = false) {
Chris Lattner815ae2b2003-10-07 22:19:19 +00001510 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001511 // Fold a few common cases
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001512 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001513 return FC;
Chris Lattneracdbe712003-04-17 19:24:48 +00001514
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001515 if (OnlyIfReduced)
1516 return nullptr;
1517
Owen Anderson1584a292009-08-04 20:25:11 +00001518 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
1519
Nadav Rotem88330432013-03-07 01:30:40 +00001520 // Look up the constant in the table first to ensure uniqueness.
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001521 ConstantExprKeyType Key(opc, C);
Galina Kistanovafc259902012-07-13 01:25:27 +00001522
Owen Anderson1584a292009-08-04 20:25:11 +00001523 return pImpl->ExprConstants.getOrCreate(Ty, Key);
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001524}
Galina Kistanovafc259902012-07-13 01:25:27 +00001525
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001526Constant *ConstantExpr::getCast(unsigned oc, Constant *C, Type *Ty,
1527 bool OnlyIfReduced) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001528 Instruction::CastOps opc = Instruction::CastOps(oc);
1529 assert(Instruction::isCast(opc) && "opcode out of range");
1530 assert(C && Ty && "Null arguments to getCast");
Chris Lattner37bc78a2010-01-26 21:51:43 +00001531 assert(CastInst::castIsValid(opc, C, Ty) && "Invalid constantexpr cast!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001532
1533 switch (opc) {
Chris Lattner37bc78a2010-01-26 21:51:43 +00001534 default:
1535 llvm_unreachable("Invalid cast opcode");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001536 case Instruction::Trunc:
1537 return getTrunc(C, Ty, OnlyIfReduced);
1538 case Instruction::ZExt:
1539 return getZExt(C, Ty, OnlyIfReduced);
1540 case Instruction::SExt:
1541 return getSExt(C, Ty, OnlyIfReduced);
1542 case Instruction::FPTrunc:
1543 return getFPTrunc(C, Ty, OnlyIfReduced);
1544 case Instruction::FPExt:
1545 return getFPExtend(C, Ty, OnlyIfReduced);
1546 case Instruction::UIToFP:
1547 return getUIToFP(C, Ty, OnlyIfReduced);
1548 case Instruction::SIToFP:
1549 return getSIToFP(C, Ty, OnlyIfReduced);
1550 case Instruction::FPToUI:
1551 return getFPToUI(C, Ty, OnlyIfReduced);
1552 case Instruction::FPToSI:
1553 return getFPToSI(C, Ty, OnlyIfReduced);
1554 case Instruction::PtrToInt:
1555 return getPtrToInt(C, Ty, OnlyIfReduced);
1556 case Instruction::IntToPtr:
1557 return getIntToPtr(C, Ty, OnlyIfReduced);
1558 case Instruction::BitCast:
1559 return getBitCast(C, Ty, OnlyIfReduced);
1560 case Instruction::AddrSpaceCast:
1561 return getAddrSpaceCast(C, Ty, OnlyIfReduced);
Chris Lattner1ece6f82005-01-01 15:59:57 +00001562 }
Galina Kistanovafc259902012-07-13 01:25:27 +00001563}
Reid Spencerf37dc652006-12-05 19:14:13 +00001564
Chris Lattner229907c2011-07-18 04:54:35 +00001565Constant *ConstantExpr::getZExtOrBitCast(Constant *C, Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001566 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001567 return getBitCast(C, Ty);
1568 return getZExt(C, Ty);
Reid Spencer5c140882006-12-04 20:17:56 +00001569}
1570
Chris Lattner229907c2011-07-18 04:54:35 +00001571Constant *ConstantExpr::getSExtOrBitCast(Constant *C, Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001572 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001573 return getBitCast(C, Ty);
1574 return getSExt(C, Ty);
Reid Spencer5c140882006-12-04 20:17:56 +00001575}
1576
Chris Lattner229907c2011-07-18 04:54:35 +00001577Constant *ConstantExpr::getTruncOrBitCast(Constant *C, Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001578 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001579 return getBitCast(C, Ty);
1580 return getTrunc(C, Ty);
Reid Spencer5c140882006-12-04 20:17:56 +00001581}
1582
Chris Lattner229907c2011-07-18 04:54:35 +00001583Constant *ConstantExpr::getPointerCast(Constant *S, Type *Ty) {
Evgeniy Stepanov23382642013-01-16 14:41:46 +00001584 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
1585 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
1586 "Invalid cast");
Reid Spencerbc245a02006-12-05 03:25:26 +00001587
Evgeniy Stepanov23382642013-01-16 14:41:46 +00001588 if (Ty->isIntOrIntVectorTy())
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001589 return getPtrToInt(S, Ty);
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00001590
1591 unsigned SrcAS = S->getType()->getPointerAddressSpace();
1592 if (Ty->isPtrOrPtrVectorTy() && SrcAS != Ty->getPointerAddressSpace())
1593 return getAddrSpaceCast(S, Ty);
1594
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001595 return getBitCast(S, Ty);
Reid Spencerbc245a02006-12-05 03:25:26 +00001596}
1597
Matt Arsenault21f38f42013-12-07 02:58:41 +00001598Constant *ConstantExpr::getPointerBitCastOrAddrSpaceCast(Constant *S,
1599 Type *Ty) {
1600 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
1601 assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
1602
1603 if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
1604 return getAddrSpaceCast(S, Ty);
1605
1606 return getBitCast(S, Ty);
1607}
1608
Sanjay Patelf3587ec2016-05-18 22:05:28 +00001609Constant *ConstantExpr::getIntegerCast(Constant *C, Type *Ty, bool isSigned) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00001610 assert(C->getType()->isIntOrIntVectorTy() &&
1611 Ty->isIntOrIntVectorTy() && "Invalid cast");
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001612 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1613 unsigned DstBits = Ty->getScalarSizeInBits();
Reid Spencer56521c42006-12-12 00:51:07 +00001614 Instruction::CastOps opcode =
1615 (SrcBits == DstBits ? Instruction::BitCast :
1616 (SrcBits > DstBits ? Instruction::Trunc :
1617 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1618 return getCast(opcode, C, Ty);
1619}
1620
Chris Lattner229907c2011-07-18 04:54:35 +00001621Constant *ConstantExpr::getFPCast(Constant *C, Type *Ty) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00001622 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
Reid Spencer56521c42006-12-12 00:51:07 +00001623 "Invalid cast");
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001624 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1625 unsigned DstBits = Ty->getScalarSizeInBits();
Reid Spencerca104e82006-12-12 05:38:50 +00001626 if (SrcBits == DstBits)
1627 return C; // Avoid a useless cast
Reid Spencer56521c42006-12-12 00:51:07 +00001628 Instruction::CastOps opcode =
Jay Foad9f32cfd2011-01-27 14:44:55 +00001629 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
Reid Spencer56521c42006-12-12 00:51:07 +00001630 return getCast(opcode, C, Ty);
1631}
1632
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001633Constant *ConstantExpr::getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001634#ifndef NDEBUG
1635 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1636 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1637#endif
1638 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001639 assert(C->getType()->isIntOrIntVectorTy() && "Trunc operand must be integer");
1640 assert(Ty->isIntOrIntVectorTy() && "Trunc produces only integral");
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001641 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001642 "SrcTy must be larger than DestTy for Trunc!");
1643
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001644 return getFoldedCast(Instruction::Trunc, C, Ty, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001645}
1646
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001647Constant *ConstantExpr::getSExt(Constant *C, Type *Ty, bool OnlyIfReduced) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001648#ifndef NDEBUG
1649 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1650 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1651#endif
1652 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001653 assert(C->getType()->isIntOrIntVectorTy() && "SExt operand must be integral");
1654 assert(Ty->isIntOrIntVectorTy() && "SExt produces only integer");
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001655 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001656 "SrcTy must be smaller than DestTy for SExt!");
1657
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001658 return getFoldedCast(Instruction::SExt, C, Ty, OnlyIfReduced);
Chris Lattnerdd284742004-04-04 23:20:30 +00001659}
1660
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001661Constant *ConstantExpr::getZExt(Constant *C, Type *Ty, bool OnlyIfReduced) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001662#ifndef NDEBUG
1663 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1664 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1665#endif
1666 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001667 assert(C->getType()->isIntOrIntVectorTy() && "ZEXt operand must be integral");
1668 assert(Ty->isIntOrIntVectorTy() && "ZExt produces only integer");
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001669 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001670 "SrcTy must be smaller than DestTy for ZExt!");
1671
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001672 return getFoldedCast(Instruction::ZExt, C, Ty, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001673}
1674
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001675Constant *ConstantExpr::getFPTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001676#ifndef NDEBUG
1677 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1678 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1679#endif
1680 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001681 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001682 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001683 "This is an illegal floating point truncation!");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001684 return getFoldedCast(Instruction::FPTrunc, C, Ty, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001685}
1686
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001687Constant *ConstantExpr::getFPExtend(Constant *C, Type *Ty, bool OnlyIfReduced) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001688#ifndef NDEBUG
1689 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1690 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1691#endif
1692 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001693 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001694 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001695 "This is an illegal floating point extension!");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001696 return getFoldedCast(Instruction::FPExt, C, Ty, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001697}
1698
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001699Constant *ConstantExpr::getUIToFP(Constant *C, Type *Ty, bool OnlyIfReduced) {
Devang Pateld26344d2008-11-03 23:20:04 +00001700#ifndef NDEBUG
Nate Begemand4d45c22007-11-17 03:58:34 +00001701 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1702 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Pateld26344d2008-11-03 23:20:04 +00001703#endif
Nate Begemand4d45c22007-11-17 03:58:34 +00001704 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001705 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
Nate Begemand4d45c22007-11-17 03:58:34 +00001706 "This is an illegal uint to floating point cast!");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001707 return getFoldedCast(Instruction::UIToFP, C, Ty, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001708}
1709
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001710Constant *ConstantExpr::getSIToFP(Constant *C, Type *Ty, bool OnlyIfReduced) {
Devang Pateld26344d2008-11-03 23:20:04 +00001711#ifndef NDEBUG
Nate Begemand4d45c22007-11-17 03:58:34 +00001712 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1713 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Pateld26344d2008-11-03 23:20:04 +00001714#endif
Nate Begemand4d45c22007-11-17 03:58:34 +00001715 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001716 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001717 "This is an illegal sint to floating point cast!");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001718 return getFoldedCast(Instruction::SIToFP, C, Ty, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001719}
1720
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001721Constant *ConstantExpr::getFPToUI(Constant *C, Type *Ty, bool OnlyIfReduced) {
Devang Pateld26344d2008-11-03 23:20:04 +00001722#ifndef NDEBUG
Nate Begemand4d45c22007-11-17 03:58:34 +00001723 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1724 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Pateld26344d2008-11-03 23:20:04 +00001725#endif
Nate Begemand4d45c22007-11-17 03:58:34 +00001726 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001727 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
Nate Begemand4d45c22007-11-17 03:58:34 +00001728 "This is an illegal floating point to uint cast!");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001729 return getFoldedCast(Instruction::FPToUI, C, Ty, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001730}
1731
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001732Constant *ConstantExpr::getFPToSI(Constant *C, Type *Ty, bool OnlyIfReduced) {
Devang Pateld26344d2008-11-03 23:20:04 +00001733#ifndef NDEBUG
Nate Begemand4d45c22007-11-17 03:58:34 +00001734 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1735 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Pateld26344d2008-11-03 23:20:04 +00001736#endif
Nate Begemand4d45c22007-11-17 03:58:34 +00001737 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001738 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
Nate Begemand4d45c22007-11-17 03:58:34 +00001739 "This is an illegal floating point to sint cast!");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001740 return getFoldedCast(Instruction::FPToSI, C, Ty, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001741}
1742
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001743Constant *ConstantExpr::getPtrToInt(Constant *C, Type *DstTy,
1744 bool OnlyIfReduced) {
Craig Topper95d23472017-07-09 07:04:00 +00001745 assert(C->getType()->isPtrOrPtrVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00001746 "PtrToInt source must be pointer or pointer vector");
Craig Topper95d23472017-07-09 07:04:00 +00001747 assert(DstTy->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00001748 "PtrToInt destination must be integer or integer vector");
Chris Lattner8a3df542012-01-25 01:32:59 +00001749 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
Nick Lewyckyff509622012-01-25 03:20:12 +00001750 if (isa<VectorType>(C->getType()))
Chris Lattner8326bd82012-01-26 00:42:34 +00001751 assert(C->getType()->getVectorNumElements()==DstTy->getVectorNumElements()&&
Chris Lattner8a3df542012-01-25 01:32:59 +00001752 "Invalid cast between a different number of vector elements");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001753 return getFoldedCast(Instruction::PtrToInt, C, DstTy, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001754}
1755
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001756Constant *ConstantExpr::getIntToPtr(Constant *C, Type *DstTy,
1757 bool OnlyIfReduced) {
Craig Topper95d23472017-07-09 07:04:00 +00001758 assert(C->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00001759 "IntToPtr source must be integer or integer vector");
Craig Topper95d23472017-07-09 07:04:00 +00001760 assert(DstTy->isPtrOrPtrVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00001761 "IntToPtr destination must be a pointer or pointer vector");
Chris Lattner8a3df542012-01-25 01:32:59 +00001762 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
Nick Lewyckyff509622012-01-25 03:20:12 +00001763 if (isa<VectorType>(C->getType()))
Chris Lattner8326bd82012-01-26 00:42:34 +00001764 assert(C->getType()->getVectorNumElements()==DstTy->getVectorNumElements()&&
Chris Lattner8a3df542012-01-25 01:32:59 +00001765 "Invalid cast between a different number of vector elements");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001766 return getFoldedCast(Instruction::IntToPtr, C, DstTy, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001767}
1768
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001769Constant *ConstantExpr::getBitCast(Constant *C, Type *DstTy,
1770 bool OnlyIfReduced) {
Chris Lattner37bc78a2010-01-26 21:51:43 +00001771 assert(CastInst::castIsValid(Instruction::BitCast, C, DstTy) &&
1772 "Invalid constantexpr bitcast!");
Galina Kistanovafc259902012-07-13 01:25:27 +00001773
Chris Lattnercbeda872009-03-21 06:55:54 +00001774 // It is common to ask for a bitcast of a value to its own type, handle this
1775 // speedily.
1776 if (C->getType() == DstTy) return C;
Galina Kistanovafc259902012-07-13 01:25:27 +00001777
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001778 return getFoldedCast(Instruction::BitCast, C, DstTy, OnlyIfReduced);
Chris Lattnerdd284742004-04-04 23:20:30 +00001779}
1780
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001781Constant *ConstantExpr::getAddrSpaceCast(Constant *C, Type *DstTy,
1782 bool OnlyIfReduced) {
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00001783 assert(CastInst::castIsValid(Instruction::AddrSpaceCast, C, DstTy) &&
1784 "Invalid constantexpr addrspacecast!");
1785
Jingyue Wubaabe502014-06-15 21:40:57 +00001786 // Canonicalize addrspacecasts between different pointer types by first
1787 // bitcasting the pointer type and then converting the address space.
1788 PointerType *SrcScalarTy = cast<PointerType>(C->getType()->getScalarType());
1789 PointerType *DstScalarTy = cast<PointerType>(DstTy->getScalarType());
1790 Type *DstElemTy = DstScalarTy->getElementType();
1791 if (SrcScalarTy->getElementType() != DstElemTy) {
1792 Type *MidTy = PointerType::get(DstElemTy, SrcScalarTy->getAddressSpace());
1793 if (VectorType *VT = dyn_cast<VectorType>(DstTy)) {
1794 // Handle vectors of pointers.
1795 MidTy = VectorType::get(MidTy, VT->getNumElements());
1796 }
1797 C = getBitCast(C, MidTy);
1798 }
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001799 return getFoldedCast(Instruction::AddrSpaceCast, C, DstTy, OnlyIfReduced);
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00001800}
1801
Cameron McInallycbde0d92018-11-13 18:15:47 +00001802Constant *ConstantExpr::get(unsigned Opcode, Constant *C, unsigned Flags,
1803 Type *OnlyIfReducedTy) {
1804 // Check the operands for consistency first.
1805 assert(Instruction::isUnaryOp(Opcode) &&
1806 "Invalid opcode in unary constant expression");
1807
1808#ifndef NDEBUG
1809 switch (Opcode) {
1810 case Instruction::FNeg:
1811 assert(C->getType()->isFPOrFPVectorTy() &&
1812 "Tried to create a floating-point operation on a "
1813 "non-floating-point type!");
1814 break;
1815 default:
1816 break;
1817 }
1818#endif
1819
1820 // TODO: Try to constant fold operation.
1821
1822 if (OnlyIfReducedTy == C->getType())
1823 return nullptr;
1824
1825 Constant *ArgVec[] = { C };
1826 ConstantExprKeyType Key(Opcode, ArgVec, 0, Flags);
1827
1828 LLVMContextImpl *pImpl = C->getContext().pImpl;
1829 return pImpl->ExprConstants.getOrCreate(C->getType(), Key);
1830}
1831
Chris Lattner887ecac2011-07-09 18:23:52 +00001832Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2,
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001833 unsigned Flags, Type *OnlyIfReducedTy) {
Chris Lattner887ecac2011-07-09 18:23:52 +00001834 // Check the operands for consistency first.
Simon Pilgrime0a6eb12018-06-22 10:48:02 +00001835 assert(Instruction::isBinaryOp(Opcode) &&
Chris Lattner38a9bcd2003-05-21 17:49:25 +00001836 "Invalid opcode in binary constant expression");
1837 assert(C1->getType() == C2->getType() &&
1838 "Operand types in binary constant expression should match");
Galina Kistanovafc259902012-07-13 01:25:27 +00001839
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001840#ifndef NDEBUG
1841 switch (Opcode) {
Dan Gohmana5b96452009-06-04 22:49:04 +00001842 case Instruction::Add:
Reid Spencer7eb55b32006-11-02 01:53:59 +00001843 case Instruction::Sub:
Dan Gohmana5b96452009-06-04 22:49:04 +00001844 case Instruction::Mul:
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001845 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001846 assert(C1->getType()->isIntOrIntVectorTy() &&
Dan Gohmana5b96452009-06-04 22:49:04 +00001847 "Tried to create an integer operation on a non-integer type!");
1848 break;
1849 case Instruction::FAdd:
1850 case Instruction::FSub:
1851 case Instruction::FMul:
1852 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001853 assert(C1->getType()->isFPOrFPVectorTy() &&
Dan Gohmana5b96452009-06-04 22:49:04 +00001854 "Tried to create a floating-point operation on a "
1855 "non-floating-point type!");
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001856 break;
Bjorn Petterssonaa025802018-07-03 12:39:52 +00001857 case Instruction::UDiv:
1858 case Instruction::SDiv:
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001859 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001860 assert(C1->getType()->isIntOrIntVectorTy() &&
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001861 "Tried to create an arithmetic operation on a non-arithmetic type!");
1862 break;
1863 case Instruction::FDiv:
1864 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001865 assert(C1->getType()->isFPOrFPVectorTy() &&
Dan Gohman7889f2b2009-06-15 22:25:12 +00001866 "Tried to create an arithmetic operation on a non-arithmetic type!");
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001867 break;
Bjorn Petterssonaa025802018-07-03 12:39:52 +00001868 case Instruction::URem:
1869 case Instruction::SRem:
Reid Spencer7eb55b32006-11-02 01:53:59 +00001870 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001871 assert(C1->getType()->isIntOrIntVectorTy() &&
Reid Spencer7eb55b32006-11-02 01:53:59 +00001872 "Tried to create an arithmetic operation on a non-arithmetic type!");
1873 break;
1874 case Instruction::FRem:
1875 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001876 assert(C1->getType()->isFPOrFPVectorTy() &&
Dan Gohman7889f2b2009-06-15 22:25:12 +00001877 "Tried to create an arithmetic operation on a non-arithmetic type!");
Reid Spencer7eb55b32006-11-02 01:53:59 +00001878 break;
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001879 case Instruction::And:
1880 case Instruction::Or:
1881 case Instruction::Xor:
1882 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001883 assert(C1->getType()->isIntOrIntVectorTy() &&
Misha Brukman3852f652005-01-27 06:46:38 +00001884 "Tried to create a logical operation on a non-integral type!");
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001885 break;
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001886 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00001887 case Instruction::LShr:
1888 case Instruction::AShr:
Reid Spencer2341c222007-02-02 02:16:23 +00001889 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001890 assert(C1->getType()->isIntOrIntVectorTy() &&
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001891 "Tried to create a shift operation on a non-integer type!");
1892 break;
1893 default:
1894 break;
1895 }
1896#endif
1897
Chris Lattner887ecac2011-07-09 18:23:52 +00001898 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1899 return FC; // Fold a few common cases.
Galina Kistanovafc259902012-07-13 01:25:27 +00001900
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001901 if (OnlyIfReducedTy == C1->getType())
1902 return nullptr;
1903
Benjamin Kramer324322b2013-03-07 20:53:34 +00001904 Constant *ArgVec[] = { C1, C2 };
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001905 ConstantExprKeyType Key(Opcode, ArgVec, 0, Flags);
Galina Kistanovafc259902012-07-13 01:25:27 +00001906
Chris Lattner887ecac2011-07-09 18:23:52 +00001907 LLVMContextImpl *pImpl = C1->getContext().pImpl;
1908 return pImpl->ExprConstants.getOrCreate(C1->getType(), Key);
Reid Spencera009d0d2006-12-04 21:35:24 +00001909}
1910
Chris Lattner229907c2011-07-18 04:54:35 +00001911Constant *ConstantExpr::getSizeOf(Type* Ty) {
Owen Anderson487375e2009-07-29 18:55:55 +00001912 // sizeof is implemented as: (i64) gep (Ty*)null, 1
1913 // Note that a non-inbounds gep is used, as null isn't within any object.
Owen Anderson55f1c092009-08-13 21:58:54 +00001914 Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
Owen Anderson487375e2009-07-29 18:55:55 +00001915 Constant *GEP = getGetElementPtr(
David Blaikie4a2e73b2015-04-02 18:55:32 +00001916 Ty, Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
Bjorn Petterssonaa025802018-07-03 12:39:52 +00001917 return getPtrToInt(GEP,
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001918 Type::getInt64Ty(Ty->getContext()));
Owen Anderson487375e2009-07-29 18:55:55 +00001919}
1920
Chris Lattner229907c2011-07-18 04:54:35 +00001921Constant *ConstantExpr::getAlignOf(Type* Ty) {
Dan Gohmancf913832010-01-28 02:15:55 +00001922 // alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1
Dan Gohman50c09d02009-08-11 17:57:01 +00001923 // Note that a non-inbounds gep is used, as null isn't within any object.
Serge Gueltone38003f2017-05-09 19:31:13 +00001924 Type *AligningTy = StructType::get(Type::getInt1Ty(Ty->getContext()), Ty);
Matt Arsenaultbe558882014-04-23 20:58:57 +00001925 Constant *NullPtr = Constant::getNullValue(AligningTy->getPointerTo(0));
Dan Gohmana9be7392010-01-28 02:43:22 +00001926 Constant *Zero = ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0);
Owen Anderson55f1c092009-08-13 21:58:54 +00001927 Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
Owen Anderson487375e2009-07-29 18:55:55 +00001928 Constant *Indices[2] = { Zero, One };
David Blaikie4a2e73b2015-04-02 18:55:32 +00001929 Constant *GEP = getGetElementPtr(AligningTy, NullPtr, Indices);
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001930 return getPtrToInt(GEP,
1931 Type::getInt64Ty(Ty->getContext()));
Owen Anderson487375e2009-07-29 18:55:55 +00001932}
1933
Chris Lattner229907c2011-07-18 04:54:35 +00001934Constant *ConstantExpr::getOffsetOf(StructType* STy, unsigned FieldNo) {
Dan Gohmanede94e62010-02-01 16:37:38 +00001935 return getOffsetOf(STy, ConstantInt::get(Type::getInt32Ty(STy->getContext()),
1936 FieldNo));
1937}
1938
Chris Lattner229907c2011-07-18 04:54:35 +00001939Constant *ConstantExpr::getOffsetOf(Type* Ty, Constant *FieldNo) {
Dan Gohmanff3af7252009-08-16 21:26:11 +00001940 // offsetof is implemented as: (i64) gep (Ty*)null, 0, FieldNo
1941 // Note that a non-inbounds gep is used, as null isn't within any object.
1942 Constant *GEPIdx[] = {
Dan Gohmanede94e62010-02-01 16:37:38 +00001943 ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0),
1944 FieldNo
Dan Gohmanff3af7252009-08-16 21:26:11 +00001945 };
1946 Constant *GEP = getGetElementPtr(
David Blaikie4a2e73b2015-04-02 18:55:32 +00001947 Ty, Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001948 return getPtrToInt(GEP,
1949 Type::getInt64Ty(Ty->getContext()));
Dan Gohmanff3af7252009-08-16 21:26:11 +00001950}
Owen Anderson487375e2009-07-29 18:55:55 +00001951
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001952Constant *ConstantExpr::getCompare(unsigned short Predicate, Constant *C1,
1953 Constant *C2, bool OnlyIfReduced) {
Reid Spencera009d0d2006-12-04 21:35:24 +00001954 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Galina Kistanovafc259902012-07-13 01:25:27 +00001955
Chris Lattner887ecac2011-07-09 18:23:52 +00001956 switch (Predicate) {
1957 default: llvm_unreachable("Invalid CmpInst predicate");
1958 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
1959 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
1960 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
1961 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
1962 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
1963 case CmpInst::FCMP_TRUE:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001964 return getFCmp(Predicate, C1, C2, OnlyIfReduced);
Galina Kistanovafc259902012-07-13 01:25:27 +00001965
Chris Lattner887ecac2011-07-09 18:23:52 +00001966 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
1967 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
1968 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
1969 case CmpInst::ICMP_SLE:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001970 return getICmp(Predicate, C1, C2, OnlyIfReduced);
Chris Lattner887ecac2011-07-09 18:23:52 +00001971 }
Chris Lattner29ca2c62004-08-04 18:50:09 +00001972}
1973
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001974Constant *ConstantExpr::getSelect(Constant *C, Constant *V1, Constant *V2,
1975 Type *OnlyIfReducedTy) {
Chris Lattner41632132008-12-29 00:16:12 +00001976 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
Chris Lattner6e415c02004-03-12 05:54:04 +00001977
Chris Lattner887ecac2011-07-09 18:23:52 +00001978 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1979 return SC; // Fold common cases
Chris Lattner6e415c02004-03-12 05:54:04 +00001980
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001981 if (OnlyIfReducedTy == V1->getType())
1982 return nullptr;
1983
Benjamin Kramer324322b2013-03-07 20:53:34 +00001984 Constant *ArgVec[] = { C, V1, V2 };
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001985 ConstantExprKeyType Key(Instruction::Select, ArgVec);
Galina Kistanovafc259902012-07-13 01:25:27 +00001986
Chris Lattner887ecac2011-07-09 18:23:52 +00001987 LLVMContextImpl *pImpl = C->getContext().pImpl;
1988 return pImpl->ExprConstants.getOrCreate(V1->getType(), Key);
Chris Lattner6e415c02004-03-12 05:54:04 +00001989}
1990
David Blaikie4a2e73b2015-04-02 18:55:32 +00001991Constant *ConstantExpr::getGetElementPtr(Type *Ty, Constant *C,
1992 ArrayRef<Value *> Idxs, bool InBounds,
Peter Collingbourned93620b2016-11-10 22:34:55 +00001993 Optional<unsigned> InRangeIndex,
David Blaikie4a2e73b2015-04-02 18:55:32 +00001994 Type *OnlyIfReducedTy) {
David Blaikie4a2e73b2015-04-02 18:55:32 +00001995 if (!Ty)
1996 Ty = cast<PointerType>(C->getType()->getScalarType())->getElementType();
1997 else
David Blaikied9d900c2015-05-07 17:28:58 +00001998 assert(
1999 Ty ==
2000 cast<PointerType>(C->getType()->getScalarType())->getContainedType(0u));
2001
Peter Collingbourned93620b2016-11-10 22:34:55 +00002002 if (Constant *FC =
2003 ConstantFoldGetElementPtr(Ty, C, InBounds, InRangeIndex, Idxs))
David Blaikied9d900c2015-05-07 17:28:58 +00002004 return FC; // Fold a few common cases.
2005
Chris Lattner887ecac2011-07-09 18:23:52 +00002006 // Get the result type of the getelementptr!
David Blaikie4a2e73b2015-04-02 18:55:32 +00002007 Type *DestTy = GetElementPtrInst::getIndexedType(Ty, Idxs);
2008 assert(DestTy && "GEP indices invalid!");
Chris Lattner8326bd82012-01-26 00:42:34 +00002009 unsigned AS = C->getType()->getPointerAddressSpace();
David Blaikie4a2e73b2015-04-02 18:55:32 +00002010 Type *ReqTy = DestTy->getPointerTo(AS);
Elena Demikhovskyee004bc2016-05-15 12:30:25 +00002011
2012 unsigned NumVecElts = 0;
2013 if (C->getType()->isVectorTy())
2014 NumVecElts = C->getType()->getVectorNumElements();
2015 else for (auto Idx : Idxs)
2016 if (Idx->getType()->isVectorTy())
2017 NumVecElts = Idx->getType()->getVectorNumElements();
2018
2019 if (NumVecElts)
2020 ReqTy = VectorType::get(ReqTy, NumVecElts);
Galina Kistanovafc259902012-07-13 01:25:27 +00002021
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002022 if (OnlyIfReducedTy == ReqTy)
2023 return nullptr;
2024
Dan Gohman1b849082009-09-07 23:54:19 +00002025 // Look up the constant in the table first to ensure uniqueness
2026 std::vector<Constant*> ArgVec;
Jay Foaded8db7d2011-07-21 14:31:17 +00002027 ArgVec.reserve(1 + Idxs.size());
Dan Gohman1b849082009-09-07 23:54:19 +00002028 ArgVec.push_back(C);
Duncan Sandse6beec62012-11-13 12:59:33 +00002029 for (unsigned i = 0, e = Idxs.size(); i != e; ++i) {
Duncan Sandse6beec62012-11-13 12:59:33 +00002030 assert((!Idxs[i]->getType()->isVectorTy() ||
Elena Demikhovskyee004bc2016-05-15 12:30:25 +00002031 Idxs[i]->getType()->getVectorNumElements() == NumVecElts) &&
Duncan Sandse6beec62012-11-13 12:59:33 +00002032 "getelementptr index type missmatch");
Elena Demikhovskyee004bc2016-05-15 12:30:25 +00002033
2034 Constant *Idx = cast<Constant>(Idxs[i]);
2035 if (NumVecElts && !Idxs[i]->getType()->isVectorTy())
2036 Idx = ConstantVector::getSplat(NumVecElts, Idx);
2037 ArgVec.push_back(Idx);
Duncan Sandse6beec62012-11-13 12:59:33 +00002038 }
Peter Collingbourned93620b2016-11-10 22:34:55 +00002039
2040 unsigned SubClassOptionalData = InBounds ? GEPOperator::IsInBounds : 0;
2041 if (InRangeIndex && *InRangeIndex < 63)
2042 SubClassOptionalData |= (*InRangeIndex + 1) << 1;
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002043 const ConstantExprKeyType Key(Instruction::GetElementPtr, ArgVec, 0,
Peter Collingbourned93620b2016-11-10 22:34:55 +00002044 SubClassOptionalData, None, Ty);
Galina Kistanovafc259902012-07-13 01:25:27 +00002045
Chris Lattner887ecac2011-07-09 18:23:52 +00002046 LLVMContextImpl *pImpl = C->getContext().pImpl;
Dan Gohman1b849082009-09-07 23:54:19 +00002047 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2048}
2049
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002050Constant *ConstantExpr::getICmp(unsigned short pred, Constant *LHS,
2051 Constant *RHS, bool OnlyIfReduced) {
Reid Spenceree3c9912006-12-04 05:19:50 +00002052 assert(LHS->getType() == RHS->getType());
Craig Topper45844762017-07-05 23:35:46 +00002053 assert(CmpInst::isIntPredicate((CmpInst::Predicate)pred) &&
2054 "Invalid ICmp Predicate");
Reid Spenceree3c9912006-12-04 05:19:50 +00002055
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00002056 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
Reid Spenceree3c9912006-12-04 05:19:50 +00002057 return FC; // Fold a few common cases...
2058
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002059 if (OnlyIfReduced)
2060 return nullptr;
2061
Reid Spenceree3c9912006-12-04 05:19:50 +00002062 // Look up the constant in the table first to ensure uniqueness
Benjamin Kramer324322b2013-03-07 20:53:34 +00002063 Constant *ArgVec[] = { LHS, RHS };
Reid Spencerb1537492006-12-24 18:42:29 +00002064 // Get the key type with both the opcode and predicate
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002065 const ConstantExprKeyType Key(Instruction::ICmp, ArgVec, pred);
Owen Anderson61794042009-06-17 20:10:08 +00002066
Chris Lattner229907c2011-07-18 04:54:35 +00002067 Type *ResultTy = Type::getInt1Ty(LHS->getContext());
2068 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
Nick Lewycky9e26c1c2010-01-21 07:03:21 +00002069 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
2070
Owen Anderson1584a292009-08-04 20:25:11 +00002071 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
Nick Lewycky9e26c1c2010-01-21 07:03:21 +00002072 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
Reid Spenceree3c9912006-12-04 05:19:50 +00002073}
2074
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002075Constant *ConstantExpr::getFCmp(unsigned short pred, Constant *LHS,
2076 Constant *RHS, bool OnlyIfReduced) {
Reid Spenceree3c9912006-12-04 05:19:50 +00002077 assert(LHS->getType() == RHS->getType());
Craig Topper45844762017-07-05 23:35:46 +00002078 assert(CmpInst::isFPPredicate((CmpInst::Predicate)pred) &&
2079 "Invalid FCmp Predicate");
Reid Spenceree3c9912006-12-04 05:19:50 +00002080
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00002081 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
Reid Spenceree3c9912006-12-04 05:19:50 +00002082 return FC; // Fold a few common cases...
2083
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002084 if (OnlyIfReduced)
2085 return nullptr;
2086
Reid Spenceree3c9912006-12-04 05:19:50 +00002087 // Look up the constant in the table first to ensure uniqueness
Benjamin Kramer324322b2013-03-07 20:53:34 +00002088 Constant *ArgVec[] = { LHS, RHS };
Reid Spencerb1537492006-12-24 18:42:29 +00002089 // Get the key type with both the opcode and predicate
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002090 const ConstantExprKeyType Key(Instruction::FCmp, ArgVec, pred);
Nick Lewycky9e26c1c2010-01-21 07:03:21 +00002091
Chris Lattner229907c2011-07-18 04:54:35 +00002092 Type *ResultTy = Type::getInt1Ty(LHS->getContext());
2093 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
Nick Lewycky9e26c1c2010-01-21 07:03:21 +00002094 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
2095
Owen Anderson1584a292009-08-04 20:25:11 +00002096 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
Nick Lewycky9e26c1c2010-01-21 07:03:21 +00002097 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
Reid Spenceree3c9912006-12-04 05:19:50 +00002098}
2099
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002100Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx,
2101 Type *OnlyIfReducedTy) {
Duncan Sands19d0b472010-02-16 11:11:14 +00002102 assert(Val->getType()->isVectorTy() &&
Reid Spencer09575ba2007-02-15 03:39:18 +00002103 "Tried to create extractelement operation on non-vector type!");
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002104 assert(Idx->getType()->isIntegerTy() &&
2105 "Extractelement index must be an integer type!");
Galina Kistanovafc259902012-07-13 01:25:27 +00002106
Chris Lattner887ecac2011-07-09 18:23:52 +00002107 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
Chris Lattner09660c92009-12-30 20:25:09 +00002108 return FC; // Fold a few common cases.
Galina Kistanovafc259902012-07-13 01:25:27 +00002109
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002110 Type *ReqTy = Val->getType()->getVectorElementType();
2111 if (OnlyIfReducedTy == ReqTy)
2112 return nullptr;
2113
Robert Bocchinoca27f032006-01-17 20:07:22 +00002114 // Look up the constant in the table first to ensure uniqueness
Benjamin Kramer324322b2013-03-07 20:53:34 +00002115 Constant *ArgVec[] = { Val, Idx };
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002116 const ConstantExprKeyType Key(Instruction::ExtractElement, ArgVec);
Galina Kistanovafc259902012-07-13 01:25:27 +00002117
Chris Lattner887ecac2011-07-09 18:23:52 +00002118 LLVMContextImpl *pImpl = Val->getContext().pImpl;
Owen Anderson1584a292009-08-04 20:25:11 +00002119 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
Robert Bocchinoca27f032006-01-17 20:07:22 +00002120}
2121
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002122Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
2123 Constant *Idx, Type *OnlyIfReducedTy) {
Duncan Sands19d0b472010-02-16 11:11:14 +00002124 assert(Val->getType()->isVectorTy() &&
Reid Spencer09575ba2007-02-15 03:39:18 +00002125 "Tried to create insertelement operation on non-vector type!");
Chris Lattner8326bd82012-01-26 00:42:34 +00002126 assert(Elt->getType() == Val->getType()->getVectorElementType() &&
2127 "Insertelement types must match!");
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002128 assert(Idx->getType()->isIntegerTy() &&
Reid Spencer2546b762007-01-26 07:37:34 +00002129 "Insertelement index must be i32 type!");
Robert Bocchinoca27f032006-01-17 20:07:22 +00002130
Chris Lattner887ecac2011-07-09 18:23:52 +00002131 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
2132 return FC; // Fold a few common cases.
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002133
2134 if (OnlyIfReducedTy == Val->getType())
2135 return nullptr;
2136
Chris Lattnerbbe0a422006-04-08 01:18:18 +00002137 // Look up the constant in the table first to ensure uniqueness
Benjamin Kramer324322b2013-03-07 20:53:34 +00002138 Constant *ArgVec[] = { Val, Elt, Idx };
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002139 const ConstantExprKeyType Key(Instruction::InsertElement, ArgVec);
Galina Kistanovafc259902012-07-13 01:25:27 +00002140
Chris Lattner887ecac2011-07-09 18:23:52 +00002141 LLVMContextImpl *pImpl = Val->getContext().pImpl;
2142 return pImpl->ExprConstants.getOrCreate(Val->getType(), Key);
Chris Lattnerbbe0a422006-04-08 01:18:18 +00002143}
2144
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002145Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
2146 Constant *Mask, Type *OnlyIfReducedTy) {
Chris Lattnerbbe0a422006-04-08 01:18:18 +00002147 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
2148 "Invalid shuffle vector constant expr operands!");
Nate Begeman94aa38d2009-02-12 21:28:33 +00002149
Chris Lattner887ecac2011-07-09 18:23:52 +00002150 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
2151 return FC; // Fold a few common cases.
2152
Chris Lattner8326bd82012-01-26 00:42:34 +00002153 unsigned NElts = Mask->getType()->getVectorNumElements();
2154 Type *EltTy = V1->getType()->getVectorElementType();
Chris Lattner229907c2011-07-18 04:54:35 +00002155 Type *ShufTy = VectorType::get(EltTy, NElts);
Chris Lattner887ecac2011-07-09 18:23:52 +00002156
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002157 if (OnlyIfReducedTy == ShufTy)
2158 return nullptr;
2159
Chris Lattner887ecac2011-07-09 18:23:52 +00002160 // Look up the constant in the table first to ensure uniqueness
Benjamin Kramer324322b2013-03-07 20:53:34 +00002161 Constant *ArgVec[] = { V1, V2, Mask };
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002162 const ConstantExprKeyType Key(Instruction::ShuffleVector, ArgVec);
Galina Kistanovafc259902012-07-13 01:25:27 +00002163
Chris Lattner887ecac2011-07-09 18:23:52 +00002164 LLVMContextImpl *pImpl = ShufTy->getContext().pImpl;
2165 return pImpl->ExprConstants.getOrCreate(ShufTy, Key);
Chris Lattnerbbe0a422006-04-08 01:18:18 +00002166}
2167
Chris Lattner887ecac2011-07-09 18:23:52 +00002168Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002169 ArrayRef<unsigned> Idxs,
2170 Type *OnlyIfReducedTy) {
Hal Finkelb31366d2013-07-10 22:51:01 +00002171 assert(Agg->getType()->isFirstClassType() &&
2172 "Non-first-class type for constant insertvalue expression");
2173
Jay Foad57aa6362011-07-13 10:26:04 +00002174 assert(ExtractValueInst::getIndexedType(Agg->getType(),
2175 Idxs) == Val->getType() &&
Dan Gohman12fce772008-05-15 19:50:34 +00002176 "insertvalue indices invalid!");
Hal Finkelb31366d2013-07-10 22:51:01 +00002177 Type *ReqTy = Val->getType();
2178
2179 if (Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs))
2180 return FC;
2181
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002182 if (OnlyIfReducedTy == ReqTy)
2183 return nullptr;
2184
Hal Finkelb31366d2013-07-10 22:51:01 +00002185 Constant *ArgVec[] = { Agg, Val };
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002186 const ConstantExprKeyType Key(Instruction::InsertValue, ArgVec, 0, 0, Idxs);
Hal Finkelb31366d2013-07-10 22:51:01 +00002187
2188 LLVMContextImpl *pImpl = Agg->getContext().pImpl;
2189 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
Dan Gohman12fce772008-05-15 19:50:34 +00002190}
2191
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002192Constant *ConstantExpr::getExtractValue(Constant *Agg, ArrayRef<unsigned> Idxs,
2193 Type *OnlyIfReducedTy) {
Dan Gohman0752bff2008-05-23 00:36:11 +00002194 assert(Agg->getType()->isFirstClassType() &&
Chris Lattner887ecac2011-07-09 18:23:52 +00002195 "Tried to create extractelement operation on non-first-class type!");
Dan Gohman12fce772008-05-15 19:50:34 +00002196
Chris Lattner229907c2011-07-18 04:54:35 +00002197 Type *ReqTy = ExtractValueInst::getIndexedType(Agg->getType(), Idxs);
Chandler Carruth9db56b82011-07-10 09:45:35 +00002198 (void)ReqTy;
Chris Lattner887ecac2011-07-09 18:23:52 +00002199 assert(ReqTy && "extractvalue indices invalid!");
Galina Kistanovafc259902012-07-13 01:25:27 +00002200
Dan Gohman0752bff2008-05-23 00:36:11 +00002201 assert(Agg->getType()->isFirstClassType() &&
2202 "Non-first-class type for constant extractvalue expression");
Hal Finkelb31366d2013-07-10 22:51:01 +00002203 if (Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs))
2204 return FC;
2205
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002206 if (OnlyIfReducedTy == ReqTy)
2207 return nullptr;
2208
Hal Finkelb31366d2013-07-10 22:51:01 +00002209 Constant *ArgVec[] = { Agg };
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002210 const ConstantExprKeyType Key(Instruction::ExtractValue, ArgVec, 0, 0, Idxs);
Hal Finkelb31366d2013-07-10 22:51:01 +00002211
2212 LLVMContextImpl *pImpl = Agg->getContext().pImpl;
2213 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
Dan Gohman12fce772008-05-15 19:50:34 +00002214}
2215
Chris Lattnere9b4ad72011-02-10 07:01:55 +00002216Constant *ConstantExpr::getNeg(Constant *C, bool HasNUW, bool HasNSW) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00002217 assert(C->getType()->isIntOrIntVectorTy() &&
Owen Anderson487375e2009-07-29 18:55:55 +00002218 "Cannot NEG a nonintegral value!");
Chris Lattnere9b4ad72011-02-10 07:01:55 +00002219 return getSub(ConstantFP::getZeroValueForNegation(C->getType()),
2220 C, HasNUW, HasNSW);
Owen Anderson487375e2009-07-29 18:55:55 +00002221}
2222
Chris Lattnera676c0f2011-02-07 16:40:21 +00002223Constant *ConstantExpr::getFNeg(Constant *C) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00002224 assert(C->getType()->isFPOrFPVectorTy() &&
Owen Anderson487375e2009-07-29 18:55:55 +00002225 "Cannot FNEG a non-floating-point value!");
Chris Lattnere9b4ad72011-02-10 07:01:55 +00002226 return getFSub(ConstantFP::getZeroValueForNegation(C->getType()), C);
Owen Anderson487375e2009-07-29 18:55:55 +00002227}
2228
Chris Lattnera676c0f2011-02-07 16:40:21 +00002229Constant *ConstantExpr::getNot(Constant *C) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00002230 assert(C->getType()->isIntOrIntVectorTy() &&
Owen Anderson487375e2009-07-29 18:55:55 +00002231 "Cannot NOT a nonintegral value!");
Owen Anderson5a1acd92009-07-31 20:28:14 +00002232 return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
Owen Anderson487375e2009-07-29 18:55:55 +00002233}
2234
Chris Lattnere9b4ad72011-02-10 07:01:55 +00002235Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2,
2236 bool HasNUW, bool HasNSW) {
2237 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2238 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2239 return get(Instruction::Add, C1, C2, Flags);
Owen Anderson487375e2009-07-29 18:55:55 +00002240}
2241
Chris Lattnera676c0f2011-02-07 16:40:21 +00002242Constant *ConstantExpr::getFAdd(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002243 return get(Instruction::FAdd, C1, C2);
2244}
2245
Chris Lattnere9b4ad72011-02-10 07:01:55 +00002246Constant *ConstantExpr::getSub(Constant *C1, Constant *C2,
2247 bool HasNUW, bool HasNSW) {
2248 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2249 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2250 return get(Instruction::Sub, C1, C2, Flags);
Owen Anderson487375e2009-07-29 18:55:55 +00002251}
2252
Chris Lattnera676c0f2011-02-07 16:40:21 +00002253Constant *ConstantExpr::getFSub(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002254 return get(Instruction::FSub, C1, C2);
2255}
2256
Chris Lattnere9b4ad72011-02-10 07:01:55 +00002257Constant *ConstantExpr::getMul(Constant *C1, Constant *C2,
2258 bool HasNUW, bool HasNSW) {
2259 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2260 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2261 return get(Instruction::Mul, C1, C2, Flags);
Owen Anderson487375e2009-07-29 18:55:55 +00002262}
2263
Chris Lattnera676c0f2011-02-07 16:40:21 +00002264Constant *ConstantExpr::getFMul(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002265 return get(Instruction::FMul, C1, C2);
2266}
2267
Chris Lattner0d75eac2011-02-09 16:43:07 +00002268Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2, bool isExact) {
2269 return get(Instruction::UDiv, C1, C2,
2270 isExact ? PossiblyExactOperator::IsExact : 0);
Owen Anderson487375e2009-07-29 18:55:55 +00002271}
2272
Chris Lattner0d75eac2011-02-09 16:43:07 +00002273Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2, bool isExact) {
2274 return get(Instruction::SDiv, C1, C2,
2275 isExact ? PossiblyExactOperator::IsExact : 0);
Owen Anderson487375e2009-07-29 18:55:55 +00002276}
2277
Chris Lattnera676c0f2011-02-07 16:40:21 +00002278Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002279 return get(Instruction::FDiv, C1, C2);
2280}
2281
Chris Lattnera676c0f2011-02-07 16:40:21 +00002282Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002283 return get(Instruction::URem, C1, C2);
2284}
2285
Chris Lattnera676c0f2011-02-07 16:40:21 +00002286Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002287 return get(Instruction::SRem, C1, C2);
2288}
2289
Chris Lattnera676c0f2011-02-07 16:40:21 +00002290Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002291 return get(Instruction::FRem, C1, C2);
2292}
2293
Chris Lattnera676c0f2011-02-07 16:40:21 +00002294Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002295 return get(Instruction::And, C1, C2);
2296}
2297
Chris Lattnera676c0f2011-02-07 16:40:21 +00002298Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002299 return get(Instruction::Or, C1, C2);
2300}
2301
Chris Lattnera676c0f2011-02-07 16:40:21 +00002302Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002303 return get(Instruction::Xor, C1, C2);
2304}
2305
Chris Lattnere9b4ad72011-02-10 07:01:55 +00002306Constant *ConstantExpr::getShl(Constant *C1, Constant *C2,
2307 bool HasNUW, bool HasNSW) {
2308 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2309 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2310 return get(Instruction::Shl, C1, C2, Flags);
Owen Anderson487375e2009-07-29 18:55:55 +00002311}
2312
Chris Lattner0d75eac2011-02-09 16:43:07 +00002313Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2, bool isExact) {
2314 return get(Instruction::LShr, C1, C2,
2315 isExact ? PossiblyExactOperator::IsExact : 0);
Owen Anderson487375e2009-07-29 18:55:55 +00002316}
2317
Chris Lattner0d75eac2011-02-09 16:43:07 +00002318Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2, bool isExact) {
2319 return get(Instruction::AShr, C1, C2,
2320 isExact ? PossiblyExactOperator::IsExact : 0);
Owen Anderson487375e2009-07-29 18:55:55 +00002321}
2322
Sanjay Patele85a3002018-07-06 15:18:58 +00002323Constant *ConstantExpr::getBinOpIdentity(unsigned Opcode, Type *Ty,
2324 bool AllowRHSConstant) {
2325 assert(Instruction::isBinaryOp(Opcode) && "Only binops allowed");
2326
2327 // Commutative opcodes: it does not matter if AllowRHSConstant is set.
2328 if (Instruction::isCommutative(Opcode)) {
2329 switch (Opcode) {
2330 case Instruction::Add: // X + 0 = X
2331 case Instruction::Or: // X | 0 = X
2332 case Instruction::Xor: // X ^ 0 = X
2333 return Constant::getNullValue(Ty);
2334 case Instruction::Mul: // X * 1 = X
2335 return ConstantInt::get(Ty, 1);
2336 case Instruction::And: // X & -1 = X
2337 return Constant::getAllOnesValue(Ty);
2338 case Instruction::FAdd: // X + -0.0 = X
2339 // TODO: If the fadd has 'nsz', should we return +0.0?
2340 return ConstantFP::getNegativeZero(Ty);
2341 case Instruction::FMul: // X * 1.0 = X
2342 return ConstantFP::get(Ty, 1.0);
2343 default:
2344 llvm_unreachable("Every commutative binop has an identity constant");
2345 }
2346 }
2347
2348 // Non-commutative opcodes: AllowRHSConstant must be set.
2349 if (!AllowRHSConstant)
Craig Topperc6207612014-04-09 06:08:46 +00002350 return nullptr;
Duncan Sands318a89d2012-06-13 09:42:13 +00002351
Sanjay Patele85a3002018-07-06 15:18:58 +00002352 switch (Opcode) {
2353 case Instruction::Sub: // X - 0 = X
2354 case Instruction::Shl: // X << 0 = X
2355 case Instruction::LShr: // X >>u 0 = X
2356 case Instruction::AShr: // X >> 0 = X
2357 case Instruction::FSub: // X - 0.0 = X
2358 return Constant::getNullValue(Ty);
2359 case Instruction::SDiv: // X / 1 = X
2360 case Instruction::UDiv: // X /u 1 = X
2361 return ConstantInt::get(Ty, 1);
2362 case Instruction::FDiv: // X / 1.0 = X
2363 return ConstantFP::get(Ty, 1.0);
2364 default:
2365 return nullptr;
Duncan Sandsd7aeefe2012-06-12 14:33:56 +00002366 }
2367}
2368
Duncan Sands318a89d2012-06-13 09:42:13 +00002369Constant *ConstantExpr::getBinOpAbsorber(unsigned Opcode, Type *Ty) {
2370 switch (Opcode) {
2371 default:
2372 // Doesn't have an absorber.
Craig Topperc6207612014-04-09 06:08:46 +00002373 return nullptr;
Duncan Sands318a89d2012-06-13 09:42:13 +00002374
2375 case Instruction::Or:
2376 return Constant::getAllOnesValue(Ty);
2377
2378 case Instruction::And:
2379 case Instruction::Mul:
2380 return Constant::getNullValue(Ty);
2381 }
2382}
2383
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00002384/// Remove the constant from the constant table.
Pete Cooper86dd4cf2015-06-23 21:55:11 +00002385void ConstantExpr::destroyConstantImpl() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002386 getType()->getContext().pImpl->ExprConstants.remove(this);
Vikram S. Adve4e537b22002-07-14 23:13:17 +00002387}
2388
Chris Lattner3cd8c562002-07-30 18:54:25 +00002389const char *ConstantExpr::getOpcodeName() const {
2390 return Instruction::getOpcodeName(getOpcode());
Vikram S. Adve4e537b22002-07-14 23:13:17 +00002391}
Reid Spencer1ebe1ab2004-07-17 23:48:33 +00002392
David Blaikie60310f22015-05-08 00:42:26 +00002393GetElementPtrConstantExpr::GetElementPtrConstantExpr(
2394 Type *SrcElementTy, Constant *C, ArrayRef<Constant *> IdxList, Type *DestTy)
2395 : ConstantExpr(DestTy, Instruction::GetElementPtr,
2396 OperandTraits<GetElementPtrConstantExpr>::op_end(this) -
2397 (IdxList.size() + 1),
2398 IdxList.size() + 1),
Eduard Burtescu19eb0312016-01-19 17:28:00 +00002399 SrcElementTy(SrcElementTy),
2400 ResElementTy(GetElementPtrInst::getIndexedType(SrcElementTy, IdxList)) {
Pete Coopereb31b682015-05-21 22:48:54 +00002401 Op<0>() = C;
Pete Cooper74510a42015-06-12 17:48:05 +00002402 Use *OperandList = getOperandList();
Chris Lattnera3b94ba2010-03-30 20:48:48 +00002403 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
2404 OperandList[i+1] = IdxList[i];
2405}
2406
David Blaikie60310f22015-05-08 00:42:26 +00002407Type *GetElementPtrConstantExpr::getSourceElementType() const {
2408 return SrcElementTy;
2409}
2410
Eduard Burtescu19eb0312016-01-19 17:28:00 +00002411Type *GetElementPtrConstantExpr::getResultElementType() const {
2412 return ResElementTy;
2413}
2414
Chris Lattner3756b912012-01-23 22:57:10 +00002415//===----------------------------------------------------------------------===//
2416// ConstantData* implementations
2417
Chris Lattnere4f3f102012-01-24 04:43:41 +00002418Type *ConstantDataSequential::getElementType() const {
2419 return getType()->getElementType();
2420}
2421
Chris Lattner5d4497b2012-01-24 09:31:43 +00002422StringRef ConstantDataSequential::getRawDataValues() const {
Chris Lattner00245f42012-01-24 13:41:11 +00002423 return StringRef(DataElements, getNumElements()*getElementByteSize());
Chris Lattner5d4497b2012-01-24 09:31:43 +00002424}
2425
Craig Toppere3dcce92015-08-01 22:20:21 +00002426bool ConstantDataSequential::isElementTypeCompatible(Type *Ty) {
Justin Bogner0ebc8602015-12-08 03:01:16 +00002427 if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) return true;
Craig Toppere3dcce92015-08-01 22:20:21 +00002428 if (auto *IT = dyn_cast<IntegerType>(Ty)) {
Chris Lattnere4f3f102012-01-24 04:43:41 +00002429 switch (IT->getBitWidth()) {
2430 case 8:
2431 case 16:
2432 case 32:
2433 case 64:
2434 return true;
2435 default: break;
2436 }
2437 }
2438 return false;
2439}
2440
Chris Lattner00245f42012-01-24 13:41:11 +00002441unsigned ConstantDataSequential::getNumElements() const {
Chris Lattner8a3df542012-01-25 01:32:59 +00002442 if (ArrayType *AT = dyn_cast<ArrayType>(getType()))
2443 return AT->getNumElements();
Chris Lattner8326bd82012-01-26 00:42:34 +00002444 return getType()->getVectorNumElements();
Chris Lattner00245f42012-01-24 13:41:11 +00002445}
2446
2447
Chris Lattnere4f3f102012-01-24 04:43:41 +00002448uint64_t ConstantDataSequential::getElementByteSize() const {
2449 return getElementType()->getPrimitiveSizeInBits()/8;
2450}
2451
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00002452/// Return the start of the specified element.
Chris Lattnere4f3f102012-01-24 04:43:41 +00002453const char *ConstantDataSequential::getElementPointer(unsigned Elt) const {
Chris Lattner00245f42012-01-24 13:41:11 +00002454 assert(Elt < getNumElements() && "Invalid Elt");
Chris Lattnere4f3f102012-01-24 04:43:41 +00002455 return DataElements+Elt*getElementByteSize();
2456}
2457
2458
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00002459/// Return true if the array is empty or all zeros.
Chris Lattner3756b912012-01-23 22:57:10 +00002460static bool isAllZeros(StringRef Arr) {
Benjamin Krameraf28e7d2016-06-26 14:10:56 +00002461 for (char I : Arr)
2462 if (I != 0)
Chris Lattner3756b912012-01-23 22:57:10 +00002463 return false;
2464 return true;
2465}
Chris Lattner030af792012-01-24 05:42:11 +00002466
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00002467/// This is the underlying implementation of all of the
Chris Lattner3756b912012-01-23 22:57:10 +00002468/// ConstantDataSequential::get methods. They all thunk down to here, providing
Chris Lattnerf06039b2012-01-30 18:19:30 +00002469/// the correct element type. We take the bytes in as a StringRef because
Chris Lattner3756b912012-01-23 22:57:10 +00002470/// we *want* an underlying "char*" to avoid TBAA type punning violations.
2471Constant *ConstantDataSequential::getImpl(StringRef Elements, Type *Ty) {
Chris Lattner8326bd82012-01-26 00:42:34 +00002472 assert(isElementTypeCompatible(Ty->getSequentialElementType()));
Chris Lattner139822f2012-01-24 14:17:05 +00002473 // If the elements are all zero or there are no elements, return a CAZ, which
2474 // is more dense and canonical.
Chris Lattner3756b912012-01-23 22:57:10 +00002475 if (isAllZeros(Elements))
2476 return ConstantAggregateZero::get(Ty);
2477
2478 // Do a lookup to see if we have already formed one of these.
David Blaikie5106ce72014-11-19 05:49:42 +00002479 auto &Slot =
2480 *Ty->getContext()
2481 .pImpl->CDSConstants.insert(std::make_pair(Elements, nullptr))
2482 .first;
Galina Kistanovafc259902012-07-13 01:25:27 +00002483
Chris Lattner3756b912012-01-23 22:57:10 +00002484 // The bucket can point to a linked list of different CDS's that have the same
2485 // body but different types. For example, 0,0,0,1 could be a 4 element array
2486 // of i8, or a 1-element array of i32. They'll both end up in the same
2487 /// StringMap bucket, linked up by their Next pointers. Walk the list.
David Blaikie5106ce72014-11-19 05:49:42 +00002488 ConstantDataSequential **Entry = &Slot.second;
Craig Topperc6207612014-04-09 06:08:46 +00002489 for (ConstantDataSequential *Node = *Entry; Node;
Chris Lattner3756b912012-01-23 22:57:10 +00002490 Entry = &Node->Next, Node = *Entry)
2491 if (Node->getType() == Ty)
2492 return Node;
Galina Kistanovafc259902012-07-13 01:25:27 +00002493
Chris Lattner3756b912012-01-23 22:57:10 +00002494 // Okay, we didn't get a hit. Create a node of the right class, link it in,
2495 // and return it.
2496 if (isa<ArrayType>(Ty))
David Blaikie5106ce72014-11-19 05:49:42 +00002497 return *Entry = new ConstantDataArray(Ty, Slot.first().data());
Chris Lattner3756b912012-01-23 22:57:10 +00002498
2499 assert(isa<VectorType>(Ty));
David Blaikie5106ce72014-11-19 05:49:42 +00002500 return *Entry = new ConstantDataVector(Ty, Slot.first().data());
Chris Lattner3756b912012-01-23 22:57:10 +00002501}
2502
Pete Cooper86dd4cf2015-06-23 21:55:11 +00002503void ConstantDataSequential::destroyConstantImpl() {
Chris Lattner3756b912012-01-23 22:57:10 +00002504 // Remove the constant from the StringMap.
Bjorn Petterssonaa025802018-07-03 12:39:52 +00002505 StringMap<ConstantDataSequential*> &CDSConstants =
Chris Lattner3756b912012-01-23 22:57:10 +00002506 getType()->getContext().pImpl->CDSConstants;
Galina Kistanovafc259902012-07-13 01:25:27 +00002507
Chris Lattner3756b912012-01-23 22:57:10 +00002508 StringMap<ConstantDataSequential*>::iterator Slot =
Chris Lattner5d4497b2012-01-24 09:31:43 +00002509 CDSConstants.find(getRawDataValues());
Chris Lattner3756b912012-01-23 22:57:10 +00002510
2511 assert(Slot != CDSConstants.end() && "CDS not found in uniquing table");
2512
2513 ConstantDataSequential **Entry = &Slot->getValue();
2514
2515 // Remove the entry from the hash table.
Craig Topperc6207612014-04-09 06:08:46 +00002516 if (!(*Entry)->Next) {
Chris Lattner3756b912012-01-23 22:57:10 +00002517 // If there is only one value in the bucket (common case) it must be this
2518 // entry, and removing the entry should remove the bucket completely.
2519 assert((*Entry) == this && "Hash mismatch in ConstantDataSequential");
2520 getContext().pImpl->CDSConstants.erase(Slot);
2521 } else {
Bjorn Petterssonaa025802018-07-03 12:39:52 +00002522 // Otherwise, there are multiple entries linked off the bucket, unlink the
Chris Lattner3756b912012-01-23 22:57:10 +00002523 // node we care about but keep the bucket around.
2524 for (ConstantDataSequential *Node = *Entry; ;
2525 Entry = &Node->Next, Node = *Entry) {
2526 assert(Node && "Didn't find entry in its uniquing hash table!");
2527 // If we found our entry, unlink it from the list and we're done.
2528 if (Node == this) {
2529 *Entry = Node->Next;
2530 break;
2531 }
2532 }
2533 }
Galina Kistanovafc259902012-07-13 01:25:27 +00002534
Chris Lattner3756b912012-01-23 22:57:10 +00002535 // If we were part of a list, make sure that we don't delete the list that is
2536 // still owned by the uniquing map.
Craig Topperc6207612014-04-09 06:08:46 +00002537 Next = nullptr;
Chris Lattner3756b912012-01-23 22:57:10 +00002538}
2539
Rafael Espindola8c97e192015-02-19 16:08:20 +00002540/// getFP() constructors - Return a constant with array type with an element
2541/// count and element type of float with precision matching the number of
2542/// bits in the ArrayRef passed in. (i.e. half for 16bits, float for 32bits,
2543/// double for 64bits) Note that this can return a ConstantAggregateZero
2544/// object.
2545Constant *ConstantDataArray::getFP(LLVMContext &Context,
2546 ArrayRef<uint16_t> Elts) {
Justin Bognerb7389d6712015-12-09 21:21:07 +00002547 Type *Ty = ArrayType::get(Type::getHalfTy(Context), Elts.size());
Rafael Espindola8c97e192015-02-19 16:08:20 +00002548 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper393ce692017-07-11 15:52:21 +00002549 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
Rafael Espindola8c97e192015-02-19 16:08:20 +00002550}
2551Constant *ConstantDataArray::getFP(LLVMContext &Context,
2552 ArrayRef<uint32_t> Elts) {
2553 Type *Ty = ArrayType::get(Type::getFloatTy(Context), Elts.size());
2554 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper393ce692017-07-11 15:52:21 +00002555 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
Rafael Espindola8c97e192015-02-19 16:08:20 +00002556}
2557Constant *ConstantDataArray::getFP(LLVMContext &Context,
2558 ArrayRef<uint64_t> Elts) {
2559 Type *Ty = ArrayType::get(Type::getDoubleTy(Context), Elts.size());
2560 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper393ce692017-07-11 15:52:21 +00002561 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002562}
2563
Chris Lattner20683932012-01-24 14:04:40 +00002564Constant *ConstantDataArray::getString(LLVMContext &Context,
2565 StringRef Str, bool AddNull) {
Galina Kistanovafc259902012-07-13 01:25:27 +00002566 if (!AddNull) {
2567 const uint8_t *Data = reinterpret_cast<const uint8_t *>(Str.data());
Craig Topper393ce692017-07-11 15:52:21 +00002568 return get(Context, makeArrayRef(Data, Str.size()));
Galina Kistanovafc259902012-07-13 01:25:27 +00002569 }
2570
Chris Lattner20683932012-01-24 14:04:40 +00002571 SmallVector<uint8_t, 64> ElementVals;
2572 ElementVals.append(Str.begin(), Str.end());
2573 ElementVals.push_back(0);
2574 return get(Context, ElementVals);
2575}
Chris Lattner3756b912012-01-23 22:57:10 +00002576
2577/// get() constructors - Return a constant with vector type with an element
2578/// count and element type matching the ArrayRef passed in. Note that this
2579/// can return a ConstantAggregateZero object.
Chris Lattner20683932012-01-24 14:04:40 +00002580Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint8_t> Elts){
Chris Lattner3756b912012-01-23 22:57:10 +00002581 Type *Ty = VectorType::get(Type::getInt8Ty(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002582 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper393ce692017-07-11 15:52:21 +00002583 return getImpl(StringRef(Data, Elts.size() * 1), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002584}
Chris Lattner20683932012-01-24 14:04:40 +00002585Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint16_t> Elts){
Chris Lattner3756b912012-01-23 22:57:10 +00002586 Type *Ty = VectorType::get(Type::getInt16Ty(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002587 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper393ce692017-07-11 15:52:21 +00002588 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002589}
Chris Lattner20683932012-01-24 14:04:40 +00002590Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint32_t> Elts){
Chris Lattner3756b912012-01-23 22:57:10 +00002591 Type *Ty = VectorType::get(Type::getInt32Ty(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002592 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper393ce692017-07-11 15:52:21 +00002593 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002594}
Chris Lattner20683932012-01-24 14:04:40 +00002595Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint64_t> Elts){
Chris Lattner3756b912012-01-23 22:57:10 +00002596 Type *Ty = VectorType::get(Type::getInt64Ty(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002597 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper393ce692017-07-11 15:52:21 +00002598 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002599}
Chris Lattner20683932012-01-24 14:04:40 +00002600Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<float> Elts) {
Chris Lattner3756b912012-01-23 22:57:10 +00002601 Type *Ty = VectorType::get(Type::getFloatTy(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002602 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper393ce692017-07-11 15:52:21 +00002603 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002604}
Chris Lattner20683932012-01-24 14:04:40 +00002605Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<double> Elts) {
Chris Lattner3756b912012-01-23 22:57:10 +00002606 Type *Ty = VectorType::get(Type::getDoubleTy(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002607 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper393ce692017-07-11 15:52:21 +00002608 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
Rafael Espindola8c97e192015-02-19 16:08:20 +00002609}
2610
2611/// getFP() constructors - Return a constant with vector type with an element
2612/// count and element type of float with the precision matching the number of
2613/// bits in the ArrayRef passed in. (i.e. half for 16bits, float for 32bits,
2614/// double for 64bits) Note that this can return a ConstantAggregateZero
2615/// object.
2616Constant *ConstantDataVector::getFP(LLVMContext &Context,
2617 ArrayRef<uint16_t> Elts) {
2618 Type *Ty = VectorType::get(Type::getHalfTy(Context), Elts.size());
2619 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper393ce692017-07-11 15:52:21 +00002620 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
Rafael Espindola8c97e192015-02-19 16:08:20 +00002621}
2622Constant *ConstantDataVector::getFP(LLVMContext &Context,
2623 ArrayRef<uint32_t> Elts) {
2624 Type *Ty = VectorType::get(Type::getFloatTy(Context), Elts.size());
2625 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper393ce692017-07-11 15:52:21 +00002626 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
Rafael Espindola8c97e192015-02-19 16:08:20 +00002627}
2628Constant *ConstantDataVector::getFP(LLVMContext &Context,
2629 ArrayRef<uint64_t> Elts) {
2630 Type *Ty = VectorType::get(Type::getDoubleTy(Context), Elts.size());
2631 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper393ce692017-07-11 15:52:21 +00002632 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002633}
2634
Chris Lattnere9eed292012-01-25 05:19:54 +00002635Constant *ConstantDataVector::getSplat(unsigned NumElts, Constant *V) {
2636 assert(isElementTypeCompatible(V->getType()) &&
2637 "Element type not compatible with ConstantData");
2638 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
2639 if (CI->getType()->isIntegerTy(8)) {
2640 SmallVector<uint8_t, 16> Elts(NumElts, CI->getZExtValue());
2641 return get(V->getContext(), Elts);
2642 }
2643 if (CI->getType()->isIntegerTy(16)) {
2644 SmallVector<uint16_t, 16> Elts(NumElts, CI->getZExtValue());
2645 return get(V->getContext(), Elts);
2646 }
2647 if (CI->getType()->isIntegerTy(32)) {
2648 SmallVector<uint32_t, 16> Elts(NumElts, CI->getZExtValue());
2649 return get(V->getContext(), Elts);
2650 }
2651 assert(CI->getType()->isIntegerTy(64) && "Unsupported ConstantData type");
2652 SmallVector<uint64_t, 16> Elts(NumElts, CI->getZExtValue());
2653 return get(V->getContext(), Elts);
2654 }
2655
Chris Lattner978fe0c2012-01-30 06:21:21 +00002656 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
Justin Bogner0ebc8602015-12-08 03:01:16 +00002657 if (CFP->getType()->isHalfTy()) {
2658 SmallVector<uint16_t, 16> Elts(
2659 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
2660 return getFP(V->getContext(), Elts);
2661 }
Chris Lattner978fe0c2012-01-30 06:21:21 +00002662 if (CFP->getType()->isFloatTy()) {
Rafael Espindola8c97e192015-02-19 16:08:20 +00002663 SmallVector<uint32_t, 16> Elts(
2664 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
2665 return getFP(V->getContext(), Elts);
Chris Lattner978fe0c2012-01-30 06:21:21 +00002666 }
2667 if (CFP->getType()->isDoubleTy()) {
Rafael Espindola8c97e192015-02-19 16:08:20 +00002668 SmallVector<uint64_t, 16> Elts(
2669 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
2670 return getFP(V->getContext(), Elts);
Chris Lattner978fe0c2012-01-30 06:21:21 +00002671 }
Chris Lattnere9eed292012-01-25 05:19:54 +00002672 }
Chris Lattner978fe0c2012-01-30 06:21:21 +00002673 return ConstantVector::getSplat(NumElts, V);
Chris Lattnere9eed292012-01-25 05:19:54 +00002674}
2675
2676
Chris Lattnere4f3f102012-01-24 04:43:41 +00002677uint64_t ConstantDataSequential::getElementAsInteger(unsigned Elt) const {
2678 assert(isa<IntegerType>(getElementType()) &&
2679 "Accessor can only be used when element is an integer");
2680 const char *EltPtr = getElementPointer(Elt);
Galina Kistanovafc259902012-07-13 01:25:27 +00002681
Chris Lattnere4f3f102012-01-24 04:43:41 +00002682 // The data is stored in host byte order, make sure to cast back to the right
2683 // type to load with the right endianness.
Chris Lattner8326bd82012-01-26 00:42:34 +00002684 switch (getElementType()->getIntegerBitWidth()) {
Craig Topperc514b542012-02-05 22:14:15 +00002685 default: llvm_unreachable("Invalid bitwidth for CDS");
Galina Kistanovafc259902012-07-13 01:25:27 +00002686 case 8:
Craig Topper393ce692017-07-11 15:52:21 +00002687 return *reinterpret_cast<const uint8_t *>(EltPtr);
Galina Kistanovafc259902012-07-13 01:25:27 +00002688 case 16:
Craig Topper393ce692017-07-11 15:52:21 +00002689 return *reinterpret_cast<const uint16_t *>(EltPtr);
Galina Kistanovafc259902012-07-13 01:25:27 +00002690 case 32:
Craig Topper393ce692017-07-11 15:52:21 +00002691 return *reinterpret_cast<const uint32_t *>(EltPtr);
Galina Kistanovafc259902012-07-13 01:25:27 +00002692 case 64:
Craig Topper393ce692017-07-11 15:52:21 +00002693 return *reinterpret_cast<const uint64_t *>(EltPtr);
Chris Lattnere4f3f102012-01-24 04:43:41 +00002694 }
2695}
2696
Craig Topper0b4b4e32017-07-15 22:06:19 +00002697APInt ConstantDataSequential::getElementAsAPInt(unsigned Elt) const {
2698 assert(isa<IntegerType>(getElementType()) &&
2699 "Accessor can only be used when element is an integer");
2700 const char *EltPtr = getElementPointer(Elt);
2701
2702 // The data is stored in host byte order, make sure to cast back to the right
2703 // type to load with the right endianness.
2704 switch (getElementType()->getIntegerBitWidth()) {
2705 default: llvm_unreachable("Invalid bitwidth for CDS");
2706 case 8: {
2707 auto EltVal = *reinterpret_cast<const uint8_t *>(EltPtr);
2708 return APInt(8, EltVal);
2709 }
2710 case 16: {
2711 auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
2712 return APInt(16, EltVal);
2713 }
2714 case 32: {
2715 auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr);
2716 return APInt(32, EltVal);
2717 }
2718 case 64: {
2719 auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr);
2720 return APInt(64, EltVal);
2721 }
2722 }
2723}
2724
Chris Lattnere4f3f102012-01-24 04:43:41 +00002725APFloat ConstantDataSequential::getElementAsAPFloat(unsigned Elt) const {
2726 const char *EltPtr = getElementPointer(Elt);
2727
2728 switch (getElementType()->getTypeID()) {
Nick Lewyckyff509622012-01-25 03:20:12 +00002729 default:
Craig Topperc514b542012-02-05 22:14:15 +00002730 llvm_unreachable("Accessor can only be used when element is float/double!");
Justin Bogner0ebc8602015-12-08 03:01:16 +00002731 case Type::HalfTyID: {
2732 auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002733 return APFloat(APFloat::IEEEhalf(), APInt(16, EltVal));
Justin Bogner0ebc8602015-12-08 03:01:16 +00002734 }
Benjamin Kramer7af984b2015-02-20 15:11:55 +00002735 case Type::FloatTyID: {
2736 auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002737 return APFloat(APFloat::IEEEsingle(), APInt(32, EltVal));
Benjamin Kramer7af984b2015-02-20 15:11:55 +00002738 }
2739 case Type::DoubleTyID: {
2740 auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002741 return APFloat(APFloat::IEEEdouble(), APInt(64, EltVal));
Chris Lattnere4f3f102012-01-24 04:43:41 +00002742 }
Benjamin Kramer7af984b2015-02-20 15:11:55 +00002743 }
Chris Lattnere4f3f102012-01-24 04:43:41 +00002744}
2745
Chris Lattnere4f3f102012-01-24 04:43:41 +00002746float ConstantDataSequential::getElementAsFloat(unsigned Elt) const {
2747 assert(getElementType()->isFloatTy() &&
2748 "Accessor can only be used when element is a 'float'");
Craig Topper393ce692017-07-11 15:52:21 +00002749 return *reinterpret_cast<const float *>(getElementPointer(Elt));
Chris Lattnere4f3f102012-01-24 04:43:41 +00002750}
2751
Chris Lattnere4f3f102012-01-24 04:43:41 +00002752double ConstantDataSequential::getElementAsDouble(unsigned Elt) const {
2753 assert(getElementType()->isDoubleTy() &&
2754 "Accessor can only be used when element is a 'float'");
Craig Topper393ce692017-07-11 15:52:21 +00002755 return *reinterpret_cast<const double *>(getElementPointer(Elt));
Chris Lattnere4f3f102012-01-24 04:43:41 +00002756}
2757
Chris Lattnere4f3f102012-01-24 04:43:41 +00002758Constant *ConstantDataSequential::getElementAsConstant(unsigned Elt) const {
Justin Bogner0ebc8602015-12-08 03:01:16 +00002759 if (getElementType()->isHalfTy() || getElementType()->isFloatTy() ||
2760 getElementType()->isDoubleTy())
Chris Lattnere4f3f102012-01-24 04:43:41 +00002761 return ConstantFP::get(getContext(), getElementAsAPFloat(Elt));
Galina Kistanovafc259902012-07-13 01:25:27 +00002762
Chris Lattnere4f3f102012-01-24 04:43:41 +00002763 return ConstantInt::get(getElementType(), getElementAsInteger(Elt));
2764}
2765
Matthias Braun50ec0b52017-05-19 22:37:09 +00002766bool ConstantDataSequential::isString(unsigned CharSize) const {
2767 return isa<ArrayType>(getType()) && getElementType()->isIntegerTy(CharSize);
Chris Lattner5dd4d872012-01-24 09:01:07 +00002768}
Chris Lattner3756b912012-01-23 22:57:10 +00002769
Chris Lattner5dd4d872012-01-24 09:01:07 +00002770bool ConstantDataSequential::isCString() const {
2771 if (!isString())
2772 return false;
Galina Kistanovafc259902012-07-13 01:25:27 +00002773
Chris Lattner5dd4d872012-01-24 09:01:07 +00002774 StringRef Str = getAsString();
Galina Kistanovafc259902012-07-13 01:25:27 +00002775
Chris Lattner5dd4d872012-01-24 09:01:07 +00002776 // The last value must be nul.
2777 if (Str.back() != 0) return false;
Galina Kistanovafc259902012-07-13 01:25:27 +00002778
Chris Lattner5dd4d872012-01-24 09:01:07 +00002779 // Other elements must be non-nul.
2780 return Str.drop_back().find(0) == StringRef::npos;
2781}
Chris Lattner3756b912012-01-23 22:57:10 +00002782
Craig Topper0b4b4e32017-07-15 22:06:19 +00002783bool ConstantDataVector::isSplat() const {
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002784 const char *Base = getRawDataValues().data();
Galina Kistanovafc259902012-07-13 01:25:27 +00002785
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002786 // Compare elements 1+ to the 0'th element.
2787 unsigned EltSize = getElementByteSize();
2788 for (unsigned i = 1, e = getNumElements(); i != e; ++i)
2789 if (memcmp(Base, Base+i*EltSize, EltSize))
Craig Topper0b4b4e32017-07-15 22:06:19 +00002790 return false;
Galina Kistanovafc259902012-07-13 01:25:27 +00002791
Craig Topper0b4b4e32017-07-15 22:06:19 +00002792 return true;
2793}
2794
2795Constant *ConstantDataVector::getSplatValue() const {
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002796 // If they're all the same, return the 0th one as a representative.
Craig Topper0b4b4e32017-07-15 22:06:19 +00002797 return isSplat() ? getElementAsConstant(0) : nullptr;
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002798}
Chris Lattnera3b94ba2010-03-30 20:48:48 +00002799
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002800//===----------------------------------------------------------------------===//
Pete Cooper5815b1f2015-06-24 18:55:24 +00002801// handleOperandChange implementations
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002802
Pete Cooper5815b1f2015-06-24 18:55:24 +00002803/// Update this constant array to change uses of
Chris Lattner913849b2007-08-21 00:55:23 +00002804/// 'From' to be uses of 'To'. This must update the uniquing data structures
2805/// etc.
2806///
2807/// Note that we intentionally replace all uses of From with To here. Consider
2808/// a large array that uses 'From' 1000 times. By handling this case all here,
Pete Cooper5815b1f2015-06-24 18:55:24 +00002809/// ConstantArray::handleOperandChange is only invoked once, and that
Chris Lattner913849b2007-08-21 00:55:23 +00002810/// single invocation handles all 1000 uses. Handling them one at a time would
2811/// work, but would be really slow because it would have to unique each updated
2812/// array instance.
Chris Lattner31b132c2009-10-28 00:01:44 +00002813///
Mehdi Amini8914d292016-02-10 22:47:15 +00002814void Constant::handleOperandChange(Value *From, Value *To) {
Pete Cooper5815b1f2015-06-24 18:55:24 +00002815 Value *Replacement = nullptr;
2816 switch (getValueID()) {
2817 default:
2818 llvm_unreachable("Not a constant!");
2819#define HANDLE_CONSTANT(Name) \
2820 case Value::Name##Val: \
Mehdi Amini8914d292016-02-10 22:47:15 +00002821 Replacement = cast<Name>(this)->handleOperandChangeImpl(From, To); \
Pete Cooper5815b1f2015-06-24 18:55:24 +00002822 break;
2823#include "llvm/IR/Value.def"
2824 }
2825
2826 // If handleOperandChangeImpl returned nullptr, then it handled
2827 // replacing itself and we don't want to delete or replace anything else here.
2828 if (!Replacement)
2829 return;
2830
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002831 // I do need to replace this with an existing value.
2832 assert(Replacement != this && "I didn't contain From!");
2833
2834 // Everyone using this now uses the replacement.
2835 replaceAllUsesWith(Replacement);
2836
2837 // Delete the old constant!
2838 destroyConstant();
2839}
2840
Mehdi Amini8914d292016-02-10 22:47:15 +00002841Value *ConstantArray::handleOperandChangeImpl(Value *From, Value *To) {
Owen Andersonc2c79322009-07-28 18:32:17 +00002842 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2843 Constant *ToC = cast<Constant>(To);
2844
Talin46e9b442012-02-05 20:54:10 +00002845 SmallVector<Constant*, 8> Values;
Owen Andersonc2c79322009-07-28 18:32:17 +00002846 Values.reserve(getNumOperands()); // Build replacement array.
2847
Galina Kistanovafc259902012-07-13 01:25:27 +00002848 // Fill values with the modified operands of the constant array. Also,
Owen Andersonc2c79322009-07-28 18:32:17 +00002849 // compute whether this turns into an all-zeros array.
Owen Andersonc2c79322009-07-28 18:32:17 +00002850 unsigned NumUpdated = 0;
Galina Kistanovafc259902012-07-13 01:25:27 +00002851
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002852 // Keep track of whether all the values in the array are "ToC".
2853 bool AllSame = true;
Pete Cooper74510a42015-06-12 17:48:05 +00002854 Use *OperandList = getOperandList();
Mehdi Amini8914d292016-02-10 22:47:15 +00002855 unsigned OperandNo = 0;
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002856 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2857 Constant *Val = cast<Constant>(O->get());
2858 if (Val == From) {
Mehdi Amini8914d292016-02-10 22:47:15 +00002859 OperandNo = (O - OperandList);
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002860 Val = ToC;
2861 ++NumUpdated;
Owen Andersonc2c79322009-07-28 18:32:17 +00002862 }
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002863 Values.push_back(Val);
Talin46e9b442012-02-05 20:54:10 +00002864 AllSame &= Val == ToC;
Owen Andersonc2c79322009-07-28 18:32:17 +00002865 }
Galina Kistanovafc259902012-07-13 01:25:27 +00002866
Pete Cooper5815b1f2015-06-24 18:55:24 +00002867 if (AllSame && ToC->isNullValue())
2868 return ConstantAggregateZero::get(getType());
2869
2870 if (AllSame && isa<UndefValue>(ToC))
2871 return UndefValue::get(getType());
Aaron Ballmane4b91dc2014-08-19 14:59:02 +00002872
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002873 // Check for any other type of constant-folding.
Pete Cooper5815b1f2015-06-24 18:55:24 +00002874 if (Constant *C = getImpl(getType(), Values))
2875 return C;
Aaron Ballmane4b91dc2014-08-19 14:59:02 +00002876
Duncan P. N. Exon Smith909620a2014-08-19 19:13:30 +00002877 // Update to the new value.
Pete Cooper5815b1f2015-06-24 18:55:24 +00002878 return getContext().pImpl->ArrayConstants.replaceOperandsInPlace(
Mehdi Amini8914d292016-02-10 22:47:15 +00002879 Values, this, From, ToC, NumUpdated, OperandNo);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002880}
2881
Mehdi Amini8914d292016-02-10 22:47:15 +00002882Value *ConstantStruct::handleOperandChangeImpl(Value *From, Value *To) {
Owen Anderson45308b52009-07-27 22:29:26 +00002883 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2884 Constant *ToC = cast<Constant>(To);
2885
Pete Cooper74510a42015-06-12 17:48:05 +00002886 Use *OperandList = getOperandList();
Owen Anderson45308b52009-07-27 22:29:26 +00002887
Talin46e9b442012-02-05 20:54:10 +00002888 SmallVector<Constant*, 8> Values;
Owen Anderson45308b52009-07-27 22:29:26 +00002889 Values.reserve(getNumOperands()); // Build replacement struct.
Galina Kistanovafc259902012-07-13 01:25:27 +00002890
2891 // Fill values with the modified operands of the constant struct. Also,
Owen Anderson45308b52009-07-27 22:29:26 +00002892 // compute whether this turns into an all-zeros struct.
Mehdi Amini8914d292016-02-10 22:47:15 +00002893 unsigned NumUpdated = 0;
2894 bool AllSame = true;
2895 unsigned OperandNo = 0;
2896 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O) {
2897 Constant *Val = cast<Constant>(O->get());
2898 if (Val == From) {
2899 OperandNo = (O - OperandList);
2900 Val = ToC;
2901 ++NumUpdated;
Owen Anderson45308b52009-07-27 22:29:26 +00002902 }
Mehdi Amini8914d292016-02-10 22:47:15 +00002903 Values.push_back(Val);
2904 AllSame &= Val == ToC;
Owen Anderson45308b52009-07-27 22:29:26 +00002905 }
Galina Kistanovafc259902012-07-13 01:25:27 +00002906
Mehdi Amini8914d292016-02-10 22:47:15 +00002907 if (AllSame && ToC->isNullValue())
Pete Cooper5815b1f2015-06-24 18:55:24 +00002908 return ConstantAggregateZero::get(getType());
2909
Mehdi Amini8914d292016-02-10 22:47:15 +00002910 if (AllSame && isa<UndefValue>(ToC))
Pete Cooper5815b1f2015-06-24 18:55:24 +00002911 return UndefValue::get(getType());
Galina Kistanovafc259902012-07-13 01:25:27 +00002912
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002913 // Update to the new value.
Pete Cooper5815b1f2015-06-24 18:55:24 +00002914 return getContext().pImpl->StructConstants.replaceOperandsInPlace(
Mehdi Amini8914d292016-02-10 22:47:15 +00002915 Values, this, From, ToC, NumUpdated, OperandNo);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002916}
2917
Mehdi Amini8914d292016-02-10 22:47:15 +00002918Value *ConstantVector::handleOperandChangeImpl(Value *From, Value *To) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002919 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002920 Constant *ToC = cast<Constant>(To);
Galina Kistanovafc259902012-07-13 01:25:27 +00002921
Chris Lattnera474bb22012-01-26 20:40:56 +00002922 SmallVector<Constant*, 8> Values;
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002923 Values.reserve(getNumOperands()); // Build replacement array...
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002924 unsigned NumUpdated = 0;
Mehdi Amini8914d292016-02-10 22:47:15 +00002925 unsigned OperandNo = 0;
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002926 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2927 Constant *Val = getOperand(i);
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002928 if (Val == From) {
Mehdi Amini8914d292016-02-10 22:47:15 +00002929 OperandNo = i;
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002930 ++NumUpdated;
2931 Val = ToC;
2932 }
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002933 Values.push_back(Val);
2934 }
Galina Kistanovafc259902012-07-13 01:25:27 +00002935
Pete Cooper5815b1f2015-06-24 18:55:24 +00002936 if (Constant *C = getImpl(Values))
2937 return C;
Duncan P. N. Exon Smith687744d2014-08-19 02:24:46 +00002938
Duncan P. N. Exon Smith909620a2014-08-19 19:13:30 +00002939 // Update to the new value.
Pete Cooper5815b1f2015-06-24 18:55:24 +00002940 return getContext().pImpl->VectorConstants.replaceOperandsInPlace(
Mehdi Amini8914d292016-02-10 22:47:15 +00002941 Values, this, From, ToC, NumUpdated, OperandNo);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002942}
2943
Mehdi Amini8914d292016-02-10 22:47:15 +00002944Value *ConstantExpr::handleOperandChangeImpl(Value *From, Value *ToV) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002945 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2946 Constant *To = cast<Constant>(ToV);
Galina Kistanovafc259902012-07-13 01:25:27 +00002947
Chris Lattner37e38352012-01-26 20:37:11 +00002948 SmallVector<Constant*, 8> NewOps;
Duncan P. N. Exon Smith33de00c2014-08-19 20:03:35 +00002949 unsigned NumUpdated = 0;
Mehdi Amini8914d292016-02-10 22:47:15 +00002950 unsigned OperandNo = 0;
Chris Lattner37e38352012-01-26 20:37:11 +00002951 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2952 Constant *Op = getOperand(i);
Duncan P. N. Exon Smith33de00c2014-08-19 20:03:35 +00002953 if (Op == From) {
Mehdi Amini8914d292016-02-10 22:47:15 +00002954 OperandNo = i;
Duncan P. N. Exon Smith33de00c2014-08-19 20:03:35 +00002955 ++NumUpdated;
2956 Op = To;
2957 }
2958 NewOps.push_back(Op);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002959 }
Duncan P. N. Exon Smith33de00c2014-08-19 20:03:35 +00002960 assert(NumUpdated && "I didn't contain From!");
Galina Kistanovafc259902012-07-13 01:25:27 +00002961
Pete Cooper5815b1f2015-06-24 18:55:24 +00002962 if (Constant *C = getWithOperands(NewOps, getType(), true))
2963 return C;
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002964
Duncan P. N. Exon Smith33de00c2014-08-19 20:03:35 +00002965 // Update to the new value.
Pete Cooper5815b1f2015-06-24 18:55:24 +00002966 return getContext().pImpl->ExprConstants.replaceOperandsInPlace(
Mehdi Amini8914d292016-02-10 22:47:15 +00002967 NewOps, this, From, To, NumUpdated, OperandNo);
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002968}
2969
James Molloyce545682012-11-17 17:56:30 +00002970Instruction *ConstantExpr::getAsInstruction() {
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00002971 SmallVector<Value *, 4> ValueOperands(op_begin(), op_end());
James Molloyce545682012-11-17 17:56:30 +00002972 ArrayRef<Value*> Ops(ValueOperands);
2973
2974 switch (getOpcode()) {
2975 case Instruction::Trunc:
2976 case Instruction::ZExt:
2977 case Instruction::SExt:
2978 case Instruction::FPTrunc:
2979 case Instruction::FPExt:
2980 case Instruction::UIToFP:
2981 case Instruction::SIToFP:
2982 case Instruction::FPToUI:
2983 case Instruction::FPToSI:
2984 case Instruction::PtrToInt:
2985 case Instruction::IntToPtr:
2986 case Instruction::BitCast:
Eli Bendersky157a97a2014-01-18 22:54:33 +00002987 case Instruction::AddrSpaceCast:
James Molloyce545682012-11-17 17:56:30 +00002988 return CastInst::Create((Instruction::CastOps)getOpcode(),
2989 Ops[0], getType());
2990 case Instruction::Select:
2991 return SelectInst::Create(Ops[0], Ops[1], Ops[2]);
2992 case Instruction::InsertElement:
2993 return InsertElementInst::Create(Ops[0], Ops[1], Ops[2]);
2994 case Instruction::ExtractElement:
2995 return ExtractElementInst::Create(Ops[0], Ops[1]);
2996 case Instruction::InsertValue:
2997 return InsertValueInst::Create(Ops[0], Ops[1], getIndices());
2998 case Instruction::ExtractValue:
2999 return ExtractValueInst::Create(Ops[0], getIndices());
3000 case Instruction::ShuffleVector:
3001 return new ShuffleVectorInst(Ops[0], Ops[1], Ops[2]);
3002
David Blaikie741c8f82015-03-14 01:53:18 +00003003 case Instruction::GetElementPtr: {
3004 const auto *GO = cast<GEPOperator>(this);
3005 if (GO->isInBounds())
3006 return GetElementPtrInst::CreateInBounds(GO->getSourceElementType(),
3007 Ops[0], Ops.slice(1));
3008 return GetElementPtrInst::Create(GO->getSourceElementType(), Ops[0],
3009 Ops.slice(1));
3010 }
James Molloyce545682012-11-17 17:56:30 +00003011 case Instruction::ICmp:
3012 case Instruction::FCmp:
3013 return CmpInst::Create((Instruction::OtherOps)getOpcode(),
Craig Topper1c3f2832015-12-15 06:11:33 +00003014 (CmpInst::Predicate)getPredicate(), Ops[0], Ops[1]);
James Molloyce545682012-11-17 17:56:30 +00003015
3016 default:
3017 assert(getNumOperands() == 2 && "Must be binary operator?");
3018 BinaryOperator *BO =
3019 BinaryOperator::Create((Instruction::BinaryOps)getOpcode(),
3020 Ops[0], Ops[1]);
3021 if (isa<OverflowingBinaryOperator>(BO)) {
3022 BO->setHasNoUnsignedWrap(SubclassOptionalData &
3023 OverflowingBinaryOperator::NoUnsignedWrap);
3024 BO->setHasNoSignedWrap(SubclassOptionalData &
3025 OverflowingBinaryOperator::NoSignedWrap);
3026 }
3027 if (isa<PossiblyExactOperator>(BO))
3028 BO->setIsExact(SubclassOptionalData & PossiblyExactOperator::IsExact);
3029 return BO;
3030 }
3031}