blob: 0b8ba418957bf1376801edc7362d2e7e2cdf5532 [file] [log] [blame]
Chris Lattner9bc02a42003-05-13 21:37:02 +00001//===-- Constants.cpp - Implement Constant nodes --------------------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner00950542001-06-06 20:29:01 +00009//
Chris Lattnere9bb2df2001-12-03 22:26:30 +000010// This file implements the Constant* classes...
Chris Lattner00950542001-06-06 20:29:01 +000011//
12//===----------------------------------------------------------------------===//
13
Chris Lattner31bcdb82002-04-28 19:55:58 +000014#include "llvm/Constants.h"
Chris Lattner92f6fea2007-02-27 03:05:06 +000015#include "ConstantFold.h"
Chris Lattner00950542001-06-06 20:29:01 +000016#include "llvm/DerivedTypes.h"
Reid Spencer1c9c8e62004-07-17 23:48:33 +000017#include "llvm/GlobalValue.h"
Misha Brukman47b14a42004-07-29 17:30:56 +000018#include "llvm/Instructions.h"
Chris Lattnerf5ec48d2001-10-13 06:57:33 +000019#include "llvm/Module.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000020#include "llvm/ADT/StringExtras.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000021#include "llvm/Support/Compiler.h"
Bill Wendling2e3def12006-11-17 08:03:48 +000022#include "llvm/Support/Debug.h"
Chris Lattner8a94bf12006-09-28 00:35:06 +000023#include "llvm/Support/ManagedStatic.h"
Bill Wendling2e3def12006-11-17 08:03:48 +000024#include "llvm/Support/MathExtras.h"
Chris Lattner6b6f6ba2007-02-20 06:39:57 +000025#include "llvm/ADT/DenseMap.h"
Chris Lattnerf9021ff2007-02-19 20:01:23 +000026#include "llvm/ADT/SmallVector.h"
Chris Lattner00950542001-06-06 20:29:01 +000027#include <algorithm>
Reid Spenceref9b9a72007-02-05 20:47:22 +000028#include <map>
Chris Lattner31f84992003-11-21 20:23:48 +000029using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000030
Chris Lattner00950542001-06-06 20:29:01 +000031//===----------------------------------------------------------------------===//
Chris Lattnere9bb2df2001-12-03 22:26:30 +000032// Constant Class
Chris Lattner00950542001-06-06 20:29:01 +000033//===----------------------------------------------------------------------===//
34
Chris Lattnere9bb2df2001-12-03 22:26:30 +000035void Constant::destroyConstantImpl() {
36 // When a Constant is destroyed, there may be lingering
Chris Lattnerf5ec48d2001-10-13 06:57:33 +000037 // references to the constant by other constants in the constant pool. These
Misha Brukmanef6a6a62003-08-21 22:14:26 +000038 // constants are implicitly dependent on the module that is being deleted,
Chris Lattnerf5ec48d2001-10-13 06:57:33 +000039 // but they don't know that. Because we only find out when the CPV is
40 // deleted, we must now notify all of our users (that should only be
Chris Lattnere9bb2df2001-12-03 22:26:30 +000041 // Constants) that they are, in fact, invalid now and should be deleted.
Chris Lattnerf5ec48d2001-10-13 06:57:33 +000042 //
43 while (!use_empty()) {
44 Value *V = use_back();
45#ifndef NDEBUG // Only in -g mode...
Chris Lattner6183b922002-07-18 00:14:50 +000046 if (!isa<Constant>(V))
Bill Wendling2e3def12006-11-17 08:03:48 +000047 DOUT << "While deleting: " << *this
48 << "\n\nUse still stuck around after Def is destroyed: "
49 << *V << "\n\n";
Chris Lattnerf5ec48d2001-10-13 06:57:33 +000050#endif
Vikram S. Adve345e0cf2002-07-14 23:13:17 +000051 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
Reid Spencer1c9c8e62004-07-17 23:48:33 +000052 Constant *CV = cast<Constant>(V);
53 CV->destroyConstant();
Chris Lattnerf5ec48d2001-10-13 06:57:33 +000054
55 // The constant should remove itself from our use list...
Vikram S. Adve345e0cf2002-07-14 23:13:17 +000056 assert((use_empty() || use_back() != V) && "Constant not removed!");
Chris Lattnerf5ec48d2001-10-13 06:57:33 +000057 }
58
59 // Value has no outstanding references it is safe to delete it now...
60 delete this;
Chris Lattner1d87bcf2001-10-01 20:11:19 +000061}
Chris Lattner00950542001-06-06 20:29:01 +000062
Chris Lattner35b89fa2006-10-20 00:27:06 +000063/// canTrap - Return true if evaluation of this constant could trap. This is
64/// true for things like constant expressions that could divide by zero.
65bool Constant::canTrap() const {
66 assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
67 // The only thing that could possibly trap are constant exprs.
68 const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
69 if (!CE) return false;
70
71 // ConstantExpr traps if any operands can trap.
72 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
73 if (getOperand(i)->canTrap())
74 return true;
75
76 // Otherwise, only specific operations can trap.
77 switch (CE->getOpcode()) {
78 default:
79 return false;
Reid Spencer1628cec2006-10-26 06:15:43 +000080 case Instruction::UDiv:
81 case Instruction::SDiv:
82 case Instruction::FDiv:
Reid Spencer0a783f72006-11-02 01:53:59 +000083 case Instruction::URem:
84 case Instruction::SRem:
85 case Instruction::FRem:
Chris Lattner35b89fa2006-10-20 00:27:06 +000086 // Div and rem can trap if the RHS is not known to be non-zero.
87 if (!isa<ConstantInt>(getOperand(1)) || getOperand(1)->isNullValue())
88 return true;
89 return false;
90 }
91}
92
Evan Chengafe15812007-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 Lattner9fb96412002-08-13 17:50:20 +0000104// Static constructor to create a '0' constant of arbitrary type...
105Constant *Constant::getNullValue(const Type *Ty) {
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +0000106 static uint64_t zero[2] = {0, 0};
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000107 switch (Ty->getTypeID()) {
Chris Lattnere0e76962007-02-20 05:46:39 +0000108 case Type::IntegerTyID:
109 return ConstantInt::get(Ty, 0);
110 case Type::FloatTyID:
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +0000111 return ConstantFP::get(Ty, APFloat(APInt(32, 0)));
Chris Lattnere0e76962007-02-20 05:46:39 +0000112 case Type::DoubleTyID:
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +0000113 return ConstantFP::get(Ty, APFloat(APInt(64, 0)));
Dale Johannesenebbc95d2007-08-09 22:51:36 +0000114 case Type::X86_FP80TyID:
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +0000115 return ConstantFP::get(Ty, APFloat(APInt(80, 2, zero)));
Dale Johannesenebbc95d2007-08-09 22:51:36 +0000116 case Type::FP128TyID:
Dale Johannesena471c2e2007-10-11 18:07:22 +0000117 return ConstantFP::get(Ty, APFloat(APInt(128, 2, zero), true));
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +0000118 case Type::PPC_FP128TyID:
119 return ConstantFP::get(Ty, APFloat(APInt(128, 2, zero)));
Misha Brukmanfd939082005-04-21 23:48:37 +0000120 case Type::PointerTyID:
Chris Lattner9fb96412002-08-13 17:50:20 +0000121 return ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattner40bbeb52004-02-15 05:53:04 +0000122 case Type::StructTyID:
123 case Type::ArrayTyID:
Reid Spencer9d6565a2007-02-15 02:26:10 +0000124 case Type::VectorTyID:
Chris Lattner40bbeb52004-02-15 05:53:04 +0000125 return ConstantAggregateZero::get(Ty);
Chris Lattner9fb96412002-08-13 17:50:20 +0000126 default:
Reid Spencer57f6efc2004-07-04 11:51:24 +0000127 // Function, Label, or Opaque type?
128 assert(!"Cannot create a null constant of that type!");
Chris Lattner9fb96412002-08-13 17:50:20 +0000129 return 0;
130 }
131}
132
Chris Lattnercef4b532007-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 Lattner9fb96412002-08-13 17:50:20 +0000138
139// Static constructor to create an integral constant with all bits set
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000140ConstantInt *ConstantInt::getAllOnesValue(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000141 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
Reid Spencer0050c732007-03-01 19:30:34 +0000142 return ConstantInt::get(APInt::getAllOnesValue(ITy->getBitWidth()));
Reid Spencera54b7cb2007-01-12 07:05:14 +0000143 return 0;
Chris Lattner9fb96412002-08-13 17:50:20 +0000144}
145
Dan Gohmanfa73ea22007-05-24 14:36:04 +0000146/// @returns the value for a vector integer constant of the given type that
Chris Lattner58513aa2007-01-04 01:49:26 +0000147/// has all its bits set to true.
148/// @brief Get the all ones value
Reid Spencer9d6565a2007-02-15 02:26:10 +0000149ConstantVector *ConstantVector::getAllOnesValue(const VectorType *Ty) {
Chris Lattner58513aa2007-01-04 01:49:26 +0000150 std::vector<Constant*> Elts;
151 Elts.resize(Ty->getNumElements(),
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000152 ConstantInt::getAllOnesValue(Ty->getElementType()));
Dan Gohmanfa73ea22007-05-24 14:36:04 +0000153 assert(Elts[0] && "Not a vector integer type!");
Reid Spencer9d6565a2007-02-15 02:26:10 +0000154 return cast<ConstantVector>(ConstantVector::get(Elts));
Chris Lattner58513aa2007-01-04 01:49:26 +0000155}
156
157
Chris Lattner00950542001-06-06 20:29:01 +0000158//===----------------------------------------------------------------------===//
Chris Lattner6b6f6ba2007-02-20 06:39:57 +0000159// ConstantInt
Chris Lattner00950542001-06-06 20:29:01 +0000160//===----------------------------------------------------------------------===//
161
Reid Spencer532d0ce2007-02-26 23:54:03 +0000162ConstantInt::ConstantInt(const IntegerType *Ty, const APInt& V)
Chris Lattnereb41bdd2007-02-20 05:55:46 +0000163 : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
Reid Spencer532d0ce2007-02-26 23:54:03 +0000164 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
Chris Lattner00950542001-06-06 20:29:01 +0000165}
166
Chris Lattner6b6f6ba2007-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 Lattner6b6f6ba2007-02-20 06:39:57 +0000190namespace {
Reid Spencer532d0ce2007-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 Lattner6b6f6ba2007-02-20 06:39:57 +0000206 static unsigned getHashValue(const KeyTy &Key) {
Chris Lattner76c1b972007-09-17 18:34:04 +0000207 return DenseMapInfo<void*>::getHashValue(Key.type) ^
Reid Spencer532d0ce2007-02-26 23:54:03 +0000208 Key.val.getHashValue();
Chris Lattner6b6f6ba2007-02-20 06:39:57 +0000209 }
Chris Lattner76c1b972007-09-17 18:34:04 +0000210 static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
211 return LHS == RHS;
212 }
Dale Johannesen343e7702007-08-24 00:56:33 +0000213 static bool isPod() { return false; }
Chris Lattner6b6f6ba2007-02-20 06:39:57 +0000214 };
215}
216
217
Reid Spencer532d0ce2007-02-26 23:54:03 +0000218typedef DenseMap<DenseMapAPIntKeyInfo::KeyTy, ConstantInt*,
219 DenseMapAPIntKeyInfo> IntMapTy;
Chris Lattner6b6f6ba2007-02-20 06:39:57 +0000220static ManagedStatic<IntMapTy> IntConstants;
221
Reid Spencer7fc44c82007-03-19 20:39:08 +0000222ConstantInt *ConstantInt::get(const Type *Ty, uint64_t V, bool isSigned) {
Chris Lattner6b6f6ba2007-02-20 06:39:57 +0000223 const IntegerType *ITy = cast<IntegerType>(Ty);
Reid Spencer7fc44c82007-03-19 20:39:08 +0000224 return get(APInt(ITy->getBitWidth(), V, isSigned));
Reid Spencer532d0ce2007-02-26 23:54:03 +0000225}
226
Reid Spencer0050c732007-03-01 19:30:34 +0000227// Get a ConstantInt from an APInt. Note that the value stored in the DenseMap
228// as the key, is a DensMapAPIntKeyInfo::KeyTy which has provided the
Reid Spencer532d0ce2007-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 Spencer0050c732007-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 Spencer532d0ce2007-02-26 23:54:03 +0000235 // get an existing value or the insertion position
Reid Spencer0050c732007-03-01 19:30:34 +0000236 DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
Reid Spencer532d0ce2007-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 Lattner6b6f6ba2007-02-20 06:39:57 +0000242 return Slot = new ConstantInt(ITy, V);
243}
244
245//===----------------------------------------------------------------------===//
Chris Lattner9b4ee0c2007-02-20 07:17:17 +0000246// ConstantFP
Chris Lattner6b6f6ba2007-02-20 06:39:57 +0000247//===----------------------------------------------------------------------===//
248
Dale Johannesenf04afdb2007-08-30 00:23:21 +0000249ConstantFP::ConstantFP(const Type *Ty, const APFloat& V)
250 : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
251 // temporary
252 if (Ty==Type::FloatTy)
253 assert(&V.getSemantics()==&APFloat::IEEEsingle);
Dale Johannesen9d5f4562007-09-12 03:30:33 +0000254 else if (Ty==Type::DoubleTy)
Dale Johannesenf04afdb2007-08-30 00:23:21 +0000255 assert(&V.getSemantics()==&APFloat::IEEEdouble);
Dale Johannesen9d5f4562007-09-12 03:30:33 +0000256 else if (Ty==Type::X86_FP80Ty)
257 assert(&V.getSemantics()==&APFloat::x87DoubleExtended);
258 else if (Ty==Type::FP128Ty)
259 assert(&V.getSemantics()==&APFloat::IEEEquad);
Dale Johannesena471c2e2007-10-11 18:07:22 +0000260 else if (Ty==Type::PPC_FP128Ty)
261 assert(&V.getSemantics()==&APFloat::PPCDoubleDouble);
Dale Johannesen9d5f4562007-09-12 03:30:33 +0000262 else
263 assert(0);
Chris Lattner00950542001-06-06 20:29:01 +0000264}
265
Chris Lattner9b4ee0c2007-02-20 07:17:17 +0000266bool ConstantFP::isNullValue() const {
Dale Johannesen343e7702007-08-24 00:56:33 +0000267 return Val.isZero() && !Val.isNegative();
Chris Lattner9b4ee0c2007-02-20 07:17:17 +0000268}
269
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +0000270ConstantFP *ConstantFP::getNegativeZero(const Type *Ty) {
271 APFloat apf = cast <ConstantFP>(Constant::getNullValue(Ty))->getValueAPF();
272 apf.changeSign();
273 return ConstantFP::get(Ty, apf);
274}
275
Dale Johannesenf04afdb2007-08-30 00:23:21 +0000276bool ConstantFP::isExactlyValue(const APFloat& V) const {
277 return Val.bitwiseIsEqual(V);
Chris Lattner9b4ee0c2007-02-20 07:17:17 +0000278}
279
Chris Lattner9b4ee0c2007-02-20 07:17:17 +0000280namespace {
Dale Johannesen343e7702007-08-24 00:56:33 +0000281 struct DenseMapAPFloatKeyInfo {
Dale Johannesen12595d72007-08-24 22:09:56 +0000282 struct KeyTy {
283 APFloat val;
284 KeyTy(const APFloat& V) : val(V){}
285 KeyTy(const KeyTy& that) : val(that.val) {}
286 bool operator==(const KeyTy& that) const {
287 return this->val.bitwiseIsEqual(that.val);
288 }
289 bool operator!=(const KeyTy& that) const {
290 return !this->operator==(that);
291 }
292 };
293 static inline KeyTy getEmptyKey() {
294 return KeyTy(APFloat(APFloat::Bogus,1));
Reid Spencer532d0ce2007-02-26 23:54:03 +0000295 }
Dale Johannesen12595d72007-08-24 22:09:56 +0000296 static inline KeyTy getTombstoneKey() {
297 return KeyTy(APFloat(APFloat::Bogus,2));
Chris Lattner9b4ee0c2007-02-20 07:17:17 +0000298 }
Dale Johannesen12595d72007-08-24 22:09:56 +0000299 static unsigned getHashValue(const KeyTy &Key) {
300 return Key.val.getHashValue();
Dale Johannesen343e7702007-08-24 00:56:33 +0000301 }
Chris Lattner76c1b972007-09-17 18:34:04 +0000302 static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
303 return LHS == RHS;
304 }
Dale Johannesen343e7702007-08-24 00:56:33 +0000305 static bool isPod() { return false; }
Chris Lattner9b4ee0c2007-02-20 07:17:17 +0000306 };
307}
308
309//---- ConstantFP::get() implementation...
310//
Dale Johannesen12595d72007-08-24 22:09:56 +0000311typedef DenseMap<DenseMapAPFloatKeyInfo::KeyTy, ConstantFP*,
Dale Johannesen343e7702007-08-24 00:56:33 +0000312 DenseMapAPFloatKeyInfo> FPMapTy;
Chris Lattner9b4ee0c2007-02-20 07:17:17 +0000313
Dale Johannesen343e7702007-08-24 00:56:33 +0000314static ManagedStatic<FPMapTy> FPConstants;
Chris Lattner9b4ee0c2007-02-20 07:17:17 +0000315
Dale Johannesenf04afdb2007-08-30 00:23:21 +0000316ConstantFP *ConstantFP::get(const Type *Ty, const APFloat& V) {
317 // temporary
318 if (Ty==Type::FloatTy)
319 assert(&V.getSemantics()==&APFloat::IEEEsingle);
Dale Johannesen9d5f4562007-09-12 03:30:33 +0000320 else if (Ty==Type::DoubleTy)
Dale Johannesenf04afdb2007-08-30 00:23:21 +0000321 assert(&V.getSemantics()==&APFloat::IEEEdouble);
Dale Johannesen9d5f4562007-09-12 03:30:33 +0000322 else if (Ty==Type::X86_FP80Ty)
323 assert(&V.getSemantics()==&APFloat::x87DoubleExtended);
324 else if (Ty==Type::FP128Ty)
325 assert(&V.getSemantics()==&APFloat::IEEEquad);
Dale Johannesena471c2e2007-10-11 18:07:22 +0000326 else if (Ty==Type::PPC_FP128Ty)
327 assert(&V.getSemantics()==&APFloat::PPCDoubleDouble);
Dale Johannesen9d5f4562007-09-12 03:30:33 +0000328 else
329 assert(0);
Dale Johannesenf04afdb2007-08-30 00:23:21 +0000330
331 DenseMapAPFloatKeyInfo::KeyTy Key(V);
332 ConstantFP *&Slot = (*FPConstants)[Key];
333 if (Slot) return Slot;
334 return Slot = new ConstantFP(Ty, V);
335}
Chris Lattner9b4ee0c2007-02-20 07:17:17 +0000336
337//===----------------------------------------------------------------------===//
338// ConstantXXX Classes
339//===----------------------------------------------------------------------===//
340
341
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000342ConstantArray::ConstantArray(const ArrayType *T,
Chris Lattnere4671472005-01-29 00:34:39 +0000343 const std::vector<Constant*> &V)
Chris Lattnerdf0ef1d2005-09-27 06:09:08 +0000344 : Constant(T, ConstantArrayVal, new Use[V.size()], V.size()) {
Alkis Evlogimenose0de1d62004-09-15 02:32:15 +0000345 assert(V.size() == T->getNumElements() &&
346 "Invalid initializer vector for constant array");
Chris Lattnere4671472005-01-29 00:34:39 +0000347 Use *OL = OperandList;
Chris Lattnerdfdd6c52005-10-03 21:56:24 +0000348 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
349 I != E; ++I, ++OL) {
Chris Lattner71abaab2005-10-07 05:23:36 +0000350 Constant *C = *I;
351 assert((C->getType() == T->getElementType() ||
Alkis Evlogimenoscad90ad2004-09-10 04:16:59 +0000352 (T->isAbstract() &&
Chris Lattner71abaab2005-10-07 05:23:36 +0000353 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
Alkis Evlogimenoscad90ad2004-09-10 04:16:59 +0000354 "Initializer for array element doesn't match array element type!");
Chris Lattner71abaab2005-10-07 05:23:36 +0000355 OL->init(C, this);
Chris Lattner00950542001-06-06 20:29:01 +0000356 }
357}
358
Gordon Henriksenafba8fe2007-12-10 02:14:30 +0000359ConstantArray::~ConstantArray() {
360 delete [] OperandList;
Chris Lattnere4671472005-01-29 00:34:39 +0000361}
362
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000363ConstantStruct::ConstantStruct(const StructType *T,
Chris Lattnere4671472005-01-29 00:34:39 +0000364 const std::vector<Constant*> &V)
Chris Lattnerdf0ef1d2005-09-27 06:09:08 +0000365 : Constant(T, ConstantStructVal, new Use[V.size()], V.size()) {
Chris Lattnerd21cd802004-02-09 04:37:31 +0000366 assert(V.size() == T->getNumElements() &&
Vikram S. Adve345e0cf2002-07-14 23:13:17 +0000367 "Invalid initializer vector for constant structure");
Chris Lattnere4671472005-01-29 00:34:39 +0000368 Use *OL = OperandList;
Chris Lattnerdfdd6c52005-10-03 21:56:24 +0000369 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
370 I != E; ++I, ++OL) {
Chris Lattner71abaab2005-10-07 05:23:36 +0000371 Constant *C = *I;
372 assert((C->getType() == T->getElementType(I-V.begin()) ||
Chris Lattnerdfdd6c52005-10-03 21:56:24 +0000373 ((T->getElementType(I-V.begin())->isAbstract() ||
Chris Lattner71abaab2005-10-07 05:23:36 +0000374 C->getType()->isAbstract()) &&
Chris Lattnerdfdd6c52005-10-03 21:56:24 +0000375 T->getElementType(I-V.begin())->getTypeID() ==
Chris Lattner71abaab2005-10-07 05:23:36 +0000376 C->getType()->getTypeID())) &&
Chris Lattnerb8438892003-06-02 17:42:47 +0000377 "Initializer for struct element doesn't match struct element type!");
Chris Lattner71abaab2005-10-07 05:23:36 +0000378 OL->init(C, this);
Chris Lattner00950542001-06-06 20:29:01 +0000379 }
380}
381
Gordon Henriksenafba8fe2007-12-10 02:14:30 +0000382ConstantStruct::~ConstantStruct() {
383 delete [] OperandList;
Chris Lattnere4671472005-01-29 00:34:39 +0000384}
385
386
Reid Spencer9d6565a2007-02-15 02:26:10 +0000387ConstantVector::ConstantVector(const VectorType *T,
Chris Lattnere4671472005-01-29 00:34:39 +0000388 const std::vector<Constant*> &V)
Reid Spencer9d6565a2007-02-15 02:26:10 +0000389 : Constant(T, ConstantVectorVal, new Use[V.size()], V.size()) {
Chris Lattnere4671472005-01-29 00:34:39 +0000390 Use *OL = OperandList;
Chris Lattnerdfdd6c52005-10-03 21:56:24 +0000391 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
392 I != E; ++I, ++OL) {
Chris Lattner71abaab2005-10-07 05:23:36 +0000393 Constant *C = *I;
394 assert((C->getType() == T->getElementType() ||
Alkis Evlogimenoscad90ad2004-09-10 04:16:59 +0000395 (T->isAbstract() &&
Chris Lattner71abaab2005-10-07 05:23:36 +0000396 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
Dan Gohmanfa73ea22007-05-24 14:36:04 +0000397 "Initializer for vector element doesn't match vector element type!");
Chris Lattner71abaab2005-10-07 05:23:36 +0000398 OL->init(C, this);
Brian Gaeke715c90b2004-08-20 06:00:58 +0000399 }
400}
401
Gordon Henriksenafba8fe2007-12-10 02:14:30 +0000402ConstantVector::~ConstantVector() {
403 delete [] OperandList;
Vikram S. Adve345e0cf2002-07-14 23:13:17 +0000404}
405
Gordon Henriksenafba8fe2007-12-10 02:14:30 +0000406// We declare several classes private to this file, so use an anonymous
407// namespace
408namespace {
Reid Spencer728b6db2006-12-03 05:48:19 +0000409
Gordon Henriksenafba8fe2007-12-10 02:14:30 +0000410/// UnaryConstantExpr - This class is private to Constants.cpp, and is used
411/// behind the scenes to implement unary constant exprs.
412class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
413 Use Op;
414public:
415 UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
416 : ConstantExpr(Ty, Opcode, &Op, 1), Op(C, this) {}
417};
Reid Spencer728b6db2006-12-03 05:48:19 +0000418
Gordon Henriksenafba8fe2007-12-10 02:14:30 +0000419/// BinaryConstantExpr - This class is private to Constants.cpp, and is used
420/// behind the scenes to implement binary constant exprs.
421class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
422 Use Ops[2];
423public:
424 BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
425 : ConstantExpr(C1->getType(), Opcode, Ops, 2) {
426 Ops[0].init(C1, this);
427 Ops[1].init(C2, this);
428 }
429};
Vikram S. Adve345e0cf2002-07-14 23:13:17 +0000430
Gordon Henriksenafba8fe2007-12-10 02:14:30 +0000431/// SelectConstantExpr - This class is private to Constants.cpp, and is used
432/// behind the scenes to implement select constant exprs.
433class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
434 Use Ops[3];
435public:
436 SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
437 : ConstantExpr(C2->getType(), Instruction::Select, Ops, 3) {
438 Ops[0].init(C1, this);
439 Ops[1].init(C2, this);
440 Ops[2].init(C3, this);
441 }
442};
Chris Lattnere4671472005-01-29 00:34:39 +0000443
Gordon Henriksenafba8fe2007-12-10 02:14:30 +0000444/// ExtractElementConstantExpr - This class is private to
445/// Constants.cpp, and is used behind the scenes to implement
446/// extractelement constant exprs.
447class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
448 Use Ops[2];
449public:
450 ExtractElementConstantExpr(Constant *C1, Constant *C2)
451 : ConstantExpr(cast<VectorType>(C1->getType())->getElementType(),
452 Instruction::ExtractElement, Ops, 2) {
453 Ops[0].init(C1, this);
454 Ops[1].init(C2, this);
455 }
456};
Robert Bocchinob52ee7f2006-01-10 19:05:34 +0000457
Gordon Henriksenafba8fe2007-12-10 02:14:30 +0000458/// InsertElementConstantExpr - This class is private to
459/// Constants.cpp, and is used behind the scenes to implement
460/// insertelement constant exprs.
461class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
462 Use Ops[3];
463public:
464 InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
465 : ConstantExpr(C1->getType(), Instruction::InsertElement,
466 Ops, 3) {
467 Ops[0].init(C1, this);
468 Ops[1].init(C2, this);
469 Ops[2].init(C3, this);
470 }
471};
Robert Bocchinoc152f9c2006-01-17 20:07:22 +0000472
Gordon Henriksenafba8fe2007-12-10 02:14:30 +0000473/// ShuffleVectorConstantExpr - This class is private to
474/// Constants.cpp, and is used behind the scenes to implement
475/// shufflevector constant exprs.
476class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
477 Use Ops[3];
478public:
479 ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
480 : ConstantExpr(C1->getType(), Instruction::ShuffleVector,
481 Ops, 3) {
482 Ops[0].init(C1, this);
483 Ops[1].init(C2, this);
484 Ops[2].init(C3, this);
485 }
486};
487
488/// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
489/// used behind the scenes to implement getelementpr constant exprs.
490struct VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
491 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
492 const Type *DestTy)
493 : ConstantExpr(DestTy, Instruction::GetElementPtr,
494 new Use[IdxList.size()+1], IdxList.size()+1) {
495 OperandList[0].init(C, this);
496 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
497 OperandList[i+1].init(IdxList[i], this);
498 }
499 ~GetElementPtrConstantExpr() {
500 delete [] OperandList;
501 }
502};
503
504// CompareConstantExpr - This class is private to Constants.cpp, and is used
505// behind the scenes to implement ICmp and FCmp constant expressions. This is
506// needed in order to store the predicate value for these instructions.
507struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
508 unsigned short predicate;
509 Use Ops[2];
510 CompareConstantExpr(Instruction::OtherOps opc, unsigned short pred,
511 Constant* LHS, Constant* RHS)
512 : ConstantExpr(Type::Int1Ty, opc, Ops, 2), predicate(pred) {
513 OperandList[0].init(LHS, this);
514 OperandList[1].init(RHS, this);
515 }
516};
517
518} // end anonymous namespace
519
Reid Spencer3da59db2006-11-27 01:05:10 +0000520
521// Utility function for determining if a ConstantExpr is a CastOp or not. This
522// can't be inline because we don't want to #include Instruction.h into
523// Constant.h
524bool ConstantExpr::isCast() const {
525 return Instruction::isCast(getOpcode());
526}
527
Reid Spencer077d0eb2006-12-04 05:19:50 +0000528bool ConstantExpr::isCompare() const {
529 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
530}
531
Chris Lattner4dcb5402004-03-29 02:37:53 +0000532/// ConstantExpr::get* - Return some common constants without having to
533/// specify the full Instruction::OPCODE identifier.
534///
535Constant *ConstantExpr::getNeg(Constant *C) {
Reid Spencer24d6da52007-01-21 00:29:26 +0000536 return get(Instruction::Sub,
537 ConstantExpr::getZeroValueForNegationExpr(C->getType()),
538 C);
Chris Lattner4dcb5402004-03-29 02:37:53 +0000539}
540Constant *ConstantExpr::getNot(Constant *C) {
Gordon Henriksen46475692007-10-06 14:29:36 +0000541 assert(isa<IntegerType>(C->getType()) && "Cannot NOT a nonintegral value!");
Chris Lattner4dcb5402004-03-29 02:37:53 +0000542 return get(Instruction::Xor, C,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000543 ConstantInt::getAllOnesValue(C->getType()));
Chris Lattner4dcb5402004-03-29 02:37:53 +0000544}
545Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
546 return get(Instruction::Add, C1, C2);
547}
548Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
549 return get(Instruction::Sub, C1, C2);
550}
551Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
552 return get(Instruction::Mul, C1, C2);
553}
Reid Spencer1628cec2006-10-26 06:15:43 +0000554Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2) {
555 return get(Instruction::UDiv, C1, C2);
556}
557Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2) {
558 return get(Instruction::SDiv, C1, C2);
559}
560Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
561 return get(Instruction::FDiv, C1, C2);
Chris Lattner4dcb5402004-03-29 02:37:53 +0000562}
Reid Spencer0a783f72006-11-02 01:53:59 +0000563Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
564 return get(Instruction::URem, C1, C2);
565}
566Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
567 return get(Instruction::SRem, C1, C2);
568}
569Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
570 return get(Instruction::FRem, C1, C2);
Chris Lattner4dcb5402004-03-29 02:37:53 +0000571}
572Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
573 return get(Instruction::And, C1, C2);
574}
575Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
576 return get(Instruction::Or, C1, C2);
577}
578Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
579 return get(Instruction::Xor, C1, C2);
580}
Reid Spencer728b6db2006-12-03 05:48:19 +0000581unsigned ConstantExpr::getPredicate() const {
582 assert(getOpcode() == Instruction::FCmp || getOpcode() == Instruction::ICmp);
Chris Lattnerb7daa842007-10-18 16:26:24 +0000583 return ((const CompareConstantExpr*)this)->predicate;
Reid Spencer728b6db2006-12-03 05:48:19 +0000584}
Chris Lattner4dcb5402004-03-29 02:37:53 +0000585Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
586 return get(Instruction::Shl, C1, C2);
587}
Reid Spencer3822ff52006-11-08 06:47:33 +0000588Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2) {
589 return get(Instruction::LShr, C1, C2);
Chris Lattner4dcb5402004-03-29 02:37:53 +0000590}
Reid Spencer3822ff52006-11-08 06:47:33 +0000591Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2) {
592 return get(Instruction::AShr, C1, C2);
Chris Lattnerc9710252004-05-25 05:32:43 +0000593}
Chris Lattnerf4ba6c72001-10-03 06:12:09 +0000594
Chris Lattner1fe8f6b2006-07-14 19:37:40 +0000595/// getWithOperandReplaced - Return a constant expression identical to this
596/// one, but with the specified operand set to the specified value.
Reid Spencer3da59db2006-11-27 01:05:10 +0000597Constant *
598ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
Chris Lattner1fe8f6b2006-07-14 19:37:40 +0000599 assert(OpNo < getNumOperands() && "Operand num is out of range!");
600 assert(Op->getType() == getOperand(OpNo)->getType() &&
601 "Replacing operand with value of different type!");
Chris Lattnerb88a7fb2006-07-14 22:20:01 +0000602 if (getOperand(OpNo) == Op)
603 return const_cast<ConstantExpr*>(this);
Chris Lattner1fe8f6b2006-07-14 19:37:40 +0000604
Chris Lattnerb88a7fb2006-07-14 22:20:01 +0000605 Constant *Op0, *Op1, *Op2;
Chris Lattner1fe8f6b2006-07-14 19:37:40 +0000606 switch (getOpcode()) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000607 case Instruction::Trunc:
608 case Instruction::ZExt:
609 case Instruction::SExt:
610 case Instruction::FPTrunc:
611 case Instruction::FPExt:
612 case Instruction::UIToFP:
613 case Instruction::SIToFP:
614 case Instruction::FPToUI:
615 case Instruction::FPToSI:
616 case Instruction::PtrToInt:
617 case Instruction::IntToPtr:
618 case Instruction::BitCast:
619 return ConstantExpr::getCast(getOpcode(), Op, getType());
Chris Lattnerb88a7fb2006-07-14 22:20:01 +0000620 case Instruction::Select:
621 Op0 = (OpNo == 0) ? Op : getOperand(0);
622 Op1 = (OpNo == 1) ? Op : getOperand(1);
623 Op2 = (OpNo == 2) ? Op : getOperand(2);
624 return ConstantExpr::getSelect(Op0, Op1, Op2);
625 case Instruction::InsertElement:
626 Op0 = (OpNo == 0) ? Op : getOperand(0);
627 Op1 = (OpNo == 1) ? Op : getOperand(1);
628 Op2 = (OpNo == 2) ? Op : getOperand(2);
629 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
630 case Instruction::ExtractElement:
631 Op0 = (OpNo == 0) ? Op : getOperand(0);
632 Op1 = (OpNo == 1) ? Op : getOperand(1);
633 return ConstantExpr::getExtractElement(Op0, Op1);
634 case Instruction::ShuffleVector:
635 Op0 = (OpNo == 0) ? Op : getOperand(0);
636 Op1 = (OpNo == 1) ? Op : getOperand(1);
637 Op2 = (OpNo == 2) ? Op : getOperand(2);
638 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattner1fe8f6b2006-07-14 19:37:40 +0000639 case Instruction::GetElementPtr: {
Chris Lattnerf9021ff2007-02-19 20:01:23 +0000640 SmallVector<Constant*, 8> Ops;
641 Ops.resize(getNumOperands());
Chris Lattner1fe8f6b2006-07-14 19:37:40 +0000642 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
Chris Lattnerf9021ff2007-02-19 20:01:23 +0000643 Ops[i] = getOperand(i);
Chris Lattner1fe8f6b2006-07-14 19:37:40 +0000644 if (OpNo == 0)
Chris Lattnerf9021ff2007-02-19 20:01:23 +0000645 return ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
Chris Lattner1fe8f6b2006-07-14 19:37:40 +0000646 Ops[OpNo-1] = Op;
Chris Lattnerf9021ff2007-02-19 20:01:23 +0000647 return ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
Chris Lattner1fe8f6b2006-07-14 19:37:40 +0000648 }
Chris Lattner1fe8f6b2006-07-14 19:37:40 +0000649 default:
650 assert(getNumOperands() == 2 && "Must be binary operator?");
Chris Lattnerb88a7fb2006-07-14 22:20:01 +0000651 Op0 = (OpNo == 0) ? Op : getOperand(0);
652 Op1 = (OpNo == 1) ? Op : getOperand(1);
653 return ConstantExpr::get(getOpcode(), Op0, Op1);
654 }
655}
656
657/// getWithOperands - This returns the current constant expression with the
658/// operands replaced with the specified values. The specified operands must
659/// match count and type with the existing ones.
660Constant *ConstantExpr::
661getWithOperands(const std::vector<Constant*> &Ops) const {
662 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
663 bool AnyChange = false;
664 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
665 assert(Ops[i]->getType() == getOperand(i)->getType() &&
666 "Operand type mismatch!");
667 AnyChange |= Ops[i] != getOperand(i);
668 }
669 if (!AnyChange) // No operands changed, return self.
670 return const_cast<ConstantExpr*>(this);
671
672 switch (getOpcode()) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000673 case Instruction::Trunc:
674 case Instruction::ZExt:
675 case Instruction::SExt:
676 case Instruction::FPTrunc:
677 case Instruction::FPExt:
678 case Instruction::UIToFP:
679 case Instruction::SIToFP:
680 case Instruction::FPToUI:
681 case Instruction::FPToSI:
682 case Instruction::PtrToInt:
683 case Instruction::IntToPtr:
684 case Instruction::BitCast:
685 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
Chris Lattnerb88a7fb2006-07-14 22:20:01 +0000686 case Instruction::Select:
687 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
688 case Instruction::InsertElement:
689 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
690 case Instruction::ExtractElement:
691 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
692 case Instruction::ShuffleVector:
693 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
Chris Lattnerf9021ff2007-02-19 20:01:23 +0000694 case Instruction::GetElementPtr:
695 return ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], Ops.size()-1);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000696 case Instruction::ICmp:
697 case Instruction::FCmp:
698 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
Chris Lattnerb88a7fb2006-07-14 22:20:01 +0000699 default:
700 assert(getNumOperands() == 2 && "Must be binary operator?");
701 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
Chris Lattner1fe8f6b2006-07-14 19:37:40 +0000702 }
703}
704
Chris Lattner00950542001-06-06 20:29:01 +0000705
706//===----------------------------------------------------------------------===//
Chris Lattner00950542001-06-06 20:29:01 +0000707// isValueValidForType implementations
708
Reid Spencer9b11d512006-12-19 01:28:19 +0000709bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000710 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
Reid Spencera54b7cb2007-01-12 07:05:14 +0000711 if (Ty == Type::Int1Ty)
712 return Val == 0 || Val == 1;
Reid Spencer554cec62007-02-05 23:47:56 +0000713 if (NumBits >= 64)
Reid Spencera54b7cb2007-01-12 07:05:14 +0000714 return true; // always true, has to fit in largest type
715 uint64_t Max = (1ll << NumBits) - 1;
716 return Val <= Max;
Reid Spencer9b11d512006-12-19 01:28:19 +0000717}
718
Reid Spencerb83eb642006-10-20 07:07:24 +0000719bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000720 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
Reid Spencera54b7cb2007-01-12 07:05:14 +0000721 if (Ty == Type::Int1Ty)
Reid Spencerc1030572007-01-19 21:13:56 +0000722 return Val == 0 || Val == 1 || Val == -1;
Reid Spencer554cec62007-02-05 23:47:56 +0000723 if (NumBits >= 64)
Reid Spencera54b7cb2007-01-12 07:05:14 +0000724 return true; // always true, has to fit in largest type
725 int64_t Min = -(1ll << (NumBits-1));
726 int64_t Max = (1ll << (NumBits-1)) - 1;
727 return (Val >= Min && Val <= Max);
Chris Lattner00950542001-06-06 20:29:01 +0000728}
729
Dale Johannesenf04afdb2007-08-30 00:23:21 +0000730bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
731 // convert modifies in place, so make a copy.
732 APFloat Val2 = APFloat(Val);
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000733 switch (Ty->getTypeID()) {
Chris Lattner00950542001-06-06 20:29:01 +0000734 default:
735 return false; // These can't be represented as floating point!
736
Dale Johannesenf04afdb2007-08-30 00:23:21 +0000737 // FIXME rounding mode needs to be more flexible
Chris Lattner00950542001-06-06 20:29:01 +0000738 case Type::FloatTyID:
Dale Johannesenf04afdb2007-08-30 00:23:21 +0000739 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
740 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven) ==
741 APFloat::opOK;
Chris Lattner00950542001-06-06 20:29:01 +0000742 case Type::DoubleTyID:
Dale Johannesenf04afdb2007-08-30 00:23:21 +0000743 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
744 &Val2.getSemantics() == &APFloat::IEEEdouble ||
745 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven) ==
746 APFloat::opOK;
Dale Johannesenebbc95d2007-08-09 22:51:36 +0000747 case Type::X86_FP80TyID:
Dale Johannesen9d5f4562007-09-12 03:30:33 +0000748 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
749 &Val2.getSemantics() == &APFloat::IEEEdouble ||
750 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
Dale Johannesenebbc95d2007-08-09 22:51:36 +0000751 case Type::FP128TyID:
Dale Johannesen9d5f4562007-09-12 03:30:33 +0000752 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
753 &Val2.getSemantics() == &APFloat::IEEEdouble ||
754 &Val2.getSemantics() == &APFloat::IEEEquad;
Dale Johannesena471c2e2007-10-11 18:07:22 +0000755 case Type::PPC_FP128TyID:
756 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
757 &Val2.getSemantics() == &APFloat::IEEEdouble ||
758 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
Chris Lattner00950542001-06-06 20:29:01 +0000759 }
Chris Lattnerd74ea2b2006-05-24 17:04:05 +0000760}
Chris Lattner37bf6302001-07-20 19:16:02 +0000761
Chris Lattner531daef2001-09-07 16:46:31 +0000762//===----------------------------------------------------------------------===//
Chris Lattner531daef2001-09-07 16:46:31 +0000763// Factory Function Implementation
764
Chris Lattner02ec5ed2003-05-23 20:03:32 +0000765// ConstantCreator - A class that is used to create constants by
766// ValueMap*. This class should be partially specialized if there is
767// something strange that needs to be done to interface to the ctor for the
768// constant.
769//
Chris Lattner31f84992003-11-21 20:23:48 +0000770namespace llvm {
771 template<class ConstantClass, class TypeClass, class ValType>
Chris Lattnerf190d382006-06-28 21:38:54 +0000772 struct VISIBILITY_HIDDEN ConstantCreator {
Chris Lattner31f84992003-11-21 20:23:48 +0000773 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
774 return new ConstantClass(Ty, V);
775 }
776 };
Misha Brukmanfd939082005-04-21 23:48:37 +0000777
Chris Lattner31f84992003-11-21 20:23:48 +0000778 template<class ConstantClass, class TypeClass>
Chris Lattnerf190d382006-06-28 21:38:54 +0000779 struct VISIBILITY_HIDDEN ConvertConstantType {
Chris Lattner31f84992003-11-21 20:23:48 +0000780 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
781 assert(0 && "This type cannot be converted!\n");
782 abort();
783 }
784 };
Chris Lattnered468e372003-10-05 00:17:43 +0000785
Chris Lattnera55b30a2005-10-04 17:48:46 +0000786 template<class ValType, class TypeClass, class ConstantClass,
787 bool HasLargeKey = false /*true for arrays and structs*/ >
Chris Lattnerf190d382006-06-28 21:38:54 +0000788 class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
Chris Lattnercea141f2005-10-03 22:51:37 +0000789 public:
Jim Laskeyede5aa42006-07-17 17:38:29 +0000790 typedef std::pair<const Type*, ValType> MapKey;
791 typedef std::map<MapKey, Constant *> MapTy;
792 typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
793 typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
Chris Lattnercea141f2005-10-03 22:51:37 +0000794 private:
Chris Lattnerd7a3fc62005-10-04 16:52:46 +0000795 /// Map - This is the main map from the element descriptor to the Constants.
796 /// This is the primary way we avoid creating two of the same shape
797 /// constant.
Chris Lattnered468e372003-10-05 00:17:43 +0000798 MapTy Map;
Chris Lattnera55b30a2005-10-04 17:48:46 +0000799
800 /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
801 /// from the constants to their element in Map. This is important for
802 /// removal of constants from the array, which would otherwise have to scan
803 /// through the map with very large keys.
Jim Laskeyede5aa42006-07-17 17:38:29 +0000804 InverseMapTy InverseMap;
Chris Lattnered468e372003-10-05 00:17:43 +0000805
Jim Laskeyede5aa42006-07-17 17:38:29 +0000806 /// AbstractTypeMap - Map for abstract type constants.
807 ///
Chris Lattnered468e372003-10-05 00:17:43 +0000808 AbstractTypeMapTy AbstractTypeMap;
Chris Lattner8a7ad2d2004-11-19 16:39:44 +0000809
Chris Lattner02ec5ed2003-05-23 20:03:32 +0000810 public:
Jim Laskeyede5aa42006-07-17 17:38:29 +0000811 typename MapTy::iterator map_end() { return Map.end(); }
Chris Lattnercea141f2005-10-03 22:51:37 +0000812
813 /// InsertOrGetItem - Return an iterator for the specified element.
814 /// If the element exists in the map, the returned iterator points to the
815 /// entry and Exists=true. If not, the iterator points to the newly
816 /// inserted entry and returns Exists=false. Newly inserted entries have
817 /// I->second == 0, and should be filled in.
Jim Laskeyede5aa42006-07-17 17:38:29 +0000818 typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
819 &InsertVal,
Chris Lattnercea141f2005-10-03 22:51:37 +0000820 bool &Exists) {
Jim Laskeyede5aa42006-07-17 17:38:29 +0000821 std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
Chris Lattnercea141f2005-10-03 22:51:37 +0000822 Exists = !IP.second;
823 return IP.first;
824 }
Chris Lattnerd7a3fc62005-10-04 16:52:46 +0000825
Chris Lattnera55b30a2005-10-04 17:48:46 +0000826private:
Jim Laskeyede5aa42006-07-17 17:38:29 +0000827 typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
Chris Lattnera55b30a2005-10-04 17:48:46 +0000828 if (HasLargeKey) {
Jim Laskeyede5aa42006-07-17 17:38:29 +0000829 typename InverseMapTy::iterator IMI = InverseMap.find(CP);
Chris Lattnera55b30a2005-10-04 17:48:46 +0000830 assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
831 IMI->second->second == CP &&
832 "InverseMap corrupt!");
833 return IMI->second;
834 }
835
Jim Laskeyede5aa42006-07-17 17:38:29 +0000836 typename MapTy::iterator I =
Chris Lattnera55b30a2005-10-04 17:48:46 +0000837 Map.find(MapKey((TypeClass*)CP->getRawType(), getValType(CP)));
Chris Lattnerd7a3fc62005-10-04 16:52:46 +0000838 if (I == Map.end() || I->second != CP) {
839 // FIXME: This should not use a linear scan. If this gets to be a
840 // performance problem, someone should look at this.
841 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
842 /* empty */;
843 }
Chris Lattnera55b30a2005-10-04 17:48:46 +0000844 return I;
845 }
846public:
847
Chris Lattnercea141f2005-10-03 22:51:37 +0000848 /// getOrCreate - Return the specified constant from the map, creating it if
849 /// necessary.
Chris Lattner02ec5ed2003-05-23 20:03:32 +0000850 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
Chris Lattnered468e372003-10-05 00:17:43 +0000851 MapKey Lookup(Ty, V);
Jim Laskeyede5aa42006-07-17 17:38:29 +0000852 typename MapTy::iterator I = Map.lower_bound(Lookup);
Reid Spencerb83eb642006-10-20 07:07:24 +0000853 // Is it in the map?
Chris Lattner02ec5ed2003-05-23 20:03:32 +0000854 if (I != Map.end() && I->first == Lookup)
Reid Spencerb83eb642006-10-20 07:07:24 +0000855 return static_cast<ConstantClass *>(I->second);
Chris Lattner02ec5ed2003-05-23 20:03:32 +0000856
857 // If no preexisting value, create one now...
858 ConstantClass *Result =
859 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
860
Chris Lattnered468e372003-10-05 00:17:43 +0000861 /// FIXME: why does this assert fail when loading 176.gcc?
862 //assert(Result->getType() == Ty && "Type specified is not correct!");
863 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
864
Chris Lattnera55b30a2005-10-04 17:48:46 +0000865 if (HasLargeKey) // Remember the reverse mapping if needed.
866 InverseMap.insert(std::make_pair(Result, I));
867
Chris Lattnered468e372003-10-05 00:17:43 +0000868 // If the type of the constant is abstract, make sure that an entry exists
869 // for it in the AbstractTypeMap.
870 if (Ty->isAbstract()) {
871 typename AbstractTypeMapTy::iterator TI =
872 AbstractTypeMap.lower_bound(Ty);
873
874 if (TI == AbstractTypeMap.end() || TI->first != Ty) {
875 // Add ourselves to the ATU list of the type.
876 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
877
878 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
879 }
880 }
Chris Lattner02ec5ed2003-05-23 20:03:32 +0000881 return Result;
882 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000883
Chris Lattner02ec5ed2003-05-23 20:03:32 +0000884 void remove(ConstantClass *CP) {
Jim Laskeyede5aa42006-07-17 17:38:29 +0000885 typename MapTy::iterator I = FindExistingElement(CP);
Chris Lattnered468e372003-10-05 00:17:43 +0000886 assert(I != Map.end() && "Constant not found in constant table!");
Chris Lattner6823c9f2004-08-04 04:48:01 +0000887 assert(I->second == CP && "Didn't find correct element?");
Chris Lattnered468e372003-10-05 00:17:43 +0000888
Chris Lattnera55b30a2005-10-04 17:48:46 +0000889 if (HasLargeKey) // Remember the reverse mapping if needed.
890 InverseMap.erase(CP);
891
Chris Lattnered468e372003-10-05 00:17:43 +0000892 // Now that we found the entry, make sure this isn't the entry that
893 // the AbstractTypeMap points to.
Jim Laskeyede5aa42006-07-17 17:38:29 +0000894 const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
Chris Lattnered468e372003-10-05 00:17:43 +0000895 if (Ty->isAbstract()) {
896 assert(AbstractTypeMap.count(Ty) &&
897 "Abstract type not in AbstractTypeMap?");
Jim Laskeyede5aa42006-07-17 17:38:29 +0000898 typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
Chris Lattnered468e372003-10-05 00:17:43 +0000899 if (ATMEntryIt == I) {
900 // Yes, we are removing the representative entry for this type.
901 // See if there are any other entries of the same type.
Jim Laskeyede5aa42006-07-17 17:38:29 +0000902 typename MapTy::iterator TmpIt = ATMEntryIt;
Misha Brukmanfd939082005-04-21 23:48:37 +0000903
Chris Lattnered468e372003-10-05 00:17:43 +0000904 // First check the entry before this one...
905 if (TmpIt != Map.begin()) {
906 --TmpIt;
907 if (TmpIt->first.first != Ty) // Not the same type, move back...
908 ++TmpIt;
909 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000910
Chris Lattnered468e372003-10-05 00:17:43 +0000911 // If we didn't find the same type, try to move forward...
912 if (TmpIt == ATMEntryIt) {
913 ++TmpIt;
914 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
915 --TmpIt; // No entry afterwards with the same type
916 }
917
918 // If there is another entry in the map of the same abstract type,
919 // update the AbstractTypeMap entry now.
920 if (TmpIt != ATMEntryIt) {
921 ATMEntryIt = TmpIt;
922 } else {
923 // Otherwise, we are removing the last instance of this type
924 // from the table. Remove from the ATM, and from user list.
925 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
926 AbstractTypeMap.erase(Ty);
927 }
Chris Lattner02ec5ed2003-05-23 20:03:32 +0000928 }
Chris Lattnered468e372003-10-05 00:17:43 +0000929 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000930
Chris Lattnered468e372003-10-05 00:17:43 +0000931 Map.erase(I);
932 }
933
Chris Lattnera1e3f542005-10-04 21:35:50 +0000934
935 /// MoveConstantToNewSlot - If we are about to change C to be the element
936 /// specified by I, update our internal data structures to reflect this
937 /// fact.
Jim Laskeyede5aa42006-07-17 17:38:29 +0000938 void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
Chris Lattnera1e3f542005-10-04 21:35:50 +0000939 // First, remove the old location of the specified constant in the map.
Jim Laskeyede5aa42006-07-17 17:38:29 +0000940 typename MapTy::iterator OldI = FindExistingElement(C);
Chris Lattnera1e3f542005-10-04 21:35:50 +0000941 assert(OldI != Map.end() && "Constant not found in constant table!");
942 assert(OldI->second == C && "Didn't find correct element?");
943
944 // If this constant is the representative element for its abstract type,
945 // update the AbstractTypeMap so that the representative element is I.
946 if (C->getType()->isAbstract()) {
947 typename AbstractTypeMapTy::iterator ATI =
948 AbstractTypeMap.find(C->getType());
949 assert(ATI != AbstractTypeMap.end() &&
950 "Abstract type not in AbstractTypeMap?");
951 if (ATI->second == OldI)
952 ATI->second = I;
953 }
954
955 // Remove the old entry from the map.
956 Map.erase(OldI);
957
958 // Update the inverse map so that we know that this constant is now
959 // located at descriptor I.
960 if (HasLargeKey) {
961 assert(I->second == C && "Bad inversemap entry!");
962 InverseMap[C] = I;
963 }
964 }
965
Chris Lattnered468e372003-10-05 00:17:43 +0000966 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
Misha Brukmanfd939082005-04-21 23:48:37 +0000967 typename AbstractTypeMapTy::iterator I =
Jim Laskeyede5aa42006-07-17 17:38:29 +0000968 AbstractTypeMap.find(cast<Type>(OldTy));
Chris Lattnered468e372003-10-05 00:17:43 +0000969
970 assert(I != AbstractTypeMap.end() &&
971 "Abstract type not in AbstractTypeMap?");
972
973 // Convert a constant at a time until the last one is gone. The last one
974 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
975 // eliminated eventually.
976 do {
977 ConvertConstantType<ConstantClass,
Jim Laskeyede5aa42006-07-17 17:38:29 +0000978 TypeClass>::convert(
979 static_cast<ConstantClass *>(I->second->second),
Chris Lattnered468e372003-10-05 00:17:43 +0000980 cast<TypeClass>(NewTy));
981
Jim Laskeyede5aa42006-07-17 17:38:29 +0000982 I = AbstractTypeMap.find(cast<Type>(OldTy));
Chris Lattnered468e372003-10-05 00:17:43 +0000983 } while (I != AbstractTypeMap.end());
984 }
985
986 // If the type became concrete without being refined to any other existing
987 // type, we just remove ourselves from the ATU list.
988 void typeBecameConcrete(const DerivedType *AbsTy) {
989 AbsTy->removeAbstractTypeUser(this);
990 }
991
992 void dump() const {
Bill Wendling2e3def12006-11-17 08:03:48 +0000993 DOUT << "Constant.cpp: ValueMap\n";
Chris Lattner02ec5ed2003-05-23 20:03:32 +0000994 }
995 };
996}
997
Chris Lattner003cbf32006-09-28 23:36:21 +0000998
Chris Lattnerd1afbd02007-02-20 06:11:36 +0000999
Chris Lattner40bbeb52004-02-15 05:53:04 +00001000//---- ConstantAggregateZero::get() implementation...
1001//
1002namespace llvm {
1003 // ConstantAggregateZero does not take extra "value" argument...
1004 template<class ValType>
1005 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
1006 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
1007 return new ConstantAggregateZero(Ty);
1008 }
1009 };
1010
1011 template<>
1012 struct ConvertConstantType<ConstantAggregateZero, Type> {
1013 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
1014 // Make everyone now use a constant of the new type...
1015 Constant *New = ConstantAggregateZero::get(NewTy);
1016 assert(New != OldC && "Didn't replace constant??");
1017 OldC->uncheckedReplaceAllUsesWith(New);
1018 OldC->destroyConstant(); // This constant is now dead, destroy it.
1019 }
1020 };
1021}
1022
Chris Lattner8a94bf12006-09-28 00:35:06 +00001023static ManagedStatic<ValueMap<char, Type,
1024 ConstantAggregateZero> > AggZeroConstants;
Chris Lattner40bbeb52004-02-15 05:53:04 +00001025
Chris Lattner6823c9f2004-08-04 04:48:01 +00001026static char getValType(ConstantAggregateZero *CPZ) { return 0; }
1027
Chris Lattner40bbeb52004-02-15 05:53:04 +00001028Constant *ConstantAggregateZero::get(const Type *Ty) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001029 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) &&
Chris Lattner31d1a2c2006-06-10 04:16:23 +00001030 "Cannot create an aggregate zero of non-aggregate type!");
Chris Lattner8a94bf12006-09-28 00:35:06 +00001031 return AggZeroConstants->getOrCreate(Ty, 0);
Chris Lattner40bbeb52004-02-15 05:53:04 +00001032}
1033
1034// destroyConstant - Remove the constant from the constant table...
1035//
1036void ConstantAggregateZero::destroyConstant() {
Chris Lattner8a94bf12006-09-28 00:35:06 +00001037 AggZeroConstants->remove(this);
Chris Lattner40bbeb52004-02-15 05:53:04 +00001038 destroyConstantImpl();
1039}
1040
Chris Lattnere9bb2df2001-12-03 22:26:30 +00001041//---- ConstantArray::get() implementation...
Chris Lattner531daef2001-09-07 16:46:31 +00001042//
Chris Lattner31f84992003-11-21 20:23:48 +00001043namespace llvm {
1044 template<>
1045 struct ConvertConstantType<ConstantArray, ArrayType> {
1046 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
1047 // Make everyone now use a constant of the new type...
1048 std::vector<Constant*> C;
1049 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1050 C.push_back(cast<Constant>(OldC->getOperand(i)));
1051 Constant *New = ConstantArray::get(NewTy, C);
1052 assert(New != OldC && "Didn't replace constant??");
1053 OldC->uncheckedReplaceAllUsesWith(New);
1054 OldC->destroyConstant(); // This constant is now dead, destroy it.
1055 }
1056 };
1057}
Chris Lattnered468e372003-10-05 00:17:43 +00001058
Chris Lattner6823c9f2004-08-04 04:48:01 +00001059static std::vector<Constant*> getValType(ConstantArray *CA) {
1060 std::vector<Constant*> Elements;
1061 Elements.reserve(CA->getNumOperands());
1062 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1063 Elements.push_back(cast<Constant>(CA->getOperand(i)));
1064 return Elements;
1065}
1066
Chris Lattnercea141f2005-10-03 22:51:37 +00001067typedef ValueMap<std::vector<Constant*>, ArrayType,
Chris Lattnera55b30a2005-10-04 17:48:46 +00001068 ConstantArray, true /*largekey*/> ArrayConstantsTy;
Chris Lattner8a94bf12006-09-28 00:35:06 +00001069static ManagedStatic<ArrayConstantsTy> ArrayConstants;
Chris Lattner531daef2001-09-07 16:46:31 +00001070
Chris Lattnerca705fa2004-02-15 04:14:47 +00001071Constant *ConstantArray::get(const ArrayType *Ty,
Chris Lattner40bbeb52004-02-15 05:53:04 +00001072 const std::vector<Constant*> &V) {
1073 // If this is an all-zero array, return a ConstantAggregateZero object
1074 if (!V.empty()) {
1075 Constant *C = V[0];
1076 if (!C->isNullValue())
Chris Lattner8a94bf12006-09-28 00:35:06 +00001077 return ArrayConstants->getOrCreate(Ty, V);
Chris Lattner40bbeb52004-02-15 05:53:04 +00001078 for (unsigned i = 1, e = V.size(); i != e; ++i)
1079 if (V[i] != C)
Chris Lattner8a94bf12006-09-28 00:35:06 +00001080 return ArrayConstants->getOrCreate(Ty, V);
Chris Lattner40bbeb52004-02-15 05:53:04 +00001081 }
1082 return ConstantAggregateZero::get(Ty);
Chris Lattner531daef2001-09-07 16:46:31 +00001083}
1084
Chris Lattner02ec5ed2003-05-23 20:03:32 +00001085// destroyConstant - Remove the constant from the constant table...
1086//
1087void ConstantArray::destroyConstant() {
Chris Lattner8a94bf12006-09-28 00:35:06 +00001088 ArrayConstants->remove(this);
Chris Lattner02ec5ed2003-05-23 20:03:32 +00001089 destroyConstantImpl();
1090}
1091
Reid Spencer89494772006-05-30 08:23:18 +00001092/// ConstantArray::get(const string&) - Return an array that is initialized to
1093/// contain the specified string. If length is zero then a null terminator is
1094/// added to the specified string so that it may be used in a natural way.
1095/// Otherwise, the length parameter specifies how much of the string to use
1096/// and it won't be null terminated.
1097///
Reid Spencer461bed22006-05-30 18:15:07 +00001098Constant *ConstantArray::get(const std::string &Str, bool AddNull) {
Chris Lattner697954c2002-01-20 22:54:45 +00001099 std::vector<Constant*> ElementVals;
Reid Spencer461bed22006-05-30 18:15:07 +00001100 for (unsigned i = 0; i < Str.length(); ++i)
Reid Spencer79e21d32006-12-31 05:26:44 +00001101 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, Str[i]));
Chris Lattnerc5bdb242001-10-14 23:54:12 +00001102
1103 // Add a null terminator to the string...
Reid Spencer461bed22006-05-30 18:15:07 +00001104 if (AddNull) {
Reid Spencer79e21d32006-12-31 05:26:44 +00001105 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, 0));
Reid Spencer89494772006-05-30 08:23:18 +00001106 }
Chris Lattnerc5bdb242001-10-14 23:54:12 +00001107
Reid Spencer79e21d32006-12-31 05:26:44 +00001108 ArrayType *ATy = ArrayType::get(Type::Int8Ty, ElementVals.size());
Chris Lattnere9bb2df2001-12-03 22:26:30 +00001109 return ConstantArray::get(ATy, ElementVals);
Vikram S. Advedb2da492001-10-14 23:17:20 +00001110}
1111
Reid Spencer3d10b0b2007-01-26 07:37:34 +00001112/// isString - This method returns true if the array is an array of i8, and
1113/// if the elements of the array are all ConstantInt's.
Chris Lattner13cfdea2004-01-14 17:06:38 +00001114bool ConstantArray::isString() const {
Reid Spencer3d10b0b2007-01-26 07:37:34 +00001115 // Check the element type for i8...
Reid Spencer79e21d32006-12-31 05:26:44 +00001116 if (getType()->getElementType() != Type::Int8Ty)
Chris Lattner13cfdea2004-01-14 17:06:38 +00001117 return false;
1118 // Check the elements to make sure they are all integers, not constant
1119 // expressions.
1120 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1121 if (!isa<ConstantInt>(getOperand(i)))
1122 return false;
1123 return true;
1124}
1125
Evan Cheng22c70302006-10-26 19:15:05 +00001126/// isCString - This method returns true if the array is a string (see
1127/// isString) and it ends in a null byte \0 and does not contains any other
1128/// null bytes except its terminator.
1129bool ConstantArray::isCString() const {
Reid Spencer3d10b0b2007-01-26 07:37:34 +00001130 // Check the element type for i8...
Reid Spencer79e21d32006-12-31 05:26:44 +00001131 if (getType()->getElementType() != Type::Int8Ty)
Evan Chengabf63452006-10-26 21:48:03 +00001132 return false;
1133 Constant *Zero = Constant::getNullValue(getOperand(0)->getType());
1134 // Last element must be a null.
1135 if (getOperand(getNumOperands()-1) != Zero)
1136 return false;
1137 // Other elements must be non-null integers.
1138 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1139 if (!isa<ConstantInt>(getOperand(i)))
Evan Cheng22c70302006-10-26 19:15:05 +00001140 return false;
Evan Chengabf63452006-10-26 21:48:03 +00001141 if (getOperand(i) == Zero)
1142 return false;
1143 }
Evan Cheng22c70302006-10-26 19:15:05 +00001144 return true;
1145}
1146
1147
Reid Spencer3d10b0b2007-01-26 07:37:34 +00001148// getAsString - If the sub-element type of this array is i8
Chris Lattner93aeea32002-08-26 17:53:56 +00001149// then this method converts the array to an std::string and returns it.
1150// Otherwise, it asserts out.
1151//
1152std::string ConstantArray::getAsString() const {
Chris Lattner13cfdea2004-01-14 17:06:38 +00001153 assert(isString() && "Not a string!");
Chris Lattner93aeea32002-08-26 17:53:56 +00001154 std::string Result;
Chris Lattnerc07736a2003-07-23 15:22:26 +00001155 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
Reid Spencerb83eb642006-10-20 07:07:24 +00001156 Result += (char)cast<ConstantInt>(getOperand(i))->getZExtValue();
Chris Lattner93aeea32002-08-26 17:53:56 +00001157 return Result;
1158}
1159
1160
Chris Lattnere9bb2df2001-12-03 22:26:30 +00001161//---- ConstantStruct::get() implementation...
Chris Lattner531daef2001-09-07 16:46:31 +00001162//
Chris Lattnered468e372003-10-05 00:17:43 +00001163
Chris Lattner31f84992003-11-21 20:23:48 +00001164namespace llvm {
1165 template<>
1166 struct ConvertConstantType<ConstantStruct, StructType> {
1167 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1168 // Make everyone now use a constant of the new type...
1169 std::vector<Constant*> C;
1170 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1171 C.push_back(cast<Constant>(OldC->getOperand(i)));
1172 Constant *New = ConstantStruct::get(NewTy, C);
1173 assert(New != OldC && "Didn't replace constant??");
Misha Brukmanfd939082005-04-21 23:48:37 +00001174
Chris Lattner31f84992003-11-21 20:23:48 +00001175 OldC->uncheckedReplaceAllUsesWith(New);
1176 OldC->destroyConstant(); // This constant is now dead, destroy it.
1177 }
1178 };
1179}
Chris Lattnered468e372003-10-05 00:17:43 +00001180
Chris Lattnerc182a882005-10-04 01:17:50 +00001181typedef ValueMap<std::vector<Constant*>, StructType,
Chris Lattnera55b30a2005-10-04 17:48:46 +00001182 ConstantStruct, true /*largekey*/> StructConstantsTy;
Chris Lattner8a94bf12006-09-28 00:35:06 +00001183static ManagedStatic<StructConstantsTy> StructConstants;
Chris Lattner531daef2001-09-07 16:46:31 +00001184
Chris Lattner6823c9f2004-08-04 04:48:01 +00001185static std::vector<Constant*> getValType(ConstantStruct *CS) {
1186 std::vector<Constant*> Elements;
1187 Elements.reserve(CS->getNumOperands());
1188 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1189 Elements.push_back(cast<Constant>(CS->getOperand(i)));
1190 return Elements;
1191}
1192
Chris Lattnerca705fa2004-02-15 04:14:47 +00001193Constant *ConstantStruct::get(const StructType *Ty,
1194 const std::vector<Constant*> &V) {
Chris Lattner40bbeb52004-02-15 05:53:04 +00001195 // Create a ConstantAggregateZero value if all elements are zeros...
1196 for (unsigned i = 0, e = V.size(); i != e; ++i)
1197 if (!V[i]->isNullValue())
Chris Lattner8a94bf12006-09-28 00:35:06 +00001198 return StructConstants->getOrCreate(Ty, V);
Chris Lattner40bbeb52004-02-15 05:53:04 +00001199
1200 return ConstantAggregateZero::get(Ty);
Chris Lattner531daef2001-09-07 16:46:31 +00001201}
Chris Lattner6a57baa2001-10-03 15:39:36 +00001202
Andrew Lenharth38ecbf12006-12-08 18:06:16 +00001203Constant *ConstantStruct::get(const std::vector<Constant*> &V, bool packed) {
Chris Lattnerb370c7a2004-07-12 20:35:11 +00001204 std::vector<const Type*> StructEls;
1205 StructEls.reserve(V.size());
1206 for (unsigned i = 0, e = V.size(); i != e; ++i)
1207 StructEls.push_back(V[i]->getType());
Andrew Lenharth38ecbf12006-12-08 18:06:16 +00001208 return get(StructType::get(StructEls, packed), V);
Chris Lattnerb370c7a2004-07-12 20:35:11 +00001209}
1210
Chris Lattnerf5ec48d2001-10-13 06:57:33 +00001211// destroyConstant - Remove the constant from the constant table...
Chris Lattner6a57baa2001-10-03 15:39:36 +00001212//
Chris Lattnere9bb2df2001-12-03 22:26:30 +00001213void ConstantStruct::destroyConstant() {
Chris Lattner8a94bf12006-09-28 00:35:06 +00001214 StructConstants->remove(this);
Chris Lattnerf5ec48d2001-10-13 06:57:33 +00001215 destroyConstantImpl();
1216}
Chris Lattner6a57baa2001-10-03 15:39:36 +00001217
Reid Spencer9d6565a2007-02-15 02:26:10 +00001218//---- ConstantVector::get() implementation...
Brian Gaeke715c90b2004-08-20 06:00:58 +00001219//
1220namespace llvm {
1221 template<>
Reid Spencer9d6565a2007-02-15 02:26:10 +00001222 struct ConvertConstantType<ConstantVector, VectorType> {
1223 static void convert(ConstantVector *OldC, const VectorType *NewTy) {
Brian Gaeke715c90b2004-08-20 06:00:58 +00001224 // Make everyone now use a constant of the new type...
1225 std::vector<Constant*> C;
1226 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1227 C.push_back(cast<Constant>(OldC->getOperand(i)));
Reid Spencer9d6565a2007-02-15 02:26:10 +00001228 Constant *New = ConstantVector::get(NewTy, C);
Brian Gaeke715c90b2004-08-20 06:00:58 +00001229 assert(New != OldC && "Didn't replace constant??");
1230 OldC->uncheckedReplaceAllUsesWith(New);
1231 OldC->destroyConstant(); // This constant is now dead, destroy it.
1232 }
1233 };
1234}
1235
Reid Spencer9d6565a2007-02-15 02:26:10 +00001236static std::vector<Constant*> getValType(ConstantVector *CP) {
Brian Gaeke715c90b2004-08-20 06:00:58 +00001237 std::vector<Constant*> Elements;
1238 Elements.reserve(CP->getNumOperands());
1239 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1240 Elements.push_back(CP->getOperand(i));
1241 return Elements;
1242}
1243
Reid Spencer9d6565a2007-02-15 02:26:10 +00001244static ManagedStatic<ValueMap<std::vector<Constant*>, VectorType,
Reid Spencerac9dcb92007-02-15 03:39:18 +00001245 ConstantVector> > VectorConstants;
Brian Gaeke715c90b2004-08-20 06:00:58 +00001246
Reid Spencer9d6565a2007-02-15 02:26:10 +00001247Constant *ConstantVector::get(const VectorType *Ty,
Brian Gaeke715c90b2004-08-20 06:00:58 +00001248 const std::vector<Constant*> &V) {
Dan Gohmanfa73ea22007-05-24 14:36:04 +00001249 // If this is an all-zero vector, return a ConstantAggregateZero object
Brian Gaeke715c90b2004-08-20 06:00:58 +00001250 if (!V.empty()) {
1251 Constant *C = V[0];
1252 if (!C->isNullValue())
Reid Spencerac9dcb92007-02-15 03:39:18 +00001253 return VectorConstants->getOrCreate(Ty, V);
Brian Gaeke715c90b2004-08-20 06:00:58 +00001254 for (unsigned i = 1, e = V.size(); i != e; ++i)
1255 if (V[i] != C)
Reid Spencerac9dcb92007-02-15 03:39:18 +00001256 return VectorConstants->getOrCreate(Ty, V);
Brian Gaeke715c90b2004-08-20 06:00:58 +00001257 }
1258 return ConstantAggregateZero::get(Ty);
1259}
1260
Reid Spencer9d6565a2007-02-15 02:26:10 +00001261Constant *ConstantVector::get(const std::vector<Constant*> &V) {
Brian Gaeke715c90b2004-08-20 06:00:58 +00001262 assert(!V.empty() && "Cannot infer type if V is empty");
Reid Spencer9d6565a2007-02-15 02:26:10 +00001263 return get(VectorType::get(V.front()->getType(),V.size()), V);
Brian Gaeke715c90b2004-08-20 06:00:58 +00001264}
1265
1266// destroyConstant - Remove the constant from the constant table...
1267//
Reid Spencer9d6565a2007-02-15 02:26:10 +00001268void ConstantVector::destroyConstant() {
Reid Spencerac9dcb92007-02-15 03:39:18 +00001269 VectorConstants->remove(this);
Brian Gaeke715c90b2004-08-20 06:00:58 +00001270 destroyConstantImpl();
1271}
1272
Dan Gohmanfa73ea22007-05-24 14:36:04 +00001273/// This function will return true iff every element in this vector constant
Jim Laskeyfa301822007-01-12 22:39:14 +00001274/// is set to all ones.
1275/// @returns true iff this constant's emements are all set to all ones.
1276/// @brief Determine if the value is all ones.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001277bool ConstantVector::isAllOnesValue() const {
Jim Laskeyfa301822007-01-12 22:39:14 +00001278 // Check out first element.
1279 const Constant *Elt = getOperand(0);
1280 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1281 if (!CI || !CI->isAllOnesValue()) return false;
1282 // Then make sure all remaining elements point to the same value.
1283 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1284 if (getOperand(I) != Elt) return false;
1285 }
1286 return true;
1287}
1288
Dan Gohman3b7cf0a2007-10-17 17:51:30 +00001289/// getSplatValue - If this is a splat constant, where all of the
1290/// elements have the same value, return that value. Otherwise return null.
1291Constant *ConstantVector::getSplatValue() {
1292 // Check out first element.
1293 Constant *Elt = getOperand(0);
1294 // Then make sure all remaining elements point to the same value.
1295 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1296 if (getOperand(I) != Elt) return 0;
1297 return Elt;
1298}
1299
Chris Lattnere9bb2df2001-12-03 22:26:30 +00001300//---- ConstantPointerNull::get() implementation...
Chris Lattnerf5ec48d2001-10-13 06:57:33 +00001301//
Chris Lattner02ec5ed2003-05-23 20:03:32 +00001302
Chris Lattner31f84992003-11-21 20:23:48 +00001303namespace llvm {
1304 // ConstantPointerNull does not take extra "value" argument...
1305 template<class ValType>
1306 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1307 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1308 return new ConstantPointerNull(Ty);
1309 }
1310 };
Chris Lattner02ec5ed2003-05-23 20:03:32 +00001311
Chris Lattner31f84992003-11-21 20:23:48 +00001312 template<>
1313 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1314 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1315 // Make everyone now use a constant of the new type...
1316 Constant *New = ConstantPointerNull::get(NewTy);
1317 assert(New != OldC && "Didn't replace constant??");
1318 OldC->uncheckedReplaceAllUsesWith(New);
1319 OldC->destroyConstant(); // This constant is now dead, destroy it.
1320 }
1321 };
1322}
Chris Lattnered468e372003-10-05 00:17:43 +00001323
Chris Lattner8a94bf12006-09-28 00:35:06 +00001324static ManagedStatic<ValueMap<char, PointerType,
1325 ConstantPointerNull> > NullPtrConstants;
Chris Lattnerf5ec48d2001-10-13 06:57:33 +00001326
Chris Lattner6823c9f2004-08-04 04:48:01 +00001327static char getValType(ConstantPointerNull *) {
1328 return 0;
1329}
1330
1331
Chris Lattnere9bb2df2001-12-03 22:26:30 +00001332ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
Chris Lattner8a94bf12006-09-28 00:35:06 +00001333 return NullPtrConstants->getOrCreate(Ty, 0);
Chris Lattner6a57baa2001-10-03 15:39:36 +00001334}
1335
Chris Lattner41661fd2002-08-18 00:40:04 +00001336// destroyConstant - Remove the constant from the constant table...
1337//
1338void ConstantPointerNull::destroyConstant() {
Chris Lattner8a94bf12006-09-28 00:35:06 +00001339 NullPtrConstants->remove(this);
Chris Lattner41661fd2002-08-18 00:40:04 +00001340 destroyConstantImpl();
1341}
1342
1343
Chris Lattnerb9f18592004-10-16 18:07:16 +00001344//---- UndefValue::get() implementation...
1345//
1346
1347namespace llvm {
1348 // UndefValue does not take extra "value" argument...
1349 template<class ValType>
1350 struct ConstantCreator<UndefValue, Type, ValType> {
1351 static UndefValue *create(const Type *Ty, const ValType &V) {
1352 return new UndefValue(Ty);
1353 }
1354 };
1355
1356 template<>
1357 struct ConvertConstantType<UndefValue, Type> {
1358 static void convert(UndefValue *OldC, const Type *NewTy) {
1359 // Make everyone now use a constant of the new type.
1360 Constant *New = UndefValue::get(NewTy);
1361 assert(New != OldC && "Didn't replace constant??");
1362 OldC->uncheckedReplaceAllUsesWith(New);
1363 OldC->destroyConstant(); // This constant is now dead, destroy it.
1364 }
1365 };
1366}
1367
Chris Lattner8a94bf12006-09-28 00:35:06 +00001368static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
Chris Lattnerb9f18592004-10-16 18:07:16 +00001369
1370static char getValType(UndefValue *) {
1371 return 0;
1372}
1373
1374
1375UndefValue *UndefValue::get(const Type *Ty) {
Chris Lattner8a94bf12006-09-28 00:35:06 +00001376 return UndefValueConstants->getOrCreate(Ty, 0);
Chris Lattnerb9f18592004-10-16 18:07:16 +00001377}
1378
1379// destroyConstant - Remove the constant from the constant table.
1380//
1381void UndefValue::destroyConstant() {
Chris Lattner8a94bf12006-09-28 00:35:06 +00001382 UndefValueConstants->remove(this);
Chris Lattnerb9f18592004-10-16 18:07:16 +00001383 destroyConstantImpl();
1384}
1385
1386
Vikram S. Adve345e0cf2002-07-14 23:13:17 +00001387//---- ConstantExpr::get() implementations...
Vikram S. Adve345e0cf2002-07-14 23:13:17 +00001388//
Reid Spencer79e21d32006-12-31 05:26:44 +00001389
Reid Spencer077d0eb2006-12-04 05:19:50 +00001390struct ExprMapKeyType {
1391 explicit ExprMapKeyType(unsigned opc, std::vector<Constant*> ops,
Reid Spencer8d5a6ae2006-12-04 18:38:05 +00001392 unsigned short pred = 0) : opcode(opc), predicate(pred), operands(ops) { }
1393 uint16_t opcode;
1394 uint16_t predicate;
Reid Spencer077d0eb2006-12-04 05:19:50 +00001395 std::vector<Constant*> operands;
Reid Spencer077d0eb2006-12-04 05:19:50 +00001396 bool operator==(const ExprMapKeyType& that) const {
1397 return this->opcode == that.opcode &&
1398 this->predicate == that.predicate &&
1399 this->operands == that.operands;
1400 }
1401 bool operator<(const ExprMapKeyType & that) const {
1402 return this->opcode < that.opcode ||
1403 (this->opcode == that.opcode && this->predicate < that.predicate) ||
1404 (this->opcode == that.opcode && this->predicate == that.predicate &&
1405 this->operands < that.operands);
1406 }
1407
1408 bool operator!=(const ExprMapKeyType& that) const {
1409 return !(*this == that);
1410 }
1411};
Chris Lattner02ec5ed2003-05-23 20:03:32 +00001412
Chris Lattner31f84992003-11-21 20:23:48 +00001413namespace llvm {
1414 template<>
1415 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
Reid Spencer728b6db2006-12-03 05:48:19 +00001416 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1417 unsigned short pred = 0) {
Reid Spencer077d0eb2006-12-04 05:19:50 +00001418 if (Instruction::isCast(V.opcode))
1419 return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1420 if ((V.opcode >= Instruction::BinaryOpsBegin &&
Reid Spencer832254e2007-02-02 02:16:23 +00001421 V.opcode < Instruction::BinaryOpsEnd))
Reid Spencer077d0eb2006-12-04 05:19:50 +00001422 return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1423 if (V.opcode == Instruction::Select)
1424 return new SelectConstantExpr(V.operands[0], V.operands[1],
1425 V.operands[2]);
1426 if (V.opcode == Instruction::ExtractElement)
1427 return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1428 if (V.opcode == Instruction::InsertElement)
1429 return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1430 V.operands[2]);
1431 if (V.opcode == Instruction::ShuffleVector)
1432 return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1433 V.operands[2]);
1434 if (V.opcode == Instruction::GetElementPtr) {
1435 std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
1436 return new GetElementPtrConstantExpr(V.operands[0], IdxList, Ty);
1437 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001438
Reid Spencer077d0eb2006-12-04 05:19:50 +00001439 // The compare instructions are weird. We have to encode the predicate
1440 // value and it is combined with the instruction opcode by multiplying
1441 // the opcode by one hundred. We must decode this to get the predicate.
1442 if (V.opcode == Instruction::ICmp)
1443 return new CompareConstantExpr(Instruction::ICmp, V.predicate,
1444 V.operands[0], V.operands[1]);
1445 if (V.opcode == Instruction::FCmp)
1446 return new CompareConstantExpr(Instruction::FCmp, V.predicate,
1447 V.operands[0], V.operands[1]);
1448 assert(0 && "Invalid ConstantExpr!");
Jeff Cohen6ebe2352006-12-15 21:47:01 +00001449 return 0;
Chris Lattnered468e372003-10-05 00:17:43 +00001450 }
Chris Lattner31f84992003-11-21 20:23:48 +00001451 };
Chris Lattnered468e372003-10-05 00:17:43 +00001452
Chris Lattner31f84992003-11-21 20:23:48 +00001453 template<>
1454 struct ConvertConstantType<ConstantExpr, Type> {
1455 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1456 Constant *New;
1457 switch (OldC->getOpcode()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001458 case Instruction::Trunc:
1459 case Instruction::ZExt:
1460 case Instruction::SExt:
1461 case Instruction::FPTrunc:
1462 case Instruction::FPExt:
1463 case Instruction::UIToFP:
1464 case Instruction::SIToFP:
1465 case Instruction::FPToUI:
1466 case Instruction::FPToSI:
1467 case Instruction::PtrToInt:
1468 case Instruction::IntToPtr:
1469 case Instruction::BitCast:
Reid Spencerd977d862006-12-12 23:36:14 +00001470 New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0),
1471 NewTy);
Chris Lattner31f84992003-11-21 20:23:48 +00001472 break;
Chris Lattner08a45cc2004-03-12 05:54:04 +00001473 case Instruction::Select:
1474 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1475 OldC->getOperand(1),
1476 OldC->getOperand(2));
1477 break;
Chris Lattner31f84992003-11-21 20:23:48 +00001478 default:
1479 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
Reid Spencer0a783f72006-11-02 01:53:59 +00001480 OldC->getOpcode() < Instruction::BinaryOpsEnd);
Chris Lattner31f84992003-11-21 20:23:48 +00001481 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1482 OldC->getOperand(1));
1483 break;
1484 case Instruction::GetElementPtr:
Misha Brukmanfd939082005-04-21 23:48:37 +00001485 // Make everyone now use a constant of the new type...
Chris Lattner7fa6e662004-10-11 22:52:25 +00001486 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
Chris Lattner2b9a5da2007-01-31 04:40:28 +00001487 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0),
1488 &Idx[0], Idx.size());
Chris Lattner31f84992003-11-21 20:23:48 +00001489 break;
1490 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001491
Chris Lattner31f84992003-11-21 20:23:48 +00001492 assert(New != OldC && "Didn't replace constant??");
1493 OldC->uncheckedReplaceAllUsesWith(New);
1494 OldC->destroyConstant(); // This constant is now dead, destroy it.
1495 }
1496 };
1497} // end namespace llvm
Chris Lattnered468e372003-10-05 00:17:43 +00001498
1499
Chris Lattner6823c9f2004-08-04 04:48:01 +00001500static ExprMapKeyType getValType(ConstantExpr *CE) {
1501 std::vector<Constant*> Operands;
1502 Operands.reserve(CE->getNumOperands());
1503 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1504 Operands.push_back(cast<Constant>(CE->getOperand(i)));
Reid Spencer077d0eb2006-12-04 05:19:50 +00001505 return ExprMapKeyType(CE->getOpcode(), Operands,
1506 CE->isCompare() ? CE->getPredicate() : 0);
Chris Lattner6823c9f2004-08-04 04:48:01 +00001507}
1508
Chris Lattner8a94bf12006-09-28 00:35:06 +00001509static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1510 ConstantExpr> > ExprConstants;
Vikram S. Adved0b1bb02002-07-15 18:19:33 +00001511
Reid Spencer3da59db2006-11-27 01:05:10 +00001512/// This is a utility function to handle folding of casts and lookup of the
1513/// cast in the ExprConstants map. It is usedby the various get* methods below.
1514static inline Constant *getFoldedCast(
1515 Instruction::CastOps opc, Constant *C, const Type *Ty) {
Chris Lattner9eacf8a2003-10-07 22:19:19 +00001516 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
Reid Spencer3da59db2006-11-27 01:05:10 +00001517 // Fold a few common cases
1518 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1519 return FC;
Chris Lattnerd628f6a2003-04-17 19:24:48 +00001520
Vikram S. Adved0b1bb02002-07-15 18:19:33 +00001521 // Look up the constant in the table first to ensure uniqueness
Chris Lattner9bc02a42003-05-13 21:37:02 +00001522 std::vector<Constant*> argVec(1, C);
Reid Spencer077d0eb2006-12-04 05:19:50 +00001523 ExprMapKeyType Key(opc, argVec);
Chris Lattner8a94bf12006-09-28 00:35:06 +00001524 return ExprConstants->getOrCreate(Ty, Key);
Vikram S. Adve345e0cf2002-07-14 23:13:17 +00001525}
Reid Spencer7858b332006-12-05 19:14:13 +00001526
Reid Spencer3da59db2006-11-27 01:05:10 +00001527Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1528 Instruction::CastOps opc = Instruction::CastOps(oc);
1529 assert(Instruction::isCast(opc) && "opcode out of range");
1530 assert(C && Ty && "Null arguments to getCast");
1531 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1532
1533 switch (opc) {
1534 default:
1535 assert(0 && "Invalid cast opcode");
1536 break;
1537 case Instruction::Trunc: return getTrunc(C, Ty);
Reid Spencerd977d862006-12-12 23:36:14 +00001538 case Instruction::ZExt: return getZExt(C, Ty);
1539 case Instruction::SExt: return getSExt(C, Ty);
Reid Spencer3da59db2006-11-27 01:05:10 +00001540 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1541 case Instruction::FPExt: return getFPExtend(C, Ty);
1542 case Instruction::UIToFP: return getUIToFP(C, Ty);
1543 case Instruction::SIToFP: return getSIToFP(C, Ty);
1544 case Instruction::FPToUI: return getFPToUI(C, Ty);
1545 case Instruction::FPToSI: return getFPToSI(C, Ty);
1546 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1547 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1548 case Instruction::BitCast: return getBitCast(C, Ty);
Chris Lattnerf5ac6c22005-01-01 15:59:57 +00001549 }
Reid Spencer3da59db2006-11-27 01:05:10 +00001550 return 0;
Reid Spencer7858b332006-12-05 19:14:13 +00001551}
1552
Reid Spencer848414e2006-12-04 20:17:56 +00001553Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1554 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1555 return getCast(Instruction::BitCast, C, Ty);
1556 return getCast(Instruction::ZExt, C, Ty);
1557}
1558
1559Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1560 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1561 return getCast(Instruction::BitCast, C, Ty);
1562 return getCast(Instruction::SExt, C, Ty);
1563}
1564
1565Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1566 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1567 return getCast(Instruction::BitCast, C, Ty);
1568 return getCast(Instruction::Trunc, C, Ty);
1569}
1570
Reid Spencerc0459fb2006-12-05 03:25:26 +00001571Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1572 assert(isa<PointerType>(S->getType()) && "Invalid cast");
Chris Lattner42a75512007-01-15 02:27:26 +00001573 assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
Reid Spencerc0459fb2006-12-05 03:25:26 +00001574
Chris Lattner42a75512007-01-15 02:27:26 +00001575 if (Ty->isInteger())
Reid Spencerc0459fb2006-12-05 03:25:26 +00001576 return getCast(Instruction::PtrToInt, S, Ty);
1577 return getCast(Instruction::BitCast, S, Ty);
1578}
1579
Reid Spencer84f3eab2006-12-12 00:51:07 +00001580Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
1581 bool isSigned) {
Chris Lattner42a75512007-01-15 02:27:26 +00001582 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
Reid Spencer84f3eab2006-12-12 00:51:07 +00001583 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1584 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1585 Instruction::CastOps opcode =
1586 (SrcBits == DstBits ? Instruction::BitCast :
1587 (SrcBits > DstBits ? Instruction::Trunc :
1588 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1589 return getCast(opcode, C, Ty);
1590}
1591
1592Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1593 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1594 "Invalid cast");
1595 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1596 unsigned DstBits = Ty->getPrimitiveSizeInBits();
Reid Spencerf25212a2006-12-12 05:38:50 +00001597 if (SrcBits == DstBits)
1598 return C; // Avoid a useless cast
Reid Spencer84f3eab2006-12-12 00:51:07 +00001599 Instruction::CastOps opcode =
Reid Spencerf25212a2006-12-12 05:38:50 +00001600 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
Reid Spencer84f3eab2006-12-12 00:51:07 +00001601 return getCast(opcode, C, Ty);
1602}
1603
Reid Spencer3da59db2006-11-27 01:05:10 +00001604Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
Chris Lattner42a75512007-01-15 02:27:26 +00001605 assert(C->getType()->isInteger() && "Trunc operand must be integer");
1606 assert(Ty->isInteger() && "Trunc produces only integral");
Reid Spencer3da59db2006-11-27 01:05:10 +00001607 assert(C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1608 "SrcTy must be larger than DestTy for Trunc!");
1609
1610 return getFoldedCast(Instruction::Trunc, C, Ty);
1611}
1612
Reid Spencerd977d862006-12-12 23:36:14 +00001613Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
Chris Lattner42a75512007-01-15 02:27:26 +00001614 assert(C->getType()->isInteger() && "SEXt operand must be integral");
1615 assert(Ty->isInteger() && "SExt produces only integer");
Reid Spencer3da59db2006-11-27 01:05:10 +00001616 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1617 "SrcTy must be smaller than DestTy for SExt!");
1618
1619 return getFoldedCast(Instruction::SExt, C, Ty);
Chris Lattnerd144f422004-04-04 23:20:30 +00001620}
1621
Reid Spencerd977d862006-12-12 23:36:14 +00001622Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
Chris Lattner42a75512007-01-15 02:27:26 +00001623 assert(C->getType()->isInteger() && "ZEXt operand must be integral");
1624 assert(Ty->isInteger() && "ZExt produces only integer");
Reid Spencer3da59db2006-11-27 01:05:10 +00001625 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1626 "SrcTy must be smaller than DestTy for ZExt!");
1627
1628 return getFoldedCast(Instruction::ZExt, C, Ty);
1629}
1630
1631Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1632 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1633 C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1634 "This is an illegal floating point truncation!");
1635 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1636}
1637
1638Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1639 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1640 C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1641 "This is an illegal floating point extension!");
1642 return getFoldedCast(Instruction::FPExt, C, Ty);
1643}
1644
1645Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
Nate Begemanb348d182007-11-17 03:58:34 +00001646 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1647 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1648 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1649 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1650 "This is an illegal uint to floating point cast!");
Reid Spencer3da59db2006-11-27 01:05:10 +00001651 return getFoldedCast(Instruction::UIToFP, C, Ty);
1652}
1653
1654Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
Nate Begemanb348d182007-11-17 03:58:34 +00001655 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1656 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1657 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1658 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
Reid Spencer3da59db2006-11-27 01:05:10 +00001659 "This is an illegal sint to floating point cast!");
1660 return getFoldedCast(Instruction::SIToFP, C, Ty);
1661}
1662
1663Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
Nate Begemanb348d182007-11-17 03:58:34 +00001664 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1665 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1666 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1667 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1668 "This is an illegal floating point to uint cast!");
Reid Spencer3da59db2006-11-27 01:05:10 +00001669 return getFoldedCast(Instruction::FPToUI, C, Ty);
1670}
1671
1672Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
Nate Begemanb348d182007-11-17 03:58:34 +00001673 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1674 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1675 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1676 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1677 "This is an illegal floating point to sint cast!");
Reid Spencer3da59db2006-11-27 01:05:10 +00001678 return getFoldedCast(Instruction::FPToSI, C, Ty);
1679}
1680
1681Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1682 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
Chris Lattner42a75512007-01-15 02:27:26 +00001683 assert(DstTy->isInteger() && "PtrToInt destination must be integral");
Reid Spencer3da59db2006-11-27 01:05:10 +00001684 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1685}
1686
1687Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
Chris Lattner42a75512007-01-15 02:27:26 +00001688 assert(C->getType()->isInteger() && "IntToPtr source must be integral");
Reid Spencer3da59db2006-11-27 01:05:10 +00001689 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
1690 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1691}
1692
1693Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1694 // BitCast implies a no-op cast of type only. No bits change. However, you
1695 // can't cast pointers to anything but pointers.
1696 const Type *SrcTy = C->getType();
1697 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
Reid Spencer848414e2006-12-04 20:17:56 +00001698 "BitCast cannot cast pointer to non-pointer and vice versa");
Reid Spencer3da59db2006-11-27 01:05:10 +00001699
1700 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
1701 // or nonptr->ptr). For all the other types, the cast is okay if source and
1702 // destination bit widths are identical.
1703 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1704 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
Reid Spencer848414e2006-12-04 20:17:56 +00001705 assert(SrcBitSize == DstBitSize && "BitCast requies types of same width");
Reid Spencer3da59db2006-11-27 01:05:10 +00001706 return getFoldedCast(Instruction::BitCast, C, DstTy);
Chris Lattnerd144f422004-04-04 23:20:30 +00001707}
1708
Alkis Evlogimenos60ab1402004-10-24 01:41:10 +00001709Constant *ConstantExpr::getSizeOf(const Type *Ty) {
Gordon Henriksen46475692007-10-06 14:29:36 +00001710 // sizeof is implemented as: (i64) gep (Ty*)null, 1
Chris Lattnerf9021ff2007-02-19 20:01:23 +00001711 Constant *GEPIdx = ConstantInt::get(Type::Int32Ty, 1);
1712 Constant *GEP =
Christopher Lamb43ad6b32007-12-17 01:12:55 +00001713 getGetElementPtr(getNullValue(PointerType::getUnqual(Ty)), &GEPIdx, 1);
Chris Lattnerf9021ff2007-02-19 20:01:23 +00001714 return getCast(Instruction::PtrToInt, GEP, Type::Int64Ty);
Alkis Evlogimenos1cecd3a2005-03-19 11:40:31 +00001715}
1716
Chris Lattnered468e372003-10-05 00:17:43 +00001717Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
Reid Spencer67263fe2006-12-04 21:35:24 +00001718 Constant *C1, Constant *C2) {
Chris Lattnerf31f5832003-05-21 17:49:25 +00001719 // Check the operands for consistency first
Reid Spencer0a783f72006-11-02 01:53:59 +00001720 assert(Opcode >= Instruction::BinaryOpsBegin &&
1721 Opcode < Instruction::BinaryOpsEnd &&
Chris Lattnerf31f5832003-05-21 17:49:25 +00001722 "Invalid opcode in binary constant expression");
1723 assert(C1->getType() == C2->getType() &&
1724 "Operand types in binary constant expression should match");
Chris Lattnered468e372003-10-05 00:17:43 +00001725
Reid Spencer4fe16d62007-01-11 18:21:29 +00001726 if (ReqTy == C1->getType() || ReqTy == Type::Int1Ty)
Chris Lattnered468e372003-10-05 00:17:43 +00001727 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1728 return FC; // Fold a few common cases...
Chris Lattnerd628f6a2003-04-17 19:24:48 +00001729
Chris Lattner9bc02a42003-05-13 21:37:02 +00001730 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
Reid Spencer67263fe2006-12-04 21:35:24 +00001731 ExprMapKeyType Key(Opcode, argVec);
Chris Lattner8a94bf12006-09-28 00:35:06 +00001732 return ExprConstants->getOrCreate(ReqTy, Key);
Vikram S. Adve345e0cf2002-07-14 23:13:17 +00001733}
1734
Reid Spencere4d87aa2006-12-23 06:05:41 +00001735Constant *ConstantExpr::getCompareTy(unsigned short predicate,
Reid Spencer67263fe2006-12-04 21:35:24 +00001736 Constant *C1, Constant *C2) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001737 switch (predicate) {
1738 default: assert(0 && "Invalid CmpInst predicate");
1739 case FCmpInst::FCMP_FALSE: case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_OGT:
1740 case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OLE:
1741 case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_ORD: case FCmpInst::FCMP_UNO:
1742 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UGT: case FCmpInst::FCMP_UGE:
1743 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_ULE: case FCmpInst::FCMP_UNE:
1744 case FCmpInst::FCMP_TRUE:
1745 return getFCmp(predicate, C1, C2);
1746 case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGT:
1747 case ICmpInst::ICMP_UGE: case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE:
1748 case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_SGE: case ICmpInst::ICMP_SLT:
1749 case ICmpInst::ICMP_SLE:
1750 return getICmp(predicate, C1, C2);
1751 }
Reid Spencer67263fe2006-12-04 21:35:24 +00001752}
1753
1754Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
Chris Lattner91b362b2004-08-17 17:28:46 +00001755#ifndef NDEBUG
1756 switch (Opcode) {
Reid Spencer0a783f72006-11-02 01:53:59 +00001757 case Instruction::Add:
1758 case Instruction::Sub:
Reid Spencer1628cec2006-10-26 06:15:43 +00001759 case Instruction::Mul:
Chris Lattner91b362b2004-08-17 17:28:46 +00001760 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Chris Lattner42a75512007-01-15 02:27:26 +00001761 assert((C1->getType()->isInteger() || C1->getType()->isFloatingPoint() ||
Reid Spencer9d6565a2007-02-15 02:26:10 +00001762 isa<VectorType>(C1->getType())) &&
Chris Lattner91b362b2004-08-17 17:28:46 +00001763 "Tried to create an arithmetic operation on a non-arithmetic type!");
1764 break;
Reid Spencer1628cec2006-10-26 06:15:43 +00001765 case Instruction::UDiv:
1766 case Instruction::SDiv:
1767 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencer9d6565a2007-02-15 02:26:10 +00001768 assert((C1->getType()->isInteger() || (isa<VectorType>(C1->getType()) &&
1769 cast<VectorType>(C1->getType())->getElementType()->isInteger())) &&
Reid Spencer1628cec2006-10-26 06:15:43 +00001770 "Tried to create an arithmetic operation on a non-arithmetic type!");
1771 break;
1772 case Instruction::FDiv:
1773 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencer9d6565a2007-02-15 02:26:10 +00001774 assert((C1->getType()->isFloatingPoint() || (isa<VectorType>(C1->getType())
1775 && cast<VectorType>(C1->getType())->getElementType()->isFloatingPoint()))
Reid Spencer1628cec2006-10-26 06:15:43 +00001776 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1777 break;
Reid Spencer0a783f72006-11-02 01:53:59 +00001778 case Instruction::URem:
1779 case Instruction::SRem:
1780 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencer9d6565a2007-02-15 02:26:10 +00001781 assert((C1->getType()->isInteger() || (isa<VectorType>(C1->getType()) &&
1782 cast<VectorType>(C1->getType())->getElementType()->isInteger())) &&
Reid Spencer0a783f72006-11-02 01:53:59 +00001783 "Tried to create an arithmetic operation on a non-arithmetic type!");
1784 break;
1785 case Instruction::FRem:
1786 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencer9d6565a2007-02-15 02:26:10 +00001787 assert((C1->getType()->isFloatingPoint() || (isa<VectorType>(C1->getType())
1788 && cast<VectorType>(C1->getType())->getElementType()->isFloatingPoint()))
Reid Spencer0a783f72006-11-02 01:53:59 +00001789 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1790 break;
Chris Lattner91b362b2004-08-17 17:28:46 +00001791 case Instruction::And:
1792 case Instruction::Or:
1793 case Instruction::Xor:
1794 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencer9d6565a2007-02-15 02:26:10 +00001795 assert((C1->getType()->isInteger() || isa<VectorType>(C1->getType())) &&
Misha Brukman1bae2912005-01-27 06:46:38 +00001796 "Tried to create a logical operation on a non-integral type!");
Chris Lattner91b362b2004-08-17 17:28:46 +00001797 break;
Chris Lattner91b362b2004-08-17 17:28:46 +00001798 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00001799 case Instruction::LShr:
1800 case Instruction::AShr:
Reid Spencer832254e2007-02-02 02:16:23 +00001801 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Chris Lattner42a75512007-01-15 02:27:26 +00001802 assert(C1->getType()->isInteger() &&
Chris Lattner91b362b2004-08-17 17:28:46 +00001803 "Tried to create a shift operation on a non-integer type!");
1804 break;
1805 default:
1806 break;
1807 }
1808#endif
1809
Reid Spencer67263fe2006-12-04 21:35:24 +00001810 return getTy(C1->getType(), Opcode, C1, C2);
1811}
1812
Reid Spencere4d87aa2006-12-23 06:05:41 +00001813Constant *ConstantExpr::getCompare(unsigned short pred,
Reid Spencer67263fe2006-12-04 21:35:24 +00001814 Constant *C1, Constant *C2) {
1815 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00001816 return getCompareTy(pred, C1, C2);
Chris Lattnerc3d12f02004-08-04 18:50:09 +00001817}
1818
Chris Lattner08a45cc2004-03-12 05:54:04 +00001819Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1820 Constant *V1, Constant *V2) {
Reid Spencer3d10b0b2007-01-26 07:37:34 +00001821 assert(C->getType() == Type::Int1Ty && "Select condition must be i1!");
Chris Lattner08a45cc2004-03-12 05:54:04 +00001822 assert(V1->getType() == V2->getType() && "Select value types must match!");
1823 assert(V1->getType()->isFirstClassType() && "Cannot select aggregate type!");
1824
1825 if (ReqTy == V1->getType())
1826 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1827 return SC; // Fold common cases
1828
1829 std::vector<Constant*> argVec(3, C);
1830 argVec[1] = V1;
1831 argVec[2] = V2;
Reid Spencer077d0eb2006-12-04 05:19:50 +00001832 ExprMapKeyType Key(Instruction::Select, argVec);
Chris Lattner8a94bf12006-09-28 00:35:06 +00001833 return ExprConstants->getOrCreate(ReqTy, Key);
Chris Lattner08a45cc2004-03-12 05:54:04 +00001834}
1835
Chris Lattnered468e372003-10-05 00:17:43 +00001836Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
Chris Lattner2b9a5da2007-01-31 04:40:28 +00001837 Value* const *Idxs,
1838 unsigned NumIdx) {
David Greeneb8f74792007-09-04 15:46:09 +00001839 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx, true) &&
Chris Lattner2e9bb1a2004-02-16 20:46:13 +00001840 "GEP indices invalid!");
1841
Chris Lattner2b9a5da2007-01-31 04:40:28 +00001842 if (Constant *FC = ConstantFoldGetElementPtr(C, (Constant**)Idxs, NumIdx))
Chris Lattnerd628f6a2003-04-17 19:24:48 +00001843 return FC; // Fold a few common cases...
Chris Lattner2e9bb1a2004-02-16 20:46:13 +00001844
Chris Lattnered468e372003-10-05 00:17:43 +00001845 assert(isa<PointerType>(C->getType()) &&
Chris Lattner02ec5ed2003-05-23 20:03:32 +00001846 "Non-pointer type for constant GetElementPtr expression");
Vikram S. Adved0b1bb02002-07-15 18:19:33 +00001847 // Look up the constant in the table first to ensure uniqueness
Chris Lattner7fa6e662004-10-11 22:52:25 +00001848 std::vector<Constant*> ArgVec;
Chris Lattner2b9a5da2007-01-31 04:40:28 +00001849 ArgVec.reserve(NumIdx+1);
Chris Lattner7fa6e662004-10-11 22:52:25 +00001850 ArgVec.push_back(C);
Chris Lattner2b9a5da2007-01-31 04:40:28 +00001851 for (unsigned i = 0; i != NumIdx; ++i)
1852 ArgVec.push_back(cast<Constant>(Idxs[i]));
1853 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
Chris Lattner8a94bf12006-09-28 00:35:06 +00001854 return ExprConstants->getOrCreate(ReqTy, Key);
Vikram S. Adved0b1bb02002-07-15 18:19:33 +00001855}
1856
Chris Lattner2b9a5da2007-01-31 04:40:28 +00001857Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
1858 unsigned NumIdx) {
Chris Lattnered468e372003-10-05 00:17:43 +00001859 // Get the result type of the getelementptr!
Chris Lattner2b9a5da2007-01-31 04:40:28 +00001860 const Type *Ty =
David Greeneb8f74792007-09-04 15:46:09 +00001861 GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx, true);
Chris Lattnered468e372003-10-05 00:17:43 +00001862 assert(Ty && "GEP indices invalid!");
Christopher Lambfe63fb92007-12-11 08:59:05 +00001863 unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
1864 return getGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx);
Chris Lattner7fa6e662004-10-11 22:52:25 +00001865}
1866
Chris Lattner2b9a5da2007-01-31 04:40:28 +00001867Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
1868 unsigned NumIdx) {
1869 return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
Chris Lattnered468e372003-10-05 00:17:43 +00001870}
1871
Chris Lattner2b9a5da2007-01-31 04:40:28 +00001872
Reid Spencer077d0eb2006-12-04 05:19:50 +00001873Constant *
1874ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1875 assert(LHS->getType() == RHS->getType());
1876 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
1877 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1878
Reid Spencere4d87aa2006-12-23 06:05:41 +00001879 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
Reid Spencer077d0eb2006-12-04 05:19:50 +00001880 return FC; // Fold a few common cases...
1881
1882 // Look up the constant in the table first to ensure uniqueness
1883 std::vector<Constant*> ArgVec;
1884 ArgVec.push_back(LHS);
1885 ArgVec.push_back(RHS);
Reid Spencer4fa021a2006-12-24 18:42:29 +00001886 // Get the key type with both the opcode and predicate
Reid Spencer077d0eb2006-12-04 05:19:50 +00001887 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
Reid Spencer4fe16d62007-01-11 18:21:29 +00001888 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
Reid Spencer077d0eb2006-12-04 05:19:50 +00001889}
1890
1891Constant *
1892ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1893 assert(LHS->getType() == RHS->getType());
1894 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1895
Reid Spencere4d87aa2006-12-23 06:05:41 +00001896 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
Reid Spencer077d0eb2006-12-04 05:19:50 +00001897 return FC; // Fold a few common cases...
1898
1899 // Look up the constant in the table first to ensure uniqueness
1900 std::vector<Constant*> ArgVec;
1901 ArgVec.push_back(LHS);
1902 ArgVec.push_back(RHS);
Reid Spencer4fa021a2006-12-24 18:42:29 +00001903 // Get the key type with both the opcode and predicate
Reid Spencer077d0eb2006-12-04 05:19:50 +00001904 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
Reid Spencer4fe16d62007-01-11 18:21:29 +00001905 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
Reid Spencer077d0eb2006-12-04 05:19:50 +00001906}
1907
Robert Bocchinob52ee7f2006-01-10 19:05:34 +00001908Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
1909 Constant *Idx) {
Robert Bocchinobb90a7a2006-01-10 20:03:46 +00001910 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
1911 return FC; // Fold a few common cases...
Robert Bocchinob52ee7f2006-01-10 19:05:34 +00001912 // Look up the constant in the table first to ensure uniqueness
1913 std::vector<Constant*> ArgVec(1, Val);
1914 ArgVec.push_back(Idx);
Reid Spencer077d0eb2006-12-04 05:19:50 +00001915 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
Chris Lattner8a94bf12006-09-28 00:35:06 +00001916 return ExprConstants->getOrCreate(ReqTy, Key);
Robert Bocchinob52ee7f2006-01-10 19:05:34 +00001917}
1918
1919Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001920 assert(isa<VectorType>(Val->getType()) &&
Reid Spencerac9dcb92007-02-15 03:39:18 +00001921 "Tried to create extractelement operation on non-vector type!");
Reid Spencer79e21d32006-12-31 05:26:44 +00001922 assert(Idx->getType() == Type::Int32Ty &&
Reid Spencer3d10b0b2007-01-26 07:37:34 +00001923 "Extractelement index must be i32 type!");
Reid Spencer9d6565a2007-02-15 02:26:10 +00001924 return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
Robert Bocchinob52ee7f2006-01-10 19:05:34 +00001925 Val, Idx);
1926}
Chris Lattnered468e372003-10-05 00:17:43 +00001927
Robert Bocchinoc152f9c2006-01-17 20:07:22 +00001928Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
1929 Constant *Elt, Constant *Idx) {
1930 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
1931 return FC; // Fold a few common cases...
1932 // Look up the constant in the table first to ensure uniqueness
1933 std::vector<Constant*> ArgVec(1, Val);
1934 ArgVec.push_back(Elt);
1935 ArgVec.push_back(Idx);
Reid Spencer077d0eb2006-12-04 05:19:50 +00001936 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
Chris Lattner8a94bf12006-09-28 00:35:06 +00001937 return ExprConstants->getOrCreate(ReqTy, Key);
Robert Bocchinoc152f9c2006-01-17 20:07:22 +00001938}
1939
1940Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1941 Constant *Idx) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001942 assert(isa<VectorType>(Val->getType()) &&
Reid Spencerac9dcb92007-02-15 03:39:18 +00001943 "Tried to create insertelement operation on non-vector type!");
Reid Spencer9d6565a2007-02-15 02:26:10 +00001944 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
Robert Bocchinoc152f9c2006-01-17 20:07:22 +00001945 && "Insertelement types must match!");
Reid Spencer79e21d32006-12-31 05:26:44 +00001946 assert(Idx->getType() == Type::Int32Ty &&
Reid Spencer3d10b0b2007-01-26 07:37:34 +00001947 "Insertelement index must be i32 type!");
Reid Spencer9d6565a2007-02-15 02:26:10 +00001948 return getInsertElementTy(cast<VectorType>(Val->getType())->getElementType(),
Robert Bocchinoc152f9c2006-01-17 20:07:22 +00001949 Val, Elt, Idx);
1950}
1951
Chris Lattner00f10232006-04-08 01:18:18 +00001952Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
1953 Constant *V2, Constant *Mask) {
1954 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
1955 return FC; // Fold a few common cases...
1956 // Look up the constant in the table first to ensure uniqueness
1957 std::vector<Constant*> ArgVec(1, V1);
1958 ArgVec.push_back(V2);
1959 ArgVec.push_back(Mask);
Reid Spencer077d0eb2006-12-04 05:19:50 +00001960 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
Chris Lattner8a94bf12006-09-28 00:35:06 +00001961 return ExprConstants->getOrCreate(ReqTy, Key);
Chris Lattner00f10232006-04-08 01:18:18 +00001962}
1963
1964Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
1965 Constant *Mask) {
1966 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1967 "Invalid shuffle vector constant expr operands!");
1968 return getShuffleVectorTy(V1->getType(), V1, V2, Mask);
1969}
1970
Reid Spencer24d6da52007-01-21 00:29:26 +00001971Constant *ConstantExpr::getZeroValueForNegationExpr(const Type *Ty) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001972 if (const VectorType *PTy = dyn_cast<VectorType>(Ty))
Reid Spencer2c7123c2007-01-21 02:29:10 +00001973 if (PTy->getElementType()->isFloatingPoint()) {
1974 std::vector<Constant*> zeros(PTy->getNumElements(),
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00001975 ConstantFP::getNegativeZero(PTy->getElementType()));
Reid Spencer9d6565a2007-02-15 02:26:10 +00001976 return ConstantVector::get(PTy, zeros);
Reid Spencer2c7123c2007-01-21 02:29:10 +00001977 }
Reid Spencer24d6da52007-01-21 00:29:26 +00001978
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00001979 if (Ty->isFloatingPoint())
1980 return ConstantFP::getNegativeZero(Ty);
Reid Spencer24d6da52007-01-21 00:29:26 +00001981
1982 return Constant::getNullValue(Ty);
1983}
1984
Vikram S. Adved0b1bb02002-07-15 18:19:33 +00001985// destroyConstant - Remove the constant from the constant table...
1986//
1987void ConstantExpr::destroyConstant() {
Chris Lattner8a94bf12006-09-28 00:35:06 +00001988 ExprConstants->remove(this);
Vikram S. Adved0b1bb02002-07-15 18:19:33 +00001989 destroyConstantImpl();
Vikram S. Adve345e0cf2002-07-14 23:13:17 +00001990}
1991
Chris Lattnerc188eeb2002-07-30 18:54:25 +00001992const char *ConstantExpr::getOpcodeName() const {
1993 return Instruction::getOpcodeName(getOpcode());
Vikram S. Adve345e0cf2002-07-14 23:13:17 +00001994}
Reid Spencer1c9c8e62004-07-17 23:48:33 +00001995
Chris Lattner5cbade92005-10-03 21:58:36 +00001996//===----------------------------------------------------------------------===//
1997// replaceUsesOfWithOnConstant implementations
1998
Chris Lattner54984052007-08-21 00:55:23 +00001999/// replaceUsesOfWithOnConstant - Update this constant array to change uses of
2000/// 'From' to be uses of 'To'. This must update the uniquing data structures
2001/// etc.
2002///
2003/// Note that we intentionally replace all uses of From with To here. Consider
2004/// a large array that uses 'From' 1000 times. By handling this case all here,
2005/// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
2006/// single invocation handles all 1000 uses. Handling them one at a time would
2007/// work, but would be really slow because it would have to unique each updated
2008/// array instance.
Chris Lattner5cbade92005-10-03 21:58:36 +00002009void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattnerd0ff1ad2005-10-04 18:13:04 +00002010 Use *U) {
Chris Lattner5cbade92005-10-03 21:58:36 +00002011 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
Chris Lattnerc182a882005-10-04 01:17:50 +00002012 Constant *ToC = cast<Constant>(To);
Chris Lattner23ec01f2005-10-04 18:47:09 +00002013
Jim Laskeyede5aa42006-07-17 17:38:29 +00002014 std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
Chris Lattnercea141f2005-10-03 22:51:37 +00002015 Lookup.first.first = getType();
2016 Lookup.second = this;
Chris Lattner23ec01f2005-10-04 18:47:09 +00002017
Chris Lattnercea141f2005-10-03 22:51:37 +00002018 std::vector<Constant*> &Values = Lookup.first.second;
2019 Values.reserve(getNumOperands()); // Build replacement array.
Chris Lattner23ec01f2005-10-04 18:47:09 +00002020
Chris Lattnerc182a882005-10-04 01:17:50 +00002021 // Fill values with the modified operands of the constant array. Also,
2022 // compute whether this turns into an all-zeros array.
Chris Lattner23ec01f2005-10-04 18:47:09 +00002023 bool isAllZeros = false;
Chris Lattner54984052007-08-21 00:55:23 +00002024 unsigned NumUpdated = 0;
Chris Lattner23ec01f2005-10-04 18:47:09 +00002025 if (!ToC->isNullValue()) {
Chris Lattner54984052007-08-21 00:55:23 +00002026 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2027 Constant *Val = cast<Constant>(O->get());
2028 if (Val == From) {
2029 Val = ToC;
2030 ++NumUpdated;
2031 }
2032 Values.push_back(Val);
2033 }
Chris Lattner23ec01f2005-10-04 18:47:09 +00002034 } else {
2035 isAllZeros = true;
2036 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2037 Constant *Val = cast<Constant>(O->get());
Chris Lattner54984052007-08-21 00:55:23 +00002038 if (Val == From) {
2039 Val = ToC;
2040 ++NumUpdated;
2041 }
Chris Lattner23ec01f2005-10-04 18:47:09 +00002042 Values.push_back(Val);
2043 if (isAllZeros) isAllZeros = Val->isNullValue();
2044 }
Chris Lattner5cbade92005-10-03 21:58:36 +00002045 }
2046
Chris Lattnercea141f2005-10-03 22:51:37 +00002047 Constant *Replacement = 0;
2048 if (isAllZeros) {
2049 Replacement = ConstantAggregateZero::get(getType());
2050 } else {
2051 // Check to see if we have this array type already.
2052 bool Exists;
Jim Laskeyede5aa42006-07-17 17:38:29 +00002053 ArrayConstantsTy::MapTy::iterator I =
Chris Lattner8a94bf12006-09-28 00:35:06 +00002054 ArrayConstants->InsertOrGetItem(Lookup, Exists);
Chris Lattnercea141f2005-10-03 22:51:37 +00002055
2056 if (Exists) {
2057 Replacement = I->second;
2058 } else {
2059 // Okay, the new shape doesn't exist in the system yet. Instead of
2060 // creating a new constant array, inserting it, replaceallusesof'ing the
2061 // old with the new, then deleting the old... just update the current one
2062 // in place!
Chris Lattner8a94bf12006-09-28 00:35:06 +00002063 ArrayConstants->MoveConstantToNewSlot(this, I);
Chris Lattnercea141f2005-10-03 22:51:37 +00002064
Chris Lattner54984052007-08-21 00:55:23 +00002065 // Update to the new value. Optimize for the case when we have a single
2066 // operand that we're changing, but handle bulk updates efficiently.
2067 if (NumUpdated == 1) {
2068 unsigned OperandToUpdate = U-OperandList;
2069 assert(getOperand(OperandToUpdate) == From &&
2070 "ReplaceAllUsesWith broken!");
2071 setOperand(OperandToUpdate, ToC);
2072 } else {
2073 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2074 if (getOperand(i) == From)
2075 setOperand(i, ToC);
2076 }
Chris Lattnercea141f2005-10-03 22:51:37 +00002077 return;
2078 }
2079 }
2080
2081 // Otherwise, I do need to replace this with an existing value.
Chris Lattner5cbade92005-10-03 21:58:36 +00002082 assert(Replacement != this && "I didn't contain From!");
2083
Chris Lattnerd0ff1ad2005-10-04 18:13:04 +00002084 // Everyone using this now uses the replacement.
2085 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattner5cbade92005-10-03 21:58:36 +00002086
2087 // Delete the old constant!
2088 destroyConstant();
2089}
2090
2091void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattnerd0ff1ad2005-10-04 18:13:04 +00002092 Use *U) {
Chris Lattner5cbade92005-10-03 21:58:36 +00002093 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
Chris Lattnerc182a882005-10-04 01:17:50 +00002094 Constant *ToC = cast<Constant>(To);
2095
Chris Lattner23ec01f2005-10-04 18:47:09 +00002096 unsigned OperandToUpdate = U-OperandList;
2097 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2098
Jim Laskeyede5aa42006-07-17 17:38:29 +00002099 std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
Chris Lattnerc182a882005-10-04 01:17:50 +00002100 Lookup.first.first = getType();
2101 Lookup.second = this;
2102 std::vector<Constant*> &Values = Lookup.first.second;
2103 Values.reserve(getNumOperands()); // Build replacement struct.
Chris Lattner5cbade92005-10-03 21:58:36 +00002104
Chris Lattner23ec01f2005-10-04 18:47:09 +00002105
Chris Lattnerc182a882005-10-04 01:17:50 +00002106 // Fill values with the modified operands of the constant struct. Also,
2107 // compute whether this turns into an all-zeros struct.
Chris Lattner23ec01f2005-10-04 18:47:09 +00002108 bool isAllZeros = false;
2109 if (!ToC->isNullValue()) {
2110 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
2111 Values.push_back(cast<Constant>(O->get()));
2112 } else {
2113 isAllZeros = true;
2114 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2115 Constant *Val = cast<Constant>(O->get());
2116 Values.push_back(Val);
2117 if (isAllZeros) isAllZeros = Val->isNullValue();
2118 }
Chris Lattnerc182a882005-10-04 01:17:50 +00002119 }
Chris Lattner23ec01f2005-10-04 18:47:09 +00002120 Values[OperandToUpdate] = ToC;
2121
Chris Lattnerc182a882005-10-04 01:17:50 +00002122 Constant *Replacement = 0;
2123 if (isAllZeros) {
2124 Replacement = ConstantAggregateZero::get(getType());
2125 } else {
2126 // Check to see if we have this array type already.
2127 bool Exists;
Jim Laskeyede5aa42006-07-17 17:38:29 +00002128 StructConstantsTy::MapTy::iterator I =
Chris Lattner8a94bf12006-09-28 00:35:06 +00002129 StructConstants->InsertOrGetItem(Lookup, Exists);
Chris Lattnerc182a882005-10-04 01:17:50 +00002130
2131 if (Exists) {
2132 Replacement = I->second;
2133 } else {
2134 // Okay, the new shape doesn't exist in the system yet. Instead of
2135 // creating a new constant struct, inserting it, replaceallusesof'ing the
2136 // old with the new, then deleting the old... just update the current one
2137 // in place!
Chris Lattner8a94bf12006-09-28 00:35:06 +00002138 StructConstants->MoveConstantToNewSlot(this, I);
Chris Lattnerc182a882005-10-04 01:17:50 +00002139
Chris Lattner23ec01f2005-10-04 18:47:09 +00002140 // Update to the new value.
2141 setOperand(OperandToUpdate, ToC);
Chris Lattnerc182a882005-10-04 01:17:50 +00002142 return;
2143 }
Chris Lattner5cbade92005-10-03 21:58:36 +00002144 }
2145
Chris Lattner5cbade92005-10-03 21:58:36 +00002146 assert(Replacement != this && "I didn't contain From!");
2147
Chris Lattnerd0ff1ad2005-10-04 18:13:04 +00002148 // Everyone using this now uses the replacement.
2149 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattner5cbade92005-10-03 21:58:36 +00002150
2151 // Delete the old constant!
2152 destroyConstant();
2153}
2154
Reid Spencer9d6565a2007-02-15 02:26:10 +00002155void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattnerd0ff1ad2005-10-04 18:13:04 +00002156 Use *U) {
Chris Lattner5cbade92005-10-03 21:58:36 +00002157 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2158
2159 std::vector<Constant*> Values;
2160 Values.reserve(getNumOperands()); // Build replacement array...
2161 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2162 Constant *Val = getOperand(i);
2163 if (Val == From) Val = cast<Constant>(To);
2164 Values.push_back(Val);
2165 }
2166
Reid Spencer9d6565a2007-02-15 02:26:10 +00002167 Constant *Replacement = ConstantVector::get(getType(), Values);
Chris Lattner5cbade92005-10-03 21:58:36 +00002168 assert(Replacement != this && "I didn't contain From!");
2169
Chris Lattnerd0ff1ad2005-10-04 18:13:04 +00002170 // Everyone using this now uses the replacement.
2171 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattner5cbade92005-10-03 21:58:36 +00002172
2173 // Delete the old constant!
2174 destroyConstant();
2175}
2176
2177void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
Chris Lattnerd0ff1ad2005-10-04 18:13:04 +00002178 Use *U) {
Chris Lattner5cbade92005-10-03 21:58:36 +00002179 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2180 Constant *To = cast<Constant>(ToV);
2181
2182 Constant *Replacement = 0;
2183 if (getOpcode() == Instruction::GetElementPtr) {
Chris Lattnerf9021ff2007-02-19 20:01:23 +00002184 SmallVector<Constant*, 8> Indices;
Chris Lattner5cbade92005-10-03 21:58:36 +00002185 Constant *Pointer = getOperand(0);
2186 Indices.reserve(getNumOperands()-1);
2187 if (Pointer == From) Pointer = To;
2188
2189 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2190 Constant *Val = getOperand(i);
2191 if (Val == From) Val = To;
2192 Indices.push_back(Val);
2193 }
Chris Lattnerf9021ff2007-02-19 20:01:23 +00002194 Replacement = ConstantExpr::getGetElementPtr(Pointer,
2195 &Indices[0], Indices.size());
Reid Spencer3da59db2006-11-27 01:05:10 +00002196 } else if (isCast()) {
Chris Lattner5cbade92005-10-03 21:58:36 +00002197 assert(getOperand(0) == From && "Cast only has one use!");
Reid Spencer3da59db2006-11-27 01:05:10 +00002198 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
Chris Lattner5cbade92005-10-03 21:58:36 +00002199 } else if (getOpcode() == Instruction::Select) {
2200 Constant *C1 = getOperand(0);
2201 Constant *C2 = getOperand(1);
2202 Constant *C3 = getOperand(2);
2203 if (C1 == From) C1 = To;
2204 if (C2 == From) C2 = To;
2205 if (C3 == From) C3 = To;
2206 Replacement = ConstantExpr::getSelect(C1, C2, C3);
Robert Bocchinob52ee7f2006-01-10 19:05:34 +00002207 } else if (getOpcode() == Instruction::ExtractElement) {
2208 Constant *C1 = getOperand(0);
2209 Constant *C2 = getOperand(1);
2210 if (C1 == From) C1 = To;
2211 if (C2 == From) C2 = To;
2212 Replacement = ConstantExpr::getExtractElement(C1, C2);
Chris Lattner42b55802006-04-08 05:09:48 +00002213 } else if (getOpcode() == Instruction::InsertElement) {
2214 Constant *C1 = getOperand(0);
2215 Constant *C2 = getOperand(1);
2216 Constant *C3 = getOperand(1);
2217 if (C1 == From) C1 = To;
2218 if (C2 == From) C2 = To;
2219 if (C3 == From) C3 = To;
2220 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2221 } else if (getOpcode() == Instruction::ShuffleVector) {
2222 Constant *C1 = getOperand(0);
2223 Constant *C2 = getOperand(1);
2224 Constant *C3 = getOperand(2);
2225 if (C1 == From) C1 = To;
2226 if (C2 == From) C2 = To;
2227 if (C3 == From) C3 = To;
2228 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
Reid Spencer077d0eb2006-12-04 05:19:50 +00002229 } else if (isCompare()) {
2230 Constant *C1 = getOperand(0);
2231 Constant *C2 = getOperand(1);
2232 if (C1 == From) C1 = To;
2233 if (C2 == From) C2 = To;
2234 if (getOpcode() == Instruction::ICmp)
2235 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2236 else
2237 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
Chris Lattner5cbade92005-10-03 21:58:36 +00002238 } else if (getNumOperands() == 2) {
2239 Constant *C1 = getOperand(0);
2240 Constant *C2 = getOperand(1);
2241 if (C1 == From) C1 = To;
2242 if (C2 == From) C2 = To;
2243 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2244 } else {
2245 assert(0 && "Unknown ConstantExpr type!");
2246 return;
2247 }
2248
2249 assert(Replacement != this && "I didn't contain From!");
2250
Chris Lattnerd0ff1ad2005-10-04 18:13:04 +00002251 // Everyone using this now uses the replacement.
2252 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattner5cbade92005-10-03 21:58:36 +00002253
2254 // Delete the old constant!
2255 destroyConstant();
2256}
2257
2258
Jim Laskey21b6c9d2006-03-08 18:11:07 +00002259/// getStringValue - Turn an LLVM constant pointer that eventually points to a
2260/// global into a string value. Return an empty string if we can't do it.
Evan Cheng09371032006-03-10 23:52:03 +00002261/// Parameter Chop determines if the result is chopped at the first null
2262/// terminator.
Jim Laskey21b6c9d2006-03-08 18:11:07 +00002263///
Evan Cheng09371032006-03-10 23:52:03 +00002264std::string Constant::getStringValue(bool Chop, unsigned Offset) {
Jim Laskey21b6c9d2006-03-08 18:11:07 +00002265 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(this)) {
2266 if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
2267 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
2268 if (Init->isString()) {
2269 std::string Result = Init->getAsString();
2270 if (Offset < Result.size()) {
2271 // If we are pointing INTO The string, erase the beginning...
2272 Result.erase(Result.begin(), Result.begin()+Offset);
2273
2274 // Take off the null terminator, and any string fragments after it.
Evan Cheng09371032006-03-10 23:52:03 +00002275 if (Chop) {
2276 std::string::size_type NullPos = Result.find_first_of((char)0);
2277 if (NullPos != std::string::npos)
2278 Result.erase(Result.begin()+NullPos, Result.end());
2279 }
Jim Laskey21b6c9d2006-03-08 18:11:07 +00002280 return Result;
2281 }
2282 }
2283 }
Chris Lattnere41dcdc2007-11-01 02:30:35 +00002284 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(this)) {
2285 if (CE->getOpcode() == Instruction::GetElementPtr) {
2286 // Turn a gep into the specified offset.
2287 if (CE->getNumOperands() == 3 &&
2288 cast<Constant>(CE->getOperand(1))->isNullValue() &&
2289 isa<ConstantInt>(CE->getOperand(2))) {
2290 Offset += cast<ConstantInt>(CE->getOperand(2))->getZExtValue();
2291 return CE->getOperand(0)->getStringValue(Chop, Offset);
Jim Laskey21b6c9d2006-03-08 18:11:07 +00002292 }
2293 }
2294 }
2295 return "";
2296}