blob: 0b8fcc43258c2c52b8d2cd762af3ec38cb35f041 [file] [log] [blame]
Chris Lattner2b383d2e2003-05-13 21:37:02 +00001//===-- Constants.cpp - Implement Constant nodes --------------------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner2f7c9632001-06-06 20:29:01 +00009//
Chris Lattner3462ae32001-12-03 22:26:30 +000010// This file implements the Constant* classes...
Chris Lattner2f7c9632001-06-06 20:29:01 +000011//
12//===----------------------------------------------------------------------===//
13
Chris Lattnerca142372002-04-28 19:55:58 +000014#include "llvm/Constants.h"
Chris Lattner33e93b82007-02-27 03:05:06 +000015#include "ConstantFold.h"
Chris Lattner2f7c9632001-06-06 20:29:01 +000016#include "llvm/DerivedTypes.h"
Reid Spencer1ebe1ab2004-07-17 23:48:33 +000017#include "llvm/GlobalValue.h"
Misha Brukman63b38bd2004-07-29 17:30:56 +000018#include "llvm/Instructions.h"
Chris Lattnerd7a73302001-10-13 06:57:33 +000019#include "llvm/Module.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000020#include "llvm/ADT/StringExtras.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000021#include "llvm/Support/Compiler.h"
Bill Wendling6a462f12006-11-17 08:03:48 +000022#include "llvm/Support/Debug.h"
Chris Lattner69edc982006-09-28 00:35:06 +000023#include "llvm/Support/ManagedStatic.h"
Bill Wendling6a462f12006-11-17 08:03:48 +000024#include "llvm/Support/MathExtras.h"
Chris Lattnera80bf0b2007-02-20 06:39:57 +000025#include "llvm/ADT/DenseMap.h"
Chris Lattnerb5d70302007-02-19 20:01:23 +000026#include "llvm/ADT/SmallVector.h"
Chris Lattner2f7c9632001-06-06 20:29:01 +000027#include <algorithm>
Reid Spencer3aaaa0b2007-02-05 20:47:22 +000028#include <map>
Chris Lattner189d19f2003-11-21 20:23:48 +000029using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000030
Chris Lattner2f7c9632001-06-06 20:29:01 +000031//===----------------------------------------------------------------------===//
Chris Lattner3462ae32001-12-03 22:26:30 +000032// Constant Class
Chris Lattner2f7c9632001-06-06 20:29:01 +000033//===----------------------------------------------------------------------===//
34
Chris Lattner3462ae32001-12-03 22:26:30 +000035void Constant::destroyConstantImpl() {
36 // When a Constant is destroyed, there may be lingering
Chris Lattnerd7a73302001-10-13 06:57:33 +000037 // references to the constant by other constants in the constant pool. These
Misha Brukmanbe372b92003-08-21 22:14:26 +000038 // constants are implicitly dependent on the module that is being deleted,
Chris Lattnerd7a73302001-10-13 06:57:33 +000039 // but they don't know that. Because we only find out when the CPV is
40 // deleted, we must now notify all of our users (that should only be
Chris Lattner3462ae32001-12-03 22:26:30 +000041 // Constants) that they are, in fact, invalid now and should be deleted.
Chris Lattnerd7a73302001-10-13 06:57:33 +000042 //
43 while (!use_empty()) {
44 Value *V = use_back();
45#ifndef NDEBUG // Only in -g mode...
Chris Lattnerd9f4ac662002-07-18 00:14:50 +000046 if (!isa<Constant>(V))
Bill Wendling6a462f12006-11-17 08:03:48 +000047 DOUT << "While deleting: " << *this
48 << "\n\nUse still stuck around after Def is destroyed: "
49 << *V << "\n\n";
Chris Lattnerd7a73302001-10-13 06:57:33 +000050#endif
Vikram S. Adve4e537b22002-07-14 23:13:17 +000051 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
Reid Spencer1ebe1ab2004-07-17 23:48:33 +000052 Constant *CV = cast<Constant>(V);
53 CV->destroyConstant();
Chris Lattnerd7a73302001-10-13 06:57:33 +000054
55 // The constant should remove itself from our use list...
Vikram S. Adve4e537b22002-07-14 23:13:17 +000056 assert((use_empty() || use_back() != V) && "Constant not removed!");
Chris Lattnerd7a73302001-10-13 06:57:33 +000057 }
58
59 // Value has no outstanding references it is safe to delete it now...
60 delete this;
Chris Lattner38569342001-10-01 20:11:19 +000061}
Chris Lattner2f7c9632001-06-06 20:29:01 +000062
Chris Lattner23dd1f62006-10-20 00:27:06 +000063/// canTrap - Return true if evaluation of this constant could trap. This is
64/// true for things like constant expressions that could divide by zero.
65bool Constant::canTrap() const {
66 assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
67 // The only thing that could possibly trap are constant exprs.
68 const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
69 if (!CE) return false;
70
71 // ConstantExpr traps if any operands can trap.
72 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
73 if (getOperand(i)->canTrap())
74 return true;
75
76 // Otherwise, only specific operations can trap.
77 switch (CE->getOpcode()) {
78 default:
79 return false;
Reid Spencer7e80b0b2006-10-26 06:15:43 +000080 case Instruction::UDiv:
81 case Instruction::SDiv:
82 case Instruction::FDiv:
Reid Spencer7eb55b32006-11-02 01:53:59 +000083 case Instruction::URem:
84 case Instruction::SRem:
85 case Instruction::FRem:
Chris Lattner23dd1f62006-10-20 00:27:06 +000086 // Div and rem can trap if the RHS is not known to be non-zero.
87 if (!isa<ConstantInt>(getOperand(1)) || getOperand(1)->isNullValue())
88 return true;
89 return false;
90 }
91}
92
Evan Chengf9e003b2007-03-08 00:59:12 +000093/// ContaintsRelocations - Return true if the constant value contains
94/// relocations which cannot be resolved at compile time.
95bool Constant::ContainsRelocations() const {
96 if (isa<GlobalValue>(this))
97 return true;
98 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
99 if (getOperand(i)->ContainsRelocations())
100 return true;
101 return false;
102}
103
Chris Lattnerb1585a92002-08-13 17:50:20 +0000104// Static constructor to create a '0' constant of arbitrary type...
105Constant *Constant::getNullValue(const Type *Ty) {
Dale Johannesen98d3a082007-09-14 22:26:36 +0000106 static uint64_t zero[2] = {0, 0};
Chris Lattner6b727592004-06-17 18:19:28 +0000107 switch (Ty->getTypeID()) {
Chris Lattnerdbcb0d32007-02-20 05:46:39 +0000108 case Type::IntegerTyID:
109 return ConstantInt::get(Ty, 0);
110 case Type::FloatTyID:
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000111 return ConstantFP::get(APFloat(APInt(32, 0)));
Chris Lattnerdbcb0d32007-02-20 05:46:39 +0000112 case Type::DoubleTyID:
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000113 return ConstantFP::get(APFloat(APInt(64, 0)));
Dale Johannesenbdad8092007-08-09 22:51:36 +0000114 case Type::X86_FP80TyID:
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000115 return ConstantFP::get(APFloat(APInt(80, 2, zero)));
Dale Johannesenbdad8092007-08-09 22:51:36 +0000116 case Type::FP128TyID:
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000117 return ConstantFP::get(APFloat(APInt(128, 2, zero), true));
Dale Johannesen98d3a082007-09-14 22:26:36 +0000118 case Type::PPC_FP128TyID:
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000119 return ConstantFP::get(APFloat(APInt(128, 2, zero)));
Misha Brukmanb1c93172005-04-21 23:48:37 +0000120 case Type::PointerTyID:
Chris Lattnerb1585a92002-08-13 17:50:20 +0000121 return ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattner9fba3da2004-02-15 05:53:04 +0000122 case Type::StructTyID:
123 case Type::ArrayTyID:
Reid Spencerd84d35b2007-02-15 02:26:10 +0000124 case Type::VectorTyID:
Chris Lattner9fba3da2004-02-15 05:53:04 +0000125 return ConstantAggregateZero::get(Ty);
Chris Lattnerb1585a92002-08-13 17:50:20 +0000126 default:
Reid Spencercf394bf2004-07-04 11:51:24 +0000127 // Function, Label, or Opaque type?
128 assert(!"Cannot create a null constant of that type!");
Chris Lattnerb1585a92002-08-13 17:50:20 +0000129 return 0;
130 }
131}
132
Chris Lattner72e39582007-06-15 06:10:53 +0000133Constant *Constant::getAllOnesValue(const Type *Ty) {
134 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
135 return ConstantInt::get(APInt::getAllOnesValue(ITy->getBitWidth()));
136 return ConstantVector::getAllOnesValue(cast<VectorType>(Ty));
137}
Chris Lattnerb1585a92002-08-13 17:50:20 +0000138
139// Static constructor to create an integral constant with all bits set
Zhou Sheng75b871f2007-01-11 12:24:14 +0000140ConstantInt *ConstantInt::getAllOnesValue(const Type *Ty) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000141 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
Reid Spencerd1bbfa52007-03-01 19:30:34 +0000142 return ConstantInt::get(APInt::getAllOnesValue(ITy->getBitWidth()));
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000143 return 0;
Chris Lattnerb1585a92002-08-13 17:50:20 +0000144}
145
Dan Gohman30978072007-05-24 14:36:04 +0000146/// @returns the value for a vector integer constant of the given type that
Chris Lattnerecab54c2007-01-04 01:49:26 +0000147/// has all its bits set to true.
148/// @brief Get the all ones value
Reid Spencerd84d35b2007-02-15 02:26:10 +0000149ConstantVector *ConstantVector::getAllOnesValue(const VectorType *Ty) {
Chris Lattnerecab54c2007-01-04 01:49:26 +0000150 std::vector<Constant*> Elts;
151 Elts.resize(Ty->getNumElements(),
Zhou Sheng75b871f2007-01-11 12:24:14 +0000152 ConstantInt::getAllOnesValue(Ty->getElementType()));
Dan Gohman30978072007-05-24 14:36:04 +0000153 assert(Elts[0] && "Not a vector integer type!");
Reid Spencerd84d35b2007-02-15 02:26:10 +0000154 return cast<ConstantVector>(ConstantVector::get(Elts));
Chris Lattnerecab54c2007-01-04 01:49:26 +0000155}
156
157
Chris Lattner2f7c9632001-06-06 20:29:01 +0000158//===----------------------------------------------------------------------===//
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000159// ConstantInt
Chris Lattner2f7c9632001-06-06 20:29:01 +0000160//===----------------------------------------------------------------------===//
161
Reid Spencerb31bffe2007-02-26 23:54:03 +0000162ConstantInt::ConstantInt(const IntegerType *Ty, const APInt& V)
Chris Lattner5db2f472007-02-20 05:55:46 +0000163 : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
Reid Spencerb31bffe2007-02-26 23:54:03 +0000164 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
Chris Lattner2f7c9632001-06-06 20:29:01 +0000165}
166
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000167ConstantInt *ConstantInt::TheTrueVal = 0;
168ConstantInt *ConstantInt::TheFalseVal = 0;
169
170namespace llvm {
171 void CleanupTrueFalse(void *) {
172 ConstantInt::ResetTrueFalse();
173 }
174}
175
176static ManagedCleanup<llvm::CleanupTrueFalse> TrueFalseCleanup;
177
178ConstantInt *ConstantInt::CreateTrueFalseVals(bool WhichOne) {
179 assert(TheTrueVal == 0 && TheFalseVal == 0);
180 TheTrueVal = get(Type::Int1Ty, 1);
181 TheFalseVal = get(Type::Int1Ty, 0);
182
183 // Ensure that llvm_shutdown nulls out TheTrueVal/TheFalseVal.
184 TrueFalseCleanup.Register();
185
186 return WhichOne ? TheTrueVal : TheFalseVal;
187}
188
189
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000190namespace {
Reid Spencerb31bffe2007-02-26 23:54:03 +0000191 struct DenseMapAPIntKeyInfo {
192 struct KeyTy {
193 APInt val;
194 const Type* type;
195 KeyTy(const APInt& V, const Type* Ty) : val(V), type(Ty) {}
196 KeyTy(const KeyTy& that) : val(that.val), type(that.type) {}
197 bool operator==(const KeyTy& that) const {
198 return type == that.type && this->val == that.val;
199 }
200 bool operator!=(const KeyTy& that) const {
201 return !this->operator==(that);
202 }
203 };
204 static inline KeyTy getEmptyKey() { return KeyTy(APInt(1,0), 0); }
205 static inline KeyTy getTombstoneKey() { return KeyTy(APInt(1,1), 0); }
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000206 static unsigned getHashValue(const KeyTy &Key) {
Chris Lattner0625bd62007-09-17 18:34:04 +0000207 return DenseMapInfo<void*>::getHashValue(Key.type) ^
Reid Spencerb31bffe2007-02-26 23:54:03 +0000208 Key.val.getHashValue();
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000209 }
Chris Lattner0625bd62007-09-17 18:34:04 +0000210 static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
211 return LHS == RHS;
212 }
Dale Johannesena719a602007-08-24 00:56:33 +0000213 static bool isPod() { return false; }
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000214 };
215}
216
217
Reid Spencerb31bffe2007-02-26 23:54:03 +0000218typedef DenseMap<DenseMapAPIntKeyInfo::KeyTy, ConstantInt*,
219 DenseMapAPIntKeyInfo> IntMapTy;
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000220static ManagedStatic<IntMapTy> IntConstants;
221
Reid Spencer362fb292007-03-19 20:39:08 +0000222ConstantInt *ConstantInt::get(const Type *Ty, uint64_t V, bool isSigned) {
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000223 const IntegerType *ITy = cast<IntegerType>(Ty);
Reid Spencer362fb292007-03-19 20:39:08 +0000224 return get(APInt(ITy->getBitWidth(), V, isSigned));
Reid Spencerb31bffe2007-02-26 23:54:03 +0000225}
226
Reid Spencerd1bbfa52007-03-01 19:30:34 +0000227// Get a ConstantInt from an APInt. Note that the value stored in the DenseMap
Dan Gohmanb3efe032008-02-07 02:30:40 +0000228// as the key, is a DenseMapAPIntKeyInfo::KeyTy which has provided the
Reid Spencerb31bffe2007-02-26 23:54:03 +0000229// operator== and operator!= to ensure that the DenseMap doesn't attempt to
230// compare APInt's of different widths, which would violate an APInt class
231// invariant which generates an assertion.
Reid Spencerd1bbfa52007-03-01 19:30:34 +0000232ConstantInt *ConstantInt::get(const APInt& V) {
233 // Get the corresponding integer type for the bit width of the value.
234 const IntegerType *ITy = IntegerType::get(V.getBitWidth());
Reid Spencerb31bffe2007-02-26 23:54:03 +0000235 // get an existing value or the insertion position
Reid Spencerd1bbfa52007-03-01 19:30:34 +0000236 DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
Reid Spencerb31bffe2007-02-26 23:54:03 +0000237 ConstantInt *&Slot = (*IntConstants)[Key];
238 // if it exists, return it.
239 if (Slot)
240 return Slot;
241 // otherwise create a new one, insert it, and return it.
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000242 return Slot = new ConstantInt(ITy, V);
243}
244
245//===----------------------------------------------------------------------===//
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000246// ConstantFP
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000247//===----------------------------------------------------------------------===//
248
Chris Lattner98bd9392008-04-09 06:38:30 +0000249static const fltSemantics *TypeToFloatSemantics(const Type *Ty) {
250 if (Ty == Type::FloatTy)
251 return &APFloat::IEEEsingle;
252 if (Ty == Type::DoubleTy)
253 return &APFloat::IEEEdouble;
254 if (Ty == Type::X86_FP80Ty)
255 return &APFloat::x87DoubleExtended;
256 else if (Ty == Type::FP128Ty)
257 return &APFloat::IEEEquad;
258
259 assert(Ty == Type::PPC_FP128Ty && "Unknown FP format");
260 return &APFloat::PPCDoubleDouble;
261}
262
Dale Johannesend246b2c2007-08-30 00:23:21 +0000263ConstantFP::ConstantFP(const Type *Ty, const APFloat& V)
264 : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
Chris Lattner98bd9392008-04-09 06:38:30 +0000265 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
266 "FP type Mismatch");
Chris Lattner2f7c9632001-06-06 20:29:01 +0000267}
268
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000269bool ConstantFP::isNullValue() const {
Dale Johannesena719a602007-08-24 00:56:33 +0000270 return Val.isZero() && !Val.isNegative();
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000271}
272
Dale Johannesen98d3a082007-09-14 22:26:36 +0000273ConstantFP *ConstantFP::getNegativeZero(const Type *Ty) {
274 APFloat apf = cast <ConstantFP>(Constant::getNullValue(Ty))->getValueAPF();
275 apf.changeSign();
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000276 return ConstantFP::get(apf);
Dale Johannesen98d3a082007-09-14 22:26:36 +0000277}
278
Dale Johannesend246b2c2007-08-30 00:23:21 +0000279bool ConstantFP::isExactlyValue(const APFloat& V) const {
280 return Val.bitwiseIsEqual(V);
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000281}
282
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000283namespace {
Dale Johannesena719a602007-08-24 00:56:33 +0000284 struct DenseMapAPFloatKeyInfo {
Dale Johannesenbdea32d2007-08-24 22:09:56 +0000285 struct KeyTy {
286 APFloat val;
287 KeyTy(const APFloat& V) : val(V){}
288 KeyTy(const KeyTy& that) : val(that.val) {}
289 bool operator==(const KeyTy& that) const {
290 return this->val.bitwiseIsEqual(that.val);
291 }
292 bool operator!=(const KeyTy& that) const {
293 return !this->operator==(that);
294 }
295 };
296 static inline KeyTy getEmptyKey() {
297 return KeyTy(APFloat(APFloat::Bogus,1));
Reid Spencerb31bffe2007-02-26 23:54:03 +0000298 }
Dale Johannesenbdea32d2007-08-24 22:09:56 +0000299 static inline KeyTy getTombstoneKey() {
300 return KeyTy(APFloat(APFloat::Bogus,2));
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000301 }
Dale Johannesenbdea32d2007-08-24 22:09:56 +0000302 static unsigned getHashValue(const KeyTy &Key) {
303 return Key.val.getHashValue();
Dale Johannesena719a602007-08-24 00:56:33 +0000304 }
Chris Lattner0625bd62007-09-17 18:34:04 +0000305 static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
306 return LHS == RHS;
307 }
Dale Johannesena719a602007-08-24 00:56:33 +0000308 static bool isPod() { return false; }
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000309 };
310}
311
312//---- ConstantFP::get() implementation...
313//
Dale Johannesenbdea32d2007-08-24 22:09:56 +0000314typedef DenseMap<DenseMapAPFloatKeyInfo::KeyTy, ConstantFP*,
Dale Johannesena719a602007-08-24 00:56:33 +0000315 DenseMapAPFloatKeyInfo> FPMapTy;
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000316
Dale Johannesena719a602007-08-24 00:56:33 +0000317static ManagedStatic<FPMapTy> FPConstants;
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000318
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000319ConstantFP *ConstantFP::get(const APFloat &V) {
Dale Johannesend246b2c2007-08-30 00:23:21 +0000320 DenseMapAPFloatKeyInfo::KeyTy Key(V);
321 ConstantFP *&Slot = (*FPConstants)[Key];
322 if (Slot) return Slot;
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000323
324 const Type *Ty;
325 if (&V.getSemantics() == &APFloat::IEEEsingle)
326 Ty = Type::FloatTy;
327 else if (&V.getSemantics() == &APFloat::IEEEdouble)
328 Ty = Type::DoubleTy;
329 else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
330 Ty = Type::X86_FP80Ty;
331 else if (&V.getSemantics() == &APFloat::IEEEquad)
332 Ty = Type::FP128Ty;
333 else {
334 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble&&"Unknown FP format");
335 Ty = Type::PPC_FP128Ty;
336 }
337
Dale Johannesend246b2c2007-08-30 00:23:21 +0000338 return Slot = new ConstantFP(Ty, V);
339}
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000340
Chris Lattner98bd9392008-04-09 06:38:30 +0000341/// get() - This returns a constant fp for the specified value in the
342/// specified type. This should only be used for simple constant values like
343/// 2.0/1.0 etc, that are known-valid both as double and as the target format.
344ConstantFP *ConstantFP::get(const Type *Ty, double V) {
345 APFloat FV(V);
346 FV.convert(*TypeToFloatSemantics(Ty), APFloat::rmNearestTiesToEven);
347 return get(FV);
348}
349
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000350//===----------------------------------------------------------------------===//
351// ConstantXXX Classes
352//===----------------------------------------------------------------------===//
353
354
Chris Lattner3462ae32001-12-03 22:26:30 +0000355ConstantArray::ConstantArray(const ArrayType *T,
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000356 const std::vector<Constant*> &V)
Chris Lattnere7e139e2005-09-27 06:09:08 +0000357 : Constant(T, ConstantArrayVal, new Use[V.size()], V.size()) {
Alkis Evlogimenos0507ffe2004-09-15 02:32:15 +0000358 assert(V.size() == T->getNumElements() &&
359 "Invalid initializer vector for constant array");
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000360 Use *OL = OperandList;
Chris Lattner0144fad2005-10-03 21:56:24 +0000361 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
362 I != E; ++I, ++OL) {
Chris Lattner20a24452005-10-07 05:23:36 +0000363 Constant *C = *I;
364 assert((C->getType() == T->getElementType() ||
Alkis Evlogimenoscb031d92004-09-10 04:16:59 +0000365 (T->isAbstract() &&
Chris Lattner20a24452005-10-07 05:23:36 +0000366 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
Alkis Evlogimenoscb031d92004-09-10 04:16:59 +0000367 "Initializer for array element doesn't match array element type!");
Chris Lattner20a24452005-10-07 05:23:36 +0000368 OL->init(C, this);
Chris Lattner2f7c9632001-06-06 20:29:01 +0000369 }
370}
371
Gordon Henriksen14a55692007-12-10 02:14:30 +0000372ConstantArray::~ConstantArray() {
373 delete [] OperandList;
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000374}
375
Chris Lattner3462ae32001-12-03 22:26:30 +0000376ConstantStruct::ConstantStruct(const StructType *T,
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000377 const std::vector<Constant*> &V)
Chris Lattnere7e139e2005-09-27 06:09:08 +0000378 : Constant(T, ConstantStructVal, new Use[V.size()], V.size()) {
Chris Lattnerac6db752004-02-09 04:37:31 +0000379 assert(V.size() == T->getNumElements() &&
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000380 "Invalid initializer vector for constant structure");
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000381 Use *OL = OperandList;
Chris Lattner0144fad2005-10-03 21:56:24 +0000382 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
383 I != E; ++I, ++OL) {
Chris Lattner20a24452005-10-07 05:23:36 +0000384 Constant *C = *I;
385 assert((C->getType() == T->getElementType(I-V.begin()) ||
Chris Lattner0144fad2005-10-03 21:56:24 +0000386 ((T->getElementType(I-V.begin())->isAbstract() ||
Chris Lattner20a24452005-10-07 05:23:36 +0000387 C->getType()->isAbstract()) &&
Chris Lattner0144fad2005-10-03 21:56:24 +0000388 T->getElementType(I-V.begin())->getTypeID() ==
Chris Lattner20a24452005-10-07 05:23:36 +0000389 C->getType()->getTypeID())) &&
Chris Lattner93c8f142003-06-02 17:42:47 +0000390 "Initializer for struct element doesn't match struct element type!");
Chris Lattner20a24452005-10-07 05:23:36 +0000391 OL->init(C, this);
Chris Lattner2f7c9632001-06-06 20:29:01 +0000392 }
393}
394
Gordon Henriksen14a55692007-12-10 02:14:30 +0000395ConstantStruct::~ConstantStruct() {
396 delete [] OperandList;
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000397}
398
399
Reid Spencerd84d35b2007-02-15 02:26:10 +0000400ConstantVector::ConstantVector(const VectorType *T,
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000401 const std::vector<Constant*> &V)
Reid Spencerd84d35b2007-02-15 02:26:10 +0000402 : Constant(T, ConstantVectorVal, new Use[V.size()], V.size()) {
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000403 Use *OL = OperandList;
Chris Lattner0144fad2005-10-03 21:56:24 +0000404 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
405 I != E; ++I, ++OL) {
Chris Lattner20a24452005-10-07 05:23:36 +0000406 Constant *C = *I;
407 assert((C->getType() == T->getElementType() ||
Alkis Evlogimenoscb031d92004-09-10 04:16:59 +0000408 (T->isAbstract() &&
Chris Lattner20a24452005-10-07 05:23:36 +0000409 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
Dan Gohman30978072007-05-24 14:36:04 +0000410 "Initializer for vector element doesn't match vector element type!");
Chris Lattner20a24452005-10-07 05:23:36 +0000411 OL->init(C, this);
Brian Gaeke02209042004-08-20 06:00:58 +0000412 }
413}
414
Gordon Henriksen14a55692007-12-10 02:14:30 +0000415ConstantVector::~ConstantVector() {
416 delete [] OperandList;
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000417}
418
Gordon Henriksen14a55692007-12-10 02:14:30 +0000419// We declare several classes private to this file, so use an anonymous
420// namespace
421namespace {
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000422
Gordon Henriksen14a55692007-12-10 02:14:30 +0000423/// UnaryConstantExpr - This class is private to Constants.cpp, and is used
424/// behind the scenes to implement unary constant exprs.
425class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
Gabor Greife9ecc682008-04-06 20:25:17 +0000426 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Gordon Henriksen14a55692007-12-10 02:14:30 +0000427 Use Op;
428public:
Gabor Greife9ecc682008-04-06 20:25:17 +0000429 // allocate space for exactly one operand
430 void *operator new(size_t s) {
431 return User::operator new(s, 1);
432 }
Gordon Henriksen14a55692007-12-10 02:14:30 +0000433 UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
434 : ConstantExpr(Ty, Opcode, &Op, 1), Op(C, this) {}
435};
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000436
Gordon Henriksen14a55692007-12-10 02:14:30 +0000437/// BinaryConstantExpr - This class is private to Constants.cpp, and is used
438/// behind the scenes to implement binary constant exprs.
439class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
Gabor Greife9ecc682008-04-06 20:25:17 +0000440 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Gordon Henriksen14a55692007-12-10 02:14:30 +0000441 Use Ops[2];
442public:
Gabor Greife9ecc682008-04-06 20:25:17 +0000443 // allocate space for exactly two operands
444 void *operator new(size_t s) {
445 return User::operator new(s, 2);
446 }
Gordon Henriksen14a55692007-12-10 02:14:30 +0000447 BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
448 : ConstantExpr(C1->getType(), Opcode, Ops, 2) {
449 Ops[0].init(C1, this);
450 Ops[1].init(C2, this);
451 }
452};
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000453
Gordon Henriksen14a55692007-12-10 02:14:30 +0000454/// SelectConstantExpr - This class is private to Constants.cpp, and is used
455/// behind the scenes to implement select constant exprs.
456class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
Gabor Greife9ecc682008-04-06 20:25:17 +0000457 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Gordon Henriksen14a55692007-12-10 02:14:30 +0000458 Use Ops[3];
459public:
Gabor Greife9ecc682008-04-06 20:25:17 +0000460 // allocate space for exactly three operands
461 void *operator new(size_t s) {
462 return User::operator new(s, 3);
463 }
Gordon Henriksen14a55692007-12-10 02:14:30 +0000464 SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
465 : ConstantExpr(C2->getType(), Instruction::Select, Ops, 3) {
466 Ops[0].init(C1, this);
467 Ops[1].init(C2, this);
468 Ops[2].init(C3, this);
469 }
470};
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000471
Gordon Henriksen14a55692007-12-10 02:14:30 +0000472/// ExtractElementConstantExpr - This class is private to
473/// Constants.cpp, and is used behind the scenes to implement
474/// extractelement constant exprs.
475class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
Gabor Greife9ecc682008-04-06 20:25:17 +0000476 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Gordon Henriksen14a55692007-12-10 02:14:30 +0000477 Use Ops[2];
478public:
Gabor Greife9ecc682008-04-06 20:25:17 +0000479 // allocate space for exactly two operands
480 void *operator new(size_t s) {
481 return User::operator new(s, 2);
482 }
Gordon Henriksen14a55692007-12-10 02:14:30 +0000483 ExtractElementConstantExpr(Constant *C1, Constant *C2)
484 : ConstantExpr(cast<VectorType>(C1->getType())->getElementType(),
485 Instruction::ExtractElement, Ops, 2) {
486 Ops[0].init(C1, this);
487 Ops[1].init(C2, this);
488 }
489};
Robert Bocchino23004482006-01-10 19:05:34 +0000490
Gordon Henriksen14a55692007-12-10 02:14:30 +0000491/// InsertElementConstantExpr - This class is private to
492/// Constants.cpp, and is used behind the scenes to implement
493/// insertelement constant exprs.
494class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
Gabor Greife9ecc682008-04-06 20:25:17 +0000495 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Gordon Henriksen14a55692007-12-10 02:14:30 +0000496 Use Ops[3];
497public:
Gabor Greife9ecc682008-04-06 20:25:17 +0000498 // allocate space for exactly three operands
499 void *operator new(size_t s) {
500 return User::operator new(s, 3);
501 }
Gordon Henriksen14a55692007-12-10 02:14:30 +0000502 InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
503 : ConstantExpr(C1->getType(), Instruction::InsertElement,
504 Ops, 3) {
505 Ops[0].init(C1, this);
506 Ops[1].init(C2, this);
507 Ops[2].init(C3, this);
508 }
509};
Robert Bocchinoca27f032006-01-17 20:07:22 +0000510
Gordon Henriksen14a55692007-12-10 02:14:30 +0000511/// ShuffleVectorConstantExpr - This class is private to
512/// Constants.cpp, and is used behind the scenes to implement
513/// shufflevector constant exprs.
514class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
Gabor Greife9ecc682008-04-06 20:25:17 +0000515 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Gordon Henriksen14a55692007-12-10 02:14:30 +0000516 Use Ops[3];
517public:
Gabor Greife9ecc682008-04-06 20:25:17 +0000518 // allocate space for exactly three operands
519 void *operator new(size_t s) {
520 return User::operator new(s, 3);
521 }
Gordon Henriksen14a55692007-12-10 02:14:30 +0000522 ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
523 : ConstantExpr(C1->getType(), Instruction::ShuffleVector,
524 Ops, 3) {
525 Ops[0].init(C1, this);
526 Ops[1].init(C2, this);
527 Ops[2].init(C3, this);
528 }
529};
530
531/// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
532/// used behind the scenes to implement getelementpr constant exprs.
Gabor Greife9ecc682008-04-06 20:25:17 +0000533class VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
Gordon Henriksen14a55692007-12-10 02:14:30 +0000534 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
535 const Type *DestTy)
536 : ConstantExpr(DestTy, Instruction::GetElementPtr,
537 new Use[IdxList.size()+1], IdxList.size()+1) {
538 OperandList[0].init(C, this);
539 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
540 OperandList[i+1].init(IdxList[i], this);
541 }
Gabor Greife9ecc682008-04-06 20:25:17 +0000542public:
543 static GetElementPtrConstantExpr *Create(Constant *C, const std::vector<Constant*> &IdxList,
544 const Type *DestTy) {
545 return new(IdxList.size() + 1/*FIXME*/) GetElementPtrConstantExpr(C, IdxList, DestTy);
546 }
Gordon Henriksen14a55692007-12-10 02:14:30 +0000547 ~GetElementPtrConstantExpr() {
548 delete [] OperandList;
549 }
550};
551
552// CompareConstantExpr - This class is private to Constants.cpp, and is used
553// behind the scenes to implement ICmp and FCmp constant expressions. This is
554// needed in order to store the predicate value for these instructions.
555struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
Gabor Greife9ecc682008-04-06 20:25:17 +0000556 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
557 // allocate space for exactly two operands
558 void *operator new(size_t s) {
559 return User::operator new(s, 2);
560 }
Gordon Henriksen14a55692007-12-10 02:14:30 +0000561 unsigned short predicate;
562 Use Ops[2];
563 CompareConstantExpr(Instruction::OtherOps opc, unsigned short pred,
564 Constant* LHS, Constant* RHS)
565 : ConstantExpr(Type::Int1Ty, opc, Ops, 2), predicate(pred) {
566 OperandList[0].init(LHS, this);
567 OperandList[1].init(RHS, this);
568 }
569};
570
571} // end anonymous namespace
572
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000573
574// Utility function for determining if a ConstantExpr is a CastOp or not. This
575// can't be inline because we don't want to #include Instruction.h into
576// Constant.h
577bool ConstantExpr::isCast() const {
578 return Instruction::isCast(getOpcode());
579}
580
Reid Spenceree3c9912006-12-04 05:19:50 +0000581bool ConstantExpr::isCompare() const {
582 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
583}
584
Chris Lattner817175f2004-03-29 02:37:53 +0000585/// ConstantExpr::get* - Return some common constants without having to
586/// specify the full Instruction::OPCODE identifier.
587///
588Constant *ConstantExpr::getNeg(Constant *C) {
Reid Spencer2eadb532007-01-21 00:29:26 +0000589 return get(Instruction::Sub,
590 ConstantExpr::getZeroValueForNegationExpr(C->getType()),
591 C);
Chris Lattner817175f2004-03-29 02:37:53 +0000592}
593Constant *ConstantExpr::getNot(Constant *C) {
Gordon Henriksen7ce31762007-10-06 14:29:36 +0000594 assert(isa<IntegerType>(C->getType()) && "Cannot NOT a nonintegral value!");
Chris Lattner817175f2004-03-29 02:37:53 +0000595 return get(Instruction::Xor, C,
Zhou Sheng75b871f2007-01-11 12:24:14 +0000596 ConstantInt::getAllOnesValue(C->getType()));
Chris Lattner817175f2004-03-29 02:37:53 +0000597}
598Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
599 return get(Instruction::Add, C1, C2);
600}
601Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
602 return get(Instruction::Sub, C1, C2);
603}
604Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
605 return get(Instruction::Mul, C1, C2);
606}
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000607Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2) {
608 return get(Instruction::UDiv, C1, C2);
609}
610Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2) {
611 return get(Instruction::SDiv, C1, C2);
612}
613Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
614 return get(Instruction::FDiv, C1, C2);
Chris Lattner817175f2004-03-29 02:37:53 +0000615}
Reid Spencer7eb55b32006-11-02 01:53:59 +0000616Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
617 return get(Instruction::URem, C1, C2);
618}
619Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
620 return get(Instruction::SRem, C1, C2);
621}
622Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
623 return get(Instruction::FRem, C1, C2);
Chris Lattner817175f2004-03-29 02:37:53 +0000624}
625Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
626 return get(Instruction::And, C1, C2);
627}
628Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
629 return get(Instruction::Or, C1, C2);
630}
631Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
632 return get(Instruction::Xor, C1, C2);
633}
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000634unsigned ConstantExpr::getPredicate() const {
635 assert(getOpcode() == Instruction::FCmp || getOpcode() == Instruction::ICmp);
Chris Lattneref650092007-10-18 16:26:24 +0000636 return ((const CompareConstantExpr*)this)->predicate;
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000637}
Chris Lattner817175f2004-03-29 02:37:53 +0000638Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
639 return get(Instruction::Shl, C1, C2);
640}
Reid Spencerfdff9382006-11-08 06:47:33 +0000641Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2) {
642 return get(Instruction::LShr, C1, C2);
Chris Lattner817175f2004-03-29 02:37:53 +0000643}
Reid Spencerfdff9382006-11-08 06:47:33 +0000644Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2) {
645 return get(Instruction::AShr, C1, C2);
Chris Lattnerdb8bdba2004-05-25 05:32:43 +0000646}
Chris Lattner60e0dd72001-10-03 06:12:09 +0000647
Chris Lattner7c1018a2006-07-14 19:37:40 +0000648/// getWithOperandReplaced - Return a constant expression identical to this
649/// one, but with the specified operand set to the specified value.
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000650Constant *
651ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
Chris Lattner7c1018a2006-07-14 19:37:40 +0000652 assert(OpNo < getNumOperands() && "Operand num is out of range!");
653 assert(Op->getType() == getOperand(OpNo)->getType() &&
654 "Replacing operand with value of different type!");
Chris Lattner227816342006-07-14 22:20:01 +0000655 if (getOperand(OpNo) == Op)
656 return const_cast<ConstantExpr*>(this);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000657
Chris Lattner227816342006-07-14 22:20:01 +0000658 Constant *Op0, *Op1, *Op2;
Chris Lattner7c1018a2006-07-14 19:37:40 +0000659 switch (getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000660 case Instruction::Trunc:
661 case Instruction::ZExt:
662 case Instruction::SExt:
663 case Instruction::FPTrunc:
664 case Instruction::FPExt:
665 case Instruction::UIToFP:
666 case Instruction::SIToFP:
667 case Instruction::FPToUI:
668 case Instruction::FPToSI:
669 case Instruction::PtrToInt:
670 case Instruction::IntToPtr:
671 case Instruction::BitCast:
672 return ConstantExpr::getCast(getOpcode(), Op, getType());
Chris Lattner227816342006-07-14 22:20:01 +0000673 case Instruction::Select:
674 Op0 = (OpNo == 0) ? Op : getOperand(0);
675 Op1 = (OpNo == 1) ? Op : getOperand(1);
676 Op2 = (OpNo == 2) ? Op : getOperand(2);
677 return ConstantExpr::getSelect(Op0, Op1, Op2);
678 case Instruction::InsertElement:
679 Op0 = (OpNo == 0) ? Op : getOperand(0);
680 Op1 = (OpNo == 1) ? Op : getOperand(1);
681 Op2 = (OpNo == 2) ? Op : getOperand(2);
682 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
683 case Instruction::ExtractElement:
684 Op0 = (OpNo == 0) ? Op : getOperand(0);
685 Op1 = (OpNo == 1) ? Op : getOperand(1);
686 return ConstantExpr::getExtractElement(Op0, Op1);
687 case Instruction::ShuffleVector:
688 Op0 = (OpNo == 0) ? Op : getOperand(0);
689 Op1 = (OpNo == 1) ? Op : getOperand(1);
690 Op2 = (OpNo == 2) ? Op : getOperand(2);
691 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000692 case Instruction::GetElementPtr: {
Chris Lattnerb5d70302007-02-19 20:01:23 +0000693 SmallVector<Constant*, 8> Ops;
694 Ops.resize(getNumOperands());
Chris Lattner7c1018a2006-07-14 19:37:40 +0000695 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
Chris Lattnerb5d70302007-02-19 20:01:23 +0000696 Ops[i] = getOperand(i);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000697 if (OpNo == 0)
Chris Lattnerb5d70302007-02-19 20:01:23 +0000698 return ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
Chris Lattner7c1018a2006-07-14 19:37:40 +0000699 Ops[OpNo-1] = Op;
Chris Lattnerb5d70302007-02-19 20:01:23 +0000700 return ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
Chris Lattner7c1018a2006-07-14 19:37:40 +0000701 }
Chris Lattner7c1018a2006-07-14 19:37:40 +0000702 default:
703 assert(getNumOperands() == 2 && "Must be binary operator?");
Chris Lattner227816342006-07-14 22:20:01 +0000704 Op0 = (OpNo == 0) ? Op : getOperand(0);
705 Op1 = (OpNo == 1) ? Op : getOperand(1);
706 return ConstantExpr::get(getOpcode(), Op0, Op1);
707 }
708}
709
710/// getWithOperands - This returns the current constant expression with the
711/// operands replaced with the specified values. The specified operands must
712/// match count and type with the existing ones.
713Constant *ConstantExpr::
714getWithOperands(const std::vector<Constant*> &Ops) const {
715 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
716 bool AnyChange = false;
717 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
718 assert(Ops[i]->getType() == getOperand(i)->getType() &&
719 "Operand type mismatch!");
720 AnyChange |= Ops[i] != getOperand(i);
721 }
722 if (!AnyChange) // No operands changed, return self.
723 return const_cast<ConstantExpr*>(this);
724
725 switch (getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000726 case Instruction::Trunc:
727 case Instruction::ZExt:
728 case Instruction::SExt:
729 case Instruction::FPTrunc:
730 case Instruction::FPExt:
731 case Instruction::UIToFP:
732 case Instruction::SIToFP:
733 case Instruction::FPToUI:
734 case Instruction::FPToSI:
735 case Instruction::PtrToInt:
736 case Instruction::IntToPtr:
737 case Instruction::BitCast:
738 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
Chris Lattner227816342006-07-14 22:20:01 +0000739 case Instruction::Select:
740 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
741 case Instruction::InsertElement:
742 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
743 case Instruction::ExtractElement:
744 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
745 case Instruction::ShuffleVector:
746 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
Chris Lattnerb5d70302007-02-19 20:01:23 +0000747 case Instruction::GetElementPtr:
748 return ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], Ops.size()-1);
Reid Spencer266e42b2006-12-23 06:05:41 +0000749 case Instruction::ICmp:
750 case Instruction::FCmp:
751 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
Chris Lattner227816342006-07-14 22:20:01 +0000752 default:
753 assert(getNumOperands() == 2 && "Must be binary operator?");
754 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000755 }
756}
757
Chris Lattner2f7c9632001-06-06 20:29:01 +0000758
759//===----------------------------------------------------------------------===//
Chris Lattner2f7c9632001-06-06 20:29:01 +0000760// isValueValidForType implementations
761
Reid Spencere7334722006-12-19 01:28:19 +0000762bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000763 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000764 if (Ty == Type::Int1Ty)
765 return Val == 0 || Val == 1;
Reid Spencerd7a00d72007-02-05 23:47:56 +0000766 if (NumBits >= 64)
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000767 return true; // always true, has to fit in largest type
768 uint64_t Max = (1ll << NumBits) - 1;
769 return Val <= Max;
Reid Spencere7334722006-12-19 01:28:19 +0000770}
771
Reid Spencere0fc4df2006-10-20 07:07:24 +0000772bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000773 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000774 if (Ty == Type::Int1Ty)
Reid Spencera94d3942007-01-19 21:13:56 +0000775 return Val == 0 || Val == 1 || Val == -1;
Reid Spencerd7a00d72007-02-05 23:47:56 +0000776 if (NumBits >= 64)
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000777 return true; // always true, has to fit in largest type
778 int64_t Min = -(1ll << (NumBits-1));
779 int64_t Max = (1ll << (NumBits-1)) - 1;
780 return (Val >= Min && Val <= Max);
Chris Lattner2f7c9632001-06-06 20:29:01 +0000781}
782
Dale Johannesend246b2c2007-08-30 00:23:21 +0000783bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
784 // convert modifies in place, so make a copy.
785 APFloat Val2 = APFloat(Val);
Chris Lattner6b727592004-06-17 18:19:28 +0000786 switch (Ty->getTypeID()) {
Chris Lattner2f7c9632001-06-06 20:29:01 +0000787 default:
788 return false; // These can't be represented as floating point!
789
Dale Johannesend246b2c2007-08-30 00:23:21 +0000790 // FIXME rounding mode needs to be more flexible
Chris Lattner2f7c9632001-06-06 20:29:01 +0000791 case Type::FloatTyID:
Dale Johannesend246b2c2007-08-30 00:23:21 +0000792 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
793 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven) ==
794 APFloat::opOK;
Chris Lattner2f7c9632001-06-06 20:29:01 +0000795 case Type::DoubleTyID:
Dale Johannesend246b2c2007-08-30 00:23:21 +0000796 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
797 &Val2.getSemantics() == &APFloat::IEEEdouble ||
798 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven) ==
799 APFloat::opOK;
Dale Johannesenbdad8092007-08-09 22:51:36 +0000800 case Type::X86_FP80TyID:
Dale Johannesen028084e2007-09-12 03:30:33 +0000801 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
802 &Val2.getSemantics() == &APFloat::IEEEdouble ||
803 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
Dale Johannesenbdad8092007-08-09 22:51:36 +0000804 case Type::FP128TyID:
Dale Johannesen028084e2007-09-12 03:30:33 +0000805 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
806 &Val2.getSemantics() == &APFloat::IEEEdouble ||
807 &Val2.getSemantics() == &APFloat::IEEEquad;
Dale Johannesen007aa372007-10-11 18:07:22 +0000808 case Type::PPC_FP128TyID:
809 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
810 &Val2.getSemantics() == &APFloat::IEEEdouble ||
811 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
Chris Lattner2f7c9632001-06-06 20:29:01 +0000812 }
Chris Lattneraa2372562006-05-24 17:04:05 +0000813}
Chris Lattner9655e542001-07-20 19:16:02 +0000814
Chris Lattner49d855c2001-09-07 16:46:31 +0000815//===----------------------------------------------------------------------===//
Chris Lattner49d855c2001-09-07 16:46:31 +0000816// Factory Function Implementation
817
Chris Lattner98fa07b2003-05-23 20:03:32 +0000818// ConstantCreator - A class that is used to create constants by
819// ValueMap*. This class should be partially specialized if there is
820// something strange that needs to be done to interface to the ctor for the
821// constant.
822//
Chris Lattner189d19f2003-11-21 20:23:48 +0000823namespace llvm {
824 template<class ConstantClass, class TypeClass, class ValType>
Chris Lattner02157b02006-06-28 21:38:54 +0000825 struct VISIBILITY_HIDDEN ConstantCreator {
Chris Lattner189d19f2003-11-21 20:23:48 +0000826 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
Gabor Greifdd8b7a02008-04-06 21:42:13 +0000827 unsigned FIXME = 0; // = traits<ValType>::uses(V)
Gabor Greife9ecc682008-04-06 20:25:17 +0000828 return new(FIXME) ConstantClass(Ty, V);
Chris Lattner189d19f2003-11-21 20:23:48 +0000829 }
830 };
Misha Brukmanb1c93172005-04-21 23:48:37 +0000831
Chris Lattner189d19f2003-11-21 20:23:48 +0000832 template<class ConstantClass, class TypeClass>
Chris Lattner02157b02006-06-28 21:38:54 +0000833 struct VISIBILITY_HIDDEN ConvertConstantType {
Chris Lattner189d19f2003-11-21 20:23:48 +0000834 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
835 assert(0 && "This type cannot be converted!\n");
836 abort();
837 }
838 };
Chris Lattnerb50d1352003-10-05 00:17:43 +0000839
Chris Lattner935aa922005-10-04 17:48:46 +0000840 template<class ValType, class TypeClass, class ConstantClass,
841 bool HasLargeKey = false /*true for arrays and structs*/ >
Chris Lattner02157b02006-06-28 21:38:54 +0000842 class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
Chris Lattnerb64419a2005-10-03 22:51:37 +0000843 public:
Jim Laskeyc03caef2006-07-17 17:38:29 +0000844 typedef std::pair<const Type*, ValType> MapKey;
845 typedef std::map<MapKey, Constant *> MapTy;
846 typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
847 typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
Chris Lattnerb64419a2005-10-03 22:51:37 +0000848 private:
Chris Lattner5bbf60a52005-10-04 16:52:46 +0000849 /// Map - This is the main map from the element descriptor to the Constants.
850 /// This is the primary way we avoid creating two of the same shape
851 /// constant.
Chris Lattnerb50d1352003-10-05 00:17:43 +0000852 MapTy Map;
Chris Lattner935aa922005-10-04 17:48:46 +0000853
854 /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
855 /// from the constants to their element in Map. This is important for
856 /// removal of constants from the array, which would otherwise have to scan
857 /// through the map with very large keys.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000858 InverseMapTy InverseMap;
Chris Lattnerb50d1352003-10-05 00:17:43 +0000859
Jim Laskeyc03caef2006-07-17 17:38:29 +0000860 /// AbstractTypeMap - Map for abstract type constants.
861 ///
Chris Lattnerb50d1352003-10-05 00:17:43 +0000862 AbstractTypeMapTy AbstractTypeMap;
Chris Lattner99a669b2004-11-19 16:39:44 +0000863
Chris Lattner98fa07b2003-05-23 20:03:32 +0000864 public:
Jim Laskeyc03caef2006-07-17 17:38:29 +0000865 typename MapTy::iterator map_end() { return Map.end(); }
Chris Lattnerb64419a2005-10-03 22:51:37 +0000866
867 /// InsertOrGetItem - Return an iterator for the specified element.
868 /// If the element exists in the map, the returned iterator points to the
869 /// entry and Exists=true. If not, the iterator points to the newly
870 /// inserted entry and returns Exists=false. Newly inserted entries have
871 /// I->second == 0, and should be filled in.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000872 typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
873 &InsertVal,
Chris Lattnerb64419a2005-10-03 22:51:37 +0000874 bool &Exists) {
Jim Laskeyc03caef2006-07-17 17:38:29 +0000875 std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
Chris Lattnerb64419a2005-10-03 22:51:37 +0000876 Exists = !IP.second;
877 return IP.first;
878 }
Chris Lattner5bbf60a52005-10-04 16:52:46 +0000879
Chris Lattner935aa922005-10-04 17:48:46 +0000880private:
Jim Laskeyc03caef2006-07-17 17:38:29 +0000881 typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
Chris Lattner935aa922005-10-04 17:48:46 +0000882 if (HasLargeKey) {
Jim Laskeyc03caef2006-07-17 17:38:29 +0000883 typename InverseMapTy::iterator IMI = InverseMap.find(CP);
Chris Lattner935aa922005-10-04 17:48:46 +0000884 assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
885 IMI->second->second == CP &&
886 "InverseMap corrupt!");
887 return IMI->second;
888 }
889
Jim Laskeyc03caef2006-07-17 17:38:29 +0000890 typename MapTy::iterator I =
Chris Lattner935aa922005-10-04 17:48:46 +0000891 Map.find(MapKey((TypeClass*)CP->getRawType(), getValType(CP)));
Chris Lattner5bbf60a52005-10-04 16:52:46 +0000892 if (I == Map.end() || I->second != CP) {
893 // FIXME: This should not use a linear scan. If this gets to be a
894 // performance problem, someone should look at this.
895 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
896 /* empty */;
897 }
Chris Lattner935aa922005-10-04 17:48:46 +0000898 return I;
899 }
900public:
901
Chris Lattnerb64419a2005-10-03 22:51:37 +0000902 /// getOrCreate - Return the specified constant from the map, creating it if
903 /// necessary.
Chris Lattner98fa07b2003-05-23 20:03:32 +0000904 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
Chris Lattnerb50d1352003-10-05 00:17:43 +0000905 MapKey Lookup(Ty, V);
Jim Laskeyc03caef2006-07-17 17:38:29 +0000906 typename MapTy::iterator I = Map.lower_bound(Lookup);
Reid Spencere0fc4df2006-10-20 07:07:24 +0000907 // Is it in the map?
Chris Lattner98fa07b2003-05-23 20:03:32 +0000908 if (I != Map.end() && I->first == Lookup)
Reid Spencere0fc4df2006-10-20 07:07:24 +0000909 return static_cast<ConstantClass *>(I->second);
Chris Lattner98fa07b2003-05-23 20:03:32 +0000910
911 // If no preexisting value, create one now...
912 ConstantClass *Result =
913 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
914
Chris Lattnerb50d1352003-10-05 00:17:43 +0000915 /// FIXME: why does this assert fail when loading 176.gcc?
916 //assert(Result->getType() == Ty && "Type specified is not correct!");
917 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
918
Chris Lattner935aa922005-10-04 17:48:46 +0000919 if (HasLargeKey) // Remember the reverse mapping if needed.
920 InverseMap.insert(std::make_pair(Result, I));
921
Chris Lattnerb50d1352003-10-05 00:17:43 +0000922 // If the type of the constant is abstract, make sure that an entry exists
923 // for it in the AbstractTypeMap.
924 if (Ty->isAbstract()) {
925 typename AbstractTypeMapTy::iterator TI =
926 AbstractTypeMap.lower_bound(Ty);
927
928 if (TI == AbstractTypeMap.end() || TI->first != Ty) {
929 // Add ourselves to the ATU list of the type.
930 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
931
932 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
933 }
934 }
Chris Lattner98fa07b2003-05-23 20:03:32 +0000935 return Result;
936 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000937
Chris Lattner98fa07b2003-05-23 20:03:32 +0000938 void remove(ConstantClass *CP) {
Jim Laskeyc03caef2006-07-17 17:38:29 +0000939 typename MapTy::iterator I = FindExistingElement(CP);
Chris Lattnerb50d1352003-10-05 00:17:43 +0000940 assert(I != Map.end() && "Constant not found in constant table!");
Chris Lattner3e650af2004-08-04 04:48:01 +0000941 assert(I->second == CP && "Didn't find correct element?");
Chris Lattnerb50d1352003-10-05 00:17:43 +0000942
Chris Lattner935aa922005-10-04 17:48:46 +0000943 if (HasLargeKey) // Remember the reverse mapping if needed.
944 InverseMap.erase(CP);
945
Chris Lattnerb50d1352003-10-05 00:17:43 +0000946 // Now that we found the entry, make sure this isn't the entry that
947 // the AbstractTypeMap points to.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000948 const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
Chris Lattnerb50d1352003-10-05 00:17:43 +0000949 if (Ty->isAbstract()) {
950 assert(AbstractTypeMap.count(Ty) &&
951 "Abstract type not in AbstractTypeMap?");
Jim Laskeyc03caef2006-07-17 17:38:29 +0000952 typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
Chris Lattnerb50d1352003-10-05 00:17:43 +0000953 if (ATMEntryIt == I) {
954 // Yes, we are removing the representative entry for this type.
955 // See if there are any other entries of the same type.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000956 typename MapTy::iterator TmpIt = ATMEntryIt;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000957
Chris Lattnerb50d1352003-10-05 00:17:43 +0000958 // First check the entry before this one...
959 if (TmpIt != Map.begin()) {
960 --TmpIt;
961 if (TmpIt->first.first != Ty) // Not the same type, move back...
962 ++TmpIt;
963 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000964
Chris Lattnerb50d1352003-10-05 00:17:43 +0000965 // If we didn't find the same type, try to move forward...
966 if (TmpIt == ATMEntryIt) {
967 ++TmpIt;
968 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
969 --TmpIt; // No entry afterwards with the same type
970 }
971
972 // If there is another entry in the map of the same abstract type,
973 // update the AbstractTypeMap entry now.
974 if (TmpIt != ATMEntryIt) {
975 ATMEntryIt = TmpIt;
976 } else {
977 // Otherwise, we are removing the last instance of this type
978 // from the table. Remove from the ATM, and from user list.
979 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
980 AbstractTypeMap.erase(Ty);
981 }
Chris Lattner98fa07b2003-05-23 20:03:32 +0000982 }
Chris Lattnerb50d1352003-10-05 00:17:43 +0000983 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000984
Chris Lattnerb50d1352003-10-05 00:17:43 +0000985 Map.erase(I);
986 }
987
Chris Lattner3b793c62005-10-04 21:35:50 +0000988
989 /// MoveConstantToNewSlot - If we are about to change C to be the element
990 /// specified by I, update our internal data structures to reflect this
991 /// fact.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000992 void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
Chris Lattner3b793c62005-10-04 21:35:50 +0000993 // First, remove the old location of the specified constant in the map.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000994 typename MapTy::iterator OldI = FindExistingElement(C);
Chris Lattner3b793c62005-10-04 21:35:50 +0000995 assert(OldI != Map.end() && "Constant not found in constant table!");
996 assert(OldI->second == C && "Didn't find correct element?");
997
998 // If this constant is the representative element for its abstract type,
999 // update the AbstractTypeMap so that the representative element is I.
1000 if (C->getType()->isAbstract()) {
1001 typename AbstractTypeMapTy::iterator ATI =
1002 AbstractTypeMap.find(C->getType());
1003 assert(ATI != AbstractTypeMap.end() &&
1004 "Abstract type not in AbstractTypeMap?");
1005 if (ATI->second == OldI)
1006 ATI->second = I;
1007 }
1008
1009 // Remove the old entry from the map.
1010 Map.erase(OldI);
1011
1012 // Update the inverse map so that we know that this constant is now
1013 // located at descriptor I.
1014 if (HasLargeKey) {
1015 assert(I->second == C && "Bad inversemap entry!");
1016 InverseMap[C] = I;
1017 }
1018 }
1019
Chris Lattnerb50d1352003-10-05 00:17:43 +00001020 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00001021 typename AbstractTypeMapTy::iterator I =
Jim Laskeyc03caef2006-07-17 17:38:29 +00001022 AbstractTypeMap.find(cast<Type>(OldTy));
Chris Lattnerb50d1352003-10-05 00:17:43 +00001023
1024 assert(I != AbstractTypeMap.end() &&
1025 "Abstract type not in AbstractTypeMap?");
1026
1027 // Convert a constant at a time until the last one is gone. The last one
1028 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
1029 // eliminated eventually.
1030 do {
1031 ConvertConstantType<ConstantClass,
Jim Laskeyc03caef2006-07-17 17:38:29 +00001032 TypeClass>::convert(
1033 static_cast<ConstantClass *>(I->second->second),
Chris Lattnerb50d1352003-10-05 00:17:43 +00001034 cast<TypeClass>(NewTy));
1035
Jim Laskeyc03caef2006-07-17 17:38:29 +00001036 I = AbstractTypeMap.find(cast<Type>(OldTy));
Chris Lattnerb50d1352003-10-05 00:17:43 +00001037 } while (I != AbstractTypeMap.end());
1038 }
1039
1040 // If the type became concrete without being refined to any other existing
1041 // type, we just remove ourselves from the ATU list.
1042 void typeBecameConcrete(const DerivedType *AbsTy) {
1043 AbsTy->removeAbstractTypeUser(this);
1044 }
1045
1046 void dump() const {
Bill Wendling6a462f12006-11-17 08:03:48 +00001047 DOUT << "Constant.cpp: ValueMap\n";
Chris Lattner98fa07b2003-05-23 20:03:32 +00001048 }
1049 };
1050}
1051
Chris Lattnera84df0a22006-09-28 23:36:21 +00001052
Chris Lattner28173502007-02-20 06:11:36 +00001053
Chris Lattner9fba3da2004-02-15 05:53:04 +00001054//---- ConstantAggregateZero::get() implementation...
1055//
1056namespace llvm {
1057 // ConstantAggregateZero does not take extra "value" argument...
1058 template<class ValType>
1059 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
1060 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
1061 return new ConstantAggregateZero(Ty);
1062 }
1063 };
1064
1065 template<>
1066 struct ConvertConstantType<ConstantAggregateZero, Type> {
1067 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
1068 // Make everyone now use a constant of the new type...
1069 Constant *New = ConstantAggregateZero::get(NewTy);
1070 assert(New != OldC && "Didn't replace constant??");
1071 OldC->uncheckedReplaceAllUsesWith(New);
1072 OldC->destroyConstant(); // This constant is now dead, destroy it.
1073 }
1074 };
1075}
1076
Chris Lattner69edc982006-09-28 00:35:06 +00001077static ManagedStatic<ValueMap<char, Type,
1078 ConstantAggregateZero> > AggZeroConstants;
Chris Lattner9fba3da2004-02-15 05:53:04 +00001079
Chris Lattner3e650af2004-08-04 04:48:01 +00001080static char getValType(ConstantAggregateZero *CPZ) { return 0; }
1081
Chris Lattner9fba3da2004-02-15 05:53:04 +00001082Constant *ConstantAggregateZero::get(const Type *Ty) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001083 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) &&
Chris Lattnerbfd0b6d2006-06-10 04:16:23 +00001084 "Cannot create an aggregate zero of non-aggregate type!");
Chris Lattner69edc982006-09-28 00:35:06 +00001085 return AggZeroConstants->getOrCreate(Ty, 0);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001086}
1087
1088// destroyConstant - Remove the constant from the constant table...
1089//
1090void ConstantAggregateZero::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001091 AggZeroConstants->remove(this);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001092 destroyConstantImpl();
1093}
1094
Chris Lattner3462ae32001-12-03 22:26:30 +00001095//---- ConstantArray::get() implementation...
Chris Lattner49d855c2001-09-07 16:46:31 +00001096//
Chris Lattner189d19f2003-11-21 20:23:48 +00001097namespace llvm {
1098 template<>
1099 struct ConvertConstantType<ConstantArray, ArrayType> {
1100 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
1101 // Make everyone now use a constant of the new type...
1102 std::vector<Constant*> C;
1103 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1104 C.push_back(cast<Constant>(OldC->getOperand(i)));
1105 Constant *New = ConstantArray::get(NewTy, C);
1106 assert(New != OldC && "Didn't replace constant??");
1107 OldC->uncheckedReplaceAllUsesWith(New);
1108 OldC->destroyConstant(); // This constant is now dead, destroy it.
1109 }
1110 };
1111}
Chris Lattnerb50d1352003-10-05 00:17:43 +00001112
Chris Lattner3e650af2004-08-04 04:48:01 +00001113static std::vector<Constant*> getValType(ConstantArray *CA) {
1114 std::vector<Constant*> Elements;
1115 Elements.reserve(CA->getNumOperands());
1116 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1117 Elements.push_back(cast<Constant>(CA->getOperand(i)));
1118 return Elements;
1119}
1120
Chris Lattnerb64419a2005-10-03 22:51:37 +00001121typedef ValueMap<std::vector<Constant*>, ArrayType,
Chris Lattner935aa922005-10-04 17:48:46 +00001122 ConstantArray, true /*largekey*/> ArrayConstantsTy;
Chris Lattner69edc982006-09-28 00:35:06 +00001123static ManagedStatic<ArrayConstantsTy> ArrayConstants;
Chris Lattner49d855c2001-09-07 16:46:31 +00001124
Chris Lattner015e8212004-02-15 04:14:47 +00001125Constant *ConstantArray::get(const ArrayType *Ty,
Chris Lattner9fba3da2004-02-15 05:53:04 +00001126 const std::vector<Constant*> &V) {
1127 // If this is an all-zero array, return a ConstantAggregateZero object
1128 if (!V.empty()) {
1129 Constant *C = V[0];
1130 if (!C->isNullValue())
Chris Lattner69edc982006-09-28 00:35:06 +00001131 return ArrayConstants->getOrCreate(Ty, V);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001132 for (unsigned i = 1, e = V.size(); i != e; ++i)
1133 if (V[i] != C)
Chris Lattner69edc982006-09-28 00:35:06 +00001134 return ArrayConstants->getOrCreate(Ty, V);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001135 }
1136 return ConstantAggregateZero::get(Ty);
Chris Lattner49d855c2001-09-07 16:46:31 +00001137}
1138
Chris Lattner98fa07b2003-05-23 20:03:32 +00001139// destroyConstant - Remove the constant from the constant table...
1140//
1141void ConstantArray::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001142 ArrayConstants->remove(this);
Chris Lattner98fa07b2003-05-23 20:03:32 +00001143 destroyConstantImpl();
1144}
1145
Reid Spencer6f614532006-05-30 08:23:18 +00001146/// ConstantArray::get(const string&) - Return an array that is initialized to
1147/// contain the specified string. If length is zero then a null terminator is
1148/// added to the specified string so that it may be used in a natural way.
1149/// Otherwise, the length parameter specifies how much of the string to use
1150/// and it won't be null terminated.
1151///
Reid Spencer82ebaba2006-05-30 18:15:07 +00001152Constant *ConstantArray::get(const std::string &Str, bool AddNull) {
Chris Lattner7f74a562002-01-20 22:54:45 +00001153 std::vector<Constant*> ElementVals;
Reid Spencer82ebaba2006-05-30 18:15:07 +00001154 for (unsigned i = 0; i < Str.length(); ++i)
Reid Spencer8d9336d2006-12-31 05:26:44 +00001155 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, Str[i]));
Chris Lattner8f80fe02001-10-14 23:54:12 +00001156
1157 // Add a null terminator to the string...
Reid Spencer82ebaba2006-05-30 18:15:07 +00001158 if (AddNull) {
Reid Spencer8d9336d2006-12-31 05:26:44 +00001159 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, 0));
Reid Spencer6f614532006-05-30 08:23:18 +00001160 }
Chris Lattner8f80fe02001-10-14 23:54:12 +00001161
Reid Spencer8d9336d2006-12-31 05:26:44 +00001162 ArrayType *ATy = ArrayType::get(Type::Int8Ty, ElementVals.size());
Chris Lattner3462ae32001-12-03 22:26:30 +00001163 return ConstantArray::get(ATy, ElementVals);
Vikram S. Adve34410432001-10-14 23:17:20 +00001164}
1165
Reid Spencer2546b762007-01-26 07:37:34 +00001166/// isString - This method returns true if the array is an array of i8, and
1167/// if the elements of the array are all ConstantInt's.
Chris Lattnere8dfcca2004-01-14 17:06:38 +00001168bool ConstantArray::isString() const {
Reid Spencer2546b762007-01-26 07:37:34 +00001169 // Check the element type for i8...
Reid Spencer8d9336d2006-12-31 05:26:44 +00001170 if (getType()->getElementType() != Type::Int8Ty)
Chris Lattnere8dfcca2004-01-14 17:06:38 +00001171 return false;
1172 // Check the elements to make sure they are all integers, not constant
1173 // expressions.
1174 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1175 if (!isa<ConstantInt>(getOperand(i)))
1176 return false;
1177 return true;
1178}
1179
Evan Cheng3763c5b2006-10-26 19:15:05 +00001180/// isCString - This method returns true if the array is a string (see
1181/// isString) and it ends in a null byte \0 and does not contains any other
1182/// null bytes except its terminator.
1183bool ConstantArray::isCString() const {
Reid Spencer2546b762007-01-26 07:37:34 +00001184 // Check the element type for i8...
Reid Spencer8d9336d2006-12-31 05:26:44 +00001185 if (getType()->getElementType() != Type::Int8Ty)
Evan Chenge974da62006-10-26 21:48:03 +00001186 return false;
1187 Constant *Zero = Constant::getNullValue(getOperand(0)->getType());
1188 // Last element must be a null.
1189 if (getOperand(getNumOperands()-1) != Zero)
1190 return false;
1191 // Other elements must be non-null integers.
1192 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1193 if (!isa<ConstantInt>(getOperand(i)))
Evan Cheng3763c5b2006-10-26 19:15:05 +00001194 return false;
Evan Chenge974da62006-10-26 21:48:03 +00001195 if (getOperand(i) == Zero)
1196 return false;
1197 }
Evan Cheng3763c5b2006-10-26 19:15:05 +00001198 return true;
1199}
1200
1201
Reid Spencer2546b762007-01-26 07:37:34 +00001202// getAsString - If the sub-element type of this array is i8
Chris Lattner81fabb02002-08-26 17:53:56 +00001203// then this method converts the array to an std::string and returns it.
1204// Otherwise, it asserts out.
1205//
1206std::string ConstantArray::getAsString() const {
Chris Lattnere8dfcca2004-01-14 17:06:38 +00001207 assert(isString() && "Not a string!");
Chris Lattner81fabb02002-08-26 17:53:56 +00001208 std::string Result;
Chris Lattner6077c312003-07-23 15:22:26 +00001209 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
Reid Spencere0fc4df2006-10-20 07:07:24 +00001210 Result += (char)cast<ConstantInt>(getOperand(i))->getZExtValue();
Chris Lattner81fabb02002-08-26 17:53:56 +00001211 return Result;
1212}
1213
1214
Chris Lattner3462ae32001-12-03 22:26:30 +00001215//---- ConstantStruct::get() implementation...
Chris Lattner49d855c2001-09-07 16:46:31 +00001216//
Chris Lattnerb50d1352003-10-05 00:17:43 +00001217
Chris Lattner189d19f2003-11-21 20:23:48 +00001218namespace llvm {
1219 template<>
1220 struct ConvertConstantType<ConstantStruct, StructType> {
1221 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1222 // Make everyone now use a constant of the new type...
1223 std::vector<Constant*> C;
1224 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1225 C.push_back(cast<Constant>(OldC->getOperand(i)));
1226 Constant *New = ConstantStruct::get(NewTy, C);
1227 assert(New != OldC && "Didn't replace constant??");
Misha Brukmanb1c93172005-04-21 23:48:37 +00001228
Chris Lattner189d19f2003-11-21 20:23:48 +00001229 OldC->uncheckedReplaceAllUsesWith(New);
1230 OldC->destroyConstant(); // This constant is now dead, destroy it.
1231 }
1232 };
1233}
Chris Lattnerb50d1352003-10-05 00:17:43 +00001234
Chris Lattner8760ec72005-10-04 01:17:50 +00001235typedef ValueMap<std::vector<Constant*>, StructType,
Chris Lattner935aa922005-10-04 17:48:46 +00001236 ConstantStruct, true /*largekey*/> StructConstantsTy;
Chris Lattner69edc982006-09-28 00:35:06 +00001237static ManagedStatic<StructConstantsTy> StructConstants;
Chris Lattner49d855c2001-09-07 16:46:31 +00001238
Chris Lattner3e650af2004-08-04 04:48:01 +00001239static std::vector<Constant*> getValType(ConstantStruct *CS) {
1240 std::vector<Constant*> Elements;
1241 Elements.reserve(CS->getNumOperands());
1242 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1243 Elements.push_back(cast<Constant>(CS->getOperand(i)));
1244 return Elements;
1245}
1246
Chris Lattner015e8212004-02-15 04:14:47 +00001247Constant *ConstantStruct::get(const StructType *Ty,
1248 const std::vector<Constant*> &V) {
Chris Lattner9fba3da2004-02-15 05:53:04 +00001249 // Create a ConstantAggregateZero value if all elements are zeros...
1250 for (unsigned i = 0, e = V.size(); i != e; ++i)
1251 if (!V[i]->isNullValue())
Chris Lattner69edc982006-09-28 00:35:06 +00001252 return StructConstants->getOrCreate(Ty, V);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001253
1254 return ConstantAggregateZero::get(Ty);
Chris Lattner49d855c2001-09-07 16:46:31 +00001255}
Chris Lattner883ad0b2001-10-03 15:39:36 +00001256
Andrew Lenharthdcb3c972006-12-08 18:06:16 +00001257Constant *ConstantStruct::get(const std::vector<Constant*> &V, bool packed) {
Chris Lattnerd6108ca2004-07-12 20:35:11 +00001258 std::vector<const Type*> StructEls;
1259 StructEls.reserve(V.size());
1260 for (unsigned i = 0, e = V.size(); i != e; ++i)
1261 StructEls.push_back(V[i]->getType());
Andrew Lenharthdcb3c972006-12-08 18:06:16 +00001262 return get(StructType::get(StructEls, packed), V);
Chris Lattnerd6108ca2004-07-12 20:35:11 +00001263}
1264
Chris Lattnerd7a73302001-10-13 06:57:33 +00001265// destroyConstant - Remove the constant from the constant table...
Chris Lattner883ad0b2001-10-03 15:39:36 +00001266//
Chris Lattner3462ae32001-12-03 22:26:30 +00001267void ConstantStruct::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001268 StructConstants->remove(this);
Chris Lattnerd7a73302001-10-13 06:57:33 +00001269 destroyConstantImpl();
1270}
Chris Lattner883ad0b2001-10-03 15:39:36 +00001271
Reid Spencerd84d35b2007-02-15 02:26:10 +00001272//---- ConstantVector::get() implementation...
Brian Gaeke02209042004-08-20 06:00:58 +00001273//
1274namespace llvm {
1275 template<>
Reid Spencerd84d35b2007-02-15 02:26:10 +00001276 struct ConvertConstantType<ConstantVector, VectorType> {
1277 static void convert(ConstantVector *OldC, const VectorType *NewTy) {
Brian Gaeke02209042004-08-20 06:00:58 +00001278 // Make everyone now use a constant of the new type...
1279 std::vector<Constant*> C;
1280 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1281 C.push_back(cast<Constant>(OldC->getOperand(i)));
Reid Spencerd84d35b2007-02-15 02:26:10 +00001282 Constant *New = ConstantVector::get(NewTy, C);
Brian Gaeke02209042004-08-20 06:00:58 +00001283 assert(New != OldC && "Didn't replace constant??");
1284 OldC->uncheckedReplaceAllUsesWith(New);
1285 OldC->destroyConstant(); // This constant is now dead, destroy it.
1286 }
1287 };
1288}
1289
Reid Spencerd84d35b2007-02-15 02:26:10 +00001290static std::vector<Constant*> getValType(ConstantVector *CP) {
Brian Gaeke02209042004-08-20 06:00:58 +00001291 std::vector<Constant*> Elements;
1292 Elements.reserve(CP->getNumOperands());
1293 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1294 Elements.push_back(CP->getOperand(i));
1295 return Elements;
1296}
1297
Reid Spencerd84d35b2007-02-15 02:26:10 +00001298static ManagedStatic<ValueMap<std::vector<Constant*>, VectorType,
Reid Spencer09575ba2007-02-15 03:39:18 +00001299 ConstantVector> > VectorConstants;
Brian Gaeke02209042004-08-20 06:00:58 +00001300
Reid Spencerd84d35b2007-02-15 02:26:10 +00001301Constant *ConstantVector::get(const VectorType *Ty,
Brian Gaeke02209042004-08-20 06:00:58 +00001302 const std::vector<Constant*> &V) {
Dan Gohman30978072007-05-24 14:36:04 +00001303 // If this is an all-zero vector, return a ConstantAggregateZero object
Brian Gaeke02209042004-08-20 06:00:58 +00001304 if (!V.empty()) {
1305 Constant *C = V[0];
1306 if (!C->isNullValue())
Reid Spencer09575ba2007-02-15 03:39:18 +00001307 return VectorConstants->getOrCreate(Ty, V);
Brian Gaeke02209042004-08-20 06:00:58 +00001308 for (unsigned i = 1, e = V.size(); i != e; ++i)
1309 if (V[i] != C)
Reid Spencer09575ba2007-02-15 03:39:18 +00001310 return VectorConstants->getOrCreate(Ty, V);
Brian Gaeke02209042004-08-20 06:00:58 +00001311 }
1312 return ConstantAggregateZero::get(Ty);
1313}
1314
Reid Spencerd84d35b2007-02-15 02:26:10 +00001315Constant *ConstantVector::get(const std::vector<Constant*> &V) {
Brian Gaeke02209042004-08-20 06:00:58 +00001316 assert(!V.empty() && "Cannot infer type if V is empty");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001317 return get(VectorType::get(V.front()->getType(),V.size()), V);
Brian Gaeke02209042004-08-20 06:00:58 +00001318}
1319
1320// destroyConstant - Remove the constant from the constant table...
1321//
Reid Spencerd84d35b2007-02-15 02:26:10 +00001322void ConstantVector::destroyConstant() {
Reid Spencer09575ba2007-02-15 03:39:18 +00001323 VectorConstants->remove(this);
Brian Gaeke02209042004-08-20 06:00:58 +00001324 destroyConstantImpl();
1325}
1326
Dan Gohman30978072007-05-24 14:36:04 +00001327/// This function will return true iff every element in this vector constant
Jim Laskeyf0478822007-01-12 22:39:14 +00001328/// is set to all ones.
1329/// @returns true iff this constant's emements are all set to all ones.
1330/// @brief Determine if the value is all ones.
Reid Spencerd84d35b2007-02-15 02:26:10 +00001331bool ConstantVector::isAllOnesValue() const {
Jim Laskeyf0478822007-01-12 22:39:14 +00001332 // Check out first element.
1333 const Constant *Elt = getOperand(0);
1334 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1335 if (!CI || !CI->isAllOnesValue()) return false;
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 false;
1339 }
1340 return true;
1341}
1342
Dan Gohman07159202007-10-17 17:51:30 +00001343/// getSplatValue - If this is a splat constant, where all of the
1344/// elements have the same value, return that value. Otherwise return null.
1345Constant *ConstantVector::getSplatValue() {
1346 // Check out first element.
1347 Constant *Elt = getOperand(0);
1348 // Then make sure all remaining elements point to the same value.
1349 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1350 if (getOperand(I) != Elt) return 0;
1351 return Elt;
1352}
1353
Chris Lattner3462ae32001-12-03 22:26:30 +00001354//---- ConstantPointerNull::get() implementation...
Chris Lattnerd7a73302001-10-13 06:57:33 +00001355//
Chris Lattner98fa07b2003-05-23 20:03:32 +00001356
Chris Lattner189d19f2003-11-21 20:23:48 +00001357namespace llvm {
1358 // ConstantPointerNull does not take extra "value" argument...
1359 template<class ValType>
1360 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1361 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1362 return new ConstantPointerNull(Ty);
1363 }
1364 };
Chris Lattner98fa07b2003-05-23 20:03:32 +00001365
Chris Lattner189d19f2003-11-21 20:23:48 +00001366 template<>
1367 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1368 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1369 // Make everyone now use a constant of the new type...
1370 Constant *New = ConstantPointerNull::get(NewTy);
1371 assert(New != OldC && "Didn't replace constant??");
1372 OldC->uncheckedReplaceAllUsesWith(New);
1373 OldC->destroyConstant(); // This constant is now dead, destroy it.
1374 }
1375 };
1376}
Chris Lattnerb50d1352003-10-05 00:17:43 +00001377
Chris Lattner69edc982006-09-28 00:35:06 +00001378static ManagedStatic<ValueMap<char, PointerType,
1379 ConstantPointerNull> > NullPtrConstants;
Chris Lattnerd7a73302001-10-13 06:57:33 +00001380
Chris Lattner3e650af2004-08-04 04:48:01 +00001381static char getValType(ConstantPointerNull *) {
1382 return 0;
1383}
1384
1385
Chris Lattner3462ae32001-12-03 22:26:30 +00001386ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
Chris Lattner69edc982006-09-28 00:35:06 +00001387 return NullPtrConstants->getOrCreate(Ty, 0);
Chris Lattner883ad0b2001-10-03 15:39:36 +00001388}
1389
Chris Lattner0c6e0b92002-08-18 00:40:04 +00001390// destroyConstant - Remove the constant from the constant table...
1391//
1392void ConstantPointerNull::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001393 NullPtrConstants->remove(this);
Chris Lattner0c6e0b92002-08-18 00:40:04 +00001394 destroyConstantImpl();
1395}
1396
1397
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001398//---- UndefValue::get() implementation...
1399//
1400
1401namespace llvm {
1402 // UndefValue does not take extra "value" argument...
1403 template<class ValType>
1404 struct ConstantCreator<UndefValue, Type, ValType> {
1405 static UndefValue *create(const Type *Ty, const ValType &V) {
1406 return new UndefValue(Ty);
1407 }
1408 };
1409
1410 template<>
1411 struct ConvertConstantType<UndefValue, Type> {
1412 static void convert(UndefValue *OldC, const Type *NewTy) {
1413 // Make everyone now use a constant of the new type.
1414 Constant *New = UndefValue::get(NewTy);
1415 assert(New != OldC && "Didn't replace constant??");
1416 OldC->uncheckedReplaceAllUsesWith(New);
1417 OldC->destroyConstant(); // This constant is now dead, destroy it.
1418 }
1419 };
1420}
1421
Chris Lattner69edc982006-09-28 00:35:06 +00001422static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001423
1424static char getValType(UndefValue *) {
1425 return 0;
1426}
1427
1428
1429UndefValue *UndefValue::get(const Type *Ty) {
Chris Lattner69edc982006-09-28 00:35:06 +00001430 return UndefValueConstants->getOrCreate(Ty, 0);
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001431}
1432
1433// destroyConstant - Remove the constant from the constant table.
1434//
1435void UndefValue::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001436 UndefValueConstants->remove(this);
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001437 destroyConstantImpl();
1438}
1439
1440
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001441//---- ConstantExpr::get() implementations...
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001442//
Reid Spencer8d9336d2006-12-31 05:26:44 +00001443
Reid Spenceree3c9912006-12-04 05:19:50 +00001444struct ExprMapKeyType {
1445 explicit ExprMapKeyType(unsigned opc, std::vector<Constant*> ops,
Reid Spencerdba6aa42006-12-04 18:38:05 +00001446 unsigned short pred = 0) : opcode(opc), predicate(pred), operands(ops) { }
1447 uint16_t opcode;
1448 uint16_t predicate;
Reid Spenceree3c9912006-12-04 05:19:50 +00001449 std::vector<Constant*> operands;
Reid Spenceree3c9912006-12-04 05:19:50 +00001450 bool operator==(const ExprMapKeyType& that) const {
1451 return this->opcode == that.opcode &&
1452 this->predicate == that.predicate &&
1453 this->operands == that.operands;
1454 }
1455 bool operator<(const ExprMapKeyType & that) const {
1456 return this->opcode < that.opcode ||
1457 (this->opcode == that.opcode && this->predicate < that.predicate) ||
1458 (this->opcode == that.opcode && this->predicate == that.predicate &&
1459 this->operands < that.operands);
1460 }
1461
1462 bool operator!=(const ExprMapKeyType& that) const {
1463 return !(*this == that);
1464 }
1465};
Chris Lattner98fa07b2003-05-23 20:03:32 +00001466
Chris Lattner189d19f2003-11-21 20:23:48 +00001467namespace llvm {
1468 template<>
1469 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
Reid Spencer10fbf0e2006-12-03 05:48:19 +00001470 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1471 unsigned short pred = 0) {
Reid Spenceree3c9912006-12-04 05:19:50 +00001472 if (Instruction::isCast(V.opcode))
1473 return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1474 if ((V.opcode >= Instruction::BinaryOpsBegin &&
Reid Spencer2341c222007-02-02 02:16:23 +00001475 V.opcode < Instruction::BinaryOpsEnd))
Reid Spenceree3c9912006-12-04 05:19:50 +00001476 return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1477 if (V.opcode == Instruction::Select)
1478 return new SelectConstantExpr(V.operands[0], V.operands[1],
1479 V.operands[2]);
1480 if (V.opcode == Instruction::ExtractElement)
1481 return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1482 if (V.opcode == Instruction::InsertElement)
1483 return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1484 V.operands[2]);
1485 if (V.opcode == Instruction::ShuffleVector)
1486 return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1487 V.operands[2]);
1488 if (V.opcode == Instruction::GetElementPtr) {
1489 std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
Gabor Greife9ecc682008-04-06 20:25:17 +00001490 return GetElementPtrConstantExpr::Create(V.operands[0], IdxList, Ty);
Reid Spenceree3c9912006-12-04 05:19:50 +00001491 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001492
Reid Spenceree3c9912006-12-04 05:19:50 +00001493 // The compare instructions are weird. We have to encode the predicate
1494 // value and it is combined with the instruction opcode by multiplying
1495 // the opcode by one hundred. We must decode this to get the predicate.
1496 if (V.opcode == Instruction::ICmp)
1497 return new CompareConstantExpr(Instruction::ICmp, V.predicate,
1498 V.operands[0], V.operands[1]);
1499 if (V.opcode == Instruction::FCmp)
1500 return new CompareConstantExpr(Instruction::FCmp, V.predicate,
1501 V.operands[0], V.operands[1]);
1502 assert(0 && "Invalid ConstantExpr!");
Jeff Cohen9f469632006-12-15 21:47:01 +00001503 return 0;
Chris Lattnerb50d1352003-10-05 00:17:43 +00001504 }
Chris Lattner189d19f2003-11-21 20:23:48 +00001505 };
Chris Lattnerb50d1352003-10-05 00:17:43 +00001506
Chris Lattner189d19f2003-11-21 20:23:48 +00001507 template<>
1508 struct ConvertConstantType<ConstantExpr, Type> {
1509 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1510 Constant *New;
1511 switch (OldC->getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001512 case Instruction::Trunc:
1513 case Instruction::ZExt:
1514 case Instruction::SExt:
1515 case Instruction::FPTrunc:
1516 case Instruction::FPExt:
1517 case Instruction::UIToFP:
1518 case Instruction::SIToFP:
1519 case Instruction::FPToUI:
1520 case Instruction::FPToSI:
1521 case Instruction::PtrToInt:
1522 case Instruction::IntToPtr:
1523 case Instruction::BitCast:
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001524 New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0),
1525 NewTy);
Chris Lattner189d19f2003-11-21 20:23:48 +00001526 break;
Chris Lattner6e415c02004-03-12 05:54:04 +00001527 case Instruction::Select:
1528 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1529 OldC->getOperand(1),
1530 OldC->getOperand(2));
1531 break;
Chris Lattner189d19f2003-11-21 20:23:48 +00001532 default:
1533 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
Reid Spencer7eb55b32006-11-02 01:53:59 +00001534 OldC->getOpcode() < Instruction::BinaryOpsEnd);
Chris Lattner189d19f2003-11-21 20:23:48 +00001535 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1536 OldC->getOperand(1));
1537 break;
1538 case Instruction::GetElementPtr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00001539 // Make everyone now use a constant of the new type...
Chris Lattner13128ab2004-10-11 22:52:25 +00001540 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
Chris Lattner302116a2007-01-31 04:40:28 +00001541 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0),
1542 &Idx[0], Idx.size());
Chris Lattner189d19f2003-11-21 20:23:48 +00001543 break;
1544 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001545
Chris Lattner189d19f2003-11-21 20:23:48 +00001546 assert(New != OldC && "Didn't replace constant??");
1547 OldC->uncheckedReplaceAllUsesWith(New);
1548 OldC->destroyConstant(); // This constant is now dead, destroy it.
1549 }
1550 };
1551} // end namespace llvm
Chris Lattnerb50d1352003-10-05 00:17:43 +00001552
1553
Chris Lattner3e650af2004-08-04 04:48:01 +00001554static ExprMapKeyType getValType(ConstantExpr *CE) {
1555 std::vector<Constant*> Operands;
1556 Operands.reserve(CE->getNumOperands());
1557 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1558 Operands.push_back(cast<Constant>(CE->getOperand(i)));
Reid Spenceree3c9912006-12-04 05:19:50 +00001559 return ExprMapKeyType(CE->getOpcode(), Operands,
1560 CE->isCompare() ? CE->getPredicate() : 0);
Chris Lattner3e650af2004-08-04 04:48:01 +00001561}
1562
Chris Lattner69edc982006-09-28 00:35:06 +00001563static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1564 ConstantExpr> > ExprConstants;
Vikram S. Adve4c485332002-07-15 18:19:33 +00001565
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001566/// This is a utility function to handle folding of casts and lookup of the
Duncan Sands7d6c8ae2008-03-30 19:38:55 +00001567/// cast in the ExprConstants map. It is used by the various get* methods below.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001568static inline Constant *getFoldedCast(
1569 Instruction::CastOps opc, Constant *C, const Type *Ty) {
Chris Lattner815ae2b2003-10-07 22:19:19 +00001570 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001571 // Fold a few common cases
1572 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1573 return FC;
Chris Lattneracdbe712003-04-17 19:24:48 +00001574
Vikram S. Adve4c485332002-07-15 18:19:33 +00001575 // Look up the constant in the table first to ensure uniqueness
Chris Lattner2b383d2e2003-05-13 21:37:02 +00001576 std::vector<Constant*> argVec(1, C);
Reid Spenceree3c9912006-12-04 05:19:50 +00001577 ExprMapKeyType Key(opc, argVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001578 return ExprConstants->getOrCreate(Ty, Key);
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001579}
Reid Spencerf37dc652006-12-05 19:14:13 +00001580
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001581Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1582 Instruction::CastOps opc = Instruction::CastOps(oc);
1583 assert(Instruction::isCast(opc) && "opcode out of range");
1584 assert(C && Ty && "Null arguments to getCast");
1585 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1586
1587 switch (opc) {
1588 default:
1589 assert(0 && "Invalid cast opcode");
1590 break;
1591 case Instruction::Trunc: return getTrunc(C, Ty);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001592 case Instruction::ZExt: return getZExt(C, Ty);
1593 case Instruction::SExt: return getSExt(C, Ty);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001594 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1595 case Instruction::FPExt: return getFPExtend(C, Ty);
1596 case Instruction::UIToFP: return getUIToFP(C, Ty);
1597 case Instruction::SIToFP: return getSIToFP(C, Ty);
1598 case Instruction::FPToUI: return getFPToUI(C, Ty);
1599 case Instruction::FPToSI: return getFPToSI(C, Ty);
1600 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1601 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1602 case Instruction::BitCast: return getBitCast(C, Ty);
Chris Lattner1ece6f82005-01-01 15:59:57 +00001603 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001604 return 0;
Reid Spencerf37dc652006-12-05 19:14:13 +00001605}
1606
Reid Spencer5c140882006-12-04 20:17:56 +00001607Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1608 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1609 return getCast(Instruction::BitCast, C, Ty);
1610 return getCast(Instruction::ZExt, C, Ty);
1611}
1612
1613Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1614 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1615 return getCast(Instruction::BitCast, C, Ty);
1616 return getCast(Instruction::SExt, C, Ty);
1617}
1618
1619Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1620 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1621 return getCast(Instruction::BitCast, C, Ty);
1622 return getCast(Instruction::Trunc, C, Ty);
1623}
1624
Reid Spencerbc245a02006-12-05 03:25:26 +00001625Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1626 assert(isa<PointerType>(S->getType()) && "Invalid cast");
Chris Lattner03c49532007-01-15 02:27:26 +00001627 assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
Reid Spencerbc245a02006-12-05 03:25:26 +00001628
Chris Lattner03c49532007-01-15 02:27:26 +00001629 if (Ty->isInteger())
Reid Spencerbc245a02006-12-05 03:25:26 +00001630 return getCast(Instruction::PtrToInt, S, Ty);
1631 return getCast(Instruction::BitCast, S, Ty);
1632}
1633
Reid Spencer56521c42006-12-12 00:51:07 +00001634Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
1635 bool isSigned) {
Chris Lattner03c49532007-01-15 02:27:26 +00001636 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
Reid Spencer56521c42006-12-12 00:51:07 +00001637 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1638 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1639 Instruction::CastOps opcode =
1640 (SrcBits == DstBits ? Instruction::BitCast :
1641 (SrcBits > DstBits ? Instruction::Trunc :
1642 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1643 return getCast(opcode, C, Ty);
1644}
1645
1646Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1647 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1648 "Invalid cast");
1649 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1650 unsigned DstBits = Ty->getPrimitiveSizeInBits();
Reid Spencerca104e82006-12-12 05:38:50 +00001651 if (SrcBits == DstBits)
1652 return C; // Avoid a useless cast
Reid Spencer56521c42006-12-12 00:51:07 +00001653 Instruction::CastOps opcode =
Reid Spencerca104e82006-12-12 05:38:50 +00001654 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
Reid Spencer56521c42006-12-12 00:51:07 +00001655 return getCast(opcode, C, Ty);
1656}
1657
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001658Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
Chris Lattner03c49532007-01-15 02:27:26 +00001659 assert(C->getType()->isInteger() && "Trunc operand must be integer");
1660 assert(Ty->isInteger() && "Trunc produces only integral");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001661 assert(C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1662 "SrcTy must be larger than DestTy for Trunc!");
1663
1664 return getFoldedCast(Instruction::Trunc, C, Ty);
1665}
1666
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001667Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
Chris Lattner03c49532007-01-15 02:27:26 +00001668 assert(C->getType()->isInteger() && "SEXt operand must be integral");
1669 assert(Ty->isInteger() && "SExt produces only integer");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001670 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1671 "SrcTy must be smaller than DestTy for SExt!");
1672
1673 return getFoldedCast(Instruction::SExt, C, Ty);
Chris Lattnerdd284742004-04-04 23:20:30 +00001674}
1675
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001676Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
Chris Lattner03c49532007-01-15 02:27:26 +00001677 assert(C->getType()->isInteger() && "ZEXt operand must be integral");
1678 assert(Ty->isInteger() && "ZExt produces only integer");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001679 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1680 "SrcTy must be smaller than DestTy for ZExt!");
1681
1682 return getFoldedCast(Instruction::ZExt, C, Ty);
1683}
1684
1685Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1686 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1687 C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1688 "This is an illegal floating point truncation!");
1689 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1690}
1691
1692Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1693 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1694 C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1695 "This is an illegal floating point extension!");
1696 return getFoldedCast(Instruction::FPExt, C, Ty);
1697}
1698
1699Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
Nate Begemand4d45c22007-11-17 03:58:34 +00001700 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1701 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1702 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1703 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1704 "This is an illegal uint to floating point cast!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001705 return getFoldedCast(Instruction::UIToFP, C, Ty);
1706}
1707
1708Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
Nate Begemand4d45c22007-11-17 03:58:34 +00001709 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1710 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1711 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1712 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001713 "This is an illegal sint to floating point cast!");
1714 return getFoldedCast(Instruction::SIToFP, C, Ty);
1715}
1716
1717Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
Nate Begemand4d45c22007-11-17 03:58:34 +00001718 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1719 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1720 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1721 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1722 "This is an illegal floating point to uint cast!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001723 return getFoldedCast(Instruction::FPToUI, C, Ty);
1724}
1725
1726Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
Nate Begemand4d45c22007-11-17 03:58:34 +00001727 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1728 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1729 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1730 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1731 "This is an illegal floating point to sint cast!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001732 return getFoldedCast(Instruction::FPToSI, C, Ty);
1733}
1734
1735Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1736 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
Chris Lattner03c49532007-01-15 02:27:26 +00001737 assert(DstTy->isInteger() && "PtrToInt destination must be integral");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001738 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1739}
1740
1741Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
Chris Lattner03c49532007-01-15 02:27:26 +00001742 assert(C->getType()->isInteger() && "IntToPtr source must be integral");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001743 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
1744 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1745}
1746
1747Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1748 // BitCast implies a no-op cast of type only. No bits change. However, you
1749 // can't cast pointers to anything but pointers.
1750 const Type *SrcTy = C->getType();
1751 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
Reid Spencer5c140882006-12-04 20:17:56 +00001752 "BitCast cannot cast pointer to non-pointer and vice versa");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001753
1754 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
1755 // or nonptr->ptr). For all the other types, the cast is okay if source and
1756 // destination bit widths are identical.
1757 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1758 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
Reid Spencer5c140882006-12-04 20:17:56 +00001759 assert(SrcBitSize == DstBitSize && "BitCast requies types of same width");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001760 return getFoldedCast(Instruction::BitCast, C, DstTy);
Chris Lattnerdd284742004-04-04 23:20:30 +00001761}
1762
Alkis Evlogimenosda5de052004-10-24 01:41:10 +00001763Constant *ConstantExpr::getSizeOf(const Type *Ty) {
Gordon Henriksen7ce31762007-10-06 14:29:36 +00001764 // sizeof is implemented as: (i64) gep (Ty*)null, 1
Chris Lattnerb5d70302007-02-19 20:01:23 +00001765 Constant *GEPIdx = ConstantInt::get(Type::Int32Ty, 1);
1766 Constant *GEP =
Christopher Lambedf07882007-12-17 01:12:55 +00001767 getGetElementPtr(getNullValue(PointerType::getUnqual(Ty)), &GEPIdx, 1);
Chris Lattnerb5d70302007-02-19 20:01:23 +00001768 return getCast(Instruction::PtrToInt, GEP, Type::Int64Ty);
Alkis Evlogimenos9160d5f2005-03-19 11:40:31 +00001769}
1770
Chris Lattnerb50d1352003-10-05 00:17:43 +00001771Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
Reid Spencera009d0d2006-12-04 21:35:24 +00001772 Constant *C1, Constant *C2) {
Chris Lattner38a9bcd2003-05-21 17:49:25 +00001773 // Check the operands for consistency first
Reid Spencer7eb55b32006-11-02 01:53:59 +00001774 assert(Opcode >= Instruction::BinaryOpsBegin &&
1775 Opcode < Instruction::BinaryOpsEnd &&
Chris Lattner38a9bcd2003-05-21 17:49:25 +00001776 "Invalid opcode in binary constant expression");
1777 assert(C1->getType() == C2->getType() &&
1778 "Operand types in binary constant expression should match");
Chris Lattnerb50d1352003-10-05 00:17:43 +00001779
Reid Spencer542964f2007-01-11 18:21:29 +00001780 if (ReqTy == C1->getType() || ReqTy == Type::Int1Ty)
Chris Lattnerb50d1352003-10-05 00:17:43 +00001781 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1782 return FC; // Fold a few common cases...
Chris Lattneracdbe712003-04-17 19:24:48 +00001783
Chris Lattner2b383d2e2003-05-13 21:37:02 +00001784 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
Reid Spencera009d0d2006-12-04 21:35:24 +00001785 ExprMapKeyType Key(Opcode, argVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001786 return ExprConstants->getOrCreate(ReqTy, Key);
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001787}
1788
Reid Spencer266e42b2006-12-23 06:05:41 +00001789Constant *ConstantExpr::getCompareTy(unsigned short predicate,
Reid Spencera009d0d2006-12-04 21:35:24 +00001790 Constant *C1, Constant *C2) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001791 switch (predicate) {
1792 default: assert(0 && "Invalid CmpInst predicate");
1793 case FCmpInst::FCMP_FALSE: case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_OGT:
1794 case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OLE:
1795 case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_ORD: case FCmpInst::FCMP_UNO:
1796 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UGT: case FCmpInst::FCMP_UGE:
1797 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_ULE: case FCmpInst::FCMP_UNE:
1798 case FCmpInst::FCMP_TRUE:
1799 return getFCmp(predicate, C1, C2);
1800 case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGT:
1801 case ICmpInst::ICMP_UGE: case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE:
1802 case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_SGE: case ICmpInst::ICMP_SLT:
1803 case ICmpInst::ICMP_SLE:
1804 return getICmp(predicate, C1, C2);
1805 }
Reid Spencera009d0d2006-12-04 21:35:24 +00001806}
1807
1808Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001809#ifndef NDEBUG
1810 switch (Opcode) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00001811 case Instruction::Add:
1812 case Instruction::Sub:
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001813 case Instruction::Mul:
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001814 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Chris Lattner03c49532007-01-15 02:27:26 +00001815 assert((C1->getType()->isInteger() || C1->getType()->isFloatingPoint() ||
Reid Spencerd84d35b2007-02-15 02:26:10 +00001816 isa<VectorType>(C1->getType())) &&
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001817 "Tried to create an arithmetic operation on a non-arithmetic type!");
1818 break;
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001819 case Instruction::UDiv:
1820 case Instruction::SDiv:
1821 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001822 assert((C1->getType()->isInteger() || (isa<VectorType>(C1->getType()) &&
1823 cast<VectorType>(C1->getType())->getElementType()->isInteger())) &&
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001824 "Tried to create an arithmetic operation on a non-arithmetic type!");
1825 break;
1826 case Instruction::FDiv:
1827 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001828 assert((C1->getType()->isFloatingPoint() || (isa<VectorType>(C1->getType())
1829 && cast<VectorType>(C1->getType())->getElementType()->isFloatingPoint()))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001830 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1831 break;
Reid Spencer7eb55b32006-11-02 01:53:59 +00001832 case Instruction::URem:
1833 case Instruction::SRem:
1834 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001835 assert((C1->getType()->isInteger() || (isa<VectorType>(C1->getType()) &&
1836 cast<VectorType>(C1->getType())->getElementType()->isInteger())) &&
Reid Spencer7eb55b32006-11-02 01:53:59 +00001837 "Tried to create an arithmetic operation on a non-arithmetic type!");
1838 break;
1839 case Instruction::FRem:
1840 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001841 assert((C1->getType()->isFloatingPoint() || (isa<VectorType>(C1->getType())
1842 && cast<VectorType>(C1->getType())->getElementType()->isFloatingPoint()))
Reid Spencer7eb55b32006-11-02 01:53:59 +00001843 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1844 break;
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001845 case Instruction::And:
1846 case Instruction::Or:
1847 case Instruction::Xor:
1848 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001849 assert((C1->getType()->isInteger() || isa<VectorType>(C1->getType())) &&
Misha Brukman3852f652005-01-27 06:46:38 +00001850 "Tried to create a logical operation on a non-integral type!");
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001851 break;
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001852 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00001853 case Instruction::LShr:
1854 case Instruction::AShr:
Reid Spencer2341c222007-02-02 02:16:23 +00001855 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Chris Lattner03c49532007-01-15 02:27:26 +00001856 assert(C1->getType()->isInteger() &&
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001857 "Tried to create a shift operation on a non-integer type!");
1858 break;
1859 default:
1860 break;
1861 }
1862#endif
1863
Reid Spencera009d0d2006-12-04 21:35:24 +00001864 return getTy(C1->getType(), Opcode, C1, C2);
1865}
1866
Reid Spencer266e42b2006-12-23 06:05:41 +00001867Constant *ConstantExpr::getCompare(unsigned short pred,
Reid Spencera009d0d2006-12-04 21:35:24 +00001868 Constant *C1, Constant *C2) {
1869 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencer266e42b2006-12-23 06:05:41 +00001870 return getCompareTy(pred, C1, C2);
Chris Lattner29ca2c62004-08-04 18:50:09 +00001871}
1872
Chris Lattner6e415c02004-03-12 05:54:04 +00001873Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1874 Constant *V1, Constant *V2) {
Reid Spencer2546b762007-01-26 07:37:34 +00001875 assert(C->getType() == Type::Int1Ty && "Select condition must be i1!");
Chris Lattner6e415c02004-03-12 05:54:04 +00001876 assert(V1->getType() == V2->getType() && "Select value types must match!");
1877 assert(V1->getType()->isFirstClassType() && "Cannot select aggregate type!");
1878
1879 if (ReqTy == V1->getType())
1880 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1881 return SC; // Fold common cases
1882
1883 std::vector<Constant*> argVec(3, C);
1884 argVec[1] = V1;
1885 argVec[2] = V2;
Reid Spenceree3c9912006-12-04 05:19:50 +00001886 ExprMapKeyType Key(Instruction::Select, argVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001887 return ExprConstants->getOrCreate(ReqTy, Key);
Chris Lattner6e415c02004-03-12 05:54:04 +00001888}
1889
Chris Lattnerb50d1352003-10-05 00:17:43 +00001890Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
Chris Lattner302116a2007-01-31 04:40:28 +00001891 Value* const *Idxs,
1892 unsigned NumIdx) {
David Greenec656cbb2007-09-04 15:46:09 +00001893 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx, true) &&
Chris Lattner04b60fe2004-02-16 20:46:13 +00001894 "GEP indices invalid!");
1895
Chris Lattner302116a2007-01-31 04:40:28 +00001896 if (Constant *FC = ConstantFoldGetElementPtr(C, (Constant**)Idxs, NumIdx))
Chris Lattneracdbe712003-04-17 19:24:48 +00001897 return FC; // Fold a few common cases...
Chris Lattner04b60fe2004-02-16 20:46:13 +00001898
Chris Lattnerb50d1352003-10-05 00:17:43 +00001899 assert(isa<PointerType>(C->getType()) &&
Chris Lattner98fa07b2003-05-23 20:03:32 +00001900 "Non-pointer type for constant GetElementPtr expression");
Vikram S. Adve4c485332002-07-15 18:19:33 +00001901 // Look up the constant in the table first to ensure uniqueness
Chris Lattner13128ab2004-10-11 22:52:25 +00001902 std::vector<Constant*> ArgVec;
Chris Lattner302116a2007-01-31 04:40:28 +00001903 ArgVec.reserve(NumIdx+1);
Chris Lattner13128ab2004-10-11 22:52:25 +00001904 ArgVec.push_back(C);
Chris Lattner302116a2007-01-31 04:40:28 +00001905 for (unsigned i = 0; i != NumIdx; ++i)
1906 ArgVec.push_back(cast<Constant>(Idxs[i]));
1907 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001908 return ExprConstants->getOrCreate(ReqTy, Key);
Vikram S. Adve4c485332002-07-15 18:19:33 +00001909}
1910
Chris Lattner302116a2007-01-31 04:40:28 +00001911Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
1912 unsigned NumIdx) {
Chris Lattnerb50d1352003-10-05 00:17:43 +00001913 // Get the result type of the getelementptr!
Chris Lattner302116a2007-01-31 04:40:28 +00001914 const Type *Ty =
David Greenec656cbb2007-09-04 15:46:09 +00001915 GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx, true);
Chris Lattnerb50d1352003-10-05 00:17:43 +00001916 assert(Ty && "GEP indices invalid!");
Christopher Lamb54dd24c2007-12-11 08:59:05 +00001917 unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
1918 return getGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx);
Chris Lattner13128ab2004-10-11 22:52:25 +00001919}
1920
Chris Lattner302116a2007-01-31 04:40:28 +00001921Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
1922 unsigned NumIdx) {
1923 return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
Chris Lattnerb50d1352003-10-05 00:17:43 +00001924}
1925
Chris Lattner302116a2007-01-31 04:40:28 +00001926
Reid Spenceree3c9912006-12-04 05:19:50 +00001927Constant *
1928ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1929 assert(LHS->getType() == RHS->getType());
1930 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
1931 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1932
Reid Spencer266e42b2006-12-23 06:05:41 +00001933 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
Reid Spenceree3c9912006-12-04 05:19:50 +00001934 return FC; // Fold a few common cases...
1935
1936 // Look up the constant in the table first to ensure uniqueness
1937 std::vector<Constant*> ArgVec;
1938 ArgVec.push_back(LHS);
1939 ArgVec.push_back(RHS);
Reid Spencerb1537492006-12-24 18:42:29 +00001940 // Get the key type with both the opcode and predicate
Reid Spenceree3c9912006-12-04 05:19:50 +00001941 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
Reid Spencer542964f2007-01-11 18:21:29 +00001942 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
Reid Spenceree3c9912006-12-04 05:19:50 +00001943}
1944
1945Constant *
1946ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1947 assert(LHS->getType() == RHS->getType());
1948 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1949
Reid Spencer266e42b2006-12-23 06:05:41 +00001950 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
Reid Spenceree3c9912006-12-04 05:19:50 +00001951 return FC; // Fold a few common cases...
1952
1953 // Look up the constant in the table first to ensure uniqueness
1954 std::vector<Constant*> ArgVec;
1955 ArgVec.push_back(LHS);
1956 ArgVec.push_back(RHS);
Reid Spencerb1537492006-12-24 18:42:29 +00001957 // Get the key type with both the opcode and predicate
Reid Spenceree3c9912006-12-04 05:19:50 +00001958 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
Reid Spencer542964f2007-01-11 18:21:29 +00001959 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
Reid Spenceree3c9912006-12-04 05:19:50 +00001960}
1961
Robert Bocchino23004482006-01-10 19:05:34 +00001962Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
1963 Constant *Idx) {
Robert Bocchinode7f1c92006-01-10 20:03:46 +00001964 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
1965 return FC; // Fold a few common cases...
Robert Bocchino23004482006-01-10 19:05:34 +00001966 // Look up the constant in the table first to ensure uniqueness
1967 std::vector<Constant*> ArgVec(1, Val);
1968 ArgVec.push_back(Idx);
Reid Spenceree3c9912006-12-04 05:19:50 +00001969 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001970 return ExprConstants->getOrCreate(ReqTy, Key);
Robert Bocchino23004482006-01-10 19:05:34 +00001971}
1972
1973Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001974 assert(isa<VectorType>(Val->getType()) &&
Reid Spencer09575ba2007-02-15 03:39:18 +00001975 "Tried to create extractelement operation on non-vector type!");
Reid Spencer8d9336d2006-12-31 05:26:44 +00001976 assert(Idx->getType() == Type::Int32Ty &&
Reid Spencer2546b762007-01-26 07:37:34 +00001977 "Extractelement index must be i32 type!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001978 return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
Robert Bocchino23004482006-01-10 19:05:34 +00001979 Val, Idx);
1980}
Chris Lattnerb50d1352003-10-05 00:17:43 +00001981
Robert Bocchinoca27f032006-01-17 20:07:22 +00001982Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
1983 Constant *Elt, Constant *Idx) {
1984 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
1985 return FC; // Fold a few common cases...
1986 // Look up the constant in the table first to ensure uniqueness
1987 std::vector<Constant*> ArgVec(1, Val);
1988 ArgVec.push_back(Elt);
1989 ArgVec.push_back(Idx);
Reid Spenceree3c9912006-12-04 05:19:50 +00001990 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001991 return ExprConstants->getOrCreate(ReqTy, Key);
Robert Bocchinoca27f032006-01-17 20:07:22 +00001992}
1993
1994Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1995 Constant *Idx) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001996 assert(isa<VectorType>(Val->getType()) &&
Reid Spencer09575ba2007-02-15 03:39:18 +00001997 "Tried to create insertelement operation on non-vector type!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001998 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
Robert Bocchinoca27f032006-01-17 20:07:22 +00001999 && "Insertelement types must match!");
Reid Spencer8d9336d2006-12-31 05:26:44 +00002000 assert(Idx->getType() == Type::Int32Ty &&
Reid Spencer2546b762007-01-26 07:37:34 +00002001 "Insertelement index must be i32 type!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00002002 return getInsertElementTy(cast<VectorType>(Val->getType())->getElementType(),
Robert Bocchinoca27f032006-01-17 20:07:22 +00002003 Val, Elt, Idx);
2004}
2005
Chris Lattnerbbe0a422006-04-08 01:18:18 +00002006Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
2007 Constant *V2, Constant *Mask) {
2008 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
2009 return FC; // Fold a few common cases...
2010 // Look up the constant in the table first to ensure uniqueness
2011 std::vector<Constant*> ArgVec(1, V1);
2012 ArgVec.push_back(V2);
2013 ArgVec.push_back(Mask);
Reid Spenceree3c9912006-12-04 05:19:50 +00002014 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
Chris Lattner69edc982006-09-28 00:35:06 +00002015 return ExprConstants->getOrCreate(ReqTy, Key);
Chris Lattnerbbe0a422006-04-08 01:18:18 +00002016}
2017
2018Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
2019 Constant *Mask) {
2020 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
2021 "Invalid shuffle vector constant expr operands!");
2022 return getShuffleVectorTy(V1->getType(), V1, V2, Mask);
2023}
2024
Reid Spencer2eadb532007-01-21 00:29:26 +00002025Constant *ConstantExpr::getZeroValueForNegationExpr(const Type *Ty) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00002026 if (const VectorType *PTy = dyn_cast<VectorType>(Ty))
Reid Spencer6598ca82007-01-21 02:29:10 +00002027 if (PTy->getElementType()->isFloatingPoint()) {
2028 std::vector<Constant*> zeros(PTy->getNumElements(),
Dale Johannesen98d3a082007-09-14 22:26:36 +00002029 ConstantFP::getNegativeZero(PTy->getElementType()));
Reid Spencerd84d35b2007-02-15 02:26:10 +00002030 return ConstantVector::get(PTy, zeros);
Reid Spencer6598ca82007-01-21 02:29:10 +00002031 }
Reid Spencer2eadb532007-01-21 00:29:26 +00002032
Dale Johannesen98d3a082007-09-14 22:26:36 +00002033 if (Ty->isFloatingPoint())
2034 return ConstantFP::getNegativeZero(Ty);
Reid Spencer2eadb532007-01-21 00:29:26 +00002035
2036 return Constant::getNullValue(Ty);
2037}
2038
Vikram S. Adve4c485332002-07-15 18:19:33 +00002039// destroyConstant - Remove the constant from the constant table...
2040//
2041void ConstantExpr::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00002042 ExprConstants->remove(this);
Vikram S. Adve4c485332002-07-15 18:19:33 +00002043 destroyConstantImpl();
Vikram S. Adve4e537b22002-07-14 23:13:17 +00002044}
2045
Chris Lattner3cd8c562002-07-30 18:54:25 +00002046const char *ConstantExpr::getOpcodeName() const {
2047 return Instruction::getOpcodeName(getOpcode());
Vikram S. Adve4e537b22002-07-14 23:13:17 +00002048}
Reid Spencer1ebe1ab2004-07-17 23:48:33 +00002049
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002050//===----------------------------------------------------------------------===//
2051// replaceUsesOfWithOnConstant implementations
2052
Chris Lattner913849b2007-08-21 00:55:23 +00002053/// replaceUsesOfWithOnConstant - Update this constant array to change uses of
2054/// 'From' to be uses of 'To'. This must update the uniquing data structures
2055/// etc.
2056///
2057/// Note that we intentionally replace all uses of From with To here. Consider
2058/// a large array that uses 'From' 1000 times. By handling this case all here,
2059/// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
2060/// single invocation handles all 1000 uses. Handling them one at a time would
2061/// work, but would be really slow because it would have to unique each updated
2062/// array instance.
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002063void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002064 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002065 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
Chris Lattner8760ec72005-10-04 01:17:50 +00002066 Constant *ToC = cast<Constant>(To);
Chris Lattnerdff59112005-10-04 18:47:09 +00002067
Jim Laskeyc03caef2006-07-17 17:38:29 +00002068 std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
Chris Lattnerb64419a2005-10-03 22:51:37 +00002069 Lookup.first.first = getType();
2070 Lookup.second = this;
Chris Lattnerdff59112005-10-04 18:47:09 +00002071
Chris Lattnerb64419a2005-10-03 22:51:37 +00002072 std::vector<Constant*> &Values = Lookup.first.second;
2073 Values.reserve(getNumOperands()); // Build replacement array.
Chris Lattnerdff59112005-10-04 18:47:09 +00002074
Chris Lattner8760ec72005-10-04 01:17:50 +00002075 // Fill values with the modified operands of the constant array. Also,
2076 // compute whether this turns into an all-zeros array.
Chris Lattnerdff59112005-10-04 18:47:09 +00002077 bool isAllZeros = false;
Chris Lattner913849b2007-08-21 00:55:23 +00002078 unsigned NumUpdated = 0;
Chris Lattnerdff59112005-10-04 18:47:09 +00002079 if (!ToC->isNullValue()) {
Chris Lattner913849b2007-08-21 00:55:23 +00002080 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2081 Constant *Val = cast<Constant>(O->get());
2082 if (Val == From) {
2083 Val = ToC;
2084 ++NumUpdated;
2085 }
2086 Values.push_back(Val);
2087 }
Chris Lattnerdff59112005-10-04 18:47:09 +00002088 } else {
2089 isAllZeros = true;
2090 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2091 Constant *Val = cast<Constant>(O->get());
Chris Lattner913849b2007-08-21 00:55:23 +00002092 if (Val == From) {
2093 Val = ToC;
2094 ++NumUpdated;
2095 }
Chris Lattnerdff59112005-10-04 18:47:09 +00002096 Values.push_back(Val);
2097 if (isAllZeros) isAllZeros = Val->isNullValue();
2098 }
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002099 }
2100
Chris Lattnerb64419a2005-10-03 22:51:37 +00002101 Constant *Replacement = 0;
2102 if (isAllZeros) {
2103 Replacement = ConstantAggregateZero::get(getType());
2104 } else {
2105 // Check to see if we have this array type already.
2106 bool Exists;
Jim Laskeyc03caef2006-07-17 17:38:29 +00002107 ArrayConstantsTy::MapTy::iterator I =
Chris Lattner69edc982006-09-28 00:35:06 +00002108 ArrayConstants->InsertOrGetItem(Lookup, Exists);
Chris Lattnerb64419a2005-10-03 22:51:37 +00002109
2110 if (Exists) {
2111 Replacement = I->second;
2112 } else {
2113 // Okay, the new shape doesn't exist in the system yet. Instead of
2114 // creating a new constant array, inserting it, replaceallusesof'ing the
2115 // old with the new, then deleting the old... just update the current one
2116 // in place!
Chris Lattner69edc982006-09-28 00:35:06 +00002117 ArrayConstants->MoveConstantToNewSlot(this, I);
Chris Lattnerb64419a2005-10-03 22:51:37 +00002118
Chris Lattner913849b2007-08-21 00:55:23 +00002119 // Update to the new value. Optimize for the case when we have a single
2120 // operand that we're changing, but handle bulk updates efficiently.
2121 if (NumUpdated == 1) {
2122 unsigned OperandToUpdate = U-OperandList;
2123 assert(getOperand(OperandToUpdate) == From &&
2124 "ReplaceAllUsesWith broken!");
2125 setOperand(OperandToUpdate, ToC);
2126 } else {
2127 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2128 if (getOperand(i) == From)
2129 setOperand(i, ToC);
2130 }
Chris Lattnerb64419a2005-10-03 22:51:37 +00002131 return;
2132 }
2133 }
2134
2135 // Otherwise, I do need to replace this with an existing value.
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002136 assert(Replacement != this && "I didn't contain From!");
2137
Chris Lattner7a1450d2005-10-04 18:13:04 +00002138 // Everyone using this now uses the replacement.
2139 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002140
2141 // Delete the old constant!
2142 destroyConstant();
2143}
2144
2145void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002146 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002147 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
Chris Lattner8760ec72005-10-04 01:17:50 +00002148 Constant *ToC = cast<Constant>(To);
2149
Chris Lattnerdff59112005-10-04 18:47:09 +00002150 unsigned OperandToUpdate = U-OperandList;
2151 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2152
Jim Laskeyc03caef2006-07-17 17:38:29 +00002153 std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
Chris Lattner8760ec72005-10-04 01:17:50 +00002154 Lookup.first.first = getType();
2155 Lookup.second = this;
2156 std::vector<Constant*> &Values = Lookup.first.second;
2157 Values.reserve(getNumOperands()); // Build replacement struct.
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002158
Chris Lattnerdff59112005-10-04 18:47:09 +00002159
Chris Lattner8760ec72005-10-04 01:17:50 +00002160 // Fill values with the modified operands of the constant struct. Also,
2161 // compute whether this turns into an all-zeros struct.
Chris Lattnerdff59112005-10-04 18:47:09 +00002162 bool isAllZeros = false;
2163 if (!ToC->isNullValue()) {
2164 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
2165 Values.push_back(cast<Constant>(O->get()));
2166 } else {
2167 isAllZeros = true;
2168 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2169 Constant *Val = cast<Constant>(O->get());
2170 Values.push_back(Val);
2171 if (isAllZeros) isAllZeros = Val->isNullValue();
2172 }
Chris Lattner8760ec72005-10-04 01:17:50 +00002173 }
Chris Lattnerdff59112005-10-04 18:47:09 +00002174 Values[OperandToUpdate] = ToC;
2175
Chris Lattner8760ec72005-10-04 01:17:50 +00002176 Constant *Replacement = 0;
2177 if (isAllZeros) {
2178 Replacement = ConstantAggregateZero::get(getType());
2179 } else {
2180 // Check to see if we have this array type already.
2181 bool Exists;
Jim Laskeyc03caef2006-07-17 17:38:29 +00002182 StructConstantsTy::MapTy::iterator I =
Chris Lattner69edc982006-09-28 00:35:06 +00002183 StructConstants->InsertOrGetItem(Lookup, Exists);
Chris Lattner8760ec72005-10-04 01:17:50 +00002184
2185 if (Exists) {
2186 Replacement = I->second;
2187 } else {
2188 // Okay, the new shape doesn't exist in the system yet. Instead of
2189 // creating a new constant struct, inserting it, replaceallusesof'ing the
2190 // old with the new, then deleting the old... just update the current one
2191 // in place!
Chris Lattner69edc982006-09-28 00:35:06 +00002192 StructConstants->MoveConstantToNewSlot(this, I);
Chris Lattner8760ec72005-10-04 01:17:50 +00002193
Chris Lattnerdff59112005-10-04 18:47:09 +00002194 // Update to the new value.
2195 setOperand(OperandToUpdate, ToC);
Chris Lattner8760ec72005-10-04 01:17:50 +00002196 return;
2197 }
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002198 }
2199
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002200 assert(Replacement != this && "I didn't contain From!");
2201
Chris Lattner7a1450d2005-10-04 18:13:04 +00002202 // Everyone using this now uses the replacement.
2203 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002204
2205 // Delete the old constant!
2206 destroyConstant();
2207}
2208
Reid Spencerd84d35b2007-02-15 02:26:10 +00002209void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002210 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002211 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2212
2213 std::vector<Constant*> Values;
2214 Values.reserve(getNumOperands()); // Build replacement array...
2215 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2216 Constant *Val = getOperand(i);
2217 if (Val == From) Val = cast<Constant>(To);
2218 Values.push_back(Val);
2219 }
2220
Reid Spencerd84d35b2007-02-15 02:26:10 +00002221 Constant *Replacement = ConstantVector::get(getType(), Values);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002222 assert(Replacement != this && "I didn't contain From!");
2223
Chris Lattner7a1450d2005-10-04 18:13:04 +00002224 // Everyone using this now uses the replacement.
2225 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002226
2227 // Delete the old constant!
2228 destroyConstant();
2229}
2230
2231void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002232 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002233 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2234 Constant *To = cast<Constant>(ToV);
2235
2236 Constant *Replacement = 0;
2237 if (getOpcode() == Instruction::GetElementPtr) {
Chris Lattnerb5d70302007-02-19 20:01:23 +00002238 SmallVector<Constant*, 8> Indices;
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002239 Constant *Pointer = getOperand(0);
2240 Indices.reserve(getNumOperands()-1);
2241 if (Pointer == From) Pointer = To;
2242
2243 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2244 Constant *Val = getOperand(i);
2245 if (Val == From) Val = To;
2246 Indices.push_back(Val);
2247 }
Chris Lattnerb5d70302007-02-19 20:01:23 +00002248 Replacement = ConstantExpr::getGetElementPtr(Pointer,
2249 &Indices[0], Indices.size());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002250 } else if (isCast()) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002251 assert(getOperand(0) == From && "Cast only has one use!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002252 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002253 } else if (getOpcode() == Instruction::Select) {
2254 Constant *C1 = getOperand(0);
2255 Constant *C2 = getOperand(1);
2256 Constant *C3 = getOperand(2);
2257 if (C1 == From) C1 = To;
2258 if (C2 == From) C2 = To;
2259 if (C3 == From) C3 = To;
2260 Replacement = ConstantExpr::getSelect(C1, C2, C3);
Robert Bocchino23004482006-01-10 19:05:34 +00002261 } else if (getOpcode() == Instruction::ExtractElement) {
2262 Constant *C1 = getOperand(0);
2263 Constant *C2 = getOperand(1);
2264 if (C1 == From) C1 = To;
2265 if (C2 == From) C2 = To;
2266 Replacement = ConstantExpr::getExtractElement(C1, C2);
Chris Lattnera93b4b52006-04-08 05:09:48 +00002267 } else if (getOpcode() == Instruction::InsertElement) {
2268 Constant *C1 = getOperand(0);
2269 Constant *C2 = getOperand(1);
2270 Constant *C3 = getOperand(1);
2271 if (C1 == From) C1 = To;
2272 if (C2 == From) C2 = To;
2273 if (C3 == From) C3 = To;
2274 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2275 } else if (getOpcode() == Instruction::ShuffleVector) {
2276 Constant *C1 = getOperand(0);
2277 Constant *C2 = getOperand(1);
2278 Constant *C3 = getOperand(2);
2279 if (C1 == From) C1 = To;
2280 if (C2 == From) C2 = To;
2281 if (C3 == From) C3 = To;
2282 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
Reid Spenceree3c9912006-12-04 05:19:50 +00002283 } else if (isCompare()) {
2284 Constant *C1 = getOperand(0);
2285 Constant *C2 = getOperand(1);
2286 if (C1 == From) C1 = To;
2287 if (C2 == From) C2 = To;
2288 if (getOpcode() == Instruction::ICmp)
2289 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2290 else
2291 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002292 } else if (getNumOperands() == 2) {
2293 Constant *C1 = getOperand(0);
2294 Constant *C2 = getOperand(1);
2295 if (C1 == From) C1 = To;
2296 if (C2 == From) C2 = To;
2297 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2298 } else {
2299 assert(0 && "Unknown ConstantExpr type!");
2300 return;
2301 }
2302
2303 assert(Replacement != this && "I didn't contain From!");
2304
Chris Lattner7a1450d2005-10-04 18:13:04 +00002305 // Everyone using this now uses the replacement.
2306 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002307
2308 // Delete the old constant!
2309 destroyConstant();
2310}
2311
2312
Jim Laskey2698f0d2006-03-08 18:11:07 +00002313/// getStringValue - Turn an LLVM constant pointer that eventually points to a
2314/// global into a string value. Return an empty string if we can't do it.
Evan Cheng38280c02006-03-10 23:52:03 +00002315/// Parameter Chop determines if the result is chopped at the first null
2316/// terminator.
Jim Laskey2698f0d2006-03-08 18:11:07 +00002317///
Evan Cheng38280c02006-03-10 23:52:03 +00002318std::string Constant::getStringValue(bool Chop, unsigned Offset) {
Jim Laskey2698f0d2006-03-08 18:11:07 +00002319 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(this)) {
2320 if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
2321 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
2322 if (Init->isString()) {
2323 std::string Result = Init->getAsString();
2324 if (Offset < Result.size()) {
2325 // If we are pointing INTO The string, erase the beginning...
2326 Result.erase(Result.begin(), Result.begin()+Offset);
2327
2328 // Take off the null terminator, and any string fragments after it.
Evan Cheng38280c02006-03-10 23:52:03 +00002329 if (Chop) {
2330 std::string::size_type NullPos = Result.find_first_of((char)0);
2331 if (NullPos != std::string::npos)
2332 Result.erase(Result.begin()+NullPos, Result.end());
2333 }
Jim Laskey2698f0d2006-03-08 18:11:07 +00002334 return Result;
2335 }
2336 }
2337 }
Chris Lattner6ab19ed2007-11-01 02:30:35 +00002338 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(this)) {
2339 if (CE->getOpcode() == Instruction::GetElementPtr) {
2340 // Turn a gep into the specified offset.
2341 if (CE->getNumOperands() == 3 &&
2342 cast<Constant>(CE->getOperand(1))->isNullValue() &&
2343 isa<ConstantInt>(CE->getOperand(2))) {
2344 Offset += cast<ConstantInt>(CE->getOperand(2))->getZExtValue();
2345 return CE->getOperand(0)->getStringValue(Chop, Offset);
Jim Laskey2698f0d2006-03-08 18:11:07 +00002346 }
2347 }
2348 }
2349 return "";
2350}