blob: 1abb65643559ad966ce0e10e17494c77f71a37e0 [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
David Tweedec7eb552013-03-18 11:54:44 +000050 // Equivalent for a vector of -0.0's.
51 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
52 if (ConstantFP *SplatCFP = dyn_cast_or_null<ConstantFP>(CV->getSplatValue()))
53 if (SplatCFP && SplatCFP->isZero() && SplatCFP->isNegative())
54 return true;
55
David Tweed974cdfb2013-03-19 10:16:40 +000056 // We've already handled true FP case; any other FP vectors can't represent -0.0.
57 if (getType()->isFPOrFPVectorTy())
58 return false;
David Tweedec7eb552013-03-18 11:54:44 +000059
Chris Lattnerb4473872011-07-15 05:58:04 +000060 // Otherwise, just use +0.0.
61 return isNullValue();
62}
63
Shuxin Yangc3d6de22013-01-09 00:53:25 +000064// Return true iff this constant is positive zero (floating point), negative
65// zero (floating point), or a null value.
Shuxin Yang935e35d2013-01-09 00:13:41 +000066bool Constant::isZeroValue() const {
67 // Floating point values have an explicit -0.0 value.
68 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
69 return CFP->isZero();
70
71 // Otherwise, just use +0.0.
72 return isNullValue();
73}
74
Chris Lattner032c6eb2011-07-15 06:14:08 +000075bool Constant::isNullValue() const {
76 // 0 is null.
77 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
78 return CI->isZero();
Galina Kistanovaa46517e2012-07-13 01:25:27 +000079
Chris Lattner032c6eb2011-07-15 06:14:08 +000080 // +0.0 is null.
81 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
82 return CFP->isZero() && !CFP->isNegative();
83
84 // constant zero is zero for aggregates and cpnull is null for pointers.
85 return isa<ConstantAggregateZero>(this) || isa<ConstantPointerNull>(this);
86}
87
Nadav Rotem4c7c0f22011-08-24 20:18:38 +000088bool Constant::isAllOnesValue() const {
89 // Check for -1 integers
90 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
91 return CI->isMinusOne();
92
93 // Check for FP which are bitcasted from -1 integers
94 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
95 return CFP->getValueAPF().bitcastToAPInt().isAllOnesValue();
96
Benjamin Kramerb518cae2011-11-14 19:12:20 +000097 // Check for constant vectors which are splats of -1 values.
Nadav Rotem4c7c0f22011-08-24 20:18:38 +000098 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
Benjamin Kramerb518cae2011-11-14 19:12:20 +000099 if (Constant *Splat = CV->getSplatValue())
100 return Splat->isAllOnesValue();
Nadav Rotem4c7c0f22011-08-24 20:18:38 +0000101
Chris Lattnere150e2d2012-01-26 02:31:22 +0000102 // Check for constant vectors which are splats of -1 values.
103 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
104 if (Constant *Splat = CV->getSplatValue())
105 return Splat->isAllOnesValue();
106
Nadav Rotem4c7c0f22011-08-24 20:18:38 +0000107 return false;
108}
Benjamin Kramerb518cae2011-11-14 19:12:20 +0000109
Owen Andersona7235ea2009-07-31 20:28:14 +0000110// Constructor to create a '0' constant of arbitrary type...
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000111Constant *Constant::getNullValue(Type *Ty) {
Owen Andersona7235ea2009-07-31 20:28:14 +0000112 switch (Ty->getTypeID()) {
113 case Type::IntegerTyID:
114 return ConstantInt::get(Ty, 0);
Dan Gohmance163392011-12-17 00:04:22 +0000115 case Type::HalfTyID:
116 return ConstantFP::get(Ty->getContext(),
117 APFloat::getZero(APFloat::IEEEhalf));
Owen Andersona7235ea2009-07-31 20:28:14 +0000118 case Type::FloatTyID:
Benjamin Kramer98383962010-12-04 14:22:24 +0000119 return ConstantFP::get(Ty->getContext(),
120 APFloat::getZero(APFloat::IEEEsingle));
Owen Andersona7235ea2009-07-31 20:28:14 +0000121 case Type::DoubleTyID:
Benjamin Kramer98383962010-12-04 14:22:24 +0000122 return ConstantFP::get(Ty->getContext(),
123 APFloat::getZero(APFloat::IEEEdouble));
Owen Andersona7235ea2009-07-31 20:28:14 +0000124 case Type::X86_FP80TyID:
Benjamin Kramer98383962010-12-04 14:22:24 +0000125 return ConstantFP::get(Ty->getContext(),
126 APFloat::getZero(APFloat::x87DoubleExtended));
Owen Andersona7235ea2009-07-31 20:28:14 +0000127 case Type::FP128TyID:
128 return ConstantFP::get(Ty->getContext(),
Benjamin Kramer98383962010-12-04 14:22:24 +0000129 APFloat::getZero(APFloat::IEEEquad));
Owen Andersona7235ea2009-07-31 20:28:14 +0000130 case Type::PPC_FP128TyID:
Benjamin Kramer98383962010-12-04 14:22:24 +0000131 return ConstantFP::get(Ty->getContext(),
Tim Northover0a29cb02013-01-22 09:46:31 +0000132 APFloat(APFloat::PPCDoubleDouble,
133 APInt::getNullValue(128)));
Owen Andersona7235ea2009-07-31 20:28:14 +0000134 case Type::PointerTyID:
135 return ConstantPointerNull::get(cast<PointerType>(Ty));
136 case Type::StructTyID:
137 case Type::ArrayTyID:
138 case Type::VectorTyID:
139 return ConstantAggregateZero::get(Ty);
140 default:
141 // Function, Label, or Opaque type?
Craig Topper50bee422012-02-05 22:14:15 +0000142 llvm_unreachable("Cannot create a null constant of that type!");
Owen Andersona7235ea2009-07-31 20:28:14 +0000143 }
144}
145
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000146Constant *Constant::getIntegerValue(Type *Ty, const APInt &V) {
147 Type *ScalarTy = Ty->getScalarType();
Dan Gohman43ee5f72009-08-03 22:07:33 +0000148
149 // Create the base integer constant.
150 Constant *C = ConstantInt::get(Ty->getContext(), V);
151
152 // Convert an integer to a pointer, if necessary.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000153 if (PointerType *PTy = dyn_cast<PointerType>(ScalarTy))
Dan Gohman43ee5f72009-08-03 22:07:33 +0000154 C = ConstantExpr::getIntToPtr(C, PTy);
155
156 // Broadcast a scalar to a vector, if necessary.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000157 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattner3c2c9542012-01-25 05:19:54 +0000158 C = ConstantVector::getSplat(VTy->getNumElements(), C);
Dan Gohman43ee5f72009-08-03 22:07:33 +0000159
160 return C;
161}
162
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000163Constant *Constant::getAllOnesValue(Type *Ty) {
164 if (IntegerType *ITy = dyn_cast<IntegerType>(Ty))
Owen Andersona7235ea2009-07-31 20:28:14 +0000165 return ConstantInt::get(Ty->getContext(),
166 APInt::getAllOnesValue(ITy->getBitWidth()));
Nadav Rotem093399c2011-02-17 21:22:27 +0000167
168 if (Ty->isFloatingPointTy()) {
169 APFloat FL = APFloat::getAllOnesValue(Ty->getPrimitiveSizeInBits(),
170 !Ty->isPPC_FP128Ty());
171 return ConstantFP::get(Ty->getContext(), FL);
172 }
173
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000174 VectorType *VTy = cast<VectorType>(Ty);
Chris Lattner3c2c9542012-01-25 05:19:54 +0000175 return ConstantVector::getSplat(VTy->getNumElements(),
176 getAllOnesValue(VTy->getElementType()));
Owen Andersona7235ea2009-07-31 20:28:14 +0000177}
178
Chris Lattner3d5ed222012-01-25 06:16:32 +0000179/// getAggregateElement - For aggregates (struct/array/vector) return the
180/// constant that corresponds to the specified element if possible, or null if
181/// not. This can return null if the element index is a ConstantExpr, or if
182/// 'this' is a constant expr.
183Constant *Constant::getAggregateElement(unsigned Elt) const {
184 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(this))
185 return Elt < CS->getNumOperands() ? CS->getOperand(Elt) : 0;
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000186
Chris Lattner3d5ed222012-01-25 06:16:32 +0000187 if (const ConstantArray *CA = dyn_cast<ConstantArray>(this))
188 return Elt < CA->getNumOperands() ? CA->getOperand(Elt) : 0;
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000189
Chris Lattner3d5ed222012-01-25 06:16:32 +0000190 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
191 return Elt < CV->getNumOperands() ? CV->getOperand(Elt) : 0;
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000192
Chris Lattner3d5ed222012-01-25 06:16:32 +0000193 if (const ConstantAggregateZero *CAZ =dyn_cast<ConstantAggregateZero>(this))
194 return CAZ->getElementValue(Elt);
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000195
Chris Lattner3d5ed222012-01-25 06:16:32 +0000196 if (const UndefValue *UV = dyn_cast<UndefValue>(this))
197 return UV->getElementValue(Elt);
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000198
Chris Lattner230cdab2012-01-26 00:42:34 +0000199 if (const ConstantDataSequential *CDS =dyn_cast<ConstantDataSequential>(this))
Chris Lattner18c7f802012-02-05 02:29:43 +0000200 return Elt < CDS->getNumElements() ? CDS->getElementAsConstant(Elt) : 0;
Chris Lattner3d5ed222012-01-25 06:16:32 +0000201 return 0;
202}
203
204Constant *Constant::getAggregateElement(Constant *Elt) const {
205 assert(isa<IntegerType>(Elt->getType()) && "Index must be an integer");
206 if (ConstantInt *CI = dyn_cast<ConstantInt>(Elt))
207 return getAggregateElement(CI->getZExtValue());
208 return 0;
209}
210
211
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000212void Constant::destroyConstantImpl() {
213 // When a Constant is destroyed, there may be lingering
Chris Lattnerf5ec48d2001-10-13 06:57:33 +0000214 // references to the constant by other constants in the constant pool. These
Misha Brukmanef6a6a62003-08-21 22:14:26 +0000215 // constants are implicitly dependent on the module that is being deleted,
Chris Lattnerf5ec48d2001-10-13 06:57:33 +0000216 // but they don't know that. Because we only find out when the CPV is
217 // deleted, we must now notify all of our users (that should only be
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000218 // Constants) that they are, in fact, invalid now and should be deleted.
Chris Lattnerf5ec48d2001-10-13 06:57:33 +0000219 //
220 while (!use_empty()) {
221 Value *V = use_back();
222#ifndef NDEBUG // Only in -g mode...
Chris Lattner37f077a2009-08-23 04:02:03 +0000223 if (!isa<Constant>(V)) {
David Greened2e63b72010-01-05 01:29:19 +0000224 dbgs() << "While deleting: " << *this
Chris Lattner37f077a2009-08-23 04:02:03 +0000225 << "\n\nUse still stuck around after Def is destroyed: "
226 << *V << "\n\n";
227 }
Chris Lattnerf5ec48d2001-10-13 06:57:33 +0000228#endif
Vikram S. Adve345e0cf2002-07-14 23:13:17 +0000229 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
Chris Lattner230cdab2012-01-26 00:42:34 +0000230 cast<Constant>(V)->destroyConstant();
Chris Lattnerf5ec48d2001-10-13 06:57:33 +0000231
232 // The constant should remove itself from our use list...
Vikram S. Adve345e0cf2002-07-14 23:13:17 +0000233 assert((use_empty() || use_back() != V) && "Constant not removed!");
Chris Lattnerf5ec48d2001-10-13 06:57:33 +0000234 }
235
236 // Value has no outstanding references it is safe to delete it now...
237 delete this;
Chris Lattner1d87bcf2001-10-01 20:11:19 +0000238}
Chris Lattner00950542001-06-06 20:29:01 +0000239
Chris Lattner35b89fa2006-10-20 00:27:06 +0000240/// canTrap - Return true if evaluation of this constant could trap. This is
241/// true for things like constant expressions that could divide by zero.
242bool Constant::canTrap() const {
243 assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
244 // The only thing that could possibly trap are constant exprs.
245 const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
246 if (!CE) return false;
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000247
248 // ConstantExpr traps if any operands can trap.
Chris Lattner35b89fa2006-10-20 00:27:06 +0000249 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000250 if (CE->getOperand(i)->canTrap())
Chris Lattner35b89fa2006-10-20 00:27:06 +0000251 return true;
252
253 // Otherwise, only specific operations can trap.
254 switch (CE->getOpcode()) {
255 default:
256 return false;
Reid Spencer1628cec2006-10-26 06:15:43 +0000257 case Instruction::UDiv:
258 case Instruction::SDiv:
259 case Instruction::FDiv:
Reid Spencer0a783f72006-11-02 01:53:59 +0000260 case Instruction::URem:
261 case Instruction::SRem:
262 case Instruction::FRem:
Chris Lattner35b89fa2006-10-20 00:27:06 +0000263 // Div and rem can trap if the RHS is not known to be non-zero.
Chris Lattner0eeb9132009-10-28 05:14:34 +0000264 if (!isa<ConstantInt>(CE->getOperand(1)) ||CE->getOperand(1)->isNullValue())
Chris Lattner35b89fa2006-10-20 00:27:06 +0000265 return true;
266 return false;
267 }
268}
269
Hans Wennborg18398582012-11-15 11:40:00 +0000270/// isThreadDependent - Return true if the value can vary between threads.
271bool Constant::isThreadDependent() const {
272 SmallPtrSet<const Constant*, 64> Visited;
273 SmallVector<const Constant*, 64> WorkList;
274 WorkList.push_back(this);
275 Visited.insert(this);
276
277 while (!WorkList.empty()) {
278 const Constant *C = WorkList.pop_back_val();
279
280 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
281 if (GV->isThreadLocal())
282 return true;
283 }
284
285 for (unsigned I = 0, E = C->getNumOperands(); I != E; ++I) {
Hans Wennborgfbeb9562012-11-16 10:33:25 +0000286 const Constant *D = dyn_cast<Constant>(C->getOperand(I));
287 if (!D)
288 continue;
Hans Wennborg18398582012-11-15 11:40:00 +0000289 if (Visited.insert(D))
290 WorkList.push_back(D);
291 }
292 }
293
294 return false;
295}
296
Chris Lattner4a7642e2009-11-01 18:11:50 +0000297/// isConstantUsed - Return true if the constant has users other than constant
298/// exprs and other dangling things.
299bool Constant::isConstantUsed() const {
Gabor Greif60ad7812010-03-25 23:06:16 +0000300 for (const_use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
Chris Lattner4a7642e2009-11-01 18:11:50 +0000301 const Constant *UC = dyn_cast<Constant>(*UI);
302 if (UC == 0 || isa<GlobalValue>(UC))
303 return true;
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000304
Chris Lattner4a7642e2009-11-01 18:11:50 +0000305 if (UC->isConstantUsed())
306 return true;
307 }
308 return false;
309}
310
311
Chris Lattner7cf12c72009-07-22 00:05:44 +0000312
313/// getRelocationInfo - This method classifies the entry according to
314/// whether or not it may generate a relocation entry. This must be
315/// conservative, so if it might codegen to a relocatable entry, it should say
316/// so. The return values are:
317///
Chris Lattner083a1e02009-07-24 03:27:21 +0000318/// NoRelocation: This constant pool entry is guaranteed to never have a
319/// relocation applied to it (because it holds a simple constant like
320/// '4').
321/// LocalRelocation: This entry has relocations, but the entries are
322/// guaranteed to be resolvable by the static linker, so the dynamic
323/// linker will never see them.
324/// GlobalRelocations: This entry may have arbitrary relocations.
Chris Lattner7cf12c72009-07-22 00:05:44 +0000325///
Chandler Carruthc2c50cd2013-01-02 09:10:48 +0000326/// FIXME: This really should not be in IR.
Chris Lattner083a1e02009-07-24 03:27:21 +0000327Constant::PossibleRelocationsTy Constant::getRelocationInfo() const {
328 if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
Chris Lattner7cf12c72009-07-22 00:05:44 +0000329 if (GV->hasLocalLinkage() || GV->hasHiddenVisibility())
Chris Lattner083a1e02009-07-24 03:27:21 +0000330 return LocalRelocation; // Local to this file/library.
331 return GlobalRelocations; // Global reference.
Anton Korobeynikovab267a22009-03-29 17:13:18 +0000332 }
Chris Lattner7cf12c72009-07-22 00:05:44 +0000333
Chris Lattner5d81bef2009-10-28 04:12:16 +0000334 if (const BlockAddress *BA = dyn_cast<BlockAddress>(this))
335 return BA->getFunction()->getRelocationInfo();
336
Chris Lattner5099b312010-01-03 18:09:40 +0000337 // While raw uses of blockaddress need to be relocated, differences between
338 // two of them don't when they are for labels in the same function. This is a
339 // common idiom when creating a table for the indirect goto extension, so we
340 // handle it efficiently here.
341 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(this))
342 if (CE->getOpcode() == Instruction::Sub) {
343 ConstantExpr *LHS = dyn_cast<ConstantExpr>(CE->getOperand(0));
344 ConstantExpr *RHS = dyn_cast<ConstantExpr>(CE->getOperand(1));
345 if (LHS && RHS &&
346 LHS->getOpcode() == Instruction::PtrToInt &&
347 RHS->getOpcode() == Instruction::PtrToInt &&
348 isa<BlockAddress>(LHS->getOperand(0)) &&
349 isa<BlockAddress>(RHS->getOperand(0)) &&
350 cast<BlockAddress>(LHS->getOperand(0))->getFunction() ==
351 cast<BlockAddress>(RHS->getOperand(0))->getFunction())
352 return NoRelocation;
353 }
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000354
Chris Lattner083a1e02009-07-24 03:27:21 +0000355 PossibleRelocationsTy Result = NoRelocation;
Evan Chengafe15812007-03-08 00:59:12 +0000356 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
Chris Lattner0eeb9132009-10-28 05:14:34 +0000357 Result = std::max(Result,
358 cast<Constant>(getOperand(i))->getRelocationInfo());
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000359
Chris Lattner7cf12c72009-07-22 00:05:44 +0000360 return Result;
Evan Chengafe15812007-03-08 00:59:12 +0000361}
362
Chris Lattner13fb0db2011-02-18 04:41:42 +0000363/// removeDeadUsersOfConstant - If the specified constantexpr is dead, remove
364/// it. This involves recursively eliminating any dead users of the
365/// constantexpr.
366static bool removeDeadUsersOfConstant(const Constant *C) {
367 if (isa<GlobalValue>(C)) return false; // Cannot remove this
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000368
Chris Lattner13fb0db2011-02-18 04:41:42 +0000369 while (!C->use_empty()) {
370 const Constant *User = dyn_cast<Constant>(C->use_back());
371 if (!User) return false; // Non-constant usage;
372 if (!removeDeadUsersOfConstant(User))
373 return false; // Constant wasn't dead
374 }
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000375
Chris Lattner13fb0db2011-02-18 04:41:42 +0000376 const_cast<Constant*>(C)->destroyConstant();
377 return true;
378}
379
380
381/// removeDeadConstantUsers - If there are any dead constant users dangling
382/// off of this constant, remove them. This method is useful for clients
383/// that want to check to see if a global is unused, but don't want to deal
384/// with potentially dead constants hanging off of the globals.
385void Constant::removeDeadConstantUsers() const {
386 Value::const_use_iterator I = use_begin(), E = use_end();
387 Value::const_use_iterator LastNonDeadUser = E;
388 while (I != E) {
389 const Constant *User = dyn_cast<Constant>(*I);
390 if (User == 0) {
391 LastNonDeadUser = I;
392 ++I;
393 continue;
394 }
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000395
Chris Lattner13fb0db2011-02-18 04:41:42 +0000396 if (!removeDeadUsersOfConstant(User)) {
397 // If the constant wasn't dead, remember that this was the last live use
398 // and move on to the next constant.
399 LastNonDeadUser = I;
400 ++I;
401 continue;
402 }
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000403
Chris Lattner13fb0db2011-02-18 04:41:42 +0000404 // If the constant was dead, then the iterator is invalidated.
405 if (LastNonDeadUser == E) {
406 I = use_begin();
407 if (I == E) break;
408 } else {
409 I = LastNonDeadUser;
410 ++I;
411 }
412 }
413}
414
415
Chris Lattner86381442008-07-10 00:28:11 +0000416
Chris Lattner00950542001-06-06 20:29:01 +0000417//===----------------------------------------------------------------------===//
Chris Lattner6b6f6ba2007-02-20 06:39:57 +0000418// ConstantInt
Chris Lattner00950542001-06-06 20:29:01 +0000419//===----------------------------------------------------------------------===//
420
David Blaikie2d24e2a2011-12-20 02:50:00 +0000421void ConstantInt::anchor() { }
422
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000423ConstantInt::ConstantInt(IntegerType *Ty, const APInt& V)
Chris Lattnereb41bdd2007-02-20 05:55:46 +0000424 : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
Reid Spencer532d0ce2007-02-26 23:54:03 +0000425 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
Chris Lattner00950542001-06-06 20:29:01 +0000426}
427
Nick Lewyckyd01f50f2011-03-06 03:36:19 +0000428ConstantInt *ConstantInt::getTrue(LLVMContext &Context) {
Owen Anderson5defacc2009-07-31 17:39:07 +0000429 LLVMContextImpl *pImpl = Context.pImpl;
Benjamin Kramerf601d6d2010-11-20 18:43:35 +0000430 if (!pImpl->TheTrueVal)
431 pImpl->TheTrueVal = ConstantInt::get(Type::getInt1Ty(Context), 1);
432 return pImpl->TheTrueVal;
Owen Anderson5defacc2009-07-31 17:39:07 +0000433}
434
Nick Lewyckyd01f50f2011-03-06 03:36:19 +0000435ConstantInt *ConstantInt::getFalse(LLVMContext &Context) {
Owen Anderson5defacc2009-07-31 17:39:07 +0000436 LLVMContextImpl *pImpl = Context.pImpl;
Benjamin Kramerf601d6d2010-11-20 18:43:35 +0000437 if (!pImpl->TheFalseVal)
438 pImpl->TheFalseVal = ConstantInt::get(Type::getInt1Ty(Context), 0);
439 return pImpl->TheFalseVal;
Owen Anderson5defacc2009-07-31 17:39:07 +0000440}
441
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000442Constant *ConstantInt::getTrue(Type *Ty) {
443 VectorType *VTy = dyn_cast<VectorType>(Ty);
Nick Lewyckyd01f50f2011-03-06 03:36:19 +0000444 if (!VTy) {
445 assert(Ty->isIntegerTy(1) && "True must be i1 or vector of i1.");
446 return ConstantInt::getTrue(Ty->getContext());
447 }
448 assert(VTy->getElementType()->isIntegerTy(1) &&
449 "True must be vector of i1 or i1.");
Chris Lattner3c2c9542012-01-25 05:19:54 +0000450 return ConstantVector::getSplat(VTy->getNumElements(),
451 ConstantInt::getTrue(Ty->getContext()));
Nick Lewyckyd01f50f2011-03-06 03:36:19 +0000452}
453
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000454Constant *ConstantInt::getFalse(Type *Ty) {
455 VectorType *VTy = dyn_cast<VectorType>(Ty);
Nick Lewyckyd01f50f2011-03-06 03:36:19 +0000456 if (!VTy) {
457 assert(Ty->isIntegerTy(1) && "False must be i1 or vector of i1.");
458 return ConstantInt::getFalse(Ty->getContext());
459 }
460 assert(VTy->getElementType()->isIntegerTy(1) &&
461 "False must be vector of i1 or i1.");
Chris Lattner3c2c9542012-01-25 05:19:54 +0000462 return ConstantVector::getSplat(VTy->getNumElements(),
463 ConstantInt::getFalse(Ty->getContext()));
Nick Lewyckyd01f50f2011-03-06 03:36:19 +0000464}
465
Owen Anderson5defacc2009-07-31 17:39:07 +0000466
Owen Andersoneed707b2009-07-24 23:12:02 +0000467// Get a ConstantInt from an APInt. Note that the value stored in the DenseMap
468// as the key, is a DenseMapAPIntKeyInfo::KeyTy which has provided the
469// operator== and operator!= to ensure that the DenseMap doesn't attempt to
470// compare APInt's of different widths, which would violate an APInt class
471// invariant which generates an assertion.
Nick Lewyckyd01f50f2011-03-06 03:36:19 +0000472ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt &V) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000473 // Get the corresponding integer type for the bit width of the value.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000474 IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
Owen Andersoneed707b2009-07-24 23:12:02 +0000475 // get an existing value or the insertion position
476 DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
Owen Andersoneed707b2009-07-24 23:12:02 +0000477 ConstantInt *&Slot = Context.pImpl->IntConstants[Key];
Owen Anderson59d5aac2009-10-19 20:11:52 +0000478 if (!Slot) Slot = new ConstantInt(ITy, V);
479 return Slot;
Owen Andersoneed707b2009-07-24 23:12:02 +0000480}
481
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000482Constant *ConstantInt::get(Type *Ty, uint64_t V, bool isSigned) {
Nick Lewyckyd01f50f2011-03-06 03:36:19 +0000483 Constant *C = get(cast<IntegerType>(Ty->getScalarType()), V, isSigned);
Owen Andersoneed707b2009-07-24 23:12:02 +0000484
485 // For vectors, broadcast the value.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000486 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattner3c2c9542012-01-25 05:19:54 +0000487 return ConstantVector::getSplat(VTy->getNumElements(), C);
Owen Andersoneed707b2009-07-24 23:12:02 +0000488
489 return C;
490}
491
Chris Lattnera78fa8c2012-01-27 03:08:05 +0000492ConstantInt *ConstantInt::get(IntegerType *Ty, uint64_t V,
Owen Andersoneed707b2009-07-24 23:12:02 +0000493 bool isSigned) {
494 return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned));
495}
496
Chris Lattnera78fa8c2012-01-27 03:08:05 +0000497ConstantInt *ConstantInt::getSigned(IntegerType *Ty, int64_t V) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000498 return get(Ty, V, true);
499}
500
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000501Constant *ConstantInt::getSigned(Type *Ty, int64_t V) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000502 return get(Ty, V, true);
503}
504
Chris Lattnera78fa8c2012-01-27 03:08:05 +0000505Constant *ConstantInt::get(Type *Ty, const APInt& V) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000506 ConstantInt *C = get(Ty->getContext(), V);
507 assert(C->getType() == Ty->getScalarType() &&
508 "ConstantInt type doesn't match the type implied by its value!");
509
510 // For vectors, broadcast the value.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000511 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattner3c2c9542012-01-25 05:19:54 +0000512 return ConstantVector::getSplat(VTy->getNumElements(), C);
Owen Andersoneed707b2009-07-24 23:12:02 +0000513
514 return C;
515}
516
Chris Lattnera78fa8c2012-01-27 03:08:05 +0000517ConstantInt *ConstantInt::get(IntegerType* Ty, StringRef Str,
Erick Tryzelaar0e81f662009-08-16 23:36:33 +0000518 uint8_t radix) {
519 return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
520}
521
Chris Lattner6b6f6ba2007-02-20 06:39:57 +0000522//===----------------------------------------------------------------------===//
Chris Lattner9b4ee0c2007-02-20 07:17:17 +0000523// ConstantFP
Chris Lattner6b6f6ba2007-02-20 06:39:57 +0000524//===----------------------------------------------------------------------===//
525
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000526static const fltSemantics *TypeToFloatSemantics(Type *Ty) {
Dan Gohmance163392011-12-17 00:04:22 +0000527 if (Ty->isHalfTy())
528 return &APFloat::IEEEhalf;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000529 if (Ty->isFloatTy())
Rafael Espindola87d1f472009-07-15 17:40:42 +0000530 return &APFloat::IEEEsingle;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000531 if (Ty->isDoubleTy())
Rafael Espindola87d1f472009-07-15 17:40:42 +0000532 return &APFloat::IEEEdouble;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000533 if (Ty->isX86_FP80Ty())
Rafael Espindola87d1f472009-07-15 17:40:42 +0000534 return &APFloat::x87DoubleExtended;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000535 else if (Ty->isFP128Ty())
Rafael Espindola87d1f472009-07-15 17:40:42 +0000536 return &APFloat::IEEEquad;
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000537
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000538 assert(Ty->isPPC_FP128Ty() && "Unknown FP format");
Rafael Espindola87d1f472009-07-15 17:40:42 +0000539 return &APFloat::PPCDoubleDouble;
540}
541
David Blaikie2d24e2a2011-12-20 02:50:00 +0000542void ConstantFP::anchor() { }
543
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000544/// get() - This returns a constant fp for the specified value in the
545/// specified type. This should only be used for simple constant values like
546/// 2.0/1.0 etc, that are known-valid both as double and as the target format.
Chris Lattnera78fa8c2012-01-27 03:08:05 +0000547Constant *ConstantFP::get(Type *Ty, double V) {
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000548 LLVMContext &Context = Ty->getContext();
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000549
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000550 APFloat FV(V);
551 bool ignored;
552 FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
553 APFloat::rmNearestTiesToEven, &ignored);
554 Constant *C = get(Context, FV);
555
556 // For vectors, broadcast the value.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000557 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattner3c2c9542012-01-25 05:19:54 +0000558 return ConstantVector::getSplat(VTy->getNumElements(), C);
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000559
560 return C;
561}
562
Erick Tryzelaar0e81f662009-08-16 23:36:33 +0000563
Chris Lattnera78fa8c2012-01-27 03:08:05 +0000564Constant *ConstantFP::get(Type *Ty, StringRef Str) {
Erick Tryzelaar0e81f662009-08-16 23:36:33 +0000565 LLVMContext &Context = Ty->getContext();
566
567 APFloat FV(*TypeToFloatSemantics(Ty->getScalarType()), Str);
568 Constant *C = get(Context, FV);
569
570 // For vectors, broadcast the value.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000571 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattner3c2c9542012-01-25 05:19:54 +0000572 return ConstantVector::getSplat(VTy->getNumElements(), C);
Erick Tryzelaar0e81f662009-08-16 23:36:33 +0000573
574 return C;
575}
576
577
Chris Lattner3c2c9542012-01-25 05:19:54 +0000578ConstantFP *ConstantFP::getNegativeZero(Type *Ty) {
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000579 LLVMContext &Context = Ty->getContext();
Chris Lattner3c2c9542012-01-25 05:19:54 +0000580 APFloat apf = cast<ConstantFP>(Constant::getNullValue(Ty))->getValueAPF();
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000581 apf.changeSign();
582 return get(Context, apf);
583}
584
585
Chris Lattner3c2c9542012-01-25 05:19:54 +0000586Constant *ConstantFP::getZeroValueForNegation(Type *Ty) {
587 Type *ScalarTy = Ty->getScalarType();
588 if (ScalarTy->isFloatingPointTy()) {
589 Constant *C = getNegativeZero(ScalarTy);
590 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
591 return ConstantVector::getSplat(VTy->getNumElements(), C);
592 return C;
593 }
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000594
Owen Andersona7235ea2009-07-31 20:28:14 +0000595 return Constant::getNullValue(Ty);
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000596}
597
598
599// ConstantFP accessors.
600ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
601 DenseMapAPFloatKeyInfo::KeyTy Key(V);
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000602
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000603 LLVMContextImpl* pImpl = Context.pImpl;
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000604
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000605 ConstantFP *&Slot = pImpl->FPConstants[Key];
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000606
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000607 if (!Slot) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000608 Type *Ty;
Dan Gohmance163392011-12-17 00:04:22 +0000609 if (&V.getSemantics() == &APFloat::IEEEhalf)
610 Ty = Type::getHalfTy(Context);
611 else if (&V.getSemantics() == &APFloat::IEEEsingle)
Owen Anderson59d5aac2009-10-19 20:11:52 +0000612 Ty = Type::getFloatTy(Context);
613 else if (&V.getSemantics() == &APFloat::IEEEdouble)
614 Ty = Type::getDoubleTy(Context);
615 else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
616 Ty = Type::getX86_FP80Ty(Context);
617 else if (&V.getSemantics() == &APFloat::IEEEquad)
618 Ty = Type::getFP128Ty(Context);
619 else {
620 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble &&
621 "Unknown FP format");
622 Ty = Type::getPPC_FP128Ty(Context);
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000623 }
Owen Anderson59d5aac2009-10-19 20:11:52 +0000624 Slot = new ConstantFP(Ty, V);
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000625 }
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000626
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000627 return Slot;
628}
629
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000630ConstantFP *ConstantFP::getInfinity(Type *Ty, bool Negative) {
Dan Gohmanf344f7f2009-09-25 23:00:48 +0000631 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty);
632 return ConstantFP::get(Ty->getContext(),
633 APFloat::getInf(Semantics, Negative));
634}
635
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000636ConstantFP::ConstantFP(Type *Ty, const APFloat& V)
Dale Johannesenf04afdb2007-08-30 00:23:21 +0000637 : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
Chris Lattner288e78f2008-04-09 06:38:30 +0000638 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
639 "FP type Mismatch");
Chris Lattner00950542001-06-06 20:29:01 +0000640}
641
Chris Lattner032c6eb2011-07-15 06:14:08 +0000642bool ConstantFP::isExactlyValue(const APFloat &V) const {
Dale Johannesenf04afdb2007-08-30 00:23:21 +0000643 return Val.bitwiseIsEqual(V);
Chris Lattner9b4ee0c2007-02-20 07:17:17 +0000644}
645
Chris Lattner9b4ee0c2007-02-20 07:17:17 +0000646//===----------------------------------------------------------------------===//
Chris Lattnerff2b7f32012-01-24 05:42:11 +0000647// ConstantAggregateZero Implementation
648//===----------------------------------------------------------------------===//
649
650/// getSequentialElement - If this CAZ has array or vector type, return a zero
651/// with the right element type.
Chris Lattner3d5ed222012-01-25 06:16:32 +0000652Constant *ConstantAggregateZero::getSequentialElement() const {
Chris Lattner230cdab2012-01-26 00:42:34 +0000653 return Constant::getNullValue(getType()->getSequentialElementType());
Chris Lattnerff2b7f32012-01-24 05:42:11 +0000654}
655
656/// getStructElement - If this CAZ has struct type, return a zero with the
657/// right element type for the specified element.
Chris Lattner3d5ed222012-01-25 06:16:32 +0000658Constant *ConstantAggregateZero::getStructElement(unsigned Elt) const {
Chris Lattner230cdab2012-01-26 00:42:34 +0000659 return Constant::getNullValue(getType()->getStructElementType(Elt));
Chris Lattnerff2b7f32012-01-24 05:42:11 +0000660}
661
662/// getElementValue - Return a zero of the right value for the specified GEP
663/// index if we can, otherwise return null (e.g. if C is a ConstantExpr).
Chris Lattner3d5ed222012-01-25 06:16:32 +0000664Constant *ConstantAggregateZero::getElementValue(Constant *C) const {
Chris Lattnerff2b7f32012-01-24 05:42:11 +0000665 if (isa<SequentialType>(getType()))
666 return getSequentialElement();
667 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
668}
669
Chris Lattnerdf390282012-01-24 07:54:10 +0000670/// getElementValue - Return a zero of the right value for the specified GEP
671/// index.
Chris Lattner3d5ed222012-01-25 06:16:32 +0000672Constant *ConstantAggregateZero::getElementValue(unsigned Idx) const {
Chris Lattnerdf390282012-01-24 07:54:10 +0000673 if (isa<SequentialType>(getType()))
674 return getSequentialElement();
675 return getStructElement(Idx);
676}
677
678
Chris Lattnerff2b7f32012-01-24 05:42:11 +0000679//===----------------------------------------------------------------------===//
680// UndefValue Implementation
681//===----------------------------------------------------------------------===//
682
683/// getSequentialElement - If this undef has array or vector type, return an
684/// undef with the right element type.
Chris Lattner3d5ed222012-01-25 06:16:32 +0000685UndefValue *UndefValue::getSequentialElement() const {
Chris Lattner230cdab2012-01-26 00:42:34 +0000686 return UndefValue::get(getType()->getSequentialElementType());
Chris Lattnerff2b7f32012-01-24 05:42:11 +0000687}
688
689/// getStructElement - If this undef has struct type, return a zero with the
690/// right element type for the specified element.
Chris Lattner3d5ed222012-01-25 06:16:32 +0000691UndefValue *UndefValue::getStructElement(unsigned Elt) const {
Chris Lattner230cdab2012-01-26 00:42:34 +0000692 return UndefValue::get(getType()->getStructElementType(Elt));
Chris Lattnerff2b7f32012-01-24 05:42:11 +0000693}
694
695/// getElementValue - Return an undef of the right value for the specified GEP
696/// index if we can, otherwise return null (e.g. if C is a ConstantExpr).
Chris Lattner3d5ed222012-01-25 06:16:32 +0000697UndefValue *UndefValue::getElementValue(Constant *C) const {
Chris Lattnerff2b7f32012-01-24 05:42:11 +0000698 if (isa<SequentialType>(getType()))
699 return getSequentialElement();
700 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
701}
702
Chris Lattnerdf390282012-01-24 07:54:10 +0000703/// getElementValue - Return an undef of the right value for the specified GEP
704/// index.
Chris Lattner3d5ed222012-01-25 06:16:32 +0000705UndefValue *UndefValue::getElementValue(unsigned Idx) const {
Chris Lattnerdf390282012-01-24 07:54:10 +0000706 if (isa<SequentialType>(getType()))
707 return getSequentialElement();
708 return getStructElement(Idx);
709}
710
711
Chris Lattnerff2b7f32012-01-24 05:42:11 +0000712
713//===----------------------------------------------------------------------===//
Chris Lattner9b4ee0c2007-02-20 07:17:17 +0000714// ConstantXXX Classes
715//===----------------------------------------------------------------------===//
716
Chris Lattner18c7f802012-02-05 02:29:43 +0000717template <typename ItTy, typename EltTy>
718static bool rangeOnlyContains(ItTy Start, ItTy End, EltTy Elt) {
719 for (; Start != End; ++Start)
720 if (*Start != Elt)
721 return false;
722 return true;
723}
Chris Lattner9b4ee0c2007-02-20 07:17:17 +0000724
Jay Foad166579e2011-07-25 10:14:44 +0000725ConstantArray::ConstantArray(ArrayType *T, ArrayRef<Constant *> V)
Gabor Greifefe65362008-05-10 08:32:32 +0000726 : Constant(T, ConstantArrayVal,
727 OperandTraits<ConstantArray>::op_end(this) - V.size(),
728 V.size()) {
Alkis Evlogimenose0de1d62004-09-15 02:32:15 +0000729 assert(V.size() == T->getNumElements() &&
730 "Invalid initializer vector for constant array");
Jay Foad166579e2011-07-25 10:14:44 +0000731 for (unsigned i = 0, e = V.size(); i != e; ++i)
732 assert(V[i]->getType() == T->getElementType() &&
Alkis Evlogimenoscad90ad2004-09-10 04:16:59 +0000733 "Initializer for array element doesn't match array element type!");
Jay Foad166579e2011-07-25 10:14:44 +0000734 std::copy(V.begin(), V.end(), op_begin());
Chris Lattner00950542001-06-06 20:29:01 +0000735}
736
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000737Constant *ConstantArray::get(ArrayType *Ty, ArrayRef<Constant*> V) {
Chris Lattner18c7f802012-02-05 02:29:43 +0000738 // Empty arrays are canonicalized to ConstantAggregateZero.
739 if (V.empty())
740 return ConstantAggregateZero::get(Ty);
741
Jeffrey Yasskin1fb613c2009-09-30 21:08:08 +0000742 for (unsigned i = 0, e = V.size(); i != e; ++i) {
743 assert(V[i]->getType() == Ty->getElementType() &&
744 "Wrong type in array element initializer");
745 }
Owen Anderson1fd70962009-07-28 18:32:17 +0000746 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000747
Chris Lattner18c7f802012-02-05 02:29:43 +0000748 // If this is an all-zero array, return a ConstantAggregateZero object. If
749 // all undef, return an UndefValue, if "all simple", then return a
750 // ConstantDataArray.
751 Constant *C = V[0];
752 if (isa<UndefValue>(C) && rangeOnlyContains(V.begin(), V.end(), C))
753 return UndefValue::get(Ty);
Chris Lattnere150e2d2012-01-26 02:31:22 +0000754
Chris Lattner18c7f802012-02-05 02:29:43 +0000755 if (C->isNullValue() && rangeOnlyContains(V.begin(), V.end(), C))
756 return ConstantAggregateZero::get(Ty);
757
758 // Check to see if all of the elements are ConstantFP or ConstantInt and if
759 // the element type is compatible with ConstantDataVector. If so, use it.
760 if (ConstantDataSequential::isElementTypeCompatible(C->getType())) {
761 // We speculatively build the elements here even if it turns out that there
762 // is a constantexpr or something else weird in the array, since it is so
763 // uncommon for that to happen.
764 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
765 if (CI->getType()->isIntegerTy(8)) {
766 SmallVector<uint8_t, 16> Elts;
767 for (unsigned i = 0, e = V.size(); i != e; ++i)
768 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
769 Elts.push_back(CI->getZExtValue());
770 else
771 break;
772 if (Elts.size() == V.size())
773 return ConstantDataArray::get(C->getContext(), Elts);
774 } else if (CI->getType()->isIntegerTy(16)) {
775 SmallVector<uint16_t, 16> Elts;
776 for (unsigned i = 0, e = V.size(); i != e; ++i)
777 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
778 Elts.push_back(CI->getZExtValue());
779 else
780 break;
781 if (Elts.size() == V.size())
782 return ConstantDataArray::get(C->getContext(), Elts);
783 } else if (CI->getType()->isIntegerTy(32)) {
784 SmallVector<uint32_t, 16> Elts;
785 for (unsigned i = 0, e = V.size(); i != e; ++i)
786 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
787 Elts.push_back(CI->getZExtValue());
788 else
789 break;
790 if (Elts.size() == V.size())
791 return ConstantDataArray::get(C->getContext(), Elts);
792 } else if (CI->getType()->isIntegerTy(64)) {
793 SmallVector<uint64_t, 16> Elts;
794 for (unsigned i = 0, e = V.size(); i != e; ++i)
795 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
796 Elts.push_back(CI->getZExtValue());
797 else
798 break;
799 if (Elts.size() == V.size())
800 return ConstantDataArray::get(C->getContext(), Elts);
801 }
802 }
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000803
Chris Lattner18c7f802012-02-05 02:29:43 +0000804 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
805 if (CFP->getType()->isFloatTy()) {
806 SmallVector<float, 16> Elts;
807 for (unsigned i = 0, e = V.size(); i != e; ++i)
808 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V[i]))
809 Elts.push_back(CFP->getValueAPF().convertToFloat());
810 else
811 break;
812 if (Elts.size() == V.size())
813 return ConstantDataArray::get(C->getContext(), Elts);
814 } else if (CFP->getType()->isDoubleTy()) {
815 SmallVector<double, 16> Elts;
816 for (unsigned i = 0, e = V.size(); i != e; ++i)
817 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V[i]))
818 Elts.push_back(CFP->getValueAPF().convertToDouble());
819 else
820 break;
821 if (Elts.size() == V.size())
822 return ConstantDataArray::get(C->getContext(), Elts);
823 }
824 }
Owen Anderson1fd70962009-07-28 18:32:17 +0000825 }
Chris Lattnere150e2d2012-01-26 02:31:22 +0000826
Chris Lattner18c7f802012-02-05 02:29:43 +0000827 // Otherwise, we really do want to create a ConstantArray.
Chris Lattnere150e2d2012-01-26 02:31:22 +0000828 return pImpl->ArrayConstants.getOrCreate(Ty, V);
Owen Anderson1fd70962009-07-28 18:32:17 +0000829}
830
Chris Lattnerb065b062011-06-20 04:01:31 +0000831/// getTypeForElements - Return an anonymous struct type to use for a constant
832/// with the specified set of elements. The list must not be empty.
833StructType *ConstantStruct::getTypeForElements(LLVMContext &Context,
834 ArrayRef<Constant*> V,
835 bool Packed) {
Bill Wendlinga7a3f042012-02-07 01:27:51 +0000836 unsigned VecSize = V.size();
837 SmallVector<Type*, 16> EltTypes(VecSize);
838 for (unsigned i = 0; i != VecSize; ++i)
839 EltTypes[i] = V[i]->getType();
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000840
Chris Lattnerb065b062011-06-20 04:01:31 +0000841 return StructType::get(Context, EltTypes, Packed);
842}
843
844
845StructType *ConstantStruct::getTypeForElements(ArrayRef<Constant*> V,
846 bool Packed) {
847 assert(!V.empty() &&
848 "ConstantStruct::getTypeForElements cannot be called on empty list");
849 return getTypeForElements(V[0]->getContext(), V, Packed);
850}
851
852
Jay Foad166579e2011-07-25 10:14:44 +0000853ConstantStruct::ConstantStruct(StructType *T, ArrayRef<Constant *> V)
Gabor Greifefe65362008-05-10 08:32:32 +0000854 : Constant(T, ConstantStructVal,
855 OperandTraits<ConstantStruct>::op_end(this) - V.size(),
856 V.size()) {
Chris Lattnerf4ef8db2011-08-07 04:18:48 +0000857 assert(V.size() == T->getNumElements() &&
Vikram S. Adve345e0cf2002-07-14 23:13:17 +0000858 "Invalid initializer vector for constant structure");
Jay Foad166579e2011-07-25 10:14:44 +0000859 for (unsigned i = 0, e = V.size(); i != e; ++i)
860 assert((T->isOpaque() || V[i]->getType() == T->getElementType(i)) &&
Chris Lattnerb8438892003-06-02 17:42:47 +0000861 "Initializer for struct element doesn't match struct element type!");
Jay Foad166579e2011-07-25 10:14:44 +0000862 std::copy(V.begin(), V.end(), op_begin());
Chris Lattner00950542001-06-06 20:29:01 +0000863}
864
Owen Anderson8fa33382009-07-27 22:29:26 +0000865// ConstantStruct accessors.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000866Constant *ConstantStruct::get(StructType *ST, ArrayRef<Constant*> V) {
Chris Lattner1afcace2011-07-09 17:41:24 +0000867 assert((ST->isOpaque() || ST->getNumElements() == V.size()) &&
868 "Incorrect # elements specified to ConstantStruct::get");
Chris Lattnere150e2d2012-01-26 02:31:22 +0000869
870 // Create a ConstantAggregateZero value if all elements are zeros.
871 bool isZero = true;
872 bool isUndef = false;
873
874 if (!V.empty()) {
875 isUndef = isa<UndefValue>(V[0]);
876 isZero = V[0]->isNullValue();
877 if (isUndef || isZero) {
878 for (unsigned i = 0, e = V.size(); i != e; ++i) {
879 if (!V[i]->isNullValue())
880 isZero = false;
881 if (!isa<UndefValue>(V[i]))
882 isUndef = false;
883 }
884 }
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000885 }
Chris Lattnere150e2d2012-01-26 02:31:22 +0000886 if (isZero)
887 return ConstantAggregateZero::get(ST);
888 if (isUndef)
889 return UndefValue::get(ST);
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000890
Chris Lattnere150e2d2012-01-26 02:31:22 +0000891 return ST->getContext().pImpl->StructConstants.getOrCreate(ST, V);
Owen Anderson8fa33382009-07-27 22:29:26 +0000892}
893
Chris Lattnerf4ef8db2011-08-07 04:18:48 +0000894Constant *ConstantStruct::get(StructType *T, ...) {
Talin41ee4e52011-02-28 23:53:27 +0000895 va_list ap;
Chris Lattnerb065b062011-06-20 04:01:31 +0000896 SmallVector<Constant*, 8> Values;
897 va_start(ap, T);
898 while (Constant *Val = va_arg(ap, llvm::Constant*))
Talin41ee4e52011-02-28 23:53:27 +0000899 Values.push_back(Val);
Talinbdcd7662011-03-01 18:00:49 +0000900 va_end(ap);
Chris Lattnerb065b062011-06-20 04:01:31 +0000901 return get(T, Values);
Talin41ee4e52011-02-28 23:53:27 +0000902}
903
Jay Foad166579e2011-07-25 10:14:44 +0000904ConstantVector::ConstantVector(VectorType *T, ArrayRef<Constant *> V)
Gabor Greifefe65362008-05-10 08:32:32 +0000905 : Constant(T, ConstantVectorVal,
906 OperandTraits<ConstantVector>::op_end(this) - V.size(),
907 V.size()) {
Jay Foad166579e2011-07-25 10:14:44 +0000908 for (size_t i = 0, e = V.size(); i != e; i++)
909 assert(V[i]->getType() == T->getElementType() &&
Dan Gohmanfa73ea22007-05-24 14:36:04 +0000910 "Initializer for vector element doesn't match vector element type!");
Jay Foad166579e2011-07-25 10:14:44 +0000911 std::copy(V.begin(), V.end(), op_begin());
Brian Gaeke715c90b2004-08-20 06:00:58 +0000912}
913
Owen Andersonaf7ec972009-07-28 21:19:26 +0000914// ConstantVector accessors.
Jay Foada0c13842011-06-22 09:10:19 +0000915Constant *ConstantVector::get(ArrayRef<Constant*> V) {
Jay Foad9afc5272011-01-27 14:44:55 +0000916 assert(!V.empty() && "Vectors can't be empty");
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000917 VectorType *T = VectorType::get(V.front()->getType(), V.size());
Chris Lattner2ca5c862011-02-15 00:14:00 +0000918 LLVMContextImpl *pImpl = T->getContext().pImpl;
Jay Foad9afc5272011-01-27 14:44:55 +0000919
Chris Lattner2ca5c862011-02-15 00:14:00 +0000920 // If this is an all-undef or all-zero vector, return a
Owen Andersonaf7ec972009-07-28 21:19:26 +0000921 // ConstantAggregateZero or UndefValue.
922 Constant *C = V[0];
923 bool isZero = C->isNullValue();
924 bool isUndef = isa<UndefValue>(C);
925
926 if (isZero || isUndef) {
927 for (unsigned i = 1, e = V.size(); i != e; ++i)
928 if (V[i] != C) {
929 isZero = isUndef = false;
930 break;
931 }
932 }
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000933
Owen Andersonaf7ec972009-07-28 21:19:26 +0000934 if (isZero)
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000935 return ConstantAggregateZero::get(T);
Owen Andersonaf7ec972009-07-28 21:19:26 +0000936 if (isUndef)
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000937 return UndefValue::get(T);
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000938
Chris Lattner36c744f2012-01-30 06:21:21 +0000939 // Check to see if all of the elements are ConstantFP or ConstantInt and if
940 // the element type is compatible with ConstantDataVector. If so, use it.
Chris Lattner18c7f802012-02-05 02:29:43 +0000941 if (ConstantDataSequential::isElementTypeCompatible(C->getType())) {
Chris Lattner36c744f2012-01-30 06:21:21 +0000942 // We speculatively build the elements here even if it turns out that there
943 // is a constantexpr or something else weird in the array, since it is so
944 // uncommon for that to happen.
945 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
946 if (CI->getType()->isIntegerTy(8)) {
947 SmallVector<uint8_t, 16> Elts;
948 for (unsigned i = 0, e = V.size(); i != e; ++i)
949 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
950 Elts.push_back(CI->getZExtValue());
951 else
952 break;
953 if (Elts.size() == V.size())
954 return ConstantDataVector::get(C->getContext(), Elts);
955 } else if (CI->getType()->isIntegerTy(16)) {
956 SmallVector<uint16_t, 16> Elts;
957 for (unsigned i = 0, e = V.size(); i != e; ++i)
958 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
959 Elts.push_back(CI->getZExtValue());
960 else
961 break;
962 if (Elts.size() == V.size())
963 return ConstantDataVector::get(C->getContext(), Elts);
964 } else if (CI->getType()->isIntegerTy(32)) {
965 SmallVector<uint32_t, 16> Elts;
966 for (unsigned i = 0, e = V.size(); i != e; ++i)
967 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
968 Elts.push_back(CI->getZExtValue());
969 else
970 break;
971 if (Elts.size() == V.size())
972 return ConstantDataVector::get(C->getContext(), Elts);
973 } else if (CI->getType()->isIntegerTy(64)) {
974 SmallVector<uint64_t, 16> Elts;
975 for (unsigned i = 0, e = V.size(); i != e; ++i)
976 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
977 Elts.push_back(CI->getZExtValue());
978 else
979 break;
980 if (Elts.size() == V.size())
981 return ConstantDataVector::get(C->getContext(), Elts);
982 }
983 }
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000984
Chris Lattner36c744f2012-01-30 06:21:21 +0000985 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
986 if (CFP->getType()->isFloatTy()) {
987 SmallVector<float, 16> Elts;
988 for (unsigned i = 0, e = V.size(); i != e; ++i)
989 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V[i]))
990 Elts.push_back(CFP->getValueAPF().convertToFloat());
991 else
992 break;
993 if (Elts.size() == V.size())
994 return ConstantDataVector::get(C->getContext(), Elts);
995 } else if (CFP->getType()->isDoubleTy()) {
996 SmallVector<double, 16> Elts;
997 for (unsigned i = 0, e = V.size(); i != e; ++i)
998 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V[i]))
999 Elts.push_back(CFP->getValueAPF().convertToDouble());
1000 else
1001 break;
1002 if (Elts.size() == V.size())
1003 return ConstantDataVector::get(C->getContext(), Elts);
1004 }
1005 }
1006 }
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001007
Chris Lattner36c744f2012-01-30 06:21:21 +00001008 // Otherwise, the element type isn't compatible with ConstantDataVector, or
1009 // the operand list constants a ConstantExpr or something else strange.
Owen Andersonaf7ec972009-07-28 21:19:26 +00001010 return pImpl->VectorConstants.getOrCreate(T, V);
1011}
1012
Chris Lattner3c2c9542012-01-25 05:19:54 +00001013Constant *ConstantVector::getSplat(unsigned NumElts, Constant *V) {
Chris Lattner36c744f2012-01-30 06:21:21 +00001014 // If this splat is compatible with ConstantDataVector, use it instead of
1015 // ConstantVector.
1016 if ((isa<ConstantFP>(V) || isa<ConstantInt>(V)) &&
1017 ConstantDataSequential::isElementTypeCompatible(V->getType()))
1018 return ConstantDataVector::getSplat(NumElts, V);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001019
Chris Lattner3c2c9542012-01-25 05:19:54 +00001020 SmallVector<Constant*, 32> Elts(NumElts, V);
1021 return get(Elts);
1022}
1023
1024
Reid Spencer3da59db2006-11-27 01:05:10 +00001025// Utility function for determining if a ConstantExpr is a CastOp or not. This
1026// can't be inline because we don't want to #include Instruction.h into
1027// Constant.h
1028bool ConstantExpr::isCast() const {
1029 return Instruction::isCast(getOpcode());
1030}
1031
Reid Spencer077d0eb2006-12-04 05:19:50 +00001032bool ConstantExpr::isCompare() const {
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00001033 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
Reid Spencer077d0eb2006-12-04 05:19:50 +00001034}
1035
Dan Gohmane6992f72009-09-10 23:37:55 +00001036bool ConstantExpr::isGEPWithNoNotionalOverIndexing() const {
1037 if (getOpcode() != Instruction::GetElementPtr) return false;
1038
1039 gep_type_iterator GEPI = gep_type_begin(this), E = gep_type_end(this);
Oscar Fuentesee56c422010-08-02 06:00:15 +00001040 User::const_op_iterator OI = llvm::next(this->op_begin());
Dan Gohmane6992f72009-09-10 23:37:55 +00001041
1042 // Skip the first index, as it has no static limit.
1043 ++GEPI;
1044 ++OI;
1045
1046 // The remaining indices must be compile-time known integers within the
1047 // bounds of the corresponding notional static array types.
1048 for (; GEPI != E; ++GEPI, ++OI) {
1049 ConstantInt *CI = dyn_cast<ConstantInt>(*OI);
1050 if (!CI) return false;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001051 if (ArrayType *ATy = dyn_cast<ArrayType>(*GEPI))
Dan Gohmane6992f72009-09-10 23:37:55 +00001052 if (CI->getValue().getActiveBits() > 64 ||
1053 CI->getZExtValue() >= ATy->getNumElements())
1054 return false;
1055 }
1056
1057 // All the indices checked out.
1058 return true;
1059}
1060
Dan Gohman81a0c0b2008-05-31 00:58:22 +00001061bool ConstantExpr::hasIndices() const {
1062 return getOpcode() == Instruction::ExtractValue ||
1063 getOpcode() == Instruction::InsertValue;
1064}
1065
Jay Foadd30aa5a2011-04-13 15:22:40 +00001066ArrayRef<unsigned> ConstantExpr::getIndices() const {
Dan Gohman81a0c0b2008-05-31 00:58:22 +00001067 if (const ExtractValueConstantExpr *EVCE =
1068 dyn_cast<ExtractValueConstantExpr>(this))
1069 return EVCE->Indices;
Dan Gohman1a203572008-06-23 16:39:44 +00001070
1071 return cast<InsertValueConstantExpr>(this)->Indices;
Dan Gohman81a0c0b2008-05-31 00:58:22 +00001072}
1073
Reid Spencer728b6db2006-12-03 05:48:19 +00001074unsigned ConstantExpr::getPredicate() const {
Chris Lattner3e194732011-07-17 06:01:30 +00001075 assert(isCompare());
Chris Lattnerb7daa842007-10-18 16:26:24 +00001076 return ((const CompareConstantExpr*)this)->predicate;
Reid Spencer728b6db2006-12-03 05:48:19 +00001077}
Chris Lattnerf4ba6c72001-10-03 06:12:09 +00001078
Chris Lattner1fe8f6b2006-07-14 19:37:40 +00001079/// getWithOperandReplaced - Return a constant expression identical to this
1080/// one, but with the specified operand set to the specified value.
Reid Spencer3da59db2006-11-27 01:05:10 +00001081Constant *
1082ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
Chris Lattner1fe8f6b2006-07-14 19:37:40 +00001083 assert(Op->getType() == getOperand(OpNo)->getType() &&
1084 "Replacing operand with value of different type!");
Chris Lattnerb88a7fb2006-07-14 22:20:01 +00001085 if (getOperand(OpNo) == Op)
1086 return const_cast<ConstantExpr*>(this);
Chris Lattner1a8def62012-01-26 20:37:11 +00001087
1088 SmallVector<Constant*, 8> NewOps;
1089 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1090 NewOps.push_back(i == OpNo ? Op : getOperand(i));
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001091
Chris Lattner1a8def62012-01-26 20:37:11 +00001092 return getWithOperands(NewOps);
Chris Lattnerb88a7fb2006-07-14 22:20:01 +00001093}
1094
1095/// getWithOperands - This returns the current constant expression with the
Chris Lattner1afcace2011-07-09 17:41:24 +00001096/// operands replaced with the specified values. The specified array must
1097/// have the same number of operands as our current one.
Chris Lattnerb88a7fb2006-07-14 22:20:01 +00001098Constant *ConstantExpr::
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001099getWithOperands(ArrayRef<Constant*> Ops, Type *Ty) const {
Jay Foadb81e4572011-04-13 13:46:01 +00001100 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
Chris Lattner1afcace2011-07-09 17:41:24 +00001101 bool AnyChange = Ty != getType();
1102 for (unsigned i = 0; i != Ops.size(); ++i)
Chris Lattnerb88a7fb2006-07-14 22:20:01 +00001103 AnyChange |= Ops[i] != getOperand(i);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001104
Chris Lattnerb88a7fb2006-07-14 22:20:01 +00001105 if (!AnyChange) // No operands changed, return self.
1106 return const_cast<ConstantExpr*>(this);
1107
1108 switch (getOpcode()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001109 case Instruction::Trunc:
1110 case Instruction::ZExt:
1111 case Instruction::SExt:
1112 case Instruction::FPTrunc:
1113 case Instruction::FPExt:
1114 case Instruction::UIToFP:
1115 case Instruction::SIToFP:
1116 case Instruction::FPToUI:
1117 case Instruction::FPToSI:
1118 case Instruction::PtrToInt:
1119 case Instruction::IntToPtr:
1120 case Instruction::BitCast:
Chris Lattner1afcace2011-07-09 17:41:24 +00001121 return ConstantExpr::getCast(getOpcode(), Ops[0], Ty);
Chris Lattnerb88a7fb2006-07-14 22:20:01 +00001122 case Instruction::Select:
1123 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
1124 case Instruction::InsertElement:
1125 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
1126 case Instruction::ExtractElement:
1127 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
Chris Lattner1a8def62012-01-26 20:37:11 +00001128 case Instruction::InsertValue:
1129 return ConstantExpr::getInsertValue(Ops[0], Ops[1], getIndices());
1130 case Instruction::ExtractValue:
1131 return ConstantExpr::getExtractValue(Ops[0], getIndices());
Chris Lattnerb88a7fb2006-07-14 22:20:01 +00001132 case Instruction::ShuffleVector:
1133 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
Chris Lattnerf9021ff2007-02-19 20:01:23 +00001134 case Instruction::GetElementPtr:
Chris Lattner1a8def62012-01-26 20:37:11 +00001135 return ConstantExpr::getGetElementPtr(Ops[0], Ops.slice(1),
1136 cast<GEPOperator>(this)->isInBounds());
Reid Spencere4d87aa2006-12-23 06:05:41 +00001137 case Instruction::ICmp:
1138 case Instruction::FCmp:
1139 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
Chris Lattnerb88a7fb2006-07-14 22:20:01 +00001140 default:
1141 assert(getNumOperands() == 2 && "Must be binary operator?");
Chris Lattnercafe9bb2009-12-29 02:14:09 +00001142 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1], SubclassOptionalData);
Chris Lattner1fe8f6b2006-07-14 19:37:40 +00001143 }
1144}
1145
Chris Lattner00950542001-06-06 20:29:01 +00001146
1147//===----------------------------------------------------------------------===//
Chris Lattner00950542001-06-06 20:29:01 +00001148// isValueValidForType implementations
1149
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001150bool ConstantInt::isValueValidForType(Type *Ty, uint64_t Val) {
Chris Lattner230cdab2012-01-26 00:42:34 +00001151 unsigned NumBits = Ty->getIntegerBitWidth(); // assert okay
1152 if (Ty->isIntegerTy(1))
Reid Spencera54b7cb2007-01-12 07:05:14 +00001153 return Val == 0 || Val == 1;
Reid Spencer554cec62007-02-05 23:47:56 +00001154 if (NumBits >= 64)
Reid Spencera54b7cb2007-01-12 07:05:14 +00001155 return true; // always true, has to fit in largest type
1156 uint64_t Max = (1ll << NumBits) - 1;
1157 return Val <= Max;
Reid Spencer9b11d512006-12-19 01:28:19 +00001158}
1159
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001160bool ConstantInt::isValueValidForType(Type *Ty, int64_t Val) {
Chris Lattner230cdab2012-01-26 00:42:34 +00001161 unsigned NumBits = Ty->getIntegerBitWidth();
1162 if (Ty->isIntegerTy(1))
Reid Spencerc1030572007-01-19 21:13:56 +00001163 return Val == 0 || Val == 1 || Val == -1;
Reid Spencer554cec62007-02-05 23:47:56 +00001164 if (NumBits >= 64)
Reid Spencera54b7cb2007-01-12 07:05:14 +00001165 return true; // always true, has to fit in largest type
1166 int64_t Min = -(1ll << (NumBits-1));
1167 int64_t Max = (1ll << (NumBits-1)) - 1;
1168 return (Val >= Min && Val <= Max);
Chris Lattner00950542001-06-06 20:29:01 +00001169}
1170
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001171bool ConstantFP::isValueValidForType(Type *Ty, const APFloat& Val) {
Dale Johannesenf04afdb2007-08-30 00:23:21 +00001172 // convert modifies in place, so make a copy.
1173 APFloat Val2 = APFloat(Val);
Dale Johannesen23a98552008-10-09 23:00:39 +00001174 bool losesInfo;
Chris Lattnerf70c22b2004-06-17 18:19:28 +00001175 switch (Ty->getTypeID()) {
Chris Lattner00950542001-06-06 20:29:01 +00001176 default:
1177 return false; // These can't be represented as floating point!
1178
Dale Johannesenf04afdb2007-08-30 00:23:21 +00001179 // FIXME rounding mode needs to be more flexible
Dan Gohmance163392011-12-17 00:04:22 +00001180 case Type::HalfTyID: {
1181 if (&Val2.getSemantics() == &APFloat::IEEEhalf)
1182 return true;
1183 Val2.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, &losesInfo);
1184 return !losesInfo;
1185 }
Dale Johannesen23a98552008-10-09 23:00:39 +00001186 case Type::FloatTyID: {
1187 if (&Val2.getSemantics() == &APFloat::IEEEsingle)
1188 return true;
1189 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
1190 return !losesInfo;
1191 }
1192 case Type::DoubleTyID: {
Dan Gohmance163392011-12-17 00:04:22 +00001193 if (&Val2.getSemantics() == &APFloat::IEEEhalf ||
1194 &Val2.getSemantics() == &APFloat::IEEEsingle ||
Dale Johannesen23a98552008-10-09 23:00:39 +00001195 &Val2.getSemantics() == &APFloat::IEEEdouble)
1196 return true;
1197 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
1198 return !losesInfo;
1199 }
Dale Johannesenebbc95d2007-08-09 22:51:36 +00001200 case Type::X86_FP80TyID:
Dan Gohmance163392011-12-17 00:04:22 +00001201 return &Val2.getSemantics() == &APFloat::IEEEhalf ||
1202 &Val2.getSemantics() == &APFloat::IEEEsingle ||
Dale Johannesen9d5f4562007-09-12 03:30:33 +00001203 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1204 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
Dale Johannesenebbc95d2007-08-09 22:51:36 +00001205 case Type::FP128TyID:
Dan Gohmance163392011-12-17 00:04:22 +00001206 return &Val2.getSemantics() == &APFloat::IEEEhalf ||
1207 &Val2.getSemantics() == &APFloat::IEEEsingle ||
Dale Johannesen9d5f4562007-09-12 03:30:33 +00001208 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1209 &Val2.getSemantics() == &APFloat::IEEEquad;
Dale Johannesena471c2e2007-10-11 18:07:22 +00001210 case Type::PPC_FP128TyID:
Dan Gohmance163392011-12-17 00:04:22 +00001211 return &Val2.getSemantics() == &APFloat::IEEEhalf ||
1212 &Val2.getSemantics() == &APFloat::IEEEsingle ||
Dale Johannesena471c2e2007-10-11 18:07:22 +00001213 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1214 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
Chris Lattner00950542001-06-06 20:29:01 +00001215 }
Chris Lattnerd74ea2b2006-05-24 17:04:05 +00001216}
Chris Lattner37bf6302001-07-20 19:16:02 +00001217
Chris Lattnerff2b7f32012-01-24 05:42:11 +00001218
Chris Lattner531daef2001-09-07 16:46:31 +00001219//===----------------------------------------------------------------------===//
Chris Lattner531daef2001-09-07 16:46:31 +00001220// Factory Function Implementation
1221
Chris Lattner9df0fb42012-01-23 15:20:12 +00001222ConstantAggregateZero *ConstantAggregateZero::get(Type *Ty) {
Chris Lattner61c70e92010-08-28 04:09:24 +00001223 assert((Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()) &&
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001224 "Cannot create an aggregate zero of non-aggregate type!");
1225
Chris Lattner9df0fb42012-01-23 15:20:12 +00001226 ConstantAggregateZero *&Entry = Ty->getContext().pImpl->CAZConstants[Ty];
1227 if (Entry == 0)
1228 Entry = new ConstantAggregateZero(Ty);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001229
Chris Lattner9df0fb42012-01-23 15:20:12 +00001230 return Entry;
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001231}
1232
Chris Lattnerff2b7f32012-01-24 05:42:11 +00001233/// destroyConstant - Remove the constant from the constant table.
Dan Gohman0f8b53f2009-03-03 02:55:14 +00001234///
Owen Anderson04fb7c32009-06-20 00:24:58 +00001235void ConstantAggregateZero::destroyConstant() {
Chris Lattner9df0fb42012-01-23 15:20:12 +00001236 getContext().pImpl->CAZConstants.erase(getType());
Chris Lattner40bbeb52004-02-15 05:53:04 +00001237 destroyConstantImpl();
1238}
1239
Dan Gohman0f8b53f2009-03-03 02:55:14 +00001240/// destroyConstant - Remove the constant from the constant table...
1241///
Owen Anderson04fb7c32009-06-20 00:24:58 +00001242void ConstantArray::destroyConstant() {
Chris Lattner1afcace2011-07-09 17:41:24 +00001243 getType()->getContext().pImpl->ArrayConstants.remove(this);
Chris Lattner02ec5ed2003-05-23 20:03:32 +00001244 destroyConstantImpl();
1245}
1246
Chris Lattner93aeea32002-08-26 17:53:56 +00001247
Chris Lattnere9bb2df2001-12-03 22:26:30 +00001248//---- ConstantStruct::get() implementation...
Chris Lattner531daef2001-09-07 16:46:31 +00001249//
Chris Lattnered468e372003-10-05 00:17:43 +00001250
Chris Lattnerf5ec48d2001-10-13 06:57:33 +00001251// destroyConstant - Remove the constant from the constant table...
Chris Lattner6a57baa2001-10-03 15:39:36 +00001252//
Owen Anderson04fb7c32009-06-20 00:24:58 +00001253void ConstantStruct::destroyConstant() {
Chris Lattner1afcace2011-07-09 17:41:24 +00001254 getType()->getContext().pImpl->StructConstants.remove(this);
Chris Lattnerf5ec48d2001-10-13 06:57:33 +00001255 destroyConstantImpl();
1256}
Chris Lattner6a57baa2001-10-03 15:39:36 +00001257
Brian Gaeke715c90b2004-08-20 06:00:58 +00001258// destroyConstant - Remove the constant from the constant table...
1259//
Owen Anderson04fb7c32009-06-20 00:24:58 +00001260void ConstantVector::destroyConstant() {
Chris Lattner1afcace2011-07-09 17:41:24 +00001261 getType()->getContext().pImpl->VectorConstants.remove(this);
Brian Gaeke715c90b2004-08-20 06:00:58 +00001262 destroyConstantImpl();
1263}
1264
Duncan Sands2333e292012-11-13 12:59:33 +00001265/// getSplatValue - If this is a splat vector constant, meaning that all of
1266/// the elements have the same value, return that value. Otherwise return 0.
1267Constant *Constant::getSplatValue() const {
1268 assert(this->getType()->isVectorTy() && "Only valid for vectors!");
1269 if (isa<ConstantAggregateZero>(this))
1270 return getNullValue(this->getType()->getVectorElementType());
1271 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
1272 return CV->getSplatValue();
1273 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
1274 return CV->getSplatValue();
1275 return 0;
1276}
1277
Dan Gohman3b7cf0a2007-10-17 17:51:30 +00001278/// getSplatValue - If this is a splat constant, where all of the
1279/// elements have the same value, return that value. Otherwise return null.
Duncan Sands7681c6d2011-02-01 08:39:12 +00001280Constant *ConstantVector::getSplatValue() const {
Dan Gohman3b7cf0a2007-10-17 17:51:30 +00001281 // Check out first element.
1282 Constant *Elt = getOperand(0);
1283 // Then make sure all remaining elements point to the same value.
1284 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
Chris Lattner3e194732011-07-17 06:01:30 +00001285 if (getOperand(I) != Elt)
1286 return 0;
Dan Gohman3b7cf0a2007-10-17 17:51:30 +00001287 return Elt;
1288}
1289
Duncan Sands2333e292012-11-13 12:59:33 +00001290/// If C is a constant integer then return its value, otherwise C must be a
1291/// vector of constant integers, all equal, and the common value is returned.
1292const APInt &Constant::getUniqueInteger() const {
1293 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
1294 return CI->getValue();
1295 assert(this->getSplatValue() && "Doesn't contain a unique integer!");
1296 const Constant *C = this->getAggregateElement(0U);
1297 assert(C && isa<ConstantInt>(C) && "Not a vector of numbers!");
1298 return cast<ConstantInt>(C)->getValue();
1299}
1300
1301
Chris Lattner2ee11ec2009-10-28 00:01:44 +00001302//---- ConstantPointerNull::get() implementation.
Chris Lattnerf5ec48d2001-10-13 06:57:33 +00001303//
Chris Lattner02ec5ed2003-05-23 20:03:32 +00001304
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001305ConstantPointerNull *ConstantPointerNull::get(PointerType *Ty) {
Chris Lattner9df0fb42012-01-23 15:20:12 +00001306 ConstantPointerNull *&Entry = Ty->getContext().pImpl->CPNConstants[Ty];
1307 if (Entry == 0)
1308 Entry = new ConstantPointerNull(Ty);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001309
Chris Lattner9df0fb42012-01-23 15:20:12 +00001310 return Entry;
Chris Lattner6a57baa2001-10-03 15:39:36 +00001311}
1312
Chris Lattner41661fd2002-08-18 00:40:04 +00001313// destroyConstant - Remove the constant from the constant table...
1314//
Owen Anderson04fb7c32009-06-20 00:24:58 +00001315void ConstantPointerNull::destroyConstant() {
Chris Lattner9df0fb42012-01-23 15:20:12 +00001316 getContext().pImpl->CPNConstants.erase(getType());
1317 // Free the constant and any dangling references to it.
Chris Lattner41661fd2002-08-18 00:40:04 +00001318 destroyConstantImpl();
1319}
1320
1321
Chris Lattner2ee11ec2009-10-28 00:01:44 +00001322//---- UndefValue::get() implementation.
Chris Lattnerb9f18592004-10-16 18:07:16 +00001323//
1324
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001325UndefValue *UndefValue::get(Type *Ty) {
Chris Lattner9df0fb42012-01-23 15:20:12 +00001326 UndefValue *&Entry = Ty->getContext().pImpl->UVConstants[Ty];
1327 if (Entry == 0)
1328 Entry = new UndefValue(Ty);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001329
Chris Lattner9df0fb42012-01-23 15:20:12 +00001330 return Entry;
Chris Lattnerb9f18592004-10-16 18:07:16 +00001331}
1332
1333// destroyConstant - Remove the constant from the constant table.
1334//
Owen Anderson04fb7c32009-06-20 00:24:58 +00001335void UndefValue::destroyConstant() {
Chris Lattner9df0fb42012-01-23 15:20:12 +00001336 // Free the constant and any dangling references to it.
1337 getContext().pImpl->UVConstants.erase(getType());
Chris Lattnerb9f18592004-10-16 18:07:16 +00001338 destroyConstantImpl();
1339}
1340
Chris Lattner2ee11ec2009-10-28 00:01:44 +00001341//---- BlockAddress::get() implementation.
1342//
1343
1344BlockAddress *BlockAddress::get(BasicBlock *BB) {
1345 assert(BB->getParent() != 0 && "Block must have a parent");
1346 return get(BB->getParent(), BB);
1347}
1348
1349BlockAddress *BlockAddress::get(Function *F, BasicBlock *BB) {
1350 BlockAddress *&BA =
1351 F->getContext().pImpl->BlockAddresses[std::make_pair(F, BB)];
1352 if (BA == 0)
1353 BA = new BlockAddress(F, BB);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001354
Chris Lattner2ee11ec2009-10-28 00:01:44 +00001355 assert(BA->getFunction() == F && "Basic block moved between functions");
1356 return BA;
1357}
1358
1359BlockAddress::BlockAddress(Function *F, BasicBlock *BB)
1360: Constant(Type::getInt8PtrTy(F->getContext()), Value::BlockAddressVal,
1361 &Op<0>(), 2) {
Chris Lattnerd0ec2352009-11-01 03:03:03 +00001362 setOperand(0, F);
1363 setOperand(1, BB);
Chris Lattnercdfc9402009-11-01 01:27:45 +00001364 BB->AdjustBlockAddressRefCount(1);
Chris Lattner2ee11ec2009-10-28 00:01:44 +00001365}
1366
1367
1368// destroyConstant - Remove the constant from the constant table.
1369//
1370void BlockAddress::destroyConstant() {
Chris Lattner1afcace2011-07-09 17:41:24 +00001371 getFunction()->getType()->getContext().pImpl
Chris Lattner2ee11ec2009-10-28 00:01:44 +00001372 ->BlockAddresses.erase(std::make_pair(getFunction(), getBasicBlock()));
Chris Lattnercdfc9402009-11-01 01:27:45 +00001373 getBasicBlock()->AdjustBlockAddressRefCount(-1);
Chris Lattner2ee11ec2009-10-28 00:01:44 +00001374 destroyConstantImpl();
1375}
1376
1377void BlockAddress::replaceUsesOfWithOnConstant(Value *From, Value *To, Use *U) {
1378 // This could be replacing either the Basic Block or the Function. In either
1379 // case, we have to remove the map entry.
1380 Function *NewF = getFunction();
1381 BasicBlock *NewBB = getBasicBlock();
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001382
Chris Lattner2ee11ec2009-10-28 00:01:44 +00001383 if (U == &Op<0>())
1384 NewF = cast<Function>(To);
1385 else
1386 NewBB = cast<BasicBlock>(To);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001387
Chris Lattner2ee11ec2009-10-28 00:01:44 +00001388 // See if the 'new' entry already exists, if not, just update this in place
1389 // and return early.
1390 BlockAddress *&NewBA =
1391 getContext().pImpl->BlockAddresses[std::make_pair(NewF, NewBB)];
1392 if (NewBA == 0) {
Chris Lattnerd0ec2352009-11-01 03:03:03 +00001393 getBasicBlock()->AdjustBlockAddressRefCount(-1);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001394
Chris Lattner2ee11ec2009-10-28 00:01:44 +00001395 // Remove the old entry, this can't cause the map to rehash (just a
1396 // tombstone will get added).
1397 getContext().pImpl->BlockAddresses.erase(std::make_pair(getFunction(),
1398 getBasicBlock()));
1399 NewBA = this;
Chris Lattnerd0ec2352009-11-01 03:03:03 +00001400 setOperand(0, NewF);
1401 setOperand(1, NewBB);
1402 getBasicBlock()->AdjustBlockAddressRefCount(1);
Chris Lattner2ee11ec2009-10-28 00:01:44 +00001403 return;
1404 }
1405
1406 // Otherwise, I do need to replace this with an existing value.
1407 assert(NewBA != this && "I didn't contain From!");
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001408
Chris Lattner2ee11ec2009-10-28 00:01:44 +00001409 // Everyone using this now uses the replacement.
Chris Lattner678f9e02011-07-15 06:18:52 +00001410 replaceAllUsesWith(NewBA);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001411
Chris Lattner2ee11ec2009-10-28 00:01:44 +00001412 destroyConstant();
1413}
1414
1415//---- ConstantExpr::get() implementations.
Vikram S. Adve345e0cf2002-07-14 23:13:17 +00001416//
Reid Spencer79e21d32006-12-31 05:26:44 +00001417
Reid Spencer3da59db2006-11-27 01:05:10 +00001418/// This is a utility function to handle folding of casts and lookup of the
Duncan Sands66a1a052008-03-30 19:38:55 +00001419/// cast in the ExprConstants map. It is used by the various get* methods below.
Reid Spencer3da59db2006-11-27 01:05:10 +00001420static inline Constant *getFoldedCast(
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001421 Instruction::CastOps opc, Constant *C, Type *Ty) {
Chris Lattner9eacf8a2003-10-07 22:19:19 +00001422 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
Reid Spencer3da59db2006-11-27 01:05:10 +00001423 // Fold a few common cases
Chris Lattnerb29d5962010-02-01 20:48:08 +00001424 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
Reid Spencer3da59db2006-11-27 01:05:10 +00001425 return FC;
Chris Lattnerd628f6a2003-04-17 19:24:48 +00001426
Owen Andersond03eecd2009-08-04 20:25:11 +00001427 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
1428
Nadav Rotem82e905a2013-03-07 01:30:40 +00001429 // Look up the constant in the table first to ensure uniqueness.
Nadav Rotem55d8f6d2013-03-07 01:38:04 +00001430 ExprMapKeyType Key(opc, C);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001431
Owen Andersond03eecd2009-08-04 20:25:11 +00001432 return pImpl->ExprConstants.getOrCreate(Ty, Key);
Vikram S. Adve345e0cf2002-07-14 23:13:17 +00001433}
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001434
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001435Constant *ConstantExpr::getCast(unsigned oc, Constant *C, Type *Ty) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001436 Instruction::CastOps opc = Instruction::CastOps(oc);
1437 assert(Instruction::isCast(opc) && "opcode out of range");
1438 assert(C && Ty && "Null arguments to getCast");
Chris Lattner0b68a002010-01-26 21:51:43 +00001439 assert(CastInst::castIsValid(opc, C, Ty) && "Invalid constantexpr cast!");
Reid Spencer3da59db2006-11-27 01:05:10 +00001440
1441 switch (opc) {
Chris Lattner0b68a002010-01-26 21:51:43 +00001442 default:
1443 llvm_unreachable("Invalid cast opcode");
Chris Lattner0b68a002010-01-26 21:51:43 +00001444 case Instruction::Trunc: return getTrunc(C, Ty);
1445 case Instruction::ZExt: return getZExt(C, Ty);
1446 case Instruction::SExt: return getSExt(C, Ty);
1447 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1448 case Instruction::FPExt: return getFPExtend(C, Ty);
1449 case Instruction::UIToFP: return getUIToFP(C, Ty);
1450 case Instruction::SIToFP: return getSIToFP(C, Ty);
1451 case Instruction::FPToUI: return getFPToUI(C, Ty);
1452 case Instruction::FPToSI: return getFPToSI(C, Ty);
1453 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1454 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1455 case Instruction::BitCast: return getBitCast(C, Ty);
Chris Lattnerf5ac6c22005-01-01 15:59:57 +00001456 }
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001457}
Reid Spencer7858b332006-12-05 19:14:13 +00001458
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001459Constant *ConstantExpr::getZExtOrBitCast(Constant *C, Type *Ty) {
Dan Gohman6de29f82009-06-15 22:12:54 +00001460 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
Dan Gohman3b490632010-04-12 22:12:29 +00001461 return getBitCast(C, Ty);
1462 return getZExt(C, Ty);
Reid Spencer848414e2006-12-04 20:17:56 +00001463}
1464
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001465Constant *ConstantExpr::getSExtOrBitCast(Constant *C, Type *Ty) {
Dan Gohman6de29f82009-06-15 22:12:54 +00001466 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
Dan Gohman3b490632010-04-12 22:12:29 +00001467 return getBitCast(C, Ty);
1468 return getSExt(C, Ty);
Reid Spencer848414e2006-12-04 20:17:56 +00001469}
1470
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001471Constant *ConstantExpr::getTruncOrBitCast(Constant *C, Type *Ty) {
Dan Gohman6de29f82009-06-15 22:12:54 +00001472 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
Dan Gohman3b490632010-04-12 22:12:29 +00001473 return getBitCast(C, Ty);
1474 return getTrunc(C, Ty);
Reid Spencer848414e2006-12-04 20:17:56 +00001475}
1476
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001477Constant *ConstantExpr::getPointerCast(Constant *S, Type *Ty) {
Evgeniy Stepanov655578f2013-01-16 14:41:46 +00001478 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
1479 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
1480 "Invalid cast");
Reid Spencerc0459fb2006-12-05 03:25:26 +00001481
Evgeniy Stepanov655578f2013-01-16 14:41:46 +00001482 if (Ty->isIntOrIntVectorTy())
Dan Gohman3b490632010-04-12 22:12:29 +00001483 return getPtrToInt(S, Ty);
1484 return getBitCast(S, Ty);
Reid Spencerc0459fb2006-12-05 03:25:26 +00001485}
1486
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001487Constant *ConstantExpr::getIntegerCast(Constant *C, Type *Ty,
Reid Spencer84f3eab2006-12-12 00:51:07 +00001488 bool isSigned) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001489 assert(C->getType()->isIntOrIntVectorTy() &&
1490 Ty->isIntOrIntVectorTy() && "Invalid cast");
Dan Gohman6de29f82009-06-15 22:12:54 +00001491 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1492 unsigned DstBits = Ty->getScalarSizeInBits();
Reid Spencer84f3eab2006-12-12 00:51:07 +00001493 Instruction::CastOps opcode =
1494 (SrcBits == DstBits ? Instruction::BitCast :
1495 (SrcBits > DstBits ? Instruction::Trunc :
1496 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1497 return getCast(opcode, C, Ty);
1498}
1499
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001500Constant *ConstantExpr::getFPCast(Constant *C, Type *Ty) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001501 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
Reid Spencer84f3eab2006-12-12 00:51:07 +00001502 "Invalid cast");
Dan Gohman6de29f82009-06-15 22:12:54 +00001503 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1504 unsigned DstBits = Ty->getScalarSizeInBits();
Reid Spencerf25212a2006-12-12 05:38:50 +00001505 if (SrcBits == DstBits)
1506 return C; // Avoid a useless cast
Reid Spencer84f3eab2006-12-12 00:51:07 +00001507 Instruction::CastOps opcode =
Jay Foad9afc5272011-01-27 14:44:55 +00001508 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
Reid Spencer84f3eab2006-12-12 00:51:07 +00001509 return getCast(opcode, C, Ty);
1510}
1511
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001512Constant *ConstantExpr::getTrunc(Constant *C, Type *Ty) {
Dan Gohman6de29f82009-06-15 22:12:54 +00001513#ifndef NDEBUG
1514 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1515 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1516#endif
1517 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001518 assert(C->getType()->isIntOrIntVectorTy() && "Trunc operand must be integer");
1519 assert(Ty->isIntOrIntVectorTy() && "Trunc produces only integral");
Dan Gohman6de29f82009-06-15 22:12:54 +00001520 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
Reid Spencer3da59db2006-11-27 01:05:10 +00001521 "SrcTy must be larger than DestTy for Trunc!");
1522
Owen Anderson04fb7c32009-06-20 00:24:58 +00001523 return getFoldedCast(Instruction::Trunc, C, Ty);
Reid Spencer3da59db2006-11-27 01:05:10 +00001524}
1525
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001526Constant *ConstantExpr::getSExt(Constant *C, Type *Ty) {
Dan Gohman6de29f82009-06-15 22:12:54 +00001527#ifndef NDEBUG
1528 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1529 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1530#endif
1531 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001532 assert(C->getType()->isIntOrIntVectorTy() && "SExt operand must be integral");
1533 assert(Ty->isIntOrIntVectorTy() && "SExt produces only integer");
Dan Gohman6de29f82009-06-15 22:12:54 +00001534 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
Reid Spencer3da59db2006-11-27 01:05:10 +00001535 "SrcTy must be smaller than DestTy for SExt!");
1536
Owen Anderson04fb7c32009-06-20 00:24:58 +00001537 return getFoldedCast(Instruction::SExt, C, Ty);
Chris Lattnerd144f422004-04-04 23:20:30 +00001538}
1539
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001540Constant *ConstantExpr::getZExt(Constant *C, Type *Ty) {
Dan Gohman6de29f82009-06-15 22:12:54 +00001541#ifndef NDEBUG
1542 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1543 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1544#endif
1545 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001546 assert(C->getType()->isIntOrIntVectorTy() && "ZEXt operand must be integral");
1547 assert(Ty->isIntOrIntVectorTy() && "ZExt produces only integer");
Dan Gohman6de29f82009-06-15 22:12:54 +00001548 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
Reid Spencer3da59db2006-11-27 01:05:10 +00001549 "SrcTy must be smaller than DestTy for ZExt!");
1550
Owen Anderson04fb7c32009-06-20 00:24:58 +00001551 return getFoldedCast(Instruction::ZExt, C, Ty);
Reid Spencer3da59db2006-11-27 01:05:10 +00001552}
1553
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001554Constant *ConstantExpr::getFPTrunc(Constant *C, Type *Ty) {
Dan Gohman6de29f82009-06-15 22:12:54 +00001555#ifndef NDEBUG
1556 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1557 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1558#endif
1559 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001560 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00001561 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
Reid Spencer3da59db2006-11-27 01:05:10 +00001562 "This is an illegal floating point truncation!");
Owen Anderson04fb7c32009-06-20 00:24:58 +00001563 return getFoldedCast(Instruction::FPTrunc, C, Ty);
Reid Spencer3da59db2006-11-27 01:05:10 +00001564}
1565
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001566Constant *ConstantExpr::getFPExtend(Constant *C, Type *Ty) {
Dan Gohman6de29f82009-06-15 22:12:54 +00001567#ifndef NDEBUG
1568 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1569 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1570#endif
1571 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001572 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00001573 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
Reid Spencer3da59db2006-11-27 01:05:10 +00001574 "This is an illegal floating point extension!");
Owen Anderson04fb7c32009-06-20 00:24:58 +00001575 return getFoldedCast(Instruction::FPExt, C, Ty);
Reid Spencer3da59db2006-11-27 01:05:10 +00001576}
1577
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001578Constant *ConstantExpr::getUIToFP(Constant *C, Type *Ty) {
Devang Patelb6dc9352008-11-03 23:20:04 +00001579#ifndef NDEBUG
Nate Begemanb348d182007-11-17 03:58:34 +00001580 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1581 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Patelb6dc9352008-11-03 23:20:04 +00001582#endif
Nate Begemanb348d182007-11-17 03:58:34 +00001583 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001584 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
Nate Begemanb348d182007-11-17 03:58:34 +00001585 "This is an illegal uint to floating point cast!");
Owen Anderson04fb7c32009-06-20 00:24:58 +00001586 return getFoldedCast(Instruction::UIToFP, C, Ty);
Reid Spencer3da59db2006-11-27 01:05:10 +00001587}
1588
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001589Constant *ConstantExpr::getSIToFP(Constant *C, Type *Ty) {
Devang Patelb6dc9352008-11-03 23:20:04 +00001590#ifndef NDEBUG
Nate Begemanb348d182007-11-17 03:58:34 +00001591 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1592 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Patelb6dc9352008-11-03 23:20:04 +00001593#endif
Nate Begemanb348d182007-11-17 03:58:34 +00001594 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001595 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
Reid Spencer3da59db2006-11-27 01:05:10 +00001596 "This is an illegal sint to floating point cast!");
Owen Anderson04fb7c32009-06-20 00:24:58 +00001597 return getFoldedCast(Instruction::SIToFP, C, Ty);
Reid Spencer3da59db2006-11-27 01:05:10 +00001598}
1599
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001600Constant *ConstantExpr::getFPToUI(Constant *C, Type *Ty) {
Devang Patelb6dc9352008-11-03 23:20:04 +00001601#ifndef NDEBUG
Nate Begemanb348d182007-11-17 03:58:34 +00001602 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1603 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Patelb6dc9352008-11-03 23:20:04 +00001604#endif
Nate Begemanb348d182007-11-17 03:58:34 +00001605 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001606 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
Nate Begemanb348d182007-11-17 03:58:34 +00001607 "This is an illegal floating point to uint cast!");
Owen Anderson04fb7c32009-06-20 00:24:58 +00001608 return getFoldedCast(Instruction::FPToUI, C, Ty);
Reid Spencer3da59db2006-11-27 01:05:10 +00001609}
1610
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001611Constant *ConstantExpr::getFPToSI(Constant *C, Type *Ty) {
Devang Patelb6dc9352008-11-03 23:20:04 +00001612#ifndef NDEBUG
Nate Begemanb348d182007-11-17 03:58:34 +00001613 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1614 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Patelb6dc9352008-11-03 23:20:04 +00001615#endif
Nate Begemanb348d182007-11-17 03:58:34 +00001616 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001617 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
Nate Begemanb348d182007-11-17 03:58:34 +00001618 "This is an illegal floating point to sint cast!");
Owen Anderson04fb7c32009-06-20 00:24:58 +00001619 return getFoldedCast(Instruction::FPToSI, C, Ty);
Reid Spencer3da59db2006-11-27 01:05:10 +00001620}
1621
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001622Constant *ConstantExpr::getPtrToInt(Constant *C, Type *DstTy) {
Nadav Rotem16087692011-12-05 06:29:09 +00001623 assert(C->getType()->getScalarType()->isPointerTy() &&
1624 "PtrToInt source must be pointer or pointer vector");
1625 assert(DstTy->getScalarType()->isIntegerTy() &&
1626 "PtrToInt destination must be integer or integer vector");
Chris Lattneraf7b4fb2012-01-25 01:32:59 +00001627 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
Nick Lewycky1486ae62012-01-25 03:20:12 +00001628 if (isa<VectorType>(C->getType()))
Chris Lattner230cdab2012-01-26 00:42:34 +00001629 assert(C->getType()->getVectorNumElements()==DstTy->getVectorNumElements()&&
Chris Lattneraf7b4fb2012-01-25 01:32:59 +00001630 "Invalid cast between a different number of vector elements");
Owen Anderson04fb7c32009-06-20 00:24:58 +00001631 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00001632}
1633
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001634Constant *ConstantExpr::getIntToPtr(Constant *C, Type *DstTy) {
Nadav Rotem16087692011-12-05 06:29:09 +00001635 assert(C->getType()->getScalarType()->isIntegerTy() &&
1636 "IntToPtr source must be integer or integer vector");
1637 assert(DstTy->getScalarType()->isPointerTy() &&
1638 "IntToPtr destination must be a pointer or pointer vector");
Chris Lattneraf7b4fb2012-01-25 01:32:59 +00001639 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
Nick Lewycky1486ae62012-01-25 03:20:12 +00001640 if (isa<VectorType>(C->getType()))
Chris Lattner230cdab2012-01-26 00:42:34 +00001641 assert(C->getType()->getVectorNumElements()==DstTy->getVectorNumElements()&&
Chris Lattneraf7b4fb2012-01-25 01:32:59 +00001642 "Invalid cast between a different number of vector elements");
Owen Anderson04fb7c32009-06-20 00:24:58 +00001643 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00001644}
1645
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001646Constant *ConstantExpr::getBitCast(Constant *C, Type *DstTy) {
Chris Lattner0b68a002010-01-26 21:51:43 +00001647 assert(CastInst::castIsValid(Instruction::BitCast, C, DstTy) &&
1648 "Invalid constantexpr bitcast!");
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001649
Chris Lattner8c7f24a2009-03-21 06:55:54 +00001650 // It is common to ask for a bitcast of a value to its own type, handle this
1651 // speedily.
1652 if (C->getType() == DstTy) return C;
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001653
Owen Anderson04fb7c32009-06-20 00:24:58 +00001654 return getFoldedCast(Instruction::BitCast, C, DstTy);
Chris Lattnerd144f422004-04-04 23:20:30 +00001655}
1656
Chris Lattnereaf79802011-07-09 18:23:52 +00001657Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2,
1658 unsigned Flags) {
1659 // Check the operands for consistency first.
Reid Spencer0a783f72006-11-02 01:53:59 +00001660 assert(Opcode >= Instruction::BinaryOpsBegin &&
1661 Opcode < Instruction::BinaryOpsEnd &&
Chris Lattnerf31f5832003-05-21 17:49:25 +00001662 "Invalid opcode in binary constant expression");
1663 assert(C1->getType() == C2->getType() &&
1664 "Operand types in binary constant expression should match");
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001665
Chris Lattner91b362b2004-08-17 17:28:46 +00001666#ifndef NDEBUG
1667 switch (Opcode) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001668 case Instruction::Add:
Reid Spencer0a783f72006-11-02 01:53:59 +00001669 case Instruction::Sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001670 case Instruction::Mul:
Chris Lattner91b362b2004-08-17 17:28:46 +00001671 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001672 assert(C1->getType()->isIntOrIntVectorTy() &&
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001673 "Tried to create an integer operation on a non-integer type!");
1674 break;
1675 case Instruction::FAdd:
1676 case Instruction::FSub:
1677 case Instruction::FMul:
1678 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001679 assert(C1->getType()->isFPOrFPVectorTy() &&
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001680 "Tried to create a floating-point operation on a "
1681 "non-floating-point type!");
Chris Lattner91b362b2004-08-17 17:28:46 +00001682 break;
Reid Spencer1628cec2006-10-26 06:15:43 +00001683 case Instruction::UDiv:
1684 case Instruction::SDiv:
1685 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001686 assert(C1->getType()->isIntOrIntVectorTy() &&
Reid Spencer1628cec2006-10-26 06:15:43 +00001687 "Tried to create an arithmetic operation on a non-arithmetic type!");
1688 break;
1689 case Instruction::FDiv:
1690 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001691 assert(C1->getType()->isFPOrFPVectorTy() &&
Dan Gohmanf57478f2009-06-15 22:25:12 +00001692 "Tried to create an arithmetic operation on a non-arithmetic type!");
Reid Spencer1628cec2006-10-26 06:15:43 +00001693 break;
Reid Spencer0a783f72006-11-02 01:53:59 +00001694 case Instruction::URem:
1695 case Instruction::SRem:
1696 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001697 assert(C1->getType()->isIntOrIntVectorTy() &&
Reid Spencer0a783f72006-11-02 01:53:59 +00001698 "Tried to create an arithmetic operation on a non-arithmetic type!");
1699 break;
1700 case Instruction::FRem:
1701 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001702 assert(C1->getType()->isFPOrFPVectorTy() &&
Dan Gohmanf57478f2009-06-15 22:25:12 +00001703 "Tried to create an arithmetic operation on a non-arithmetic type!");
Reid Spencer0a783f72006-11-02 01:53:59 +00001704 break;
Chris Lattner91b362b2004-08-17 17:28:46 +00001705 case Instruction::And:
1706 case Instruction::Or:
1707 case Instruction::Xor:
1708 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001709 assert(C1->getType()->isIntOrIntVectorTy() &&
Misha Brukman1bae2912005-01-27 06:46:38 +00001710 "Tried to create a logical operation on a non-integral type!");
Chris Lattner91b362b2004-08-17 17:28:46 +00001711 break;
Chris Lattner91b362b2004-08-17 17:28:46 +00001712 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00001713 case Instruction::LShr:
1714 case Instruction::AShr:
Reid Spencer832254e2007-02-02 02:16:23 +00001715 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001716 assert(C1->getType()->isIntOrIntVectorTy() &&
Chris Lattner91b362b2004-08-17 17:28:46 +00001717 "Tried to create a shift operation on a non-integer type!");
1718 break;
1719 default:
1720 break;
1721 }
1722#endif
1723
Chris Lattnereaf79802011-07-09 18:23:52 +00001724 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1725 return FC; // Fold a few common cases.
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001726
Benjamin Kramer4e4cc7d2013-03-07 20:53:34 +00001727 Constant *ArgVec[] = { C1, C2 };
1728 ExprMapKeyType Key(Opcode, ArgVec, 0, Flags);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001729
Chris Lattnereaf79802011-07-09 18:23:52 +00001730 LLVMContextImpl *pImpl = C1->getContext().pImpl;
1731 return pImpl->ExprConstants.getOrCreate(C1->getType(), Key);
Reid Spencer67263fe2006-12-04 21:35:24 +00001732}
1733
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001734Constant *ConstantExpr::getSizeOf(Type* Ty) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00001735 // sizeof is implemented as: (i64) gep (Ty*)null, 1
1736 // Note that a non-inbounds gep is used, as null isn't within any object.
Owen Anderson1d0be152009-08-13 21:58:54 +00001737 Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001738 Constant *GEP = getGetElementPtr(
Jay Foaddab3d292011-07-21 14:31:17 +00001739 Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
Dan Gohman3b490632010-04-12 22:12:29 +00001740 return getPtrToInt(GEP,
1741 Type::getInt64Ty(Ty->getContext()));
Owen Andersonbaf3c402009-07-29 18:55:55 +00001742}
1743
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001744Constant *ConstantExpr::getAlignOf(Type* Ty) {
Dan Gohman0f5efe52010-01-28 02:15:55 +00001745 // alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1
Dan Gohmane2574d32009-08-11 17:57:01 +00001746 // Note that a non-inbounds gep is used, as null isn't within any object.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001747 Type *AligningTy =
Chris Lattnerb2318662011-06-18 22:48:56 +00001748 StructType::get(Type::getInt1Ty(Ty->getContext()), Ty, NULL);
Micah Villmowb8bce922012-10-24 17:25:11 +00001749 Constant *NullPtr = Constant::getNullValue(AligningTy->getPointerTo());
Dan Gohman06ed3e72010-01-28 02:43:22 +00001750 Constant *Zero = ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0);
Owen Anderson1d0be152009-08-13 21:58:54 +00001751 Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001752 Constant *Indices[2] = { Zero, One };
Jay Foaddab3d292011-07-21 14:31:17 +00001753 Constant *GEP = getGetElementPtr(NullPtr, Indices);
Dan Gohman3b490632010-04-12 22:12:29 +00001754 return getPtrToInt(GEP,
1755 Type::getInt64Ty(Ty->getContext()));
Owen Andersonbaf3c402009-07-29 18:55:55 +00001756}
1757
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001758Constant *ConstantExpr::getOffsetOf(StructType* STy, unsigned FieldNo) {
Dan Gohman2544a1d2010-02-01 16:37:38 +00001759 return getOffsetOf(STy, ConstantInt::get(Type::getInt32Ty(STy->getContext()),
1760 FieldNo));
1761}
1762
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001763Constant *ConstantExpr::getOffsetOf(Type* Ty, Constant *FieldNo) {
Dan Gohman3778f212009-08-16 21:26:11 +00001764 // offsetof is implemented as: (i64) gep (Ty*)null, 0, FieldNo
1765 // Note that a non-inbounds gep is used, as null isn't within any object.
1766 Constant *GEPIdx[] = {
Dan Gohman2544a1d2010-02-01 16:37:38 +00001767 ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0),
1768 FieldNo
Dan Gohman3778f212009-08-16 21:26:11 +00001769 };
1770 Constant *GEP = getGetElementPtr(
Jay Foaddab3d292011-07-21 14:31:17 +00001771 Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
Dan Gohman3b490632010-04-12 22:12:29 +00001772 return getPtrToInt(GEP,
1773 Type::getInt64Ty(Ty->getContext()));
Dan Gohman3778f212009-08-16 21:26:11 +00001774}
Owen Andersonbaf3c402009-07-29 18:55:55 +00001775
Chris Lattnereaf79802011-07-09 18:23:52 +00001776Constant *ConstantExpr::getCompare(unsigned short Predicate,
1777 Constant *C1, Constant *C2) {
Reid Spencer67263fe2006-12-04 21:35:24 +00001778 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001779
Chris Lattnereaf79802011-07-09 18:23:52 +00001780 switch (Predicate) {
1781 default: llvm_unreachable("Invalid CmpInst predicate");
1782 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
1783 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
1784 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
1785 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
1786 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
1787 case CmpInst::FCMP_TRUE:
1788 return getFCmp(Predicate, C1, C2);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001789
Chris Lattnereaf79802011-07-09 18:23:52 +00001790 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
1791 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
1792 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
1793 case CmpInst::ICMP_SLE:
1794 return getICmp(Predicate, C1, C2);
1795 }
Chris Lattnerc3d12f02004-08-04 18:50:09 +00001796}
1797
Chris Lattnereaf79802011-07-09 18:23:52 +00001798Constant *ConstantExpr::getSelect(Constant *C, Constant *V1, Constant *V2) {
Chris Lattner9ace0cd2008-12-29 00:16:12 +00001799 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
Chris Lattner08a45cc2004-03-12 05:54:04 +00001800
Chris Lattnereaf79802011-07-09 18:23:52 +00001801 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1802 return SC; // Fold common cases
Chris Lattner08a45cc2004-03-12 05:54:04 +00001803
Benjamin Kramer4e4cc7d2013-03-07 20:53:34 +00001804 Constant *ArgVec[] = { C, V1, V2 };
1805 ExprMapKeyType Key(Instruction::Select, ArgVec);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001806
Chris Lattnereaf79802011-07-09 18:23:52 +00001807 LLVMContextImpl *pImpl = C->getContext().pImpl;
1808 return pImpl->ExprConstants.getOrCreate(V1->getType(), Key);
Chris Lattner08a45cc2004-03-12 05:54:04 +00001809}
1810
Jay Foaddab3d292011-07-21 14:31:17 +00001811Constant *ConstantExpr::getGetElementPtr(Constant *C, ArrayRef<Value *> Idxs,
1812 bool InBounds) {
Duncan Sands2333e292012-11-13 12:59:33 +00001813 assert(C->getType()->isPtrOrPtrVectorTy() &&
1814 "Non-pointer type for constant GetElementPtr expression");
1815
Jay Foaddab3d292011-07-21 14:31:17 +00001816 if (Constant *FC = ConstantFoldGetElementPtr(C, InBounds, Idxs))
Chris Lattner1f78d512011-02-11 05:34:33 +00001817 return FC; // Fold a few common cases.
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001818
Chris Lattnereaf79802011-07-09 18:23:52 +00001819 // Get the result type of the getelementptr!
Jay Foada9203102011-07-25 09:48:08 +00001820 Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), Idxs);
Chris Lattnereaf79802011-07-09 18:23:52 +00001821 assert(Ty && "GEP indices invalid!");
Chris Lattner230cdab2012-01-26 00:42:34 +00001822 unsigned AS = C->getType()->getPointerAddressSpace();
Chris Lattnereaf79802011-07-09 18:23:52 +00001823 Type *ReqTy = Ty->getPointerTo(AS);
Duncan Sands2333e292012-11-13 12:59:33 +00001824 if (VectorType *VecTy = dyn_cast<VectorType>(C->getType()))
1825 ReqTy = VectorType::get(ReqTy, VecTy->getNumElements());
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001826
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001827 // Look up the constant in the table first to ensure uniqueness
1828 std::vector<Constant*> ArgVec;
Jay Foaddab3d292011-07-21 14:31:17 +00001829 ArgVec.reserve(1 + Idxs.size());
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001830 ArgVec.push_back(C);
Duncan Sands2333e292012-11-13 12:59:33 +00001831 for (unsigned i = 0, e = Idxs.size(); i != e; ++i) {
1832 assert(Idxs[i]->getType()->isVectorTy() == ReqTy->isVectorTy() &&
1833 "getelementptr index type missmatch");
1834 assert((!Idxs[i]->getType()->isVectorTy() ||
1835 ReqTy->getVectorNumElements() ==
1836 Idxs[i]->getType()->getVectorNumElements()) &&
1837 "getelementptr index type missmatch");
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001838 ArgVec.push_back(cast<Constant>(Idxs[i]));
Duncan Sands2333e292012-11-13 12:59:33 +00001839 }
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001840 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec, 0,
Chris Lattner1f78d512011-02-11 05:34:33 +00001841 InBounds ? GEPOperator::IsInBounds : 0);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001842
Chris Lattnereaf79802011-07-09 18:23:52 +00001843 LLVMContextImpl *pImpl = C->getContext().pImpl;
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001844 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1845}
1846
Reid Spencer077d0eb2006-12-04 05:19:50 +00001847Constant *
Nick Lewycky401f3252010-01-21 07:03:21 +00001848ConstantExpr::getICmp(unsigned short pred, Constant *LHS, Constant *RHS) {
Reid Spencer077d0eb2006-12-04 05:19:50 +00001849 assert(LHS->getType() == RHS->getType());
1850 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
1851 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1852
Chris Lattnerb29d5962010-02-01 20:48:08 +00001853 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
Reid Spencer077d0eb2006-12-04 05:19:50 +00001854 return FC; // Fold a few common cases...
1855
1856 // Look up the constant in the table first to ensure uniqueness
Benjamin Kramer4e4cc7d2013-03-07 20:53:34 +00001857 Constant *ArgVec[] = { LHS, RHS };
Reid Spencer4fa021a2006-12-24 18:42:29 +00001858 // Get the key type with both the opcode and predicate
Reid Spencer077d0eb2006-12-04 05:19:50 +00001859 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
Owen Anderson31c36f02009-06-17 20:10:08 +00001860
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001861 Type *ResultTy = Type::getInt1Ty(LHS->getContext());
1862 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
Nick Lewycky401f3252010-01-21 07:03:21 +00001863 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
1864
Owen Andersond03eecd2009-08-04 20:25:11 +00001865 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
Nick Lewycky401f3252010-01-21 07:03:21 +00001866 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
Reid Spencer077d0eb2006-12-04 05:19:50 +00001867}
1868
1869Constant *
Nick Lewycky401f3252010-01-21 07:03:21 +00001870ConstantExpr::getFCmp(unsigned short pred, Constant *LHS, Constant *RHS) {
Reid Spencer077d0eb2006-12-04 05:19:50 +00001871 assert(LHS->getType() == RHS->getType());
1872 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1873
Chris Lattnerb29d5962010-02-01 20:48:08 +00001874 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
Reid Spencer077d0eb2006-12-04 05:19:50 +00001875 return FC; // Fold a few common cases...
1876
1877 // Look up the constant in the table first to ensure uniqueness
Benjamin Kramer4e4cc7d2013-03-07 20:53:34 +00001878 Constant *ArgVec[] = { LHS, RHS };
Reid Spencer4fa021a2006-12-24 18:42:29 +00001879 // Get the key type with both the opcode and predicate
Reid Spencer077d0eb2006-12-04 05:19:50 +00001880 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
Nick Lewycky401f3252010-01-21 07:03:21 +00001881
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001882 Type *ResultTy = Type::getInt1Ty(LHS->getContext());
1883 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
Nick Lewycky401f3252010-01-21 07:03:21 +00001884 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
1885
Owen Andersond03eecd2009-08-04 20:25:11 +00001886 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
Nick Lewycky401f3252010-01-21 07:03:21 +00001887 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
Reid Spencer077d0eb2006-12-04 05:19:50 +00001888}
1889
Robert Bocchinob52ee7f2006-01-10 19:05:34 +00001890Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
Duncan Sands1df98592010-02-16 11:11:14 +00001891 assert(Val->getType()->isVectorTy() &&
Reid Spencerac9dcb92007-02-15 03:39:18 +00001892 "Tried to create extractelement operation on non-vector type!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001893 assert(Idx->getType()->isIntegerTy(32) &&
Reid Spencer3d10b0b2007-01-26 07:37:34 +00001894 "Extractelement index must be i32 type!");
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001895
Chris Lattnereaf79802011-07-09 18:23:52 +00001896 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
Chris Lattner83738a22009-12-30 20:25:09 +00001897 return FC; // Fold a few common cases.
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001898
Robert Bocchinoc152f9c2006-01-17 20:07:22 +00001899 // Look up the constant in the table first to ensure uniqueness
Benjamin Kramer4e4cc7d2013-03-07 20:53:34 +00001900 Constant *ArgVec[] = { Val, Idx };
1901 const ExprMapKeyType Key(Instruction::ExtractElement, ArgVec);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001902
Chris Lattnereaf79802011-07-09 18:23:52 +00001903 LLVMContextImpl *pImpl = Val->getContext().pImpl;
Chris Lattner230cdab2012-01-26 00:42:34 +00001904 Type *ReqTy = Val->getType()->getVectorElementType();
Owen Andersond03eecd2009-08-04 20:25:11 +00001905 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
Robert Bocchinoc152f9c2006-01-17 20:07:22 +00001906}
1907
1908Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1909 Constant *Idx) {
Duncan Sands1df98592010-02-16 11:11:14 +00001910 assert(Val->getType()->isVectorTy() &&
Reid Spencerac9dcb92007-02-15 03:39:18 +00001911 "Tried to create insertelement operation on non-vector type!");
Chris Lattner230cdab2012-01-26 00:42:34 +00001912 assert(Elt->getType() == Val->getType()->getVectorElementType() &&
1913 "Insertelement types must match!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001914 assert(Idx->getType()->isIntegerTy(32) &&
Reid Spencer3d10b0b2007-01-26 07:37:34 +00001915 "Insertelement index must be i32 type!");
Robert Bocchinoc152f9c2006-01-17 20:07:22 +00001916
Chris Lattnereaf79802011-07-09 18:23:52 +00001917 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
1918 return FC; // Fold a few common cases.
Chris Lattner00f10232006-04-08 01:18:18 +00001919 // Look up the constant in the table first to ensure uniqueness
Benjamin Kramer4e4cc7d2013-03-07 20:53:34 +00001920 Constant *ArgVec[] = { Val, Elt, 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
Benjamin Kramer4e4cc7d2013-03-07 20:53:34 +00001940 Constant *ArgVec[] = { V1, V2, Mask };
1941 const ExprMapKeyType Key(Instruction::ShuffleVector, ArgVec);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001942
Chris Lattnereaf79802011-07-09 18:23:52 +00001943 LLVMContextImpl *pImpl = ShufTy->getContext().pImpl;
1944 return pImpl->ExprConstants.getOrCreate(ShufTy, Key);
Chris Lattner00f10232006-04-08 01:18:18 +00001945}
1946
Chris Lattnereaf79802011-07-09 18:23:52 +00001947Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
Jay Foadfc6d3a42011-07-13 10:26:04 +00001948 ArrayRef<unsigned> Idxs) {
1949 assert(ExtractValueInst::getIndexedType(Agg->getType(),
1950 Idxs) == Val->getType() &&
Dan Gohman041e2eb2008-05-15 19:50:34 +00001951 "insertvalue indices invalid!");
Dan Gohmane4569942008-05-23 00:36:11 +00001952 assert(Agg->getType()->isFirstClassType() &&
Chris Lattner4e47aad2011-07-12 05:26:21 +00001953 "Non-first-class type for constant insertvalue expression");
Jay Foadfc6d3a42011-07-13 10:26:04 +00001954 Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs);
Chris Lattner4e47aad2011-07-12 05:26:21 +00001955 assert(FC && "insertvalue constant expr couldn't be folded!");
Dan Gohmane0891602008-07-21 23:30:30 +00001956 return FC;
Dan Gohman041e2eb2008-05-15 19:50:34 +00001957}
1958
Chris Lattnereaf79802011-07-09 18:23:52 +00001959Constant *ConstantExpr::getExtractValue(Constant *Agg,
Jay Foadfc6d3a42011-07-13 10:26:04 +00001960 ArrayRef<unsigned> Idxs) {
Dan Gohmane4569942008-05-23 00:36:11 +00001961 assert(Agg->getType()->isFirstClassType() &&
Chris Lattnereaf79802011-07-09 18:23:52 +00001962 "Tried to create extractelement operation on non-first-class type!");
Dan Gohman041e2eb2008-05-15 19:50:34 +00001963
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001964 Type *ReqTy = ExtractValueInst::getIndexedType(Agg->getType(), Idxs);
Chandler Carruthdc770fc2011-07-10 09:45:35 +00001965 (void)ReqTy;
Chris Lattnereaf79802011-07-09 18:23:52 +00001966 assert(ReqTy && "extractvalue indices invalid!");
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001967
Dan Gohmane4569942008-05-23 00:36:11 +00001968 assert(Agg->getType()->isFirstClassType() &&
1969 "Non-first-class type for constant extractvalue expression");
Jay Foadfc6d3a42011-07-13 10:26:04 +00001970 Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs);
Dan Gohmane0891602008-07-21 23:30:30 +00001971 assert(FC && "ExtractValue constant expr couldn't be folded!");
1972 return FC;
Dan Gohman041e2eb2008-05-15 19:50:34 +00001973}
1974
Chris Lattner81baf142011-02-10 07:01:55 +00001975Constant *ConstantExpr::getNeg(Constant *C, bool HasNUW, bool HasNSW) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001976 assert(C->getType()->isIntOrIntVectorTy() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00001977 "Cannot NEG a nonintegral value!");
Chris Lattner81baf142011-02-10 07:01:55 +00001978 return getSub(ConstantFP::getZeroValueForNegation(C->getType()),
1979 C, HasNUW, HasNSW);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001980}
1981
Chris Lattnerf067d582011-02-07 16:40:21 +00001982Constant *ConstantExpr::getFNeg(Constant *C) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001983 assert(C->getType()->isFPOrFPVectorTy() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00001984 "Cannot FNEG a non-floating-point value!");
Chris Lattner81baf142011-02-10 07:01:55 +00001985 return getFSub(ConstantFP::getZeroValueForNegation(C->getType()), C);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001986}
1987
Chris Lattnerf067d582011-02-07 16:40:21 +00001988Constant *ConstantExpr::getNot(Constant *C) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001989 assert(C->getType()->isIntOrIntVectorTy() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00001990 "Cannot NOT a nonintegral value!");
Owen Andersona7235ea2009-07-31 20:28:14 +00001991 return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
Owen Andersonbaf3c402009-07-29 18:55:55 +00001992}
1993
Chris Lattner81baf142011-02-10 07:01:55 +00001994Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2,
1995 bool HasNUW, bool HasNSW) {
1996 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
1997 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
1998 return get(Instruction::Add, C1, C2, Flags);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001999}
2000
Chris Lattnerf067d582011-02-07 16:40:21 +00002001Constant *ConstantExpr::getFAdd(Constant *C1, Constant *C2) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002002 return get(Instruction::FAdd, C1, C2);
2003}
2004
Chris Lattner81baf142011-02-10 07:01:55 +00002005Constant *ConstantExpr::getSub(Constant *C1, Constant *C2,
2006 bool HasNUW, bool HasNSW) {
2007 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2008 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2009 return get(Instruction::Sub, C1, C2, Flags);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002010}
2011
Chris Lattnerf067d582011-02-07 16:40:21 +00002012Constant *ConstantExpr::getFSub(Constant *C1, Constant *C2) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002013 return get(Instruction::FSub, C1, C2);
2014}
2015
Chris Lattner81baf142011-02-10 07:01:55 +00002016Constant *ConstantExpr::getMul(Constant *C1, Constant *C2,
2017 bool HasNUW, bool HasNSW) {
2018 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2019 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2020 return get(Instruction::Mul, C1, C2, Flags);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002021}
2022
Chris Lattnerf067d582011-02-07 16:40:21 +00002023Constant *ConstantExpr::getFMul(Constant *C1, Constant *C2) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002024 return get(Instruction::FMul, C1, C2);
2025}
2026
Chris Lattner74f5c5a2011-02-09 16:43:07 +00002027Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2, bool isExact) {
2028 return get(Instruction::UDiv, C1, C2,
2029 isExact ? PossiblyExactOperator::IsExact : 0);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002030}
2031
Chris Lattner74f5c5a2011-02-09 16:43:07 +00002032Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2, bool isExact) {
2033 return get(Instruction::SDiv, C1, C2,
2034 isExact ? PossiblyExactOperator::IsExact : 0);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002035}
2036
Chris Lattnerf067d582011-02-07 16:40:21 +00002037Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002038 return get(Instruction::FDiv, C1, C2);
2039}
2040
Chris Lattnerf067d582011-02-07 16:40:21 +00002041Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002042 return get(Instruction::URem, C1, C2);
2043}
2044
Chris Lattnerf067d582011-02-07 16:40:21 +00002045Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002046 return get(Instruction::SRem, C1, C2);
2047}
2048
Chris Lattnerf067d582011-02-07 16:40:21 +00002049Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002050 return get(Instruction::FRem, C1, C2);
2051}
2052
Chris Lattnerf067d582011-02-07 16:40:21 +00002053Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002054 return get(Instruction::And, C1, C2);
2055}
2056
Chris Lattnerf067d582011-02-07 16:40:21 +00002057Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002058 return get(Instruction::Or, C1, C2);
2059}
2060
Chris Lattnerf067d582011-02-07 16:40:21 +00002061Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002062 return get(Instruction::Xor, C1, C2);
2063}
2064
Chris Lattner81baf142011-02-10 07:01:55 +00002065Constant *ConstantExpr::getShl(Constant *C1, Constant *C2,
2066 bool HasNUW, bool HasNSW) {
2067 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2068 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2069 return get(Instruction::Shl, C1, C2, Flags);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002070}
2071
Chris Lattner74f5c5a2011-02-09 16:43:07 +00002072Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2, bool isExact) {
2073 return get(Instruction::LShr, C1, C2,
2074 isExact ? PossiblyExactOperator::IsExact : 0);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002075}
2076
Chris Lattner74f5c5a2011-02-09 16:43:07 +00002077Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2, bool isExact) {
2078 return get(Instruction::AShr, C1, C2,
2079 isExact ? PossiblyExactOperator::IsExact : 0);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002080}
2081
Duncan Sandsc038a782012-06-12 14:33:56 +00002082/// getBinOpIdentity - Return the identity for the given binary operation,
2083/// 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 +00002084/// returns null if the operator doesn't have an identity.
Duncan Sandsc038a782012-06-12 14:33:56 +00002085Constant *ConstantExpr::getBinOpIdentity(unsigned Opcode, Type *Ty) {
2086 switch (Opcode) {
2087 default:
Duncan Sandsee5a0942012-06-13 09:42:13 +00002088 // Doesn't have an identity.
2089 return 0;
2090
Duncan Sandsc038a782012-06-12 14:33:56 +00002091 case Instruction::Add:
2092 case Instruction::Or:
2093 case Instruction::Xor:
2094 return Constant::getNullValue(Ty);
2095
2096 case Instruction::Mul:
2097 return ConstantInt::get(Ty, 1);
2098
2099 case Instruction::And:
2100 return Constant::getAllOnesValue(Ty);
2101 }
2102}
2103
Duncan Sandsee5a0942012-06-13 09:42:13 +00002104/// getBinOpAbsorber - Return the absorbing element for the given binary
2105/// operation, i.e. a constant C such that X op C = C and C op X = C for
2106/// every X. For example, this returns zero for integer multiplication.
2107/// It returns null if the operator doesn't have an absorbing element.
2108Constant *ConstantExpr::getBinOpAbsorber(unsigned Opcode, Type *Ty) {
2109 switch (Opcode) {
2110 default:
2111 // Doesn't have an absorber.
2112 return 0;
2113
2114 case Instruction::Or:
2115 return Constant::getAllOnesValue(Ty);
2116
2117 case Instruction::And:
2118 case Instruction::Mul:
2119 return Constant::getNullValue(Ty);
2120 }
2121}
2122
Vikram S. Adved0b1bb02002-07-15 18:19:33 +00002123// destroyConstant - Remove the constant from the constant table...
2124//
Owen Anderson04fb7c32009-06-20 00:24:58 +00002125void ConstantExpr::destroyConstant() {
Chris Lattner1afcace2011-07-09 17:41:24 +00002126 getType()->getContext().pImpl->ExprConstants.remove(this);
Vikram S. Adved0b1bb02002-07-15 18:19:33 +00002127 destroyConstantImpl();
Vikram S. Adve345e0cf2002-07-14 23:13:17 +00002128}
2129
Chris Lattnerc188eeb2002-07-30 18:54:25 +00002130const char *ConstantExpr::getOpcodeName() const {
2131 return Instruction::getOpcodeName(getOpcode());
Vikram S. Adve345e0cf2002-07-14 23:13:17 +00002132}
Reid Spencer1c9c8e62004-07-17 23:48:33 +00002133
Chris Lattner04e3b1e2010-03-30 20:48:48 +00002134
2135
2136GetElementPtrConstantExpr::
Chris Lattnera7c69882012-01-26 20:40:56 +00002137GetElementPtrConstantExpr(Constant *C, ArrayRef<Constant*> IdxList,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002138 Type *DestTy)
Chris Lattner04e3b1e2010-03-30 20:48:48 +00002139 : ConstantExpr(DestTy, Instruction::GetElementPtr,
2140 OperandTraits<GetElementPtrConstantExpr>::op_end(this)
2141 - (IdxList.size()+1), IdxList.size()+1) {
2142 OperandList[0] = C;
2143 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
2144 OperandList[i+1] = IdxList[i];
2145}
2146
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002147//===----------------------------------------------------------------------===//
2148// ConstantData* implementations
2149
2150void ConstantDataArray::anchor() {}
2151void ConstantDataVector::anchor() {}
2152
Chris Lattner45bb5c52012-01-24 04:43:41 +00002153/// getElementType - Return the element type of the array/vector.
2154Type *ConstantDataSequential::getElementType() const {
2155 return getType()->getElementType();
2156}
2157
Chris Lattner9e631da2012-01-24 09:31:43 +00002158StringRef ConstantDataSequential::getRawDataValues() const {
Chris Lattner1ee0ecf2012-01-24 13:41:11 +00002159 return StringRef(DataElements, getNumElements()*getElementByteSize());
Chris Lattner9e631da2012-01-24 09:31:43 +00002160}
2161
Chris Lattnerff2b7f32012-01-24 05:42:11 +00002162/// isElementTypeCompatible - Return true if a ConstantDataSequential can be
2163/// formed with a vector or array of the specified element type.
2164/// ConstantDataArray only works with normal float and int types that are
2165/// stored densely in memory, not with things like i42 or x86_f80.
2166bool ConstantDataSequential::isElementTypeCompatible(const Type *Ty) {
Chris Lattner45bb5c52012-01-24 04:43:41 +00002167 if (Ty->isFloatTy() || Ty->isDoubleTy()) return true;
2168 if (const IntegerType *IT = dyn_cast<IntegerType>(Ty)) {
2169 switch (IT->getBitWidth()) {
2170 case 8:
2171 case 16:
2172 case 32:
2173 case 64:
2174 return true;
2175 default: break;
2176 }
2177 }
2178 return false;
2179}
2180
Chris Lattner1ee0ecf2012-01-24 13:41:11 +00002181/// getNumElements - Return the number of elements in the array or vector.
2182unsigned ConstantDataSequential::getNumElements() const {
Chris Lattneraf7b4fb2012-01-25 01:32:59 +00002183 if (ArrayType *AT = dyn_cast<ArrayType>(getType()))
2184 return AT->getNumElements();
Chris Lattner230cdab2012-01-26 00:42:34 +00002185 return getType()->getVectorNumElements();
Chris Lattner1ee0ecf2012-01-24 13:41:11 +00002186}
2187
2188
Chris Lattner45bb5c52012-01-24 04:43:41 +00002189/// getElementByteSize - Return the size in bytes of the elements in the data.
2190uint64_t ConstantDataSequential::getElementByteSize() const {
2191 return getElementType()->getPrimitiveSizeInBits()/8;
2192}
2193
2194/// getElementPointer - Return the start of the specified element.
2195const char *ConstantDataSequential::getElementPointer(unsigned Elt) const {
Chris Lattner1ee0ecf2012-01-24 13:41:11 +00002196 assert(Elt < getNumElements() && "Invalid Elt");
Chris Lattner45bb5c52012-01-24 04:43:41 +00002197 return DataElements+Elt*getElementByteSize();
2198}
2199
2200
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002201/// isAllZeros - return true if the array is empty or all zeros.
2202static bool isAllZeros(StringRef Arr) {
2203 for (StringRef::iterator I = Arr.begin(), E = Arr.end(); I != E; ++I)
2204 if (*I != 0)
2205 return false;
2206 return true;
2207}
Chris Lattnerff2b7f32012-01-24 05:42:11 +00002208
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002209/// getImpl - This is the underlying implementation of all of the
2210/// ConstantDataSequential::get methods. They all thunk down to here, providing
Chris Lattner8cf27ef2012-01-30 18:19:30 +00002211/// the correct element type. We take the bytes in as a StringRef because
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002212/// we *want* an underlying "char*" to avoid TBAA type punning violations.
2213Constant *ConstantDataSequential::getImpl(StringRef Elements, Type *Ty) {
Chris Lattner230cdab2012-01-26 00:42:34 +00002214 assert(isElementTypeCompatible(Ty->getSequentialElementType()));
Chris Lattner29cc6cb2012-01-24 14:17:05 +00002215 // If the elements are all zero or there are no elements, return a CAZ, which
2216 // is more dense and canonical.
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002217 if (isAllZeros(Elements))
2218 return ConstantAggregateZero::get(Ty);
2219
2220 // Do a lookup to see if we have already formed one of these.
2221 StringMap<ConstantDataSequential*>::MapEntryTy &Slot =
2222 Ty->getContext().pImpl->CDSConstants.GetOrCreateValue(Elements);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002223
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002224 // The bucket can point to a linked list of different CDS's that have the same
2225 // body but different types. For example, 0,0,0,1 could be a 4 element array
2226 // of i8, or a 1-element array of i32. They'll both end up in the same
2227 /// StringMap bucket, linked up by their Next pointers. Walk the list.
2228 ConstantDataSequential **Entry = &Slot.getValue();
2229 for (ConstantDataSequential *Node = *Entry; Node != 0;
2230 Entry = &Node->Next, Node = *Entry)
2231 if (Node->getType() == Ty)
2232 return Node;
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002233
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002234 // Okay, we didn't get a hit. Create a node of the right class, link it in,
2235 // and return it.
2236 if (isa<ArrayType>(Ty))
2237 return *Entry = new ConstantDataArray(Ty, Slot.getKeyData());
2238
2239 assert(isa<VectorType>(Ty));
2240 return *Entry = new ConstantDataVector(Ty, Slot.getKeyData());
2241}
2242
2243void ConstantDataSequential::destroyConstant() {
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002244 // Remove the constant from the StringMap.
2245 StringMap<ConstantDataSequential*> &CDSConstants =
2246 getType()->getContext().pImpl->CDSConstants;
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002247
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002248 StringMap<ConstantDataSequential*>::iterator Slot =
Chris Lattner9e631da2012-01-24 09:31:43 +00002249 CDSConstants.find(getRawDataValues());
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002250
2251 assert(Slot != CDSConstants.end() && "CDS not found in uniquing table");
2252
2253 ConstantDataSequential **Entry = &Slot->getValue();
2254
2255 // Remove the entry from the hash table.
2256 if ((*Entry)->Next == 0) {
2257 // If there is only one value in the bucket (common case) it must be this
2258 // entry, and removing the entry should remove the bucket completely.
2259 assert((*Entry) == this && "Hash mismatch in ConstantDataSequential");
2260 getContext().pImpl->CDSConstants.erase(Slot);
2261 } else {
2262 // Otherwise, there are multiple entries linked off the bucket, unlink the
2263 // node we care about but keep the bucket around.
2264 for (ConstantDataSequential *Node = *Entry; ;
2265 Entry = &Node->Next, Node = *Entry) {
2266 assert(Node && "Didn't find entry in its uniquing hash table!");
2267 // If we found our entry, unlink it from the list and we're done.
2268 if (Node == this) {
2269 *Entry = Node->Next;
2270 break;
2271 }
2272 }
2273 }
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002274
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002275 // If we were part of a list, make sure that we don't delete the list that is
2276 // still owned by the uniquing map.
2277 Next = 0;
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002278
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002279 // Finally, actually delete it.
2280 destroyConstantImpl();
2281}
2282
2283/// get() constructors - Return a constant with array type with an element
2284/// count and element type matching the ArrayRef passed in. Note that this
2285/// can return a ConstantAggregateZero object.
Chris Lattner32100602012-01-24 14:04:40 +00002286Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint8_t> Elts) {
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002287 Type *Ty = ArrayType::get(Type::getInt8Ty(Context), Elts.size());
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002288 const char *Data = reinterpret_cast<const char *>(Elts.data());
2289 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*1), Ty);
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002290}
Chris Lattner32100602012-01-24 14:04:40 +00002291Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint16_t> Elts){
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002292 Type *Ty = ArrayType::get(Type::getInt16Ty(Context), Elts.size());
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002293 const char *Data = reinterpret_cast<const char *>(Elts.data());
2294 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*2), Ty);
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002295}
Chris Lattner32100602012-01-24 14:04:40 +00002296Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint32_t> Elts){
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002297 Type *Ty = ArrayType::get(Type::getInt32Ty(Context), Elts.size());
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002298 const char *Data = reinterpret_cast<const char *>(Elts.data());
2299 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002300}
Chris Lattner32100602012-01-24 14:04:40 +00002301Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint64_t> Elts){
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002302 Type *Ty = ArrayType::get(Type::getInt64Ty(Context), Elts.size());
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002303 const char *Data = reinterpret_cast<const char *>(Elts.data());
2304 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*8), Ty);
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002305}
Chris Lattner32100602012-01-24 14:04:40 +00002306Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<float> Elts) {
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002307 Type *Ty = ArrayType::get(Type::getFloatTy(Context), Elts.size());
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002308 const char *Data = reinterpret_cast<const char *>(Elts.data());
2309 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002310}
Chris Lattner32100602012-01-24 14:04:40 +00002311Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<double> Elts) {
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002312 Type *Ty = ArrayType::get(Type::getDoubleTy(Context), Elts.size());
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002313 const char *Data = reinterpret_cast<const char *>(Elts.data());
2314 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*8), Ty);
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002315}
2316
Chris Lattner32100602012-01-24 14:04:40 +00002317/// getString - This method constructs a CDS and initializes it with a text
2318/// string. The default behavior (AddNull==true) causes a null terminator to
2319/// be placed at the end of the array (increasing the length of the string by
2320/// one more than the StringRef would normally indicate. Pass AddNull=false
2321/// to disable this behavior.
2322Constant *ConstantDataArray::getString(LLVMContext &Context,
2323 StringRef Str, bool AddNull) {
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002324 if (!AddNull) {
2325 const uint8_t *Data = reinterpret_cast<const uint8_t *>(Str.data());
2326 return get(Context, ArrayRef<uint8_t>(const_cast<uint8_t *>(Data),
2327 Str.size()));
2328 }
2329
Chris Lattner32100602012-01-24 14:04:40 +00002330 SmallVector<uint8_t, 64> ElementVals;
2331 ElementVals.append(Str.begin(), Str.end());
2332 ElementVals.push_back(0);
2333 return get(Context, ElementVals);
2334}
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002335
2336/// get() constructors - Return a constant with vector type with an element
2337/// count and element type matching the ArrayRef passed in. Note that this
2338/// can return a ConstantAggregateZero object.
Chris Lattner32100602012-01-24 14:04:40 +00002339Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint8_t> Elts){
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002340 Type *Ty = VectorType::get(Type::getInt8Ty(Context), Elts.size());
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002341 const char *Data = reinterpret_cast<const char *>(Elts.data());
2342 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*1), Ty);
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002343}
Chris Lattner32100602012-01-24 14:04:40 +00002344Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint16_t> Elts){
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002345 Type *Ty = VectorType::get(Type::getInt16Ty(Context), Elts.size());
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002346 const char *Data = reinterpret_cast<const char *>(Elts.data());
2347 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*2), Ty);
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002348}
Chris Lattner32100602012-01-24 14:04:40 +00002349Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint32_t> Elts){
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002350 Type *Ty = VectorType::get(Type::getInt32Ty(Context), Elts.size());
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002351 const char *Data = reinterpret_cast<const char *>(Elts.data());
2352 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002353}
Chris Lattner32100602012-01-24 14:04:40 +00002354Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint64_t> Elts){
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002355 Type *Ty = VectorType::get(Type::getInt64Ty(Context), Elts.size());
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002356 const char *Data = reinterpret_cast<const char *>(Elts.data());
2357 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*8), Ty);
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002358}
Chris Lattner32100602012-01-24 14:04:40 +00002359Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<float> Elts) {
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002360 Type *Ty = VectorType::get(Type::getFloatTy(Context), Elts.size());
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002361 const char *Data = reinterpret_cast<const char *>(Elts.data());
2362 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002363}
Chris Lattner32100602012-01-24 14:04:40 +00002364Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<double> Elts) {
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002365 Type *Ty = VectorType::get(Type::getDoubleTy(Context), Elts.size());
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002366 const char *Data = reinterpret_cast<const char *>(Elts.data());
2367 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*8), Ty);
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002368}
2369
Chris Lattner3c2c9542012-01-25 05:19:54 +00002370Constant *ConstantDataVector::getSplat(unsigned NumElts, Constant *V) {
2371 assert(isElementTypeCompatible(V->getType()) &&
2372 "Element type not compatible with ConstantData");
2373 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
2374 if (CI->getType()->isIntegerTy(8)) {
2375 SmallVector<uint8_t, 16> Elts(NumElts, CI->getZExtValue());
2376 return get(V->getContext(), Elts);
2377 }
2378 if (CI->getType()->isIntegerTy(16)) {
2379 SmallVector<uint16_t, 16> Elts(NumElts, CI->getZExtValue());
2380 return get(V->getContext(), Elts);
2381 }
2382 if (CI->getType()->isIntegerTy(32)) {
2383 SmallVector<uint32_t, 16> Elts(NumElts, CI->getZExtValue());
2384 return get(V->getContext(), Elts);
2385 }
2386 assert(CI->getType()->isIntegerTy(64) && "Unsupported ConstantData type");
2387 SmallVector<uint64_t, 16> Elts(NumElts, CI->getZExtValue());
2388 return get(V->getContext(), Elts);
2389 }
2390
Chris Lattner36c744f2012-01-30 06:21:21 +00002391 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
2392 if (CFP->getType()->isFloatTy()) {
2393 SmallVector<float, 16> Elts(NumElts, CFP->getValueAPF().convertToFloat());
2394 return get(V->getContext(), Elts);
2395 }
2396 if (CFP->getType()->isDoubleTy()) {
2397 SmallVector<double, 16> Elts(NumElts,
2398 CFP->getValueAPF().convertToDouble());
2399 return get(V->getContext(), Elts);
2400 }
Chris Lattner3c2c9542012-01-25 05:19:54 +00002401 }
Chris Lattner36c744f2012-01-30 06:21:21 +00002402 return ConstantVector::getSplat(NumElts, V);
Chris Lattner3c2c9542012-01-25 05:19:54 +00002403}
2404
2405
Chris Lattner45bb5c52012-01-24 04:43:41 +00002406/// getElementAsInteger - If this is a sequential container of integers (of
2407/// any size), return the specified element in the low bits of a uint64_t.
2408uint64_t ConstantDataSequential::getElementAsInteger(unsigned Elt) const {
2409 assert(isa<IntegerType>(getElementType()) &&
2410 "Accessor can only be used when element is an integer");
2411 const char *EltPtr = getElementPointer(Elt);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002412
Chris Lattner45bb5c52012-01-24 04:43:41 +00002413 // The data is stored in host byte order, make sure to cast back to the right
2414 // type to load with the right endianness.
Chris Lattner230cdab2012-01-26 00:42:34 +00002415 switch (getElementType()->getIntegerBitWidth()) {
Craig Topper50bee422012-02-05 22:14:15 +00002416 default: llvm_unreachable("Invalid bitwidth for CDS");
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002417 case 8:
2418 return *const_cast<uint8_t *>(reinterpret_cast<const uint8_t *>(EltPtr));
2419 case 16:
2420 return *const_cast<uint16_t *>(reinterpret_cast<const uint16_t *>(EltPtr));
2421 case 32:
2422 return *const_cast<uint32_t *>(reinterpret_cast<const uint32_t *>(EltPtr));
2423 case 64:
2424 return *const_cast<uint64_t *>(reinterpret_cast<const uint64_t *>(EltPtr));
Chris Lattner45bb5c52012-01-24 04:43:41 +00002425 }
2426}
2427
2428/// getElementAsAPFloat - If this is a sequential container of floating point
2429/// type, return the specified element as an APFloat.
2430APFloat ConstantDataSequential::getElementAsAPFloat(unsigned Elt) const {
2431 const char *EltPtr = getElementPointer(Elt);
2432
2433 switch (getElementType()->getTypeID()) {
Nick Lewycky1486ae62012-01-25 03:20:12 +00002434 default:
Craig Topper50bee422012-02-05 22:14:15 +00002435 llvm_unreachable("Accessor can only be used when element is float/double!");
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002436 case Type::FloatTyID: {
2437 const float *FloatPrt = reinterpret_cast<const float *>(EltPtr);
2438 return APFloat(*const_cast<float *>(FloatPrt));
2439 }
2440 case Type::DoubleTyID: {
2441 const double *DoublePtr = reinterpret_cast<const double *>(EltPtr);
2442 return APFloat(*const_cast<double *>(DoublePtr));
2443 }
Chris Lattner45bb5c52012-01-24 04:43:41 +00002444 }
2445}
2446
2447/// getElementAsFloat - If this is an sequential container of floats, return
2448/// the specified element as a float.
2449float ConstantDataSequential::getElementAsFloat(unsigned Elt) const {
2450 assert(getElementType()->isFloatTy() &&
2451 "Accessor can only be used when element is a 'float'");
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002452 const float *EltPtr = reinterpret_cast<const float *>(getElementPointer(Elt));
2453 return *const_cast<float *>(EltPtr);
Chris Lattner45bb5c52012-01-24 04:43:41 +00002454}
2455
2456/// getElementAsDouble - If this is an sequential container of doubles, return
2457/// the specified element as a float.
2458double ConstantDataSequential::getElementAsDouble(unsigned Elt) const {
2459 assert(getElementType()->isDoubleTy() &&
2460 "Accessor can only be used when element is a 'float'");
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002461 const double *EltPtr =
2462 reinterpret_cast<const double *>(getElementPointer(Elt));
2463 return *const_cast<double *>(EltPtr);
Chris Lattner45bb5c52012-01-24 04:43:41 +00002464}
2465
2466/// getElementAsConstant - Return a Constant for a specified index's element.
2467/// Note that this has to compute a new constant to return, so it isn't as
2468/// efficient as getElementAsInteger/Float/Double.
2469Constant *ConstantDataSequential::getElementAsConstant(unsigned Elt) const {
2470 if (getElementType()->isFloatTy() || getElementType()->isDoubleTy())
2471 return ConstantFP::get(getContext(), getElementAsAPFloat(Elt));
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002472
Chris Lattner45bb5c52012-01-24 04:43:41 +00002473 return ConstantInt::get(getElementType(), getElementAsInteger(Elt));
2474}
2475
Chris Lattner62339072012-01-24 09:01:07 +00002476/// isString - This method returns true if this is an array of i8.
2477bool ConstantDataSequential::isString() const {
2478 return isa<ArrayType>(getType()) && getElementType()->isIntegerTy(8);
2479}
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002480
Chris Lattner62339072012-01-24 09:01:07 +00002481/// isCString - This method returns true if the array "isString", ends with a
2482/// nul byte, and does not contains any other nul bytes.
2483bool ConstantDataSequential::isCString() const {
2484 if (!isString())
2485 return false;
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002486
Chris Lattner62339072012-01-24 09:01:07 +00002487 StringRef Str = getAsString();
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002488
Chris Lattner62339072012-01-24 09:01:07 +00002489 // The last value must be nul.
2490 if (Str.back() != 0) return false;
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002491
Chris Lattner62339072012-01-24 09:01:07 +00002492 // Other elements must be non-nul.
2493 return Str.drop_back().find(0) == StringRef::npos;
2494}
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002495
Chris Lattnere150e2d2012-01-26 02:31:22 +00002496/// getSplatValue - If this is a splat constant, meaning that all of the
2497/// elements have the same value, return that value. Otherwise return NULL.
2498Constant *ConstantDataVector::getSplatValue() const {
2499 const char *Base = getRawDataValues().data();
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002500
Chris Lattnere150e2d2012-01-26 02:31:22 +00002501 // Compare elements 1+ to the 0'th element.
2502 unsigned EltSize = getElementByteSize();
2503 for (unsigned i = 1, e = getNumElements(); i != e; ++i)
2504 if (memcmp(Base, Base+i*EltSize, EltSize))
2505 return 0;
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002506
Chris Lattnere150e2d2012-01-26 02:31:22 +00002507 // If they're all the same, return the 0th one as a representative.
2508 return getElementAsConstant(0);
2509}
Chris Lattner04e3b1e2010-03-30 20:48:48 +00002510
Chris Lattner5cbade92005-10-03 21:58:36 +00002511//===----------------------------------------------------------------------===//
2512// replaceUsesOfWithOnConstant implementations
2513
Chris Lattner54984052007-08-21 00:55:23 +00002514/// replaceUsesOfWithOnConstant - Update this constant array to change uses of
2515/// 'From' to be uses of 'To'. This must update the uniquing data structures
2516/// etc.
2517///
2518/// Note that we intentionally replace all uses of From with To here. Consider
2519/// a large array that uses 'From' 1000 times. By handling this case all here,
2520/// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
2521/// single invocation handles all 1000 uses. Handling them one at a time would
2522/// work, but would be really slow because it would have to unique each updated
2523/// array instance.
Chris Lattner2ee11ec2009-10-28 00:01:44 +00002524///
Chris Lattner5cbade92005-10-03 21:58:36 +00002525void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattnerd0ff1ad2005-10-04 18:13:04 +00002526 Use *U) {
Owen Anderson1fd70962009-07-28 18:32:17 +00002527 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2528 Constant *ToC = cast<Constant>(To);
2529
Chris Lattner1afcace2011-07-09 17:41:24 +00002530 LLVMContextImpl *pImpl = getType()->getContext().pImpl;
Owen Anderson1fd70962009-07-28 18:32:17 +00002531
Talin2cb395e2012-02-05 20:54:10 +00002532 SmallVector<Constant*, 8> Values;
2533 LLVMContextImpl::ArrayConstantsTy::LookupKey Lookup;
2534 Lookup.first = cast<ArrayType>(getType());
Owen Anderson1fd70962009-07-28 18:32:17 +00002535 Values.reserve(getNumOperands()); // Build replacement array.
2536
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002537 // Fill values with the modified operands of the constant array. Also,
Owen Anderson1fd70962009-07-28 18:32:17 +00002538 // compute whether this turns into an all-zeros array.
Owen Anderson1fd70962009-07-28 18:32:17 +00002539 unsigned NumUpdated = 0;
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002540
Chris Lattnere150e2d2012-01-26 02:31:22 +00002541 // Keep track of whether all the values in the array are "ToC".
2542 bool AllSame = true;
2543 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2544 Constant *Val = cast<Constant>(O->get());
2545 if (Val == From) {
2546 Val = ToC;
2547 ++NumUpdated;
Owen Anderson1fd70962009-07-28 18:32:17 +00002548 }
Chris Lattnere150e2d2012-01-26 02:31:22 +00002549 Values.push_back(Val);
Talin2cb395e2012-02-05 20:54:10 +00002550 AllSame &= Val == ToC;
Owen Anderson1fd70962009-07-28 18:32:17 +00002551 }
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002552
Owen Anderson1fd70962009-07-28 18:32:17 +00002553 Constant *Replacement = 0;
Chris Lattnere150e2d2012-01-26 02:31:22 +00002554 if (AllSame && ToC->isNullValue()) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002555 Replacement = ConstantAggregateZero::get(getType());
Chris Lattnere150e2d2012-01-26 02:31:22 +00002556 } else if (AllSame && isa<UndefValue>(ToC)) {
2557 Replacement = UndefValue::get(getType());
Owen Anderson1fd70962009-07-28 18:32:17 +00002558 } else {
2559 // Check to see if we have this array type already.
Talin2cb395e2012-02-05 20:54:10 +00002560 Lookup.second = makeArrayRef(Values);
Owen Anderson1fd70962009-07-28 18:32:17 +00002561 LLVMContextImpl::ArrayConstantsTy::MapTy::iterator I =
Talin2cb395e2012-02-05 20:54:10 +00002562 pImpl->ArrayConstants.find(Lookup);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002563
Talin2cb395e2012-02-05 20:54:10 +00002564 if (I != pImpl->ArrayConstants.map_end()) {
2565 Replacement = I->first;
Owen Anderson1fd70962009-07-28 18:32:17 +00002566 } else {
2567 // Okay, the new shape doesn't exist in the system yet. Instead of
2568 // creating a new constant array, inserting it, replaceallusesof'ing the
2569 // old with the new, then deleting the old... just update the current one
2570 // in place!
Talin2cb395e2012-02-05 20:54:10 +00002571 pImpl->ArrayConstants.remove(this);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002572
Owen Anderson1fd70962009-07-28 18:32:17 +00002573 // Update to the new value. Optimize for the case when we have a single
2574 // operand that we're changing, but handle bulk updates efficiently.
2575 if (NumUpdated == 1) {
2576 unsigned OperandToUpdate = U - OperandList;
2577 assert(getOperand(OperandToUpdate) == From &&
2578 "ReplaceAllUsesWith broken!");
2579 setOperand(OperandToUpdate, ToC);
2580 } else {
2581 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2582 if (getOperand(i) == From)
2583 setOperand(i, ToC);
2584 }
Talin2cb395e2012-02-05 20:54:10 +00002585 pImpl->ArrayConstants.insert(this);
Owen Anderson1fd70962009-07-28 18:32:17 +00002586 return;
2587 }
2588 }
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002589
Chris Lattnercea141f2005-10-03 22:51:37 +00002590 // Otherwise, I do need to replace this with an existing value.
Chris Lattner5cbade92005-10-03 21:58:36 +00002591 assert(Replacement != this && "I didn't contain From!");
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002592
Chris Lattnerd0ff1ad2005-10-04 18:13:04 +00002593 // Everyone using this now uses the replacement.
Chris Lattner678f9e02011-07-15 06:18:52 +00002594 replaceAllUsesWith(Replacement);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002595
Chris Lattner5cbade92005-10-03 21:58:36 +00002596 // Delete the old constant!
2597 destroyConstant();
2598}
2599
2600void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattnerd0ff1ad2005-10-04 18:13:04 +00002601 Use *U) {
Owen Anderson8fa33382009-07-27 22:29:26 +00002602 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2603 Constant *ToC = cast<Constant>(To);
2604
2605 unsigned OperandToUpdate = U-OperandList;
2606 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2607
Talin2cb395e2012-02-05 20:54:10 +00002608 SmallVector<Constant*, 8> Values;
2609 LLVMContextImpl::StructConstantsTy::LookupKey Lookup;
2610 Lookup.first = cast<StructType>(getType());
Owen Anderson8fa33382009-07-27 22:29:26 +00002611 Values.reserve(getNumOperands()); // Build replacement struct.
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002612
2613 // Fill values with the modified operands of the constant struct. Also,
Owen Anderson8fa33382009-07-27 22:29:26 +00002614 // compute whether this turns into an all-zeros struct.
2615 bool isAllZeros = false;
Chris Lattnere150e2d2012-01-26 02:31:22 +00002616 bool isAllUndef = false;
2617 if (ToC->isNullValue()) {
Owen Anderson8fa33382009-07-27 22:29:26 +00002618 isAllZeros = true;
2619 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2620 Constant *Val = cast<Constant>(O->get());
2621 Values.push_back(Val);
2622 if (isAllZeros) isAllZeros = Val->isNullValue();
2623 }
Chris Lattnere150e2d2012-01-26 02:31:22 +00002624 } else if (isa<UndefValue>(ToC)) {
2625 isAllUndef = true;
2626 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2627 Constant *Val = cast<Constant>(O->get());
2628 Values.push_back(Val);
2629 if (isAllUndef) isAllUndef = isa<UndefValue>(Val);
2630 }
2631 } else {
2632 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O)
2633 Values.push_back(cast<Constant>(O->get()));
Owen Anderson8fa33382009-07-27 22:29:26 +00002634 }
2635 Values[OperandToUpdate] = ToC;
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002636
Chris Lattner1afcace2011-07-09 17:41:24 +00002637 LLVMContextImpl *pImpl = getContext().pImpl;
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002638
Owen Anderson8fa33382009-07-27 22:29:26 +00002639 Constant *Replacement = 0;
2640 if (isAllZeros) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002641 Replacement = ConstantAggregateZero::get(getType());
Chris Lattnere150e2d2012-01-26 02:31:22 +00002642 } else if (isAllUndef) {
2643 Replacement = UndefValue::get(getType());
Owen Anderson8fa33382009-07-27 22:29:26 +00002644 } else {
Chris Lattner93604b62010-07-17 06:13:52 +00002645 // Check to see if we have this struct type already.
Talin2cb395e2012-02-05 20:54:10 +00002646 Lookup.second = makeArrayRef(Values);
Owen Anderson8fa33382009-07-27 22:29:26 +00002647 LLVMContextImpl::StructConstantsTy::MapTy::iterator I =
Talin2cb395e2012-02-05 20:54:10 +00002648 pImpl->StructConstants.find(Lookup);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002649
Talin2cb395e2012-02-05 20:54:10 +00002650 if (I != pImpl->StructConstants.map_end()) {
2651 Replacement = I->first;
Owen Anderson8fa33382009-07-27 22:29:26 +00002652 } else {
2653 // Okay, the new shape doesn't exist in the system yet. Instead of
2654 // creating a new constant struct, inserting it, replaceallusesof'ing the
2655 // old with the new, then deleting the old... just update the current one
2656 // in place!
Talin2cb395e2012-02-05 20:54:10 +00002657 pImpl->StructConstants.remove(this);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002658
Owen Anderson8fa33382009-07-27 22:29:26 +00002659 // Update to the new value.
2660 setOperand(OperandToUpdate, ToC);
Talin2cb395e2012-02-05 20:54:10 +00002661 pImpl->StructConstants.insert(this);
Owen Anderson8fa33382009-07-27 22:29:26 +00002662 return;
2663 }
2664 }
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002665
Owen Anderson8fa33382009-07-27 22:29:26 +00002666 assert(Replacement != this && "I didn't contain From!");
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002667
Chris Lattnerd0ff1ad2005-10-04 18:13:04 +00002668 // Everyone using this now uses the replacement.
Chris Lattner678f9e02011-07-15 06:18:52 +00002669 replaceAllUsesWith(Replacement);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002670
Chris Lattner5cbade92005-10-03 21:58:36 +00002671 // Delete the old constant!
2672 destroyConstant();
2673}
2674
Reid Spencer9d6565a2007-02-15 02:26:10 +00002675void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattnerd0ff1ad2005-10-04 18:13:04 +00002676 Use *U) {
Chris Lattner5cbade92005-10-03 21:58:36 +00002677 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002678
Chris Lattnera7c69882012-01-26 20:40:56 +00002679 SmallVector<Constant*, 8> Values;
Chris Lattner5cbade92005-10-03 21:58:36 +00002680 Values.reserve(getNumOperands()); // Build replacement array...
2681 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2682 Constant *Val = getOperand(i);
2683 if (Val == From) Val = cast<Constant>(To);
2684 Values.push_back(Val);
2685 }
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002686
Jay Foada0c13842011-06-22 09:10:19 +00002687 Constant *Replacement = get(Values);
Chris Lattner5cbade92005-10-03 21:58:36 +00002688 assert(Replacement != this && "I didn't contain From!");
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002689
Chris Lattnerd0ff1ad2005-10-04 18:13:04 +00002690 // Everyone using this now uses the replacement.
Chris Lattner678f9e02011-07-15 06:18:52 +00002691 replaceAllUsesWith(Replacement);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002692
Chris Lattner5cbade92005-10-03 21:58:36 +00002693 // Delete the old constant!
2694 destroyConstant();
2695}
2696
2697void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
Chris Lattnerd0ff1ad2005-10-04 18:13:04 +00002698 Use *U) {
Chris Lattner5cbade92005-10-03 21:58:36 +00002699 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2700 Constant *To = cast<Constant>(ToV);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002701
Chris Lattner1a8def62012-01-26 20:37:11 +00002702 SmallVector<Constant*, 8> NewOps;
2703 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2704 Constant *Op = getOperand(i);
2705 NewOps.push_back(Op == From ? To : Op);
Chris Lattner5cbade92005-10-03 21:58:36 +00002706 }
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002707
Chris Lattner1a8def62012-01-26 20:37:11 +00002708 Constant *Replacement = getWithOperands(NewOps);
Chris Lattner5cbade92005-10-03 21:58:36 +00002709 assert(Replacement != this && "I didn't contain From!");
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002710
Chris Lattnerd0ff1ad2005-10-04 18:13:04 +00002711 // Everyone using this now uses the replacement.
Chris Lattner678f9e02011-07-15 06:18:52 +00002712 replaceAllUsesWith(Replacement);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002713
Chris Lattner5cbade92005-10-03 21:58:36 +00002714 // Delete the old constant!
2715 destroyConstant();
Matthijs Kooijman10b9de62008-07-03 07:46:41 +00002716}
James Molloyb9478c22012-11-17 17:56:30 +00002717
2718Instruction *ConstantExpr::getAsInstruction() {
2719 SmallVector<Value*,4> ValueOperands;
2720 for (op_iterator I = op_begin(), E = op_end(); I != E; ++I)
2721 ValueOperands.push_back(cast<Value>(I));
2722
2723 ArrayRef<Value*> Ops(ValueOperands);
2724
2725 switch (getOpcode()) {
2726 case Instruction::Trunc:
2727 case Instruction::ZExt:
2728 case Instruction::SExt:
2729 case Instruction::FPTrunc:
2730 case Instruction::FPExt:
2731 case Instruction::UIToFP:
2732 case Instruction::SIToFP:
2733 case Instruction::FPToUI:
2734 case Instruction::FPToSI:
2735 case Instruction::PtrToInt:
2736 case Instruction::IntToPtr:
2737 case Instruction::BitCast:
2738 return CastInst::Create((Instruction::CastOps)getOpcode(),
2739 Ops[0], getType());
2740 case Instruction::Select:
2741 return SelectInst::Create(Ops[0], Ops[1], Ops[2]);
2742 case Instruction::InsertElement:
2743 return InsertElementInst::Create(Ops[0], Ops[1], Ops[2]);
2744 case Instruction::ExtractElement:
2745 return ExtractElementInst::Create(Ops[0], Ops[1]);
2746 case Instruction::InsertValue:
2747 return InsertValueInst::Create(Ops[0], Ops[1], getIndices());
2748 case Instruction::ExtractValue:
2749 return ExtractValueInst::Create(Ops[0], getIndices());
2750 case Instruction::ShuffleVector:
2751 return new ShuffleVectorInst(Ops[0], Ops[1], Ops[2]);
2752
2753 case Instruction::GetElementPtr:
2754 if (cast<GEPOperator>(this)->isInBounds())
2755 return GetElementPtrInst::CreateInBounds(Ops[0], Ops.slice(1));
2756 else
2757 return GetElementPtrInst::Create(Ops[0], Ops.slice(1));
2758
2759 case Instruction::ICmp:
2760 case Instruction::FCmp:
2761 return CmpInst::Create((Instruction::OtherOps)getOpcode(),
2762 getPredicate(), Ops[0], Ops[1]);
2763
2764 default:
2765 assert(getNumOperands() == 2 && "Must be binary operator?");
2766 BinaryOperator *BO =
2767 BinaryOperator::Create((Instruction::BinaryOps)getOpcode(),
2768 Ops[0], Ops[1]);
2769 if (isa<OverflowingBinaryOperator>(BO)) {
2770 BO->setHasNoUnsignedWrap(SubclassOptionalData &
2771 OverflowingBinaryOperator::NoUnsignedWrap);
2772 BO->setHasNoSignedWrap(SubclassOptionalData &
2773 OverflowingBinaryOperator::NoSignedWrap);
2774 }
2775 if (isa<PossiblyExactOperator>(BO))
2776 BO->setIsExact(SubclassOptionalData & PossiblyExactOperator::IsExact);
2777 return BO;
2778 }
2779}