blob: e984aaca33bfff20ecb33b5807e02f69a2c0c1b2 [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"
17#include "llvm/ADT/DenseMap.h"
18#include "llvm/ADT/FoldingSet.h"
19#include "llvm/ADT/STLExtras.h"
20#include "llvm/ADT/SmallVector.h"
21#include "llvm/ADT/StringExtras.h"
22#include "llvm/ADT/StringMap.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/DerivedTypes.h"
24#include "llvm/IR/GlobalValue.h"
25#include "llvm/IR/Instructions.h"
26#include "llvm/IR/Module.h"
27#include "llvm/IR/Operator.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000028#include "llvm/Support/Compiler.h"
Bill Wendling6a462f12006-11-17 08:03:48 +000029#include "llvm/Support/Debug.h"
Torok Edwinccb29cd2009-07-11 13:10:19 +000030#include "llvm/Support/ErrorHandling.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000031#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner69edc982006-09-28 00:35:06 +000032#include "llvm/Support/ManagedStatic.h"
Bill Wendling6a462f12006-11-17 08:03:48 +000033#include "llvm/Support/MathExtras.h"
Chris Lattner78683a72009-08-23 04:02:03 +000034#include "llvm/Support/raw_ostream.h"
Chris Lattner2f7c9632001-06-06 20:29:01 +000035#include <algorithm>
Talin3a0a30d2011-02-28 23:53:27 +000036#include <cstdarg>
Chris Lattner189d19f2003-11-21 20:23:48 +000037using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000038
Chris Lattner2f7c9632001-06-06 20:29:01 +000039//===----------------------------------------------------------------------===//
Chris Lattner3462ae32001-12-03 22:26:30 +000040// Constant Class
Chris Lattner2f7c9632001-06-06 20:29:01 +000041//===----------------------------------------------------------------------===//
42
David Blaikiea379b1812011-12-20 02:50:00 +000043void Constant::anchor() { }
44
Chris Lattnerac5fb562011-07-15 05:58:04 +000045bool Constant::isNegativeZeroValue() const {
46 // Floating point values have an explicit -0.0 value.
47 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
48 return CFP->isZero() && CFP->isNegative();
Galina Kistanovafc259902012-07-13 01:25:27 +000049
Chris Lattnerac5fb562011-07-15 05:58:04 +000050 // Otherwise, just use +0.0.
51 return isNullValue();
52}
53
Shuxin Yang9ca562e2013-01-09 00:53:25 +000054// Return true iff this constant is positive zero (floating point), negative
55// zero (floating point), or a null value.
Shuxin Yangf0537ab2013-01-09 00:13:41 +000056bool Constant::isZeroValue() const {
57 // Floating point values have an explicit -0.0 value.
58 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
59 return CFP->isZero();
60
61 // Otherwise, just use +0.0.
62 return isNullValue();
63}
64
Chris Lattnerbe6610c2011-07-15 06:14:08 +000065bool Constant::isNullValue() const {
66 // 0 is null.
67 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
68 return CI->isZero();
Galina Kistanovafc259902012-07-13 01:25:27 +000069
Chris Lattnerbe6610c2011-07-15 06:14:08 +000070 // +0.0 is null.
71 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
72 return CFP->isZero() && !CFP->isNegative();
73
74 // constant zero is zero for aggregates and cpnull is null for pointers.
75 return isa<ConstantAggregateZero>(this) || isa<ConstantPointerNull>(this);
76}
77
Nadav Rotem365af6f2011-08-24 20:18:38 +000078bool Constant::isAllOnesValue() const {
79 // Check for -1 integers
80 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
81 return CI->isMinusOne();
82
83 // Check for FP which are bitcasted from -1 integers
84 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
85 return CFP->getValueAPF().bitcastToAPInt().isAllOnesValue();
86
Benjamin Kramer42d098e2011-11-14 19:12:20 +000087 // Check for constant vectors which are splats of -1 values.
Nadav Rotem365af6f2011-08-24 20:18:38 +000088 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
Benjamin Kramer42d098e2011-11-14 19:12:20 +000089 if (Constant *Splat = CV->getSplatValue())
90 return Splat->isAllOnesValue();
Nadav Rotem365af6f2011-08-24 20:18:38 +000091
Chris Lattnerf14a67f2012-01-26 02:31:22 +000092 // Check for constant vectors which are splats of -1 values.
93 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
94 if (Constant *Splat = CV->getSplatValue())
95 return Splat->isAllOnesValue();
96
Nadav Rotem365af6f2011-08-24 20:18:38 +000097 return false;
98}
Benjamin Kramer42d098e2011-11-14 19:12:20 +000099
Owen Anderson5a1acd92009-07-31 20:28:14 +0000100// Constructor to create a '0' constant of arbitrary type...
Chris Lattner229907c2011-07-18 04:54:35 +0000101Constant *Constant::getNullValue(Type *Ty) {
Owen Anderson5a1acd92009-07-31 20:28:14 +0000102 switch (Ty->getTypeID()) {
103 case Type::IntegerTyID:
104 return ConstantInt::get(Ty, 0);
Dan Gohman518cda42011-12-17 00:04:22 +0000105 case Type::HalfTyID:
106 return ConstantFP::get(Ty->getContext(),
107 APFloat::getZero(APFloat::IEEEhalf));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000108 case Type::FloatTyID:
Benjamin Kramer8ceebfa2010-12-04 14:22:24 +0000109 return ConstantFP::get(Ty->getContext(),
110 APFloat::getZero(APFloat::IEEEsingle));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000111 case Type::DoubleTyID:
Benjamin Kramer8ceebfa2010-12-04 14:22:24 +0000112 return ConstantFP::get(Ty->getContext(),
113 APFloat::getZero(APFloat::IEEEdouble));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000114 case Type::X86_FP80TyID:
Benjamin Kramer8ceebfa2010-12-04 14:22:24 +0000115 return ConstantFP::get(Ty->getContext(),
116 APFloat::getZero(APFloat::x87DoubleExtended));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000117 case Type::FP128TyID:
118 return ConstantFP::get(Ty->getContext(),
Benjamin Kramer8ceebfa2010-12-04 14:22:24 +0000119 APFloat::getZero(APFloat::IEEEquad));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000120 case Type::PPC_FP128TyID:
Benjamin Kramer8ceebfa2010-12-04 14:22:24 +0000121 return ConstantFP::get(Ty->getContext(),
Benjamin Kramer6f88fcb2010-12-04 14:43:08 +0000122 APFloat(APInt::getNullValue(128)));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000123 case Type::PointerTyID:
124 return ConstantPointerNull::get(cast<PointerType>(Ty));
125 case Type::StructTyID:
126 case Type::ArrayTyID:
127 case Type::VectorTyID:
128 return ConstantAggregateZero::get(Ty);
129 default:
130 // Function, Label, or Opaque type?
Craig Topperc514b542012-02-05 22:14:15 +0000131 llvm_unreachable("Cannot create a null constant of that type!");
Owen Anderson5a1acd92009-07-31 20:28:14 +0000132 }
133}
134
Chris Lattner229907c2011-07-18 04:54:35 +0000135Constant *Constant::getIntegerValue(Type *Ty, const APInt &V) {
136 Type *ScalarTy = Ty->getScalarType();
Dan Gohmanf011f5a2009-08-03 22:07:33 +0000137
138 // Create the base integer constant.
139 Constant *C = ConstantInt::get(Ty->getContext(), V);
140
141 // Convert an integer to a pointer, if necessary.
Chris Lattner229907c2011-07-18 04:54:35 +0000142 if (PointerType *PTy = dyn_cast<PointerType>(ScalarTy))
Dan Gohmanf011f5a2009-08-03 22:07:33 +0000143 C = ConstantExpr::getIntToPtr(C, PTy);
144
145 // Broadcast a scalar to a vector, if necessary.
Chris Lattner229907c2011-07-18 04:54:35 +0000146 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattnere9eed292012-01-25 05:19:54 +0000147 C = ConstantVector::getSplat(VTy->getNumElements(), C);
Dan Gohmanf011f5a2009-08-03 22:07:33 +0000148
149 return C;
150}
151
Chris Lattner229907c2011-07-18 04:54:35 +0000152Constant *Constant::getAllOnesValue(Type *Ty) {
153 if (IntegerType *ITy = dyn_cast<IntegerType>(Ty))
Owen Anderson5a1acd92009-07-31 20:28:14 +0000154 return ConstantInt::get(Ty->getContext(),
155 APInt::getAllOnesValue(ITy->getBitWidth()));
Nadav Rotem7cc6d122011-02-17 21:22:27 +0000156
157 if (Ty->isFloatingPointTy()) {
158 APFloat FL = APFloat::getAllOnesValue(Ty->getPrimitiveSizeInBits(),
159 !Ty->isPPC_FP128Ty());
160 return ConstantFP::get(Ty->getContext(), FL);
161 }
162
Chris Lattner229907c2011-07-18 04:54:35 +0000163 VectorType *VTy = cast<VectorType>(Ty);
Chris Lattnere9eed292012-01-25 05:19:54 +0000164 return ConstantVector::getSplat(VTy->getNumElements(),
165 getAllOnesValue(VTy->getElementType()));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000166}
167
Chris Lattner7e683d12012-01-25 06:16:32 +0000168/// getAggregateElement - For aggregates (struct/array/vector) return the
169/// constant that corresponds to the specified element if possible, or null if
170/// not. This can return null if the element index is a ConstantExpr, or if
171/// 'this' is a constant expr.
172Constant *Constant::getAggregateElement(unsigned Elt) const {
173 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(this))
174 return Elt < CS->getNumOperands() ? CS->getOperand(Elt) : 0;
Galina Kistanovafc259902012-07-13 01:25:27 +0000175
Chris Lattner7e683d12012-01-25 06:16:32 +0000176 if (const ConstantArray *CA = dyn_cast<ConstantArray>(this))
177 return Elt < CA->getNumOperands() ? CA->getOperand(Elt) : 0;
Galina Kistanovafc259902012-07-13 01:25:27 +0000178
Chris Lattner7e683d12012-01-25 06:16:32 +0000179 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
180 return Elt < CV->getNumOperands() ? CV->getOperand(Elt) : 0;
Galina Kistanovafc259902012-07-13 01:25:27 +0000181
Chris Lattner7e683d12012-01-25 06:16:32 +0000182 if (const ConstantAggregateZero *CAZ =dyn_cast<ConstantAggregateZero>(this))
183 return CAZ->getElementValue(Elt);
Galina Kistanovafc259902012-07-13 01:25:27 +0000184
Chris Lattner7e683d12012-01-25 06:16:32 +0000185 if (const UndefValue *UV = dyn_cast<UndefValue>(this))
186 return UV->getElementValue(Elt);
Galina Kistanovafc259902012-07-13 01:25:27 +0000187
Chris Lattner8326bd82012-01-26 00:42:34 +0000188 if (const ConstantDataSequential *CDS =dyn_cast<ConstantDataSequential>(this))
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000189 return Elt < CDS->getNumElements() ? CDS->getElementAsConstant(Elt) : 0;
Chris Lattner7e683d12012-01-25 06:16:32 +0000190 return 0;
191}
192
193Constant *Constant::getAggregateElement(Constant *Elt) const {
194 assert(isa<IntegerType>(Elt->getType()) && "Index must be an integer");
195 if (ConstantInt *CI = dyn_cast<ConstantInt>(Elt))
196 return getAggregateElement(CI->getZExtValue());
197 return 0;
198}
199
200
Chris Lattner3462ae32001-12-03 22:26:30 +0000201void Constant::destroyConstantImpl() {
202 // When a Constant is destroyed, there may be lingering
Chris Lattnerd7a73302001-10-13 06:57:33 +0000203 // references to the constant by other constants in the constant pool. These
Misha Brukmanbe372b92003-08-21 22:14:26 +0000204 // constants are implicitly dependent on the module that is being deleted,
Chris Lattnerd7a73302001-10-13 06:57:33 +0000205 // but they don't know that. Because we only find out when the CPV is
206 // deleted, we must now notify all of our users (that should only be
Chris Lattner3462ae32001-12-03 22:26:30 +0000207 // Constants) that they are, in fact, invalid now and should be deleted.
Chris Lattnerd7a73302001-10-13 06:57:33 +0000208 //
209 while (!use_empty()) {
210 Value *V = use_back();
211#ifndef NDEBUG // Only in -g mode...
Chris Lattner78683a72009-08-23 04:02:03 +0000212 if (!isa<Constant>(V)) {
David Greene1e27a132010-01-05 01:29:19 +0000213 dbgs() << "While deleting: " << *this
Chris Lattner78683a72009-08-23 04:02:03 +0000214 << "\n\nUse still stuck around after Def is destroyed: "
215 << *V << "\n\n";
216 }
Chris Lattnerd7a73302001-10-13 06:57:33 +0000217#endif
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000218 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
Chris Lattner8326bd82012-01-26 00:42:34 +0000219 cast<Constant>(V)->destroyConstant();
Chris Lattnerd7a73302001-10-13 06:57:33 +0000220
221 // The constant should remove itself from our use list...
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000222 assert((use_empty() || use_back() != V) && "Constant not removed!");
Chris Lattnerd7a73302001-10-13 06:57:33 +0000223 }
224
225 // Value has no outstanding references it is safe to delete it now...
226 delete this;
Chris Lattner38569342001-10-01 20:11:19 +0000227}
Chris Lattner2f7c9632001-06-06 20:29:01 +0000228
Chris Lattner23dd1f62006-10-20 00:27:06 +0000229/// canTrap - Return true if evaluation of this constant could trap. This is
230/// true for things like constant expressions that could divide by zero.
231bool Constant::canTrap() const {
232 assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
233 // The only thing that could possibly trap are constant exprs.
234 const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
235 if (!CE) return false;
Galina Kistanovafc259902012-07-13 01:25:27 +0000236
237 // ConstantExpr traps if any operands can trap.
Chris Lattner23dd1f62006-10-20 00:27:06 +0000238 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
Galina Kistanovafc259902012-07-13 01:25:27 +0000239 if (CE->getOperand(i)->canTrap())
Chris Lattner23dd1f62006-10-20 00:27:06 +0000240 return true;
241
242 // Otherwise, only specific operations can trap.
243 switch (CE->getOpcode()) {
244 default:
245 return false;
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000246 case Instruction::UDiv:
247 case Instruction::SDiv:
248 case Instruction::FDiv:
Reid Spencer7eb55b32006-11-02 01:53:59 +0000249 case Instruction::URem:
250 case Instruction::SRem:
251 case Instruction::FRem:
Chris Lattner23dd1f62006-10-20 00:27:06 +0000252 // Div and rem can trap if the RHS is not known to be non-zero.
Chris Lattnera91a5632009-10-28 05:14:34 +0000253 if (!isa<ConstantInt>(CE->getOperand(1)) ||CE->getOperand(1)->isNullValue())
Chris Lattner23dd1f62006-10-20 00:27:06 +0000254 return true;
255 return false;
256 }
257}
258
Hans Wennborg709e0152012-11-15 11:40:00 +0000259/// isThreadDependent - Return true if the value can vary between threads.
260bool Constant::isThreadDependent() const {
261 SmallPtrSet<const Constant*, 64> Visited;
262 SmallVector<const Constant*, 64> WorkList;
263 WorkList.push_back(this);
264 Visited.insert(this);
265
266 while (!WorkList.empty()) {
267 const Constant *C = WorkList.pop_back_val();
268
269 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
270 if (GV->isThreadLocal())
271 return true;
272 }
273
274 for (unsigned I = 0, E = C->getNumOperands(); I != E; ++I) {
Hans Wennborg18aa12402012-11-16 10:33:25 +0000275 const Constant *D = dyn_cast<Constant>(C->getOperand(I));
276 if (!D)
277 continue;
Hans Wennborg709e0152012-11-15 11:40:00 +0000278 if (Visited.insert(D))
279 WorkList.push_back(D);
280 }
281 }
282
283 return false;
284}
285
Chris Lattner253bc772009-11-01 18:11:50 +0000286/// isConstantUsed - Return true if the constant has users other than constant
287/// exprs and other dangling things.
288bool Constant::isConstantUsed() const {
Gabor Greifc78d7202010-03-25 23:06:16 +0000289 for (const_use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
Chris Lattner253bc772009-11-01 18:11:50 +0000290 const Constant *UC = dyn_cast<Constant>(*UI);
291 if (UC == 0 || isa<GlobalValue>(UC))
292 return true;
Galina Kistanovafc259902012-07-13 01:25:27 +0000293
Chris Lattner253bc772009-11-01 18:11:50 +0000294 if (UC->isConstantUsed())
295 return true;
296 }
297 return false;
298}
299
300
Chris Lattner4565ef52009-07-22 00:05:44 +0000301
302/// getRelocationInfo - This method classifies the entry according to
303/// whether or not it may generate a relocation entry. This must be
304/// conservative, so if it might codegen to a relocatable entry, it should say
305/// so. The return values are:
306///
Chris Lattner5cd4dd32009-07-24 03:27:21 +0000307/// NoRelocation: This constant pool entry is guaranteed to never have a
308/// relocation applied to it (because it holds a simple constant like
309/// '4').
310/// LocalRelocation: This entry has relocations, but the entries are
311/// guaranteed to be resolvable by the static linker, so the dynamic
312/// linker will never see them.
313/// GlobalRelocations: This entry may have arbitrary relocations.
Chris Lattner4565ef52009-07-22 00:05:44 +0000314///
Chandler Carruthef860a22013-01-02 09:10:48 +0000315/// FIXME: This really should not be in IR.
Chris Lattner5cd4dd32009-07-24 03:27:21 +0000316Constant::PossibleRelocationsTy Constant::getRelocationInfo() const {
317 if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
Chris Lattner4565ef52009-07-22 00:05:44 +0000318 if (GV->hasLocalLinkage() || GV->hasHiddenVisibility())
Chris Lattner5cd4dd32009-07-24 03:27:21 +0000319 return LocalRelocation; // Local to this file/library.
320 return GlobalRelocations; // Global reference.
Anton Korobeynikov7437b592009-03-29 17:13:18 +0000321 }
Chris Lattner4565ef52009-07-22 00:05:44 +0000322
Chris Lattner2cb85b42009-10-28 04:12:16 +0000323 if (const BlockAddress *BA = dyn_cast<BlockAddress>(this))
324 return BA->getFunction()->getRelocationInfo();
325
Chris Lattnera7cfc432010-01-03 18:09:40 +0000326 // While raw uses of blockaddress need to be relocated, differences between
327 // two of them don't when they are for labels in the same function. This is a
328 // common idiom when creating a table for the indirect goto extension, so we
329 // handle it efficiently here.
330 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(this))
331 if (CE->getOpcode() == Instruction::Sub) {
332 ConstantExpr *LHS = dyn_cast<ConstantExpr>(CE->getOperand(0));
333 ConstantExpr *RHS = dyn_cast<ConstantExpr>(CE->getOperand(1));
334 if (LHS && RHS &&
335 LHS->getOpcode() == Instruction::PtrToInt &&
336 RHS->getOpcode() == Instruction::PtrToInt &&
337 isa<BlockAddress>(LHS->getOperand(0)) &&
338 isa<BlockAddress>(RHS->getOperand(0)) &&
339 cast<BlockAddress>(LHS->getOperand(0))->getFunction() ==
340 cast<BlockAddress>(RHS->getOperand(0))->getFunction())
341 return NoRelocation;
342 }
Galina Kistanovafc259902012-07-13 01:25:27 +0000343
Chris Lattner5cd4dd32009-07-24 03:27:21 +0000344 PossibleRelocationsTy Result = NoRelocation;
Evan Chengf9e003b2007-03-08 00:59:12 +0000345 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
Chris Lattnera91a5632009-10-28 05:14:34 +0000346 Result = std::max(Result,
347 cast<Constant>(getOperand(i))->getRelocationInfo());
Galina Kistanovafc259902012-07-13 01:25:27 +0000348
Chris Lattner4565ef52009-07-22 00:05:44 +0000349 return Result;
Evan Chengf9e003b2007-03-08 00:59:12 +0000350}
351
Chris Lattner84886402011-02-18 04:41:42 +0000352/// removeDeadUsersOfConstant - If the specified constantexpr is dead, remove
353/// it. This involves recursively eliminating any dead users of the
354/// constantexpr.
355static bool removeDeadUsersOfConstant(const Constant *C) {
356 if (isa<GlobalValue>(C)) return false; // Cannot remove this
Galina Kistanovafc259902012-07-13 01:25:27 +0000357
Chris Lattner84886402011-02-18 04:41:42 +0000358 while (!C->use_empty()) {
359 const Constant *User = dyn_cast<Constant>(C->use_back());
360 if (!User) return false; // Non-constant usage;
361 if (!removeDeadUsersOfConstant(User))
362 return false; // Constant wasn't dead
363 }
Galina Kistanovafc259902012-07-13 01:25:27 +0000364
Chris Lattner84886402011-02-18 04:41:42 +0000365 const_cast<Constant*>(C)->destroyConstant();
366 return true;
367}
368
369
370/// removeDeadConstantUsers - If there are any dead constant users dangling
371/// off of this constant, remove them. This method is useful for clients
372/// that want to check to see if a global is unused, but don't want to deal
373/// with potentially dead constants hanging off of the globals.
374void Constant::removeDeadConstantUsers() const {
375 Value::const_use_iterator I = use_begin(), E = use_end();
376 Value::const_use_iterator LastNonDeadUser = E;
377 while (I != E) {
378 const Constant *User = dyn_cast<Constant>(*I);
379 if (User == 0) {
380 LastNonDeadUser = I;
381 ++I;
382 continue;
383 }
Galina Kistanovafc259902012-07-13 01:25:27 +0000384
Chris Lattner84886402011-02-18 04:41:42 +0000385 if (!removeDeadUsersOfConstant(User)) {
386 // If the constant wasn't dead, remember that this was the last live use
387 // and move on to the next constant.
388 LastNonDeadUser = I;
389 ++I;
390 continue;
391 }
Galina Kistanovafc259902012-07-13 01:25:27 +0000392
Chris Lattner84886402011-02-18 04:41:42 +0000393 // If the constant was dead, then the iterator is invalidated.
394 if (LastNonDeadUser == E) {
395 I = use_begin();
396 if (I == E) break;
397 } else {
398 I = LastNonDeadUser;
399 ++I;
400 }
401 }
402}
403
404
Chris Lattner2105d662008-07-10 00:28:11 +0000405
Chris Lattner2f7c9632001-06-06 20:29:01 +0000406//===----------------------------------------------------------------------===//
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000407// ConstantInt
Chris Lattner2f7c9632001-06-06 20:29:01 +0000408//===----------------------------------------------------------------------===//
409
David Blaikiea379b1812011-12-20 02:50:00 +0000410void ConstantInt::anchor() { }
411
Chris Lattner229907c2011-07-18 04:54:35 +0000412ConstantInt::ConstantInt(IntegerType *Ty, const APInt& V)
Chris Lattner5db2f472007-02-20 05:55:46 +0000413 : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
Reid Spencerb31bffe2007-02-26 23:54:03 +0000414 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
Chris Lattner2f7c9632001-06-06 20:29:01 +0000415}
416
Nick Lewycky92db8e82011-03-06 03:36:19 +0000417ConstantInt *ConstantInt::getTrue(LLVMContext &Context) {
Owen Anderson23a204d2009-07-31 17:39:07 +0000418 LLVMContextImpl *pImpl = Context.pImpl;
Benjamin Kramerddd1b7b2010-11-20 18:43:35 +0000419 if (!pImpl->TheTrueVal)
420 pImpl->TheTrueVal = ConstantInt::get(Type::getInt1Ty(Context), 1);
421 return pImpl->TheTrueVal;
Owen Anderson23a204d2009-07-31 17:39:07 +0000422}
423
Nick Lewycky92db8e82011-03-06 03:36:19 +0000424ConstantInt *ConstantInt::getFalse(LLVMContext &Context) {
Owen Anderson23a204d2009-07-31 17:39:07 +0000425 LLVMContextImpl *pImpl = Context.pImpl;
Benjamin Kramerddd1b7b2010-11-20 18:43:35 +0000426 if (!pImpl->TheFalseVal)
427 pImpl->TheFalseVal = ConstantInt::get(Type::getInt1Ty(Context), 0);
428 return pImpl->TheFalseVal;
Owen Anderson23a204d2009-07-31 17:39:07 +0000429}
430
Chris Lattner229907c2011-07-18 04:54:35 +0000431Constant *ConstantInt::getTrue(Type *Ty) {
432 VectorType *VTy = dyn_cast<VectorType>(Ty);
Nick Lewycky92db8e82011-03-06 03:36:19 +0000433 if (!VTy) {
434 assert(Ty->isIntegerTy(1) && "True must be i1 or vector of i1.");
435 return ConstantInt::getTrue(Ty->getContext());
436 }
437 assert(VTy->getElementType()->isIntegerTy(1) &&
438 "True must be vector of i1 or i1.");
Chris Lattnere9eed292012-01-25 05:19:54 +0000439 return ConstantVector::getSplat(VTy->getNumElements(),
440 ConstantInt::getTrue(Ty->getContext()));
Nick Lewycky92db8e82011-03-06 03:36:19 +0000441}
442
Chris Lattner229907c2011-07-18 04:54:35 +0000443Constant *ConstantInt::getFalse(Type *Ty) {
444 VectorType *VTy = dyn_cast<VectorType>(Ty);
Nick Lewycky92db8e82011-03-06 03:36:19 +0000445 if (!VTy) {
446 assert(Ty->isIntegerTy(1) && "False must be i1 or vector of i1.");
447 return ConstantInt::getFalse(Ty->getContext());
448 }
449 assert(VTy->getElementType()->isIntegerTy(1) &&
450 "False must be vector of i1 or i1.");
Chris Lattnere9eed292012-01-25 05:19:54 +0000451 return ConstantVector::getSplat(VTy->getNumElements(),
452 ConstantInt::getFalse(Ty->getContext()));
Nick Lewycky92db8e82011-03-06 03:36:19 +0000453}
454
Owen Anderson23a204d2009-07-31 17:39:07 +0000455
Owen Andersonedb4a702009-07-24 23:12:02 +0000456// Get a ConstantInt from an APInt. Note that the value stored in the DenseMap
457// as the key, is a DenseMapAPIntKeyInfo::KeyTy which has provided the
458// operator== and operator!= to ensure that the DenseMap doesn't attempt to
459// compare APInt's of different widths, which would violate an APInt class
460// invariant which generates an assertion.
Nick Lewycky92db8e82011-03-06 03:36:19 +0000461ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt &V) {
Owen Andersonedb4a702009-07-24 23:12:02 +0000462 // Get the corresponding integer type for the bit width of the value.
Chris Lattner229907c2011-07-18 04:54:35 +0000463 IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
Owen Andersonedb4a702009-07-24 23:12:02 +0000464 // get an existing value or the insertion position
465 DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
Owen Andersonedb4a702009-07-24 23:12:02 +0000466 ConstantInt *&Slot = Context.pImpl->IntConstants[Key];
Owen Anderson5dab84c2009-10-19 20:11:52 +0000467 if (!Slot) Slot = new ConstantInt(ITy, V);
468 return Slot;
Owen Andersonedb4a702009-07-24 23:12:02 +0000469}
470
Chris Lattner229907c2011-07-18 04:54:35 +0000471Constant *ConstantInt::get(Type *Ty, uint64_t V, bool isSigned) {
Nick Lewycky92db8e82011-03-06 03:36:19 +0000472 Constant *C = get(cast<IntegerType>(Ty->getScalarType()), V, isSigned);
Owen Andersonedb4a702009-07-24 23:12:02 +0000473
474 // For vectors, broadcast the value.
Chris Lattner229907c2011-07-18 04:54:35 +0000475 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattnere9eed292012-01-25 05:19:54 +0000476 return ConstantVector::getSplat(VTy->getNumElements(), C);
Owen Andersonedb4a702009-07-24 23:12:02 +0000477
478 return C;
479}
480
Chris Lattner0256be92012-01-27 03:08:05 +0000481ConstantInt *ConstantInt::get(IntegerType *Ty, uint64_t V,
Owen Andersonedb4a702009-07-24 23:12:02 +0000482 bool isSigned) {
483 return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned));
484}
485
Chris Lattner0256be92012-01-27 03:08:05 +0000486ConstantInt *ConstantInt::getSigned(IntegerType *Ty, int64_t V) {
Owen Andersonedb4a702009-07-24 23:12:02 +0000487 return get(Ty, V, true);
488}
489
Chris Lattner229907c2011-07-18 04:54:35 +0000490Constant *ConstantInt::getSigned(Type *Ty, int64_t V) {
Owen Andersonedb4a702009-07-24 23:12:02 +0000491 return get(Ty, V, true);
492}
493
Chris Lattner0256be92012-01-27 03:08:05 +0000494Constant *ConstantInt::get(Type *Ty, const APInt& V) {
Owen Andersonedb4a702009-07-24 23:12:02 +0000495 ConstantInt *C = get(Ty->getContext(), V);
496 assert(C->getType() == Ty->getScalarType() &&
497 "ConstantInt type doesn't match the type implied by its value!");
498
499 // For vectors, broadcast the value.
Chris Lattner229907c2011-07-18 04:54:35 +0000500 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattnere9eed292012-01-25 05:19:54 +0000501 return ConstantVector::getSplat(VTy->getNumElements(), C);
Owen Andersonedb4a702009-07-24 23:12:02 +0000502
503 return C;
504}
505
Chris Lattner0256be92012-01-27 03:08:05 +0000506ConstantInt *ConstantInt::get(IntegerType* Ty, StringRef Str,
Erick Tryzelaarfc2280d2009-08-16 23:36:33 +0000507 uint8_t radix) {
508 return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
509}
510
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000511//===----------------------------------------------------------------------===//
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000512// ConstantFP
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000513//===----------------------------------------------------------------------===//
514
Chris Lattner229907c2011-07-18 04:54:35 +0000515static const fltSemantics *TypeToFloatSemantics(Type *Ty) {
Dan Gohman518cda42011-12-17 00:04:22 +0000516 if (Ty->isHalfTy())
517 return &APFloat::IEEEhalf;
Chris Lattnerfdd87902009-10-05 05:54:46 +0000518 if (Ty->isFloatTy())
Rafael Espindolaf5d53d42009-07-15 17:40:42 +0000519 return &APFloat::IEEEsingle;
Chris Lattnerfdd87902009-10-05 05:54:46 +0000520 if (Ty->isDoubleTy())
Rafael Espindolaf5d53d42009-07-15 17:40:42 +0000521 return &APFloat::IEEEdouble;
Chris Lattnerfdd87902009-10-05 05:54:46 +0000522 if (Ty->isX86_FP80Ty())
Rafael Espindolaf5d53d42009-07-15 17:40:42 +0000523 return &APFloat::x87DoubleExtended;
Chris Lattnerfdd87902009-10-05 05:54:46 +0000524 else if (Ty->isFP128Ty())
Rafael Espindolaf5d53d42009-07-15 17:40:42 +0000525 return &APFloat::IEEEquad;
Galina Kistanovafc259902012-07-13 01:25:27 +0000526
Chris Lattnerfdd87902009-10-05 05:54:46 +0000527 assert(Ty->isPPC_FP128Ty() && "Unknown FP format");
Rafael Espindolaf5d53d42009-07-15 17:40:42 +0000528 return &APFloat::PPCDoubleDouble;
529}
530
David Blaikiea379b1812011-12-20 02:50:00 +0000531void ConstantFP::anchor() { }
532
Owen Anderson69c464d2009-07-27 20:59:43 +0000533/// get() - This returns a constant fp for the specified value in the
534/// specified type. This should only be used for simple constant values like
535/// 2.0/1.0 etc, that are known-valid both as double and as the target format.
Chris Lattner0256be92012-01-27 03:08:05 +0000536Constant *ConstantFP::get(Type *Ty, double V) {
Owen Anderson69c464d2009-07-27 20:59:43 +0000537 LLVMContext &Context = Ty->getContext();
Galina Kistanovafc259902012-07-13 01:25:27 +0000538
Owen Anderson69c464d2009-07-27 20:59:43 +0000539 APFloat FV(V);
540 bool ignored;
541 FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
542 APFloat::rmNearestTiesToEven, &ignored);
543 Constant *C = get(Context, FV);
544
545 // For vectors, broadcast the value.
Chris Lattner229907c2011-07-18 04:54:35 +0000546 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattnere9eed292012-01-25 05:19:54 +0000547 return ConstantVector::getSplat(VTy->getNumElements(), C);
Owen Anderson69c464d2009-07-27 20:59:43 +0000548
549 return C;
550}
551
Erick Tryzelaarfc2280d2009-08-16 23:36:33 +0000552
Chris Lattner0256be92012-01-27 03:08:05 +0000553Constant *ConstantFP::get(Type *Ty, StringRef Str) {
Erick Tryzelaarfc2280d2009-08-16 23:36:33 +0000554 LLVMContext &Context = Ty->getContext();
555
556 APFloat FV(*TypeToFloatSemantics(Ty->getScalarType()), Str);
557 Constant *C = get(Context, FV);
558
559 // For vectors, broadcast the value.
Chris Lattner229907c2011-07-18 04:54:35 +0000560 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattnere9eed292012-01-25 05:19:54 +0000561 return ConstantVector::getSplat(VTy->getNumElements(), C);
Erick Tryzelaarfc2280d2009-08-16 23:36:33 +0000562
563 return C;
564}
565
566
Chris Lattnere9eed292012-01-25 05:19:54 +0000567ConstantFP *ConstantFP::getNegativeZero(Type *Ty) {
Owen Anderson69c464d2009-07-27 20:59:43 +0000568 LLVMContext &Context = Ty->getContext();
Chris Lattnere9eed292012-01-25 05:19:54 +0000569 APFloat apf = cast<ConstantFP>(Constant::getNullValue(Ty))->getValueAPF();
Owen Anderson69c464d2009-07-27 20:59:43 +0000570 apf.changeSign();
571 return get(Context, apf);
572}
573
574
Chris Lattnere9eed292012-01-25 05:19:54 +0000575Constant *ConstantFP::getZeroValueForNegation(Type *Ty) {
576 Type *ScalarTy = Ty->getScalarType();
577 if (ScalarTy->isFloatingPointTy()) {
578 Constant *C = getNegativeZero(ScalarTy);
579 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
580 return ConstantVector::getSplat(VTy->getNumElements(), C);
581 return C;
582 }
Owen Anderson69c464d2009-07-27 20:59:43 +0000583
Owen Anderson5a1acd92009-07-31 20:28:14 +0000584 return Constant::getNullValue(Ty);
Owen Anderson69c464d2009-07-27 20:59:43 +0000585}
586
587
588// ConstantFP accessors.
589ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
590 DenseMapAPFloatKeyInfo::KeyTy Key(V);
Galina Kistanovafc259902012-07-13 01:25:27 +0000591
Owen Anderson69c464d2009-07-27 20:59:43 +0000592 LLVMContextImpl* pImpl = Context.pImpl;
Galina Kistanovafc259902012-07-13 01:25:27 +0000593
Owen Anderson69c464d2009-07-27 20:59:43 +0000594 ConstantFP *&Slot = pImpl->FPConstants[Key];
Galina Kistanovafc259902012-07-13 01:25:27 +0000595
Owen Anderson69c464d2009-07-27 20:59:43 +0000596 if (!Slot) {
Chris Lattner229907c2011-07-18 04:54:35 +0000597 Type *Ty;
Dan Gohman518cda42011-12-17 00:04:22 +0000598 if (&V.getSemantics() == &APFloat::IEEEhalf)
599 Ty = Type::getHalfTy(Context);
600 else if (&V.getSemantics() == &APFloat::IEEEsingle)
Owen Anderson5dab84c2009-10-19 20:11:52 +0000601 Ty = Type::getFloatTy(Context);
602 else if (&V.getSemantics() == &APFloat::IEEEdouble)
603 Ty = Type::getDoubleTy(Context);
604 else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
605 Ty = Type::getX86_FP80Ty(Context);
606 else if (&V.getSemantics() == &APFloat::IEEEquad)
607 Ty = Type::getFP128Ty(Context);
608 else {
609 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble &&
610 "Unknown FP format");
611 Ty = Type::getPPC_FP128Ty(Context);
Owen Anderson69c464d2009-07-27 20:59:43 +0000612 }
Owen Anderson5dab84c2009-10-19 20:11:52 +0000613 Slot = new ConstantFP(Ty, V);
Owen Anderson69c464d2009-07-27 20:59:43 +0000614 }
Galina Kistanovafc259902012-07-13 01:25:27 +0000615
Owen Anderson69c464d2009-07-27 20:59:43 +0000616 return Slot;
617}
618
Chris Lattner229907c2011-07-18 04:54:35 +0000619ConstantFP *ConstantFP::getInfinity(Type *Ty, bool Negative) {
Dan Gohmanfeb50212009-09-25 23:00:48 +0000620 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty);
621 return ConstantFP::get(Ty->getContext(),
622 APFloat::getInf(Semantics, Negative));
623}
624
Chris Lattner229907c2011-07-18 04:54:35 +0000625ConstantFP::ConstantFP(Type *Ty, const APFloat& V)
Dale Johannesend246b2c2007-08-30 00:23:21 +0000626 : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
Chris Lattner98bd9392008-04-09 06:38:30 +0000627 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
628 "FP type Mismatch");
Chris Lattner2f7c9632001-06-06 20:29:01 +0000629}
630
Chris Lattnerbe6610c2011-07-15 06:14:08 +0000631bool ConstantFP::isExactlyValue(const APFloat &V) const {
Dale Johannesend246b2c2007-08-30 00:23:21 +0000632 return Val.bitwiseIsEqual(V);
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000633}
634
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000635//===----------------------------------------------------------------------===//
Chris Lattner030af792012-01-24 05:42:11 +0000636// ConstantAggregateZero Implementation
637//===----------------------------------------------------------------------===//
638
639/// getSequentialElement - If this CAZ has array or vector type, return a zero
640/// with the right element type.
Chris Lattner7e683d12012-01-25 06:16:32 +0000641Constant *ConstantAggregateZero::getSequentialElement() const {
Chris Lattner8326bd82012-01-26 00:42:34 +0000642 return Constant::getNullValue(getType()->getSequentialElementType());
Chris Lattner030af792012-01-24 05:42:11 +0000643}
644
645/// getStructElement - If this CAZ has struct type, return a zero with the
646/// right element type for the specified element.
Chris Lattner7e683d12012-01-25 06:16:32 +0000647Constant *ConstantAggregateZero::getStructElement(unsigned Elt) const {
Chris Lattner8326bd82012-01-26 00:42:34 +0000648 return Constant::getNullValue(getType()->getStructElementType(Elt));
Chris Lattner030af792012-01-24 05:42:11 +0000649}
650
651/// getElementValue - Return a zero of the right value for the specified GEP
652/// index if we can, otherwise return null (e.g. if C is a ConstantExpr).
Chris Lattner7e683d12012-01-25 06:16:32 +0000653Constant *ConstantAggregateZero::getElementValue(Constant *C) const {
Chris Lattner030af792012-01-24 05:42:11 +0000654 if (isa<SequentialType>(getType()))
655 return getSequentialElement();
656 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
657}
658
Chris Lattnerf7eb5432012-01-24 07:54:10 +0000659/// getElementValue - Return a zero of the right value for the specified GEP
660/// index.
Chris Lattner7e683d12012-01-25 06:16:32 +0000661Constant *ConstantAggregateZero::getElementValue(unsigned Idx) const {
Chris Lattnerf7eb5432012-01-24 07:54:10 +0000662 if (isa<SequentialType>(getType()))
663 return getSequentialElement();
664 return getStructElement(Idx);
665}
666
667
Chris Lattner030af792012-01-24 05:42:11 +0000668//===----------------------------------------------------------------------===//
669// UndefValue Implementation
670//===----------------------------------------------------------------------===//
671
672/// getSequentialElement - If this undef has array or vector type, return an
673/// undef with the right element type.
Chris Lattner7e683d12012-01-25 06:16:32 +0000674UndefValue *UndefValue::getSequentialElement() const {
Chris Lattner8326bd82012-01-26 00:42:34 +0000675 return UndefValue::get(getType()->getSequentialElementType());
Chris Lattner030af792012-01-24 05:42:11 +0000676}
677
678/// getStructElement - If this undef has struct type, return a zero with the
679/// right element type for the specified element.
Chris Lattner7e683d12012-01-25 06:16:32 +0000680UndefValue *UndefValue::getStructElement(unsigned Elt) const {
Chris Lattner8326bd82012-01-26 00:42:34 +0000681 return UndefValue::get(getType()->getStructElementType(Elt));
Chris Lattner030af792012-01-24 05:42:11 +0000682}
683
684/// getElementValue - Return an undef of the right value for the specified GEP
685/// index if we can, otherwise return null (e.g. if C is a ConstantExpr).
Chris Lattner7e683d12012-01-25 06:16:32 +0000686UndefValue *UndefValue::getElementValue(Constant *C) const {
Chris Lattner030af792012-01-24 05:42:11 +0000687 if (isa<SequentialType>(getType()))
688 return getSequentialElement();
689 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
690}
691
Chris Lattnerf7eb5432012-01-24 07:54:10 +0000692/// getElementValue - Return an undef of the right value for the specified GEP
693/// index.
Chris Lattner7e683d12012-01-25 06:16:32 +0000694UndefValue *UndefValue::getElementValue(unsigned Idx) const {
Chris Lattnerf7eb5432012-01-24 07:54:10 +0000695 if (isa<SequentialType>(getType()))
696 return getSequentialElement();
697 return getStructElement(Idx);
698}
699
700
Chris Lattner030af792012-01-24 05:42:11 +0000701
702//===----------------------------------------------------------------------===//
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000703// ConstantXXX Classes
704//===----------------------------------------------------------------------===//
705
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000706template <typename ItTy, typename EltTy>
707static bool rangeOnlyContains(ItTy Start, ItTy End, EltTy Elt) {
708 for (; Start != End; ++Start)
709 if (*Start != Elt)
710 return false;
711 return true;
712}
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000713
Jay Foad89d9b812011-07-25 10:14:44 +0000714ConstantArray::ConstantArray(ArrayType *T, ArrayRef<Constant *> V)
Gabor Greiff6caff662008-05-10 08:32:32 +0000715 : Constant(T, ConstantArrayVal,
716 OperandTraits<ConstantArray>::op_end(this) - V.size(),
717 V.size()) {
Alkis Evlogimenos0507ffe2004-09-15 02:32:15 +0000718 assert(V.size() == T->getNumElements() &&
719 "Invalid initializer vector for constant array");
Jay Foad89d9b812011-07-25 10:14:44 +0000720 for (unsigned i = 0, e = V.size(); i != e; ++i)
721 assert(V[i]->getType() == T->getElementType() &&
Alkis Evlogimenoscb031d92004-09-10 04:16:59 +0000722 "Initializer for array element doesn't match array element type!");
Jay Foad89d9b812011-07-25 10:14:44 +0000723 std::copy(V.begin(), V.end(), op_begin());
Chris Lattner2f7c9632001-06-06 20:29:01 +0000724}
725
Chris Lattner229907c2011-07-18 04:54:35 +0000726Constant *ConstantArray::get(ArrayType *Ty, ArrayRef<Constant*> V) {
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000727 // Empty arrays are canonicalized to ConstantAggregateZero.
728 if (V.empty())
729 return ConstantAggregateZero::get(Ty);
730
Jeffrey Yasskin8ce67f82009-09-30 21:08:08 +0000731 for (unsigned i = 0, e = V.size(); i != e; ++i) {
732 assert(V[i]->getType() == Ty->getElementType() &&
733 "Wrong type in array element initializer");
734 }
Owen Andersonc2c79322009-07-28 18:32:17 +0000735 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
Galina Kistanovafc259902012-07-13 01:25:27 +0000736
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000737 // If this is an all-zero array, return a ConstantAggregateZero object. If
738 // all undef, return an UndefValue, if "all simple", then return a
739 // ConstantDataArray.
740 Constant *C = V[0];
741 if (isa<UndefValue>(C) && rangeOnlyContains(V.begin(), V.end(), C))
742 return UndefValue::get(Ty);
Chris Lattnerf14a67f2012-01-26 02:31:22 +0000743
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000744 if (C->isNullValue() && rangeOnlyContains(V.begin(), V.end(), C))
745 return ConstantAggregateZero::get(Ty);
746
747 // Check to see if all of the elements are ConstantFP or ConstantInt and if
748 // the element type is compatible with ConstantDataVector. If so, use it.
749 if (ConstantDataSequential::isElementTypeCompatible(C->getType())) {
750 // We speculatively build the elements here even if it turns out that there
751 // is a constantexpr or something else weird in the array, since it is so
752 // uncommon for that to happen.
753 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
754 if (CI->getType()->isIntegerTy(8)) {
755 SmallVector<uint8_t, 16> Elts;
756 for (unsigned i = 0, e = V.size(); i != e; ++i)
757 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
758 Elts.push_back(CI->getZExtValue());
759 else
760 break;
761 if (Elts.size() == V.size())
762 return ConstantDataArray::get(C->getContext(), Elts);
763 } else if (CI->getType()->isIntegerTy(16)) {
764 SmallVector<uint16_t, 16> Elts;
765 for (unsigned i = 0, e = V.size(); i != e; ++i)
766 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
767 Elts.push_back(CI->getZExtValue());
768 else
769 break;
770 if (Elts.size() == V.size())
771 return ConstantDataArray::get(C->getContext(), Elts);
772 } else if (CI->getType()->isIntegerTy(32)) {
773 SmallVector<uint32_t, 16> Elts;
774 for (unsigned i = 0, e = V.size(); i != e; ++i)
775 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
776 Elts.push_back(CI->getZExtValue());
777 else
778 break;
779 if (Elts.size() == V.size())
780 return ConstantDataArray::get(C->getContext(), Elts);
781 } else if (CI->getType()->isIntegerTy(64)) {
782 SmallVector<uint64_t, 16> Elts;
783 for (unsigned i = 0, e = V.size(); i != e; ++i)
784 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
785 Elts.push_back(CI->getZExtValue());
786 else
787 break;
788 if (Elts.size() == V.size())
789 return ConstantDataArray::get(C->getContext(), Elts);
790 }
791 }
Galina Kistanovafc259902012-07-13 01:25:27 +0000792
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000793 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
794 if (CFP->getType()->isFloatTy()) {
795 SmallVector<float, 16> Elts;
796 for (unsigned i = 0, e = V.size(); i != e; ++i)
797 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V[i]))
798 Elts.push_back(CFP->getValueAPF().convertToFloat());
799 else
800 break;
801 if (Elts.size() == V.size())
802 return ConstantDataArray::get(C->getContext(), Elts);
803 } else if (CFP->getType()->isDoubleTy()) {
804 SmallVector<double, 16> Elts;
805 for (unsigned i = 0, e = V.size(); i != e; ++i)
806 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V[i]))
807 Elts.push_back(CFP->getValueAPF().convertToDouble());
808 else
809 break;
810 if (Elts.size() == V.size())
811 return ConstantDataArray::get(C->getContext(), Elts);
812 }
813 }
Owen Andersonc2c79322009-07-28 18:32:17 +0000814 }
Chris Lattnerf14a67f2012-01-26 02:31:22 +0000815
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000816 // Otherwise, we really do want to create a ConstantArray.
Chris Lattnerf14a67f2012-01-26 02:31:22 +0000817 return pImpl->ArrayConstants.getOrCreate(Ty, V);
Owen Andersonc2c79322009-07-28 18:32:17 +0000818}
819
Chris Lattnercc19efa2011-06-20 04:01:31 +0000820/// getTypeForElements - Return an anonymous struct type to use for a constant
821/// with the specified set of elements. The list must not be empty.
822StructType *ConstantStruct::getTypeForElements(LLVMContext &Context,
823 ArrayRef<Constant*> V,
824 bool Packed) {
Bill Wendling3ae7dd32012-02-07 01:27:51 +0000825 unsigned VecSize = V.size();
826 SmallVector<Type*, 16> EltTypes(VecSize);
827 for (unsigned i = 0; i != VecSize; ++i)
828 EltTypes[i] = V[i]->getType();
Galina Kistanovafc259902012-07-13 01:25:27 +0000829
Chris Lattnercc19efa2011-06-20 04:01:31 +0000830 return StructType::get(Context, EltTypes, Packed);
831}
832
833
834StructType *ConstantStruct::getTypeForElements(ArrayRef<Constant*> V,
835 bool Packed) {
836 assert(!V.empty() &&
837 "ConstantStruct::getTypeForElements cannot be called on empty list");
838 return getTypeForElements(V[0]->getContext(), V, Packed);
839}
840
841
Jay Foad89d9b812011-07-25 10:14:44 +0000842ConstantStruct::ConstantStruct(StructType *T, ArrayRef<Constant *> V)
Gabor Greiff6caff662008-05-10 08:32:32 +0000843 : Constant(T, ConstantStructVal,
844 OperandTraits<ConstantStruct>::op_end(this) - V.size(),
845 V.size()) {
Chris Lattnerc3e74cd2011-08-07 04:18:48 +0000846 assert(V.size() == T->getNumElements() &&
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000847 "Invalid initializer vector for constant structure");
Jay Foad89d9b812011-07-25 10:14:44 +0000848 for (unsigned i = 0, e = V.size(); i != e; ++i)
849 assert((T->isOpaque() || V[i]->getType() == T->getElementType(i)) &&
Chris Lattner93c8f142003-06-02 17:42:47 +0000850 "Initializer for struct element doesn't match struct element type!");
Jay Foad89d9b812011-07-25 10:14:44 +0000851 std::copy(V.begin(), V.end(), op_begin());
Chris Lattner2f7c9632001-06-06 20:29:01 +0000852}
853
Owen Anderson45308b52009-07-27 22:29:26 +0000854// ConstantStruct accessors.
Chris Lattner229907c2011-07-18 04:54:35 +0000855Constant *ConstantStruct::get(StructType *ST, ArrayRef<Constant*> V) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000856 assert((ST->isOpaque() || ST->getNumElements() == V.size()) &&
857 "Incorrect # elements specified to ConstantStruct::get");
Chris Lattnerf14a67f2012-01-26 02:31:22 +0000858
859 // Create a ConstantAggregateZero value if all elements are zeros.
860 bool isZero = true;
861 bool isUndef = false;
862
863 if (!V.empty()) {
864 isUndef = isa<UndefValue>(V[0]);
865 isZero = V[0]->isNullValue();
866 if (isUndef || isZero) {
867 for (unsigned i = 0, e = V.size(); i != e; ++i) {
868 if (!V[i]->isNullValue())
869 isZero = false;
870 if (!isa<UndefValue>(V[i]))
871 isUndef = false;
872 }
873 }
Galina Kistanovafc259902012-07-13 01:25:27 +0000874 }
Chris Lattnerf14a67f2012-01-26 02:31:22 +0000875 if (isZero)
876 return ConstantAggregateZero::get(ST);
877 if (isUndef)
878 return UndefValue::get(ST);
Galina Kistanovafc259902012-07-13 01:25:27 +0000879
Chris Lattnerf14a67f2012-01-26 02:31:22 +0000880 return ST->getContext().pImpl->StructConstants.getOrCreate(ST, V);
Owen Anderson45308b52009-07-27 22:29:26 +0000881}
882
Chris Lattnerc3e74cd2011-08-07 04:18:48 +0000883Constant *ConstantStruct::get(StructType *T, ...) {
Talin3a0a30d2011-02-28 23:53:27 +0000884 va_list ap;
Chris Lattnercc19efa2011-06-20 04:01:31 +0000885 SmallVector<Constant*, 8> Values;
886 va_start(ap, T);
887 while (Constant *Val = va_arg(ap, llvm::Constant*))
Talin3a0a30d2011-02-28 23:53:27 +0000888 Values.push_back(Val);
Talinde422be2011-03-01 18:00:49 +0000889 va_end(ap);
Chris Lattnercc19efa2011-06-20 04:01:31 +0000890 return get(T, Values);
Talin3a0a30d2011-02-28 23:53:27 +0000891}
892
Jay Foad89d9b812011-07-25 10:14:44 +0000893ConstantVector::ConstantVector(VectorType *T, ArrayRef<Constant *> V)
Gabor Greiff6caff662008-05-10 08:32:32 +0000894 : Constant(T, ConstantVectorVal,
895 OperandTraits<ConstantVector>::op_end(this) - V.size(),
896 V.size()) {
Jay Foad89d9b812011-07-25 10:14:44 +0000897 for (size_t i = 0, e = V.size(); i != e; i++)
898 assert(V[i]->getType() == T->getElementType() &&
Dan Gohman30978072007-05-24 14:36:04 +0000899 "Initializer for vector element doesn't match vector element type!");
Jay Foad89d9b812011-07-25 10:14:44 +0000900 std::copy(V.begin(), V.end(), op_begin());
Brian Gaeke02209042004-08-20 06:00:58 +0000901}
902
Owen Anderson4aa32952009-07-28 21:19:26 +0000903// ConstantVector accessors.
Jay Foadb8a8bed32011-06-22 09:10:19 +0000904Constant *ConstantVector::get(ArrayRef<Constant*> V) {
Jay Foad9f32cfd2011-01-27 14:44:55 +0000905 assert(!V.empty() && "Vectors can't be empty");
Chris Lattner229907c2011-07-18 04:54:35 +0000906 VectorType *T = VectorType::get(V.front()->getType(), V.size());
Chris Lattner69229312011-02-15 00:14:00 +0000907 LLVMContextImpl *pImpl = T->getContext().pImpl;
Jay Foad9f32cfd2011-01-27 14:44:55 +0000908
Chris Lattner69229312011-02-15 00:14:00 +0000909 // If this is an all-undef or all-zero vector, return a
Owen Anderson4aa32952009-07-28 21:19:26 +0000910 // ConstantAggregateZero or UndefValue.
911 Constant *C = V[0];
912 bool isZero = C->isNullValue();
913 bool isUndef = isa<UndefValue>(C);
914
915 if (isZero || isUndef) {
916 for (unsigned i = 1, e = V.size(); i != e; ++i)
917 if (V[i] != C) {
918 isZero = isUndef = false;
919 break;
920 }
921 }
Galina Kistanovafc259902012-07-13 01:25:27 +0000922
Owen Anderson4aa32952009-07-28 21:19:26 +0000923 if (isZero)
Owen Andersonb292b8c2009-07-30 23:03:37 +0000924 return ConstantAggregateZero::get(T);
Owen Anderson4aa32952009-07-28 21:19:26 +0000925 if (isUndef)
Owen Andersonb292b8c2009-07-30 23:03:37 +0000926 return UndefValue::get(T);
Galina Kistanovafc259902012-07-13 01:25:27 +0000927
Chris Lattner978fe0c2012-01-30 06:21:21 +0000928 // Check to see if all of the elements are ConstantFP or ConstantInt and if
929 // the element type is compatible with ConstantDataVector. If so, use it.
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000930 if (ConstantDataSequential::isElementTypeCompatible(C->getType())) {
Chris Lattner978fe0c2012-01-30 06:21:21 +0000931 // We speculatively build the elements here even if it turns out that there
932 // is a constantexpr or something else weird in the array, since it is so
933 // uncommon for that to happen.
934 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
935 if (CI->getType()->isIntegerTy(8)) {
936 SmallVector<uint8_t, 16> Elts;
937 for (unsigned i = 0, e = V.size(); i != e; ++i)
938 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
939 Elts.push_back(CI->getZExtValue());
940 else
941 break;
942 if (Elts.size() == V.size())
943 return ConstantDataVector::get(C->getContext(), Elts);
944 } else if (CI->getType()->isIntegerTy(16)) {
945 SmallVector<uint16_t, 16> Elts;
946 for (unsigned i = 0, e = V.size(); i != e; ++i)
947 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
948 Elts.push_back(CI->getZExtValue());
949 else
950 break;
951 if (Elts.size() == V.size())
952 return ConstantDataVector::get(C->getContext(), Elts);
953 } else if (CI->getType()->isIntegerTy(32)) {
954 SmallVector<uint32_t, 16> Elts;
955 for (unsigned i = 0, e = V.size(); i != e; ++i)
956 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
957 Elts.push_back(CI->getZExtValue());
958 else
959 break;
960 if (Elts.size() == V.size())
961 return ConstantDataVector::get(C->getContext(), Elts);
962 } else if (CI->getType()->isIntegerTy(64)) {
963 SmallVector<uint64_t, 16> Elts;
964 for (unsigned i = 0, e = V.size(); i != e; ++i)
965 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
966 Elts.push_back(CI->getZExtValue());
967 else
968 break;
969 if (Elts.size() == V.size())
970 return ConstantDataVector::get(C->getContext(), Elts);
971 }
972 }
Galina Kistanovafc259902012-07-13 01:25:27 +0000973
Chris Lattner978fe0c2012-01-30 06:21:21 +0000974 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
975 if (CFP->getType()->isFloatTy()) {
976 SmallVector<float, 16> Elts;
977 for (unsigned i = 0, e = V.size(); i != e; ++i)
978 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V[i]))
979 Elts.push_back(CFP->getValueAPF().convertToFloat());
980 else
981 break;
982 if (Elts.size() == V.size())
983 return ConstantDataVector::get(C->getContext(), Elts);
984 } else if (CFP->getType()->isDoubleTy()) {
985 SmallVector<double, 16> Elts;
986 for (unsigned i = 0, e = V.size(); i != e; ++i)
987 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V[i]))
988 Elts.push_back(CFP->getValueAPF().convertToDouble());
989 else
990 break;
991 if (Elts.size() == V.size())
992 return ConstantDataVector::get(C->getContext(), Elts);
993 }
994 }
995 }
Galina Kistanovafc259902012-07-13 01:25:27 +0000996
Chris Lattner978fe0c2012-01-30 06:21:21 +0000997 // Otherwise, the element type isn't compatible with ConstantDataVector, or
998 // the operand list constants a ConstantExpr or something else strange.
Owen Anderson4aa32952009-07-28 21:19:26 +0000999 return pImpl->VectorConstants.getOrCreate(T, V);
1000}
1001
Chris Lattnere9eed292012-01-25 05:19:54 +00001002Constant *ConstantVector::getSplat(unsigned NumElts, Constant *V) {
Chris Lattner978fe0c2012-01-30 06:21:21 +00001003 // If this splat is compatible with ConstantDataVector, use it instead of
1004 // ConstantVector.
1005 if ((isa<ConstantFP>(V) || isa<ConstantInt>(V)) &&
1006 ConstantDataSequential::isElementTypeCompatible(V->getType()))
1007 return ConstantDataVector::getSplat(NumElts, V);
Galina Kistanovafc259902012-07-13 01:25:27 +00001008
Chris Lattnere9eed292012-01-25 05:19:54 +00001009 SmallVector<Constant*, 32> Elts(NumElts, V);
1010 return get(Elts);
1011}
1012
1013
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001014// Utility function for determining if a ConstantExpr is a CastOp or not. This
1015// can't be inline because we don't want to #include Instruction.h into
1016// Constant.h
1017bool ConstantExpr::isCast() const {
1018 return Instruction::isCast(getOpcode());
1019}
1020
Reid Spenceree3c9912006-12-04 05:19:50 +00001021bool ConstantExpr::isCompare() const {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00001022 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
Reid Spenceree3c9912006-12-04 05:19:50 +00001023}
1024
Dan Gohman7190d482009-09-10 23:37:55 +00001025bool ConstantExpr::isGEPWithNoNotionalOverIndexing() const {
1026 if (getOpcode() != Instruction::GetElementPtr) return false;
1027
1028 gep_type_iterator GEPI = gep_type_begin(this), E = gep_type_end(this);
Oscar Fuentes40b31ad2010-08-02 06:00:15 +00001029 User::const_op_iterator OI = llvm::next(this->op_begin());
Dan Gohman7190d482009-09-10 23:37:55 +00001030
1031 // Skip the first index, as it has no static limit.
1032 ++GEPI;
1033 ++OI;
1034
1035 // The remaining indices must be compile-time known integers within the
1036 // bounds of the corresponding notional static array types.
1037 for (; GEPI != E; ++GEPI, ++OI) {
1038 ConstantInt *CI = dyn_cast<ConstantInt>(*OI);
1039 if (!CI) return false;
Chris Lattner229907c2011-07-18 04:54:35 +00001040 if (ArrayType *ATy = dyn_cast<ArrayType>(*GEPI))
Dan Gohman7190d482009-09-10 23:37:55 +00001041 if (CI->getValue().getActiveBits() > 64 ||
1042 CI->getZExtValue() >= ATy->getNumElements())
1043 return false;
1044 }
1045
1046 // All the indices checked out.
1047 return true;
1048}
1049
Dan Gohman1ecaf452008-05-31 00:58:22 +00001050bool ConstantExpr::hasIndices() const {
1051 return getOpcode() == Instruction::ExtractValue ||
1052 getOpcode() == Instruction::InsertValue;
1053}
1054
Jay Foad0091fe82011-04-13 15:22:40 +00001055ArrayRef<unsigned> ConstantExpr::getIndices() const {
Dan Gohman1ecaf452008-05-31 00:58:22 +00001056 if (const ExtractValueConstantExpr *EVCE =
1057 dyn_cast<ExtractValueConstantExpr>(this))
1058 return EVCE->Indices;
Dan Gohmana469bdb2008-06-23 16:39:44 +00001059
1060 return cast<InsertValueConstantExpr>(this)->Indices;
Dan Gohman1ecaf452008-05-31 00:58:22 +00001061}
1062
Reid Spencer10fbf0e2006-12-03 05:48:19 +00001063unsigned ConstantExpr::getPredicate() const {
Chris Lattnerd04e32d2011-07-17 06:01:30 +00001064 assert(isCompare());
Chris Lattneref650092007-10-18 16:26:24 +00001065 return ((const CompareConstantExpr*)this)->predicate;
Reid Spencer10fbf0e2006-12-03 05:48:19 +00001066}
Chris Lattner60e0dd72001-10-03 06:12:09 +00001067
Chris Lattner7c1018a2006-07-14 19:37:40 +00001068/// getWithOperandReplaced - Return a constant expression identical to this
1069/// one, but with the specified operand set to the specified value.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001070Constant *
1071ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
Chris Lattner7c1018a2006-07-14 19:37:40 +00001072 assert(Op->getType() == getOperand(OpNo)->getType() &&
1073 "Replacing operand with value of different type!");
Chris Lattner227816342006-07-14 22:20:01 +00001074 if (getOperand(OpNo) == Op)
1075 return const_cast<ConstantExpr*>(this);
Chris Lattner37e38352012-01-26 20:37:11 +00001076
1077 SmallVector<Constant*, 8> NewOps;
1078 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1079 NewOps.push_back(i == OpNo ? Op : getOperand(i));
Galina Kistanovafc259902012-07-13 01:25:27 +00001080
Chris Lattner37e38352012-01-26 20:37:11 +00001081 return getWithOperands(NewOps);
Chris Lattner227816342006-07-14 22:20:01 +00001082}
1083
1084/// getWithOperands - This returns the current constant expression with the
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001085/// operands replaced with the specified values. The specified array must
1086/// have the same number of operands as our current one.
Chris Lattner227816342006-07-14 22:20:01 +00001087Constant *ConstantExpr::
Chris Lattner229907c2011-07-18 04:54:35 +00001088getWithOperands(ArrayRef<Constant*> Ops, Type *Ty) const {
Jay Foad5c984e562011-04-13 13:46:01 +00001089 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001090 bool AnyChange = Ty != getType();
1091 for (unsigned i = 0; i != Ops.size(); ++i)
Chris Lattner227816342006-07-14 22:20:01 +00001092 AnyChange |= Ops[i] != getOperand(i);
Galina Kistanovafc259902012-07-13 01:25:27 +00001093
Chris Lattner227816342006-07-14 22:20:01 +00001094 if (!AnyChange) // No operands changed, return self.
1095 return const_cast<ConstantExpr*>(this);
1096
1097 switch (getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001098 case Instruction::Trunc:
1099 case Instruction::ZExt:
1100 case Instruction::SExt:
1101 case Instruction::FPTrunc:
1102 case Instruction::FPExt:
1103 case Instruction::UIToFP:
1104 case Instruction::SIToFP:
1105 case Instruction::FPToUI:
1106 case Instruction::FPToSI:
1107 case Instruction::PtrToInt:
1108 case Instruction::IntToPtr:
1109 case Instruction::BitCast:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001110 return ConstantExpr::getCast(getOpcode(), Ops[0], Ty);
Chris Lattner227816342006-07-14 22:20:01 +00001111 case Instruction::Select:
1112 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
1113 case Instruction::InsertElement:
1114 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
1115 case Instruction::ExtractElement:
1116 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
Chris Lattner37e38352012-01-26 20:37:11 +00001117 case Instruction::InsertValue:
1118 return ConstantExpr::getInsertValue(Ops[0], Ops[1], getIndices());
1119 case Instruction::ExtractValue:
1120 return ConstantExpr::getExtractValue(Ops[0], getIndices());
Chris Lattner227816342006-07-14 22:20:01 +00001121 case Instruction::ShuffleVector:
1122 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
Chris Lattnerb5d70302007-02-19 20:01:23 +00001123 case Instruction::GetElementPtr:
Chris Lattner37e38352012-01-26 20:37:11 +00001124 return ConstantExpr::getGetElementPtr(Ops[0], Ops.slice(1),
1125 cast<GEPOperator>(this)->isInBounds());
Reid Spencer266e42b2006-12-23 06:05:41 +00001126 case Instruction::ICmp:
1127 case Instruction::FCmp:
1128 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
Chris Lattner227816342006-07-14 22:20:01 +00001129 default:
1130 assert(getNumOperands() == 2 && "Must be binary operator?");
Chris Lattnerb9c86512009-12-29 02:14:09 +00001131 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1], SubclassOptionalData);
Chris Lattner7c1018a2006-07-14 19:37:40 +00001132 }
1133}
1134
Chris Lattner2f7c9632001-06-06 20:29:01 +00001135
1136//===----------------------------------------------------------------------===//
Chris Lattner2f7c9632001-06-06 20:29:01 +00001137// isValueValidForType implementations
1138
Chris Lattner229907c2011-07-18 04:54:35 +00001139bool ConstantInt::isValueValidForType(Type *Ty, uint64_t Val) {
Chris Lattner8326bd82012-01-26 00:42:34 +00001140 unsigned NumBits = Ty->getIntegerBitWidth(); // assert okay
1141 if (Ty->isIntegerTy(1))
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001142 return Val == 0 || Val == 1;
Reid Spencerd7a00d72007-02-05 23:47:56 +00001143 if (NumBits >= 64)
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001144 return true; // always true, has to fit in largest type
1145 uint64_t Max = (1ll << NumBits) - 1;
1146 return Val <= Max;
Reid Spencere7334722006-12-19 01:28:19 +00001147}
1148
Chris Lattner229907c2011-07-18 04:54:35 +00001149bool ConstantInt::isValueValidForType(Type *Ty, int64_t Val) {
Chris Lattner8326bd82012-01-26 00:42:34 +00001150 unsigned NumBits = Ty->getIntegerBitWidth();
1151 if (Ty->isIntegerTy(1))
Reid Spencera94d3942007-01-19 21:13:56 +00001152 return Val == 0 || Val == 1 || Val == -1;
Reid Spencerd7a00d72007-02-05 23:47:56 +00001153 if (NumBits >= 64)
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001154 return true; // always true, has to fit in largest type
1155 int64_t Min = -(1ll << (NumBits-1));
1156 int64_t Max = (1ll << (NumBits-1)) - 1;
1157 return (Val >= Min && Val <= Max);
Chris Lattner2f7c9632001-06-06 20:29:01 +00001158}
1159
Chris Lattner229907c2011-07-18 04:54:35 +00001160bool ConstantFP::isValueValidForType(Type *Ty, const APFloat& Val) {
Dale Johannesend246b2c2007-08-30 00:23:21 +00001161 // convert modifies in place, so make a copy.
1162 APFloat Val2 = APFloat(Val);
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001163 bool losesInfo;
Chris Lattner6b727592004-06-17 18:19:28 +00001164 switch (Ty->getTypeID()) {
Chris Lattner2f7c9632001-06-06 20:29:01 +00001165 default:
1166 return false; // These can't be represented as floating point!
1167
Dale Johannesend246b2c2007-08-30 00:23:21 +00001168 // FIXME rounding mode needs to be more flexible
Dan Gohman518cda42011-12-17 00:04:22 +00001169 case Type::HalfTyID: {
1170 if (&Val2.getSemantics() == &APFloat::IEEEhalf)
1171 return true;
1172 Val2.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, &losesInfo);
1173 return !losesInfo;
1174 }
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001175 case Type::FloatTyID: {
1176 if (&Val2.getSemantics() == &APFloat::IEEEsingle)
1177 return true;
1178 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
1179 return !losesInfo;
1180 }
1181 case Type::DoubleTyID: {
Dan Gohman518cda42011-12-17 00:04:22 +00001182 if (&Val2.getSemantics() == &APFloat::IEEEhalf ||
1183 &Val2.getSemantics() == &APFloat::IEEEsingle ||
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001184 &Val2.getSemantics() == &APFloat::IEEEdouble)
1185 return true;
1186 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
1187 return !losesInfo;
1188 }
Dale Johannesenbdad8092007-08-09 22:51:36 +00001189 case Type::X86_FP80TyID:
Dan Gohman518cda42011-12-17 00:04:22 +00001190 return &Val2.getSemantics() == &APFloat::IEEEhalf ||
1191 &Val2.getSemantics() == &APFloat::IEEEsingle ||
Dale Johannesen028084e2007-09-12 03:30:33 +00001192 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1193 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
Dale Johannesenbdad8092007-08-09 22:51:36 +00001194 case Type::FP128TyID:
Dan Gohman518cda42011-12-17 00:04:22 +00001195 return &Val2.getSemantics() == &APFloat::IEEEhalf ||
1196 &Val2.getSemantics() == &APFloat::IEEEsingle ||
Dale Johannesen028084e2007-09-12 03:30:33 +00001197 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1198 &Val2.getSemantics() == &APFloat::IEEEquad;
Dale Johannesen007aa372007-10-11 18:07:22 +00001199 case Type::PPC_FP128TyID:
Dan Gohman518cda42011-12-17 00:04:22 +00001200 return &Val2.getSemantics() == &APFloat::IEEEhalf ||
1201 &Val2.getSemantics() == &APFloat::IEEEsingle ||
Dale Johannesen007aa372007-10-11 18:07:22 +00001202 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1203 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
Chris Lattner2f7c9632001-06-06 20:29:01 +00001204 }
Chris Lattneraa2372562006-05-24 17:04:05 +00001205}
Chris Lattner9655e542001-07-20 19:16:02 +00001206
Chris Lattner030af792012-01-24 05:42:11 +00001207
Chris Lattner49d855c2001-09-07 16:46:31 +00001208//===----------------------------------------------------------------------===//
Chris Lattner49d855c2001-09-07 16:46:31 +00001209// Factory Function Implementation
1210
Chris Lattnerc7f9fd42012-01-23 15:20:12 +00001211ConstantAggregateZero *ConstantAggregateZero::get(Type *Ty) {
Chris Lattner13ee7952010-08-28 04:09:24 +00001212 assert((Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()) &&
Owen Andersonb292b8c2009-07-30 23:03:37 +00001213 "Cannot create an aggregate zero of non-aggregate type!");
1214
Chris Lattnerc7f9fd42012-01-23 15:20:12 +00001215 ConstantAggregateZero *&Entry = Ty->getContext().pImpl->CAZConstants[Ty];
1216 if (Entry == 0)
1217 Entry = new ConstantAggregateZero(Ty);
Galina Kistanovafc259902012-07-13 01:25:27 +00001218
Chris Lattnerc7f9fd42012-01-23 15:20:12 +00001219 return Entry;
Owen Andersonb292b8c2009-07-30 23:03:37 +00001220}
1221
Chris Lattner030af792012-01-24 05:42:11 +00001222/// destroyConstant - Remove the constant from the constant table.
Dan Gohman92b551b2009-03-03 02:55:14 +00001223///
Owen Anderson0d2de8c2009-06-20 00:24:58 +00001224void ConstantAggregateZero::destroyConstant() {
Chris Lattnerc7f9fd42012-01-23 15:20:12 +00001225 getContext().pImpl->CAZConstants.erase(getType());
Chris Lattner9fba3da2004-02-15 05:53:04 +00001226 destroyConstantImpl();
1227}
1228
Dan Gohman92b551b2009-03-03 02:55:14 +00001229/// destroyConstant - Remove the constant from the constant table...
1230///
Owen Anderson0d2de8c2009-06-20 00:24:58 +00001231void ConstantArray::destroyConstant() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001232 getType()->getContext().pImpl->ArrayConstants.remove(this);
Chris Lattner98fa07b2003-05-23 20:03:32 +00001233 destroyConstantImpl();
1234}
1235
Chris Lattner81fabb02002-08-26 17:53:56 +00001236
Chris Lattner3462ae32001-12-03 22:26:30 +00001237//---- ConstantStruct::get() implementation...
Chris Lattner49d855c2001-09-07 16:46:31 +00001238//
Chris Lattnerb50d1352003-10-05 00:17:43 +00001239
Chris Lattnerd7a73302001-10-13 06:57:33 +00001240// destroyConstant - Remove the constant from the constant table...
Chris Lattner883ad0b2001-10-03 15:39:36 +00001241//
Owen Anderson0d2de8c2009-06-20 00:24:58 +00001242void ConstantStruct::destroyConstant() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001243 getType()->getContext().pImpl->StructConstants.remove(this);
Chris Lattnerd7a73302001-10-13 06:57:33 +00001244 destroyConstantImpl();
1245}
Chris Lattner883ad0b2001-10-03 15:39:36 +00001246
Brian Gaeke02209042004-08-20 06:00:58 +00001247// destroyConstant - Remove the constant from the constant table...
1248//
Owen Anderson0d2de8c2009-06-20 00:24:58 +00001249void ConstantVector::destroyConstant() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001250 getType()->getContext().pImpl->VectorConstants.remove(this);
Brian Gaeke02209042004-08-20 06:00:58 +00001251 destroyConstantImpl();
1252}
1253
Duncan Sandse6beec62012-11-13 12:59:33 +00001254/// getSplatValue - If this is a splat vector constant, meaning that all of
1255/// the elements have the same value, return that value. Otherwise return 0.
1256Constant *Constant::getSplatValue() const {
1257 assert(this->getType()->isVectorTy() && "Only valid for vectors!");
1258 if (isa<ConstantAggregateZero>(this))
1259 return getNullValue(this->getType()->getVectorElementType());
1260 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
1261 return CV->getSplatValue();
1262 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
1263 return CV->getSplatValue();
1264 return 0;
1265}
1266
Dan Gohman07159202007-10-17 17:51:30 +00001267/// getSplatValue - If this is a splat constant, where all of the
1268/// elements have the same value, return that value. Otherwise return null.
Duncan Sandscf0ff032011-02-01 08:39:12 +00001269Constant *ConstantVector::getSplatValue() const {
Dan Gohman07159202007-10-17 17:51:30 +00001270 // Check out first element.
1271 Constant *Elt = getOperand(0);
1272 // Then make sure all remaining elements point to the same value.
1273 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
Chris Lattnerd04e32d2011-07-17 06:01:30 +00001274 if (getOperand(I) != Elt)
1275 return 0;
Dan Gohman07159202007-10-17 17:51:30 +00001276 return Elt;
1277}
1278
Duncan Sandse6beec62012-11-13 12:59:33 +00001279/// If C is a constant integer then return its value, otherwise C must be a
1280/// vector of constant integers, all equal, and the common value is returned.
1281const APInt &Constant::getUniqueInteger() const {
1282 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
1283 return CI->getValue();
1284 assert(this->getSplatValue() && "Doesn't contain a unique integer!");
1285 const Constant *C = this->getAggregateElement(0U);
1286 assert(C && isa<ConstantInt>(C) && "Not a vector of numbers!");
1287 return cast<ConstantInt>(C)->getValue();
1288}
1289
1290
Chris Lattner31b132c2009-10-28 00:01:44 +00001291//---- ConstantPointerNull::get() implementation.
Chris Lattnerd7a73302001-10-13 06:57:33 +00001292//
Chris Lattner98fa07b2003-05-23 20:03:32 +00001293
Chris Lattner229907c2011-07-18 04:54:35 +00001294ConstantPointerNull *ConstantPointerNull::get(PointerType *Ty) {
Chris Lattnerc7f9fd42012-01-23 15:20:12 +00001295 ConstantPointerNull *&Entry = Ty->getContext().pImpl->CPNConstants[Ty];
1296 if (Entry == 0)
1297 Entry = new ConstantPointerNull(Ty);
Galina Kistanovafc259902012-07-13 01:25:27 +00001298
Chris Lattnerc7f9fd42012-01-23 15:20:12 +00001299 return Entry;
Chris Lattner883ad0b2001-10-03 15:39:36 +00001300}
1301
Chris Lattner0c6e0b92002-08-18 00:40:04 +00001302// destroyConstant - Remove the constant from the constant table...
1303//
Owen Anderson0d2de8c2009-06-20 00:24:58 +00001304void ConstantPointerNull::destroyConstant() {
Chris Lattnerc7f9fd42012-01-23 15:20:12 +00001305 getContext().pImpl->CPNConstants.erase(getType());
1306 // Free the constant and any dangling references to it.
Chris Lattner0c6e0b92002-08-18 00:40:04 +00001307 destroyConstantImpl();
1308}
1309
1310
Chris Lattner31b132c2009-10-28 00:01:44 +00001311//---- UndefValue::get() implementation.
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001312//
1313
Chris Lattner229907c2011-07-18 04:54:35 +00001314UndefValue *UndefValue::get(Type *Ty) {
Chris Lattnerc7f9fd42012-01-23 15:20:12 +00001315 UndefValue *&Entry = Ty->getContext().pImpl->UVConstants[Ty];
1316 if (Entry == 0)
1317 Entry = new UndefValue(Ty);
Galina Kistanovafc259902012-07-13 01:25:27 +00001318
Chris Lattnerc7f9fd42012-01-23 15:20:12 +00001319 return Entry;
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001320}
1321
1322// destroyConstant - Remove the constant from the constant table.
1323//
Owen Anderson0d2de8c2009-06-20 00:24:58 +00001324void UndefValue::destroyConstant() {
Chris Lattnerc7f9fd42012-01-23 15:20:12 +00001325 // Free the constant and any dangling references to it.
1326 getContext().pImpl->UVConstants.erase(getType());
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001327 destroyConstantImpl();
1328}
1329
Chris Lattner31b132c2009-10-28 00:01:44 +00001330//---- BlockAddress::get() implementation.
1331//
1332
1333BlockAddress *BlockAddress::get(BasicBlock *BB) {
1334 assert(BB->getParent() != 0 && "Block must have a parent");
1335 return get(BB->getParent(), BB);
1336}
1337
1338BlockAddress *BlockAddress::get(Function *F, BasicBlock *BB) {
1339 BlockAddress *&BA =
1340 F->getContext().pImpl->BlockAddresses[std::make_pair(F, BB)];
1341 if (BA == 0)
1342 BA = new BlockAddress(F, BB);
Galina Kistanovafc259902012-07-13 01:25:27 +00001343
Chris Lattner31b132c2009-10-28 00:01:44 +00001344 assert(BA->getFunction() == F && "Basic block moved between functions");
1345 return BA;
1346}
1347
1348BlockAddress::BlockAddress(Function *F, BasicBlock *BB)
1349: Constant(Type::getInt8PtrTy(F->getContext()), Value::BlockAddressVal,
1350 &Op<0>(), 2) {
Chris Lattnerc559a9f2009-11-01 03:03:03 +00001351 setOperand(0, F);
1352 setOperand(1, BB);
Chris Lattneraa99c942009-11-01 01:27:45 +00001353 BB->AdjustBlockAddressRefCount(1);
Chris Lattner31b132c2009-10-28 00:01:44 +00001354}
1355
1356
1357// destroyConstant - Remove the constant from the constant table.
1358//
1359void BlockAddress::destroyConstant() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001360 getFunction()->getType()->getContext().pImpl
Chris Lattner31b132c2009-10-28 00:01:44 +00001361 ->BlockAddresses.erase(std::make_pair(getFunction(), getBasicBlock()));
Chris Lattneraa99c942009-11-01 01:27:45 +00001362 getBasicBlock()->AdjustBlockAddressRefCount(-1);
Chris Lattner31b132c2009-10-28 00:01:44 +00001363 destroyConstantImpl();
1364}
1365
1366void BlockAddress::replaceUsesOfWithOnConstant(Value *From, Value *To, Use *U) {
1367 // This could be replacing either the Basic Block or the Function. In either
1368 // case, we have to remove the map entry.
1369 Function *NewF = getFunction();
1370 BasicBlock *NewBB = getBasicBlock();
Galina Kistanovafc259902012-07-13 01:25:27 +00001371
Chris Lattner31b132c2009-10-28 00:01:44 +00001372 if (U == &Op<0>())
1373 NewF = cast<Function>(To);
1374 else
1375 NewBB = cast<BasicBlock>(To);
Galina Kistanovafc259902012-07-13 01:25:27 +00001376
Chris Lattner31b132c2009-10-28 00:01:44 +00001377 // See if the 'new' entry already exists, if not, just update this in place
1378 // and return early.
1379 BlockAddress *&NewBA =
1380 getContext().pImpl->BlockAddresses[std::make_pair(NewF, NewBB)];
1381 if (NewBA == 0) {
Chris Lattnerc559a9f2009-11-01 03:03:03 +00001382 getBasicBlock()->AdjustBlockAddressRefCount(-1);
Galina Kistanovafc259902012-07-13 01:25:27 +00001383
Chris Lattner31b132c2009-10-28 00:01:44 +00001384 // Remove the old entry, this can't cause the map to rehash (just a
1385 // tombstone will get added).
1386 getContext().pImpl->BlockAddresses.erase(std::make_pair(getFunction(),
1387 getBasicBlock()));
1388 NewBA = this;
Chris Lattnerc559a9f2009-11-01 03:03:03 +00001389 setOperand(0, NewF);
1390 setOperand(1, NewBB);
1391 getBasicBlock()->AdjustBlockAddressRefCount(1);
Chris Lattner31b132c2009-10-28 00:01:44 +00001392 return;
1393 }
1394
1395 // Otherwise, I do need to replace this with an existing value.
1396 assert(NewBA != this && "I didn't contain From!");
Galina Kistanovafc259902012-07-13 01:25:27 +00001397
Chris Lattner31b132c2009-10-28 00:01:44 +00001398 // Everyone using this now uses the replacement.
Chris Lattneraf1783f2011-07-15 06:18:52 +00001399 replaceAllUsesWith(NewBA);
Galina Kistanovafc259902012-07-13 01:25:27 +00001400
Chris Lattner31b132c2009-10-28 00:01:44 +00001401 destroyConstant();
1402}
1403
1404//---- ConstantExpr::get() implementations.
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001405//
Reid Spencer8d9336d2006-12-31 05:26:44 +00001406
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001407/// This is a utility function to handle folding of casts and lookup of the
Duncan Sands7d6c8ae2008-03-30 19:38:55 +00001408/// cast in the ExprConstants map. It is used by the various get* methods below.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001409static inline Constant *getFoldedCast(
Chris Lattner229907c2011-07-18 04:54:35 +00001410 Instruction::CastOps opc, Constant *C, Type *Ty) {
Chris Lattner815ae2b2003-10-07 22:19:19 +00001411 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001412 // Fold a few common cases
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001413 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001414 return FC;
Chris Lattneracdbe712003-04-17 19:24:48 +00001415
Owen Anderson1584a292009-08-04 20:25:11 +00001416 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
1417
Vikram S. Adve4c485332002-07-15 18:19:33 +00001418 // Look up the constant in the table first to ensure uniqueness
Chris Lattner2b383d2e2003-05-13 21:37:02 +00001419 std::vector<Constant*> argVec(1, C);
Reid Spenceree3c9912006-12-04 05:19:50 +00001420 ExprMapKeyType Key(opc, argVec);
Galina Kistanovafc259902012-07-13 01:25:27 +00001421
Owen Anderson1584a292009-08-04 20:25:11 +00001422 return pImpl->ExprConstants.getOrCreate(Ty, Key);
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001423}
Galina Kistanovafc259902012-07-13 01:25:27 +00001424
Chris Lattner229907c2011-07-18 04:54:35 +00001425Constant *ConstantExpr::getCast(unsigned oc, Constant *C, Type *Ty) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001426 Instruction::CastOps opc = Instruction::CastOps(oc);
1427 assert(Instruction::isCast(opc) && "opcode out of range");
1428 assert(C && Ty && "Null arguments to getCast");
Chris Lattner37bc78a2010-01-26 21:51:43 +00001429 assert(CastInst::castIsValid(opc, C, Ty) && "Invalid constantexpr cast!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001430
1431 switch (opc) {
Chris Lattner37bc78a2010-01-26 21:51:43 +00001432 default:
1433 llvm_unreachable("Invalid cast opcode");
Chris Lattner37bc78a2010-01-26 21:51:43 +00001434 case Instruction::Trunc: return getTrunc(C, Ty);
1435 case Instruction::ZExt: return getZExt(C, Ty);
1436 case Instruction::SExt: return getSExt(C, Ty);
1437 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1438 case Instruction::FPExt: return getFPExtend(C, Ty);
1439 case Instruction::UIToFP: return getUIToFP(C, Ty);
1440 case Instruction::SIToFP: return getSIToFP(C, Ty);
1441 case Instruction::FPToUI: return getFPToUI(C, Ty);
1442 case Instruction::FPToSI: return getFPToSI(C, Ty);
1443 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1444 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1445 case Instruction::BitCast: return getBitCast(C, Ty);
Chris Lattner1ece6f82005-01-01 15:59:57 +00001446 }
Galina Kistanovafc259902012-07-13 01:25:27 +00001447}
Reid Spencerf37dc652006-12-05 19:14:13 +00001448
Chris Lattner229907c2011-07-18 04:54:35 +00001449Constant *ConstantExpr::getZExtOrBitCast(Constant *C, Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001450 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001451 return getBitCast(C, Ty);
1452 return getZExt(C, Ty);
Reid Spencer5c140882006-12-04 20:17:56 +00001453}
1454
Chris Lattner229907c2011-07-18 04:54:35 +00001455Constant *ConstantExpr::getSExtOrBitCast(Constant *C, Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001456 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001457 return getBitCast(C, Ty);
1458 return getSExt(C, Ty);
Reid Spencer5c140882006-12-04 20:17:56 +00001459}
1460
Chris Lattner229907c2011-07-18 04:54:35 +00001461Constant *ConstantExpr::getTruncOrBitCast(Constant *C, Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001462 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001463 return getBitCast(C, Ty);
1464 return getTrunc(C, Ty);
Reid Spencer5c140882006-12-04 20:17:56 +00001465}
1466
Chris Lattner229907c2011-07-18 04:54:35 +00001467Constant *ConstantExpr::getPointerCast(Constant *S, Type *Ty) {
Evgeniy Stepanov23382642013-01-16 14:41:46 +00001468 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
1469 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
1470 "Invalid cast");
Reid Spencerbc245a02006-12-05 03:25:26 +00001471
Evgeniy Stepanov23382642013-01-16 14:41:46 +00001472 if (Ty->isIntOrIntVectorTy())
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001473 return getPtrToInt(S, Ty);
1474 return getBitCast(S, Ty);
Reid Spencerbc245a02006-12-05 03:25:26 +00001475}
1476
Chris Lattner229907c2011-07-18 04:54:35 +00001477Constant *ConstantExpr::getIntegerCast(Constant *C, Type *Ty,
Reid Spencer56521c42006-12-12 00:51:07 +00001478 bool isSigned) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00001479 assert(C->getType()->isIntOrIntVectorTy() &&
1480 Ty->isIntOrIntVectorTy() && "Invalid cast");
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001481 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1482 unsigned DstBits = Ty->getScalarSizeInBits();
Reid Spencer56521c42006-12-12 00:51:07 +00001483 Instruction::CastOps opcode =
1484 (SrcBits == DstBits ? Instruction::BitCast :
1485 (SrcBits > DstBits ? Instruction::Trunc :
1486 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1487 return getCast(opcode, C, Ty);
1488}
1489
Chris Lattner229907c2011-07-18 04:54:35 +00001490Constant *ConstantExpr::getFPCast(Constant *C, Type *Ty) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00001491 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
Reid Spencer56521c42006-12-12 00:51:07 +00001492 "Invalid cast");
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001493 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1494 unsigned DstBits = Ty->getScalarSizeInBits();
Reid Spencerca104e82006-12-12 05:38:50 +00001495 if (SrcBits == DstBits)
1496 return C; // Avoid a useless cast
Reid Spencer56521c42006-12-12 00:51:07 +00001497 Instruction::CastOps opcode =
Jay Foad9f32cfd2011-01-27 14:44:55 +00001498 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
Reid Spencer56521c42006-12-12 00:51:07 +00001499 return getCast(opcode, C, Ty);
1500}
1501
Chris Lattner229907c2011-07-18 04:54:35 +00001502Constant *ConstantExpr::getTrunc(Constant *C, Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001503#ifndef NDEBUG
1504 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1505 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1506#endif
1507 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001508 assert(C->getType()->isIntOrIntVectorTy() && "Trunc operand must be integer");
1509 assert(Ty->isIntOrIntVectorTy() && "Trunc produces only integral");
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001510 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001511 "SrcTy must be larger than DestTy for Trunc!");
1512
Owen Anderson0d2de8c2009-06-20 00:24:58 +00001513 return getFoldedCast(Instruction::Trunc, C, Ty);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001514}
1515
Chris Lattner229907c2011-07-18 04:54:35 +00001516Constant *ConstantExpr::getSExt(Constant *C, Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001517#ifndef NDEBUG
1518 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1519 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1520#endif
1521 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001522 assert(C->getType()->isIntOrIntVectorTy() && "SExt operand must be integral");
1523 assert(Ty->isIntOrIntVectorTy() && "SExt produces only integer");
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001524 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001525 "SrcTy must be smaller than DestTy for SExt!");
1526
Owen Anderson0d2de8c2009-06-20 00:24:58 +00001527 return getFoldedCast(Instruction::SExt, C, Ty);
Chris Lattnerdd284742004-04-04 23:20:30 +00001528}
1529
Chris Lattner229907c2011-07-18 04:54:35 +00001530Constant *ConstantExpr::getZExt(Constant *C, Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001531#ifndef NDEBUG
1532 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1533 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1534#endif
1535 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001536 assert(C->getType()->isIntOrIntVectorTy() && "ZEXt operand must be integral");
1537 assert(Ty->isIntOrIntVectorTy() && "ZExt produces only integer");
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001538 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001539 "SrcTy must be smaller than DestTy for ZExt!");
1540
Owen Anderson0d2de8c2009-06-20 00:24:58 +00001541 return getFoldedCast(Instruction::ZExt, C, Ty);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001542}
1543
Chris Lattner229907c2011-07-18 04:54:35 +00001544Constant *ConstantExpr::getFPTrunc(Constant *C, Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001545#ifndef NDEBUG
1546 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1547 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1548#endif
1549 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001550 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001551 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001552 "This is an illegal floating point truncation!");
Owen Anderson0d2de8c2009-06-20 00:24:58 +00001553 return getFoldedCast(Instruction::FPTrunc, C, Ty);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001554}
1555
Chris Lattner229907c2011-07-18 04:54:35 +00001556Constant *ConstantExpr::getFPExtend(Constant *C, Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001557#ifndef NDEBUG
1558 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1559 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1560#endif
1561 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001562 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001563 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001564 "This is an illegal floating point extension!");
Owen Anderson0d2de8c2009-06-20 00:24:58 +00001565 return getFoldedCast(Instruction::FPExt, C, Ty);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001566}
1567
Chris Lattner229907c2011-07-18 04:54:35 +00001568Constant *ConstantExpr::getUIToFP(Constant *C, Type *Ty) {
Devang Pateld26344d2008-11-03 23:20:04 +00001569#ifndef NDEBUG
Nate Begemand4d45c22007-11-17 03:58:34 +00001570 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1571 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Pateld26344d2008-11-03 23:20:04 +00001572#endif
Nate Begemand4d45c22007-11-17 03:58:34 +00001573 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001574 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
Nate Begemand4d45c22007-11-17 03:58:34 +00001575 "This is an illegal uint to floating point cast!");
Owen Anderson0d2de8c2009-06-20 00:24:58 +00001576 return getFoldedCast(Instruction::UIToFP, C, Ty);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001577}
1578
Chris Lattner229907c2011-07-18 04:54:35 +00001579Constant *ConstantExpr::getSIToFP(Constant *C, Type *Ty) {
Devang Pateld26344d2008-11-03 23:20:04 +00001580#ifndef NDEBUG
Nate Begemand4d45c22007-11-17 03:58:34 +00001581 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1582 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Pateld26344d2008-11-03 23:20:04 +00001583#endif
Nate Begemand4d45c22007-11-17 03:58:34 +00001584 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001585 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001586 "This is an illegal sint to floating point cast!");
Owen Anderson0d2de8c2009-06-20 00:24:58 +00001587 return getFoldedCast(Instruction::SIToFP, C, Ty);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001588}
1589
Chris Lattner229907c2011-07-18 04:54:35 +00001590Constant *ConstantExpr::getFPToUI(Constant *C, Type *Ty) {
Devang Pateld26344d2008-11-03 23:20:04 +00001591#ifndef NDEBUG
Nate Begemand4d45c22007-11-17 03:58:34 +00001592 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1593 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Pateld26344d2008-11-03 23:20:04 +00001594#endif
Nate Begemand4d45c22007-11-17 03:58:34 +00001595 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001596 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
Nate Begemand4d45c22007-11-17 03:58:34 +00001597 "This is an illegal floating point to uint cast!");
Owen Anderson0d2de8c2009-06-20 00:24:58 +00001598 return getFoldedCast(Instruction::FPToUI, C, Ty);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001599}
1600
Chris Lattner229907c2011-07-18 04:54:35 +00001601Constant *ConstantExpr::getFPToSI(Constant *C, Type *Ty) {
Devang Pateld26344d2008-11-03 23:20:04 +00001602#ifndef NDEBUG
Nate Begemand4d45c22007-11-17 03:58:34 +00001603 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1604 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Pateld26344d2008-11-03 23:20:04 +00001605#endif
Nate Begemand4d45c22007-11-17 03:58:34 +00001606 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001607 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
Nate Begemand4d45c22007-11-17 03:58:34 +00001608 "This is an illegal floating point to sint cast!");
Owen Anderson0d2de8c2009-06-20 00:24:58 +00001609 return getFoldedCast(Instruction::FPToSI, C, Ty);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001610}
1611
Chris Lattner229907c2011-07-18 04:54:35 +00001612Constant *ConstantExpr::getPtrToInt(Constant *C, Type *DstTy) {
Nadav Rotem3924cb02011-12-05 06:29:09 +00001613 assert(C->getType()->getScalarType()->isPointerTy() &&
1614 "PtrToInt source must be pointer or pointer vector");
1615 assert(DstTy->getScalarType()->isIntegerTy() &&
1616 "PtrToInt destination must be integer or integer vector");
Chris Lattner8a3df542012-01-25 01:32:59 +00001617 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
Nick Lewyckyff509622012-01-25 03:20:12 +00001618 if (isa<VectorType>(C->getType()))
Chris Lattner8326bd82012-01-26 00:42:34 +00001619 assert(C->getType()->getVectorNumElements()==DstTy->getVectorNumElements()&&
Chris Lattner8a3df542012-01-25 01:32:59 +00001620 "Invalid cast between a different number of vector elements");
Owen Anderson0d2de8c2009-06-20 00:24:58 +00001621 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001622}
1623
Chris Lattner229907c2011-07-18 04:54:35 +00001624Constant *ConstantExpr::getIntToPtr(Constant *C, Type *DstTy) {
Nadav Rotem3924cb02011-12-05 06:29:09 +00001625 assert(C->getType()->getScalarType()->isIntegerTy() &&
1626 "IntToPtr source must be integer or integer vector");
1627 assert(DstTy->getScalarType()->isPointerTy() &&
1628 "IntToPtr destination must be a pointer or pointer vector");
Chris Lattner8a3df542012-01-25 01:32:59 +00001629 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
Nick Lewyckyff509622012-01-25 03:20:12 +00001630 if (isa<VectorType>(C->getType()))
Chris Lattner8326bd82012-01-26 00:42:34 +00001631 assert(C->getType()->getVectorNumElements()==DstTy->getVectorNumElements()&&
Chris Lattner8a3df542012-01-25 01:32:59 +00001632 "Invalid cast between a different number of vector elements");
Owen Anderson0d2de8c2009-06-20 00:24:58 +00001633 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001634}
1635
Chris Lattner229907c2011-07-18 04:54:35 +00001636Constant *ConstantExpr::getBitCast(Constant *C, Type *DstTy) {
Chris Lattner37bc78a2010-01-26 21:51:43 +00001637 assert(CastInst::castIsValid(Instruction::BitCast, C, DstTy) &&
1638 "Invalid constantexpr bitcast!");
Galina Kistanovafc259902012-07-13 01:25:27 +00001639
Chris Lattnercbeda872009-03-21 06:55:54 +00001640 // It is common to ask for a bitcast of a value to its own type, handle this
1641 // speedily.
1642 if (C->getType() == DstTy) return C;
Galina Kistanovafc259902012-07-13 01:25:27 +00001643
Owen Anderson0d2de8c2009-06-20 00:24:58 +00001644 return getFoldedCast(Instruction::BitCast, C, DstTy);
Chris Lattnerdd284742004-04-04 23:20:30 +00001645}
1646
Chris Lattner887ecac2011-07-09 18:23:52 +00001647Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2,
1648 unsigned Flags) {
1649 // Check the operands for consistency first.
Reid Spencer7eb55b32006-11-02 01:53:59 +00001650 assert(Opcode >= Instruction::BinaryOpsBegin &&
1651 Opcode < Instruction::BinaryOpsEnd &&
Chris Lattner38a9bcd2003-05-21 17:49:25 +00001652 "Invalid opcode in binary constant expression");
1653 assert(C1->getType() == C2->getType() &&
1654 "Operand types in binary constant expression should match");
Galina Kistanovafc259902012-07-13 01:25:27 +00001655
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001656#ifndef NDEBUG
1657 switch (Opcode) {
Dan Gohmana5b96452009-06-04 22:49:04 +00001658 case Instruction::Add:
Reid Spencer7eb55b32006-11-02 01:53:59 +00001659 case Instruction::Sub:
Dan Gohmana5b96452009-06-04 22:49:04 +00001660 case Instruction::Mul:
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001661 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001662 assert(C1->getType()->isIntOrIntVectorTy() &&
Dan Gohmana5b96452009-06-04 22:49:04 +00001663 "Tried to create an integer operation on a non-integer type!");
1664 break;
1665 case Instruction::FAdd:
1666 case Instruction::FSub:
1667 case Instruction::FMul:
1668 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001669 assert(C1->getType()->isFPOrFPVectorTy() &&
Dan Gohmana5b96452009-06-04 22:49:04 +00001670 "Tried to create a floating-point operation on a "
1671 "non-floating-point type!");
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001672 break;
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001673 case Instruction::UDiv:
1674 case Instruction::SDiv:
1675 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001676 assert(C1->getType()->isIntOrIntVectorTy() &&
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001677 "Tried to create an arithmetic operation on a non-arithmetic type!");
1678 break;
1679 case Instruction::FDiv:
1680 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001681 assert(C1->getType()->isFPOrFPVectorTy() &&
Dan Gohman7889f2b2009-06-15 22:25:12 +00001682 "Tried to create an arithmetic operation on a non-arithmetic type!");
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001683 break;
Reid Spencer7eb55b32006-11-02 01:53:59 +00001684 case Instruction::URem:
1685 case Instruction::SRem:
1686 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001687 assert(C1->getType()->isIntOrIntVectorTy() &&
Reid Spencer7eb55b32006-11-02 01:53:59 +00001688 "Tried to create an arithmetic operation on a non-arithmetic type!");
1689 break;
1690 case Instruction::FRem:
1691 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001692 assert(C1->getType()->isFPOrFPVectorTy() &&
Dan Gohman7889f2b2009-06-15 22:25:12 +00001693 "Tried to create an arithmetic operation on a non-arithmetic type!");
Reid Spencer7eb55b32006-11-02 01:53:59 +00001694 break;
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001695 case Instruction::And:
1696 case Instruction::Or:
1697 case Instruction::Xor:
1698 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001699 assert(C1->getType()->isIntOrIntVectorTy() &&
Misha Brukman3852f652005-01-27 06:46:38 +00001700 "Tried to create a logical operation on a non-integral type!");
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001701 break;
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001702 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00001703 case Instruction::LShr:
1704 case Instruction::AShr:
Reid Spencer2341c222007-02-02 02:16:23 +00001705 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001706 assert(C1->getType()->isIntOrIntVectorTy() &&
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001707 "Tried to create a shift operation on a non-integer type!");
1708 break;
1709 default:
1710 break;
1711 }
1712#endif
1713
Chris Lattner887ecac2011-07-09 18:23:52 +00001714 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1715 return FC; // Fold a few common cases.
Galina Kistanovafc259902012-07-13 01:25:27 +00001716
Chris Lattner887ecac2011-07-09 18:23:52 +00001717 std::vector<Constant*> argVec(1, C1);
1718 argVec.push_back(C2);
1719 ExprMapKeyType Key(Opcode, argVec, 0, Flags);
Galina Kistanovafc259902012-07-13 01:25:27 +00001720
Chris Lattner887ecac2011-07-09 18:23:52 +00001721 LLVMContextImpl *pImpl = C1->getContext().pImpl;
1722 return pImpl->ExprConstants.getOrCreate(C1->getType(), Key);
Reid Spencera009d0d2006-12-04 21:35:24 +00001723}
1724
Chris Lattner229907c2011-07-18 04:54:35 +00001725Constant *ConstantExpr::getSizeOf(Type* Ty) {
Owen Anderson487375e2009-07-29 18:55:55 +00001726 // sizeof is implemented as: (i64) gep (Ty*)null, 1
1727 // Note that a non-inbounds gep is used, as null isn't within any object.
Owen Anderson55f1c092009-08-13 21:58:54 +00001728 Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
Owen Anderson487375e2009-07-29 18:55:55 +00001729 Constant *GEP = getGetElementPtr(
Jay Foaded8db7d2011-07-21 14:31:17 +00001730 Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001731 return getPtrToInt(GEP,
1732 Type::getInt64Ty(Ty->getContext()));
Owen Anderson487375e2009-07-29 18:55:55 +00001733}
1734
Chris Lattner229907c2011-07-18 04:54:35 +00001735Constant *ConstantExpr::getAlignOf(Type* Ty) {
Dan Gohmancf913832010-01-28 02:15:55 +00001736 // alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1
Dan Gohman50c09d02009-08-11 17:57:01 +00001737 // Note that a non-inbounds gep is used, as null isn't within any object.
Chris Lattner229907c2011-07-18 04:54:35 +00001738 Type *AligningTy =
Chris Lattnerf3f545e2011-06-18 22:48:56 +00001739 StructType::get(Type::getInt1Ty(Ty->getContext()), Ty, NULL);
Micah Villmow51e72462012-10-24 17:25:11 +00001740 Constant *NullPtr = Constant::getNullValue(AligningTy->getPointerTo());
Dan Gohmana9be7392010-01-28 02:43:22 +00001741 Constant *Zero = ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0);
Owen Anderson55f1c092009-08-13 21:58:54 +00001742 Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
Owen Anderson487375e2009-07-29 18:55:55 +00001743 Constant *Indices[2] = { Zero, One };
Jay Foaded8db7d2011-07-21 14:31:17 +00001744 Constant *GEP = getGetElementPtr(NullPtr, Indices);
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001745 return getPtrToInt(GEP,
1746 Type::getInt64Ty(Ty->getContext()));
Owen Anderson487375e2009-07-29 18:55:55 +00001747}
1748
Chris Lattner229907c2011-07-18 04:54:35 +00001749Constant *ConstantExpr::getOffsetOf(StructType* STy, unsigned FieldNo) {
Dan Gohmanede94e62010-02-01 16:37:38 +00001750 return getOffsetOf(STy, ConstantInt::get(Type::getInt32Ty(STy->getContext()),
1751 FieldNo));
1752}
1753
Chris Lattner229907c2011-07-18 04:54:35 +00001754Constant *ConstantExpr::getOffsetOf(Type* Ty, Constant *FieldNo) {
Dan Gohmanff3af7252009-08-16 21:26:11 +00001755 // offsetof is implemented as: (i64) gep (Ty*)null, 0, FieldNo
1756 // Note that a non-inbounds gep is used, as null isn't within any object.
1757 Constant *GEPIdx[] = {
Dan Gohmanede94e62010-02-01 16:37:38 +00001758 ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0),
1759 FieldNo
Dan Gohmanff3af7252009-08-16 21:26:11 +00001760 };
1761 Constant *GEP = getGetElementPtr(
Jay Foaded8db7d2011-07-21 14:31:17 +00001762 Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001763 return getPtrToInt(GEP,
1764 Type::getInt64Ty(Ty->getContext()));
Dan Gohmanff3af7252009-08-16 21:26:11 +00001765}
Owen Anderson487375e2009-07-29 18:55:55 +00001766
Chris Lattner887ecac2011-07-09 18:23:52 +00001767Constant *ConstantExpr::getCompare(unsigned short Predicate,
1768 Constant *C1, Constant *C2) {
Reid Spencera009d0d2006-12-04 21:35:24 +00001769 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Galina Kistanovafc259902012-07-13 01:25:27 +00001770
Chris Lattner887ecac2011-07-09 18:23:52 +00001771 switch (Predicate) {
1772 default: llvm_unreachable("Invalid CmpInst predicate");
1773 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
1774 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
1775 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
1776 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
1777 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
1778 case CmpInst::FCMP_TRUE:
1779 return getFCmp(Predicate, C1, C2);
Galina Kistanovafc259902012-07-13 01:25:27 +00001780
Chris Lattner887ecac2011-07-09 18:23:52 +00001781 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
1782 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
1783 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
1784 case CmpInst::ICMP_SLE:
1785 return getICmp(Predicate, C1, C2);
1786 }
Chris Lattner29ca2c62004-08-04 18:50:09 +00001787}
1788
Chris Lattner887ecac2011-07-09 18:23:52 +00001789Constant *ConstantExpr::getSelect(Constant *C, Constant *V1, Constant *V2) {
Chris Lattner41632132008-12-29 00:16:12 +00001790 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
Chris Lattner6e415c02004-03-12 05:54:04 +00001791
Chris Lattner887ecac2011-07-09 18:23:52 +00001792 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1793 return SC; // Fold common cases
Chris Lattner6e415c02004-03-12 05:54:04 +00001794
1795 std::vector<Constant*> argVec(3, C);
1796 argVec[1] = V1;
1797 argVec[2] = V2;
Reid Spenceree3c9912006-12-04 05:19:50 +00001798 ExprMapKeyType Key(Instruction::Select, argVec);
Galina Kistanovafc259902012-07-13 01:25:27 +00001799
Chris Lattner887ecac2011-07-09 18:23:52 +00001800 LLVMContextImpl *pImpl = C->getContext().pImpl;
1801 return pImpl->ExprConstants.getOrCreate(V1->getType(), Key);
Chris Lattner6e415c02004-03-12 05:54:04 +00001802}
1803
Jay Foaded8db7d2011-07-21 14:31:17 +00001804Constant *ConstantExpr::getGetElementPtr(Constant *C, ArrayRef<Value *> Idxs,
1805 bool InBounds) {
Duncan Sandse6beec62012-11-13 12:59:33 +00001806 assert(C->getType()->isPtrOrPtrVectorTy() &&
1807 "Non-pointer type for constant GetElementPtr expression");
1808
Jay Foaded8db7d2011-07-21 14:31:17 +00001809 if (Constant *FC = ConstantFoldGetElementPtr(C, InBounds, Idxs))
Chris Lattner94c8d292011-02-11 05:34:33 +00001810 return FC; // Fold a few common cases.
Dan Gohman1b849082009-09-07 23:54:19 +00001811
Chris Lattner887ecac2011-07-09 18:23:52 +00001812 // Get the result type of the getelementptr!
Jay Foadd1b78492011-07-25 09:48:08 +00001813 Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), Idxs);
Chris Lattner887ecac2011-07-09 18:23:52 +00001814 assert(Ty && "GEP indices invalid!");
Chris Lattner8326bd82012-01-26 00:42:34 +00001815 unsigned AS = C->getType()->getPointerAddressSpace();
Chris Lattner887ecac2011-07-09 18:23:52 +00001816 Type *ReqTy = Ty->getPointerTo(AS);
Duncan Sandse6beec62012-11-13 12:59:33 +00001817 if (VectorType *VecTy = dyn_cast<VectorType>(C->getType()))
1818 ReqTy = VectorType::get(ReqTy, VecTy->getNumElements());
Galina Kistanovafc259902012-07-13 01:25:27 +00001819
Dan Gohman1b849082009-09-07 23:54:19 +00001820 // Look up the constant in the table first to ensure uniqueness
1821 std::vector<Constant*> ArgVec;
Jay Foaded8db7d2011-07-21 14:31:17 +00001822 ArgVec.reserve(1 + Idxs.size());
Dan Gohman1b849082009-09-07 23:54:19 +00001823 ArgVec.push_back(C);
Duncan Sandse6beec62012-11-13 12:59:33 +00001824 for (unsigned i = 0, e = Idxs.size(); i != e; ++i) {
1825 assert(Idxs[i]->getType()->isVectorTy() == ReqTy->isVectorTy() &&
1826 "getelementptr index type missmatch");
1827 assert((!Idxs[i]->getType()->isVectorTy() ||
1828 ReqTy->getVectorNumElements() ==
1829 Idxs[i]->getType()->getVectorNumElements()) &&
1830 "getelementptr index type missmatch");
Dan Gohman1b849082009-09-07 23:54:19 +00001831 ArgVec.push_back(cast<Constant>(Idxs[i]));
Duncan Sandse6beec62012-11-13 12:59:33 +00001832 }
Dan Gohman1b849082009-09-07 23:54:19 +00001833 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec, 0,
Chris Lattner94c8d292011-02-11 05:34:33 +00001834 InBounds ? GEPOperator::IsInBounds : 0);
Galina Kistanovafc259902012-07-13 01:25:27 +00001835
Chris Lattner887ecac2011-07-09 18:23:52 +00001836 LLVMContextImpl *pImpl = C->getContext().pImpl;
Dan Gohman1b849082009-09-07 23:54:19 +00001837 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1838}
1839
Reid Spenceree3c9912006-12-04 05:19:50 +00001840Constant *
Nick Lewycky9e26c1c2010-01-21 07:03:21 +00001841ConstantExpr::getICmp(unsigned short pred, Constant *LHS, Constant *RHS) {
Reid Spenceree3c9912006-12-04 05:19:50 +00001842 assert(LHS->getType() == RHS->getType());
1843 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
1844 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1845
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001846 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
Reid Spenceree3c9912006-12-04 05:19:50 +00001847 return FC; // Fold a few common cases...
1848
1849 // Look up the constant in the table first to ensure uniqueness
1850 std::vector<Constant*> ArgVec;
1851 ArgVec.push_back(LHS);
1852 ArgVec.push_back(RHS);
Reid Spencerb1537492006-12-24 18:42:29 +00001853 // Get the key type with both the opcode and predicate
Reid Spenceree3c9912006-12-04 05:19:50 +00001854 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
Owen Anderson61794042009-06-17 20:10:08 +00001855
Chris Lattner229907c2011-07-18 04:54:35 +00001856 Type *ResultTy = Type::getInt1Ty(LHS->getContext());
1857 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
Nick Lewycky9e26c1c2010-01-21 07:03:21 +00001858 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
1859
Owen Anderson1584a292009-08-04 20:25:11 +00001860 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
Nick Lewycky9e26c1c2010-01-21 07:03:21 +00001861 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
Reid Spenceree3c9912006-12-04 05:19:50 +00001862}
1863
1864Constant *
Nick Lewycky9e26c1c2010-01-21 07:03:21 +00001865ConstantExpr::getFCmp(unsigned short pred, Constant *LHS, Constant *RHS) {
Reid Spenceree3c9912006-12-04 05:19:50 +00001866 assert(LHS->getType() == RHS->getType());
1867 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1868
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001869 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
Reid Spenceree3c9912006-12-04 05:19:50 +00001870 return FC; // Fold a few common cases...
1871
1872 // Look up the constant in the table first to ensure uniqueness
1873 std::vector<Constant*> ArgVec;
1874 ArgVec.push_back(LHS);
1875 ArgVec.push_back(RHS);
Reid Spencerb1537492006-12-24 18:42:29 +00001876 // Get the key type with both the opcode and predicate
Reid Spenceree3c9912006-12-04 05:19:50 +00001877 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
Nick Lewycky9e26c1c2010-01-21 07:03:21 +00001878
Chris Lattner229907c2011-07-18 04:54:35 +00001879 Type *ResultTy = Type::getInt1Ty(LHS->getContext());
1880 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
Nick Lewycky9e26c1c2010-01-21 07:03:21 +00001881 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
1882
Owen Anderson1584a292009-08-04 20:25:11 +00001883 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
Nick Lewycky9e26c1c2010-01-21 07:03:21 +00001884 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
Reid Spenceree3c9912006-12-04 05:19:50 +00001885}
1886
Robert Bocchino23004482006-01-10 19:05:34 +00001887Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
Duncan Sands19d0b472010-02-16 11:11:14 +00001888 assert(Val->getType()->isVectorTy() &&
Reid Spencer09575ba2007-02-15 03:39:18 +00001889 "Tried to create extractelement operation on non-vector type!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001890 assert(Idx->getType()->isIntegerTy(32) &&
Reid Spencer2546b762007-01-26 07:37:34 +00001891 "Extractelement index must be i32 type!");
Galina Kistanovafc259902012-07-13 01:25:27 +00001892
Chris Lattner887ecac2011-07-09 18:23:52 +00001893 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
Chris Lattner09660c92009-12-30 20:25:09 +00001894 return FC; // Fold a few common cases.
Galina Kistanovafc259902012-07-13 01:25:27 +00001895
Robert Bocchinoca27f032006-01-17 20:07:22 +00001896 // Look up the constant in the table first to ensure uniqueness
1897 std::vector<Constant*> ArgVec(1, Val);
Robert Bocchinoca27f032006-01-17 20:07:22 +00001898 ArgVec.push_back(Idx);
Chris Lattner887ecac2011-07-09 18:23:52 +00001899 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
Galina Kistanovafc259902012-07-13 01:25:27 +00001900
Chris Lattner887ecac2011-07-09 18:23:52 +00001901 LLVMContextImpl *pImpl = Val->getContext().pImpl;
Chris Lattner8326bd82012-01-26 00:42:34 +00001902 Type *ReqTy = Val->getType()->getVectorElementType();
Owen Anderson1584a292009-08-04 20:25:11 +00001903 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
Robert Bocchinoca27f032006-01-17 20:07:22 +00001904}
1905
1906Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1907 Constant *Idx) {
Duncan Sands19d0b472010-02-16 11:11:14 +00001908 assert(Val->getType()->isVectorTy() &&
Reid Spencer09575ba2007-02-15 03:39:18 +00001909 "Tried to create insertelement operation on non-vector type!");
Chris Lattner8326bd82012-01-26 00:42:34 +00001910 assert(Elt->getType() == Val->getType()->getVectorElementType() &&
1911 "Insertelement types must match!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001912 assert(Idx->getType()->isIntegerTy(32) &&
Reid Spencer2546b762007-01-26 07:37:34 +00001913 "Insertelement index must be i32 type!");
Robert Bocchinoca27f032006-01-17 20:07:22 +00001914
Chris Lattner887ecac2011-07-09 18:23:52 +00001915 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
1916 return FC; // Fold a few common cases.
Chris Lattnerbbe0a422006-04-08 01:18:18 +00001917 // Look up the constant in the table first to ensure uniqueness
Chris Lattner887ecac2011-07-09 18:23:52 +00001918 std::vector<Constant*> ArgVec(1, Val);
1919 ArgVec.push_back(Elt);
1920 ArgVec.push_back(Idx);
1921 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
Galina Kistanovafc259902012-07-13 01:25:27 +00001922
Chris Lattner887ecac2011-07-09 18:23:52 +00001923 LLVMContextImpl *pImpl = Val->getContext().pImpl;
1924 return pImpl->ExprConstants.getOrCreate(Val->getType(), Key);
Chris Lattnerbbe0a422006-04-08 01:18:18 +00001925}
1926
1927Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
1928 Constant *Mask) {
1929 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1930 "Invalid shuffle vector constant expr operands!");
Nate Begeman94aa38d2009-02-12 21:28:33 +00001931
Chris Lattner887ecac2011-07-09 18:23:52 +00001932 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
1933 return FC; // Fold a few common cases.
1934
Chris Lattner8326bd82012-01-26 00:42:34 +00001935 unsigned NElts = Mask->getType()->getVectorNumElements();
1936 Type *EltTy = V1->getType()->getVectorElementType();
Chris Lattner229907c2011-07-18 04:54:35 +00001937 Type *ShufTy = VectorType::get(EltTy, NElts);
Chris Lattner887ecac2011-07-09 18:23:52 +00001938
1939 // Look up the constant in the table first to ensure uniqueness
1940 std::vector<Constant*> ArgVec(1, V1);
1941 ArgVec.push_back(V2);
1942 ArgVec.push_back(Mask);
1943 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
Galina Kistanovafc259902012-07-13 01:25:27 +00001944
Chris Lattner887ecac2011-07-09 18:23:52 +00001945 LLVMContextImpl *pImpl = ShufTy->getContext().pImpl;
1946 return pImpl->ExprConstants.getOrCreate(ShufTy, Key);
Chris Lattnerbbe0a422006-04-08 01:18:18 +00001947}
1948
Chris Lattner887ecac2011-07-09 18:23:52 +00001949Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
Jay Foad57aa6362011-07-13 10:26:04 +00001950 ArrayRef<unsigned> Idxs) {
1951 assert(ExtractValueInst::getIndexedType(Agg->getType(),
1952 Idxs) == Val->getType() &&
Dan Gohman12fce772008-05-15 19:50:34 +00001953 "insertvalue indices invalid!");
Dan Gohman0752bff2008-05-23 00:36:11 +00001954 assert(Agg->getType()->isFirstClassType() &&
Chris Lattner6ebfbf52011-07-12 05:26:21 +00001955 "Non-first-class type for constant insertvalue expression");
Jay Foad57aa6362011-07-13 10:26:04 +00001956 Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs);
Chris Lattner6ebfbf52011-07-12 05:26:21 +00001957 assert(FC && "insertvalue constant expr couldn't be folded!");
Dan Gohmand5d24f62008-07-21 23:30:30 +00001958 return FC;
Dan Gohman12fce772008-05-15 19:50:34 +00001959}
1960
Chris Lattner887ecac2011-07-09 18:23:52 +00001961Constant *ConstantExpr::getExtractValue(Constant *Agg,
Jay Foad57aa6362011-07-13 10:26:04 +00001962 ArrayRef<unsigned> Idxs) {
Dan Gohman0752bff2008-05-23 00:36:11 +00001963 assert(Agg->getType()->isFirstClassType() &&
Chris Lattner887ecac2011-07-09 18:23:52 +00001964 "Tried to create extractelement operation on non-first-class type!");
Dan Gohman12fce772008-05-15 19:50:34 +00001965
Chris Lattner229907c2011-07-18 04:54:35 +00001966 Type *ReqTy = ExtractValueInst::getIndexedType(Agg->getType(), Idxs);
Chandler Carruth9db56b82011-07-10 09:45:35 +00001967 (void)ReqTy;
Chris Lattner887ecac2011-07-09 18:23:52 +00001968 assert(ReqTy && "extractvalue indices invalid!");
Galina Kistanovafc259902012-07-13 01:25:27 +00001969
Dan Gohman0752bff2008-05-23 00:36:11 +00001970 assert(Agg->getType()->isFirstClassType() &&
1971 "Non-first-class type for constant extractvalue expression");
Jay Foad57aa6362011-07-13 10:26:04 +00001972 Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs);
Dan Gohmand5d24f62008-07-21 23:30:30 +00001973 assert(FC && "ExtractValue constant expr couldn't be folded!");
1974 return FC;
Dan Gohman12fce772008-05-15 19:50:34 +00001975}
1976
Chris Lattnere9b4ad72011-02-10 07:01:55 +00001977Constant *ConstantExpr::getNeg(Constant *C, bool HasNUW, bool HasNSW) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00001978 assert(C->getType()->isIntOrIntVectorTy() &&
Owen Anderson487375e2009-07-29 18:55:55 +00001979 "Cannot NEG a nonintegral value!");
Chris Lattnere9b4ad72011-02-10 07:01:55 +00001980 return getSub(ConstantFP::getZeroValueForNegation(C->getType()),
1981 C, HasNUW, HasNSW);
Owen Anderson487375e2009-07-29 18:55:55 +00001982}
1983
Chris Lattnera676c0f2011-02-07 16:40:21 +00001984Constant *ConstantExpr::getFNeg(Constant *C) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00001985 assert(C->getType()->isFPOrFPVectorTy() &&
Owen Anderson487375e2009-07-29 18:55:55 +00001986 "Cannot FNEG a non-floating-point value!");
Chris Lattnere9b4ad72011-02-10 07:01:55 +00001987 return getFSub(ConstantFP::getZeroValueForNegation(C->getType()), C);
Owen Anderson487375e2009-07-29 18:55:55 +00001988}
1989
Chris Lattnera676c0f2011-02-07 16:40:21 +00001990Constant *ConstantExpr::getNot(Constant *C) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00001991 assert(C->getType()->isIntOrIntVectorTy() &&
Owen Anderson487375e2009-07-29 18:55:55 +00001992 "Cannot NOT a nonintegral value!");
Owen Anderson5a1acd92009-07-31 20:28:14 +00001993 return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
Owen Anderson487375e2009-07-29 18:55:55 +00001994}
1995
Chris Lattnere9b4ad72011-02-10 07:01:55 +00001996Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2,
1997 bool HasNUW, bool HasNSW) {
1998 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
1999 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2000 return get(Instruction::Add, C1, C2, Flags);
Owen Anderson487375e2009-07-29 18:55:55 +00002001}
2002
Chris Lattnera676c0f2011-02-07 16:40:21 +00002003Constant *ConstantExpr::getFAdd(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002004 return get(Instruction::FAdd, C1, C2);
2005}
2006
Chris Lattnere9b4ad72011-02-10 07:01:55 +00002007Constant *ConstantExpr::getSub(Constant *C1, Constant *C2,
2008 bool HasNUW, bool HasNSW) {
2009 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2010 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2011 return get(Instruction::Sub, C1, C2, Flags);
Owen Anderson487375e2009-07-29 18:55:55 +00002012}
2013
Chris Lattnera676c0f2011-02-07 16:40:21 +00002014Constant *ConstantExpr::getFSub(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002015 return get(Instruction::FSub, C1, C2);
2016}
2017
Chris Lattnere9b4ad72011-02-10 07:01:55 +00002018Constant *ConstantExpr::getMul(Constant *C1, Constant *C2,
2019 bool HasNUW, bool HasNSW) {
2020 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2021 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2022 return get(Instruction::Mul, C1, C2, Flags);
Owen Anderson487375e2009-07-29 18:55:55 +00002023}
2024
Chris Lattnera676c0f2011-02-07 16:40:21 +00002025Constant *ConstantExpr::getFMul(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002026 return get(Instruction::FMul, C1, C2);
2027}
2028
Chris Lattner0d75eac2011-02-09 16:43:07 +00002029Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2, bool isExact) {
2030 return get(Instruction::UDiv, C1, C2,
2031 isExact ? PossiblyExactOperator::IsExact : 0);
Owen Anderson487375e2009-07-29 18:55:55 +00002032}
2033
Chris Lattner0d75eac2011-02-09 16:43:07 +00002034Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2, bool isExact) {
2035 return get(Instruction::SDiv, C1, C2,
2036 isExact ? PossiblyExactOperator::IsExact : 0);
Owen Anderson487375e2009-07-29 18:55:55 +00002037}
2038
Chris Lattnera676c0f2011-02-07 16:40:21 +00002039Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002040 return get(Instruction::FDiv, C1, C2);
2041}
2042
Chris Lattnera676c0f2011-02-07 16:40:21 +00002043Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002044 return get(Instruction::URem, C1, C2);
2045}
2046
Chris Lattnera676c0f2011-02-07 16:40:21 +00002047Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002048 return get(Instruction::SRem, C1, C2);
2049}
2050
Chris Lattnera676c0f2011-02-07 16:40:21 +00002051Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002052 return get(Instruction::FRem, C1, C2);
2053}
2054
Chris Lattnera676c0f2011-02-07 16:40:21 +00002055Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002056 return get(Instruction::And, C1, C2);
2057}
2058
Chris Lattnera676c0f2011-02-07 16:40:21 +00002059Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002060 return get(Instruction::Or, C1, C2);
2061}
2062
Chris Lattnera676c0f2011-02-07 16:40:21 +00002063Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002064 return get(Instruction::Xor, C1, C2);
2065}
2066
Chris Lattnere9b4ad72011-02-10 07:01:55 +00002067Constant *ConstantExpr::getShl(Constant *C1, Constant *C2,
2068 bool HasNUW, bool HasNSW) {
2069 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2070 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2071 return get(Instruction::Shl, C1, C2, Flags);
Owen Anderson487375e2009-07-29 18:55:55 +00002072}
2073
Chris Lattner0d75eac2011-02-09 16:43:07 +00002074Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2, bool isExact) {
2075 return get(Instruction::LShr, C1, C2,
2076 isExact ? PossiblyExactOperator::IsExact : 0);
Owen Anderson487375e2009-07-29 18:55:55 +00002077}
2078
Chris Lattner0d75eac2011-02-09 16:43:07 +00002079Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2, bool isExact) {
2080 return get(Instruction::AShr, C1, C2,
2081 isExact ? PossiblyExactOperator::IsExact : 0);
Owen Anderson487375e2009-07-29 18:55:55 +00002082}
2083
Duncan Sandsd7aeefe2012-06-12 14:33:56 +00002084/// getBinOpIdentity - Return the identity for the given binary operation,
2085/// i.e. a constant C such that X op C = X and C op X = X for every X. It
Duncan Sands318a89d2012-06-13 09:42:13 +00002086/// returns null if the operator doesn't have an identity.
Duncan Sandsd7aeefe2012-06-12 14:33:56 +00002087Constant *ConstantExpr::getBinOpIdentity(unsigned Opcode, Type *Ty) {
2088 switch (Opcode) {
2089 default:
Duncan Sands318a89d2012-06-13 09:42:13 +00002090 // Doesn't have an identity.
2091 return 0;
2092
Duncan Sandsd7aeefe2012-06-12 14:33:56 +00002093 case Instruction::Add:
2094 case Instruction::Or:
2095 case Instruction::Xor:
2096 return Constant::getNullValue(Ty);
2097
2098 case Instruction::Mul:
2099 return ConstantInt::get(Ty, 1);
2100
2101 case Instruction::And:
2102 return Constant::getAllOnesValue(Ty);
2103 }
2104}
2105
Duncan Sands318a89d2012-06-13 09:42:13 +00002106/// getBinOpAbsorber - Return the absorbing element for the given binary
2107/// operation, i.e. a constant C such that X op C = C and C op X = C for
2108/// every X. For example, this returns zero for integer multiplication.
2109/// It returns null if the operator doesn't have an absorbing element.
2110Constant *ConstantExpr::getBinOpAbsorber(unsigned Opcode, Type *Ty) {
2111 switch (Opcode) {
2112 default:
2113 // Doesn't have an absorber.
2114 return 0;
2115
2116 case Instruction::Or:
2117 return Constant::getAllOnesValue(Ty);
2118
2119 case Instruction::And:
2120 case Instruction::Mul:
2121 return Constant::getNullValue(Ty);
2122 }
2123}
2124
Vikram S. Adve4c485332002-07-15 18:19:33 +00002125// destroyConstant - Remove the constant from the constant table...
2126//
Owen Anderson0d2de8c2009-06-20 00:24:58 +00002127void ConstantExpr::destroyConstant() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002128 getType()->getContext().pImpl->ExprConstants.remove(this);
Vikram S. Adve4c485332002-07-15 18:19:33 +00002129 destroyConstantImpl();
Vikram S. Adve4e537b22002-07-14 23:13:17 +00002130}
2131
Chris Lattner3cd8c562002-07-30 18:54:25 +00002132const char *ConstantExpr::getOpcodeName() const {
2133 return Instruction::getOpcodeName(getOpcode());
Vikram S. Adve4e537b22002-07-14 23:13:17 +00002134}
Reid Spencer1ebe1ab2004-07-17 23:48:33 +00002135
Chris Lattnera3b94ba2010-03-30 20:48:48 +00002136
2137
2138GetElementPtrConstantExpr::
Chris Lattnera474bb22012-01-26 20:40:56 +00002139GetElementPtrConstantExpr(Constant *C, ArrayRef<Constant*> IdxList,
Chris Lattner229907c2011-07-18 04:54:35 +00002140 Type *DestTy)
Chris Lattnera3b94ba2010-03-30 20:48:48 +00002141 : ConstantExpr(DestTy, Instruction::GetElementPtr,
2142 OperandTraits<GetElementPtrConstantExpr>::op_end(this)
2143 - (IdxList.size()+1), IdxList.size()+1) {
2144 OperandList[0] = C;
2145 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
2146 OperandList[i+1] = IdxList[i];
2147}
2148
Chris Lattner3756b912012-01-23 22:57:10 +00002149//===----------------------------------------------------------------------===//
2150// ConstantData* implementations
2151
2152void ConstantDataArray::anchor() {}
2153void ConstantDataVector::anchor() {}
2154
Chris Lattnere4f3f102012-01-24 04:43:41 +00002155/// getElementType - Return the element type of the array/vector.
2156Type *ConstantDataSequential::getElementType() const {
2157 return getType()->getElementType();
2158}
2159
Chris Lattner5d4497b2012-01-24 09:31:43 +00002160StringRef ConstantDataSequential::getRawDataValues() const {
Chris Lattner00245f42012-01-24 13:41:11 +00002161 return StringRef(DataElements, getNumElements()*getElementByteSize());
Chris Lattner5d4497b2012-01-24 09:31:43 +00002162}
2163
Chris Lattner030af792012-01-24 05:42:11 +00002164/// isElementTypeCompatible - Return true if a ConstantDataSequential can be
2165/// formed with a vector or array of the specified element type.
2166/// ConstantDataArray only works with normal float and int types that are
2167/// stored densely in memory, not with things like i42 or x86_f80.
2168bool ConstantDataSequential::isElementTypeCompatible(const Type *Ty) {
Chris Lattnere4f3f102012-01-24 04:43:41 +00002169 if (Ty->isFloatTy() || Ty->isDoubleTy()) return true;
2170 if (const IntegerType *IT = dyn_cast<IntegerType>(Ty)) {
2171 switch (IT->getBitWidth()) {
2172 case 8:
2173 case 16:
2174 case 32:
2175 case 64:
2176 return true;
2177 default: break;
2178 }
2179 }
2180 return false;
2181}
2182
Chris Lattner00245f42012-01-24 13:41:11 +00002183/// getNumElements - Return the number of elements in the array or vector.
2184unsigned ConstantDataSequential::getNumElements() const {
Chris Lattner8a3df542012-01-25 01:32:59 +00002185 if (ArrayType *AT = dyn_cast<ArrayType>(getType()))
2186 return AT->getNumElements();
Chris Lattner8326bd82012-01-26 00:42:34 +00002187 return getType()->getVectorNumElements();
Chris Lattner00245f42012-01-24 13:41:11 +00002188}
2189
2190
Chris Lattnere4f3f102012-01-24 04:43:41 +00002191/// getElementByteSize - Return the size in bytes of the elements in the data.
2192uint64_t ConstantDataSequential::getElementByteSize() const {
2193 return getElementType()->getPrimitiveSizeInBits()/8;
2194}
2195
2196/// getElementPointer - Return the start of the specified element.
2197const char *ConstantDataSequential::getElementPointer(unsigned Elt) const {
Chris Lattner00245f42012-01-24 13:41:11 +00002198 assert(Elt < getNumElements() && "Invalid Elt");
Chris Lattnere4f3f102012-01-24 04:43:41 +00002199 return DataElements+Elt*getElementByteSize();
2200}
2201
2202
Chris Lattner3756b912012-01-23 22:57:10 +00002203/// isAllZeros - return true if the array is empty or all zeros.
2204static bool isAllZeros(StringRef Arr) {
2205 for (StringRef::iterator I = Arr.begin(), E = Arr.end(); I != E; ++I)
2206 if (*I != 0)
2207 return false;
2208 return true;
2209}
Chris Lattner030af792012-01-24 05:42:11 +00002210
Chris Lattner3756b912012-01-23 22:57:10 +00002211/// getImpl - This is the underlying implementation of all of the
2212/// ConstantDataSequential::get methods. They all thunk down to here, providing
Chris Lattnerf06039b2012-01-30 18:19:30 +00002213/// the correct element type. We take the bytes in as a StringRef because
Chris Lattner3756b912012-01-23 22:57:10 +00002214/// we *want* an underlying "char*" to avoid TBAA type punning violations.
2215Constant *ConstantDataSequential::getImpl(StringRef Elements, Type *Ty) {
Chris Lattner8326bd82012-01-26 00:42:34 +00002216 assert(isElementTypeCompatible(Ty->getSequentialElementType()));
Chris Lattner139822f2012-01-24 14:17:05 +00002217 // If the elements are all zero or there are no elements, return a CAZ, which
2218 // is more dense and canonical.
Chris Lattner3756b912012-01-23 22:57:10 +00002219 if (isAllZeros(Elements))
2220 return ConstantAggregateZero::get(Ty);
2221
2222 // Do a lookup to see if we have already formed one of these.
2223 StringMap<ConstantDataSequential*>::MapEntryTy &Slot =
2224 Ty->getContext().pImpl->CDSConstants.GetOrCreateValue(Elements);
Galina Kistanovafc259902012-07-13 01:25:27 +00002225
Chris Lattner3756b912012-01-23 22:57:10 +00002226 // The bucket can point to a linked list of different CDS's that have the same
2227 // body but different types. For example, 0,0,0,1 could be a 4 element array
2228 // of i8, or a 1-element array of i32. They'll both end up in the same
2229 /// StringMap bucket, linked up by their Next pointers. Walk the list.
2230 ConstantDataSequential **Entry = &Slot.getValue();
2231 for (ConstantDataSequential *Node = *Entry; Node != 0;
2232 Entry = &Node->Next, Node = *Entry)
2233 if (Node->getType() == Ty)
2234 return Node;
Galina Kistanovafc259902012-07-13 01:25:27 +00002235
Chris Lattner3756b912012-01-23 22:57:10 +00002236 // Okay, we didn't get a hit. Create a node of the right class, link it in,
2237 // and return it.
2238 if (isa<ArrayType>(Ty))
2239 return *Entry = new ConstantDataArray(Ty, Slot.getKeyData());
2240
2241 assert(isa<VectorType>(Ty));
2242 return *Entry = new ConstantDataVector(Ty, Slot.getKeyData());
2243}
2244
2245void ConstantDataSequential::destroyConstant() {
Chris Lattner3756b912012-01-23 22:57:10 +00002246 // Remove the constant from the StringMap.
2247 StringMap<ConstantDataSequential*> &CDSConstants =
2248 getType()->getContext().pImpl->CDSConstants;
Galina Kistanovafc259902012-07-13 01:25:27 +00002249
Chris Lattner3756b912012-01-23 22:57:10 +00002250 StringMap<ConstantDataSequential*>::iterator Slot =
Chris Lattner5d4497b2012-01-24 09:31:43 +00002251 CDSConstants.find(getRawDataValues());
Chris Lattner3756b912012-01-23 22:57:10 +00002252
2253 assert(Slot != CDSConstants.end() && "CDS not found in uniquing table");
2254
2255 ConstantDataSequential **Entry = &Slot->getValue();
2256
2257 // Remove the entry from the hash table.
2258 if ((*Entry)->Next == 0) {
2259 // If there is only one value in the bucket (common case) it must be this
2260 // entry, and removing the entry should remove the bucket completely.
2261 assert((*Entry) == this && "Hash mismatch in ConstantDataSequential");
2262 getContext().pImpl->CDSConstants.erase(Slot);
2263 } else {
2264 // Otherwise, there are multiple entries linked off the bucket, unlink the
2265 // node we care about but keep the bucket around.
2266 for (ConstantDataSequential *Node = *Entry; ;
2267 Entry = &Node->Next, Node = *Entry) {
2268 assert(Node && "Didn't find entry in its uniquing hash table!");
2269 // If we found our entry, unlink it from the list and we're done.
2270 if (Node == this) {
2271 *Entry = Node->Next;
2272 break;
2273 }
2274 }
2275 }
Galina Kistanovafc259902012-07-13 01:25:27 +00002276
Chris Lattner3756b912012-01-23 22:57:10 +00002277 // If we were part of a list, make sure that we don't delete the list that is
2278 // still owned by the uniquing map.
2279 Next = 0;
Galina Kistanovafc259902012-07-13 01:25:27 +00002280
Chris Lattner3756b912012-01-23 22:57:10 +00002281 // Finally, actually delete it.
2282 destroyConstantImpl();
2283}
2284
2285/// get() constructors - Return a constant with array type with an element
2286/// count and element type matching the ArrayRef passed in. Note that this
2287/// can return a ConstantAggregateZero object.
Chris Lattner20683932012-01-24 14:04:40 +00002288Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint8_t> Elts) {
Chris Lattner3756b912012-01-23 22:57:10 +00002289 Type *Ty = ArrayType::get(Type::getInt8Ty(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002290 const char *Data = reinterpret_cast<const char *>(Elts.data());
2291 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*1), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002292}
Chris Lattner20683932012-01-24 14:04:40 +00002293Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint16_t> Elts){
Chris Lattner3756b912012-01-23 22:57:10 +00002294 Type *Ty = ArrayType::get(Type::getInt16Ty(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002295 const char *Data = reinterpret_cast<const char *>(Elts.data());
2296 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*2), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002297}
Chris Lattner20683932012-01-24 14:04:40 +00002298Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint32_t> Elts){
Chris Lattner3756b912012-01-23 22:57:10 +00002299 Type *Ty = ArrayType::get(Type::getInt32Ty(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002300 const char *Data = reinterpret_cast<const char *>(Elts.data());
2301 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002302}
Chris Lattner20683932012-01-24 14:04:40 +00002303Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint64_t> Elts){
Chris Lattner3756b912012-01-23 22:57:10 +00002304 Type *Ty = ArrayType::get(Type::getInt64Ty(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002305 const char *Data = reinterpret_cast<const char *>(Elts.data());
2306 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*8), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002307}
Chris Lattner20683932012-01-24 14:04:40 +00002308Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<float> Elts) {
Chris Lattner3756b912012-01-23 22:57:10 +00002309 Type *Ty = ArrayType::get(Type::getFloatTy(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002310 const char *Data = reinterpret_cast<const char *>(Elts.data());
2311 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002312}
Chris Lattner20683932012-01-24 14:04:40 +00002313Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<double> Elts) {
Chris Lattner3756b912012-01-23 22:57:10 +00002314 Type *Ty = ArrayType::get(Type::getDoubleTy(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002315 const char *Data = reinterpret_cast<const char *>(Elts.data());
2316 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*8), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002317}
2318
Chris Lattner20683932012-01-24 14:04:40 +00002319/// getString - This method constructs a CDS and initializes it with a text
2320/// string. The default behavior (AddNull==true) causes a null terminator to
2321/// be placed at the end of the array (increasing the length of the string by
2322/// one more than the StringRef would normally indicate. Pass AddNull=false
2323/// to disable this behavior.
2324Constant *ConstantDataArray::getString(LLVMContext &Context,
2325 StringRef Str, bool AddNull) {
Galina Kistanovafc259902012-07-13 01:25:27 +00002326 if (!AddNull) {
2327 const uint8_t *Data = reinterpret_cast<const uint8_t *>(Str.data());
2328 return get(Context, ArrayRef<uint8_t>(const_cast<uint8_t *>(Data),
2329 Str.size()));
2330 }
2331
Chris Lattner20683932012-01-24 14:04:40 +00002332 SmallVector<uint8_t, 64> ElementVals;
2333 ElementVals.append(Str.begin(), Str.end());
2334 ElementVals.push_back(0);
2335 return get(Context, ElementVals);
2336}
Chris Lattner3756b912012-01-23 22:57:10 +00002337
2338/// get() constructors - Return a constant with vector type with an element
2339/// count and element type matching the ArrayRef passed in. Note that this
2340/// can return a ConstantAggregateZero object.
Chris Lattner20683932012-01-24 14:04:40 +00002341Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint8_t> Elts){
Chris Lattner3756b912012-01-23 22:57:10 +00002342 Type *Ty = VectorType::get(Type::getInt8Ty(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002343 const char *Data = reinterpret_cast<const char *>(Elts.data());
2344 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*1), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002345}
Chris Lattner20683932012-01-24 14:04:40 +00002346Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint16_t> Elts){
Chris Lattner3756b912012-01-23 22:57:10 +00002347 Type *Ty = VectorType::get(Type::getInt16Ty(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002348 const char *Data = reinterpret_cast<const char *>(Elts.data());
2349 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*2), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002350}
Chris Lattner20683932012-01-24 14:04:40 +00002351Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint32_t> Elts){
Chris Lattner3756b912012-01-23 22:57:10 +00002352 Type *Ty = VectorType::get(Type::getInt32Ty(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002353 const char *Data = reinterpret_cast<const char *>(Elts.data());
2354 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002355}
Chris Lattner20683932012-01-24 14:04:40 +00002356Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint64_t> Elts){
Chris Lattner3756b912012-01-23 22:57:10 +00002357 Type *Ty = VectorType::get(Type::getInt64Ty(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002358 const char *Data = reinterpret_cast<const char *>(Elts.data());
2359 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*8), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002360}
Chris Lattner20683932012-01-24 14:04:40 +00002361Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<float> Elts) {
Chris Lattner3756b912012-01-23 22:57:10 +00002362 Type *Ty = VectorType::get(Type::getFloatTy(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002363 const char *Data = reinterpret_cast<const char *>(Elts.data());
2364 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002365}
Chris Lattner20683932012-01-24 14:04:40 +00002366Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<double> Elts) {
Chris Lattner3756b912012-01-23 22:57:10 +00002367 Type *Ty = VectorType::get(Type::getDoubleTy(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002368 const char *Data = reinterpret_cast<const char *>(Elts.data());
2369 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*8), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002370}
2371
Chris Lattnere9eed292012-01-25 05:19:54 +00002372Constant *ConstantDataVector::getSplat(unsigned NumElts, Constant *V) {
2373 assert(isElementTypeCompatible(V->getType()) &&
2374 "Element type not compatible with ConstantData");
2375 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
2376 if (CI->getType()->isIntegerTy(8)) {
2377 SmallVector<uint8_t, 16> Elts(NumElts, CI->getZExtValue());
2378 return get(V->getContext(), Elts);
2379 }
2380 if (CI->getType()->isIntegerTy(16)) {
2381 SmallVector<uint16_t, 16> Elts(NumElts, CI->getZExtValue());
2382 return get(V->getContext(), Elts);
2383 }
2384 if (CI->getType()->isIntegerTy(32)) {
2385 SmallVector<uint32_t, 16> Elts(NumElts, CI->getZExtValue());
2386 return get(V->getContext(), Elts);
2387 }
2388 assert(CI->getType()->isIntegerTy(64) && "Unsupported ConstantData type");
2389 SmallVector<uint64_t, 16> Elts(NumElts, CI->getZExtValue());
2390 return get(V->getContext(), Elts);
2391 }
2392
Chris Lattner978fe0c2012-01-30 06:21:21 +00002393 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
2394 if (CFP->getType()->isFloatTy()) {
2395 SmallVector<float, 16> Elts(NumElts, CFP->getValueAPF().convertToFloat());
2396 return get(V->getContext(), Elts);
2397 }
2398 if (CFP->getType()->isDoubleTy()) {
2399 SmallVector<double, 16> Elts(NumElts,
2400 CFP->getValueAPF().convertToDouble());
2401 return get(V->getContext(), Elts);
2402 }
Chris Lattnere9eed292012-01-25 05:19:54 +00002403 }
Chris Lattner978fe0c2012-01-30 06:21:21 +00002404 return ConstantVector::getSplat(NumElts, V);
Chris Lattnere9eed292012-01-25 05:19:54 +00002405}
2406
2407
Chris Lattnere4f3f102012-01-24 04:43:41 +00002408/// getElementAsInteger - If this is a sequential container of integers (of
2409/// any size), return the specified element in the low bits of a uint64_t.
2410uint64_t ConstantDataSequential::getElementAsInteger(unsigned Elt) const {
2411 assert(isa<IntegerType>(getElementType()) &&
2412 "Accessor can only be used when element is an integer");
2413 const char *EltPtr = getElementPointer(Elt);
Galina Kistanovafc259902012-07-13 01:25:27 +00002414
Chris Lattnere4f3f102012-01-24 04:43:41 +00002415 // The data is stored in host byte order, make sure to cast back to the right
2416 // type to load with the right endianness.
Chris Lattner8326bd82012-01-26 00:42:34 +00002417 switch (getElementType()->getIntegerBitWidth()) {
Craig Topperc514b542012-02-05 22:14:15 +00002418 default: llvm_unreachable("Invalid bitwidth for CDS");
Galina Kistanovafc259902012-07-13 01:25:27 +00002419 case 8:
2420 return *const_cast<uint8_t *>(reinterpret_cast<const uint8_t *>(EltPtr));
2421 case 16:
2422 return *const_cast<uint16_t *>(reinterpret_cast<const uint16_t *>(EltPtr));
2423 case 32:
2424 return *const_cast<uint32_t *>(reinterpret_cast<const uint32_t *>(EltPtr));
2425 case 64:
2426 return *const_cast<uint64_t *>(reinterpret_cast<const uint64_t *>(EltPtr));
Chris Lattnere4f3f102012-01-24 04:43:41 +00002427 }
2428}
2429
2430/// getElementAsAPFloat - If this is a sequential container of floating point
2431/// type, return the specified element as an APFloat.
2432APFloat ConstantDataSequential::getElementAsAPFloat(unsigned Elt) const {
2433 const char *EltPtr = getElementPointer(Elt);
2434
2435 switch (getElementType()->getTypeID()) {
Nick Lewyckyff509622012-01-25 03:20:12 +00002436 default:
Craig Topperc514b542012-02-05 22:14:15 +00002437 llvm_unreachable("Accessor can only be used when element is float/double!");
Galina Kistanovafc259902012-07-13 01:25:27 +00002438 case Type::FloatTyID: {
2439 const float *FloatPrt = reinterpret_cast<const float *>(EltPtr);
2440 return APFloat(*const_cast<float *>(FloatPrt));
2441 }
2442 case Type::DoubleTyID: {
2443 const double *DoublePtr = reinterpret_cast<const double *>(EltPtr);
2444 return APFloat(*const_cast<double *>(DoublePtr));
2445 }
Chris Lattnere4f3f102012-01-24 04:43:41 +00002446 }
2447}
2448
2449/// getElementAsFloat - If this is an sequential container of floats, return
2450/// the specified element as a float.
2451float ConstantDataSequential::getElementAsFloat(unsigned Elt) const {
2452 assert(getElementType()->isFloatTy() &&
2453 "Accessor can only be used when element is a 'float'");
Galina Kistanovafc259902012-07-13 01:25:27 +00002454 const float *EltPtr = reinterpret_cast<const float *>(getElementPointer(Elt));
2455 return *const_cast<float *>(EltPtr);
Chris Lattnere4f3f102012-01-24 04:43:41 +00002456}
2457
2458/// getElementAsDouble - If this is an sequential container of doubles, return
2459/// the specified element as a float.
2460double ConstantDataSequential::getElementAsDouble(unsigned Elt) const {
2461 assert(getElementType()->isDoubleTy() &&
2462 "Accessor can only be used when element is a 'float'");
Galina Kistanovafc259902012-07-13 01:25:27 +00002463 const double *EltPtr =
2464 reinterpret_cast<const double *>(getElementPointer(Elt));
2465 return *const_cast<double *>(EltPtr);
Chris Lattnere4f3f102012-01-24 04:43:41 +00002466}
2467
2468/// getElementAsConstant - Return a Constant for a specified index's element.
2469/// Note that this has to compute a new constant to return, so it isn't as
2470/// efficient as getElementAsInteger/Float/Double.
2471Constant *ConstantDataSequential::getElementAsConstant(unsigned Elt) const {
2472 if (getElementType()->isFloatTy() || getElementType()->isDoubleTy())
2473 return ConstantFP::get(getContext(), getElementAsAPFloat(Elt));
Galina Kistanovafc259902012-07-13 01:25:27 +00002474
Chris Lattnere4f3f102012-01-24 04:43:41 +00002475 return ConstantInt::get(getElementType(), getElementAsInteger(Elt));
2476}
2477
Chris Lattner5dd4d872012-01-24 09:01:07 +00002478/// isString - This method returns true if this is an array of i8.
2479bool ConstantDataSequential::isString() const {
2480 return isa<ArrayType>(getType()) && getElementType()->isIntegerTy(8);
2481}
Chris Lattner3756b912012-01-23 22:57:10 +00002482
Chris Lattner5dd4d872012-01-24 09:01:07 +00002483/// isCString - This method returns true if the array "isString", ends with a
2484/// nul byte, and does not contains any other nul bytes.
2485bool ConstantDataSequential::isCString() const {
2486 if (!isString())
2487 return false;
Galina Kistanovafc259902012-07-13 01:25:27 +00002488
Chris Lattner5dd4d872012-01-24 09:01:07 +00002489 StringRef Str = getAsString();
Galina Kistanovafc259902012-07-13 01:25:27 +00002490
Chris Lattner5dd4d872012-01-24 09:01:07 +00002491 // The last value must be nul.
2492 if (Str.back() != 0) return false;
Galina Kistanovafc259902012-07-13 01:25:27 +00002493
Chris Lattner5dd4d872012-01-24 09:01:07 +00002494 // Other elements must be non-nul.
2495 return Str.drop_back().find(0) == StringRef::npos;
2496}
Chris Lattner3756b912012-01-23 22:57:10 +00002497
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002498/// getSplatValue - If this is a splat constant, meaning that all of the
2499/// elements have the same value, return that value. Otherwise return NULL.
2500Constant *ConstantDataVector::getSplatValue() const {
2501 const char *Base = getRawDataValues().data();
Galina Kistanovafc259902012-07-13 01:25:27 +00002502
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002503 // Compare elements 1+ to the 0'th element.
2504 unsigned EltSize = getElementByteSize();
2505 for (unsigned i = 1, e = getNumElements(); i != e; ++i)
2506 if (memcmp(Base, Base+i*EltSize, EltSize))
2507 return 0;
Galina Kistanovafc259902012-07-13 01:25:27 +00002508
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002509 // If they're all the same, return the 0th one as a representative.
2510 return getElementAsConstant(0);
2511}
Chris Lattnera3b94ba2010-03-30 20:48:48 +00002512
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002513//===----------------------------------------------------------------------===//
2514// replaceUsesOfWithOnConstant implementations
2515
Chris Lattner913849b2007-08-21 00:55:23 +00002516/// replaceUsesOfWithOnConstant - Update this constant array to change uses of
2517/// 'From' to be uses of 'To'. This must update the uniquing data structures
2518/// etc.
2519///
2520/// Note that we intentionally replace all uses of From with To here. Consider
2521/// a large array that uses 'From' 1000 times. By handling this case all here,
2522/// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
2523/// single invocation handles all 1000 uses. Handling them one at a time would
2524/// work, but would be really slow because it would have to unique each updated
2525/// array instance.
Chris Lattner31b132c2009-10-28 00:01:44 +00002526///
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002527void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002528 Use *U) {
Owen Andersonc2c79322009-07-28 18:32:17 +00002529 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2530 Constant *ToC = cast<Constant>(To);
2531
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002532 LLVMContextImpl *pImpl = getType()->getContext().pImpl;
Owen Andersonc2c79322009-07-28 18:32:17 +00002533
Talin46e9b442012-02-05 20:54:10 +00002534 SmallVector<Constant*, 8> Values;
2535 LLVMContextImpl::ArrayConstantsTy::LookupKey Lookup;
2536 Lookup.first = cast<ArrayType>(getType());
Owen Andersonc2c79322009-07-28 18:32:17 +00002537 Values.reserve(getNumOperands()); // Build replacement array.
2538
Galina Kistanovafc259902012-07-13 01:25:27 +00002539 // Fill values with the modified operands of the constant array. Also,
Owen Andersonc2c79322009-07-28 18:32:17 +00002540 // compute whether this turns into an all-zeros array.
Owen Andersonc2c79322009-07-28 18:32:17 +00002541 unsigned NumUpdated = 0;
Galina Kistanovafc259902012-07-13 01:25:27 +00002542
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002543 // Keep track of whether all the values in the array are "ToC".
2544 bool AllSame = true;
2545 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2546 Constant *Val = cast<Constant>(O->get());
2547 if (Val == From) {
2548 Val = ToC;
2549 ++NumUpdated;
Owen Andersonc2c79322009-07-28 18:32:17 +00002550 }
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002551 Values.push_back(Val);
Talin46e9b442012-02-05 20:54:10 +00002552 AllSame &= Val == ToC;
Owen Andersonc2c79322009-07-28 18:32:17 +00002553 }
Galina Kistanovafc259902012-07-13 01:25:27 +00002554
Owen Andersonc2c79322009-07-28 18:32:17 +00002555 Constant *Replacement = 0;
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002556 if (AllSame && ToC->isNullValue()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002557 Replacement = ConstantAggregateZero::get(getType());
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002558 } else if (AllSame && isa<UndefValue>(ToC)) {
2559 Replacement = UndefValue::get(getType());
Owen Andersonc2c79322009-07-28 18:32:17 +00002560 } else {
2561 // Check to see if we have this array type already.
Talin46e9b442012-02-05 20:54:10 +00002562 Lookup.second = makeArrayRef(Values);
Owen Andersonc2c79322009-07-28 18:32:17 +00002563 LLVMContextImpl::ArrayConstantsTy::MapTy::iterator I =
Talin46e9b442012-02-05 20:54:10 +00002564 pImpl->ArrayConstants.find(Lookup);
Galina Kistanovafc259902012-07-13 01:25:27 +00002565
Talin46e9b442012-02-05 20:54:10 +00002566 if (I != pImpl->ArrayConstants.map_end()) {
2567 Replacement = I->first;
Owen Andersonc2c79322009-07-28 18:32:17 +00002568 } else {
2569 // Okay, the new shape doesn't exist in the system yet. Instead of
2570 // creating a new constant array, inserting it, replaceallusesof'ing the
2571 // old with the new, then deleting the old... just update the current one
2572 // in place!
Talin46e9b442012-02-05 20:54:10 +00002573 pImpl->ArrayConstants.remove(this);
Galina Kistanovafc259902012-07-13 01:25:27 +00002574
Owen Andersonc2c79322009-07-28 18:32:17 +00002575 // Update to the new value. Optimize for the case when we have a single
2576 // operand that we're changing, but handle bulk updates efficiently.
2577 if (NumUpdated == 1) {
2578 unsigned OperandToUpdate = U - OperandList;
2579 assert(getOperand(OperandToUpdate) == From &&
2580 "ReplaceAllUsesWith broken!");
2581 setOperand(OperandToUpdate, ToC);
2582 } else {
2583 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2584 if (getOperand(i) == From)
2585 setOperand(i, ToC);
2586 }
Talin46e9b442012-02-05 20:54:10 +00002587 pImpl->ArrayConstants.insert(this);
Owen Andersonc2c79322009-07-28 18:32:17 +00002588 return;
2589 }
2590 }
Galina Kistanovafc259902012-07-13 01:25:27 +00002591
Chris Lattnerb64419a2005-10-03 22:51:37 +00002592 // Otherwise, I do need to replace this with an existing value.
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002593 assert(Replacement != this && "I didn't contain From!");
Galina Kistanovafc259902012-07-13 01:25:27 +00002594
Chris Lattner7a1450d2005-10-04 18:13:04 +00002595 // Everyone using this now uses the replacement.
Chris Lattneraf1783f2011-07-15 06:18:52 +00002596 replaceAllUsesWith(Replacement);
Galina Kistanovafc259902012-07-13 01:25:27 +00002597
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002598 // Delete the old constant!
2599 destroyConstant();
2600}
2601
2602void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002603 Use *U) {
Owen Anderson45308b52009-07-27 22:29:26 +00002604 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2605 Constant *ToC = cast<Constant>(To);
2606
2607 unsigned OperandToUpdate = U-OperandList;
2608 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2609
Talin46e9b442012-02-05 20:54:10 +00002610 SmallVector<Constant*, 8> Values;
2611 LLVMContextImpl::StructConstantsTy::LookupKey Lookup;
2612 Lookup.first = cast<StructType>(getType());
Owen Anderson45308b52009-07-27 22:29:26 +00002613 Values.reserve(getNumOperands()); // Build replacement struct.
Galina Kistanovafc259902012-07-13 01:25:27 +00002614
2615 // Fill values with the modified operands of the constant struct. Also,
Owen Anderson45308b52009-07-27 22:29:26 +00002616 // compute whether this turns into an all-zeros struct.
2617 bool isAllZeros = false;
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002618 bool isAllUndef = false;
2619 if (ToC->isNullValue()) {
Owen Anderson45308b52009-07-27 22:29:26 +00002620 isAllZeros = true;
2621 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2622 Constant *Val = cast<Constant>(O->get());
2623 Values.push_back(Val);
2624 if (isAllZeros) isAllZeros = Val->isNullValue();
2625 }
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002626 } else if (isa<UndefValue>(ToC)) {
2627 isAllUndef = true;
2628 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2629 Constant *Val = cast<Constant>(O->get());
2630 Values.push_back(Val);
2631 if (isAllUndef) isAllUndef = isa<UndefValue>(Val);
2632 }
2633 } else {
2634 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O)
2635 Values.push_back(cast<Constant>(O->get()));
Owen Anderson45308b52009-07-27 22:29:26 +00002636 }
2637 Values[OperandToUpdate] = ToC;
Galina Kistanovafc259902012-07-13 01:25:27 +00002638
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002639 LLVMContextImpl *pImpl = getContext().pImpl;
Galina Kistanovafc259902012-07-13 01:25:27 +00002640
Owen Anderson45308b52009-07-27 22:29:26 +00002641 Constant *Replacement = 0;
2642 if (isAllZeros) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002643 Replacement = ConstantAggregateZero::get(getType());
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002644 } else if (isAllUndef) {
2645 Replacement = UndefValue::get(getType());
Owen Anderson45308b52009-07-27 22:29:26 +00002646 } else {
Chris Lattner718da702010-07-17 06:13:52 +00002647 // Check to see if we have this struct type already.
Talin46e9b442012-02-05 20:54:10 +00002648 Lookup.second = makeArrayRef(Values);
Owen Anderson45308b52009-07-27 22:29:26 +00002649 LLVMContextImpl::StructConstantsTy::MapTy::iterator I =
Talin46e9b442012-02-05 20:54:10 +00002650 pImpl->StructConstants.find(Lookup);
Galina Kistanovafc259902012-07-13 01:25:27 +00002651
Talin46e9b442012-02-05 20:54:10 +00002652 if (I != pImpl->StructConstants.map_end()) {
2653 Replacement = I->first;
Owen Anderson45308b52009-07-27 22:29:26 +00002654 } else {
2655 // Okay, the new shape doesn't exist in the system yet. Instead of
2656 // creating a new constant struct, inserting it, replaceallusesof'ing the
2657 // old with the new, then deleting the old... just update the current one
2658 // in place!
Talin46e9b442012-02-05 20:54:10 +00002659 pImpl->StructConstants.remove(this);
Galina Kistanovafc259902012-07-13 01:25:27 +00002660
Owen Anderson45308b52009-07-27 22:29:26 +00002661 // Update to the new value.
2662 setOperand(OperandToUpdate, ToC);
Talin46e9b442012-02-05 20:54:10 +00002663 pImpl->StructConstants.insert(this);
Owen Anderson45308b52009-07-27 22:29:26 +00002664 return;
2665 }
2666 }
Galina Kistanovafc259902012-07-13 01:25:27 +00002667
Owen Anderson45308b52009-07-27 22:29:26 +00002668 assert(Replacement != this && "I didn't contain From!");
Galina Kistanovafc259902012-07-13 01:25:27 +00002669
Chris Lattner7a1450d2005-10-04 18:13:04 +00002670 // Everyone using this now uses the replacement.
Chris Lattneraf1783f2011-07-15 06:18:52 +00002671 replaceAllUsesWith(Replacement);
Galina Kistanovafc259902012-07-13 01:25:27 +00002672
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002673 // Delete the old constant!
2674 destroyConstant();
2675}
2676
Reid Spencerd84d35b2007-02-15 02:26:10 +00002677void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002678 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002679 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
Galina Kistanovafc259902012-07-13 01:25:27 +00002680
Chris Lattnera474bb22012-01-26 20:40:56 +00002681 SmallVector<Constant*, 8> Values;
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002682 Values.reserve(getNumOperands()); // Build replacement array...
2683 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2684 Constant *Val = getOperand(i);
2685 if (Val == From) Val = cast<Constant>(To);
2686 Values.push_back(Val);
2687 }
Galina Kistanovafc259902012-07-13 01:25:27 +00002688
Jay Foadb8a8bed32011-06-22 09:10:19 +00002689 Constant *Replacement = get(Values);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002690 assert(Replacement != this && "I didn't contain From!");
Galina Kistanovafc259902012-07-13 01:25:27 +00002691
Chris Lattner7a1450d2005-10-04 18:13:04 +00002692 // Everyone using this now uses the replacement.
Chris Lattneraf1783f2011-07-15 06:18:52 +00002693 replaceAllUsesWith(Replacement);
Galina Kistanovafc259902012-07-13 01:25:27 +00002694
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002695 // Delete the old constant!
2696 destroyConstant();
2697}
2698
2699void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002700 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002701 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2702 Constant *To = cast<Constant>(ToV);
Galina Kistanovafc259902012-07-13 01:25:27 +00002703
Chris Lattner37e38352012-01-26 20:37:11 +00002704 SmallVector<Constant*, 8> NewOps;
2705 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2706 Constant *Op = getOperand(i);
2707 NewOps.push_back(Op == From ? To : Op);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002708 }
Galina Kistanovafc259902012-07-13 01:25:27 +00002709
Chris Lattner37e38352012-01-26 20:37:11 +00002710 Constant *Replacement = getWithOperands(NewOps);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002711 assert(Replacement != this && "I didn't contain From!");
Galina Kistanovafc259902012-07-13 01:25:27 +00002712
Chris Lattner7a1450d2005-10-04 18:13:04 +00002713 // Everyone using this now uses the replacement.
Chris Lattneraf1783f2011-07-15 06:18:52 +00002714 replaceAllUsesWith(Replacement);
Galina Kistanovafc259902012-07-13 01:25:27 +00002715
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002716 // Delete the old constant!
2717 destroyConstant();
Matthijs Kooijmanba5d7ef2008-07-03 07:46:41 +00002718}
James Molloyce545682012-11-17 17:56:30 +00002719
2720Instruction *ConstantExpr::getAsInstruction() {
2721 SmallVector<Value*,4> ValueOperands;
2722 for (op_iterator I = op_begin(), E = op_end(); I != E; ++I)
2723 ValueOperands.push_back(cast<Value>(I));
2724
2725 ArrayRef<Value*> Ops(ValueOperands);
2726
2727 switch (getOpcode()) {
2728 case Instruction::Trunc:
2729 case Instruction::ZExt:
2730 case Instruction::SExt:
2731 case Instruction::FPTrunc:
2732 case Instruction::FPExt:
2733 case Instruction::UIToFP:
2734 case Instruction::SIToFP:
2735 case Instruction::FPToUI:
2736 case Instruction::FPToSI:
2737 case Instruction::PtrToInt:
2738 case Instruction::IntToPtr:
2739 case Instruction::BitCast:
2740 return CastInst::Create((Instruction::CastOps)getOpcode(),
2741 Ops[0], getType());
2742 case Instruction::Select:
2743 return SelectInst::Create(Ops[0], Ops[1], Ops[2]);
2744 case Instruction::InsertElement:
2745 return InsertElementInst::Create(Ops[0], Ops[1], Ops[2]);
2746 case Instruction::ExtractElement:
2747 return ExtractElementInst::Create(Ops[0], Ops[1]);
2748 case Instruction::InsertValue:
2749 return InsertValueInst::Create(Ops[0], Ops[1], getIndices());
2750 case Instruction::ExtractValue:
2751 return ExtractValueInst::Create(Ops[0], getIndices());
2752 case Instruction::ShuffleVector:
2753 return new ShuffleVectorInst(Ops[0], Ops[1], Ops[2]);
2754
2755 case Instruction::GetElementPtr:
2756 if (cast<GEPOperator>(this)->isInBounds())
2757 return GetElementPtrInst::CreateInBounds(Ops[0], Ops.slice(1));
2758 else
2759 return GetElementPtrInst::Create(Ops[0], Ops.slice(1));
2760
2761 case Instruction::ICmp:
2762 case Instruction::FCmp:
2763 return CmpInst::Create((Instruction::OtherOps)getOpcode(),
2764 getPredicate(), Ops[0], Ops[1]);
2765
2766 default:
2767 assert(getNumOperands() == 2 && "Must be binary operator?");
2768 BinaryOperator *BO =
2769 BinaryOperator::Create((Instruction::BinaryOps)getOpcode(),
2770 Ops[0], Ops[1]);
2771 if (isa<OverflowingBinaryOperator>(BO)) {
2772 BO->setHasNoUnsignedWrap(SubclassOptionalData &
2773 OverflowingBinaryOperator::NoUnsignedWrap);
2774 BO->setHasNoSignedWrap(SubclassOptionalData &
2775 OverflowingBinaryOperator::NoSignedWrap);
2776 }
2777 if (isa<PossiblyExactOperator>(BO))
2778 BO->setIsExact(SubclassOptionalData & PossiblyExactOperator::IsExact);
2779 return BO;
2780 }
2781}