blob: 2bcd7b68b75f294e5f7a93445faecae84a870831 [file] [log] [blame]
Chris Lattner2b383d2e2003-05-13 21:37:02 +00001//===-- Constants.cpp - Implement Constant nodes --------------------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner2f7c9632001-06-06 20:29:01 +00009//
Chris Lattner3462ae32001-12-03 22:26:30 +000010// This file implements the Constant* classes...
Chris Lattner2f7c9632001-06-06 20:29:01 +000011//
12//===----------------------------------------------------------------------===//
13
Chris Lattnerca142372002-04-28 19:55:58 +000014#include "llvm/Constants.h"
Chris Lattner33e93b82007-02-27 03:05:06 +000015#include "ConstantFold.h"
Chris Lattner2f7c9632001-06-06 20:29:01 +000016#include "llvm/DerivedTypes.h"
Reid Spencer1ebe1ab2004-07-17 23:48:33 +000017#include "llvm/GlobalValue.h"
Misha Brukman63b38bd2004-07-29 17:30:56 +000018#include "llvm/Instructions.h"
Chris Lattnerd7a73302001-10-13 06:57:33 +000019#include "llvm/Module.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000020#include "llvm/ADT/StringExtras.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000021#include "llvm/Support/Compiler.h"
Bill Wendling6a462f12006-11-17 08:03:48 +000022#include "llvm/Support/Debug.h"
Chris Lattner69edc982006-09-28 00:35:06 +000023#include "llvm/Support/ManagedStatic.h"
Bill Wendling6a462f12006-11-17 08:03:48 +000024#include "llvm/Support/MathExtras.h"
Chris Lattnera80bf0b2007-02-20 06:39:57 +000025#include "llvm/ADT/DenseMap.h"
Chris Lattnerb5d70302007-02-19 20:01:23 +000026#include "llvm/ADT/SmallVector.h"
Chris Lattner2f7c9632001-06-06 20:29:01 +000027#include <algorithm>
Reid Spencer3aaaa0b2007-02-05 20:47:22 +000028#include <map>
Chris Lattner189d19f2003-11-21 20:23:48 +000029using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000030
Chris Lattner2f7c9632001-06-06 20:29:01 +000031//===----------------------------------------------------------------------===//
Chris Lattner3462ae32001-12-03 22:26:30 +000032// Constant Class
Chris Lattner2f7c9632001-06-06 20:29:01 +000033//===----------------------------------------------------------------------===//
34
Chris Lattner3462ae32001-12-03 22:26:30 +000035void Constant::destroyConstantImpl() {
36 // When a Constant is destroyed, there may be lingering
Chris Lattnerd7a73302001-10-13 06:57:33 +000037 // references to the constant by other constants in the constant pool. These
Misha Brukmanbe372b92003-08-21 22:14:26 +000038 // constants are implicitly dependent on the module that is being deleted,
Chris Lattnerd7a73302001-10-13 06:57:33 +000039 // but they don't know that. Because we only find out when the CPV is
40 // deleted, we must now notify all of our users (that should only be
Chris Lattner3462ae32001-12-03 22:26:30 +000041 // Constants) that they are, in fact, invalid now and should be deleted.
Chris Lattnerd7a73302001-10-13 06:57:33 +000042 //
43 while (!use_empty()) {
44 Value *V = use_back();
45#ifndef NDEBUG // Only in -g mode...
Chris Lattnerd9f4ac662002-07-18 00:14:50 +000046 if (!isa<Constant>(V))
Bill Wendling6a462f12006-11-17 08:03:48 +000047 DOUT << "While deleting: " << *this
48 << "\n\nUse still stuck around after Def is destroyed: "
49 << *V << "\n\n";
Chris Lattnerd7a73302001-10-13 06:57:33 +000050#endif
Vikram S. Adve4e537b22002-07-14 23:13:17 +000051 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
Reid Spencer1ebe1ab2004-07-17 23:48:33 +000052 Constant *CV = cast<Constant>(V);
53 CV->destroyConstant();
Chris Lattnerd7a73302001-10-13 06:57:33 +000054
55 // The constant should remove itself from our use list...
Vikram S. Adve4e537b22002-07-14 23:13:17 +000056 assert((use_empty() || use_back() != V) && "Constant not removed!");
Chris Lattnerd7a73302001-10-13 06:57:33 +000057 }
58
59 // Value has no outstanding references it is safe to delete it now...
60 delete this;
Chris Lattner38569342001-10-01 20:11:19 +000061}
Chris Lattner2f7c9632001-06-06 20:29:01 +000062
Chris Lattner23dd1f62006-10-20 00:27:06 +000063/// canTrap - Return true if evaluation of this constant could trap. This is
64/// true for things like constant expressions that could divide by zero.
65bool Constant::canTrap() const {
66 assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
67 // The only thing that could possibly trap are constant exprs.
68 const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
69 if (!CE) return false;
70
71 // ConstantExpr traps if any operands can trap.
72 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
73 if (getOperand(i)->canTrap())
74 return true;
75
76 // Otherwise, only specific operations can trap.
77 switch (CE->getOpcode()) {
78 default:
79 return false;
Reid Spencer7e80b0b2006-10-26 06:15:43 +000080 case Instruction::UDiv:
81 case Instruction::SDiv:
82 case Instruction::FDiv:
Reid Spencer7eb55b32006-11-02 01:53:59 +000083 case Instruction::URem:
84 case Instruction::SRem:
85 case Instruction::FRem:
Chris Lattner23dd1f62006-10-20 00:27:06 +000086 // Div and rem can trap if the RHS is not known to be non-zero.
87 if (!isa<ConstantInt>(getOperand(1)) || getOperand(1)->isNullValue())
88 return true;
89 return false;
90 }
91}
92
Evan Chengf9e003b2007-03-08 00:59:12 +000093/// ContaintsRelocations - Return true if the constant value contains
94/// relocations which cannot be resolved at compile time.
95bool Constant::ContainsRelocations() const {
96 if (isa<GlobalValue>(this))
97 return true;
98 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
99 if (getOperand(i)->ContainsRelocations())
100 return true;
101 return false;
102}
103
Chris Lattnerb1585a92002-08-13 17:50:20 +0000104// Static constructor to create a '0' constant of arbitrary type...
105Constant *Constant::getNullValue(const Type *Ty) {
Dale Johannesen98d3a082007-09-14 22:26:36 +0000106 static uint64_t zero[2] = {0, 0};
Chris Lattner6b727592004-06-17 18:19:28 +0000107 switch (Ty->getTypeID()) {
Chris Lattnerdbcb0d32007-02-20 05:46:39 +0000108 case Type::IntegerTyID:
109 return ConstantInt::get(Ty, 0);
110 case Type::FloatTyID:
Dale Johannesen98d3a082007-09-14 22:26:36 +0000111 return ConstantFP::get(Ty, APFloat(APInt(32, 0)));
Chris Lattnerdbcb0d32007-02-20 05:46:39 +0000112 case Type::DoubleTyID:
Dale Johannesen98d3a082007-09-14 22:26:36 +0000113 return ConstantFP::get(Ty, APFloat(APInt(64, 0)));
Dale Johannesenbdad8092007-08-09 22:51:36 +0000114 case Type::X86_FP80TyID:
Dale Johannesen98d3a082007-09-14 22:26:36 +0000115 return ConstantFP::get(Ty, APFloat(APInt(80, 2, zero)));
Dale Johannesenbdad8092007-08-09 22:51:36 +0000116 case Type::FP128TyID:
Dale Johannesen98d3a082007-09-14 22:26:36 +0000117 case Type::PPC_FP128TyID:
118 return ConstantFP::get(Ty, APFloat(APInt(128, 2, zero)));
Misha Brukmanb1c93172005-04-21 23:48:37 +0000119 case Type::PointerTyID:
Chris Lattnerb1585a92002-08-13 17:50:20 +0000120 return ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattner9fba3da2004-02-15 05:53:04 +0000121 case Type::StructTyID:
122 case Type::ArrayTyID:
Reid Spencerd84d35b2007-02-15 02:26:10 +0000123 case Type::VectorTyID:
Chris Lattner9fba3da2004-02-15 05:53:04 +0000124 return ConstantAggregateZero::get(Ty);
Chris Lattnerb1585a92002-08-13 17:50:20 +0000125 default:
Reid Spencercf394bf2004-07-04 11:51:24 +0000126 // Function, Label, or Opaque type?
127 assert(!"Cannot create a null constant of that type!");
Chris Lattnerb1585a92002-08-13 17:50:20 +0000128 return 0;
129 }
130}
131
Chris Lattner72e39582007-06-15 06:10:53 +0000132Constant *Constant::getAllOnesValue(const Type *Ty) {
133 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
134 return ConstantInt::get(APInt::getAllOnesValue(ITy->getBitWidth()));
135 return ConstantVector::getAllOnesValue(cast<VectorType>(Ty));
136}
Chris Lattnerb1585a92002-08-13 17:50:20 +0000137
138// Static constructor to create an integral constant with all bits set
Zhou Sheng75b871f2007-01-11 12:24:14 +0000139ConstantInt *ConstantInt::getAllOnesValue(const Type *Ty) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000140 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
Reid Spencerd1bbfa52007-03-01 19:30:34 +0000141 return ConstantInt::get(APInt::getAllOnesValue(ITy->getBitWidth()));
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000142 return 0;
Chris Lattnerb1585a92002-08-13 17:50:20 +0000143}
144
Dan Gohman30978072007-05-24 14:36:04 +0000145/// @returns the value for a vector integer constant of the given type that
Chris Lattnerecab54c2007-01-04 01:49:26 +0000146/// has all its bits set to true.
147/// @brief Get the all ones value
Reid Spencerd84d35b2007-02-15 02:26:10 +0000148ConstantVector *ConstantVector::getAllOnesValue(const VectorType *Ty) {
Chris Lattnerecab54c2007-01-04 01:49:26 +0000149 std::vector<Constant*> Elts;
150 Elts.resize(Ty->getNumElements(),
Zhou Sheng75b871f2007-01-11 12:24:14 +0000151 ConstantInt::getAllOnesValue(Ty->getElementType()));
Dan Gohman30978072007-05-24 14:36:04 +0000152 assert(Elts[0] && "Not a vector integer type!");
Reid Spencerd84d35b2007-02-15 02:26:10 +0000153 return cast<ConstantVector>(ConstantVector::get(Elts));
Chris Lattnerecab54c2007-01-04 01:49:26 +0000154}
155
156
Chris Lattner2f7c9632001-06-06 20:29:01 +0000157//===----------------------------------------------------------------------===//
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000158// ConstantInt
Chris Lattner2f7c9632001-06-06 20:29:01 +0000159//===----------------------------------------------------------------------===//
160
Reid Spencerb31bffe2007-02-26 23:54:03 +0000161ConstantInt::ConstantInt(const IntegerType *Ty, const APInt& V)
Chris Lattner5db2f472007-02-20 05:55:46 +0000162 : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
Reid Spencerb31bffe2007-02-26 23:54:03 +0000163 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
Chris Lattner2f7c9632001-06-06 20:29:01 +0000164}
165
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000166ConstantInt *ConstantInt::TheTrueVal = 0;
167ConstantInt *ConstantInt::TheFalseVal = 0;
168
169namespace llvm {
170 void CleanupTrueFalse(void *) {
171 ConstantInt::ResetTrueFalse();
172 }
173}
174
175static ManagedCleanup<llvm::CleanupTrueFalse> TrueFalseCleanup;
176
177ConstantInt *ConstantInt::CreateTrueFalseVals(bool WhichOne) {
178 assert(TheTrueVal == 0 && TheFalseVal == 0);
179 TheTrueVal = get(Type::Int1Ty, 1);
180 TheFalseVal = get(Type::Int1Ty, 0);
181
182 // Ensure that llvm_shutdown nulls out TheTrueVal/TheFalseVal.
183 TrueFalseCleanup.Register();
184
185 return WhichOne ? TheTrueVal : TheFalseVal;
186}
187
188
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000189namespace {
Reid Spencerb31bffe2007-02-26 23:54:03 +0000190 struct DenseMapAPIntKeyInfo {
191 struct KeyTy {
192 APInt val;
193 const Type* type;
194 KeyTy(const APInt& V, const Type* Ty) : val(V), type(Ty) {}
195 KeyTy(const KeyTy& that) : val(that.val), type(that.type) {}
196 bool operator==(const KeyTy& that) const {
197 return type == that.type && this->val == that.val;
198 }
199 bool operator!=(const KeyTy& that) const {
200 return !this->operator==(that);
201 }
202 };
203 static inline KeyTy getEmptyKey() { return KeyTy(APInt(1,0), 0); }
204 static inline KeyTy getTombstoneKey() { return KeyTy(APInt(1,1), 0); }
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000205 static unsigned getHashValue(const KeyTy &Key) {
Reid Spencerb31bffe2007-02-26 23:54:03 +0000206 return DenseMapKeyInfo<void*>::getHashValue(Key.type) ^
207 Key.val.getHashValue();
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000208 }
Dale Johannesena719a602007-08-24 00:56:33 +0000209 static bool isPod() { return false; }
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000210 };
211}
212
213
Reid Spencerb31bffe2007-02-26 23:54:03 +0000214typedef DenseMap<DenseMapAPIntKeyInfo::KeyTy, ConstantInt*,
215 DenseMapAPIntKeyInfo> IntMapTy;
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000216static ManagedStatic<IntMapTy> IntConstants;
217
Reid Spencer362fb292007-03-19 20:39:08 +0000218ConstantInt *ConstantInt::get(const Type *Ty, uint64_t V, bool isSigned) {
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000219 const IntegerType *ITy = cast<IntegerType>(Ty);
Reid Spencer362fb292007-03-19 20:39:08 +0000220 return get(APInt(ITy->getBitWidth(), V, isSigned));
Reid Spencerb31bffe2007-02-26 23:54:03 +0000221}
222
Reid Spencerd1bbfa52007-03-01 19:30:34 +0000223// Get a ConstantInt from an APInt. Note that the value stored in the DenseMap
224// as the key, is a DensMapAPIntKeyInfo::KeyTy which has provided the
Reid Spencerb31bffe2007-02-26 23:54:03 +0000225// operator== and operator!= to ensure that the DenseMap doesn't attempt to
226// compare APInt's of different widths, which would violate an APInt class
227// invariant which generates an assertion.
Reid Spencerd1bbfa52007-03-01 19:30:34 +0000228ConstantInt *ConstantInt::get(const APInt& V) {
229 // Get the corresponding integer type for the bit width of the value.
230 const IntegerType *ITy = IntegerType::get(V.getBitWidth());
Reid Spencerb31bffe2007-02-26 23:54:03 +0000231 // get an existing value or the insertion position
Reid Spencerd1bbfa52007-03-01 19:30:34 +0000232 DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
Reid Spencerb31bffe2007-02-26 23:54:03 +0000233 ConstantInt *&Slot = (*IntConstants)[Key];
234 // if it exists, return it.
235 if (Slot)
236 return Slot;
237 // otherwise create a new one, insert it, and return it.
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000238 return Slot = new ConstantInt(ITy, V);
239}
240
241//===----------------------------------------------------------------------===//
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000242// ConstantFP
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000243//===----------------------------------------------------------------------===//
244
Dale Johannesend246b2c2007-08-30 00:23:21 +0000245ConstantFP::ConstantFP(const Type *Ty, const APFloat& V)
246 : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
247 // temporary
248 if (Ty==Type::FloatTy)
249 assert(&V.getSemantics()==&APFloat::IEEEsingle);
Dale Johannesen028084e2007-09-12 03:30:33 +0000250 else if (Ty==Type::DoubleTy)
Dale Johannesend246b2c2007-08-30 00:23:21 +0000251 assert(&V.getSemantics()==&APFloat::IEEEdouble);
Dale Johannesen028084e2007-09-12 03:30:33 +0000252 else if (Ty==Type::X86_FP80Ty)
253 assert(&V.getSemantics()==&APFloat::x87DoubleExtended);
254 else if (Ty==Type::FP128Ty)
255 assert(&V.getSemantics()==&APFloat::IEEEquad);
256 else
257 assert(0);
Chris Lattner2f7c9632001-06-06 20:29:01 +0000258}
259
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000260bool ConstantFP::isNullValue() const {
Dale Johannesena719a602007-08-24 00:56:33 +0000261 return Val.isZero() && !Val.isNegative();
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000262}
263
Dale Johannesen98d3a082007-09-14 22:26:36 +0000264ConstantFP *ConstantFP::getNegativeZero(const Type *Ty) {
265 APFloat apf = cast <ConstantFP>(Constant::getNullValue(Ty))->getValueAPF();
266 apf.changeSign();
267 return ConstantFP::get(Ty, apf);
268}
269
Dale Johannesend246b2c2007-08-30 00:23:21 +0000270bool ConstantFP::isExactlyValue(const APFloat& V) const {
271 return Val.bitwiseIsEqual(V);
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000272}
273
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000274namespace {
Dale Johannesena719a602007-08-24 00:56:33 +0000275 struct DenseMapAPFloatKeyInfo {
Dale Johannesenbdea32d2007-08-24 22:09:56 +0000276 struct KeyTy {
277 APFloat val;
278 KeyTy(const APFloat& V) : val(V){}
279 KeyTy(const KeyTy& that) : val(that.val) {}
280 bool operator==(const KeyTy& that) const {
281 return this->val.bitwiseIsEqual(that.val);
282 }
283 bool operator!=(const KeyTy& that) const {
284 return !this->operator==(that);
285 }
286 };
287 static inline KeyTy getEmptyKey() {
288 return KeyTy(APFloat(APFloat::Bogus,1));
Reid Spencerb31bffe2007-02-26 23:54:03 +0000289 }
Dale Johannesenbdea32d2007-08-24 22:09:56 +0000290 static inline KeyTy getTombstoneKey() {
291 return KeyTy(APFloat(APFloat::Bogus,2));
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000292 }
Dale Johannesenbdea32d2007-08-24 22:09:56 +0000293 static unsigned getHashValue(const KeyTy &Key) {
294 return Key.val.getHashValue();
Dale Johannesena719a602007-08-24 00:56:33 +0000295 }
296 static bool isPod() { return false; }
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000297 };
298}
299
300//---- ConstantFP::get() implementation...
301//
Dale Johannesenbdea32d2007-08-24 22:09:56 +0000302typedef DenseMap<DenseMapAPFloatKeyInfo::KeyTy, ConstantFP*,
Dale Johannesena719a602007-08-24 00:56:33 +0000303 DenseMapAPFloatKeyInfo> FPMapTy;
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000304
Dale Johannesena719a602007-08-24 00:56:33 +0000305static ManagedStatic<FPMapTy> FPConstants;
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000306
Dale Johannesend246b2c2007-08-30 00:23:21 +0000307ConstantFP *ConstantFP::get(const Type *Ty, const APFloat& V) {
308 // temporary
309 if (Ty==Type::FloatTy)
310 assert(&V.getSemantics()==&APFloat::IEEEsingle);
Dale Johannesen028084e2007-09-12 03:30:33 +0000311 else if (Ty==Type::DoubleTy)
Dale Johannesend246b2c2007-08-30 00:23:21 +0000312 assert(&V.getSemantics()==&APFloat::IEEEdouble);
Dale Johannesen028084e2007-09-12 03:30:33 +0000313 else if (Ty==Type::X86_FP80Ty)
314 assert(&V.getSemantics()==&APFloat::x87DoubleExtended);
315 else if (Ty==Type::FP128Ty)
316 assert(&V.getSemantics()==&APFloat::IEEEquad);
317 else
318 assert(0);
Dale Johannesend246b2c2007-08-30 00:23:21 +0000319
320 DenseMapAPFloatKeyInfo::KeyTy Key(V);
321 ConstantFP *&Slot = (*FPConstants)[Key];
322 if (Slot) return Slot;
323 return Slot = new ConstantFP(Ty, V);
324}
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000325
326//===----------------------------------------------------------------------===//
327// ConstantXXX Classes
328//===----------------------------------------------------------------------===//
329
330
Chris Lattner3462ae32001-12-03 22:26:30 +0000331ConstantArray::ConstantArray(const ArrayType *T,
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000332 const std::vector<Constant*> &V)
Chris Lattnere7e139e2005-09-27 06:09:08 +0000333 : Constant(T, ConstantArrayVal, new Use[V.size()], V.size()) {
Alkis Evlogimenos0507ffe2004-09-15 02:32:15 +0000334 assert(V.size() == T->getNumElements() &&
335 "Invalid initializer vector for constant array");
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000336 Use *OL = OperandList;
Chris Lattner0144fad2005-10-03 21:56:24 +0000337 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
338 I != E; ++I, ++OL) {
Chris Lattner20a24452005-10-07 05:23:36 +0000339 Constant *C = *I;
340 assert((C->getType() == T->getElementType() ||
Alkis Evlogimenoscb031d92004-09-10 04:16:59 +0000341 (T->isAbstract() &&
Chris Lattner20a24452005-10-07 05:23:36 +0000342 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
Alkis Evlogimenoscb031d92004-09-10 04:16:59 +0000343 "Initializer for array element doesn't match array element type!");
Chris Lattner20a24452005-10-07 05:23:36 +0000344 OL->init(C, this);
Chris Lattner2f7c9632001-06-06 20:29:01 +0000345 }
346}
347
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000348ConstantArray::~ConstantArray() {
349 delete [] OperandList;
350}
351
Chris Lattner3462ae32001-12-03 22:26:30 +0000352ConstantStruct::ConstantStruct(const StructType *T,
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000353 const std::vector<Constant*> &V)
Chris Lattnere7e139e2005-09-27 06:09:08 +0000354 : Constant(T, ConstantStructVal, new Use[V.size()], V.size()) {
Chris Lattnerac6db752004-02-09 04:37:31 +0000355 assert(V.size() == T->getNumElements() &&
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000356 "Invalid initializer vector for constant structure");
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000357 Use *OL = OperandList;
Chris Lattner0144fad2005-10-03 21:56:24 +0000358 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
359 I != E; ++I, ++OL) {
Chris Lattner20a24452005-10-07 05:23:36 +0000360 Constant *C = *I;
361 assert((C->getType() == T->getElementType(I-V.begin()) ||
Chris Lattner0144fad2005-10-03 21:56:24 +0000362 ((T->getElementType(I-V.begin())->isAbstract() ||
Chris Lattner20a24452005-10-07 05:23:36 +0000363 C->getType()->isAbstract()) &&
Chris Lattner0144fad2005-10-03 21:56:24 +0000364 T->getElementType(I-V.begin())->getTypeID() ==
Chris Lattner20a24452005-10-07 05:23:36 +0000365 C->getType()->getTypeID())) &&
Chris Lattner93c8f142003-06-02 17:42:47 +0000366 "Initializer for struct element doesn't match struct element type!");
Chris Lattner20a24452005-10-07 05:23:36 +0000367 OL->init(C, this);
Chris Lattner2f7c9632001-06-06 20:29:01 +0000368 }
369}
370
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000371ConstantStruct::~ConstantStruct() {
372 delete [] OperandList;
373}
374
375
Reid Spencerd84d35b2007-02-15 02:26:10 +0000376ConstantVector::ConstantVector(const VectorType *T,
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000377 const std::vector<Constant*> &V)
Reid Spencerd84d35b2007-02-15 02:26:10 +0000378 : Constant(T, ConstantVectorVal, new Use[V.size()], V.size()) {
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000379 Use *OL = OperandList;
Chris Lattner0144fad2005-10-03 21:56:24 +0000380 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
381 I != E; ++I, ++OL) {
Chris Lattner20a24452005-10-07 05:23:36 +0000382 Constant *C = *I;
383 assert((C->getType() == T->getElementType() ||
Alkis Evlogimenoscb031d92004-09-10 04:16:59 +0000384 (T->isAbstract() &&
Chris Lattner20a24452005-10-07 05:23:36 +0000385 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
Dan Gohman30978072007-05-24 14:36:04 +0000386 "Initializer for vector element doesn't match vector element type!");
Chris Lattner20a24452005-10-07 05:23:36 +0000387 OL->init(C, this);
Brian Gaeke02209042004-08-20 06:00:58 +0000388 }
389}
390
Reid Spencerd84d35b2007-02-15 02:26:10 +0000391ConstantVector::~ConstantVector() {
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000392 delete [] OperandList;
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000393}
394
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000395// We declare several classes private to this file, so use an anonymous
396// namespace
397namespace {
398
399/// UnaryConstantExpr - This class is private to Constants.cpp, and is used
400/// behind the scenes to implement unary constant exprs.
401class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
402 Use Op;
403public:
404 UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
405 : ConstantExpr(Ty, Opcode, &Op, 1), Op(C, this) {}
406};
407
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000408/// BinaryConstantExpr - This class is private to Constants.cpp, and is used
409/// behind the scenes to implement binary constant exprs.
Chris Lattner02157b02006-06-28 21:38:54 +0000410class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000411 Use Ops[2];
412public:
413 BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
Reid Spencer266e42b2006-12-23 06:05:41 +0000414 : ConstantExpr(C1->getType(), Opcode, Ops, 2) {
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000415 Ops[0].init(C1, this);
416 Ops[1].init(C2, this);
417 }
418};
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000419
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000420/// SelectConstantExpr - This class is private to Constants.cpp, and is used
421/// behind the scenes to implement select constant exprs.
Chris Lattner02157b02006-06-28 21:38:54 +0000422class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000423 Use Ops[3];
424public:
425 SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
426 : ConstantExpr(C2->getType(), Instruction::Select, Ops, 3) {
427 Ops[0].init(C1, this);
428 Ops[1].init(C2, this);
429 Ops[2].init(C3, this);
430 }
431};
432
Robert Bocchinoca27f032006-01-17 20:07:22 +0000433/// ExtractElementConstantExpr - This class is private to
434/// Constants.cpp, and is used behind the scenes to implement
435/// extractelement constant exprs.
Chris Lattner02157b02006-06-28 21:38:54 +0000436class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
Robert Bocchino23004482006-01-10 19:05:34 +0000437 Use Ops[2];
438public:
439 ExtractElementConstantExpr(Constant *C1, Constant *C2)
Reid Spencerd84d35b2007-02-15 02:26:10 +0000440 : ConstantExpr(cast<VectorType>(C1->getType())->getElementType(),
Robert Bocchino23004482006-01-10 19:05:34 +0000441 Instruction::ExtractElement, Ops, 2) {
442 Ops[0].init(C1, this);
443 Ops[1].init(C2, this);
444 }
445};
446
Robert Bocchinoca27f032006-01-17 20:07:22 +0000447/// InsertElementConstantExpr - This class is private to
448/// Constants.cpp, and is used behind the scenes to implement
449/// insertelement constant exprs.
Chris Lattner02157b02006-06-28 21:38:54 +0000450class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
Robert Bocchinoca27f032006-01-17 20:07:22 +0000451 Use Ops[3];
452public:
453 InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
454 : ConstantExpr(C1->getType(), Instruction::InsertElement,
455 Ops, 3) {
456 Ops[0].init(C1, this);
457 Ops[1].init(C2, this);
458 Ops[2].init(C3, this);
459 }
460};
461
Chris Lattnerbbe0a422006-04-08 01:18:18 +0000462/// ShuffleVectorConstantExpr - This class is private to
463/// Constants.cpp, and is used behind the scenes to implement
464/// shufflevector constant exprs.
Chris Lattner02157b02006-06-28 21:38:54 +0000465class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
Chris Lattnerbbe0a422006-04-08 01:18:18 +0000466 Use Ops[3];
467public:
468 ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
469 : ConstantExpr(C1->getType(), Instruction::ShuffleVector,
470 Ops, 3) {
471 Ops[0].init(C1, this);
472 Ops[1].init(C2, this);
473 Ops[2].init(C3, this);
474 }
475};
476
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000477/// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
478/// used behind the scenes to implement getelementpr constant exprs.
Chris Lattner02157b02006-06-28 21:38:54 +0000479struct VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000480 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
481 const Type *DestTy)
482 : ConstantExpr(DestTy, Instruction::GetElementPtr,
483 new Use[IdxList.size()+1], IdxList.size()+1) {
484 OperandList[0].init(C, this);
485 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
486 OperandList[i+1].init(IdxList[i], this);
487 }
488 ~GetElementPtrConstantExpr() {
Misha Brukmanb1c93172005-04-21 23:48:37 +0000489 delete [] OperandList;
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000490 }
491};
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000492
493// CompareConstantExpr - This class is private to Constants.cpp, and is used
494// behind the scenes to implement ICmp and FCmp constant expressions. This is
495// needed in order to store the predicate value for these instructions.
496struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
497 unsigned short predicate;
498 Use Ops[2];
499 CompareConstantExpr(Instruction::OtherOps opc, unsigned short pred,
500 Constant* LHS, Constant* RHS)
Reid Spencer542964f2007-01-11 18:21:29 +0000501 : ConstantExpr(Type::Int1Ty, opc, Ops, 2), predicate(pred) {
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000502 OperandList[0].init(LHS, this);
503 OperandList[1].init(RHS, this);
504 }
505};
506
507} // end anonymous namespace
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000508
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000509
510// Utility function for determining if a ConstantExpr is a CastOp or not. This
511// can't be inline because we don't want to #include Instruction.h into
512// Constant.h
513bool ConstantExpr::isCast() const {
514 return Instruction::isCast(getOpcode());
515}
516
Reid Spenceree3c9912006-12-04 05:19:50 +0000517bool ConstantExpr::isCompare() const {
518 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
519}
520
Chris Lattner817175f2004-03-29 02:37:53 +0000521/// ConstantExpr::get* - Return some common constants without having to
522/// specify the full Instruction::OPCODE identifier.
523///
524Constant *ConstantExpr::getNeg(Constant *C) {
Reid Spencer2eadb532007-01-21 00:29:26 +0000525 return get(Instruction::Sub,
526 ConstantExpr::getZeroValueForNegationExpr(C->getType()),
527 C);
Chris Lattner817175f2004-03-29 02:37:53 +0000528}
529Constant *ConstantExpr::getNot(Constant *C) {
Zhou Sheng75b871f2007-01-11 12:24:14 +0000530 assert(isa<ConstantInt>(C) && "Cannot NOT a nonintegral type!");
Chris Lattner817175f2004-03-29 02:37:53 +0000531 return get(Instruction::Xor, C,
Zhou Sheng75b871f2007-01-11 12:24:14 +0000532 ConstantInt::getAllOnesValue(C->getType()));
Chris Lattner817175f2004-03-29 02:37:53 +0000533}
534Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
535 return get(Instruction::Add, C1, C2);
536}
537Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
538 return get(Instruction::Sub, C1, C2);
539}
540Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
541 return get(Instruction::Mul, C1, C2);
542}
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000543Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2) {
544 return get(Instruction::UDiv, C1, C2);
545}
546Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2) {
547 return get(Instruction::SDiv, C1, C2);
548}
549Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
550 return get(Instruction::FDiv, C1, C2);
Chris Lattner817175f2004-03-29 02:37:53 +0000551}
Reid Spencer7eb55b32006-11-02 01:53:59 +0000552Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
553 return get(Instruction::URem, C1, C2);
554}
555Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
556 return get(Instruction::SRem, C1, C2);
557}
558Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
559 return get(Instruction::FRem, C1, C2);
Chris Lattner817175f2004-03-29 02:37:53 +0000560}
561Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
562 return get(Instruction::And, C1, C2);
563}
564Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
565 return get(Instruction::Or, C1, C2);
566}
567Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
568 return get(Instruction::Xor, C1, C2);
569}
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000570unsigned ConstantExpr::getPredicate() const {
571 assert(getOpcode() == Instruction::FCmp || getOpcode() == Instruction::ICmp);
572 return dynamic_cast<const CompareConstantExpr*>(this)->predicate;
573}
Chris Lattner817175f2004-03-29 02:37:53 +0000574Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
575 return get(Instruction::Shl, C1, C2);
576}
Reid Spencerfdff9382006-11-08 06:47:33 +0000577Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2) {
578 return get(Instruction::LShr, C1, C2);
Chris Lattner817175f2004-03-29 02:37:53 +0000579}
Reid Spencerfdff9382006-11-08 06:47:33 +0000580Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2) {
581 return get(Instruction::AShr, C1, C2);
Chris Lattnerdb8bdba2004-05-25 05:32:43 +0000582}
Chris Lattner60e0dd72001-10-03 06:12:09 +0000583
Chris Lattner7c1018a2006-07-14 19:37:40 +0000584/// getWithOperandReplaced - Return a constant expression identical to this
585/// one, but with the specified operand set to the specified value.
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000586Constant *
587ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
Chris Lattner7c1018a2006-07-14 19:37:40 +0000588 assert(OpNo < getNumOperands() && "Operand num is out of range!");
589 assert(Op->getType() == getOperand(OpNo)->getType() &&
590 "Replacing operand with value of different type!");
Chris Lattner227816342006-07-14 22:20:01 +0000591 if (getOperand(OpNo) == Op)
592 return const_cast<ConstantExpr*>(this);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000593
Chris Lattner227816342006-07-14 22:20:01 +0000594 Constant *Op0, *Op1, *Op2;
Chris Lattner7c1018a2006-07-14 19:37:40 +0000595 switch (getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000596 case Instruction::Trunc:
597 case Instruction::ZExt:
598 case Instruction::SExt:
599 case Instruction::FPTrunc:
600 case Instruction::FPExt:
601 case Instruction::UIToFP:
602 case Instruction::SIToFP:
603 case Instruction::FPToUI:
604 case Instruction::FPToSI:
605 case Instruction::PtrToInt:
606 case Instruction::IntToPtr:
607 case Instruction::BitCast:
608 return ConstantExpr::getCast(getOpcode(), Op, getType());
Chris Lattner227816342006-07-14 22:20:01 +0000609 case Instruction::Select:
610 Op0 = (OpNo == 0) ? Op : getOperand(0);
611 Op1 = (OpNo == 1) ? Op : getOperand(1);
612 Op2 = (OpNo == 2) ? Op : getOperand(2);
613 return ConstantExpr::getSelect(Op0, Op1, Op2);
614 case Instruction::InsertElement:
615 Op0 = (OpNo == 0) ? Op : getOperand(0);
616 Op1 = (OpNo == 1) ? Op : getOperand(1);
617 Op2 = (OpNo == 2) ? Op : getOperand(2);
618 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
619 case Instruction::ExtractElement:
620 Op0 = (OpNo == 0) ? Op : getOperand(0);
621 Op1 = (OpNo == 1) ? Op : getOperand(1);
622 return ConstantExpr::getExtractElement(Op0, Op1);
623 case Instruction::ShuffleVector:
624 Op0 = (OpNo == 0) ? Op : getOperand(0);
625 Op1 = (OpNo == 1) ? Op : getOperand(1);
626 Op2 = (OpNo == 2) ? Op : getOperand(2);
627 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000628 case Instruction::GetElementPtr: {
Chris Lattnerb5d70302007-02-19 20:01:23 +0000629 SmallVector<Constant*, 8> Ops;
630 Ops.resize(getNumOperands());
Chris Lattner7c1018a2006-07-14 19:37:40 +0000631 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
Chris Lattnerb5d70302007-02-19 20:01:23 +0000632 Ops[i] = getOperand(i);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000633 if (OpNo == 0)
Chris Lattnerb5d70302007-02-19 20:01:23 +0000634 return ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
Chris Lattner7c1018a2006-07-14 19:37:40 +0000635 Ops[OpNo-1] = Op;
Chris Lattnerb5d70302007-02-19 20:01:23 +0000636 return ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
Chris Lattner7c1018a2006-07-14 19:37:40 +0000637 }
Chris Lattner7c1018a2006-07-14 19:37:40 +0000638 default:
639 assert(getNumOperands() == 2 && "Must be binary operator?");
Chris Lattner227816342006-07-14 22:20:01 +0000640 Op0 = (OpNo == 0) ? Op : getOperand(0);
641 Op1 = (OpNo == 1) ? Op : getOperand(1);
642 return ConstantExpr::get(getOpcode(), Op0, Op1);
643 }
644}
645
646/// getWithOperands - This returns the current constant expression with the
647/// operands replaced with the specified values. The specified operands must
648/// match count and type with the existing ones.
649Constant *ConstantExpr::
650getWithOperands(const std::vector<Constant*> &Ops) const {
651 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
652 bool AnyChange = false;
653 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
654 assert(Ops[i]->getType() == getOperand(i)->getType() &&
655 "Operand type mismatch!");
656 AnyChange |= Ops[i] != getOperand(i);
657 }
658 if (!AnyChange) // No operands changed, return self.
659 return const_cast<ConstantExpr*>(this);
660
661 switch (getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000662 case Instruction::Trunc:
663 case Instruction::ZExt:
664 case Instruction::SExt:
665 case Instruction::FPTrunc:
666 case Instruction::FPExt:
667 case Instruction::UIToFP:
668 case Instruction::SIToFP:
669 case Instruction::FPToUI:
670 case Instruction::FPToSI:
671 case Instruction::PtrToInt:
672 case Instruction::IntToPtr:
673 case Instruction::BitCast:
674 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
Chris Lattner227816342006-07-14 22:20:01 +0000675 case Instruction::Select:
676 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
677 case Instruction::InsertElement:
678 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
679 case Instruction::ExtractElement:
680 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
681 case Instruction::ShuffleVector:
682 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
Chris Lattnerb5d70302007-02-19 20:01:23 +0000683 case Instruction::GetElementPtr:
684 return ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], Ops.size()-1);
Reid Spencer266e42b2006-12-23 06:05:41 +0000685 case Instruction::ICmp:
686 case Instruction::FCmp:
687 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
Chris Lattner227816342006-07-14 22:20:01 +0000688 default:
689 assert(getNumOperands() == 2 && "Must be binary operator?");
690 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000691 }
692}
693
Chris Lattner2f7c9632001-06-06 20:29:01 +0000694
695//===----------------------------------------------------------------------===//
Chris Lattner2f7c9632001-06-06 20:29:01 +0000696// isValueValidForType implementations
697
Reid Spencere7334722006-12-19 01:28:19 +0000698bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000699 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000700 if (Ty == Type::Int1Ty)
701 return Val == 0 || Val == 1;
Reid Spencerd7a00d72007-02-05 23:47:56 +0000702 if (NumBits >= 64)
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000703 return true; // always true, has to fit in largest type
704 uint64_t Max = (1ll << NumBits) - 1;
705 return Val <= Max;
Reid Spencere7334722006-12-19 01:28:19 +0000706}
707
Reid Spencere0fc4df2006-10-20 07:07:24 +0000708bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000709 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000710 if (Ty == Type::Int1Ty)
Reid Spencera94d3942007-01-19 21:13:56 +0000711 return Val == 0 || Val == 1 || Val == -1;
Reid Spencerd7a00d72007-02-05 23:47:56 +0000712 if (NumBits >= 64)
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000713 return true; // always true, has to fit in largest type
714 int64_t Min = -(1ll << (NumBits-1));
715 int64_t Max = (1ll << (NumBits-1)) - 1;
716 return (Val >= Min && Val <= Max);
Chris Lattner2f7c9632001-06-06 20:29:01 +0000717}
718
Dale Johannesend246b2c2007-08-30 00:23:21 +0000719bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
720 // convert modifies in place, so make a copy.
721 APFloat Val2 = APFloat(Val);
Chris Lattner6b727592004-06-17 18:19:28 +0000722 switch (Ty->getTypeID()) {
Chris Lattner2f7c9632001-06-06 20:29:01 +0000723 default:
724 return false; // These can't be represented as floating point!
725
Dale Johannesend246b2c2007-08-30 00:23:21 +0000726 // FIXME rounding mode needs to be more flexible
Chris Lattner2f7c9632001-06-06 20:29:01 +0000727 case Type::FloatTyID:
Dale Johannesend246b2c2007-08-30 00:23:21 +0000728 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
729 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven) ==
730 APFloat::opOK;
Chris Lattner2f7c9632001-06-06 20:29:01 +0000731 case Type::DoubleTyID:
Dale Johannesend246b2c2007-08-30 00:23:21 +0000732 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
733 &Val2.getSemantics() == &APFloat::IEEEdouble ||
734 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven) ==
735 APFloat::opOK;
Dale Johannesenbdad8092007-08-09 22:51:36 +0000736 case Type::X86_FP80TyID:
Dale Johannesen028084e2007-09-12 03:30:33 +0000737 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
738 &Val2.getSemantics() == &APFloat::IEEEdouble ||
739 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
Dale Johannesenbdad8092007-08-09 22:51:36 +0000740 case Type::FP128TyID:
Dale Johannesen028084e2007-09-12 03:30:33 +0000741 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
742 &Val2.getSemantics() == &APFloat::IEEEdouble ||
743 &Val2.getSemantics() == &APFloat::IEEEquad;
Chris Lattner2f7c9632001-06-06 20:29:01 +0000744 }
Chris Lattneraa2372562006-05-24 17:04:05 +0000745}
Chris Lattner9655e542001-07-20 19:16:02 +0000746
Chris Lattner49d855c2001-09-07 16:46:31 +0000747//===----------------------------------------------------------------------===//
Chris Lattner49d855c2001-09-07 16:46:31 +0000748// Factory Function Implementation
749
Chris Lattner98fa07b2003-05-23 20:03:32 +0000750// ConstantCreator - A class that is used to create constants by
751// ValueMap*. This class should be partially specialized if there is
752// something strange that needs to be done to interface to the ctor for the
753// constant.
754//
Chris Lattner189d19f2003-11-21 20:23:48 +0000755namespace llvm {
756 template<class ConstantClass, class TypeClass, class ValType>
Chris Lattner02157b02006-06-28 21:38:54 +0000757 struct VISIBILITY_HIDDEN ConstantCreator {
Chris Lattner189d19f2003-11-21 20:23:48 +0000758 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
759 return new ConstantClass(Ty, V);
760 }
761 };
Misha Brukmanb1c93172005-04-21 23:48:37 +0000762
Chris Lattner189d19f2003-11-21 20:23:48 +0000763 template<class ConstantClass, class TypeClass>
Chris Lattner02157b02006-06-28 21:38:54 +0000764 struct VISIBILITY_HIDDEN ConvertConstantType {
Chris Lattner189d19f2003-11-21 20:23:48 +0000765 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
766 assert(0 && "This type cannot be converted!\n");
767 abort();
768 }
769 };
Chris Lattnerb50d1352003-10-05 00:17:43 +0000770
Chris Lattner935aa922005-10-04 17:48:46 +0000771 template<class ValType, class TypeClass, class ConstantClass,
772 bool HasLargeKey = false /*true for arrays and structs*/ >
Chris Lattner02157b02006-06-28 21:38:54 +0000773 class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
Chris Lattnerb64419a2005-10-03 22:51:37 +0000774 public:
Jim Laskeyc03caef2006-07-17 17:38:29 +0000775 typedef std::pair<const Type*, ValType> MapKey;
776 typedef std::map<MapKey, Constant *> MapTy;
777 typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
778 typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
Chris Lattnerb64419a2005-10-03 22:51:37 +0000779 private:
Chris Lattner5bbf60a52005-10-04 16:52:46 +0000780 /// Map - This is the main map from the element descriptor to the Constants.
781 /// This is the primary way we avoid creating two of the same shape
782 /// constant.
Chris Lattnerb50d1352003-10-05 00:17:43 +0000783 MapTy Map;
Chris Lattner935aa922005-10-04 17:48:46 +0000784
785 /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
786 /// from the constants to their element in Map. This is important for
787 /// removal of constants from the array, which would otherwise have to scan
788 /// through the map with very large keys.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000789 InverseMapTy InverseMap;
Chris Lattnerb50d1352003-10-05 00:17:43 +0000790
Jim Laskeyc03caef2006-07-17 17:38:29 +0000791 /// AbstractTypeMap - Map for abstract type constants.
792 ///
Chris Lattnerb50d1352003-10-05 00:17:43 +0000793 AbstractTypeMapTy AbstractTypeMap;
Chris Lattner99a669b2004-11-19 16:39:44 +0000794
Chris Lattner98fa07b2003-05-23 20:03:32 +0000795 public:
Jim Laskeyc03caef2006-07-17 17:38:29 +0000796 typename MapTy::iterator map_end() { return Map.end(); }
Chris Lattnerb64419a2005-10-03 22:51:37 +0000797
798 /// InsertOrGetItem - Return an iterator for the specified element.
799 /// If the element exists in the map, the returned iterator points to the
800 /// entry and Exists=true. If not, the iterator points to the newly
801 /// inserted entry and returns Exists=false. Newly inserted entries have
802 /// I->second == 0, and should be filled in.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000803 typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
804 &InsertVal,
Chris Lattnerb64419a2005-10-03 22:51:37 +0000805 bool &Exists) {
Jim Laskeyc03caef2006-07-17 17:38:29 +0000806 std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
Chris Lattnerb64419a2005-10-03 22:51:37 +0000807 Exists = !IP.second;
808 return IP.first;
809 }
Chris Lattner5bbf60a52005-10-04 16:52:46 +0000810
Chris Lattner935aa922005-10-04 17:48:46 +0000811private:
Jim Laskeyc03caef2006-07-17 17:38:29 +0000812 typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
Chris Lattner935aa922005-10-04 17:48:46 +0000813 if (HasLargeKey) {
Jim Laskeyc03caef2006-07-17 17:38:29 +0000814 typename InverseMapTy::iterator IMI = InverseMap.find(CP);
Chris Lattner935aa922005-10-04 17:48:46 +0000815 assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
816 IMI->second->second == CP &&
817 "InverseMap corrupt!");
818 return IMI->second;
819 }
820
Jim Laskeyc03caef2006-07-17 17:38:29 +0000821 typename MapTy::iterator I =
Chris Lattner935aa922005-10-04 17:48:46 +0000822 Map.find(MapKey((TypeClass*)CP->getRawType(), getValType(CP)));
Chris Lattner5bbf60a52005-10-04 16:52:46 +0000823 if (I == Map.end() || I->second != CP) {
824 // FIXME: This should not use a linear scan. If this gets to be a
825 // performance problem, someone should look at this.
826 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
827 /* empty */;
828 }
Chris Lattner935aa922005-10-04 17:48:46 +0000829 return I;
830 }
831public:
832
Chris Lattnerb64419a2005-10-03 22:51:37 +0000833 /// getOrCreate - Return the specified constant from the map, creating it if
834 /// necessary.
Chris Lattner98fa07b2003-05-23 20:03:32 +0000835 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
Chris Lattnerb50d1352003-10-05 00:17:43 +0000836 MapKey Lookup(Ty, V);
Jim Laskeyc03caef2006-07-17 17:38:29 +0000837 typename MapTy::iterator I = Map.lower_bound(Lookup);
Reid Spencere0fc4df2006-10-20 07:07:24 +0000838 // Is it in the map?
Chris Lattner98fa07b2003-05-23 20:03:32 +0000839 if (I != Map.end() && I->first == Lookup)
Reid Spencere0fc4df2006-10-20 07:07:24 +0000840 return static_cast<ConstantClass *>(I->second);
Chris Lattner98fa07b2003-05-23 20:03:32 +0000841
842 // If no preexisting value, create one now...
843 ConstantClass *Result =
844 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
845
Chris Lattnerb50d1352003-10-05 00:17:43 +0000846 /// FIXME: why does this assert fail when loading 176.gcc?
847 //assert(Result->getType() == Ty && "Type specified is not correct!");
848 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
849
Chris Lattner935aa922005-10-04 17:48:46 +0000850 if (HasLargeKey) // Remember the reverse mapping if needed.
851 InverseMap.insert(std::make_pair(Result, I));
852
Chris Lattnerb50d1352003-10-05 00:17:43 +0000853 // If the type of the constant is abstract, make sure that an entry exists
854 // for it in the AbstractTypeMap.
855 if (Ty->isAbstract()) {
856 typename AbstractTypeMapTy::iterator TI =
857 AbstractTypeMap.lower_bound(Ty);
858
859 if (TI == AbstractTypeMap.end() || TI->first != Ty) {
860 // Add ourselves to the ATU list of the type.
861 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
862
863 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
864 }
865 }
Chris Lattner98fa07b2003-05-23 20:03:32 +0000866 return Result;
867 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000868
Chris Lattner98fa07b2003-05-23 20:03:32 +0000869 void remove(ConstantClass *CP) {
Jim Laskeyc03caef2006-07-17 17:38:29 +0000870 typename MapTy::iterator I = FindExistingElement(CP);
Chris Lattnerb50d1352003-10-05 00:17:43 +0000871 assert(I != Map.end() && "Constant not found in constant table!");
Chris Lattner3e650af2004-08-04 04:48:01 +0000872 assert(I->second == CP && "Didn't find correct element?");
Chris Lattnerb50d1352003-10-05 00:17:43 +0000873
Chris Lattner935aa922005-10-04 17:48:46 +0000874 if (HasLargeKey) // Remember the reverse mapping if needed.
875 InverseMap.erase(CP);
876
Chris Lattnerb50d1352003-10-05 00:17:43 +0000877 // Now that we found the entry, make sure this isn't the entry that
878 // the AbstractTypeMap points to.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000879 const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
Chris Lattnerb50d1352003-10-05 00:17:43 +0000880 if (Ty->isAbstract()) {
881 assert(AbstractTypeMap.count(Ty) &&
882 "Abstract type not in AbstractTypeMap?");
Jim Laskeyc03caef2006-07-17 17:38:29 +0000883 typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
Chris Lattnerb50d1352003-10-05 00:17:43 +0000884 if (ATMEntryIt == I) {
885 // Yes, we are removing the representative entry for this type.
886 // See if there are any other entries of the same type.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000887 typename MapTy::iterator TmpIt = ATMEntryIt;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000888
Chris Lattnerb50d1352003-10-05 00:17:43 +0000889 // First check the entry before this one...
890 if (TmpIt != Map.begin()) {
891 --TmpIt;
892 if (TmpIt->first.first != Ty) // Not the same type, move back...
893 ++TmpIt;
894 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000895
Chris Lattnerb50d1352003-10-05 00:17:43 +0000896 // If we didn't find the same type, try to move forward...
897 if (TmpIt == ATMEntryIt) {
898 ++TmpIt;
899 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
900 --TmpIt; // No entry afterwards with the same type
901 }
902
903 // If there is another entry in the map of the same abstract type,
904 // update the AbstractTypeMap entry now.
905 if (TmpIt != ATMEntryIt) {
906 ATMEntryIt = TmpIt;
907 } else {
908 // Otherwise, we are removing the last instance of this type
909 // from the table. Remove from the ATM, and from user list.
910 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
911 AbstractTypeMap.erase(Ty);
912 }
Chris Lattner98fa07b2003-05-23 20:03:32 +0000913 }
Chris Lattnerb50d1352003-10-05 00:17:43 +0000914 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000915
Chris Lattnerb50d1352003-10-05 00:17:43 +0000916 Map.erase(I);
917 }
918
Chris Lattner3b793c62005-10-04 21:35:50 +0000919
920 /// MoveConstantToNewSlot - If we are about to change C to be the element
921 /// specified by I, update our internal data structures to reflect this
922 /// fact.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000923 void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
Chris Lattner3b793c62005-10-04 21:35:50 +0000924 // First, remove the old location of the specified constant in the map.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000925 typename MapTy::iterator OldI = FindExistingElement(C);
Chris Lattner3b793c62005-10-04 21:35:50 +0000926 assert(OldI != Map.end() && "Constant not found in constant table!");
927 assert(OldI->second == C && "Didn't find correct element?");
928
929 // If this constant is the representative element for its abstract type,
930 // update the AbstractTypeMap so that the representative element is I.
931 if (C->getType()->isAbstract()) {
932 typename AbstractTypeMapTy::iterator ATI =
933 AbstractTypeMap.find(C->getType());
934 assert(ATI != AbstractTypeMap.end() &&
935 "Abstract type not in AbstractTypeMap?");
936 if (ATI->second == OldI)
937 ATI->second = I;
938 }
939
940 // Remove the old entry from the map.
941 Map.erase(OldI);
942
943 // Update the inverse map so that we know that this constant is now
944 // located at descriptor I.
945 if (HasLargeKey) {
946 assert(I->second == C && "Bad inversemap entry!");
947 InverseMap[C] = I;
948 }
949 }
950
Chris Lattnerb50d1352003-10-05 00:17:43 +0000951 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
Misha Brukmanb1c93172005-04-21 23:48:37 +0000952 typename AbstractTypeMapTy::iterator I =
Jim Laskeyc03caef2006-07-17 17:38:29 +0000953 AbstractTypeMap.find(cast<Type>(OldTy));
Chris Lattnerb50d1352003-10-05 00:17:43 +0000954
955 assert(I != AbstractTypeMap.end() &&
956 "Abstract type not in AbstractTypeMap?");
957
958 // Convert a constant at a time until the last one is gone. The last one
959 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
960 // eliminated eventually.
961 do {
962 ConvertConstantType<ConstantClass,
Jim Laskeyc03caef2006-07-17 17:38:29 +0000963 TypeClass>::convert(
964 static_cast<ConstantClass *>(I->second->second),
Chris Lattnerb50d1352003-10-05 00:17:43 +0000965 cast<TypeClass>(NewTy));
966
Jim Laskeyc03caef2006-07-17 17:38:29 +0000967 I = AbstractTypeMap.find(cast<Type>(OldTy));
Chris Lattnerb50d1352003-10-05 00:17:43 +0000968 } while (I != AbstractTypeMap.end());
969 }
970
971 // If the type became concrete without being refined to any other existing
972 // type, we just remove ourselves from the ATU list.
973 void typeBecameConcrete(const DerivedType *AbsTy) {
974 AbsTy->removeAbstractTypeUser(this);
975 }
976
977 void dump() const {
Bill Wendling6a462f12006-11-17 08:03:48 +0000978 DOUT << "Constant.cpp: ValueMap\n";
Chris Lattner98fa07b2003-05-23 20:03:32 +0000979 }
980 };
981}
982
Chris Lattnera84df0a22006-09-28 23:36:21 +0000983
Chris Lattner28173502007-02-20 06:11:36 +0000984
Chris Lattner9fba3da2004-02-15 05:53:04 +0000985//---- ConstantAggregateZero::get() implementation...
986//
987namespace llvm {
988 // ConstantAggregateZero does not take extra "value" argument...
989 template<class ValType>
990 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
991 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
992 return new ConstantAggregateZero(Ty);
993 }
994 };
995
996 template<>
997 struct ConvertConstantType<ConstantAggregateZero, Type> {
998 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
999 // Make everyone now use a constant of the new type...
1000 Constant *New = ConstantAggregateZero::get(NewTy);
1001 assert(New != OldC && "Didn't replace constant??");
1002 OldC->uncheckedReplaceAllUsesWith(New);
1003 OldC->destroyConstant(); // This constant is now dead, destroy it.
1004 }
1005 };
1006}
1007
Chris Lattner69edc982006-09-28 00:35:06 +00001008static ManagedStatic<ValueMap<char, Type,
1009 ConstantAggregateZero> > AggZeroConstants;
Chris Lattner9fba3da2004-02-15 05:53:04 +00001010
Chris Lattner3e650af2004-08-04 04:48:01 +00001011static char getValType(ConstantAggregateZero *CPZ) { return 0; }
1012
Chris Lattner9fba3da2004-02-15 05:53:04 +00001013Constant *ConstantAggregateZero::get(const Type *Ty) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001014 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) &&
Chris Lattnerbfd0b6d2006-06-10 04:16:23 +00001015 "Cannot create an aggregate zero of non-aggregate type!");
Chris Lattner69edc982006-09-28 00:35:06 +00001016 return AggZeroConstants->getOrCreate(Ty, 0);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001017}
1018
1019// destroyConstant - Remove the constant from the constant table...
1020//
1021void ConstantAggregateZero::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001022 AggZeroConstants->remove(this);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001023 destroyConstantImpl();
1024}
1025
Chris Lattner3462ae32001-12-03 22:26:30 +00001026//---- ConstantArray::get() implementation...
Chris Lattner49d855c2001-09-07 16:46:31 +00001027//
Chris Lattner189d19f2003-11-21 20:23:48 +00001028namespace llvm {
1029 template<>
1030 struct ConvertConstantType<ConstantArray, ArrayType> {
1031 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
1032 // Make everyone now use a constant of the new type...
1033 std::vector<Constant*> C;
1034 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1035 C.push_back(cast<Constant>(OldC->getOperand(i)));
1036 Constant *New = ConstantArray::get(NewTy, C);
1037 assert(New != OldC && "Didn't replace constant??");
1038 OldC->uncheckedReplaceAllUsesWith(New);
1039 OldC->destroyConstant(); // This constant is now dead, destroy it.
1040 }
1041 };
1042}
Chris Lattnerb50d1352003-10-05 00:17:43 +00001043
Chris Lattner3e650af2004-08-04 04:48:01 +00001044static std::vector<Constant*> getValType(ConstantArray *CA) {
1045 std::vector<Constant*> Elements;
1046 Elements.reserve(CA->getNumOperands());
1047 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1048 Elements.push_back(cast<Constant>(CA->getOperand(i)));
1049 return Elements;
1050}
1051
Chris Lattnerb64419a2005-10-03 22:51:37 +00001052typedef ValueMap<std::vector<Constant*>, ArrayType,
Chris Lattner935aa922005-10-04 17:48:46 +00001053 ConstantArray, true /*largekey*/> ArrayConstantsTy;
Chris Lattner69edc982006-09-28 00:35:06 +00001054static ManagedStatic<ArrayConstantsTy> ArrayConstants;
Chris Lattner49d855c2001-09-07 16:46:31 +00001055
Chris Lattner015e8212004-02-15 04:14:47 +00001056Constant *ConstantArray::get(const ArrayType *Ty,
Chris Lattner9fba3da2004-02-15 05:53:04 +00001057 const std::vector<Constant*> &V) {
1058 // If this is an all-zero array, return a ConstantAggregateZero object
1059 if (!V.empty()) {
1060 Constant *C = V[0];
1061 if (!C->isNullValue())
Chris Lattner69edc982006-09-28 00:35:06 +00001062 return ArrayConstants->getOrCreate(Ty, V);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001063 for (unsigned i = 1, e = V.size(); i != e; ++i)
1064 if (V[i] != C)
Chris Lattner69edc982006-09-28 00:35:06 +00001065 return ArrayConstants->getOrCreate(Ty, V);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001066 }
1067 return ConstantAggregateZero::get(Ty);
Chris Lattner49d855c2001-09-07 16:46:31 +00001068}
1069
Chris Lattner98fa07b2003-05-23 20:03:32 +00001070// destroyConstant - Remove the constant from the constant table...
1071//
1072void ConstantArray::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001073 ArrayConstants->remove(this);
Chris Lattner98fa07b2003-05-23 20:03:32 +00001074 destroyConstantImpl();
1075}
1076
Reid Spencer6f614532006-05-30 08:23:18 +00001077/// ConstantArray::get(const string&) - Return an array that is initialized to
1078/// contain the specified string. If length is zero then a null terminator is
1079/// added to the specified string so that it may be used in a natural way.
1080/// Otherwise, the length parameter specifies how much of the string to use
1081/// and it won't be null terminated.
1082///
Reid Spencer82ebaba2006-05-30 18:15:07 +00001083Constant *ConstantArray::get(const std::string &Str, bool AddNull) {
Chris Lattner7f74a562002-01-20 22:54:45 +00001084 std::vector<Constant*> ElementVals;
Reid Spencer82ebaba2006-05-30 18:15:07 +00001085 for (unsigned i = 0; i < Str.length(); ++i)
Reid Spencer8d9336d2006-12-31 05:26:44 +00001086 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, Str[i]));
Chris Lattner8f80fe02001-10-14 23:54:12 +00001087
1088 // Add a null terminator to the string...
Reid Spencer82ebaba2006-05-30 18:15:07 +00001089 if (AddNull) {
Reid Spencer8d9336d2006-12-31 05:26:44 +00001090 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, 0));
Reid Spencer6f614532006-05-30 08:23:18 +00001091 }
Chris Lattner8f80fe02001-10-14 23:54:12 +00001092
Reid Spencer8d9336d2006-12-31 05:26:44 +00001093 ArrayType *ATy = ArrayType::get(Type::Int8Ty, ElementVals.size());
Chris Lattner3462ae32001-12-03 22:26:30 +00001094 return ConstantArray::get(ATy, ElementVals);
Vikram S. Adve34410432001-10-14 23:17:20 +00001095}
1096
Reid Spencer2546b762007-01-26 07:37:34 +00001097/// isString - This method returns true if the array is an array of i8, and
1098/// if the elements of the array are all ConstantInt's.
Chris Lattnere8dfcca2004-01-14 17:06:38 +00001099bool ConstantArray::isString() const {
Reid Spencer2546b762007-01-26 07:37:34 +00001100 // Check the element type for i8...
Reid Spencer8d9336d2006-12-31 05:26:44 +00001101 if (getType()->getElementType() != Type::Int8Ty)
Chris Lattnere8dfcca2004-01-14 17:06:38 +00001102 return false;
1103 // Check the elements to make sure they are all integers, not constant
1104 // expressions.
1105 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1106 if (!isa<ConstantInt>(getOperand(i)))
1107 return false;
1108 return true;
1109}
1110
Evan Cheng3763c5b2006-10-26 19:15:05 +00001111/// isCString - This method returns true if the array is a string (see
1112/// isString) and it ends in a null byte \0 and does not contains any other
1113/// null bytes except its terminator.
1114bool ConstantArray::isCString() const {
Reid Spencer2546b762007-01-26 07:37:34 +00001115 // Check the element type for i8...
Reid Spencer8d9336d2006-12-31 05:26:44 +00001116 if (getType()->getElementType() != Type::Int8Ty)
Evan Chenge974da62006-10-26 21:48:03 +00001117 return false;
1118 Constant *Zero = Constant::getNullValue(getOperand(0)->getType());
1119 // Last element must be a null.
1120 if (getOperand(getNumOperands()-1) != Zero)
1121 return false;
1122 // Other elements must be non-null integers.
1123 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1124 if (!isa<ConstantInt>(getOperand(i)))
Evan Cheng3763c5b2006-10-26 19:15:05 +00001125 return false;
Evan Chenge974da62006-10-26 21:48:03 +00001126 if (getOperand(i) == Zero)
1127 return false;
1128 }
Evan Cheng3763c5b2006-10-26 19:15:05 +00001129 return true;
1130}
1131
1132
Reid Spencer2546b762007-01-26 07:37:34 +00001133// getAsString - If the sub-element type of this array is i8
Chris Lattner81fabb02002-08-26 17:53:56 +00001134// then this method converts the array to an std::string and returns it.
1135// Otherwise, it asserts out.
1136//
1137std::string ConstantArray::getAsString() const {
Chris Lattnere8dfcca2004-01-14 17:06:38 +00001138 assert(isString() && "Not a string!");
Chris Lattner81fabb02002-08-26 17:53:56 +00001139 std::string Result;
Chris Lattner6077c312003-07-23 15:22:26 +00001140 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
Reid Spencere0fc4df2006-10-20 07:07:24 +00001141 Result += (char)cast<ConstantInt>(getOperand(i))->getZExtValue();
Chris Lattner81fabb02002-08-26 17:53:56 +00001142 return Result;
1143}
1144
1145
Chris Lattner3462ae32001-12-03 22:26:30 +00001146//---- ConstantStruct::get() implementation...
Chris Lattner49d855c2001-09-07 16:46:31 +00001147//
Chris Lattnerb50d1352003-10-05 00:17:43 +00001148
Chris Lattner189d19f2003-11-21 20:23:48 +00001149namespace llvm {
1150 template<>
1151 struct ConvertConstantType<ConstantStruct, StructType> {
1152 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1153 // Make everyone now use a constant of the new type...
1154 std::vector<Constant*> C;
1155 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1156 C.push_back(cast<Constant>(OldC->getOperand(i)));
1157 Constant *New = ConstantStruct::get(NewTy, C);
1158 assert(New != OldC && "Didn't replace constant??");
Misha Brukmanb1c93172005-04-21 23:48:37 +00001159
Chris Lattner189d19f2003-11-21 20:23:48 +00001160 OldC->uncheckedReplaceAllUsesWith(New);
1161 OldC->destroyConstant(); // This constant is now dead, destroy it.
1162 }
1163 };
1164}
Chris Lattnerb50d1352003-10-05 00:17:43 +00001165
Chris Lattner8760ec72005-10-04 01:17:50 +00001166typedef ValueMap<std::vector<Constant*>, StructType,
Chris Lattner935aa922005-10-04 17:48:46 +00001167 ConstantStruct, true /*largekey*/> StructConstantsTy;
Chris Lattner69edc982006-09-28 00:35:06 +00001168static ManagedStatic<StructConstantsTy> StructConstants;
Chris Lattner49d855c2001-09-07 16:46:31 +00001169
Chris Lattner3e650af2004-08-04 04:48:01 +00001170static std::vector<Constant*> getValType(ConstantStruct *CS) {
1171 std::vector<Constant*> Elements;
1172 Elements.reserve(CS->getNumOperands());
1173 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1174 Elements.push_back(cast<Constant>(CS->getOperand(i)));
1175 return Elements;
1176}
1177
Chris Lattner015e8212004-02-15 04:14:47 +00001178Constant *ConstantStruct::get(const StructType *Ty,
1179 const std::vector<Constant*> &V) {
Chris Lattner9fba3da2004-02-15 05:53:04 +00001180 // Create a ConstantAggregateZero value if all elements are zeros...
1181 for (unsigned i = 0, e = V.size(); i != e; ++i)
1182 if (!V[i]->isNullValue())
Chris Lattner69edc982006-09-28 00:35:06 +00001183 return StructConstants->getOrCreate(Ty, V);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001184
1185 return ConstantAggregateZero::get(Ty);
Chris Lattner49d855c2001-09-07 16:46:31 +00001186}
Chris Lattner883ad0b2001-10-03 15:39:36 +00001187
Andrew Lenharthdcb3c972006-12-08 18:06:16 +00001188Constant *ConstantStruct::get(const std::vector<Constant*> &V, bool packed) {
Chris Lattnerd6108ca2004-07-12 20:35:11 +00001189 std::vector<const Type*> StructEls;
1190 StructEls.reserve(V.size());
1191 for (unsigned i = 0, e = V.size(); i != e; ++i)
1192 StructEls.push_back(V[i]->getType());
Andrew Lenharthdcb3c972006-12-08 18:06:16 +00001193 return get(StructType::get(StructEls, packed), V);
Chris Lattnerd6108ca2004-07-12 20:35:11 +00001194}
1195
Chris Lattnerd7a73302001-10-13 06:57:33 +00001196// destroyConstant - Remove the constant from the constant table...
Chris Lattner883ad0b2001-10-03 15:39:36 +00001197//
Chris Lattner3462ae32001-12-03 22:26:30 +00001198void ConstantStruct::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001199 StructConstants->remove(this);
Chris Lattnerd7a73302001-10-13 06:57:33 +00001200 destroyConstantImpl();
1201}
Chris Lattner883ad0b2001-10-03 15:39:36 +00001202
Reid Spencerd84d35b2007-02-15 02:26:10 +00001203//---- ConstantVector::get() implementation...
Brian Gaeke02209042004-08-20 06:00:58 +00001204//
1205namespace llvm {
1206 template<>
Reid Spencerd84d35b2007-02-15 02:26:10 +00001207 struct ConvertConstantType<ConstantVector, VectorType> {
1208 static void convert(ConstantVector *OldC, const VectorType *NewTy) {
Brian Gaeke02209042004-08-20 06:00:58 +00001209 // Make everyone now use a constant of the new type...
1210 std::vector<Constant*> C;
1211 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1212 C.push_back(cast<Constant>(OldC->getOperand(i)));
Reid Spencerd84d35b2007-02-15 02:26:10 +00001213 Constant *New = ConstantVector::get(NewTy, C);
Brian Gaeke02209042004-08-20 06:00:58 +00001214 assert(New != OldC && "Didn't replace constant??");
1215 OldC->uncheckedReplaceAllUsesWith(New);
1216 OldC->destroyConstant(); // This constant is now dead, destroy it.
1217 }
1218 };
1219}
1220
Reid Spencerd84d35b2007-02-15 02:26:10 +00001221static std::vector<Constant*> getValType(ConstantVector *CP) {
Brian Gaeke02209042004-08-20 06:00:58 +00001222 std::vector<Constant*> Elements;
1223 Elements.reserve(CP->getNumOperands());
1224 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1225 Elements.push_back(CP->getOperand(i));
1226 return Elements;
1227}
1228
Reid Spencerd84d35b2007-02-15 02:26:10 +00001229static ManagedStatic<ValueMap<std::vector<Constant*>, VectorType,
Reid Spencer09575ba2007-02-15 03:39:18 +00001230 ConstantVector> > VectorConstants;
Brian Gaeke02209042004-08-20 06:00:58 +00001231
Reid Spencerd84d35b2007-02-15 02:26:10 +00001232Constant *ConstantVector::get(const VectorType *Ty,
Brian Gaeke02209042004-08-20 06:00:58 +00001233 const std::vector<Constant*> &V) {
Dan Gohman30978072007-05-24 14:36:04 +00001234 // If this is an all-zero vector, return a ConstantAggregateZero object
Brian Gaeke02209042004-08-20 06:00:58 +00001235 if (!V.empty()) {
1236 Constant *C = V[0];
1237 if (!C->isNullValue())
Reid Spencer09575ba2007-02-15 03:39:18 +00001238 return VectorConstants->getOrCreate(Ty, V);
Brian Gaeke02209042004-08-20 06:00:58 +00001239 for (unsigned i = 1, e = V.size(); i != e; ++i)
1240 if (V[i] != C)
Reid Spencer09575ba2007-02-15 03:39:18 +00001241 return VectorConstants->getOrCreate(Ty, V);
Brian Gaeke02209042004-08-20 06:00:58 +00001242 }
1243 return ConstantAggregateZero::get(Ty);
1244}
1245
Reid Spencerd84d35b2007-02-15 02:26:10 +00001246Constant *ConstantVector::get(const std::vector<Constant*> &V) {
Brian Gaeke02209042004-08-20 06:00:58 +00001247 assert(!V.empty() && "Cannot infer type if V is empty");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001248 return get(VectorType::get(V.front()->getType(),V.size()), V);
Brian Gaeke02209042004-08-20 06:00:58 +00001249}
1250
1251// destroyConstant - Remove the constant from the constant table...
1252//
Reid Spencerd84d35b2007-02-15 02:26:10 +00001253void ConstantVector::destroyConstant() {
Reid Spencer09575ba2007-02-15 03:39:18 +00001254 VectorConstants->remove(this);
Brian Gaeke02209042004-08-20 06:00:58 +00001255 destroyConstantImpl();
1256}
1257
Dan Gohman30978072007-05-24 14:36:04 +00001258/// This function will return true iff every element in this vector constant
Jim Laskeyf0478822007-01-12 22:39:14 +00001259/// is set to all ones.
1260/// @returns true iff this constant's emements are all set to all ones.
1261/// @brief Determine if the value is all ones.
Reid Spencerd84d35b2007-02-15 02:26:10 +00001262bool ConstantVector::isAllOnesValue() const {
Jim Laskeyf0478822007-01-12 22:39:14 +00001263 // Check out first element.
1264 const Constant *Elt = getOperand(0);
1265 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1266 if (!CI || !CI->isAllOnesValue()) return false;
1267 // Then make sure all remaining elements point to the same value.
1268 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1269 if (getOperand(I) != Elt) return false;
1270 }
1271 return true;
1272}
1273
Chris Lattner3462ae32001-12-03 22:26:30 +00001274//---- ConstantPointerNull::get() implementation...
Chris Lattnerd7a73302001-10-13 06:57:33 +00001275//
Chris Lattner98fa07b2003-05-23 20:03:32 +00001276
Chris Lattner189d19f2003-11-21 20:23:48 +00001277namespace llvm {
1278 // ConstantPointerNull does not take extra "value" argument...
1279 template<class ValType>
1280 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1281 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1282 return new ConstantPointerNull(Ty);
1283 }
1284 };
Chris Lattner98fa07b2003-05-23 20:03:32 +00001285
Chris Lattner189d19f2003-11-21 20:23:48 +00001286 template<>
1287 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1288 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1289 // Make everyone now use a constant of the new type...
1290 Constant *New = ConstantPointerNull::get(NewTy);
1291 assert(New != OldC && "Didn't replace constant??");
1292 OldC->uncheckedReplaceAllUsesWith(New);
1293 OldC->destroyConstant(); // This constant is now dead, destroy it.
1294 }
1295 };
1296}
Chris Lattnerb50d1352003-10-05 00:17:43 +00001297
Chris Lattner69edc982006-09-28 00:35:06 +00001298static ManagedStatic<ValueMap<char, PointerType,
1299 ConstantPointerNull> > NullPtrConstants;
Chris Lattnerd7a73302001-10-13 06:57:33 +00001300
Chris Lattner3e650af2004-08-04 04:48:01 +00001301static char getValType(ConstantPointerNull *) {
1302 return 0;
1303}
1304
1305
Chris Lattner3462ae32001-12-03 22:26:30 +00001306ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
Chris Lattner69edc982006-09-28 00:35:06 +00001307 return NullPtrConstants->getOrCreate(Ty, 0);
Chris Lattner883ad0b2001-10-03 15:39:36 +00001308}
1309
Chris Lattner0c6e0b92002-08-18 00:40:04 +00001310// destroyConstant - Remove the constant from the constant table...
1311//
1312void ConstantPointerNull::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001313 NullPtrConstants->remove(this);
Chris Lattner0c6e0b92002-08-18 00:40:04 +00001314 destroyConstantImpl();
1315}
1316
1317
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001318//---- UndefValue::get() implementation...
1319//
1320
1321namespace llvm {
1322 // UndefValue does not take extra "value" argument...
1323 template<class ValType>
1324 struct ConstantCreator<UndefValue, Type, ValType> {
1325 static UndefValue *create(const Type *Ty, const ValType &V) {
1326 return new UndefValue(Ty);
1327 }
1328 };
1329
1330 template<>
1331 struct ConvertConstantType<UndefValue, Type> {
1332 static void convert(UndefValue *OldC, const Type *NewTy) {
1333 // Make everyone now use a constant of the new type.
1334 Constant *New = UndefValue::get(NewTy);
1335 assert(New != OldC && "Didn't replace constant??");
1336 OldC->uncheckedReplaceAllUsesWith(New);
1337 OldC->destroyConstant(); // This constant is now dead, destroy it.
1338 }
1339 };
1340}
1341
Chris Lattner69edc982006-09-28 00:35:06 +00001342static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001343
1344static char getValType(UndefValue *) {
1345 return 0;
1346}
1347
1348
1349UndefValue *UndefValue::get(const Type *Ty) {
Chris Lattner69edc982006-09-28 00:35:06 +00001350 return UndefValueConstants->getOrCreate(Ty, 0);
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001351}
1352
1353// destroyConstant - Remove the constant from the constant table.
1354//
1355void UndefValue::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001356 UndefValueConstants->remove(this);
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001357 destroyConstantImpl();
1358}
1359
1360
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001361//---- ConstantExpr::get() implementations...
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001362//
Reid Spencer8d9336d2006-12-31 05:26:44 +00001363
Reid Spenceree3c9912006-12-04 05:19:50 +00001364struct ExprMapKeyType {
1365 explicit ExprMapKeyType(unsigned opc, std::vector<Constant*> ops,
Reid Spencerdba6aa42006-12-04 18:38:05 +00001366 unsigned short pred = 0) : opcode(opc), predicate(pred), operands(ops) { }
1367 uint16_t opcode;
1368 uint16_t predicate;
Reid Spenceree3c9912006-12-04 05:19:50 +00001369 std::vector<Constant*> operands;
Reid Spenceree3c9912006-12-04 05:19:50 +00001370 bool operator==(const ExprMapKeyType& that) const {
1371 return this->opcode == that.opcode &&
1372 this->predicate == that.predicate &&
1373 this->operands == that.operands;
1374 }
1375 bool operator<(const ExprMapKeyType & that) const {
1376 return this->opcode < that.opcode ||
1377 (this->opcode == that.opcode && this->predicate < that.predicate) ||
1378 (this->opcode == that.opcode && this->predicate == that.predicate &&
1379 this->operands < that.operands);
1380 }
1381
1382 bool operator!=(const ExprMapKeyType& that) const {
1383 return !(*this == that);
1384 }
1385};
Chris Lattner98fa07b2003-05-23 20:03:32 +00001386
Chris Lattner189d19f2003-11-21 20:23:48 +00001387namespace llvm {
1388 template<>
1389 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
Reid Spencer10fbf0e2006-12-03 05:48:19 +00001390 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1391 unsigned short pred = 0) {
Reid Spenceree3c9912006-12-04 05:19:50 +00001392 if (Instruction::isCast(V.opcode))
1393 return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1394 if ((V.opcode >= Instruction::BinaryOpsBegin &&
Reid Spencer2341c222007-02-02 02:16:23 +00001395 V.opcode < Instruction::BinaryOpsEnd))
Reid Spenceree3c9912006-12-04 05:19:50 +00001396 return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1397 if (V.opcode == Instruction::Select)
1398 return new SelectConstantExpr(V.operands[0], V.operands[1],
1399 V.operands[2]);
1400 if (V.opcode == Instruction::ExtractElement)
1401 return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1402 if (V.opcode == Instruction::InsertElement)
1403 return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1404 V.operands[2]);
1405 if (V.opcode == Instruction::ShuffleVector)
1406 return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1407 V.operands[2]);
1408 if (V.opcode == Instruction::GetElementPtr) {
1409 std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
1410 return new GetElementPtrConstantExpr(V.operands[0], IdxList, Ty);
1411 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001412
Reid Spenceree3c9912006-12-04 05:19:50 +00001413 // The compare instructions are weird. We have to encode the predicate
1414 // value and it is combined with the instruction opcode by multiplying
1415 // the opcode by one hundred. We must decode this to get the predicate.
1416 if (V.opcode == Instruction::ICmp)
1417 return new CompareConstantExpr(Instruction::ICmp, V.predicate,
1418 V.operands[0], V.operands[1]);
1419 if (V.opcode == Instruction::FCmp)
1420 return new CompareConstantExpr(Instruction::FCmp, V.predicate,
1421 V.operands[0], V.operands[1]);
1422 assert(0 && "Invalid ConstantExpr!");
Jeff Cohen9f469632006-12-15 21:47:01 +00001423 return 0;
Chris Lattnerb50d1352003-10-05 00:17:43 +00001424 }
Chris Lattner189d19f2003-11-21 20:23:48 +00001425 };
Chris Lattnerb50d1352003-10-05 00:17:43 +00001426
Chris Lattner189d19f2003-11-21 20:23:48 +00001427 template<>
1428 struct ConvertConstantType<ConstantExpr, Type> {
1429 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1430 Constant *New;
1431 switch (OldC->getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001432 case Instruction::Trunc:
1433 case Instruction::ZExt:
1434 case Instruction::SExt:
1435 case Instruction::FPTrunc:
1436 case Instruction::FPExt:
1437 case Instruction::UIToFP:
1438 case Instruction::SIToFP:
1439 case Instruction::FPToUI:
1440 case Instruction::FPToSI:
1441 case Instruction::PtrToInt:
1442 case Instruction::IntToPtr:
1443 case Instruction::BitCast:
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001444 New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0),
1445 NewTy);
Chris Lattner189d19f2003-11-21 20:23:48 +00001446 break;
Chris Lattner6e415c02004-03-12 05:54:04 +00001447 case Instruction::Select:
1448 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1449 OldC->getOperand(1),
1450 OldC->getOperand(2));
1451 break;
Chris Lattner189d19f2003-11-21 20:23:48 +00001452 default:
1453 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
Reid Spencer7eb55b32006-11-02 01:53:59 +00001454 OldC->getOpcode() < Instruction::BinaryOpsEnd);
Chris Lattner189d19f2003-11-21 20:23:48 +00001455 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1456 OldC->getOperand(1));
1457 break;
1458 case Instruction::GetElementPtr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00001459 // Make everyone now use a constant of the new type...
Chris Lattner13128ab2004-10-11 22:52:25 +00001460 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
Chris Lattner302116a2007-01-31 04:40:28 +00001461 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0),
1462 &Idx[0], Idx.size());
Chris Lattner189d19f2003-11-21 20:23:48 +00001463 break;
1464 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001465
Chris Lattner189d19f2003-11-21 20:23:48 +00001466 assert(New != OldC && "Didn't replace constant??");
1467 OldC->uncheckedReplaceAllUsesWith(New);
1468 OldC->destroyConstant(); // This constant is now dead, destroy it.
1469 }
1470 };
1471} // end namespace llvm
Chris Lattnerb50d1352003-10-05 00:17:43 +00001472
1473
Chris Lattner3e650af2004-08-04 04:48:01 +00001474static ExprMapKeyType getValType(ConstantExpr *CE) {
1475 std::vector<Constant*> Operands;
1476 Operands.reserve(CE->getNumOperands());
1477 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1478 Operands.push_back(cast<Constant>(CE->getOperand(i)));
Reid Spenceree3c9912006-12-04 05:19:50 +00001479 return ExprMapKeyType(CE->getOpcode(), Operands,
1480 CE->isCompare() ? CE->getPredicate() : 0);
Chris Lattner3e650af2004-08-04 04:48:01 +00001481}
1482
Chris Lattner69edc982006-09-28 00:35:06 +00001483static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1484 ConstantExpr> > ExprConstants;
Vikram S. Adve4c485332002-07-15 18:19:33 +00001485
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001486/// This is a utility function to handle folding of casts and lookup of the
1487/// cast in the ExprConstants map. It is usedby the various get* methods below.
1488static inline Constant *getFoldedCast(
1489 Instruction::CastOps opc, Constant *C, const Type *Ty) {
Chris Lattner815ae2b2003-10-07 22:19:19 +00001490 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001491 // Fold a few common cases
1492 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1493 return FC;
Chris Lattneracdbe712003-04-17 19:24:48 +00001494
Vikram S. Adve4c485332002-07-15 18:19:33 +00001495 // Look up the constant in the table first to ensure uniqueness
Chris Lattner2b383d2e2003-05-13 21:37:02 +00001496 std::vector<Constant*> argVec(1, C);
Reid Spenceree3c9912006-12-04 05:19:50 +00001497 ExprMapKeyType Key(opc, argVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001498 return ExprConstants->getOrCreate(Ty, Key);
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001499}
Reid Spencerf37dc652006-12-05 19:14:13 +00001500
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001501Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1502 Instruction::CastOps opc = Instruction::CastOps(oc);
1503 assert(Instruction::isCast(opc) && "opcode out of range");
1504 assert(C && Ty && "Null arguments to getCast");
1505 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1506
1507 switch (opc) {
1508 default:
1509 assert(0 && "Invalid cast opcode");
1510 break;
1511 case Instruction::Trunc: return getTrunc(C, Ty);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001512 case Instruction::ZExt: return getZExt(C, Ty);
1513 case Instruction::SExt: return getSExt(C, Ty);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001514 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1515 case Instruction::FPExt: return getFPExtend(C, Ty);
1516 case Instruction::UIToFP: return getUIToFP(C, Ty);
1517 case Instruction::SIToFP: return getSIToFP(C, Ty);
1518 case Instruction::FPToUI: return getFPToUI(C, Ty);
1519 case Instruction::FPToSI: return getFPToSI(C, Ty);
1520 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1521 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1522 case Instruction::BitCast: return getBitCast(C, Ty);
Chris Lattner1ece6f82005-01-01 15:59:57 +00001523 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001524 return 0;
Reid Spencerf37dc652006-12-05 19:14:13 +00001525}
1526
Reid Spencer5c140882006-12-04 20:17:56 +00001527Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1528 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1529 return getCast(Instruction::BitCast, C, Ty);
1530 return getCast(Instruction::ZExt, C, Ty);
1531}
1532
1533Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1534 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1535 return getCast(Instruction::BitCast, C, Ty);
1536 return getCast(Instruction::SExt, C, Ty);
1537}
1538
1539Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1540 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1541 return getCast(Instruction::BitCast, C, Ty);
1542 return getCast(Instruction::Trunc, C, Ty);
1543}
1544
Reid Spencerbc245a02006-12-05 03:25:26 +00001545Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1546 assert(isa<PointerType>(S->getType()) && "Invalid cast");
Chris Lattner03c49532007-01-15 02:27:26 +00001547 assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
Reid Spencerbc245a02006-12-05 03:25:26 +00001548
Chris Lattner03c49532007-01-15 02:27:26 +00001549 if (Ty->isInteger())
Reid Spencerbc245a02006-12-05 03:25:26 +00001550 return getCast(Instruction::PtrToInt, S, Ty);
1551 return getCast(Instruction::BitCast, S, Ty);
1552}
1553
Reid Spencer56521c42006-12-12 00:51:07 +00001554Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
1555 bool isSigned) {
Chris Lattner03c49532007-01-15 02:27:26 +00001556 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
Reid Spencer56521c42006-12-12 00:51:07 +00001557 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1558 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1559 Instruction::CastOps opcode =
1560 (SrcBits == DstBits ? Instruction::BitCast :
1561 (SrcBits > DstBits ? Instruction::Trunc :
1562 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1563 return getCast(opcode, C, Ty);
1564}
1565
1566Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1567 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1568 "Invalid cast");
1569 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1570 unsigned DstBits = Ty->getPrimitiveSizeInBits();
Reid Spencerca104e82006-12-12 05:38:50 +00001571 if (SrcBits == DstBits)
1572 return C; // Avoid a useless cast
Reid Spencer56521c42006-12-12 00:51:07 +00001573 Instruction::CastOps opcode =
Reid Spencerca104e82006-12-12 05:38:50 +00001574 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
Reid Spencer56521c42006-12-12 00:51:07 +00001575 return getCast(opcode, C, Ty);
1576}
1577
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001578Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
Chris Lattner03c49532007-01-15 02:27:26 +00001579 assert(C->getType()->isInteger() && "Trunc operand must be integer");
1580 assert(Ty->isInteger() && "Trunc produces only integral");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001581 assert(C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1582 "SrcTy must be larger than DestTy for Trunc!");
1583
1584 return getFoldedCast(Instruction::Trunc, C, Ty);
1585}
1586
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001587Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
Chris Lattner03c49532007-01-15 02:27:26 +00001588 assert(C->getType()->isInteger() && "SEXt operand must be integral");
1589 assert(Ty->isInteger() && "SExt produces only integer");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001590 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1591 "SrcTy must be smaller than DestTy for SExt!");
1592
1593 return getFoldedCast(Instruction::SExt, C, Ty);
Chris Lattnerdd284742004-04-04 23:20:30 +00001594}
1595
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001596Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
Chris Lattner03c49532007-01-15 02:27:26 +00001597 assert(C->getType()->isInteger() && "ZEXt operand must be integral");
1598 assert(Ty->isInteger() && "ZExt produces only integer");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001599 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1600 "SrcTy must be smaller than DestTy for ZExt!");
1601
1602 return getFoldedCast(Instruction::ZExt, C, Ty);
1603}
1604
1605Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1606 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1607 C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1608 "This is an illegal floating point truncation!");
1609 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1610}
1611
1612Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1613 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1614 C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1615 "This is an illegal floating point extension!");
1616 return getFoldedCast(Instruction::FPExt, C, Ty);
1617}
1618
1619Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
Chris Lattner03c49532007-01-15 02:27:26 +00001620 assert(C->getType()->isInteger() && Ty->isFloatingPoint() &&
Reid Spencer2546b762007-01-26 07:37:34 +00001621 "This is an illegal i32 to floating point cast!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001622 return getFoldedCast(Instruction::UIToFP, C, Ty);
1623}
1624
1625Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
Chris Lattner03c49532007-01-15 02:27:26 +00001626 assert(C->getType()->isInteger() && Ty->isFloatingPoint() &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001627 "This is an illegal sint to floating point cast!");
1628 return getFoldedCast(Instruction::SIToFP, C, Ty);
1629}
1630
1631Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
Chris Lattner03c49532007-01-15 02:27:26 +00001632 assert(C->getType()->isFloatingPoint() && Ty->isInteger() &&
Reid Spencer2546b762007-01-26 07:37:34 +00001633 "This is an illegal floating point to i32 cast!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001634 return getFoldedCast(Instruction::FPToUI, C, Ty);
1635}
1636
1637Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
Chris Lattner03c49532007-01-15 02:27:26 +00001638 assert(C->getType()->isFloatingPoint() && Ty->isInteger() &&
Reid Spencer2546b762007-01-26 07:37:34 +00001639 "This is an illegal floating point to i32 cast!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001640 return getFoldedCast(Instruction::FPToSI, C, Ty);
1641}
1642
1643Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1644 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
Chris Lattner03c49532007-01-15 02:27:26 +00001645 assert(DstTy->isInteger() && "PtrToInt destination must be integral");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001646 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1647}
1648
1649Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
Chris Lattner03c49532007-01-15 02:27:26 +00001650 assert(C->getType()->isInteger() && "IntToPtr source must be integral");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001651 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
1652 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1653}
1654
1655Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1656 // BitCast implies a no-op cast of type only. No bits change. However, you
1657 // can't cast pointers to anything but pointers.
1658 const Type *SrcTy = C->getType();
1659 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
Reid Spencer5c140882006-12-04 20:17:56 +00001660 "BitCast cannot cast pointer to non-pointer and vice versa");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001661
1662 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
1663 // or nonptr->ptr). For all the other types, the cast is okay if source and
1664 // destination bit widths are identical.
1665 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1666 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
Reid Spencer5c140882006-12-04 20:17:56 +00001667 assert(SrcBitSize == DstBitSize && "BitCast requies types of same width");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001668 return getFoldedCast(Instruction::BitCast, C, DstTy);
Chris Lattnerdd284742004-04-04 23:20:30 +00001669}
1670
Alkis Evlogimenosda5de052004-10-24 01:41:10 +00001671Constant *ConstantExpr::getSizeOf(const Type *Ty) {
Chris Lattneracc4e542004-12-13 19:48:51 +00001672 // sizeof is implemented as: (ulong) gep (Ty*)null, 1
Chris Lattnerb5d70302007-02-19 20:01:23 +00001673 Constant *GEPIdx = ConstantInt::get(Type::Int32Ty, 1);
1674 Constant *GEP =
1675 getGetElementPtr(getNullValue(PointerType::get(Ty)), &GEPIdx, 1);
1676 return getCast(Instruction::PtrToInt, GEP, Type::Int64Ty);
Alkis Evlogimenos9160d5f2005-03-19 11:40:31 +00001677}
1678
Chris Lattnerb50d1352003-10-05 00:17:43 +00001679Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
Reid Spencera009d0d2006-12-04 21:35:24 +00001680 Constant *C1, Constant *C2) {
Chris Lattner38a9bcd2003-05-21 17:49:25 +00001681 // Check the operands for consistency first
Reid Spencer7eb55b32006-11-02 01:53:59 +00001682 assert(Opcode >= Instruction::BinaryOpsBegin &&
1683 Opcode < Instruction::BinaryOpsEnd &&
Chris Lattner38a9bcd2003-05-21 17:49:25 +00001684 "Invalid opcode in binary constant expression");
1685 assert(C1->getType() == C2->getType() &&
1686 "Operand types in binary constant expression should match");
Chris Lattnerb50d1352003-10-05 00:17:43 +00001687
Reid Spencer542964f2007-01-11 18:21:29 +00001688 if (ReqTy == C1->getType() || ReqTy == Type::Int1Ty)
Chris Lattnerb50d1352003-10-05 00:17:43 +00001689 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1690 return FC; // Fold a few common cases...
Chris Lattneracdbe712003-04-17 19:24:48 +00001691
Chris Lattner2b383d2e2003-05-13 21:37:02 +00001692 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
Reid Spencera009d0d2006-12-04 21:35:24 +00001693 ExprMapKeyType Key(Opcode, argVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001694 return ExprConstants->getOrCreate(ReqTy, Key);
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001695}
1696
Reid Spencer266e42b2006-12-23 06:05:41 +00001697Constant *ConstantExpr::getCompareTy(unsigned short predicate,
Reid Spencera009d0d2006-12-04 21:35:24 +00001698 Constant *C1, Constant *C2) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001699 switch (predicate) {
1700 default: assert(0 && "Invalid CmpInst predicate");
1701 case FCmpInst::FCMP_FALSE: case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_OGT:
1702 case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OLE:
1703 case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_ORD: case FCmpInst::FCMP_UNO:
1704 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UGT: case FCmpInst::FCMP_UGE:
1705 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_ULE: case FCmpInst::FCMP_UNE:
1706 case FCmpInst::FCMP_TRUE:
1707 return getFCmp(predicate, C1, C2);
1708 case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGT:
1709 case ICmpInst::ICMP_UGE: case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE:
1710 case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_SGE: case ICmpInst::ICMP_SLT:
1711 case ICmpInst::ICMP_SLE:
1712 return getICmp(predicate, C1, C2);
1713 }
Reid Spencera009d0d2006-12-04 21:35:24 +00001714}
1715
1716Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001717#ifndef NDEBUG
1718 switch (Opcode) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00001719 case Instruction::Add:
1720 case Instruction::Sub:
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001721 case Instruction::Mul:
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001722 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Chris Lattner03c49532007-01-15 02:27:26 +00001723 assert((C1->getType()->isInteger() || C1->getType()->isFloatingPoint() ||
Reid Spencerd84d35b2007-02-15 02:26:10 +00001724 isa<VectorType>(C1->getType())) &&
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001725 "Tried to create an arithmetic operation on a non-arithmetic type!");
1726 break;
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001727 case Instruction::UDiv:
1728 case Instruction::SDiv:
1729 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001730 assert((C1->getType()->isInteger() || (isa<VectorType>(C1->getType()) &&
1731 cast<VectorType>(C1->getType())->getElementType()->isInteger())) &&
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001732 "Tried to create an arithmetic operation on a non-arithmetic type!");
1733 break;
1734 case Instruction::FDiv:
1735 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001736 assert((C1->getType()->isFloatingPoint() || (isa<VectorType>(C1->getType())
1737 && cast<VectorType>(C1->getType())->getElementType()->isFloatingPoint()))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001738 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1739 break;
Reid Spencer7eb55b32006-11-02 01:53:59 +00001740 case Instruction::URem:
1741 case Instruction::SRem:
1742 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001743 assert((C1->getType()->isInteger() || (isa<VectorType>(C1->getType()) &&
1744 cast<VectorType>(C1->getType())->getElementType()->isInteger())) &&
Reid Spencer7eb55b32006-11-02 01:53:59 +00001745 "Tried to create an arithmetic operation on a non-arithmetic type!");
1746 break;
1747 case Instruction::FRem:
1748 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001749 assert((C1->getType()->isFloatingPoint() || (isa<VectorType>(C1->getType())
1750 && cast<VectorType>(C1->getType())->getElementType()->isFloatingPoint()))
Reid Spencer7eb55b32006-11-02 01:53:59 +00001751 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1752 break;
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001753 case Instruction::And:
1754 case Instruction::Or:
1755 case Instruction::Xor:
1756 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001757 assert((C1->getType()->isInteger() || isa<VectorType>(C1->getType())) &&
Misha Brukman3852f652005-01-27 06:46:38 +00001758 "Tried to create a logical operation on a non-integral type!");
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001759 break;
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001760 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00001761 case Instruction::LShr:
1762 case Instruction::AShr:
Reid Spencer2341c222007-02-02 02:16:23 +00001763 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Chris Lattner03c49532007-01-15 02:27:26 +00001764 assert(C1->getType()->isInteger() &&
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001765 "Tried to create a shift operation on a non-integer type!");
1766 break;
1767 default:
1768 break;
1769 }
1770#endif
1771
Reid Spencera009d0d2006-12-04 21:35:24 +00001772 return getTy(C1->getType(), Opcode, C1, C2);
1773}
1774
Reid Spencer266e42b2006-12-23 06:05:41 +00001775Constant *ConstantExpr::getCompare(unsigned short pred,
Reid Spencera009d0d2006-12-04 21:35:24 +00001776 Constant *C1, Constant *C2) {
1777 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencer266e42b2006-12-23 06:05:41 +00001778 return getCompareTy(pred, C1, C2);
Chris Lattner29ca2c62004-08-04 18:50:09 +00001779}
1780
Chris Lattner6e415c02004-03-12 05:54:04 +00001781Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1782 Constant *V1, Constant *V2) {
Reid Spencer2546b762007-01-26 07:37:34 +00001783 assert(C->getType() == Type::Int1Ty && "Select condition must be i1!");
Chris Lattner6e415c02004-03-12 05:54:04 +00001784 assert(V1->getType() == V2->getType() && "Select value types must match!");
1785 assert(V1->getType()->isFirstClassType() && "Cannot select aggregate type!");
1786
1787 if (ReqTy == V1->getType())
1788 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1789 return SC; // Fold common cases
1790
1791 std::vector<Constant*> argVec(3, C);
1792 argVec[1] = V1;
1793 argVec[2] = V2;
Reid Spenceree3c9912006-12-04 05:19:50 +00001794 ExprMapKeyType Key(Instruction::Select, argVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001795 return ExprConstants->getOrCreate(ReqTy, Key);
Chris Lattner6e415c02004-03-12 05:54:04 +00001796}
1797
Chris Lattnerb50d1352003-10-05 00:17:43 +00001798Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
Chris Lattner302116a2007-01-31 04:40:28 +00001799 Value* const *Idxs,
1800 unsigned NumIdx) {
David Greenec656cbb2007-09-04 15:46:09 +00001801 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx, true) &&
Chris Lattner04b60fe2004-02-16 20:46:13 +00001802 "GEP indices invalid!");
1803
Chris Lattner302116a2007-01-31 04:40:28 +00001804 if (Constant *FC = ConstantFoldGetElementPtr(C, (Constant**)Idxs, NumIdx))
Chris Lattneracdbe712003-04-17 19:24:48 +00001805 return FC; // Fold a few common cases...
Chris Lattner04b60fe2004-02-16 20:46:13 +00001806
Chris Lattnerb50d1352003-10-05 00:17:43 +00001807 assert(isa<PointerType>(C->getType()) &&
Chris Lattner98fa07b2003-05-23 20:03:32 +00001808 "Non-pointer type for constant GetElementPtr expression");
Vikram S. Adve4c485332002-07-15 18:19:33 +00001809 // Look up the constant in the table first to ensure uniqueness
Chris Lattner13128ab2004-10-11 22:52:25 +00001810 std::vector<Constant*> ArgVec;
Chris Lattner302116a2007-01-31 04:40:28 +00001811 ArgVec.reserve(NumIdx+1);
Chris Lattner13128ab2004-10-11 22:52:25 +00001812 ArgVec.push_back(C);
Chris Lattner302116a2007-01-31 04:40:28 +00001813 for (unsigned i = 0; i != NumIdx; ++i)
1814 ArgVec.push_back(cast<Constant>(Idxs[i]));
1815 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001816 return ExprConstants->getOrCreate(ReqTy, Key);
Vikram S. Adve4c485332002-07-15 18:19:33 +00001817}
1818
Chris Lattner302116a2007-01-31 04:40:28 +00001819Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
1820 unsigned NumIdx) {
Chris Lattnerb50d1352003-10-05 00:17:43 +00001821 // Get the result type of the getelementptr!
Chris Lattner302116a2007-01-31 04:40:28 +00001822 const Type *Ty =
David Greenec656cbb2007-09-04 15:46:09 +00001823 GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx, true);
Chris Lattnerb50d1352003-10-05 00:17:43 +00001824 assert(Ty && "GEP indices invalid!");
Chris Lattner302116a2007-01-31 04:40:28 +00001825 return getGetElementPtrTy(PointerType::get(Ty), C, Idxs, NumIdx);
Chris Lattner13128ab2004-10-11 22:52:25 +00001826}
1827
Chris Lattner302116a2007-01-31 04:40:28 +00001828Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
1829 unsigned NumIdx) {
1830 return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
Chris Lattnerb50d1352003-10-05 00:17:43 +00001831}
1832
Chris Lattner302116a2007-01-31 04:40:28 +00001833
Reid Spenceree3c9912006-12-04 05:19:50 +00001834Constant *
1835ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1836 assert(LHS->getType() == RHS->getType());
1837 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
1838 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1839
Reid Spencer266e42b2006-12-23 06:05:41 +00001840 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
Reid Spenceree3c9912006-12-04 05:19:50 +00001841 return FC; // Fold a few common cases...
1842
1843 // Look up the constant in the table first to ensure uniqueness
1844 std::vector<Constant*> ArgVec;
1845 ArgVec.push_back(LHS);
1846 ArgVec.push_back(RHS);
Reid Spencerb1537492006-12-24 18:42:29 +00001847 // Get the key type with both the opcode and predicate
Reid Spenceree3c9912006-12-04 05:19:50 +00001848 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
Reid Spencer542964f2007-01-11 18:21:29 +00001849 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
Reid Spenceree3c9912006-12-04 05:19:50 +00001850}
1851
1852Constant *
1853ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1854 assert(LHS->getType() == RHS->getType());
1855 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1856
Reid Spencer266e42b2006-12-23 06:05:41 +00001857 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
Reid Spenceree3c9912006-12-04 05:19:50 +00001858 return FC; // Fold a few common cases...
1859
1860 // Look up the constant in the table first to ensure uniqueness
1861 std::vector<Constant*> ArgVec;
1862 ArgVec.push_back(LHS);
1863 ArgVec.push_back(RHS);
Reid Spencerb1537492006-12-24 18:42:29 +00001864 // Get the key type with both the opcode and predicate
Reid Spenceree3c9912006-12-04 05:19:50 +00001865 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
Reid Spencer542964f2007-01-11 18:21:29 +00001866 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
Reid Spenceree3c9912006-12-04 05:19:50 +00001867}
1868
Robert Bocchino23004482006-01-10 19:05:34 +00001869Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
1870 Constant *Idx) {
Robert Bocchinode7f1c92006-01-10 20:03:46 +00001871 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
1872 return FC; // Fold a few common cases...
Robert Bocchino23004482006-01-10 19:05:34 +00001873 // Look up the constant in the table first to ensure uniqueness
1874 std::vector<Constant*> ArgVec(1, Val);
1875 ArgVec.push_back(Idx);
Reid Spenceree3c9912006-12-04 05:19:50 +00001876 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001877 return ExprConstants->getOrCreate(ReqTy, Key);
Robert Bocchino23004482006-01-10 19:05:34 +00001878}
1879
1880Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001881 assert(isa<VectorType>(Val->getType()) &&
Reid Spencer09575ba2007-02-15 03:39:18 +00001882 "Tried to create extractelement operation on non-vector type!");
Reid Spencer8d9336d2006-12-31 05:26:44 +00001883 assert(Idx->getType() == Type::Int32Ty &&
Reid Spencer2546b762007-01-26 07:37:34 +00001884 "Extractelement index must be i32 type!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001885 return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
Robert Bocchino23004482006-01-10 19:05:34 +00001886 Val, Idx);
1887}
Chris Lattnerb50d1352003-10-05 00:17:43 +00001888
Robert Bocchinoca27f032006-01-17 20:07:22 +00001889Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
1890 Constant *Elt, Constant *Idx) {
1891 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
1892 return FC; // Fold a few common cases...
1893 // Look up the constant in the table first to ensure uniqueness
1894 std::vector<Constant*> ArgVec(1, Val);
1895 ArgVec.push_back(Elt);
1896 ArgVec.push_back(Idx);
Reid Spenceree3c9912006-12-04 05:19:50 +00001897 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001898 return ExprConstants->getOrCreate(ReqTy, Key);
Robert Bocchinoca27f032006-01-17 20:07:22 +00001899}
1900
1901Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1902 Constant *Idx) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001903 assert(isa<VectorType>(Val->getType()) &&
Reid Spencer09575ba2007-02-15 03:39:18 +00001904 "Tried to create insertelement operation on non-vector type!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001905 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
Robert Bocchinoca27f032006-01-17 20:07:22 +00001906 && "Insertelement types must match!");
Reid Spencer8d9336d2006-12-31 05:26:44 +00001907 assert(Idx->getType() == Type::Int32Ty &&
Reid Spencer2546b762007-01-26 07:37:34 +00001908 "Insertelement index must be i32 type!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001909 return getInsertElementTy(cast<VectorType>(Val->getType())->getElementType(),
Robert Bocchinoca27f032006-01-17 20:07:22 +00001910 Val, Elt, Idx);
1911}
1912
Chris Lattnerbbe0a422006-04-08 01:18:18 +00001913Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
1914 Constant *V2, Constant *Mask) {
1915 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
1916 return FC; // Fold a few common cases...
1917 // Look up the constant in the table first to ensure uniqueness
1918 std::vector<Constant*> ArgVec(1, V1);
1919 ArgVec.push_back(V2);
1920 ArgVec.push_back(Mask);
Reid Spenceree3c9912006-12-04 05:19:50 +00001921 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001922 return ExprConstants->getOrCreate(ReqTy, Key);
Chris Lattnerbbe0a422006-04-08 01:18:18 +00001923}
1924
1925Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
1926 Constant *Mask) {
1927 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1928 "Invalid shuffle vector constant expr operands!");
1929 return getShuffleVectorTy(V1->getType(), V1, V2, Mask);
1930}
1931
Reid Spencer2eadb532007-01-21 00:29:26 +00001932Constant *ConstantExpr::getZeroValueForNegationExpr(const Type *Ty) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001933 if (const VectorType *PTy = dyn_cast<VectorType>(Ty))
Reid Spencer6598ca82007-01-21 02:29:10 +00001934 if (PTy->getElementType()->isFloatingPoint()) {
1935 std::vector<Constant*> zeros(PTy->getNumElements(),
Dale Johannesen98d3a082007-09-14 22:26:36 +00001936 ConstantFP::getNegativeZero(PTy->getElementType()));
Reid Spencerd84d35b2007-02-15 02:26:10 +00001937 return ConstantVector::get(PTy, zeros);
Reid Spencer6598ca82007-01-21 02:29:10 +00001938 }
Reid Spencer2eadb532007-01-21 00:29:26 +00001939
Dale Johannesen98d3a082007-09-14 22:26:36 +00001940 if (Ty->isFloatingPoint())
1941 return ConstantFP::getNegativeZero(Ty);
Reid Spencer2eadb532007-01-21 00:29:26 +00001942
1943 return Constant::getNullValue(Ty);
1944}
1945
Vikram S. Adve4c485332002-07-15 18:19:33 +00001946// destroyConstant - Remove the constant from the constant table...
1947//
1948void ConstantExpr::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001949 ExprConstants->remove(this);
Vikram S. Adve4c485332002-07-15 18:19:33 +00001950 destroyConstantImpl();
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001951}
1952
Chris Lattner3cd8c562002-07-30 18:54:25 +00001953const char *ConstantExpr::getOpcodeName() const {
1954 return Instruction::getOpcodeName(getOpcode());
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001955}
Reid Spencer1ebe1ab2004-07-17 23:48:33 +00001956
Chris Lattnerc4062ba2005-10-03 21:58:36 +00001957//===----------------------------------------------------------------------===//
1958// replaceUsesOfWithOnConstant implementations
1959
Chris Lattner913849b2007-08-21 00:55:23 +00001960/// replaceUsesOfWithOnConstant - Update this constant array to change uses of
1961/// 'From' to be uses of 'To'. This must update the uniquing data structures
1962/// etc.
1963///
1964/// Note that we intentionally replace all uses of From with To here. Consider
1965/// a large array that uses 'From' 1000 times. By handling this case all here,
1966/// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
1967/// single invocation handles all 1000 uses. Handling them one at a time would
1968/// work, but would be really slow because it would have to unique each updated
1969/// array instance.
Chris Lattnerc4062ba2005-10-03 21:58:36 +00001970void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattner7a1450d2005-10-04 18:13:04 +00001971 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00001972 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
Chris Lattner8760ec72005-10-04 01:17:50 +00001973 Constant *ToC = cast<Constant>(To);
Chris Lattnerdff59112005-10-04 18:47:09 +00001974
Jim Laskeyc03caef2006-07-17 17:38:29 +00001975 std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
Chris Lattnerb64419a2005-10-03 22:51:37 +00001976 Lookup.first.first = getType();
1977 Lookup.second = this;
Chris Lattnerdff59112005-10-04 18:47:09 +00001978
Chris Lattnerb64419a2005-10-03 22:51:37 +00001979 std::vector<Constant*> &Values = Lookup.first.second;
1980 Values.reserve(getNumOperands()); // Build replacement array.
Chris Lattnerdff59112005-10-04 18:47:09 +00001981
Chris Lattner8760ec72005-10-04 01:17:50 +00001982 // Fill values with the modified operands of the constant array. Also,
1983 // compute whether this turns into an all-zeros array.
Chris Lattnerdff59112005-10-04 18:47:09 +00001984 bool isAllZeros = false;
Chris Lattner913849b2007-08-21 00:55:23 +00001985 unsigned NumUpdated = 0;
Chris Lattnerdff59112005-10-04 18:47:09 +00001986 if (!ToC->isNullValue()) {
Chris Lattner913849b2007-08-21 00:55:23 +00001987 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1988 Constant *Val = cast<Constant>(O->get());
1989 if (Val == From) {
1990 Val = ToC;
1991 ++NumUpdated;
1992 }
1993 Values.push_back(Val);
1994 }
Chris Lattnerdff59112005-10-04 18:47:09 +00001995 } else {
1996 isAllZeros = true;
1997 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1998 Constant *Val = cast<Constant>(O->get());
Chris Lattner913849b2007-08-21 00:55:23 +00001999 if (Val == From) {
2000 Val = ToC;
2001 ++NumUpdated;
2002 }
Chris Lattnerdff59112005-10-04 18:47:09 +00002003 Values.push_back(Val);
2004 if (isAllZeros) isAllZeros = Val->isNullValue();
2005 }
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002006 }
2007
Chris Lattnerb64419a2005-10-03 22:51:37 +00002008 Constant *Replacement = 0;
2009 if (isAllZeros) {
2010 Replacement = ConstantAggregateZero::get(getType());
2011 } else {
2012 // Check to see if we have this array type already.
2013 bool Exists;
Jim Laskeyc03caef2006-07-17 17:38:29 +00002014 ArrayConstantsTy::MapTy::iterator I =
Chris Lattner69edc982006-09-28 00:35:06 +00002015 ArrayConstants->InsertOrGetItem(Lookup, Exists);
Chris Lattnerb64419a2005-10-03 22:51:37 +00002016
2017 if (Exists) {
2018 Replacement = I->second;
2019 } else {
2020 // Okay, the new shape doesn't exist in the system yet. Instead of
2021 // creating a new constant array, inserting it, replaceallusesof'ing the
2022 // old with the new, then deleting the old... just update the current one
2023 // in place!
Chris Lattner69edc982006-09-28 00:35:06 +00002024 ArrayConstants->MoveConstantToNewSlot(this, I);
Chris Lattnerb64419a2005-10-03 22:51:37 +00002025
Chris Lattner913849b2007-08-21 00:55:23 +00002026 // Update to the new value. Optimize for the case when we have a single
2027 // operand that we're changing, but handle bulk updates efficiently.
2028 if (NumUpdated == 1) {
2029 unsigned OperandToUpdate = U-OperandList;
2030 assert(getOperand(OperandToUpdate) == From &&
2031 "ReplaceAllUsesWith broken!");
2032 setOperand(OperandToUpdate, ToC);
2033 } else {
2034 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2035 if (getOperand(i) == From)
2036 setOperand(i, ToC);
2037 }
Chris Lattnerb64419a2005-10-03 22:51:37 +00002038 return;
2039 }
2040 }
2041
2042 // Otherwise, I do need to replace this with an existing value.
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002043 assert(Replacement != this && "I didn't contain From!");
2044
Chris Lattner7a1450d2005-10-04 18:13:04 +00002045 // Everyone using this now uses the replacement.
2046 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002047
2048 // Delete the old constant!
2049 destroyConstant();
2050}
2051
2052void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002053 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002054 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
Chris Lattner8760ec72005-10-04 01:17:50 +00002055 Constant *ToC = cast<Constant>(To);
2056
Chris Lattnerdff59112005-10-04 18:47:09 +00002057 unsigned OperandToUpdate = U-OperandList;
2058 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2059
Jim Laskeyc03caef2006-07-17 17:38:29 +00002060 std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
Chris Lattner8760ec72005-10-04 01:17:50 +00002061 Lookup.first.first = getType();
2062 Lookup.second = this;
2063 std::vector<Constant*> &Values = Lookup.first.second;
2064 Values.reserve(getNumOperands()); // Build replacement struct.
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002065
Chris Lattnerdff59112005-10-04 18:47:09 +00002066
Chris Lattner8760ec72005-10-04 01:17:50 +00002067 // Fill values with the modified operands of the constant struct. Also,
2068 // compute whether this turns into an all-zeros struct.
Chris Lattnerdff59112005-10-04 18:47:09 +00002069 bool isAllZeros = false;
2070 if (!ToC->isNullValue()) {
2071 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
2072 Values.push_back(cast<Constant>(O->get()));
2073 } else {
2074 isAllZeros = true;
2075 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2076 Constant *Val = cast<Constant>(O->get());
2077 Values.push_back(Val);
2078 if (isAllZeros) isAllZeros = Val->isNullValue();
2079 }
Chris Lattner8760ec72005-10-04 01:17:50 +00002080 }
Chris Lattnerdff59112005-10-04 18:47:09 +00002081 Values[OperandToUpdate] = ToC;
2082
Chris Lattner8760ec72005-10-04 01:17:50 +00002083 Constant *Replacement = 0;
2084 if (isAllZeros) {
2085 Replacement = ConstantAggregateZero::get(getType());
2086 } else {
2087 // Check to see if we have this array type already.
2088 bool Exists;
Jim Laskeyc03caef2006-07-17 17:38:29 +00002089 StructConstantsTy::MapTy::iterator I =
Chris Lattner69edc982006-09-28 00:35:06 +00002090 StructConstants->InsertOrGetItem(Lookup, Exists);
Chris Lattner8760ec72005-10-04 01:17:50 +00002091
2092 if (Exists) {
2093 Replacement = I->second;
2094 } else {
2095 // Okay, the new shape doesn't exist in the system yet. Instead of
2096 // creating a new constant struct, inserting it, replaceallusesof'ing the
2097 // old with the new, then deleting the old... just update the current one
2098 // in place!
Chris Lattner69edc982006-09-28 00:35:06 +00002099 StructConstants->MoveConstantToNewSlot(this, I);
Chris Lattner8760ec72005-10-04 01:17:50 +00002100
Chris Lattnerdff59112005-10-04 18:47:09 +00002101 // Update to the new value.
2102 setOperand(OperandToUpdate, ToC);
Chris Lattner8760ec72005-10-04 01:17:50 +00002103 return;
2104 }
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002105 }
2106
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002107 assert(Replacement != this && "I didn't contain From!");
2108
Chris Lattner7a1450d2005-10-04 18:13:04 +00002109 // Everyone using this now uses the replacement.
2110 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002111
2112 // Delete the old constant!
2113 destroyConstant();
2114}
2115
Reid Spencerd84d35b2007-02-15 02:26:10 +00002116void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002117 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002118 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2119
2120 std::vector<Constant*> Values;
2121 Values.reserve(getNumOperands()); // Build replacement array...
2122 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2123 Constant *Val = getOperand(i);
2124 if (Val == From) Val = cast<Constant>(To);
2125 Values.push_back(Val);
2126 }
2127
Reid Spencerd84d35b2007-02-15 02:26:10 +00002128 Constant *Replacement = ConstantVector::get(getType(), Values);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002129 assert(Replacement != this && "I didn't contain From!");
2130
Chris Lattner7a1450d2005-10-04 18:13:04 +00002131 // Everyone using this now uses the replacement.
2132 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002133
2134 // Delete the old constant!
2135 destroyConstant();
2136}
2137
2138void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002139 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002140 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2141 Constant *To = cast<Constant>(ToV);
2142
2143 Constant *Replacement = 0;
2144 if (getOpcode() == Instruction::GetElementPtr) {
Chris Lattnerb5d70302007-02-19 20:01:23 +00002145 SmallVector<Constant*, 8> Indices;
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002146 Constant *Pointer = getOperand(0);
2147 Indices.reserve(getNumOperands()-1);
2148 if (Pointer == From) Pointer = To;
2149
2150 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2151 Constant *Val = getOperand(i);
2152 if (Val == From) Val = To;
2153 Indices.push_back(Val);
2154 }
Chris Lattnerb5d70302007-02-19 20:01:23 +00002155 Replacement = ConstantExpr::getGetElementPtr(Pointer,
2156 &Indices[0], Indices.size());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002157 } else if (isCast()) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002158 assert(getOperand(0) == From && "Cast only has one use!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002159 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002160 } else if (getOpcode() == Instruction::Select) {
2161 Constant *C1 = getOperand(0);
2162 Constant *C2 = getOperand(1);
2163 Constant *C3 = getOperand(2);
2164 if (C1 == From) C1 = To;
2165 if (C2 == From) C2 = To;
2166 if (C3 == From) C3 = To;
2167 Replacement = ConstantExpr::getSelect(C1, C2, C3);
Robert Bocchino23004482006-01-10 19:05:34 +00002168 } else if (getOpcode() == Instruction::ExtractElement) {
2169 Constant *C1 = getOperand(0);
2170 Constant *C2 = getOperand(1);
2171 if (C1 == From) C1 = To;
2172 if (C2 == From) C2 = To;
2173 Replacement = ConstantExpr::getExtractElement(C1, C2);
Chris Lattnera93b4b52006-04-08 05:09:48 +00002174 } else if (getOpcode() == Instruction::InsertElement) {
2175 Constant *C1 = getOperand(0);
2176 Constant *C2 = getOperand(1);
2177 Constant *C3 = getOperand(1);
2178 if (C1 == From) C1 = To;
2179 if (C2 == From) C2 = To;
2180 if (C3 == From) C3 = To;
2181 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2182 } else if (getOpcode() == Instruction::ShuffleVector) {
2183 Constant *C1 = getOperand(0);
2184 Constant *C2 = getOperand(1);
2185 Constant *C3 = getOperand(2);
2186 if (C1 == From) C1 = To;
2187 if (C2 == From) C2 = To;
2188 if (C3 == From) C3 = To;
2189 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
Reid Spenceree3c9912006-12-04 05:19:50 +00002190 } else if (isCompare()) {
2191 Constant *C1 = getOperand(0);
2192 Constant *C2 = getOperand(1);
2193 if (C1 == From) C1 = To;
2194 if (C2 == From) C2 = To;
2195 if (getOpcode() == Instruction::ICmp)
2196 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2197 else
2198 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002199 } else if (getNumOperands() == 2) {
2200 Constant *C1 = getOperand(0);
2201 Constant *C2 = getOperand(1);
2202 if (C1 == From) C1 = To;
2203 if (C2 == From) C2 = To;
2204 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2205 } else {
2206 assert(0 && "Unknown ConstantExpr type!");
2207 return;
2208 }
2209
2210 assert(Replacement != this && "I didn't contain From!");
2211
Chris Lattner7a1450d2005-10-04 18:13:04 +00002212 // Everyone using this now uses the replacement.
2213 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002214
2215 // Delete the old constant!
2216 destroyConstant();
2217}
2218
2219
Jim Laskey2698f0d2006-03-08 18:11:07 +00002220/// getStringValue - Turn an LLVM constant pointer that eventually points to a
2221/// global into a string value. Return an empty string if we can't do it.
Evan Cheng38280c02006-03-10 23:52:03 +00002222/// Parameter Chop determines if the result is chopped at the first null
2223/// terminator.
Jim Laskey2698f0d2006-03-08 18:11:07 +00002224///
Evan Cheng38280c02006-03-10 23:52:03 +00002225std::string Constant::getStringValue(bool Chop, unsigned Offset) {
Jim Laskey2698f0d2006-03-08 18:11:07 +00002226 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(this)) {
2227 if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
2228 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
2229 if (Init->isString()) {
2230 std::string Result = Init->getAsString();
2231 if (Offset < Result.size()) {
2232 // If we are pointing INTO The string, erase the beginning...
2233 Result.erase(Result.begin(), Result.begin()+Offset);
2234
2235 // Take off the null terminator, and any string fragments after it.
Evan Cheng38280c02006-03-10 23:52:03 +00002236 if (Chop) {
2237 std::string::size_type NullPos = Result.find_first_of((char)0);
2238 if (NullPos != std::string::npos)
2239 Result.erase(Result.begin()+NullPos, Result.end());
2240 }
Jim Laskey2698f0d2006-03-08 18:11:07 +00002241 return Result;
2242 }
2243 }
2244 }
2245 } else if (Constant *C = dyn_cast<Constant>(this)) {
2246 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
Evan Cheng2c5e5302006-03-11 00:13:10 +00002247 return GV->getStringValue(Chop, Offset);
Jim Laskey2698f0d2006-03-08 18:11:07 +00002248 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2249 if (CE->getOpcode() == Instruction::GetElementPtr) {
2250 // Turn a gep into the specified offset.
2251 if (CE->getNumOperands() == 3 &&
2252 cast<Constant>(CE->getOperand(1))->isNullValue() &&
2253 isa<ConstantInt>(CE->getOperand(2))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002254 Offset += cast<ConstantInt>(CE->getOperand(2))->getZExtValue();
Evan Cheng2c5e5302006-03-11 00:13:10 +00002255 return CE->getOperand(0)->getStringValue(Chop, Offset);
Jim Laskey2698f0d2006-03-08 18:11:07 +00002256 }
2257 }
2258 }
2259 }
2260 return "";
2261}