blob: e984aaca33bfff20ecb33b5807e02f69a2c0c1b2 [file] [log] [blame]
Chris Lattner9bc02a42003-05-13 21:37:02 +00001//===-- Constants.cpp - Implement Constant nodes --------------------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner00950542001-06-06 20:29:01 +00009//
Chris Lattnereb59ca92011-02-07 20:03:14 +000010// This file implements the Constant* classes.
Chris Lattner00950542001-06-06 20:29:01 +000011//
12//===----------------------------------------------------------------------===//
13
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000014#include "llvm/IR/Constants.h"
Chris Lattner92f6fea2007-02-27 03:05:06 +000015#include "ConstantFold.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000016#include "LLVMContextImpl.h"
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 Carruth0b8c9a82013-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 Lattnera4f0b3a2006-08-27 12:54:02 +000028#include "llvm/Support/Compiler.h"
Bill Wendling2e3def12006-11-17 08:03:48 +000029#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000030#include "llvm/Support/ErrorHandling.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000031#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner8a94bf12006-09-28 00:35:06 +000032#include "llvm/Support/ManagedStatic.h"
Bill Wendling2e3def12006-11-17 08:03:48 +000033#include "llvm/Support/MathExtras.h"
Chris Lattner37f077a2009-08-23 04:02:03 +000034#include "llvm/Support/raw_ostream.h"
Chris Lattner00950542001-06-06 20:29:01 +000035#include <algorithm>
Talin41ee4e52011-02-28 23:53:27 +000036#include <cstdarg>
Chris Lattner31f84992003-11-21 20:23:48 +000037using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000038
Chris Lattner00950542001-06-06 20:29:01 +000039//===----------------------------------------------------------------------===//
Chris Lattnere9bb2df2001-12-03 22:26:30 +000040// Constant Class
Chris Lattner00950542001-06-06 20:29:01 +000041//===----------------------------------------------------------------------===//
42
David Blaikie2d24e2a2011-12-20 02:50:00 +000043void Constant::anchor() { }
44
Chris Lattnerb4473872011-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 Kistanovaa46517e2012-07-13 01:25:27 +000049
Chris Lattnerb4473872011-07-15 05:58:04 +000050 // Otherwise, just use +0.0.
51 return isNullValue();
52}
53
Shuxin Yangc3d6de22013-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 Yang935e35d2013-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 Lattner032c6eb2011-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 Kistanovaa46517e2012-07-13 01:25:27 +000069
Chris Lattner032c6eb2011-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 Rotem4c7c0f22011-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 Kramerb518cae2011-11-14 19:12:20 +000087 // Check for constant vectors which are splats of -1 values.
Nadav Rotem4c7c0f22011-08-24 20:18:38 +000088 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
Benjamin Kramerb518cae2011-11-14 19:12:20 +000089 if (Constant *Splat = CV->getSplatValue())
90 return Splat->isAllOnesValue();
Nadav Rotem4c7c0f22011-08-24 20:18:38 +000091
Chris Lattnere150e2d2012-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 Rotem4c7c0f22011-08-24 20:18:38 +000097 return false;
98}
Benjamin Kramerb518cae2011-11-14 19:12:20 +000099
Owen Andersona7235ea2009-07-31 20:28:14 +0000100// Constructor to create a '0' constant of arbitrary type...
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000101Constant *Constant::getNullValue(Type *Ty) {
Owen Andersona7235ea2009-07-31 20:28:14 +0000102 switch (Ty->getTypeID()) {
103 case Type::IntegerTyID:
104 return ConstantInt::get(Ty, 0);
Dan Gohmance163392011-12-17 00:04:22 +0000105 case Type::HalfTyID:
106 return ConstantFP::get(Ty->getContext(),
107 APFloat::getZero(APFloat::IEEEhalf));
Owen Andersona7235ea2009-07-31 20:28:14 +0000108 case Type::FloatTyID:
Benjamin Kramer98383962010-12-04 14:22:24 +0000109 return ConstantFP::get(Ty->getContext(),
110 APFloat::getZero(APFloat::IEEEsingle));
Owen Andersona7235ea2009-07-31 20:28:14 +0000111 case Type::DoubleTyID:
Benjamin Kramer98383962010-12-04 14:22:24 +0000112 return ConstantFP::get(Ty->getContext(),
113 APFloat::getZero(APFloat::IEEEdouble));
Owen Andersona7235ea2009-07-31 20:28:14 +0000114 case Type::X86_FP80TyID:
Benjamin Kramer98383962010-12-04 14:22:24 +0000115 return ConstantFP::get(Ty->getContext(),
116 APFloat::getZero(APFloat::x87DoubleExtended));
Owen Andersona7235ea2009-07-31 20:28:14 +0000117 case Type::FP128TyID:
118 return ConstantFP::get(Ty->getContext(),
Benjamin Kramer98383962010-12-04 14:22:24 +0000119 APFloat::getZero(APFloat::IEEEquad));
Owen Andersona7235ea2009-07-31 20:28:14 +0000120 case Type::PPC_FP128TyID:
Benjamin Kramer98383962010-12-04 14:22:24 +0000121 return ConstantFP::get(Ty->getContext(),
Benjamin Kramer299ee182010-12-04 14:43:08 +0000122 APFloat(APInt::getNullValue(128)));
Owen Andersona7235ea2009-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 Topper50bee422012-02-05 22:14:15 +0000131 llvm_unreachable("Cannot create a null constant of that type!");
Owen Andersona7235ea2009-07-31 20:28:14 +0000132 }
133}
134
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000135Constant *Constant::getIntegerValue(Type *Ty, const APInt &V) {
136 Type *ScalarTy = Ty->getScalarType();
Dan Gohman43ee5f72009-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 Lattnerdb125cf2011-07-18 04:54:35 +0000142 if (PointerType *PTy = dyn_cast<PointerType>(ScalarTy))
Dan Gohman43ee5f72009-08-03 22:07:33 +0000143 C = ConstantExpr::getIntToPtr(C, PTy);
144
145 // Broadcast a scalar to a vector, if necessary.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000146 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattner3c2c9542012-01-25 05:19:54 +0000147 C = ConstantVector::getSplat(VTy->getNumElements(), C);
Dan Gohman43ee5f72009-08-03 22:07:33 +0000148
149 return C;
150}
151
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000152Constant *Constant::getAllOnesValue(Type *Ty) {
153 if (IntegerType *ITy = dyn_cast<IntegerType>(Ty))
Owen Andersona7235ea2009-07-31 20:28:14 +0000154 return ConstantInt::get(Ty->getContext(),
155 APInt::getAllOnesValue(ITy->getBitWidth()));
Nadav Rotem093399c2011-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 Lattnerdb125cf2011-07-18 04:54:35 +0000163 VectorType *VTy = cast<VectorType>(Ty);
Chris Lattner3c2c9542012-01-25 05:19:54 +0000164 return ConstantVector::getSplat(VTy->getNumElements(),
165 getAllOnesValue(VTy->getElementType()));
Owen Andersona7235ea2009-07-31 20:28:14 +0000166}
167
Chris Lattner3d5ed222012-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 Kistanovaa46517e2012-07-13 01:25:27 +0000175
Chris Lattner3d5ed222012-01-25 06:16:32 +0000176 if (const ConstantArray *CA = dyn_cast<ConstantArray>(this))
177 return Elt < CA->getNumOperands() ? CA->getOperand(Elt) : 0;
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000178
Chris Lattner3d5ed222012-01-25 06:16:32 +0000179 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
180 return Elt < CV->getNumOperands() ? CV->getOperand(Elt) : 0;
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000181
Chris Lattner3d5ed222012-01-25 06:16:32 +0000182 if (const ConstantAggregateZero *CAZ =dyn_cast<ConstantAggregateZero>(this))
183 return CAZ->getElementValue(Elt);
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000184
Chris Lattner3d5ed222012-01-25 06:16:32 +0000185 if (const UndefValue *UV = dyn_cast<UndefValue>(this))
186 return UV->getElementValue(Elt);
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000187
Chris Lattner230cdab2012-01-26 00:42:34 +0000188 if (const ConstantDataSequential *CDS =dyn_cast<ConstantDataSequential>(this))
Chris Lattner18c7f802012-02-05 02:29:43 +0000189 return Elt < CDS->getNumElements() ? CDS->getElementAsConstant(Elt) : 0;
Chris Lattner3d5ed222012-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 Lattnere9bb2df2001-12-03 22:26:30 +0000201void Constant::destroyConstantImpl() {
202 // When a Constant is destroyed, there may be lingering
Chris Lattnerf5ec48d2001-10-13 06:57:33 +0000203 // references to the constant by other constants in the constant pool. These
Misha Brukmanef6a6a62003-08-21 22:14:26 +0000204 // constants are implicitly dependent on the module that is being deleted,
Chris Lattnerf5ec48d2001-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 Lattnere9bb2df2001-12-03 22:26:30 +0000207 // Constants) that they are, in fact, invalid now and should be deleted.
Chris Lattnerf5ec48d2001-10-13 06:57:33 +0000208 //
209 while (!use_empty()) {
210 Value *V = use_back();
211#ifndef NDEBUG // Only in -g mode...
Chris Lattner37f077a2009-08-23 04:02:03 +0000212 if (!isa<Constant>(V)) {
David Greened2e63b72010-01-05 01:29:19 +0000213 dbgs() << "While deleting: " << *this
Chris Lattner37f077a2009-08-23 04:02:03 +0000214 << "\n\nUse still stuck around after Def is destroyed: "
215 << *V << "\n\n";
216 }
Chris Lattnerf5ec48d2001-10-13 06:57:33 +0000217#endif
Vikram S. Adve345e0cf2002-07-14 23:13:17 +0000218 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
Chris Lattner230cdab2012-01-26 00:42:34 +0000219 cast<Constant>(V)->destroyConstant();
Chris Lattnerf5ec48d2001-10-13 06:57:33 +0000220
221 // The constant should remove itself from our use list...
Vikram S. Adve345e0cf2002-07-14 23:13:17 +0000222 assert((use_empty() || use_back() != V) && "Constant not removed!");
Chris Lattnerf5ec48d2001-10-13 06:57:33 +0000223 }
224
225 // Value has no outstanding references it is safe to delete it now...
226 delete this;
Chris Lattner1d87bcf2001-10-01 20:11:19 +0000227}
Chris Lattner00950542001-06-06 20:29:01 +0000228
Chris Lattner35b89fa2006-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 Kistanovaa46517e2012-07-13 01:25:27 +0000236
237 // ConstantExpr traps if any operands can trap.
Chris Lattner35b89fa2006-10-20 00:27:06 +0000238 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000239 if (CE->getOperand(i)->canTrap())
Chris Lattner35b89fa2006-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 Spencer1628cec2006-10-26 06:15:43 +0000246 case Instruction::UDiv:
247 case Instruction::SDiv:
248 case Instruction::FDiv:
Reid Spencer0a783f72006-11-02 01:53:59 +0000249 case Instruction::URem:
250 case Instruction::SRem:
251 case Instruction::FRem:
Chris Lattner35b89fa2006-10-20 00:27:06 +0000252 // Div and rem can trap if the RHS is not known to be non-zero.
Chris Lattner0eeb9132009-10-28 05:14:34 +0000253 if (!isa<ConstantInt>(CE->getOperand(1)) ||CE->getOperand(1)->isNullValue())
Chris Lattner35b89fa2006-10-20 00:27:06 +0000254 return true;
255 return false;
256 }
257}
258
Hans Wennborg18398582012-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 Wennborgfbeb9562012-11-16 10:33:25 +0000275 const Constant *D = dyn_cast<Constant>(C->getOperand(I));
276 if (!D)
277 continue;
Hans Wennborg18398582012-11-15 11:40:00 +0000278 if (Visited.insert(D))
279 WorkList.push_back(D);
280 }
281 }
282
283 return false;
284}
285
Chris Lattner4a7642e2009-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 Greif60ad7812010-03-25 23:06:16 +0000289 for (const_use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
Chris Lattner4a7642e2009-11-01 18:11:50 +0000290 const Constant *UC = dyn_cast<Constant>(*UI);
291 if (UC == 0 || isa<GlobalValue>(UC))
292 return true;
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000293
Chris Lattner4a7642e2009-11-01 18:11:50 +0000294 if (UC->isConstantUsed())
295 return true;
296 }
297 return false;
298}
299
300
Chris Lattner7cf12c72009-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 Lattner083a1e02009-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 Lattner7cf12c72009-07-22 00:05:44 +0000314///
Chandler Carruthc2c50cd2013-01-02 09:10:48 +0000315/// FIXME: This really should not be in IR.
Chris Lattner083a1e02009-07-24 03:27:21 +0000316Constant::PossibleRelocationsTy Constant::getRelocationInfo() const {
317 if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
Chris Lattner7cf12c72009-07-22 00:05:44 +0000318 if (GV->hasLocalLinkage() || GV->hasHiddenVisibility())
Chris Lattner083a1e02009-07-24 03:27:21 +0000319 return LocalRelocation; // Local to this file/library.
320 return GlobalRelocations; // Global reference.
Anton Korobeynikovab267a22009-03-29 17:13:18 +0000321 }
Chris Lattner7cf12c72009-07-22 00:05:44 +0000322
Chris Lattner5d81bef2009-10-28 04:12:16 +0000323 if (const BlockAddress *BA = dyn_cast<BlockAddress>(this))
324 return BA->getFunction()->getRelocationInfo();
325
Chris Lattner5099b312010-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 Kistanovaa46517e2012-07-13 01:25:27 +0000343
Chris Lattner083a1e02009-07-24 03:27:21 +0000344 PossibleRelocationsTy Result = NoRelocation;
Evan Chengafe15812007-03-08 00:59:12 +0000345 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
Chris Lattner0eeb9132009-10-28 05:14:34 +0000346 Result = std::max(Result,
347 cast<Constant>(getOperand(i))->getRelocationInfo());
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000348
Chris Lattner7cf12c72009-07-22 00:05:44 +0000349 return Result;
Evan Chengafe15812007-03-08 00:59:12 +0000350}
351
Chris Lattner13fb0db2011-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 Kistanovaa46517e2012-07-13 01:25:27 +0000357
Chris Lattner13fb0db2011-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 Kistanovaa46517e2012-07-13 01:25:27 +0000364
Chris Lattner13fb0db2011-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 Kistanovaa46517e2012-07-13 01:25:27 +0000384
Chris Lattner13fb0db2011-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 Kistanovaa46517e2012-07-13 01:25:27 +0000392
Chris Lattner13fb0db2011-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 Lattner86381442008-07-10 00:28:11 +0000405
Chris Lattner00950542001-06-06 20:29:01 +0000406//===----------------------------------------------------------------------===//
Chris Lattner6b6f6ba2007-02-20 06:39:57 +0000407// ConstantInt
Chris Lattner00950542001-06-06 20:29:01 +0000408//===----------------------------------------------------------------------===//
409
David Blaikie2d24e2a2011-12-20 02:50:00 +0000410void ConstantInt::anchor() { }
411
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000412ConstantInt::ConstantInt(IntegerType *Ty, const APInt& V)
Chris Lattnereb41bdd2007-02-20 05:55:46 +0000413 : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
Reid Spencer532d0ce2007-02-26 23:54:03 +0000414 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
Chris Lattner00950542001-06-06 20:29:01 +0000415}
416
Nick Lewyckyd01f50f2011-03-06 03:36:19 +0000417ConstantInt *ConstantInt::getTrue(LLVMContext &Context) {
Owen Anderson5defacc2009-07-31 17:39:07 +0000418 LLVMContextImpl *pImpl = Context.pImpl;
Benjamin Kramerf601d6d2010-11-20 18:43:35 +0000419 if (!pImpl->TheTrueVal)
420 pImpl->TheTrueVal = ConstantInt::get(Type::getInt1Ty(Context), 1);
421 return pImpl->TheTrueVal;
Owen Anderson5defacc2009-07-31 17:39:07 +0000422}
423
Nick Lewyckyd01f50f2011-03-06 03:36:19 +0000424ConstantInt *ConstantInt::getFalse(LLVMContext &Context) {
Owen Anderson5defacc2009-07-31 17:39:07 +0000425 LLVMContextImpl *pImpl = Context.pImpl;
Benjamin Kramerf601d6d2010-11-20 18:43:35 +0000426 if (!pImpl->TheFalseVal)
427 pImpl->TheFalseVal = ConstantInt::get(Type::getInt1Ty(Context), 0);
428 return pImpl->TheFalseVal;
Owen Anderson5defacc2009-07-31 17:39:07 +0000429}
430
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000431Constant *ConstantInt::getTrue(Type *Ty) {
432 VectorType *VTy = dyn_cast<VectorType>(Ty);
Nick Lewyckyd01f50f2011-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 Lattner3c2c9542012-01-25 05:19:54 +0000439 return ConstantVector::getSplat(VTy->getNumElements(),
440 ConstantInt::getTrue(Ty->getContext()));
Nick Lewyckyd01f50f2011-03-06 03:36:19 +0000441}
442
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000443Constant *ConstantInt::getFalse(Type *Ty) {
444 VectorType *VTy = dyn_cast<VectorType>(Ty);
Nick Lewyckyd01f50f2011-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 Lattner3c2c9542012-01-25 05:19:54 +0000451 return ConstantVector::getSplat(VTy->getNumElements(),
452 ConstantInt::getFalse(Ty->getContext()));
Nick Lewyckyd01f50f2011-03-06 03:36:19 +0000453}
454
Owen Anderson5defacc2009-07-31 17:39:07 +0000455
Owen Andersoneed707b2009-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 Lewyckyd01f50f2011-03-06 03:36:19 +0000461ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt &V) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000462 // Get the corresponding integer type for the bit width of the value.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000463 IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
Owen Andersoneed707b2009-07-24 23:12:02 +0000464 // get an existing value or the insertion position
465 DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
Owen Andersoneed707b2009-07-24 23:12:02 +0000466 ConstantInt *&Slot = Context.pImpl->IntConstants[Key];
Owen Anderson59d5aac2009-10-19 20:11:52 +0000467 if (!Slot) Slot = new ConstantInt(ITy, V);
468 return Slot;
Owen Andersoneed707b2009-07-24 23:12:02 +0000469}
470
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000471Constant *ConstantInt::get(Type *Ty, uint64_t V, bool isSigned) {
Nick Lewyckyd01f50f2011-03-06 03:36:19 +0000472 Constant *C = get(cast<IntegerType>(Ty->getScalarType()), V, isSigned);
Owen Andersoneed707b2009-07-24 23:12:02 +0000473
474 // For vectors, broadcast the value.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000475 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattner3c2c9542012-01-25 05:19:54 +0000476 return ConstantVector::getSplat(VTy->getNumElements(), C);
Owen Andersoneed707b2009-07-24 23:12:02 +0000477
478 return C;
479}
480
Chris Lattnera78fa8c2012-01-27 03:08:05 +0000481ConstantInt *ConstantInt::get(IntegerType *Ty, uint64_t V,
Owen Andersoneed707b2009-07-24 23:12:02 +0000482 bool isSigned) {
483 return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned));
484}
485
Chris Lattnera78fa8c2012-01-27 03:08:05 +0000486ConstantInt *ConstantInt::getSigned(IntegerType *Ty, int64_t V) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000487 return get(Ty, V, true);
488}
489
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000490Constant *ConstantInt::getSigned(Type *Ty, int64_t V) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000491 return get(Ty, V, true);
492}
493
Chris Lattnera78fa8c2012-01-27 03:08:05 +0000494Constant *ConstantInt::get(Type *Ty, const APInt& V) {
Owen Andersoneed707b2009-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 Lattnerdb125cf2011-07-18 04:54:35 +0000500 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattner3c2c9542012-01-25 05:19:54 +0000501 return ConstantVector::getSplat(VTy->getNumElements(), C);
Owen Andersoneed707b2009-07-24 23:12:02 +0000502
503 return C;
504}
505
Chris Lattnera78fa8c2012-01-27 03:08:05 +0000506ConstantInt *ConstantInt::get(IntegerType* Ty, StringRef Str,
Erick Tryzelaar0e81f662009-08-16 23:36:33 +0000507 uint8_t radix) {
508 return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
509}
510
Chris Lattner6b6f6ba2007-02-20 06:39:57 +0000511//===----------------------------------------------------------------------===//
Chris Lattner9b4ee0c2007-02-20 07:17:17 +0000512// ConstantFP
Chris Lattner6b6f6ba2007-02-20 06:39:57 +0000513//===----------------------------------------------------------------------===//
514
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000515static const fltSemantics *TypeToFloatSemantics(Type *Ty) {
Dan Gohmance163392011-12-17 00:04:22 +0000516 if (Ty->isHalfTy())
517 return &APFloat::IEEEhalf;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000518 if (Ty->isFloatTy())
Rafael Espindola87d1f472009-07-15 17:40:42 +0000519 return &APFloat::IEEEsingle;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000520 if (Ty->isDoubleTy())
Rafael Espindola87d1f472009-07-15 17:40:42 +0000521 return &APFloat::IEEEdouble;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000522 if (Ty->isX86_FP80Ty())
Rafael Espindola87d1f472009-07-15 17:40:42 +0000523 return &APFloat::x87DoubleExtended;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000524 else if (Ty->isFP128Ty())
Rafael Espindola87d1f472009-07-15 17:40:42 +0000525 return &APFloat::IEEEquad;
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000526
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000527 assert(Ty->isPPC_FP128Ty() && "Unknown FP format");
Rafael Espindola87d1f472009-07-15 17:40:42 +0000528 return &APFloat::PPCDoubleDouble;
529}
530
David Blaikie2d24e2a2011-12-20 02:50:00 +0000531void ConstantFP::anchor() { }
532
Owen Anderson6f83c9c2009-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 Lattnera78fa8c2012-01-27 03:08:05 +0000536Constant *ConstantFP::get(Type *Ty, double V) {
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000537 LLVMContext &Context = Ty->getContext();
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000538
Owen Anderson6f83c9c2009-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 Lattnerdb125cf2011-07-18 04:54:35 +0000546 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattner3c2c9542012-01-25 05:19:54 +0000547 return ConstantVector::getSplat(VTy->getNumElements(), C);
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000548
549 return C;
550}
551
Erick Tryzelaar0e81f662009-08-16 23:36:33 +0000552
Chris Lattnera78fa8c2012-01-27 03:08:05 +0000553Constant *ConstantFP::get(Type *Ty, StringRef Str) {
Erick Tryzelaar0e81f662009-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 Lattnerdb125cf2011-07-18 04:54:35 +0000560 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattner3c2c9542012-01-25 05:19:54 +0000561 return ConstantVector::getSplat(VTy->getNumElements(), C);
Erick Tryzelaar0e81f662009-08-16 23:36:33 +0000562
563 return C;
564}
565
566
Chris Lattner3c2c9542012-01-25 05:19:54 +0000567ConstantFP *ConstantFP::getNegativeZero(Type *Ty) {
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000568 LLVMContext &Context = Ty->getContext();
Chris Lattner3c2c9542012-01-25 05:19:54 +0000569 APFloat apf = cast<ConstantFP>(Constant::getNullValue(Ty))->getValueAPF();
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000570 apf.changeSign();
571 return get(Context, apf);
572}
573
574
Chris Lattner3c2c9542012-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 Anderson6f83c9c2009-07-27 20:59:43 +0000583
Owen Andersona7235ea2009-07-31 20:28:14 +0000584 return Constant::getNullValue(Ty);
Owen Anderson6f83c9c2009-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 Kistanovaa46517e2012-07-13 01:25:27 +0000591
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000592 LLVMContextImpl* pImpl = Context.pImpl;
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000593
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000594 ConstantFP *&Slot = pImpl->FPConstants[Key];
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000595
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000596 if (!Slot) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000597 Type *Ty;
Dan Gohmance163392011-12-17 00:04:22 +0000598 if (&V.getSemantics() == &APFloat::IEEEhalf)
599 Ty = Type::getHalfTy(Context);
600 else if (&V.getSemantics() == &APFloat::IEEEsingle)
Owen Anderson59d5aac2009-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 Anderson6f83c9c2009-07-27 20:59:43 +0000612 }
Owen Anderson59d5aac2009-10-19 20:11:52 +0000613 Slot = new ConstantFP(Ty, V);
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000614 }
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000615
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000616 return Slot;
617}
618
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000619ConstantFP *ConstantFP::getInfinity(Type *Ty, bool Negative) {
Dan Gohmanf344f7f2009-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 Lattnerdb125cf2011-07-18 04:54:35 +0000625ConstantFP::ConstantFP(Type *Ty, const APFloat& V)
Dale Johannesenf04afdb2007-08-30 00:23:21 +0000626 : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
Chris Lattner288e78f2008-04-09 06:38:30 +0000627 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
628 "FP type Mismatch");
Chris Lattner00950542001-06-06 20:29:01 +0000629}
630
Chris Lattner032c6eb2011-07-15 06:14:08 +0000631bool ConstantFP::isExactlyValue(const APFloat &V) const {
Dale Johannesenf04afdb2007-08-30 00:23:21 +0000632 return Val.bitwiseIsEqual(V);
Chris Lattner9b4ee0c2007-02-20 07:17:17 +0000633}
634
Chris Lattner9b4ee0c2007-02-20 07:17:17 +0000635//===----------------------------------------------------------------------===//
Chris Lattnerff2b7f32012-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 Lattner3d5ed222012-01-25 06:16:32 +0000641Constant *ConstantAggregateZero::getSequentialElement() const {
Chris Lattner230cdab2012-01-26 00:42:34 +0000642 return Constant::getNullValue(getType()->getSequentialElementType());
Chris Lattnerff2b7f32012-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 Lattner3d5ed222012-01-25 06:16:32 +0000647Constant *ConstantAggregateZero::getStructElement(unsigned Elt) const {
Chris Lattner230cdab2012-01-26 00:42:34 +0000648 return Constant::getNullValue(getType()->getStructElementType(Elt));
Chris Lattnerff2b7f32012-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 Lattner3d5ed222012-01-25 06:16:32 +0000653Constant *ConstantAggregateZero::getElementValue(Constant *C) const {
Chris Lattnerff2b7f32012-01-24 05:42:11 +0000654 if (isa<SequentialType>(getType()))
655 return getSequentialElement();
656 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
657}
658
Chris Lattnerdf390282012-01-24 07:54:10 +0000659/// getElementValue - Return a zero of the right value for the specified GEP
660/// index.
Chris Lattner3d5ed222012-01-25 06:16:32 +0000661Constant *ConstantAggregateZero::getElementValue(unsigned Idx) const {
Chris Lattnerdf390282012-01-24 07:54:10 +0000662 if (isa<SequentialType>(getType()))
663 return getSequentialElement();
664 return getStructElement(Idx);
665}
666
667
Chris Lattnerff2b7f32012-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 Lattner3d5ed222012-01-25 06:16:32 +0000674UndefValue *UndefValue::getSequentialElement() const {
Chris Lattner230cdab2012-01-26 00:42:34 +0000675 return UndefValue::get(getType()->getSequentialElementType());
Chris Lattnerff2b7f32012-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 Lattner3d5ed222012-01-25 06:16:32 +0000680UndefValue *UndefValue::getStructElement(unsigned Elt) const {
Chris Lattner230cdab2012-01-26 00:42:34 +0000681 return UndefValue::get(getType()->getStructElementType(Elt));
Chris Lattnerff2b7f32012-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 Lattner3d5ed222012-01-25 06:16:32 +0000686UndefValue *UndefValue::getElementValue(Constant *C) const {
Chris Lattnerff2b7f32012-01-24 05:42:11 +0000687 if (isa<SequentialType>(getType()))
688 return getSequentialElement();
689 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
690}
691
Chris Lattnerdf390282012-01-24 07:54:10 +0000692/// getElementValue - Return an undef of the right value for the specified GEP
693/// index.
Chris Lattner3d5ed222012-01-25 06:16:32 +0000694UndefValue *UndefValue::getElementValue(unsigned Idx) const {
Chris Lattnerdf390282012-01-24 07:54:10 +0000695 if (isa<SequentialType>(getType()))
696 return getSequentialElement();
697 return getStructElement(Idx);
698}
699
700
Chris Lattnerff2b7f32012-01-24 05:42:11 +0000701
702//===----------------------------------------------------------------------===//
Chris Lattner9b4ee0c2007-02-20 07:17:17 +0000703// ConstantXXX Classes
704//===----------------------------------------------------------------------===//
705
Chris Lattner18c7f802012-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 Lattner9b4ee0c2007-02-20 07:17:17 +0000713
Jay Foad166579e2011-07-25 10:14:44 +0000714ConstantArray::ConstantArray(ArrayType *T, ArrayRef<Constant *> V)
Gabor Greifefe65362008-05-10 08:32:32 +0000715 : Constant(T, ConstantArrayVal,
716 OperandTraits<ConstantArray>::op_end(this) - V.size(),
717 V.size()) {
Alkis Evlogimenose0de1d62004-09-15 02:32:15 +0000718 assert(V.size() == T->getNumElements() &&
719 "Invalid initializer vector for constant array");
Jay Foad166579e2011-07-25 10:14:44 +0000720 for (unsigned i = 0, e = V.size(); i != e; ++i)
721 assert(V[i]->getType() == T->getElementType() &&
Alkis Evlogimenoscad90ad2004-09-10 04:16:59 +0000722 "Initializer for array element doesn't match array element type!");
Jay Foad166579e2011-07-25 10:14:44 +0000723 std::copy(V.begin(), V.end(), op_begin());
Chris Lattner00950542001-06-06 20:29:01 +0000724}
725
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000726Constant *ConstantArray::get(ArrayType *Ty, ArrayRef<Constant*> V) {
Chris Lattner18c7f802012-02-05 02:29:43 +0000727 // Empty arrays are canonicalized to ConstantAggregateZero.
728 if (V.empty())
729 return ConstantAggregateZero::get(Ty);
730
Jeffrey Yasskin1fb613c2009-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 Anderson1fd70962009-07-28 18:32:17 +0000735 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000736
Chris Lattner18c7f802012-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 Lattnere150e2d2012-01-26 02:31:22 +0000743
Chris Lattner18c7f802012-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 Kistanovaa46517e2012-07-13 01:25:27 +0000792
Chris Lattner18c7f802012-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 Anderson1fd70962009-07-28 18:32:17 +0000814 }
Chris Lattnere150e2d2012-01-26 02:31:22 +0000815
Chris Lattner18c7f802012-02-05 02:29:43 +0000816 // Otherwise, we really do want to create a ConstantArray.
Chris Lattnere150e2d2012-01-26 02:31:22 +0000817 return pImpl->ArrayConstants.getOrCreate(Ty, V);
Owen Anderson1fd70962009-07-28 18:32:17 +0000818}
819
Chris Lattnerb065b062011-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 Wendlinga7a3f042012-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 Kistanovaa46517e2012-07-13 01:25:27 +0000829
Chris Lattnerb065b062011-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 Foad166579e2011-07-25 10:14:44 +0000842ConstantStruct::ConstantStruct(StructType *T, ArrayRef<Constant *> V)
Gabor Greifefe65362008-05-10 08:32:32 +0000843 : Constant(T, ConstantStructVal,
844 OperandTraits<ConstantStruct>::op_end(this) - V.size(),
845 V.size()) {
Chris Lattnerf4ef8db2011-08-07 04:18:48 +0000846 assert(V.size() == T->getNumElements() &&
Vikram S. Adve345e0cf2002-07-14 23:13:17 +0000847 "Invalid initializer vector for constant structure");
Jay Foad166579e2011-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 Lattnerb8438892003-06-02 17:42:47 +0000850 "Initializer for struct element doesn't match struct element type!");
Jay Foad166579e2011-07-25 10:14:44 +0000851 std::copy(V.begin(), V.end(), op_begin());
Chris Lattner00950542001-06-06 20:29:01 +0000852}
853
Owen Anderson8fa33382009-07-27 22:29:26 +0000854// ConstantStruct accessors.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000855Constant *ConstantStruct::get(StructType *ST, ArrayRef<Constant*> V) {
Chris Lattner1afcace2011-07-09 17:41:24 +0000856 assert((ST->isOpaque() || ST->getNumElements() == V.size()) &&
857 "Incorrect # elements specified to ConstantStruct::get");
Chris Lattnere150e2d2012-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 Kistanovaa46517e2012-07-13 01:25:27 +0000874 }
Chris Lattnere150e2d2012-01-26 02:31:22 +0000875 if (isZero)
876 return ConstantAggregateZero::get(ST);
877 if (isUndef)
878 return UndefValue::get(ST);
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000879
Chris Lattnere150e2d2012-01-26 02:31:22 +0000880 return ST->getContext().pImpl->StructConstants.getOrCreate(ST, V);
Owen Anderson8fa33382009-07-27 22:29:26 +0000881}
882
Chris Lattnerf4ef8db2011-08-07 04:18:48 +0000883Constant *ConstantStruct::get(StructType *T, ...) {
Talin41ee4e52011-02-28 23:53:27 +0000884 va_list ap;
Chris Lattnerb065b062011-06-20 04:01:31 +0000885 SmallVector<Constant*, 8> Values;
886 va_start(ap, T);
887 while (Constant *Val = va_arg(ap, llvm::Constant*))
Talin41ee4e52011-02-28 23:53:27 +0000888 Values.push_back(Val);
Talinbdcd7662011-03-01 18:00:49 +0000889 va_end(ap);
Chris Lattnerb065b062011-06-20 04:01:31 +0000890 return get(T, Values);
Talin41ee4e52011-02-28 23:53:27 +0000891}
892
Jay Foad166579e2011-07-25 10:14:44 +0000893ConstantVector::ConstantVector(VectorType *T, ArrayRef<Constant *> V)
Gabor Greifefe65362008-05-10 08:32:32 +0000894 : Constant(T, ConstantVectorVal,
895 OperandTraits<ConstantVector>::op_end(this) - V.size(),
896 V.size()) {
Jay Foad166579e2011-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 Gohmanfa73ea22007-05-24 14:36:04 +0000899 "Initializer for vector element doesn't match vector element type!");
Jay Foad166579e2011-07-25 10:14:44 +0000900 std::copy(V.begin(), V.end(), op_begin());
Brian Gaeke715c90b2004-08-20 06:00:58 +0000901}
902
Owen Andersonaf7ec972009-07-28 21:19:26 +0000903// ConstantVector accessors.
Jay Foada0c13842011-06-22 09:10:19 +0000904Constant *ConstantVector::get(ArrayRef<Constant*> V) {
Jay Foad9afc5272011-01-27 14:44:55 +0000905 assert(!V.empty() && "Vectors can't be empty");
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000906 VectorType *T = VectorType::get(V.front()->getType(), V.size());
Chris Lattner2ca5c862011-02-15 00:14:00 +0000907 LLVMContextImpl *pImpl = T->getContext().pImpl;
Jay Foad9afc5272011-01-27 14:44:55 +0000908
Chris Lattner2ca5c862011-02-15 00:14:00 +0000909 // If this is an all-undef or all-zero vector, return a
Owen Andersonaf7ec972009-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 Kistanovaa46517e2012-07-13 01:25:27 +0000922
Owen Andersonaf7ec972009-07-28 21:19:26 +0000923 if (isZero)
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000924 return ConstantAggregateZero::get(T);
Owen Andersonaf7ec972009-07-28 21:19:26 +0000925 if (isUndef)
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000926 return UndefValue::get(T);
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000927
Chris Lattner36c744f2012-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 Lattner18c7f802012-02-05 02:29:43 +0000930 if (ConstantDataSequential::isElementTypeCompatible(C->getType())) {
Chris Lattner36c744f2012-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 Kistanovaa46517e2012-07-13 01:25:27 +0000973
Chris Lattner36c744f2012-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 Kistanovaa46517e2012-07-13 01:25:27 +0000996
Chris Lattner36c744f2012-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 Andersonaf7ec972009-07-28 21:19:26 +0000999 return pImpl->VectorConstants.getOrCreate(T, V);
1000}
1001
Chris Lattner3c2c9542012-01-25 05:19:54 +00001002Constant *ConstantVector::getSplat(unsigned NumElts, Constant *V) {
Chris Lattner36c744f2012-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 Kistanovaa46517e2012-07-13 01:25:27 +00001008
Chris Lattner3c2c9542012-01-25 05:19:54 +00001009 SmallVector<Constant*, 32> Elts(NumElts, V);
1010 return get(Elts);
1011}
1012
1013
Reid Spencer3da59db2006-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 Spencer077d0eb2006-12-04 05:19:50 +00001021bool ConstantExpr::isCompare() const {
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00001022 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
Reid Spencer077d0eb2006-12-04 05:19:50 +00001023}
1024
Dan Gohmane6992f72009-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 Fuentesee56c422010-08-02 06:00:15 +00001029 User::const_op_iterator OI = llvm::next(this->op_begin());
Dan Gohmane6992f72009-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 Lattnerdb125cf2011-07-18 04:54:35 +00001040 if (ArrayType *ATy = dyn_cast<ArrayType>(*GEPI))
Dan Gohmane6992f72009-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 Gohman81a0c0b2008-05-31 00:58:22 +00001050bool ConstantExpr::hasIndices() const {
1051 return getOpcode() == Instruction::ExtractValue ||
1052 getOpcode() == Instruction::InsertValue;
1053}
1054
Jay Foadd30aa5a2011-04-13 15:22:40 +00001055ArrayRef<unsigned> ConstantExpr::getIndices() const {
Dan Gohman81a0c0b2008-05-31 00:58:22 +00001056 if (const ExtractValueConstantExpr *EVCE =
1057 dyn_cast<ExtractValueConstantExpr>(this))
1058 return EVCE->Indices;
Dan Gohman1a203572008-06-23 16:39:44 +00001059
1060 return cast<InsertValueConstantExpr>(this)->Indices;
Dan Gohman81a0c0b2008-05-31 00:58:22 +00001061}
1062
Reid Spencer728b6db2006-12-03 05:48:19 +00001063unsigned ConstantExpr::getPredicate() const {
Chris Lattner3e194732011-07-17 06:01:30 +00001064 assert(isCompare());
Chris Lattnerb7daa842007-10-18 16:26:24 +00001065 return ((const CompareConstantExpr*)this)->predicate;
Reid Spencer728b6db2006-12-03 05:48:19 +00001066}
Chris Lattnerf4ba6c72001-10-03 06:12:09 +00001067
Chris Lattner1fe8f6b2006-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 Spencer3da59db2006-11-27 01:05:10 +00001070Constant *
1071ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
Chris Lattner1fe8f6b2006-07-14 19:37:40 +00001072 assert(Op->getType() == getOperand(OpNo)->getType() &&
1073 "Replacing operand with value of different type!");
Chris Lattnerb88a7fb2006-07-14 22:20:01 +00001074 if (getOperand(OpNo) == Op)
1075 return const_cast<ConstantExpr*>(this);
Chris Lattner1a8def62012-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 Kistanovaa46517e2012-07-13 01:25:27 +00001080
Chris Lattner1a8def62012-01-26 20:37:11 +00001081 return getWithOperands(NewOps);
Chris Lattnerb88a7fb2006-07-14 22:20:01 +00001082}
1083
1084/// getWithOperands - This returns the current constant expression with the
Chris Lattner1afcace2011-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 Lattnerb88a7fb2006-07-14 22:20:01 +00001087Constant *ConstantExpr::
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001088getWithOperands(ArrayRef<Constant*> Ops, Type *Ty) const {
Jay Foadb81e4572011-04-13 13:46:01 +00001089 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
Chris Lattner1afcace2011-07-09 17:41:24 +00001090 bool AnyChange = Ty != getType();
1091 for (unsigned i = 0; i != Ops.size(); ++i)
Chris Lattnerb88a7fb2006-07-14 22:20:01 +00001092 AnyChange |= Ops[i] != getOperand(i);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001093
Chris Lattnerb88a7fb2006-07-14 22:20:01 +00001094 if (!AnyChange) // No operands changed, return self.
1095 return const_cast<ConstantExpr*>(this);
1096
1097 switch (getOpcode()) {
Reid Spencer3da59db2006-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 Lattner1afcace2011-07-09 17:41:24 +00001110 return ConstantExpr::getCast(getOpcode(), Ops[0], Ty);
Chris Lattnerb88a7fb2006-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 Lattner1a8def62012-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 Lattnerb88a7fb2006-07-14 22:20:01 +00001121 case Instruction::ShuffleVector:
1122 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
Chris Lattnerf9021ff2007-02-19 20:01:23 +00001123 case Instruction::GetElementPtr:
Chris Lattner1a8def62012-01-26 20:37:11 +00001124 return ConstantExpr::getGetElementPtr(Ops[0], Ops.slice(1),
1125 cast<GEPOperator>(this)->isInBounds());
Reid Spencere4d87aa2006-12-23 06:05:41 +00001126 case Instruction::ICmp:
1127 case Instruction::FCmp:
1128 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
Chris Lattnerb88a7fb2006-07-14 22:20:01 +00001129 default:
1130 assert(getNumOperands() == 2 && "Must be binary operator?");
Chris Lattnercafe9bb2009-12-29 02:14:09 +00001131 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1], SubclassOptionalData);
Chris Lattner1fe8f6b2006-07-14 19:37:40 +00001132 }
1133}
1134
Chris Lattner00950542001-06-06 20:29:01 +00001135
1136//===----------------------------------------------------------------------===//
Chris Lattner00950542001-06-06 20:29:01 +00001137// isValueValidForType implementations
1138
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001139bool ConstantInt::isValueValidForType(Type *Ty, uint64_t Val) {
Chris Lattner230cdab2012-01-26 00:42:34 +00001140 unsigned NumBits = Ty->getIntegerBitWidth(); // assert okay
1141 if (Ty->isIntegerTy(1))
Reid Spencera54b7cb2007-01-12 07:05:14 +00001142 return Val == 0 || Val == 1;
Reid Spencer554cec62007-02-05 23:47:56 +00001143 if (NumBits >= 64)
Reid Spencera54b7cb2007-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 Spencer9b11d512006-12-19 01:28:19 +00001147}
1148
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001149bool ConstantInt::isValueValidForType(Type *Ty, int64_t Val) {
Chris Lattner230cdab2012-01-26 00:42:34 +00001150 unsigned NumBits = Ty->getIntegerBitWidth();
1151 if (Ty->isIntegerTy(1))
Reid Spencerc1030572007-01-19 21:13:56 +00001152 return Val == 0 || Val == 1 || Val == -1;
Reid Spencer554cec62007-02-05 23:47:56 +00001153 if (NumBits >= 64)
Reid Spencera54b7cb2007-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 Lattner00950542001-06-06 20:29:01 +00001158}
1159
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001160bool ConstantFP::isValueValidForType(Type *Ty, const APFloat& Val) {
Dale Johannesenf04afdb2007-08-30 00:23:21 +00001161 // convert modifies in place, so make a copy.
1162 APFloat Val2 = APFloat(Val);
Dale Johannesen23a98552008-10-09 23:00:39 +00001163 bool losesInfo;
Chris Lattnerf70c22b2004-06-17 18:19:28 +00001164 switch (Ty->getTypeID()) {
Chris Lattner00950542001-06-06 20:29:01 +00001165 default:
1166 return false; // These can't be represented as floating point!
1167
Dale Johannesenf04afdb2007-08-30 00:23:21 +00001168 // FIXME rounding mode needs to be more flexible
Dan Gohmance163392011-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 Johannesen23a98552008-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 Gohmance163392011-12-17 00:04:22 +00001182 if (&Val2.getSemantics() == &APFloat::IEEEhalf ||
1183 &Val2.getSemantics() == &APFloat::IEEEsingle ||
Dale Johannesen23a98552008-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 Johannesenebbc95d2007-08-09 22:51:36 +00001189 case Type::X86_FP80TyID:
Dan Gohmance163392011-12-17 00:04:22 +00001190 return &Val2.getSemantics() == &APFloat::IEEEhalf ||
1191 &Val2.getSemantics() == &APFloat::IEEEsingle ||
Dale Johannesen9d5f4562007-09-12 03:30:33 +00001192 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1193 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
Dale Johannesenebbc95d2007-08-09 22:51:36 +00001194 case Type::FP128TyID:
Dan Gohmance163392011-12-17 00:04:22 +00001195 return &Val2.getSemantics() == &APFloat::IEEEhalf ||
1196 &Val2.getSemantics() == &APFloat::IEEEsingle ||
Dale Johannesen9d5f4562007-09-12 03:30:33 +00001197 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1198 &Val2.getSemantics() == &APFloat::IEEEquad;
Dale Johannesena471c2e2007-10-11 18:07:22 +00001199 case Type::PPC_FP128TyID:
Dan Gohmance163392011-12-17 00:04:22 +00001200 return &Val2.getSemantics() == &APFloat::IEEEhalf ||
1201 &Val2.getSemantics() == &APFloat::IEEEsingle ||
Dale Johannesena471c2e2007-10-11 18:07:22 +00001202 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1203 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
Chris Lattner00950542001-06-06 20:29:01 +00001204 }
Chris Lattnerd74ea2b2006-05-24 17:04:05 +00001205}
Chris Lattner37bf6302001-07-20 19:16:02 +00001206
Chris Lattnerff2b7f32012-01-24 05:42:11 +00001207
Chris Lattner531daef2001-09-07 16:46:31 +00001208//===----------------------------------------------------------------------===//
Chris Lattner531daef2001-09-07 16:46:31 +00001209// Factory Function Implementation
1210
Chris Lattner9df0fb42012-01-23 15:20:12 +00001211ConstantAggregateZero *ConstantAggregateZero::get(Type *Ty) {
Chris Lattner61c70e92010-08-28 04:09:24 +00001212 assert((Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()) &&
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001213 "Cannot create an aggregate zero of non-aggregate type!");
1214
Chris Lattner9df0fb42012-01-23 15:20:12 +00001215 ConstantAggregateZero *&Entry = Ty->getContext().pImpl->CAZConstants[Ty];
1216 if (Entry == 0)
1217 Entry = new ConstantAggregateZero(Ty);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001218
Chris Lattner9df0fb42012-01-23 15:20:12 +00001219 return Entry;
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001220}
1221
Chris Lattnerff2b7f32012-01-24 05:42:11 +00001222/// destroyConstant - Remove the constant from the constant table.
Dan Gohman0f8b53f2009-03-03 02:55:14 +00001223///
Owen Anderson04fb7c32009-06-20 00:24:58 +00001224void ConstantAggregateZero::destroyConstant() {
Chris Lattner9df0fb42012-01-23 15:20:12 +00001225 getContext().pImpl->CAZConstants.erase(getType());
Chris Lattner40bbeb52004-02-15 05:53:04 +00001226 destroyConstantImpl();
1227}
1228
Dan Gohman0f8b53f2009-03-03 02:55:14 +00001229/// destroyConstant - Remove the constant from the constant table...
1230///
Owen Anderson04fb7c32009-06-20 00:24:58 +00001231void ConstantArray::destroyConstant() {
Chris Lattner1afcace2011-07-09 17:41:24 +00001232 getType()->getContext().pImpl->ArrayConstants.remove(this);
Chris Lattner02ec5ed2003-05-23 20:03:32 +00001233 destroyConstantImpl();
1234}
1235
Chris Lattner93aeea32002-08-26 17:53:56 +00001236
Chris Lattnere9bb2df2001-12-03 22:26:30 +00001237//---- ConstantStruct::get() implementation...
Chris Lattner531daef2001-09-07 16:46:31 +00001238//
Chris Lattnered468e372003-10-05 00:17:43 +00001239
Chris Lattnerf5ec48d2001-10-13 06:57:33 +00001240// destroyConstant - Remove the constant from the constant table...
Chris Lattner6a57baa2001-10-03 15:39:36 +00001241//
Owen Anderson04fb7c32009-06-20 00:24:58 +00001242void ConstantStruct::destroyConstant() {
Chris Lattner1afcace2011-07-09 17:41:24 +00001243 getType()->getContext().pImpl->StructConstants.remove(this);
Chris Lattnerf5ec48d2001-10-13 06:57:33 +00001244 destroyConstantImpl();
1245}
Chris Lattner6a57baa2001-10-03 15:39:36 +00001246
Brian Gaeke715c90b2004-08-20 06:00:58 +00001247// destroyConstant - Remove the constant from the constant table...
1248//
Owen Anderson04fb7c32009-06-20 00:24:58 +00001249void ConstantVector::destroyConstant() {
Chris Lattner1afcace2011-07-09 17:41:24 +00001250 getType()->getContext().pImpl->VectorConstants.remove(this);
Brian Gaeke715c90b2004-08-20 06:00:58 +00001251 destroyConstantImpl();
1252}
1253
Duncan Sands2333e292012-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 Gohman3b7cf0a2007-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 Sands7681c6d2011-02-01 08:39:12 +00001269Constant *ConstantVector::getSplatValue() const {
Dan Gohman3b7cf0a2007-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 Lattner3e194732011-07-17 06:01:30 +00001274 if (getOperand(I) != Elt)
1275 return 0;
Dan Gohman3b7cf0a2007-10-17 17:51:30 +00001276 return Elt;
1277}
1278
Duncan Sands2333e292012-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 Lattner2ee11ec2009-10-28 00:01:44 +00001291//---- ConstantPointerNull::get() implementation.
Chris Lattnerf5ec48d2001-10-13 06:57:33 +00001292//
Chris Lattner02ec5ed2003-05-23 20:03:32 +00001293
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001294ConstantPointerNull *ConstantPointerNull::get(PointerType *Ty) {
Chris Lattner9df0fb42012-01-23 15:20:12 +00001295 ConstantPointerNull *&Entry = Ty->getContext().pImpl->CPNConstants[Ty];
1296 if (Entry == 0)
1297 Entry = new ConstantPointerNull(Ty);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001298
Chris Lattner9df0fb42012-01-23 15:20:12 +00001299 return Entry;
Chris Lattner6a57baa2001-10-03 15:39:36 +00001300}
1301
Chris Lattner41661fd2002-08-18 00:40:04 +00001302// destroyConstant - Remove the constant from the constant table...
1303//
Owen Anderson04fb7c32009-06-20 00:24:58 +00001304void ConstantPointerNull::destroyConstant() {
Chris Lattner9df0fb42012-01-23 15:20:12 +00001305 getContext().pImpl->CPNConstants.erase(getType());
1306 // Free the constant and any dangling references to it.
Chris Lattner41661fd2002-08-18 00:40:04 +00001307 destroyConstantImpl();
1308}
1309
1310
Chris Lattner2ee11ec2009-10-28 00:01:44 +00001311//---- UndefValue::get() implementation.
Chris Lattnerb9f18592004-10-16 18:07:16 +00001312//
1313
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001314UndefValue *UndefValue::get(Type *Ty) {
Chris Lattner9df0fb42012-01-23 15:20:12 +00001315 UndefValue *&Entry = Ty->getContext().pImpl->UVConstants[Ty];
1316 if (Entry == 0)
1317 Entry = new UndefValue(Ty);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001318
Chris Lattner9df0fb42012-01-23 15:20:12 +00001319 return Entry;
Chris Lattnerb9f18592004-10-16 18:07:16 +00001320}
1321
1322// destroyConstant - Remove the constant from the constant table.
1323//
Owen Anderson04fb7c32009-06-20 00:24:58 +00001324void UndefValue::destroyConstant() {
Chris Lattner9df0fb42012-01-23 15:20:12 +00001325 // Free the constant and any dangling references to it.
1326 getContext().pImpl->UVConstants.erase(getType());
Chris Lattnerb9f18592004-10-16 18:07:16 +00001327 destroyConstantImpl();
1328}
1329
Chris Lattner2ee11ec2009-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 Kistanovaa46517e2012-07-13 01:25:27 +00001343
Chris Lattner2ee11ec2009-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 Lattnerd0ec2352009-11-01 03:03:03 +00001351 setOperand(0, F);
1352 setOperand(1, BB);
Chris Lattnercdfc9402009-11-01 01:27:45 +00001353 BB->AdjustBlockAddressRefCount(1);
Chris Lattner2ee11ec2009-10-28 00:01:44 +00001354}
1355
1356
1357// destroyConstant - Remove the constant from the constant table.
1358//
1359void BlockAddress::destroyConstant() {
Chris Lattner1afcace2011-07-09 17:41:24 +00001360 getFunction()->getType()->getContext().pImpl
Chris Lattner2ee11ec2009-10-28 00:01:44 +00001361 ->BlockAddresses.erase(std::make_pair(getFunction(), getBasicBlock()));
Chris Lattnercdfc9402009-11-01 01:27:45 +00001362 getBasicBlock()->AdjustBlockAddressRefCount(-1);
Chris Lattner2ee11ec2009-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 Kistanovaa46517e2012-07-13 01:25:27 +00001371
Chris Lattner2ee11ec2009-10-28 00:01:44 +00001372 if (U == &Op<0>())
1373 NewF = cast<Function>(To);
1374 else
1375 NewBB = cast<BasicBlock>(To);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001376
Chris Lattner2ee11ec2009-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 Lattnerd0ec2352009-11-01 03:03:03 +00001382 getBasicBlock()->AdjustBlockAddressRefCount(-1);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001383
Chris Lattner2ee11ec2009-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 Lattnerd0ec2352009-11-01 03:03:03 +00001389 setOperand(0, NewF);
1390 setOperand(1, NewBB);
1391 getBasicBlock()->AdjustBlockAddressRefCount(1);
Chris Lattner2ee11ec2009-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 Kistanovaa46517e2012-07-13 01:25:27 +00001397
Chris Lattner2ee11ec2009-10-28 00:01:44 +00001398 // Everyone using this now uses the replacement.
Chris Lattner678f9e02011-07-15 06:18:52 +00001399 replaceAllUsesWith(NewBA);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001400
Chris Lattner2ee11ec2009-10-28 00:01:44 +00001401 destroyConstant();
1402}
1403
1404//---- ConstantExpr::get() implementations.
Vikram S. Adve345e0cf2002-07-14 23:13:17 +00001405//
Reid Spencer79e21d32006-12-31 05:26:44 +00001406
Reid Spencer3da59db2006-11-27 01:05:10 +00001407/// This is a utility function to handle folding of casts and lookup of the
Duncan Sands66a1a052008-03-30 19:38:55 +00001408/// cast in the ExprConstants map. It is used by the various get* methods below.
Reid Spencer3da59db2006-11-27 01:05:10 +00001409static inline Constant *getFoldedCast(
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001410 Instruction::CastOps opc, Constant *C, Type *Ty) {
Chris Lattner9eacf8a2003-10-07 22:19:19 +00001411 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
Reid Spencer3da59db2006-11-27 01:05:10 +00001412 // Fold a few common cases
Chris Lattnerb29d5962010-02-01 20:48:08 +00001413 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
Reid Spencer3da59db2006-11-27 01:05:10 +00001414 return FC;
Chris Lattnerd628f6a2003-04-17 19:24:48 +00001415
Owen Andersond03eecd2009-08-04 20:25:11 +00001416 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
1417
Vikram S. Adved0b1bb02002-07-15 18:19:33 +00001418 // Look up the constant in the table first to ensure uniqueness
Chris Lattner9bc02a42003-05-13 21:37:02 +00001419 std::vector<Constant*> argVec(1, C);
Reid Spencer077d0eb2006-12-04 05:19:50 +00001420 ExprMapKeyType Key(opc, argVec);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001421
Owen Andersond03eecd2009-08-04 20:25:11 +00001422 return pImpl->ExprConstants.getOrCreate(Ty, Key);
Vikram S. Adve345e0cf2002-07-14 23:13:17 +00001423}
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001424
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001425Constant *ConstantExpr::getCast(unsigned oc, Constant *C, Type *Ty) {
Reid Spencer3da59db2006-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 Lattner0b68a002010-01-26 21:51:43 +00001429 assert(CastInst::castIsValid(opc, C, Ty) && "Invalid constantexpr cast!");
Reid Spencer3da59db2006-11-27 01:05:10 +00001430
1431 switch (opc) {
Chris Lattner0b68a002010-01-26 21:51:43 +00001432 default:
1433 llvm_unreachable("Invalid cast opcode");
Chris Lattner0b68a002010-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 Lattnerf5ac6c22005-01-01 15:59:57 +00001446 }
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001447}
Reid Spencer7858b332006-12-05 19:14:13 +00001448
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001449Constant *ConstantExpr::getZExtOrBitCast(Constant *C, Type *Ty) {
Dan Gohman6de29f82009-06-15 22:12:54 +00001450 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
Dan Gohman3b490632010-04-12 22:12:29 +00001451 return getBitCast(C, Ty);
1452 return getZExt(C, Ty);
Reid Spencer848414e2006-12-04 20:17:56 +00001453}
1454
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001455Constant *ConstantExpr::getSExtOrBitCast(Constant *C, Type *Ty) {
Dan Gohman6de29f82009-06-15 22:12:54 +00001456 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
Dan Gohman3b490632010-04-12 22:12:29 +00001457 return getBitCast(C, Ty);
1458 return getSExt(C, Ty);
Reid Spencer848414e2006-12-04 20:17:56 +00001459}
1460
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001461Constant *ConstantExpr::getTruncOrBitCast(Constant *C, Type *Ty) {
Dan Gohman6de29f82009-06-15 22:12:54 +00001462 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
Dan Gohman3b490632010-04-12 22:12:29 +00001463 return getBitCast(C, Ty);
1464 return getTrunc(C, Ty);
Reid Spencer848414e2006-12-04 20:17:56 +00001465}
1466
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001467Constant *ConstantExpr::getPointerCast(Constant *S, Type *Ty) {
Evgeniy Stepanov655578f2013-01-16 14:41:46 +00001468 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
1469 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
1470 "Invalid cast");
Reid Spencerc0459fb2006-12-05 03:25:26 +00001471
Evgeniy Stepanov655578f2013-01-16 14:41:46 +00001472 if (Ty->isIntOrIntVectorTy())
Dan Gohman3b490632010-04-12 22:12:29 +00001473 return getPtrToInt(S, Ty);
1474 return getBitCast(S, Ty);
Reid Spencerc0459fb2006-12-05 03:25:26 +00001475}
1476
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001477Constant *ConstantExpr::getIntegerCast(Constant *C, Type *Ty,
Reid Spencer84f3eab2006-12-12 00:51:07 +00001478 bool isSigned) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001479 assert(C->getType()->isIntOrIntVectorTy() &&
1480 Ty->isIntOrIntVectorTy() && "Invalid cast");
Dan Gohman6de29f82009-06-15 22:12:54 +00001481 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1482 unsigned DstBits = Ty->getScalarSizeInBits();
Reid Spencer84f3eab2006-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 Lattnerdb125cf2011-07-18 04:54:35 +00001490Constant *ConstantExpr::getFPCast(Constant *C, Type *Ty) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001491 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
Reid Spencer84f3eab2006-12-12 00:51:07 +00001492 "Invalid cast");
Dan Gohman6de29f82009-06-15 22:12:54 +00001493 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1494 unsigned DstBits = Ty->getScalarSizeInBits();
Reid Spencerf25212a2006-12-12 05:38:50 +00001495 if (SrcBits == DstBits)
1496 return C; // Avoid a useless cast
Reid Spencer84f3eab2006-12-12 00:51:07 +00001497 Instruction::CastOps opcode =
Jay Foad9afc5272011-01-27 14:44:55 +00001498 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
Reid Spencer84f3eab2006-12-12 00:51:07 +00001499 return getCast(opcode, C, Ty);
1500}
1501
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001502Constant *ConstantExpr::getTrunc(Constant *C, Type *Ty) {
Dan Gohman6de29f82009-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 Sandsb0bc6c32010-02-15 16:12:20 +00001508 assert(C->getType()->isIntOrIntVectorTy() && "Trunc operand must be integer");
1509 assert(Ty->isIntOrIntVectorTy() && "Trunc produces only integral");
Dan Gohman6de29f82009-06-15 22:12:54 +00001510 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
Reid Spencer3da59db2006-11-27 01:05:10 +00001511 "SrcTy must be larger than DestTy for Trunc!");
1512
Owen Anderson04fb7c32009-06-20 00:24:58 +00001513 return getFoldedCast(Instruction::Trunc, C, Ty);
Reid Spencer3da59db2006-11-27 01:05:10 +00001514}
1515
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001516Constant *ConstantExpr::getSExt(Constant *C, Type *Ty) {
Dan Gohman6de29f82009-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 Sandsb0bc6c32010-02-15 16:12:20 +00001522 assert(C->getType()->isIntOrIntVectorTy() && "SExt operand must be integral");
1523 assert(Ty->isIntOrIntVectorTy() && "SExt produces only integer");
Dan Gohman6de29f82009-06-15 22:12:54 +00001524 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
Reid Spencer3da59db2006-11-27 01:05:10 +00001525 "SrcTy must be smaller than DestTy for SExt!");
1526
Owen Anderson04fb7c32009-06-20 00:24:58 +00001527 return getFoldedCast(Instruction::SExt, C, Ty);
Chris Lattnerd144f422004-04-04 23:20:30 +00001528}
1529
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001530Constant *ConstantExpr::getZExt(Constant *C, Type *Ty) {
Dan Gohman6de29f82009-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 Sandsb0bc6c32010-02-15 16:12:20 +00001536 assert(C->getType()->isIntOrIntVectorTy() && "ZEXt operand must be integral");
1537 assert(Ty->isIntOrIntVectorTy() && "ZExt produces only integer");
Dan Gohman6de29f82009-06-15 22:12:54 +00001538 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
Reid Spencer3da59db2006-11-27 01:05:10 +00001539 "SrcTy must be smaller than DestTy for ZExt!");
1540
Owen Anderson04fb7c32009-06-20 00:24:58 +00001541 return getFoldedCast(Instruction::ZExt, C, Ty);
Reid Spencer3da59db2006-11-27 01:05:10 +00001542}
1543
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001544Constant *ConstantExpr::getFPTrunc(Constant *C, Type *Ty) {
Dan Gohman6de29f82009-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 Sandsb0bc6c32010-02-15 16:12:20 +00001550 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00001551 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
Reid Spencer3da59db2006-11-27 01:05:10 +00001552 "This is an illegal floating point truncation!");
Owen Anderson04fb7c32009-06-20 00:24:58 +00001553 return getFoldedCast(Instruction::FPTrunc, C, Ty);
Reid Spencer3da59db2006-11-27 01:05:10 +00001554}
1555
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001556Constant *ConstantExpr::getFPExtend(Constant *C, Type *Ty) {
Dan Gohman6de29f82009-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 Sandsb0bc6c32010-02-15 16:12:20 +00001562 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00001563 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
Reid Spencer3da59db2006-11-27 01:05:10 +00001564 "This is an illegal floating point extension!");
Owen Anderson04fb7c32009-06-20 00:24:58 +00001565 return getFoldedCast(Instruction::FPExt, C, Ty);
Reid Spencer3da59db2006-11-27 01:05:10 +00001566}
1567
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001568Constant *ConstantExpr::getUIToFP(Constant *C, Type *Ty) {
Devang Patelb6dc9352008-11-03 23:20:04 +00001569#ifndef NDEBUG
Nate Begemanb348d182007-11-17 03:58:34 +00001570 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1571 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Patelb6dc9352008-11-03 23:20:04 +00001572#endif
Nate Begemanb348d182007-11-17 03:58:34 +00001573 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001574 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
Nate Begemanb348d182007-11-17 03:58:34 +00001575 "This is an illegal uint to floating point cast!");
Owen Anderson04fb7c32009-06-20 00:24:58 +00001576 return getFoldedCast(Instruction::UIToFP, C, Ty);
Reid Spencer3da59db2006-11-27 01:05:10 +00001577}
1578
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001579Constant *ConstantExpr::getSIToFP(Constant *C, Type *Ty) {
Devang Patelb6dc9352008-11-03 23:20:04 +00001580#ifndef NDEBUG
Nate Begemanb348d182007-11-17 03:58:34 +00001581 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1582 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Patelb6dc9352008-11-03 23:20:04 +00001583#endif
Nate Begemanb348d182007-11-17 03:58:34 +00001584 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001585 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
Reid Spencer3da59db2006-11-27 01:05:10 +00001586 "This is an illegal sint to floating point cast!");
Owen Anderson04fb7c32009-06-20 00:24:58 +00001587 return getFoldedCast(Instruction::SIToFP, C, Ty);
Reid Spencer3da59db2006-11-27 01:05:10 +00001588}
1589
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001590Constant *ConstantExpr::getFPToUI(Constant *C, Type *Ty) {
Devang Patelb6dc9352008-11-03 23:20:04 +00001591#ifndef NDEBUG
Nate Begemanb348d182007-11-17 03:58:34 +00001592 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1593 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Patelb6dc9352008-11-03 23:20:04 +00001594#endif
Nate Begemanb348d182007-11-17 03:58:34 +00001595 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001596 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
Nate Begemanb348d182007-11-17 03:58:34 +00001597 "This is an illegal floating point to uint cast!");
Owen Anderson04fb7c32009-06-20 00:24:58 +00001598 return getFoldedCast(Instruction::FPToUI, C, Ty);
Reid Spencer3da59db2006-11-27 01:05:10 +00001599}
1600
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001601Constant *ConstantExpr::getFPToSI(Constant *C, Type *Ty) {
Devang Patelb6dc9352008-11-03 23:20:04 +00001602#ifndef NDEBUG
Nate Begemanb348d182007-11-17 03:58:34 +00001603 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1604 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Patelb6dc9352008-11-03 23:20:04 +00001605#endif
Nate Begemanb348d182007-11-17 03:58:34 +00001606 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001607 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
Nate Begemanb348d182007-11-17 03:58:34 +00001608 "This is an illegal floating point to sint cast!");
Owen Anderson04fb7c32009-06-20 00:24:58 +00001609 return getFoldedCast(Instruction::FPToSI, C, Ty);
Reid Spencer3da59db2006-11-27 01:05:10 +00001610}
1611
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001612Constant *ConstantExpr::getPtrToInt(Constant *C, Type *DstTy) {
Nadav Rotem16087692011-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 Lattneraf7b4fb2012-01-25 01:32:59 +00001617 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
Nick Lewycky1486ae62012-01-25 03:20:12 +00001618 if (isa<VectorType>(C->getType()))
Chris Lattner230cdab2012-01-26 00:42:34 +00001619 assert(C->getType()->getVectorNumElements()==DstTy->getVectorNumElements()&&
Chris Lattneraf7b4fb2012-01-25 01:32:59 +00001620 "Invalid cast between a different number of vector elements");
Owen Anderson04fb7c32009-06-20 00:24:58 +00001621 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00001622}
1623
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001624Constant *ConstantExpr::getIntToPtr(Constant *C, Type *DstTy) {
Nadav Rotem16087692011-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 Lattneraf7b4fb2012-01-25 01:32:59 +00001629 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
Nick Lewycky1486ae62012-01-25 03:20:12 +00001630 if (isa<VectorType>(C->getType()))
Chris Lattner230cdab2012-01-26 00:42:34 +00001631 assert(C->getType()->getVectorNumElements()==DstTy->getVectorNumElements()&&
Chris Lattneraf7b4fb2012-01-25 01:32:59 +00001632 "Invalid cast between a different number of vector elements");
Owen Anderson04fb7c32009-06-20 00:24:58 +00001633 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00001634}
1635
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001636Constant *ConstantExpr::getBitCast(Constant *C, Type *DstTy) {
Chris Lattner0b68a002010-01-26 21:51:43 +00001637 assert(CastInst::castIsValid(Instruction::BitCast, C, DstTy) &&
1638 "Invalid constantexpr bitcast!");
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001639
Chris Lattner8c7f24a2009-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 Kistanovaa46517e2012-07-13 01:25:27 +00001643
Owen Anderson04fb7c32009-06-20 00:24:58 +00001644 return getFoldedCast(Instruction::BitCast, C, DstTy);
Chris Lattnerd144f422004-04-04 23:20:30 +00001645}
1646
Chris Lattnereaf79802011-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 Spencer0a783f72006-11-02 01:53:59 +00001650 assert(Opcode >= Instruction::BinaryOpsBegin &&
1651 Opcode < Instruction::BinaryOpsEnd &&
Chris Lattnerf31f5832003-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 Kistanovaa46517e2012-07-13 01:25:27 +00001655
Chris Lattner91b362b2004-08-17 17:28:46 +00001656#ifndef NDEBUG
1657 switch (Opcode) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001658 case Instruction::Add:
Reid Spencer0a783f72006-11-02 01:53:59 +00001659 case Instruction::Sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001660 case Instruction::Mul:
Chris Lattner91b362b2004-08-17 17:28:46 +00001661 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001662 assert(C1->getType()->isIntOrIntVectorTy() &&
Dan Gohmanae3a0be2009-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 Sandsb0bc6c32010-02-15 16:12:20 +00001669 assert(C1->getType()->isFPOrFPVectorTy() &&
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001670 "Tried to create a floating-point operation on a "
1671 "non-floating-point type!");
Chris Lattner91b362b2004-08-17 17:28:46 +00001672 break;
Reid Spencer1628cec2006-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 Sandsb0bc6c32010-02-15 16:12:20 +00001676 assert(C1->getType()->isIntOrIntVectorTy() &&
Reid Spencer1628cec2006-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 Sandsb0bc6c32010-02-15 16:12:20 +00001681 assert(C1->getType()->isFPOrFPVectorTy() &&
Dan Gohmanf57478f2009-06-15 22:25:12 +00001682 "Tried to create an arithmetic operation on a non-arithmetic type!");
Reid Spencer1628cec2006-10-26 06:15:43 +00001683 break;
Reid Spencer0a783f72006-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 Sandsb0bc6c32010-02-15 16:12:20 +00001687 assert(C1->getType()->isIntOrIntVectorTy() &&
Reid Spencer0a783f72006-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 Sandsb0bc6c32010-02-15 16:12:20 +00001692 assert(C1->getType()->isFPOrFPVectorTy() &&
Dan Gohmanf57478f2009-06-15 22:25:12 +00001693 "Tried to create an arithmetic operation on a non-arithmetic type!");
Reid Spencer0a783f72006-11-02 01:53:59 +00001694 break;
Chris Lattner91b362b2004-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 Sandsb0bc6c32010-02-15 16:12:20 +00001699 assert(C1->getType()->isIntOrIntVectorTy() &&
Misha Brukman1bae2912005-01-27 06:46:38 +00001700 "Tried to create a logical operation on a non-integral type!");
Chris Lattner91b362b2004-08-17 17:28:46 +00001701 break;
Chris Lattner91b362b2004-08-17 17:28:46 +00001702 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00001703 case Instruction::LShr:
1704 case Instruction::AShr:
Reid Spencer832254e2007-02-02 02:16:23 +00001705 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001706 assert(C1->getType()->isIntOrIntVectorTy() &&
Chris Lattner91b362b2004-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 Lattnereaf79802011-07-09 18:23:52 +00001714 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1715 return FC; // Fold a few common cases.
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001716
Chris Lattnereaf79802011-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 Kistanovaa46517e2012-07-13 01:25:27 +00001720
Chris Lattnereaf79802011-07-09 18:23:52 +00001721 LLVMContextImpl *pImpl = C1->getContext().pImpl;
1722 return pImpl->ExprConstants.getOrCreate(C1->getType(), Key);
Reid Spencer67263fe2006-12-04 21:35:24 +00001723}
1724
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001725Constant *ConstantExpr::getSizeOf(Type* Ty) {
Owen Andersonbaf3c402009-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 Anderson1d0be152009-08-13 21:58:54 +00001728 Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001729 Constant *GEP = getGetElementPtr(
Jay Foaddab3d292011-07-21 14:31:17 +00001730 Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
Dan Gohman3b490632010-04-12 22:12:29 +00001731 return getPtrToInt(GEP,
1732 Type::getInt64Ty(Ty->getContext()));
Owen Andersonbaf3c402009-07-29 18:55:55 +00001733}
1734
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001735Constant *ConstantExpr::getAlignOf(Type* Ty) {
Dan Gohman0f5efe52010-01-28 02:15:55 +00001736 // alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1
Dan Gohmane2574d32009-08-11 17:57:01 +00001737 // Note that a non-inbounds gep is used, as null isn't within any object.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001738 Type *AligningTy =
Chris Lattnerb2318662011-06-18 22:48:56 +00001739 StructType::get(Type::getInt1Ty(Ty->getContext()), Ty, NULL);
Micah Villmowb8bce922012-10-24 17:25:11 +00001740 Constant *NullPtr = Constant::getNullValue(AligningTy->getPointerTo());
Dan Gohman06ed3e72010-01-28 02:43:22 +00001741 Constant *Zero = ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0);
Owen Anderson1d0be152009-08-13 21:58:54 +00001742 Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001743 Constant *Indices[2] = { Zero, One };
Jay Foaddab3d292011-07-21 14:31:17 +00001744 Constant *GEP = getGetElementPtr(NullPtr, Indices);
Dan Gohman3b490632010-04-12 22:12:29 +00001745 return getPtrToInt(GEP,
1746 Type::getInt64Ty(Ty->getContext()));
Owen Andersonbaf3c402009-07-29 18:55:55 +00001747}
1748
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001749Constant *ConstantExpr::getOffsetOf(StructType* STy, unsigned FieldNo) {
Dan Gohman2544a1d2010-02-01 16:37:38 +00001750 return getOffsetOf(STy, ConstantInt::get(Type::getInt32Ty(STy->getContext()),
1751 FieldNo));
1752}
1753
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001754Constant *ConstantExpr::getOffsetOf(Type* Ty, Constant *FieldNo) {
Dan Gohman3778f212009-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 Gohman2544a1d2010-02-01 16:37:38 +00001758 ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0),
1759 FieldNo
Dan Gohman3778f212009-08-16 21:26:11 +00001760 };
1761 Constant *GEP = getGetElementPtr(
Jay Foaddab3d292011-07-21 14:31:17 +00001762 Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
Dan Gohman3b490632010-04-12 22:12:29 +00001763 return getPtrToInt(GEP,
1764 Type::getInt64Ty(Ty->getContext()));
Dan Gohman3778f212009-08-16 21:26:11 +00001765}
Owen Andersonbaf3c402009-07-29 18:55:55 +00001766
Chris Lattnereaf79802011-07-09 18:23:52 +00001767Constant *ConstantExpr::getCompare(unsigned short Predicate,
1768 Constant *C1, Constant *C2) {
Reid Spencer67263fe2006-12-04 21:35:24 +00001769 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001770
Chris Lattnereaf79802011-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 Kistanovaa46517e2012-07-13 01:25:27 +00001780
Chris Lattnereaf79802011-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 Lattnerc3d12f02004-08-04 18:50:09 +00001787}
1788
Chris Lattnereaf79802011-07-09 18:23:52 +00001789Constant *ConstantExpr::getSelect(Constant *C, Constant *V1, Constant *V2) {
Chris Lattner9ace0cd2008-12-29 00:16:12 +00001790 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
Chris Lattner08a45cc2004-03-12 05:54:04 +00001791
Chris Lattnereaf79802011-07-09 18:23:52 +00001792 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1793 return SC; // Fold common cases
Chris Lattner08a45cc2004-03-12 05:54:04 +00001794
1795 std::vector<Constant*> argVec(3, C);
1796 argVec[1] = V1;
1797 argVec[2] = V2;
Reid Spencer077d0eb2006-12-04 05:19:50 +00001798 ExprMapKeyType Key(Instruction::Select, argVec);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001799
Chris Lattnereaf79802011-07-09 18:23:52 +00001800 LLVMContextImpl *pImpl = C->getContext().pImpl;
1801 return pImpl->ExprConstants.getOrCreate(V1->getType(), Key);
Chris Lattner08a45cc2004-03-12 05:54:04 +00001802}
1803
Jay Foaddab3d292011-07-21 14:31:17 +00001804Constant *ConstantExpr::getGetElementPtr(Constant *C, ArrayRef<Value *> Idxs,
1805 bool InBounds) {
Duncan Sands2333e292012-11-13 12:59:33 +00001806 assert(C->getType()->isPtrOrPtrVectorTy() &&
1807 "Non-pointer type for constant GetElementPtr expression");
1808
Jay Foaddab3d292011-07-21 14:31:17 +00001809 if (Constant *FC = ConstantFoldGetElementPtr(C, InBounds, Idxs))
Chris Lattner1f78d512011-02-11 05:34:33 +00001810 return FC; // Fold a few common cases.
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001811
Chris Lattnereaf79802011-07-09 18:23:52 +00001812 // Get the result type of the getelementptr!
Jay Foada9203102011-07-25 09:48:08 +00001813 Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), Idxs);
Chris Lattnereaf79802011-07-09 18:23:52 +00001814 assert(Ty && "GEP indices invalid!");
Chris Lattner230cdab2012-01-26 00:42:34 +00001815 unsigned AS = C->getType()->getPointerAddressSpace();
Chris Lattnereaf79802011-07-09 18:23:52 +00001816 Type *ReqTy = Ty->getPointerTo(AS);
Duncan Sands2333e292012-11-13 12:59:33 +00001817 if (VectorType *VecTy = dyn_cast<VectorType>(C->getType()))
1818 ReqTy = VectorType::get(ReqTy, VecTy->getNumElements());
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001819
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001820 // Look up the constant in the table first to ensure uniqueness
1821 std::vector<Constant*> ArgVec;
Jay Foaddab3d292011-07-21 14:31:17 +00001822 ArgVec.reserve(1 + Idxs.size());
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001823 ArgVec.push_back(C);
Duncan Sands2333e292012-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 Gohmanf8dbee72009-09-07 23:54:19 +00001831 ArgVec.push_back(cast<Constant>(Idxs[i]));
Duncan Sands2333e292012-11-13 12:59:33 +00001832 }
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001833 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec, 0,
Chris Lattner1f78d512011-02-11 05:34:33 +00001834 InBounds ? GEPOperator::IsInBounds : 0);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001835
Chris Lattnereaf79802011-07-09 18:23:52 +00001836 LLVMContextImpl *pImpl = C->getContext().pImpl;
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001837 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1838}
1839
Reid Spencer077d0eb2006-12-04 05:19:50 +00001840Constant *
Nick Lewycky401f3252010-01-21 07:03:21 +00001841ConstantExpr::getICmp(unsigned short pred, Constant *LHS, Constant *RHS) {
Reid Spencer077d0eb2006-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 Lattnerb29d5962010-02-01 20:48:08 +00001846 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
Reid Spencer077d0eb2006-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 Spencer4fa021a2006-12-24 18:42:29 +00001853 // Get the key type with both the opcode and predicate
Reid Spencer077d0eb2006-12-04 05:19:50 +00001854 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
Owen Anderson31c36f02009-06-17 20:10:08 +00001855
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001856 Type *ResultTy = Type::getInt1Ty(LHS->getContext());
1857 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
Nick Lewycky401f3252010-01-21 07:03:21 +00001858 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
1859
Owen Andersond03eecd2009-08-04 20:25:11 +00001860 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
Nick Lewycky401f3252010-01-21 07:03:21 +00001861 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
Reid Spencer077d0eb2006-12-04 05:19:50 +00001862}
1863
1864Constant *
Nick Lewycky401f3252010-01-21 07:03:21 +00001865ConstantExpr::getFCmp(unsigned short pred, Constant *LHS, Constant *RHS) {
Reid Spencer077d0eb2006-12-04 05:19:50 +00001866 assert(LHS->getType() == RHS->getType());
1867 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1868
Chris Lattnerb29d5962010-02-01 20:48:08 +00001869 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
Reid Spencer077d0eb2006-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 Spencer4fa021a2006-12-24 18:42:29 +00001876 // Get the key type with both the opcode and predicate
Reid Spencer077d0eb2006-12-04 05:19:50 +00001877 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
Nick Lewycky401f3252010-01-21 07:03:21 +00001878
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001879 Type *ResultTy = Type::getInt1Ty(LHS->getContext());
1880 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
Nick Lewycky401f3252010-01-21 07:03:21 +00001881 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
1882
Owen Andersond03eecd2009-08-04 20:25:11 +00001883 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
Nick Lewycky401f3252010-01-21 07:03:21 +00001884 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
Reid Spencer077d0eb2006-12-04 05:19:50 +00001885}
1886
Robert Bocchinob52ee7f2006-01-10 19:05:34 +00001887Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
Duncan Sands1df98592010-02-16 11:11:14 +00001888 assert(Val->getType()->isVectorTy() &&
Reid Spencerac9dcb92007-02-15 03:39:18 +00001889 "Tried to create extractelement operation on non-vector type!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001890 assert(Idx->getType()->isIntegerTy(32) &&
Reid Spencer3d10b0b2007-01-26 07:37:34 +00001891 "Extractelement index must be i32 type!");
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001892
Chris Lattnereaf79802011-07-09 18:23:52 +00001893 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
Chris Lattner83738a22009-12-30 20:25:09 +00001894 return FC; // Fold a few common cases.
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001895
Robert Bocchinoc152f9c2006-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 Bocchinoc152f9c2006-01-17 20:07:22 +00001898 ArgVec.push_back(Idx);
Chris Lattnereaf79802011-07-09 18:23:52 +00001899 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001900
Chris Lattnereaf79802011-07-09 18:23:52 +00001901 LLVMContextImpl *pImpl = Val->getContext().pImpl;
Chris Lattner230cdab2012-01-26 00:42:34 +00001902 Type *ReqTy = Val->getType()->getVectorElementType();
Owen Andersond03eecd2009-08-04 20:25:11 +00001903 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
Robert Bocchinoc152f9c2006-01-17 20:07:22 +00001904}
1905
1906Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1907 Constant *Idx) {
Duncan Sands1df98592010-02-16 11:11:14 +00001908 assert(Val->getType()->isVectorTy() &&
Reid Spencerac9dcb92007-02-15 03:39:18 +00001909 "Tried to create insertelement operation on non-vector type!");
Chris Lattner230cdab2012-01-26 00:42:34 +00001910 assert(Elt->getType() == Val->getType()->getVectorElementType() &&
1911 "Insertelement types must match!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001912 assert(Idx->getType()->isIntegerTy(32) &&
Reid Spencer3d10b0b2007-01-26 07:37:34 +00001913 "Insertelement index must be i32 type!");
Robert Bocchinoc152f9c2006-01-17 20:07:22 +00001914
Chris Lattnereaf79802011-07-09 18:23:52 +00001915 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
1916 return FC; // Fold a few common cases.
Chris Lattner00f10232006-04-08 01:18:18 +00001917 // Look up the constant in the table first to ensure uniqueness
Chris Lattnereaf79802011-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 Kistanovaa46517e2012-07-13 01:25:27 +00001922
Chris Lattnereaf79802011-07-09 18:23:52 +00001923 LLVMContextImpl *pImpl = Val->getContext().pImpl;
1924 return pImpl->ExprConstants.getOrCreate(Val->getType(), Key);
Chris Lattner00f10232006-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 Begeman0f123cf2009-02-12 21:28:33 +00001931
Chris Lattnereaf79802011-07-09 18:23:52 +00001932 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
1933 return FC; // Fold a few common cases.
1934
Chris Lattner230cdab2012-01-26 00:42:34 +00001935 unsigned NElts = Mask->getType()->getVectorNumElements();
1936 Type *EltTy = V1->getType()->getVectorElementType();
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001937 Type *ShufTy = VectorType::get(EltTy, NElts);
Chris Lattnereaf79802011-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 Kistanovaa46517e2012-07-13 01:25:27 +00001944
Chris Lattnereaf79802011-07-09 18:23:52 +00001945 LLVMContextImpl *pImpl = ShufTy->getContext().pImpl;
1946 return pImpl->ExprConstants.getOrCreate(ShufTy, Key);
Chris Lattner00f10232006-04-08 01:18:18 +00001947}
1948
Chris Lattnereaf79802011-07-09 18:23:52 +00001949Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
Jay Foadfc6d3a42011-07-13 10:26:04 +00001950 ArrayRef<unsigned> Idxs) {
1951 assert(ExtractValueInst::getIndexedType(Agg->getType(),
1952 Idxs) == Val->getType() &&
Dan Gohman041e2eb2008-05-15 19:50:34 +00001953 "insertvalue indices invalid!");
Dan Gohmane4569942008-05-23 00:36:11 +00001954 assert(Agg->getType()->isFirstClassType() &&
Chris Lattner4e47aad2011-07-12 05:26:21 +00001955 "Non-first-class type for constant insertvalue expression");
Jay Foadfc6d3a42011-07-13 10:26:04 +00001956 Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs);
Chris Lattner4e47aad2011-07-12 05:26:21 +00001957 assert(FC && "insertvalue constant expr couldn't be folded!");
Dan Gohmane0891602008-07-21 23:30:30 +00001958 return FC;
Dan Gohman041e2eb2008-05-15 19:50:34 +00001959}
1960
Chris Lattnereaf79802011-07-09 18:23:52 +00001961Constant *ConstantExpr::getExtractValue(Constant *Agg,
Jay Foadfc6d3a42011-07-13 10:26:04 +00001962 ArrayRef<unsigned> Idxs) {
Dan Gohmane4569942008-05-23 00:36:11 +00001963 assert(Agg->getType()->isFirstClassType() &&
Chris Lattnereaf79802011-07-09 18:23:52 +00001964 "Tried to create extractelement operation on non-first-class type!");
Dan Gohman041e2eb2008-05-15 19:50:34 +00001965
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001966 Type *ReqTy = ExtractValueInst::getIndexedType(Agg->getType(), Idxs);
Chandler Carruthdc770fc2011-07-10 09:45:35 +00001967 (void)ReqTy;
Chris Lattnereaf79802011-07-09 18:23:52 +00001968 assert(ReqTy && "extractvalue indices invalid!");
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001969
Dan Gohmane4569942008-05-23 00:36:11 +00001970 assert(Agg->getType()->isFirstClassType() &&
1971 "Non-first-class type for constant extractvalue expression");
Jay Foadfc6d3a42011-07-13 10:26:04 +00001972 Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs);
Dan Gohmane0891602008-07-21 23:30:30 +00001973 assert(FC && "ExtractValue constant expr couldn't be folded!");
1974 return FC;
Dan Gohman041e2eb2008-05-15 19:50:34 +00001975}
1976
Chris Lattner81baf142011-02-10 07:01:55 +00001977Constant *ConstantExpr::getNeg(Constant *C, bool HasNUW, bool HasNSW) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001978 assert(C->getType()->isIntOrIntVectorTy() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00001979 "Cannot NEG a nonintegral value!");
Chris Lattner81baf142011-02-10 07:01:55 +00001980 return getSub(ConstantFP::getZeroValueForNegation(C->getType()),
1981 C, HasNUW, HasNSW);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001982}
1983
Chris Lattnerf067d582011-02-07 16:40:21 +00001984Constant *ConstantExpr::getFNeg(Constant *C) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001985 assert(C->getType()->isFPOrFPVectorTy() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00001986 "Cannot FNEG a non-floating-point value!");
Chris Lattner81baf142011-02-10 07:01:55 +00001987 return getFSub(ConstantFP::getZeroValueForNegation(C->getType()), C);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001988}
1989
Chris Lattnerf067d582011-02-07 16:40:21 +00001990Constant *ConstantExpr::getNot(Constant *C) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001991 assert(C->getType()->isIntOrIntVectorTy() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00001992 "Cannot NOT a nonintegral value!");
Owen Andersona7235ea2009-07-31 20:28:14 +00001993 return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
Owen Andersonbaf3c402009-07-29 18:55:55 +00001994}
1995
Chris Lattner81baf142011-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 Andersonbaf3c402009-07-29 18:55:55 +00002001}
2002
Chris Lattnerf067d582011-02-07 16:40:21 +00002003Constant *ConstantExpr::getFAdd(Constant *C1, Constant *C2) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002004 return get(Instruction::FAdd, C1, C2);
2005}
2006
Chris Lattner81baf142011-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 Andersonbaf3c402009-07-29 18:55:55 +00002012}
2013
Chris Lattnerf067d582011-02-07 16:40:21 +00002014Constant *ConstantExpr::getFSub(Constant *C1, Constant *C2) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002015 return get(Instruction::FSub, C1, C2);
2016}
2017
Chris Lattner81baf142011-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 Andersonbaf3c402009-07-29 18:55:55 +00002023}
2024
Chris Lattnerf067d582011-02-07 16:40:21 +00002025Constant *ConstantExpr::getFMul(Constant *C1, Constant *C2) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002026 return get(Instruction::FMul, C1, C2);
2027}
2028
Chris Lattner74f5c5a2011-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 Andersonbaf3c402009-07-29 18:55:55 +00002032}
2033
Chris Lattner74f5c5a2011-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 Andersonbaf3c402009-07-29 18:55:55 +00002037}
2038
Chris Lattnerf067d582011-02-07 16:40:21 +00002039Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002040 return get(Instruction::FDiv, C1, C2);
2041}
2042
Chris Lattnerf067d582011-02-07 16:40:21 +00002043Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002044 return get(Instruction::URem, C1, C2);
2045}
2046
Chris Lattnerf067d582011-02-07 16:40:21 +00002047Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002048 return get(Instruction::SRem, C1, C2);
2049}
2050
Chris Lattnerf067d582011-02-07 16:40:21 +00002051Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002052 return get(Instruction::FRem, C1, C2);
2053}
2054
Chris Lattnerf067d582011-02-07 16:40:21 +00002055Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002056 return get(Instruction::And, C1, C2);
2057}
2058
Chris Lattnerf067d582011-02-07 16:40:21 +00002059Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002060 return get(Instruction::Or, C1, C2);
2061}
2062
Chris Lattnerf067d582011-02-07 16:40:21 +00002063Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002064 return get(Instruction::Xor, C1, C2);
2065}
2066
Chris Lattner81baf142011-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 Andersonbaf3c402009-07-29 18:55:55 +00002072}
2073
Chris Lattner74f5c5a2011-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 Andersonbaf3c402009-07-29 18:55:55 +00002077}
2078
Chris Lattner74f5c5a2011-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 Andersonbaf3c402009-07-29 18:55:55 +00002082}
2083
Duncan Sandsc038a782012-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 Sandsee5a0942012-06-13 09:42:13 +00002086/// returns null if the operator doesn't have an identity.
Duncan Sandsc038a782012-06-12 14:33:56 +00002087Constant *ConstantExpr::getBinOpIdentity(unsigned Opcode, Type *Ty) {
2088 switch (Opcode) {
2089 default:
Duncan Sandsee5a0942012-06-13 09:42:13 +00002090 // Doesn't have an identity.
2091 return 0;
2092
Duncan Sandsc038a782012-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 Sandsee5a0942012-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. Adved0b1bb02002-07-15 18:19:33 +00002125// destroyConstant - Remove the constant from the constant table...
2126//
Owen Anderson04fb7c32009-06-20 00:24:58 +00002127void ConstantExpr::destroyConstant() {
Chris Lattner1afcace2011-07-09 17:41:24 +00002128 getType()->getContext().pImpl->ExprConstants.remove(this);
Vikram S. Adved0b1bb02002-07-15 18:19:33 +00002129 destroyConstantImpl();
Vikram S. Adve345e0cf2002-07-14 23:13:17 +00002130}
2131
Chris Lattnerc188eeb2002-07-30 18:54:25 +00002132const char *ConstantExpr::getOpcodeName() const {
2133 return Instruction::getOpcodeName(getOpcode());
Vikram S. Adve345e0cf2002-07-14 23:13:17 +00002134}
Reid Spencer1c9c8e62004-07-17 23:48:33 +00002135
Chris Lattner04e3b1e2010-03-30 20:48:48 +00002136
2137
2138GetElementPtrConstantExpr::
Chris Lattnera7c69882012-01-26 20:40:56 +00002139GetElementPtrConstantExpr(Constant *C, ArrayRef<Constant*> IdxList,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002140 Type *DestTy)
Chris Lattner04e3b1e2010-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 Lattner27dd9cf2012-01-23 22:57:10 +00002149//===----------------------------------------------------------------------===//
2150// ConstantData* implementations
2151
2152void ConstantDataArray::anchor() {}
2153void ConstantDataVector::anchor() {}
2154
Chris Lattner45bb5c52012-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 Lattner9e631da2012-01-24 09:31:43 +00002160StringRef ConstantDataSequential::getRawDataValues() const {
Chris Lattner1ee0ecf2012-01-24 13:41:11 +00002161 return StringRef(DataElements, getNumElements()*getElementByteSize());
Chris Lattner9e631da2012-01-24 09:31:43 +00002162}
2163
Chris Lattnerff2b7f32012-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 Lattner45bb5c52012-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 Lattner1ee0ecf2012-01-24 13:41:11 +00002183/// getNumElements - Return the number of elements in the array or vector.
2184unsigned ConstantDataSequential::getNumElements() const {
Chris Lattneraf7b4fb2012-01-25 01:32:59 +00002185 if (ArrayType *AT = dyn_cast<ArrayType>(getType()))
2186 return AT->getNumElements();
Chris Lattner230cdab2012-01-26 00:42:34 +00002187 return getType()->getVectorNumElements();
Chris Lattner1ee0ecf2012-01-24 13:41:11 +00002188}
2189
2190
Chris Lattner45bb5c52012-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 Lattner1ee0ecf2012-01-24 13:41:11 +00002198 assert(Elt < getNumElements() && "Invalid Elt");
Chris Lattner45bb5c52012-01-24 04:43:41 +00002199 return DataElements+Elt*getElementByteSize();
2200}
2201
2202
Chris Lattner27dd9cf2012-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 Lattnerff2b7f32012-01-24 05:42:11 +00002210
Chris Lattner27dd9cf2012-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 Lattner8cf27ef2012-01-30 18:19:30 +00002213/// the correct element type. We take the bytes in as a StringRef because
Chris Lattner27dd9cf2012-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 Lattner230cdab2012-01-26 00:42:34 +00002216 assert(isElementTypeCompatible(Ty->getSequentialElementType()));
Chris Lattner29cc6cb2012-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 Lattner27dd9cf2012-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 Kistanovaa46517e2012-07-13 01:25:27 +00002225
Chris Lattner27dd9cf2012-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 Kistanovaa46517e2012-07-13 01:25:27 +00002235
Chris Lattner27dd9cf2012-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 Lattner27dd9cf2012-01-23 22:57:10 +00002246 // Remove the constant from the StringMap.
2247 StringMap<ConstantDataSequential*> &CDSConstants =
2248 getType()->getContext().pImpl->CDSConstants;
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002249
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002250 StringMap<ConstantDataSequential*>::iterator Slot =
Chris Lattner9e631da2012-01-24 09:31:43 +00002251 CDSConstants.find(getRawDataValues());
Chris Lattner27dd9cf2012-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 Kistanovaa46517e2012-07-13 01:25:27 +00002276
Chris Lattner27dd9cf2012-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 Kistanovaa46517e2012-07-13 01:25:27 +00002280
Chris Lattner27dd9cf2012-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 Lattner32100602012-01-24 14:04:40 +00002288Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint8_t> Elts) {
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002289 Type *Ty = ArrayType::get(Type::getInt8Ty(Context), Elts.size());
Galina Kistanovaa46517e2012-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 Lattner27dd9cf2012-01-23 22:57:10 +00002292}
Chris Lattner32100602012-01-24 14:04:40 +00002293Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint16_t> Elts){
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002294 Type *Ty = ArrayType::get(Type::getInt16Ty(Context), Elts.size());
Galina Kistanovaa46517e2012-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 Lattner27dd9cf2012-01-23 22:57:10 +00002297}
Chris Lattner32100602012-01-24 14:04:40 +00002298Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint32_t> Elts){
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002299 Type *Ty = ArrayType::get(Type::getInt32Ty(Context), Elts.size());
Galina Kistanovaa46517e2012-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 Lattner27dd9cf2012-01-23 22:57:10 +00002302}
Chris Lattner32100602012-01-24 14:04:40 +00002303Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint64_t> Elts){
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002304 Type *Ty = ArrayType::get(Type::getInt64Ty(Context), Elts.size());
Galina Kistanovaa46517e2012-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 Lattner27dd9cf2012-01-23 22:57:10 +00002307}
Chris Lattner32100602012-01-24 14:04:40 +00002308Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<float> Elts) {
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002309 Type *Ty = ArrayType::get(Type::getFloatTy(Context), Elts.size());
Galina Kistanovaa46517e2012-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 Lattner27dd9cf2012-01-23 22:57:10 +00002312}
Chris Lattner32100602012-01-24 14:04:40 +00002313Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<double> Elts) {
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002314 Type *Ty = ArrayType::get(Type::getDoubleTy(Context), Elts.size());
Galina Kistanovaa46517e2012-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 Lattner27dd9cf2012-01-23 22:57:10 +00002317}
2318
Chris Lattner32100602012-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 Kistanovaa46517e2012-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 Lattner32100602012-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 Lattner27dd9cf2012-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 Lattner32100602012-01-24 14:04:40 +00002341Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint8_t> Elts){
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002342 Type *Ty = VectorType::get(Type::getInt8Ty(Context), Elts.size());
Galina Kistanovaa46517e2012-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 Lattner27dd9cf2012-01-23 22:57:10 +00002345}
Chris Lattner32100602012-01-24 14:04:40 +00002346Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint16_t> Elts){
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002347 Type *Ty = VectorType::get(Type::getInt16Ty(Context), Elts.size());
Galina Kistanovaa46517e2012-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 Lattner27dd9cf2012-01-23 22:57:10 +00002350}
Chris Lattner32100602012-01-24 14:04:40 +00002351Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint32_t> Elts){
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002352 Type *Ty = VectorType::get(Type::getInt32Ty(Context), Elts.size());
Galina Kistanovaa46517e2012-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 Lattner27dd9cf2012-01-23 22:57:10 +00002355}
Chris Lattner32100602012-01-24 14:04:40 +00002356Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint64_t> Elts){
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002357 Type *Ty = VectorType::get(Type::getInt64Ty(Context), Elts.size());
Galina Kistanovaa46517e2012-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 Lattner27dd9cf2012-01-23 22:57:10 +00002360}
Chris Lattner32100602012-01-24 14:04:40 +00002361Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<float> Elts) {
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002362 Type *Ty = VectorType::get(Type::getFloatTy(Context), Elts.size());
Galina Kistanovaa46517e2012-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 Lattner27dd9cf2012-01-23 22:57:10 +00002365}
Chris Lattner32100602012-01-24 14:04:40 +00002366Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<double> Elts) {
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002367 Type *Ty = VectorType::get(Type::getDoubleTy(Context), Elts.size());
Galina Kistanovaa46517e2012-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 Lattner27dd9cf2012-01-23 22:57:10 +00002370}
2371
Chris Lattner3c2c9542012-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 Lattner36c744f2012-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 Lattner3c2c9542012-01-25 05:19:54 +00002403 }
Chris Lattner36c744f2012-01-30 06:21:21 +00002404 return ConstantVector::getSplat(NumElts, V);
Chris Lattner3c2c9542012-01-25 05:19:54 +00002405}
2406
2407
Chris Lattner45bb5c52012-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 Kistanovaa46517e2012-07-13 01:25:27 +00002414
Chris Lattner45bb5c52012-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 Lattner230cdab2012-01-26 00:42:34 +00002417 switch (getElementType()->getIntegerBitWidth()) {
Craig Topper50bee422012-02-05 22:14:15 +00002418 default: llvm_unreachable("Invalid bitwidth for CDS");
Galina Kistanovaa46517e2012-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 Lattner45bb5c52012-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 Lewycky1486ae62012-01-25 03:20:12 +00002436 default:
Craig Topper50bee422012-02-05 22:14:15 +00002437 llvm_unreachable("Accessor can only be used when element is float/double!");
Galina Kistanovaa46517e2012-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 Lattner45bb5c52012-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 Kistanovaa46517e2012-07-13 01:25:27 +00002454 const float *EltPtr = reinterpret_cast<const float *>(getElementPointer(Elt));
2455 return *const_cast<float *>(EltPtr);
Chris Lattner45bb5c52012-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 Kistanovaa46517e2012-07-13 01:25:27 +00002463 const double *EltPtr =
2464 reinterpret_cast<const double *>(getElementPointer(Elt));
2465 return *const_cast<double *>(EltPtr);
Chris Lattner45bb5c52012-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 Kistanovaa46517e2012-07-13 01:25:27 +00002474
Chris Lattner45bb5c52012-01-24 04:43:41 +00002475 return ConstantInt::get(getElementType(), getElementAsInteger(Elt));
2476}
2477
Chris Lattner62339072012-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 Lattner27dd9cf2012-01-23 22:57:10 +00002482
Chris Lattner62339072012-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 Kistanovaa46517e2012-07-13 01:25:27 +00002488
Chris Lattner62339072012-01-24 09:01:07 +00002489 StringRef Str = getAsString();
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002490
Chris Lattner62339072012-01-24 09:01:07 +00002491 // The last value must be nul.
2492 if (Str.back() != 0) return false;
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002493
Chris Lattner62339072012-01-24 09:01:07 +00002494 // Other elements must be non-nul.
2495 return Str.drop_back().find(0) == StringRef::npos;
2496}
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002497
Chris Lattnere150e2d2012-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 Kistanovaa46517e2012-07-13 01:25:27 +00002502
Chris Lattnere150e2d2012-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 Kistanovaa46517e2012-07-13 01:25:27 +00002508
Chris Lattnere150e2d2012-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 Lattner04e3b1e2010-03-30 20:48:48 +00002512
Chris Lattner5cbade92005-10-03 21:58:36 +00002513//===----------------------------------------------------------------------===//
2514// replaceUsesOfWithOnConstant implementations
2515
Chris Lattner54984052007-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 Lattner2ee11ec2009-10-28 00:01:44 +00002526///
Chris Lattner5cbade92005-10-03 21:58:36 +00002527void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattnerd0ff1ad2005-10-04 18:13:04 +00002528 Use *U) {
Owen Anderson1fd70962009-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 Lattner1afcace2011-07-09 17:41:24 +00002532 LLVMContextImpl *pImpl = getType()->getContext().pImpl;
Owen Anderson1fd70962009-07-28 18:32:17 +00002533
Talin2cb395e2012-02-05 20:54:10 +00002534 SmallVector<Constant*, 8> Values;
2535 LLVMContextImpl::ArrayConstantsTy::LookupKey Lookup;
2536 Lookup.first = cast<ArrayType>(getType());
Owen Anderson1fd70962009-07-28 18:32:17 +00002537 Values.reserve(getNumOperands()); // Build replacement array.
2538
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002539 // Fill values with the modified operands of the constant array. Also,
Owen Anderson1fd70962009-07-28 18:32:17 +00002540 // compute whether this turns into an all-zeros array.
Owen Anderson1fd70962009-07-28 18:32:17 +00002541 unsigned NumUpdated = 0;
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002542
Chris Lattnere150e2d2012-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 Anderson1fd70962009-07-28 18:32:17 +00002550 }
Chris Lattnere150e2d2012-01-26 02:31:22 +00002551 Values.push_back(Val);
Talin2cb395e2012-02-05 20:54:10 +00002552 AllSame &= Val == ToC;
Owen Anderson1fd70962009-07-28 18:32:17 +00002553 }
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002554
Owen Anderson1fd70962009-07-28 18:32:17 +00002555 Constant *Replacement = 0;
Chris Lattnere150e2d2012-01-26 02:31:22 +00002556 if (AllSame && ToC->isNullValue()) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002557 Replacement = ConstantAggregateZero::get(getType());
Chris Lattnere150e2d2012-01-26 02:31:22 +00002558 } else if (AllSame && isa<UndefValue>(ToC)) {
2559 Replacement = UndefValue::get(getType());
Owen Anderson1fd70962009-07-28 18:32:17 +00002560 } else {
2561 // Check to see if we have this array type already.
Talin2cb395e2012-02-05 20:54:10 +00002562 Lookup.second = makeArrayRef(Values);
Owen Anderson1fd70962009-07-28 18:32:17 +00002563 LLVMContextImpl::ArrayConstantsTy::MapTy::iterator I =
Talin2cb395e2012-02-05 20:54:10 +00002564 pImpl->ArrayConstants.find(Lookup);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002565
Talin2cb395e2012-02-05 20:54:10 +00002566 if (I != pImpl->ArrayConstants.map_end()) {
2567 Replacement = I->first;
Owen Anderson1fd70962009-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!
Talin2cb395e2012-02-05 20:54:10 +00002573 pImpl->ArrayConstants.remove(this);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002574
Owen Anderson1fd70962009-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 }
Talin2cb395e2012-02-05 20:54:10 +00002587 pImpl->ArrayConstants.insert(this);
Owen Anderson1fd70962009-07-28 18:32:17 +00002588 return;
2589 }
2590 }
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002591
Chris Lattnercea141f2005-10-03 22:51:37 +00002592 // Otherwise, I do need to replace this with an existing value.
Chris Lattner5cbade92005-10-03 21:58:36 +00002593 assert(Replacement != this && "I didn't contain From!");
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002594
Chris Lattnerd0ff1ad2005-10-04 18:13:04 +00002595 // Everyone using this now uses the replacement.
Chris Lattner678f9e02011-07-15 06:18:52 +00002596 replaceAllUsesWith(Replacement);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002597
Chris Lattner5cbade92005-10-03 21:58:36 +00002598 // Delete the old constant!
2599 destroyConstant();
2600}
2601
2602void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattnerd0ff1ad2005-10-04 18:13:04 +00002603 Use *U) {
Owen Anderson8fa33382009-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
Talin2cb395e2012-02-05 20:54:10 +00002610 SmallVector<Constant*, 8> Values;
2611 LLVMContextImpl::StructConstantsTy::LookupKey Lookup;
2612 Lookup.first = cast<StructType>(getType());
Owen Anderson8fa33382009-07-27 22:29:26 +00002613 Values.reserve(getNumOperands()); // Build replacement struct.
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002614
2615 // Fill values with the modified operands of the constant struct. Also,
Owen Anderson8fa33382009-07-27 22:29:26 +00002616 // compute whether this turns into an all-zeros struct.
2617 bool isAllZeros = false;
Chris Lattnere150e2d2012-01-26 02:31:22 +00002618 bool isAllUndef = false;
2619 if (ToC->isNullValue()) {
Owen Anderson8fa33382009-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 Lattnere150e2d2012-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 Anderson8fa33382009-07-27 22:29:26 +00002636 }
2637 Values[OperandToUpdate] = ToC;
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002638
Chris Lattner1afcace2011-07-09 17:41:24 +00002639 LLVMContextImpl *pImpl = getContext().pImpl;
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002640
Owen Anderson8fa33382009-07-27 22:29:26 +00002641 Constant *Replacement = 0;
2642 if (isAllZeros) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002643 Replacement = ConstantAggregateZero::get(getType());
Chris Lattnere150e2d2012-01-26 02:31:22 +00002644 } else if (isAllUndef) {
2645 Replacement = UndefValue::get(getType());
Owen Anderson8fa33382009-07-27 22:29:26 +00002646 } else {
Chris Lattner93604b62010-07-17 06:13:52 +00002647 // Check to see if we have this struct type already.
Talin2cb395e2012-02-05 20:54:10 +00002648 Lookup.second = makeArrayRef(Values);
Owen Anderson8fa33382009-07-27 22:29:26 +00002649 LLVMContextImpl::StructConstantsTy::MapTy::iterator I =
Talin2cb395e2012-02-05 20:54:10 +00002650 pImpl->StructConstants.find(Lookup);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002651
Talin2cb395e2012-02-05 20:54:10 +00002652 if (I != pImpl->StructConstants.map_end()) {
2653 Replacement = I->first;
Owen Anderson8fa33382009-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!
Talin2cb395e2012-02-05 20:54:10 +00002659 pImpl->StructConstants.remove(this);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002660
Owen Anderson8fa33382009-07-27 22:29:26 +00002661 // Update to the new value.
2662 setOperand(OperandToUpdate, ToC);
Talin2cb395e2012-02-05 20:54:10 +00002663 pImpl->StructConstants.insert(this);
Owen Anderson8fa33382009-07-27 22:29:26 +00002664 return;
2665 }
2666 }
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002667
Owen Anderson8fa33382009-07-27 22:29:26 +00002668 assert(Replacement != this && "I didn't contain From!");
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002669
Chris Lattnerd0ff1ad2005-10-04 18:13:04 +00002670 // Everyone using this now uses the replacement.
Chris Lattner678f9e02011-07-15 06:18:52 +00002671 replaceAllUsesWith(Replacement);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002672
Chris Lattner5cbade92005-10-03 21:58:36 +00002673 // Delete the old constant!
2674 destroyConstant();
2675}
2676
Reid Spencer9d6565a2007-02-15 02:26:10 +00002677void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattnerd0ff1ad2005-10-04 18:13:04 +00002678 Use *U) {
Chris Lattner5cbade92005-10-03 21:58:36 +00002679 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002680
Chris Lattnera7c69882012-01-26 20:40:56 +00002681 SmallVector<Constant*, 8> Values;
Chris Lattner5cbade92005-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 Kistanovaa46517e2012-07-13 01:25:27 +00002688
Jay Foada0c13842011-06-22 09:10:19 +00002689 Constant *Replacement = get(Values);
Chris Lattner5cbade92005-10-03 21:58:36 +00002690 assert(Replacement != this && "I didn't contain From!");
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002691
Chris Lattnerd0ff1ad2005-10-04 18:13:04 +00002692 // Everyone using this now uses the replacement.
Chris Lattner678f9e02011-07-15 06:18:52 +00002693 replaceAllUsesWith(Replacement);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002694
Chris Lattner5cbade92005-10-03 21:58:36 +00002695 // Delete the old constant!
2696 destroyConstant();
2697}
2698
2699void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
Chris Lattnerd0ff1ad2005-10-04 18:13:04 +00002700 Use *U) {
Chris Lattner5cbade92005-10-03 21:58:36 +00002701 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2702 Constant *To = cast<Constant>(ToV);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002703
Chris Lattner1a8def62012-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 Lattner5cbade92005-10-03 21:58:36 +00002708 }
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002709
Chris Lattner1a8def62012-01-26 20:37:11 +00002710 Constant *Replacement = getWithOperands(NewOps);
Chris Lattner5cbade92005-10-03 21:58:36 +00002711 assert(Replacement != this && "I didn't contain From!");
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002712
Chris Lattnerd0ff1ad2005-10-04 18:13:04 +00002713 // Everyone using this now uses the replacement.
Chris Lattner678f9e02011-07-15 06:18:52 +00002714 replaceAllUsesWith(Replacement);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002715
Chris Lattner5cbade92005-10-03 21:58:36 +00002716 // Delete the old constant!
2717 destroyConstant();
Matthijs Kooijman10b9de62008-07-03 07:46:41 +00002718}
James Molloyb9478c22012-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}