blob: dc017b355af34beec69074a75d9f3234c5fa617e [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//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source 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 Lattnere9bb2df2001-12-03 22:26:30 +000010// This file implements the Constant* classes...
Chris Lattner00950542001-06-06 20:29:01 +000011//
12//===----------------------------------------------------------------------===//
13
Chris Lattner31bcdb82002-04-28 19:55:58 +000014#include "llvm/Constants.h"
Chris Lattnercbfd4062004-01-12 21:13:12 +000015#include "ConstantFolding.h"
Chris Lattner00950542001-06-06 20:29:01 +000016#include "llvm/DerivedTypes.h"
Reid Spencer1c9c8e62004-07-17 23:48:33 +000017#include "llvm/GlobalValue.h"
Misha Brukman47b14a42004-07-29 17:30:56 +000018#include "llvm/Instructions.h"
Chris Lattnerf5ec48d2001-10-13 06:57:33 +000019#include "llvm/Module.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000020#include "llvm/ADT/StringExtras.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000021#include "llvm/Support/Compiler.h"
Bill Wendling2e3def12006-11-17 08:03:48 +000022#include "llvm/Support/Debug.h"
Chris Lattner8a94bf12006-09-28 00:35:06 +000023#include "llvm/Support/ManagedStatic.h"
Bill Wendling2e3def12006-11-17 08:03:48 +000024#include "llvm/Support/MathExtras.h"
Chris Lattner6b6f6ba2007-02-20 06:39:57 +000025#include "llvm/ADT/DenseMap.h"
Chris Lattnerf9021ff2007-02-19 20:01:23 +000026#include "llvm/ADT/SmallVector.h"
Chris Lattner00950542001-06-06 20:29:01 +000027#include <algorithm>
Reid Spenceref9b9a72007-02-05 20:47:22 +000028#include <map>
Chris Lattner31f84992003-11-21 20:23:48 +000029using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000030
Chris Lattner00950542001-06-06 20:29:01 +000031//===----------------------------------------------------------------------===//
Chris Lattnere9bb2df2001-12-03 22:26:30 +000032// Constant Class
Chris Lattner00950542001-06-06 20:29:01 +000033//===----------------------------------------------------------------------===//
34
Chris Lattnere9bb2df2001-12-03 22:26:30 +000035void Constant::destroyConstantImpl() {
36 // When a Constant is destroyed, there may be lingering
Chris Lattnerf5ec48d2001-10-13 06:57:33 +000037 // references to the constant by other constants in the constant pool. These
Misha Brukmanef6a6a62003-08-21 22:14:26 +000038 // constants are implicitly dependent on the module that is being deleted,
Chris Lattnerf5ec48d2001-10-13 06:57:33 +000039 // but they don't know that. Because we only find out when the CPV is
40 // deleted, we must now notify all of our users (that should only be
Chris Lattnere9bb2df2001-12-03 22:26:30 +000041 // Constants) that they are, in fact, invalid now and should be deleted.
Chris Lattnerf5ec48d2001-10-13 06:57:33 +000042 //
43 while (!use_empty()) {
44 Value *V = use_back();
45#ifndef NDEBUG // Only in -g mode...
Chris Lattner6183b922002-07-18 00:14:50 +000046 if (!isa<Constant>(V))
Bill Wendling2e3def12006-11-17 08:03:48 +000047 DOUT << "While deleting: " << *this
48 << "\n\nUse still stuck around after Def is destroyed: "
49 << *V << "\n\n";
Chris Lattnerf5ec48d2001-10-13 06:57:33 +000050#endif
Vikram S. Adve345e0cf2002-07-14 23:13:17 +000051 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
Reid Spencer1c9c8e62004-07-17 23:48:33 +000052 Constant *CV = cast<Constant>(V);
53 CV->destroyConstant();
Chris Lattnerf5ec48d2001-10-13 06:57:33 +000054
55 // The constant should remove itself from our use list...
Vikram S. Adve345e0cf2002-07-14 23:13:17 +000056 assert((use_empty() || use_back() != V) && "Constant not removed!");
Chris Lattnerf5ec48d2001-10-13 06:57:33 +000057 }
58
59 // Value has no outstanding references it is safe to delete it now...
60 delete this;
Chris Lattner1d87bcf2001-10-01 20:11:19 +000061}
Chris Lattner00950542001-06-06 20:29:01 +000062
Chris Lattner35b89fa2006-10-20 00:27:06 +000063/// canTrap - Return true if evaluation of this constant could trap. This is
64/// true for things like constant expressions that could divide by zero.
65bool Constant::canTrap() const {
66 assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
67 // The only thing that could possibly trap are constant exprs.
68 const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
69 if (!CE) return false;
70
71 // ConstantExpr traps if any operands can trap.
72 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
73 if (getOperand(i)->canTrap())
74 return true;
75
76 // Otherwise, only specific operations can trap.
77 switch (CE->getOpcode()) {
78 default:
79 return false;
Reid Spencer1628cec2006-10-26 06:15:43 +000080 case Instruction::UDiv:
81 case Instruction::SDiv:
82 case Instruction::FDiv:
Reid Spencer0a783f72006-11-02 01:53:59 +000083 case Instruction::URem:
84 case Instruction::SRem:
85 case Instruction::FRem:
Chris Lattner35b89fa2006-10-20 00:27:06 +000086 // Div and rem can trap if the RHS is not known to be non-zero.
87 if (!isa<ConstantInt>(getOperand(1)) || getOperand(1)->isNullValue())
88 return true;
89 return false;
90 }
91}
92
Chris Lattner9fb96412002-08-13 17:50:20 +000093// Static constructor to create a '0' constant of arbitrary type...
94Constant *Constant::getNullValue(const Type *Ty) {
Chris Lattnerf70c22b2004-06-17 18:19:28 +000095 switch (Ty->getTypeID()) {
Chris Lattnere0e76962007-02-20 05:46:39 +000096 case Type::IntegerTyID:
97 return ConstantInt::get(Ty, 0);
98 case Type::FloatTyID:
99 case Type::DoubleTyID:
100 return ConstantFP::get(Ty, 0.0);
Misha Brukmanfd939082005-04-21 23:48:37 +0000101 case Type::PointerTyID:
Chris Lattner9fb96412002-08-13 17:50:20 +0000102 return ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattner40bbeb52004-02-15 05:53:04 +0000103 case Type::StructTyID:
104 case Type::ArrayTyID:
Reid Spencer9d6565a2007-02-15 02:26:10 +0000105 case Type::VectorTyID:
Chris Lattner40bbeb52004-02-15 05:53:04 +0000106 return ConstantAggregateZero::get(Ty);
Chris Lattner9fb96412002-08-13 17:50:20 +0000107 default:
Reid Spencer57f6efc2004-07-04 11:51:24 +0000108 // Function, Label, or Opaque type?
109 assert(!"Cannot create a null constant of that type!");
Chris Lattner9fb96412002-08-13 17:50:20 +0000110 return 0;
111 }
112}
113
Chris Lattner9fb96412002-08-13 17:50:20 +0000114
115// Static constructor to create an integral constant with all bits set
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000116ConstantInt *ConstantInt::getAllOnesValue(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000117 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
118 if (ITy->getBitWidth() == 1)
119 return ConstantInt::getTrue();
120 else
121 return ConstantInt::get(Ty, int64_t(-1));
122 return 0;
Chris Lattner9fb96412002-08-13 17:50:20 +0000123}
124
Chris Lattner58513aa2007-01-04 01:49:26 +0000125/// @returns the value for an packed integer constant of the given type that
126/// has all its bits set to true.
127/// @brief Get the all ones value
Reid Spencer9d6565a2007-02-15 02:26:10 +0000128ConstantVector *ConstantVector::getAllOnesValue(const VectorType *Ty) {
Chris Lattner58513aa2007-01-04 01:49:26 +0000129 std::vector<Constant*> Elts;
130 Elts.resize(Ty->getNumElements(),
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000131 ConstantInt::getAllOnesValue(Ty->getElementType()));
Chris Lattner58513aa2007-01-04 01:49:26 +0000132 assert(Elts[0] && "Not a packed integer type!");
Reid Spencer9d6565a2007-02-15 02:26:10 +0000133 return cast<ConstantVector>(ConstantVector::get(Elts));
Chris Lattner58513aa2007-01-04 01:49:26 +0000134}
135
136
Chris Lattner00950542001-06-06 20:29:01 +0000137//===----------------------------------------------------------------------===//
Chris Lattner6b6f6ba2007-02-20 06:39:57 +0000138// ConstantInt
Chris Lattner00950542001-06-06 20:29:01 +0000139//===----------------------------------------------------------------------===//
140
Reid Spencer532d0ce2007-02-26 23:54:03 +0000141ConstantInt::ConstantInt(const IntegerType *Ty, const APInt& V)
Chris Lattnereb41bdd2007-02-20 05:55:46 +0000142 : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
Reid Spencer532d0ce2007-02-26 23:54:03 +0000143 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
Chris Lattner00950542001-06-06 20:29:01 +0000144}
145
Chris Lattner6b6f6ba2007-02-20 06:39:57 +0000146ConstantInt *ConstantInt::TheTrueVal = 0;
147ConstantInt *ConstantInt::TheFalseVal = 0;
148
149namespace llvm {
150 void CleanupTrueFalse(void *) {
151 ConstantInt::ResetTrueFalse();
152 }
153}
154
155static ManagedCleanup<llvm::CleanupTrueFalse> TrueFalseCleanup;
156
157ConstantInt *ConstantInt::CreateTrueFalseVals(bool WhichOne) {
158 assert(TheTrueVal == 0 && TheFalseVal == 0);
159 TheTrueVal = get(Type::Int1Ty, 1);
160 TheFalseVal = get(Type::Int1Ty, 0);
161
162 // Ensure that llvm_shutdown nulls out TheTrueVal/TheFalseVal.
163 TrueFalseCleanup.Register();
164
165 return WhichOne ? TheTrueVal : TheFalseVal;
166}
167
168
Chris Lattner6b6f6ba2007-02-20 06:39:57 +0000169namespace {
Reid Spencer532d0ce2007-02-26 23:54:03 +0000170 struct DenseMapAPIntKeyInfo {
171 struct KeyTy {
172 APInt val;
173 const Type* type;
174 KeyTy(const APInt& V, const Type* Ty) : val(V), type(Ty) {}
175 KeyTy(const KeyTy& that) : val(that.val), type(that.type) {}
176 bool operator==(const KeyTy& that) const {
177 return type == that.type && this->val == that.val;
178 }
179 bool operator!=(const KeyTy& that) const {
180 return !this->operator==(that);
181 }
182 };
183 static inline KeyTy getEmptyKey() { return KeyTy(APInt(1,0), 0); }
184 static inline KeyTy getTombstoneKey() { return KeyTy(APInt(1,1), 0); }
Chris Lattner6b6f6ba2007-02-20 06:39:57 +0000185 static unsigned getHashValue(const KeyTy &Key) {
Reid Spencer532d0ce2007-02-26 23:54:03 +0000186 return DenseMapKeyInfo<void*>::getHashValue(Key.type) ^
187 Key.val.getHashValue();
Chris Lattner6b6f6ba2007-02-20 06:39:57 +0000188 }
189 static bool isPod() { return true; }
190 };
191}
192
193
Reid Spencer532d0ce2007-02-26 23:54:03 +0000194typedef DenseMap<DenseMapAPIntKeyInfo::KeyTy, ConstantInt*,
195 DenseMapAPIntKeyInfo> IntMapTy;
Chris Lattner6b6f6ba2007-02-20 06:39:57 +0000196static ManagedStatic<IntMapTy> IntConstants;
197
Chris Lattner6b6f6ba2007-02-20 06:39:57 +0000198ConstantInt *ConstantInt::get(const Type *Ty, int64_t V) {
199 const IntegerType *ITy = cast<IntegerType>(Ty);
Reid Spencer532d0ce2007-02-26 23:54:03 +0000200 APInt Tmp(ITy->getBitWidth(), V);
201 return get(Ty, Tmp);
202}
203
204// Get a ConstantInt from a Type and APInt. Note that the value stored in
205// the DenseMap as the key is a DensMapAPIntKeyInfo::KeyTy which has provided
206// operator== and operator!= to ensure that the DenseMap doesn't attempt to
207// compare APInt's of different widths, which would violate an APInt class
208// invariant which generates an assertion.
209ConstantInt *ConstantInt::get(const Type *Ty, const APInt& V) {
210 const IntegerType *ITy = cast<IntegerType>(Ty);
211 assert(ITy->getBitWidth() == V.getBitWidth() && "Invalid type for constant");
212 // get an existing value or the insertion position
213 DenseMapAPIntKeyInfo::KeyTy Key(V, Ty);
214 ConstantInt *&Slot = (*IntConstants)[Key];
215 // if it exists, return it.
216 if (Slot)
217 return Slot;
218 // otherwise create a new one, insert it, and return it.
Chris Lattner6b6f6ba2007-02-20 06:39:57 +0000219 return Slot = new ConstantInt(ITy, V);
220}
221
222//===----------------------------------------------------------------------===//
Chris Lattner9b4ee0c2007-02-20 07:17:17 +0000223// ConstantFP
Chris Lattner6b6f6ba2007-02-20 06:39:57 +0000224//===----------------------------------------------------------------------===//
225
226
Chris Lattnere4671472005-01-29 00:34:39 +0000227ConstantFP::ConstantFP(const Type *Ty, double V)
Chris Lattnerdf0ef1d2005-09-27 06:09:08 +0000228 : Constant(Ty, ConstantFPVal, 0, 0) {
Chris Lattner00950542001-06-06 20:29:01 +0000229 Val = V;
230}
231
Chris Lattner9b4ee0c2007-02-20 07:17:17 +0000232bool ConstantFP::isNullValue() const {
233 return DoubleToBits(Val) == 0;
234}
235
236bool ConstantFP::isExactlyValue(double V) const {
237 return DoubleToBits(V) == DoubleToBits(Val);
238}
239
240
241namespace {
Reid Spencer532d0ce2007-02-26 23:54:03 +0000242 struct DenseMapInt64KeyInfo {
243 typedef std::pair<uint64_t, const Type*> KeyTy;
244 static inline KeyTy getEmptyKey() { return KeyTy(0, 0); }
245 static inline KeyTy getTombstoneKey() { return KeyTy(1, 0); }
246 static unsigned getHashValue(const KeyTy &Key) {
247 return DenseMapKeyInfo<void*>::getHashValue(Key.second) ^ Key.first;
248 }
249 static bool isPod() { return true; }
250 };
Chris Lattner9b4ee0c2007-02-20 07:17:17 +0000251 struct DenseMapInt32KeyInfo {
252 typedef std::pair<uint32_t, const Type*> KeyTy;
253 static inline KeyTy getEmptyKey() { return KeyTy(0, 0); }
254 static inline KeyTy getTombstoneKey() { return KeyTy(1, 0); }
255 static unsigned getHashValue(const KeyTy &Key) {
256 return DenseMapKeyInfo<void*>::getHashValue(Key.second) ^ Key.first;
257 }
258 static bool isPod() { return true; }
259 };
260}
261
262//---- ConstantFP::get() implementation...
263//
264typedef DenseMap<DenseMapInt32KeyInfo::KeyTy, ConstantFP*,
265 DenseMapInt32KeyInfo> FloatMapTy;
266typedef DenseMap<DenseMapInt64KeyInfo::KeyTy, ConstantFP*,
267 DenseMapInt64KeyInfo> DoubleMapTy;
268
269static ManagedStatic<FloatMapTy> FloatConstants;
270static ManagedStatic<DoubleMapTy> DoubleConstants;
271
272ConstantFP *ConstantFP::get(const Type *Ty, double V) {
273 if (Ty == Type::FloatTy) {
274 uint32_t IntVal = FloatToBits((float)V);
275
276 ConstantFP *&Slot = (*FloatConstants)[std::make_pair(IntVal, Ty)];
277 if (Slot) return Slot;
278 return Slot = new ConstantFP(Ty, (float)V);
279 } else {
280 assert(Ty == Type::DoubleTy);
281 uint64_t IntVal = DoubleToBits(V);
282 ConstantFP *&Slot = (*DoubleConstants)[std::make_pair(IntVal, Ty)];
283 if (Slot) return Slot;
Evan Chenge8116362007-02-20 21:30:56 +0000284 return Slot = new ConstantFP(Ty, V);
Chris Lattner9b4ee0c2007-02-20 07:17:17 +0000285 }
286}
287
288
289//===----------------------------------------------------------------------===//
290// ConstantXXX Classes
291//===----------------------------------------------------------------------===//
292
293
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000294ConstantArray::ConstantArray(const ArrayType *T,
Chris Lattnere4671472005-01-29 00:34:39 +0000295 const std::vector<Constant*> &V)
Chris Lattnerdf0ef1d2005-09-27 06:09:08 +0000296 : Constant(T, ConstantArrayVal, new Use[V.size()], V.size()) {
Alkis Evlogimenose0de1d62004-09-15 02:32:15 +0000297 assert(V.size() == T->getNumElements() &&
298 "Invalid initializer vector for constant array");
Chris Lattnere4671472005-01-29 00:34:39 +0000299 Use *OL = OperandList;
Chris Lattnerdfdd6c52005-10-03 21:56:24 +0000300 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
301 I != E; ++I, ++OL) {
Chris Lattner71abaab2005-10-07 05:23:36 +0000302 Constant *C = *I;
303 assert((C->getType() == T->getElementType() ||
Alkis Evlogimenoscad90ad2004-09-10 04:16:59 +0000304 (T->isAbstract() &&
Chris Lattner71abaab2005-10-07 05:23:36 +0000305 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
Alkis Evlogimenoscad90ad2004-09-10 04:16:59 +0000306 "Initializer for array element doesn't match array element type!");
Chris Lattner71abaab2005-10-07 05:23:36 +0000307 OL->init(C, this);
Chris Lattner00950542001-06-06 20:29:01 +0000308 }
309}
310
Chris Lattnere4671472005-01-29 00:34:39 +0000311ConstantArray::~ConstantArray() {
312 delete [] OperandList;
313}
314
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000315ConstantStruct::ConstantStruct(const StructType *T,
Chris Lattnere4671472005-01-29 00:34:39 +0000316 const std::vector<Constant*> &V)
Chris Lattnerdf0ef1d2005-09-27 06:09:08 +0000317 : Constant(T, ConstantStructVal, new Use[V.size()], V.size()) {
Chris Lattnerd21cd802004-02-09 04:37:31 +0000318 assert(V.size() == T->getNumElements() &&
Vikram S. Adve345e0cf2002-07-14 23:13:17 +0000319 "Invalid initializer vector for constant structure");
Chris Lattnere4671472005-01-29 00:34:39 +0000320 Use *OL = OperandList;
Chris Lattnerdfdd6c52005-10-03 21:56:24 +0000321 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
322 I != E; ++I, ++OL) {
Chris Lattner71abaab2005-10-07 05:23:36 +0000323 Constant *C = *I;
324 assert((C->getType() == T->getElementType(I-V.begin()) ||
Chris Lattnerdfdd6c52005-10-03 21:56:24 +0000325 ((T->getElementType(I-V.begin())->isAbstract() ||
Chris Lattner71abaab2005-10-07 05:23:36 +0000326 C->getType()->isAbstract()) &&
Chris Lattnerdfdd6c52005-10-03 21:56:24 +0000327 T->getElementType(I-V.begin())->getTypeID() ==
Chris Lattner71abaab2005-10-07 05:23:36 +0000328 C->getType()->getTypeID())) &&
Chris Lattnerb8438892003-06-02 17:42:47 +0000329 "Initializer for struct element doesn't match struct element type!");
Chris Lattner71abaab2005-10-07 05:23:36 +0000330 OL->init(C, this);
Chris Lattner00950542001-06-06 20:29:01 +0000331 }
332}
333
Chris Lattnere4671472005-01-29 00:34:39 +0000334ConstantStruct::~ConstantStruct() {
335 delete [] OperandList;
336}
337
338
Reid Spencer9d6565a2007-02-15 02:26:10 +0000339ConstantVector::ConstantVector(const VectorType *T,
Chris Lattnere4671472005-01-29 00:34:39 +0000340 const std::vector<Constant*> &V)
Reid Spencer9d6565a2007-02-15 02:26:10 +0000341 : Constant(T, ConstantVectorVal, new Use[V.size()], V.size()) {
Chris Lattnere4671472005-01-29 00:34:39 +0000342 Use *OL = OperandList;
Chris Lattnerdfdd6c52005-10-03 21:56:24 +0000343 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
344 I != E; ++I, ++OL) {
Chris Lattner71abaab2005-10-07 05:23:36 +0000345 Constant *C = *I;
346 assert((C->getType() == T->getElementType() ||
Alkis Evlogimenoscad90ad2004-09-10 04:16:59 +0000347 (T->isAbstract() &&
Chris Lattner71abaab2005-10-07 05:23:36 +0000348 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
Alkis Evlogimenoscad90ad2004-09-10 04:16:59 +0000349 "Initializer for packed element doesn't match packed element type!");
Chris Lattner71abaab2005-10-07 05:23:36 +0000350 OL->init(C, this);
Brian Gaeke715c90b2004-08-20 06:00:58 +0000351 }
352}
353
Reid Spencer9d6565a2007-02-15 02:26:10 +0000354ConstantVector::~ConstantVector() {
Chris Lattnere4671472005-01-29 00:34:39 +0000355 delete [] OperandList;
Vikram S. Adve345e0cf2002-07-14 23:13:17 +0000356}
357
Reid Spencer728b6db2006-12-03 05:48:19 +0000358// We declare several classes private to this file, so use an anonymous
359// namespace
360namespace {
361
362/// UnaryConstantExpr - This class is private to Constants.cpp, and is used
363/// behind the scenes to implement unary constant exprs.
364class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
365 Use Op;
366public:
367 UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
368 : ConstantExpr(Ty, Opcode, &Op, 1), Op(C, this) {}
369};
370
Chris Lattnere4671472005-01-29 00:34:39 +0000371/// BinaryConstantExpr - This class is private to Constants.cpp, and is used
372/// behind the scenes to implement binary constant exprs.
Chris Lattnerf190d382006-06-28 21:38:54 +0000373class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
Chris Lattnere4671472005-01-29 00:34:39 +0000374 Use Ops[2];
375public:
376 BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
Reid Spencere4d87aa2006-12-23 06:05:41 +0000377 : ConstantExpr(C1->getType(), Opcode, Ops, 2) {
Chris Lattnere4671472005-01-29 00:34:39 +0000378 Ops[0].init(C1, this);
379 Ops[1].init(C2, this);
380 }
381};
Vikram S. Adve345e0cf2002-07-14 23:13:17 +0000382
Chris Lattnere4671472005-01-29 00:34:39 +0000383/// SelectConstantExpr - This class is private to Constants.cpp, and is used
384/// behind the scenes to implement select constant exprs.
Chris Lattnerf190d382006-06-28 21:38:54 +0000385class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
Chris Lattnere4671472005-01-29 00:34:39 +0000386 Use Ops[3];
387public:
388 SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
389 : ConstantExpr(C2->getType(), Instruction::Select, Ops, 3) {
390 Ops[0].init(C1, this);
391 Ops[1].init(C2, this);
392 Ops[2].init(C3, this);
393 }
394};
395
Robert Bocchinoc152f9c2006-01-17 20:07:22 +0000396/// ExtractElementConstantExpr - This class is private to
397/// Constants.cpp, and is used behind the scenes to implement
398/// extractelement constant exprs.
Chris Lattnerf190d382006-06-28 21:38:54 +0000399class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
Robert Bocchinob52ee7f2006-01-10 19:05:34 +0000400 Use Ops[2];
401public:
402 ExtractElementConstantExpr(Constant *C1, Constant *C2)
Reid Spencer9d6565a2007-02-15 02:26:10 +0000403 : ConstantExpr(cast<VectorType>(C1->getType())->getElementType(),
Robert Bocchinob52ee7f2006-01-10 19:05:34 +0000404 Instruction::ExtractElement, Ops, 2) {
405 Ops[0].init(C1, this);
406 Ops[1].init(C2, this);
407 }
408};
409
Robert Bocchinoc152f9c2006-01-17 20:07:22 +0000410/// InsertElementConstantExpr - This class is private to
411/// Constants.cpp, and is used behind the scenes to implement
412/// insertelement constant exprs.
Chris Lattnerf190d382006-06-28 21:38:54 +0000413class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
Robert Bocchinoc152f9c2006-01-17 20:07:22 +0000414 Use Ops[3];
415public:
416 InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
417 : ConstantExpr(C1->getType(), Instruction::InsertElement,
418 Ops, 3) {
419 Ops[0].init(C1, this);
420 Ops[1].init(C2, this);
421 Ops[2].init(C3, this);
422 }
423};
424
Chris Lattner00f10232006-04-08 01:18:18 +0000425/// ShuffleVectorConstantExpr - This class is private to
426/// Constants.cpp, and is used behind the scenes to implement
427/// shufflevector constant exprs.
Chris Lattnerf190d382006-06-28 21:38:54 +0000428class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
Chris Lattner00f10232006-04-08 01:18:18 +0000429 Use Ops[3];
430public:
431 ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
432 : ConstantExpr(C1->getType(), Instruction::ShuffleVector,
433 Ops, 3) {
434 Ops[0].init(C1, this);
435 Ops[1].init(C2, this);
436 Ops[2].init(C3, this);
437 }
438};
439
Chris Lattnere4671472005-01-29 00:34:39 +0000440/// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
441/// used behind the scenes to implement getelementpr constant exprs.
Chris Lattnerf190d382006-06-28 21:38:54 +0000442struct VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
Chris Lattnere4671472005-01-29 00:34:39 +0000443 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
444 const Type *DestTy)
445 : ConstantExpr(DestTy, Instruction::GetElementPtr,
446 new Use[IdxList.size()+1], IdxList.size()+1) {
447 OperandList[0].init(C, this);
448 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
449 OperandList[i+1].init(IdxList[i], this);
450 }
451 ~GetElementPtrConstantExpr() {
Misha Brukmanfd939082005-04-21 23:48:37 +0000452 delete [] OperandList;
Chris Lattnere4671472005-01-29 00:34:39 +0000453 }
454};
Reid Spencer728b6db2006-12-03 05:48:19 +0000455
456// CompareConstantExpr - This class is private to Constants.cpp, and is used
457// behind the scenes to implement ICmp and FCmp constant expressions. This is
458// needed in order to store the predicate value for these instructions.
459struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
460 unsigned short predicate;
461 Use Ops[2];
462 CompareConstantExpr(Instruction::OtherOps opc, unsigned short pred,
463 Constant* LHS, Constant* RHS)
Reid Spencer4fe16d62007-01-11 18:21:29 +0000464 : ConstantExpr(Type::Int1Ty, opc, Ops, 2), predicate(pred) {
Reid Spencer728b6db2006-12-03 05:48:19 +0000465 OperandList[0].init(LHS, this);
466 OperandList[1].init(RHS, this);
467 }
468};
469
470} // end anonymous namespace
Vikram S. Adve345e0cf2002-07-14 23:13:17 +0000471
Reid Spencer3da59db2006-11-27 01:05:10 +0000472
473// Utility function for determining if a ConstantExpr is a CastOp or not. This
474// can't be inline because we don't want to #include Instruction.h into
475// Constant.h
476bool ConstantExpr::isCast() const {
477 return Instruction::isCast(getOpcode());
478}
479
Reid Spencer077d0eb2006-12-04 05:19:50 +0000480bool ConstantExpr::isCompare() const {
481 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
482}
483
Chris Lattner4dcb5402004-03-29 02:37:53 +0000484/// ConstantExpr::get* - Return some common constants without having to
485/// specify the full Instruction::OPCODE identifier.
486///
487Constant *ConstantExpr::getNeg(Constant *C) {
Reid Spencer24d6da52007-01-21 00:29:26 +0000488 return get(Instruction::Sub,
489 ConstantExpr::getZeroValueForNegationExpr(C->getType()),
490 C);
Chris Lattner4dcb5402004-03-29 02:37:53 +0000491}
492Constant *ConstantExpr::getNot(Constant *C) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000493 assert(isa<ConstantInt>(C) && "Cannot NOT a nonintegral type!");
Chris Lattner4dcb5402004-03-29 02:37:53 +0000494 return get(Instruction::Xor, C,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000495 ConstantInt::getAllOnesValue(C->getType()));
Chris Lattner4dcb5402004-03-29 02:37:53 +0000496}
497Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
498 return get(Instruction::Add, C1, C2);
499}
500Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
501 return get(Instruction::Sub, C1, C2);
502}
503Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
504 return get(Instruction::Mul, C1, C2);
505}
Reid Spencer1628cec2006-10-26 06:15:43 +0000506Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2) {
507 return get(Instruction::UDiv, C1, C2);
508}
509Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2) {
510 return get(Instruction::SDiv, C1, C2);
511}
512Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
513 return get(Instruction::FDiv, C1, C2);
Chris Lattner4dcb5402004-03-29 02:37:53 +0000514}
Reid Spencer0a783f72006-11-02 01:53:59 +0000515Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
516 return get(Instruction::URem, C1, C2);
517}
518Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
519 return get(Instruction::SRem, C1, C2);
520}
521Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
522 return get(Instruction::FRem, C1, C2);
Chris Lattner4dcb5402004-03-29 02:37:53 +0000523}
524Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
525 return get(Instruction::And, C1, C2);
526}
527Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
528 return get(Instruction::Or, C1, C2);
529}
530Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
531 return get(Instruction::Xor, C1, C2);
532}
Reid Spencer728b6db2006-12-03 05:48:19 +0000533unsigned ConstantExpr::getPredicate() const {
534 assert(getOpcode() == Instruction::FCmp || getOpcode() == Instruction::ICmp);
535 return dynamic_cast<const CompareConstantExpr*>(this)->predicate;
536}
Chris Lattner4dcb5402004-03-29 02:37:53 +0000537Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
538 return get(Instruction::Shl, C1, C2);
539}
Reid Spencer3822ff52006-11-08 06:47:33 +0000540Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2) {
541 return get(Instruction::LShr, C1, C2);
Chris Lattner4dcb5402004-03-29 02:37:53 +0000542}
Reid Spencer3822ff52006-11-08 06:47:33 +0000543Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2) {
544 return get(Instruction::AShr, C1, C2);
Chris Lattnerc9710252004-05-25 05:32:43 +0000545}
Chris Lattnerf4ba6c72001-10-03 06:12:09 +0000546
Chris Lattner1fe8f6b2006-07-14 19:37:40 +0000547/// getWithOperandReplaced - Return a constant expression identical to this
548/// one, but with the specified operand set to the specified value.
Reid Spencer3da59db2006-11-27 01:05:10 +0000549Constant *
550ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
Chris Lattner1fe8f6b2006-07-14 19:37:40 +0000551 assert(OpNo < getNumOperands() && "Operand num is out of range!");
552 assert(Op->getType() == getOperand(OpNo)->getType() &&
553 "Replacing operand with value of different type!");
Chris Lattnerb88a7fb2006-07-14 22:20:01 +0000554 if (getOperand(OpNo) == Op)
555 return const_cast<ConstantExpr*>(this);
Chris Lattner1fe8f6b2006-07-14 19:37:40 +0000556
Chris Lattnerb88a7fb2006-07-14 22:20:01 +0000557 Constant *Op0, *Op1, *Op2;
Chris Lattner1fe8f6b2006-07-14 19:37:40 +0000558 switch (getOpcode()) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000559 case Instruction::Trunc:
560 case Instruction::ZExt:
561 case Instruction::SExt:
562 case Instruction::FPTrunc:
563 case Instruction::FPExt:
564 case Instruction::UIToFP:
565 case Instruction::SIToFP:
566 case Instruction::FPToUI:
567 case Instruction::FPToSI:
568 case Instruction::PtrToInt:
569 case Instruction::IntToPtr:
570 case Instruction::BitCast:
571 return ConstantExpr::getCast(getOpcode(), Op, getType());
Chris Lattnerb88a7fb2006-07-14 22:20:01 +0000572 case Instruction::Select:
573 Op0 = (OpNo == 0) ? Op : getOperand(0);
574 Op1 = (OpNo == 1) ? Op : getOperand(1);
575 Op2 = (OpNo == 2) ? Op : getOperand(2);
576 return ConstantExpr::getSelect(Op0, Op1, Op2);
577 case Instruction::InsertElement:
578 Op0 = (OpNo == 0) ? Op : getOperand(0);
579 Op1 = (OpNo == 1) ? Op : getOperand(1);
580 Op2 = (OpNo == 2) ? Op : getOperand(2);
581 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
582 case Instruction::ExtractElement:
583 Op0 = (OpNo == 0) ? Op : getOperand(0);
584 Op1 = (OpNo == 1) ? Op : getOperand(1);
585 return ConstantExpr::getExtractElement(Op0, Op1);
586 case Instruction::ShuffleVector:
587 Op0 = (OpNo == 0) ? Op : getOperand(0);
588 Op1 = (OpNo == 1) ? Op : getOperand(1);
589 Op2 = (OpNo == 2) ? Op : getOperand(2);
590 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattner1fe8f6b2006-07-14 19:37:40 +0000591 case Instruction::GetElementPtr: {
Chris Lattnerf9021ff2007-02-19 20:01:23 +0000592 SmallVector<Constant*, 8> Ops;
593 Ops.resize(getNumOperands());
Chris Lattner1fe8f6b2006-07-14 19:37:40 +0000594 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
Chris Lattnerf9021ff2007-02-19 20:01:23 +0000595 Ops[i] = getOperand(i);
Chris Lattner1fe8f6b2006-07-14 19:37:40 +0000596 if (OpNo == 0)
Chris Lattnerf9021ff2007-02-19 20:01:23 +0000597 return ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
Chris Lattner1fe8f6b2006-07-14 19:37:40 +0000598 Ops[OpNo-1] = Op;
Chris Lattnerf9021ff2007-02-19 20:01:23 +0000599 return ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
Chris Lattner1fe8f6b2006-07-14 19:37:40 +0000600 }
Chris Lattner1fe8f6b2006-07-14 19:37:40 +0000601 default:
602 assert(getNumOperands() == 2 && "Must be binary operator?");
Chris Lattnerb88a7fb2006-07-14 22:20:01 +0000603 Op0 = (OpNo == 0) ? Op : getOperand(0);
604 Op1 = (OpNo == 1) ? Op : getOperand(1);
605 return ConstantExpr::get(getOpcode(), Op0, Op1);
606 }
607}
608
609/// getWithOperands - This returns the current constant expression with the
610/// operands replaced with the specified values. The specified operands must
611/// match count and type with the existing ones.
612Constant *ConstantExpr::
613getWithOperands(const std::vector<Constant*> &Ops) const {
614 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
615 bool AnyChange = false;
616 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
617 assert(Ops[i]->getType() == getOperand(i)->getType() &&
618 "Operand type mismatch!");
619 AnyChange |= Ops[i] != getOperand(i);
620 }
621 if (!AnyChange) // No operands changed, return self.
622 return const_cast<ConstantExpr*>(this);
623
624 switch (getOpcode()) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000625 case Instruction::Trunc:
626 case Instruction::ZExt:
627 case Instruction::SExt:
628 case Instruction::FPTrunc:
629 case Instruction::FPExt:
630 case Instruction::UIToFP:
631 case Instruction::SIToFP:
632 case Instruction::FPToUI:
633 case Instruction::FPToSI:
634 case Instruction::PtrToInt:
635 case Instruction::IntToPtr:
636 case Instruction::BitCast:
637 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
Chris Lattnerb88a7fb2006-07-14 22:20:01 +0000638 case Instruction::Select:
639 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
640 case Instruction::InsertElement:
641 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
642 case Instruction::ExtractElement:
643 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
644 case Instruction::ShuffleVector:
645 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
Chris Lattnerf9021ff2007-02-19 20:01:23 +0000646 case Instruction::GetElementPtr:
647 return ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], Ops.size()-1);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000648 case Instruction::ICmp:
649 case Instruction::FCmp:
650 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
Chris Lattnerb88a7fb2006-07-14 22:20:01 +0000651 default:
652 assert(getNumOperands() == 2 && "Must be binary operator?");
653 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
Chris Lattner1fe8f6b2006-07-14 19:37:40 +0000654 }
655}
656
Chris Lattner00950542001-06-06 20:29:01 +0000657
658//===----------------------------------------------------------------------===//
Chris Lattner00950542001-06-06 20:29:01 +0000659// isValueValidForType implementations
660
Reid Spencer9b11d512006-12-19 01:28:19 +0000661bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000662 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
Reid Spencera54b7cb2007-01-12 07:05:14 +0000663 if (Ty == Type::Int1Ty)
664 return Val == 0 || Val == 1;
Reid Spencer554cec62007-02-05 23:47:56 +0000665 if (NumBits >= 64)
Reid Spencera54b7cb2007-01-12 07:05:14 +0000666 return true; // always true, has to fit in largest type
667 uint64_t Max = (1ll << NumBits) - 1;
668 return Val <= Max;
Reid Spencer9b11d512006-12-19 01:28:19 +0000669}
670
Reid Spencerb83eb642006-10-20 07:07:24 +0000671bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000672 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
Reid Spencera54b7cb2007-01-12 07:05:14 +0000673 if (Ty == Type::Int1Ty)
Reid Spencerc1030572007-01-19 21:13:56 +0000674 return Val == 0 || Val == 1 || Val == -1;
Reid Spencer554cec62007-02-05 23:47:56 +0000675 if (NumBits >= 64)
Reid Spencera54b7cb2007-01-12 07:05:14 +0000676 return true; // always true, has to fit in largest type
677 int64_t Min = -(1ll << (NumBits-1));
678 int64_t Max = (1ll << (NumBits-1)) - 1;
679 return (Val >= Min && Val <= Max);
Chris Lattner00950542001-06-06 20:29:01 +0000680}
681
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000682bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000683 switch (Ty->getTypeID()) {
Chris Lattner00950542001-06-06 20:29:01 +0000684 default:
685 return false; // These can't be represented as floating point!
686
Reid Spencer574cdb32004-12-07 07:38:08 +0000687 // TODO: Figure out how to test if a double can be cast to a float!
Chris Lattner00950542001-06-06 20:29:01 +0000688 case Type::FloatTyID:
Chris Lattner00950542001-06-06 20:29:01 +0000689 case Type::DoubleTyID:
690 return true; // This is the largest type...
691 }
Chris Lattnerd74ea2b2006-05-24 17:04:05 +0000692}
Chris Lattner37bf6302001-07-20 19:16:02 +0000693
Chris Lattner531daef2001-09-07 16:46:31 +0000694//===----------------------------------------------------------------------===//
Chris Lattner531daef2001-09-07 16:46:31 +0000695// Factory Function Implementation
696
Chris Lattner02ec5ed2003-05-23 20:03:32 +0000697// ConstantCreator - A class that is used to create constants by
698// ValueMap*. This class should be partially specialized if there is
699// something strange that needs to be done to interface to the ctor for the
700// constant.
701//
Chris Lattner31f84992003-11-21 20:23:48 +0000702namespace llvm {
703 template<class ConstantClass, class TypeClass, class ValType>
Chris Lattnerf190d382006-06-28 21:38:54 +0000704 struct VISIBILITY_HIDDEN ConstantCreator {
Chris Lattner31f84992003-11-21 20:23:48 +0000705 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
706 return new ConstantClass(Ty, V);
707 }
708 };
Misha Brukmanfd939082005-04-21 23:48:37 +0000709
Chris Lattner31f84992003-11-21 20:23:48 +0000710 template<class ConstantClass, class TypeClass>
Chris Lattnerf190d382006-06-28 21:38:54 +0000711 struct VISIBILITY_HIDDEN ConvertConstantType {
Chris Lattner31f84992003-11-21 20:23:48 +0000712 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
713 assert(0 && "This type cannot be converted!\n");
714 abort();
715 }
716 };
Chris Lattnered468e372003-10-05 00:17:43 +0000717
Chris Lattnera55b30a2005-10-04 17:48:46 +0000718 template<class ValType, class TypeClass, class ConstantClass,
719 bool HasLargeKey = false /*true for arrays and structs*/ >
Chris Lattnerf190d382006-06-28 21:38:54 +0000720 class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
Chris Lattnercea141f2005-10-03 22:51:37 +0000721 public:
Jim Laskeyede5aa42006-07-17 17:38:29 +0000722 typedef std::pair<const Type*, ValType> MapKey;
723 typedef std::map<MapKey, Constant *> MapTy;
724 typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
725 typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
Chris Lattnercea141f2005-10-03 22:51:37 +0000726 private:
Chris Lattnerd7a3fc62005-10-04 16:52:46 +0000727 /// Map - This is the main map from the element descriptor to the Constants.
728 /// This is the primary way we avoid creating two of the same shape
729 /// constant.
Chris Lattnered468e372003-10-05 00:17:43 +0000730 MapTy Map;
Chris Lattnera55b30a2005-10-04 17:48:46 +0000731
732 /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
733 /// from the constants to their element in Map. This is important for
734 /// removal of constants from the array, which would otherwise have to scan
735 /// through the map with very large keys.
Jim Laskeyede5aa42006-07-17 17:38:29 +0000736 InverseMapTy InverseMap;
Chris Lattnered468e372003-10-05 00:17:43 +0000737
Jim Laskeyede5aa42006-07-17 17:38:29 +0000738 /// AbstractTypeMap - Map for abstract type constants.
739 ///
Chris Lattnered468e372003-10-05 00:17:43 +0000740 AbstractTypeMapTy AbstractTypeMap;
Chris Lattner8a7ad2d2004-11-19 16:39:44 +0000741
Chris Lattner02ec5ed2003-05-23 20:03:32 +0000742 public:
Jim Laskeyede5aa42006-07-17 17:38:29 +0000743 typename MapTy::iterator map_end() { return Map.end(); }
Chris Lattnercea141f2005-10-03 22:51:37 +0000744
745 /// InsertOrGetItem - Return an iterator for the specified element.
746 /// If the element exists in the map, the returned iterator points to the
747 /// entry and Exists=true. If not, the iterator points to the newly
748 /// inserted entry and returns Exists=false. Newly inserted entries have
749 /// I->second == 0, and should be filled in.
Jim Laskeyede5aa42006-07-17 17:38:29 +0000750 typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
751 &InsertVal,
Chris Lattnercea141f2005-10-03 22:51:37 +0000752 bool &Exists) {
Jim Laskeyede5aa42006-07-17 17:38:29 +0000753 std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
Chris Lattnercea141f2005-10-03 22:51:37 +0000754 Exists = !IP.second;
755 return IP.first;
756 }
Chris Lattnerd7a3fc62005-10-04 16:52:46 +0000757
Chris Lattnera55b30a2005-10-04 17:48:46 +0000758private:
Jim Laskeyede5aa42006-07-17 17:38:29 +0000759 typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
Chris Lattnera55b30a2005-10-04 17:48:46 +0000760 if (HasLargeKey) {
Jim Laskeyede5aa42006-07-17 17:38:29 +0000761 typename InverseMapTy::iterator IMI = InverseMap.find(CP);
Chris Lattnera55b30a2005-10-04 17:48:46 +0000762 assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
763 IMI->second->second == CP &&
764 "InverseMap corrupt!");
765 return IMI->second;
766 }
767
Jim Laskeyede5aa42006-07-17 17:38:29 +0000768 typename MapTy::iterator I =
Chris Lattnera55b30a2005-10-04 17:48:46 +0000769 Map.find(MapKey((TypeClass*)CP->getRawType(), getValType(CP)));
Chris Lattnerd7a3fc62005-10-04 16:52:46 +0000770 if (I == Map.end() || I->second != CP) {
771 // FIXME: This should not use a linear scan. If this gets to be a
772 // performance problem, someone should look at this.
773 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
774 /* empty */;
775 }
Chris Lattnera55b30a2005-10-04 17:48:46 +0000776 return I;
777 }
778public:
779
Chris Lattnercea141f2005-10-03 22:51:37 +0000780 /// getOrCreate - Return the specified constant from the map, creating it if
781 /// necessary.
Chris Lattner02ec5ed2003-05-23 20:03:32 +0000782 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
Chris Lattnered468e372003-10-05 00:17:43 +0000783 MapKey Lookup(Ty, V);
Jim Laskeyede5aa42006-07-17 17:38:29 +0000784 typename MapTy::iterator I = Map.lower_bound(Lookup);
Reid Spencerb83eb642006-10-20 07:07:24 +0000785 // Is it in the map?
Chris Lattner02ec5ed2003-05-23 20:03:32 +0000786 if (I != Map.end() && I->first == Lookup)
Reid Spencerb83eb642006-10-20 07:07:24 +0000787 return static_cast<ConstantClass *>(I->second);
Chris Lattner02ec5ed2003-05-23 20:03:32 +0000788
789 // If no preexisting value, create one now...
790 ConstantClass *Result =
791 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
792
Chris Lattnered468e372003-10-05 00:17:43 +0000793 /// FIXME: why does this assert fail when loading 176.gcc?
794 //assert(Result->getType() == Ty && "Type specified is not correct!");
795 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
796
Chris Lattnera55b30a2005-10-04 17:48:46 +0000797 if (HasLargeKey) // Remember the reverse mapping if needed.
798 InverseMap.insert(std::make_pair(Result, I));
799
Chris Lattnered468e372003-10-05 00:17:43 +0000800 // If the type of the constant is abstract, make sure that an entry exists
801 // for it in the AbstractTypeMap.
802 if (Ty->isAbstract()) {
803 typename AbstractTypeMapTy::iterator TI =
804 AbstractTypeMap.lower_bound(Ty);
805
806 if (TI == AbstractTypeMap.end() || TI->first != Ty) {
807 // Add ourselves to the ATU list of the type.
808 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
809
810 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
811 }
812 }
Chris Lattner02ec5ed2003-05-23 20:03:32 +0000813 return Result;
814 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000815
Chris Lattner02ec5ed2003-05-23 20:03:32 +0000816 void remove(ConstantClass *CP) {
Jim Laskeyede5aa42006-07-17 17:38:29 +0000817 typename MapTy::iterator I = FindExistingElement(CP);
Chris Lattnered468e372003-10-05 00:17:43 +0000818 assert(I != Map.end() && "Constant not found in constant table!");
Chris Lattner6823c9f2004-08-04 04:48:01 +0000819 assert(I->second == CP && "Didn't find correct element?");
Chris Lattnered468e372003-10-05 00:17:43 +0000820
Chris Lattnera55b30a2005-10-04 17:48:46 +0000821 if (HasLargeKey) // Remember the reverse mapping if needed.
822 InverseMap.erase(CP);
823
Chris Lattnered468e372003-10-05 00:17:43 +0000824 // Now that we found the entry, make sure this isn't the entry that
825 // the AbstractTypeMap points to.
Jim Laskeyede5aa42006-07-17 17:38:29 +0000826 const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
Chris Lattnered468e372003-10-05 00:17:43 +0000827 if (Ty->isAbstract()) {
828 assert(AbstractTypeMap.count(Ty) &&
829 "Abstract type not in AbstractTypeMap?");
Jim Laskeyede5aa42006-07-17 17:38:29 +0000830 typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
Chris Lattnered468e372003-10-05 00:17:43 +0000831 if (ATMEntryIt == I) {
832 // Yes, we are removing the representative entry for this type.
833 // See if there are any other entries of the same type.
Jim Laskeyede5aa42006-07-17 17:38:29 +0000834 typename MapTy::iterator TmpIt = ATMEntryIt;
Misha Brukmanfd939082005-04-21 23:48:37 +0000835
Chris Lattnered468e372003-10-05 00:17:43 +0000836 // First check the entry before this one...
837 if (TmpIt != Map.begin()) {
838 --TmpIt;
839 if (TmpIt->first.first != Ty) // Not the same type, move back...
840 ++TmpIt;
841 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000842
Chris Lattnered468e372003-10-05 00:17:43 +0000843 // If we didn't find the same type, try to move forward...
844 if (TmpIt == ATMEntryIt) {
845 ++TmpIt;
846 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
847 --TmpIt; // No entry afterwards with the same type
848 }
849
850 // If there is another entry in the map of the same abstract type,
851 // update the AbstractTypeMap entry now.
852 if (TmpIt != ATMEntryIt) {
853 ATMEntryIt = TmpIt;
854 } else {
855 // Otherwise, we are removing the last instance of this type
856 // from the table. Remove from the ATM, and from user list.
857 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
858 AbstractTypeMap.erase(Ty);
859 }
Chris Lattner02ec5ed2003-05-23 20:03:32 +0000860 }
Chris Lattnered468e372003-10-05 00:17:43 +0000861 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000862
Chris Lattnered468e372003-10-05 00:17:43 +0000863 Map.erase(I);
864 }
865
Chris Lattnera1e3f542005-10-04 21:35:50 +0000866
867 /// MoveConstantToNewSlot - If we are about to change C to be the element
868 /// specified by I, update our internal data structures to reflect this
869 /// fact.
Jim Laskeyede5aa42006-07-17 17:38:29 +0000870 void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
Chris Lattnera1e3f542005-10-04 21:35:50 +0000871 // First, remove the old location of the specified constant in the map.
Jim Laskeyede5aa42006-07-17 17:38:29 +0000872 typename MapTy::iterator OldI = FindExistingElement(C);
Chris Lattnera1e3f542005-10-04 21:35:50 +0000873 assert(OldI != Map.end() && "Constant not found in constant table!");
874 assert(OldI->second == C && "Didn't find correct element?");
875
876 // If this constant is the representative element for its abstract type,
877 // update the AbstractTypeMap so that the representative element is I.
878 if (C->getType()->isAbstract()) {
879 typename AbstractTypeMapTy::iterator ATI =
880 AbstractTypeMap.find(C->getType());
881 assert(ATI != AbstractTypeMap.end() &&
882 "Abstract type not in AbstractTypeMap?");
883 if (ATI->second == OldI)
884 ATI->second = I;
885 }
886
887 // Remove the old entry from the map.
888 Map.erase(OldI);
889
890 // Update the inverse map so that we know that this constant is now
891 // located at descriptor I.
892 if (HasLargeKey) {
893 assert(I->second == C && "Bad inversemap entry!");
894 InverseMap[C] = I;
895 }
896 }
897
Chris Lattnered468e372003-10-05 00:17:43 +0000898 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
Misha Brukmanfd939082005-04-21 23:48:37 +0000899 typename AbstractTypeMapTy::iterator I =
Jim Laskeyede5aa42006-07-17 17:38:29 +0000900 AbstractTypeMap.find(cast<Type>(OldTy));
Chris Lattnered468e372003-10-05 00:17:43 +0000901
902 assert(I != AbstractTypeMap.end() &&
903 "Abstract type not in AbstractTypeMap?");
904
905 // Convert a constant at a time until the last one is gone. The last one
906 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
907 // eliminated eventually.
908 do {
909 ConvertConstantType<ConstantClass,
Jim Laskeyede5aa42006-07-17 17:38:29 +0000910 TypeClass>::convert(
911 static_cast<ConstantClass *>(I->second->second),
Chris Lattnered468e372003-10-05 00:17:43 +0000912 cast<TypeClass>(NewTy));
913
Jim Laskeyede5aa42006-07-17 17:38:29 +0000914 I = AbstractTypeMap.find(cast<Type>(OldTy));
Chris Lattnered468e372003-10-05 00:17:43 +0000915 } while (I != AbstractTypeMap.end());
916 }
917
918 // If the type became concrete without being refined to any other existing
919 // type, we just remove ourselves from the ATU list.
920 void typeBecameConcrete(const DerivedType *AbsTy) {
921 AbsTy->removeAbstractTypeUser(this);
922 }
923
924 void dump() const {
Bill Wendling2e3def12006-11-17 08:03:48 +0000925 DOUT << "Constant.cpp: ValueMap\n";
Chris Lattner02ec5ed2003-05-23 20:03:32 +0000926 }
927 };
928}
929
Chris Lattner003cbf32006-09-28 23:36:21 +0000930
Chris Lattnerd1afbd02007-02-20 06:11:36 +0000931
Chris Lattner40bbeb52004-02-15 05:53:04 +0000932//---- ConstantAggregateZero::get() implementation...
933//
934namespace llvm {
935 // ConstantAggregateZero does not take extra "value" argument...
936 template<class ValType>
937 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
938 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
939 return new ConstantAggregateZero(Ty);
940 }
941 };
942
943 template<>
944 struct ConvertConstantType<ConstantAggregateZero, Type> {
945 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
946 // Make everyone now use a constant of the new type...
947 Constant *New = ConstantAggregateZero::get(NewTy);
948 assert(New != OldC && "Didn't replace constant??");
949 OldC->uncheckedReplaceAllUsesWith(New);
950 OldC->destroyConstant(); // This constant is now dead, destroy it.
951 }
952 };
953}
954
Chris Lattner8a94bf12006-09-28 00:35:06 +0000955static ManagedStatic<ValueMap<char, Type,
956 ConstantAggregateZero> > AggZeroConstants;
Chris Lattner40bbeb52004-02-15 05:53:04 +0000957
Chris Lattner6823c9f2004-08-04 04:48:01 +0000958static char getValType(ConstantAggregateZero *CPZ) { return 0; }
959
Chris Lattner40bbeb52004-02-15 05:53:04 +0000960Constant *ConstantAggregateZero::get(const Type *Ty) {
Reid Spencer9d6565a2007-02-15 02:26:10 +0000961 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) &&
Chris Lattner31d1a2c2006-06-10 04:16:23 +0000962 "Cannot create an aggregate zero of non-aggregate type!");
Chris Lattner8a94bf12006-09-28 00:35:06 +0000963 return AggZeroConstants->getOrCreate(Ty, 0);
Chris Lattner40bbeb52004-02-15 05:53:04 +0000964}
965
966// destroyConstant - Remove the constant from the constant table...
967//
968void ConstantAggregateZero::destroyConstant() {
Chris Lattner8a94bf12006-09-28 00:35:06 +0000969 AggZeroConstants->remove(this);
Chris Lattner40bbeb52004-02-15 05:53:04 +0000970 destroyConstantImpl();
971}
972
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000973//---- ConstantArray::get() implementation...
Chris Lattner531daef2001-09-07 16:46:31 +0000974//
Chris Lattner31f84992003-11-21 20:23:48 +0000975namespace llvm {
976 template<>
977 struct ConvertConstantType<ConstantArray, ArrayType> {
978 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
979 // Make everyone now use a constant of the new type...
980 std::vector<Constant*> C;
981 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
982 C.push_back(cast<Constant>(OldC->getOperand(i)));
983 Constant *New = ConstantArray::get(NewTy, C);
984 assert(New != OldC && "Didn't replace constant??");
985 OldC->uncheckedReplaceAllUsesWith(New);
986 OldC->destroyConstant(); // This constant is now dead, destroy it.
987 }
988 };
989}
Chris Lattnered468e372003-10-05 00:17:43 +0000990
Chris Lattner6823c9f2004-08-04 04:48:01 +0000991static std::vector<Constant*> getValType(ConstantArray *CA) {
992 std::vector<Constant*> Elements;
993 Elements.reserve(CA->getNumOperands());
994 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
995 Elements.push_back(cast<Constant>(CA->getOperand(i)));
996 return Elements;
997}
998
Chris Lattnercea141f2005-10-03 22:51:37 +0000999typedef ValueMap<std::vector<Constant*>, ArrayType,
Chris Lattnera55b30a2005-10-04 17:48:46 +00001000 ConstantArray, true /*largekey*/> ArrayConstantsTy;
Chris Lattner8a94bf12006-09-28 00:35:06 +00001001static ManagedStatic<ArrayConstantsTy> ArrayConstants;
Chris Lattner531daef2001-09-07 16:46:31 +00001002
Chris Lattnerca705fa2004-02-15 04:14:47 +00001003Constant *ConstantArray::get(const ArrayType *Ty,
Chris Lattner40bbeb52004-02-15 05:53:04 +00001004 const std::vector<Constant*> &V) {
1005 // If this is an all-zero array, return a ConstantAggregateZero object
1006 if (!V.empty()) {
1007 Constant *C = V[0];
1008 if (!C->isNullValue())
Chris Lattner8a94bf12006-09-28 00:35:06 +00001009 return ArrayConstants->getOrCreate(Ty, V);
Chris Lattner40bbeb52004-02-15 05:53:04 +00001010 for (unsigned i = 1, e = V.size(); i != e; ++i)
1011 if (V[i] != C)
Chris Lattner8a94bf12006-09-28 00:35:06 +00001012 return ArrayConstants->getOrCreate(Ty, V);
Chris Lattner40bbeb52004-02-15 05:53:04 +00001013 }
1014 return ConstantAggregateZero::get(Ty);
Chris Lattner531daef2001-09-07 16:46:31 +00001015}
1016
Chris Lattner02ec5ed2003-05-23 20:03:32 +00001017// destroyConstant - Remove the constant from the constant table...
1018//
1019void ConstantArray::destroyConstant() {
Chris Lattner8a94bf12006-09-28 00:35:06 +00001020 ArrayConstants->remove(this);
Chris Lattner02ec5ed2003-05-23 20:03:32 +00001021 destroyConstantImpl();
1022}
1023
Reid Spencer89494772006-05-30 08:23:18 +00001024/// ConstantArray::get(const string&) - Return an array that is initialized to
1025/// contain the specified string. If length is zero then a null terminator is
1026/// added to the specified string so that it may be used in a natural way.
1027/// Otherwise, the length parameter specifies how much of the string to use
1028/// and it won't be null terminated.
1029///
Reid Spencer461bed22006-05-30 18:15:07 +00001030Constant *ConstantArray::get(const std::string &Str, bool AddNull) {
Chris Lattner697954c2002-01-20 22:54:45 +00001031 std::vector<Constant*> ElementVals;
Reid Spencer461bed22006-05-30 18:15:07 +00001032 for (unsigned i = 0; i < Str.length(); ++i)
Reid Spencer79e21d32006-12-31 05:26:44 +00001033 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, Str[i]));
Chris Lattnerc5bdb242001-10-14 23:54:12 +00001034
1035 // Add a null terminator to the string...
Reid Spencer461bed22006-05-30 18:15:07 +00001036 if (AddNull) {
Reid Spencer79e21d32006-12-31 05:26:44 +00001037 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, 0));
Reid Spencer89494772006-05-30 08:23:18 +00001038 }
Chris Lattnerc5bdb242001-10-14 23:54:12 +00001039
Reid Spencer79e21d32006-12-31 05:26:44 +00001040 ArrayType *ATy = ArrayType::get(Type::Int8Ty, ElementVals.size());
Chris Lattnere9bb2df2001-12-03 22:26:30 +00001041 return ConstantArray::get(ATy, ElementVals);
Vikram S. Advedb2da492001-10-14 23:17:20 +00001042}
1043
Reid Spencer3d10b0b2007-01-26 07:37:34 +00001044/// isString - This method returns true if the array is an array of i8, and
1045/// if the elements of the array are all ConstantInt's.
Chris Lattner13cfdea2004-01-14 17:06:38 +00001046bool ConstantArray::isString() const {
Reid Spencer3d10b0b2007-01-26 07:37:34 +00001047 // Check the element type for i8...
Reid Spencer79e21d32006-12-31 05:26:44 +00001048 if (getType()->getElementType() != Type::Int8Ty)
Chris Lattner13cfdea2004-01-14 17:06:38 +00001049 return false;
1050 // Check the elements to make sure they are all integers, not constant
1051 // expressions.
1052 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1053 if (!isa<ConstantInt>(getOperand(i)))
1054 return false;
1055 return true;
1056}
1057
Evan Cheng22c70302006-10-26 19:15:05 +00001058/// isCString - This method returns true if the array is a string (see
1059/// isString) and it ends in a null byte \0 and does not contains any other
1060/// null bytes except its terminator.
1061bool ConstantArray::isCString() const {
Reid Spencer3d10b0b2007-01-26 07:37:34 +00001062 // Check the element type for i8...
Reid Spencer79e21d32006-12-31 05:26:44 +00001063 if (getType()->getElementType() != Type::Int8Ty)
Evan Chengabf63452006-10-26 21:48:03 +00001064 return false;
1065 Constant *Zero = Constant::getNullValue(getOperand(0)->getType());
1066 // Last element must be a null.
1067 if (getOperand(getNumOperands()-1) != Zero)
1068 return false;
1069 // Other elements must be non-null integers.
1070 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1071 if (!isa<ConstantInt>(getOperand(i)))
Evan Cheng22c70302006-10-26 19:15:05 +00001072 return false;
Evan Chengabf63452006-10-26 21:48:03 +00001073 if (getOperand(i) == Zero)
1074 return false;
1075 }
Evan Cheng22c70302006-10-26 19:15:05 +00001076 return true;
1077}
1078
1079
Reid Spencer3d10b0b2007-01-26 07:37:34 +00001080// getAsString - If the sub-element type of this array is i8
Chris Lattner93aeea32002-08-26 17:53:56 +00001081// then this method converts the array to an std::string and returns it.
1082// Otherwise, it asserts out.
1083//
1084std::string ConstantArray::getAsString() const {
Chris Lattner13cfdea2004-01-14 17:06:38 +00001085 assert(isString() && "Not a string!");
Chris Lattner93aeea32002-08-26 17:53:56 +00001086 std::string Result;
Chris Lattnerc07736a2003-07-23 15:22:26 +00001087 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
Reid Spencerb83eb642006-10-20 07:07:24 +00001088 Result += (char)cast<ConstantInt>(getOperand(i))->getZExtValue();
Chris Lattner93aeea32002-08-26 17:53:56 +00001089 return Result;
1090}
1091
1092
Chris Lattnere9bb2df2001-12-03 22:26:30 +00001093//---- ConstantStruct::get() implementation...
Chris Lattner531daef2001-09-07 16:46:31 +00001094//
Chris Lattnered468e372003-10-05 00:17:43 +00001095
Chris Lattner31f84992003-11-21 20:23:48 +00001096namespace llvm {
1097 template<>
1098 struct ConvertConstantType<ConstantStruct, StructType> {
1099 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1100 // Make everyone now use a constant of the new type...
1101 std::vector<Constant*> C;
1102 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1103 C.push_back(cast<Constant>(OldC->getOperand(i)));
1104 Constant *New = ConstantStruct::get(NewTy, C);
1105 assert(New != OldC && "Didn't replace constant??");
Misha Brukmanfd939082005-04-21 23:48:37 +00001106
Chris Lattner31f84992003-11-21 20:23:48 +00001107 OldC->uncheckedReplaceAllUsesWith(New);
1108 OldC->destroyConstant(); // This constant is now dead, destroy it.
1109 }
1110 };
1111}
Chris Lattnered468e372003-10-05 00:17:43 +00001112
Chris Lattnerc182a882005-10-04 01:17:50 +00001113typedef ValueMap<std::vector<Constant*>, StructType,
Chris Lattnera55b30a2005-10-04 17:48:46 +00001114 ConstantStruct, true /*largekey*/> StructConstantsTy;
Chris Lattner8a94bf12006-09-28 00:35:06 +00001115static ManagedStatic<StructConstantsTy> StructConstants;
Chris Lattner531daef2001-09-07 16:46:31 +00001116
Chris Lattner6823c9f2004-08-04 04:48:01 +00001117static std::vector<Constant*> getValType(ConstantStruct *CS) {
1118 std::vector<Constant*> Elements;
1119 Elements.reserve(CS->getNumOperands());
1120 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1121 Elements.push_back(cast<Constant>(CS->getOperand(i)));
1122 return Elements;
1123}
1124
Chris Lattnerca705fa2004-02-15 04:14:47 +00001125Constant *ConstantStruct::get(const StructType *Ty,
1126 const std::vector<Constant*> &V) {
Chris Lattner40bbeb52004-02-15 05:53:04 +00001127 // Create a ConstantAggregateZero value if all elements are zeros...
1128 for (unsigned i = 0, e = V.size(); i != e; ++i)
1129 if (!V[i]->isNullValue())
Chris Lattner8a94bf12006-09-28 00:35:06 +00001130 return StructConstants->getOrCreate(Ty, V);
Chris Lattner40bbeb52004-02-15 05:53:04 +00001131
1132 return ConstantAggregateZero::get(Ty);
Chris Lattner531daef2001-09-07 16:46:31 +00001133}
Chris Lattner6a57baa2001-10-03 15:39:36 +00001134
Andrew Lenharth38ecbf12006-12-08 18:06:16 +00001135Constant *ConstantStruct::get(const std::vector<Constant*> &V, bool packed) {
Chris Lattnerb370c7a2004-07-12 20:35:11 +00001136 std::vector<const Type*> StructEls;
1137 StructEls.reserve(V.size());
1138 for (unsigned i = 0, e = V.size(); i != e; ++i)
1139 StructEls.push_back(V[i]->getType());
Andrew Lenharth38ecbf12006-12-08 18:06:16 +00001140 return get(StructType::get(StructEls, packed), V);
Chris Lattnerb370c7a2004-07-12 20:35:11 +00001141}
1142
Chris Lattnerf5ec48d2001-10-13 06:57:33 +00001143// destroyConstant - Remove the constant from the constant table...
Chris Lattner6a57baa2001-10-03 15:39:36 +00001144//
Chris Lattnere9bb2df2001-12-03 22:26:30 +00001145void ConstantStruct::destroyConstant() {
Chris Lattner8a94bf12006-09-28 00:35:06 +00001146 StructConstants->remove(this);
Chris Lattnerf5ec48d2001-10-13 06:57:33 +00001147 destroyConstantImpl();
1148}
Chris Lattner6a57baa2001-10-03 15:39:36 +00001149
Reid Spencer9d6565a2007-02-15 02:26:10 +00001150//---- ConstantVector::get() implementation...
Brian Gaeke715c90b2004-08-20 06:00:58 +00001151//
1152namespace llvm {
1153 template<>
Reid Spencer9d6565a2007-02-15 02:26:10 +00001154 struct ConvertConstantType<ConstantVector, VectorType> {
1155 static void convert(ConstantVector *OldC, const VectorType *NewTy) {
Brian Gaeke715c90b2004-08-20 06:00:58 +00001156 // Make everyone now use a constant of the new type...
1157 std::vector<Constant*> C;
1158 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1159 C.push_back(cast<Constant>(OldC->getOperand(i)));
Reid Spencer9d6565a2007-02-15 02:26:10 +00001160 Constant *New = ConstantVector::get(NewTy, C);
Brian Gaeke715c90b2004-08-20 06:00:58 +00001161 assert(New != OldC && "Didn't replace constant??");
1162 OldC->uncheckedReplaceAllUsesWith(New);
1163 OldC->destroyConstant(); // This constant is now dead, destroy it.
1164 }
1165 };
1166}
1167
Reid Spencer9d6565a2007-02-15 02:26:10 +00001168static std::vector<Constant*> getValType(ConstantVector *CP) {
Brian Gaeke715c90b2004-08-20 06:00:58 +00001169 std::vector<Constant*> Elements;
1170 Elements.reserve(CP->getNumOperands());
1171 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1172 Elements.push_back(CP->getOperand(i));
1173 return Elements;
1174}
1175
Reid Spencer9d6565a2007-02-15 02:26:10 +00001176static ManagedStatic<ValueMap<std::vector<Constant*>, VectorType,
Reid Spencerac9dcb92007-02-15 03:39:18 +00001177 ConstantVector> > VectorConstants;
Brian Gaeke715c90b2004-08-20 06:00:58 +00001178
Reid Spencer9d6565a2007-02-15 02:26:10 +00001179Constant *ConstantVector::get(const VectorType *Ty,
Brian Gaeke715c90b2004-08-20 06:00:58 +00001180 const std::vector<Constant*> &V) {
1181 // If this is an all-zero packed, return a ConstantAggregateZero object
1182 if (!V.empty()) {
1183 Constant *C = V[0];
1184 if (!C->isNullValue())
Reid Spencerac9dcb92007-02-15 03:39:18 +00001185 return VectorConstants->getOrCreate(Ty, V);
Brian Gaeke715c90b2004-08-20 06:00:58 +00001186 for (unsigned i = 1, e = V.size(); i != e; ++i)
1187 if (V[i] != C)
Reid Spencerac9dcb92007-02-15 03:39:18 +00001188 return VectorConstants->getOrCreate(Ty, V);
Brian Gaeke715c90b2004-08-20 06:00:58 +00001189 }
1190 return ConstantAggregateZero::get(Ty);
1191}
1192
Reid Spencer9d6565a2007-02-15 02:26:10 +00001193Constant *ConstantVector::get(const std::vector<Constant*> &V) {
Brian Gaeke715c90b2004-08-20 06:00:58 +00001194 assert(!V.empty() && "Cannot infer type if V is empty");
Reid Spencer9d6565a2007-02-15 02:26:10 +00001195 return get(VectorType::get(V.front()->getType(),V.size()), V);
Brian Gaeke715c90b2004-08-20 06:00:58 +00001196}
1197
1198// destroyConstant - Remove the constant from the constant table...
1199//
Reid Spencer9d6565a2007-02-15 02:26:10 +00001200void ConstantVector::destroyConstant() {
Reid Spencerac9dcb92007-02-15 03:39:18 +00001201 VectorConstants->remove(this);
Brian Gaeke715c90b2004-08-20 06:00:58 +00001202 destroyConstantImpl();
1203}
1204
Jim Laskeyfa301822007-01-12 22:39:14 +00001205/// This function will return true iff every element in this packed constant
1206/// is set to all ones.
1207/// @returns true iff this constant's emements are all set to all ones.
1208/// @brief Determine if the value is all ones.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001209bool ConstantVector::isAllOnesValue() const {
Jim Laskeyfa301822007-01-12 22:39:14 +00001210 // Check out first element.
1211 const Constant *Elt = getOperand(0);
1212 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1213 if (!CI || !CI->isAllOnesValue()) return false;
1214 // Then make sure all remaining elements point to the same value.
1215 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1216 if (getOperand(I) != Elt) return false;
1217 }
1218 return true;
1219}
1220
Chris Lattnere9bb2df2001-12-03 22:26:30 +00001221//---- ConstantPointerNull::get() implementation...
Chris Lattnerf5ec48d2001-10-13 06:57:33 +00001222//
Chris Lattner02ec5ed2003-05-23 20:03:32 +00001223
Chris Lattner31f84992003-11-21 20:23:48 +00001224namespace llvm {
1225 // ConstantPointerNull does not take extra "value" argument...
1226 template<class ValType>
1227 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1228 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1229 return new ConstantPointerNull(Ty);
1230 }
1231 };
Chris Lattner02ec5ed2003-05-23 20:03:32 +00001232
Chris Lattner31f84992003-11-21 20:23:48 +00001233 template<>
1234 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1235 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1236 // Make everyone now use a constant of the new type...
1237 Constant *New = ConstantPointerNull::get(NewTy);
1238 assert(New != OldC && "Didn't replace constant??");
1239 OldC->uncheckedReplaceAllUsesWith(New);
1240 OldC->destroyConstant(); // This constant is now dead, destroy it.
1241 }
1242 };
1243}
Chris Lattnered468e372003-10-05 00:17:43 +00001244
Chris Lattner8a94bf12006-09-28 00:35:06 +00001245static ManagedStatic<ValueMap<char, PointerType,
1246 ConstantPointerNull> > NullPtrConstants;
Chris Lattnerf5ec48d2001-10-13 06:57:33 +00001247
Chris Lattner6823c9f2004-08-04 04:48:01 +00001248static char getValType(ConstantPointerNull *) {
1249 return 0;
1250}
1251
1252
Chris Lattnere9bb2df2001-12-03 22:26:30 +00001253ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
Chris Lattner8a94bf12006-09-28 00:35:06 +00001254 return NullPtrConstants->getOrCreate(Ty, 0);
Chris Lattner6a57baa2001-10-03 15:39:36 +00001255}
1256
Chris Lattner41661fd2002-08-18 00:40:04 +00001257// destroyConstant - Remove the constant from the constant table...
1258//
1259void ConstantPointerNull::destroyConstant() {
Chris Lattner8a94bf12006-09-28 00:35:06 +00001260 NullPtrConstants->remove(this);
Chris Lattner41661fd2002-08-18 00:40:04 +00001261 destroyConstantImpl();
1262}
1263
1264
Chris Lattnerb9f18592004-10-16 18:07:16 +00001265//---- UndefValue::get() implementation...
1266//
1267
1268namespace llvm {
1269 // UndefValue does not take extra "value" argument...
1270 template<class ValType>
1271 struct ConstantCreator<UndefValue, Type, ValType> {
1272 static UndefValue *create(const Type *Ty, const ValType &V) {
1273 return new UndefValue(Ty);
1274 }
1275 };
1276
1277 template<>
1278 struct ConvertConstantType<UndefValue, Type> {
1279 static void convert(UndefValue *OldC, const Type *NewTy) {
1280 // Make everyone now use a constant of the new type.
1281 Constant *New = UndefValue::get(NewTy);
1282 assert(New != OldC && "Didn't replace constant??");
1283 OldC->uncheckedReplaceAllUsesWith(New);
1284 OldC->destroyConstant(); // This constant is now dead, destroy it.
1285 }
1286 };
1287}
1288
Chris Lattner8a94bf12006-09-28 00:35:06 +00001289static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
Chris Lattnerb9f18592004-10-16 18:07:16 +00001290
1291static char getValType(UndefValue *) {
1292 return 0;
1293}
1294
1295
1296UndefValue *UndefValue::get(const Type *Ty) {
Chris Lattner8a94bf12006-09-28 00:35:06 +00001297 return UndefValueConstants->getOrCreate(Ty, 0);
Chris Lattnerb9f18592004-10-16 18:07:16 +00001298}
1299
1300// destroyConstant - Remove the constant from the constant table.
1301//
1302void UndefValue::destroyConstant() {
Chris Lattner8a94bf12006-09-28 00:35:06 +00001303 UndefValueConstants->remove(this);
Chris Lattnerb9f18592004-10-16 18:07:16 +00001304 destroyConstantImpl();
1305}
1306
1307
Vikram S. Adve345e0cf2002-07-14 23:13:17 +00001308//---- ConstantExpr::get() implementations...
Vikram S. Adve345e0cf2002-07-14 23:13:17 +00001309//
Reid Spencer79e21d32006-12-31 05:26:44 +00001310
Reid Spencer077d0eb2006-12-04 05:19:50 +00001311struct ExprMapKeyType {
1312 explicit ExprMapKeyType(unsigned opc, std::vector<Constant*> ops,
Reid Spencer8d5a6ae2006-12-04 18:38:05 +00001313 unsigned short pred = 0) : opcode(opc), predicate(pred), operands(ops) { }
1314 uint16_t opcode;
1315 uint16_t predicate;
Reid Spencer077d0eb2006-12-04 05:19:50 +00001316 std::vector<Constant*> operands;
Reid Spencer077d0eb2006-12-04 05:19:50 +00001317 bool operator==(const ExprMapKeyType& that) const {
1318 return this->opcode == that.opcode &&
1319 this->predicate == that.predicate &&
1320 this->operands == that.operands;
1321 }
1322 bool operator<(const ExprMapKeyType & that) const {
1323 return this->opcode < that.opcode ||
1324 (this->opcode == that.opcode && this->predicate < that.predicate) ||
1325 (this->opcode == that.opcode && this->predicate == that.predicate &&
1326 this->operands < that.operands);
1327 }
1328
1329 bool operator!=(const ExprMapKeyType& that) const {
1330 return !(*this == that);
1331 }
1332};
Chris Lattner02ec5ed2003-05-23 20:03:32 +00001333
Chris Lattner31f84992003-11-21 20:23:48 +00001334namespace llvm {
1335 template<>
1336 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
Reid Spencer728b6db2006-12-03 05:48:19 +00001337 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1338 unsigned short pred = 0) {
Reid Spencer077d0eb2006-12-04 05:19:50 +00001339 if (Instruction::isCast(V.opcode))
1340 return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1341 if ((V.opcode >= Instruction::BinaryOpsBegin &&
Reid Spencer832254e2007-02-02 02:16:23 +00001342 V.opcode < Instruction::BinaryOpsEnd))
Reid Spencer077d0eb2006-12-04 05:19:50 +00001343 return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1344 if (V.opcode == Instruction::Select)
1345 return new SelectConstantExpr(V.operands[0], V.operands[1],
1346 V.operands[2]);
1347 if (V.opcode == Instruction::ExtractElement)
1348 return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1349 if (V.opcode == Instruction::InsertElement)
1350 return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1351 V.operands[2]);
1352 if (V.opcode == Instruction::ShuffleVector)
1353 return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1354 V.operands[2]);
1355 if (V.opcode == Instruction::GetElementPtr) {
1356 std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
1357 return new GetElementPtrConstantExpr(V.operands[0], IdxList, Ty);
1358 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001359
Reid Spencer077d0eb2006-12-04 05:19:50 +00001360 // The compare instructions are weird. We have to encode the predicate
1361 // value and it is combined with the instruction opcode by multiplying
1362 // the opcode by one hundred. We must decode this to get the predicate.
1363 if (V.opcode == Instruction::ICmp)
1364 return new CompareConstantExpr(Instruction::ICmp, V.predicate,
1365 V.operands[0], V.operands[1]);
1366 if (V.opcode == Instruction::FCmp)
1367 return new CompareConstantExpr(Instruction::FCmp, V.predicate,
1368 V.operands[0], V.operands[1]);
1369 assert(0 && "Invalid ConstantExpr!");
Jeff Cohen6ebe2352006-12-15 21:47:01 +00001370 return 0;
Chris Lattnered468e372003-10-05 00:17:43 +00001371 }
Chris Lattner31f84992003-11-21 20:23:48 +00001372 };
Chris Lattnered468e372003-10-05 00:17:43 +00001373
Chris Lattner31f84992003-11-21 20:23:48 +00001374 template<>
1375 struct ConvertConstantType<ConstantExpr, Type> {
1376 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1377 Constant *New;
1378 switch (OldC->getOpcode()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001379 case Instruction::Trunc:
1380 case Instruction::ZExt:
1381 case Instruction::SExt:
1382 case Instruction::FPTrunc:
1383 case Instruction::FPExt:
1384 case Instruction::UIToFP:
1385 case Instruction::SIToFP:
1386 case Instruction::FPToUI:
1387 case Instruction::FPToSI:
1388 case Instruction::PtrToInt:
1389 case Instruction::IntToPtr:
1390 case Instruction::BitCast:
Reid Spencerd977d862006-12-12 23:36:14 +00001391 New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0),
1392 NewTy);
Chris Lattner31f84992003-11-21 20:23:48 +00001393 break;
Chris Lattner08a45cc2004-03-12 05:54:04 +00001394 case Instruction::Select:
1395 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1396 OldC->getOperand(1),
1397 OldC->getOperand(2));
1398 break;
Chris Lattner31f84992003-11-21 20:23:48 +00001399 default:
1400 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
Reid Spencer0a783f72006-11-02 01:53:59 +00001401 OldC->getOpcode() < Instruction::BinaryOpsEnd);
Chris Lattner31f84992003-11-21 20:23:48 +00001402 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1403 OldC->getOperand(1));
1404 break;
1405 case Instruction::GetElementPtr:
Misha Brukmanfd939082005-04-21 23:48:37 +00001406 // Make everyone now use a constant of the new type...
Chris Lattner7fa6e662004-10-11 22:52:25 +00001407 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
Chris Lattner2b9a5da2007-01-31 04:40:28 +00001408 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0),
1409 &Idx[0], Idx.size());
Chris Lattner31f84992003-11-21 20:23:48 +00001410 break;
1411 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001412
Chris Lattner31f84992003-11-21 20:23:48 +00001413 assert(New != OldC && "Didn't replace constant??");
1414 OldC->uncheckedReplaceAllUsesWith(New);
1415 OldC->destroyConstant(); // This constant is now dead, destroy it.
1416 }
1417 };
1418} // end namespace llvm
Chris Lattnered468e372003-10-05 00:17:43 +00001419
1420
Chris Lattner6823c9f2004-08-04 04:48:01 +00001421static ExprMapKeyType getValType(ConstantExpr *CE) {
1422 std::vector<Constant*> Operands;
1423 Operands.reserve(CE->getNumOperands());
1424 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1425 Operands.push_back(cast<Constant>(CE->getOperand(i)));
Reid Spencer077d0eb2006-12-04 05:19:50 +00001426 return ExprMapKeyType(CE->getOpcode(), Operands,
1427 CE->isCompare() ? CE->getPredicate() : 0);
Chris Lattner6823c9f2004-08-04 04:48:01 +00001428}
1429
Chris Lattner8a94bf12006-09-28 00:35:06 +00001430static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1431 ConstantExpr> > ExprConstants;
Vikram S. Adved0b1bb02002-07-15 18:19:33 +00001432
Reid Spencer3da59db2006-11-27 01:05:10 +00001433/// This is a utility function to handle folding of casts and lookup of the
1434/// cast in the ExprConstants map. It is usedby the various get* methods below.
1435static inline Constant *getFoldedCast(
1436 Instruction::CastOps opc, Constant *C, const Type *Ty) {
Chris Lattner9eacf8a2003-10-07 22:19:19 +00001437 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
Reid Spencer3da59db2006-11-27 01:05:10 +00001438 // Fold a few common cases
1439 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1440 return FC;
Chris Lattnerd628f6a2003-04-17 19:24:48 +00001441
Vikram S. Adved0b1bb02002-07-15 18:19:33 +00001442 // Look up the constant in the table first to ensure uniqueness
Chris Lattner9bc02a42003-05-13 21:37:02 +00001443 std::vector<Constant*> argVec(1, C);
Reid Spencer077d0eb2006-12-04 05:19:50 +00001444 ExprMapKeyType Key(opc, argVec);
Chris Lattner8a94bf12006-09-28 00:35:06 +00001445 return ExprConstants->getOrCreate(Ty, Key);
Vikram S. Adve345e0cf2002-07-14 23:13:17 +00001446}
Reid Spencer7858b332006-12-05 19:14:13 +00001447
Reid Spencer3da59db2006-11-27 01:05:10 +00001448Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1449 Instruction::CastOps opc = Instruction::CastOps(oc);
1450 assert(Instruction::isCast(opc) && "opcode out of range");
1451 assert(C && Ty && "Null arguments to getCast");
1452 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1453
1454 switch (opc) {
1455 default:
1456 assert(0 && "Invalid cast opcode");
1457 break;
1458 case Instruction::Trunc: return getTrunc(C, Ty);
Reid Spencerd977d862006-12-12 23:36:14 +00001459 case Instruction::ZExt: return getZExt(C, Ty);
1460 case Instruction::SExt: return getSExt(C, Ty);
Reid Spencer3da59db2006-11-27 01:05:10 +00001461 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1462 case Instruction::FPExt: return getFPExtend(C, Ty);
1463 case Instruction::UIToFP: return getUIToFP(C, Ty);
1464 case Instruction::SIToFP: return getSIToFP(C, Ty);
1465 case Instruction::FPToUI: return getFPToUI(C, Ty);
1466 case Instruction::FPToSI: return getFPToSI(C, Ty);
1467 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1468 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1469 case Instruction::BitCast: return getBitCast(C, Ty);
Chris Lattnerf5ac6c22005-01-01 15:59:57 +00001470 }
Reid Spencer3da59db2006-11-27 01:05:10 +00001471 return 0;
Reid Spencer7858b332006-12-05 19:14:13 +00001472}
1473
Reid Spencer848414e2006-12-04 20:17:56 +00001474Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1475 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1476 return getCast(Instruction::BitCast, C, Ty);
1477 return getCast(Instruction::ZExt, C, Ty);
1478}
1479
1480Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1481 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1482 return getCast(Instruction::BitCast, C, Ty);
1483 return getCast(Instruction::SExt, C, Ty);
1484}
1485
1486Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1487 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1488 return getCast(Instruction::BitCast, C, Ty);
1489 return getCast(Instruction::Trunc, C, Ty);
1490}
1491
Reid Spencerc0459fb2006-12-05 03:25:26 +00001492Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1493 assert(isa<PointerType>(S->getType()) && "Invalid cast");
Chris Lattner42a75512007-01-15 02:27:26 +00001494 assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
Reid Spencerc0459fb2006-12-05 03:25:26 +00001495
Chris Lattner42a75512007-01-15 02:27:26 +00001496 if (Ty->isInteger())
Reid Spencerc0459fb2006-12-05 03:25:26 +00001497 return getCast(Instruction::PtrToInt, S, Ty);
1498 return getCast(Instruction::BitCast, S, Ty);
1499}
1500
Reid Spencer84f3eab2006-12-12 00:51:07 +00001501Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
1502 bool isSigned) {
Chris Lattner42a75512007-01-15 02:27:26 +00001503 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
Reid Spencer84f3eab2006-12-12 00:51:07 +00001504 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1505 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1506 Instruction::CastOps opcode =
1507 (SrcBits == DstBits ? Instruction::BitCast :
1508 (SrcBits > DstBits ? Instruction::Trunc :
1509 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1510 return getCast(opcode, C, Ty);
1511}
1512
1513Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1514 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1515 "Invalid cast");
1516 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1517 unsigned DstBits = Ty->getPrimitiveSizeInBits();
Reid Spencerf25212a2006-12-12 05:38:50 +00001518 if (SrcBits == DstBits)
1519 return C; // Avoid a useless cast
Reid Spencer84f3eab2006-12-12 00:51:07 +00001520 Instruction::CastOps opcode =
Reid Spencerf25212a2006-12-12 05:38:50 +00001521 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
Reid Spencer84f3eab2006-12-12 00:51:07 +00001522 return getCast(opcode, C, Ty);
1523}
1524
Reid Spencer3da59db2006-11-27 01:05:10 +00001525Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
Chris Lattner42a75512007-01-15 02:27:26 +00001526 assert(C->getType()->isInteger() && "Trunc operand must be integer");
1527 assert(Ty->isInteger() && "Trunc produces only integral");
Reid Spencer3da59db2006-11-27 01:05:10 +00001528 assert(C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1529 "SrcTy must be larger than DestTy for Trunc!");
1530
1531 return getFoldedCast(Instruction::Trunc, C, Ty);
1532}
1533
Reid Spencerd977d862006-12-12 23:36:14 +00001534Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
Chris Lattner42a75512007-01-15 02:27:26 +00001535 assert(C->getType()->isInteger() && "SEXt operand must be integral");
1536 assert(Ty->isInteger() && "SExt produces only integer");
Reid Spencer3da59db2006-11-27 01:05:10 +00001537 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1538 "SrcTy must be smaller than DestTy for SExt!");
1539
1540 return getFoldedCast(Instruction::SExt, C, Ty);
Chris Lattnerd144f422004-04-04 23:20:30 +00001541}
1542
Reid Spencerd977d862006-12-12 23:36:14 +00001543Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
Chris Lattner42a75512007-01-15 02:27:26 +00001544 assert(C->getType()->isInteger() && "ZEXt operand must be integral");
1545 assert(Ty->isInteger() && "ZExt produces only integer");
Reid Spencer3da59db2006-11-27 01:05:10 +00001546 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1547 "SrcTy must be smaller than DestTy for ZExt!");
1548
1549 return getFoldedCast(Instruction::ZExt, C, Ty);
1550}
1551
1552Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1553 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1554 C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1555 "This is an illegal floating point truncation!");
1556 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1557}
1558
1559Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1560 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1561 C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1562 "This is an illegal floating point extension!");
1563 return getFoldedCast(Instruction::FPExt, C, Ty);
1564}
1565
1566Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
Chris Lattner42a75512007-01-15 02:27:26 +00001567 assert(C->getType()->isInteger() && Ty->isFloatingPoint() &&
Reid Spencer3d10b0b2007-01-26 07:37:34 +00001568 "This is an illegal i32 to floating point cast!");
Reid Spencer3da59db2006-11-27 01:05:10 +00001569 return getFoldedCast(Instruction::UIToFP, C, Ty);
1570}
1571
1572Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
Chris Lattner42a75512007-01-15 02:27:26 +00001573 assert(C->getType()->isInteger() && Ty->isFloatingPoint() &&
Reid Spencer3da59db2006-11-27 01:05:10 +00001574 "This is an illegal sint to floating point cast!");
1575 return getFoldedCast(Instruction::SIToFP, C, Ty);
1576}
1577
1578Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
Chris Lattner42a75512007-01-15 02:27:26 +00001579 assert(C->getType()->isFloatingPoint() && Ty->isInteger() &&
Reid Spencer3d10b0b2007-01-26 07:37:34 +00001580 "This is an illegal floating point to i32 cast!");
Reid Spencer3da59db2006-11-27 01:05:10 +00001581 return getFoldedCast(Instruction::FPToUI, C, Ty);
1582}
1583
1584Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
Chris Lattner42a75512007-01-15 02:27:26 +00001585 assert(C->getType()->isFloatingPoint() && Ty->isInteger() &&
Reid Spencer3d10b0b2007-01-26 07:37:34 +00001586 "This is an illegal floating point to i32 cast!");
Reid Spencer3da59db2006-11-27 01:05:10 +00001587 return getFoldedCast(Instruction::FPToSI, C, Ty);
1588}
1589
1590Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1591 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
Chris Lattner42a75512007-01-15 02:27:26 +00001592 assert(DstTy->isInteger() && "PtrToInt destination must be integral");
Reid Spencer3da59db2006-11-27 01:05:10 +00001593 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1594}
1595
1596Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
Chris Lattner42a75512007-01-15 02:27:26 +00001597 assert(C->getType()->isInteger() && "IntToPtr source must be integral");
Reid Spencer3da59db2006-11-27 01:05:10 +00001598 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
1599 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1600}
1601
1602Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1603 // BitCast implies a no-op cast of type only. No bits change. However, you
1604 // can't cast pointers to anything but pointers.
1605 const Type *SrcTy = C->getType();
1606 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
Reid Spencer848414e2006-12-04 20:17:56 +00001607 "BitCast cannot cast pointer to non-pointer and vice versa");
Reid Spencer3da59db2006-11-27 01:05:10 +00001608
1609 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
1610 // or nonptr->ptr). For all the other types, the cast is okay if source and
1611 // destination bit widths are identical.
1612 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1613 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
Reid Spencer848414e2006-12-04 20:17:56 +00001614 assert(SrcBitSize == DstBitSize && "BitCast requies types of same width");
Reid Spencer3da59db2006-11-27 01:05:10 +00001615 return getFoldedCast(Instruction::BitCast, C, DstTy);
Chris Lattnerd144f422004-04-04 23:20:30 +00001616}
1617
Alkis Evlogimenos60ab1402004-10-24 01:41:10 +00001618Constant *ConstantExpr::getSizeOf(const Type *Ty) {
Chris Lattnerfcdd82e2004-12-13 19:48:51 +00001619 // sizeof is implemented as: (ulong) gep (Ty*)null, 1
Chris Lattnerf9021ff2007-02-19 20:01:23 +00001620 Constant *GEPIdx = ConstantInt::get(Type::Int32Ty, 1);
1621 Constant *GEP =
1622 getGetElementPtr(getNullValue(PointerType::get(Ty)), &GEPIdx, 1);
1623 return getCast(Instruction::PtrToInt, GEP, Type::Int64Ty);
Alkis Evlogimenos1cecd3a2005-03-19 11:40:31 +00001624}
1625
Chris Lattnered468e372003-10-05 00:17:43 +00001626Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
Reid Spencer67263fe2006-12-04 21:35:24 +00001627 Constant *C1, Constant *C2) {
Chris Lattnerf31f5832003-05-21 17:49:25 +00001628 // Check the operands for consistency first
Reid Spencer0a783f72006-11-02 01:53:59 +00001629 assert(Opcode >= Instruction::BinaryOpsBegin &&
1630 Opcode < Instruction::BinaryOpsEnd &&
Chris Lattnerf31f5832003-05-21 17:49:25 +00001631 "Invalid opcode in binary constant expression");
1632 assert(C1->getType() == C2->getType() &&
1633 "Operand types in binary constant expression should match");
Chris Lattnered468e372003-10-05 00:17:43 +00001634
Reid Spencer4fe16d62007-01-11 18:21:29 +00001635 if (ReqTy == C1->getType() || ReqTy == Type::Int1Ty)
Chris Lattnered468e372003-10-05 00:17:43 +00001636 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1637 return FC; // Fold a few common cases...
Chris Lattnerd628f6a2003-04-17 19:24:48 +00001638
Chris Lattner9bc02a42003-05-13 21:37:02 +00001639 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
Reid Spencer67263fe2006-12-04 21:35:24 +00001640 ExprMapKeyType Key(Opcode, argVec);
Chris Lattner8a94bf12006-09-28 00:35:06 +00001641 return ExprConstants->getOrCreate(ReqTy, Key);
Vikram S. Adve345e0cf2002-07-14 23:13:17 +00001642}
1643
Reid Spencere4d87aa2006-12-23 06:05:41 +00001644Constant *ConstantExpr::getCompareTy(unsigned short predicate,
Reid Spencer67263fe2006-12-04 21:35:24 +00001645 Constant *C1, Constant *C2) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001646 switch (predicate) {
1647 default: assert(0 && "Invalid CmpInst predicate");
1648 case FCmpInst::FCMP_FALSE: case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_OGT:
1649 case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OLE:
1650 case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_ORD: case FCmpInst::FCMP_UNO:
1651 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UGT: case FCmpInst::FCMP_UGE:
1652 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_ULE: case FCmpInst::FCMP_UNE:
1653 case FCmpInst::FCMP_TRUE:
1654 return getFCmp(predicate, C1, C2);
1655 case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGT:
1656 case ICmpInst::ICMP_UGE: case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE:
1657 case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_SGE: case ICmpInst::ICMP_SLT:
1658 case ICmpInst::ICMP_SLE:
1659 return getICmp(predicate, C1, C2);
1660 }
Reid Spencer67263fe2006-12-04 21:35:24 +00001661}
1662
1663Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
Chris Lattner91b362b2004-08-17 17:28:46 +00001664#ifndef NDEBUG
1665 switch (Opcode) {
Reid Spencer0a783f72006-11-02 01:53:59 +00001666 case Instruction::Add:
1667 case Instruction::Sub:
Reid Spencer1628cec2006-10-26 06:15:43 +00001668 case Instruction::Mul:
Chris Lattner91b362b2004-08-17 17:28:46 +00001669 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Chris Lattner42a75512007-01-15 02:27:26 +00001670 assert((C1->getType()->isInteger() || C1->getType()->isFloatingPoint() ||
Reid Spencer9d6565a2007-02-15 02:26:10 +00001671 isa<VectorType>(C1->getType())) &&
Chris Lattner91b362b2004-08-17 17:28:46 +00001672 "Tried to create an arithmetic operation on a non-arithmetic type!");
1673 break;
Reid Spencer1628cec2006-10-26 06:15:43 +00001674 case Instruction::UDiv:
1675 case Instruction::SDiv:
1676 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencer9d6565a2007-02-15 02:26:10 +00001677 assert((C1->getType()->isInteger() || (isa<VectorType>(C1->getType()) &&
1678 cast<VectorType>(C1->getType())->getElementType()->isInteger())) &&
Reid Spencer1628cec2006-10-26 06:15:43 +00001679 "Tried to create an arithmetic operation on a non-arithmetic type!");
1680 break;
1681 case Instruction::FDiv:
1682 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencer9d6565a2007-02-15 02:26:10 +00001683 assert((C1->getType()->isFloatingPoint() || (isa<VectorType>(C1->getType())
1684 && cast<VectorType>(C1->getType())->getElementType()->isFloatingPoint()))
Reid Spencer1628cec2006-10-26 06:15:43 +00001685 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1686 break;
Reid Spencer0a783f72006-11-02 01:53:59 +00001687 case Instruction::URem:
1688 case Instruction::SRem:
1689 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencer9d6565a2007-02-15 02:26:10 +00001690 assert((C1->getType()->isInteger() || (isa<VectorType>(C1->getType()) &&
1691 cast<VectorType>(C1->getType())->getElementType()->isInteger())) &&
Reid Spencer0a783f72006-11-02 01:53:59 +00001692 "Tried to create an arithmetic operation on a non-arithmetic type!");
1693 break;
1694 case Instruction::FRem:
1695 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencer9d6565a2007-02-15 02:26:10 +00001696 assert((C1->getType()->isFloatingPoint() || (isa<VectorType>(C1->getType())
1697 && cast<VectorType>(C1->getType())->getElementType()->isFloatingPoint()))
Reid Spencer0a783f72006-11-02 01:53:59 +00001698 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1699 break;
Chris Lattner91b362b2004-08-17 17:28:46 +00001700 case Instruction::And:
1701 case Instruction::Or:
1702 case Instruction::Xor:
1703 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencer9d6565a2007-02-15 02:26:10 +00001704 assert((C1->getType()->isInteger() || isa<VectorType>(C1->getType())) &&
Misha Brukman1bae2912005-01-27 06:46:38 +00001705 "Tried to create a logical operation on a non-integral type!");
Chris Lattner91b362b2004-08-17 17:28:46 +00001706 break;
Chris Lattner91b362b2004-08-17 17:28:46 +00001707 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00001708 case Instruction::LShr:
1709 case Instruction::AShr:
Reid Spencer832254e2007-02-02 02:16:23 +00001710 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Chris Lattner42a75512007-01-15 02:27:26 +00001711 assert(C1->getType()->isInteger() &&
Chris Lattner91b362b2004-08-17 17:28:46 +00001712 "Tried to create a shift operation on a non-integer type!");
1713 break;
1714 default:
1715 break;
1716 }
1717#endif
1718
Reid Spencer67263fe2006-12-04 21:35:24 +00001719 return getTy(C1->getType(), Opcode, C1, C2);
1720}
1721
Reid Spencere4d87aa2006-12-23 06:05:41 +00001722Constant *ConstantExpr::getCompare(unsigned short pred,
Reid Spencer67263fe2006-12-04 21:35:24 +00001723 Constant *C1, Constant *C2) {
1724 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00001725 return getCompareTy(pred, C1, C2);
Chris Lattnerc3d12f02004-08-04 18:50:09 +00001726}
1727
Chris Lattner08a45cc2004-03-12 05:54:04 +00001728Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1729 Constant *V1, Constant *V2) {
Reid Spencer3d10b0b2007-01-26 07:37:34 +00001730 assert(C->getType() == Type::Int1Ty && "Select condition must be i1!");
Chris Lattner08a45cc2004-03-12 05:54:04 +00001731 assert(V1->getType() == V2->getType() && "Select value types must match!");
1732 assert(V1->getType()->isFirstClassType() && "Cannot select aggregate type!");
1733
1734 if (ReqTy == V1->getType())
1735 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1736 return SC; // Fold common cases
1737
1738 std::vector<Constant*> argVec(3, C);
1739 argVec[1] = V1;
1740 argVec[2] = V2;
Reid Spencer077d0eb2006-12-04 05:19:50 +00001741 ExprMapKeyType Key(Instruction::Select, argVec);
Chris Lattner8a94bf12006-09-28 00:35:06 +00001742 return ExprConstants->getOrCreate(ReqTy, Key);
Chris Lattner08a45cc2004-03-12 05:54:04 +00001743}
1744
Chris Lattnered468e372003-10-05 00:17:43 +00001745Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
Chris Lattner2b9a5da2007-01-31 04:40:28 +00001746 Value* const *Idxs,
1747 unsigned NumIdx) {
1748 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs, NumIdx, true) &&
Chris Lattner2e9bb1a2004-02-16 20:46:13 +00001749 "GEP indices invalid!");
1750
Chris Lattner2b9a5da2007-01-31 04:40:28 +00001751 if (Constant *FC = ConstantFoldGetElementPtr(C, (Constant**)Idxs, NumIdx))
Chris Lattnerd628f6a2003-04-17 19:24:48 +00001752 return FC; // Fold a few common cases...
Chris Lattner2e9bb1a2004-02-16 20:46:13 +00001753
Chris Lattnered468e372003-10-05 00:17:43 +00001754 assert(isa<PointerType>(C->getType()) &&
Chris Lattner02ec5ed2003-05-23 20:03:32 +00001755 "Non-pointer type for constant GetElementPtr expression");
Vikram S. Adved0b1bb02002-07-15 18:19:33 +00001756 // Look up the constant in the table first to ensure uniqueness
Chris Lattner7fa6e662004-10-11 22:52:25 +00001757 std::vector<Constant*> ArgVec;
Chris Lattner2b9a5da2007-01-31 04:40:28 +00001758 ArgVec.reserve(NumIdx+1);
Chris Lattner7fa6e662004-10-11 22:52:25 +00001759 ArgVec.push_back(C);
Chris Lattner2b9a5da2007-01-31 04:40:28 +00001760 for (unsigned i = 0; i != NumIdx; ++i)
1761 ArgVec.push_back(cast<Constant>(Idxs[i]));
1762 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
Chris Lattner8a94bf12006-09-28 00:35:06 +00001763 return ExprConstants->getOrCreate(ReqTy, Key);
Vikram S. Adved0b1bb02002-07-15 18:19:33 +00001764}
1765
Chris Lattner2b9a5da2007-01-31 04:40:28 +00001766Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
1767 unsigned NumIdx) {
Chris Lattnered468e372003-10-05 00:17:43 +00001768 // Get the result type of the getelementptr!
Chris Lattner2b9a5da2007-01-31 04:40:28 +00001769 const Type *Ty =
1770 GetElementPtrInst::getIndexedType(C->getType(), Idxs, NumIdx, true);
Chris Lattnered468e372003-10-05 00:17:43 +00001771 assert(Ty && "GEP indices invalid!");
Chris Lattner2b9a5da2007-01-31 04:40:28 +00001772 return getGetElementPtrTy(PointerType::get(Ty), C, Idxs, NumIdx);
Chris Lattner7fa6e662004-10-11 22:52:25 +00001773}
1774
Chris Lattner2b9a5da2007-01-31 04:40:28 +00001775Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
1776 unsigned NumIdx) {
1777 return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
Chris Lattnered468e372003-10-05 00:17:43 +00001778}
1779
Chris Lattner2b9a5da2007-01-31 04:40:28 +00001780
Reid Spencer077d0eb2006-12-04 05:19:50 +00001781Constant *
1782ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1783 assert(LHS->getType() == RHS->getType());
1784 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
1785 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1786
Reid Spencere4d87aa2006-12-23 06:05:41 +00001787 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
Reid Spencer077d0eb2006-12-04 05:19:50 +00001788 return FC; // Fold a few common cases...
1789
1790 // Look up the constant in the table first to ensure uniqueness
1791 std::vector<Constant*> ArgVec;
1792 ArgVec.push_back(LHS);
1793 ArgVec.push_back(RHS);
Reid Spencer4fa021a2006-12-24 18:42:29 +00001794 // Get the key type with both the opcode and predicate
Reid Spencer077d0eb2006-12-04 05:19:50 +00001795 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
Reid Spencer4fe16d62007-01-11 18:21:29 +00001796 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
Reid Spencer077d0eb2006-12-04 05:19:50 +00001797}
1798
1799Constant *
1800ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1801 assert(LHS->getType() == RHS->getType());
1802 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1803
Reid Spencere4d87aa2006-12-23 06:05:41 +00001804 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
Reid Spencer077d0eb2006-12-04 05:19:50 +00001805 return FC; // Fold a few common cases...
1806
1807 // Look up the constant in the table first to ensure uniqueness
1808 std::vector<Constant*> ArgVec;
1809 ArgVec.push_back(LHS);
1810 ArgVec.push_back(RHS);
Reid Spencer4fa021a2006-12-24 18:42:29 +00001811 // Get the key type with both the opcode and predicate
Reid Spencer077d0eb2006-12-04 05:19:50 +00001812 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
Reid Spencer4fe16d62007-01-11 18:21:29 +00001813 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
Reid Spencer077d0eb2006-12-04 05:19:50 +00001814}
1815
Robert Bocchinob52ee7f2006-01-10 19:05:34 +00001816Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
1817 Constant *Idx) {
Robert Bocchinobb90a7a2006-01-10 20:03:46 +00001818 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
1819 return FC; // Fold a few common cases...
Robert Bocchinob52ee7f2006-01-10 19:05:34 +00001820 // Look up the constant in the table first to ensure uniqueness
1821 std::vector<Constant*> ArgVec(1, Val);
1822 ArgVec.push_back(Idx);
Reid Spencer077d0eb2006-12-04 05:19:50 +00001823 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
Chris Lattner8a94bf12006-09-28 00:35:06 +00001824 return ExprConstants->getOrCreate(ReqTy, Key);
Robert Bocchinob52ee7f2006-01-10 19:05:34 +00001825}
1826
1827Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001828 assert(isa<VectorType>(Val->getType()) &&
Reid Spencerac9dcb92007-02-15 03:39:18 +00001829 "Tried to create extractelement operation on non-vector type!");
Reid Spencer79e21d32006-12-31 05:26:44 +00001830 assert(Idx->getType() == Type::Int32Ty &&
Reid Spencer3d10b0b2007-01-26 07:37:34 +00001831 "Extractelement index must be i32 type!");
Reid Spencer9d6565a2007-02-15 02:26:10 +00001832 return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
Robert Bocchinob52ee7f2006-01-10 19:05:34 +00001833 Val, Idx);
1834}
Chris Lattnered468e372003-10-05 00:17:43 +00001835
Robert Bocchinoc152f9c2006-01-17 20:07:22 +00001836Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
1837 Constant *Elt, Constant *Idx) {
1838 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
1839 return FC; // Fold a few common cases...
1840 // Look up the constant in the table first to ensure uniqueness
1841 std::vector<Constant*> ArgVec(1, Val);
1842 ArgVec.push_back(Elt);
1843 ArgVec.push_back(Idx);
Reid Spencer077d0eb2006-12-04 05:19:50 +00001844 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
Chris Lattner8a94bf12006-09-28 00:35:06 +00001845 return ExprConstants->getOrCreate(ReqTy, Key);
Robert Bocchinoc152f9c2006-01-17 20:07:22 +00001846}
1847
1848Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1849 Constant *Idx) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001850 assert(isa<VectorType>(Val->getType()) &&
Reid Spencerac9dcb92007-02-15 03:39:18 +00001851 "Tried to create insertelement operation on non-vector type!");
Reid Spencer9d6565a2007-02-15 02:26:10 +00001852 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
Robert Bocchinoc152f9c2006-01-17 20:07:22 +00001853 && "Insertelement types must match!");
Reid Spencer79e21d32006-12-31 05:26:44 +00001854 assert(Idx->getType() == Type::Int32Ty &&
Reid Spencer3d10b0b2007-01-26 07:37:34 +00001855 "Insertelement index must be i32 type!");
Reid Spencer9d6565a2007-02-15 02:26:10 +00001856 return getInsertElementTy(cast<VectorType>(Val->getType())->getElementType(),
Robert Bocchinoc152f9c2006-01-17 20:07:22 +00001857 Val, Elt, Idx);
1858}
1859
Chris Lattner00f10232006-04-08 01:18:18 +00001860Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
1861 Constant *V2, Constant *Mask) {
1862 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
1863 return FC; // Fold a few common cases...
1864 // Look up the constant in the table first to ensure uniqueness
1865 std::vector<Constant*> ArgVec(1, V1);
1866 ArgVec.push_back(V2);
1867 ArgVec.push_back(Mask);
Reid Spencer077d0eb2006-12-04 05:19:50 +00001868 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
Chris Lattner8a94bf12006-09-28 00:35:06 +00001869 return ExprConstants->getOrCreate(ReqTy, Key);
Chris Lattner00f10232006-04-08 01:18:18 +00001870}
1871
1872Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
1873 Constant *Mask) {
1874 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1875 "Invalid shuffle vector constant expr operands!");
1876 return getShuffleVectorTy(V1->getType(), V1, V2, Mask);
1877}
1878
Reid Spencer24d6da52007-01-21 00:29:26 +00001879Constant *ConstantExpr::getZeroValueForNegationExpr(const Type *Ty) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001880 if (const VectorType *PTy = dyn_cast<VectorType>(Ty))
Reid Spencer2c7123c2007-01-21 02:29:10 +00001881 if (PTy->getElementType()->isFloatingPoint()) {
1882 std::vector<Constant*> zeros(PTy->getNumElements(),
1883 ConstantFP::get(PTy->getElementType(),-0.0));
Reid Spencer9d6565a2007-02-15 02:26:10 +00001884 return ConstantVector::get(PTy, zeros);
Reid Spencer2c7123c2007-01-21 02:29:10 +00001885 }
Reid Spencer24d6da52007-01-21 00:29:26 +00001886
1887 if (Ty->isFloatingPoint())
1888 return ConstantFP::get(Ty, -0.0);
1889
1890 return Constant::getNullValue(Ty);
1891}
1892
Vikram S. Adved0b1bb02002-07-15 18:19:33 +00001893// destroyConstant - Remove the constant from the constant table...
1894//
1895void ConstantExpr::destroyConstant() {
Chris Lattner8a94bf12006-09-28 00:35:06 +00001896 ExprConstants->remove(this);
Vikram S. Adved0b1bb02002-07-15 18:19:33 +00001897 destroyConstantImpl();
Vikram S. Adve345e0cf2002-07-14 23:13:17 +00001898}
1899
Chris Lattnerc188eeb2002-07-30 18:54:25 +00001900const char *ConstantExpr::getOpcodeName() const {
1901 return Instruction::getOpcodeName(getOpcode());
Vikram S. Adve345e0cf2002-07-14 23:13:17 +00001902}
Reid Spencer1c9c8e62004-07-17 23:48:33 +00001903
Chris Lattner5cbade92005-10-03 21:58:36 +00001904//===----------------------------------------------------------------------===//
1905// replaceUsesOfWithOnConstant implementations
1906
1907void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattnerd0ff1ad2005-10-04 18:13:04 +00001908 Use *U) {
Chris Lattner5cbade92005-10-03 21:58:36 +00001909 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
Chris Lattnerc182a882005-10-04 01:17:50 +00001910 Constant *ToC = cast<Constant>(To);
Chris Lattner23ec01f2005-10-04 18:47:09 +00001911
1912 unsigned OperandToUpdate = U-OperandList;
1913 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
1914
Jim Laskeyede5aa42006-07-17 17:38:29 +00001915 std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
Chris Lattnercea141f2005-10-03 22:51:37 +00001916 Lookup.first.first = getType();
1917 Lookup.second = this;
Chris Lattner23ec01f2005-10-04 18:47:09 +00001918
Chris Lattnercea141f2005-10-03 22:51:37 +00001919 std::vector<Constant*> &Values = Lookup.first.second;
1920 Values.reserve(getNumOperands()); // Build replacement array.
Chris Lattner23ec01f2005-10-04 18:47:09 +00001921
Chris Lattnerc182a882005-10-04 01:17:50 +00001922 // Fill values with the modified operands of the constant array. Also,
1923 // compute whether this turns into an all-zeros array.
Chris Lattner23ec01f2005-10-04 18:47:09 +00001924 bool isAllZeros = false;
1925 if (!ToC->isNullValue()) {
1926 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
1927 Values.push_back(cast<Constant>(O->get()));
1928 } else {
1929 isAllZeros = true;
1930 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1931 Constant *Val = cast<Constant>(O->get());
1932 Values.push_back(Val);
1933 if (isAllZeros) isAllZeros = Val->isNullValue();
1934 }
Chris Lattner5cbade92005-10-03 21:58:36 +00001935 }
Chris Lattner23ec01f2005-10-04 18:47:09 +00001936 Values[OperandToUpdate] = ToC;
Chris Lattner5cbade92005-10-03 21:58:36 +00001937
Chris Lattnercea141f2005-10-03 22:51:37 +00001938 Constant *Replacement = 0;
1939 if (isAllZeros) {
1940 Replacement = ConstantAggregateZero::get(getType());
1941 } else {
1942 // Check to see if we have this array type already.
1943 bool Exists;
Jim Laskeyede5aa42006-07-17 17:38:29 +00001944 ArrayConstantsTy::MapTy::iterator I =
Chris Lattner8a94bf12006-09-28 00:35:06 +00001945 ArrayConstants->InsertOrGetItem(Lookup, Exists);
Chris Lattnercea141f2005-10-03 22:51:37 +00001946
1947 if (Exists) {
1948 Replacement = I->second;
1949 } else {
1950 // Okay, the new shape doesn't exist in the system yet. Instead of
1951 // creating a new constant array, inserting it, replaceallusesof'ing the
1952 // old with the new, then deleting the old... just update the current one
1953 // in place!
Chris Lattner8a94bf12006-09-28 00:35:06 +00001954 ArrayConstants->MoveConstantToNewSlot(this, I);
Chris Lattnercea141f2005-10-03 22:51:37 +00001955
Chris Lattner23ec01f2005-10-04 18:47:09 +00001956 // Update to the new value.
1957 setOperand(OperandToUpdate, ToC);
Chris Lattnercea141f2005-10-03 22:51:37 +00001958 return;
1959 }
1960 }
1961
1962 // Otherwise, I do need to replace this with an existing value.
Chris Lattner5cbade92005-10-03 21:58:36 +00001963 assert(Replacement != this && "I didn't contain From!");
1964
Chris Lattnerd0ff1ad2005-10-04 18:13:04 +00001965 // Everyone using this now uses the replacement.
1966 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattner5cbade92005-10-03 21:58:36 +00001967
1968 // Delete the old constant!
1969 destroyConstant();
1970}
1971
1972void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattnerd0ff1ad2005-10-04 18:13:04 +00001973 Use *U) {
Chris Lattner5cbade92005-10-03 21:58:36 +00001974 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
Chris Lattnerc182a882005-10-04 01:17:50 +00001975 Constant *ToC = cast<Constant>(To);
1976
Chris Lattner23ec01f2005-10-04 18:47:09 +00001977 unsigned OperandToUpdate = U-OperandList;
1978 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
1979
Jim Laskeyede5aa42006-07-17 17:38:29 +00001980 std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
Chris Lattnerc182a882005-10-04 01:17:50 +00001981 Lookup.first.first = getType();
1982 Lookup.second = this;
1983 std::vector<Constant*> &Values = Lookup.first.second;
1984 Values.reserve(getNumOperands()); // Build replacement struct.
Chris Lattner5cbade92005-10-03 21:58:36 +00001985
Chris Lattner23ec01f2005-10-04 18:47:09 +00001986
Chris Lattnerc182a882005-10-04 01:17:50 +00001987 // Fill values with the modified operands of the constant struct. Also,
1988 // compute whether this turns into an all-zeros struct.
Chris Lattner23ec01f2005-10-04 18:47:09 +00001989 bool isAllZeros = false;
1990 if (!ToC->isNullValue()) {
1991 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
1992 Values.push_back(cast<Constant>(O->get()));
1993 } else {
1994 isAllZeros = true;
1995 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1996 Constant *Val = cast<Constant>(O->get());
1997 Values.push_back(Val);
1998 if (isAllZeros) isAllZeros = Val->isNullValue();
1999 }
Chris Lattnerc182a882005-10-04 01:17:50 +00002000 }
Chris Lattner23ec01f2005-10-04 18:47:09 +00002001 Values[OperandToUpdate] = ToC;
2002
Chris Lattnerc182a882005-10-04 01:17:50 +00002003 Constant *Replacement = 0;
2004 if (isAllZeros) {
2005 Replacement = ConstantAggregateZero::get(getType());
2006 } else {
2007 // Check to see if we have this array type already.
2008 bool Exists;
Jim Laskeyede5aa42006-07-17 17:38:29 +00002009 StructConstantsTy::MapTy::iterator I =
Chris Lattner8a94bf12006-09-28 00:35:06 +00002010 StructConstants->InsertOrGetItem(Lookup, Exists);
Chris Lattnerc182a882005-10-04 01:17:50 +00002011
2012 if (Exists) {
2013 Replacement = I->second;
2014 } else {
2015 // Okay, the new shape doesn't exist in the system yet. Instead of
2016 // creating a new constant struct, inserting it, replaceallusesof'ing the
2017 // old with the new, then deleting the old... just update the current one
2018 // in place!
Chris Lattner8a94bf12006-09-28 00:35:06 +00002019 StructConstants->MoveConstantToNewSlot(this, I);
Chris Lattnerc182a882005-10-04 01:17:50 +00002020
Chris Lattner23ec01f2005-10-04 18:47:09 +00002021 // Update to the new value.
2022 setOperand(OperandToUpdate, ToC);
Chris Lattnerc182a882005-10-04 01:17:50 +00002023 return;
2024 }
Chris Lattner5cbade92005-10-03 21:58:36 +00002025 }
2026
Chris Lattner5cbade92005-10-03 21:58:36 +00002027 assert(Replacement != this && "I didn't contain From!");
2028
Chris Lattnerd0ff1ad2005-10-04 18:13:04 +00002029 // Everyone using this now uses the replacement.
2030 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattner5cbade92005-10-03 21:58:36 +00002031
2032 // Delete the old constant!
2033 destroyConstant();
2034}
2035
Reid Spencer9d6565a2007-02-15 02:26:10 +00002036void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattnerd0ff1ad2005-10-04 18:13:04 +00002037 Use *U) {
Chris Lattner5cbade92005-10-03 21:58:36 +00002038 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2039
2040 std::vector<Constant*> Values;
2041 Values.reserve(getNumOperands()); // Build replacement array...
2042 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2043 Constant *Val = getOperand(i);
2044 if (Val == From) Val = cast<Constant>(To);
2045 Values.push_back(Val);
2046 }
2047
Reid Spencer9d6565a2007-02-15 02:26:10 +00002048 Constant *Replacement = ConstantVector::get(getType(), Values);
Chris Lattner5cbade92005-10-03 21:58:36 +00002049 assert(Replacement != this && "I didn't contain From!");
2050
Chris Lattnerd0ff1ad2005-10-04 18:13:04 +00002051 // Everyone using this now uses the replacement.
2052 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattner5cbade92005-10-03 21:58:36 +00002053
2054 // Delete the old constant!
2055 destroyConstant();
2056}
2057
2058void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
Chris Lattnerd0ff1ad2005-10-04 18:13:04 +00002059 Use *U) {
Chris Lattner5cbade92005-10-03 21:58:36 +00002060 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2061 Constant *To = cast<Constant>(ToV);
2062
2063 Constant *Replacement = 0;
2064 if (getOpcode() == Instruction::GetElementPtr) {
Chris Lattnerf9021ff2007-02-19 20:01:23 +00002065 SmallVector<Constant*, 8> Indices;
Chris Lattner5cbade92005-10-03 21:58:36 +00002066 Constant *Pointer = getOperand(0);
2067 Indices.reserve(getNumOperands()-1);
2068 if (Pointer == From) Pointer = To;
2069
2070 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2071 Constant *Val = getOperand(i);
2072 if (Val == From) Val = To;
2073 Indices.push_back(Val);
2074 }
Chris Lattnerf9021ff2007-02-19 20:01:23 +00002075 Replacement = ConstantExpr::getGetElementPtr(Pointer,
2076 &Indices[0], Indices.size());
Reid Spencer3da59db2006-11-27 01:05:10 +00002077 } else if (isCast()) {
Chris Lattner5cbade92005-10-03 21:58:36 +00002078 assert(getOperand(0) == From && "Cast only has one use!");
Reid Spencer3da59db2006-11-27 01:05:10 +00002079 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
Chris Lattner5cbade92005-10-03 21:58:36 +00002080 } else if (getOpcode() == Instruction::Select) {
2081 Constant *C1 = getOperand(0);
2082 Constant *C2 = getOperand(1);
2083 Constant *C3 = getOperand(2);
2084 if (C1 == From) C1 = To;
2085 if (C2 == From) C2 = To;
2086 if (C3 == From) C3 = To;
2087 Replacement = ConstantExpr::getSelect(C1, C2, C3);
Robert Bocchinob52ee7f2006-01-10 19:05:34 +00002088 } else if (getOpcode() == Instruction::ExtractElement) {
2089 Constant *C1 = getOperand(0);
2090 Constant *C2 = getOperand(1);
2091 if (C1 == From) C1 = To;
2092 if (C2 == From) C2 = To;
2093 Replacement = ConstantExpr::getExtractElement(C1, C2);
Chris Lattner42b55802006-04-08 05:09:48 +00002094 } else if (getOpcode() == Instruction::InsertElement) {
2095 Constant *C1 = getOperand(0);
2096 Constant *C2 = getOperand(1);
2097 Constant *C3 = getOperand(1);
2098 if (C1 == From) C1 = To;
2099 if (C2 == From) C2 = To;
2100 if (C3 == From) C3 = To;
2101 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2102 } else if (getOpcode() == Instruction::ShuffleVector) {
2103 Constant *C1 = getOperand(0);
2104 Constant *C2 = getOperand(1);
2105 Constant *C3 = getOperand(2);
2106 if (C1 == From) C1 = To;
2107 if (C2 == From) C2 = To;
2108 if (C3 == From) C3 = To;
2109 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
Reid Spencer077d0eb2006-12-04 05:19:50 +00002110 } else if (isCompare()) {
2111 Constant *C1 = getOperand(0);
2112 Constant *C2 = getOperand(1);
2113 if (C1 == From) C1 = To;
2114 if (C2 == From) C2 = To;
2115 if (getOpcode() == Instruction::ICmp)
2116 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2117 else
2118 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
Chris Lattner5cbade92005-10-03 21:58:36 +00002119 } else if (getNumOperands() == 2) {
2120 Constant *C1 = getOperand(0);
2121 Constant *C2 = getOperand(1);
2122 if (C1 == From) C1 = To;
2123 if (C2 == From) C2 = To;
2124 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2125 } else {
2126 assert(0 && "Unknown ConstantExpr type!");
2127 return;
2128 }
2129
2130 assert(Replacement != this && "I didn't contain From!");
2131
Chris Lattnerd0ff1ad2005-10-04 18:13:04 +00002132 // Everyone using this now uses the replacement.
2133 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattner5cbade92005-10-03 21:58:36 +00002134
2135 // Delete the old constant!
2136 destroyConstant();
2137}
2138
2139
Jim Laskey21b6c9d2006-03-08 18:11:07 +00002140/// getStringValue - Turn an LLVM constant pointer that eventually points to a
2141/// global into a string value. Return an empty string if we can't do it.
Evan Cheng09371032006-03-10 23:52:03 +00002142/// Parameter Chop determines if the result is chopped at the first null
2143/// terminator.
Jim Laskey21b6c9d2006-03-08 18:11:07 +00002144///
Evan Cheng09371032006-03-10 23:52:03 +00002145std::string Constant::getStringValue(bool Chop, unsigned Offset) {
Jim Laskey21b6c9d2006-03-08 18:11:07 +00002146 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(this)) {
2147 if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
2148 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
2149 if (Init->isString()) {
2150 std::string Result = Init->getAsString();
2151 if (Offset < Result.size()) {
2152 // If we are pointing INTO The string, erase the beginning...
2153 Result.erase(Result.begin(), Result.begin()+Offset);
2154
2155 // Take off the null terminator, and any string fragments after it.
Evan Cheng09371032006-03-10 23:52:03 +00002156 if (Chop) {
2157 std::string::size_type NullPos = Result.find_first_of((char)0);
2158 if (NullPos != std::string::npos)
2159 Result.erase(Result.begin()+NullPos, Result.end());
2160 }
Jim Laskey21b6c9d2006-03-08 18:11:07 +00002161 return Result;
2162 }
2163 }
2164 }
2165 } else if (Constant *C = dyn_cast<Constant>(this)) {
2166 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
Evan Cheng2352ce92006-03-11 00:13:10 +00002167 return GV->getStringValue(Chop, Offset);
Jim Laskey21b6c9d2006-03-08 18:11:07 +00002168 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2169 if (CE->getOpcode() == Instruction::GetElementPtr) {
2170 // Turn a gep into the specified offset.
2171 if (CE->getNumOperands() == 3 &&
2172 cast<Constant>(CE->getOperand(1))->isNullValue() &&
2173 isa<ConstantInt>(CE->getOperand(2))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002174 Offset += cast<ConstantInt>(CE->getOperand(2))->getZExtValue();
Evan Cheng2352ce92006-03-11 00:13:10 +00002175 return CE->getOperand(0)->getStringValue(Chop, Offset);
Jim Laskey21b6c9d2006-03-08 18:11:07 +00002176 }
2177 }
2178 }
2179 }
2180 return "";
2181}