blob: 6a6820234a01fbccff9b49526273f14b12c6e6b7 [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"
19#include "llvm/ADT/StringExtras.h"
20#include "llvm/ADT/StringMap.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000021#include "llvm/IR/DerivedTypes.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000022#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/GlobalValue.h"
24#include "llvm/IR/Instructions.h"
25#include "llvm/IR/Module.h"
26#include "llvm/IR/Operator.h"
Bill Wendling6a462f12006-11-17 08:03:48 +000027#include "llvm/Support/Debug.h"
Torok Edwinccb29cd2009-07-11 13:10:19 +000028#include "llvm/Support/ErrorHandling.h"
Chris Lattner69edc982006-09-28 00:35:06 +000029#include "llvm/Support/ManagedStatic.h"
Bill Wendling6a462f12006-11-17 08:03:48 +000030#include "llvm/Support/MathExtras.h"
Chris Lattner78683a72009-08-23 04:02:03 +000031#include "llvm/Support/raw_ostream.h"
Chris Lattner2f7c9632001-06-06 20:29:01 +000032#include <algorithm>
Talin3a0a30d2011-02-28 23:53:27 +000033#include <cstdarg>
Chris Lattner189d19f2003-11-21 20:23:48 +000034using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000035
Chris Lattner2f7c9632001-06-06 20:29:01 +000036//===----------------------------------------------------------------------===//
Chris Lattner3462ae32001-12-03 22:26:30 +000037// Constant Class
Chris Lattner2f7c9632001-06-06 20:29:01 +000038//===----------------------------------------------------------------------===//
39
David Blaikiea379b1812011-12-20 02:50:00 +000040void Constant::anchor() { }
41
Duncan P. N. Exon Smithb6452792016-02-21 02:39:49 +000042void ConstantData::anchor() {}
43
Chris Lattnerac5fb562011-07-15 05:58:04 +000044bool Constant::isNegativeZeroValue() const {
45 // Floating point values have an explicit -0.0 value.
46 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
47 return CFP->isZero() && CFP->isNegative();
Galina Kistanovafc259902012-07-13 01:25:27 +000048
David Tweed5493fee2013-03-18 11:54:44 +000049 // Equivalent for a vector of -0.0's.
50 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
51 if (ConstantFP *SplatCFP = dyn_cast_or_null<ConstantFP>(CV->getSplatValue()))
52 if (SplatCFP && SplatCFP->isZero() && SplatCFP->isNegative())
53 return true;
54
Owen Anderson8e851302015-11-20 22:34:48 +000055 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
56 if (ConstantFP *SplatCFP = dyn_cast_or_null<ConstantFP>(CV->getSplatValue()))
57 if (SplatCFP && SplatCFP->isZero() && SplatCFP->isNegative())
58 return true;
59
David Tweed298e4192013-03-19 10:16:40 +000060 // We've already handled true FP case; any other FP vectors can't represent -0.0.
61 if (getType()->isFPOrFPVectorTy())
62 return false;
David Tweed5493fee2013-03-18 11:54:44 +000063
Chris Lattnerac5fb562011-07-15 05:58:04 +000064 // Otherwise, just use +0.0.
65 return isNullValue();
66}
67
Shuxin Yang9ca562e2013-01-09 00:53:25 +000068// Return true iff this constant is positive zero (floating point), negative
69// zero (floating point), or a null value.
Shuxin Yangf0537ab2013-01-09 00:13:41 +000070bool Constant::isZeroValue() const {
71 // Floating point values have an explicit -0.0 value.
72 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
73 return CFP->isZero();
74
Owen Anderson630077e2015-11-20 08:16:13 +000075 // Equivalent for a vector of -0.0's.
76 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
77 if (ConstantFP *SplatCFP = dyn_cast_or_null<ConstantFP>(CV->getSplatValue()))
78 if (SplatCFP && SplatCFP->isZero())
79 return true;
80
Owen Anderson8e851302015-11-20 22:34:48 +000081 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
82 if (ConstantFP *SplatCFP = dyn_cast_or_null<ConstantFP>(CV->getSplatValue()))
83 if (SplatCFP && SplatCFP->isZero())
84 return true;
85
Shuxin Yangf0537ab2013-01-09 00:13:41 +000086 // Otherwise, just use +0.0.
87 return isNullValue();
88}
89
Chris Lattnerbe6610c2011-07-15 06:14:08 +000090bool Constant::isNullValue() const {
91 // 0 is null.
92 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
93 return CI->isZero();
Galina Kistanovafc259902012-07-13 01:25:27 +000094
Chris Lattnerbe6610c2011-07-15 06:14:08 +000095 // +0.0 is null.
96 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
97 return CFP->isZero() && !CFP->isNegative();
98
David Majnemerf0f224d2015-11-11 21:57:16 +000099 // constant zero is zero for aggregates, cpnull is null for pointers, none for
100 // tokens.
101 return isa<ConstantAggregateZero>(this) || isa<ConstantPointerNull>(this) ||
102 isa<ConstantTokenNone>(this);
Chris Lattnerbe6610c2011-07-15 06:14:08 +0000103}
104
Nadav Rotem365af6f2011-08-24 20:18:38 +0000105bool Constant::isAllOnesValue() const {
106 // Check for -1 integers
107 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
108 return CI->isMinusOne();
109
110 // Check for FP which are bitcasted from -1 integers
111 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
112 return CFP->getValueAPF().bitcastToAPInt().isAllOnesValue();
113
Benjamin Kramer42d098e2011-11-14 19:12:20 +0000114 // Check for constant vectors which are splats of -1 values.
Nadav Rotem365af6f2011-08-24 20:18:38 +0000115 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
Benjamin Kramer42d098e2011-11-14 19:12:20 +0000116 if (Constant *Splat = CV->getSplatValue())
117 return Splat->isAllOnesValue();
Nadav Rotem365af6f2011-08-24 20:18:38 +0000118
Chris Lattnerf14a67f2012-01-26 02:31:22 +0000119 // Check for constant vectors which are splats of -1 values.
120 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
121 if (Constant *Splat = CV->getSplatValue())
122 return Splat->isAllOnesValue();
123
Nadav Rotem365af6f2011-08-24 20:18:38 +0000124 return false;
125}
Benjamin Kramer42d098e2011-11-14 19:12:20 +0000126
David Majnemer1a0bbc82014-08-16 09:23:42 +0000127bool Constant::isOneValue() const {
128 // Check for 1 integers
129 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
130 return CI->isOne();
131
132 // Check for FP which are bitcasted from 1 integers
133 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
134 return CFP->getValueAPF().bitcastToAPInt() == 1;
135
136 // Check for constant vectors which are splats of 1 values.
137 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
138 if (Constant *Splat = CV->getSplatValue())
139 return Splat->isOneValue();
140
141 // Check for constant vectors which are splats of 1 values.
142 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
143 if (Constant *Splat = CV->getSplatValue())
144 return Splat->isOneValue();
145
146 return false;
147}
148
David Majnemerbdeef602014-07-02 06:07:09 +0000149bool Constant::isMinSignedValue() const {
150 // Check for INT_MIN integers
151 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
152 return CI->isMinValue(/*isSigned=*/true);
153
154 // Check for FP which are bitcasted from INT_MIN integers
155 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
156 return CFP->getValueAPF().bitcastToAPInt().isMinSignedValue();
157
158 // Check for constant vectors which are splats of INT_MIN values.
159 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
160 if (Constant *Splat = CV->getSplatValue())
161 return Splat->isMinSignedValue();
162
163 // Check for constant vectors which are splats of INT_MIN values.
164 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
165 if (Constant *Splat = CV->getSplatValue())
166 return Splat->isMinSignedValue();
167
168 return false;
169}
170
David Majnemer0e6c9862014-08-22 16:41:23 +0000171bool Constant::isNotMinSignedValue() const {
172 // Check for INT_MIN integers
173 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
174 return !CI->isMinValue(/*isSigned=*/true);
175
176 // Check for FP which are bitcasted from INT_MIN integers
177 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
178 return !CFP->getValueAPF().bitcastToAPInt().isMinSignedValue();
179
180 // Check for constant vectors which are splats of INT_MIN values.
181 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
182 if (Constant *Splat = CV->getSplatValue())
183 return Splat->isNotMinSignedValue();
184
185 // Check for constant vectors which are splats of INT_MIN values.
186 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
187 if (Constant *Splat = CV->getSplatValue())
188 return Splat->isNotMinSignedValue();
189
190 // It *may* contain INT_MIN, we can't tell.
191 return false;
192}
193
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +0000194/// Constructor to create a '0' constant of arbitrary type.
Chris Lattner229907c2011-07-18 04:54:35 +0000195Constant *Constant::getNullValue(Type *Ty) {
Owen Anderson5a1acd92009-07-31 20:28:14 +0000196 switch (Ty->getTypeID()) {
197 case Type::IntegerTyID:
198 return ConstantInt::get(Ty, 0);
Dan Gohman518cda42011-12-17 00:04:22 +0000199 case Type::HalfTyID:
200 return ConstantFP::get(Ty->getContext(),
201 APFloat::getZero(APFloat::IEEEhalf));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000202 case Type::FloatTyID:
Benjamin Kramer8ceebfa2010-12-04 14:22:24 +0000203 return ConstantFP::get(Ty->getContext(),
204 APFloat::getZero(APFloat::IEEEsingle));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000205 case Type::DoubleTyID:
Benjamin Kramer8ceebfa2010-12-04 14:22:24 +0000206 return ConstantFP::get(Ty->getContext(),
207 APFloat::getZero(APFloat::IEEEdouble));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000208 case Type::X86_FP80TyID:
Benjamin Kramer8ceebfa2010-12-04 14:22:24 +0000209 return ConstantFP::get(Ty->getContext(),
210 APFloat::getZero(APFloat::x87DoubleExtended));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000211 case Type::FP128TyID:
212 return ConstantFP::get(Ty->getContext(),
Benjamin Kramer8ceebfa2010-12-04 14:22:24 +0000213 APFloat::getZero(APFloat::IEEEquad));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000214 case Type::PPC_FP128TyID:
Benjamin Kramer8ceebfa2010-12-04 14:22:24 +0000215 return ConstantFP::get(Ty->getContext(),
Tim Northover29178a32013-01-22 09:46:31 +0000216 APFloat(APFloat::PPCDoubleDouble,
217 APInt::getNullValue(128)));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000218 case Type::PointerTyID:
219 return ConstantPointerNull::get(cast<PointerType>(Ty));
220 case Type::StructTyID:
221 case Type::ArrayTyID:
222 case Type::VectorTyID:
223 return ConstantAggregateZero::get(Ty);
David Majnemerf0f224d2015-11-11 21:57:16 +0000224 case Type::TokenTyID:
225 return ConstantTokenNone::get(Ty->getContext());
Owen Anderson5a1acd92009-07-31 20:28:14 +0000226 default:
227 // Function, Label, or Opaque type?
Craig Topperc514b542012-02-05 22:14:15 +0000228 llvm_unreachable("Cannot create a null constant of that type!");
Owen Anderson5a1acd92009-07-31 20:28:14 +0000229 }
230}
231
Chris Lattner229907c2011-07-18 04:54:35 +0000232Constant *Constant::getIntegerValue(Type *Ty, const APInt &V) {
233 Type *ScalarTy = Ty->getScalarType();
Dan Gohmanf011f5a2009-08-03 22:07:33 +0000234
235 // Create the base integer constant.
236 Constant *C = ConstantInt::get(Ty->getContext(), V);
237
238 // Convert an integer to a pointer, if necessary.
Chris Lattner229907c2011-07-18 04:54:35 +0000239 if (PointerType *PTy = dyn_cast<PointerType>(ScalarTy))
Dan Gohmanf011f5a2009-08-03 22:07:33 +0000240 C = ConstantExpr::getIntToPtr(C, PTy);
241
242 // Broadcast a scalar to a vector, if necessary.
Chris Lattner229907c2011-07-18 04:54:35 +0000243 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattnere9eed292012-01-25 05:19:54 +0000244 C = ConstantVector::getSplat(VTy->getNumElements(), C);
Dan Gohmanf011f5a2009-08-03 22:07:33 +0000245
246 return C;
247}
248
Chris Lattner229907c2011-07-18 04:54:35 +0000249Constant *Constant::getAllOnesValue(Type *Ty) {
250 if (IntegerType *ITy = dyn_cast<IntegerType>(Ty))
Owen Anderson5a1acd92009-07-31 20:28:14 +0000251 return ConstantInt::get(Ty->getContext(),
252 APInt::getAllOnesValue(ITy->getBitWidth()));
Nadav Rotem7cc6d122011-02-17 21:22:27 +0000253
254 if (Ty->isFloatingPointTy()) {
255 APFloat FL = APFloat::getAllOnesValue(Ty->getPrimitiveSizeInBits(),
256 !Ty->isPPC_FP128Ty());
257 return ConstantFP::get(Ty->getContext(), FL);
258 }
259
Chris Lattner229907c2011-07-18 04:54:35 +0000260 VectorType *VTy = cast<VectorType>(Ty);
Chris Lattnere9eed292012-01-25 05:19:54 +0000261 return ConstantVector::getSplat(VTy->getNumElements(),
262 getAllOnesValue(VTy->getElementType()));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000263}
264
Chris Lattner7e683d12012-01-25 06:16:32 +0000265Constant *Constant::getAggregateElement(unsigned Elt) const {
Duncan P. N. Exon Smith1de3c7e2016-04-05 21:10:45 +0000266 if (const ConstantAggregate *CC = dyn_cast<ConstantAggregate>(this))
267 return Elt < CC->getNumOperands() ? CC->getOperand(Elt) : nullptr;
Galina Kistanovafc259902012-07-13 01:25:27 +0000268
David Majnemer9b529a72015-02-16 04:02:09 +0000269 if (const ConstantAggregateZero *CAZ = dyn_cast<ConstantAggregateZero>(this))
270 return Elt < CAZ->getNumElements() ? CAZ->getElementValue(Elt) : nullptr;
Galina Kistanovafc259902012-07-13 01:25:27 +0000271
Chris Lattner7e683d12012-01-25 06:16:32 +0000272 if (const UndefValue *UV = dyn_cast<UndefValue>(this))
David Majnemer9b529a72015-02-16 04:02:09 +0000273 return Elt < UV->getNumElements() ? UV->getElementValue(Elt) : nullptr;
Galina Kistanovafc259902012-07-13 01:25:27 +0000274
Chris Lattner8326bd82012-01-26 00:42:34 +0000275 if (const ConstantDataSequential *CDS =dyn_cast<ConstantDataSequential>(this))
Craig Topperc6207612014-04-09 06:08:46 +0000276 return Elt < CDS->getNumElements() ? CDS->getElementAsConstant(Elt)
277 : nullptr;
278 return nullptr;
Chris Lattner7e683d12012-01-25 06:16:32 +0000279}
280
281Constant *Constant::getAggregateElement(Constant *Elt) const {
282 assert(isa<IntegerType>(Elt->getType()) && "Index must be an integer");
283 if (ConstantInt *CI = dyn_cast<ConstantInt>(Elt))
284 return getAggregateElement(CI->getZExtValue());
Craig Topperc6207612014-04-09 06:08:46 +0000285 return nullptr;
Chris Lattner7e683d12012-01-25 06:16:32 +0000286}
287
Pete Cooper86dd4cf2015-06-23 21:55:11 +0000288void Constant::destroyConstant() {
289 /// First call destroyConstantImpl on the subclass. This gives the subclass
290 /// a chance to remove the constant from any maps/pools it's contained in.
291 switch (getValueID()) {
292 default:
293 llvm_unreachable("Not a constant!");
294#define HANDLE_CONSTANT(Name) \
295 case Value::Name##Val: \
296 cast<Name>(this)->destroyConstantImpl(); \
297 break;
298#include "llvm/IR/Value.def"
299 }
Chris Lattner7e683d12012-01-25 06:16:32 +0000300
Chris Lattner3462ae32001-12-03 22:26:30 +0000301 // When a Constant is destroyed, there may be lingering
Chris Lattnerd7a73302001-10-13 06:57:33 +0000302 // references to the constant by other constants in the constant pool. These
Misha Brukmanbe372b92003-08-21 22:14:26 +0000303 // constants are implicitly dependent on the module that is being deleted,
Chris Lattnerd7a73302001-10-13 06:57:33 +0000304 // but they don't know that. Because we only find out when the CPV is
305 // deleted, we must now notify all of our users (that should only be
Chris Lattner3462ae32001-12-03 22:26:30 +0000306 // Constants) that they are, in fact, invalid now and should be deleted.
Chris Lattnerd7a73302001-10-13 06:57:33 +0000307 //
308 while (!use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000309 Value *V = user_back();
Pete Cooper86dd4cf2015-06-23 21:55:11 +0000310#ifndef NDEBUG // Only in -g mode...
Chris Lattner78683a72009-08-23 04:02:03 +0000311 if (!isa<Constant>(V)) {
David Greene1e27a132010-01-05 01:29:19 +0000312 dbgs() << "While deleting: " << *this
Pete Cooper86dd4cf2015-06-23 21:55:11 +0000313 << "\n\nUse still stuck around after Def is destroyed: " << *V
314 << "\n\n";
Chris Lattner78683a72009-08-23 04:02:03 +0000315 }
Chris Lattnerd7a73302001-10-13 06:57:33 +0000316#endif
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000317 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
Chris Lattner8326bd82012-01-26 00:42:34 +0000318 cast<Constant>(V)->destroyConstant();
Chris Lattnerd7a73302001-10-13 06:57:33 +0000319
320 // The constant should remove itself from our use list...
Chandler Carruthcdf47882014-03-09 03:16:01 +0000321 assert((use_empty() || user_back() != V) && "Constant not removed!");
Chris Lattnerd7a73302001-10-13 06:57:33 +0000322 }
323
324 // Value has no outstanding references it is safe to delete it now...
325 delete this;
Chris Lattner38569342001-10-01 20:11:19 +0000326}
Chris Lattner2f7c9632001-06-06 20:29:01 +0000327
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000328static bool canTrapImpl(const Constant *C,
Craig Topper71b7b682014-08-21 05:55:13 +0000329 SmallPtrSetImpl<const ConstantExpr *> &NonTrappingOps) {
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000330 assert(C->getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
Chris Lattner23dd1f62006-10-20 00:27:06 +0000331 // The only thing that could possibly trap are constant exprs.
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000332 const ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
333 if (!CE)
334 return false;
Galina Kistanovafc259902012-07-13 01:25:27 +0000335
336 // ConstantExpr traps if any operands can trap.
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000337 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
338 if (ConstantExpr *Op = dyn_cast<ConstantExpr>(CE->getOperand(i))) {
David Blaikie70573dc2014-11-19 07:49:26 +0000339 if (NonTrappingOps.insert(Op).second && canTrapImpl(Op, NonTrappingOps))
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000340 return true;
341 }
342 }
Chris Lattner23dd1f62006-10-20 00:27:06 +0000343
344 // Otherwise, only specific operations can trap.
345 switch (CE->getOpcode()) {
346 default:
347 return false;
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000348 case Instruction::UDiv:
349 case Instruction::SDiv:
Reid Spencer7eb55b32006-11-02 01:53:59 +0000350 case Instruction::URem:
351 case Instruction::SRem:
Chris Lattner23dd1f62006-10-20 00:27:06 +0000352 // Div and rem can trap if the RHS is not known to be non-zero.
Chris Lattnera91a5632009-10-28 05:14:34 +0000353 if (!isa<ConstantInt>(CE->getOperand(1)) ||CE->getOperand(1)->isNullValue())
Chris Lattner23dd1f62006-10-20 00:27:06 +0000354 return true;
355 return false;
356 }
357}
358
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000359bool Constant::canTrap() const {
360 SmallPtrSet<const ConstantExpr *, 4> NonTrappingOps;
361 return canTrapImpl(this, NonTrappingOps);
362}
363
Hans Wennborg4dc89512014-06-20 00:38:12 +0000364/// Check if C contains a GlobalValue for which Predicate is true.
365static bool
366ConstHasGlobalValuePredicate(const Constant *C,
367 bool (*Predicate)(const GlobalValue *)) {
368 SmallPtrSet<const Constant *, 8> Visited;
369 SmallVector<const Constant *, 8> WorkList;
370 WorkList.push_back(C);
371 Visited.insert(C);
Hans Wennborg709e0152012-11-15 11:40:00 +0000372
373 while (!WorkList.empty()) {
Hans Wennborg4dc89512014-06-20 00:38:12 +0000374 const Constant *WorkItem = WorkList.pop_back_val();
375 if (const auto *GV = dyn_cast<GlobalValue>(WorkItem))
376 if (Predicate(GV))
Hans Wennborg709e0152012-11-15 11:40:00 +0000377 return true;
Hans Wennborg4dc89512014-06-20 00:38:12 +0000378 for (const Value *Op : WorkItem->operands()) {
379 const Constant *ConstOp = dyn_cast<Constant>(Op);
380 if (!ConstOp)
Hans Wennborg18aa12402012-11-16 10:33:25 +0000381 continue;
David Blaikie70573dc2014-11-19 07:49:26 +0000382 if (Visited.insert(ConstOp).second)
Hans Wennborg4dc89512014-06-20 00:38:12 +0000383 WorkList.push_back(ConstOp);
Hans Wennborg709e0152012-11-15 11:40:00 +0000384 }
385 }
Hans Wennborg709e0152012-11-15 11:40:00 +0000386 return false;
387}
388
Hans Wennborg4dc89512014-06-20 00:38:12 +0000389bool Constant::isThreadDependent() const {
390 auto DLLImportPredicate = [](const GlobalValue *GV) {
391 return GV->isThreadLocal();
392 };
393 return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
394}
395
396bool Constant::isDLLImportDependent() const {
397 auto DLLImportPredicate = [](const GlobalValue *GV) {
398 return GV->hasDLLImportStorageClass();
399 };
400 return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
401}
402
Chris Lattner253bc772009-11-01 18:11:50 +0000403bool Constant::isConstantUsed() const {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000404 for (const User *U : users()) {
405 const Constant *UC = dyn_cast<Constant>(U);
Craig Topperc6207612014-04-09 06:08:46 +0000406 if (!UC || isa<GlobalValue>(UC))
Chris Lattner253bc772009-11-01 18:11:50 +0000407 return true;
Galina Kistanovafc259902012-07-13 01:25:27 +0000408
Chris Lattner253bc772009-11-01 18:11:50 +0000409 if (UC->isConstantUsed())
410 return true;
411 }
412 return false;
413}
414
Rafael Espindola65e49022015-11-17 00:51:23 +0000415bool Constant::needsRelocation() const {
416 if (isa<GlobalValue>(this))
417 return true; // Global reference.
418
Chris Lattner2cb85b42009-10-28 04:12:16 +0000419 if (const BlockAddress *BA = dyn_cast<BlockAddress>(this))
Rafael Espindola65e49022015-11-17 00:51:23 +0000420 return BA->getFunction()->needsRelocation();
421
Chris Lattnera7cfc432010-01-03 18:09:40 +0000422 // While raw uses of blockaddress need to be relocated, differences between
423 // two of them don't when they are for labels in the same function. This is a
424 // common idiom when creating a table for the indirect goto extension, so we
425 // handle it efficiently here.
426 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(this))
427 if (CE->getOpcode() == Instruction::Sub) {
428 ConstantExpr *LHS = dyn_cast<ConstantExpr>(CE->getOperand(0));
429 ConstantExpr *RHS = dyn_cast<ConstantExpr>(CE->getOperand(1));
Rafael Espindola65e49022015-11-17 00:51:23 +0000430 if (LHS && RHS && LHS->getOpcode() == Instruction::PtrToInt &&
Chris Lattnera7cfc432010-01-03 18:09:40 +0000431 RHS->getOpcode() == Instruction::PtrToInt &&
432 isa<BlockAddress>(LHS->getOperand(0)) &&
433 isa<BlockAddress>(RHS->getOperand(0)) &&
434 cast<BlockAddress>(LHS->getOperand(0))->getFunction() ==
Rafael Espindola65e49022015-11-17 00:51:23 +0000435 cast<BlockAddress>(RHS->getOperand(0))->getFunction())
436 return false;
Chris Lattnera7cfc432010-01-03 18:09:40 +0000437 }
Galina Kistanovafc259902012-07-13 01:25:27 +0000438
Rafael Espindola65e49022015-11-17 00:51:23 +0000439 bool Result = false;
Evan Chengf9e003b2007-03-08 00:59:12 +0000440 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
Rafael Espindola65e49022015-11-17 00:51:23 +0000441 Result |= cast<Constant>(getOperand(i))->needsRelocation();
Galina Kistanovafc259902012-07-13 01:25:27 +0000442
Chris Lattner4565ef52009-07-22 00:05:44 +0000443 return Result;
Evan Chengf9e003b2007-03-08 00:59:12 +0000444}
445
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +0000446/// If the specified constantexpr is dead, remove it. This involves recursively
447/// eliminating any dead users of the constantexpr.
Chris Lattner84886402011-02-18 04:41:42 +0000448static bool removeDeadUsersOfConstant(const Constant *C) {
449 if (isa<GlobalValue>(C)) return false; // Cannot remove this
Galina Kistanovafc259902012-07-13 01:25:27 +0000450
Chris Lattner84886402011-02-18 04:41:42 +0000451 while (!C->use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000452 const Constant *User = dyn_cast<Constant>(C->user_back());
Chris Lattner84886402011-02-18 04:41:42 +0000453 if (!User) return false; // Non-constant usage;
454 if (!removeDeadUsersOfConstant(User))
455 return false; // Constant wasn't dead
456 }
Galina Kistanovafc259902012-07-13 01:25:27 +0000457
Chris Lattner84886402011-02-18 04:41:42 +0000458 const_cast<Constant*>(C)->destroyConstant();
459 return true;
460}
461
462
Chris Lattner84886402011-02-18 04:41:42 +0000463void Constant::removeDeadConstantUsers() const {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000464 Value::const_user_iterator I = user_begin(), E = user_end();
465 Value::const_user_iterator LastNonDeadUser = E;
Chris Lattner84886402011-02-18 04:41:42 +0000466 while (I != E) {
467 const Constant *User = dyn_cast<Constant>(*I);
Craig Topperc6207612014-04-09 06:08:46 +0000468 if (!User) {
Chris Lattner84886402011-02-18 04:41:42 +0000469 LastNonDeadUser = I;
470 ++I;
471 continue;
472 }
Galina Kistanovafc259902012-07-13 01:25:27 +0000473
Chris Lattner84886402011-02-18 04:41:42 +0000474 if (!removeDeadUsersOfConstant(User)) {
475 // If the constant wasn't dead, remember that this was the last live use
476 // and move on to the next constant.
477 LastNonDeadUser = I;
478 ++I;
479 continue;
480 }
Galina Kistanovafc259902012-07-13 01:25:27 +0000481
Chris Lattner84886402011-02-18 04:41:42 +0000482 // If the constant was dead, then the iterator is invalidated.
483 if (LastNonDeadUser == E) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000484 I = user_begin();
Chris Lattner84886402011-02-18 04:41:42 +0000485 if (I == E) break;
486 } else {
487 I = LastNonDeadUser;
488 ++I;
489 }
490 }
491}
492
493
Chris Lattner2105d662008-07-10 00:28:11 +0000494
Chris Lattner2f7c9632001-06-06 20:29:01 +0000495//===----------------------------------------------------------------------===//
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000496// ConstantInt
Chris Lattner2f7c9632001-06-06 20:29:01 +0000497//===----------------------------------------------------------------------===//
498
David Blaikiea379b1812011-12-20 02:50:00 +0000499void ConstantInt::anchor() { }
500
Duncan P. N. Exon Smithb6452792016-02-21 02:39:49 +0000501ConstantInt::ConstantInt(IntegerType *Ty, const APInt &V)
502 : ConstantData(Ty, ConstantIntVal), Val(V) {
Reid Spencerb31bffe2007-02-26 23:54:03 +0000503 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
Chris Lattner2f7c9632001-06-06 20:29:01 +0000504}
505
Nick Lewycky92db8e82011-03-06 03:36:19 +0000506ConstantInt *ConstantInt::getTrue(LLVMContext &Context) {
Owen Anderson23a204d2009-07-31 17:39:07 +0000507 LLVMContextImpl *pImpl = Context.pImpl;
Benjamin Kramerddd1b7b2010-11-20 18:43:35 +0000508 if (!pImpl->TheTrueVal)
509 pImpl->TheTrueVal = ConstantInt::get(Type::getInt1Ty(Context), 1);
510 return pImpl->TheTrueVal;
Owen Anderson23a204d2009-07-31 17:39:07 +0000511}
512
Nick Lewycky92db8e82011-03-06 03:36:19 +0000513ConstantInt *ConstantInt::getFalse(LLVMContext &Context) {
Owen Anderson23a204d2009-07-31 17:39:07 +0000514 LLVMContextImpl *pImpl = Context.pImpl;
Benjamin Kramerddd1b7b2010-11-20 18:43:35 +0000515 if (!pImpl->TheFalseVal)
516 pImpl->TheFalseVal = ConstantInt::get(Type::getInt1Ty(Context), 0);
517 return pImpl->TheFalseVal;
Owen Anderson23a204d2009-07-31 17:39:07 +0000518}
519
Chris Lattner229907c2011-07-18 04:54:35 +0000520Constant *ConstantInt::getTrue(Type *Ty) {
521 VectorType *VTy = dyn_cast<VectorType>(Ty);
Nick Lewycky92db8e82011-03-06 03:36:19 +0000522 if (!VTy) {
523 assert(Ty->isIntegerTy(1) && "True must be i1 or vector of i1.");
524 return ConstantInt::getTrue(Ty->getContext());
525 }
526 assert(VTy->getElementType()->isIntegerTy(1) &&
527 "True must be vector of i1 or i1.");
Chris Lattnere9eed292012-01-25 05:19:54 +0000528 return ConstantVector::getSplat(VTy->getNumElements(),
529 ConstantInt::getTrue(Ty->getContext()));
Nick Lewycky92db8e82011-03-06 03:36:19 +0000530}
531
Chris Lattner229907c2011-07-18 04:54:35 +0000532Constant *ConstantInt::getFalse(Type *Ty) {
533 VectorType *VTy = dyn_cast<VectorType>(Ty);
Nick Lewycky92db8e82011-03-06 03:36:19 +0000534 if (!VTy) {
535 assert(Ty->isIntegerTy(1) && "False must be i1 or vector of i1.");
536 return ConstantInt::getFalse(Ty->getContext());
537 }
538 assert(VTy->getElementType()->isIntegerTy(1) &&
539 "False must be vector of i1 or i1.");
Chris Lattnere9eed292012-01-25 05:19:54 +0000540 return ConstantVector::getSplat(VTy->getNumElements(),
541 ConstantInt::getFalse(Ty->getContext()));
Nick Lewycky92db8e82011-03-06 03:36:19 +0000542}
543
Benjamin Kramer8e5dc532014-12-06 13:12:56 +0000544// Get a ConstantInt from an APInt.
Nick Lewycky92db8e82011-03-06 03:36:19 +0000545ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt &V) {
Owen Andersonedb4a702009-07-24 23:12:02 +0000546 // get an existing value or the insertion position
Benjamin Kramer320682f2013-06-01 17:51:03 +0000547 LLVMContextImpl *pImpl = Context.pImpl;
Justin Lebar611c5c22016-10-10 16:26:13 +0000548 std::unique_ptr<ConstantInt> &Slot = pImpl->IntConstants[V];
Benjamin Kramer8e5dc532014-12-06 13:12:56 +0000549 if (!Slot) {
550 // Get the corresponding integer type for the bit width of the value.
551 IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
Justin Lebar611c5c22016-10-10 16:26:13 +0000552 Slot.reset(new ConstantInt(ITy, V));
Benjamin Kramer8e5dc532014-12-06 13:12:56 +0000553 }
554 assert(Slot->getType() == IntegerType::get(Context, V.getBitWidth()));
Justin Lebar611c5c22016-10-10 16:26:13 +0000555 return Slot.get();
Owen Andersonedb4a702009-07-24 23:12:02 +0000556}
557
Chris Lattner229907c2011-07-18 04:54:35 +0000558Constant *ConstantInt::get(Type *Ty, uint64_t V, bool isSigned) {
Nick Lewycky92db8e82011-03-06 03:36:19 +0000559 Constant *C = get(cast<IntegerType>(Ty->getScalarType()), V, isSigned);
Owen Andersonedb4a702009-07-24 23:12:02 +0000560
561 // For vectors, broadcast the value.
Chris Lattner229907c2011-07-18 04:54:35 +0000562 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattnere9eed292012-01-25 05:19:54 +0000563 return ConstantVector::getSplat(VTy->getNumElements(), C);
Owen Andersonedb4a702009-07-24 23:12:02 +0000564
565 return C;
566}
567
Sanjay Patelf3587ec2016-05-18 22:05:28 +0000568ConstantInt *ConstantInt::get(IntegerType *Ty, uint64_t V, bool isSigned) {
Owen Andersonedb4a702009-07-24 23:12:02 +0000569 return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned));
570}
571
Chris Lattner0256be92012-01-27 03:08:05 +0000572ConstantInt *ConstantInt::getSigned(IntegerType *Ty, int64_t V) {
Owen Andersonedb4a702009-07-24 23:12:02 +0000573 return get(Ty, V, true);
574}
575
Chris Lattner229907c2011-07-18 04:54:35 +0000576Constant *ConstantInt::getSigned(Type *Ty, int64_t V) {
Owen Andersonedb4a702009-07-24 23:12:02 +0000577 return get(Ty, V, true);
578}
579
Chris Lattner0256be92012-01-27 03:08:05 +0000580Constant *ConstantInt::get(Type *Ty, const APInt& V) {
Owen Andersonedb4a702009-07-24 23:12:02 +0000581 ConstantInt *C = get(Ty->getContext(), V);
582 assert(C->getType() == Ty->getScalarType() &&
583 "ConstantInt type doesn't match the type implied by its value!");
584
585 // For vectors, broadcast the value.
Chris Lattner229907c2011-07-18 04:54:35 +0000586 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattnere9eed292012-01-25 05:19:54 +0000587 return ConstantVector::getSplat(VTy->getNumElements(), C);
Owen Andersonedb4a702009-07-24 23:12:02 +0000588
589 return C;
590}
591
Sanjay Patelf3587ec2016-05-18 22:05:28 +0000592ConstantInt *ConstantInt::get(IntegerType* Ty, StringRef Str, uint8_t radix) {
Erick Tryzelaarfc2280d2009-08-16 23:36:33 +0000593 return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
594}
595
Pete Cooper86dd4cf2015-06-23 21:55:11 +0000596/// Remove the constant from the constant table.
597void ConstantInt::destroyConstantImpl() {
598 llvm_unreachable("You can't ConstantInt->destroyConstantImpl()!");
599}
600
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000601//===----------------------------------------------------------------------===//
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000602// ConstantFP
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000603//===----------------------------------------------------------------------===//
604
Chris Lattner229907c2011-07-18 04:54:35 +0000605static const fltSemantics *TypeToFloatSemantics(Type *Ty) {
Dan Gohman518cda42011-12-17 00:04:22 +0000606 if (Ty->isHalfTy())
607 return &APFloat::IEEEhalf;
Chris Lattnerfdd87902009-10-05 05:54:46 +0000608 if (Ty->isFloatTy())
Rafael Espindolaf5d53d42009-07-15 17:40:42 +0000609 return &APFloat::IEEEsingle;
Chris Lattnerfdd87902009-10-05 05:54:46 +0000610 if (Ty->isDoubleTy())
Rafael Espindolaf5d53d42009-07-15 17:40:42 +0000611 return &APFloat::IEEEdouble;
Chris Lattnerfdd87902009-10-05 05:54:46 +0000612 if (Ty->isX86_FP80Ty())
Rafael Espindolaf5d53d42009-07-15 17:40:42 +0000613 return &APFloat::x87DoubleExtended;
Chris Lattnerfdd87902009-10-05 05:54:46 +0000614 else if (Ty->isFP128Ty())
Rafael Espindolaf5d53d42009-07-15 17:40:42 +0000615 return &APFloat::IEEEquad;
Galina Kistanovafc259902012-07-13 01:25:27 +0000616
Chris Lattnerfdd87902009-10-05 05:54:46 +0000617 assert(Ty->isPPC_FP128Ty() && "Unknown FP format");
Rafael Espindolaf5d53d42009-07-15 17:40:42 +0000618 return &APFloat::PPCDoubleDouble;
619}
620
David Blaikiea379b1812011-12-20 02:50:00 +0000621void ConstantFP::anchor() { }
622
Chris Lattner0256be92012-01-27 03:08:05 +0000623Constant *ConstantFP::get(Type *Ty, double V) {
Owen Anderson69c464d2009-07-27 20:59:43 +0000624 LLVMContext &Context = Ty->getContext();
Galina Kistanovafc259902012-07-13 01:25:27 +0000625
Owen Anderson69c464d2009-07-27 20:59:43 +0000626 APFloat FV(V);
627 bool ignored;
628 FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
629 APFloat::rmNearestTiesToEven, &ignored);
630 Constant *C = get(Context, FV);
631
632 // For vectors, broadcast the value.
Chris Lattner229907c2011-07-18 04:54:35 +0000633 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattnere9eed292012-01-25 05:19:54 +0000634 return ConstantVector::getSplat(VTy->getNumElements(), C);
Owen Anderson69c464d2009-07-27 20:59:43 +0000635
636 return C;
637}
638
Erick Tryzelaarfc2280d2009-08-16 23:36:33 +0000639
Chris Lattner0256be92012-01-27 03:08:05 +0000640Constant *ConstantFP::get(Type *Ty, StringRef Str) {
Erick Tryzelaarfc2280d2009-08-16 23:36:33 +0000641 LLVMContext &Context = Ty->getContext();
642
643 APFloat FV(*TypeToFloatSemantics(Ty->getScalarType()), Str);
644 Constant *C = get(Context, FV);
645
646 // For vectors, broadcast the value.
Chris Lattner229907c2011-07-18 04:54:35 +0000647 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattnere9eed292012-01-25 05:19:54 +0000648 return ConstantVector::getSplat(VTy->getNumElements(), C);
Erick Tryzelaarfc2280d2009-08-16 23:36:33 +0000649
650 return C;
651}
652
Tom Stellard67246d12015-04-20 19:38:24 +0000653Constant *ConstantFP::getNaN(Type *Ty, bool Negative, unsigned Type) {
654 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
655 APFloat NaN = APFloat::getNaN(Semantics, Negative, Type);
656 Constant *C = get(Ty->getContext(), NaN);
657
658 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
659 return ConstantVector::getSplat(VTy->getNumElements(), C);
660
661 return C;
662}
663
Benjamin Kramer5d2ff222014-01-18 16:43:06 +0000664Constant *ConstantFP::getNegativeZero(Type *Ty) {
665 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
666 APFloat NegZero = APFloat::getZero(Semantics, /*Negative=*/true);
667 Constant *C = get(Ty->getContext(), NegZero);
Erick Tryzelaarfc2280d2009-08-16 23:36:33 +0000668
Benjamin Kramer5d2ff222014-01-18 16:43:06 +0000669 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
670 return ConstantVector::getSplat(VTy->getNumElements(), C);
671
672 return C;
Owen Anderson69c464d2009-07-27 20:59:43 +0000673}
674
675
Chris Lattnere9eed292012-01-25 05:19:54 +0000676Constant *ConstantFP::getZeroValueForNegation(Type *Ty) {
Benjamin Kramer5d2ff222014-01-18 16:43:06 +0000677 if (Ty->isFPOrFPVectorTy())
678 return getNegativeZero(Ty);
Owen Anderson69c464d2009-07-27 20:59:43 +0000679
Owen Anderson5a1acd92009-07-31 20:28:14 +0000680 return Constant::getNullValue(Ty);
Owen Anderson69c464d2009-07-27 20:59:43 +0000681}
682
683
684// ConstantFP accessors.
685ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
Owen Anderson69c464d2009-07-27 20:59:43 +0000686 LLVMContextImpl* pImpl = Context.pImpl;
Galina Kistanovafc259902012-07-13 01:25:27 +0000687
Justin Lebar611c5c22016-10-10 16:26:13 +0000688 std::unique_ptr<ConstantFP> &Slot = pImpl->FPConstants[V];
Galina Kistanovafc259902012-07-13 01:25:27 +0000689
Owen Anderson69c464d2009-07-27 20:59:43 +0000690 if (!Slot) {
Chris Lattner229907c2011-07-18 04:54:35 +0000691 Type *Ty;
Dan Gohman518cda42011-12-17 00:04:22 +0000692 if (&V.getSemantics() == &APFloat::IEEEhalf)
693 Ty = Type::getHalfTy(Context);
694 else if (&V.getSemantics() == &APFloat::IEEEsingle)
Owen Anderson5dab84c2009-10-19 20:11:52 +0000695 Ty = Type::getFloatTy(Context);
696 else if (&V.getSemantics() == &APFloat::IEEEdouble)
697 Ty = Type::getDoubleTy(Context);
698 else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
699 Ty = Type::getX86_FP80Ty(Context);
700 else if (&V.getSemantics() == &APFloat::IEEEquad)
701 Ty = Type::getFP128Ty(Context);
702 else {
703 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble &&
704 "Unknown FP format");
705 Ty = Type::getPPC_FP128Ty(Context);
Owen Anderson69c464d2009-07-27 20:59:43 +0000706 }
Justin Lebar611c5c22016-10-10 16:26:13 +0000707 Slot.reset(new ConstantFP(Ty, V));
Owen Anderson69c464d2009-07-27 20:59:43 +0000708 }
Galina Kistanovafc259902012-07-13 01:25:27 +0000709
Justin Lebar611c5c22016-10-10 16:26:13 +0000710 return Slot.get();
Owen Anderson69c464d2009-07-27 20:59:43 +0000711}
712
Benjamin Kramer5d2ff222014-01-18 16:43:06 +0000713Constant *ConstantFP::getInfinity(Type *Ty, bool Negative) {
714 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
715 Constant *C = get(Ty->getContext(), APFloat::getInf(Semantics, Negative));
716
717 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
718 return ConstantVector::getSplat(VTy->getNumElements(), C);
719
720 return C;
Dan Gohmanfeb50212009-09-25 23:00:48 +0000721}
722
Duncan P. N. Exon Smithb6452792016-02-21 02:39:49 +0000723ConstantFP::ConstantFP(Type *Ty, const APFloat &V)
724 : ConstantData(Ty, ConstantFPVal), Val(V) {
Chris Lattner98bd9392008-04-09 06:38:30 +0000725 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
726 "FP type Mismatch");
Chris Lattner2f7c9632001-06-06 20:29:01 +0000727}
728
Chris Lattnerbe6610c2011-07-15 06:14:08 +0000729bool ConstantFP::isExactlyValue(const APFloat &V) const {
Dale Johannesend246b2c2007-08-30 00:23:21 +0000730 return Val.bitwiseIsEqual(V);
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000731}
732
Pete Cooper86dd4cf2015-06-23 21:55:11 +0000733/// Remove the constant from the constant table.
734void ConstantFP::destroyConstantImpl() {
735 llvm_unreachable("You can't ConstantInt->destroyConstantImpl()!");
736}
737
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000738//===----------------------------------------------------------------------===//
Chris Lattner030af792012-01-24 05:42:11 +0000739// ConstantAggregateZero Implementation
740//===----------------------------------------------------------------------===//
741
Chris Lattner7e683d12012-01-25 06:16:32 +0000742Constant *ConstantAggregateZero::getSequentialElement() const {
Chris Lattner8326bd82012-01-26 00:42:34 +0000743 return Constant::getNullValue(getType()->getSequentialElementType());
Chris Lattner030af792012-01-24 05:42:11 +0000744}
745
Chris Lattner7e683d12012-01-25 06:16:32 +0000746Constant *ConstantAggregateZero::getStructElement(unsigned Elt) const {
Chris Lattner8326bd82012-01-26 00:42:34 +0000747 return Constant::getNullValue(getType()->getStructElementType(Elt));
Chris Lattner030af792012-01-24 05:42:11 +0000748}
749
Chris Lattner7e683d12012-01-25 06:16:32 +0000750Constant *ConstantAggregateZero::getElementValue(Constant *C) const {
Chris Lattner030af792012-01-24 05:42:11 +0000751 if (isa<SequentialType>(getType()))
752 return getSequentialElement();
753 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
754}
755
Chris Lattner7e683d12012-01-25 06:16:32 +0000756Constant *ConstantAggregateZero::getElementValue(unsigned Idx) const {
Chris Lattnerf7eb5432012-01-24 07:54:10 +0000757 if (isa<SequentialType>(getType()))
758 return getSequentialElement();
759 return getStructElement(Idx);
760}
761
David Majnemer9b529a72015-02-16 04:02:09 +0000762unsigned ConstantAggregateZero::getNumElements() const {
Craig Toppere3dcce92015-08-01 22:20:21 +0000763 Type *Ty = getType();
764 if (auto *AT = dyn_cast<ArrayType>(Ty))
David Majnemer9b529a72015-02-16 04:02:09 +0000765 return AT->getNumElements();
Craig Toppere3dcce92015-08-01 22:20:21 +0000766 if (auto *VT = dyn_cast<VectorType>(Ty))
David Majnemer9b529a72015-02-16 04:02:09 +0000767 return VT->getNumElements();
768 return Ty->getStructNumElements();
769}
Chris Lattnerf7eb5432012-01-24 07:54:10 +0000770
Chris Lattner030af792012-01-24 05:42:11 +0000771//===----------------------------------------------------------------------===//
772// UndefValue Implementation
773//===----------------------------------------------------------------------===//
774
Chris Lattner7e683d12012-01-25 06:16:32 +0000775UndefValue *UndefValue::getSequentialElement() const {
Chris Lattner8326bd82012-01-26 00:42:34 +0000776 return UndefValue::get(getType()->getSequentialElementType());
Chris Lattner030af792012-01-24 05:42:11 +0000777}
778
Chris Lattner7e683d12012-01-25 06:16:32 +0000779UndefValue *UndefValue::getStructElement(unsigned Elt) const {
Chris Lattner8326bd82012-01-26 00:42:34 +0000780 return UndefValue::get(getType()->getStructElementType(Elt));
Chris Lattner030af792012-01-24 05:42:11 +0000781}
782
Chris Lattner7e683d12012-01-25 06:16:32 +0000783UndefValue *UndefValue::getElementValue(Constant *C) const {
Chris Lattner030af792012-01-24 05:42:11 +0000784 if (isa<SequentialType>(getType()))
785 return getSequentialElement();
786 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
787}
788
Chris Lattner7e683d12012-01-25 06:16:32 +0000789UndefValue *UndefValue::getElementValue(unsigned Idx) const {
Chris Lattnerf7eb5432012-01-24 07:54:10 +0000790 if (isa<SequentialType>(getType()))
791 return getSequentialElement();
792 return getStructElement(Idx);
793}
794
David Majnemer9b529a72015-02-16 04:02:09 +0000795unsigned UndefValue::getNumElements() const {
Craig Toppere3dcce92015-08-01 22:20:21 +0000796 Type *Ty = getType();
Peter Collingbournebc070522016-12-02 03:20:58 +0000797 if (auto *ST = dyn_cast<SequentialType>(Ty))
798 return ST->getNumElements();
David Majnemer9b529a72015-02-16 04:02:09 +0000799 return Ty->getStructNumElements();
800}
Chris Lattner030af792012-01-24 05:42:11 +0000801
802//===----------------------------------------------------------------------===//
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000803// ConstantXXX Classes
804//===----------------------------------------------------------------------===//
805
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000806template <typename ItTy, typename EltTy>
807static bool rangeOnlyContains(ItTy Start, ItTy End, EltTy Elt) {
808 for (; Start != End; ++Start)
809 if (*Start != Elt)
810 return false;
811 return true;
812}
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000813
Justin Bogner909e1c02015-12-01 20:20:49 +0000814template <typename SequentialTy, typename ElementTy>
815static Constant *getIntSequenceIfElementsMatch(ArrayRef<Constant *> V) {
816 assert(!V.empty() && "Cannot get empty int sequence.");
817
818 SmallVector<ElementTy, 16> Elts;
819 for (Constant *C : V)
820 if (auto *CI = dyn_cast<ConstantInt>(C))
821 Elts.push_back(CI->getZExtValue());
822 else
823 return nullptr;
824 return SequentialTy::get(V[0]->getContext(), Elts);
825}
826
827template <typename SequentialTy, typename ElementTy>
828static Constant *getFPSequenceIfElementsMatch(ArrayRef<Constant *> V) {
829 assert(!V.empty() && "Cannot get empty FP sequence.");
830
831 SmallVector<ElementTy, 16> Elts;
832 for (Constant *C : V)
833 if (auto *CFP = dyn_cast<ConstantFP>(C))
834 Elts.push_back(CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
835 else
836 return nullptr;
837 return SequentialTy::getFP(V[0]->getContext(), Elts);
838}
839
840template <typename SequenceTy>
841static Constant *getSequenceIfElementsMatch(Constant *C,
842 ArrayRef<Constant *> V) {
843 // We speculatively build the elements here even if it turns out that there is
844 // a constantexpr or something else weird, since it is so uncommon for that to
845 // happen.
846 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
847 if (CI->getType()->isIntegerTy(8))
848 return getIntSequenceIfElementsMatch<SequenceTy, uint8_t>(V);
849 else if (CI->getType()->isIntegerTy(16))
850 return getIntSequenceIfElementsMatch<SequenceTy, uint16_t>(V);
851 else if (CI->getType()->isIntegerTy(32))
852 return getIntSequenceIfElementsMatch<SequenceTy, uint32_t>(V);
853 else if (CI->getType()->isIntegerTy(64))
854 return getIntSequenceIfElementsMatch<SequenceTy, uint64_t>(V);
855 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
Justin Bogner0ebc8602015-12-08 03:01:16 +0000856 if (CFP->getType()->isHalfTy())
857 return getFPSequenceIfElementsMatch<SequenceTy, uint16_t>(V);
858 else if (CFP->getType()->isFloatTy())
Justin Bogner909e1c02015-12-01 20:20:49 +0000859 return getFPSequenceIfElementsMatch<SequenceTy, uint32_t>(V);
860 else if (CFP->getType()->isDoubleTy())
861 return getFPSequenceIfElementsMatch<SequenceTy, uint64_t>(V);
862 }
863
864 return nullptr;
865}
866
Duncan P. N. Exon Smith1de3c7e2016-04-05 21:10:45 +0000867ConstantAggregate::ConstantAggregate(CompositeType *T, ValueTy VT,
868 ArrayRef<Constant *> V)
869 : Constant(T, VT, OperandTraits<ConstantAggregate>::op_end(this) - V.size(),
870 V.size()) {
Jay Foad89d9b812011-07-25 10:14:44 +0000871 std::copy(V.begin(), V.end(), op_begin());
Duncan P. N. Exon Smith1de3c7e2016-04-05 21:10:45 +0000872
873 // Check that types match, unless this is an opaque struct.
874 if (auto *ST = dyn_cast<StructType>(T))
875 if (ST->isOpaque())
876 return;
877 for (unsigned I = 0, E = V.size(); I != E; ++I)
878 assert(V[I]->getType() == T->getTypeAtIndex(I) &&
879 "Initializer for composite element doesn't match!");
880}
881
882ConstantArray::ConstantArray(ArrayType *T, ArrayRef<Constant *> V)
883 : ConstantAggregate(T, ConstantArrayVal, V) {
884 assert(V.size() == T->getNumElements() &&
885 "Invalid initializer for constant array");
Chris Lattner2f7c9632001-06-06 20:29:01 +0000886}
887
Chris Lattner229907c2011-07-18 04:54:35 +0000888Constant *ConstantArray::get(ArrayType *Ty, ArrayRef<Constant*> V) {
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +0000889 if (Constant *C = getImpl(Ty, V))
890 return C;
891 return Ty->getContext().pImpl->ArrayConstants.getOrCreate(Ty, V);
892}
Justin Bogner909e1c02015-12-01 20:20:49 +0000893
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +0000894Constant *ConstantArray::getImpl(ArrayType *Ty, ArrayRef<Constant*> V) {
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000895 // Empty arrays are canonicalized to ConstantAggregateZero.
896 if (V.empty())
897 return ConstantAggregateZero::get(Ty);
898
Jeffrey Yasskin8ce67f82009-09-30 21:08:08 +0000899 for (unsigned i = 0, e = V.size(); i != e; ++i) {
900 assert(V[i]->getType() == Ty->getElementType() &&
901 "Wrong type in array element initializer");
902 }
Galina Kistanovafc259902012-07-13 01:25:27 +0000903
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000904 // If this is an all-zero array, return a ConstantAggregateZero object. If
905 // all undef, return an UndefValue, if "all simple", then return a
906 // ConstantDataArray.
907 Constant *C = V[0];
908 if (isa<UndefValue>(C) && rangeOnlyContains(V.begin(), V.end(), C))
909 return UndefValue::get(Ty);
Chris Lattnerf14a67f2012-01-26 02:31:22 +0000910
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000911 if (C->isNullValue() && rangeOnlyContains(V.begin(), V.end(), C))
912 return ConstantAggregateZero::get(Ty);
913
914 // Check to see if all of the elements are ConstantFP or ConstantInt and if
915 // the element type is compatible with ConstantDataVector. If so, use it.
Justin Bogner909e1c02015-12-01 20:20:49 +0000916 if (ConstantDataSequential::isElementTypeCompatible(C->getType()))
917 return getSequenceIfElementsMatch<ConstantDataArray>(C, V);
Chris Lattnerf14a67f2012-01-26 02:31:22 +0000918
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000919 // Otherwise, we really do want to create a ConstantArray.
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +0000920 return nullptr;
Owen Andersonc2c79322009-07-28 18:32:17 +0000921}
922
Chris Lattnercc19efa2011-06-20 04:01:31 +0000923StructType *ConstantStruct::getTypeForElements(LLVMContext &Context,
924 ArrayRef<Constant*> V,
925 bool Packed) {
Bill Wendling3ae7dd32012-02-07 01:27:51 +0000926 unsigned VecSize = V.size();
927 SmallVector<Type*, 16> EltTypes(VecSize);
928 for (unsigned i = 0; i != VecSize; ++i)
929 EltTypes[i] = V[i]->getType();
Galina Kistanovafc259902012-07-13 01:25:27 +0000930
Chris Lattnercc19efa2011-06-20 04:01:31 +0000931 return StructType::get(Context, EltTypes, Packed);
932}
933
934
935StructType *ConstantStruct::getTypeForElements(ArrayRef<Constant*> V,
936 bool Packed) {
937 assert(!V.empty() &&
938 "ConstantStruct::getTypeForElements cannot be called on empty list");
939 return getTypeForElements(V[0]->getContext(), V, Packed);
940}
941
Jay Foad89d9b812011-07-25 10:14:44 +0000942ConstantStruct::ConstantStruct(StructType *T, ArrayRef<Constant *> V)
Duncan P. N. Exon Smith1de3c7e2016-04-05 21:10:45 +0000943 : ConstantAggregate(T, ConstantStructVal, V) {
944 assert((T->isOpaque() || V.size() == T->getNumElements()) &&
945 "Invalid initializer for constant struct");
Chris Lattner2f7c9632001-06-06 20:29:01 +0000946}
947
Owen Anderson45308b52009-07-27 22:29:26 +0000948// ConstantStruct accessors.
Chris Lattner229907c2011-07-18 04:54:35 +0000949Constant *ConstantStruct::get(StructType *ST, ArrayRef<Constant*> V) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000950 assert((ST->isOpaque() || ST->getNumElements() == V.size()) &&
951 "Incorrect # elements specified to ConstantStruct::get");
Chris Lattnerf14a67f2012-01-26 02:31:22 +0000952
953 // Create a ConstantAggregateZero value if all elements are zeros.
954 bool isZero = true;
955 bool isUndef = false;
956
957 if (!V.empty()) {
958 isUndef = isa<UndefValue>(V[0]);
959 isZero = V[0]->isNullValue();
960 if (isUndef || isZero) {
961 for (unsigned i = 0, e = V.size(); i != e; ++i) {
962 if (!V[i]->isNullValue())
963 isZero = false;
964 if (!isa<UndefValue>(V[i]))
965 isUndef = false;
966 }
967 }
Galina Kistanovafc259902012-07-13 01:25:27 +0000968 }
Chris Lattnerf14a67f2012-01-26 02:31:22 +0000969 if (isZero)
970 return ConstantAggregateZero::get(ST);
971 if (isUndef)
972 return UndefValue::get(ST);
Galina Kistanovafc259902012-07-13 01:25:27 +0000973
Chris Lattnerf14a67f2012-01-26 02:31:22 +0000974 return ST->getContext().pImpl->StructConstants.getOrCreate(ST, V);
Owen Anderson45308b52009-07-27 22:29:26 +0000975}
976
Chris Lattnerc3e74cd2011-08-07 04:18:48 +0000977Constant *ConstantStruct::get(StructType *T, ...) {
Talin3a0a30d2011-02-28 23:53:27 +0000978 va_list ap;
Chris Lattnercc19efa2011-06-20 04:01:31 +0000979 SmallVector<Constant*, 8> Values;
980 va_start(ap, T);
981 while (Constant *Val = va_arg(ap, llvm::Constant*))
Talin3a0a30d2011-02-28 23:53:27 +0000982 Values.push_back(Val);
Talinde422be2011-03-01 18:00:49 +0000983 va_end(ap);
Chris Lattnercc19efa2011-06-20 04:01:31 +0000984 return get(T, Values);
Talin3a0a30d2011-02-28 23:53:27 +0000985}
986
Jay Foad89d9b812011-07-25 10:14:44 +0000987ConstantVector::ConstantVector(VectorType *T, ArrayRef<Constant *> V)
Duncan P. N. Exon Smith1de3c7e2016-04-05 21:10:45 +0000988 : ConstantAggregate(T, ConstantVectorVal, V) {
Duncan P. N. Exon Smithdb63bda2016-04-05 20:53:47 +0000989 assert(V.size() == T->getNumElements() &&
Duncan P. N. Exon Smith1de3c7e2016-04-05 21:10:45 +0000990 "Invalid initializer for constant vector");
Brian Gaeke02209042004-08-20 06:00:58 +0000991}
992
Owen Anderson4aa32952009-07-28 21:19:26 +0000993// ConstantVector accessors.
Jay Foadb8a8bed32011-06-22 09:10:19 +0000994Constant *ConstantVector::get(ArrayRef<Constant*> V) {
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +0000995 if (Constant *C = getImpl(V))
996 return C;
997 VectorType *Ty = VectorType::get(V.front()->getType(), V.size());
998 return Ty->getContext().pImpl->VectorConstants.getOrCreate(Ty, V);
999}
Justin Bogner909e1c02015-12-01 20:20:49 +00001000
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001001Constant *ConstantVector::getImpl(ArrayRef<Constant*> V) {
Jay Foad9f32cfd2011-01-27 14:44:55 +00001002 assert(!V.empty() && "Vectors can't be empty");
Chris Lattner229907c2011-07-18 04:54:35 +00001003 VectorType *T = VectorType::get(V.front()->getType(), V.size());
Jay Foad9f32cfd2011-01-27 14:44:55 +00001004
Chris Lattner69229312011-02-15 00:14:00 +00001005 // If this is an all-undef or all-zero vector, return a
Owen Anderson4aa32952009-07-28 21:19:26 +00001006 // ConstantAggregateZero or UndefValue.
1007 Constant *C = V[0];
1008 bool isZero = C->isNullValue();
1009 bool isUndef = isa<UndefValue>(C);
1010
1011 if (isZero || isUndef) {
1012 for (unsigned i = 1, e = V.size(); i != e; ++i)
1013 if (V[i] != C) {
1014 isZero = isUndef = false;
1015 break;
1016 }
1017 }
Galina Kistanovafc259902012-07-13 01:25:27 +00001018
Owen Anderson4aa32952009-07-28 21:19:26 +00001019 if (isZero)
Owen Andersonb292b8c2009-07-30 23:03:37 +00001020 return ConstantAggregateZero::get(T);
Owen Anderson4aa32952009-07-28 21:19:26 +00001021 if (isUndef)
Owen Andersonb292b8c2009-07-30 23:03:37 +00001022 return UndefValue::get(T);
Galina Kistanovafc259902012-07-13 01:25:27 +00001023
Chris Lattner978fe0c2012-01-30 06:21:21 +00001024 // Check to see if all of the elements are ConstantFP or ConstantInt and if
1025 // the element type is compatible with ConstantDataVector. If so, use it.
Justin Bogner909e1c02015-12-01 20:20:49 +00001026 if (ConstantDataSequential::isElementTypeCompatible(C->getType()))
1027 return getSequenceIfElementsMatch<ConstantDataVector>(C, V);
Galina Kistanovafc259902012-07-13 01:25:27 +00001028
Chris Lattner978fe0c2012-01-30 06:21:21 +00001029 // Otherwise, the element type isn't compatible with ConstantDataVector, or
1030 // the operand list constants a ConstantExpr or something else strange.
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001031 return nullptr;
Owen Anderson4aa32952009-07-28 21:19:26 +00001032}
1033
Chris Lattnere9eed292012-01-25 05:19:54 +00001034Constant *ConstantVector::getSplat(unsigned NumElts, Constant *V) {
Chris Lattner978fe0c2012-01-30 06:21:21 +00001035 // If this splat is compatible with ConstantDataVector, use it instead of
1036 // ConstantVector.
1037 if ((isa<ConstantFP>(V) || isa<ConstantInt>(V)) &&
1038 ConstantDataSequential::isElementTypeCompatible(V->getType()))
1039 return ConstantDataVector::getSplat(NumElts, V);
Galina Kistanovafc259902012-07-13 01:25:27 +00001040
Chris Lattnere9eed292012-01-25 05:19:54 +00001041 SmallVector<Constant*, 32> Elts(NumElts, V);
1042 return get(Elts);
1043}
1044
David Majnemerf0f224d2015-11-11 21:57:16 +00001045ConstantTokenNone *ConstantTokenNone::get(LLVMContext &Context) {
1046 LLVMContextImpl *pImpl = Context.pImpl;
1047 if (!pImpl->TheNoneToken)
David Majnemer2dd41c52015-11-16 20:55:57 +00001048 pImpl->TheNoneToken.reset(new ConstantTokenNone(Context));
1049 return pImpl->TheNoneToken.get();
David Majnemerf0f224d2015-11-11 21:57:16 +00001050}
1051
1052/// Remove the constant from the constant table.
1053void ConstantTokenNone::destroyConstantImpl() {
1054 llvm_unreachable("You can't ConstantTokenNone->destroyConstantImpl()!");
1055}
Chris Lattnere9eed292012-01-25 05:19:54 +00001056
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001057// Utility function for determining if a ConstantExpr is a CastOp or not. This
1058// can't be inline because we don't want to #include Instruction.h into
1059// Constant.h
1060bool ConstantExpr::isCast() const {
1061 return Instruction::isCast(getOpcode());
1062}
1063
Reid Spenceree3c9912006-12-04 05:19:50 +00001064bool ConstantExpr::isCompare() const {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00001065 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
Reid Spenceree3c9912006-12-04 05:19:50 +00001066}
1067
Dan Gohman7190d482009-09-10 23:37:55 +00001068bool ConstantExpr::isGEPWithNoNotionalOverIndexing() const {
1069 if (getOpcode() != Instruction::GetElementPtr) return false;
1070
1071 gep_type_iterator GEPI = gep_type_begin(this), E = gep_type_end(this);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001072 User::const_op_iterator OI = std::next(this->op_begin());
Dan Gohman7190d482009-09-10 23:37:55 +00001073
Dan Gohman7190d482009-09-10 23:37:55 +00001074 // The remaining indices must be compile-time known integers within the
1075 // bounds of the corresponding notional static array types.
1076 for (; GEPI != E; ++GEPI, ++OI) {
1077 ConstantInt *CI = dyn_cast<ConstantInt>(*OI);
Peter Collingbourneab85225b2016-12-02 02:24:42 +00001078 if (GEPI.isBoundedSequential() &&
1079 (CI->getValue().getActiveBits() > 64 ||
1080 CI->getZExtValue() >= GEPI.getSequentialNumElements()))
1081 return false;
Dan Gohman7190d482009-09-10 23:37:55 +00001082 }
1083
1084 // All the indices checked out.
1085 return true;
1086}
1087
Dan Gohman1ecaf452008-05-31 00:58:22 +00001088bool ConstantExpr::hasIndices() const {
1089 return getOpcode() == Instruction::ExtractValue ||
1090 getOpcode() == Instruction::InsertValue;
1091}
1092
Jay Foad0091fe82011-04-13 15:22:40 +00001093ArrayRef<unsigned> ConstantExpr::getIndices() const {
Dan Gohman1ecaf452008-05-31 00:58:22 +00001094 if (const ExtractValueConstantExpr *EVCE =
1095 dyn_cast<ExtractValueConstantExpr>(this))
1096 return EVCE->Indices;
Dan Gohmana469bdb2008-06-23 16:39:44 +00001097
1098 return cast<InsertValueConstantExpr>(this)->Indices;
Dan Gohman1ecaf452008-05-31 00:58:22 +00001099}
1100
Reid Spencer10fbf0e2006-12-03 05:48:19 +00001101unsigned ConstantExpr::getPredicate() const {
Craig Toppercc03b492015-12-15 06:11:36 +00001102 return cast<CompareConstantExpr>(this)->predicate;
Reid Spencer10fbf0e2006-12-03 05:48:19 +00001103}
Chris Lattner60e0dd72001-10-03 06:12:09 +00001104
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001105Constant *
1106ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
Chris Lattner7c1018a2006-07-14 19:37:40 +00001107 assert(Op->getType() == getOperand(OpNo)->getType() &&
1108 "Replacing operand with value of different type!");
Chris Lattner227816342006-07-14 22:20:01 +00001109 if (getOperand(OpNo) == Op)
1110 return const_cast<ConstantExpr*>(this);
Chris Lattner37e38352012-01-26 20:37:11 +00001111
1112 SmallVector<Constant*, 8> NewOps;
1113 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1114 NewOps.push_back(i == OpNo ? Op : getOperand(i));
Galina Kistanovafc259902012-07-13 01:25:27 +00001115
Chris Lattner37e38352012-01-26 20:37:11 +00001116 return getWithOperands(NewOps);
Chris Lattner227816342006-07-14 22:20:01 +00001117}
1118
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001119Constant *ConstantExpr::getWithOperands(ArrayRef<Constant *> Ops, Type *Ty,
David Blaikie88208842015-08-21 20:16:51 +00001120 bool OnlyIfReduced, Type *SrcTy) const {
Jay Foad5c984e562011-04-13 13:46:01 +00001121 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
Galina Kistanovafc259902012-07-13 01:25:27 +00001122
Benjamin Kramer8008e9f2015-03-02 11:57:04 +00001123 // If no operands changed return self.
1124 if (Ty == getType() && std::equal(Ops.begin(), Ops.end(), op_begin()))
Chris Lattner227816342006-07-14 22:20:01 +00001125 return const_cast<ConstantExpr*>(this);
1126
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001127 Type *OnlyIfReducedTy = OnlyIfReduced ? Ty : nullptr;
Chris Lattner227816342006-07-14 22:20:01 +00001128 switch (getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001129 case Instruction::Trunc:
1130 case Instruction::ZExt:
1131 case Instruction::SExt:
1132 case Instruction::FPTrunc:
1133 case Instruction::FPExt:
1134 case Instruction::UIToFP:
1135 case Instruction::SIToFP:
1136 case Instruction::FPToUI:
1137 case Instruction::FPToSI:
1138 case Instruction::PtrToInt:
1139 case Instruction::IntToPtr:
1140 case Instruction::BitCast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00001141 case Instruction::AddrSpaceCast:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001142 return ConstantExpr::getCast(getOpcode(), Ops[0], Ty, OnlyIfReduced);
Chris Lattner227816342006-07-14 22:20:01 +00001143 case Instruction::Select:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001144 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2], OnlyIfReducedTy);
Chris Lattner227816342006-07-14 22:20:01 +00001145 case Instruction::InsertElement:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001146 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2],
1147 OnlyIfReducedTy);
Chris Lattner227816342006-07-14 22:20:01 +00001148 case Instruction::ExtractElement:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001149 return ConstantExpr::getExtractElement(Ops[0], Ops[1], OnlyIfReducedTy);
Chris Lattner37e38352012-01-26 20:37:11 +00001150 case Instruction::InsertValue:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001151 return ConstantExpr::getInsertValue(Ops[0], Ops[1], getIndices(),
1152 OnlyIfReducedTy);
Chris Lattner37e38352012-01-26 20:37:11 +00001153 case Instruction::ExtractValue:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001154 return ConstantExpr::getExtractValue(Ops[0], getIndices(), OnlyIfReducedTy);
Chris Lattner227816342006-07-14 22:20:01 +00001155 case Instruction::ShuffleVector:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001156 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2],
1157 OnlyIfReducedTy);
David Blaikie88208842015-08-21 20:16:51 +00001158 case Instruction::GetElementPtr: {
1159 auto *GEPO = cast<GEPOperator>(this);
1160 assert(SrcTy || (Ops[0]->getType() == getOperand(0)->getType()));
1161 return ConstantExpr::getGetElementPtr(
1162 SrcTy ? SrcTy : GEPO->getSourceElementType(), Ops[0], Ops.slice(1),
Peter Collingbourned93620b2016-11-10 22:34:55 +00001163 GEPO->isInBounds(), GEPO->getInRangeIndex(), OnlyIfReducedTy);
David Blaikie88208842015-08-21 20:16:51 +00001164 }
Reid Spencer266e42b2006-12-23 06:05:41 +00001165 case Instruction::ICmp:
1166 case Instruction::FCmp:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001167 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1],
1168 OnlyIfReducedTy);
Chris Lattner227816342006-07-14 22:20:01 +00001169 default:
1170 assert(getNumOperands() == 2 && "Must be binary operator?");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001171 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1], SubclassOptionalData,
1172 OnlyIfReducedTy);
Chris Lattner7c1018a2006-07-14 19:37:40 +00001173 }
1174}
1175
Chris Lattner2f7c9632001-06-06 20:29:01 +00001176
1177//===----------------------------------------------------------------------===//
Chris Lattner2f7c9632001-06-06 20:29:01 +00001178// isValueValidForType implementations
1179
Chris Lattner229907c2011-07-18 04:54:35 +00001180bool ConstantInt::isValueValidForType(Type *Ty, uint64_t Val) {
Chris Lattner8326bd82012-01-26 00:42:34 +00001181 unsigned NumBits = Ty->getIntegerBitWidth(); // assert okay
1182 if (Ty->isIntegerTy(1))
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001183 return Val == 0 || Val == 1;
Reid Spencerd7a00d72007-02-05 23:47:56 +00001184 if (NumBits >= 64)
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001185 return true; // always true, has to fit in largest type
1186 uint64_t Max = (1ll << NumBits) - 1;
1187 return Val <= Max;
Reid Spencere7334722006-12-19 01:28:19 +00001188}
1189
Chris Lattner229907c2011-07-18 04:54:35 +00001190bool ConstantInt::isValueValidForType(Type *Ty, int64_t Val) {
Chris Lattner8326bd82012-01-26 00:42:34 +00001191 unsigned NumBits = Ty->getIntegerBitWidth();
1192 if (Ty->isIntegerTy(1))
Reid Spencera94d3942007-01-19 21:13:56 +00001193 return Val == 0 || Val == 1 || Val == -1;
Reid Spencerd7a00d72007-02-05 23:47:56 +00001194 if (NumBits >= 64)
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001195 return true; // always true, has to fit in largest type
1196 int64_t Min = -(1ll << (NumBits-1));
1197 int64_t Max = (1ll << (NumBits-1)) - 1;
1198 return (Val >= Min && Val <= Max);
Chris Lattner2f7c9632001-06-06 20:29:01 +00001199}
1200
Chris Lattner229907c2011-07-18 04:54:35 +00001201bool ConstantFP::isValueValidForType(Type *Ty, const APFloat& Val) {
Dale Johannesend246b2c2007-08-30 00:23:21 +00001202 // convert modifies in place, so make a copy.
1203 APFloat Val2 = APFloat(Val);
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001204 bool losesInfo;
Chris Lattner6b727592004-06-17 18:19:28 +00001205 switch (Ty->getTypeID()) {
Chris Lattner2f7c9632001-06-06 20:29:01 +00001206 default:
1207 return false; // These can't be represented as floating point!
1208
Dale Johannesend246b2c2007-08-30 00:23:21 +00001209 // FIXME rounding mode needs to be more flexible
Dan Gohman518cda42011-12-17 00:04:22 +00001210 case Type::HalfTyID: {
1211 if (&Val2.getSemantics() == &APFloat::IEEEhalf)
1212 return true;
1213 Val2.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, &losesInfo);
1214 return !losesInfo;
1215 }
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001216 case Type::FloatTyID: {
1217 if (&Val2.getSemantics() == &APFloat::IEEEsingle)
1218 return true;
1219 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
1220 return !losesInfo;
1221 }
1222 case Type::DoubleTyID: {
Dan Gohman518cda42011-12-17 00:04:22 +00001223 if (&Val2.getSemantics() == &APFloat::IEEEhalf ||
1224 &Val2.getSemantics() == &APFloat::IEEEsingle ||
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001225 &Val2.getSemantics() == &APFloat::IEEEdouble)
1226 return true;
1227 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
1228 return !losesInfo;
1229 }
Dale Johannesenbdad8092007-08-09 22:51:36 +00001230 case Type::X86_FP80TyID:
Dan Gohman518cda42011-12-17 00:04:22 +00001231 return &Val2.getSemantics() == &APFloat::IEEEhalf ||
1232 &Val2.getSemantics() == &APFloat::IEEEsingle ||
Dale Johannesen028084e2007-09-12 03:30:33 +00001233 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1234 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
Dale Johannesenbdad8092007-08-09 22:51:36 +00001235 case Type::FP128TyID:
Dan Gohman518cda42011-12-17 00:04:22 +00001236 return &Val2.getSemantics() == &APFloat::IEEEhalf ||
1237 &Val2.getSemantics() == &APFloat::IEEEsingle ||
Dale Johannesen028084e2007-09-12 03:30:33 +00001238 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1239 &Val2.getSemantics() == &APFloat::IEEEquad;
Dale Johannesen007aa372007-10-11 18:07:22 +00001240 case Type::PPC_FP128TyID:
Dan Gohman518cda42011-12-17 00:04:22 +00001241 return &Val2.getSemantics() == &APFloat::IEEEhalf ||
1242 &Val2.getSemantics() == &APFloat::IEEEsingle ||
Dale Johannesen007aa372007-10-11 18:07:22 +00001243 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1244 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
Chris Lattner2f7c9632001-06-06 20:29:01 +00001245 }
Chris Lattneraa2372562006-05-24 17:04:05 +00001246}
Chris Lattner9655e542001-07-20 19:16:02 +00001247
Chris Lattner030af792012-01-24 05:42:11 +00001248
Chris Lattner49d855c2001-09-07 16:46:31 +00001249//===----------------------------------------------------------------------===//
Chris Lattner49d855c2001-09-07 16:46:31 +00001250// Factory Function Implementation
1251
Chris Lattnerc7f9fd42012-01-23 15:20:12 +00001252ConstantAggregateZero *ConstantAggregateZero::get(Type *Ty) {
Chris Lattner13ee7952010-08-28 04:09:24 +00001253 assert((Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()) &&
Owen Andersonb292b8c2009-07-30 23:03:37 +00001254 "Cannot create an aggregate zero of non-aggregate type!");
David Blaikie899b85a2014-11-25 02:13:54 +00001255
Justin Lebar611c5c22016-10-10 16:26:13 +00001256 std::unique_ptr<ConstantAggregateZero> &Entry =
1257 Ty->getContext().pImpl->CAZConstants[Ty];
1258 if (!Entry)
1259 Entry.reset(new ConstantAggregateZero(Ty));
1260
1261 return Entry.get();
Owen Andersonb292b8c2009-07-30 23:03:37 +00001262}
1263
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00001264/// Remove the constant from the constant table.
Pete Cooper86dd4cf2015-06-23 21:55:11 +00001265void ConstantAggregateZero::destroyConstantImpl() {
Chris Lattnerc7f9fd42012-01-23 15:20:12 +00001266 getContext().pImpl->CAZConstants.erase(getType());
Chris Lattner9fba3da2004-02-15 05:53:04 +00001267}
1268
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00001269/// Remove the constant from the constant table.
Pete Cooper86dd4cf2015-06-23 21:55:11 +00001270void ConstantArray::destroyConstantImpl() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001271 getType()->getContext().pImpl->ArrayConstants.remove(this);
Chris Lattner98fa07b2003-05-23 20:03:32 +00001272}
1273
Chris Lattner81fabb02002-08-26 17:53:56 +00001274
Chris Lattner3462ae32001-12-03 22:26:30 +00001275//---- ConstantStruct::get() implementation...
Chris Lattner49d855c2001-09-07 16:46:31 +00001276//
Chris Lattnerb50d1352003-10-05 00:17:43 +00001277
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00001278/// Remove the constant from the constant table.
Pete Cooper86dd4cf2015-06-23 21:55:11 +00001279void ConstantStruct::destroyConstantImpl() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001280 getType()->getContext().pImpl->StructConstants.remove(this);
Chris Lattnerd7a73302001-10-13 06:57:33 +00001281}
Chris Lattner883ad0b2001-10-03 15:39:36 +00001282
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00001283/// Remove the constant from the constant table.
Pete Cooper86dd4cf2015-06-23 21:55:11 +00001284void ConstantVector::destroyConstantImpl() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001285 getType()->getContext().pImpl->VectorConstants.remove(this);
Brian Gaeke02209042004-08-20 06:00:58 +00001286}
1287
Duncan Sandse6beec62012-11-13 12:59:33 +00001288Constant *Constant::getSplatValue() const {
1289 assert(this->getType()->isVectorTy() && "Only valid for vectors!");
1290 if (isa<ConstantAggregateZero>(this))
1291 return getNullValue(this->getType()->getVectorElementType());
1292 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
1293 return CV->getSplatValue();
1294 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
1295 return CV->getSplatValue();
Craig Topperc6207612014-04-09 06:08:46 +00001296 return nullptr;
Duncan Sandse6beec62012-11-13 12:59:33 +00001297}
1298
Duncan Sandscf0ff032011-02-01 08:39:12 +00001299Constant *ConstantVector::getSplatValue() const {
Dan Gohman07159202007-10-17 17:51:30 +00001300 // Check out first element.
1301 Constant *Elt = getOperand(0);
1302 // Then make sure all remaining elements point to the same value.
1303 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
Chris Lattnerd04e32d2011-07-17 06:01:30 +00001304 if (getOperand(I) != Elt)
Craig Topperc6207612014-04-09 06:08:46 +00001305 return nullptr;
Dan Gohman07159202007-10-17 17:51:30 +00001306 return Elt;
1307}
1308
Duncan Sandse6beec62012-11-13 12:59:33 +00001309const APInt &Constant::getUniqueInteger() const {
1310 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
1311 return CI->getValue();
1312 assert(this->getSplatValue() && "Doesn't contain a unique integer!");
1313 const Constant *C = this->getAggregateElement(0U);
1314 assert(C && isa<ConstantInt>(C) && "Not a vector of numbers!");
1315 return cast<ConstantInt>(C)->getValue();
1316}
1317
Chris Lattner31b132c2009-10-28 00:01:44 +00001318//---- ConstantPointerNull::get() implementation.
Chris Lattnerd7a73302001-10-13 06:57:33 +00001319//
Chris Lattner98fa07b2003-05-23 20:03:32 +00001320
Chris Lattner229907c2011-07-18 04:54:35 +00001321ConstantPointerNull *ConstantPointerNull::get(PointerType *Ty) {
Justin Lebar611c5c22016-10-10 16:26:13 +00001322 std::unique_ptr<ConstantPointerNull> &Entry =
1323 Ty->getContext().pImpl->CPNConstants[Ty];
Craig Topperc6207612014-04-09 06:08:46 +00001324 if (!Entry)
Justin Lebar611c5c22016-10-10 16:26:13 +00001325 Entry.reset(new ConstantPointerNull(Ty));
Galina Kistanovafc259902012-07-13 01:25:27 +00001326
Justin Lebar611c5c22016-10-10 16:26:13 +00001327 return Entry.get();
Chris Lattner883ad0b2001-10-03 15:39:36 +00001328}
1329
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00001330/// Remove the constant from the constant table.
Pete Cooper86dd4cf2015-06-23 21:55:11 +00001331void ConstantPointerNull::destroyConstantImpl() {
Chris Lattnerc7f9fd42012-01-23 15:20:12 +00001332 getContext().pImpl->CPNConstants.erase(getType());
Chris Lattner0c6e0b92002-08-18 00:40:04 +00001333}
1334
Chris Lattner229907c2011-07-18 04:54:35 +00001335UndefValue *UndefValue::get(Type *Ty) {
Justin Lebar611c5c22016-10-10 16:26:13 +00001336 std::unique_ptr<UndefValue> &Entry = Ty->getContext().pImpl->UVConstants[Ty];
Craig Topperc6207612014-04-09 06:08:46 +00001337 if (!Entry)
Justin Lebar611c5c22016-10-10 16:26:13 +00001338 Entry.reset(new UndefValue(Ty));
Galina Kistanovafc259902012-07-13 01:25:27 +00001339
Justin Lebar611c5c22016-10-10 16:26:13 +00001340 return Entry.get();
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001341}
1342
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00001343/// Remove the constant from the constant table.
Pete Cooper86dd4cf2015-06-23 21:55:11 +00001344void UndefValue::destroyConstantImpl() {
Chris Lattnerc7f9fd42012-01-23 15:20:12 +00001345 // Free the constant and any dangling references to it.
1346 getContext().pImpl->UVConstants.erase(getType());
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001347}
1348
Chris Lattner31b132c2009-10-28 00:01:44 +00001349BlockAddress *BlockAddress::get(BasicBlock *BB) {
Craig Topper2617dcc2014-04-15 06:32:26 +00001350 assert(BB->getParent() && "Block must have a parent");
Chris Lattner31b132c2009-10-28 00:01:44 +00001351 return get(BB->getParent(), BB);
1352}
1353
1354BlockAddress *BlockAddress::get(Function *F, BasicBlock *BB) {
1355 BlockAddress *&BA =
1356 F->getContext().pImpl->BlockAddresses[std::make_pair(F, BB)];
Craig Topperc6207612014-04-09 06:08:46 +00001357 if (!BA)
Chris Lattner31b132c2009-10-28 00:01:44 +00001358 BA = new BlockAddress(F, BB);
Galina Kistanovafc259902012-07-13 01:25:27 +00001359
Chris Lattner31b132c2009-10-28 00:01:44 +00001360 assert(BA->getFunction() == F && "Basic block moved between functions");
1361 return BA;
1362}
1363
1364BlockAddress::BlockAddress(Function *F, BasicBlock *BB)
1365: Constant(Type::getInt8PtrTy(F->getContext()), Value::BlockAddressVal,
1366 &Op<0>(), 2) {
Chris Lattnerc559a9f2009-11-01 03:03:03 +00001367 setOperand(0, F);
1368 setOperand(1, BB);
Chris Lattneraa99c942009-11-01 01:27:45 +00001369 BB->AdjustBlockAddressRefCount(1);
Chris Lattner31b132c2009-10-28 00:01:44 +00001370}
1371
Chandler Carruth6a936922014-01-19 02:13:50 +00001372BlockAddress *BlockAddress::lookup(const BasicBlock *BB) {
1373 if (!BB->hasAddressTaken())
Craig Topperc6207612014-04-09 06:08:46 +00001374 return nullptr;
Chandler Carruth6a936922014-01-19 02:13:50 +00001375
1376 const Function *F = BB->getParent();
Craig Topper2617dcc2014-04-15 06:32:26 +00001377 assert(F && "Block must have a parent");
Chandler Carruth6a936922014-01-19 02:13:50 +00001378 BlockAddress *BA =
1379 F->getContext().pImpl->BlockAddresses.lookup(std::make_pair(F, BB));
1380 assert(BA && "Refcount and block address map disagree!");
1381 return BA;
1382}
Chris Lattner31b132c2009-10-28 00:01:44 +00001383
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00001384/// Remove the constant from the constant table.
Pete Cooper86dd4cf2015-06-23 21:55:11 +00001385void BlockAddress::destroyConstantImpl() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001386 getFunction()->getType()->getContext().pImpl
Chris Lattner31b132c2009-10-28 00:01:44 +00001387 ->BlockAddresses.erase(std::make_pair(getFunction(), getBasicBlock()));
Chris Lattneraa99c942009-11-01 01:27:45 +00001388 getBasicBlock()->AdjustBlockAddressRefCount(-1);
Chris Lattner31b132c2009-10-28 00:01:44 +00001389}
1390
Mehdi Amini8914d292016-02-10 22:47:15 +00001391Value *BlockAddress::handleOperandChangeImpl(Value *From, Value *To) {
Chris Lattner31b132c2009-10-28 00:01:44 +00001392 // This could be replacing either the Basic Block or the Function. In either
1393 // case, we have to remove the map entry.
1394 Function *NewF = getFunction();
1395 BasicBlock *NewBB = getBasicBlock();
Galina Kistanovafc259902012-07-13 01:25:27 +00001396
Mehdi Amini8914d292016-02-10 22:47:15 +00001397 if (From == NewF)
Derek Schuffec9dc012013-06-13 19:51:17 +00001398 NewF = cast<Function>(To->stripPointerCasts());
Mehdi Amini8914d292016-02-10 22:47:15 +00001399 else {
1400 assert(From == NewBB && "From does not match any operand");
Chris Lattner31b132c2009-10-28 00:01:44 +00001401 NewBB = cast<BasicBlock>(To);
Mehdi Amini8914d292016-02-10 22:47:15 +00001402 }
Galina Kistanovafc259902012-07-13 01:25:27 +00001403
Chris Lattner31b132c2009-10-28 00:01:44 +00001404 // See if the 'new' entry already exists, if not, just update this in place
1405 // and return early.
1406 BlockAddress *&NewBA =
1407 getContext().pImpl->BlockAddresses[std::make_pair(NewF, NewBB)];
Pete Cooper5815b1f2015-06-24 18:55:24 +00001408 if (NewBA)
1409 return NewBA;
Chris Lattner31b132c2009-10-28 00:01:44 +00001410
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001411 getBasicBlock()->AdjustBlockAddressRefCount(-1);
Galina Kistanovafc259902012-07-13 01:25:27 +00001412
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001413 // Remove the old entry, this can't cause the map to rehash (just a
1414 // tombstone will get added).
1415 getContext().pImpl->BlockAddresses.erase(std::make_pair(getFunction(),
1416 getBasicBlock()));
1417 NewBA = this;
1418 setOperand(0, NewF);
1419 setOperand(1, NewBB);
1420 getBasicBlock()->AdjustBlockAddressRefCount(1);
Pete Cooper5815b1f2015-06-24 18:55:24 +00001421
1422 // If we just want to keep the existing value, then return null.
1423 // Callers know that this means we shouldn't delete this value.
1424 return nullptr;
Chris Lattner31b132c2009-10-28 00:01:44 +00001425}
1426
1427//---- ConstantExpr::get() implementations.
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001428//
Reid Spencer8d9336d2006-12-31 05:26:44 +00001429
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001430/// This is a utility function to handle folding of casts and lookup of the
Duncan Sands7d6c8ae2008-03-30 19:38:55 +00001431/// cast in the ExprConstants map. It is used by the various get* methods below.
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001432static Constant *getFoldedCast(Instruction::CastOps opc, Constant *C, Type *Ty,
1433 bool OnlyIfReduced = false) {
Chris Lattner815ae2b2003-10-07 22:19:19 +00001434 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001435 // Fold a few common cases
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001436 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001437 return FC;
Chris Lattneracdbe712003-04-17 19:24:48 +00001438
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001439 if (OnlyIfReduced)
1440 return nullptr;
1441
Owen Anderson1584a292009-08-04 20:25:11 +00001442 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
1443
Nadav Rotem88330432013-03-07 01:30:40 +00001444 // Look up the constant in the table first to ensure uniqueness.
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001445 ConstantExprKeyType Key(opc, C);
Galina Kistanovafc259902012-07-13 01:25:27 +00001446
Owen Anderson1584a292009-08-04 20:25:11 +00001447 return pImpl->ExprConstants.getOrCreate(Ty, Key);
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001448}
Galina Kistanovafc259902012-07-13 01:25:27 +00001449
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001450Constant *ConstantExpr::getCast(unsigned oc, Constant *C, Type *Ty,
1451 bool OnlyIfReduced) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001452 Instruction::CastOps opc = Instruction::CastOps(oc);
1453 assert(Instruction::isCast(opc) && "opcode out of range");
1454 assert(C && Ty && "Null arguments to getCast");
Chris Lattner37bc78a2010-01-26 21:51:43 +00001455 assert(CastInst::castIsValid(opc, C, Ty) && "Invalid constantexpr cast!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001456
1457 switch (opc) {
Chris Lattner37bc78a2010-01-26 21:51:43 +00001458 default:
1459 llvm_unreachable("Invalid cast opcode");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001460 case Instruction::Trunc:
1461 return getTrunc(C, Ty, OnlyIfReduced);
1462 case Instruction::ZExt:
1463 return getZExt(C, Ty, OnlyIfReduced);
1464 case Instruction::SExt:
1465 return getSExt(C, Ty, OnlyIfReduced);
1466 case Instruction::FPTrunc:
1467 return getFPTrunc(C, Ty, OnlyIfReduced);
1468 case Instruction::FPExt:
1469 return getFPExtend(C, Ty, OnlyIfReduced);
1470 case Instruction::UIToFP:
1471 return getUIToFP(C, Ty, OnlyIfReduced);
1472 case Instruction::SIToFP:
1473 return getSIToFP(C, Ty, OnlyIfReduced);
1474 case Instruction::FPToUI:
1475 return getFPToUI(C, Ty, OnlyIfReduced);
1476 case Instruction::FPToSI:
1477 return getFPToSI(C, Ty, OnlyIfReduced);
1478 case Instruction::PtrToInt:
1479 return getPtrToInt(C, Ty, OnlyIfReduced);
1480 case Instruction::IntToPtr:
1481 return getIntToPtr(C, Ty, OnlyIfReduced);
1482 case Instruction::BitCast:
1483 return getBitCast(C, Ty, OnlyIfReduced);
1484 case Instruction::AddrSpaceCast:
1485 return getAddrSpaceCast(C, Ty, OnlyIfReduced);
Chris Lattner1ece6f82005-01-01 15:59:57 +00001486 }
Galina Kistanovafc259902012-07-13 01:25:27 +00001487}
Reid Spencerf37dc652006-12-05 19:14:13 +00001488
Chris Lattner229907c2011-07-18 04:54:35 +00001489Constant *ConstantExpr::getZExtOrBitCast(Constant *C, Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001490 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001491 return getBitCast(C, Ty);
1492 return getZExt(C, Ty);
Reid Spencer5c140882006-12-04 20:17:56 +00001493}
1494
Chris Lattner229907c2011-07-18 04:54:35 +00001495Constant *ConstantExpr::getSExtOrBitCast(Constant *C, Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001496 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001497 return getBitCast(C, Ty);
1498 return getSExt(C, Ty);
Reid Spencer5c140882006-12-04 20:17:56 +00001499}
1500
Chris Lattner229907c2011-07-18 04:54:35 +00001501Constant *ConstantExpr::getTruncOrBitCast(Constant *C, Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001502 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001503 return getBitCast(C, Ty);
1504 return getTrunc(C, Ty);
Reid Spencer5c140882006-12-04 20:17:56 +00001505}
1506
Chris Lattner229907c2011-07-18 04:54:35 +00001507Constant *ConstantExpr::getPointerCast(Constant *S, Type *Ty) {
Evgeniy Stepanov23382642013-01-16 14:41:46 +00001508 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
1509 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
1510 "Invalid cast");
Reid Spencerbc245a02006-12-05 03:25:26 +00001511
Evgeniy Stepanov23382642013-01-16 14:41:46 +00001512 if (Ty->isIntOrIntVectorTy())
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001513 return getPtrToInt(S, Ty);
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00001514
1515 unsigned SrcAS = S->getType()->getPointerAddressSpace();
1516 if (Ty->isPtrOrPtrVectorTy() && SrcAS != Ty->getPointerAddressSpace())
1517 return getAddrSpaceCast(S, Ty);
1518
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001519 return getBitCast(S, Ty);
Reid Spencerbc245a02006-12-05 03:25:26 +00001520}
1521
Matt Arsenault21f38f42013-12-07 02:58:41 +00001522Constant *ConstantExpr::getPointerBitCastOrAddrSpaceCast(Constant *S,
1523 Type *Ty) {
1524 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
1525 assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
1526
1527 if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
1528 return getAddrSpaceCast(S, Ty);
1529
1530 return getBitCast(S, Ty);
1531}
1532
Sanjay Patelf3587ec2016-05-18 22:05:28 +00001533Constant *ConstantExpr::getIntegerCast(Constant *C, Type *Ty, bool isSigned) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00001534 assert(C->getType()->isIntOrIntVectorTy() &&
1535 Ty->isIntOrIntVectorTy() && "Invalid cast");
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001536 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1537 unsigned DstBits = Ty->getScalarSizeInBits();
Reid Spencer56521c42006-12-12 00:51:07 +00001538 Instruction::CastOps opcode =
1539 (SrcBits == DstBits ? Instruction::BitCast :
1540 (SrcBits > DstBits ? Instruction::Trunc :
1541 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1542 return getCast(opcode, C, Ty);
1543}
1544
Chris Lattner229907c2011-07-18 04:54:35 +00001545Constant *ConstantExpr::getFPCast(Constant *C, Type *Ty) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00001546 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
Reid Spencer56521c42006-12-12 00:51:07 +00001547 "Invalid cast");
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001548 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1549 unsigned DstBits = Ty->getScalarSizeInBits();
Reid Spencerca104e82006-12-12 05:38:50 +00001550 if (SrcBits == DstBits)
1551 return C; // Avoid a useless cast
Reid Spencer56521c42006-12-12 00:51:07 +00001552 Instruction::CastOps opcode =
Jay Foad9f32cfd2011-01-27 14:44:55 +00001553 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
Reid Spencer56521c42006-12-12 00:51:07 +00001554 return getCast(opcode, C, Ty);
1555}
1556
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001557Constant *ConstantExpr::getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001558#ifndef NDEBUG
1559 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1560 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1561#endif
1562 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001563 assert(C->getType()->isIntOrIntVectorTy() && "Trunc operand must be integer");
1564 assert(Ty->isIntOrIntVectorTy() && "Trunc produces only integral");
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001565 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001566 "SrcTy must be larger than DestTy for Trunc!");
1567
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001568 return getFoldedCast(Instruction::Trunc, C, Ty, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001569}
1570
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001571Constant *ConstantExpr::getSExt(Constant *C, Type *Ty, bool OnlyIfReduced) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001572#ifndef NDEBUG
1573 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1574 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1575#endif
1576 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001577 assert(C->getType()->isIntOrIntVectorTy() && "SExt operand must be integral");
1578 assert(Ty->isIntOrIntVectorTy() && "SExt produces only integer");
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001579 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001580 "SrcTy must be smaller than DestTy for SExt!");
1581
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001582 return getFoldedCast(Instruction::SExt, C, Ty, OnlyIfReduced);
Chris Lattnerdd284742004-04-04 23:20:30 +00001583}
1584
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001585Constant *ConstantExpr::getZExt(Constant *C, Type *Ty, bool OnlyIfReduced) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001586#ifndef NDEBUG
1587 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1588 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1589#endif
1590 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001591 assert(C->getType()->isIntOrIntVectorTy() && "ZEXt operand must be integral");
1592 assert(Ty->isIntOrIntVectorTy() && "ZExt produces only integer");
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001593 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001594 "SrcTy must be smaller than DestTy for ZExt!");
1595
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001596 return getFoldedCast(Instruction::ZExt, C, Ty, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001597}
1598
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001599Constant *ConstantExpr::getFPTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001600#ifndef NDEBUG
1601 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1602 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1603#endif
1604 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001605 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001606 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001607 "This is an illegal floating point truncation!");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001608 return getFoldedCast(Instruction::FPTrunc, C, Ty, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001609}
1610
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001611Constant *ConstantExpr::getFPExtend(Constant *C, Type *Ty, bool OnlyIfReduced) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001612#ifndef NDEBUG
1613 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1614 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1615#endif
1616 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001617 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001618 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001619 "This is an illegal floating point extension!");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001620 return getFoldedCast(Instruction::FPExt, C, Ty, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001621}
1622
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001623Constant *ConstantExpr::getUIToFP(Constant *C, Type *Ty, bool OnlyIfReduced) {
Devang Pateld26344d2008-11-03 23:20:04 +00001624#ifndef NDEBUG
Nate Begemand4d45c22007-11-17 03:58:34 +00001625 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1626 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Pateld26344d2008-11-03 23:20:04 +00001627#endif
Nate Begemand4d45c22007-11-17 03:58:34 +00001628 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001629 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
Nate Begemand4d45c22007-11-17 03:58:34 +00001630 "This is an illegal uint to floating point cast!");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001631 return getFoldedCast(Instruction::UIToFP, C, Ty, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001632}
1633
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001634Constant *ConstantExpr::getSIToFP(Constant *C, Type *Ty, bool OnlyIfReduced) {
Devang Pateld26344d2008-11-03 23:20:04 +00001635#ifndef NDEBUG
Nate Begemand4d45c22007-11-17 03:58:34 +00001636 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1637 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Pateld26344d2008-11-03 23:20:04 +00001638#endif
Nate Begemand4d45c22007-11-17 03:58:34 +00001639 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001640 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001641 "This is an illegal sint to floating point cast!");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001642 return getFoldedCast(Instruction::SIToFP, C, Ty, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001643}
1644
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001645Constant *ConstantExpr::getFPToUI(Constant *C, Type *Ty, bool OnlyIfReduced) {
Devang Pateld26344d2008-11-03 23:20:04 +00001646#ifndef NDEBUG
Nate Begemand4d45c22007-11-17 03:58:34 +00001647 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1648 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Pateld26344d2008-11-03 23:20:04 +00001649#endif
Nate Begemand4d45c22007-11-17 03:58:34 +00001650 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001651 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
Nate Begemand4d45c22007-11-17 03:58:34 +00001652 "This is an illegal floating point to uint cast!");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001653 return getFoldedCast(Instruction::FPToUI, C, Ty, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001654}
1655
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001656Constant *ConstantExpr::getFPToSI(Constant *C, Type *Ty, bool OnlyIfReduced) {
Devang Pateld26344d2008-11-03 23:20:04 +00001657#ifndef NDEBUG
Nate Begemand4d45c22007-11-17 03:58:34 +00001658 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1659 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Pateld26344d2008-11-03 23:20:04 +00001660#endif
Nate Begemand4d45c22007-11-17 03:58:34 +00001661 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001662 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
Nate Begemand4d45c22007-11-17 03:58:34 +00001663 "This is an illegal floating point to sint cast!");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001664 return getFoldedCast(Instruction::FPToSI, C, Ty, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001665}
1666
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001667Constant *ConstantExpr::getPtrToInt(Constant *C, Type *DstTy,
1668 bool OnlyIfReduced) {
Nadav Rotem3924cb02011-12-05 06:29:09 +00001669 assert(C->getType()->getScalarType()->isPointerTy() &&
1670 "PtrToInt source must be pointer or pointer vector");
1671 assert(DstTy->getScalarType()->isIntegerTy() &&
1672 "PtrToInt destination must be integer or integer vector");
Chris Lattner8a3df542012-01-25 01:32:59 +00001673 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
Nick Lewyckyff509622012-01-25 03:20:12 +00001674 if (isa<VectorType>(C->getType()))
Chris Lattner8326bd82012-01-26 00:42:34 +00001675 assert(C->getType()->getVectorNumElements()==DstTy->getVectorNumElements()&&
Chris Lattner8a3df542012-01-25 01:32:59 +00001676 "Invalid cast between a different number of vector elements");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001677 return getFoldedCast(Instruction::PtrToInt, C, DstTy, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001678}
1679
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001680Constant *ConstantExpr::getIntToPtr(Constant *C, Type *DstTy,
1681 bool OnlyIfReduced) {
Nadav Rotem3924cb02011-12-05 06:29:09 +00001682 assert(C->getType()->getScalarType()->isIntegerTy() &&
1683 "IntToPtr source must be integer or integer vector");
1684 assert(DstTy->getScalarType()->isPointerTy() &&
1685 "IntToPtr destination must be a pointer or pointer vector");
Chris Lattner8a3df542012-01-25 01:32:59 +00001686 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
Nick Lewyckyff509622012-01-25 03:20:12 +00001687 if (isa<VectorType>(C->getType()))
Chris Lattner8326bd82012-01-26 00:42:34 +00001688 assert(C->getType()->getVectorNumElements()==DstTy->getVectorNumElements()&&
Chris Lattner8a3df542012-01-25 01:32:59 +00001689 "Invalid cast between a different number of vector elements");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001690 return getFoldedCast(Instruction::IntToPtr, C, DstTy, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001691}
1692
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001693Constant *ConstantExpr::getBitCast(Constant *C, Type *DstTy,
1694 bool OnlyIfReduced) {
Chris Lattner37bc78a2010-01-26 21:51:43 +00001695 assert(CastInst::castIsValid(Instruction::BitCast, C, DstTy) &&
1696 "Invalid constantexpr bitcast!");
Galina Kistanovafc259902012-07-13 01:25:27 +00001697
Chris Lattnercbeda872009-03-21 06:55:54 +00001698 // It is common to ask for a bitcast of a value to its own type, handle this
1699 // speedily.
1700 if (C->getType() == DstTy) return C;
Galina Kistanovafc259902012-07-13 01:25:27 +00001701
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001702 return getFoldedCast(Instruction::BitCast, C, DstTy, OnlyIfReduced);
Chris Lattnerdd284742004-04-04 23:20:30 +00001703}
1704
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001705Constant *ConstantExpr::getAddrSpaceCast(Constant *C, Type *DstTy,
1706 bool OnlyIfReduced) {
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00001707 assert(CastInst::castIsValid(Instruction::AddrSpaceCast, C, DstTy) &&
1708 "Invalid constantexpr addrspacecast!");
1709
Jingyue Wubaabe502014-06-15 21:40:57 +00001710 // Canonicalize addrspacecasts between different pointer types by first
1711 // bitcasting the pointer type and then converting the address space.
1712 PointerType *SrcScalarTy = cast<PointerType>(C->getType()->getScalarType());
1713 PointerType *DstScalarTy = cast<PointerType>(DstTy->getScalarType());
1714 Type *DstElemTy = DstScalarTy->getElementType();
1715 if (SrcScalarTy->getElementType() != DstElemTy) {
1716 Type *MidTy = PointerType::get(DstElemTy, SrcScalarTy->getAddressSpace());
1717 if (VectorType *VT = dyn_cast<VectorType>(DstTy)) {
1718 // Handle vectors of pointers.
1719 MidTy = VectorType::get(MidTy, VT->getNumElements());
1720 }
1721 C = getBitCast(C, MidTy);
1722 }
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001723 return getFoldedCast(Instruction::AddrSpaceCast, C, DstTy, OnlyIfReduced);
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00001724}
1725
Chris Lattner887ecac2011-07-09 18:23:52 +00001726Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2,
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001727 unsigned Flags, Type *OnlyIfReducedTy) {
Chris Lattner887ecac2011-07-09 18:23:52 +00001728 // Check the operands for consistency first.
Reid Spencer7eb55b32006-11-02 01:53:59 +00001729 assert(Opcode >= Instruction::BinaryOpsBegin &&
1730 Opcode < Instruction::BinaryOpsEnd &&
Chris Lattner38a9bcd2003-05-21 17:49:25 +00001731 "Invalid opcode in binary constant expression");
1732 assert(C1->getType() == C2->getType() &&
1733 "Operand types in binary constant expression should match");
Galina Kistanovafc259902012-07-13 01:25:27 +00001734
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001735#ifndef NDEBUG
1736 switch (Opcode) {
Dan Gohmana5b96452009-06-04 22:49:04 +00001737 case Instruction::Add:
Reid Spencer7eb55b32006-11-02 01:53:59 +00001738 case Instruction::Sub:
Dan Gohmana5b96452009-06-04 22:49:04 +00001739 case Instruction::Mul:
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001740 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001741 assert(C1->getType()->isIntOrIntVectorTy() &&
Dan Gohmana5b96452009-06-04 22:49:04 +00001742 "Tried to create an integer operation on a non-integer type!");
1743 break;
1744 case Instruction::FAdd:
1745 case Instruction::FSub:
1746 case Instruction::FMul:
1747 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001748 assert(C1->getType()->isFPOrFPVectorTy() &&
Dan Gohmana5b96452009-06-04 22:49:04 +00001749 "Tried to create a floating-point operation on a "
1750 "non-floating-point type!");
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001751 break;
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001752 case Instruction::UDiv:
1753 case Instruction::SDiv:
1754 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001755 assert(C1->getType()->isIntOrIntVectorTy() &&
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001756 "Tried to create an arithmetic operation on a non-arithmetic type!");
1757 break;
1758 case Instruction::FDiv:
1759 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001760 assert(C1->getType()->isFPOrFPVectorTy() &&
Dan Gohman7889f2b2009-06-15 22:25:12 +00001761 "Tried to create an arithmetic operation on a non-arithmetic type!");
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001762 break;
Reid Spencer7eb55b32006-11-02 01:53:59 +00001763 case Instruction::URem:
1764 case Instruction::SRem:
1765 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001766 assert(C1->getType()->isIntOrIntVectorTy() &&
Reid Spencer7eb55b32006-11-02 01:53:59 +00001767 "Tried to create an arithmetic operation on a non-arithmetic type!");
1768 break;
1769 case Instruction::FRem:
1770 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001771 assert(C1->getType()->isFPOrFPVectorTy() &&
Dan Gohman7889f2b2009-06-15 22:25:12 +00001772 "Tried to create an arithmetic operation on a non-arithmetic type!");
Reid Spencer7eb55b32006-11-02 01:53:59 +00001773 break;
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001774 case Instruction::And:
1775 case Instruction::Or:
1776 case Instruction::Xor:
1777 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001778 assert(C1->getType()->isIntOrIntVectorTy() &&
Misha Brukman3852f652005-01-27 06:46:38 +00001779 "Tried to create a logical operation on a non-integral type!");
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001780 break;
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001781 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00001782 case Instruction::LShr:
1783 case Instruction::AShr:
Reid Spencer2341c222007-02-02 02:16:23 +00001784 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001785 assert(C1->getType()->isIntOrIntVectorTy() &&
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001786 "Tried to create a shift operation on a non-integer type!");
1787 break;
1788 default:
1789 break;
1790 }
1791#endif
1792
Chris Lattner887ecac2011-07-09 18:23:52 +00001793 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1794 return FC; // Fold a few common cases.
Galina Kistanovafc259902012-07-13 01:25:27 +00001795
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001796 if (OnlyIfReducedTy == C1->getType())
1797 return nullptr;
1798
Benjamin Kramer324322b2013-03-07 20:53:34 +00001799 Constant *ArgVec[] = { C1, C2 };
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001800 ConstantExprKeyType Key(Opcode, ArgVec, 0, Flags);
Galina Kistanovafc259902012-07-13 01:25:27 +00001801
Chris Lattner887ecac2011-07-09 18:23:52 +00001802 LLVMContextImpl *pImpl = C1->getContext().pImpl;
1803 return pImpl->ExprConstants.getOrCreate(C1->getType(), Key);
Reid Spencera009d0d2006-12-04 21:35:24 +00001804}
1805
Chris Lattner229907c2011-07-18 04:54:35 +00001806Constant *ConstantExpr::getSizeOf(Type* Ty) {
Owen Anderson487375e2009-07-29 18:55:55 +00001807 // sizeof is implemented as: (i64) gep (Ty*)null, 1
1808 // Note that a non-inbounds gep is used, as null isn't within any object.
Owen Anderson55f1c092009-08-13 21:58:54 +00001809 Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
Owen Anderson487375e2009-07-29 18:55:55 +00001810 Constant *GEP = getGetElementPtr(
David Blaikie4a2e73b2015-04-02 18:55:32 +00001811 Ty, Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001812 return getPtrToInt(GEP,
1813 Type::getInt64Ty(Ty->getContext()));
Owen Anderson487375e2009-07-29 18:55:55 +00001814}
1815
Chris Lattner229907c2011-07-18 04:54:35 +00001816Constant *ConstantExpr::getAlignOf(Type* Ty) {
Dan Gohmancf913832010-01-28 02:15:55 +00001817 // alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1
Dan Gohman50c09d02009-08-11 17:57:01 +00001818 // Note that a non-inbounds gep is used, as null isn't within any object.
Chris Lattner229907c2011-07-18 04:54:35 +00001819 Type *AligningTy =
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001820 StructType::get(Type::getInt1Ty(Ty->getContext()), Ty, nullptr);
Matt Arsenaultbe558882014-04-23 20:58:57 +00001821 Constant *NullPtr = Constant::getNullValue(AligningTy->getPointerTo(0));
Dan Gohmana9be7392010-01-28 02:43:22 +00001822 Constant *Zero = ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0);
Owen Anderson55f1c092009-08-13 21:58:54 +00001823 Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
Owen Anderson487375e2009-07-29 18:55:55 +00001824 Constant *Indices[2] = { Zero, One };
David Blaikie4a2e73b2015-04-02 18:55:32 +00001825 Constant *GEP = getGetElementPtr(AligningTy, NullPtr, Indices);
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001826 return getPtrToInt(GEP,
1827 Type::getInt64Ty(Ty->getContext()));
Owen Anderson487375e2009-07-29 18:55:55 +00001828}
1829
Chris Lattner229907c2011-07-18 04:54:35 +00001830Constant *ConstantExpr::getOffsetOf(StructType* STy, unsigned FieldNo) {
Dan Gohmanede94e62010-02-01 16:37:38 +00001831 return getOffsetOf(STy, ConstantInt::get(Type::getInt32Ty(STy->getContext()),
1832 FieldNo));
1833}
1834
Chris Lattner229907c2011-07-18 04:54:35 +00001835Constant *ConstantExpr::getOffsetOf(Type* Ty, Constant *FieldNo) {
Dan Gohmanff3af7252009-08-16 21:26:11 +00001836 // offsetof is implemented as: (i64) gep (Ty*)null, 0, FieldNo
1837 // Note that a non-inbounds gep is used, as null isn't within any object.
1838 Constant *GEPIdx[] = {
Dan Gohmanede94e62010-02-01 16:37:38 +00001839 ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0),
1840 FieldNo
Dan Gohmanff3af7252009-08-16 21:26:11 +00001841 };
1842 Constant *GEP = getGetElementPtr(
David Blaikie4a2e73b2015-04-02 18:55:32 +00001843 Ty, Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001844 return getPtrToInt(GEP,
1845 Type::getInt64Ty(Ty->getContext()));
Dan Gohmanff3af7252009-08-16 21:26:11 +00001846}
Owen Anderson487375e2009-07-29 18:55:55 +00001847
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001848Constant *ConstantExpr::getCompare(unsigned short Predicate, Constant *C1,
1849 Constant *C2, bool OnlyIfReduced) {
Reid Spencera009d0d2006-12-04 21:35:24 +00001850 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Galina Kistanovafc259902012-07-13 01:25:27 +00001851
Chris Lattner887ecac2011-07-09 18:23:52 +00001852 switch (Predicate) {
1853 default: llvm_unreachable("Invalid CmpInst predicate");
1854 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
1855 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
1856 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
1857 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
1858 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
1859 case CmpInst::FCMP_TRUE:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001860 return getFCmp(Predicate, C1, C2, OnlyIfReduced);
Galina Kistanovafc259902012-07-13 01:25:27 +00001861
Chris Lattner887ecac2011-07-09 18:23:52 +00001862 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
1863 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
1864 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
1865 case CmpInst::ICMP_SLE:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001866 return getICmp(Predicate, C1, C2, OnlyIfReduced);
Chris Lattner887ecac2011-07-09 18:23:52 +00001867 }
Chris Lattner29ca2c62004-08-04 18:50:09 +00001868}
1869
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001870Constant *ConstantExpr::getSelect(Constant *C, Constant *V1, Constant *V2,
1871 Type *OnlyIfReducedTy) {
Chris Lattner41632132008-12-29 00:16:12 +00001872 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
Chris Lattner6e415c02004-03-12 05:54:04 +00001873
Chris Lattner887ecac2011-07-09 18:23:52 +00001874 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1875 return SC; // Fold common cases
Chris Lattner6e415c02004-03-12 05:54:04 +00001876
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001877 if (OnlyIfReducedTy == V1->getType())
1878 return nullptr;
1879
Benjamin Kramer324322b2013-03-07 20:53:34 +00001880 Constant *ArgVec[] = { C, V1, V2 };
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001881 ConstantExprKeyType Key(Instruction::Select, ArgVec);
Galina Kistanovafc259902012-07-13 01:25:27 +00001882
Chris Lattner887ecac2011-07-09 18:23:52 +00001883 LLVMContextImpl *pImpl = C->getContext().pImpl;
1884 return pImpl->ExprConstants.getOrCreate(V1->getType(), Key);
Chris Lattner6e415c02004-03-12 05:54:04 +00001885}
1886
David Blaikie4a2e73b2015-04-02 18:55:32 +00001887Constant *ConstantExpr::getGetElementPtr(Type *Ty, Constant *C,
1888 ArrayRef<Value *> Idxs, bool InBounds,
Peter Collingbourned93620b2016-11-10 22:34:55 +00001889 Optional<unsigned> InRangeIndex,
David Blaikie4a2e73b2015-04-02 18:55:32 +00001890 Type *OnlyIfReducedTy) {
David Blaikie4a2e73b2015-04-02 18:55:32 +00001891 if (!Ty)
1892 Ty = cast<PointerType>(C->getType()->getScalarType())->getElementType();
1893 else
David Blaikied9d900c2015-05-07 17:28:58 +00001894 assert(
1895 Ty ==
1896 cast<PointerType>(C->getType()->getScalarType())->getContainedType(0u));
1897
Peter Collingbourned93620b2016-11-10 22:34:55 +00001898 if (Constant *FC =
1899 ConstantFoldGetElementPtr(Ty, C, InBounds, InRangeIndex, Idxs))
David Blaikied9d900c2015-05-07 17:28:58 +00001900 return FC; // Fold a few common cases.
1901
Chris Lattner887ecac2011-07-09 18:23:52 +00001902 // Get the result type of the getelementptr!
David Blaikie4a2e73b2015-04-02 18:55:32 +00001903 Type *DestTy = GetElementPtrInst::getIndexedType(Ty, Idxs);
1904 assert(DestTy && "GEP indices invalid!");
Chris Lattner8326bd82012-01-26 00:42:34 +00001905 unsigned AS = C->getType()->getPointerAddressSpace();
David Blaikie4a2e73b2015-04-02 18:55:32 +00001906 Type *ReqTy = DestTy->getPointerTo(AS);
Elena Demikhovskyee004bc2016-05-15 12:30:25 +00001907
1908 unsigned NumVecElts = 0;
1909 if (C->getType()->isVectorTy())
1910 NumVecElts = C->getType()->getVectorNumElements();
1911 else for (auto Idx : Idxs)
1912 if (Idx->getType()->isVectorTy())
1913 NumVecElts = Idx->getType()->getVectorNumElements();
1914
1915 if (NumVecElts)
1916 ReqTy = VectorType::get(ReqTy, NumVecElts);
Galina Kistanovafc259902012-07-13 01:25:27 +00001917
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001918 if (OnlyIfReducedTy == ReqTy)
1919 return nullptr;
1920
Dan Gohman1b849082009-09-07 23:54:19 +00001921 // Look up the constant in the table first to ensure uniqueness
1922 std::vector<Constant*> ArgVec;
Jay Foaded8db7d2011-07-21 14:31:17 +00001923 ArgVec.reserve(1 + Idxs.size());
Dan Gohman1b849082009-09-07 23:54:19 +00001924 ArgVec.push_back(C);
Duncan Sandse6beec62012-11-13 12:59:33 +00001925 for (unsigned i = 0, e = Idxs.size(); i != e; ++i) {
Duncan Sandse6beec62012-11-13 12:59:33 +00001926 assert((!Idxs[i]->getType()->isVectorTy() ||
Elena Demikhovskyee004bc2016-05-15 12:30:25 +00001927 Idxs[i]->getType()->getVectorNumElements() == NumVecElts) &&
Duncan Sandse6beec62012-11-13 12:59:33 +00001928 "getelementptr index type missmatch");
Elena Demikhovskyee004bc2016-05-15 12:30:25 +00001929
1930 Constant *Idx = cast<Constant>(Idxs[i]);
1931 if (NumVecElts && !Idxs[i]->getType()->isVectorTy())
1932 Idx = ConstantVector::getSplat(NumVecElts, Idx);
1933 ArgVec.push_back(Idx);
Duncan Sandse6beec62012-11-13 12:59:33 +00001934 }
Peter Collingbourned93620b2016-11-10 22:34:55 +00001935
1936 unsigned SubClassOptionalData = InBounds ? GEPOperator::IsInBounds : 0;
1937 if (InRangeIndex && *InRangeIndex < 63)
1938 SubClassOptionalData |= (*InRangeIndex + 1) << 1;
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001939 const ConstantExprKeyType Key(Instruction::GetElementPtr, ArgVec, 0,
Peter Collingbourned93620b2016-11-10 22:34:55 +00001940 SubClassOptionalData, None, Ty);
Galina Kistanovafc259902012-07-13 01:25:27 +00001941
Chris Lattner887ecac2011-07-09 18:23:52 +00001942 LLVMContextImpl *pImpl = C->getContext().pImpl;
Dan Gohman1b849082009-09-07 23:54:19 +00001943 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1944}
1945
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001946Constant *ConstantExpr::getICmp(unsigned short pred, Constant *LHS,
1947 Constant *RHS, bool OnlyIfReduced) {
Reid Spenceree3c9912006-12-04 05:19:50 +00001948 assert(LHS->getType() == RHS->getType());
1949 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
1950 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1951
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001952 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
Reid Spenceree3c9912006-12-04 05:19:50 +00001953 return FC; // Fold a few common cases...
1954
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001955 if (OnlyIfReduced)
1956 return nullptr;
1957
Reid Spenceree3c9912006-12-04 05:19:50 +00001958 // Look up the constant in the table first to ensure uniqueness
Benjamin Kramer324322b2013-03-07 20:53:34 +00001959 Constant *ArgVec[] = { LHS, RHS };
Reid Spencerb1537492006-12-24 18:42:29 +00001960 // Get the key type with both the opcode and predicate
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001961 const ConstantExprKeyType Key(Instruction::ICmp, ArgVec, pred);
Owen Anderson61794042009-06-17 20:10:08 +00001962
Chris Lattner229907c2011-07-18 04:54:35 +00001963 Type *ResultTy = Type::getInt1Ty(LHS->getContext());
1964 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
Nick Lewycky9e26c1c2010-01-21 07:03:21 +00001965 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
1966
Owen Anderson1584a292009-08-04 20:25:11 +00001967 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
Nick Lewycky9e26c1c2010-01-21 07:03:21 +00001968 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
Reid Spenceree3c9912006-12-04 05:19:50 +00001969}
1970
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001971Constant *ConstantExpr::getFCmp(unsigned short pred, Constant *LHS,
1972 Constant *RHS, bool OnlyIfReduced) {
Reid Spenceree3c9912006-12-04 05:19:50 +00001973 assert(LHS->getType() == RHS->getType());
1974 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1975
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001976 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
Reid Spenceree3c9912006-12-04 05:19:50 +00001977 return FC; // Fold a few common cases...
1978
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001979 if (OnlyIfReduced)
1980 return nullptr;
1981
Reid Spenceree3c9912006-12-04 05:19:50 +00001982 // Look up the constant in the table first to ensure uniqueness
Benjamin Kramer324322b2013-03-07 20:53:34 +00001983 Constant *ArgVec[] = { LHS, RHS };
Reid Spencerb1537492006-12-24 18:42:29 +00001984 // Get the key type with both the opcode and predicate
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001985 const ConstantExprKeyType Key(Instruction::FCmp, ArgVec, pred);
Nick Lewycky9e26c1c2010-01-21 07:03:21 +00001986
Chris Lattner229907c2011-07-18 04:54:35 +00001987 Type *ResultTy = Type::getInt1Ty(LHS->getContext());
1988 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
Nick Lewycky9e26c1c2010-01-21 07:03:21 +00001989 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
1990
Owen Anderson1584a292009-08-04 20:25:11 +00001991 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
Nick Lewycky9e26c1c2010-01-21 07:03:21 +00001992 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
Reid Spenceree3c9912006-12-04 05:19:50 +00001993}
1994
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001995Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx,
1996 Type *OnlyIfReducedTy) {
Duncan Sands19d0b472010-02-16 11:11:14 +00001997 assert(Val->getType()->isVectorTy() &&
Reid Spencer09575ba2007-02-15 03:39:18 +00001998 "Tried to create extractelement operation on non-vector type!");
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00001999 assert(Idx->getType()->isIntegerTy() &&
2000 "Extractelement index must be an integer type!");
Galina Kistanovafc259902012-07-13 01:25:27 +00002001
Chris Lattner887ecac2011-07-09 18:23:52 +00002002 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
Chris Lattner09660c92009-12-30 20:25:09 +00002003 return FC; // Fold a few common cases.
Galina Kistanovafc259902012-07-13 01:25:27 +00002004
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002005 Type *ReqTy = Val->getType()->getVectorElementType();
2006 if (OnlyIfReducedTy == ReqTy)
2007 return nullptr;
2008
Robert Bocchinoca27f032006-01-17 20:07:22 +00002009 // Look up the constant in the table first to ensure uniqueness
Benjamin Kramer324322b2013-03-07 20:53:34 +00002010 Constant *ArgVec[] = { Val, Idx };
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002011 const ConstantExprKeyType Key(Instruction::ExtractElement, ArgVec);
Galina Kistanovafc259902012-07-13 01:25:27 +00002012
Chris Lattner887ecac2011-07-09 18:23:52 +00002013 LLVMContextImpl *pImpl = Val->getContext().pImpl;
Owen Anderson1584a292009-08-04 20:25:11 +00002014 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
Robert Bocchinoca27f032006-01-17 20:07:22 +00002015}
2016
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002017Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
2018 Constant *Idx, Type *OnlyIfReducedTy) {
Duncan Sands19d0b472010-02-16 11:11:14 +00002019 assert(Val->getType()->isVectorTy() &&
Reid Spencer09575ba2007-02-15 03:39:18 +00002020 "Tried to create insertelement operation on non-vector type!");
Chris Lattner8326bd82012-01-26 00:42:34 +00002021 assert(Elt->getType() == Val->getType()->getVectorElementType() &&
2022 "Insertelement types must match!");
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002023 assert(Idx->getType()->isIntegerTy() &&
Reid Spencer2546b762007-01-26 07:37:34 +00002024 "Insertelement index must be i32 type!");
Robert Bocchinoca27f032006-01-17 20:07:22 +00002025
Chris Lattner887ecac2011-07-09 18:23:52 +00002026 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
2027 return FC; // Fold a few common cases.
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002028
2029 if (OnlyIfReducedTy == Val->getType())
2030 return nullptr;
2031
Chris Lattnerbbe0a422006-04-08 01:18:18 +00002032 // Look up the constant in the table first to ensure uniqueness
Benjamin Kramer324322b2013-03-07 20:53:34 +00002033 Constant *ArgVec[] = { Val, Elt, Idx };
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002034 const ConstantExprKeyType Key(Instruction::InsertElement, ArgVec);
Galina Kistanovafc259902012-07-13 01:25:27 +00002035
Chris Lattner887ecac2011-07-09 18:23:52 +00002036 LLVMContextImpl *pImpl = Val->getContext().pImpl;
2037 return pImpl->ExprConstants.getOrCreate(Val->getType(), Key);
Chris Lattnerbbe0a422006-04-08 01:18:18 +00002038}
2039
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002040Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
2041 Constant *Mask, Type *OnlyIfReducedTy) {
Chris Lattnerbbe0a422006-04-08 01:18:18 +00002042 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
2043 "Invalid shuffle vector constant expr operands!");
Nate Begeman94aa38d2009-02-12 21:28:33 +00002044
Chris Lattner887ecac2011-07-09 18:23:52 +00002045 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
2046 return FC; // Fold a few common cases.
2047
Chris Lattner8326bd82012-01-26 00:42:34 +00002048 unsigned NElts = Mask->getType()->getVectorNumElements();
2049 Type *EltTy = V1->getType()->getVectorElementType();
Chris Lattner229907c2011-07-18 04:54:35 +00002050 Type *ShufTy = VectorType::get(EltTy, NElts);
Chris Lattner887ecac2011-07-09 18:23:52 +00002051
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002052 if (OnlyIfReducedTy == ShufTy)
2053 return nullptr;
2054
Chris Lattner887ecac2011-07-09 18:23:52 +00002055 // Look up the constant in the table first to ensure uniqueness
Benjamin Kramer324322b2013-03-07 20:53:34 +00002056 Constant *ArgVec[] = { V1, V2, Mask };
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002057 const ConstantExprKeyType Key(Instruction::ShuffleVector, ArgVec);
Galina Kistanovafc259902012-07-13 01:25:27 +00002058
Chris Lattner887ecac2011-07-09 18:23:52 +00002059 LLVMContextImpl *pImpl = ShufTy->getContext().pImpl;
2060 return pImpl->ExprConstants.getOrCreate(ShufTy, Key);
Chris Lattnerbbe0a422006-04-08 01:18:18 +00002061}
2062
Chris Lattner887ecac2011-07-09 18:23:52 +00002063Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002064 ArrayRef<unsigned> Idxs,
2065 Type *OnlyIfReducedTy) {
Hal Finkelb31366d2013-07-10 22:51:01 +00002066 assert(Agg->getType()->isFirstClassType() &&
2067 "Non-first-class type for constant insertvalue expression");
2068
Jay Foad57aa6362011-07-13 10:26:04 +00002069 assert(ExtractValueInst::getIndexedType(Agg->getType(),
2070 Idxs) == Val->getType() &&
Dan Gohman12fce772008-05-15 19:50:34 +00002071 "insertvalue indices invalid!");
Hal Finkelb31366d2013-07-10 22:51:01 +00002072 Type *ReqTy = Val->getType();
2073
2074 if (Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs))
2075 return FC;
2076
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002077 if (OnlyIfReducedTy == ReqTy)
2078 return nullptr;
2079
Hal Finkelb31366d2013-07-10 22:51:01 +00002080 Constant *ArgVec[] = { Agg, Val };
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002081 const ConstantExprKeyType Key(Instruction::InsertValue, ArgVec, 0, 0, Idxs);
Hal Finkelb31366d2013-07-10 22:51:01 +00002082
2083 LLVMContextImpl *pImpl = Agg->getContext().pImpl;
2084 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
Dan Gohman12fce772008-05-15 19:50:34 +00002085}
2086
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002087Constant *ConstantExpr::getExtractValue(Constant *Agg, ArrayRef<unsigned> Idxs,
2088 Type *OnlyIfReducedTy) {
Dan Gohman0752bff2008-05-23 00:36:11 +00002089 assert(Agg->getType()->isFirstClassType() &&
Chris Lattner887ecac2011-07-09 18:23:52 +00002090 "Tried to create extractelement operation on non-first-class type!");
Dan Gohman12fce772008-05-15 19:50:34 +00002091
Chris Lattner229907c2011-07-18 04:54:35 +00002092 Type *ReqTy = ExtractValueInst::getIndexedType(Agg->getType(), Idxs);
Chandler Carruth9db56b82011-07-10 09:45:35 +00002093 (void)ReqTy;
Chris Lattner887ecac2011-07-09 18:23:52 +00002094 assert(ReqTy && "extractvalue indices invalid!");
Galina Kistanovafc259902012-07-13 01:25:27 +00002095
Dan Gohman0752bff2008-05-23 00:36:11 +00002096 assert(Agg->getType()->isFirstClassType() &&
2097 "Non-first-class type for constant extractvalue expression");
Hal Finkelb31366d2013-07-10 22:51:01 +00002098 if (Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs))
2099 return FC;
2100
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002101 if (OnlyIfReducedTy == ReqTy)
2102 return nullptr;
2103
Hal Finkelb31366d2013-07-10 22:51:01 +00002104 Constant *ArgVec[] = { Agg };
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002105 const ConstantExprKeyType Key(Instruction::ExtractValue, ArgVec, 0, 0, Idxs);
Hal Finkelb31366d2013-07-10 22:51:01 +00002106
2107 LLVMContextImpl *pImpl = Agg->getContext().pImpl;
2108 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
Dan Gohman12fce772008-05-15 19:50:34 +00002109}
2110
Chris Lattnere9b4ad72011-02-10 07:01:55 +00002111Constant *ConstantExpr::getNeg(Constant *C, bool HasNUW, bool HasNSW) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00002112 assert(C->getType()->isIntOrIntVectorTy() &&
Owen Anderson487375e2009-07-29 18:55:55 +00002113 "Cannot NEG a nonintegral value!");
Chris Lattnere9b4ad72011-02-10 07:01:55 +00002114 return getSub(ConstantFP::getZeroValueForNegation(C->getType()),
2115 C, HasNUW, HasNSW);
Owen Anderson487375e2009-07-29 18:55:55 +00002116}
2117
Chris Lattnera676c0f2011-02-07 16:40:21 +00002118Constant *ConstantExpr::getFNeg(Constant *C) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00002119 assert(C->getType()->isFPOrFPVectorTy() &&
Owen Anderson487375e2009-07-29 18:55:55 +00002120 "Cannot FNEG a non-floating-point value!");
Chris Lattnere9b4ad72011-02-10 07:01:55 +00002121 return getFSub(ConstantFP::getZeroValueForNegation(C->getType()), C);
Owen Anderson487375e2009-07-29 18:55:55 +00002122}
2123
Chris Lattnera676c0f2011-02-07 16:40:21 +00002124Constant *ConstantExpr::getNot(Constant *C) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00002125 assert(C->getType()->isIntOrIntVectorTy() &&
Owen Anderson487375e2009-07-29 18:55:55 +00002126 "Cannot NOT a nonintegral value!");
Owen Anderson5a1acd92009-07-31 20:28:14 +00002127 return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
Owen Anderson487375e2009-07-29 18:55:55 +00002128}
2129
Chris Lattnere9b4ad72011-02-10 07:01:55 +00002130Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2,
2131 bool HasNUW, bool HasNSW) {
2132 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2133 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2134 return get(Instruction::Add, C1, C2, Flags);
Owen Anderson487375e2009-07-29 18:55:55 +00002135}
2136
Chris Lattnera676c0f2011-02-07 16:40:21 +00002137Constant *ConstantExpr::getFAdd(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002138 return get(Instruction::FAdd, C1, C2);
2139}
2140
Chris Lattnere9b4ad72011-02-10 07:01:55 +00002141Constant *ConstantExpr::getSub(Constant *C1, Constant *C2,
2142 bool HasNUW, bool HasNSW) {
2143 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2144 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2145 return get(Instruction::Sub, C1, C2, Flags);
Owen Anderson487375e2009-07-29 18:55:55 +00002146}
2147
Chris Lattnera676c0f2011-02-07 16:40:21 +00002148Constant *ConstantExpr::getFSub(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002149 return get(Instruction::FSub, C1, C2);
2150}
2151
Chris Lattnere9b4ad72011-02-10 07:01:55 +00002152Constant *ConstantExpr::getMul(Constant *C1, Constant *C2,
2153 bool HasNUW, bool HasNSW) {
2154 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2155 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2156 return get(Instruction::Mul, C1, C2, Flags);
Owen Anderson487375e2009-07-29 18:55:55 +00002157}
2158
Chris Lattnera676c0f2011-02-07 16:40:21 +00002159Constant *ConstantExpr::getFMul(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002160 return get(Instruction::FMul, C1, C2);
2161}
2162
Chris Lattner0d75eac2011-02-09 16:43:07 +00002163Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2, bool isExact) {
2164 return get(Instruction::UDiv, C1, C2,
2165 isExact ? PossiblyExactOperator::IsExact : 0);
Owen Anderson487375e2009-07-29 18:55:55 +00002166}
2167
Chris Lattner0d75eac2011-02-09 16:43:07 +00002168Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2, bool isExact) {
2169 return get(Instruction::SDiv, C1, C2,
2170 isExact ? PossiblyExactOperator::IsExact : 0);
Owen Anderson487375e2009-07-29 18:55:55 +00002171}
2172
Chris Lattnera676c0f2011-02-07 16:40:21 +00002173Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002174 return get(Instruction::FDiv, C1, C2);
2175}
2176
Chris Lattnera676c0f2011-02-07 16:40:21 +00002177Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002178 return get(Instruction::URem, C1, C2);
2179}
2180
Chris Lattnera676c0f2011-02-07 16:40:21 +00002181Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002182 return get(Instruction::SRem, C1, C2);
2183}
2184
Chris Lattnera676c0f2011-02-07 16:40:21 +00002185Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002186 return get(Instruction::FRem, C1, C2);
2187}
2188
Chris Lattnera676c0f2011-02-07 16:40:21 +00002189Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002190 return get(Instruction::And, C1, C2);
2191}
2192
Chris Lattnera676c0f2011-02-07 16:40:21 +00002193Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002194 return get(Instruction::Or, C1, C2);
2195}
2196
Chris Lattnera676c0f2011-02-07 16:40:21 +00002197Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002198 return get(Instruction::Xor, C1, C2);
2199}
2200
Chris Lattnere9b4ad72011-02-10 07:01:55 +00002201Constant *ConstantExpr::getShl(Constant *C1, Constant *C2,
2202 bool HasNUW, bool HasNSW) {
2203 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2204 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2205 return get(Instruction::Shl, C1, C2, Flags);
Owen Anderson487375e2009-07-29 18:55:55 +00002206}
2207
Chris Lattner0d75eac2011-02-09 16:43:07 +00002208Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2, bool isExact) {
2209 return get(Instruction::LShr, C1, C2,
2210 isExact ? PossiblyExactOperator::IsExact : 0);
Owen Anderson487375e2009-07-29 18:55:55 +00002211}
2212
Chris Lattner0d75eac2011-02-09 16:43:07 +00002213Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2, bool isExact) {
2214 return get(Instruction::AShr, C1, C2,
2215 isExact ? PossiblyExactOperator::IsExact : 0);
Owen Anderson487375e2009-07-29 18:55:55 +00002216}
2217
Duncan Sandsd7aeefe2012-06-12 14:33:56 +00002218Constant *ConstantExpr::getBinOpIdentity(unsigned Opcode, Type *Ty) {
2219 switch (Opcode) {
2220 default:
Duncan Sands318a89d2012-06-13 09:42:13 +00002221 // Doesn't have an identity.
Craig Topperc6207612014-04-09 06:08:46 +00002222 return nullptr;
Duncan Sands318a89d2012-06-13 09:42:13 +00002223
Duncan Sandsd7aeefe2012-06-12 14:33:56 +00002224 case Instruction::Add:
2225 case Instruction::Or:
2226 case Instruction::Xor:
2227 return Constant::getNullValue(Ty);
2228
2229 case Instruction::Mul:
2230 return ConstantInt::get(Ty, 1);
2231
2232 case Instruction::And:
2233 return Constant::getAllOnesValue(Ty);
2234 }
2235}
2236
Duncan Sands318a89d2012-06-13 09:42:13 +00002237Constant *ConstantExpr::getBinOpAbsorber(unsigned Opcode, Type *Ty) {
2238 switch (Opcode) {
2239 default:
2240 // Doesn't have an absorber.
Craig Topperc6207612014-04-09 06:08:46 +00002241 return nullptr;
Duncan Sands318a89d2012-06-13 09:42:13 +00002242
2243 case Instruction::Or:
2244 return Constant::getAllOnesValue(Ty);
2245
2246 case Instruction::And:
2247 case Instruction::Mul:
2248 return Constant::getNullValue(Ty);
2249 }
2250}
2251
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00002252/// Remove the constant from the constant table.
Pete Cooper86dd4cf2015-06-23 21:55:11 +00002253void ConstantExpr::destroyConstantImpl() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002254 getType()->getContext().pImpl->ExprConstants.remove(this);
Vikram S. Adve4e537b22002-07-14 23:13:17 +00002255}
2256
Chris Lattner3cd8c562002-07-30 18:54:25 +00002257const char *ConstantExpr::getOpcodeName() const {
2258 return Instruction::getOpcodeName(getOpcode());
Vikram S. Adve4e537b22002-07-14 23:13:17 +00002259}
Reid Spencer1ebe1ab2004-07-17 23:48:33 +00002260
David Blaikie60310f22015-05-08 00:42:26 +00002261GetElementPtrConstantExpr::GetElementPtrConstantExpr(
2262 Type *SrcElementTy, Constant *C, ArrayRef<Constant *> IdxList, Type *DestTy)
2263 : ConstantExpr(DestTy, Instruction::GetElementPtr,
2264 OperandTraits<GetElementPtrConstantExpr>::op_end(this) -
2265 (IdxList.size() + 1),
2266 IdxList.size() + 1),
Eduard Burtescu19eb0312016-01-19 17:28:00 +00002267 SrcElementTy(SrcElementTy),
2268 ResElementTy(GetElementPtrInst::getIndexedType(SrcElementTy, IdxList)) {
Pete Coopereb31b682015-05-21 22:48:54 +00002269 Op<0>() = C;
Pete Cooper74510a42015-06-12 17:48:05 +00002270 Use *OperandList = getOperandList();
Chris Lattnera3b94ba2010-03-30 20:48:48 +00002271 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
2272 OperandList[i+1] = IdxList[i];
2273}
2274
David Blaikie60310f22015-05-08 00:42:26 +00002275Type *GetElementPtrConstantExpr::getSourceElementType() const {
2276 return SrcElementTy;
2277}
2278
Eduard Burtescu19eb0312016-01-19 17:28:00 +00002279Type *GetElementPtrConstantExpr::getResultElementType() const {
2280 return ResElementTy;
2281}
2282
Chris Lattner3756b912012-01-23 22:57:10 +00002283//===----------------------------------------------------------------------===//
2284// ConstantData* implementations
2285
2286void ConstantDataArray::anchor() {}
2287void ConstantDataVector::anchor() {}
2288
Chris Lattnere4f3f102012-01-24 04:43:41 +00002289Type *ConstantDataSequential::getElementType() const {
2290 return getType()->getElementType();
2291}
2292
Chris Lattner5d4497b2012-01-24 09:31:43 +00002293StringRef ConstantDataSequential::getRawDataValues() const {
Chris Lattner00245f42012-01-24 13:41:11 +00002294 return StringRef(DataElements, getNumElements()*getElementByteSize());
Chris Lattner5d4497b2012-01-24 09:31:43 +00002295}
2296
Craig Toppere3dcce92015-08-01 22:20:21 +00002297bool ConstantDataSequential::isElementTypeCompatible(Type *Ty) {
Justin Bogner0ebc8602015-12-08 03:01:16 +00002298 if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) return true;
Craig Toppere3dcce92015-08-01 22:20:21 +00002299 if (auto *IT = dyn_cast<IntegerType>(Ty)) {
Chris Lattnere4f3f102012-01-24 04:43:41 +00002300 switch (IT->getBitWidth()) {
2301 case 8:
2302 case 16:
2303 case 32:
2304 case 64:
2305 return true;
2306 default: break;
2307 }
2308 }
2309 return false;
2310}
2311
Chris Lattner00245f42012-01-24 13:41:11 +00002312unsigned ConstantDataSequential::getNumElements() const {
Chris Lattner8a3df542012-01-25 01:32:59 +00002313 if (ArrayType *AT = dyn_cast<ArrayType>(getType()))
2314 return AT->getNumElements();
Chris Lattner8326bd82012-01-26 00:42:34 +00002315 return getType()->getVectorNumElements();
Chris Lattner00245f42012-01-24 13:41:11 +00002316}
2317
2318
Chris Lattnere4f3f102012-01-24 04:43:41 +00002319uint64_t ConstantDataSequential::getElementByteSize() const {
2320 return getElementType()->getPrimitiveSizeInBits()/8;
2321}
2322
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00002323/// Return the start of the specified element.
Chris Lattnere4f3f102012-01-24 04:43:41 +00002324const char *ConstantDataSequential::getElementPointer(unsigned Elt) const {
Chris Lattner00245f42012-01-24 13:41:11 +00002325 assert(Elt < getNumElements() && "Invalid Elt");
Chris Lattnere4f3f102012-01-24 04:43:41 +00002326 return DataElements+Elt*getElementByteSize();
2327}
2328
2329
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00002330/// Return true if the array is empty or all zeros.
Chris Lattner3756b912012-01-23 22:57:10 +00002331static bool isAllZeros(StringRef Arr) {
Benjamin Krameraf28e7d2016-06-26 14:10:56 +00002332 for (char I : Arr)
2333 if (I != 0)
Chris Lattner3756b912012-01-23 22:57:10 +00002334 return false;
2335 return true;
2336}
Chris Lattner030af792012-01-24 05:42:11 +00002337
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00002338/// This is the underlying implementation of all of the
Chris Lattner3756b912012-01-23 22:57:10 +00002339/// ConstantDataSequential::get methods. They all thunk down to here, providing
Chris Lattnerf06039b2012-01-30 18:19:30 +00002340/// the correct element type. We take the bytes in as a StringRef because
Chris Lattner3756b912012-01-23 22:57:10 +00002341/// we *want* an underlying "char*" to avoid TBAA type punning violations.
2342Constant *ConstantDataSequential::getImpl(StringRef Elements, Type *Ty) {
Chris Lattner8326bd82012-01-26 00:42:34 +00002343 assert(isElementTypeCompatible(Ty->getSequentialElementType()));
Chris Lattner139822f2012-01-24 14:17:05 +00002344 // If the elements are all zero or there are no elements, return a CAZ, which
2345 // is more dense and canonical.
Chris Lattner3756b912012-01-23 22:57:10 +00002346 if (isAllZeros(Elements))
2347 return ConstantAggregateZero::get(Ty);
2348
2349 // Do a lookup to see if we have already formed one of these.
David Blaikie5106ce72014-11-19 05:49:42 +00002350 auto &Slot =
2351 *Ty->getContext()
2352 .pImpl->CDSConstants.insert(std::make_pair(Elements, nullptr))
2353 .first;
Galina Kistanovafc259902012-07-13 01:25:27 +00002354
Chris Lattner3756b912012-01-23 22:57:10 +00002355 // The bucket can point to a linked list of different CDS's that have the same
2356 // body but different types. For example, 0,0,0,1 could be a 4 element array
2357 // of i8, or a 1-element array of i32. They'll both end up in the same
2358 /// StringMap bucket, linked up by their Next pointers. Walk the list.
David Blaikie5106ce72014-11-19 05:49:42 +00002359 ConstantDataSequential **Entry = &Slot.second;
Craig Topperc6207612014-04-09 06:08:46 +00002360 for (ConstantDataSequential *Node = *Entry; Node;
Chris Lattner3756b912012-01-23 22:57:10 +00002361 Entry = &Node->Next, Node = *Entry)
2362 if (Node->getType() == Ty)
2363 return Node;
Galina Kistanovafc259902012-07-13 01:25:27 +00002364
Chris Lattner3756b912012-01-23 22:57:10 +00002365 // Okay, we didn't get a hit. Create a node of the right class, link it in,
2366 // and return it.
2367 if (isa<ArrayType>(Ty))
David Blaikie5106ce72014-11-19 05:49:42 +00002368 return *Entry = new ConstantDataArray(Ty, Slot.first().data());
Chris Lattner3756b912012-01-23 22:57:10 +00002369
2370 assert(isa<VectorType>(Ty));
David Blaikie5106ce72014-11-19 05:49:42 +00002371 return *Entry = new ConstantDataVector(Ty, Slot.first().data());
Chris Lattner3756b912012-01-23 22:57:10 +00002372}
2373
Pete Cooper86dd4cf2015-06-23 21:55:11 +00002374void ConstantDataSequential::destroyConstantImpl() {
Chris Lattner3756b912012-01-23 22:57:10 +00002375 // Remove the constant from the StringMap.
2376 StringMap<ConstantDataSequential*> &CDSConstants =
2377 getType()->getContext().pImpl->CDSConstants;
Galina Kistanovafc259902012-07-13 01:25:27 +00002378
Chris Lattner3756b912012-01-23 22:57:10 +00002379 StringMap<ConstantDataSequential*>::iterator Slot =
Chris Lattner5d4497b2012-01-24 09:31:43 +00002380 CDSConstants.find(getRawDataValues());
Chris Lattner3756b912012-01-23 22:57:10 +00002381
2382 assert(Slot != CDSConstants.end() && "CDS not found in uniquing table");
2383
2384 ConstantDataSequential **Entry = &Slot->getValue();
2385
2386 // Remove the entry from the hash table.
Craig Topperc6207612014-04-09 06:08:46 +00002387 if (!(*Entry)->Next) {
Chris Lattner3756b912012-01-23 22:57:10 +00002388 // If there is only one value in the bucket (common case) it must be this
2389 // entry, and removing the entry should remove the bucket completely.
2390 assert((*Entry) == this && "Hash mismatch in ConstantDataSequential");
2391 getContext().pImpl->CDSConstants.erase(Slot);
2392 } else {
2393 // Otherwise, there are multiple entries linked off the bucket, unlink the
2394 // node we care about but keep the bucket around.
2395 for (ConstantDataSequential *Node = *Entry; ;
2396 Entry = &Node->Next, Node = *Entry) {
2397 assert(Node && "Didn't find entry in its uniquing hash table!");
2398 // If we found our entry, unlink it from the list and we're done.
2399 if (Node == this) {
2400 *Entry = Node->Next;
2401 break;
2402 }
2403 }
2404 }
Galina Kistanovafc259902012-07-13 01:25:27 +00002405
Chris Lattner3756b912012-01-23 22:57:10 +00002406 // If we were part of a list, make sure that we don't delete the list that is
2407 // still owned by the uniquing map.
Craig Topperc6207612014-04-09 06:08:46 +00002408 Next = nullptr;
Chris Lattner3756b912012-01-23 22:57:10 +00002409}
2410
2411/// get() constructors - Return a constant with array type with an element
2412/// count and element type matching the ArrayRef passed in. Note that this
2413/// can return a ConstantAggregateZero object.
Chris Lattner20683932012-01-24 14:04:40 +00002414Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint8_t> Elts) {
Chris Lattner3756b912012-01-23 22:57:10 +00002415 Type *Ty = ArrayType::get(Type::getInt8Ty(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002416 const char *Data = reinterpret_cast<const char *>(Elts.data());
2417 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*1), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002418}
Chris Lattner20683932012-01-24 14:04:40 +00002419Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint16_t> Elts){
Chris Lattner3756b912012-01-23 22:57:10 +00002420 Type *Ty = ArrayType::get(Type::getInt16Ty(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002421 const char *Data = reinterpret_cast<const char *>(Elts.data());
2422 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*2), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002423}
Chris Lattner20683932012-01-24 14:04:40 +00002424Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint32_t> Elts){
Chris Lattner3756b912012-01-23 22:57:10 +00002425 Type *Ty = ArrayType::get(Type::getInt32Ty(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002426 const char *Data = reinterpret_cast<const char *>(Elts.data());
2427 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002428}
Chris Lattner20683932012-01-24 14:04:40 +00002429Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint64_t> Elts){
Chris Lattner3756b912012-01-23 22:57:10 +00002430 Type *Ty = ArrayType::get(Type::getInt64Ty(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002431 const char *Data = reinterpret_cast<const char *>(Elts.data());
2432 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*8), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002433}
Chris Lattner20683932012-01-24 14:04:40 +00002434Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<float> Elts) {
Chris Lattner3756b912012-01-23 22:57:10 +00002435 Type *Ty = ArrayType::get(Type::getFloatTy(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002436 const char *Data = reinterpret_cast<const char *>(Elts.data());
2437 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002438}
Chris Lattner20683932012-01-24 14:04:40 +00002439Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<double> Elts) {
Chris Lattner3756b912012-01-23 22:57:10 +00002440 Type *Ty = ArrayType::get(Type::getDoubleTy(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002441 const char *Data = reinterpret_cast<const char *>(Elts.data());
Rafael Espindola8c97e192015-02-19 16:08:20 +00002442 return getImpl(StringRef(const_cast<char *>(Data), Elts.size() * 8), Ty);
2443}
2444
2445/// getFP() constructors - Return a constant with array type with an element
2446/// count and element type of float with precision matching the number of
2447/// bits in the ArrayRef passed in. (i.e. half for 16bits, float for 32bits,
2448/// double for 64bits) Note that this can return a ConstantAggregateZero
2449/// object.
2450Constant *ConstantDataArray::getFP(LLVMContext &Context,
2451 ArrayRef<uint16_t> Elts) {
Justin Bognerb7389d6712015-12-09 21:21:07 +00002452 Type *Ty = ArrayType::get(Type::getHalfTy(Context), Elts.size());
Rafael Espindola8c97e192015-02-19 16:08:20 +00002453 const char *Data = reinterpret_cast<const char *>(Elts.data());
2454 return getImpl(StringRef(const_cast<char *>(Data), Elts.size() * 2), Ty);
2455}
2456Constant *ConstantDataArray::getFP(LLVMContext &Context,
2457 ArrayRef<uint32_t> Elts) {
2458 Type *Ty = ArrayType::get(Type::getFloatTy(Context), Elts.size());
2459 const char *Data = reinterpret_cast<const char *>(Elts.data());
2460 return getImpl(StringRef(const_cast<char *>(Data), Elts.size() * 4), Ty);
2461}
2462Constant *ConstantDataArray::getFP(LLVMContext &Context,
2463 ArrayRef<uint64_t> Elts) {
2464 Type *Ty = ArrayType::get(Type::getDoubleTy(Context), Elts.size());
2465 const char *Data = reinterpret_cast<const char *>(Elts.data());
2466 return getImpl(StringRef(const_cast<char *>(Data), Elts.size() * 8), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002467}
2468
Chris Lattner20683932012-01-24 14:04:40 +00002469Constant *ConstantDataArray::getString(LLVMContext &Context,
2470 StringRef Str, bool AddNull) {
Galina Kistanovafc259902012-07-13 01:25:27 +00002471 if (!AddNull) {
2472 const uint8_t *Data = reinterpret_cast<const uint8_t *>(Str.data());
Craig Toppere1d12942014-08-27 05:25:25 +00002473 return get(Context, makeArrayRef(const_cast<uint8_t *>(Data),
Galina Kistanovafc259902012-07-13 01:25:27 +00002474 Str.size()));
2475 }
2476
Chris Lattner20683932012-01-24 14:04:40 +00002477 SmallVector<uint8_t, 64> ElementVals;
2478 ElementVals.append(Str.begin(), Str.end());
2479 ElementVals.push_back(0);
2480 return get(Context, ElementVals);
2481}
Chris Lattner3756b912012-01-23 22:57:10 +00002482
2483/// get() constructors - Return a constant with vector type with an element
2484/// count and element type matching the ArrayRef passed in. Note that this
2485/// can return a ConstantAggregateZero object.
Chris Lattner20683932012-01-24 14:04:40 +00002486Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint8_t> Elts){
Chris Lattner3756b912012-01-23 22:57:10 +00002487 Type *Ty = VectorType::get(Type::getInt8Ty(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002488 const char *Data = reinterpret_cast<const char *>(Elts.data());
2489 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*1), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002490}
Chris Lattner20683932012-01-24 14:04:40 +00002491Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint16_t> Elts){
Chris Lattner3756b912012-01-23 22:57:10 +00002492 Type *Ty = VectorType::get(Type::getInt16Ty(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002493 const char *Data = reinterpret_cast<const char *>(Elts.data());
2494 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*2), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002495}
Chris Lattner20683932012-01-24 14:04:40 +00002496Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint32_t> Elts){
Chris Lattner3756b912012-01-23 22:57:10 +00002497 Type *Ty = VectorType::get(Type::getInt32Ty(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002498 const char *Data = reinterpret_cast<const char *>(Elts.data());
2499 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002500}
Chris Lattner20683932012-01-24 14:04:40 +00002501Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint64_t> Elts){
Chris Lattner3756b912012-01-23 22:57:10 +00002502 Type *Ty = VectorType::get(Type::getInt64Ty(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002503 const char *Data = reinterpret_cast<const char *>(Elts.data());
2504 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*8), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002505}
Chris Lattner20683932012-01-24 14:04:40 +00002506Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<float> Elts) {
Chris Lattner3756b912012-01-23 22:57:10 +00002507 Type *Ty = VectorType::get(Type::getFloatTy(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002508 const char *Data = reinterpret_cast<const char *>(Elts.data());
2509 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002510}
Chris Lattner20683932012-01-24 14:04:40 +00002511Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<double> Elts) {
Chris Lattner3756b912012-01-23 22:57:10 +00002512 Type *Ty = VectorType::get(Type::getDoubleTy(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002513 const char *Data = reinterpret_cast<const char *>(Elts.data());
Rafael Espindola8c97e192015-02-19 16:08:20 +00002514 return getImpl(StringRef(const_cast<char *>(Data), Elts.size() * 8), Ty);
2515}
2516
2517/// getFP() constructors - Return a constant with vector type with an element
2518/// count and element type of float with the precision matching the number of
2519/// bits in the ArrayRef passed in. (i.e. half for 16bits, float for 32bits,
2520/// double for 64bits) Note that this can return a ConstantAggregateZero
2521/// object.
2522Constant *ConstantDataVector::getFP(LLVMContext &Context,
2523 ArrayRef<uint16_t> Elts) {
2524 Type *Ty = VectorType::get(Type::getHalfTy(Context), Elts.size());
2525 const char *Data = reinterpret_cast<const char *>(Elts.data());
2526 return getImpl(StringRef(const_cast<char *>(Data), Elts.size() * 2), Ty);
2527}
2528Constant *ConstantDataVector::getFP(LLVMContext &Context,
2529 ArrayRef<uint32_t> Elts) {
2530 Type *Ty = VectorType::get(Type::getFloatTy(Context), Elts.size());
2531 const char *Data = reinterpret_cast<const char *>(Elts.data());
2532 return getImpl(StringRef(const_cast<char *>(Data), Elts.size() * 4), Ty);
2533}
2534Constant *ConstantDataVector::getFP(LLVMContext &Context,
2535 ArrayRef<uint64_t> Elts) {
2536 Type *Ty = VectorType::get(Type::getDoubleTy(Context), Elts.size());
2537 const char *Data = reinterpret_cast<const char *>(Elts.data());
2538 return getImpl(StringRef(const_cast<char *>(Data), Elts.size() * 8), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002539}
2540
Chris Lattnere9eed292012-01-25 05:19:54 +00002541Constant *ConstantDataVector::getSplat(unsigned NumElts, Constant *V) {
2542 assert(isElementTypeCompatible(V->getType()) &&
2543 "Element type not compatible with ConstantData");
2544 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
2545 if (CI->getType()->isIntegerTy(8)) {
2546 SmallVector<uint8_t, 16> Elts(NumElts, CI->getZExtValue());
2547 return get(V->getContext(), Elts);
2548 }
2549 if (CI->getType()->isIntegerTy(16)) {
2550 SmallVector<uint16_t, 16> Elts(NumElts, CI->getZExtValue());
2551 return get(V->getContext(), Elts);
2552 }
2553 if (CI->getType()->isIntegerTy(32)) {
2554 SmallVector<uint32_t, 16> Elts(NumElts, CI->getZExtValue());
2555 return get(V->getContext(), Elts);
2556 }
2557 assert(CI->getType()->isIntegerTy(64) && "Unsupported ConstantData type");
2558 SmallVector<uint64_t, 16> Elts(NumElts, CI->getZExtValue());
2559 return get(V->getContext(), Elts);
2560 }
2561
Chris Lattner978fe0c2012-01-30 06:21:21 +00002562 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
Justin Bogner0ebc8602015-12-08 03:01:16 +00002563 if (CFP->getType()->isHalfTy()) {
2564 SmallVector<uint16_t, 16> Elts(
2565 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
2566 return getFP(V->getContext(), Elts);
2567 }
Chris Lattner978fe0c2012-01-30 06:21:21 +00002568 if (CFP->getType()->isFloatTy()) {
Rafael Espindola8c97e192015-02-19 16:08:20 +00002569 SmallVector<uint32_t, 16> Elts(
2570 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
2571 return getFP(V->getContext(), Elts);
Chris Lattner978fe0c2012-01-30 06:21:21 +00002572 }
2573 if (CFP->getType()->isDoubleTy()) {
Rafael Espindola8c97e192015-02-19 16:08:20 +00002574 SmallVector<uint64_t, 16> Elts(
2575 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
2576 return getFP(V->getContext(), Elts);
Chris Lattner978fe0c2012-01-30 06:21:21 +00002577 }
Chris Lattnere9eed292012-01-25 05:19:54 +00002578 }
Chris Lattner978fe0c2012-01-30 06:21:21 +00002579 return ConstantVector::getSplat(NumElts, V);
Chris Lattnere9eed292012-01-25 05:19:54 +00002580}
2581
2582
Chris Lattnere4f3f102012-01-24 04:43:41 +00002583uint64_t ConstantDataSequential::getElementAsInteger(unsigned Elt) const {
2584 assert(isa<IntegerType>(getElementType()) &&
2585 "Accessor can only be used when element is an integer");
2586 const char *EltPtr = getElementPointer(Elt);
Galina Kistanovafc259902012-07-13 01:25:27 +00002587
Chris Lattnere4f3f102012-01-24 04:43:41 +00002588 // The data is stored in host byte order, make sure to cast back to the right
2589 // type to load with the right endianness.
Chris Lattner8326bd82012-01-26 00:42:34 +00002590 switch (getElementType()->getIntegerBitWidth()) {
Craig Topperc514b542012-02-05 22:14:15 +00002591 default: llvm_unreachable("Invalid bitwidth for CDS");
Galina Kistanovafc259902012-07-13 01:25:27 +00002592 case 8:
2593 return *const_cast<uint8_t *>(reinterpret_cast<const uint8_t *>(EltPtr));
2594 case 16:
2595 return *const_cast<uint16_t *>(reinterpret_cast<const uint16_t *>(EltPtr));
2596 case 32:
2597 return *const_cast<uint32_t *>(reinterpret_cast<const uint32_t *>(EltPtr));
2598 case 64:
2599 return *const_cast<uint64_t *>(reinterpret_cast<const uint64_t *>(EltPtr));
Chris Lattnere4f3f102012-01-24 04:43:41 +00002600 }
2601}
2602
Chris Lattnere4f3f102012-01-24 04:43:41 +00002603APFloat ConstantDataSequential::getElementAsAPFloat(unsigned Elt) const {
2604 const char *EltPtr = getElementPointer(Elt);
2605
2606 switch (getElementType()->getTypeID()) {
Nick Lewyckyff509622012-01-25 03:20:12 +00002607 default:
Craig Topperc514b542012-02-05 22:14:15 +00002608 llvm_unreachable("Accessor can only be used when element is float/double!");
Justin Bogner0ebc8602015-12-08 03:01:16 +00002609 case Type::HalfTyID: {
2610 auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
2611 return APFloat(APFloat::IEEEhalf, APInt(16, EltVal));
2612 }
Benjamin Kramer7af984b2015-02-20 15:11:55 +00002613 case Type::FloatTyID: {
2614 auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr);
NAKAMURA Takumie86b9b72015-02-20 14:24:49 +00002615 return APFloat(APFloat::IEEEsingle, APInt(32, EltVal));
Benjamin Kramer7af984b2015-02-20 15:11:55 +00002616 }
2617 case Type::DoubleTyID: {
2618 auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr);
NAKAMURA Takumie86b9b72015-02-20 14:24:49 +00002619 return APFloat(APFloat::IEEEdouble, APInt(64, EltVal));
Chris Lattnere4f3f102012-01-24 04:43:41 +00002620 }
Benjamin Kramer7af984b2015-02-20 15:11:55 +00002621 }
Chris Lattnere4f3f102012-01-24 04:43:41 +00002622}
2623
Chris Lattnere4f3f102012-01-24 04:43:41 +00002624float ConstantDataSequential::getElementAsFloat(unsigned Elt) const {
2625 assert(getElementType()->isFloatTy() &&
2626 "Accessor can only be used when element is a 'float'");
Galina Kistanovafc259902012-07-13 01:25:27 +00002627 const float *EltPtr = reinterpret_cast<const float *>(getElementPointer(Elt));
2628 return *const_cast<float *>(EltPtr);
Chris Lattnere4f3f102012-01-24 04:43:41 +00002629}
2630
Chris Lattnere4f3f102012-01-24 04:43:41 +00002631double ConstantDataSequential::getElementAsDouble(unsigned Elt) const {
2632 assert(getElementType()->isDoubleTy() &&
2633 "Accessor can only be used when element is a 'float'");
Galina Kistanovafc259902012-07-13 01:25:27 +00002634 const double *EltPtr =
2635 reinterpret_cast<const double *>(getElementPointer(Elt));
2636 return *const_cast<double *>(EltPtr);
Chris Lattnere4f3f102012-01-24 04:43:41 +00002637}
2638
Chris Lattnere4f3f102012-01-24 04:43:41 +00002639Constant *ConstantDataSequential::getElementAsConstant(unsigned Elt) const {
Justin Bogner0ebc8602015-12-08 03:01:16 +00002640 if (getElementType()->isHalfTy() || getElementType()->isFloatTy() ||
2641 getElementType()->isDoubleTy())
Chris Lattnere4f3f102012-01-24 04:43:41 +00002642 return ConstantFP::get(getContext(), getElementAsAPFloat(Elt));
Galina Kistanovafc259902012-07-13 01:25:27 +00002643
Chris Lattnere4f3f102012-01-24 04:43:41 +00002644 return ConstantInt::get(getElementType(), getElementAsInteger(Elt));
2645}
2646
Chris Lattner5dd4d872012-01-24 09:01:07 +00002647bool ConstantDataSequential::isString() const {
2648 return isa<ArrayType>(getType()) && getElementType()->isIntegerTy(8);
2649}
Chris Lattner3756b912012-01-23 22:57:10 +00002650
Chris Lattner5dd4d872012-01-24 09:01:07 +00002651bool ConstantDataSequential::isCString() const {
2652 if (!isString())
2653 return false;
Galina Kistanovafc259902012-07-13 01:25:27 +00002654
Chris Lattner5dd4d872012-01-24 09:01:07 +00002655 StringRef Str = getAsString();
Galina Kistanovafc259902012-07-13 01:25:27 +00002656
Chris Lattner5dd4d872012-01-24 09:01:07 +00002657 // The last value must be nul.
2658 if (Str.back() != 0) return false;
Galina Kistanovafc259902012-07-13 01:25:27 +00002659
Chris Lattner5dd4d872012-01-24 09:01:07 +00002660 // Other elements must be non-nul.
2661 return Str.drop_back().find(0) == StringRef::npos;
2662}
Chris Lattner3756b912012-01-23 22:57:10 +00002663
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002664Constant *ConstantDataVector::getSplatValue() const {
2665 const char *Base = getRawDataValues().data();
Galina Kistanovafc259902012-07-13 01:25:27 +00002666
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002667 // Compare elements 1+ to the 0'th element.
2668 unsigned EltSize = getElementByteSize();
2669 for (unsigned i = 1, e = getNumElements(); i != e; ++i)
2670 if (memcmp(Base, Base+i*EltSize, EltSize))
Craig Topperc6207612014-04-09 06:08:46 +00002671 return nullptr;
Galina Kistanovafc259902012-07-13 01:25:27 +00002672
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002673 // If they're all the same, return the 0th one as a representative.
2674 return getElementAsConstant(0);
2675}
Chris Lattnera3b94ba2010-03-30 20:48:48 +00002676
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002677//===----------------------------------------------------------------------===//
Pete Cooper5815b1f2015-06-24 18:55:24 +00002678// handleOperandChange implementations
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002679
Pete Cooper5815b1f2015-06-24 18:55:24 +00002680/// Update this constant array to change uses of
Chris Lattner913849b2007-08-21 00:55:23 +00002681/// 'From' to be uses of 'To'. This must update the uniquing data structures
2682/// etc.
2683///
2684/// Note that we intentionally replace all uses of From with To here. Consider
2685/// a large array that uses 'From' 1000 times. By handling this case all here,
Pete Cooper5815b1f2015-06-24 18:55:24 +00002686/// ConstantArray::handleOperandChange is only invoked once, and that
Chris Lattner913849b2007-08-21 00:55:23 +00002687/// single invocation handles all 1000 uses. Handling them one at a time would
2688/// work, but would be really slow because it would have to unique each updated
2689/// array instance.
Chris Lattner31b132c2009-10-28 00:01:44 +00002690///
Mehdi Amini8914d292016-02-10 22:47:15 +00002691void Constant::handleOperandChange(Value *From, Value *To) {
Pete Cooper5815b1f2015-06-24 18:55:24 +00002692 Value *Replacement = nullptr;
2693 switch (getValueID()) {
2694 default:
2695 llvm_unreachable("Not a constant!");
2696#define HANDLE_CONSTANT(Name) \
2697 case Value::Name##Val: \
Mehdi Amini8914d292016-02-10 22:47:15 +00002698 Replacement = cast<Name>(this)->handleOperandChangeImpl(From, To); \
Pete Cooper5815b1f2015-06-24 18:55:24 +00002699 break;
2700#include "llvm/IR/Value.def"
2701 }
2702
2703 // If handleOperandChangeImpl returned nullptr, then it handled
2704 // replacing itself and we don't want to delete or replace anything else here.
2705 if (!Replacement)
2706 return;
2707
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002708 // I do need to replace this with an existing value.
2709 assert(Replacement != this && "I didn't contain From!");
2710
2711 // Everyone using this now uses the replacement.
2712 replaceAllUsesWith(Replacement);
2713
2714 // Delete the old constant!
2715 destroyConstant();
2716}
2717
Mehdi Amini8914d292016-02-10 22:47:15 +00002718Value *ConstantArray::handleOperandChangeImpl(Value *From, Value *To) {
Owen Andersonc2c79322009-07-28 18:32:17 +00002719 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2720 Constant *ToC = cast<Constant>(To);
2721
Talin46e9b442012-02-05 20:54:10 +00002722 SmallVector<Constant*, 8> Values;
Owen Andersonc2c79322009-07-28 18:32:17 +00002723 Values.reserve(getNumOperands()); // Build replacement array.
2724
Galina Kistanovafc259902012-07-13 01:25:27 +00002725 // Fill values with the modified operands of the constant array. Also,
Owen Andersonc2c79322009-07-28 18:32:17 +00002726 // compute whether this turns into an all-zeros array.
Owen Andersonc2c79322009-07-28 18:32:17 +00002727 unsigned NumUpdated = 0;
Galina Kistanovafc259902012-07-13 01:25:27 +00002728
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002729 // Keep track of whether all the values in the array are "ToC".
2730 bool AllSame = true;
Pete Cooper74510a42015-06-12 17:48:05 +00002731 Use *OperandList = getOperandList();
Mehdi Amini8914d292016-02-10 22:47:15 +00002732 unsigned OperandNo = 0;
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002733 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2734 Constant *Val = cast<Constant>(O->get());
2735 if (Val == From) {
Mehdi Amini8914d292016-02-10 22:47:15 +00002736 OperandNo = (O - OperandList);
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002737 Val = ToC;
2738 ++NumUpdated;
Owen Andersonc2c79322009-07-28 18:32:17 +00002739 }
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002740 Values.push_back(Val);
Talin46e9b442012-02-05 20:54:10 +00002741 AllSame &= Val == ToC;
Owen Andersonc2c79322009-07-28 18:32:17 +00002742 }
Galina Kistanovafc259902012-07-13 01:25:27 +00002743
Pete Cooper5815b1f2015-06-24 18:55:24 +00002744 if (AllSame && ToC->isNullValue())
2745 return ConstantAggregateZero::get(getType());
2746
2747 if (AllSame && isa<UndefValue>(ToC))
2748 return UndefValue::get(getType());
Aaron Ballmane4b91dc2014-08-19 14:59:02 +00002749
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002750 // Check for any other type of constant-folding.
Pete Cooper5815b1f2015-06-24 18:55:24 +00002751 if (Constant *C = getImpl(getType(), Values))
2752 return C;
Aaron Ballmane4b91dc2014-08-19 14:59:02 +00002753
Duncan P. N. Exon Smith909620a2014-08-19 19:13:30 +00002754 // Update to the new value.
Pete Cooper5815b1f2015-06-24 18:55:24 +00002755 return getContext().pImpl->ArrayConstants.replaceOperandsInPlace(
Mehdi Amini8914d292016-02-10 22:47:15 +00002756 Values, this, From, ToC, NumUpdated, OperandNo);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002757}
2758
Mehdi Amini8914d292016-02-10 22:47:15 +00002759Value *ConstantStruct::handleOperandChangeImpl(Value *From, Value *To) {
Owen Anderson45308b52009-07-27 22:29:26 +00002760 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2761 Constant *ToC = cast<Constant>(To);
2762
Pete Cooper74510a42015-06-12 17:48:05 +00002763 Use *OperandList = getOperandList();
Owen Anderson45308b52009-07-27 22:29:26 +00002764
Talin46e9b442012-02-05 20:54:10 +00002765 SmallVector<Constant*, 8> Values;
Owen Anderson45308b52009-07-27 22:29:26 +00002766 Values.reserve(getNumOperands()); // Build replacement struct.
Galina Kistanovafc259902012-07-13 01:25:27 +00002767
2768 // Fill values with the modified operands of the constant struct. Also,
Owen Anderson45308b52009-07-27 22:29:26 +00002769 // compute whether this turns into an all-zeros struct.
Mehdi Amini8914d292016-02-10 22:47:15 +00002770 unsigned NumUpdated = 0;
2771 bool AllSame = true;
2772 unsigned OperandNo = 0;
2773 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O) {
2774 Constant *Val = cast<Constant>(O->get());
2775 if (Val == From) {
2776 OperandNo = (O - OperandList);
2777 Val = ToC;
2778 ++NumUpdated;
Owen Anderson45308b52009-07-27 22:29:26 +00002779 }
Mehdi Amini8914d292016-02-10 22:47:15 +00002780 Values.push_back(Val);
2781 AllSame &= Val == ToC;
Owen Anderson45308b52009-07-27 22:29:26 +00002782 }
Galina Kistanovafc259902012-07-13 01:25:27 +00002783
Mehdi Amini8914d292016-02-10 22:47:15 +00002784 if (AllSame && ToC->isNullValue())
Pete Cooper5815b1f2015-06-24 18:55:24 +00002785 return ConstantAggregateZero::get(getType());
2786
Mehdi Amini8914d292016-02-10 22:47:15 +00002787 if (AllSame && isa<UndefValue>(ToC))
Pete Cooper5815b1f2015-06-24 18:55:24 +00002788 return UndefValue::get(getType());
Galina Kistanovafc259902012-07-13 01:25:27 +00002789
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002790 // Update to the new value.
Pete Cooper5815b1f2015-06-24 18:55:24 +00002791 return getContext().pImpl->StructConstants.replaceOperandsInPlace(
Mehdi Amini8914d292016-02-10 22:47:15 +00002792 Values, this, From, ToC, NumUpdated, OperandNo);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002793}
2794
Mehdi Amini8914d292016-02-10 22:47:15 +00002795Value *ConstantVector::handleOperandChangeImpl(Value *From, Value *To) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002796 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002797 Constant *ToC = cast<Constant>(To);
Galina Kistanovafc259902012-07-13 01:25:27 +00002798
Chris Lattnera474bb22012-01-26 20:40:56 +00002799 SmallVector<Constant*, 8> Values;
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002800 Values.reserve(getNumOperands()); // Build replacement array...
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002801 unsigned NumUpdated = 0;
Mehdi Amini8914d292016-02-10 22:47:15 +00002802 unsigned OperandNo = 0;
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002803 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2804 Constant *Val = getOperand(i);
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002805 if (Val == From) {
Mehdi Amini8914d292016-02-10 22:47:15 +00002806 OperandNo = i;
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002807 ++NumUpdated;
2808 Val = ToC;
2809 }
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002810 Values.push_back(Val);
2811 }
Galina Kistanovafc259902012-07-13 01:25:27 +00002812
Pete Cooper5815b1f2015-06-24 18:55:24 +00002813 if (Constant *C = getImpl(Values))
2814 return C;
Duncan P. N. Exon Smith687744d2014-08-19 02:24:46 +00002815
Duncan P. N. Exon Smith909620a2014-08-19 19:13:30 +00002816 // Update to the new value.
Pete Cooper5815b1f2015-06-24 18:55:24 +00002817 return getContext().pImpl->VectorConstants.replaceOperandsInPlace(
Mehdi Amini8914d292016-02-10 22:47:15 +00002818 Values, this, From, ToC, NumUpdated, OperandNo);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002819}
2820
Mehdi Amini8914d292016-02-10 22:47:15 +00002821Value *ConstantExpr::handleOperandChangeImpl(Value *From, Value *ToV) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002822 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2823 Constant *To = cast<Constant>(ToV);
Galina Kistanovafc259902012-07-13 01:25:27 +00002824
Chris Lattner37e38352012-01-26 20:37:11 +00002825 SmallVector<Constant*, 8> NewOps;
Duncan P. N. Exon Smith33de00c2014-08-19 20:03:35 +00002826 unsigned NumUpdated = 0;
Mehdi Amini8914d292016-02-10 22:47:15 +00002827 unsigned OperandNo = 0;
Chris Lattner37e38352012-01-26 20:37:11 +00002828 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2829 Constant *Op = getOperand(i);
Duncan P. N. Exon Smith33de00c2014-08-19 20:03:35 +00002830 if (Op == From) {
Mehdi Amini8914d292016-02-10 22:47:15 +00002831 OperandNo = i;
Duncan P. N. Exon Smith33de00c2014-08-19 20:03:35 +00002832 ++NumUpdated;
2833 Op = To;
2834 }
2835 NewOps.push_back(Op);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002836 }
Duncan P. N. Exon Smith33de00c2014-08-19 20:03:35 +00002837 assert(NumUpdated && "I didn't contain From!");
Galina Kistanovafc259902012-07-13 01:25:27 +00002838
Pete Cooper5815b1f2015-06-24 18:55:24 +00002839 if (Constant *C = getWithOperands(NewOps, getType(), true))
2840 return C;
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002841
Duncan P. N. Exon Smith33de00c2014-08-19 20:03:35 +00002842 // Update to the new value.
Pete Cooper5815b1f2015-06-24 18:55:24 +00002843 return getContext().pImpl->ExprConstants.replaceOperandsInPlace(
Mehdi Amini8914d292016-02-10 22:47:15 +00002844 NewOps, this, From, To, NumUpdated, OperandNo);
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002845}
2846
James Molloyce545682012-11-17 17:56:30 +00002847Instruction *ConstantExpr::getAsInstruction() {
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00002848 SmallVector<Value *, 4> ValueOperands(op_begin(), op_end());
James Molloyce545682012-11-17 17:56:30 +00002849 ArrayRef<Value*> Ops(ValueOperands);
2850
2851 switch (getOpcode()) {
2852 case Instruction::Trunc:
2853 case Instruction::ZExt:
2854 case Instruction::SExt:
2855 case Instruction::FPTrunc:
2856 case Instruction::FPExt:
2857 case Instruction::UIToFP:
2858 case Instruction::SIToFP:
2859 case Instruction::FPToUI:
2860 case Instruction::FPToSI:
2861 case Instruction::PtrToInt:
2862 case Instruction::IntToPtr:
2863 case Instruction::BitCast:
Eli Bendersky157a97a2014-01-18 22:54:33 +00002864 case Instruction::AddrSpaceCast:
James Molloyce545682012-11-17 17:56:30 +00002865 return CastInst::Create((Instruction::CastOps)getOpcode(),
2866 Ops[0], getType());
2867 case Instruction::Select:
2868 return SelectInst::Create(Ops[0], Ops[1], Ops[2]);
2869 case Instruction::InsertElement:
2870 return InsertElementInst::Create(Ops[0], Ops[1], Ops[2]);
2871 case Instruction::ExtractElement:
2872 return ExtractElementInst::Create(Ops[0], Ops[1]);
2873 case Instruction::InsertValue:
2874 return InsertValueInst::Create(Ops[0], Ops[1], getIndices());
2875 case Instruction::ExtractValue:
2876 return ExtractValueInst::Create(Ops[0], getIndices());
2877 case Instruction::ShuffleVector:
2878 return new ShuffleVectorInst(Ops[0], Ops[1], Ops[2]);
2879
David Blaikie741c8f82015-03-14 01:53:18 +00002880 case Instruction::GetElementPtr: {
2881 const auto *GO = cast<GEPOperator>(this);
2882 if (GO->isInBounds())
2883 return GetElementPtrInst::CreateInBounds(GO->getSourceElementType(),
2884 Ops[0], Ops.slice(1));
2885 return GetElementPtrInst::Create(GO->getSourceElementType(), Ops[0],
2886 Ops.slice(1));
2887 }
James Molloyce545682012-11-17 17:56:30 +00002888 case Instruction::ICmp:
2889 case Instruction::FCmp:
2890 return CmpInst::Create((Instruction::OtherOps)getOpcode(),
Craig Topper1c3f2832015-12-15 06:11:33 +00002891 (CmpInst::Predicate)getPredicate(), Ops[0], Ops[1]);
James Molloyce545682012-11-17 17:56:30 +00002892
2893 default:
2894 assert(getNumOperands() == 2 && "Must be binary operator?");
2895 BinaryOperator *BO =
2896 BinaryOperator::Create((Instruction::BinaryOps)getOpcode(),
2897 Ops[0], Ops[1]);
2898 if (isa<OverflowingBinaryOperator>(BO)) {
2899 BO->setHasNoUnsignedWrap(SubclassOptionalData &
2900 OverflowingBinaryOperator::NoUnsignedWrap);
2901 BO->setHasNoSignedWrap(SubclassOptionalData &
2902 OverflowingBinaryOperator::NoSignedWrap);
2903 }
2904 if (isa<PossiblyExactOperator>(BO))
2905 BO->setIsExact(SubclassOptionalData & PossiblyExactOperator::IsExact);
2906 return BO;
2907 }
2908}