blob: 74e30f6f960b721ba1ef235fae5d6bfc0a6749d5 [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
Dale Johannesend246b2c2007-08-30 00:23:21 +0000249ConstantFP::ConstantFP(const Type *Ty, const APFloat& V)
250 : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
251 // temporary
252 if (Ty==Type::FloatTy)
253 assert(&V.getSemantics()==&APFloat::IEEEsingle);
Dale Johannesen028084e2007-09-12 03:30:33 +0000254 else if (Ty==Type::DoubleTy)
Dale Johannesend246b2c2007-08-30 00:23:21 +0000255 assert(&V.getSemantics()==&APFloat::IEEEdouble);
Dale Johannesen028084e2007-09-12 03:30:33 +0000256 else if (Ty==Type::X86_FP80Ty)
257 assert(&V.getSemantics()==&APFloat::x87DoubleExtended);
258 else if (Ty==Type::FP128Ty)
259 assert(&V.getSemantics()==&APFloat::IEEEquad);
Dale Johannesen007aa372007-10-11 18:07:22 +0000260 else if (Ty==Type::PPC_FP128Ty)
261 assert(&V.getSemantics()==&APFloat::PPCDoubleDouble);
Dale Johannesen028084e2007-09-12 03:30:33 +0000262 else
263 assert(0);
Chris Lattner2f7c9632001-06-06 20:29:01 +0000264}
265
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000266bool ConstantFP::isNullValue() const {
Dale Johannesena719a602007-08-24 00:56:33 +0000267 return Val.isZero() && !Val.isNegative();
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000268}
269
Dale Johannesen98d3a082007-09-14 22:26:36 +0000270ConstantFP *ConstantFP::getNegativeZero(const Type *Ty) {
271 APFloat apf = cast <ConstantFP>(Constant::getNullValue(Ty))->getValueAPF();
272 apf.changeSign();
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000273 return ConstantFP::get(apf);
Dale Johannesen98d3a082007-09-14 22:26:36 +0000274}
275
Dale Johannesend246b2c2007-08-30 00:23:21 +0000276bool ConstantFP::isExactlyValue(const APFloat& V) const {
277 return Val.bitwiseIsEqual(V);
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000278}
279
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000280namespace {
Dale Johannesena719a602007-08-24 00:56:33 +0000281 struct DenseMapAPFloatKeyInfo {
Dale Johannesenbdea32d2007-08-24 22:09:56 +0000282 struct KeyTy {
283 APFloat val;
284 KeyTy(const APFloat& V) : val(V){}
285 KeyTy(const KeyTy& that) : val(that.val) {}
286 bool operator==(const KeyTy& that) const {
287 return this->val.bitwiseIsEqual(that.val);
288 }
289 bool operator!=(const KeyTy& that) const {
290 return !this->operator==(that);
291 }
292 };
293 static inline KeyTy getEmptyKey() {
294 return KeyTy(APFloat(APFloat::Bogus,1));
Reid Spencerb31bffe2007-02-26 23:54:03 +0000295 }
Dale Johannesenbdea32d2007-08-24 22:09:56 +0000296 static inline KeyTy getTombstoneKey() {
297 return KeyTy(APFloat(APFloat::Bogus,2));
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000298 }
Dale Johannesenbdea32d2007-08-24 22:09:56 +0000299 static unsigned getHashValue(const KeyTy &Key) {
300 return Key.val.getHashValue();
Dale Johannesena719a602007-08-24 00:56:33 +0000301 }
Chris Lattner0625bd62007-09-17 18:34:04 +0000302 static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
303 return LHS == RHS;
304 }
Dale Johannesena719a602007-08-24 00:56:33 +0000305 static bool isPod() { return false; }
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000306 };
307}
308
309//---- ConstantFP::get() implementation...
310//
Dale Johannesenbdea32d2007-08-24 22:09:56 +0000311typedef DenseMap<DenseMapAPFloatKeyInfo::KeyTy, ConstantFP*,
Dale Johannesena719a602007-08-24 00:56:33 +0000312 DenseMapAPFloatKeyInfo> FPMapTy;
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000313
Dale Johannesena719a602007-08-24 00:56:33 +0000314static ManagedStatic<FPMapTy> FPConstants;
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000315
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000316ConstantFP *ConstantFP::get(const APFloat &V) {
Dale Johannesend246b2c2007-08-30 00:23:21 +0000317 DenseMapAPFloatKeyInfo::KeyTy Key(V);
318 ConstantFP *&Slot = (*FPConstants)[Key];
319 if (Slot) return Slot;
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000320
321 const Type *Ty;
322 if (&V.getSemantics() == &APFloat::IEEEsingle)
323 Ty = Type::FloatTy;
324 else if (&V.getSemantics() == &APFloat::IEEEdouble)
325 Ty = Type::DoubleTy;
326 else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
327 Ty = Type::X86_FP80Ty;
328 else if (&V.getSemantics() == &APFloat::IEEEquad)
329 Ty = Type::FP128Ty;
330 else {
331 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble&&"Unknown FP format");
332 Ty = Type::PPC_FP128Ty;
333 }
334
Dale Johannesend246b2c2007-08-30 00:23:21 +0000335 return Slot = new ConstantFP(Ty, V);
336}
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000337
338//===----------------------------------------------------------------------===//
339// ConstantXXX Classes
340//===----------------------------------------------------------------------===//
341
342
Chris Lattner3462ae32001-12-03 22:26:30 +0000343ConstantArray::ConstantArray(const ArrayType *T,
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000344 const std::vector<Constant*> &V)
Chris Lattnere7e139e2005-09-27 06:09:08 +0000345 : Constant(T, ConstantArrayVal, new Use[V.size()], V.size()) {
Alkis Evlogimenos0507ffe2004-09-15 02:32:15 +0000346 assert(V.size() == T->getNumElements() &&
347 "Invalid initializer vector for constant array");
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000348 Use *OL = OperandList;
Chris Lattner0144fad2005-10-03 21:56:24 +0000349 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
350 I != E; ++I, ++OL) {
Chris Lattner20a24452005-10-07 05:23:36 +0000351 Constant *C = *I;
352 assert((C->getType() == T->getElementType() ||
Alkis Evlogimenoscb031d92004-09-10 04:16:59 +0000353 (T->isAbstract() &&
Chris Lattner20a24452005-10-07 05:23:36 +0000354 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
Alkis Evlogimenoscb031d92004-09-10 04:16:59 +0000355 "Initializer for array element doesn't match array element type!");
Chris Lattner20a24452005-10-07 05:23:36 +0000356 OL->init(C, this);
Chris Lattner2f7c9632001-06-06 20:29:01 +0000357 }
358}
359
Gordon Henriksen14a55692007-12-10 02:14:30 +0000360ConstantArray::~ConstantArray() {
361 delete [] OperandList;
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000362}
363
Chris Lattner3462ae32001-12-03 22:26:30 +0000364ConstantStruct::ConstantStruct(const StructType *T,
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000365 const std::vector<Constant*> &V)
Chris Lattnere7e139e2005-09-27 06:09:08 +0000366 : Constant(T, ConstantStructVal, new Use[V.size()], V.size()) {
Chris Lattnerac6db752004-02-09 04:37:31 +0000367 assert(V.size() == T->getNumElements() &&
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000368 "Invalid initializer vector for constant structure");
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000369 Use *OL = OperandList;
Chris Lattner0144fad2005-10-03 21:56:24 +0000370 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
371 I != E; ++I, ++OL) {
Chris Lattner20a24452005-10-07 05:23:36 +0000372 Constant *C = *I;
373 assert((C->getType() == T->getElementType(I-V.begin()) ||
Chris Lattner0144fad2005-10-03 21:56:24 +0000374 ((T->getElementType(I-V.begin())->isAbstract() ||
Chris Lattner20a24452005-10-07 05:23:36 +0000375 C->getType()->isAbstract()) &&
Chris Lattner0144fad2005-10-03 21:56:24 +0000376 T->getElementType(I-V.begin())->getTypeID() ==
Chris Lattner20a24452005-10-07 05:23:36 +0000377 C->getType()->getTypeID())) &&
Chris Lattner93c8f142003-06-02 17:42:47 +0000378 "Initializer for struct element doesn't match struct element type!");
Chris Lattner20a24452005-10-07 05:23:36 +0000379 OL->init(C, this);
Chris Lattner2f7c9632001-06-06 20:29:01 +0000380 }
381}
382
Gordon Henriksen14a55692007-12-10 02:14:30 +0000383ConstantStruct::~ConstantStruct() {
384 delete [] OperandList;
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000385}
386
387
Reid Spencerd84d35b2007-02-15 02:26:10 +0000388ConstantVector::ConstantVector(const VectorType *T,
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000389 const std::vector<Constant*> &V)
Reid Spencerd84d35b2007-02-15 02:26:10 +0000390 : Constant(T, ConstantVectorVal, new Use[V.size()], V.size()) {
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000391 Use *OL = OperandList;
Chris Lattner0144fad2005-10-03 21:56:24 +0000392 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
393 I != E; ++I, ++OL) {
Chris Lattner20a24452005-10-07 05:23:36 +0000394 Constant *C = *I;
395 assert((C->getType() == T->getElementType() ||
Alkis Evlogimenoscb031d92004-09-10 04:16:59 +0000396 (T->isAbstract() &&
Chris Lattner20a24452005-10-07 05:23:36 +0000397 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
Dan Gohman30978072007-05-24 14:36:04 +0000398 "Initializer for vector element doesn't match vector element type!");
Chris Lattner20a24452005-10-07 05:23:36 +0000399 OL->init(C, this);
Brian Gaeke02209042004-08-20 06:00:58 +0000400 }
401}
402
Gordon Henriksen14a55692007-12-10 02:14:30 +0000403ConstantVector::~ConstantVector() {
404 delete [] OperandList;
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000405}
406
Gordon Henriksen14a55692007-12-10 02:14:30 +0000407// We declare several classes private to this file, so use an anonymous
408// namespace
409namespace {
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000410
Gordon Henriksen14a55692007-12-10 02:14:30 +0000411/// UnaryConstantExpr - This class is private to Constants.cpp, and is used
412/// behind the scenes to implement unary constant exprs.
413class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
Gabor Greife9ecc682008-04-06 20:25:17 +0000414 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Gordon Henriksen14a55692007-12-10 02:14:30 +0000415 Use Op;
416public:
Gabor Greife9ecc682008-04-06 20:25:17 +0000417 // allocate space for exactly one operand
418 void *operator new(size_t s) {
419 return User::operator new(s, 1);
420 }
Gordon Henriksen14a55692007-12-10 02:14:30 +0000421 UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
422 : ConstantExpr(Ty, Opcode, &Op, 1), Op(C, this) {}
423};
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000424
Gordon Henriksen14a55692007-12-10 02:14:30 +0000425/// BinaryConstantExpr - This class is private to Constants.cpp, and is used
426/// behind the scenes to implement binary constant exprs.
427class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
Gabor Greife9ecc682008-04-06 20:25:17 +0000428 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Gordon Henriksen14a55692007-12-10 02:14:30 +0000429 Use Ops[2];
430public:
Gabor Greife9ecc682008-04-06 20:25:17 +0000431 // allocate space for exactly two operands
432 void *operator new(size_t s) {
433 return User::operator new(s, 2);
434 }
Gordon Henriksen14a55692007-12-10 02:14:30 +0000435 BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
436 : ConstantExpr(C1->getType(), Opcode, Ops, 2) {
437 Ops[0].init(C1, this);
438 Ops[1].init(C2, this);
439 }
440};
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000441
Gordon Henriksen14a55692007-12-10 02:14:30 +0000442/// SelectConstantExpr - This class is private to Constants.cpp, and is used
443/// behind the scenes to implement select constant exprs.
444class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
Gabor Greife9ecc682008-04-06 20:25:17 +0000445 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Gordon Henriksen14a55692007-12-10 02:14:30 +0000446 Use Ops[3];
447public:
Gabor Greife9ecc682008-04-06 20:25:17 +0000448 // allocate space for exactly three operands
449 void *operator new(size_t s) {
450 return User::operator new(s, 3);
451 }
Gordon Henriksen14a55692007-12-10 02:14:30 +0000452 SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
453 : ConstantExpr(C2->getType(), Instruction::Select, Ops, 3) {
454 Ops[0].init(C1, this);
455 Ops[1].init(C2, this);
456 Ops[2].init(C3, this);
457 }
458};
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000459
Gordon Henriksen14a55692007-12-10 02:14:30 +0000460/// ExtractElementConstantExpr - This class is private to
461/// Constants.cpp, and is used behind the scenes to implement
462/// extractelement constant exprs.
463class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
Gabor Greife9ecc682008-04-06 20:25:17 +0000464 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Gordon Henriksen14a55692007-12-10 02:14:30 +0000465 Use Ops[2];
466public:
Gabor Greife9ecc682008-04-06 20:25:17 +0000467 // allocate space for exactly two operands
468 void *operator new(size_t s) {
469 return User::operator new(s, 2);
470 }
Gordon Henriksen14a55692007-12-10 02:14:30 +0000471 ExtractElementConstantExpr(Constant *C1, Constant *C2)
472 : ConstantExpr(cast<VectorType>(C1->getType())->getElementType(),
473 Instruction::ExtractElement, Ops, 2) {
474 Ops[0].init(C1, this);
475 Ops[1].init(C2, this);
476 }
477};
Robert Bocchino23004482006-01-10 19:05:34 +0000478
Gordon Henriksen14a55692007-12-10 02:14:30 +0000479/// InsertElementConstantExpr - This class is private to
480/// Constants.cpp, and is used behind the scenes to implement
481/// insertelement constant exprs.
482class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
Gabor Greife9ecc682008-04-06 20:25:17 +0000483 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Gordon Henriksen14a55692007-12-10 02:14:30 +0000484 Use Ops[3];
485public:
Gabor Greife9ecc682008-04-06 20:25:17 +0000486 // allocate space for exactly three operands
487 void *operator new(size_t s) {
488 return User::operator new(s, 3);
489 }
Gordon Henriksen14a55692007-12-10 02:14:30 +0000490 InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
491 : ConstantExpr(C1->getType(), Instruction::InsertElement,
492 Ops, 3) {
493 Ops[0].init(C1, this);
494 Ops[1].init(C2, this);
495 Ops[2].init(C3, this);
496 }
497};
Robert Bocchinoca27f032006-01-17 20:07:22 +0000498
Gordon Henriksen14a55692007-12-10 02:14:30 +0000499/// ShuffleVectorConstantExpr - This class is private to
500/// Constants.cpp, and is used behind the scenes to implement
501/// shufflevector constant exprs.
502class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
Gabor Greife9ecc682008-04-06 20:25:17 +0000503 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Gordon Henriksen14a55692007-12-10 02:14:30 +0000504 Use Ops[3];
505public:
Gabor Greife9ecc682008-04-06 20:25:17 +0000506 // allocate space for exactly three operands
507 void *operator new(size_t s) {
508 return User::operator new(s, 3);
509 }
Gordon Henriksen14a55692007-12-10 02:14:30 +0000510 ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
511 : ConstantExpr(C1->getType(), Instruction::ShuffleVector,
512 Ops, 3) {
513 Ops[0].init(C1, this);
514 Ops[1].init(C2, this);
515 Ops[2].init(C3, this);
516 }
517};
518
519/// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
520/// used behind the scenes to implement getelementpr constant exprs.
Gabor Greife9ecc682008-04-06 20:25:17 +0000521class VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
Gordon Henriksen14a55692007-12-10 02:14:30 +0000522 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
523 const Type *DestTy)
524 : ConstantExpr(DestTy, Instruction::GetElementPtr,
525 new Use[IdxList.size()+1], IdxList.size()+1) {
526 OperandList[0].init(C, this);
527 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
528 OperandList[i+1].init(IdxList[i], this);
529 }
Gabor Greife9ecc682008-04-06 20:25:17 +0000530public:
531 static GetElementPtrConstantExpr *Create(Constant *C, const std::vector<Constant*> &IdxList,
532 const Type *DestTy) {
533 return new(IdxList.size() + 1/*FIXME*/) GetElementPtrConstantExpr(C, IdxList, DestTy);
534 }
Gordon Henriksen14a55692007-12-10 02:14:30 +0000535 ~GetElementPtrConstantExpr() {
536 delete [] OperandList;
537 }
538};
539
540// CompareConstantExpr - This class is private to Constants.cpp, and is used
541// behind the scenes to implement ICmp and FCmp constant expressions. This is
542// needed in order to store the predicate value for these instructions.
543struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
Gabor Greife9ecc682008-04-06 20:25:17 +0000544 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
545 // allocate space for exactly two operands
546 void *operator new(size_t s) {
547 return User::operator new(s, 2);
548 }
Gordon Henriksen14a55692007-12-10 02:14:30 +0000549 unsigned short predicate;
550 Use Ops[2];
551 CompareConstantExpr(Instruction::OtherOps opc, unsigned short pred,
552 Constant* LHS, Constant* RHS)
553 : ConstantExpr(Type::Int1Ty, opc, Ops, 2), predicate(pred) {
554 OperandList[0].init(LHS, this);
555 OperandList[1].init(RHS, this);
556 }
557};
558
559} // end anonymous namespace
560
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000561
562// Utility function for determining if a ConstantExpr is a CastOp or not. This
563// can't be inline because we don't want to #include Instruction.h into
564// Constant.h
565bool ConstantExpr::isCast() const {
566 return Instruction::isCast(getOpcode());
567}
568
Reid Spenceree3c9912006-12-04 05:19:50 +0000569bool ConstantExpr::isCompare() const {
570 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
571}
572
Chris Lattner817175f2004-03-29 02:37:53 +0000573/// ConstantExpr::get* - Return some common constants without having to
574/// specify the full Instruction::OPCODE identifier.
575///
576Constant *ConstantExpr::getNeg(Constant *C) {
Reid Spencer2eadb532007-01-21 00:29:26 +0000577 return get(Instruction::Sub,
578 ConstantExpr::getZeroValueForNegationExpr(C->getType()),
579 C);
Chris Lattner817175f2004-03-29 02:37:53 +0000580}
581Constant *ConstantExpr::getNot(Constant *C) {
Gordon Henriksen7ce31762007-10-06 14:29:36 +0000582 assert(isa<IntegerType>(C->getType()) && "Cannot NOT a nonintegral value!");
Chris Lattner817175f2004-03-29 02:37:53 +0000583 return get(Instruction::Xor, C,
Zhou Sheng75b871f2007-01-11 12:24:14 +0000584 ConstantInt::getAllOnesValue(C->getType()));
Chris Lattner817175f2004-03-29 02:37:53 +0000585}
586Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
587 return get(Instruction::Add, C1, C2);
588}
589Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
590 return get(Instruction::Sub, C1, C2);
591}
592Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
593 return get(Instruction::Mul, C1, C2);
594}
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000595Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2) {
596 return get(Instruction::UDiv, C1, C2);
597}
598Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2) {
599 return get(Instruction::SDiv, C1, C2);
600}
601Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
602 return get(Instruction::FDiv, C1, C2);
Chris Lattner817175f2004-03-29 02:37:53 +0000603}
Reid Spencer7eb55b32006-11-02 01:53:59 +0000604Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
605 return get(Instruction::URem, C1, C2);
606}
607Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
608 return get(Instruction::SRem, C1, C2);
609}
610Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
611 return get(Instruction::FRem, C1, C2);
Chris Lattner817175f2004-03-29 02:37:53 +0000612}
613Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
614 return get(Instruction::And, C1, C2);
615}
616Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
617 return get(Instruction::Or, C1, C2);
618}
619Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
620 return get(Instruction::Xor, C1, C2);
621}
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000622unsigned ConstantExpr::getPredicate() const {
623 assert(getOpcode() == Instruction::FCmp || getOpcode() == Instruction::ICmp);
Chris Lattneref650092007-10-18 16:26:24 +0000624 return ((const CompareConstantExpr*)this)->predicate;
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000625}
Chris Lattner817175f2004-03-29 02:37:53 +0000626Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
627 return get(Instruction::Shl, C1, C2);
628}
Reid Spencerfdff9382006-11-08 06:47:33 +0000629Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2) {
630 return get(Instruction::LShr, C1, C2);
Chris Lattner817175f2004-03-29 02:37:53 +0000631}
Reid Spencerfdff9382006-11-08 06:47:33 +0000632Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2) {
633 return get(Instruction::AShr, C1, C2);
Chris Lattnerdb8bdba2004-05-25 05:32:43 +0000634}
Chris Lattner60e0dd72001-10-03 06:12:09 +0000635
Chris Lattner7c1018a2006-07-14 19:37:40 +0000636/// getWithOperandReplaced - Return a constant expression identical to this
637/// one, but with the specified operand set to the specified value.
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000638Constant *
639ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
Chris Lattner7c1018a2006-07-14 19:37:40 +0000640 assert(OpNo < getNumOperands() && "Operand num is out of range!");
641 assert(Op->getType() == getOperand(OpNo)->getType() &&
642 "Replacing operand with value of different type!");
Chris Lattner227816342006-07-14 22:20:01 +0000643 if (getOperand(OpNo) == Op)
644 return const_cast<ConstantExpr*>(this);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000645
Chris Lattner227816342006-07-14 22:20:01 +0000646 Constant *Op0, *Op1, *Op2;
Chris Lattner7c1018a2006-07-14 19:37:40 +0000647 switch (getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000648 case Instruction::Trunc:
649 case Instruction::ZExt:
650 case Instruction::SExt:
651 case Instruction::FPTrunc:
652 case Instruction::FPExt:
653 case Instruction::UIToFP:
654 case Instruction::SIToFP:
655 case Instruction::FPToUI:
656 case Instruction::FPToSI:
657 case Instruction::PtrToInt:
658 case Instruction::IntToPtr:
659 case Instruction::BitCast:
660 return ConstantExpr::getCast(getOpcode(), Op, getType());
Chris Lattner227816342006-07-14 22:20:01 +0000661 case Instruction::Select:
662 Op0 = (OpNo == 0) ? Op : getOperand(0);
663 Op1 = (OpNo == 1) ? Op : getOperand(1);
664 Op2 = (OpNo == 2) ? Op : getOperand(2);
665 return ConstantExpr::getSelect(Op0, Op1, Op2);
666 case Instruction::InsertElement:
667 Op0 = (OpNo == 0) ? Op : getOperand(0);
668 Op1 = (OpNo == 1) ? Op : getOperand(1);
669 Op2 = (OpNo == 2) ? Op : getOperand(2);
670 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
671 case Instruction::ExtractElement:
672 Op0 = (OpNo == 0) ? Op : getOperand(0);
673 Op1 = (OpNo == 1) ? Op : getOperand(1);
674 return ConstantExpr::getExtractElement(Op0, Op1);
675 case Instruction::ShuffleVector:
676 Op0 = (OpNo == 0) ? Op : getOperand(0);
677 Op1 = (OpNo == 1) ? Op : getOperand(1);
678 Op2 = (OpNo == 2) ? Op : getOperand(2);
679 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000680 case Instruction::GetElementPtr: {
Chris Lattnerb5d70302007-02-19 20:01:23 +0000681 SmallVector<Constant*, 8> Ops;
682 Ops.resize(getNumOperands());
Chris Lattner7c1018a2006-07-14 19:37:40 +0000683 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
Chris Lattnerb5d70302007-02-19 20:01:23 +0000684 Ops[i] = getOperand(i);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000685 if (OpNo == 0)
Chris Lattnerb5d70302007-02-19 20:01:23 +0000686 return ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
Chris Lattner7c1018a2006-07-14 19:37:40 +0000687 Ops[OpNo-1] = Op;
Chris Lattnerb5d70302007-02-19 20:01:23 +0000688 return ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
Chris Lattner7c1018a2006-07-14 19:37:40 +0000689 }
Chris Lattner7c1018a2006-07-14 19:37:40 +0000690 default:
691 assert(getNumOperands() == 2 && "Must be binary operator?");
Chris Lattner227816342006-07-14 22:20:01 +0000692 Op0 = (OpNo == 0) ? Op : getOperand(0);
693 Op1 = (OpNo == 1) ? Op : getOperand(1);
694 return ConstantExpr::get(getOpcode(), Op0, Op1);
695 }
696}
697
698/// getWithOperands - This returns the current constant expression with the
699/// operands replaced with the specified values. The specified operands must
700/// match count and type with the existing ones.
701Constant *ConstantExpr::
702getWithOperands(const std::vector<Constant*> &Ops) const {
703 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
704 bool AnyChange = false;
705 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
706 assert(Ops[i]->getType() == getOperand(i)->getType() &&
707 "Operand type mismatch!");
708 AnyChange |= Ops[i] != getOperand(i);
709 }
710 if (!AnyChange) // No operands changed, return self.
711 return const_cast<ConstantExpr*>(this);
712
713 switch (getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000714 case Instruction::Trunc:
715 case Instruction::ZExt:
716 case Instruction::SExt:
717 case Instruction::FPTrunc:
718 case Instruction::FPExt:
719 case Instruction::UIToFP:
720 case Instruction::SIToFP:
721 case Instruction::FPToUI:
722 case Instruction::FPToSI:
723 case Instruction::PtrToInt:
724 case Instruction::IntToPtr:
725 case Instruction::BitCast:
726 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
Chris Lattner227816342006-07-14 22:20:01 +0000727 case Instruction::Select:
728 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
729 case Instruction::InsertElement:
730 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
731 case Instruction::ExtractElement:
732 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
733 case Instruction::ShuffleVector:
734 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
Chris Lattnerb5d70302007-02-19 20:01:23 +0000735 case Instruction::GetElementPtr:
736 return ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], Ops.size()-1);
Reid Spencer266e42b2006-12-23 06:05:41 +0000737 case Instruction::ICmp:
738 case Instruction::FCmp:
739 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
Chris Lattner227816342006-07-14 22:20:01 +0000740 default:
741 assert(getNumOperands() == 2 && "Must be binary operator?");
742 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000743 }
744}
745
Chris Lattner2f7c9632001-06-06 20:29:01 +0000746
747//===----------------------------------------------------------------------===//
Chris Lattner2f7c9632001-06-06 20:29:01 +0000748// isValueValidForType implementations
749
Reid Spencere7334722006-12-19 01:28:19 +0000750bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000751 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000752 if (Ty == Type::Int1Ty)
753 return Val == 0 || Val == 1;
Reid Spencerd7a00d72007-02-05 23:47:56 +0000754 if (NumBits >= 64)
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000755 return true; // always true, has to fit in largest type
756 uint64_t Max = (1ll << NumBits) - 1;
757 return Val <= Max;
Reid Spencere7334722006-12-19 01:28:19 +0000758}
759
Reid Spencere0fc4df2006-10-20 07:07:24 +0000760bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000761 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000762 if (Ty == Type::Int1Ty)
Reid Spencera94d3942007-01-19 21:13:56 +0000763 return Val == 0 || Val == 1 || Val == -1;
Reid Spencerd7a00d72007-02-05 23:47:56 +0000764 if (NumBits >= 64)
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000765 return true; // always true, has to fit in largest type
766 int64_t Min = -(1ll << (NumBits-1));
767 int64_t Max = (1ll << (NumBits-1)) - 1;
768 return (Val >= Min && Val <= Max);
Chris Lattner2f7c9632001-06-06 20:29:01 +0000769}
770
Dale Johannesend246b2c2007-08-30 00:23:21 +0000771bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
772 // convert modifies in place, so make a copy.
773 APFloat Val2 = APFloat(Val);
Chris Lattner6b727592004-06-17 18:19:28 +0000774 switch (Ty->getTypeID()) {
Chris Lattner2f7c9632001-06-06 20:29:01 +0000775 default:
776 return false; // These can't be represented as floating point!
777
Dale Johannesend246b2c2007-08-30 00:23:21 +0000778 // FIXME rounding mode needs to be more flexible
Chris Lattner2f7c9632001-06-06 20:29:01 +0000779 case Type::FloatTyID:
Dale Johannesend246b2c2007-08-30 00:23:21 +0000780 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
781 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven) ==
782 APFloat::opOK;
Chris Lattner2f7c9632001-06-06 20:29:01 +0000783 case Type::DoubleTyID:
Dale Johannesend246b2c2007-08-30 00:23:21 +0000784 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
785 &Val2.getSemantics() == &APFloat::IEEEdouble ||
786 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven) ==
787 APFloat::opOK;
Dale Johannesenbdad8092007-08-09 22:51:36 +0000788 case Type::X86_FP80TyID:
Dale Johannesen028084e2007-09-12 03:30:33 +0000789 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
790 &Val2.getSemantics() == &APFloat::IEEEdouble ||
791 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
Dale Johannesenbdad8092007-08-09 22:51:36 +0000792 case Type::FP128TyID:
Dale Johannesen028084e2007-09-12 03:30:33 +0000793 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
794 &Val2.getSemantics() == &APFloat::IEEEdouble ||
795 &Val2.getSemantics() == &APFloat::IEEEquad;
Dale Johannesen007aa372007-10-11 18:07:22 +0000796 case Type::PPC_FP128TyID:
797 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
798 &Val2.getSemantics() == &APFloat::IEEEdouble ||
799 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
Chris Lattner2f7c9632001-06-06 20:29:01 +0000800 }
Chris Lattneraa2372562006-05-24 17:04:05 +0000801}
Chris Lattner9655e542001-07-20 19:16:02 +0000802
Chris Lattner49d855c2001-09-07 16:46:31 +0000803//===----------------------------------------------------------------------===//
Chris Lattner49d855c2001-09-07 16:46:31 +0000804// Factory Function Implementation
805
Chris Lattner98fa07b2003-05-23 20:03:32 +0000806// ConstantCreator - A class that is used to create constants by
807// ValueMap*. This class should be partially specialized if there is
808// something strange that needs to be done to interface to the ctor for the
809// constant.
810//
Chris Lattner189d19f2003-11-21 20:23:48 +0000811namespace llvm {
812 template<class ConstantClass, class TypeClass, class ValType>
Chris Lattner02157b02006-06-28 21:38:54 +0000813 struct VISIBILITY_HIDDEN ConstantCreator {
Chris Lattner189d19f2003-11-21 20:23:48 +0000814 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
Gabor Greifdd8b7a02008-04-06 21:42:13 +0000815 unsigned FIXME = 0; // = traits<ValType>::uses(V)
Gabor Greife9ecc682008-04-06 20:25:17 +0000816 return new(FIXME) ConstantClass(Ty, V);
Chris Lattner189d19f2003-11-21 20:23:48 +0000817 }
818 };
Misha Brukmanb1c93172005-04-21 23:48:37 +0000819
Chris Lattner189d19f2003-11-21 20:23:48 +0000820 template<class ConstantClass, class TypeClass>
Chris Lattner02157b02006-06-28 21:38:54 +0000821 struct VISIBILITY_HIDDEN ConvertConstantType {
Chris Lattner189d19f2003-11-21 20:23:48 +0000822 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
823 assert(0 && "This type cannot be converted!\n");
824 abort();
825 }
826 };
Chris Lattnerb50d1352003-10-05 00:17:43 +0000827
Chris Lattner935aa922005-10-04 17:48:46 +0000828 template<class ValType, class TypeClass, class ConstantClass,
829 bool HasLargeKey = false /*true for arrays and structs*/ >
Chris Lattner02157b02006-06-28 21:38:54 +0000830 class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
Chris Lattnerb64419a2005-10-03 22:51:37 +0000831 public:
Jim Laskeyc03caef2006-07-17 17:38:29 +0000832 typedef std::pair<const Type*, ValType> MapKey;
833 typedef std::map<MapKey, Constant *> MapTy;
834 typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
835 typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
Chris Lattnerb64419a2005-10-03 22:51:37 +0000836 private:
Chris Lattner5bbf60a52005-10-04 16:52:46 +0000837 /// Map - This is the main map from the element descriptor to the Constants.
838 /// This is the primary way we avoid creating two of the same shape
839 /// constant.
Chris Lattnerb50d1352003-10-05 00:17:43 +0000840 MapTy Map;
Chris Lattner935aa922005-10-04 17:48:46 +0000841
842 /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
843 /// from the constants to their element in Map. This is important for
844 /// removal of constants from the array, which would otherwise have to scan
845 /// through the map with very large keys.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000846 InverseMapTy InverseMap;
Chris Lattnerb50d1352003-10-05 00:17:43 +0000847
Jim Laskeyc03caef2006-07-17 17:38:29 +0000848 /// AbstractTypeMap - Map for abstract type constants.
849 ///
Chris Lattnerb50d1352003-10-05 00:17:43 +0000850 AbstractTypeMapTy AbstractTypeMap;
Chris Lattner99a669b2004-11-19 16:39:44 +0000851
Chris Lattner98fa07b2003-05-23 20:03:32 +0000852 public:
Jim Laskeyc03caef2006-07-17 17:38:29 +0000853 typename MapTy::iterator map_end() { return Map.end(); }
Chris Lattnerb64419a2005-10-03 22:51:37 +0000854
855 /// InsertOrGetItem - Return an iterator for the specified element.
856 /// If the element exists in the map, the returned iterator points to the
857 /// entry and Exists=true. If not, the iterator points to the newly
858 /// inserted entry and returns Exists=false. Newly inserted entries have
859 /// I->second == 0, and should be filled in.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000860 typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
861 &InsertVal,
Chris Lattnerb64419a2005-10-03 22:51:37 +0000862 bool &Exists) {
Jim Laskeyc03caef2006-07-17 17:38:29 +0000863 std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
Chris Lattnerb64419a2005-10-03 22:51:37 +0000864 Exists = !IP.second;
865 return IP.first;
866 }
Chris Lattner5bbf60a52005-10-04 16:52:46 +0000867
Chris Lattner935aa922005-10-04 17:48:46 +0000868private:
Jim Laskeyc03caef2006-07-17 17:38:29 +0000869 typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
Chris Lattner935aa922005-10-04 17:48:46 +0000870 if (HasLargeKey) {
Jim Laskeyc03caef2006-07-17 17:38:29 +0000871 typename InverseMapTy::iterator IMI = InverseMap.find(CP);
Chris Lattner935aa922005-10-04 17:48:46 +0000872 assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
873 IMI->second->second == CP &&
874 "InverseMap corrupt!");
875 return IMI->second;
876 }
877
Jim Laskeyc03caef2006-07-17 17:38:29 +0000878 typename MapTy::iterator I =
Chris Lattner935aa922005-10-04 17:48:46 +0000879 Map.find(MapKey((TypeClass*)CP->getRawType(), getValType(CP)));
Chris Lattner5bbf60a52005-10-04 16:52:46 +0000880 if (I == Map.end() || I->second != CP) {
881 // FIXME: This should not use a linear scan. If this gets to be a
882 // performance problem, someone should look at this.
883 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
884 /* empty */;
885 }
Chris Lattner935aa922005-10-04 17:48:46 +0000886 return I;
887 }
888public:
889
Chris Lattnerb64419a2005-10-03 22:51:37 +0000890 /// getOrCreate - Return the specified constant from the map, creating it if
891 /// necessary.
Chris Lattner98fa07b2003-05-23 20:03:32 +0000892 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
Chris Lattnerb50d1352003-10-05 00:17:43 +0000893 MapKey Lookup(Ty, V);
Jim Laskeyc03caef2006-07-17 17:38:29 +0000894 typename MapTy::iterator I = Map.lower_bound(Lookup);
Reid Spencere0fc4df2006-10-20 07:07:24 +0000895 // Is it in the map?
Chris Lattner98fa07b2003-05-23 20:03:32 +0000896 if (I != Map.end() && I->first == Lookup)
Reid Spencere0fc4df2006-10-20 07:07:24 +0000897 return static_cast<ConstantClass *>(I->second);
Chris Lattner98fa07b2003-05-23 20:03:32 +0000898
899 // If no preexisting value, create one now...
900 ConstantClass *Result =
901 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
902
Chris Lattnerb50d1352003-10-05 00:17:43 +0000903 /// FIXME: why does this assert fail when loading 176.gcc?
904 //assert(Result->getType() == Ty && "Type specified is not correct!");
905 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
906
Chris Lattner935aa922005-10-04 17:48:46 +0000907 if (HasLargeKey) // Remember the reverse mapping if needed.
908 InverseMap.insert(std::make_pair(Result, I));
909
Chris Lattnerb50d1352003-10-05 00:17:43 +0000910 // If the type of the constant is abstract, make sure that an entry exists
911 // for it in the AbstractTypeMap.
912 if (Ty->isAbstract()) {
913 typename AbstractTypeMapTy::iterator TI =
914 AbstractTypeMap.lower_bound(Ty);
915
916 if (TI == AbstractTypeMap.end() || TI->first != Ty) {
917 // Add ourselves to the ATU list of the type.
918 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
919
920 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
921 }
922 }
Chris Lattner98fa07b2003-05-23 20:03:32 +0000923 return Result;
924 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000925
Chris Lattner98fa07b2003-05-23 20:03:32 +0000926 void remove(ConstantClass *CP) {
Jim Laskeyc03caef2006-07-17 17:38:29 +0000927 typename MapTy::iterator I = FindExistingElement(CP);
Chris Lattnerb50d1352003-10-05 00:17:43 +0000928 assert(I != Map.end() && "Constant not found in constant table!");
Chris Lattner3e650af2004-08-04 04:48:01 +0000929 assert(I->second == CP && "Didn't find correct element?");
Chris Lattnerb50d1352003-10-05 00:17:43 +0000930
Chris Lattner935aa922005-10-04 17:48:46 +0000931 if (HasLargeKey) // Remember the reverse mapping if needed.
932 InverseMap.erase(CP);
933
Chris Lattnerb50d1352003-10-05 00:17:43 +0000934 // Now that we found the entry, make sure this isn't the entry that
935 // the AbstractTypeMap points to.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000936 const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
Chris Lattnerb50d1352003-10-05 00:17:43 +0000937 if (Ty->isAbstract()) {
938 assert(AbstractTypeMap.count(Ty) &&
939 "Abstract type not in AbstractTypeMap?");
Jim Laskeyc03caef2006-07-17 17:38:29 +0000940 typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
Chris Lattnerb50d1352003-10-05 00:17:43 +0000941 if (ATMEntryIt == I) {
942 // Yes, we are removing the representative entry for this type.
943 // See if there are any other entries of the same type.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000944 typename MapTy::iterator TmpIt = ATMEntryIt;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000945
Chris Lattnerb50d1352003-10-05 00:17:43 +0000946 // First check the entry before this one...
947 if (TmpIt != Map.begin()) {
948 --TmpIt;
949 if (TmpIt->first.first != Ty) // Not the same type, move back...
950 ++TmpIt;
951 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000952
Chris Lattnerb50d1352003-10-05 00:17:43 +0000953 // If we didn't find the same type, try to move forward...
954 if (TmpIt == ATMEntryIt) {
955 ++TmpIt;
956 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
957 --TmpIt; // No entry afterwards with the same type
958 }
959
960 // If there is another entry in the map of the same abstract type,
961 // update the AbstractTypeMap entry now.
962 if (TmpIt != ATMEntryIt) {
963 ATMEntryIt = TmpIt;
964 } else {
965 // Otherwise, we are removing the last instance of this type
966 // from the table. Remove from the ATM, and from user list.
967 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
968 AbstractTypeMap.erase(Ty);
969 }
Chris Lattner98fa07b2003-05-23 20:03:32 +0000970 }
Chris Lattnerb50d1352003-10-05 00:17:43 +0000971 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000972
Chris Lattnerb50d1352003-10-05 00:17:43 +0000973 Map.erase(I);
974 }
975
Chris Lattner3b793c62005-10-04 21:35:50 +0000976
977 /// MoveConstantToNewSlot - If we are about to change C to be the element
978 /// specified by I, update our internal data structures to reflect this
979 /// fact.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000980 void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
Chris Lattner3b793c62005-10-04 21:35:50 +0000981 // First, remove the old location of the specified constant in the map.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000982 typename MapTy::iterator OldI = FindExistingElement(C);
Chris Lattner3b793c62005-10-04 21:35:50 +0000983 assert(OldI != Map.end() && "Constant not found in constant table!");
984 assert(OldI->second == C && "Didn't find correct element?");
985
986 // If this constant is the representative element for its abstract type,
987 // update the AbstractTypeMap so that the representative element is I.
988 if (C->getType()->isAbstract()) {
989 typename AbstractTypeMapTy::iterator ATI =
990 AbstractTypeMap.find(C->getType());
991 assert(ATI != AbstractTypeMap.end() &&
992 "Abstract type not in AbstractTypeMap?");
993 if (ATI->second == OldI)
994 ATI->second = I;
995 }
996
997 // Remove the old entry from the map.
998 Map.erase(OldI);
999
1000 // Update the inverse map so that we know that this constant is now
1001 // located at descriptor I.
1002 if (HasLargeKey) {
1003 assert(I->second == C && "Bad inversemap entry!");
1004 InverseMap[C] = I;
1005 }
1006 }
1007
Chris Lattnerb50d1352003-10-05 00:17:43 +00001008 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00001009 typename AbstractTypeMapTy::iterator I =
Jim Laskeyc03caef2006-07-17 17:38:29 +00001010 AbstractTypeMap.find(cast<Type>(OldTy));
Chris Lattnerb50d1352003-10-05 00:17:43 +00001011
1012 assert(I != AbstractTypeMap.end() &&
1013 "Abstract type not in AbstractTypeMap?");
1014
1015 // Convert a constant at a time until the last one is gone. The last one
1016 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
1017 // eliminated eventually.
1018 do {
1019 ConvertConstantType<ConstantClass,
Jim Laskeyc03caef2006-07-17 17:38:29 +00001020 TypeClass>::convert(
1021 static_cast<ConstantClass *>(I->second->second),
Chris Lattnerb50d1352003-10-05 00:17:43 +00001022 cast<TypeClass>(NewTy));
1023
Jim Laskeyc03caef2006-07-17 17:38:29 +00001024 I = AbstractTypeMap.find(cast<Type>(OldTy));
Chris Lattnerb50d1352003-10-05 00:17:43 +00001025 } while (I != AbstractTypeMap.end());
1026 }
1027
1028 // If the type became concrete without being refined to any other existing
1029 // type, we just remove ourselves from the ATU list.
1030 void typeBecameConcrete(const DerivedType *AbsTy) {
1031 AbsTy->removeAbstractTypeUser(this);
1032 }
1033
1034 void dump() const {
Bill Wendling6a462f12006-11-17 08:03:48 +00001035 DOUT << "Constant.cpp: ValueMap\n";
Chris Lattner98fa07b2003-05-23 20:03:32 +00001036 }
1037 };
1038}
1039
Chris Lattnera84df0a22006-09-28 23:36:21 +00001040
Chris Lattner28173502007-02-20 06:11:36 +00001041
Chris Lattner9fba3da2004-02-15 05:53:04 +00001042//---- ConstantAggregateZero::get() implementation...
1043//
1044namespace llvm {
1045 // ConstantAggregateZero does not take extra "value" argument...
1046 template<class ValType>
1047 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
1048 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
1049 return new ConstantAggregateZero(Ty);
1050 }
1051 };
1052
1053 template<>
1054 struct ConvertConstantType<ConstantAggregateZero, Type> {
1055 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
1056 // Make everyone now use a constant of the new type...
1057 Constant *New = ConstantAggregateZero::get(NewTy);
1058 assert(New != OldC && "Didn't replace constant??");
1059 OldC->uncheckedReplaceAllUsesWith(New);
1060 OldC->destroyConstant(); // This constant is now dead, destroy it.
1061 }
1062 };
1063}
1064
Chris Lattner69edc982006-09-28 00:35:06 +00001065static ManagedStatic<ValueMap<char, Type,
1066 ConstantAggregateZero> > AggZeroConstants;
Chris Lattner9fba3da2004-02-15 05:53:04 +00001067
Chris Lattner3e650af2004-08-04 04:48:01 +00001068static char getValType(ConstantAggregateZero *CPZ) { return 0; }
1069
Chris Lattner9fba3da2004-02-15 05:53:04 +00001070Constant *ConstantAggregateZero::get(const Type *Ty) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001071 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) &&
Chris Lattnerbfd0b6d2006-06-10 04:16:23 +00001072 "Cannot create an aggregate zero of non-aggregate type!");
Chris Lattner69edc982006-09-28 00:35:06 +00001073 return AggZeroConstants->getOrCreate(Ty, 0);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001074}
1075
1076// destroyConstant - Remove the constant from the constant table...
1077//
1078void ConstantAggregateZero::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001079 AggZeroConstants->remove(this);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001080 destroyConstantImpl();
1081}
1082
Chris Lattner3462ae32001-12-03 22:26:30 +00001083//---- ConstantArray::get() implementation...
Chris Lattner49d855c2001-09-07 16:46:31 +00001084//
Chris Lattner189d19f2003-11-21 20:23:48 +00001085namespace llvm {
1086 template<>
1087 struct ConvertConstantType<ConstantArray, ArrayType> {
1088 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
1089 // Make everyone now use a constant of the new type...
1090 std::vector<Constant*> C;
1091 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1092 C.push_back(cast<Constant>(OldC->getOperand(i)));
1093 Constant *New = ConstantArray::get(NewTy, C);
1094 assert(New != OldC && "Didn't replace constant??");
1095 OldC->uncheckedReplaceAllUsesWith(New);
1096 OldC->destroyConstant(); // This constant is now dead, destroy it.
1097 }
1098 };
1099}
Chris Lattnerb50d1352003-10-05 00:17:43 +00001100
Chris Lattner3e650af2004-08-04 04:48:01 +00001101static std::vector<Constant*> getValType(ConstantArray *CA) {
1102 std::vector<Constant*> Elements;
1103 Elements.reserve(CA->getNumOperands());
1104 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1105 Elements.push_back(cast<Constant>(CA->getOperand(i)));
1106 return Elements;
1107}
1108
Chris Lattnerb64419a2005-10-03 22:51:37 +00001109typedef ValueMap<std::vector<Constant*>, ArrayType,
Chris Lattner935aa922005-10-04 17:48:46 +00001110 ConstantArray, true /*largekey*/> ArrayConstantsTy;
Chris Lattner69edc982006-09-28 00:35:06 +00001111static ManagedStatic<ArrayConstantsTy> ArrayConstants;
Chris Lattner49d855c2001-09-07 16:46:31 +00001112
Chris Lattner015e8212004-02-15 04:14:47 +00001113Constant *ConstantArray::get(const ArrayType *Ty,
Chris Lattner9fba3da2004-02-15 05:53:04 +00001114 const std::vector<Constant*> &V) {
1115 // If this is an all-zero array, return a ConstantAggregateZero object
1116 if (!V.empty()) {
1117 Constant *C = V[0];
1118 if (!C->isNullValue())
Chris Lattner69edc982006-09-28 00:35:06 +00001119 return ArrayConstants->getOrCreate(Ty, V);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001120 for (unsigned i = 1, e = V.size(); i != e; ++i)
1121 if (V[i] != C)
Chris Lattner69edc982006-09-28 00:35:06 +00001122 return ArrayConstants->getOrCreate(Ty, V);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001123 }
1124 return ConstantAggregateZero::get(Ty);
Chris Lattner49d855c2001-09-07 16:46:31 +00001125}
1126
Chris Lattner98fa07b2003-05-23 20:03:32 +00001127// destroyConstant - Remove the constant from the constant table...
1128//
1129void ConstantArray::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001130 ArrayConstants->remove(this);
Chris Lattner98fa07b2003-05-23 20:03:32 +00001131 destroyConstantImpl();
1132}
1133
Reid Spencer6f614532006-05-30 08:23:18 +00001134/// ConstantArray::get(const string&) - Return an array that is initialized to
1135/// contain the specified string. If length is zero then a null terminator is
1136/// added to the specified string so that it may be used in a natural way.
1137/// Otherwise, the length parameter specifies how much of the string to use
1138/// and it won't be null terminated.
1139///
Reid Spencer82ebaba2006-05-30 18:15:07 +00001140Constant *ConstantArray::get(const std::string &Str, bool AddNull) {
Chris Lattner7f74a562002-01-20 22:54:45 +00001141 std::vector<Constant*> ElementVals;
Reid Spencer82ebaba2006-05-30 18:15:07 +00001142 for (unsigned i = 0; i < Str.length(); ++i)
Reid Spencer8d9336d2006-12-31 05:26:44 +00001143 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, Str[i]));
Chris Lattner8f80fe02001-10-14 23:54:12 +00001144
1145 // Add a null terminator to the string...
Reid Spencer82ebaba2006-05-30 18:15:07 +00001146 if (AddNull) {
Reid Spencer8d9336d2006-12-31 05:26:44 +00001147 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, 0));
Reid Spencer6f614532006-05-30 08:23:18 +00001148 }
Chris Lattner8f80fe02001-10-14 23:54:12 +00001149
Reid Spencer8d9336d2006-12-31 05:26:44 +00001150 ArrayType *ATy = ArrayType::get(Type::Int8Ty, ElementVals.size());
Chris Lattner3462ae32001-12-03 22:26:30 +00001151 return ConstantArray::get(ATy, ElementVals);
Vikram S. Adve34410432001-10-14 23:17:20 +00001152}
1153
Reid Spencer2546b762007-01-26 07:37:34 +00001154/// isString - This method returns true if the array is an array of i8, and
1155/// if the elements of the array are all ConstantInt's.
Chris Lattnere8dfcca2004-01-14 17:06:38 +00001156bool ConstantArray::isString() const {
Reid Spencer2546b762007-01-26 07:37:34 +00001157 // Check the element type for i8...
Reid Spencer8d9336d2006-12-31 05:26:44 +00001158 if (getType()->getElementType() != Type::Int8Ty)
Chris Lattnere8dfcca2004-01-14 17:06:38 +00001159 return false;
1160 // Check the elements to make sure they are all integers, not constant
1161 // expressions.
1162 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1163 if (!isa<ConstantInt>(getOperand(i)))
1164 return false;
1165 return true;
1166}
1167
Evan Cheng3763c5b2006-10-26 19:15:05 +00001168/// isCString - This method returns true if the array is a string (see
1169/// isString) and it ends in a null byte \0 and does not contains any other
1170/// null bytes except its terminator.
1171bool ConstantArray::isCString() const {
Reid Spencer2546b762007-01-26 07:37:34 +00001172 // Check the element type for i8...
Reid Spencer8d9336d2006-12-31 05:26:44 +00001173 if (getType()->getElementType() != Type::Int8Ty)
Evan Chenge974da62006-10-26 21:48:03 +00001174 return false;
1175 Constant *Zero = Constant::getNullValue(getOperand(0)->getType());
1176 // Last element must be a null.
1177 if (getOperand(getNumOperands()-1) != Zero)
1178 return false;
1179 // Other elements must be non-null integers.
1180 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1181 if (!isa<ConstantInt>(getOperand(i)))
Evan Cheng3763c5b2006-10-26 19:15:05 +00001182 return false;
Evan Chenge974da62006-10-26 21:48:03 +00001183 if (getOperand(i) == Zero)
1184 return false;
1185 }
Evan Cheng3763c5b2006-10-26 19:15:05 +00001186 return true;
1187}
1188
1189
Reid Spencer2546b762007-01-26 07:37:34 +00001190// getAsString - If the sub-element type of this array is i8
Chris Lattner81fabb02002-08-26 17:53:56 +00001191// then this method converts the array to an std::string and returns it.
1192// Otherwise, it asserts out.
1193//
1194std::string ConstantArray::getAsString() const {
Chris Lattnere8dfcca2004-01-14 17:06:38 +00001195 assert(isString() && "Not a string!");
Chris Lattner81fabb02002-08-26 17:53:56 +00001196 std::string Result;
Chris Lattner6077c312003-07-23 15:22:26 +00001197 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
Reid Spencere0fc4df2006-10-20 07:07:24 +00001198 Result += (char)cast<ConstantInt>(getOperand(i))->getZExtValue();
Chris Lattner81fabb02002-08-26 17:53:56 +00001199 return Result;
1200}
1201
1202
Chris Lattner3462ae32001-12-03 22:26:30 +00001203//---- ConstantStruct::get() implementation...
Chris Lattner49d855c2001-09-07 16:46:31 +00001204//
Chris Lattnerb50d1352003-10-05 00:17:43 +00001205
Chris Lattner189d19f2003-11-21 20:23:48 +00001206namespace llvm {
1207 template<>
1208 struct ConvertConstantType<ConstantStruct, StructType> {
1209 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1210 // Make everyone now use a constant of the new type...
1211 std::vector<Constant*> C;
1212 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1213 C.push_back(cast<Constant>(OldC->getOperand(i)));
1214 Constant *New = ConstantStruct::get(NewTy, C);
1215 assert(New != OldC && "Didn't replace constant??");
Misha Brukmanb1c93172005-04-21 23:48:37 +00001216
Chris Lattner189d19f2003-11-21 20:23:48 +00001217 OldC->uncheckedReplaceAllUsesWith(New);
1218 OldC->destroyConstant(); // This constant is now dead, destroy it.
1219 }
1220 };
1221}
Chris Lattnerb50d1352003-10-05 00:17:43 +00001222
Chris Lattner8760ec72005-10-04 01:17:50 +00001223typedef ValueMap<std::vector<Constant*>, StructType,
Chris Lattner935aa922005-10-04 17:48:46 +00001224 ConstantStruct, true /*largekey*/> StructConstantsTy;
Chris Lattner69edc982006-09-28 00:35:06 +00001225static ManagedStatic<StructConstantsTy> StructConstants;
Chris Lattner49d855c2001-09-07 16:46:31 +00001226
Chris Lattner3e650af2004-08-04 04:48:01 +00001227static std::vector<Constant*> getValType(ConstantStruct *CS) {
1228 std::vector<Constant*> Elements;
1229 Elements.reserve(CS->getNumOperands());
1230 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1231 Elements.push_back(cast<Constant>(CS->getOperand(i)));
1232 return Elements;
1233}
1234
Chris Lattner015e8212004-02-15 04:14:47 +00001235Constant *ConstantStruct::get(const StructType *Ty,
1236 const std::vector<Constant*> &V) {
Chris Lattner9fba3da2004-02-15 05:53:04 +00001237 // Create a ConstantAggregateZero value if all elements are zeros...
1238 for (unsigned i = 0, e = V.size(); i != e; ++i)
1239 if (!V[i]->isNullValue())
Chris Lattner69edc982006-09-28 00:35:06 +00001240 return StructConstants->getOrCreate(Ty, V);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001241
1242 return ConstantAggregateZero::get(Ty);
Chris Lattner49d855c2001-09-07 16:46:31 +00001243}
Chris Lattner883ad0b2001-10-03 15:39:36 +00001244
Andrew Lenharthdcb3c972006-12-08 18:06:16 +00001245Constant *ConstantStruct::get(const std::vector<Constant*> &V, bool packed) {
Chris Lattnerd6108ca2004-07-12 20:35:11 +00001246 std::vector<const Type*> StructEls;
1247 StructEls.reserve(V.size());
1248 for (unsigned i = 0, e = V.size(); i != e; ++i)
1249 StructEls.push_back(V[i]->getType());
Andrew Lenharthdcb3c972006-12-08 18:06:16 +00001250 return get(StructType::get(StructEls, packed), V);
Chris Lattnerd6108ca2004-07-12 20:35:11 +00001251}
1252
Chris Lattnerd7a73302001-10-13 06:57:33 +00001253// destroyConstant - Remove the constant from the constant table...
Chris Lattner883ad0b2001-10-03 15:39:36 +00001254//
Chris Lattner3462ae32001-12-03 22:26:30 +00001255void ConstantStruct::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001256 StructConstants->remove(this);
Chris Lattnerd7a73302001-10-13 06:57:33 +00001257 destroyConstantImpl();
1258}
Chris Lattner883ad0b2001-10-03 15:39:36 +00001259
Reid Spencerd84d35b2007-02-15 02:26:10 +00001260//---- ConstantVector::get() implementation...
Brian Gaeke02209042004-08-20 06:00:58 +00001261//
1262namespace llvm {
1263 template<>
Reid Spencerd84d35b2007-02-15 02:26:10 +00001264 struct ConvertConstantType<ConstantVector, VectorType> {
1265 static void convert(ConstantVector *OldC, const VectorType *NewTy) {
Brian Gaeke02209042004-08-20 06:00:58 +00001266 // Make everyone now use a constant of the new type...
1267 std::vector<Constant*> C;
1268 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1269 C.push_back(cast<Constant>(OldC->getOperand(i)));
Reid Spencerd84d35b2007-02-15 02:26:10 +00001270 Constant *New = ConstantVector::get(NewTy, C);
Brian Gaeke02209042004-08-20 06:00:58 +00001271 assert(New != OldC && "Didn't replace constant??");
1272 OldC->uncheckedReplaceAllUsesWith(New);
1273 OldC->destroyConstant(); // This constant is now dead, destroy it.
1274 }
1275 };
1276}
1277
Reid Spencerd84d35b2007-02-15 02:26:10 +00001278static std::vector<Constant*> getValType(ConstantVector *CP) {
Brian Gaeke02209042004-08-20 06:00:58 +00001279 std::vector<Constant*> Elements;
1280 Elements.reserve(CP->getNumOperands());
1281 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1282 Elements.push_back(CP->getOperand(i));
1283 return Elements;
1284}
1285
Reid Spencerd84d35b2007-02-15 02:26:10 +00001286static ManagedStatic<ValueMap<std::vector<Constant*>, VectorType,
Reid Spencer09575ba2007-02-15 03:39:18 +00001287 ConstantVector> > VectorConstants;
Brian Gaeke02209042004-08-20 06:00:58 +00001288
Reid Spencerd84d35b2007-02-15 02:26:10 +00001289Constant *ConstantVector::get(const VectorType *Ty,
Brian Gaeke02209042004-08-20 06:00:58 +00001290 const std::vector<Constant*> &V) {
Dan Gohman30978072007-05-24 14:36:04 +00001291 // If this is an all-zero vector, return a ConstantAggregateZero object
Brian Gaeke02209042004-08-20 06:00:58 +00001292 if (!V.empty()) {
1293 Constant *C = V[0];
1294 if (!C->isNullValue())
Reid Spencer09575ba2007-02-15 03:39:18 +00001295 return VectorConstants->getOrCreate(Ty, V);
Brian Gaeke02209042004-08-20 06:00:58 +00001296 for (unsigned i = 1, e = V.size(); i != e; ++i)
1297 if (V[i] != C)
Reid Spencer09575ba2007-02-15 03:39:18 +00001298 return VectorConstants->getOrCreate(Ty, V);
Brian Gaeke02209042004-08-20 06:00:58 +00001299 }
1300 return ConstantAggregateZero::get(Ty);
1301}
1302
Reid Spencerd84d35b2007-02-15 02:26:10 +00001303Constant *ConstantVector::get(const std::vector<Constant*> &V) {
Brian Gaeke02209042004-08-20 06:00:58 +00001304 assert(!V.empty() && "Cannot infer type if V is empty");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001305 return get(VectorType::get(V.front()->getType(),V.size()), V);
Brian Gaeke02209042004-08-20 06:00:58 +00001306}
1307
1308// destroyConstant - Remove the constant from the constant table...
1309//
Reid Spencerd84d35b2007-02-15 02:26:10 +00001310void ConstantVector::destroyConstant() {
Reid Spencer09575ba2007-02-15 03:39:18 +00001311 VectorConstants->remove(this);
Brian Gaeke02209042004-08-20 06:00:58 +00001312 destroyConstantImpl();
1313}
1314
Dan Gohman30978072007-05-24 14:36:04 +00001315/// This function will return true iff every element in this vector constant
Jim Laskeyf0478822007-01-12 22:39:14 +00001316/// is set to all ones.
1317/// @returns true iff this constant's emements are all set to all ones.
1318/// @brief Determine if the value is all ones.
Reid Spencerd84d35b2007-02-15 02:26:10 +00001319bool ConstantVector::isAllOnesValue() const {
Jim Laskeyf0478822007-01-12 22:39:14 +00001320 // Check out first element.
1321 const Constant *Elt = getOperand(0);
1322 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1323 if (!CI || !CI->isAllOnesValue()) return false;
1324 // Then make sure all remaining elements point to the same value.
1325 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1326 if (getOperand(I) != Elt) return false;
1327 }
1328 return true;
1329}
1330
Dan Gohman07159202007-10-17 17:51:30 +00001331/// getSplatValue - If this is a splat constant, where all of the
1332/// elements have the same value, return that value. Otherwise return null.
1333Constant *ConstantVector::getSplatValue() {
1334 // Check out first element.
1335 Constant *Elt = getOperand(0);
1336 // Then make sure all remaining elements point to the same value.
1337 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1338 if (getOperand(I) != Elt) return 0;
1339 return Elt;
1340}
1341
Chris Lattner3462ae32001-12-03 22:26:30 +00001342//---- ConstantPointerNull::get() implementation...
Chris Lattnerd7a73302001-10-13 06:57:33 +00001343//
Chris Lattner98fa07b2003-05-23 20:03:32 +00001344
Chris Lattner189d19f2003-11-21 20:23:48 +00001345namespace llvm {
1346 // ConstantPointerNull does not take extra "value" argument...
1347 template<class ValType>
1348 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1349 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1350 return new ConstantPointerNull(Ty);
1351 }
1352 };
Chris Lattner98fa07b2003-05-23 20:03:32 +00001353
Chris Lattner189d19f2003-11-21 20:23:48 +00001354 template<>
1355 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1356 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1357 // Make everyone now use a constant of the new type...
1358 Constant *New = ConstantPointerNull::get(NewTy);
1359 assert(New != OldC && "Didn't replace constant??");
1360 OldC->uncheckedReplaceAllUsesWith(New);
1361 OldC->destroyConstant(); // This constant is now dead, destroy it.
1362 }
1363 };
1364}
Chris Lattnerb50d1352003-10-05 00:17:43 +00001365
Chris Lattner69edc982006-09-28 00:35:06 +00001366static ManagedStatic<ValueMap<char, PointerType,
1367 ConstantPointerNull> > NullPtrConstants;
Chris Lattnerd7a73302001-10-13 06:57:33 +00001368
Chris Lattner3e650af2004-08-04 04:48:01 +00001369static char getValType(ConstantPointerNull *) {
1370 return 0;
1371}
1372
1373
Chris Lattner3462ae32001-12-03 22:26:30 +00001374ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
Chris Lattner69edc982006-09-28 00:35:06 +00001375 return NullPtrConstants->getOrCreate(Ty, 0);
Chris Lattner883ad0b2001-10-03 15:39:36 +00001376}
1377
Chris Lattner0c6e0b92002-08-18 00:40:04 +00001378// destroyConstant - Remove the constant from the constant table...
1379//
1380void ConstantPointerNull::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001381 NullPtrConstants->remove(this);
Chris Lattner0c6e0b92002-08-18 00:40:04 +00001382 destroyConstantImpl();
1383}
1384
1385
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001386//---- UndefValue::get() implementation...
1387//
1388
1389namespace llvm {
1390 // UndefValue does not take extra "value" argument...
1391 template<class ValType>
1392 struct ConstantCreator<UndefValue, Type, ValType> {
1393 static UndefValue *create(const Type *Ty, const ValType &V) {
1394 return new UndefValue(Ty);
1395 }
1396 };
1397
1398 template<>
1399 struct ConvertConstantType<UndefValue, Type> {
1400 static void convert(UndefValue *OldC, const Type *NewTy) {
1401 // Make everyone now use a constant of the new type.
1402 Constant *New = UndefValue::get(NewTy);
1403 assert(New != OldC && "Didn't replace constant??");
1404 OldC->uncheckedReplaceAllUsesWith(New);
1405 OldC->destroyConstant(); // This constant is now dead, destroy it.
1406 }
1407 };
1408}
1409
Chris Lattner69edc982006-09-28 00:35:06 +00001410static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001411
1412static char getValType(UndefValue *) {
1413 return 0;
1414}
1415
1416
1417UndefValue *UndefValue::get(const Type *Ty) {
Chris Lattner69edc982006-09-28 00:35:06 +00001418 return UndefValueConstants->getOrCreate(Ty, 0);
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001419}
1420
1421// destroyConstant - Remove the constant from the constant table.
1422//
1423void UndefValue::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001424 UndefValueConstants->remove(this);
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001425 destroyConstantImpl();
1426}
1427
1428
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001429//---- ConstantExpr::get() implementations...
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001430//
Reid Spencer8d9336d2006-12-31 05:26:44 +00001431
Reid Spenceree3c9912006-12-04 05:19:50 +00001432struct ExprMapKeyType {
1433 explicit ExprMapKeyType(unsigned opc, std::vector<Constant*> ops,
Reid Spencerdba6aa42006-12-04 18:38:05 +00001434 unsigned short pred = 0) : opcode(opc), predicate(pred), operands(ops) { }
1435 uint16_t opcode;
1436 uint16_t predicate;
Reid Spenceree3c9912006-12-04 05:19:50 +00001437 std::vector<Constant*> operands;
Reid Spenceree3c9912006-12-04 05:19:50 +00001438 bool operator==(const ExprMapKeyType& that) const {
1439 return this->opcode == that.opcode &&
1440 this->predicate == that.predicate &&
1441 this->operands == that.operands;
1442 }
1443 bool operator<(const ExprMapKeyType & that) const {
1444 return this->opcode < that.opcode ||
1445 (this->opcode == that.opcode && this->predicate < that.predicate) ||
1446 (this->opcode == that.opcode && this->predicate == that.predicate &&
1447 this->operands < that.operands);
1448 }
1449
1450 bool operator!=(const ExprMapKeyType& that) const {
1451 return !(*this == that);
1452 }
1453};
Chris Lattner98fa07b2003-05-23 20:03:32 +00001454
Chris Lattner189d19f2003-11-21 20:23:48 +00001455namespace llvm {
1456 template<>
1457 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
Reid Spencer10fbf0e2006-12-03 05:48:19 +00001458 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1459 unsigned short pred = 0) {
Reid Spenceree3c9912006-12-04 05:19:50 +00001460 if (Instruction::isCast(V.opcode))
1461 return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1462 if ((V.opcode >= Instruction::BinaryOpsBegin &&
Reid Spencer2341c222007-02-02 02:16:23 +00001463 V.opcode < Instruction::BinaryOpsEnd))
Reid Spenceree3c9912006-12-04 05:19:50 +00001464 return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1465 if (V.opcode == Instruction::Select)
1466 return new SelectConstantExpr(V.operands[0], V.operands[1],
1467 V.operands[2]);
1468 if (V.opcode == Instruction::ExtractElement)
1469 return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1470 if (V.opcode == Instruction::InsertElement)
1471 return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1472 V.operands[2]);
1473 if (V.opcode == Instruction::ShuffleVector)
1474 return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1475 V.operands[2]);
1476 if (V.opcode == Instruction::GetElementPtr) {
1477 std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
Gabor Greife9ecc682008-04-06 20:25:17 +00001478 return GetElementPtrConstantExpr::Create(V.operands[0], IdxList, Ty);
Reid Spenceree3c9912006-12-04 05:19:50 +00001479 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001480
Reid Spenceree3c9912006-12-04 05:19:50 +00001481 // The compare instructions are weird. We have to encode the predicate
1482 // value and it is combined with the instruction opcode by multiplying
1483 // the opcode by one hundred. We must decode this to get the predicate.
1484 if (V.opcode == Instruction::ICmp)
1485 return new CompareConstantExpr(Instruction::ICmp, V.predicate,
1486 V.operands[0], V.operands[1]);
1487 if (V.opcode == Instruction::FCmp)
1488 return new CompareConstantExpr(Instruction::FCmp, V.predicate,
1489 V.operands[0], V.operands[1]);
1490 assert(0 && "Invalid ConstantExpr!");
Jeff Cohen9f469632006-12-15 21:47:01 +00001491 return 0;
Chris Lattnerb50d1352003-10-05 00:17:43 +00001492 }
Chris Lattner189d19f2003-11-21 20:23:48 +00001493 };
Chris Lattnerb50d1352003-10-05 00:17:43 +00001494
Chris Lattner189d19f2003-11-21 20:23:48 +00001495 template<>
1496 struct ConvertConstantType<ConstantExpr, Type> {
1497 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1498 Constant *New;
1499 switch (OldC->getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001500 case Instruction::Trunc:
1501 case Instruction::ZExt:
1502 case Instruction::SExt:
1503 case Instruction::FPTrunc:
1504 case Instruction::FPExt:
1505 case Instruction::UIToFP:
1506 case Instruction::SIToFP:
1507 case Instruction::FPToUI:
1508 case Instruction::FPToSI:
1509 case Instruction::PtrToInt:
1510 case Instruction::IntToPtr:
1511 case Instruction::BitCast:
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001512 New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0),
1513 NewTy);
Chris Lattner189d19f2003-11-21 20:23:48 +00001514 break;
Chris Lattner6e415c02004-03-12 05:54:04 +00001515 case Instruction::Select:
1516 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1517 OldC->getOperand(1),
1518 OldC->getOperand(2));
1519 break;
Chris Lattner189d19f2003-11-21 20:23:48 +00001520 default:
1521 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
Reid Spencer7eb55b32006-11-02 01:53:59 +00001522 OldC->getOpcode() < Instruction::BinaryOpsEnd);
Chris Lattner189d19f2003-11-21 20:23:48 +00001523 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1524 OldC->getOperand(1));
1525 break;
1526 case Instruction::GetElementPtr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00001527 // Make everyone now use a constant of the new type...
Chris Lattner13128ab2004-10-11 22:52:25 +00001528 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
Chris Lattner302116a2007-01-31 04:40:28 +00001529 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0),
1530 &Idx[0], Idx.size());
Chris Lattner189d19f2003-11-21 20:23:48 +00001531 break;
1532 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001533
Chris Lattner189d19f2003-11-21 20:23:48 +00001534 assert(New != OldC && "Didn't replace constant??");
1535 OldC->uncheckedReplaceAllUsesWith(New);
1536 OldC->destroyConstant(); // This constant is now dead, destroy it.
1537 }
1538 };
1539} // end namespace llvm
Chris Lattnerb50d1352003-10-05 00:17:43 +00001540
1541
Chris Lattner3e650af2004-08-04 04:48:01 +00001542static ExprMapKeyType getValType(ConstantExpr *CE) {
1543 std::vector<Constant*> Operands;
1544 Operands.reserve(CE->getNumOperands());
1545 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1546 Operands.push_back(cast<Constant>(CE->getOperand(i)));
Reid Spenceree3c9912006-12-04 05:19:50 +00001547 return ExprMapKeyType(CE->getOpcode(), Operands,
1548 CE->isCompare() ? CE->getPredicate() : 0);
Chris Lattner3e650af2004-08-04 04:48:01 +00001549}
1550
Chris Lattner69edc982006-09-28 00:35:06 +00001551static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1552 ConstantExpr> > ExprConstants;
Vikram S. Adve4c485332002-07-15 18:19:33 +00001553
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001554/// This is a utility function to handle folding of casts and lookup of the
Duncan Sands7d6c8ae2008-03-30 19:38:55 +00001555/// cast in the ExprConstants map. It is used by the various get* methods below.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001556static inline Constant *getFoldedCast(
1557 Instruction::CastOps opc, Constant *C, const Type *Ty) {
Chris Lattner815ae2b2003-10-07 22:19:19 +00001558 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001559 // Fold a few common cases
1560 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1561 return FC;
Chris Lattneracdbe712003-04-17 19:24:48 +00001562
Vikram S. Adve4c485332002-07-15 18:19:33 +00001563 // Look up the constant in the table first to ensure uniqueness
Chris Lattner2b383d2e2003-05-13 21:37:02 +00001564 std::vector<Constant*> argVec(1, C);
Reid Spenceree3c9912006-12-04 05:19:50 +00001565 ExprMapKeyType Key(opc, argVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001566 return ExprConstants->getOrCreate(Ty, Key);
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001567}
Reid Spencerf37dc652006-12-05 19:14:13 +00001568
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001569Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1570 Instruction::CastOps opc = Instruction::CastOps(oc);
1571 assert(Instruction::isCast(opc) && "opcode out of range");
1572 assert(C && Ty && "Null arguments to getCast");
1573 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1574
1575 switch (opc) {
1576 default:
1577 assert(0 && "Invalid cast opcode");
1578 break;
1579 case Instruction::Trunc: return getTrunc(C, Ty);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001580 case Instruction::ZExt: return getZExt(C, Ty);
1581 case Instruction::SExt: return getSExt(C, Ty);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001582 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1583 case Instruction::FPExt: return getFPExtend(C, Ty);
1584 case Instruction::UIToFP: return getUIToFP(C, Ty);
1585 case Instruction::SIToFP: return getSIToFP(C, Ty);
1586 case Instruction::FPToUI: return getFPToUI(C, Ty);
1587 case Instruction::FPToSI: return getFPToSI(C, Ty);
1588 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1589 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1590 case Instruction::BitCast: return getBitCast(C, Ty);
Chris Lattner1ece6f82005-01-01 15:59:57 +00001591 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001592 return 0;
Reid Spencerf37dc652006-12-05 19:14:13 +00001593}
1594
Reid Spencer5c140882006-12-04 20:17:56 +00001595Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1596 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1597 return getCast(Instruction::BitCast, C, Ty);
1598 return getCast(Instruction::ZExt, C, Ty);
1599}
1600
1601Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1602 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1603 return getCast(Instruction::BitCast, C, Ty);
1604 return getCast(Instruction::SExt, C, Ty);
1605}
1606
1607Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1608 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1609 return getCast(Instruction::BitCast, C, Ty);
1610 return getCast(Instruction::Trunc, C, Ty);
1611}
1612
Reid Spencerbc245a02006-12-05 03:25:26 +00001613Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1614 assert(isa<PointerType>(S->getType()) && "Invalid cast");
Chris Lattner03c49532007-01-15 02:27:26 +00001615 assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
Reid Spencerbc245a02006-12-05 03:25:26 +00001616
Chris Lattner03c49532007-01-15 02:27:26 +00001617 if (Ty->isInteger())
Reid Spencerbc245a02006-12-05 03:25:26 +00001618 return getCast(Instruction::PtrToInt, S, Ty);
1619 return getCast(Instruction::BitCast, S, Ty);
1620}
1621
Reid Spencer56521c42006-12-12 00:51:07 +00001622Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
1623 bool isSigned) {
Chris Lattner03c49532007-01-15 02:27:26 +00001624 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
Reid Spencer56521c42006-12-12 00:51:07 +00001625 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1626 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1627 Instruction::CastOps opcode =
1628 (SrcBits == DstBits ? Instruction::BitCast :
1629 (SrcBits > DstBits ? Instruction::Trunc :
1630 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1631 return getCast(opcode, C, Ty);
1632}
1633
1634Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1635 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1636 "Invalid cast");
1637 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1638 unsigned DstBits = Ty->getPrimitiveSizeInBits();
Reid Spencerca104e82006-12-12 05:38:50 +00001639 if (SrcBits == DstBits)
1640 return C; // Avoid a useless cast
Reid Spencer56521c42006-12-12 00:51:07 +00001641 Instruction::CastOps opcode =
Reid Spencerca104e82006-12-12 05:38:50 +00001642 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
Reid Spencer56521c42006-12-12 00:51:07 +00001643 return getCast(opcode, C, Ty);
1644}
1645
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001646Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
Chris Lattner03c49532007-01-15 02:27:26 +00001647 assert(C->getType()->isInteger() && "Trunc operand must be integer");
1648 assert(Ty->isInteger() && "Trunc produces only integral");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001649 assert(C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1650 "SrcTy must be larger than DestTy for Trunc!");
1651
1652 return getFoldedCast(Instruction::Trunc, C, Ty);
1653}
1654
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001655Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
Chris Lattner03c49532007-01-15 02:27:26 +00001656 assert(C->getType()->isInteger() && "SEXt operand must be integral");
1657 assert(Ty->isInteger() && "SExt produces only integer");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001658 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1659 "SrcTy must be smaller than DestTy for SExt!");
1660
1661 return getFoldedCast(Instruction::SExt, C, Ty);
Chris Lattnerdd284742004-04-04 23:20:30 +00001662}
1663
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001664Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
Chris Lattner03c49532007-01-15 02:27:26 +00001665 assert(C->getType()->isInteger() && "ZEXt operand must be integral");
1666 assert(Ty->isInteger() && "ZExt produces only integer");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001667 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1668 "SrcTy must be smaller than DestTy for ZExt!");
1669
1670 return getFoldedCast(Instruction::ZExt, C, Ty);
1671}
1672
1673Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1674 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1675 C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1676 "This is an illegal floating point truncation!");
1677 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1678}
1679
1680Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1681 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1682 C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1683 "This is an illegal floating point extension!");
1684 return getFoldedCast(Instruction::FPExt, C, Ty);
1685}
1686
1687Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
Nate Begemand4d45c22007-11-17 03:58:34 +00001688 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1689 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1690 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1691 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1692 "This is an illegal uint to floating point cast!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001693 return getFoldedCast(Instruction::UIToFP, C, Ty);
1694}
1695
1696Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
Nate Begemand4d45c22007-11-17 03:58:34 +00001697 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1698 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1699 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1700 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001701 "This is an illegal sint to floating point cast!");
1702 return getFoldedCast(Instruction::SIToFP, C, Ty);
1703}
1704
1705Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
Nate Begemand4d45c22007-11-17 03:58:34 +00001706 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1707 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1708 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1709 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1710 "This is an illegal floating point to uint cast!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001711 return getFoldedCast(Instruction::FPToUI, C, Ty);
1712}
1713
1714Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
Nate Begemand4d45c22007-11-17 03:58:34 +00001715 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1716 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1717 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1718 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1719 "This is an illegal floating point to sint cast!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001720 return getFoldedCast(Instruction::FPToSI, C, Ty);
1721}
1722
1723Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1724 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
Chris Lattner03c49532007-01-15 02:27:26 +00001725 assert(DstTy->isInteger() && "PtrToInt destination must be integral");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001726 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1727}
1728
1729Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
Chris Lattner03c49532007-01-15 02:27:26 +00001730 assert(C->getType()->isInteger() && "IntToPtr source must be integral");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001731 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
1732 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1733}
1734
1735Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1736 // BitCast implies a no-op cast of type only. No bits change. However, you
1737 // can't cast pointers to anything but pointers.
1738 const Type *SrcTy = C->getType();
1739 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
Reid Spencer5c140882006-12-04 20:17:56 +00001740 "BitCast cannot cast pointer to non-pointer and vice versa");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001741
1742 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
1743 // or nonptr->ptr). For all the other types, the cast is okay if source and
1744 // destination bit widths are identical.
1745 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1746 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
Reid Spencer5c140882006-12-04 20:17:56 +00001747 assert(SrcBitSize == DstBitSize && "BitCast requies types of same width");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001748 return getFoldedCast(Instruction::BitCast, C, DstTy);
Chris Lattnerdd284742004-04-04 23:20:30 +00001749}
1750
Alkis Evlogimenosda5de052004-10-24 01:41:10 +00001751Constant *ConstantExpr::getSizeOf(const Type *Ty) {
Gordon Henriksen7ce31762007-10-06 14:29:36 +00001752 // sizeof is implemented as: (i64) gep (Ty*)null, 1
Chris Lattnerb5d70302007-02-19 20:01:23 +00001753 Constant *GEPIdx = ConstantInt::get(Type::Int32Ty, 1);
1754 Constant *GEP =
Christopher Lambedf07882007-12-17 01:12:55 +00001755 getGetElementPtr(getNullValue(PointerType::getUnqual(Ty)), &GEPIdx, 1);
Chris Lattnerb5d70302007-02-19 20:01:23 +00001756 return getCast(Instruction::PtrToInt, GEP, Type::Int64Ty);
Alkis Evlogimenos9160d5f2005-03-19 11:40:31 +00001757}
1758
Chris Lattnerb50d1352003-10-05 00:17:43 +00001759Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
Reid Spencera009d0d2006-12-04 21:35:24 +00001760 Constant *C1, Constant *C2) {
Chris Lattner38a9bcd2003-05-21 17:49:25 +00001761 // Check the operands for consistency first
Reid Spencer7eb55b32006-11-02 01:53:59 +00001762 assert(Opcode >= Instruction::BinaryOpsBegin &&
1763 Opcode < Instruction::BinaryOpsEnd &&
Chris Lattner38a9bcd2003-05-21 17:49:25 +00001764 "Invalid opcode in binary constant expression");
1765 assert(C1->getType() == C2->getType() &&
1766 "Operand types in binary constant expression should match");
Chris Lattnerb50d1352003-10-05 00:17:43 +00001767
Reid Spencer542964f2007-01-11 18:21:29 +00001768 if (ReqTy == C1->getType() || ReqTy == Type::Int1Ty)
Chris Lattnerb50d1352003-10-05 00:17:43 +00001769 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1770 return FC; // Fold a few common cases...
Chris Lattneracdbe712003-04-17 19:24:48 +00001771
Chris Lattner2b383d2e2003-05-13 21:37:02 +00001772 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
Reid Spencera009d0d2006-12-04 21:35:24 +00001773 ExprMapKeyType Key(Opcode, argVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001774 return ExprConstants->getOrCreate(ReqTy, Key);
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001775}
1776
Reid Spencer266e42b2006-12-23 06:05:41 +00001777Constant *ConstantExpr::getCompareTy(unsigned short predicate,
Reid Spencera009d0d2006-12-04 21:35:24 +00001778 Constant *C1, Constant *C2) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001779 switch (predicate) {
1780 default: assert(0 && "Invalid CmpInst predicate");
1781 case FCmpInst::FCMP_FALSE: case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_OGT:
1782 case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OLE:
1783 case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_ORD: case FCmpInst::FCMP_UNO:
1784 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UGT: case FCmpInst::FCMP_UGE:
1785 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_ULE: case FCmpInst::FCMP_UNE:
1786 case FCmpInst::FCMP_TRUE:
1787 return getFCmp(predicate, C1, C2);
1788 case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGT:
1789 case ICmpInst::ICMP_UGE: case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE:
1790 case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_SGE: case ICmpInst::ICMP_SLT:
1791 case ICmpInst::ICMP_SLE:
1792 return getICmp(predicate, C1, C2);
1793 }
Reid Spencera009d0d2006-12-04 21:35:24 +00001794}
1795
1796Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001797#ifndef NDEBUG
1798 switch (Opcode) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00001799 case Instruction::Add:
1800 case Instruction::Sub:
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001801 case Instruction::Mul:
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001802 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Chris Lattner03c49532007-01-15 02:27:26 +00001803 assert((C1->getType()->isInteger() || C1->getType()->isFloatingPoint() ||
Reid Spencerd84d35b2007-02-15 02:26:10 +00001804 isa<VectorType>(C1->getType())) &&
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001805 "Tried to create an arithmetic operation on a non-arithmetic type!");
1806 break;
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001807 case Instruction::UDiv:
1808 case Instruction::SDiv:
1809 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001810 assert((C1->getType()->isInteger() || (isa<VectorType>(C1->getType()) &&
1811 cast<VectorType>(C1->getType())->getElementType()->isInteger())) &&
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001812 "Tried to create an arithmetic operation on a non-arithmetic type!");
1813 break;
1814 case Instruction::FDiv:
1815 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001816 assert((C1->getType()->isFloatingPoint() || (isa<VectorType>(C1->getType())
1817 && cast<VectorType>(C1->getType())->getElementType()->isFloatingPoint()))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001818 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1819 break;
Reid Spencer7eb55b32006-11-02 01:53:59 +00001820 case Instruction::URem:
1821 case Instruction::SRem:
1822 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001823 assert((C1->getType()->isInteger() || (isa<VectorType>(C1->getType()) &&
1824 cast<VectorType>(C1->getType())->getElementType()->isInteger())) &&
Reid Spencer7eb55b32006-11-02 01:53:59 +00001825 "Tried to create an arithmetic operation on a non-arithmetic type!");
1826 break;
1827 case Instruction::FRem:
1828 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001829 assert((C1->getType()->isFloatingPoint() || (isa<VectorType>(C1->getType())
1830 && cast<VectorType>(C1->getType())->getElementType()->isFloatingPoint()))
Reid Spencer7eb55b32006-11-02 01:53:59 +00001831 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1832 break;
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001833 case Instruction::And:
1834 case Instruction::Or:
1835 case Instruction::Xor:
1836 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001837 assert((C1->getType()->isInteger() || isa<VectorType>(C1->getType())) &&
Misha Brukman3852f652005-01-27 06:46:38 +00001838 "Tried to create a logical operation on a non-integral type!");
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001839 break;
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001840 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00001841 case Instruction::LShr:
1842 case Instruction::AShr:
Reid Spencer2341c222007-02-02 02:16:23 +00001843 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Chris Lattner03c49532007-01-15 02:27:26 +00001844 assert(C1->getType()->isInteger() &&
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001845 "Tried to create a shift operation on a non-integer type!");
1846 break;
1847 default:
1848 break;
1849 }
1850#endif
1851
Reid Spencera009d0d2006-12-04 21:35:24 +00001852 return getTy(C1->getType(), Opcode, C1, C2);
1853}
1854
Reid Spencer266e42b2006-12-23 06:05:41 +00001855Constant *ConstantExpr::getCompare(unsigned short pred,
Reid Spencera009d0d2006-12-04 21:35:24 +00001856 Constant *C1, Constant *C2) {
1857 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencer266e42b2006-12-23 06:05:41 +00001858 return getCompareTy(pred, C1, C2);
Chris Lattner29ca2c62004-08-04 18:50:09 +00001859}
1860
Chris Lattner6e415c02004-03-12 05:54:04 +00001861Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1862 Constant *V1, Constant *V2) {
Reid Spencer2546b762007-01-26 07:37:34 +00001863 assert(C->getType() == Type::Int1Ty && "Select condition must be i1!");
Chris Lattner6e415c02004-03-12 05:54:04 +00001864 assert(V1->getType() == V2->getType() && "Select value types must match!");
1865 assert(V1->getType()->isFirstClassType() && "Cannot select aggregate type!");
1866
1867 if (ReqTy == V1->getType())
1868 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1869 return SC; // Fold common cases
1870
1871 std::vector<Constant*> argVec(3, C);
1872 argVec[1] = V1;
1873 argVec[2] = V2;
Reid Spenceree3c9912006-12-04 05:19:50 +00001874 ExprMapKeyType Key(Instruction::Select, argVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001875 return ExprConstants->getOrCreate(ReqTy, Key);
Chris Lattner6e415c02004-03-12 05:54:04 +00001876}
1877
Chris Lattnerb50d1352003-10-05 00:17:43 +00001878Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
Chris Lattner302116a2007-01-31 04:40:28 +00001879 Value* const *Idxs,
1880 unsigned NumIdx) {
David Greenec656cbb2007-09-04 15:46:09 +00001881 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx, true) &&
Chris Lattner04b60fe2004-02-16 20:46:13 +00001882 "GEP indices invalid!");
1883
Chris Lattner302116a2007-01-31 04:40:28 +00001884 if (Constant *FC = ConstantFoldGetElementPtr(C, (Constant**)Idxs, NumIdx))
Chris Lattneracdbe712003-04-17 19:24:48 +00001885 return FC; // Fold a few common cases...
Chris Lattner04b60fe2004-02-16 20:46:13 +00001886
Chris Lattnerb50d1352003-10-05 00:17:43 +00001887 assert(isa<PointerType>(C->getType()) &&
Chris Lattner98fa07b2003-05-23 20:03:32 +00001888 "Non-pointer type for constant GetElementPtr expression");
Vikram S. Adve4c485332002-07-15 18:19:33 +00001889 // Look up the constant in the table first to ensure uniqueness
Chris Lattner13128ab2004-10-11 22:52:25 +00001890 std::vector<Constant*> ArgVec;
Chris Lattner302116a2007-01-31 04:40:28 +00001891 ArgVec.reserve(NumIdx+1);
Chris Lattner13128ab2004-10-11 22:52:25 +00001892 ArgVec.push_back(C);
Chris Lattner302116a2007-01-31 04:40:28 +00001893 for (unsigned i = 0; i != NumIdx; ++i)
1894 ArgVec.push_back(cast<Constant>(Idxs[i]));
1895 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001896 return ExprConstants->getOrCreate(ReqTy, Key);
Vikram S. Adve4c485332002-07-15 18:19:33 +00001897}
1898
Chris Lattner302116a2007-01-31 04:40:28 +00001899Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
1900 unsigned NumIdx) {
Chris Lattnerb50d1352003-10-05 00:17:43 +00001901 // Get the result type of the getelementptr!
Chris Lattner302116a2007-01-31 04:40:28 +00001902 const Type *Ty =
David Greenec656cbb2007-09-04 15:46:09 +00001903 GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx, true);
Chris Lattnerb50d1352003-10-05 00:17:43 +00001904 assert(Ty && "GEP indices invalid!");
Christopher Lamb54dd24c2007-12-11 08:59:05 +00001905 unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
1906 return getGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx);
Chris Lattner13128ab2004-10-11 22:52:25 +00001907}
1908
Chris Lattner302116a2007-01-31 04:40:28 +00001909Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
1910 unsigned NumIdx) {
1911 return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
Chris Lattnerb50d1352003-10-05 00:17:43 +00001912}
1913
Chris Lattner302116a2007-01-31 04:40:28 +00001914
Reid Spenceree3c9912006-12-04 05:19:50 +00001915Constant *
1916ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1917 assert(LHS->getType() == RHS->getType());
1918 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
1919 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1920
Reid Spencer266e42b2006-12-23 06:05:41 +00001921 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
Reid Spenceree3c9912006-12-04 05:19:50 +00001922 return FC; // Fold a few common cases...
1923
1924 // Look up the constant in the table first to ensure uniqueness
1925 std::vector<Constant*> ArgVec;
1926 ArgVec.push_back(LHS);
1927 ArgVec.push_back(RHS);
Reid Spencerb1537492006-12-24 18:42:29 +00001928 // Get the key type with both the opcode and predicate
Reid Spenceree3c9912006-12-04 05:19:50 +00001929 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
Reid Spencer542964f2007-01-11 18:21:29 +00001930 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
Reid Spenceree3c9912006-12-04 05:19:50 +00001931}
1932
1933Constant *
1934ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1935 assert(LHS->getType() == RHS->getType());
1936 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1937
Reid Spencer266e42b2006-12-23 06:05:41 +00001938 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
Reid Spenceree3c9912006-12-04 05:19:50 +00001939 return FC; // Fold a few common cases...
1940
1941 // Look up the constant in the table first to ensure uniqueness
1942 std::vector<Constant*> ArgVec;
1943 ArgVec.push_back(LHS);
1944 ArgVec.push_back(RHS);
Reid Spencerb1537492006-12-24 18:42:29 +00001945 // Get the key type with both the opcode and predicate
Reid Spenceree3c9912006-12-04 05:19:50 +00001946 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
Reid Spencer542964f2007-01-11 18:21:29 +00001947 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
Reid Spenceree3c9912006-12-04 05:19:50 +00001948}
1949
Robert Bocchino23004482006-01-10 19:05:34 +00001950Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
1951 Constant *Idx) {
Robert Bocchinode7f1c92006-01-10 20:03:46 +00001952 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
1953 return FC; // Fold a few common cases...
Robert Bocchino23004482006-01-10 19:05:34 +00001954 // Look up the constant in the table first to ensure uniqueness
1955 std::vector<Constant*> ArgVec(1, Val);
1956 ArgVec.push_back(Idx);
Reid Spenceree3c9912006-12-04 05:19:50 +00001957 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001958 return ExprConstants->getOrCreate(ReqTy, Key);
Robert Bocchino23004482006-01-10 19:05:34 +00001959}
1960
1961Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001962 assert(isa<VectorType>(Val->getType()) &&
Reid Spencer09575ba2007-02-15 03:39:18 +00001963 "Tried to create extractelement operation on non-vector type!");
Reid Spencer8d9336d2006-12-31 05:26:44 +00001964 assert(Idx->getType() == Type::Int32Ty &&
Reid Spencer2546b762007-01-26 07:37:34 +00001965 "Extractelement index must be i32 type!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001966 return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
Robert Bocchino23004482006-01-10 19:05:34 +00001967 Val, Idx);
1968}
Chris Lattnerb50d1352003-10-05 00:17:43 +00001969
Robert Bocchinoca27f032006-01-17 20:07:22 +00001970Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
1971 Constant *Elt, Constant *Idx) {
1972 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
1973 return FC; // Fold a few common cases...
1974 // Look up the constant in the table first to ensure uniqueness
1975 std::vector<Constant*> ArgVec(1, Val);
1976 ArgVec.push_back(Elt);
1977 ArgVec.push_back(Idx);
Reid Spenceree3c9912006-12-04 05:19:50 +00001978 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001979 return ExprConstants->getOrCreate(ReqTy, Key);
Robert Bocchinoca27f032006-01-17 20:07:22 +00001980}
1981
1982Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1983 Constant *Idx) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001984 assert(isa<VectorType>(Val->getType()) &&
Reid Spencer09575ba2007-02-15 03:39:18 +00001985 "Tried to create insertelement operation on non-vector type!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001986 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
Robert Bocchinoca27f032006-01-17 20:07:22 +00001987 && "Insertelement types must match!");
Reid Spencer8d9336d2006-12-31 05:26:44 +00001988 assert(Idx->getType() == Type::Int32Ty &&
Reid Spencer2546b762007-01-26 07:37:34 +00001989 "Insertelement index must be i32 type!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001990 return getInsertElementTy(cast<VectorType>(Val->getType())->getElementType(),
Robert Bocchinoca27f032006-01-17 20:07:22 +00001991 Val, Elt, Idx);
1992}
1993
Chris Lattnerbbe0a422006-04-08 01:18:18 +00001994Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
1995 Constant *V2, Constant *Mask) {
1996 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
1997 return FC; // Fold a few common cases...
1998 // Look up the constant in the table first to ensure uniqueness
1999 std::vector<Constant*> ArgVec(1, V1);
2000 ArgVec.push_back(V2);
2001 ArgVec.push_back(Mask);
Reid Spenceree3c9912006-12-04 05:19:50 +00002002 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
Chris Lattner69edc982006-09-28 00:35:06 +00002003 return ExprConstants->getOrCreate(ReqTy, Key);
Chris Lattnerbbe0a422006-04-08 01:18:18 +00002004}
2005
2006Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
2007 Constant *Mask) {
2008 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
2009 "Invalid shuffle vector constant expr operands!");
2010 return getShuffleVectorTy(V1->getType(), V1, V2, Mask);
2011}
2012
Reid Spencer2eadb532007-01-21 00:29:26 +00002013Constant *ConstantExpr::getZeroValueForNegationExpr(const Type *Ty) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00002014 if (const VectorType *PTy = dyn_cast<VectorType>(Ty))
Reid Spencer6598ca82007-01-21 02:29:10 +00002015 if (PTy->getElementType()->isFloatingPoint()) {
2016 std::vector<Constant*> zeros(PTy->getNumElements(),
Dale Johannesen98d3a082007-09-14 22:26:36 +00002017 ConstantFP::getNegativeZero(PTy->getElementType()));
Reid Spencerd84d35b2007-02-15 02:26:10 +00002018 return ConstantVector::get(PTy, zeros);
Reid Spencer6598ca82007-01-21 02:29:10 +00002019 }
Reid Spencer2eadb532007-01-21 00:29:26 +00002020
Dale Johannesen98d3a082007-09-14 22:26:36 +00002021 if (Ty->isFloatingPoint())
2022 return ConstantFP::getNegativeZero(Ty);
Reid Spencer2eadb532007-01-21 00:29:26 +00002023
2024 return Constant::getNullValue(Ty);
2025}
2026
Vikram S. Adve4c485332002-07-15 18:19:33 +00002027// destroyConstant - Remove the constant from the constant table...
2028//
2029void ConstantExpr::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00002030 ExprConstants->remove(this);
Vikram S. Adve4c485332002-07-15 18:19:33 +00002031 destroyConstantImpl();
Vikram S. Adve4e537b22002-07-14 23:13:17 +00002032}
2033
Chris Lattner3cd8c562002-07-30 18:54:25 +00002034const char *ConstantExpr::getOpcodeName() const {
2035 return Instruction::getOpcodeName(getOpcode());
Vikram S. Adve4e537b22002-07-14 23:13:17 +00002036}
Reid Spencer1ebe1ab2004-07-17 23:48:33 +00002037
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002038//===----------------------------------------------------------------------===//
2039// replaceUsesOfWithOnConstant implementations
2040
Chris Lattner913849b2007-08-21 00:55:23 +00002041/// replaceUsesOfWithOnConstant - Update this constant array to change uses of
2042/// 'From' to be uses of 'To'. This must update the uniquing data structures
2043/// etc.
2044///
2045/// Note that we intentionally replace all uses of From with To here. Consider
2046/// a large array that uses 'From' 1000 times. By handling this case all here,
2047/// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
2048/// single invocation handles all 1000 uses. Handling them one at a time would
2049/// work, but would be really slow because it would have to unique each updated
2050/// array instance.
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002051void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002052 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002053 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
Chris Lattner8760ec72005-10-04 01:17:50 +00002054 Constant *ToC = cast<Constant>(To);
Chris Lattnerdff59112005-10-04 18:47:09 +00002055
Jim Laskeyc03caef2006-07-17 17:38:29 +00002056 std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
Chris Lattnerb64419a2005-10-03 22:51:37 +00002057 Lookup.first.first = getType();
2058 Lookup.second = this;
Chris Lattnerdff59112005-10-04 18:47:09 +00002059
Chris Lattnerb64419a2005-10-03 22:51:37 +00002060 std::vector<Constant*> &Values = Lookup.first.second;
2061 Values.reserve(getNumOperands()); // Build replacement array.
Chris Lattnerdff59112005-10-04 18:47:09 +00002062
Chris Lattner8760ec72005-10-04 01:17:50 +00002063 // Fill values with the modified operands of the constant array. Also,
2064 // compute whether this turns into an all-zeros array.
Chris Lattnerdff59112005-10-04 18:47:09 +00002065 bool isAllZeros = false;
Chris Lattner913849b2007-08-21 00:55:23 +00002066 unsigned NumUpdated = 0;
Chris Lattnerdff59112005-10-04 18:47:09 +00002067 if (!ToC->isNullValue()) {
Chris Lattner913849b2007-08-21 00:55:23 +00002068 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2069 Constant *Val = cast<Constant>(O->get());
2070 if (Val == From) {
2071 Val = ToC;
2072 ++NumUpdated;
2073 }
2074 Values.push_back(Val);
2075 }
Chris Lattnerdff59112005-10-04 18:47:09 +00002076 } else {
2077 isAllZeros = true;
2078 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2079 Constant *Val = cast<Constant>(O->get());
Chris Lattner913849b2007-08-21 00:55:23 +00002080 if (Val == From) {
2081 Val = ToC;
2082 ++NumUpdated;
2083 }
Chris Lattnerdff59112005-10-04 18:47:09 +00002084 Values.push_back(Val);
2085 if (isAllZeros) isAllZeros = Val->isNullValue();
2086 }
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002087 }
2088
Chris Lattnerb64419a2005-10-03 22:51:37 +00002089 Constant *Replacement = 0;
2090 if (isAllZeros) {
2091 Replacement = ConstantAggregateZero::get(getType());
2092 } else {
2093 // Check to see if we have this array type already.
2094 bool Exists;
Jim Laskeyc03caef2006-07-17 17:38:29 +00002095 ArrayConstantsTy::MapTy::iterator I =
Chris Lattner69edc982006-09-28 00:35:06 +00002096 ArrayConstants->InsertOrGetItem(Lookup, Exists);
Chris Lattnerb64419a2005-10-03 22:51:37 +00002097
2098 if (Exists) {
2099 Replacement = I->second;
2100 } else {
2101 // Okay, the new shape doesn't exist in the system yet. Instead of
2102 // creating a new constant array, inserting it, replaceallusesof'ing the
2103 // old with the new, then deleting the old... just update the current one
2104 // in place!
Chris Lattner69edc982006-09-28 00:35:06 +00002105 ArrayConstants->MoveConstantToNewSlot(this, I);
Chris Lattnerb64419a2005-10-03 22:51:37 +00002106
Chris Lattner913849b2007-08-21 00:55:23 +00002107 // Update to the new value. Optimize for the case when we have a single
2108 // operand that we're changing, but handle bulk updates efficiently.
2109 if (NumUpdated == 1) {
2110 unsigned OperandToUpdate = U-OperandList;
2111 assert(getOperand(OperandToUpdate) == From &&
2112 "ReplaceAllUsesWith broken!");
2113 setOperand(OperandToUpdate, ToC);
2114 } else {
2115 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2116 if (getOperand(i) == From)
2117 setOperand(i, ToC);
2118 }
Chris Lattnerb64419a2005-10-03 22:51:37 +00002119 return;
2120 }
2121 }
2122
2123 // Otherwise, I do need to replace this with an existing value.
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002124 assert(Replacement != this && "I didn't contain From!");
2125
Chris Lattner7a1450d2005-10-04 18:13:04 +00002126 // Everyone using this now uses the replacement.
2127 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002128
2129 // Delete the old constant!
2130 destroyConstant();
2131}
2132
2133void ConstantStruct::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);
2137
Chris Lattnerdff59112005-10-04 18:47:09 +00002138 unsigned OperandToUpdate = U-OperandList;
2139 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2140
Jim Laskeyc03caef2006-07-17 17:38:29 +00002141 std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
Chris Lattner8760ec72005-10-04 01:17:50 +00002142 Lookup.first.first = getType();
2143 Lookup.second = this;
2144 std::vector<Constant*> &Values = Lookup.first.second;
2145 Values.reserve(getNumOperands()); // Build replacement struct.
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002146
Chris Lattnerdff59112005-10-04 18:47:09 +00002147
Chris Lattner8760ec72005-10-04 01:17:50 +00002148 // Fill values with the modified operands of the constant struct. Also,
2149 // compute whether this turns into an all-zeros struct.
Chris Lattnerdff59112005-10-04 18:47:09 +00002150 bool isAllZeros = false;
2151 if (!ToC->isNullValue()) {
2152 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
2153 Values.push_back(cast<Constant>(O->get()));
2154 } else {
2155 isAllZeros = true;
2156 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2157 Constant *Val = cast<Constant>(O->get());
2158 Values.push_back(Val);
2159 if (isAllZeros) isAllZeros = Val->isNullValue();
2160 }
Chris Lattner8760ec72005-10-04 01:17:50 +00002161 }
Chris Lattnerdff59112005-10-04 18:47:09 +00002162 Values[OperandToUpdate] = ToC;
2163
Chris Lattner8760ec72005-10-04 01:17:50 +00002164 Constant *Replacement = 0;
2165 if (isAllZeros) {
2166 Replacement = ConstantAggregateZero::get(getType());
2167 } else {
2168 // Check to see if we have this array type already.
2169 bool Exists;
Jim Laskeyc03caef2006-07-17 17:38:29 +00002170 StructConstantsTy::MapTy::iterator I =
Chris Lattner69edc982006-09-28 00:35:06 +00002171 StructConstants->InsertOrGetItem(Lookup, Exists);
Chris Lattner8760ec72005-10-04 01:17:50 +00002172
2173 if (Exists) {
2174 Replacement = I->second;
2175 } else {
2176 // Okay, the new shape doesn't exist in the system yet. Instead of
2177 // creating a new constant struct, inserting it, replaceallusesof'ing the
2178 // old with the new, then deleting the old... just update the current one
2179 // in place!
Chris Lattner69edc982006-09-28 00:35:06 +00002180 StructConstants->MoveConstantToNewSlot(this, I);
Chris Lattner8760ec72005-10-04 01:17:50 +00002181
Chris Lattnerdff59112005-10-04 18:47:09 +00002182 // Update to the new value.
2183 setOperand(OperandToUpdate, ToC);
Chris Lattner8760ec72005-10-04 01:17:50 +00002184 return;
2185 }
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002186 }
2187
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002188 assert(Replacement != this && "I didn't contain From!");
2189
Chris Lattner7a1450d2005-10-04 18:13:04 +00002190 // Everyone using this now uses the replacement.
2191 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002192
2193 // Delete the old constant!
2194 destroyConstant();
2195}
2196
Reid Spencerd84d35b2007-02-15 02:26:10 +00002197void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002198 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002199 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2200
2201 std::vector<Constant*> Values;
2202 Values.reserve(getNumOperands()); // Build replacement array...
2203 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2204 Constant *Val = getOperand(i);
2205 if (Val == From) Val = cast<Constant>(To);
2206 Values.push_back(Val);
2207 }
2208
Reid Spencerd84d35b2007-02-15 02:26:10 +00002209 Constant *Replacement = ConstantVector::get(getType(), Values);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002210 assert(Replacement != this && "I didn't contain From!");
2211
Chris Lattner7a1450d2005-10-04 18:13:04 +00002212 // Everyone using this now uses the replacement.
2213 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002214
2215 // Delete the old constant!
2216 destroyConstant();
2217}
2218
2219void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002220 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002221 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2222 Constant *To = cast<Constant>(ToV);
2223
2224 Constant *Replacement = 0;
2225 if (getOpcode() == Instruction::GetElementPtr) {
Chris Lattnerb5d70302007-02-19 20:01:23 +00002226 SmallVector<Constant*, 8> Indices;
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002227 Constant *Pointer = getOperand(0);
2228 Indices.reserve(getNumOperands()-1);
2229 if (Pointer == From) Pointer = To;
2230
2231 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2232 Constant *Val = getOperand(i);
2233 if (Val == From) Val = To;
2234 Indices.push_back(Val);
2235 }
Chris Lattnerb5d70302007-02-19 20:01:23 +00002236 Replacement = ConstantExpr::getGetElementPtr(Pointer,
2237 &Indices[0], Indices.size());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002238 } else if (isCast()) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002239 assert(getOperand(0) == From && "Cast only has one use!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002240 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002241 } else if (getOpcode() == Instruction::Select) {
2242 Constant *C1 = getOperand(0);
2243 Constant *C2 = getOperand(1);
2244 Constant *C3 = getOperand(2);
2245 if (C1 == From) C1 = To;
2246 if (C2 == From) C2 = To;
2247 if (C3 == From) C3 = To;
2248 Replacement = ConstantExpr::getSelect(C1, C2, C3);
Robert Bocchino23004482006-01-10 19:05:34 +00002249 } else if (getOpcode() == Instruction::ExtractElement) {
2250 Constant *C1 = getOperand(0);
2251 Constant *C2 = getOperand(1);
2252 if (C1 == From) C1 = To;
2253 if (C2 == From) C2 = To;
2254 Replacement = ConstantExpr::getExtractElement(C1, C2);
Chris Lattnera93b4b52006-04-08 05:09:48 +00002255 } else if (getOpcode() == Instruction::InsertElement) {
2256 Constant *C1 = getOperand(0);
2257 Constant *C2 = getOperand(1);
2258 Constant *C3 = getOperand(1);
2259 if (C1 == From) C1 = To;
2260 if (C2 == From) C2 = To;
2261 if (C3 == From) C3 = To;
2262 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2263 } else if (getOpcode() == Instruction::ShuffleVector) {
2264 Constant *C1 = getOperand(0);
2265 Constant *C2 = getOperand(1);
2266 Constant *C3 = getOperand(2);
2267 if (C1 == From) C1 = To;
2268 if (C2 == From) C2 = To;
2269 if (C3 == From) C3 = To;
2270 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
Reid Spenceree3c9912006-12-04 05:19:50 +00002271 } else if (isCompare()) {
2272 Constant *C1 = getOperand(0);
2273 Constant *C2 = getOperand(1);
2274 if (C1 == From) C1 = To;
2275 if (C2 == From) C2 = To;
2276 if (getOpcode() == Instruction::ICmp)
2277 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2278 else
2279 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002280 } else if (getNumOperands() == 2) {
2281 Constant *C1 = getOperand(0);
2282 Constant *C2 = getOperand(1);
2283 if (C1 == From) C1 = To;
2284 if (C2 == From) C2 = To;
2285 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2286 } else {
2287 assert(0 && "Unknown ConstantExpr type!");
2288 return;
2289 }
2290
2291 assert(Replacement != this && "I didn't contain From!");
2292
Chris Lattner7a1450d2005-10-04 18:13:04 +00002293 // Everyone using this now uses the replacement.
2294 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002295
2296 // Delete the old constant!
2297 destroyConstant();
2298}
2299
2300
Jim Laskey2698f0d2006-03-08 18:11:07 +00002301/// getStringValue - Turn an LLVM constant pointer that eventually points to a
2302/// global into a string value. Return an empty string if we can't do it.
Evan Cheng38280c02006-03-10 23:52:03 +00002303/// Parameter Chop determines if the result is chopped at the first null
2304/// terminator.
Jim Laskey2698f0d2006-03-08 18:11:07 +00002305///
Evan Cheng38280c02006-03-10 23:52:03 +00002306std::string Constant::getStringValue(bool Chop, unsigned Offset) {
Jim Laskey2698f0d2006-03-08 18:11:07 +00002307 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(this)) {
2308 if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
2309 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
2310 if (Init->isString()) {
2311 std::string Result = Init->getAsString();
2312 if (Offset < Result.size()) {
2313 // If we are pointing INTO The string, erase the beginning...
2314 Result.erase(Result.begin(), Result.begin()+Offset);
2315
2316 // Take off the null terminator, and any string fragments after it.
Evan Cheng38280c02006-03-10 23:52:03 +00002317 if (Chop) {
2318 std::string::size_type NullPos = Result.find_first_of((char)0);
2319 if (NullPos != std::string::npos)
2320 Result.erase(Result.begin()+NullPos, Result.end());
2321 }
Jim Laskey2698f0d2006-03-08 18:11:07 +00002322 return Result;
2323 }
2324 }
2325 }
Chris Lattner6ab19ed2007-11-01 02:30:35 +00002326 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(this)) {
2327 if (CE->getOpcode() == Instruction::GetElementPtr) {
2328 // Turn a gep into the specified offset.
2329 if (CE->getNumOperands() == 3 &&
2330 cast<Constant>(CE->getOperand(1))->isNullValue() &&
2331 isa<ConstantInt>(CE->getOperand(2))) {
2332 Offset += cast<ConstantInt>(CE->getOperand(2))->getZExtValue();
2333 return CE->getOperand(0)->getStringValue(Chop, Offset);
Jim Laskey2698f0d2006-03-08 18:11:07 +00002334 }
2335 }
2336 }
2337 return "";
2338}