blob: d0c837335dcee118e4accb91a1451a9e34b9797c [file] [log] [blame]
Chris Lattner2b383d2e2003-05-13 21:37:02 +00001//===-- Constants.cpp - Implement Constant nodes --------------------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner2f7c9632001-06-06 20:29:01 +00009//
Chris Lattner3462ae32001-12-03 22:26:30 +000010// This file implements the Constant* classes...
Chris Lattner2f7c9632001-06-06 20:29:01 +000011//
12//===----------------------------------------------------------------------===//
13
Chris Lattnerca142372002-04-28 19:55:58 +000014#include "llvm/Constants.h"
Chris Lattner33e93b82007-02-27 03:05:06 +000015#include "ConstantFold.h"
Chris Lattner2f7c9632001-06-06 20:29:01 +000016#include "llvm/DerivedTypes.h"
Reid Spencer1ebe1ab2004-07-17 23:48:33 +000017#include "llvm/GlobalValue.h"
Misha Brukman63b38bd2004-07-29 17:30:56 +000018#include "llvm/Instructions.h"
Chris Lattnerd7a73302001-10-13 06:57:33 +000019#include "llvm/Module.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000020#include "llvm/ADT/StringExtras.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000021#include "llvm/Support/Compiler.h"
Bill Wendling6a462f12006-11-17 08:03:48 +000022#include "llvm/Support/Debug.h"
Chris Lattner69edc982006-09-28 00:35:06 +000023#include "llvm/Support/ManagedStatic.h"
Bill Wendling6a462f12006-11-17 08:03:48 +000024#include "llvm/Support/MathExtras.h"
Chris Lattnera80bf0b2007-02-20 06:39:57 +000025#include "llvm/ADT/DenseMap.h"
Chris Lattnerb5d70302007-02-19 20:01:23 +000026#include "llvm/ADT/SmallVector.h"
Chris Lattner2f7c9632001-06-06 20:29:01 +000027#include <algorithm>
Reid Spencer3aaaa0b2007-02-05 20:47:22 +000028#include <map>
Chris Lattner189d19f2003-11-21 20:23:48 +000029using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000030
Chris Lattner2f7c9632001-06-06 20:29:01 +000031//===----------------------------------------------------------------------===//
Chris Lattner3462ae32001-12-03 22:26:30 +000032// Constant Class
Chris Lattner2f7c9632001-06-06 20:29:01 +000033//===----------------------------------------------------------------------===//
34
Chris Lattner3462ae32001-12-03 22:26:30 +000035void Constant::destroyConstantImpl() {
36 // When a Constant is destroyed, there may be lingering
Chris Lattnerd7a73302001-10-13 06:57:33 +000037 // references to the constant by other constants in the constant pool. These
Misha Brukmanbe372b92003-08-21 22:14:26 +000038 // constants are implicitly dependent on the module that is being deleted,
Chris Lattnerd7a73302001-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 Lattner3462ae32001-12-03 22:26:30 +000041 // Constants) that they are, in fact, invalid now and should be deleted.
Chris Lattnerd7a73302001-10-13 06:57:33 +000042 //
43 while (!use_empty()) {
44 Value *V = use_back();
45#ifndef NDEBUG // Only in -g mode...
Chris Lattnerd9f4ac662002-07-18 00:14:50 +000046 if (!isa<Constant>(V))
Bill Wendling6a462f12006-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 Lattnerd7a73302001-10-13 06:57:33 +000050#endif
Vikram S. Adve4e537b22002-07-14 23:13:17 +000051 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
Reid Spencer1ebe1ab2004-07-17 23:48:33 +000052 Constant *CV = cast<Constant>(V);
53 CV->destroyConstant();
Chris Lattnerd7a73302001-10-13 06:57:33 +000054
55 // The constant should remove itself from our use list...
Vikram S. Adve4e537b22002-07-14 23:13:17 +000056 assert((use_empty() || use_back() != V) && "Constant not removed!");
Chris Lattnerd7a73302001-10-13 06:57:33 +000057 }
58
59 // Value has no outstanding references it is safe to delete it now...
60 delete this;
Chris Lattner38569342001-10-01 20:11:19 +000061}
Chris Lattner2f7c9632001-06-06 20:29:01 +000062
Chris Lattner23dd1f62006-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 Spencer7e80b0b2006-10-26 06:15:43 +000080 case Instruction::UDiv:
81 case Instruction::SDiv:
82 case Instruction::FDiv:
Reid Spencer7eb55b32006-11-02 01:53:59 +000083 case Instruction::URem:
84 case Instruction::SRem:
85 case Instruction::FRem:
Chris Lattner23dd1f62006-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
Evan Chengf9e003b2007-03-08 00:59:12 +000093/// ContaintsRelocations - Return true if the constant value contains
94/// relocations which cannot be resolved at compile time.
95bool Constant::ContainsRelocations() const {
96 if (isa<GlobalValue>(this))
97 return true;
98 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
99 if (getOperand(i)->ContainsRelocations())
100 return true;
101 return false;
102}
103
Chris Lattnerb1585a92002-08-13 17:50:20 +0000104// Static constructor to create a '0' constant of arbitrary type...
105Constant *Constant::getNullValue(const Type *Ty) {
Dale Johannesen98d3a082007-09-14 22:26:36 +0000106 static uint64_t zero[2] = {0, 0};
Chris Lattner6b727592004-06-17 18:19:28 +0000107 switch (Ty->getTypeID()) {
Chris Lattnerdbcb0d32007-02-20 05:46:39 +0000108 case Type::IntegerTyID:
109 return ConstantInt::get(Ty, 0);
110 case Type::FloatTyID:
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000111 return ConstantFP::get(APFloat(APInt(32, 0)));
Chris Lattnerdbcb0d32007-02-20 05:46:39 +0000112 case Type::DoubleTyID:
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000113 return ConstantFP::get(APFloat(APInt(64, 0)));
Dale Johannesenbdad8092007-08-09 22:51:36 +0000114 case Type::X86_FP80TyID:
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000115 return ConstantFP::get(APFloat(APInt(80, 2, zero)));
Dale Johannesenbdad8092007-08-09 22:51:36 +0000116 case Type::FP128TyID:
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000117 return ConstantFP::get(APFloat(APInt(128, 2, zero), true));
Dale Johannesen98d3a082007-09-14 22:26:36 +0000118 case Type::PPC_FP128TyID:
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000119 return ConstantFP::get(APFloat(APInt(128, 2, zero)));
Misha Brukmanb1c93172005-04-21 23:48:37 +0000120 case Type::PointerTyID:
Chris Lattnerb1585a92002-08-13 17:50:20 +0000121 return ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattner9fba3da2004-02-15 05:53:04 +0000122 case Type::StructTyID:
123 case Type::ArrayTyID:
Reid Spencerd84d35b2007-02-15 02:26:10 +0000124 case Type::VectorTyID:
Chris Lattner9fba3da2004-02-15 05:53:04 +0000125 return ConstantAggregateZero::get(Ty);
Chris Lattnerb1585a92002-08-13 17:50:20 +0000126 default:
Reid Spencercf394bf2004-07-04 11:51:24 +0000127 // Function, Label, or Opaque type?
128 assert(!"Cannot create a null constant of that type!");
Chris Lattnerb1585a92002-08-13 17:50:20 +0000129 return 0;
130 }
131}
132
Chris Lattner72e39582007-06-15 06:10:53 +0000133Constant *Constant::getAllOnesValue(const Type *Ty) {
134 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
135 return ConstantInt::get(APInt::getAllOnesValue(ITy->getBitWidth()));
136 return ConstantVector::getAllOnesValue(cast<VectorType>(Ty));
137}
Chris Lattnerb1585a92002-08-13 17:50:20 +0000138
139// Static constructor to create an integral constant with all bits set
Zhou Sheng75b871f2007-01-11 12:24:14 +0000140ConstantInt *ConstantInt::getAllOnesValue(const Type *Ty) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000141 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
Reid Spencerd1bbfa52007-03-01 19:30:34 +0000142 return ConstantInt::get(APInt::getAllOnesValue(ITy->getBitWidth()));
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000143 return 0;
Chris Lattnerb1585a92002-08-13 17:50:20 +0000144}
145
Dan Gohman30978072007-05-24 14:36:04 +0000146/// @returns the value for a vector integer constant of the given type that
Chris Lattnerecab54c2007-01-04 01:49:26 +0000147/// has all its bits set to true.
148/// @brief Get the all ones value
Reid Spencerd84d35b2007-02-15 02:26:10 +0000149ConstantVector *ConstantVector::getAllOnesValue(const VectorType *Ty) {
Chris Lattnerecab54c2007-01-04 01:49:26 +0000150 std::vector<Constant*> Elts;
151 Elts.resize(Ty->getNumElements(),
Zhou Sheng75b871f2007-01-11 12:24:14 +0000152 ConstantInt::getAllOnesValue(Ty->getElementType()));
Dan Gohman30978072007-05-24 14:36:04 +0000153 assert(Elts[0] && "Not a vector integer type!");
Reid Spencerd84d35b2007-02-15 02:26:10 +0000154 return cast<ConstantVector>(ConstantVector::get(Elts));
Chris Lattnerecab54c2007-01-04 01:49:26 +0000155}
156
157
Chris Lattner2f7c9632001-06-06 20:29:01 +0000158//===----------------------------------------------------------------------===//
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000159// ConstantInt
Chris Lattner2f7c9632001-06-06 20:29:01 +0000160//===----------------------------------------------------------------------===//
161
Reid Spencerb31bffe2007-02-26 23:54:03 +0000162ConstantInt::ConstantInt(const IntegerType *Ty, const APInt& V)
Chris Lattner5db2f472007-02-20 05:55:46 +0000163 : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
Reid Spencerb31bffe2007-02-26 23:54:03 +0000164 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
Chris Lattner2f7c9632001-06-06 20:29:01 +0000165}
166
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000167ConstantInt *ConstantInt::TheTrueVal = 0;
168ConstantInt *ConstantInt::TheFalseVal = 0;
169
170namespace llvm {
171 void CleanupTrueFalse(void *) {
172 ConstantInt::ResetTrueFalse();
173 }
174}
175
176static ManagedCleanup<llvm::CleanupTrueFalse> TrueFalseCleanup;
177
178ConstantInt *ConstantInt::CreateTrueFalseVals(bool WhichOne) {
179 assert(TheTrueVal == 0 && TheFalseVal == 0);
180 TheTrueVal = get(Type::Int1Ty, 1);
181 TheFalseVal = get(Type::Int1Ty, 0);
182
183 // Ensure that llvm_shutdown nulls out TheTrueVal/TheFalseVal.
184 TrueFalseCleanup.Register();
185
186 return WhichOne ? TheTrueVal : TheFalseVal;
187}
188
189
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000190namespace {
Reid Spencerb31bffe2007-02-26 23:54:03 +0000191 struct DenseMapAPIntKeyInfo {
192 struct KeyTy {
193 APInt val;
194 const Type* type;
195 KeyTy(const APInt& V, const Type* Ty) : val(V), type(Ty) {}
196 KeyTy(const KeyTy& that) : val(that.val), type(that.type) {}
197 bool operator==(const KeyTy& that) const {
198 return type == that.type && this->val == that.val;
199 }
200 bool operator!=(const KeyTy& that) const {
201 return !this->operator==(that);
202 }
203 };
204 static inline KeyTy getEmptyKey() { return KeyTy(APInt(1,0), 0); }
205 static inline KeyTy getTombstoneKey() { return KeyTy(APInt(1,1), 0); }
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000206 static unsigned getHashValue(const KeyTy &Key) {
Chris Lattner0625bd62007-09-17 18:34:04 +0000207 return DenseMapInfo<void*>::getHashValue(Key.type) ^
Reid Spencerb31bffe2007-02-26 23:54:03 +0000208 Key.val.getHashValue();
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000209 }
Chris Lattner0625bd62007-09-17 18:34:04 +0000210 static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
211 return LHS == RHS;
212 }
Dale Johannesena719a602007-08-24 00:56:33 +0000213 static bool isPod() { return false; }
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000214 };
215}
216
217
Reid Spencerb31bffe2007-02-26 23:54:03 +0000218typedef DenseMap<DenseMapAPIntKeyInfo::KeyTy, ConstantInt*,
219 DenseMapAPIntKeyInfo> IntMapTy;
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000220static ManagedStatic<IntMapTy> IntConstants;
221
Reid Spencer362fb292007-03-19 20:39:08 +0000222ConstantInt *ConstantInt::get(const Type *Ty, uint64_t V, bool isSigned) {
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000223 const IntegerType *ITy = cast<IntegerType>(Ty);
Reid Spencer362fb292007-03-19 20:39:08 +0000224 return get(APInt(ITy->getBitWidth(), V, isSigned));
Reid Spencerb31bffe2007-02-26 23:54:03 +0000225}
226
Reid Spencerd1bbfa52007-03-01 19:30:34 +0000227// Get a ConstantInt from an APInt. Note that the value stored in the DenseMap
Dan Gohmanb3efe032008-02-07 02:30:40 +0000228// as the key, is a DenseMapAPIntKeyInfo::KeyTy which has provided the
Reid Spencerb31bffe2007-02-26 23:54:03 +0000229// operator== and operator!= to ensure that the DenseMap doesn't attempt to
230// compare APInt's of different widths, which would violate an APInt class
231// invariant which generates an assertion.
Reid Spencerd1bbfa52007-03-01 19:30:34 +0000232ConstantInt *ConstantInt::get(const APInt& V) {
233 // Get the corresponding integer type for the bit width of the value.
234 const IntegerType *ITy = IntegerType::get(V.getBitWidth());
Reid Spencerb31bffe2007-02-26 23:54:03 +0000235 // get an existing value or the insertion position
Reid Spencerd1bbfa52007-03-01 19:30:34 +0000236 DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
Reid Spencerb31bffe2007-02-26 23:54:03 +0000237 ConstantInt *&Slot = (*IntConstants)[Key];
238 // if it exists, return it.
239 if (Slot)
240 return Slot;
241 // otherwise create a new one, insert it, and return it.
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000242 return Slot = new ConstantInt(ITy, V);
243}
244
245//===----------------------------------------------------------------------===//
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000246// ConstantFP
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000247//===----------------------------------------------------------------------===//
248
Chris Lattner98bd9392008-04-09 06:38:30 +0000249static const fltSemantics *TypeToFloatSemantics(const Type *Ty) {
250 if (Ty == Type::FloatTy)
251 return &APFloat::IEEEsingle;
252 if (Ty == Type::DoubleTy)
253 return &APFloat::IEEEdouble;
254 if (Ty == Type::X86_FP80Ty)
255 return &APFloat::x87DoubleExtended;
256 else if (Ty == Type::FP128Ty)
257 return &APFloat::IEEEquad;
258
259 assert(Ty == Type::PPC_FP128Ty && "Unknown FP format");
260 return &APFloat::PPCDoubleDouble;
261}
262
Dale Johannesend246b2c2007-08-30 00:23:21 +0000263ConstantFP::ConstantFP(const Type *Ty, const APFloat& V)
264 : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
Chris Lattner98bd9392008-04-09 06:38:30 +0000265 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
266 "FP type Mismatch");
Chris Lattner2f7c9632001-06-06 20:29:01 +0000267}
268
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000269bool ConstantFP::isNullValue() const {
Dale Johannesena719a602007-08-24 00:56:33 +0000270 return Val.isZero() && !Val.isNegative();
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000271}
272
Dale Johannesen98d3a082007-09-14 22:26:36 +0000273ConstantFP *ConstantFP::getNegativeZero(const Type *Ty) {
274 APFloat apf = cast <ConstantFP>(Constant::getNullValue(Ty))->getValueAPF();
275 apf.changeSign();
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000276 return ConstantFP::get(apf);
Dale Johannesen98d3a082007-09-14 22:26:36 +0000277}
278
Dale Johannesend246b2c2007-08-30 00:23:21 +0000279bool ConstantFP::isExactlyValue(const APFloat& V) const {
280 return Val.bitwiseIsEqual(V);
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000281}
282
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000283namespace {
Dale Johannesena719a602007-08-24 00:56:33 +0000284 struct DenseMapAPFloatKeyInfo {
Dale Johannesenbdea32d2007-08-24 22:09:56 +0000285 struct KeyTy {
286 APFloat val;
287 KeyTy(const APFloat& V) : val(V){}
288 KeyTy(const KeyTy& that) : val(that.val) {}
289 bool operator==(const KeyTy& that) const {
290 return this->val.bitwiseIsEqual(that.val);
291 }
292 bool operator!=(const KeyTy& that) const {
293 return !this->operator==(that);
294 }
295 };
296 static inline KeyTy getEmptyKey() {
297 return KeyTy(APFloat(APFloat::Bogus,1));
Reid Spencerb31bffe2007-02-26 23:54:03 +0000298 }
Dale Johannesenbdea32d2007-08-24 22:09:56 +0000299 static inline KeyTy getTombstoneKey() {
300 return KeyTy(APFloat(APFloat::Bogus,2));
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000301 }
Dale Johannesenbdea32d2007-08-24 22:09:56 +0000302 static unsigned getHashValue(const KeyTy &Key) {
303 return Key.val.getHashValue();
Dale Johannesena719a602007-08-24 00:56:33 +0000304 }
Chris Lattner0625bd62007-09-17 18:34:04 +0000305 static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
306 return LHS == RHS;
307 }
Dale Johannesena719a602007-08-24 00:56:33 +0000308 static bool isPod() { return false; }
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000309 };
310}
311
312//---- ConstantFP::get() implementation...
313//
Dale Johannesenbdea32d2007-08-24 22:09:56 +0000314typedef DenseMap<DenseMapAPFloatKeyInfo::KeyTy, ConstantFP*,
Dale Johannesena719a602007-08-24 00:56:33 +0000315 DenseMapAPFloatKeyInfo> FPMapTy;
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000316
Dale Johannesena719a602007-08-24 00:56:33 +0000317static ManagedStatic<FPMapTy> FPConstants;
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000318
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000319ConstantFP *ConstantFP::get(const APFloat &V) {
Dale Johannesend246b2c2007-08-30 00:23:21 +0000320 DenseMapAPFloatKeyInfo::KeyTy Key(V);
321 ConstantFP *&Slot = (*FPConstants)[Key];
322 if (Slot) return Slot;
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000323
324 const Type *Ty;
325 if (&V.getSemantics() == &APFloat::IEEEsingle)
326 Ty = Type::FloatTy;
327 else if (&V.getSemantics() == &APFloat::IEEEdouble)
328 Ty = Type::DoubleTy;
329 else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
330 Ty = Type::X86_FP80Ty;
331 else if (&V.getSemantics() == &APFloat::IEEEquad)
332 Ty = Type::FP128Ty;
333 else {
334 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble&&"Unknown FP format");
335 Ty = Type::PPC_FP128Ty;
336 }
337
Dale Johannesend246b2c2007-08-30 00:23:21 +0000338 return Slot = new ConstantFP(Ty, V);
339}
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000340
Chris Lattner98bd9392008-04-09 06:38:30 +0000341/// get() - This returns a constant fp for the specified value in the
342/// specified type. This should only be used for simple constant values like
343/// 2.0/1.0 etc, that are known-valid both as double and as the target format.
344ConstantFP *ConstantFP::get(const Type *Ty, double V) {
345 APFloat FV(V);
346 FV.convert(*TypeToFloatSemantics(Ty), APFloat::rmNearestTiesToEven);
347 return get(FV);
348}
349
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000350//===----------------------------------------------------------------------===//
351// ConstantXXX Classes
352//===----------------------------------------------------------------------===//
353
354
Chris Lattner3462ae32001-12-03 22:26:30 +0000355ConstantArray::ConstantArray(const ArrayType *T,
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000356 const std::vector<Constant*> &V)
Gabor Greiff6caff662008-05-10 08:32:32 +0000357 : Constant(T, ConstantArrayVal,
358 OperandTraits<ConstantArray>::op_end(this) - V.size(),
359 V.size()) {
Alkis Evlogimenos0507ffe2004-09-15 02:32:15 +0000360 assert(V.size() == T->getNumElements() &&
361 "Invalid initializer vector for constant array");
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000362 Use *OL = OperandList;
Chris Lattner0144fad2005-10-03 21:56:24 +0000363 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
364 I != E; ++I, ++OL) {
Chris Lattner20a24452005-10-07 05:23:36 +0000365 Constant *C = *I;
366 assert((C->getType() == T->getElementType() ||
Alkis Evlogimenoscb031d92004-09-10 04:16:59 +0000367 (T->isAbstract() &&
Chris Lattner20a24452005-10-07 05:23:36 +0000368 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
Alkis Evlogimenoscb031d92004-09-10 04:16:59 +0000369 "Initializer for array element doesn't match array element type!");
Chris Lattner20a24452005-10-07 05:23:36 +0000370 OL->init(C, this);
Chris Lattner2f7c9632001-06-06 20:29:01 +0000371 }
372}
373
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000374
Chris Lattner3462ae32001-12-03 22:26:30 +0000375ConstantStruct::ConstantStruct(const StructType *T,
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000376 const std::vector<Constant*> &V)
Gabor Greiff6caff662008-05-10 08:32:32 +0000377 : Constant(T, ConstantStructVal,
378 OperandTraits<ConstantStruct>::op_end(this) - V.size(),
379 V.size()) {
Chris Lattnerac6db752004-02-09 04:37:31 +0000380 assert(V.size() == T->getNumElements() &&
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000381 "Invalid initializer vector for constant structure");
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000382 Use *OL = OperandList;
Chris Lattner0144fad2005-10-03 21:56:24 +0000383 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
384 I != E; ++I, ++OL) {
Chris Lattner20a24452005-10-07 05:23:36 +0000385 Constant *C = *I;
386 assert((C->getType() == T->getElementType(I-V.begin()) ||
Chris Lattner0144fad2005-10-03 21:56:24 +0000387 ((T->getElementType(I-V.begin())->isAbstract() ||
Chris Lattner20a24452005-10-07 05:23:36 +0000388 C->getType()->isAbstract()) &&
Chris Lattner0144fad2005-10-03 21:56:24 +0000389 T->getElementType(I-V.begin())->getTypeID() ==
Chris Lattner20a24452005-10-07 05:23:36 +0000390 C->getType()->getTypeID())) &&
Chris Lattner93c8f142003-06-02 17:42:47 +0000391 "Initializer for struct element doesn't match struct element type!");
Chris Lattner20a24452005-10-07 05:23:36 +0000392 OL->init(C, this);
Chris Lattner2f7c9632001-06-06 20:29:01 +0000393 }
394}
395
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000396
Reid Spencerd84d35b2007-02-15 02:26:10 +0000397ConstantVector::ConstantVector(const VectorType *T,
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000398 const std::vector<Constant*> &V)
Gabor Greiff6caff662008-05-10 08:32:32 +0000399 : Constant(T, ConstantVectorVal,
400 OperandTraits<ConstantVector>::op_end(this) - V.size(),
401 V.size()) {
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000402 Use *OL = OperandList;
Chris Lattner0144fad2005-10-03 21:56:24 +0000403 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
404 I != E; ++I, ++OL) {
Chris Lattner20a24452005-10-07 05:23:36 +0000405 Constant *C = *I;
406 assert((C->getType() == T->getElementType() ||
Alkis Evlogimenoscb031d92004-09-10 04:16:59 +0000407 (T->isAbstract() &&
Chris Lattner20a24452005-10-07 05:23:36 +0000408 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
Dan Gohman30978072007-05-24 14:36:04 +0000409 "Initializer for vector element doesn't match vector element type!");
Chris Lattner20a24452005-10-07 05:23:36 +0000410 OL->init(C, this);
Brian Gaeke02209042004-08-20 06:00:58 +0000411 }
412}
413
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000414
Gabor Greiff6caff662008-05-10 08:32:32 +0000415namespace llvm {
Gordon Henriksen14a55692007-12-10 02:14:30 +0000416// We declare several classes private to this file, so use an anonymous
417// namespace
418namespace {
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000419
Gordon Henriksen14a55692007-12-10 02:14:30 +0000420/// UnaryConstantExpr - This class is private to Constants.cpp, and is used
421/// behind the scenes to implement unary constant exprs.
422class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
Gabor Greife9ecc682008-04-06 20:25:17 +0000423 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Gordon Henriksen14a55692007-12-10 02:14:30 +0000424public:
Gabor Greife9ecc682008-04-06 20:25:17 +0000425 // allocate space for exactly one operand
426 void *operator new(size_t s) {
427 return User::operator new(s, 1);
428 }
Gordon Henriksen14a55692007-12-10 02:14:30 +0000429 UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
Gabor Greiff6caff662008-05-10 08:32:32 +0000430 : ConstantExpr(Ty, Opcode, &Op<0>(), 1) {
431 Op<0>() = C;
432 }
433 /// Transparently provide more efficient getOperand methods.
434 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000435};
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000436
Gordon Henriksen14a55692007-12-10 02:14:30 +0000437/// BinaryConstantExpr - This class is private to Constants.cpp, and is used
438/// behind the scenes to implement binary constant exprs.
439class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
Gabor Greife9ecc682008-04-06 20:25:17 +0000440 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Gordon Henriksen14a55692007-12-10 02:14:30 +0000441public:
Gabor Greife9ecc682008-04-06 20:25:17 +0000442 // allocate space for exactly two operands
443 void *operator new(size_t s) {
444 return User::operator new(s, 2);
445 }
Gordon Henriksen14a55692007-12-10 02:14:30 +0000446 BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
Gabor Greiff6caff662008-05-10 08:32:32 +0000447 : ConstantExpr(C1->getType(), Opcode, &Op<0>(), 2) {
448 Op<0>().init(C1, this);
449 Op<1>().init(C2, this);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000450 }
Gabor Greiff6caff662008-05-10 08:32:32 +0000451 /// Transparently provide more efficient getOperand methods.
452 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000453};
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000454
Gordon Henriksen14a55692007-12-10 02:14:30 +0000455/// SelectConstantExpr - This class is private to Constants.cpp, and is used
456/// behind the scenes to implement select constant exprs.
457class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
Gabor Greife9ecc682008-04-06 20:25:17 +0000458 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Gordon Henriksen14a55692007-12-10 02:14:30 +0000459public:
Gabor Greife9ecc682008-04-06 20:25:17 +0000460 // allocate space for exactly three operands
461 void *operator new(size_t s) {
462 return User::operator new(s, 3);
463 }
Gordon Henriksen14a55692007-12-10 02:14:30 +0000464 SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
Gabor Greiff6caff662008-05-10 08:32:32 +0000465 : ConstantExpr(C2->getType(), Instruction::Select, &Op<0>(), 3) {
466 Op<0>().init(C1, this);
467 Op<1>().init(C2, this);
468 Op<2>().init(C3, this);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000469 }
Gabor Greiff6caff662008-05-10 08:32:32 +0000470 /// Transparently provide more efficient getOperand methods.
471 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000472};
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000473
Gordon Henriksen14a55692007-12-10 02:14:30 +0000474/// ExtractElementConstantExpr - This class is private to
475/// Constants.cpp, and is used behind the scenes to implement
476/// extractelement constant exprs.
477class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
Gabor Greife9ecc682008-04-06 20:25:17 +0000478 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Gordon Henriksen14a55692007-12-10 02:14:30 +0000479public:
Gabor Greife9ecc682008-04-06 20:25:17 +0000480 // allocate space for exactly two operands
481 void *operator new(size_t s) {
482 return User::operator new(s, 2);
483 }
Gordon Henriksen14a55692007-12-10 02:14:30 +0000484 ExtractElementConstantExpr(Constant *C1, Constant *C2)
485 : ConstantExpr(cast<VectorType>(C1->getType())->getElementType(),
Gabor Greiff6caff662008-05-10 08:32:32 +0000486 Instruction::ExtractElement, &Op<0>(), 2) {
487 Op<0>().init(C1, this);
488 Op<1>().init(C2, this);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000489 }
Gabor Greiff6caff662008-05-10 08:32:32 +0000490 /// Transparently provide more efficient getOperand methods.
491 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000492};
Robert Bocchino23004482006-01-10 19:05:34 +0000493
Gordon Henriksen14a55692007-12-10 02:14:30 +0000494/// InsertElementConstantExpr - This class is private to
495/// Constants.cpp, and is used behind the scenes to implement
496/// insertelement constant exprs.
497class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
Gabor Greife9ecc682008-04-06 20:25:17 +0000498 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Gordon Henriksen14a55692007-12-10 02:14:30 +0000499public:
Gabor Greife9ecc682008-04-06 20:25:17 +0000500 // allocate space for exactly three operands
501 void *operator new(size_t s) {
502 return User::operator new(s, 3);
503 }
Gordon Henriksen14a55692007-12-10 02:14:30 +0000504 InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
505 : ConstantExpr(C1->getType(), Instruction::InsertElement,
Gabor Greiff6caff662008-05-10 08:32:32 +0000506 &Op<0>(), 3) {
507 Op<0>().init(C1, this);
508 Op<1>().init(C2, this);
509 Op<2>().init(C3, this);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000510 }
Gabor Greiff6caff662008-05-10 08:32:32 +0000511 /// Transparently provide more efficient getOperand methods.
512 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000513};
Robert Bocchinoca27f032006-01-17 20:07:22 +0000514
Gordon Henriksen14a55692007-12-10 02:14:30 +0000515/// ShuffleVectorConstantExpr - This class is private to
516/// Constants.cpp, and is used behind the scenes to implement
517/// shufflevector constant exprs.
518class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
Gabor Greife9ecc682008-04-06 20:25:17 +0000519 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Gordon Henriksen14a55692007-12-10 02:14:30 +0000520public:
Gabor Greife9ecc682008-04-06 20:25:17 +0000521 // allocate space for exactly three operands
522 void *operator new(size_t s) {
523 return User::operator new(s, 3);
524 }
Gordon Henriksen14a55692007-12-10 02:14:30 +0000525 ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
526 : ConstantExpr(C1->getType(), Instruction::ShuffleVector,
Gabor Greiff6caff662008-05-10 08:32:32 +0000527 &Op<0>(), 3) {
528 Op<0>().init(C1, this);
529 Op<1>().init(C2, this);
530 Op<2>().init(C3, this);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000531 }
Gabor Greiff6caff662008-05-10 08:32:32 +0000532 /// Transparently provide more efficient getOperand methods.
533 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000534};
535
536/// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
537/// used behind the scenes to implement getelementpr constant exprs.
Gabor Greife9ecc682008-04-06 20:25:17 +0000538class VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
Gordon Henriksen14a55692007-12-10 02:14:30 +0000539 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
Gabor Greiff6caff662008-05-10 08:32:32 +0000540 const Type *DestTy);
Gabor Greife9ecc682008-04-06 20:25:17 +0000541public:
542 static GetElementPtrConstantExpr *Create(Constant *C, const std::vector<Constant*> &IdxList,
Gabor Greiff6caff662008-05-10 08:32:32 +0000543 const Type *DestTy) {
544 return new(IdxList.size() + 1) GetElementPtrConstantExpr(C, IdxList, DestTy);
Gabor Greife9ecc682008-04-06 20:25:17 +0000545 }
Gabor Greiff6caff662008-05-10 08:32:32 +0000546 /// Transparently provide more efficient getOperand methods.
547 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000548};
549
550// CompareConstantExpr - This class is private to Constants.cpp, and is used
551// behind the scenes to implement ICmp and FCmp constant expressions. This is
552// needed in order to store the predicate value for these instructions.
553struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
Gabor Greife9ecc682008-04-06 20:25:17 +0000554 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
555 // allocate space for exactly two operands
556 void *operator new(size_t s) {
557 return User::operator new(s, 2);
558 }
Gordon Henriksen14a55692007-12-10 02:14:30 +0000559 unsigned short predicate;
Gordon Henriksen14a55692007-12-10 02:14:30 +0000560 CompareConstantExpr(Instruction::OtherOps opc, unsigned short pred,
561 Constant* LHS, Constant* RHS)
Gabor Greiff6caff662008-05-10 08:32:32 +0000562 : ConstantExpr(Type::Int1Ty, opc, &Op<0>(), 2), predicate(pred) {
563 Op<0>().init(LHS, this);
564 Op<1>().init(RHS, this);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000565 }
Gabor Greiff6caff662008-05-10 08:32:32 +0000566 /// Transparently provide more efficient getOperand methods.
567 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000568};
569
570} // end anonymous namespace
571
Gabor Greiff6caff662008-05-10 08:32:32 +0000572template <>
573struct OperandTraits<UnaryConstantExpr> : FixedNumOperandTraits<1> {
574};
575DEFINE_TRANSPARENT_OPERAND_ACCESSORS(UnaryConstantExpr, Value)
576
577template <>
578struct OperandTraits<BinaryConstantExpr> : FixedNumOperandTraits<2> {
579};
580DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BinaryConstantExpr, Value)
581
582template <>
583struct OperandTraits<SelectConstantExpr> : FixedNumOperandTraits<3> {
584};
585DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectConstantExpr, Value)
586
587template <>
588struct OperandTraits<ExtractElementConstantExpr> : FixedNumOperandTraits<2> {
589};
590DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementConstantExpr, Value)
591
592template <>
593struct OperandTraits<InsertElementConstantExpr> : FixedNumOperandTraits<3> {
594};
595DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementConstantExpr, Value)
596
597template <>
598struct OperandTraits<ShuffleVectorConstantExpr> : FixedNumOperandTraits<3> {
599};
600DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorConstantExpr, Value)
601
602
603template <>
604struct OperandTraits<GetElementPtrConstantExpr> : VariadicOperandTraits<1> {
605};
606
607GetElementPtrConstantExpr::GetElementPtrConstantExpr
608 (Constant *C,
609 const std::vector<Constant*> &IdxList,
610 const Type *DestTy)
611 : ConstantExpr(DestTy, Instruction::GetElementPtr,
612 OperandTraits<GetElementPtrConstantExpr>::op_end(this)
613 - (IdxList.size()+1),
614 IdxList.size()+1) {
615 OperandList[0].init(C, this);
616 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
617 OperandList[i+1].init(IdxList[i], this);
618}
619
620DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrConstantExpr, Value)
621
622
623template <>
624struct OperandTraits<CompareConstantExpr> : FixedNumOperandTraits<2> {
625};
626DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CompareConstantExpr, Value)
627
628
629} // End llvm namespace
630
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000631
632// Utility function for determining if a ConstantExpr is a CastOp or not. This
633// can't be inline because we don't want to #include Instruction.h into
634// Constant.h
635bool ConstantExpr::isCast() const {
636 return Instruction::isCast(getOpcode());
637}
638
Reid Spenceree3c9912006-12-04 05:19:50 +0000639bool ConstantExpr::isCompare() const {
640 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
641}
642
Chris Lattner817175f2004-03-29 02:37:53 +0000643/// ConstantExpr::get* - Return some common constants without having to
644/// specify the full Instruction::OPCODE identifier.
645///
646Constant *ConstantExpr::getNeg(Constant *C) {
Reid Spencer2eadb532007-01-21 00:29:26 +0000647 return get(Instruction::Sub,
648 ConstantExpr::getZeroValueForNegationExpr(C->getType()),
649 C);
Chris Lattner817175f2004-03-29 02:37:53 +0000650}
651Constant *ConstantExpr::getNot(Constant *C) {
Gordon Henriksen7ce31762007-10-06 14:29:36 +0000652 assert(isa<IntegerType>(C->getType()) && "Cannot NOT a nonintegral value!");
Chris Lattner817175f2004-03-29 02:37:53 +0000653 return get(Instruction::Xor, C,
Zhou Sheng75b871f2007-01-11 12:24:14 +0000654 ConstantInt::getAllOnesValue(C->getType()));
Chris Lattner817175f2004-03-29 02:37:53 +0000655}
656Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
657 return get(Instruction::Add, C1, C2);
658}
659Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
660 return get(Instruction::Sub, C1, C2);
661}
662Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
663 return get(Instruction::Mul, C1, C2);
664}
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000665Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2) {
666 return get(Instruction::UDiv, C1, C2);
667}
668Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2) {
669 return get(Instruction::SDiv, C1, C2);
670}
671Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
672 return get(Instruction::FDiv, C1, C2);
Chris Lattner817175f2004-03-29 02:37:53 +0000673}
Reid Spencer7eb55b32006-11-02 01:53:59 +0000674Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
675 return get(Instruction::URem, C1, C2);
676}
677Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
678 return get(Instruction::SRem, C1, C2);
679}
680Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
681 return get(Instruction::FRem, C1, C2);
Chris Lattner817175f2004-03-29 02:37:53 +0000682}
683Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
684 return get(Instruction::And, C1, C2);
685}
686Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
687 return get(Instruction::Or, C1, C2);
688}
689Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
690 return get(Instruction::Xor, C1, C2);
691}
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000692unsigned ConstantExpr::getPredicate() const {
693 assert(getOpcode() == Instruction::FCmp || getOpcode() == Instruction::ICmp);
Chris Lattneref650092007-10-18 16:26:24 +0000694 return ((const CompareConstantExpr*)this)->predicate;
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000695}
Chris Lattner817175f2004-03-29 02:37:53 +0000696Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
697 return get(Instruction::Shl, C1, C2);
698}
Reid Spencerfdff9382006-11-08 06:47:33 +0000699Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2) {
700 return get(Instruction::LShr, C1, C2);
Chris Lattner817175f2004-03-29 02:37:53 +0000701}
Reid Spencerfdff9382006-11-08 06:47:33 +0000702Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2) {
703 return get(Instruction::AShr, C1, C2);
Chris Lattnerdb8bdba2004-05-25 05:32:43 +0000704}
Chris Lattner60e0dd72001-10-03 06:12:09 +0000705
Chris Lattner7c1018a2006-07-14 19:37:40 +0000706/// getWithOperandReplaced - Return a constant expression identical to this
707/// one, but with the specified operand set to the specified value.
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000708Constant *
709ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
Chris Lattner7c1018a2006-07-14 19:37:40 +0000710 assert(OpNo < getNumOperands() && "Operand num is out of range!");
711 assert(Op->getType() == getOperand(OpNo)->getType() &&
712 "Replacing operand with value of different type!");
Chris Lattner227816342006-07-14 22:20:01 +0000713 if (getOperand(OpNo) == Op)
714 return const_cast<ConstantExpr*>(this);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000715
Chris Lattner227816342006-07-14 22:20:01 +0000716 Constant *Op0, *Op1, *Op2;
Chris Lattner7c1018a2006-07-14 19:37:40 +0000717 switch (getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000718 case Instruction::Trunc:
719 case Instruction::ZExt:
720 case Instruction::SExt:
721 case Instruction::FPTrunc:
722 case Instruction::FPExt:
723 case Instruction::UIToFP:
724 case Instruction::SIToFP:
725 case Instruction::FPToUI:
726 case Instruction::FPToSI:
727 case Instruction::PtrToInt:
728 case Instruction::IntToPtr:
729 case Instruction::BitCast:
730 return ConstantExpr::getCast(getOpcode(), Op, getType());
Chris Lattner227816342006-07-14 22:20:01 +0000731 case Instruction::Select:
732 Op0 = (OpNo == 0) ? Op : getOperand(0);
733 Op1 = (OpNo == 1) ? Op : getOperand(1);
734 Op2 = (OpNo == 2) ? Op : getOperand(2);
735 return ConstantExpr::getSelect(Op0, Op1, Op2);
736 case Instruction::InsertElement:
737 Op0 = (OpNo == 0) ? Op : getOperand(0);
738 Op1 = (OpNo == 1) ? Op : getOperand(1);
739 Op2 = (OpNo == 2) ? Op : getOperand(2);
740 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
741 case Instruction::ExtractElement:
742 Op0 = (OpNo == 0) ? Op : getOperand(0);
743 Op1 = (OpNo == 1) ? Op : getOperand(1);
744 return ConstantExpr::getExtractElement(Op0, Op1);
745 case Instruction::ShuffleVector:
746 Op0 = (OpNo == 0) ? Op : getOperand(0);
747 Op1 = (OpNo == 1) ? Op : getOperand(1);
748 Op2 = (OpNo == 2) ? Op : getOperand(2);
749 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000750 case Instruction::GetElementPtr: {
Chris Lattnerb5d70302007-02-19 20:01:23 +0000751 SmallVector<Constant*, 8> Ops;
752 Ops.resize(getNumOperands());
Chris Lattner7c1018a2006-07-14 19:37:40 +0000753 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
Chris Lattnerb5d70302007-02-19 20:01:23 +0000754 Ops[i] = getOperand(i);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000755 if (OpNo == 0)
Chris Lattnerb5d70302007-02-19 20:01:23 +0000756 return ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
Chris Lattner7c1018a2006-07-14 19:37:40 +0000757 Ops[OpNo-1] = Op;
Chris Lattnerb5d70302007-02-19 20:01:23 +0000758 return ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
Chris Lattner7c1018a2006-07-14 19:37:40 +0000759 }
Chris Lattner7c1018a2006-07-14 19:37:40 +0000760 default:
761 assert(getNumOperands() == 2 && "Must be binary operator?");
Chris Lattner227816342006-07-14 22:20:01 +0000762 Op0 = (OpNo == 0) ? Op : getOperand(0);
763 Op1 = (OpNo == 1) ? Op : getOperand(1);
764 return ConstantExpr::get(getOpcode(), Op0, Op1);
765 }
766}
767
768/// getWithOperands - This returns the current constant expression with the
769/// operands replaced with the specified values. The specified operands must
770/// match count and type with the existing ones.
771Constant *ConstantExpr::
772getWithOperands(const std::vector<Constant*> &Ops) const {
773 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
774 bool AnyChange = false;
775 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
776 assert(Ops[i]->getType() == getOperand(i)->getType() &&
777 "Operand type mismatch!");
778 AnyChange |= Ops[i] != getOperand(i);
779 }
780 if (!AnyChange) // No operands changed, return self.
781 return const_cast<ConstantExpr*>(this);
782
783 switch (getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000784 case Instruction::Trunc:
785 case Instruction::ZExt:
786 case Instruction::SExt:
787 case Instruction::FPTrunc:
788 case Instruction::FPExt:
789 case Instruction::UIToFP:
790 case Instruction::SIToFP:
791 case Instruction::FPToUI:
792 case Instruction::FPToSI:
793 case Instruction::PtrToInt:
794 case Instruction::IntToPtr:
795 case Instruction::BitCast:
796 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
Chris Lattner227816342006-07-14 22:20:01 +0000797 case Instruction::Select:
798 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
799 case Instruction::InsertElement:
800 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
801 case Instruction::ExtractElement:
802 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
803 case Instruction::ShuffleVector:
804 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
Chris Lattnerb5d70302007-02-19 20:01:23 +0000805 case Instruction::GetElementPtr:
806 return ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], Ops.size()-1);
Reid Spencer266e42b2006-12-23 06:05:41 +0000807 case Instruction::ICmp:
808 case Instruction::FCmp:
809 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
Chris Lattner227816342006-07-14 22:20:01 +0000810 default:
811 assert(getNumOperands() == 2 && "Must be binary operator?");
812 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000813 }
814}
815
Chris Lattner2f7c9632001-06-06 20:29:01 +0000816
817//===----------------------------------------------------------------------===//
Chris Lattner2f7c9632001-06-06 20:29:01 +0000818// isValueValidForType implementations
819
Reid Spencere7334722006-12-19 01:28:19 +0000820bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000821 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000822 if (Ty == Type::Int1Ty)
823 return Val == 0 || Val == 1;
Reid Spencerd7a00d72007-02-05 23:47:56 +0000824 if (NumBits >= 64)
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000825 return true; // always true, has to fit in largest type
826 uint64_t Max = (1ll << NumBits) - 1;
827 return Val <= Max;
Reid Spencere7334722006-12-19 01:28:19 +0000828}
829
Reid Spencere0fc4df2006-10-20 07:07:24 +0000830bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000831 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000832 if (Ty == Type::Int1Ty)
Reid Spencera94d3942007-01-19 21:13:56 +0000833 return Val == 0 || Val == 1 || Val == -1;
Reid Spencerd7a00d72007-02-05 23:47:56 +0000834 if (NumBits >= 64)
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000835 return true; // always true, has to fit in largest type
836 int64_t Min = -(1ll << (NumBits-1));
837 int64_t Max = (1ll << (NumBits-1)) - 1;
838 return (Val >= Min && Val <= Max);
Chris Lattner2f7c9632001-06-06 20:29:01 +0000839}
840
Dale Johannesend246b2c2007-08-30 00:23:21 +0000841bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
842 // convert modifies in place, so make a copy.
843 APFloat Val2 = APFloat(Val);
Chris Lattner6b727592004-06-17 18:19:28 +0000844 switch (Ty->getTypeID()) {
Chris Lattner2f7c9632001-06-06 20:29:01 +0000845 default:
846 return false; // These can't be represented as floating point!
847
Dale Johannesend246b2c2007-08-30 00:23:21 +0000848 // FIXME rounding mode needs to be more flexible
Chris Lattner2f7c9632001-06-06 20:29:01 +0000849 case Type::FloatTyID:
Dale Johannesend246b2c2007-08-30 00:23:21 +0000850 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
851 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven) ==
852 APFloat::opOK;
Chris Lattner2f7c9632001-06-06 20:29:01 +0000853 case Type::DoubleTyID:
Dale Johannesend246b2c2007-08-30 00:23:21 +0000854 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
855 &Val2.getSemantics() == &APFloat::IEEEdouble ||
856 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven) ==
857 APFloat::opOK;
Dale Johannesenbdad8092007-08-09 22:51:36 +0000858 case Type::X86_FP80TyID:
Dale Johannesen028084e2007-09-12 03:30:33 +0000859 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
860 &Val2.getSemantics() == &APFloat::IEEEdouble ||
861 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
Dale Johannesenbdad8092007-08-09 22:51:36 +0000862 case Type::FP128TyID:
Dale Johannesen028084e2007-09-12 03:30:33 +0000863 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
864 &Val2.getSemantics() == &APFloat::IEEEdouble ||
865 &Val2.getSemantics() == &APFloat::IEEEquad;
Dale Johannesen007aa372007-10-11 18:07:22 +0000866 case Type::PPC_FP128TyID:
867 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
868 &Val2.getSemantics() == &APFloat::IEEEdouble ||
869 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
Chris Lattner2f7c9632001-06-06 20:29:01 +0000870 }
Chris Lattneraa2372562006-05-24 17:04:05 +0000871}
Chris Lattner9655e542001-07-20 19:16:02 +0000872
Chris Lattner49d855c2001-09-07 16:46:31 +0000873//===----------------------------------------------------------------------===//
Chris Lattner49d855c2001-09-07 16:46:31 +0000874// Factory Function Implementation
875
Gabor Greiff6caff662008-05-10 08:32:32 +0000876
877// The number of operands for each ConstantCreator::create method is
878// determined by the ConstantTraits template.
Chris Lattner98fa07b2003-05-23 20:03:32 +0000879// ConstantCreator - A class that is used to create constants by
880// ValueMap*. This class should be partially specialized if there is
881// something strange that needs to be done to interface to the ctor for the
882// constant.
883//
Chris Lattner189d19f2003-11-21 20:23:48 +0000884namespace llvm {
Gabor Greiff6caff662008-05-10 08:32:32 +0000885 template<class ValType>
886 struct ConstantTraits;
887
888 template<typename T, typename Alloc>
889 struct VISIBILITY_HIDDEN ConstantTraits< std::vector<T, Alloc> > {
890 static unsigned uses(const std::vector<T, Alloc>& v) {
891 return v.size();
892 }
893 };
894
Chris Lattner189d19f2003-11-21 20:23:48 +0000895 template<class ConstantClass, class TypeClass, class ValType>
Chris Lattner02157b02006-06-28 21:38:54 +0000896 struct VISIBILITY_HIDDEN ConstantCreator {
Chris Lattner189d19f2003-11-21 20:23:48 +0000897 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
Gabor Greiff6caff662008-05-10 08:32:32 +0000898 return new(ConstantTraits<ValType>::uses(V)) ConstantClass(Ty, V);
Chris Lattner189d19f2003-11-21 20:23:48 +0000899 }
900 };
Misha Brukmanb1c93172005-04-21 23:48:37 +0000901
Chris Lattner189d19f2003-11-21 20:23:48 +0000902 template<class ConstantClass, class TypeClass>
Chris Lattner02157b02006-06-28 21:38:54 +0000903 struct VISIBILITY_HIDDEN ConvertConstantType {
Chris Lattner189d19f2003-11-21 20:23:48 +0000904 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
905 assert(0 && "This type cannot be converted!\n");
906 abort();
907 }
908 };
Chris Lattnerb50d1352003-10-05 00:17:43 +0000909
Chris Lattner935aa922005-10-04 17:48:46 +0000910 template<class ValType, class TypeClass, class ConstantClass,
911 bool HasLargeKey = false /*true for arrays and structs*/ >
Chris Lattner02157b02006-06-28 21:38:54 +0000912 class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
Chris Lattnerb64419a2005-10-03 22:51:37 +0000913 public:
Jim Laskeyc03caef2006-07-17 17:38:29 +0000914 typedef std::pair<const Type*, ValType> MapKey;
915 typedef std::map<MapKey, Constant *> MapTy;
916 typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
917 typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
Chris Lattnerb64419a2005-10-03 22:51:37 +0000918 private:
Chris Lattner5bbf60a52005-10-04 16:52:46 +0000919 /// Map - This is the main map from the element descriptor to the Constants.
920 /// This is the primary way we avoid creating two of the same shape
921 /// constant.
Chris Lattnerb50d1352003-10-05 00:17:43 +0000922 MapTy Map;
Chris Lattner935aa922005-10-04 17:48:46 +0000923
924 /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
925 /// from the constants to their element in Map. This is important for
926 /// removal of constants from the array, which would otherwise have to scan
927 /// through the map with very large keys.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000928 InverseMapTy InverseMap;
Chris Lattnerb50d1352003-10-05 00:17:43 +0000929
Jim Laskeyc03caef2006-07-17 17:38:29 +0000930 /// AbstractTypeMap - Map for abstract type constants.
931 ///
Chris Lattnerb50d1352003-10-05 00:17:43 +0000932 AbstractTypeMapTy AbstractTypeMap;
Chris Lattner99a669b2004-11-19 16:39:44 +0000933
Chris Lattner98fa07b2003-05-23 20:03:32 +0000934 public:
Jim Laskeyc03caef2006-07-17 17:38:29 +0000935 typename MapTy::iterator map_end() { return Map.end(); }
Chris Lattnerb64419a2005-10-03 22:51:37 +0000936
937 /// InsertOrGetItem - Return an iterator for the specified element.
938 /// If the element exists in the map, the returned iterator points to the
939 /// entry and Exists=true. If not, the iterator points to the newly
940 /// inserted entry and returns Exists=false. Newly inserted entries have
941 /// I->second == 0, and should be filled in.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000942 typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
943 &InsertVal,
Chris Lattnerb64419a2005-10-03 22:51:37 +0000944 bool &Exists) {
Jim Laskeyc03caef2006-07-17 17:38:29 +0000945 std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
Chris Lattnerb64419a2005-10-03 22:51:37 +0000946 Exists = !IP.second;
947 return IP.first;
948 }
Chris Lattner5bbf60a52005-10-04 16:52:46 +0000949
Chris Lattner935aa922005-10-04 17:48:46 +0000950private:
Jim Laskeyc03caef2006-07-17 17:38:29 +0000951 typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
Chris Lattner935aa922005-10-04 17:48:46 +0000952 if (HasLargeKey) {
Jim Laskeyc03caef2006-07-17 17:38:29 +0000953 typename InverseMapTy::iterator IMI = InverseMap.find(CP);
Chris Lattner935aa922005-10-04 17:48:46 +0000954 assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
955 IMI->second->second == CP &&
956 "InverseMap corrupt!");
957 return IMI->second;
958 }
959
Jim Laskeyc03caef2006-07-17 17:38:29 +0000960 typename MapTy::iterator I =
Chris Lattner935aa922005-10-04 17:48:46 +0000961 Map.find(MapKey((TypeClass*)CP->getRawType(), getValType(CP)));
Chris Lattner5bbf60a52005-10-04 16:52:46 +0000962 if (I == Map.end() || I->second != CP) {
963 // FIXME: This should not use a linear scan. If this gets to be a
964 // performance problem, someone should look at this.
965 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
966 /* empty */;
967 }
Chris Lattner935aa922005-10-04 17:48:46 +0000968 return I;
969 }
970public:
971
Chris Lattnerb64419a2005-10-03 22:51:37 +0000972 /// getOrCreate - Return the specified constant from the map, creating it if
973 /// necessary.
Chris Lattner98fa07b2003-05-23 20:03:32 +0000974 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
Chris Lattnerb50d1352003-10-05 00:17:43 +0000975 MapKey Lookup(Ty, V);
Jim Laskeyc03caef2006-07-17 17:38:29 +0000976 typename MapTy::iterator I = Map.lower_bound(Lookup);
Reid Spencere0fc4df2006-10-20 07:07:24 +0000977 // Is it in the map?
Chris Lattner98fa07b2003-05-23 20:03:32 +0000978 if (I != Map.end() && I->first == Lookup)
Reid Spencere0fc4df2006-10-20 07:07:24 +0000979 return static_cast<ConstantClass *>(I->second);
Chris Lattner98fa07b2003-05-23 20:03:32 +0000980
981 // If no preexisting value, create one now...
982 ConstantClass *Result =
983 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
984
Chris Lattnerb50d1352003-10-05 00:17:43 +0000985 /// FIXME: why does this assert fail when loading 176.gcc?
986 //assert(Result->getType() == Ty && "Type specified is not correct!");
987 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
988
Chris Lattner935aa922005-10-04 17:48:46 +0000989 if (HasLargeKey) // Remember the reverse mapping if needed.
990 InverseMap.insert(std::make_pair(Result, I));
991
Chris Lattnerb50d1352003-10-05 00:17:43 +0000992 // If the type of the constant is abstract, make sure that an entry exists
993 // for it in the AbstractTypeMap.
994 if (Ty->isAbstract()) {
995 typename AbstractTypeMapTy::iterator TI =
996 AbstractTypeMap.lower_bound(Ty);
997
998 if (TI == AbstractTypeMap.end() || TI->first != Ty) {
999 // Add ourselves to the ATU list of the type.
1000 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
1001
1002 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
1003 }
1004 }
Chris Lattner98fa07b2003-05-23 20:03:32 +00001005 return Result;
1006 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001007
Chris Lattner98fa07b2003-05-23 20:03:32 +00001008 void remove(ConstantClass *CP) {
Jim Laskeyc03caef2006-07-17 17:38:29 +00001009 typename MapTy::iterator I = FindExistingElement(CP);
Chris Lattnerb50d1352003-10-05 00:17:43 +00001010 assert(I != Map.end() && "Constant not found in constant table!");
Chris Lattner3e650af2004-08-04 04:48:01 +00001011 assert(I->second == CP && "Didn't find correct element?");
Chris Lattnerb50d1352003-10-05 00:17:43 +00001012
Chris Lattner935aa922005-10-04 17:48:46 +00001013 if (HasLargeKey) // Remember the reverse mapping if needed.
1014 InverseMap.erase(CP);
1015
Chris Lattnerb50d1352003-10-05 00:17:43 +00001016 // Now that we found the entry, make sure this isn't the entry that
1017 // the AbstractTypeMap points to.
Jim Laskeyc03caef2006-07-17 17:38:29 +00001018 const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
Chris Lattnerb50d1352003-10-05 00:17:43 +00001019 if (Ty->isAbstract()) {
1020 assert(AbstractTypeMap.count(Ty) &&
1021 "Abstract type not in AbstractTypeMap?");
Jim Laskeyc03caef2006-07-17 17:38:29 +00001022 typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
Chris Lattnerb50d1352003-10-05 00:17:43 +00001023 if (ATMEntryIt == I) {
1024 // Yes, we are removing the representative entry for this type.
1025 // See if there are any other entries of the same type.
Jim Laskeyc03caef2006-07-17 17:38:29 +00001026 typename MapTy::iterator TmpIt = ATMEntryIt;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001027
Chris Lattnerb50d1352003-10-05 00:17:43 +00001028 // First check the entry before this one...
1029 if (TmpIt != Map.begin()) {
1030 --TmpIt;
1031 if (TmpIt->first.first != Ty) // Not the same type, move back...
1032 ++TmpIt;
1033 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001034
Chris Lattnerb50d1352003-10-05 00:17:43 +00001035 // If we didn't find the same type, try to move forward...
1036 if (TmpIt == ATMEntryIt) {
1037 ++TmpIt;
1038 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
1039 --TmpIt; // No entry afterwards with the same type
1040 }
1041
1042 // If there is another entry in the map of the same abstract type,
1043 // update the AbstractTypeMap entry now.
1044 if (TmpIt != ATMEntryIt) {
1045 ATMEntryIt = TmpIt;
1046 } else {
1047 // Otherwise, we are removing the last instance of this type
1048 // from the table. Remove from the ATM, and from user list.
1049 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
1050 AbstractTypeMap.erase(Ty);
1051 }
Chris Lattner98fa07b2003-05-23 20:03:32 +00001052 }
Chris Lattnerb50d1352003-10-05 00:17:43 +00001053 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001054
Chris Lattnerb50d1352003-10-05 00:17:43 +00001055 Map.erase(I);
1056 }
1057
Chris Lattner3b793c62005-10-04 21:35:50 +00001058
1059 /// MoveConstantToNewSlot - If we are about to change C to be the element
1060 /// specified by I, update our internal data structures to reflect this
1061 /// fact.
Jim Laskeyc03caef2006-07-17 17:38:29 +00001062 void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
Chris Lattner3b793c62005-10-04 21:35:50 +00001063 // First, remove the old location of the specified constant in the map.
Jim Laskeyc03caef2006-07-17 17:38:29 +00001064 typename MapTy::iterator OldI = FindExistingElement(C);
Chris Lattner3b793c62005-10-04 21:35:50 +00001065 assert(OldI != Map.end() && "Constant not found in constant table!");
1066 assert(OldI->second == C && "Didn't find correct element?");
1067
1068 // If this constant is the representative element for its abstract type,
1069 // update the AbstractTypeMap so that the representative element is I.
1070 if (C->getType()->isAbstract()) {
1071 typename AbstractTypeMapTy::iterator ATI =
1072 AbstractTypeMap.find(C->getType());
1073 assert(ATI != AbstractTypeMap.end() &&
1074 "Abstract type not in AbstractTypeMap?");
1075 if (ATI->second == OldI)
1076 ATI->second = I;
1077 }
1078
1079 // Remove the old entry from the map.
1080 Map.erase(OldI);
1081
1082 // Update the inverse map so that we know that this constant is now
1083 // located at descriptor I.
1084 if (HasLargeKey) {
1085 assert(I->second == C && "Bad inversemap entry!");
1086 InverseMap[C] = I;
1087 }
1088 }
1089
Chris Lattnerb50d1352003-10-05 00:17:43 +00001090 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00001091 typename AbstractTypeMapTy::iterator I =
Jim Laskeyc03caef2006-07-17 17:38:29 +00001092 AbstractTypeMap.find(cast<Type>(OldTy));
Chris Lattnerb50d1352003-10-05 00:17:43 +00001093
1094 assert(I != AbstractTypeMap.end() &&
1095 "Abstract type not in AbstractTypeMap?");
1096
1097 // Convert a constant at a time until the last one is gone. The last one
1098 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
1099 // eliminated eventually.
1100 do {
1101 ConvertConstantType<ConstantClass,
Jim Laskeyc03caef2006-07-17 17:38:29 +00001102 TypeClass>::convert(
1103 static_cast<ConstantClass *>(I->second->second),
Chris Lattnerb50d1352003-10-05 00:17:43 +00001104 cast<TypeClass>(NewTy));
1105
Jim Laskeyc03caef2006-07-17 17:38:29 +00001106 I = AbstractTypeMap.find(cast<Type>(OldTy));
Chris Lattnerb50d1352003-10-05 00:17:43 +00001107 } while (I != AbstractTypeMap.end());
1108 }
1109
1110 // If the type became concrete without being refined to any other existing
1111 // type, we just remove ourselves from the ATU list.
1112 void typeBecameConcrete(const DerivedType *AbsTy) {
1113 AbsTy->removeAbstractTypeUser(this);
1114 }
1115
1116 void dump() const {
Bill Wendling6a462f12006-11-17 08:03:48 +00001117 DOUT << "Constant.cpp: ValueMap\n";
Chris Lattner98fa07b2003-05-23 20:03:32 +00001118 }
1119 };
1120}
1121
Chris Lattnera84df0a22006-09-28 23:36:21 +00001122
Chris Lattner28173502007-02-20 06:11:36 +00001123
Chris Lattner9fba3da2004-02-15 05:53:04 +00001124//---- ConstantAggregateZero::get() implementation...
1125//
1126namespace llvm {
1127 // ConstantAggregateZero does not take extra "value" argument...
1128 template<class ValType>
1129 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
1130 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
1131 return new ConstantAggregateZero(Ty);
1132 }
1133 };
1134
1135 template<>
1136 struct ConvertConstantType<ConstantAggregateZero, Type> {
1137 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
1138 // Make everyone now use a constant of the new type...
1139 Constant *New = ConstantAggregateZero::get(NewTy);
1140 assert(New != OldC && "Didn't replace constant??");
1141 OldC->uncheckedReplaceAllUsesWith(New);
1142 OldC->destroyConstant(); // This constant is now dead, destroy it.
1143 }
1144 };
1145}
1146
Chris Lattner69edc982006-09-28 00:35:06 +00001147static ManagedStatic<ValueMap<char, Type,
1148 ConstantAggregateZero> > AggZeroConstants;
Chris Lattner9fba3da2004-02-15 05:53:04 +00001149
Chris Lattner3e650af2004-08-04 04:48:01 +00001150static char getValType(ConstantAggregateZero *CPZ) { return 0; }
1151
Chris Lattner9fba3da2004-02-15 05:53:04 +00001152Constant *ConstantAggregateZero::get(const Type *Ty) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001153 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) &&
Chris Lattnerbfd0b6d2006-06-10 04:16:23 +00001154 "Cannot create an aggregate zero of non-aggregate type!");
Chris Lattner69edc982006-09-28 00:35:06 +00001155 return AggZeroConstants->getOrCreate(Ty, 0);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001156}
1157
1158// destroyConstant - Remove the constant from the constant table...
1159//
1160void ConstantAggregateZero::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001161 AggZeroConstants->remove(this);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001162 destroyConstantImpl();
1163}
1164
Chris Lattner3462ae32001-12-03 22:26:30 +00001165//---- ConstantArray::get() implementation...
Chris Lattner49d855c2001-09-07 16:46:31 +00001166//
Chris Lattner189d19f2003-11-21 20:23:48 +00001167namespace llvm {
1168 template<>
1169 struct ConvertConstantType<ConstantArray, ArrayType> {
1170 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
1171 // Make everyone now use a constant of the new type...
1172 std::vector<Constant*> C;
1173 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1174 C.push_back(cast<Constant>(OldC->getOperand(i)));
1175 Constant *New = ConstantArray::get(NewTy, C);
1176 assert(New != OldC && "Didn't replace constant??");
1177 OldC->uncheckedReplaceAllUsesWith(New);
1178 OldC->destroyConstant(); // This constant is now dead, destroy it.
1179 }
1180 };
1181}
Chris Lattnerb50d1352003-10-05 00:17:43 +00001182
Chris Lattner3e650af2004-08-04 04:48:01 +00001183static std::vector<Constant*> getValType(ConstantArray *CA) {
1184 std::vector<Constant*> Elements;
1185 Elements.reserve(CA->getNumOperands());
1186 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1187 Elements.push_back(cast<Constant>(CA->getOperand(i)));
1188 return Elements;
1189}
1190
Chris Lattnerb64419a2005-10-03 22:51:37 +00001191typedef ValueMap<std::vector<Constant*>, ArrayType,
Chris Lattner935aa922005-10-04 17:48:46 +00001192 ConstantArray, true /*largekey*/> ArrayConstantsTy;
Chris Lattner69edc982006-09-28 00:35:06 +00001193static ManagedStatic<ArrayConstantsTy> ArrayConstants;
Chris Lattner49d855c2001-09-07 16:46:31 +00001194
Chris Lattner015e8212004-02-15 04:14:47 +00001195Constant *ConstantArray::get(const ArrayType *Ty,
Chris Lattner9fba3da2004-02-15 05:53:04 +00001196 const std::vector<Constant*> &V) {
1197 // If this is an all-zero array, return a ConstantAggregateZero object
1198 if (!V.empty()) {
1199 Constant *C = V[0];
1200 if (!C->isNullValue())
Chris Lattner69edc982006-09-28 00:35:06 +00001201 return ArrayConstants->getOrCreate(Ty, V);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001202 for (unsigned i = 1, e = V.size(); i != e; ++i)
1203 if (V[i] != C)
Chris Lattner69edc982006-09-28 00:35:06 +00001204 return ArrayConstants->getOrCreate(Ty, V);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001205 }
1206 return ConstantAggregateZero::get(Ty);
Chris Lattner49d855c2001-09-07 16:46:31 +00001207}
1208
Chris Lattner98fa07b2003-05-23 20:03:32 +00001209// destroyConstant - Remove the constant from the constant table...
1210//
1211void ConstantArray::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001212 ArrayConstants->remove(this);
Chris Lattner98fa07b2003-05-23 20:03:32 +00001213 destroyConstantImpl();
1214}
1215
Reid Spencer6f614532006-05-30 08:23:18 +00001216/// ConstantArray::get(const string&) - Return an array that is initialized to
1217/// contain the specified string. If length is zero then a null terminator is
1218/// added to the specified string so that it may be used in a natural way.
1219/// Otherwise, the length parameter specifies how much of the string to use
1220/// and it won't be null terminated.
1221///
Reid Spencer82ebaba2006-05-30 18:15:07 +00001222Constant *ConstantArray::get(const std::string &Str, bool AddNull) {
Chris Lattner7f74a562002-01-20 22:54:45 +00001223 std::vector<Constant*> ElementVals;
Reid Spencer82ebaba2006-05-30 18:15:07 +00001224 for (unsigned i = 0; i < Str.length(); ++i)
Reid Spencer8d9336d2006-12-31 05:26:44 +00001225 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, Str[i]));
Chris Lattner8f80fe02001-10-14 23:54:12 +00001226
1227 // Add a null terminator to the string...
Reid Spencer82ebaba2006-05-30 18:15:07 +00001228 if (AddNull) {
Reid Spencer8d9336d2006-12-31 05:26:44 +00001229 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, 0));
Reid Spencer6f614532006-05-30 08:23:18 +00001230 }
Chris Lattner8f80fe02001-10-14 23:54:12 +00001231
Reid Spencer8d9336d2006-12-31 05:26:44 +00001232 ArrayType *ATy = ArrayType::get(Type::Int8Ty, ElementVals.size());
Chris Lattner3462ae32001-12-03 22:26:30 +00001233 return ConstantArray::get(ATy, ElementVals);
Vikram S. Adve34410432001-10-14 23:17:20 +00001234}
1235
Reid Spencer2546b762007-01-26 07:37:34 +00001236/// isString - This method returns true if the array is an array of i8, and
1237/// if the elements of the array are all ConstantInt's.
Chris Lattnere8dfcca2004-01-14 17:06:38 +00001238bool ConstantArray::isString() const {
Reid Spencer2546b762007-01-26 07:37:34 +00001239 // Check the element type for i8...
Reid Spencer8d9336d2006-12-31 05:26:44 +00001240 if (getType()->getElementType() != Type::Int8Ty)
Chris Lattnere8dfcca2004-01-14 17:06:38 +00001241 return false;
1242 // Check the elements to make sure they are all integers, not constant
1243 // expressions.
1244 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1245 if (!isa<ConstantInt>(getOperand(i)))
1246 return false;
1247 return true;
1248}
1249
Evan Cheng3763c5b2006-10-26 19:15:05 +00001250/// isCString - This method returns true if the array is a string (see
1251/// isString) and it ends in a null byte \0 and does not contains any other
1252/// null bytes except its terminator.
1253bool ConstantArray::isCString() const {
Reid Spencer2546b762007-01-26 07:37:34 +00001254 // Check the element type for i8...
Reid Spencer8d9336d2006-12-31 05:26:44 +00001255 if (getType()->getElementType() != Type::Int8Ty)
Evan Chenge974da62006-10-26 21:48:03 +00001256 return false;
1257 Constant *Zero = Constant::getNullValue(getOperand(0)->getType());
1258 // Last element must be a null.
1259 if (getOperand(getNumOperands()-1) != Zero)
1260 return false;
1261 // Other elements must be non-null integers.
1262 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1263 if (!isa<ConstantInt>(getOperand(i)))
Evan Cheng3763c5b2006-10-26 19:15:05 +00001264 return false;
Evan Chenge974da62006-10-26 21:48:03 +00001265 if (getOperand(i) == Zero)
1266 return false;
1267 }
Evan Cheng3763c5b2006-10-26 19:15:05 +00001268 return true;
1269}
1270
1271
Reid Spencer2546b762007-01-26 07:37:34 +00001272// getAsString - If the sub-element type of this array is i8
Chris Lattner81fabb02002-08-26 17:53:56 +00001273// then this method converts the array to an std::string and returns it.
1274// Otherwise, it asserts out.
1275//
1276std::string ConstantArray::getAsString() const {
Chris Lattnere8dfcca2004-01-14 17:06:38 +00001277 assert(isString() && "Not a string!");
Chris Lattner81fabb02002-08-26 17:53:56 +00001278 std::string Result;
Chris Lattner6077c312003-07-23 15:22:26 +00001279 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
Reid Spencere0fc4df2006-10-20 07:07:24 +00001280 Result += (char)cast<ConstantInt>(getOperand(i))->getZExtValue();
Chris Lattner81fabb02002-08-26 17:53:56 +00001281 return Result;
1282}
1283
1284
Chris Lattner3462ae32001-12-03 22:26:30 +00001285//---- ConstantStruct::get() implementation...
Chris Lattner49d855c2001-09-07 16:46:31 +00001286//
Chris Lattnerb50d1352003-10-05 00:17:43 +00001287
Chris Lattner189d19f2003-11-21 20:23:48 +00001288namespace llvm {
1289 template<>
1290 struct ConvertConstantType<ConstantStruct, StructType> {
1291 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1292 // Make everyone now use a constant of the new type...
1293 std::vector<Constant*> C;
1294 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1295 C.push_back(cast<Constant>(OldC->getOperand(i)));
1296 Constant *New = ConstantStruct::get(NewTy, C);
1297 assert(New != OldC && "Didn't replace constant??");
Misha Brukmanb1c93172005-04-21 23:48:37 +00001298
Chris Lattner189d19f2003-11-21 20:23:48 +00001299 OldC->uncheckedReplaceAllUsesWith(New);
1300 OldC->destroyConstant(); // This constant is now dead, destroy it.
1301 }
1302 };
1303}
Chris Lattnerb50d1352003-10-05 00:17:43 +00001304
Chris Lattner8760ec72005-10-04 01:17:50 +00001305typedef ValueMap<std::vector<Constant*>, StructType,
Chris Lattner935aa922005-10-04 17:48:46 +00001306 ConstantStruct, true /*largekey*/> StructConstantsTy;
Chris Lattner69edc982006-09-28 00:35:06 +00001307static ManagedStatic<StructConstantsTy> StructConstants;
Chris Lattner49d855c2001-09-07 16:46:31 +00001308
Chris Lattner3e650af2004-08-04 04:48:01 +00001309static std::vector<Constant*> getValType(ConstantStruct *CS) {
1310 std::vector<Constant*> Elements;
1311 Elements.reserve(CS->getNumOperands());
1312 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1313 Elements.push_back(cast<Constant>(CS->getOperand(i)));
1314 return Elements;
1315}
1316
Chris Lattner015e8212004-02-15 04:14:47 +00001317Constant *ConstantStruct::get(const StructType *Ty,
1318 const std::vector<Constant*> &V) {
Chris Lattner9fba3da2004-02-15 05:53:04 +00001319 // Create a ConstantAggregateZero value if all elements are zeros...
1320 for (unsigned i = 0, e = V.size(); i != e; ++i)
1321 if (!V[i]->isNullValue())
Chris Lattner69edc982006-09-28 00:35:06 +00001322 return StructConstants->getOrCreate(Ty, V);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001323
1324 return ConstantAggregateZero::get(Ty);
Chris Lattner49d855c2001-09-07 16:46:31 +00001325}
Chris Lattner883ad0b2001-10-03 15:39:36 +00001326
Andrew Lenharthdcb3c972006-12-08 18:06:16 +00001327Constant *ConstantStruct::get(const std::vector<Constant*> &V, bool packed) {
Chris Lattnerd6108ca2004-07-12 20:35:11 +00001328 std::vector<const Type*> StructEls;
1329 StructEls.reserve(V.size());
1330 for (unsigned i = 0, e = V.size(); i != e; ++i)
1331 StructEls.push_back(V[i]->getType());
Andrew Lenharthdcb3c972006-12-08 18:06:16 +00001332 return get(StructType::get(StructEls, packed), V);
Chris Lattnerd6108ca2004-07-12 20:35:11 +00001333}
1334
Chris Lattnerd7a73302001-10-13 06:57:33 +00001335// destroyConstant - Remove the constant from the constant table...
Chris Lattner883ad0b2001-10-03 15:39:36 +00001336//
Chris Lattner3462ae32001-12-03 22:26:30 +00001337void ConstantStruct::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001338 StructConstants->remove(this);
Chris Lattnerd7a73302001-10-13 06:57:33 +00001339 destroyConstantImpl();
1340}
Chris Lattner883ad0b2001-10-03 15:39:36 +00001341
Reid Spencerd84d35b2007-02-15 02:26:10 +00001342//---- ConstantVector::get() implementation...
Brian Gaeke02209042004-08-20 06:00:58 +00001343//
1344namespace llvm {
1345 template<>
Reid Spencerd84d35b2007-02-15 02:26:10 +00001346 struct ConvertConstantType<ConstantVector, VectorType> {
1347 static void convert(ConstantVector *OldC, const VectorType *NewTy) {
Brian Gaeke02209042004-08-20 06:00:58 +00001348 // Make everyone now use a constant of the new type...
1349 std::vector<Constant*> C;
1350 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1351 C.push_back(cast<Constant>(OldC->getOperand(i)));
Reid Spencerd84d35b2007-02-15 02:26:10 +00001352 Constant *New = ConstantVector::get(NewTy, C);
Brian Gaeke02209042004-08-20 06:00:58 +00001353 assert(New != OldC && "Didn't replace constant??");
1354 OldC->uncheckedReplaceAllUsesWith(New);
1355 OldC->destroyConstant(); // This constant is now dead, destroy it.
1356 }
1357 };
1358}
1359
Reid Spencerd84d35b2007-02-15 02:26:10 +00001360static std::vector<Constant*> getValType(ConstantVector *CP) {
Brian Gaeke02209042004-08-20 06:00:58 +00001361 std::vector<Constant*> Elements;
1362 Elements.reserve(CP->getNumOperands());
1363 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1364 Elements.push_back(CP->getOperand(i));
1365 return Elements;
1366}
1367
Reid Spencerd84d35b2007-02-15 02:26:10 +00001368static ManagedStatic<ValueMap<std::vector<Constant*>, VectorType,
Reid Spencer09575ba2007-02-15 03:39:18 +00001369 ConstantVector> > VectorConstants;
Brian Gaeke02209042004-08-20 06:00:58 +00001370
Reid Spencerd84d35b2007-02-15 02:26:10 +00001371Constant *ConstantVector::get(const VectorType *Ty,
Brian Gaeke02209042004-08-20 06:00:58 +00001372 const std::vector<Constant*> &V) {
Dan Gohman30978072007-05-24 14:36:04 +00001373 // If this is an all-zero vector, return a ConstantAggregateZero object
Brian Gaeke02209042004-08-20 06:00:58 +00001374 if (!V.empty()) {
1375 Constant *C = V[0];
1376 if (!C->isNullValue())
Reid Spencer09575ba2007-02-15 03:39:18 +00001377 return VectorConstants->getOrCreate(Ty, V);
Brian Gaeke02209042004-08-20 06:00:58 +00001378 for (unsigned i = 1, e = V.size(); i != e; ++i)
1379 if (V[i] != C)
Reid Spencer09575ba2007-02-15 03:39:18 +00001380 return VectorConstants->getOrCreate(Ty, V);
Brian Gaeke02209042004-08-20 06:00:58 +00001381 }
1382 return ConstantAggregateZero::get(Ty);
1383}
1384
Reid Spencerd84d35b2007-02-15 02:26:10 +00001385Constant *ConstantVector::get(const std::vector<Constant*> &V) {
Brian Gaeke02209042004-08-20 06:00:58 +00001386 assert(!V.empty() && "Cannot infer type if V is empty");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001387 return get(VectorType::get(V.front()->getType(),V.size()), V);
Brian Gaeke02209042004-08-20 06:00:58 +00001388}
1389
1390// destroyConstant - Remove the constant from the constant table...
1391//
Reid Spencerd84d35b2007-02-15 02:26:10 +00001392void ConstantVector::destroyConstant() {
Reid Spencer09575ba2007-02-15 03:39:18 +00001393 VectorConstants->remove(this);
Brian Gaeke02209042004-08-20 06:00:58 +00001394 destroyConstantImpl();
1395}
1396
Dan Gohman30978072007-05-24 14:36:04 +00001397/// This function will return true iff every element in this vector constant
Jim Laskeyf0478822007-01-12 22:39:14 +00001398/// is set to all ones.
1399/// @returns true iff this constant's emements are all set to all ones.
1400/// @brief Determine if the value is all ones.
Reid Spencerd84d35b2007-02-15 02:26:10 +00001401bool ConstantVector::isAllOnesValue() const {
Jim Laskeyf0478822007-01-12 22:39:14 +00001402 // Check out first element.
1403 const Constant *Elt = getOperand(0);
1404 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1405 if (!CI || !CI->isAllOnesValue()) return false;
1406 // Then make sure all remaining elements point to the same value.
1407 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1408 if (getOperand(I) != Elt) return false;
1409 }
1410 return true;
1411}
1412
Dan Gohman07159202007-10-17 17:51:30 +00001413/// getSplatValue - If this is a splat constant, where all of the
1414/// elements have the same value, return that value. Otherwise return null.
1415Constant *ConstantVector::getSplatValue() {
1416 // Check out first element.
1417 Constant *Elt = getOperand(0);
1418 // Then make sure all remaining elements point to the same value.
1419 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1420 if (getOperand(I) != Elt) return 0;
1421 return Elt;
1422}
1423
Chris Lattner3462ae32001-12-03 22:26:30 +00001424//---- ConstantPointerNull::get() implementation...
Chris Lattnerd7a73302001-10-13 06:57:33 +00001425//
Chris Lattner98fa07b2003-05-23 20:03:32 +00001426
Chris Lattner189d19f2003-11-21 20:23:48 +00001427namespace llvm {
1428 // ConstantPointerNull does not take extra "value" argument...
1429 template<class ValType>
1430 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1431 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1432 return new ConstantPointerNull(Ty);
1433 }
1434 };
Chris Lattner98fa07b2003-05-23 20:03:32 +00001435
Chris Lattner189d19f2003-11-21 20:23:48 +00001436 template<>
1437 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1438 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1439 // Make everyone now use a constant of the new type...
1440 Constant *New = ConstantPointerNull::get(NewTy);
1441 assert(New != OldC && "Didn't replace constant??");
1442 OldC->uncheckedReplaceAllUsesWith(New);
1443 OldC->destroyConstant(); // This constant is now dead, destroy it.
1444 }
1445 };
1446}
Chris Lattnerb50d1352003-10-05 00:17:43 +00001447
Chris Lattner69edc982006-09-28 00:35:06 +00001448static ManagedStatic<ValueMap<char, PointerType,
1449 ConstantPointerNull> > NullPtrConstants;
Chris Lattnerd7a73302001-10-13 06:57:33 +00001450
Chris Lattner3e650af2004-08-04 04:48:01 +00001451static char getValType(ConstantPointerNull *) {
1452 return 0;
1453}
1454
1455
Chris Lattner3462ae32001-12-03 22:26:30 +00001456ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
Chris Lattner69edc982006-09-28 00:35:06 +00001457 return NullPtrConstants->getOrCreate(Ty, 0);
Chris Lattner883ad0b2001-10-03 15:39:36 +00001458}
1459
Chris Lattner0c6e0b92002-08-18 00:40:04 +00001460// destroyConstant - Remove the constant from the constant table...
1461//
1462void ConstantPointerNull::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001463 NullPtrConstants->remove(this);
Chris Lattner0c6e0b92002-08-18 00:40:04 +00001464 destroyConstantImpl();
1465}
1466
1467
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001468//---- UndefValue::get() implementation...
1469//
1470
1471namespace llvm {
1472 // UndefValue does not take extra "value" argument...
1473 template<class ValType>
1474 struct ConstantCreator<UndefValue, Type, ValType> {
1475 static UndefValue *create(const Type *Ty, const ValType &V) {
1476 return new UndefValue(Ty);
1477 }
1478 };
1479
1480 template<>
1481 struct ConvertConstantType<UndefValue, Type> {
1482 static void convert(UndefValue *OldC, const Type *NewTy) {
1483 // Make everyone now use a constant of the new type.
1484 Constant *New = UndefValue::get(NewTy);
1485 assert(New != OldC && "Didn't replace constant??");
1486 OldC->uncheckedReplaceAllUsesWith(New);
1487 OldC->destroyConstant(); // This constant is now dead, destroy it.
1488 }
1489 };
1490}
1491
Chris Lattner69edc982006-09-28 00:35:06 +00001492static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001493
1494static char getValType(UndefValue *) {
1495 return 0;
1496}
1497
1498
1499UndefValue *UndefValue::get(const Type *Ty) {
Chris Lattner69edc982006-09-28 00:35:06 +00001500 return UndefValueConstants->getOrCreate(Ty, 0);
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001501}
1502
1503// destroyConstant - Remove the constant from the constant table.
1504//
1505void UndefValue::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001506 UndefValueConstants->remove(this);
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001507 destroyConstantImpl();
1508}
1509
1510
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001511//---- ConstantExpr::get() implementations...
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001512//
Reid Spencer8d9336d2006-12-31 05:26:44 +00001513
Reid Spenceree3c9912006-12-04 05:19:50 +00001514struct ExprMapKeyType {
1515 explicit ExprMapKeyType(unsigned opc, std::vector<Constant*> ops,
Reid Spencerdba6aa42006-12-04 18:38:05 +00001516 unsigned short pred = 0) : opcode(opc), predicate(pred), operands(ops) { }
1517 uint16_t opcode;
1518 uint16_t predicate;
Reid Spenceree3c9912006-12-04 05:19:50 +00001519 std::vector<Constant*> operands;
Reid Spenceree3c9912006-12-04 05:19:50 +00001520 bool operator==(const ExprMapKeyType& that) const {
1521 return this->opcode == that.opcode &&
1522 this->predicate == that.predicate &&
1523 this->operands == that.operands;
1524 }
1525 bool operator<(const ExprMapKeyType & that) const {
1526 return this->opcode < that.opcode ||
1527 (this->opcode == that.opcode && this->predicate < that.predicate) ||
1528 (this->opcode == that.opcode && this->predicate == that.predicate &&
1529 this->operands < that.operands);
1530 }
1531
1532 bool operator!=(const ExprMapKeyType& that) const {
1533 return !(*this == that);
1534 }
1535};
Chris Lattner98fa07b2003-05-23 20:03:32 +00001536
Chris Lattner189d19f2003-11-21 20:23:48 +00001537namespace llvm {
1538 template<>
1539 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
Reid Spencer10fbf0e2006-12-03 05:48:19 +00001540 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1541 unsigned short pred = 0) {
Reid Spenceree3c9912006-12-04 05:19:50 +00001542 if (Instruction::isCast(V.opcode))
1543 return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1544 if ((V.opcode >= Instruction::BinaryOpsBegin &&
Reid Spencer2341c222007-02-02 02:16:23 +00001545 V.opcode < Instruction::BinaryOpsEnd))
Reid Spenceree3c9912006-12-04 05:19:50 +00001546 return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1547 if (V.opcode == Instruction::Select)
1548 return new SelectConstantExpr(V.operands[0], V.operands[1],
1549 V.operands[2]);
1550 if (V.opcode == Instruction::ExtractElement)
1551 return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1552 if (V.opcode == Instruction::InsertElement)
1553 return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1554 V.operands[2]);
1555 if (V.opcode == Instruction::ShuffleVector)
1556 return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1557 V.operands[2]);
1558 if (V.opcode == Instruction::GetElementPtr) {
1559 std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
Gabor Greife9ecc682008-04-06 20:25:17 +00001560 return GetElementPtrConstantExpr::Create(V.operands[0], IdxList, Ty);
Reid Spenceree3c9912006-12-04 05:19:50 +00001561 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001562
Reid Spenceree3c9912006-12-04 05:19:50 +00001563 // The compare instructions are weird. We have to encode the predicate
1564 // value and it is combined with the instruction opcode by multiplying
1565 // the opcode by one hundred. We must decode this to get the predicate.
1566 if (V.opcode == Instruction::ICmp)
1567 return new CompareConstantExpr(Instruction::ICmp, V.predicate,
1568 V.operands[0], V.operands[1]);
1569 if (V.opcode == Instruction::FCmp)
1570 return new CompareConstantExpr(Instruction::FCmp, V.predicate,
1571 V.operands[0], V.operands[1]);
1572 assert(0 && "Invalid ConstantExpr!");
Jeff Cohen9f469632006-12-15 21:47:01 +00001573 return 0;
Chris Lattnerb50d1352003-10-05 00:17:43 +00001574 }
Chris Lattner189d19f2003-11-21 20:23:48 +00001575 };
Chris Lattnerb50d1352003-10-05 00:17:43 +00001576
Chris Lattner189d19f2003-11-21 20:23:48 +00001577 template<>
1578 struct ConvertConstantType<ConstantExpr, Type> {
1579 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1580 Constant *New;
1581 switch (OldC->getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001582 case Instruction::Trunc:
1583 case Instruction::ZExt:
1584 case Instruction::SExt:
1585 case Instruction::FPTrunc:
1586 case Instruction::FPExt:
1587 case Instruction::UIToFP:
1588 case Instruction::SIToFP:
1589 case Instruction::FPToUI:
1590 case Instruction::FPToSI:
1591 case Instruction::PtrToInt:
1592 case Instruction::IntToPtr:
1593 case Instruction::BitCast:
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001594 New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0),
1595 NewTy);
Chris Lattner189d19f2003-11-21 20:23:48 +00001596 break;
Chris Lattner6e415c02004-03-12 05:54:04 +00001597 case Instruction::Select:
1598 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1599 OldC->getOperand(1),
1600 OldC->getOperand(2));
1601 break;
Chris Lattner189d19f2003-11-21 20:23:48 +00001602 default:
1603 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
Reid Spencer7eb55b32006-11-02 01:53:59 +00001604 OldC->getOpcode() < Instruction::BinaryOpsEnd);
Chris Lattner189d19f2003-11-21 20:23:48 +00001605 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1606 OldC->getOperand(1));
1607 break;
1608 case Instruction::GetElementPtr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00001609 // Make everyone now use a constant of the new type...
Chris Lattner13128ab2004-10-11 22:52:25 +00001610 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
Chris Lattner302116a2007-01-31 04:40:28 +00001611 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0),
1612 &Idx[0], Idx.size());
Chris Lattner189d19f2003-11-21 20:23:48 +00001613 break;
1614 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001615
Chris Lattner189d19f2003-11-21 20:23:48 +00001616 assert(New != OldC && "Didn't replace constant??");
1617 OldC->uncheckedReplaceAllUsesWith(New);
1618 OldC->destroyConstant(); // This constant is now dead, destroy it.
1619 }
1620 };
1621} // end namespace llvm
Chris Lattnerb50d1352003-10-05 00:17:43 +00001622
1623
Chris Lattner3e650af2004-08-04 04:48:01 +00001624static ExprMapKeyType getValType(ConstantExpr *CE) {
1625 std::vector<Constant*> Operands;
1626 Operands.reserve(CE->getNumOperands());
1627 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1628 Operands.push_back(cast<Constant>(CE->getOperand(i)));
Reid Spenceree3c9912006-12-04 05:19:50 +00001629 return ExprMapKeyType(CE->getOpcode(), Operands,
1630 CE->isCompare() ? CE->getPredicate() : 0);
Chris Lattner3e650af2004-08-04 04:48:01 +00001631}
1632
Chris Lattner69edc982006-09-28 00:35:06 +00001633static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1634 ConstantExpr> > ExprConstants;
Vikram S. Adve4c485332002-07-15 18:19:33 +00001635
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001636/// This is a utility function to handle folding of casts and lookup of the
Duncan Sands7d6c8ae2008-03-30 19:38:55 +00001637/// cast in the ExprConstants map. It is used by the various get* methods below.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001638static inline Constant *getFoldedCast(
1639 Instruction::CastOps opc, Constant *C, const Type *Ty) {
Chris Lattner815ae2b2003-10-07 22:19:19 +00001640 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001641 // Fold a few common cases
1642 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1643 return FC;
Chris Lattneracdbe712003-04-17 19:24:48 +00001644
Vikram S. Adve4c485332002-07-15 18:19:33 +00001645 // Look up the constant in the table first to ensure uniqueness
Chris Lattner2b383d2e2003-05-13 21:37:02 +00001646 std::vector<Constant*> argVec(1, C);
Reid Spenceree3c9912006-12-04 05:19:50 +00001647 ExprMapKeyType Key(opc, argVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001648 return ExprConstants->getOrCreate(Ty, Key);
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001649}
Reid Spencerf37dc652006-12-05 19:14:13 +00001650
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001651Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1652 Instruction::CastOps opc = Instruction::CastOps(oc);
1653 assert(Instruction::isCast(opc) && "opcode out of range");
1654 assert(C && Ty && "Null arguments to getCast");
1655 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1656
1657 switch (opc) {
1658 default:
1659 assert(0 && "Invalid cast opcode");
1660 break;
1661 case Instruction::Trunc: return getTrunc(C, Ty);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001662 case Instruction::ZExt: return getZExt(C, Ty);
1663 case Instruction::SExt: return getSExt(C, Ty);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001664 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1665 case Instruction::FPExt: return getFPExtend(C, Ty);
1666 case Instruction::UIToFP: return getUIToFP(C, Ty);
1667 case Instruction::SIToFP: return getSIToFP(C, Ty);
1668 case Instruction::FPToUI: return getFPToUI(C, Ty);
1669 case Instruction::FPToSI: return getFPToSI(C, Ty);
1670 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1671 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1672 case Instruction::BitCast: return getBitCast(C, Ty);
Chris Lattner1ece6f82005-01-01 15:59:57 +00001673 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001674 return 0;
Reid Spencerf37dc652006-12-05 19:14:13 +00001675}
1676
Reid Spencer5c140882006-12-04 20:17:56 +00001677Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1678 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1679 return getCast(Instruction::BitCast, C, Ty);
1680 return getCast(Instruction::ZExt, C, Ty);
1681}
1682
1683Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1684 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1685 return getCast(Instruction::BitCast, C, Ty);
1686 return getCast(Instruction::SExt, C, Ty);
1687}
1688
1689Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1690 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1691 return getCast(Instruction::BitCast, C, Ty);
1692 return getCast(Instruction::Trunc, C, Ty);
1693}
1694
Reid Spencerbc245a02006-12-05 03:25:26 +00001695Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1696 assert(isa<PointerType>(S->getType()) && "Invalid cast");
Chris Lattner03c49532007-01-15 02:27:26 +00001697 assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
Reid Spencerbc245a02006-12-05 03:25:26 +00001698
Chris Lattner03c49532007-01-15 02:27:26 +00001699 if (Ty->isInteger())
Reid Spencerbc245a02006-12-05 03:25:26 +00001700 return getCast(Instruction::PtrToInt, S, Ty);
1701 return getCast(Instruction::BitCast, S, Ty);
1702}
1703
Reid Spencer56521c42006-12-12 00:51:07 +00001704Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
1705 bool isSigned) {
Chris Lattner03c49532007-01-15 02:27:26 +00001706 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
Reid Spencer56521c42006-12-12 00:51:07 +00001707 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1708 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1709 Instruction::CastOps opcode =
1710 (SrcBits == DstBits ? Instruction::BitCast :
1711 (SrcBits > DstBits ? Instruction::Trunc :
1712 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1713 return getCast(opcode, C, Ty);
1714}
1715
1716Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1717 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1718 "Invalid cast");
1719 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1720 unsigned DstBits = Ty->getPrimitiveSizeInBits();
Reid Spencerca104e82006-12-12 05:38:50 +00001721 if (SrcBits == DstBits)
1722 return C; // Avoid a useless cast
Reid Spencer56521c42006-12-12 00:51:07 +00001723 Instruction::CastOps opcode =
Reid Spencerca104e82006-12-12 05:38:50 +00001724 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
Reid Spencer56521c42006-12-12 00:51:07 +00001725 return getCast(opcode, C, Ty);
1726}
1727
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001728Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
Chris Lattner03c49532007-01-15 02:27:26 +00001729 assert(C->getType()->isInteger() && "Trunc operand must be integer");
1730 assert(Ty->isInteger() && "Trunc produces only integral");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001731 assert(C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1732 "SrcTy must be larger than DestTy for Trunc!");
1733
1734 return getFoldedCast(Instruction::Trunc, C, Ty);
1735}
1736
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001737Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
Chris Lattner03c49532007-01-15 02:27:26 +00001738 assert(C->getType()->isInteger() && "SEXt operand must be integral");
1739 assert(Ty->isInteger() && "SExt produces only integer");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001740 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1741 "SrcTy must be smaller than DestTy for SExt!");
1742
1743 return getFoldedCast(Instruction::SExt, C, Ty);
Chris Lattnerdd284742004-04-04 23:20:30 +00001744}
1745
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001746Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
Chris Lattner03c49532007-01-15 02:27:26 +00001747 assert(C->getType()->isInteger() && "ZEXt operand must be integral");
1748 assert(Ty->isInteger() && "ZExt produces only integer");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001749 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1750 "SrcTy must be smaller than DestTy for ZExt!");
1751
1752 return getFoldedCast(Instruction::ZExt, C, Ty);
1753}
1754
1755Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1756 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1757 C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1758 "This is an illegal floating point truncation!");
1759 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1760}
1761
1762Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1763 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1764 C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1765 "This is an illegal floating point extension!");
1766 return getFoldedCast(Instruction::FPExt, C, Ty);
1767}
1768
1769Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
Nate Begemand4d45c22007-11-17 03:58:34 +00001770 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1771 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1772 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1773 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1774 "This is an illegal uint to floating point cast!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001775 return getFoldedCast(Instruction::UIToFP, C, Ty);
1776}
1777
1778Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
Nate Begemand4d45c22007-11-17 03:58:34 +00001779 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1780 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1781 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1782 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001783 "This is an illegal sint to floating point cast!");
1784 return getFoldedCast(Instruction::SIToFP, C, Ty);
1785}
1786
1787Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
Nate Begemand4d45c22007-11-17 03:58:34 +00001788 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1789 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1790 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1791 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1792 "This is an illegal floating point to uint cast!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001793 return getFoldedCast(Instruction::FPToUI, C, Ty);
1794}
1795
1796Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
Nate Begemand4d45c22007-11-17 03:58:34 +00001797 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1798 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1799 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1800 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1801 "This is an illegal floating point to sint cast!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001802 return getFoldedCast(Instruction::FPToSI, C, Ty);
1803}
1804
1805Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1806 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
Chris Lattner03c49532007-01-15 02:27:26 +00001807 assert(DstTy->isInteger() && "PtrToInt destination must be integral");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001808 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1809}
1810
1811Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
Chris Lattner03c49532007-01-15 02:27:26 +00001812 assert(C->getType()->isInteger() && "IntToPtr source must be integral");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001813 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
1814 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1815}
1816
1817Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1818 // BitCast implies a no-op cast of type only. No bits change. However, you
1819 // can't cast pointers to anything but pointers.
1820 const Type *SrcTy = C->getType();
1821 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
Reid Spencer5c140882006-12-04 20:17:56 +00001822 "BitCast cannot cast pointer to non-pointer and vice versa");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001823
1824 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
1825 // or nonptr->ptr). For all the other types, the cast is okay if source and
1826 // destination bit widths are identical.
1827 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1828 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
Reid Spencer5c140882006-12-04 20:17:56 +00001829 assert(SrcBitSize == DstBitSize && "BitCast requies types of same width");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001830 return getFoldedCast(Instruction::BitCast, C, DstTy);
Chris Lattnerdd284742004-04-04 23:20:30 +00001831}
1832
Alkis Evlogimenosda5de052004-10-24 01:41:10 +00001833Constant *ConstantExpr::getSizeOf(const Type *Ty) {
Gordon Henriksen7ce31762007-10-06 14:29:36 +00001834 // sizeof is implemented as: (i64) gep (Ty*)null, 1
Chris Lattnerb5d70302007-02-19 20:01:23 +00001835 Constant *GEPIdx = ConstantInt::get(Type::Int32Ty, 1);
1836 Constant *GEP =
Christopher Lambedf07882007-12-17 01:12:55 +00001837 getGetElementPtr(getNullValue(PointerType::getUnqual(Ty)), &GEPIdx, 1);
Chris Lattnerb5d70302007-02-19 20:01:23 +00001838 return getCast(Instruction::PtrToInt, GEP, Type::Int64Ty);
Alkis Evlogimenos9160d5f2005-03-19 11:40:31 +00001839}
1840
Chris Lattnerb50d1352003-10-05 00:17:43 +00001841Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
Reid Spencera009d0d2006-12-04 21:35:24 +00001842 Constant *C1, Constant *C2) {
Chris Lattner38a9bcd2003-05-21 17:49:25 +00001843 // Check the operands for consistency first
Reid Spencer7eb55b32006-11-02 01:53:59 +00001844 assert(Opcode >= Instruction::BinaryOpsBegin &&
1845 Opcode < Instruction::BinaryOpsEnd &&
Chris Lattner38a9bcd2003-05-21 17:49:25 +00001846 "Invalid opcode in binary constant expression");
1847 assert(C1->getType() == C2->getType() &&
1848 "Operand types in binary constant expression should match");
Chris Lattnerb50d1352003-10-05 00:17:43 +00001849
Reid Spencer542964f2007-01-11 18:21:29 +00001850 if (ReqTy == C1->getType() || ReqTy == Type::Int1Ty)
Chris Lattnerb50d1352003-10-05 00:17:43 +00001851 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1852 return FC; // Fold a few common cases...
Chris Lattneracdbe712003-04-17 19:24:48 +00001853
Chris Lattner2b383d2e2003-05-13 21:37:02 +00001854 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
Reid Spencera009d0d2006-12-04 21:35:24 +00001855 ExprMapKeyType Key(Opcode, argVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001856 return ExprConstants->getOrCreate(ReqTy, Key);
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001857}
1858
Reid Spencer266e42b2006-12-23 06:05:41 +00001859Constant *ConstantExpr::getCompareTy(unsigned short predicate,
Reid Spencera009d0d2006-12-04 21:35:24 +00001860 Constant *C1, Constant *C2) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001861 switch (predicate) {
1862 default: assert(0 && "Invalid CmpInst predicate");
1863 case FCmpInst::FCMP_FALSE: case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_OGT:
1864 case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OLE:
1865 case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_ORD: case FCmpInst::FCMP_UNO:
1866 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UGT: case FCmpInst::FCMP_UGE:
1867 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_ULE: case FCmpInst::FCMP_UNE:
1868 case FCmpInst::FCMP_TRUE:
1869 return getFCmp(predicate, C1, C2);
1870 case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGT:
1871 case ICmpInst::ICMP_UGE: case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE:
1872 case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_SGE: case ICmpInst::ICMP_SLT:
1873 case ICmpInst::ICMP_SLE:
1874 return getICmp(predicate, C1, C2);
1875 }
Reid Spencera009d0d2006-12-04 21:35:24 +00001876}
1877
1878Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001879#ifndef NDEBUG
1880 switch (Opcode) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00001881 case Instruction::Add:
1882 case Instruction::Sub:
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001883 case Instruction::Mul:
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001884 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Chris Lattner03c49532007-01-15 02:27:26 +00001885 assert((C1->getType()->isInteger() || C1->getType()->isFloatingPoint() ||
Reid Spencerd84d35b2007-02-15 02:26:10 +00001886 isa<VectorType>(C1->getType())) &&
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001887 "Tried to create an arithmetic operation on a non-arithmetic type!");
1888 break;
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001889 case Instruction::UDiv:
1890 case Instruction::SDiv:
1891 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001892 assert((C1->getType()->isInteger() || (isa<VectorType>(C1->getType()) &&
1893 cast<VectorType>(C1->getType())->getElementType()->isInteger())) &&
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001894 "Tried to create an arithmetic operation on a non-arithmetic type!");
1895 break;
1896 case Instruction::FDiv:
1897 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001898 assert((C1->getType()->isFloatingPoint() || (isa<VectorType>(C1->getType())
1899 && cast<VectorType>(C1->getType())->getElementType()->isFloatingPoint()))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001900 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1901 break;
Reid Spencer7eb55b32006-11-02 01:53:59 +00001902 case Instruction::URem:
1903 case Instruction::SRem:
1904 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001905 assert((C1->getType()->isInteger() || (isa<VectorType>(C1->getType()) &&
1906 cast<VectorType>(C1->getType())->getElementType()->isInteger())) &&
Reid Spencer7eb55b32006-11-02 01:53:59 +00001907 "Tried to create an arithmetic operation on a non-arithmetic type!");
1908 break;
1909 case Instruction::FRem:
1910 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001911 assert((C1->getType()->isFloatingPoint() || (isa<VectorType>(C1->getType())
1912 && cast<VectorType>(C1->getType())->getElementType()->isFloatingPoint()))
Reid Spencer7eb55b32006-11-02 01:53:59 +00001913 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1914 break;
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001915 case Instruction::And:
1916 case Instruction::Or:
1917 case Instruction::Xor:
1918 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001919 assert((C1->getType()->isInteger() || isa<VectorType>(C1->getType())) &&
Misha Brukman3852f652005-01-27 06:46:38 +00001920 "Tried to create a logical operation on a non-integral type!");
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001921 break;
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001922 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00001923 case Instruction::LShr:
1924 case Instruction::AShr:
Reid Spencer2341c222007-02-02 02:16:23 +00001925 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Chris Lattner03c49532007-01-15 02:27:26 +00001926 assert(C1->getType()->isInteger() &&
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001927 "Tried to create a shift operation on a non-integer type!");
1928 break;
1929 default:
1930 break;
1931 }
1932#endif
1933
Reid Spencera009d0d2006-12-04 21:35:24 +00001934 return getTy(C1->getType(), Opcode, C1, C2);
1935}
1936
Reid Spencer266e42b2006-12-23 06:05:41 +00001937Constant *ConstantExpr::getCompare(unsigned short pred,
Reid Spencera009d0d2006-12-04 21:35:24 +00001938 Constant *C1, Constant *C2) {
1939 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencer266e42b2006-12-23 06:05:41 +00001940 return getCompareTy(pred, C1, C2);
Chris Lattner29ca2c62004-08-04 18:50:09 +00001941}
1942
Chris Lattner6e415c02004-03-12 05:54:04 +00001943Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1944 Constant *V1, Constant *V2) {
Reid Spencer2546b762007-01-26 07:37:34 +00001945 assert(C->getType() == Type::Int1Ty && "Select condition must be i1!");
Chris Lattner6e415c02004-03-12 05:54:04 +00001946 assert(V1->getType() == V2->getType() && "Select value types must match!");
1947 assert(V1->getType()->isFirstClassType() && "Cannot select aggregate type!");
1948
1949 if (ReqTy == V1->getType())
1950 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1951 return SC; // Fold common cases
1952
1953 std::vector<Constant*> argVec(3, C);
1954 argVec[1] = V1;
1955 argVec[2] = V2;
Reid Spenceree3c9912006-12-04 05:19:50 +00001956 ExprMapKeyType Key(Instruction::Select, argVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001957 return ExprConstants->getOrCreate(ReqTy, Key);
Chris Lattner6e415c02004-03-12 05:54:04 +00001958}
1959
Chris Lattnerb50d1352003-10-05 00:17:43 +00001960Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
Chris Lattner302116a2007-01-31 04:40:28 +00001961 Value* const *Idxs,
1962 unsigned NumIdx) {
David Greenec656cbb2007-09-04 15:46:09 +00001963 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx, true) &&
Chris Lattner04b60fe2004-02-16 20:46:13 +00001964 "GEP indices invalid!");
1965
Chris Lattner302116a2007-01-31 04:40:28 +00001966 if (Constant *FC = ConstantFoldGetElementPtr(C, (Constant**)Idxs, NumIdx))
Chris Lattneracdbe712003-04-17 19:24:48 +00001967 return FC; // Fold a few common cases...
Chris Lattner04b60fe2004-02-16 20:46:13 +00001968
Chris Lattnerb50d1352003-10-05 00:17:43 +00001969 assert(isa<PointerType>(C->getType()) &&
Chris Lattner98fa07b2003-05-23 20:03:32 +00001970 "Non-pointer type for constant GetElementPtr expression");
Vikram S. Adve4c485332002-07-15 18:19:33 +00001971 // Look up the constant in the table first to ensure uniqueness
Chris Lattner13128ab2004-10-11 22:52:25 +00001972 std::vector<Constant*> ArgVec;
Chris Lattner302116a2007-01-31 04:40:28 +00001973 ArgVec.reserve(NumIdx+1);
Chris Lattner13128ab2004-10-11 22:52:25 +00001974 ArgVec.push_back(C);
Chris Lattner302116a2007-01-31 04:40:28 +00001975 for (unsigned i = 0; i != NumIdx; ++i)
1976 ArgVec.push_back(cast<Constant>(Idxs[i]));
1977 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001978 return ExprConstants->getOrCreate(ReqTy, Key);
Vikram S. Adve4c485332002-07-15 18:19:33 +00001979}
1980
Chris Lattner302116a2007-01-31 04:40:28 +00001981Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
1982 unsigned NumIdx) {
Chris Lattnerb50d1352003-10-05 00:17:43 +00001983 // Get the result type of the getelementptr!
Chris Lattner302116a2007-01-31 04:40:28 +00001984 const Type *Ty =
David Greenec656cbb2007-09-04 15:46:09 +00001985 GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx, true);
Chris Lattnerb50d1352003-10-05 00:17:43 +00001986 assert(Ty && "GEP indices invalid!");
Christopher Lamb54dd24c2007-12-11 08:59:05 +00001987 unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
1988 return getGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx);
Chris Lattner13128ab2004-10-11 22:52:25 +00001989}
1990
Chris Lattner302116a2007-01-31 04:40:28 +00001991Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
1992 unsigned NumIdx) {
1993 return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
Chris Lattnerb50d1352003-10-05 00:17:43 +00001994}
1995
Chris Lattner302116a2007-01-31 04:40:28 +00001996
Reid Spenceree3c9912006-12-04 05:19:50 +00001997Constant *
1998ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1999 assert(LHS->getType() == RHS->getType());
2000 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
2001 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
2002
Reid Spencer266e42b2006-12-23 06:05:41 +00002003 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
Reid Spenceree3c9912006-12-04 05:19:50 +00002004 return FC; // Fold a few common cases...
2005
2006 // Look up the constant in the table first to ensure uniqueness
2007 std::vector<Constant*> ArgVec;
2008 ArgVec.push_back(LHS);
2009 ArgVec.push_back(RHS);
Reid Spencerb1537492006-12-24 18:42:29 +00002010 // Get the key type with both the opcode and predicate
Reid Spenceree3c9912006-12-04 05:19:50 +00002011 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
Reid Spencer542964f2007-01-11 18:21:29 +00002012 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
Reid Spenceree3c9912006-12-04 05:19:50 +00002013}
2014
2015Constant *
2016ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2017 assert(LHS->getType() == RHS->getType());
2018 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
2019
Reid Spencer266e42b2006-12-23 06:05:41 +00002020 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
Reid Spenceree3c9912006-12-04 05:19:50 +00002021 return FC; // Fold a few common cases...
2022
2023 // Look up the constant in the table first to ensure uniqueness
2024 std::vector<Constant*> ArgVec;
2025 ArgVec.push_back(LHS);
2026 ArgVec.push_back(RHS);
Reid Spencerb1537492006-12-24 18:42:29 +00002027 // Get the key type with both the opcode and predicate
Reid Spenceree3c9912006-12-04 05:19:50 +00002028 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
Reid Spencer542964f2007-01-11 18:21:29 +00002029 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
Reid Spenceree3c9912006-12-04 05:19:50 +00002030}
2031
Robert Bocchino23004482006-01-10 19:05:34 +00002032Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
2033 Constant *Idx) {
Robert Bocchinode7f1c92006-01-10 20:03:46 +00002034 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
2035 return FC; // Fold a few common cases...
Robert Bocchino23004482006-01-10 19:05:34 +00002036 // Look up the constant in the table first to ensure uniqueness
2037 std::vector<Constant*> ArgVec(1, Val);
2038 ArgVec.push_back(Idx);
Reid Spenceree3c9912006-12-04 05:19:50 +00002039 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
Chris Lattner69edc982006-09-28 00:35:06 +00002040 return ExprConstants->getOrCreate(ReqTy, Key);
Robert Bocchino23004482006-01-10 19:05:34 +00002041}
2042
2043Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00002044 assert(isa<VectorType>(Val->getType()) &&
Reid Spencer09575ba2007-02-15 03:39:18 +00002045 "Tried to create extractelement operation on non-vector type!");
Reid Spencer8d9336d2006-12-31 05:26:44 +00002046 assert(Idx->getType() == Type::Int32Ty &&
Reid Spencer2546b762007-01-26 07:37:34 +00002047 "Extractelement index must be i32 type!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00002048 return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
Robert Bocchino23004482006-01-10 19:05:34 +00002049 Val, Idx);
2050}
Chris Lattnerb50d1352003-10-05 00:17:43 +00002051
Robert Bocchinoca27f032006-01-17 20:07:22 +00002052Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
2053 Constant *Elt, Constant *Idx) {
2054 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
2055 return FC; // Fold a few common cases...
2056 // Look up the constant in the table first to ensure uniqueness
2057 std::vector<Constant*> ArgVec(1, Val);
2058 ArgVec.push_back(Elt);
2059 ArgVec.push_back(Idx);
Reid Spenceree3c9912006-12-04 05:19:50 +00002060 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
Chris Lattner69edc982006-09-28 00:35:06 +00002061 return ExprConstants->getOrCreate(ReqTy, Key);
Robert Bocchinoca27f032006-01-17 20:07:22 +00002062}
2063
2064Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
2065 Constant *Idx) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00002066 assert(isa<VectorType>(Val->getType()) &&
Reid Spencer09575ba2007-02-15 03:39:18 +00002067 "Tried to create insertelement operation on non-vector type!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00002068 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
Robert Bocchinoca27f032006-01-17 20:07:22 +00002069 && "Insertelement types must match!");
Reid Spencer8d9336d2006-12-31 05:26:44 +00002070 assert(Idx->getType() == Type::Int32Ty &&
Reid Spencer2546b762007-01-26 07:37:34 +00002071 "Insertelement index must be i32 type!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00002072 return getInsertElementTy(cast<VectorType>(Val->getType())->getElementType(),
Robert Bocchinoca27f032006-01-17 20:07:22 +00002073 Val, Elt, Idx);
2074}
2075
Chris Lattnerbbe0a422006-04-08 01:18:18 +00002076Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
2077 Constant *V2, Constant *Mask) {
2078 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
2079 return FC; // Fold a few common cases...
2080 // Look up the constant in the table first to ensure uniqueness
2081 std::vector<Constant*> ArgVec(1, V1);
2082 ArgVec.push_back(V2);
2083 ArgVec.push_back(Mask);
Reid Spenceree3c9912006-12-04 05:19:50 +00002084 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
Chris Lattner69edc982006-09-28 00:35:06 +00002085 return ExprConstants->getOrCreate(ReqTy, Key);
Chris Lattnerbbe0a422006-04-08 01:18:18 +00002086}
2087
2088Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
2089 Constant *Mask) {
2090 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
2091 "Invalid shuffle vector constant expr operands!");
2092 return getShuffleVectorTy(V1->getType(), V1, V2, Mask);
2093}
2094
Reid Spencer2eadb532007-01-21 00:29:26 +00002095Constant *ConstantExpr::getZeroValueForNegationExpr(const Type *Ty) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00002096 if (const VectorType *PTy = dyn_cast<VectorType>(Ty))
Reid Spencer6598ca82007-01-21 02:29:10 +00002097 if (PTy->getElementType()->isFloatingPoint()) {
2098 std::vector<Constant*> zeros(PTy->getNumElements(),
Dale Johannesen98d3a082007-09-14 22:26:36 +00002099 ConstantFP::getNegativeZero(PTy->getElementType()));
Reid Spencerd84d35b2007-02-15 02:26:10 +00002100 return ConstantVector::get(PTy, zeros);
Reid Spencer6598ca82007-01-21 02:29:10 +00002101 }
Reid Spencer2eadb532007-01-21 00:29:26 +00002102
Dale Johannesen98d3a082007-09-14 22:26:36 +00002103 if (Ty->isFloatingPoint())
2104 return ConstantFP::getNegativeZero(Ty);
Reid Spencer2eadb532007-01-21 00:29:26 +00002105
2106 return Constant::getNullValue(Ty);
2107}
2108
Vikram S. Adve4c485332002-07-15 18:19:33 +00002109// destroyConstant - Remove the constant from the constant table...
2110//
2111void ConstantExpr::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00002112 ExprConstants->remove(this);
Vikram S. Adve4c485332002-07-15 18:19:33 +00002113 destroyConstantImpl();
Vikram S. Adve4e537b22002-07-14 23:13:17 +00002114}
2115
Chris Lattner3cd8c562002-07-30 18:54:25 +00002116const char *ConstantExpr::getOpcodeName() const {
2117 return Instruction::getOpcodeName(getOpcode());
Vikram S. Adve4e537b22002-07-14 23:13:17 +00002118}
Reid Spencer1ebe1ab2004-07-17 23:48:33 +00002119
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002120//===----------------------------------------------------------------------===//
2121// replaceUsesOfWithOnConstant implementations
2122
Chris Lattner913849b2007-08-21 00:55:23 +00002123/// replaceUsesOfWithOnConstant - Update this constant array to change uses of
2124/// 'From' to be uses of 'To'. This must update the uniquing data structures
2125/// etc.
2126///
2127/// Note that we intentionally replace all uses of From with To here. Consider
2128/// a large array that uses 'From' 1000 times. By handling this case all here,
2129/// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
2130/// single invocation handles all 1000 uses. Handling them one at a time would
2131/// work, but would be really slow because it would have to unique each updated
2132/// array instance.
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002133void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002134 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002135 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
Chris Lattner8760ec72005-10-04 01:17:50 +00002136 Constant *ToC = cast<Constant>(To);
Chris Lattnerdff59112005-10-04 18:47:09 +00002137
Jim Laskeyc03caef2006-07-17 17:38:29 +00002138 std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
Chris Lattnerb64419a2005-10-03 22:51:37 +00002139 Lookup.first.first = getType();
2140 Lookup.second = this;
Chris Lattnerdff59112005-10-04 18:47:09 +00002141
Chris Lattnerb64419a2005-10-03 22:51:37 +00002142 std::vector<Constant*> &Values = Lookup.first.second;
2143 Values.reserve(getNumOperands()); // Build replacement array.
Chris Lattnerdff59112005-10-04 18:47:09 +00002144
Chris Lattner8760ec72005-10-04 01:17:50 +00002145 // Fill values with the modified operands of the constant array. Also,
2146 // compute whether this turns into an all-zeros array.
Chris Lattnerdff59112005-10-04 18:47:09 +00002147 bool isAllZeros = false;
Chris Lattner913849b2007-08-21 00:55:23 +00002148 unsigned NumUpdated = 0;
Chris Lattnerdff59112005-10-04 18:47:09 +00002149 if (!ToC->isNullValue()) {
Chris Lattner913849b2007-08-21 00:55:23 +00002150 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2151 Constant *Val = cast<Constant>(O->get());
2152 if (Val == From) {
2153 Val = ToC;
2154 ++NumUpdated;
2155 }
2156 Values.push_back(Val);
2157 }
Chris Lattnerdff59112005-10-04 18:47:09 +00002158 } else {
2159 isAllZeros = true;
2160 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2161 Constant *Val = cast<Constant>(O->get());
Chris Lattner913849b2007-08-21 00:55:23 +00002162 if (Val == From) {
2163 Val = ToC;
2164 ++NumUpdated;
2165 }
Chris Lattnerdff59112005-10-04 18:47:09 +00002166 Values.push_back(Val);
2167 if (isAllZeros) isAllZeros = Val->isNullValue();
2168 }
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002169 }
2170
Chris Lattnerb64419a2005-10-03 22:51:37 +00002171 Constant *Replacement = 0;
2172 if (isAllZeros) {
2173 Replacement = ConstantAggregateZero::get(getType());
2174 } else {
2175 // Check to see if we have this array type already.
2176 bool Exists;
Jim Laskeyc03caef2006-07-17 17:38:29 +00002177 ArrayConstantsTy::MapTy::iterator I =
Chris Lattner69edc982006-09-28 00:35:06 +00002178 ArrayConstants->InsertOrGetItem(Lookup, Exists);
Chris Lattnerb64419a2005-10-03 22:51:37 +00002179
2180 if (Exists) {
2181 Replacement = I->second;
2182 } else {
2183 // Okay, the new shape doesn't exist in the system yet. Instead of
2184 // creating a new constant array, inserting it, replaceallusesof'ing the
2185 // old with the new, then deleting the old... just update the current one
2186 // in place!
Chris Lattner69edc982006-09-28 00:35:06 +00002187 ArrayConstants->MoveConstantToNewSlot(this, I);
Chris Lattnerb64419a2005-10-03 22:51:37 +00002188
Chris Lattner913849b2007-08-21 00:55:23 +00002189 // Update to the new value. Optimize for the case when we have a single
2190 // operand that we're changing, but handle bulk updates efficiently.
2191 if (NumUpdated == 1) {
2192 unsigned OperandToUpdate = U-OperandList;
2193 assert(getOperand(OperandToUpdate) == From &&
2194 "ReplaceAllUsesWith broken!");
2195 setOperand(OperandToUpdate, ToC);
2196 } else {
2197 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2198 if (getOperand(i) == From)
2199 setOperand(i, ToC);
2200 }
Chris Lattnerb64419a2005-10-03 22:51:37 +00002201 return;
2202 }
2203 }
2204
2205 // Otherwise, I do need to replace this with an existing value.
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002206 assert(Replacement != this && "I didn't contain From!");
2207
Chris Lattner7a1450d2005-10-04 18:13:04 +00002208 // Everyone using this now uses the replacement.
2209 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002210
2211 // Delete the old constant!
2212 destroyConstant();
2213}
2214
2215void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002216 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002217 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
Chris Lattner8760ec72005-10-04 01:17:50 +00002218 Constant *ToC = cast<Constant>(To);
2219
Chris Lattnerdff59112005-10-04 18:47:09 +00002220 unsigned OperandToUpdate = U-OperandList;
2221 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2222
Jim Laskeyc03caef2006-07-17 17:38:29 +00002223 std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
Chris Lattner8760ec72005-10-04 01:17:50 +00002224 Lookup.first.first = getType();
2225 Lookup.second = this;
2226 std::vector<Constant*> &Values = Lookup.first.second;
2227 Values.reserve(getNumOperands()); // Build replacement struct.
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002228
Chris Lattnerdff59112005-10-04 18:47:09 +00002229
Chris Lattner8760ec72005-10-04 01:17:50 +00002230 // Fill values with the modified operands of the constant struct. Also,
2231 // compute whether this turns into an all-zeros struct.
Chris Lattnerdff59112005-10-04 18:47:09 +00002232 bool isAllZeros = false;
2233 if (!ToC->isNullValue()) {
2234 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
2235 Values.push_back(cast<Constant>(O->get()));
2236 } else {
2237 isAllZeros = true;
2238 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2239 Constant *Val = cast<Constant>(O->get());
2240 Values.push_back(Val);
2241 if (isAllZeros) isAllZeros = Val->isNullValue();
2242 }
Chris Lattner8760ec72005-10-04 01:17:50 +00002243 }
Chris Lattnerdff59112005-10-04 18:47:09 +00002244 Values[OperandToUpdate] = ToC;
2245
Chris Lattner8760ec72005-10-04 01:17:50 +00002246 Constant *Replacement = 0;
2247 if (isAllZeros) {
2248 Replacement = ConstantAggregateZero::get(getType());
2249 } else {
2250 // Check to see if we have this array type already.
2251 bool Exists;
Jim Laskeyc03caef2006-07-17 17:38:29 +00002252 StructConstantsTy::MapTy::iterator I =
Chris Lattner69edc982006-09-28 00:35:06 +00002253 StructConstants->InsertOrGetItem(Lookup, Exists);
Chris Lattner8760ec72005-10-04 01:17:50 +00002254
2255 if (Exists) {
2256 Replacement = I->second;
2257 } else {
2258 // Okay, the new shape doesn't exist in the system yet. Instead of
2259 // creating a new constant struct, inserting it, replaceallusesof'ing the
2260 // old with the new, then deleting the old... just update the current one
2261 // in place!
Chris Lattner69edc982006-09-28 00:35:06 +00002262 StructConstants->MoveConstantToNewSlot(this, I);
Chris Lattner8760ec72005-10-04 01:17:50 +00002263
Chris Lattnerdff59112005-10-04 18:47:09 +00002264 // Update to the new value.
2265 setOperand(OperandToUpdate, ToC);
Chris Lattner8760ec72005-10-04 01:17:50 +00002266 return;
2267 }
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002268 }
2269
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002270 assert(Replacement != this && "I didn't contain From!");
2271
Chris Lattner7a1450d2005-10-04 18:13:04 +00002272 // Everyone using this now uses the replacement.
2273 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002274
2275 // Delete the old constant!
2276 destroyConstant();
2277}
2278
Reid Spencerd84d35b2007-02-15 02:26:10 +00002279void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002280 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002281 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2282
2283 std::vector<Constant*> Values;
2284 Values.reserve(getNumOperands()); // Build replacement array...
2285 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2286 Constant *Val = getOperand(i);
2287 if (Val == From) Val = cast<Constant>(To);
2288 Values.push_back(Val);
2289 }
2290
Reid Spencerd84d35b2007-02-15 02:26:10 +00002291 Constant *Replacement = ConstantVector::get(getType(), Values);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002292 assert(Replacement != this && "I didn't contain From!");
2293
Chris Lattner7a1450d2005-10-04 18:13:04 +00002294 // Everyone using this now uses the replacement.
2295 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002296
2297 // Delete the old constant!
2298 destroyConstant();
2299}
2300
2301void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002302 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002303 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2304 Constant *To = cast<Constant>(ToV);
2305
2306 Constant *Replacement = 0;
2307 if (getOpcode() == Instruction::GetElementPtr) {
Chris Lattnerb5d70302007-02-19 20:01:23 +00002308 SmallVector<Constant*, 8> Indices;
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002309 Constant *Pointer = getOperand(0);
2310 Indices.reserve(getNumOperands()-1);
2311 if (Pointer == From) Pointer = To;
2312
2313 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2314 Constant *Val = getOperand(i);
2315 if (Val == From) Val = To;
2316 Indices.push_back(Val);
2317 }
Chris Lattnerb5d70302007-02-19 20:01:23 +00002318 Replacement = ConstantExpr::getGetElementPtr(Pointer,
2319 &Indices[0], Indices.size());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002320 } else if (isCast()) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002321 assert(getOperand(0) == From && "Cast only has one use!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002322 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002323 } else if (getOpcode() == Instruction::Select) {
2324 Constant *C1 = getOperand(0);
2325 Constant *C2 = getOperand(1);
2326 Constant *C3 = getOperand(2);
2327 if (C1 == From) C1 = To;
2328 if (C2 == From) C2 = To;
2329 if (C3 == From) C3 = To;
2330 Replacement = ConstantExpr::getSelect(C1, C2, C3);
Robert Bocchino23004482006-01-10 19:05:34 +00002331 } else if (getOpcode() == Instruction::ExtractElement) {
2332 Constant *C1 = getOperand(0);
2333 Constant *C2 = getOperand(1);
2334 if (C1 == From) C1 = To;
2335 if (C2 == From) C2 = To;
2336 Replacement = ConstantExpr::getExtractElement(C1, C2);
Chris Lattnera93b4b52006-04-08 05:09:48 +00002337 } else if (getOpcode() == Instruction::InsertElement) {
2338 Constant *C1 = getOperand(0);
2339 Constant *C2 = getOperand(1);
2340 Constant *C3 = getOperand(1);
2341 if (C1 == From) C1 = To;
2342 if (C2 == From) C2 = To;
2343 if (C3 == From) C3 = To;
2344 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2345 } else if (getOpcode() == Instruction::ShuffleVector) {
2346 Constant *C1 = getOperand(0);
2347 Constant *C2 = getOperand(1);
2348 Constant *C3 = getOperand(2);
2349 if (C1 == From) C1 = To;
2350 if (C2 == From) C2 = To;
2351 if (C3 == From) C3 = To;
2352 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
Reid Spenceree3c9912006-12-04 05:19:50 +00002353 } else if (isCompare()) {
2354 Constant *C1 = getOperand(0);
2355 Constant *C2 = getOperand(1);
2356 if (C1 == From) C1 = To;
2357 if (C2 == From) C2 = To;
2358 if (getOpcode() == Instruction::ICmp)
2359 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2360 else
2361 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002362 } else if (getNumOperands() == 2) {
2363 Constant *C1 = getOperand(0);
2364 Constant *C2 = getOperand(1);
2365 if (C1 == From) C1 = To;
2366 if (C2 == From) C2 = To;
2367 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2368 } else {
2369 assert(0 && "Unknown ConstantExpr type!");
2370 return;
2371 }
2372
2373 assert(Replacement != this && "I didn't contain From!");
2374
Chris Lattner7a1450d2005-10-04 18:13:04 +00002375 // Everyone using this now uses the replacement.
2376 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002377
2378 // Delete the old constant!
2379 destroyConstant();
2380}
2381
2382
Jim Laskey2698f0d2006-03-08 18:11:07 +00002383/// getStringValue - Turn an LLVM constant pointer that eventually points to a
2384/// global into a string value. Return an empty string if we can't do it.
Evan Cheng38280c02006-03-10 23:52:03 +00002385/// Parameter Chop determines if the result is chopped at the first null
2386/// terminator.
Jim Laskey2698f0d2006-03-08 18:11:07 +00002387///
Evan Cheng38280c02006-03-10 23:52:03 +00002388std::string Constant::getStringValue(bool Chop, unsigned Offset) {
Jim Laskey2698f0d2006-03-08 18:11:07 +00002389 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(this)) {
2390 if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
2391 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
2392 if (Init->isString()) {
2393 std::string Result = Init->getAsString();
2394 if (Offset < Result.size()) {
2395 // If we are pointing INTO The string, erase the beginning...
2396 Result.erase(Result.begin(), Result.begin()+Offset);
2397
2398 // Take off the null terminator, and any string fragments after it.
Evan Cheng38280c02006-03-10 23:52:03 +00002399 if (Chop) {
2400 std::string::size_type NullPos = Result.find_first_of((char)0);
2401 if (NullPos != std::string::npos)
2402 Result.erase(Result.begin()+NullPos, Result.end());
2403 }
Jim Laskey2698f0d2006-03-08 18:11:07 +00002404 return Result;
2405 }
2406 }
2407 }
Chris Lattner6ab19ed2007-11-01 02:30:35 +00002408 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(this)) {
2409 if (CE->getOpcode() == Instruction::GetElementPtr) {
2410 // Turn a gep into the specified offset.
2411 if (CE->getNumOperands() == 3 &&
2412 cast<Constant>(CE->getOperand(1))->isNullValue() &&
2413 isa<ConstantInt>(CE->getOperand(2))) {
2414 Offset += cast<ConstantInt>(CE->getOperand(2))->getZExtValue();
2415 return CE->getOperand(0)->getStringValue(Chop, Offset);
Jim Laskey2698f0d2006-03-08 18:11:07 +00002416 }
2417 }
2418 }
2419 return "";
2420}