blob: f63a5bc1c56a04c43b1c15060b75f1502f00608a [file] [log] [blame]
Chris Lattner2b383d2e2003-05-13 21:37:02 +00001//===-- Constants.cpp - Implement Constant nodes --------------------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner2f7c9632001-06-06 20:29:01 +00009//
Chris Lattner3462ae32001-12-03 22:26:30 +000010// This file implements the Constant* classes...
Chris Lattner2f7c9632001-06-06 20:29:01 +000011//
12//===----------------------------------------------------------------------===//
13
Chris Lattnerca142372002-04-28 19:55:58 +000014#include "llvm/Constants.h"
Chris Lattner33e93b82007-02-27 03:05:06 +000015#include "ConstantFold.h"
Chris Lattner2f7c9632001-06-06 20:29:01 +000016#include "llvm/DerivedTypes.h"
Reid Spencer1ebe1ab2004-07-17 23:48:33 +000017#include "llvm/GlobalValue.h"
Misha Brukman63b38bd2004-07-29 17:30:56 +000018#include "llvm/Instructions.h"
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +000019#include "llvm/MDNode.h"
Chris Lattnerd7a73302001-10-13 06:57:33 +000020#include "llvm/Module.h"
Nick Lewycky49f89192009-04-04 07:22:01 +000021#include "llvm/ADT/FoldingSet.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000022#include "llvm/ADT/StringExtras.h"
Nick Lewycky49f89192009-04-04 07:22:01 +000023#include "llvm/ADT/StringMap.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000024#include "llvm/Support/Compiler.h"
Bill Wendling6a462f12006-11-17 08:03:48 +000025#include "llvm/Support/Debug.h"
Chris Lattner69edc982006-09-28 00:35:06 +000026#include "llvm/Support/ManagedStatic.h"
Bill Wendling6a462f12006-11-17 08:03:48 +000027#include "llvm/Support/MathExtras.h"
Chris Lattnera80bf0b2007-02-20 06:39:57 +000028#include "llvm/ADT/DenseMap.h"
Chris Lattnerb5d70302007-02-19 20:01:23 +000029#include "llvm/ADT/SmallVector.h"
Chris Lattner2f7c9632001-06-06 20:29:01 +000030#include <algorithm>
Reid Spencer3aaaa0b2007-02-05 20:47:22 +000031#include <map>
Chris Lattner189d19f2003-11-21 20:23:48 +000032using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000033
Chris Lattner2f7c9632001-06-06 20:29:01 +000034//===----------------------------------------------------------------------===//
Chris Lattner3462ae32001-12-03 22:26:30 +000035// Constant Class
Chris Lattner2f7c9632001-06-06 20:29:01 +000036//===----------------------------------------------------------------------===//
37
Chris Lattner3462ae32001-12-03 22:26:30 +000038void Constant::destroyConstantImpl() {
39 // When a Constant is destroyed, there may be lingering
Chris Lattnerd7a73302001-10-13 06:57:33 +000040 // references to the constant by other constants in the constant pool. These
Misha Brukmanbe372b92003-08-21 22:14:26 +000041 // constants are implicitly dependent on the module that is being deleted,
Chris Lattnerd7a73302001-10-13 06:57:33 +000042 // but they don't know that. Because we only find out when the CPV is
43 // deleted, we must now notify all of our users (that should only be
Chris Lattner3462ae32001-12-03 22:26:30 +000044 // Constants) that they are, in fact, invalid now and should be deleted.
Chris Lattnerd7a73302001-10-13 06:57:33 +000045 //
46 while (!use_empty()) {
47 Value *V = use_back();
48#ifndef NDEBUG // Only in -g mode...
Chris Lattnerd9f4ac662002-07-18 00:14:50 +000049 if (!isa<Constant>(V))
Bill Wendling6a462f12006-11-17 08:03:48 +000050 DOUT << "While deleting: " << *this
51 << "\n\nUse still stuck around after Def is destroyed: "
52 << *V << "\n\n";
Chris Lattnerd7a73302001-10-13 06:57:33 +000053#endif
Vikram S. Adve4e537b22002-07-14 23:13:17 +000054 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
Reid Spencer1ebe1ab2004-07-17 23:48:33 +000055 Constant *CV = cast<Constant>(V);
56 CV->destroyConstant();
Chris Lattnerd7a73302001-10-13 06:57:33 +000057
58 // The constant should remove itself from our use list...
Vikram S. Adve4e537b22002-07-14 23:13:17 +000059 assert((use_empty() || use_back() != V) && "Constant not removed!");
Chris Lattnerd7a73302001-10-13 06:57:33 +000060 }
61
62 // Value has no outstanding references it is safe to delete it now...
63 delete this;
Chris Lattner38569342001-10-01 20:11:19 +000064}
Chris Lattner2f7c9632001-06-06 20:29:01 +000065
Chris Lattner23dd1f62006-10-20 00:27:06 +000066/// canTrap - Return true if evaluation of this constant could trap. This is
67/// true for things like constant expressions that could divide by zero.
68bool Constant::canTrap() const {
69 assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
70 // The only thing that could possibly trap are constant exprs.
71 const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
72 if (!CE) return false;
73
74 // ConstantExpr traps if any operands can trap.
75 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
76 if (getOperand(i)->canTrap())
77 return true;
78
79 // Otherwise, only specific operations can trap.
80 switch (CE->getOpcode()) {
81 default:
82 return false;
Reid Spencer7e80b0b2006-10-26 06:15:43 +000083 case Instruction::UDiv:
84 case Instruction::SDiv:
85 case Instruction::FDiv:
Reid Spencer7eb55b32006-11-02 01:53:59 +000086 case Instruction::URem:
87 case Instruction::SRem:
88 case Instruction::FRem:
Chris Lattner23dd1f62006-10-20 00:27:06 +000089 // Div and rem can trap if the RHS is not known to be non-zero.
90 if (!isa<ConstantInt>(getOperand(1)) || getOperand(1)->isNullValue())
91 return true;
92 return false;
93 }
94}
95
Anton Korobeynikov7437b592009-03-29 17:13:18 +000096/// ContainsRelocations - Return true if the constant value contains relocations
97/// which cannot be resolved at compile time. Kind argument is used to filter
98/// only 'interesting' sorts of relocations.
99bool Constant::ContainsRelocations(unsigned Kind) const {
100 if (const GlobalValue* GV = dyn_cast<GlobalValue>(this)) {
101 bool isLocal = GV->hasLocalLinkage();
102 if ((Kind & Reloc::Local) && isLocal) {
103 // Global has local linkage and 'local' kind of relocations are
104 // requested
105 return true;
106 }
107
108 if ((Kind & Reloc::Global) && !isLocal) {
109 // Global has non-local linkage and 'global' kind of relocations are
110 // requested
111 return true;
112 }
Anton Korobeynikov255a3cb2009-03-30 15:28:21 +0000113
114 return false;
Anton Korobeynikov7437b592009-03-29 17:13:18 +0000115 }
116
Evan Chengf9e003b2007-03-08 00:59:12 +0000117 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
Anton Korobeynikovd5e8e932009-03-30 15:28:00 +0000118 if (getOperand(i)->ContainsRelocations(Kind))
Evan Chengf9e003b2007-03-08 00:59:12 +0000119 return true;
Anton Korobeynikov7437b592009-03-29 17:13:18 +0000120
Evan Chengf9e003b2007-03-08 00:59:12 +0000121 return false;
122}
123
Chris Lattnerb1585a92002-08-13 17:50:20 +0000124// Static constructor to create a '0' constant of arbitrary type...
125Constant *Constant::getNullValue(const Type *Ty) {
Dale Johannesen98d3a082007-09-14 22:26:36 +0000126 static uint64_t zero[2] = {0, 0};
Chris Lattner6b727592004-06-17 18:19:28 +0000127 switch (Ty->getTypeID()) {
Chris Lattnerdbcb0d32007-02-20 05:46:39 +0000128 case Type::IntegerTyID:
129 return ConstantInt::get(Ty, 0);
130 case Type::FloatTyID:
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000131 return ConstantFP::get(APFloat(APInt(32, 0)));
Chris Lattnerdbcb0d32007-02-20 05:46:39 +0000132 case Type::DoubleTyID:
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000133 return ConstantFP::get(APFloat(APInt(64, 0)));
Dale Johannesenbdad8092007-08-09 22:51:36 +0000134 case Type::X86_FP80TyID:
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000135 return ConstantFP::get(APFloat(APInt(80, 2, zero)));
Dale Johannesenbdad8092007-08-09 22:51:36 +0000136 case Type::FP128TyID:
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000137 return ConstantFP::get(APFloat(APInt(128, 2, zero), true));
Dale Johannesen98d3a082007-09-14 22:26:36 +0000138 case Type::PPC_FP128TyID:
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000139 return ConstantFP::get(APFloat(APInt(128, 2, zero)));
Misha Brukmanb1c93172005-04-21 23:48:37 +0000140 case Type::PointerTyID:
Chris Lattnerb1585a92002-08-13 17:50:20 +0000141 return ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattner9fba3da2004-02-15 05:53:04 +0000142 case Type::StructTyID:
143 case Type::ArrayTyID:
Reid Spencerd84d35b2007-02-15 02:26:10 +0000144 case Type::VectorTyID:
Chris Lattner9fba3da2004-02-15 05:53:04 +0000145 return ConstantAggregateZero::get(Ty);
Chris Lattnerb1585a92002-08-13 17:50:20 +0000146 default:
Reid Spencercf394bf2004-07-04 11:51:24 +0000147 // Function, Label, or Opaque type?
148 assert(!"Cannot create a null constant of that type!");
Chris Lattnerb1585a92002-08-13 17:50:20 +0000149 return 0;
150 }
151}
152
Chris Lattner72e39582007-06-15 06:10:53 +0000153Constant *Constant::getAllOnesValue(const Type *Ty) {
154 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
155 return ConstantInt::get(APInt::getAllOnesValue(ITy->getBitWidth()));
156 return ConstantVector::getAllOnesValue(cast<VectorType>(Ty));
157}
Chris Lattnerb1585a92002-08-13 17:50:20 +0000158
159// Static constructor to create an integral constant with all bits set
Zhou Sheng75b871f2007-01-11 12:24:14 +0000160ConstantInt *ConstantInt::getAllOnesValue(const Type *Ty) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000161 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
Reid Spencerd1bbfa52007-03-01 19:30:34 +0000162 return ConstantInt::get(APInt::getAllOnesValue(ITy->getBitWidth()));
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000163 return 0;
Chris Lattnerb1585a92002-08-13 17:50:20 +0000164}
165
Dan Gohman30978072007-05-24 14:36:04 +0000166/// @returns the value for a vector integer constant of the given type that
Chris Lattnerecab54c2007-01-04 01:49:26 +0000167/// has all its bits set to true.
168/// @brief Get the all ones value
Reid Spencerd84d35b2007-02-15 02:26:10 +0000169ConstantVector *ConstantVector::getAllOnesValue(const VectorType *Ty) {
Chris Lattnerecab54c2007-01-04 01:49:26 +0000170 std::vector<Constant*> Elts;
171 Elts.resize(Ty->getNumElements(),
Zhou Sheng75b871f2007-01-11 12:24:14 +0000172 ConstantInt::getAllOnesValue(Ty->getElementType()));
Dan Gohman30978072007-05-24 14:36:04 +0000173 assert(Elts[0] && "Not a vector integer type!");
Reid Spencerd84d35b2007-02-15 02:26:10 +0000174 return cast<ConstantVector>(ConstantVector::get(Elts));
Chris Lattnerecab54c2007-01-04 01:49:26 +0000175}
176
177
Chris Lattner2105d662008-07-10 00:28:11 +0000178/// getVectorElements - This method, which is only valid on constant of vector
179/// type, returns the elements of the vector in the specified smallvector.
Chris Lattnerc5098a22008-07-14 05:10:41 +0000180/// This handles breaking down a vector undef into undef elements, etc. For
181/// constant exprs and other cases we can't handle, we return an empty vector.
Chris Lattner2105d662008-07-10 00:28:11 +0000182void Constant::getVectorElements(SmallVectorImpl<Constant*> &Elts) const {
183 assert(isa<VectorType>(getType()) && "Not a vector constant!");
184
185 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this)) {
186 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i)
187 Elts.push_back(CV->getOperand(i));
188 return;
189 }
190
191 const VectorType *VT = cast<VectorType>(getType());
192 if (isa<ConstantAggregateZero>(this)) {
193 Elts.assign(VT->getNumElements(),
194 Constant::getNullValue(VT->getElementType()));
195 return;
196 }
197
Chris Lattnerc5098a22008-07-14 05:10:41 +0000198 if (isa<UndefValue>(this)) {
199 Elts.assign(VT->getNumElements(), UndefValue::get(VT->getElementType()));
200 return;
201 }
202
203 // Unknown type, must be constant expr etc.
Chris Lattner2105d662008-07-10 00:28:11 +0000204}
205
206
207
Chris Lattner2f7c9632001-06-06 20:29:01 +0000208//===----------------------------------------------------------------------===//
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000209// ConstantInt
Chris Lattner2f7c9632001-06-06 20:29:01 +0000210//===----------------------------------------------------------------------===//
211
Reid Spencerb31bffe2007-02-26 23:54:03 +0000212ConstantInt::ConstantInt(const IntegerType *Ty, const APInt& V)
Chris Lattner5db2f472007-02-20 05:55:46 +0000213 : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
Reid Spencerb31bffe2007-02-26 23:54:03 +0000214 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
Chris Lattner2f7c9632001-06-06 20:29:01 +0000215}
216
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000217ConstantInt *ConstantInt::TheTrueVal = 0;
218ConstantInt *ConstantInt::TheFalseVal = 0;
219
220namespace llvm {
221 void CleanupTrueFalse(void *) {
222 ConstantInt::ResetTrueFalse();
223 }
224}
225
226static ManagedCleanup<llvm::CleanupTrueFalse> TrueFalseCleanup;
227
228ConstantInt *ConstantInt::CreateTrueFalseVals(bool WhichOne) {
229 assert(TheTrueVal == 0 && TheFalseVal == 0);
230 TheTrueVal = get(Type::Int1Ty, 1);
231 TheFalseVal = get(Type::Int1Ty, 0);
232
233 // Ensure that llvm_shutdown nulls out TheTrueVal/TheFalseVal.
234 TrueFalseCleanup.Register();
235
236 return WhichOne ? TheTrueVal : TheFalseVal;
237}
238
239
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000240namespace {
Reid Spencerb31bffe2007-02-26 23:54:03 +0000241 struct DenseMapAPIntKeyInfo {
242 struct KeyTy {
243 APInt val;
244 const Type* type;
245 KeyTy(const APInt& V, const Type* Ty) : val(V), type(Ty) {}
246 KeyTy(const KeyTy& that) : val(that.val), type(that.type) {}
247 bool operator==(const KeyTy& that) const {
248 return type == that.type && this->val == that.val;
249 }
250 bool operator!=(const KeyTy& that) const {
251 return !this->operator==(that);
252 }
253 };
254 static inline KeyTy getEmptyKey() { return KeyTy(APInt(1,0), 0); }
255 static inline KeyTy getTombstoneKey() { return KeyTy(APInt(1,1), 0); }
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000256 static unsigned getHashValue(const KeyTy &Key) {
Chris Lattner0625bd62007-09-17 18:34:04 +0000257 return DenseMapInfo<void*>::getHashValue(Key.type) ^
Reid Spencerb31bffe2007-02-26 23:54:03 +0000258 Key.val.getHashValue();
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000259 }
Chris Lattner0625bd62007-09-17 18:34:04 +0000260 static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
261 return LHS == RHS;
262 }
Dale Johannesena719a602007-08-24 00:56:33 +0000263 static bool isPod() { return false; }
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000264 };
265}
266
267
Reid Spencerb31bffe2007-02-26 23:54:03 +0000268typedef DenseMap<DenseMapAPIntKeyInfo::KeyTy, ConstantInt*,
269 DenseMapAPIntKeyInfo> IntMapTy;
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000270static ManagedStatic<IntMapTy> IntConstants;
271
Dan Gohman7ccc52f2009-06-15 22:12:54 +0000272ConstantInt *ConstantInt::get(const IntegerType *Ty,
273 uint64_t V, bool isSigned) {
274 return get(APInt(Ty->getBitWidth(), V, isSigned));
275}
276
277Constant *ConstantInt::get(const Type *Ty, uint64_t V, bool isSigned) {
278 Constant *C = get(cast<IntegerType>(Ty->getScalarType()), V, isSigned);
279
280 // For vectors, broadcast the value.
281 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
282 return
283 ConstantVector::get(std::vector<Constant *>(VTy->getNumElements(), C));
284
285 return C;
Reid Spencerb31bffe2007-02-26 23:54:03 +0000286}
287
Reid Spencerd1bbfa52007-03-01 19:30:34 +0000288// Get a ConstantInt from an APInt. Note that the value stored in the DenseMap
Dan Gohmanb3efe032008-02-07 02:30:40 +0000289// as the key, is a DenseMapAPIntKeyInfo::KeyTy which has provided the
Reid Spencerb31bffe2007-02-26 23:54:03 +0000290// operator== and operator!= to ensure that the DenseMap doesn't attempt to
291// compare APInt's of different widths, which would violate an APInt class
292// invariant which generates an assertion.
Reid Spencerd1bbfa52007-03-01 19:30:34 +0000293ConstantInt *ConstantInt::get(const APInt& V) {
294 // Get the corresponding integer type for the bit width of the value.
295 const IntegerType *ITy = IntegerType::get(V.getBitWidth());
Reid Spencerb31bffe2007-02-26 23:54:03 +0000296 // get an existing value or the insertion position
Reid Spencerd1bbfa52007-03-01 19:30:34 +0000297 DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
Reid Spencerb31bffe2007-02-26 23:54:03 +0000298 ConstantInt *&Slot = (*IntConstants)[Key];
299 // if it exists, return it.
300 if (Slot)
301 return Slot;
302 // otherwise create a new one, insert it, and return it.
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000303 return Slot = new ConstantInt(ITy, V);
304}
305
Dan Gohman7ccc52f2009-06-15 22:12:54 +0000306Constant *ConstantInt::get(const Type *Ty, const APInt &V) {
307 ConstantInt *C = ConstantInt::get(V);
308 assert(C->getType() == Ty->getScalarType() &&
309 "ConstantInt type doesn't match the type implied by its value!");
310
311 // For vectors, broadcast the value.
312 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
313 return
314 ConstantVector::get(std::vector<Constant *>(VTy->getNumElements(), C));
315
316 return C;
317}
318
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000319//===----------------------------------------------------------------------===//
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000320// ConstantFP
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000321//===----------------------------------------------------------------------===//
322
Chris Lattner98bd9392008-04-09 06:38:30 +0000323static const fltSemantics *TypeToFloatSemantics(const Type *Ty) {
324 if (Ty == Type::FloatTy)
325 return &APFloat::IEEEsingle;
326 if (Ty == Type::DoubleTy)
327 return &APFloat::IEEEdouble;
328 if (Ty == Type::X86_FP80Ty)
329 return &APFloat::x87DoubleExtended;
330 else if (Ty == Type::FP128Ty)
331 return &APFloat::IEEEquad;
332
333 assert(Ty == Type::PPC_FP128Ty && "Unknown FP format");
334 return &APFloat::PPCDoubleDouble;
335}
336
Dale Johannesend246b2c2007-08-30 00:23:21 +0000337ConstantFP::ConstantFP(const Type *Ty, const APFloat& V)
338 : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
Chris Lattner98bd9392008-04-09 06:38:30 +0000339 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
340 "FP type Mismatch");
Chris Lattner2f7c9632001-06-06 20:29:01 +0000341}
342
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000343bool ConstantFP::isNullValue() const {
Dale Johannesena719a602007-08-24 00:56:33 +0000344 return Val.isZero() && !Val.isNegative();
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000345}
346
Dale Johannesen98d3a082007-09-14 22:26:36 +0000347ConstantFP *ConstantFP::getNegativeZero(const Type *Ty) {
348 APFloat apf = cast <ConstantFP>(Constant::getNullValue(Ty))->getValueAPF();
349 apf.changeSign();
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000350 return ConstantFP::get(apf);
Dale Johannesen98d3a082007-09-14 22:26:36 +0000351}
352
Dale Johannesend246b2c2007-08-30 00:23:21 +0000353bool ConstantFP::isExactlyValue(const APFloat& V) const {
354 return Val.bitwiseIsEqual(V);
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000355}
356
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000357namespace {
Dale Johannesena719a602007-08-24 00:56:33 +0000358 struct DenseMapAPFloatKeyInfo {
Dale Johannesenbdea32d2007-08-24 22:09:56 +0000359 struct KeyTy {
360 APFloat val;
361 KeyTy(const APFloat& V) : val(V){}
362 KeyTy(const KeyTy& that) : val(that.val) {}
363 bool operator==(const KeyTy& that) const {
364 return this->val.bitwiseIsEqual(that.val);
365 }
366 bool operator!=(const KeyTy& that) const {
367 return !this->operator==(that);
368 }
369 };
370 static inline KeyTy getEmptyKey() {
371 return KeyTy(APFloat(APFloat::Bogus,1));
Reid Spencerb31bffe2007-02-26 23:54:03 +0000372 }
Dale Johannesenbdea32d2007-08-24 22:09:56 +0000373 static inline KeyTy getTombstoneKey() {
374 return KeyTy(APFloat(APFloat::Bogus,2));
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000375 }
Dale Johannesenbdea32d2007-08-24 22:09:56 +0000376 static unsigned getHashValue(const KeyTy &Key) {
377 return Key.val.getHashValue();
Dale Johannesena719a602007-08-24 00:56:33 +0000378 }
Chris Lattner0625bd62007-09-17 18:34:04 +0000379 static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
380 return LHS == RHS;
381 }
Dale Johannesena719a602007-08-24 00:56:33 +0000382 static bool isPod() { return false; }
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000383 };
384}
385
386//---- ConstantFP::get() implementation...
387//
Dale Johannesenbdea32d2007-08-24 22:09:56 +0000388typedef DenseMap<DenseMapAPFloatKeyInfo::KeyTy, ConstantFP*,
Dale Johannesena719a602007-08-24 00:56:33 +0000389 DenseMapAPFloatKeyInfo> FPMapTy;
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000390
Dale Johannesena719a602007-08-24 00:56:33 +0000391static ManagedStatic<FPMapTy> FPConstants;
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000392
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000393ConstantFP *ConstantFP::get(const APFloat &V) {
Dale Johannesend246b2c2007-08-30 00:23:21 +0000394 DenseMapAPFloatKeyInfo::KeyTy Key(V);
395 ConstantFP *&Slot = (*FPConstants)[Key];
396 if (Slot) return Slot;
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000397
398 const Type *Ty;
399 if (&V.getSemantics() == &APFloat::IEEEsingle)
400 Ty = Type::FloatTy;
401 else if (&V.getSemantics() == &APFloat::IEEEdouble)
402 Ty = Type::DoubleTy;
403 else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
404 Ty = Type::X86_FP80Ty;
405 else if (&V.getSemantics() == &APFloat::IEEEquad)
406 Ty = Type::FP128Ty;
407 else {
408 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble&&"Unknown FP format");
409 Ty = Type::PPC_FP128Ty;
410 }
411
Dale Johannesend246b2c2007-08-30 00:23:21 +0000412 return Slot = new ConstantFP(Ty, V);
413}
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000414
Chris Lattner98bd9392008-04-09 06:38:30 +0000415/// get() - This returns a constant fp for the specified value in the
416/// specified type. This should only be used for simple constant values like
417/// 2.0/1.0 etc, that are known-valid both as double and as the target format.
Dan Gohman7ccc52f2009-06-15 22:12:54 +0000418Constant *ConstantFP::get(const Type *Ty, double V) {
Chris Lattner98bd9392008-04-09 06:38:30 +0000419 APFloat FV(V);
Dale Johannesen4f0bd682008-10-09 23:00:39 +0000420 bool ignored;
Dan Gohman7ccc52f2009-06-15 22:12:54 +0000421 FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
422 APFloat::rmNearestTiesToEven, &ignored);
423 Constant *C = get(FV);
424
425 // For vectors, broadcast the value.
426 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
427 return
428 ConstantVector::get(std::vector<Constant *>(VTy->getNumElements(), C));
429
430 return C;
Chris Lattner98bd9392008-04-09 06:38:30 +0000431}
432
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000433//===----------------------------------------------------------------------===//
434// ConstantXXX Classes
435//===----------------------------------------------------------------------===//
436
437
Chris Lattner3462ae32001-12-03 22:26:30 +0000438ConstantArray::ConstantArray(const ArrayType *T,
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000439 const std::vector<Constant*> &V)
Gabor Greiff6caff662008-05-10 08:32:32 +0000440 : Constant(T, ConstantArrayVal,
441 OperandTraits<ConstantArray>::op_end(this) - V.size(),
442 V.size()) {
Alkis Evlogimenos0507ffe2004-09-15 02:32:15 +0000443 assert(V.size() == T->getNumElements() &&
444 "Invalid initializer vector for constant array");
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000445 Use *OL = OperandList;
Chris Lattner0144fad2005-10-03 21:56:24 +0000446 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
447 I != E; ++I, ++OL) {
Chris Lattner20a24452005-10-07 05:23:36 +0000448 Constant *C = *I;
449 assert((C->getType() == T->getElementType() ||
Alkis Evlogimenoscb031d92004-09-10 04:16:59 +0000450 (T->isAbstract() &&
Chris Lattner20a24452005-10-07 05:23:36 +0000451 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
Alkis Evlogimenoscb031d92004-09-10 04:16:59 +0000452 "Initializer for array element doesn't match array element type!");
Gabor Greif2d3024d2008-05-26 21:33:52 +0000453 *OL = C;
Chris Lattner2f7c9632001-06-06 20:29:01 +0000454 }
455}
456
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000457
Chris Lattner3462ae32001-12-03 22:26:30 +0000458ConstantStruct::ConstantStruct(const StructType *T,
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000459 const std::vector<Constant*> &V)
Gabor Greiff6caff662008-05-10 08:32:32 +0000460 : Constant(T, ConstantStructVal,
461 OperandTraits<ConstantStruct>::op_end(this) - V.size(),
462 V.size()) {
Chris Lattnerac6db752004-02-09 04:37:31 +0000463 assert(V.size() == T->getNumElements() &&
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000464 "Invalid initializer vector for constant structure");
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000465 Use *OL = OperandList;
Chris Lattner0144fad2005-10-03 21:56:24 +0000466 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
467 I != E; ++I, ++OL) {
Chris Lattner20a24452005-10-07 05:23:36 +0000468 Constant *C = *I;
469 assert((C->getType() == T->getElementType(I-V.begin()) ||
Chris Lattner0144fad2005-10-03 21:56:24 +0000470 ((T->getElementType(I-V.begin())->isAbstract() ||
Chris Lattner20a24452005-10-07 05:23:36 +0000471 C->getType()->isAbstract()) &&
Chris Lattner0144fad2005-10-03 21:56:24 +0000472 T->getElementType(I-V.begin())->getTypeID() ==
Chris Lattner20a24452005-10-07 05:23:36 +0000473 C->getType()->getTypeID())) &&
Chris Lattner93c8f142003-06-02 17:42:47 +0000474 "Initializer for struct element doesn't match struct element type!");
Gabor Greif2d3024d2008-05-26 21:33:52 +0000475 *OL = C;
Chris Lattner2f7c9632001-06-06 20:29:01 +0000476 }
477}
478
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000479
Reid Spencerd84d35b2007-02-15 02:26:10 +0000480ConstantVector::ConstantVector(const VectorType *T,
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000481 const std::vector<Constant*> &V)
Gabor Greiff6caff662008-05-10 08:32:32 +0000482 : Constant(T, ConstantVectorVal,
483 OperandTraits<ConstantVector>::op_end(this) - V.size(),
484 V.size()) {
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000485 Use *OL = OperandList;
Chris Lattner0144fad2005-10-03 21:56:24 +0000486 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
487 I != E; ++I, ++OL) {
Chris Lattner20a24452005-10-07 05:23:36 +0000488 Constant *C = *I;
489 assert((C->getType() == T->getElementType() ||
Alkis Evlogimenoscb031d92004-09-10 04:16:59 +0000490 (T->isAbstract() &&
Chris Lattner20a24452005-10-07 05:23:36 +0000491 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
Dan Gohman30978072007-05-24 14:36:04 +0000492 "Initializer for vector element doesn't match vector element type!");
Gabor Greif2d3024d2008-05-26 21:33:52 +0000493 *OL = C;
Brian Gaeke02209042004-08-20 06:00:58 +0000494 }
495}
496
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000497
Gabor Greiff6caff662008-05-10 08:32:32 +0000498namespace llvm {
Gordon Henriksen14a55692007-12-10 02:14:30 +0000499// We declare several classes private to this file, so use an anonymous
500// namespace
501namespace {
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000502
Gordon Henriksen14a55692007-12-10 02:14:30 +0000503/// UnaryConstantExpr - This class is private to Constants.cpp, and is used
504/// behind the scenes to implement unary constant exprs.
505class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
Gabor Greife9ecc682008-04-06 20:25:17 +0000506 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Gordon Henriksen14a55692007-12-10 02:14:30 +0000507public:
Gabor Greife9ecc682008-04-06 20:25:17 +0000508 // allocate space for exactly one operand
509 void *operator new(size_t s) {
510 return User::operator new(s, 1);
511 }
Gordon Henriksen14a55692007-12-10 02:14:30 +0000512 UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
Gabor Greiff6caff662008-05-10 08:32:32 +0000513 : ConstantExpr(Ty, Opcode, &Op<0>(), 1) {
514 Op<0>() = C;
515 }
516 /// Transparently provide more efficient getOperand methods.
517 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000518};
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000519
Gordon Henriksen14a55692007-12-10 02:14:30 +0000520/// BinaryConstantExpr - This class is private to Constants.cpp, and is used
521/// behind the scenes to implement binary constant exprs.
522class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
Gabor Greife9ecc682008-04-06 20:25:17 +0000523 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Gordon Henriksen14a55692007-12-10 02:14:30 +0000524public:
Gabor Greife9ecc682008-04-06 20:25:17 +0000525 // allocate space for exactly two operands
526 void *operator new(size_t s) {
527 return User::operator new(s, 2);
528 }
Gordon Henriksen14a55692007-12-10 02:14:30 +0000529 BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
Gabor Greiff6caff662008-05-10 08:32:32 +0000530 : ConstantExpr(C1->getType(), Opcode, &Op<0>(), 2) {
Gabor Greif2d3024d2008-05-26 21:33:52 +0000531 Op<0>() = C1;
532 Op<1>() = C2;
Gordon Henriksen14a55692007-12-10 02:14:30 +0000533 }
Gabor Greiff6caff662008-05-10 08:32:32 +0000534 /// Transparently provide more efficient getOperand methods.
535 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000536};
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000537
Gordon Henriksen14a55692007-12-10 02:14:30 +0000538/// SelectConstantExpr - This class is private to Constants.cpp, and is used
539/// behind the scenes to implement select constant exprs.
540class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
Gabor Greife9ecc682008-04-06 20:25:17 +0000541 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Gordon Henriksen14a55692007-12-10 02:14:30 +0000542public:
Gabor Greife9ecc682008-04-06 20:25:17 +0000543 // allocate space for exactly three operands
544 void *operator new(size_t s) {
545 return User::operator new(s, 3);
546 }
Gordon Henriksen14a55692007-12-10 02:14:30 +0000547 SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
Gabor Greiff6caff662008-05-10 08:32:32 +0000548 : ConstantExpr(C2->getType(), Instruction::Select, &Op<0>(), 3) {
Gabor Greif2d3024d2008-05-26 21:33:52 +0000549 Op<0>() = C1;
550 Op<1>() = C2;
551 Op<2>() = C3;
Gordon Henriksen14a55692007-12-10 02:14:30 +0000552 }
Gabor Greiff6caff662008-05-10 08:32:32 +0000553 /// Transparently provide more efficient getOperand methods.
554 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000555};
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000556
Gordon Henriksen14a55692007-12-10 02:14:30 +0000557/// ExtractElementConstantExpr - This class is private to
558/// Constants.cpp, and is used behind the scenes to implement
559/// extractelement constant exprs.
560class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
Gabor Greife9ecc682008-04-06 20:25:17 +0000561 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Gordon Henriksen14a55692007-12-10 02:14:30 +0000562public:
Gabor Greife9ecc682008-04-06 20:25:17 +0000563 // allocate space for exactly two operands
564 void *operator new(size_t s) {
565 return User::operator new(s, 2);
566 }
Gordon Henriksen14a55692007-12-10 02:14:30 +0000567 ExtractElementConstantExpr(Constant *C1, Constant *C2)
568 : ConstantExpr(cast<VectorType>(C1->getType())->getElementType(),
Gabor Greiff6caff662008-05-10 08:32:32 +0000569 Instruction::ExtractElement, &Op<0>(), 2) {
Gabor Greif2d3024d2008-05-26 21:33:52 +0000570 Op<0>() = C1;
571 Op<1>() = C2;
Gordon Henriksen14a55692007-12-10 02:14:30 +0000572 }
Gabor Greiff6caff662008-05-10 08:32:32 +0000573 /// Transparently provide more efficient getOperand methods.
574 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000575};
Robert Bocchino23004482006-01-10 19:05:34 +0000576
Gordon Henriksen14a55692007-12-10 02:14:30 +0000577/// InsertElementConstantExpr - This class is private to
578/// Constants.cpp, and is used behind the scenes to implement
579/// insertelement constant exprs.
580class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
Gabor Greife9ecc682008-04-06 20:25:17 +0000581 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Gordon Henriksen14a55692007-12-10 02:14:30 +0000582public:
Gabor Greife9ecc682008-04-06 20:25:17 +0000583 // allocate space for exactly three operands
584 void *operator new(size_t s) {
585 return User::operator new(s, 3);
586 }
Gordon Henriksen14a55692007-12-10 02:14:30 +0000587 InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
588 : ConstantExpr(C1->getType(), Instruction::InsertElement,
Gabor Greiff6caff662008-05-10 08:32:32 +0000589 &Op<0>(), 3) {
Gabor Greif2d3024d2008-05-26 21:33:52 +0000590 Op<0>() = C1;
591 Op<1>() = C2;
592 Op<2>() = C3;
Gordon Henriksen14a55692007-12-10 02:14:30 +0000593 }
Gabor Greiff6caff662008-05-10 08:32:32 +0000594 /// Transparently provide more efficient getOperand methods.
595 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000596};
Robert Bocchinoca27f032006-01-17 20:07:22 +0000597
Gordon Henriksen14a55692007-12-10 02:14:30 +0000598/// ShuffleVectorConstantExpr - This class is private to
599/// Constants.cpp, and is used behind the scenes to implement
600/// shufflevector constant exprs.
601class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
Gabor Greife9ecc682008-04-06 20:25:17 +0000602 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Gordon Henriksen14a55692007-12-10 02:14:30 +0000603public:
Gabor Greife9ecc682008-04-06 20:25:17 +0000604 // allocate space for exactly three operands
605 void *operator new(size_t s) {
606 return User::operator new(s, 3);
607 }
Gordon Henriksen14a55692007-12-10 02:14:30 +0000608 ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
Nate Begeman94aa38d2009-02-12 21:28:33 +0000609 : ConstantExpr(VectorType::get(
610 cast<VectorType>(C1->getType())->getElementType(),
611 cast<VectorType>(C3->getType())->getNumElements()),
612 Instruction::ShuffleVector,
Gabor Greiff6caff662008-05-10 08:32:32 +0000613 &Op<0>(), 3) {
Gabor Greif2d3024d2008-05-26 21:33:52 +0000614 Op<0>() = C1;
615 Op<1>() = C2;
616 Op<2>() = C3;
Gordon Henriksen14a55692007-12-10 02:14:30 +0000617 }
Gabor Greiff6caff662008-05-10 08:32:32 +0000618 /// Transparently provide more efficient getOperand methods.
619 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000620};
621
Dan Gohman12fce772008-05-15 19:50:34 +0000622/// ExtractValueConstantExpr - This class is private to
623/// Constants.cpp, and is used behind the scenes to implement
624/// extractvalue constant exprs.
625class VISIBILITY_HIDDEN ExtractValueConstantExpr : public ConstantExpr {
Dan Gohman1ecaf452008-05-31 00:58:22 +0000626 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Dan Gohman12fce772008-05-15 19:50:34 +0000627public:
Dan Gohman1ecaf452008-05-31 00:58:22 +0000628 // allocate space for exactly one operand
629 void *operator new(size_t s) {
630 return User::operator new(s, 1);
Dan Gohman12fce772008-05-15 19:50:34 +0000631 }
Dan Gohman1ecaf452008-05-31 00:58:22 +0000632 ExtractValueConstantExpr(Constant *Agg,
633 const SmallVector<unsigned, 4> &IdxList,
634 const Type *DestTy)
635 : ConstantExpr(DestTy, Instruction::ExtractValue, &Op<0>(), 1),
636 Indices(IdxList) {
637 Op<0>() = Agg;
638 }
639
Dan Gohman7bb04502008-05-31 19:09:08 +0000640 /// Indices - These identify which value to extract.
Dan Gohman1ecaf452008-05-31 00:58:22 +0000641 const SmallVector<unsigned, 4> Indices;
642
Dan Gohman12fce772008-05-15 19:50:34 +0000643 /// Transparently provide more efficient getOperand methods.
644 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
645};
646
647/// InsertValueConstantExpr - This class is private to
648/// Constants.cpp, and is used behind the scenes to implement
649/// insertvalue constant exprs.
650class VISIBILITY_HIDDEN InsertValueConstantExpr : public ConstantExpr {
Dan Gohman1ecaf452008-05-31 00:58:22 +0000651 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Dan Gohman12fce772008-05-15 19:50:34 +0000652public:
Dan Gohman1ecaf452008-05-31 00:58:22 +0000653 // allocate space for exactly one operand
654 void *operator new(size_t s) {
655 return User::operator new(s, 2);
Dan Gohman12fce772008-05-15 19:50:34 +0000656 }
Dan Gohman1ecaf452008-05-31 00:58:22 +0000657 InsertValueConstantExpr(Constant *Agg, Constant *Val,
658 const SmallVector<unsigned, 4> &IdxList,
659 const Type *DestTy)
660 : ConstantExpr(DestTy, Instruction::InsertValue, &Op<0>(), 2),
661 Indices(IdxList) {
662 Op<0>() = Agg;
663 Op<1>() = Val;
664 }
665
Dan Gohman7bb04502008-05-31 19:09:08 +0000666 /// Indices - These identify the position for the insertion.
Dan Gohman1ecaf452008-05-31 00:58:22 +0000667 const SmallVector<unsigned, 4> Indices;
668
Dan Gohman12fce772008-05-15 19:50:34 +0000669 /// Transparently provide more efficient getOperand methods.
670 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
671};
672
673
Gordon Henriksen14a55692007-12-10 02:14:30 +0000674/// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
675/// used behind the scenes to implement getelementpr constant exprs.
Gabor Greife9ecc682008-04-06 20:25:17 +0000676class VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
Gordon Henriksen14a55692007-12-10 02:14:30 +0000677 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
Gabor Greiff6caff662008-05-10 08:32:32 +0000678 const Type *DestTy);
Gabor Greife9ecc682008-04-06 20:25:17 +0000679public:
Gabor Greif697e94c2008-05-15 10:04:30 +0000680 static GetElementPtrConstantExpr *Create(Constant *C,
681 const std::vector<Constant*>&IdxList,
Gabor Greiff6caff662008-05-10 08:32:32 +0000682 const Type *DestTy) {
Gabor Greif697e94c2008-05-15 10:04:30 +0000683 return new(IdxList.size() + 1)
684 GetElementPtrConstantExpr(C, IdxList, DestTy);
Gabor Greife9ecc682008-04-06 20:25:17 +0000685 }
Gabor Greiff6caff662008-05-10 08:32:32 +0000686 /// Transparently provide more efficient getOperand methods.
687 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000688};
689
690// CompareConstantExpr - This class is private to Constants.cpp, and is used
691// behind the scenes to implement ICmp and FCmp constant expressions. This is
692// needed in order to store the predicate value for these instructions.
693struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
Gabor Greife9ecc682008-04-06 20:25:17 +0000694 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
695 // allocate space for exactly two operands
696 void *operator new(size_t s) {
697 return User::operator new(s, 2);
698 }
Gordon Henriksen14a55692007-12-10 02:14:30 +0000699 unsigned short predicate;
Nate Begemand2195702008-05-12 19:01:56 +0000700 CompareConstantExpr(const Type *ty, Instruction::OtherOps opc,
701 unsigned short pred, Constant* LHS, Constant* RHS)
702 : ConstantExpr(ty, opc, &Op<0>(), 2), predicate(pred) {
Gabor Greif2d3024d2008-05-26 21:33:52 +0000703 Op<0>() = LHS;
704 Op<1>() = RHS;
Gordon Henriksen14a55692007-12-10 02:14:30 +0000705 }
Gabor Greiff6caff662008-05-10 08:32:32 +0000706 /// Transparently provide more efficient getOperand methods.
707 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000708};
709
710} // end anonymous namespace
711
Gabor Greiff6caff662008-05-10 08:32:32 +0000712template <>
713struct OperandTraits<UnaryConstantExpr> : FixedNumOperandTraits<1> {
714};
715DEFINE_TRANSPARENT_OPERAND_ACCESSORS(UnaryConstantExpr, Value)
716
717template <>
718struct OperandTraits<BinaryConstantExpr> : FixedNumOperandTraits<2> {
719};
720DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BinaryConstantExpr, Value)
721
722template <>
723struct OperandTraits<SelectConstantExpr> : FixedNumOperandTraits<3> {
724};
725DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectConstantExpr, Value)
726
727template <>
728struct OperandTraits<ExtractElementConstantExpr> : FixedNumOperandTraits<2> {
729};
730DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementConstantExpr, Value)
731
732template <>
733struct OperandTraits<InsertElementConstantExpr> : FixedNumOperandTraits<3> {
734};
735DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementConstantExpr, Value)
736
737template <>
738struct OperandTraits<ShuffleVectorConstantExpr> : FixedNumOperandTraits<3> {
739};
740DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorConstantExpr, Value)
741
Dan Gohman12fce772008-05-15 19:50:34 +0000742template <>
Dan Gohman1ecaf452008-05-31 00:58:22 +0000743struct OperandTraits<ExtractValueConstantExpr> : FixedNumOperandTraits<1> {
Dan Gohman12fce772008-05-15 19:50:34 +0000744};
Dan Gohman12fce772008-05-15 19:50:34 +0000745DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractValueConstantExpr, Value)
746
747template <>
Dan Gohman1ecaf452008-05-31 00:58:22 +0000748struct OperandTraits<InsertValueConstantExpr> : FixedNumOperandTraits<2> {
Dan Gohman12fce772008-05-15 19:50:34 +0000749};
Dan Gohman12fce772008-05-15 19:50:34 +0000750DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueConstantExpr, Value)
751
Gabor Greiff6caff662008-05-10 08:32:32 +0000752template <>
753struct OperandTraits<GetElementPtrConstantExpr> : VariadicOperandTraits<1> {
754};
755
756GetElementPtrConstantExpr::GetElementPtrConstantExpr
757 (Constant *C,
758 const std::vector<Constant*> &IdxList,
759 const Type *DestTy)
760 : ConstantExpr(DestTy, Instruction::GetElementPtr,
761 OperandTraits<GetElementPtrConstantExpr>::op_end(this)
762 - (IdxList.size()+1),
763 IdxList.size()+1) {
Gabor Greif2d3024d2008-05-26 21:33:52 +0000764 OperandList[0] = C;
Gabor Greiff6caff662008-05-10 08:32:32 +0000765 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
Gabor Greif2d3024d2008-05-26 21:33:52 +0000766 OperandList[i+1] = IdxList[i];
Gabor Greiff6caff662008-05-10 08:32:32 +0000767}
768
769DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrConstantExpr, Value)
770
771
772template <>
773struct OperandTraits<CompareConstantExpr> : FixedNumOperandTraits<2> {
774};
775DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CompareConstantExpr, Value)
776
777
778} // End llvm namespace
779
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000780
781// Utility function for determining if a ConstantExpr is a CastOp or not. This
782// can't be inline because we don't want to #include Instruction.h into
783// Constant.h
784bool ConstantExpr::isCast() const {
785 return Instruction::isCast(getOpcode());
786}
787
Reid Spenceree3c9912006-12-04 05:19:50 +0000788bool ConstantExpr::isCompare() const {
Chris Lattnereab49262008-07-14 05:17:31 +0000789 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp ||
790 getOpcode() == Instruction::VICmp || getOpcode() == Instruction::VFCmp;
Reid Spenceree3c9912006-12-04 05:19:50 +0000791}
792
Dan Gohman1ecaf452008-05-31 00:58:22 +0000793bool ConstantExpr::hasIndices() const {
794 return getOpcode() == Instruction::ExtractValue ||
795 getOpcode() == Instruction::InsertValue;
796}
797
798const SmallVector<unsigned, 4> &ConstantExpr::getIndices() const {
799 if (const ExtractValueConstantExpr *EVCE =
800 dyn_cast<ExtractValueConstantExpr>(this))
801 return EVCE->Indices;
Dan Gohmana469bdb2008-06-23 16:39:44 +0000802
803 return cast<InsertValueConstantExpr>(this)->Indices;
Dan Gohman1ecaf452008-05-31 00:58:22 +0000804}
805
Chris Lattner817175f2004-03-29 02:37:53 +0000806/// ConstantExpr::get* - Return some common constants without having to
807/// specify the full Instruction::OPCODE identifier.
808///
809Constant *ConstantExpr::getNeg(Constant *C) {
Dan Gohmana5b96452009-06-04 22:49:04 +0000810 // API compatibility: Adjust integer opcodes to floating-point opcodes.
811 if (C->getType()->isFPOrFPVector())
812 return getFNeg(C);
813 assert(C->getType()->isIntOrIntVector() &&
814 "Cannot NEG a nonintegral value!");
Reid Spencer2eadb532007-01-21 00:29:26 +0000815 return get(Instruction::Sub,
816 ConstantExpr::getZeroValueForNegationExpr(C->getType()),
817 C);
Chris Lattner817175f2004-03-29 02:37:53 +0000818}
Dan Gohmana5b96452009-06-04 22:49:04 +0000819Constant *ConstantExpr::getFNeg(Constant *C) {
820 assert(C->getType()->isFPOrFPVector() &&
821 "Cannot FNEG a non-floating-point value!");
822 return get(Instruction::FSub,
823 ConstantExpr::getZeroValueForNegationExpr(C->getType()),
824 C);
825}
Chris Lattner817175f2004-03-29 02:37:53 +0000826Constant *ConstantExpr::getNot(Constant *C) {
Dan Gohmana5b96452009-06-04 22:49:04 +0000827 assert(C->getType()->isIntOrIntVector() &&
828 "Cannot NOT a nonintegral value!");
Chris Lattner817175f2004-03-29 02:37:53 +0000829 return get(Instruction::Xor, C,
Dale Johannesen47a5ef32008-08-21 21:20:09 +0000830 Constant::getAllOnesValue(C->getType()));
Chris Lattner817175f2004-03-29 02:37:53 +0000831}
832Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
833 return get(Instruction::Add, C1, C2);
834}
Dan Gohmana5b96452009-06-04 22:49:04 +0000835Constant *ConstantExpr::getFAdd(Constant *C1, Constant *C2) {
836 return get(Instruction::FAdd, C1, C2);
837}
Chris Lattner817175f2004-03-29 02:37:53 +0000838Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
839 return get(Instruction::Sub, C1, C2);
840}
Dan Gohmana5b96452009-06-04 22:49:04 +0000841Constant *ConstantExpr::getFSub(Constant *C1, Constant *C2) {
842 return get(Instruction::FSub, C1, C2);
843}
Chris Lattner817175f2004-03-29 02:37:53 +0000844Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
845 return get(Instruction::Mul, C1, C2);
846}
Dan Gohmana5b96452009-06-04 22:49:04 +0000847Constant *ConstantExpr::getFMul(Constant *C1, Constant *C2) {
848 return get(Instruction::FMul, C1, C2);
849}
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000850Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2) {
851 return get(Instruction::UDiv, C1, C2);
852}
853Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2) {
854 return get(Instruction::SDiv, C1, C2);
855}
856Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
857 return get(Instruction::FDiv, C1, C2);
Chris Lattner817175f2004-03-29 02:37:53 +0000858}
Reid Spencer7eb55b32006-11-02 01:53:59 +0000859Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
860 return get(Instruction::URem, C1, C2);
861}
862Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
863 return get(Instruction::SRem, C1, C2);
864}
865Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
866 return get(Instruction::FRem, C1, C2);
Chris Lattner817175f2004-03-29 02:37:53 +0000867}
868Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
869 return get(Instruction::And, C1, C2);
870}
871Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
872 return get(Instruction::Or, C1, C2);
873}
874Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
875 return get(Instruction::Xor, C1, C2);
876}
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000877unsigned ConstantExpr::getPredicate() const {
Nate Begemand2195702008-05-12 19:01:56 +0000878 assert(getOpcode() == Instruction::FCmp ||
879 getOpcode() == Instruction::ICmp ||
880 getOpcode() == Instruction::VFCmp ||
881 getOpcode() == Instruction::VICmp);
Chris Lattneref650092007-10-18 16:26:24 +0000882 return ((const CompareConstantExpr*)this)->predicate;
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000883}
Chris Lattner817175f2004-03-29 02:37:53 +0000884Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
885 return get(Instruction::Shl, C1, C2);
886}
Reid Spencerfdff9382006-11-08 06:47:33 +0000887Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2) {
888 return get(Instruction::LShr, C1, C2);
Chris Lattner817175f2004-03-29 02:37:53 +0000889}
Reid Spencerfdff9382006-11-08 06:47:33 +0000890Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2) {
891 return get(Instruction::AShr, C1, C2);
Chris Lattnerdb8bdba2004-05-25 05:32:43 +0000892}
Chris Lattner60e0dd72001-10-03 06:12:09 +0000893
Chris Lattner7c1018a2006-07-14 19:37:40 +0000894/// getWithOperandReplaced - Return a constant expression identical to this
895/// one, but with the specified operand set to the specified value.
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000896Constant *
897ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
Chris Lattner7c1018a2006-07-14 19:37:40 +0000898 assert(OpNo < getNumOperands() && "Operand num is out of range!");
899 assert(Op->getType() == getOperand(OpNo)->getType() &&
900 "Replacing operand with value of different type!");
Chris Lattner227816342006-07-14 22:20:01 +0000901 if (getOperand(OpNo) == Op)
902 return const_cast<ConstantExpr*>(this);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000903
Chris Lattner227816342006-07-14 22:20:01 +0000904 Constant *Op0, *Op1, *Op2;
Chris Lattner7c1018a2006-07-14 19:37:40 +0000905 switch (getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000906 case Instruction::Trunc:
907 case Instruction::ZExt:
908 case Instruction::SExt:
909 case Instruction::FPTrunc:
910 case Instruction::FPExt:
911 case Instruction::UIToFP:
912 case Instruction::SIToFP:
913 case Instruction::FPToUI:
914 case Instruction::FPToSI:
915 case Instruction::PtrToInt:
916 case Instruction::IntToPtr:
917 case Instruction::BitCast:
918 return ConstantExpr::getCast(getOpcode(), Op, getType());
Chris Lattner227816342006-07-14 22:20:01 +0000919 case Instruction::Select:
920 Op0 = (OpNo == 0) ? Op : getOperand(0);
921 Op1 = (OpNo == 1) ? Op : getOperand(1);
922 Op2 = (OpNo == 2) ? Op : getOperand(2);
923 return ConstantExpr::getSelect(Op0, Op1, Op2);
924 case Instruction::InsertElement:
925 Op0 = (OpNo == 0) ? Op : getOperand(0);
926 Op1 = (OpNo == 1) ? Op : getOperand(1);
927 Op2 = (OpNo == 2) ? Op : getOperand(2);
928 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
929 case Instruction::ExtractElement:
930 Op0 = (OpNo == 0) ? Op : getOperand(0);
931 Op1 = (OpNo == 1) ? Op : getOperand(1);
932 return ConstantExpr::getExtractElement(Op0, Op1);
933 case Instruction::ShuffleVector:
934 Op0 = (OpNo == 0) ? Op : getOperand(0);
935 Op1 = (OpNo == 1) ? Op : getOperand(1);
936 Op2 = (OpNo == 2) ? Op : getOperand(2);
937 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000938 case Instruction::GetElementPtr: {
Chris Lattnerb5d70302007-02-19 20:01:23 +0000939 SmallVector<Constant*, 8> Ops;
Dan Gohman12fce772008-05-15 19:50:34 +0000940 Ops.resize(getNumOperands()-1);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000941 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
Dan Gohman12fce772008-05-15 19:50:34 +0000942 Ops[i-1] = getOperand(i);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000943 if (OpNo == 0)
Chris Lattnerb5d70302007-02-19 20:01:23 +0000944 return ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
Chris Lattner7c1018a2006-07-14 19:37:40 +0000945 Ops[OpNo-1] = Op;
Chris Lattnerb5d70302007-02-19 20:01:23 +0000946 return ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
Chris Lattner7c1018a2006-07-14 19:37:40 +0000947 }
Chris Lattner7c1018a2006-07-14 19:37:40 +0000948 default:
949 assert(getNumOperands() == 2 && "Must be binary operator?");
Chris Lattner227816342006-07-14 22:20:01 +0000950 Op0 = (OpNo == 0) ? Op : getOperand(0);
951 Op1 = (OpNo == 1) ? Op : getOperand(1);
952 return ConstantExpr::get(getOpcode(), Op0, Op1);
953 }
954}
955
956/// getWithOperands - This returns the current constant expression with the
957/// operands replaced with the specified values. The specified operands must
958/// match count and type with the existing ones.
959Constant *ConstantExpr::
Chris Lattnerb078e282008-08-20 22:27:40 +0000960getWithOperands(Constant* const *Ops, unsigned NumOps) const {
961 assert(NumOps == getNumOperands() && "Operand count mismatch!");
Chris Lattner227816342006-07-14 22:20:01 +0000962 bool AnyChange = false;
Chris Lattnerb078e282008-08-20 22:27:40 +0000963 for (unsigned i = 0; i != NumOps; ++i) {
Chris Lattner227816342006-07-14 22:20:01 +0000964 assert(Ops[i]->getType() == getOperand(i)->getType() &&
965 "Operand type mismatch!");
966 AnyChange |= Ops[i] != getOperand(i);
967 }
968 if (!AnyChange) // No operands changed, return self.
969 return const_cast<ConstantExpr*>(this);
970
971 switch (getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000972 case Instruction::Trunc:
973 case Instruction::ZExt:
974 case Instruction::SExt:
975 case Instruction::FPTrunc:
976 case Instruction::FPExt:
977 case Instruction::UIToFP:
978 case Instruction::SIToFP:
979 case Instruction::FPToUI:
980 case Instruction::FPToSI:
981 case Instruction::PtrToInt:
982 case Instruction::IntToPtr:
983 case Instruction::BitCast:
984 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
Chris Lattner227816342006-07-14 22:20:01 +0000985 case Instruction::Select:
986 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
987 case Instruction::InsertElement:
988 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
989 case Instruction::ExtractElement:
990 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
991 case Instruction::ShuffleVector:
992 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
Chris Lattnerb5d70302007-02-19 20:01:23 +0000993 case Instruction::GetElementPtr:
Chris Lattnerb078e282008-08-20 22:27:40 +0000994 return ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], NumOps-1);
Reid Spencer266e42b2006-12-23 06:05:41 +0000995 case Instruction::ICmp:
996 case Instruction::FCmp:
Nate Begeman098cc6f2008-07-25 17:56:27 +0000997 case Instruction::VICmp:
998 case Instruction::VFCmp:
Reid Spencer266e42b2006-12-23 06:05:41 +0000999 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
Chris Lattner227816342006-07-14 22:20:01 +00001000 default:
1001 assert(getNumOperands() == 2 && "Must be binary operator?");
1002 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
Chris Lattner7c1018a2006-07-14 19:37:40 +00001003 }
1004}
1005
Chris Lattner2f7c9632001-06-06 20:29:01 +00001006
1007//===----------------------------------------------------------------------===//
Chris Lattner2f7c9632001-06-06 20:29:01 +00001008// isValueValidForType implementations
1009
Reid Spencere7334722006-12-19 01:28:19 +00001010bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001011 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001012 if (Ty == Type::Int1Ty)
1013 return Val == 0 || Val == 1;
Reid Spencerd7a00d72007-02-05 23:47:56 +00001014 if (NumBits >= 64)
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001015 return true; // always true, has to fit in largest type
1016 uint64_t Max = (1ll << NumBits) - 1;
1017 return Val <= Max;
Reid Spencere7334722006-12-19 01:28:19 +00001018}
1019
Reid Spencere0fc4df2006-10-20 07:07:24 +00001020bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001021 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001022 if (Ty == Type::Int1Ty)
Reid Spencera94d3942007-01-19 21:13:56 +00001023 return Val == 0 || Val == 1 || Val == -1;
Reid Spencerd7a00d72007-02-05 23:47:56 +00001024 if (NumBits >= 64)
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001025 return true; // always true, has to fit in largest type
1026 int64_t Min = -(1ll << (NumBits-1));
1027 int64_t Max = (1ll << (NumBits-1)) - 1;
1028 return (Val >= Min && Val <= Max);
Chris Lattner2f7c9632001-06-06 20:29:01 +00001029}
1030
Dale Johannesend246b2c2007-08-30 00:23:21 +00001031bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
1032 // convert modifies in place, so make a copy.
1033 APFloat Val2 = APFloat(Val);
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001034 bool losesInfo;
Chris Lattner6b727592004-06-17 18:19:28 +00001035 switch (Ty->getTypeID()) {
Chris Lattner2f7c9632001-06-06 20:29:01 +00001036 default:
1037 return false; // These can't be represented as floating point!
1038
Dale Johannesend246b2c2007-08-30 00:23:21 +00001039 // FIXME rounding mode needs to be more flexible
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001040 case Type::FloatTyID: {
1041 if (&Val2.getSemantics() == &APFloat::IEEEsingle)
1042 return true;
1043 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
1044 return !losesInfo;
1045 }
1046 case Type::DoubleTyID: {
1047 if (&Val2.getSemantics() == &APFloat::IEEEsingle ||
1048 &Val2.getSemantics() == &APFloat::IEEEdouble)
1049 return true;
1050 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
1051 return !losesInfo;
1052 }
Dale Johannesenbdad8092007-08-09 22:51:36 +00001053 case Type::X86_FP80TyID:
Dale Johannesen028084e2007-09-12 03:30:33 +00001054 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
1055 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1056 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
Dale Johannesenbdad8092007-08-09 22:51:36 +00001057 case Type::FP128TyID:
Dale Johannesen028084e2007-09-12 03:30:33 +00001058 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
1059 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1060 &Val2.getSemantics() == &APFloat::IEEEquad;
Dale Johannesen007aa372007-10-11 18:07:22 +00001061 case Type::PPC_FP128TyID:
1062 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
1063 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1064 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
Chris Lattner2f7c9632001-06-06 20:29:01 +00001065 }
Chris Lattneraa2372562006-05-24 17:04:05 +00001066}
Chris Lattner9655e542001-07-20 19:16:02 +00001067
Chris Lattner49d855c2001-09-07 16:46:31 +00001068//===----------------------------------------------------------------------===//
Chris Lattner49d855c2001-09-07 16:46:31 +00001069// Factory Function Implementation
1070
Gabor Greiff6caff662008-05-10 08:32:32 +00001071
1072// The number of operands for each ConstantCreator::create method is
1073// determined by the ConstantTraits template.
Chris Lattner98fa07b2003-05-23 20:03:32 +00001074// ConstantCreator - A class that is used to create constants by
1075// ValueMap*. This class should be partially specialized if there is
1076// something strange that needs to be done to interface to the ctor for the
1077// constant.
1078//
Chris Lattner189d19f2003-11-21 20:23:48 +00001079namespace llvm {
Gabor Greiff6caff662008-05-10 08:32:32 +00001080 template<class ValType>
1081 struct ConstantTraits;
1082
1083 template<typename T, typename Alloc>
1084 struct VISIBILITY_HIDDEN ConstantTraits< std::vector<T, Alloc> > {
1085 static unsigned uses(const std::vector<T, Alloc>& v) {
1086 return v.size();
1087 }
1088 };
1089
Chris Lattner189d19f2003-11-21 20:23:48 +00001090 template<class ConstantClass, class TypeClass, class ValType>
Chris Lattner02157b02006-06-28 21:38:54 +00001091 struct VISIBILITY_HIDDEN ConstantCreator {
Chris Lattner189d19f2003-11-21 20:23:48 +00001092 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
Gabor Greiff6caff662008-05-10 08:32:32 +00001093 return new(ConstantTraits<ValType>::uses(V)) ConstantClass(Ty, V);
Chris Lattner189d19f2003-11-21 20:23:48 +00001094 }
1095 };
Misha Brukmanb1c93172005-04-21 23:48:37 +00001096
Chris Lattner189d19f2003-11-21 20:23:48 +00001097 template<class ConstantClass, class TypeClass>
Chris Lattner02157b02006-06-28 21:38:54 +00001098 struct VISIBILITY_HIDDEN ConvertConstantType {
Chris Lattner189d19f2003-11-21 20:23:48 +00001099 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
1100 assert(0 && "This type cannot be converted!\n");
1101 abort();
1102 }
1103 };
Chris Lattnerb50d1352003-10-05 00:17:43 +00001104
Chris Lattner935aa922005-10-04 17:48:46 +00001105 template<class ValType, class TypeClass, class ConstantClass,
1106 bool HasLargeKey = false /*true for arrays and structs*/ >
Chris Lattner02157b02006-06-28 21:38:54 +00001107 class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
Chris Lattnerb64419a2005-10-03 22:51:37 +00001108 public:
Jim Laskeyc03caef2006-07-17 17:38:29 +00001109 typedef std::pair<const Type*, ValType> MapKey;
1110 typedef std::map<MapKey, Constant *> MapTy;
1111 typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
1112 typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
Chris Lattnerb64419a2005-10-03 22:51:37 +00001113 private:
Chris Lattner5bbf60a52005-10-04 16:52:46 +00001114 /// Map - This is the main map from the element descriptor to the Constants.
1115 /// This is the primary way we avoid creating two of the same shape
1116 /// constant.
Chris Lattnerb50d1352003-10-05 00:17:43 +00001117 MapTy Map;
Chris Lattner935aa922005-10-04 17:48:46 +00001118
1119 /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
1120 /// from the constants to their element in Map. This is important for
1121 /// removal of constants from the array, which would otherwise have to scan
1122 /// through the map with very large keys.
Jim Laskeyc03caef2006-07-17 17:38:29 +00001123 InverseMapTy InverseMap;
Chris Lattnerb50d1352003-10-05 00:17:43 +00001124
Jim Laskeyc03caef2006-07-17 17:38:29 +00001125 /// AbstractTypeMap - Map for abstract type constants.
1126 ///
Chris Lattnerb50d1352003-10-05 00:17:43 +00001127 AbstractTypeMapTy AbstractTypeMap;
Chris Lattner99a669b2004-11-19 16:39:44 +00001128
Chris Lattner98fa07b2003-05-23 20:03:32 +00001129 public:
Jim Laskeyc03caef2006-07-17 17:38:29 +00001130 typename MapTy::iterator map_end() { return Map.end(); }
Chris Lattnerb64419a2005-10-03 22:51:37 +00001131
1132 /// InsertOrGetItem - Return an iterator for the specified element.
1133 /// If the element exists in the map, the returned iterator points to the
1134 /// entry and Exists=true. If not, the iterator points to the newly
1135 /// inserted entry and returns Exists=false. Newly inserted entries have
1136 /// I->second == 0, and should be filled in.
Jim Laskeyc03caef2006-07-17 17:38:29 +00001137 typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
1138 &InsertVal,
Chris Lattnerb64419a2005-10-03 22:51:37 +00001139 bool &Exists) {
Jim Laskeyc03caef2006-07-17 17:38:29 +00001140 std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
Chris Lattnerb64419a2005-10-03 22:51:37 +00001141 Exists = !IP.second;
1142 return IP.first;
1143 }
Chris Lattner5bbf60a52005-10-04 16:52:46 +00001144
Chris Lattner935aa922005-10-04 17:48:46 +00001145private:
Jim Laskeyc03caef2006-07-17 17:38:29 +00001146 typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
Chris Lattner935aa922005-10-04 17:48:46 +00001147 if (HasLargeKey) {
Jim Laskeyc03caef2006-07-17 17:38:29 +00001148 typename InverseMapTy::iterator IMI = InverseMap.find(CP);
Chris Lattner935aa922005-10-04 17:48:46 +00001149 assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
1150 IMI->second->second == CP &&
1151 "InverseMap corrupt!");
1152 return IMI->second;
1153 }
1154
Jim Laskeyc03caef2006-07-17 17:38:29 +00001155 typename MapTy::iterator I =
Dan Gohmane955c482008-08-05 14:45:15 +00001156 Map.find(MapKey(static_cast<const TypeClass*>(CP->getRawType()),
1157 getValType(CP)));
Chris Lattner5bbf60a52005-10-04 16:52:46 +00001158 if (I == Map.end() || I->second != CP) {
1159 // FIXME: This should not use a linear scan. If this gets to be a
1160 // performance problem, someone should look at this.
1161 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
1162 /* empty */;
1163 }
Chris Lattner935aa922005-10-04 17:48:46 +00001164 return I;
1165 }
1166public:
1167
Chris Lattnerb64419a2005-10-03 22:51:37 +00001168 /// getOrCreate - Return the specified constant from the map, creating it if
1169 /// necessary.
Chris Lattner98fa07b2003-05-23 20:03:32 +00001170 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
Chris Lattnerb50d1352003-10-05 00:17:43 +00001171 MapKey Lookup(Ty, V);
Dan Gohman3707f1d2008-07-11 20:58:19 +00001172 typename MapTy::iterator I = Map.find(Lookup);
Reid Spencere0fc4df2006-10-20 07:07:24 +00001173 // Is it in the map?
Dan Gohman3707f1d2008-07-11 20:58:19 +00001174 if (I != Map.end())
Reid Spencere0fc4df2006-10-20 07:07:24 +00001175 return static_cast<ConstantClass *>(I->second);
Chris Lattner98fa07b2003-05-23 20:03:32 +00001176
1177 // If no preexisting value, create one now...
1178 ConstantClass *Result =
1179 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
1180
Chris Lattnerf97ab6d2008-08-23 03:48:35 +00001181 assert(Result->getType() == Ty && "Type specified is not correct!");
Chris Lattnerb50d1352003-10-05 00:17:43 +00001182 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
1183
Chris Lattner935aa922005-10-04 17:48:46 +00001184 if (HasLargeKey) // Remember the reverse mapping if needed.
1185 InverseMap.insert(std::make_pair(Result, I));
1186
Chris Lattnerb50d1352003-10-05 00:17:43 +00001187 // If the type of the constant is abstract, make sure that an entry exists
1188 // for it in the AbstractTypeMap.
1189 if (Ty->isAbstract()) {
Dan Gohman3707f1d2008-07-11 20:58:19 +00001190 typename AbstractTypeMapTy::iterator TI = AbstractTypeMap.find(Ty);
Chris Lattnerb50d1352003-10-05 00:17:43 +00001191
Dan Gohman3707f1d2008-07-11 20:58:19 +00001192 if (TI == AbstractTypeMap.end()) {
Chris Lattnerb50d1352003-10-05 00:17:43 +00001193 // Add ourselves to the ATU list of the type.
1194 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
1195
1196 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
1197 }
1198 }
Chris Lattner98fa07b2003-05-23 20:03:32 +00001199 return Result;
1200 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001201
Chris Lattner98fa07b2003-05-23 20:03:32 +00001202 void remove(ConstantClass *CP) {
Jim Laskeyc03caef2006-07-17 17:38:29 +00001203 typename MapTy::iterator I = FindExistingElement(CP);
Chris Lattnerb50d1352003-10-05 00:17:43 +00001204 assert(I != Map.end() && "Constant not found in constant table!");
Chris Lattner3e650af2004-08-04 04:48:01 +00001205 assert(I->second == CP && "Didn't find correct element?");
Chris Lattnerb50d1352003-10-05 00:17:43 +00001206
Chris Lattner935aa922005-10-04 17:48:46 +00001207 if (HasLargeKey) // Remember the reverse mapping if needed.
1208 InverseMap.erase(CP);
1209
Chris Lattnerb50d1352003-10-05 00:17:43 +00001210 // Now that we found the entry, make sure this isn't the entry that
1211 // the AbstractTypeMap points to.
Jim Laskeyc03caef2006-07-17 17:38:29 +00001212 const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
Chris Lattnerb50d1352003-10-05 00:17:43 +00001213 if (Ty->isAbstract()) {
1214 assert(AbstractTypeMap.count(Ty) &&
1215 "Abstract type not in AbstractTypeMap?");
Jim Laskeyc03caef2006-07-17 17:38:29 +00001216 typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
Chris Lattnerb50d1352003-10-05 00:17:43 +00001217 if (ATMEntryIt == I) {
1218 // Yes, we are removing the representative entry for this type.
1219 // See if there are any other entries of the same type.
Jim Laskeyc03caef2006-07-17 17:38:29 +00001220 typename MapTy::iterator TmpIt = ATMEntryIt;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001221
Chris Lattnerb50d1352003-10-05 00:17:43 +00001222 // First check the entry before this one...
1223 if (TmpIt != Map.begin()) {
1224 --TmpIt;
1225 if (TmpIt->first.first != Ty) // Not the same type, move back...
1226 ++TmpIt;
1227 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001228
Chris Lattnerb50d1352003-10-05 00:17:43 +00001229 // If we didn't find the same type, try to move forward...
1230 if (TmpIt == ATMEntryIt) {
1231 ++TmpIt;
1232 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
1233 --TmpIt; // No entry afterwards with the same type
1234 }
1235
1236 // If there is another entry in the map of the same abstract type,
1237 // update the AbstractTypeMap entry now.
1238 if (TmpIt != ATMEntryIt) {
1239 ATMEntryIt = TmpIt;
1240 } else {
1241 // Otherwise, we are removing the last instance of this type
1242 // from the table. Remove from the ATM, and from user list.
1243 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
1244 AbstractTypeMap.erase(Ty);
1245 }
Chris Lattner98fa07b2003-05-23 20:03:32 +00001246 }
Chris Lattnerb50d1352003-10-05 00:17:43 +00001247 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001248
Chris Lattnerb50d1352003-10-05 00:17:43 +00001249 Map.erase(I);
1250 }
1251
Chris Lattner3b793c62005-10-04 21:35:50 +00001252
1253 /// MoveConstantToNewSlot - If we are about to change C to be the element
1254 /// specified by I, update our internal data structures to reflect this
1255 /// fact.
Jim Laskeyc03caef2006-07-17 17:38:29 +00001256 void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
Chris Lattner3b793c62005-10-04 21:35:50 +00001257 // First, remove the old location of the specified constant in the map.
Jim Laskeyc03caef2006-07-17 17:38:29 +00001258 typename MapTy::iterator OldI = FindExistingElement(C);
Chris Lattner3b793c62005-10-04 21:35:50 +00001259 assert(OldI != Map.end() && "Constant not found in constant table!");
1260 assert(OldI->second == C && "Didn't find correct element?");
1261
1262 // If this constant is the representative element for its abstract type,
1263 // update the AbstractTypeMap so that the representative element is I.
1264 if (C->getType()->isAbstract()) {
1265 typename AbstractTypeMapTy::iterator ATI =
1266 AbstractTypeMap.find(C->getType());
1267 assert(ATI != AbstractTypeMap.end() &&
1268 "Abstract type not in AbstractTypeMap?");
1269 if (ATI->second == OldI)
1270 ATI->second = I;
1271 }
1272
1273 // Remove the old entry from the map.
1274 Map.erase(OldI);
1275
1276 // Update the inverse map so that we know that this constant is now
1277 // located at descriptor I.
1278 if (HasLargeKey) {
1279 assert(I->second == C && "Bad inversemap entry!");
1280 InverseMap[C] = I;
1281 }
1282 }
1283
Chris Lattnerb50d1352003-10-05 00:17:43 +00001284 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00001285 typename AbstractTypeMapTy::iterator I =
Jim Laskeyc03caef2006-07-17 17:38:29 +00001286 AbstractTypeMap.find(cast<Type>(OldTy));
Chris Lattnerb50d1352003-10-05 00:17:43 +00001287
1288 assert(I != AbstractTypeMap.end() &&
1289 "Abstract type not in AbstractTypeMap?");
1290
1291 // Convert a constant at a time until the last one is gone. The last one
1292 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
1293 // eliminated eventually.
1294 do {
1295 ConvertConstantType<ConstantClass,
Jim Laskeyc03caef2006-07-17 17:38:29 +00001296 TypeClass>::convert(
1297 static_cast<ConstantClass *>(I->second->second),
Chris Lattnerb50d1352003-10-05 00:17:43 +00001298 cast<TypeClass>(NewTy));
1299
Jim Laskeyc03caef2006-07-17 17:38:29 +00001300 I = AbstractTypeMap.find(cast<Type>(OldTy));
Chris Lattnerb50d1352003-10-05 00:17:43 +00001301 } while (I != AbstractTypeMap.end());
1302 }
1303
1304 // If the type became concrete without being refined to any other existing
1305 // type, we just remove ourselves from the ATU list.
1306 void typeBecameConcrete(const DerivedType *AbsTy) {
1307 AbsTy->removeAbstractTypeUser(this);
1308 }
1309
1310 void dump() const {
Bill Wendling6a462f12006-11-17 08:03:48 +00001311 DOUT << "Constant.cpp: ValueMap\n";
Chris Lattner98fa07b2003-05-23 20:03:32 +00001312 }
1313 };
1314}
1315
Chris Lattnera84df0a22006-09-28 23:36:21 +00001316
Chris Lattner28173502007-02-20 06:11:36 +00001317
Chris Lattner9fba3da2004-02-15 05:53:04 +00001318//---- ConstantAggregateZero::get() implementation...
1319//
1320namespace llvm {
1321 // ConstantAggregateZero does not take extra "value" argument...
1322 template<class ValType>
1323 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
1324 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
1325 return new ConstantAggregateZero(Ty);
1326 }
1327 };
1328
1329 template<>
1330 struct ConvertConstantType<ConstantAggregateZero, Type> {
1331 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
1332 // Make everyone now use a constant of the new type...
1333 Constant *New = ConstantAggregateZero::get(NewTy);
1334 assert(New != OldC && "Didn't replace constant??");
1335 OldC->uncheckedReplaceAllUsesWith(New);
1336 OldC->destroyConstant(); // This constant is now dead, destroy it.
1337 }
1338 };
1339}
1340
Chris Lattner69edc982006-09-28 00:35:06 +00001341static ManagedStatic<ValueMap<char, Type,
1342 ConstantAggregateZero> > AggZeroConstants;
Chris Lattner9fba3da2004-02-15 05:53:04 +00001343
Chris Lattner3e650af2004-08-04 04:48:01 +00001344static char getValType(ConstantAggregateZero *CPZ) { return 0; }
1345
Dan Gohman8214fc12008-12-08 07:10:54 +00001346ConstantAggregateZero *ConstantAggregateZero::get(const Type *Ty) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001347 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) &&
Chris Lattnerbfd0b6d2006-06-10 04:16:23 +00001348 "Cannot create an aggregate zero of non-aggregate type!");
Chris Lattner69edc982006-09-28 00:35:06 +00001349 return AggZeroConstants->getOrCreate(Ty, 0);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001350}
1351
Dan Gohman92b551b2009-03-03 02:55:14 +00001352/// destroyConstant - Remove the constant from the constant table...
1353///
Chris Lattner9fba3da2004-02-15 05:53:04 +00001354void ConstantAggregateZero::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001355 AggZeroConstants->remove(this);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001356 destroyConstantImpl();
1357}
1358
Chris Lattner3462ae32001-12-03 22:26:30 +00001359//---- ConstantArray::get() implementation...
Chris Lattner49d855c2001-09-07 16:46:31 +00001360//
Chris Lattner189d19f2003-11-21 20:23:48 +00001361namespace llvm {
1362 template<>
1363 struct ConvertConstantType<ConstantArray, ArrayType> {
1364 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
1365 // Make everyone now use a constant of the new type...
1366 std::vector<Constant*> C;
1367 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1368 C.push_back(cast<Constant>(OldC->getOperand(i)));
1369 Constant *New = ConstantArray::get(NewTy, C);
1370 assert(New != OldC && "Didn't replace constant??");
1371 OldC->uncheckedReplaceAllUsesWith(New);
1372 OldC->destroyConstant(); // This constant is now dead, destroy it.
1373 }
1374 };
1375}
Chris Lattnerb50d1352003-10-05 00:17:43 +00001376
Chris Lattner3e650af2004-08-04 04:48:01 +00001377static std::vector<Constant*> getValType(ConstantArray *CA) {
1378 std::vector<Constant*> Elements;
1379 Elements.reserve(CA->getNumOperands());
1380 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1381 Elements.push_back(cast<Constant>(CA->getOperand(i)));
1382 return Elements;
1383}
1384
Chris Lattnerb64419a2005-10-03 22:51:37 +00001385typedef ValueMap<std::vector<Constant*>, ArrayType,
Chris Lattner935aa922005-10-04 17:48:46 +00001386 ConstantArray, true /*largekey*/> ArrayConstantsTy;
Chris Lattner69edc982006-09-28 00:35:06 +00001387static ManagedStatic<ArrayConstantsTy> ArrayConstants;
Chris Lattner49d855c2001-09-07 16:46:31 +00001388
Chris Lattner015e8212004-02-15 04:14:47 +00001389Constant *ConstantArray::get(const ArrayType *Ty,
Chris Lattner9fba3da2004-02-15 05:53:04 +00001390 const std::vector<Constant*> &V) {
1391 // If this is an all-zero array, return a ConstantAggregateZero object
1392 if (!V.empty()) {
1393 Constant *C = V[0];
1394 if (!C->isNullValue())
Chris Lattner69edc982006-09-28 00:35:06 +00001395 return ArrayConstants->getOrCreate(Ty, V);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001396 for (unsigned i = 1, e = V.size(); i != e; ++i)
1397 if (V[i] != C)
Chris Lattner69edc982006-09-28 00:35:06 +00001398 return ArrayConstants->getOrCreate(Ty, V);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001399 }
1400 return ConstantAggregateZero::get(Ty);
Chris Lattner49d855c2001-09-07 16:46:31 +00001401}
1402
Dan Gohman92b551b2009-03-03 02:55:14 +00001403/// destroyConstant - Remove the constant from the constant table...
1404///
Chris Lattner98fa07b2003-05-23 20:03:32 +00001405void ConstantArray::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001406 ArrayConstants->remove(this);
Chris Lattner98fa07b2003-05-23 20:03:32 +00001407 destroyConstantImpl();
1408}
1409
Reid Spencer6f614532006-05-30 08:23:18 +00001410/// ConstantArray::get(const string&) - Return an array that is initialized to
1411/// contain the specified string. If length is zero then a null terminator is
1412/// added to the specified string so that it may be used in a natural way.
1413/// Otherwise, the length parameter specifies how much of the string to use
1414/// and it won't be null terminated.
1415///
Reid Spencer82ebaba2006-05-30 18:15:07 +00001416Constant *ConstantArray::get(const std::string &Str, bool AddNull) {
Chris Lattner7f74a562002-01-20 22:54:45 +00001417 std::vector<Constant*> ElementVals;
Reid Spencer82ebaba2006-05-30 18:15:07 +00001418 for (unsigned i = 0; i < Str.length(); ++i)
Reid Spencer8d9336d2006-12-31 05:26:44 +00001419 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, Str[i]));
Chris Lattner8f80fe02001-10-14 23:54:12 +00001420
1421 // Add a null terminator to the string...
Reid Spencer82ebaba2006-05-30 18:15:07 +00001422 if (AddNull) {
Reid Spencer8d9336d2006-12-31 05:26:44 +00001423 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, 0));
Reid Spencer6f614532006-05-30 08:23:18 +00001424 }
Chris Lattner8f80fe02001-10-14 23:54:12 +00001425
Reid Spencer8d9336d2006-12-31 05:26:44 +00001426 ArrayType *ATy = ArrayType::get(Type::Int8Ty, ElementVals.size());
Chris Lattner3462ae32001-12-03 22:26:30 +00001427 return ConstantArray::get(ATy, ElementVals);
Vikram S. Adve34410432001-10-14 23:17:20 +00001428}
1429
Reid Spencer2546b762007-01-26 07:37:34 +00001430/// isString - This method returns true if the array is an array of i8, and
1431/// if the elements of the array are all ConstantInt's.
Chris Lattnere8dfcca2004-01-14 17:06:38 +00001432bool ConstantArray::isString() const {
Reid Spencer2546b762007-01-26 07:37:34 +00001433 // Check the element type for i8...
Reid Spencer8d9336d2006-12-31 05:26:44 +00001434 if (getType()->getElementType() != Type::Int8Ty)
Chris Lattnere8dfcca2004-01-14 17:06:38 +00001435 return false;
1436 // Check the elements to make sure they are all integers, not constant
1437 // expressions.
1438 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1439 if (!isa<ConstantInt>(getOperand(i)))
1440 return false;
1441 return true;
1442}
1443
Evan Cheng3763c5b2006-10-26 19:15:05 +00001444/// isCString - This method returns true if the array is a string (see
Dan Gohman92b551b2009-03-03 02:55:14 +00001445/// isString) and it ends in a null byte \\0 and does not contains any other
Evan Cheng3763c5b2006-10-26 19:15:05 +00001446/// null bytes except its terminator.
1447bool ConstantArray::isCString() const {
Reid Spencer2546b762007-01-26 07:37:34 +00001448 // Check the element type for i8...
Reid Spencer8d9336d2006-12-31 05:26:44 +00001449 if (getType()->getElementType() != Type::Int8Ty)
Evan Chenge974da62006-10-26 21:48:03 +00001450 return false;
1451 Constant *Zero = Constant::getNullValue(getOperand(0)->getType());
1452 // Last element must be a null.
1453 if (getOperand(getNumOperands()-1) != Zero)
1454 return false;
1455 // Other elements must be non-null integers.
1456 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1457 if (!isa<ConstantInt>(getOperand(i)))
Evan Cheng3763c5b2006-10-26 19:15:05 +00001458 return false;
Evan Chenge974da62006-10-26 21:48:03 +00001459 if (getOperand(i) == Zero)
1460 return false;
1461 }
Evan Cheng3763c5b2006-10-26 19:15:05 +00001462 return true;
1463}
1464
1465
Dan Gohman92b551b2009-03-03 02:55:14 +00001466/// getAsString - If the sub-element type of this array is i8
1467/// then this method converts the array to an std::string and returns it.
1468/// Otherwise, it asserts out.
1469///
Chris Lattner81fabb02002-08-26 17:53:56 +00001470std::string ConstantArray::getAsString() const {
Chris Lattnere8dfcca2004-01-14 17:06:38 +00001471 assert(isString() && "Not a string!");
Chris Lattner81fabb02002-08-26 17:53:56 +00001472 std::string Result;
Owen Anderson79c69bc2008-06-24 21:58:29 +00001473 Result.reserve(getNumOperands());
Chris Lattner6077c312003-07-23 15:22:26 +00001474 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
Owen Andersonee9c30d2008-06-25 01:05:05 +00001475 Result.push_back((char)cast<ConstantInt>(getOperand(i))->getZExtValue());
Chris Lattner81fabb02002-08-26 17:53:56 +00001476 return Result;
1477}
1478
1479
Chris Lattner3462ae32001-12-03 22:26:30 +00001480//---- ConstantStruct::get() implementation...
Chris Lattner49d855c2001-09-07 16:46:31 +00001481//
Chris Lattnerb50d1352003-10-05 00:17:43 +00001482
Chris Lattner189d19f2003-11-21 20:23:48 +00001483namespace llvm {
1484 template<>
1485 struct ConvertConstantType<ConstantStruct, StructType> {
1486 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1487 // Make everyone now use a constant of the new type...
1488 std::vector<Constant*> C;
1489 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1490 C.push_back(cast<Constant>(OldC->getOperand(i)));
1491 Constant *New = ConstantStruct::get(NewTy, C);
1492 assert(New != OldC && "Didn't replace constant??");
Misha Brukmanb1c93172005-04-21 23:48:37 +00001493
Chris Lattner189d19f2003-11-21 20:23:48 +00001494 OldC->uncheckedReplaceAllUsesWith(New);
1495 OldC->destroyConstant(); // This constant is now dead, destroy it.
1496 }
1497 };
1498}
Chris Lattnerb50d1352003-10-05 00:17:43 +00001499
Chris Lattner8760ec72005-10-04 01:17:50 +00001500typedef ValueMap<std::vector<Constant*>, StructType,
Chris Lattner935aa922005-10-04 17:48:46 +00001501 ConstantStruct, true /*largekey*/> StructConstantsTy;
Chris Lattner69edc982006-09-28 00:35:06 +00001502static ManagedStatic<StructConstantsTy> StructConstants;
Chris Lattner49d855c2001-09-07 16:46:31 +00001503
Chris Lattner3e650af2004-08-04 04:48:01 +00001504static std::vector<Constant*> getValType(ConstantStruct *CS) {
1505 std::vector<Constant*> Elements;
1506 Elements.reserve(CS->getNumOperands());
1507 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1508 Elements.push_back(cast<Constant>(CS->getOperand(i)));
1509 return Elements;
1510}
1511
Chris Lattner015e8212004-02-15 04:14:47 +00001512Constant *ConstantStruct::get(const StructType *Ty,
1513 const std::vector<Constant*> &V) {
Chris Lattner9fba3da2004-02-15 05:53:04 +00001514 // Create a ConstantAggregateZero value if all elements are zeros...
1515 for (unsigned i = 0, e = V.size(); i != e; ++i)
1516 if (!V[i]->isNullValue())
Chris Lattner69edc982006-09-28 00:35:06 +00001517 return StructConstants->getOrCreate(Ty, V);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001518
1519 return ConstantAggregateZero::get(Ty);
Chris Lattner49d855c2001-09-07 16:46:31 +00001520}
Chris Lattner883ad0b2001-10-03 15:39:36 +00001521
Andrew Lenharthdcb3c972006-12-08 18:06:16 +00001522Constant *ConstantStruct::get(const std::vector<Constant*> &V, bool packed) {
Chris Lattnerd6108ca2004-07-12 20:35:11 +00001523 std::vector<const Type*> StructEls;
1524 StructEls.reserve(V.size());
1525 for (unsigned i = 0, e = V.size(); i != e; ++i)
1526 StructEls.push_back(V[i]->getType());
Andrew Lenharthdcb3c972006-12-08 18:06:16 +00001527 return get(StructType::get(StructEls, packed), V);
Chris Lattnerd6108ca2004-07-12 20:35:11 +00001528}
1529
Chris Lattnerd7a73302001-10-13 06:57:33 +00001530// destroyConstant - Remove the constant from the constant table...
Chris Lattner883ad0b2001-10-03 15:39:36 +00001531//
Chris Lattner3462ae32001-12-03 22:26:30 +00001532void ConstantStruct::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001533 StructConstants->remove(this);
Chris Lattnerd7a73302001-10-13 06:57:33 +00001534 destroyConstantImpl();
1535}
Chris Lattner883ad0b2001-10-03 15:39:36 +00001536
Reid Spencerd84d35b2007-02-15 02:26:10 +00001537//---- ConstantVector::get() implementation...
Brian Gaeke02209042004-08-20 06:00:58 +00001538//
1539namespace llvm {
1540 template<>
Reid Spencerd84d35b2007-02-15 02:26:10 +00001541 struct ConvertConstantType<ConstantVector, VectorType> {
1542 static void convert(ConstantVector *OldC, const VectorType *NewTy) {
Brian Gaeke02209042004-08-20 06:00:58 +00001543 // Make everyone now use a constant of the new type...
1544 std::vector<Constant*> C;
1545 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1546 C.push_back(cast<Constant>(OldC->getOperand(i)));
Reid Spencerd84d35b2007-02-15 02:26:10 +00001547 Constant *New = ConstantVector::get(NewTy, C);
Brian Gaeke02209042004-08-20 06:00:58 +00001548 assert(New != OldC && "Didn't replace constant??");
1549 OldC->uncheckedReplaceAllUsesWith(New);
1550 OldC->destroyConstant(); // This constant is now dead, destroy it.
1551 }
1552 };
1553}
1554
Reid Spencerd84d35b2007-02-15 02:26:10 +00001555static std::vector<Constant*> getValType(ConstantVector *CP) {
Brian Gaeke02209042004-08-20 06:00:58 +00001556 std::vector<Constant*> Elements;
1557 Elements.reserve(CP->getNumOperands());
1558 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1559 Elements.push_back(CP->getOperand(i));
1560 return Elements;
1561}
1562
Reid Spencerd84d35b2007-02-15 02:26:10 +00001563static ManagedStatic<ValueMap<std::vector<Constant*>, VectorType,
Reid Spencer09575ba2007-02-15 03:39:18 +00001564 ConstantVector> > VectorConstants;
Brian Gaeke02209042004-08-20 06:00:58 +00001565
Reid Spencerd84d35b2007-02-15 02:26:10 +00001566Constant *ConstantVector::get(const VectorType *Ty,
Brian Gaeke02209042004-08-20 06:00:58 +00001567 const std::vector<Constant*> &V) {
Chris Lattnerd977c072008-07-10 00:44:03 +00001568 assert(!V.empty() && "Vectors can't be empty");
1569 // If this is an all-undef or alll-zero vector, return a
1570 // ConstantAggregateZero or UndefValue.
1571 Constant *C = V[0];
1572 bool isZero = C->isNullValue();
1573 bool isUndef = isa<UndefValue>(C);
1574
1575 if (isZero || isUndef) {
Brian Gaeke02209042004-08-20 06:00:58 +00001576 for (unsigned i = 1, e = V.size(); i != e; ++i)
Chris Lattnerd977c072008-07-10 00:44:03 +00001577 if (V[i] != C) {
1578 isZero = isUndef = false;
1579 break;
1580 }
Brian Gaeke02209042004-08-20 06:00:58 +00001581 }
Chris Lattnerd977c072008-07-10 00:44:03 +00001582
1583 if (isZero)
1584 return ConstantAggregateZero::get(Ty);
1585 if (isUndef)
1586 return UndefValue::get(Ty);
1587 return VectorConstants->getOrCreate(Ty, V);
Brian Gaeke02209042004-08-20 06:00:58 +00001588}
1589
Reid Spencerd84d35b2007-02-15 02:26:10 +00001590Constant *ConstantVector::get(const std::vector<Constant*> &V) {
Brian Gaeke02209042004-08-20 06:00:58 +00001591 assert(!V.empty() && "Cannot infer type if V is empty");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001592 return get(VectorType::get(V.front()->getType(),V.size()), V);
Brian Gaeke02209042004-08-20 06:00:58 +00001593}
1594
1595// destroyConstant - Remove the constant from the constant table...
1596//
Reid Spencerd84d35b2007-02-15 02:26:10 +00001597void ConstantVector::destroyConstant() {
Reid Spencer09575ba2007-02-15 03:39:18 +00001598 VectorConstants->remove(this);
Brian Gaeke02209042004-08-20 06:00:58 +00001599 destroyConstantImpl();
1600}
1601
Dan Gohman30978072007-05-24 14:36:04 +00001602/// This function will return true iff every element in this vector constant
Jim Laskeyf0478822007-01-12 22:39:14 +00001603/// is set to all ones.
1604/// @returns true iff this constant's emements are all set to all ones.
1605/// @brief Determine if the value is all ones.
Reid Spencerd84d35b2007-02-15 02:26:10 +00001606bool ConstantVector::isAllOnesValue() const {
Jim Laskeyf0478822007-01-12 22:39:14 +00001607 // Check out first element.
1608 const Constant *Elt = getOperand(0);
1609 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1610 if (!CI || !CI->isAllOnesValue()) return false;
1611 // Then make sure all remaining elements point to the same value.
1612 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1613 if (getOperand(I) != Elt) return false;
1614 }
1615 return true;
1616}
1617
Dan Gohman07159202007-10-17 17:51:30 +00001618/// getSplatValue - If this is a splat constant, where all of the
1619/// elements have the same value, return that value. Otherwise return null.
1620Constant *ConstantVector::getSplatValue() {
1621 // Check out first element.
1622 Constant *Elt = getOperand(0);
1623 // Then make sure all remaining elements point to the same value.
1624 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1625 if (getOperand(I) != Elt) return 0;
1626 return Elt;
1627}
1628
Chris Lattner3462ae32001-12-03 22:26:30 +00001629//---- ConstantPointerNull::get() implementation...
Chris Lattnerd7a73302001-10-13 06:57:33 +00001630//
Chris Lattner98fa07b2003-05-23 20:03:32 +00001631
Chris Lattner189d19f2003-11-21 20:23:48 +00001632namespace llvm {
1633 // ConstantPointerNull does not take extra "value" argument...
1634 template<class ValType>
1635 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1636 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1637 return new ConstantPointerNull(Ty);
1638 }
1639 };
Chris Lattner98fa07b2003-05-23 20:03:32 +00001640
Chris Lattner189d19f2003-11-21 20:23:48 +00001641 template<>
1642 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1643 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1644 // Make everyone now use a constant of the new type...
1645 Constant *New = ConstantPointerNull::get(NewTy);
1646 assert(New != OldC && "Didn't replace constant??");
1647 OldC->uncheckedReplaceAllUsesWith(New);
1648 OldC->destroyConstant(); // This constant is now dead, destroy it.
1649 }
1650 };
1651}
Chris Lattnerb50d1352003-10-05 00:17:43 +00001652
Chris Lattner69edc982006-09-28 00:35:06 +00001653static ManagedStatic<ValueMap<char, PointerType,
1654 ConstantPointerNull> > NullPtrConstants;
Chris Lattnerd7a73302001-10-13 06:57:33 +00001655
Chris Lattner3e650af2004-08-04 04:48:01 +00001656static char getValType(ConstantPointerNull *) {
1657 return 0;
1658}
1659
1660
Chris Lattner3462ae32001-12-03 22:26:30 +00001661ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
Chris Lattner69edc982006-09-28 00:35:06 +00001662 return NullPtrConstants->getOrCreate(Ty, 0);
Chris Lattner883ad0b2001-10-03 15:39:36 +00001663}
1664
Chris Lattner0c6e0b92002-08-18 00:40:04 +00001665// destroyConstant - Remove the constant from the constant table...
1666//
1667void ConstantPointerNull::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001668 NullPtrConstants->remove(this);
Chris Lattner0c6e0b92002-08-18 00:40:04 +00001669 destroyConstantImpl();
1670}
1671
1672
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001673//---- UndefValue::get() implementation...
1674//
1675
1676namespace llvm {
1677 // UndefValue does not take extra "value" argument...
1678 template<class ValType>
1679 struct ConstantCreator<UndefValue, Type, ValType> {
1680 static UndefValue *create(const Type *Ty, const ValType &V) {
1681 return new UndefValue(Ty);
1682 }
1683 };
1684
1685 template<>
1686 struct ConvertConstantType<UndefValue, Type> {
1687 static void convert(UndefValue *OldC, const Type *NewTy) {
1688 // Make everyone now use a constant of the new type.
1689 Constant *New = UndefValue::get(NewTy);
1690 assert(New != OldC && "Didn't replace constant??");
1691 OldC->uncheckedReplaceAllUsesWith(New);
1692 OldC->destroyConstant(); // This constant is now dead, destroy it.
1693 }
1694 };
1695}
1696
Chris Lattner69edc982006-09-28 00:35:06 +00001697static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001698
1699static char getValType(UndefValue *) {
1700 return 0;
1701}
1702
1703
1704UndefValue *UndefValue::get(const Type *Ty) {
Chris Lattner69edc982006-09-28 00:35:06 +00001705 return UndefValueConstants->getOrCreate(Ty, 0);
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001706}
1707
1708// destroyConstant - Remove the constant from the constant table.
1709//
1710void UndefValue::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001711 UndefValueConstants->remove(this);
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001712 destroyConstantImpl();
1713}
1714
Nick Lewycky49f89192009-04-04 07:22:01 +00001715//---- MDString::get() implementation
1716//
1717
1718MDString::MDString(const char *begin, const char *end)
Nick Lewyckyadbc2842009-05-30 05:06:04 +00001719 : Constant(Type::MetadataTy, MDStringVal, 0, 0),
Nick Lewycky49f89192009-04-04 07:22:01 +00001720 StrBegin(begin), StrEnd(end) {}
1721
1722static ManagedStatic<StringMap<MDString*> > MDStringCache;
1723
1724MDString *MDString::get(const char *StrBegin, const char *StrEnd) {
1725 StringMapEntry<MDString *> &Entry = MDStringCache->GetOrCreateValue(StrBegin,
1726 StrEnd);
1727 MDString *&S = Entry.getValue();
1728 if (!S) S = new MDString(Entry.getKeyData(),
1729 Entry.getKeyData() + Entry.getKeyLength());
1730 return S;
1731}
1732
1733void MDString::destroyConstant() {
1734 MDStringCache->erase(MDStringCache->find(StrBegin, StrEnd));
1735 destroyConstantImpl();
1736}
1737
1738//---- MDNode::get() implementation
1739//
1740
1741static ManagedStatic<FoldingSet<MDNode> > MDNodeSet;
1742
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00001743MDNode::MDNode(Value*const* Vals, unsigned NumVals)
Nick Lewyckyadbc2842009-05-30 05:06:04 +00001744 : Constant(Type::MetadataTy, MDNodeVal, 0, 0) {
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00001745 for (unsigned i = 0; i != NumVals; ++i)
1746 Node.push_back(ElementVH(Vals[i], this));
Nick Lewycky49f89192009-04-04 07:22:01 +00001747}
1748
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00001749void MDNode::Profile(FoldingSetNodeID &ID) const {
1750 for (const_elem_iterator I = elem_begin(), E = elem_end(); I != E; ++I)
Nick Lewycky49f89192009-04-04 07:22:01 +00001751 ID.AddPointer(*I);
1752}
1753
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00001754MDNode *MDNode::get(Value*const* Vals, unsigned NumVals) {
Nick Lewycky49f89192009-04-04 07:22:01 +00001755 FoldingSetNodeID ID;
1756 for (unsigned i = 0; i != NumVals; ++i)
1757 ID.AddPointer(Vals[i]);
1758
1759 void *InsertPoint;
1760 if (MDNode *N = MDNodeSet->FindNodeOrInsertPos(ID, InsertPoint))
1761 return N;
1762
1763 // InsertPoint will have been set by the FindNodeOrInsertPos call.
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00001764 MDNode *N = new(0) MDNode(Vals, NumVals);
Nick Lewycky49f89192009-04-04 07:22:01 +00001765 MDNodeSet->InsertNode(N, InsertPoint);
1766 return N;
1767}
1768
1769void MDNode::destroyConstant() {
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00001770 MDNodeSet->RemoveNode(this);
Nick Lewycky49f89192009-04-04 07:22:01 +00001771 destroyConstantImpl();
1772}
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001773
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001774//---- ConstantExpr::get() implementations...
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001775//
Reid Spencer8d9336d2006-12-31 05:26:44 +00001776
Dan Gohmand78c4002008-05-13 00:00:25 +00001777namespace {
1778
Reid Spenceree3c9912006-12-04 05:19:50 +00001779struct ExprMapKeyType {
Dan Gohman1ecaf452008-05-31 00:58:22 +00001780 typedef SmallVector<unsigned, 4> IndexList;
1781
1782 ExprMapKeyType(unsigned opc,
1783 const std::vector<Constant*> &ops,
1784 unsigned short pred = 0,
1785 const IndexList &inds = IndexList())
1786 : opcode(opc), predicate(pred), operands(ops), indices(inds) {}
Reid Spencerdba6aa42006-12-04 18:38:05 +00001787 uint16_t opcode;
1788 uint16_t predicate;
Reid Spenceree3c9912006-12-04 05:19:50 +00001789 std::vector<Constant*> operands;
Dan Gohman1ecaf452008-05-31 00:58:22 +00001790 IndexList indices;
Reid Spenceree3c9912006-12-04 05:19:50 +00001791 bool operator==(const ExprMapKeyType& that) const {
1792 return this->opcode == that.opcode &&
1793 this->predicate == that.predicate &&
Bill Wendling97f7de82008-10-26 00:19:56 +00001794 this->operands == that.operands &&
Dan Gohman1ecaf452008-05-31 00:58:22 +00001795 this->indices == that.indices;
Reid Spenceree3c9912006-12-04 05:19:50 +00001796 }
1797 bool operator<(const ExprMapKeyType & that) const {
1798 return this->opcode < that.opcode ||
1799 (this->opcode == that.opcode && this->predicate < that.predicate) ||
1800 (this->opcode == that.opcode && this->predicate == that.predicate &&
Dan Gohman1ecaf452008-05-31 00:58:22 +00001801 this->operands < that.operands) ||
1802 (this->opcode == that.opcode && this->predicate == that.predicate &&
1803 this->operands == that.operands && this->indices < that.indices);
Reid Spenceree3c9912006-12-04 05:19:50 +00001804 }
1805
1806 bool operator!=(const ExprMapKeyType& that) const {
1807 return !(*this == that);
1808 }
1809};
Chris Lattner98fa07b2003-05-23 20:03:32 +00001810
Dan Gohmand78c4002008-05-13 00:00:25 +00001811}
1812
Chris Lattner189d19f2003-11-21 20:23:48 +00001813namespace llvm {
1814 template<>
1815 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
Reid Spencer10fbf0e2006-12-03 05:48:19 +00001816 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1817 unsigned short pred = 0) {
Reid Spenceree3c9912006-12-04 05:19:50 +00001818 if (Instruction::isCast(V.opcode))
1819 return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1820 if ((V.opcode >= Instruction::BinaryOpsBegin &&
Reid Spencer2341c222007-02-02 02:16:23 +00001821 V.opcode < Instruction::BinaryOpsEnd))
Reid Spenceree3c9912006-12-04 05:19:50 +00001822 return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1823 if (V.opcode == Instruction::Select)
1824 return new SelectConstantExpr(V.operands[0], V.operands[1],
1825 V.operands[2]);
1826 if (V.opcode == Instruction::ExtractElement)
1827 return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1828 if (V.opcode == Instruction::InsertElement)
1829 return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1830 V.operands[2]);
1831 if (V.opcode == Instruction::ShuffleVector)
1832 return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1833 V.operands[2]);
Dan Gohman1ecaf452008-05-31 00:58:22 +00001834 if (V.opcode == Instruction::InsertValue)
1835 return new InsertValueConstantExpr(V.operands[0], V.operands[1],
1836 V.indices, Ty);
1837 if (V.opcode == Instruction::ExtractValue)
1838 return new ExtractValueConstantExpr(V.operands[0], V.indices, Ty);
Reid Spenceree3c9912006-12-04 05:19:50 +00001839 if (V.opcode == Instruction::GetElementPtr) {
1840 std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
Gabor Greife9ecc682008-04-06 20:25:17 +00001841 return GetElementPtrConstantExpr::Create(V.operands[0], IdxList, Ty);
Reid Spenceree3c9912006-12-04 05:19:50 +00001842 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001843
Reid Spenceree3c9912006-12-04 05:19:50 +00001844 // The compare instructions are weird. We have to encode the predicate
1845 // value and it is combined with the instruction opcode by multiplying
1846 // the opcode by one hundred. We must decode this to get the predicate.
1847 if (V.opcode == Instruction::ICmp)
Nate Begemand2195702008-05-12 19:01:56 +00001848 return new CompareConstantExpr(Ty, Instruction::ICmp, V.predicate,
Reid Spenceree3c9912006-12-04 05:19:50 +00001849 V.operands[0], V.operands[1]);
1850 if (V.opcode == Instruction::FCmp)
Nate Begemand2195702008-05-12 19:01:56 +00001851 return new CompareConstantExpr(Ty, Instruction::FCmp, V.predicate,
1852 V.operands[0], V.operands[1]);
1853 if (V.opcode == Instruction::VICmp)
1854 return new CompareConstantExpr(Ty, Instruction::VICmp, V.predicate,
1855 V.operands[0], V.operands[1]);
1856 if (V.opcode == Instruction::VFCmp)
1857 return new CompareConstantExpr(Ty, Instruction::VFCmp, V.predicate,
Reid Spenceree3c9912006-12-04 05:19:50 +00001858 V.operands[0], V.operands[1]);
1859 assert(0 && "Invalid ConstantExpr!");
Jeff Cohen9f469632006-12-15 21:47:01 +00001860 return 0;
Chris Lattnerb50d1352003-10-05 00:17:43 +00001861 }
Chris Lattner189d19f2003-11-21 20:23:48 +00001862 };
Chris Lattnerb50d1352003-10-05 00:17:43 +00001863
Chris Lattner189d19f2003-11-21 20:23:48 +00001864 template<>
1865 struct ConvertConstantType<ConstantExpr, Type> {
1866 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1867 Constant *New;
1868 switch (OldC->getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001869 case Instruction::Trunc:
1870 case Instruction::ZExt:
1871 case Instruction::SExt:
1872 case Instruction::FPTrunc:
1873 case Instruction::FPExt:
1874 case Instruction::UIToFP:
1875 case Instruction::SIToFP:
1876 case Instruction::FPToUI:
1877 case Instruction::FPToSI:
1878 case Instruction::PtrToInt:
1879 case Instruction::IntToPtr:
1880 case Instruction::BitCast:
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001881 New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0),
1882 NewTy);
Chris Lattner189d19f2003-11-21 20:23:48 +00001883 break;
Chris Lattner6e415c02004-03-12 05:54:04 +00001884 case Instruction::Select:
1885 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1886 OldC->getOperand(1),
1887 OldC->getOperand(2));
1888 break;
Chris Lattner189d19f2003-11-21 20:23:48 +00001889 default:
1890 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
Reid Spencer7eb55b32006-11-02 01:53:59 +00001891 OldC->getOpcode() < Instruction::BinaryOpsEnd);
Chris Lattner189d19f2003-11-21 20:23:48 +00001892 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1893 OldC->getOperand(1));
1894 break;
1895 case Instruction::GetElementPtr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00001896 // Make everyone now use a constant of the new type...
Chris Lattner13128ab2004-10-11 22:52:25 +00001897 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
Chris Lattner302116a2007-01-31 04:40:28 +00001898 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0),
1899 &Idx[0], Idx.size());
Chris Lattner189d19f2003-11-21 20:23:48 +00001900 break;
1901 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001902
Chris Lattner189d19f2003-11-21 20:23:48 +00001903 assert(New != OldC && "Didn't replace constant??");
1904 OldC->uncheckedReplaceAllUsesWith(New);
1905 OldC->destroyConstant(); // This constant is now dead, destroy it.
1906 }
1907 };
1908} // end namespace llvm
Chris Lattnerb50d1352003-10-05 00:17:43 +00001909
1910
Chris Lattner3e650af2004-08-04 04:48:01 +00001911static ExprMapKeyType getValType(ConstantExpr *CE) {
1912 std::vector<Constant*> Operands;
1913 Operands.reserve(CE->getNumOperands());
1914 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1915 Operands.push_back(cast<Constant>(CE->getOperand(i)));
Reid Spenceree3c9912006-12-04 05:19:50 +00001916 return ExprMapKeyType(CE->getOpcode(), Operands,
Dan Gohman1ecaf452008-05-31 00:58:22 +00001917 CE->isCompare() ? CE->getPredicate() : 0,
1918 CE->hasIndices() ?
1919 CE->getIndices() : SmallVector<unsigned, 4>());
Chris Lattner3e650af2004-08-04 04:48:01 +00001920}
1921
Chris Lattner69edc982006-09-28 00:35:06 +00001922static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1923 ConstantExpr> > ExprConstants;
Vikram S. Adve4c485332002-07-15 18:19:33 +00001924
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001925/// This is a utility function to handle folding of casts and lookup of the
Duncan Sands7d6c8ae2008-03-30 19:38:55 +00001926/// cast in the ExprConstants map. It is used by the various get* methods below.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001927static inline Constant *getFoldedCast(
1928 Instruction::CastOps opc, Constant *C, const Type *Ty) {
Chris Lattner815ae2b2003-10-07 22:19:19 +00001929 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001930 // Fold a few common cases
1931 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1932 return FC;
Chris Lattneracdbe712003-04-17 19:24:48 +00001933
Vikram S. Adve4c485332002-07-15 18:19:33 +00001934 // Look up the constant in the table first to ensure uniqueness
Chris Lattner2b383d2e2003-05-13 21:37:02 +00001935 std::vector<Constant*> argVec(1, C);
Reid Spenceree3c9912006-12-04 05:19:50 +00001936 ExprMapKeyType Key(opc, argVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001937 return ExprConstants->getOrCreate(Ty, Key);
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001938}
Reid Spencerf37dc652006-12-05 19:14:13 +00001939
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001940Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1941 Instruction::CastOps opc = Instruction::CastOps(oc);
1942 assert(Instruction::isCast(opc) && "opcode out of range");
1943 assert(C && Ty && "Null arguments to getCast");
1944 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1945
1946 switch (opc) {
1947 default:
1948 assert(0 && "Invalid cast opcode");
1949 break;
1950 case Instruction::Trunc: return getTrunc(C, Ty);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001951 case Instruction::ZExt: return getZExt(C, Ty);
1952 case Instruction::SExt: return getSExt(C, Ty);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001953 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1954 case Instruction::FPExt: return getFPExtend(C, Ty);
1955 case Instruction::UIToFP: return getUIToFP(C, Ty);
1956 case Instruction::SIToFP: return getSIToFP(C, Ty);
1957 case Instruction::FPToUI: return getFPToUI(C, Ty);
1958 case Instruction::FPToSI: return getFPToSI(C, Ty);
1959 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1960 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1961 case Instruction::BitCast: return getBitCast(C, Ty);
Chris Lattner1ece6f82005-01-01 15:59:57 +00001962 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001963 return 0;
Reid Spencerf37dc652006-12-05 19:14:13 +00001964}
1965
Reid Spencer5c140882006-12-04 20:17:56 +00001966Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001967 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
Reid Spencer5c140882006-12-04 20:17:56 +00001968 return getCast(Instruction::BitCast, C, Ty);
1969 return getCast(Instruction::ZExt, C, Ty);
1970}
1971
1972Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001973 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
Reid Spencer5c140882006-12-04 20:17:56 +00001974 return getCast(Instruction::BitCast, C, Ty);
1975 return getCast(Instruction::SExt, C, Ty);
1976}
1977
1978Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001979 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
Reid Spencer5c140882006-12-04 20:17:56 +00001980 return getCast(Instruction::BitCast, C, Ty);
1981 return getCast(Instruction::Trunc, C, Ty);
1982}
1983
Reid Spencerbc245a02006-12-05 03:25:26 +00001984Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1985 assert(isa<PointerType>(S->getType()) && "Invalid cast");
Chris Lattner03c49532007-01-15 02:27:26 +00001986 assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
Reid Spencerbc245a02006-12-05 03:25:26 +00001987
Chris Lattner03c49532007-01-15 02:27:26 +00001988 if (Ty->isInteger())
Reid Spencerbc245a02006-12-05 03:25:26 +00001989 return getCast(Instruction::PtrToInt, S, Ty);
1990 return getCast(Instruction::BitCast, S, Ty);
1991}
1992
Reid Spencer56521c42006-12-12 00:51:07 +00001993Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
1994 bool isSigned) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001995 assert(C->getType()->isIntOrIntVector() &&
1996 Ty->isIntOrIntVector() && "Invalid cast");
1997 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1998 unsigned DstBits = Ty->getScalarSizeInBits();
Reid Spencer56521c42006-12-12 00:51:07 +00001999 Instruction::CastOps opcode =
2000 (SrcBits == DstBits ? Instruction::BitCast :
2001 (SrcBits > DstBits ? Instruction::Trunc :
2002 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2003 return getCast(opcode, C, Ty);
2004}
2005
2006Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00002007 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
Reid Spencer56521c42006-12-12 00:51:07 +00002008 "Invalid cast");
Dan Gohman7ccc52f2009-06-15 22:12:54 +00002009 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2010 unsigned DstBits = Ty->getScalarSizeInBits();
Reid Spencerca104e82006-12-12 05:38:50 +00002011 if (SrcBits == DstBits)
2012 return C; // Avoid a useless cast
Reid Spencer56521c42006-12-12 00:51:07 +00002013 Instruction::CastOps opcode =
Reid Spencerca104e82006-12-12 05:38:50 +00002014 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
Reid Spencer56521c42006-12-12 00:51:07 +00002015 return getCast(opcode, C, Ty);
2016}
2017
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002018Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00002019#ifndef NDEBUG
2020 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2021 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2022#endif
2023 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2024 assert(C->getType()->isIntOrIntVector() && "Trunc operand must be integer");
2025 assert(Ty->isIntOrIntVector() && "Trunc produces only integral");
2026 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002027 "SrcTy must be larger than DestTy for Trunc!");
2028
2029 return getFoldedCast(Instruction::Trunc, C, Ty);
2030}
2031
Reid Spencerbb65ebf2006-12-12 23:36:14 +00002032Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00002033#ifndef NDEBUG
2034 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2035 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2036#endif
2037 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2038 assert(C->getType()->isIntOrIntVector() && "SExt operand must be integral");
2039 assert(Ty->isIntOrIntVector() && "SExt produces only integer");
2040 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002041 "SrcTy must be smaller than DestTy for SExt!");
2042
2043 return getFoldedCast(Instruction::SExt, C, Ty);
Chris Lattnerdd284742004-04-04 23:20:30 +00002044}
2045
Reid Spencerbb65ebf2006-12-12 23:36:14 +00002046Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00002047#ifndef NDEBUG
2048 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2049 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2050#endif
2051 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2052 assert(C->getType()->isIntOrIntVector() && "ZEXt operand must be integral");
2053 assert(Ty->isIntOrIntVector() && "ZExt produces only integer");
2054 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002055 "SrcTy must be smaller than DestTy for ZExt!");
2056
2057 return getFoldedCast(Instruction::ZExt, C, Ty);
2058}
2059
2060Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00002061#ifndef NDEBUG
2062 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2063 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2064#endif
2065 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2066 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
2067 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002068 "This is an illegal floating point truncation!");
2069 return getFoldedCast(Instruction::FPTrunc, C, Ty);
2070}
2071
2072Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00002073#ifndef NDEBUG
2074 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2075 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2076#endif
2077 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2078 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
2079 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002080 "This is an illegal floating point extension!");
2081 return getFoldedCast(Instruction::FPExt, C, Ty);
2082}
2083
2084Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
Devang Pateld26344d2008-11-03 23:20:04 +00002085#ifndef NDEBUG
Nate Begemand4d45c22007-11-17 03:58:34 +00002086 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2087 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Pateld26344d2008-11-03 23:20:04 +00002088#endif
Nate Begemand4d45c22007-11-17 03:58:34 +00002089 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2090 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
2091 "This is an illegal uint to floating point cast!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002092 return getFoldedCast(Instruction::UIToFP, C, Ty);
2093}
2094
2095Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
Devang Pateld26344d2008-11-03 23:20:04 +00002096#ifndef NDEBUG
Nate Begemand4d45c22007-11-17 03:58:34 +00002097 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2098 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Pateld26344d2008-11-03 23:20:04 +00002099#endif
Nate Begemand4d45c22007-11-17 03:58:34 +00002100 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2101 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002102 "This is an illegal sint to floating point cast!");
2103 return getFoldedCast(Instruction::SIToFP, C, Ty);
2104}
2105
2106Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
Devang Pateld26344d2008-11-03 23:20:04 +00002107#ifndef NDEBUG
Nate Begemand4d45c22007-11-17 03:58:34 +00002108 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2109 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Pateld26344d2008-11-03 23:20:04 +00002110#endif
Nate Begemand4d45c22007-11-17 03:58:34 +00002111 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2112 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
2113 "This is an illegal floating point to uint cast!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002114 return getFoldedCast(Instruction::FPToUI, C, Ty);
2115}
2116
2117Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
Devang Pateld26344d2008-11-03 23:20:04 +00002118#ifndef NDEBUG
Nate Begemand4d45c22007-11-17 03:58:34 +00002119 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2120 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Pateld26344d2008-11-03 23:20:04 +00002121#endif
Nate Begemand4d45c22007-11-17 03:58:34 +00002122 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2123 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
2124 "This is an illegal floating point to sint cast!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002125 return getFoldedCast(Instruction::FPToSI, C, Ty);
2126}
2127
2128Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
2129 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
Chris Lattner03c49532007-01-15 02:27:26 +00002130 assert(DstTy->isInteger() && "PtrToInt destination must be integral");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002131 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
2132}
2133
2134Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
Chris Lattner03c49532007-01-15 02:27:26 +00002135 assert(C->getType()->isInteger() && "IntToPtr source must be integral");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002136 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
2137 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
2138}
2139
2140Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
2141 // BitCast implies a no-op cast of type only. No bits change. However, you
2142 // can't cast pointers to anything but pointers.
Devang Pateld26344d2008-11-03 23:20:04 +00002143#ifndef NDEBUG
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002144 const Type *SrcTy = C->getType();
2145 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
Reid Spencer5c140882006-12-04 20:17:56 +00002146 "BitCast cannot cast pointer to non-pointer and vice versa");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002147
2148 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
2149 // or nonptr->ptr). For all the other types, the cast is okay if source and
2150 // destination bit widths are identical.
2151 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
2152 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
Devang Pateld26344d2008-11-03 23:20:04 +00002153#endif
Chris Lattnere4086012009-03-08 04:06:26 +00002154 assert(SrcBitSize == DstBitSize && "BitCast requires types of same width");
Chris Lattnercbeda872009-03-21 06:55:54 +00002155
2156 // It is common to ask for a bitcast of a value to its own type, handle this
2157 // speedily.
2158 if (C->getType() == DstTy) return C;
2159
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002160 return getFoldedCast(Instruction::BitCast, C, DstTy);
Chris Lattnerdd284742004-04-04 23:20:30 +00002161}
2162
Duncan Sandsd334aca2009-05-21 15:52:21 +00002163Constant *ConstantExpr::getAlignOf(const Type *Ty) {
2164 // alignof is implemented as: (i64) gep ({i8,Ty}*)null, 0, 1
2165 const Type *AligningTy = StructType::get(Type::Int8Ty, Ty, NULL);
2166 Constant *NullPtr = getNullValue(AligningTy->getPointerTo());
2167 Constant *Zero = ConstantInt::get(Type::Int32Ty, 0);
2168 Constant *One = ConstantInt::get(Type::Int32Ty, 1);
2169 Constant *Indices[2] = { Zero, One };
2170 Constant *GEP = getGetElementPtr(NullPtr, Indices, 2);
2171 return getCast(Instruction::PtrToInt, GEP, Type::Int32Ty);
2172}
2173
Alkis Evlogimenosda5de052004-10-24 01:41:10 +00002174Constant *ConstantExpr::getSizeOf(const Type *Ty) {
Gordon Henriksen7ce31762007-10-06 14:29:36 +00002175 // sizeof is implemented as: (i64) gep (Ty*)null, 1
Chris Lattnerb5d70302007-02-19 20:01:23 +00002176 Constant *GEPIdx = ConstantInt::get(Type::Int32Ty, 1);
2177 Constant *GEP =
Christopher Lambedf07882007-12-17 01:12:55 +00002178 getGetElementPtr(getNullValue(PointerType::getUnqual(Ty)), &GEPIdx, 1);
Chris Lattnerb5d70302007-02-19 20:01:23 +00002179 return getCast(Instruction::PtrToInt, GEP, Type::Int64Ty);
Alkis Evlogimenos9160d5f2005-03-19 11:40:31 +00002180}
2181
Chris Lattnerb50d1352003-10-05 00:17:43 +00002182Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
Reid Spencera009d0d2006-12-04 21:35:24 +00002183 Constant *C1, Constant *C2) {
Chris Lattner38a9bcd2003-05-21 17:49:25 +00002184 // Check the operands for consistency first
Reid Spencer7eb55b32006-11-02 01:53:59 +00002185 assert(Opcode >= Instruction::BinaryOpsBegin &&
2186 Opcode < Instruction::BinaryOpsEnd &&
Chris Lattner38a9bcd2003-05-21 17:49:25 +00002187 "Invalid opcode in binary constant expression");
2188 assert(C1->getType() == C2->getType() &&
2189 "Operand types in binary constant expression should match");
Chris Lattnerb50d1352003-10-05 00:17:43 +00002190
Reid Spencer542964f2007-01-11 18:21:29 +00002191 if (ReqTy == C1->getType() || ReqTy == Type::Int1Ty)
Chris Lattnerb50d1352003-10-05 00:17:43 +00002192 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
2193 return FC; // Fold a few common cases...
Chris Lattneracdbe712003-04-17 19:24:48 +00002194
Chris Lattner2b383d2e2003-05-13 21:37:02 +00002195 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
Reid Spencera009d0d2006-12-04 21:35:24 +00002196 ExprMapKeyType Key(Opcode, argVec);
Chris Lattner69edc982006-09-28 00:35:06 +00002197 return ExprConstants->getOrCreate(ReqTy, Key);
Vikram S. Adve4e537b22002-07-14 23:13:17 +00002198}
2199
Reid Spencer266e42b2006-12-23 06:05:41 +00002200Constant *ConstantExpr::getCompareTy(unsigned short predicate,
Nate Begeman098cc6f2008-07-25 17:56:27 +00002201 Constant *C1, Constant *C2) {
2202 bool isVectorType = C1->getType()->getTypeID() == Type::VectorTyID;
Reid Spencer266e42b2006-12-23 06:05:41 +00002203 switch (predicate) {
2204 default: assert(0 && "Invalid CmpInst predicate");
Nate Begemanc96e2e42008-07-25 17:35:37 +00002205 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
2206 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
2207 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
2208 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
2209 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
2210 case CmpInst::FCMP_TRUE:
Nate Begeman098cc6f2008-07-25 17:56:27 +00002211 return isVectorType ? getVFCmp(predicate, C1, C2)
2212 : getFCmp(predicate, C1, C2);
Nate Begemanc96e2e42008-07-25 17:35:37 +00002213 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
2214 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
2215 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
2216 case CmpInst::ICMP_SLE:
Nate Begeman098cc6f2008-07-25 17:56:27 +00002217 return isVectorType ? getVICmp(predicate, C1, C2)
2218 : getICmp(predicate, C1, C2);
Reid Spencer266e42b2006-12-23 06:05:41 +00002219 }
Reid Spencera009d0d2006-12-04 21:35:24 +00002220}
2221
2222Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
Dan Gohmana5b96452009-06-04 22:49:04 +00002223 // API compatibility: Adjust integer opcodes to floating-point opcodes.
2224 if (C1->getType()->isFPOrFPVector()) {
2225 if (Opcode == Instruction::Add) Opcode = Instruction::FAdd;
2226 else if (Opcode == Instruction::Sub) Opcode = Instruction::FSub;
2227 else if (Opcode == Instruction::Mul) Opcode = Instruction::FMul;
2228 }
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00002229#ifndef NDEBUG
2230 switch (Opcode) {
Dan Gohmana5b96452009-06-04 22:49:04 +00002231 case Instruction::Add:
Reid Spencer7eb55b32006-11-02 01:53:59 +00002232 case Instruction::Sub:
Dan Gohmana5b96452009-06-04 22:49:04 +00002233 case Instruction::Mul:
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00002234 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Dan Gohmana5b96452009-06-04 22:49:04 +00002235 assert(C1->getType()->isIntOrIntVector() &&
2236 "Tried to create an integer operation on a non-integer type!");
2237 break;
2238 case Instruction::FAdd:
2239 case Instruction::FSub:
2240 case Instruction::FMul:
2241 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2242 assert(C1->getType()->isFPOrFPVector() &&
2243 "Tried to create a floating-point operation on a "
2244 "non-floating-point type!");
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00002245 break;
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002246 case Instruction::UDiv:
2247 case Instruction::SDiv:
2248 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Dan Gohman7889f2b2009-06-15 22:25:12 +00002249 assert(C1->getType()->isIntOrIntVector() &&
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002250 "Tried to create an arithmetic operation on a non-arithmetic type!");
2251 break;
2252 case Instruction::FDiv:
2253 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Dan Gohman7889f2b2009-06-15 22:25:12 +00002254 assert(C1->getType()->isFPOrFPVector() &&
2255 "Tried to create an arithmetic operation on a non-arithmetic type!");
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002256 break;
Reid Spencer7eb55b32006-11-02 01:53:59 +00002257 case Instruction::URem:
2258 case Instruction::SRem:
2259 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Dan Gohman7889f2b2009-06-15 22:25:12 +00002260 assert(C1->getType()->isIntOrIntVector() &&
Reid Spencer7eb55b32006-11-02 01:53:59 +00002261 "Tried to create an arithmetic operation on a non-arithmetic type!");
2262 break;
2263 case Instruction::FRem:
2264 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Dan Gohman7889f2b2009-06-15 22:25:12 +00002265 assert(C1->getType()->isFPOrFPVector() &&
2266 "Tried to create an arithmetic operation on a non-arithmetic type!");
Reid Spencer7eb55b32006-11-02 01:53:59 +00002267 break;
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00002268 case Instruction::And:
2269 case Instruction::Or:
2270 case Instruction::Xor:
2271 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Dan Gohman7889f2b2009-06-15 22:25:12 +00002272 assert(C1->getType()->isIntOrIntVector() &&
Misha Brukman3852f652005-01-27 06:46:38 +00002273 "Tried to create a logical operation on a non-integral type!");
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00002274 break;
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00002275 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00002276 case Instruction::LShr:
2277 case Instruction::AShr:
Reid Spencer2341c222007-02-02 02:16:23 +00002278 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Dan Gohman79975d52009-03-14 17:09:17 +00002279 assert(C1->getType()->isIntOrIntVector() &&
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00002280 "Tried to create a shift operation on a non-integer type!");
2281 break;
2282 default:
2283 break;
2284 }
2285#endif
2286
Reid Spencera009d0d2006-12-04 21:35:24 +00002287 return getTy(C1->getType(), Opcode, C1, C2);
2288}
2289
Reid Spencer266e42b2006-12-23 06:05:41 +00002290Constant *ConstantExpr::getCompare(unsigned short pred,
Reid Spencera009d0d2006-12-04 21:35:24 +00002291 Constant *C1, Constant *C2) {
2292 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencer266e42b2006-12-23 06:05:41 +00002293 return getCompareTy(pred, C1, C2);
Chris Lattner29ca2c62004-08-04 18:50:09 +00002294}
2295
Chris Lattner6e415c02004-03-12 05:54:04 +00002296Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
2297 Constant *V1, Constant *V2) {
Chris Lattner41632132008-12-29 00:16:12 +00002298 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
Chris Lattner6e415c02004-03-12 05:54:04 +00002299
2300 if (ReqTy == V1->getType())
2301 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
2302 return SC; // Fold common cases
2303
2304 std::vector<Constant*> argVec(3, C);
2305 argVec[1] = V1;
2306 argVec[2] = V2;
Reid Spenceree3c9912006-12-04 05:19:50 +00002307 ExprMapKeyType Key(Instruction::Select, argVec);
Chris Lattner69edc982006-09-28 00:35:06 +00002308 return ExprConstants->getOrCreate(ReqTy, Key);
Chris Lattner6e415c02004-03-12 05:54:04 +00002309}
2310
Chris Lattnerb50d1352003-10-05 00:17:43 +00002311Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
Chris Lattner302116a2007-01-31 04:40:28 +00002312 Value* const *Idxs,
2313 unsigned NumIdx) {
Dan Gohman12fce772008-05-15 19:50:34 +00002314 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs,
2315 Idxs+NumIdx) ==
2316 cast<PointerType>(ReqTy)->getElementType() &&
2317 "GEP indices invalid!");
Chris Lattner04b60fe2004-02-16 20:46:13 +00002318
Chris Lattner302116a2007-01-31 04:40:28 +00002319 if (Constant *FC = ConstantFoldGetElementPtr(C, (Constant**)Idxs, NumIdx))
Chris Lattneracdbe712003-04-17 19:24:48 +00002320 return FC; // Fold a few common cases...
Chris Lattner04b60fe2004-02-16 20:46:13 +00002321
Chris Lattnerb50d1352003-10-05 00:17:43 +00002322 assert(isa<PointerType>(C->getType()) &&
Chris Lattner98fa07b2003-05-23 20:03:32 +00002323 "Non-pointer type for constant GetElementPtr expression");
Vikram S. Adve4c485332002-07-15 18:19:33 +00002324 // Look up the constant in the table first to ensure uniqueness
Chris Lattner13128ab2004-10-11 22:52:25 +00002325 std::vector<Constant*> ArgVec;
Chris Lattner302116a2007-01-31 04:40:28 +00002326 ArgVec.reserve(NumIdx+1);
Chris Lattner13128ab2004-10-11 22:52:25 +00002327 ArgVec.push_back(C);
Chris Lattner302116a2007-01-31 04:40:28 +00002328 for (unsigned i = 0; i != NumIdx; ++i)
2329 ArgVec.push_back(cast<Constant>(Idxs[i]));
2330 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
Chris Lattner69edc982006-09-28 00:35:06 +00002331 return ExprConstants->getOrCreate(ReqTy, Key);
Vikram S. Adve4c485332002-07-15 18:19:33 +00002332}
2333
Chris Lattner302116a2007-01-31 04:40:28 +00002334Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
2335 unsigned NumIdx) {
Chris Lattnerb50d1352003-10-05 00:17:43 +00002336 // Get the result type of the getelementptr!
Chris Lattner302116a2007-01-31 04:40:28 +00002337 const Type *Ty =
Dan Gohman12fce772008-05-15 19:50:34 +00002338 GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx);
Chris Lattnerb50d1352003-10-05 00:17:43 +00002339 assert(Ty && "GEP indices invalid!");
Christopher Lamb54dd24c2007-12-11 08:59:05 +00002340 unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
2341 return getGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx);
Chris Lattner13128ab2004-10-11 22:52:25 +00002342}
2343
Chris Lattner302116a2007-01-31 04:40:28 +00002344Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
2345 unsigned NumIdx) {
2346 return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
Chris Lattnerb50d1352003-10-05 00:17:43 +00002347}
2348
Chris Lattner302116a2007-01-31 04:40:28 +00002349
Reid Spenceree3c9912006-12-04 05:19:50 +00002350Constant *
2351ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2352 assert(LHS->getType() == RHS->getType());
2353 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
2354 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
2355
Reid Spencer266e42b2006-12-23 06:05:41 +00002356 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
Reid Spenceree3c9912006-12-04 05:19:50 +00002357 return FC; // Fold a few common cases...
2358
2359 // Look up the constant in the table first to ensure uniqueness
2360 std::vector<Constant*> ArgVec;
2361 ArgVec.push_back(LHS);
2362 ArgVec.push_back(RHS);
Reid Spencerb1537492006-12-24 18:42:29 +00002363 // Get the key type with both the opcode and predicate
Reid Spenceree3c9912006-12-04 05:19:50 +00002364 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
Reid Spencer542964f2007-01-11 18:21:29 +00002365 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
Reid Spenceree3c9912006-12-04 05:19:50 +00002366}
2367
2368Constant *
2369ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2370 assert(LHS->getType() == RHS->getType());
2371 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
2372
Reid Spencer266e42b2006-12-23 06:05:41 +00002373 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
Reid Spenceree3c9912006-12-04 05:19:50 +00002374 return FC; // Fold a few common cases...
2375
2376 // Look up the constant in the table first to ensure uniqueness
2377 std::vector<Constant*> ArgVec;
2378 ArgVec.push_back(LHS);
2379 ArgVec.push_back(RHS);
Reid Spencerb1537492006-12-24 18:42:29 +00002380 // Get the key type with both the opcode and predicate
Reid Spenceree3c9912006-12-04 05:19:50 +00002381 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
Reid Spencer542964f2007-01-11 18:21:29 +00002382 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
Reid Spenceree3c9912006-12-04 05:19:50 +00002383}
2384
Nate Begemand2195702008-05-12 19:01:56 +00002385Constant *
2386ConstantExpr::getVICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
Chris Lattnereab49262008-07-14 05:17:31 +00002387 assert(isa<VectorType>(LHS->getType()) && LHS->getType() == RHS->getType() &&
Nate Begemand2195702008-05-12 19:01:56 +00002388 "Tried to create vicmp operation on non-vector type!");
Nate Begemand2195702008-05-12 19:01:56 +00002389 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
2390 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid VICmp Predicate");
2391
Nate Begemanac7f3d92008-05-12 19:23:22 +00002392 const VectorType *VTy = cast<VectorType>(LHS->getType());
Nate Begemand2195702008-05-12 19:01:56 +00002393 const Type *EltTy = VTy->getElementType();
2394 unsigned NumElts = VTy->getNumElements();
2395
Chris Lattnereab49262008-07-14 05:17:31 +00002396 // See if we can fold the element-wise comparison of the LHS and RHS.
2397 SmallVector<Constant *, 16> LHSElts, RHSElts;
2398 LHS->getVectorElements(LHSElts);
2399 RHS->getVectorElements(RHSElts);
2400
2401 if (!LHSElts.empty() && !RHSElts.empty()) {
2402 SmallVector<Constant *, 16> Elts;
2403 for (unsigned i = 0; i != NumElts; ++i) {
2404 Constant *FC = ConstantFoldCompareInstruction(pred, LHSElts[i],
2405 RHSElts[i]);
2406 if (ConstantInt *FCI = dyn_cast_or_null<ConstantInt>(FC)) {
2407 if (FCI->getZExtValue())
2408 Elts.push_back(ConstantInt::getAllOnesValue(EltTy));
2409 else
2410 Elts.push_back(ConstantInt::get(EltTy, 0ULL));
2411 } else if (FC && isa<UndefValue>(FC)) {
2412 Elts.push_back(UndefValue::get(EltTy));
2413 } else {
2414 break;
2415 }
Nate Begemand2195702008-05-12 19:01:56 +00002416 }
Chris Lattnereab49262008-07-14 05:17:31 +00002417 if (Elts.size() == NumElts)
2418 return ConstantVector::get(&Elts[0], Elts.size());
Nate Begemand2195702008-05-12 19:01:56 +00002419 }
Nate Begemand2195702008-05-12 19:01:56 +00002420
2421 // Look up the constant in the table first to ensure uniqueness
2422 std::vector<Constant*> ArgVec;
2423 ArgVec.push_back(LHS);
2424 ArgVec.push_back(RHS);
2425 // Get the key type with both the opcode and predicate
2426 const ExprMapKeyType Key(Instruction::VICmp, ArgVec, pred);
2427 return ExprConstants->getOrCreate(LHS->getType(), Key);
2428}
2429
2430Constant *
2431ConstantExpr::getVFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2432 assert(isa<VectorType>(LHS->getType()) &&
2433 "Tried to create vfcmp operation on non-vector type!");
2434 assert(LHS->getType() == RHS->getType());
2435 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid VFCmp Predicate");
2436
2437 const VectorType *VTy = cast<VectorType>(LHS->getType());
2438 unsigned NumElts = VTy->getNumElements();
2439 const Type *EltTy = VTy->getElementType();
2440 const Type *REltTy = IntegerType::get(EltTy->getPrimitiveSizeInBits());
2441 const Type *ResultTy = VectorType::get(REltTy, NumElts);
2442
Chris Lattnereab49262008-07-14 05:17:31 +00002443 // See if we can fold the element-wise comparison of the LHS and RHS.
2444 SmallVector<Constant *, 16> LHSElts, RHSElts;
2445 LHS->getVectorElements(LHSElts);
2446 RHS->getVectorElements(RHSElts);
2447
2448 if (!LHSElts.empty() && !RHSElts.empty()) {
2449 SmallVector<Constant *, 16> Elts;
2450 for (unsigned i = 0; i != NumElts; ++i) {
2451 Constant *FC = ConstantFoldCompareInstruction(pred, LHSElts[i],
2452 RHSElts[i]);
2453 if (ConstantInt *FCI = dyn_cast_or_null<ConstantInt>(FC)) {
2454 if (FCI->getZExtValue())
2455 Elts.push_back(ConstantInt::getAllOnesValue(REltTy));
2456 else
2457 Elts.push_back(ConstantInt::get(REltTy, 0ULL));
2458 } else if (FC && isa<UndefValue>(FC)) {
2459 Elts.push_back(UndefValue::get(REltTy));
2460 } else {
2461 break;
2462 }
Nate Begemand2195702008-05-12 19:01:56 +00002463 }
Chris Lattnereab49262008-07-14 05:17:31 +00002464 if (Elts.size() == NumElts)
2465 return ConstantVector::get(&Elts[0], Elts.size());
Nate Begemand2195702008-05-12 19:01:56 +00002466 }
Nate Begemand2195702008-05-12 19:01:56 +00002467
2468 // Look up the constant in the table first to ensure uniqueness
2469 std::vector<Constant*> ArgVec;
2470 ArgVec.push_back(LHS);
2471 ArgVec.push_back(RHS);
2472 // Get the key type with both the opcode and predicate
2473 const ExprMapKeyType Key(Instruction::VFCmp, ArgVec, pred);
2474 return ExprConstants->getOrCreate(ResultTy, Key);
2475}
2476
Robert Bocchino23004482006-01-10 19:05:34 +00002477Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
2478 Constant *Idx) {
Robert Bocchinode7f1c92006-01-10 20:03:46 +00002479 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
2480 return FC; // Fold a few common cases...
Robert Bocchino23004482006-01-10 19:05:34 +00002481 // Look up the constant in the table first to ensure uniqueness
2482 std::vector<Constant*> ArgVec(1, Val);
2483 ArgVec.push_back(Idx);
Reid Spenceree3c9912006-12-04 05:19:50 +00002484 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
Chris Lattner69edc982006-09-28 00:35:06 +00002485 return ExprConstants->getOrCreate(ReqTy, Key);
Robert Bocchino23004482006-01-10 19:05:34 +00002486}
2487
2488Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00002489 assert(isa<VectorType>(Val->getType()) &&
Reid Spencer09575ba2007-02-15 03:39:18 +00002490 "Tried to create extractelement operation on non-vector type!");
Reid Spencer8d9336d2006-12-31 05:26:44 +00002491 assert(Idx->getType() == Type::Int32Ty &&
Reid Spencer2546b762007-01-26 07:37:34 +00002492 "Extractelement index must be i32 type!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00002493 return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
Robert Bocchino23004482006-01-10 19:05:34 +00002494 Val, Idx);
2495}
Chris Lattnerb50d1352003-10-05 00:17:43 +00002496
Robert Bocchinoca27f032006-01-17 20:07:22 +00002497Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
2498 Constant *Elt, Constant *Idx) {
2499 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
2500 return FC; // Fold a few common cases...
2501 // Look up the constant in the table first to ensure uniqueness
2502 std::vector<Constant*> ArgVec(1, Val);
2503 ArgVec.push_back(Elt);
2504 ArgVec.push_back(Idx);
Reid Spenceree3c9912006-12-04 05:19:50 +00002505 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
Chris Lattner69edc982006-09-28 00:35:06 +00002506 return ExprConstants->getOrCreate(ReqTy, Key);
Robert Bocchinoca27f032006-01-17 20:07:22 +00002507}
2508
2509Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
2510 Constant *Idx) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00002511 assert(isa<VectorType>(Val->getType()) &&
Reid Spencer09575ba2007-02-15 03:39:18 +00002512 "Tried to create insertelement operation on non-vector type!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00002513 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
Robert Bocchinoca27f032006-01-17 20:07:22 +00002514 && "Insertelement types must match!");
Reid Spencer8d9336d2006-12-31 05:26:44 +00002515 assert(Idx->getType() == Type::Int32Ty &&
Reid Spencer2546b762007-01-26 07:37:34 +00002516 "Insertelement index must be i32 type!");
Gordon Henriksenb52d1ed2008-08-30 15:41:51 +00002517 return getInsertElementTy(Val->getType(), Val, Elt, Idx);
Robert Bocchinoca27f032006-01-17 20:07:22 +00002518}
2519
Chris Lattnerbbe0a422006-04-08 01:18:18 +00002520Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
2521 Constant *V2, Constant *Mask) {
2522 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
2523 return FC; // Fold a few common cases...
2524 // Look up the constant in the table first to ensure uniqueness
2525 std::vector<Constant*> ArgVec(1, V1);
2526 ArgVec.push_back(V2);
2527 ArgVec.push_back(Mask);
Reid Spenceree3c9912006-12-04 05:19:50 +00002528 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
Chris Lattner69edc982006-09-28 00:35:06 +00002529 return ExprConstants->getOrCreate(ReqTy, Key);
Chris Lattnerbbe0a422006-04-08 01:18:18 +00002530}
2531
2532Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
2533 Constant *Mask) {
2534 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
2535 "Invalid shuffle vector constant expr operands!");
Nate Begeman94aa38d2009-02-12 21:28:33 +00002536
2537 unsigned NElts = cast<VectorType>(Mask->getType())->getNumElements();
2538 const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
2539 const Type *ShufTy = VectorType::get(EltTy, NElts);
2540 return getShuffleVectorTy(ShufTy, V1, V2, Mask);
Chris Lattnerbbe0a422006-04-08 01:18:18 +00002541}
2542
Dan Gohman12fce772008-05-15 19:50:34 +00002543Constant *ConstantExpr::getInsertValueTy(const Type *ReqTy, Constant *Agg,
2544 Constant *Val,
Dan Gohman1ecaf452008-05-31 00:58:22 +00002545 const unsigned *Idxs, unsigned NumIdx) {
Dan Gohman12fce772008-05-15 19:50:34 +00002546 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
2547 Idxs+NumIdx) == Val->getType() &&
2548 "insertvalue indices invalid!");
2549 assert(Agg->getType() == ReqTy &&
2550 "insertvalue type invalid!");
Dan Gohman0752bff2008-05-23 00:36:11 +00002551 assert(Agg->getType()->isFirstClassType() &&
2552 "Non-first-class type for constant InsertValue expression");
Dan Gohmand5d24f62008-07-21 23:30:30 +00002553 Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs, NumIdx);
2554 assert(FC && "InsertValue constant expr couldn't be folded!");
2555 return FC;
Dan Gohman12fce772008-05-15 19:50:34 +00002556}
2557
2558Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
Dan Gohman1ecaf452008-05-31 00:58:22 +00002559 const unsigned *IdxList, unsigned NumIdx) {
Dan Gohman0752bff2008-05-23 00:36:11 +00002560 assert(Agg->getType()->isFirstClassType() &&
2561 "Tried to create insertelement operation on non-first-class type!");
Dan Gohman12fce772008-05-15 19:50:34 +00002562
Dan Gohman0752bff2008-05-23 00:36:11 +00002563 const Type *ReqTy = Agg->getType();
Devang Pateld26344d2008-11-03 23:20:04 +00002564#ifndef NDEBUG
Dan Gohman0752bff2008-05-23 00:36:11 +00002565 const Type *ValTy =
Dan Gohman12fce772008-05-15 19:50:34 +00002566 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
Devang Pateld26344d2008-11-03 23:20:04 +00002567#endif
Dan Gohman0752bff2008-05-23 00:36:11 +00002568 assert(ValTy == Val->getType() && "insertvalue indices invalid!");
Dan Gohman12fce772008-05-15 19:50:34 +00002569 return getInsertValueTy(ReqTy, Agg, Val, IdxList, NumIdx);
2570}
2571
2572Constant *ConstantExpr::getExtractValueTy(const Type *ReqTy, Constant *Agg,
Dan Gohman1ecaf452008-05-31 00:58:22 +00002573 const unsigned *Idxs, unsigned NumIdx) {
Dan Gohman12fce772008-05-15 19:50:34 +00002574 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
2575 Idxs+NumIdx) == ReqTy &&
2576 "extractvalue indices invalid!");
Dan Gohman0752bff2008-05-23 00:36:11 +00002577 assert(Agg->getType()->isFirstClassType() &&
2578 "Non-first-class type for constant extractvalue expression");
Dan Gohmand5d24f62008-07-21 23:30:30 +00002579 Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs, NumIdx);
2580 assert(FC && "ExtractValue constant expr couldn't be folded!");
2581 return FC;
Dan Gohman12fce772008-05-15 19:50:34 +00002582}
2583
2584Constant *ConstantExpr::getExtractValue(Constant *Agg,
Dan Gohman1ecaf452008-05-31 00:58:22 +00002585 const unsigned *IdxList, unsigned NumIdx) {
Dan Gohman0752bff2008-05-23 00:36:11 +00002586 assert(Agg->getType()->isFirstClassType() &&
2587 "Tried to create extractelement operation on non-first-class type!");
Dan Gohman12fce772008-05-15 19:50:34 +00002588
2589 const Type *ReqTy =
2590 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
2591 assert(ReqTy && "extractvalue indices invalid!");
2592 return getExtractValueTy(ReqTy, Agg, IdxList, NumIdx);
2593}
2594
Reid Spencer2eadb532007-01-21 00:29:26 +00002595Constant *ConstantExpr::getZeroValueForNegationExpr(const Type *Ty) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00002596 if (const VectorType *PTy = dyn_cast<VectorType>(Ty))
Reid Spencer6598ca82007-01-21 02:29:10 +00002597 if (PTy->getElementType()->isFloatingPoint()) {
2598 std::vector<Constant*> zeros(PTy->getNumElements(),
Dale Johannesen98d3a082007-09-14 22:26:36 +00002599 ConstantFP::getNegativeZero(PTy->getElementType()));
Reid Spencerd84d35b2007-02-15 02:26:10 +00002600 return ConstantVector::get(PTy, zeros);
Reid Spencer6598ca82007-01-21 02:29:10 +00002601 }
Reid Spencer2eadb532007-01-21 00:29:26 +00002602
Dale Johannesen98d3a082007-09-14 22:26:36 +00002603 if (Ty->isFloatingPoint())
2604 return ConstantFP::getNegativeZero(Ty);
Reid Spencer2eadb532007-01-21 00:29:26 +00002605
2606 return Constant::getNullValue(Ty);
2607}
2608
Vikram S. Adve4c485332002-07-15 18:19:33 +00002609// destroyConstant - Remove the constant from the constant table...
2610//
2611void ConstantExpr::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00002612 ExprConstants->remove(this);
Vikram S. Adve4c485332002-07-15 18:19:33 +00002613 destroyConstantImpl();
Vikram S. Adve4e537b22002-07-14 23:13:17 +00002614}
2615
Chris Lattner3cd8c562002-07-30 18:54:25 +00002616const char *ConstantExpr::getOpcodeName() const {
2617 return Instruction::getOpcodeName(getOpcode());
Vikram S. Adve4e537b22002-07-14 23:13:17 +00002618}
Reid Spencer1ebe1ab2004-07-17 23:48:33 +00002619
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002620//===----------------------------------------------------------------------===//
2621// replaceUsesOfWithOnConstant implementations
2622
Chris Lattner913849b2007-08-21 00:55:23 +00002623/// replaceUsesOfWithOnConstant - Update this constant array to change uses of
2624/// 'From' to be uses of 'To'. This must update the uniquing data structures
2625/// etc.
2626///
2627/// Note that we intentionally replace all uses of From with To here. Consider
2628/// a large array that uses 'From' 1000 times. By handling this case all here,
2629/// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
2630/// single invocation handles all 1000 uses. Handling them one at a time would
2631/// work, but would be really slow because it would have to unique each updated
2632/// array instance.
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002633void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002634 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002635 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
Chris Lattner8760ec72005-10-04 01:17:50 +00002636 Constant *ToC = cast<Constant>(To);
Chris Lattnerdff59112005-10-04 18:47:09 +00002637
Jim Laskeyc03caef2006-07-17 17:38:29 +00002638 std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
Chris Lattnerb64419a2005-10-03 22:51:37 +00002639 Lookup.first.first = getType();
2640 Lookup.second = this;
Chris Lattnerdff59112005-10-04 18:47:09 +00002641
Chris Lattnerb64419a2005-10-03 22:51:37 +00002642 std::vector<Constant*> &Values = Lookup.first.second;
2643 Values.reserve(getNumOperands()); // Build replacement array.
Chris Lattnerdff59112005-10-04 18:47:09 +00002644
Chris Lattner8760ec72005-10-04 01:17:50 +00002645 // Fill values with the modified operands of the constant array. Also,
2646 // compute whether this turns into an all-zeros array.
Chris Lattnerdff59112005-10-04 18:47:09 +00002647 bool isAllZeros = false;
Chris Lattner913849b2007-08-21 00:55:23 +00002648 unsigned NumUpdated = 0;
Chris Lattnerdff59112005-10-04 18:47:09 +00002649 if (!ToC->isNullValue()) {
Chris Lattner913849b2007-08-21 00:55:23 +00002650 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2651 Constant *Val = cast<Constant>(O->get());
2652 if (Val == From) {
2653 Val = ToC;
2654 ++NumUpdated;
2655 }
2656 Values.push_back(Val);
2657 }
Chris Lattnerdff59112005-10-04 18:47:09 +00002658 } else {
2659 isAllZeros = true;
2660 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2661 Constant *Val = cast<Constant>(O->get());
Chris Lattner913849b2007-08-21 00:55:23 +00002662 if (Val == From) {
2663 Val = ToC;
2664 ++NumUpdated;
2665 }
Chris Lattnerdff59112005-10-04 18:47:09 +00002666 Values.push_back(Val);
2667 if (isAllZeros) isAllZeros = Val->isNullValue();
2668 }
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002669 }
2670
Chris Lattnerb64419a2005-10-03 22:51:37 +00002671 Constant *Replacement = 0;
2672 if (isAllZeros) {
2673 Replacement = ConstantAggregateZero::get(getType());
2674 } else {
2675 // Check to see if we have this array type already.
2676 bool Exists;
Jim Laskeyc03caef2006-07-17 17:38:29 +00002677 ArrayConstantsTy::MapTy::iterator I =
Chris Lattner69edc982006-09-28 00:35:06 +00002678 ArrayConstants->InsertOrGetItem(Lookup, Exists);
Chris Lattnerb64419a2005-10-03 22:51:37 +00002679
2680 if (Exists) {
2681 Replacement = I->second;
2682 } else {
2683 // Okay, the new shape doesn't exist in the system yet. Instead of
2684 // creating a new constant array, inserting it, replaceallusesof'ing the
2685 // old with the new, then deleting the old... just update the current one
2686 // in place!
Chris Lattner69edc982006-09-28 00:35:06 +00002687 ArrayConstants->MoveConstantToNewSlot(this, I);
Chris Lattnerb64419a2005-10-03 22:51:37 +00002688
Chris Lattner913849b2007-08-21 00:55:23 +00002689 // Update to the new value. Optimize for the case when we have a single
2690 // operand that we're changing, but handle bulk updates efficiently.
2691 if (NumUpdated == 1) {
2692 unsigned OperandToUpdate = U-OperandList;
2693 assert(getOperand(OperandToUpdate) == From &&
2694 "ReplaceAllUsesWith broken!");
2695 setOperand(OperandToUpdate, ToC);
2696 } else {
2697 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2698 if (getOperand(i) == From)
2699 setOperand(i, ToC);
2700 }
Chris Lattnerb64419a2005-10-03 22:51:37 +00002701 return;
2702 }
2703 }
2704
2705 // Otherwise, I do need to replace this with an existing value.
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002706 assert(Replacement != this && "I didn't contain From!");
2707
Chris Lattner7a1450d2005-10-04 18:13:04 +00002708 // Everyone using this now uses the replacement.
2709 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002710
2711 // Delete the old constant!
2712 destroyConstant();
2713}
2714
2715void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002716 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002717 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
Chris Lattner8760ec72005-10-04 01:17:50 +00002718 Constant *ToC = cast<Constant>(To);
2719
Chris Lattnerdff59112005-10-04 18:47:09 +00002720 unsigned OperandToUpdate = U-OperandList;
2721 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2722
Jim Laskeyc03caef2006-07-17 17:38:29 +00002723 std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
Chris Lattner8760ec72005-10-04 01:17:50 +00002724 Lookup.first.first = getType();
2725 Lookup.second = this;
2726 std::vector<Constant*> &Values = Lookup.first.second;
2727 Values.reserve(getNumOperands()); // Build replacement struct.
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002728
Chris Lattnerdff59112005-10-04 18:47:09 +00002729
Chris Lattner8760ec72005-10-04 01:17:50 +00002730 // Fill values with the modified operands of the constant struct. Also,
2731 // compute whether this turns into an all-zeros struct.
Chris Lattnerdff59112005-10-04 18:47:09 +00002732 bool isAllZeros = false;
2733 if (!ToC->isNullValue()) {
2734 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
2735 Values.push_back(cast<Constant>(O->get()));
2736 } else {
2737 isAllZeros = true;
2738 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2739 Constant *Val = cast<Constant>(O->get());
2740 Values.push_back(Val);
2741 if (isAllZeros) isAllZeros = Val->isNullValue();
2742 }
Chris Lattner8760ec72005-10-04 01:17:50 +00002743 }
Chris Lattnerdff59112005-10-04 18:47:09 +00002744 Values[OperandToUpdate] = ToC;
2745
Chris Lattner8760ec72005-10-04 01:17:50 +00002746 Constant *Replacement = 0;
2747 if (isAllZeros) {
2748 Replacement = ConstantAggregateZero::get(getType());
2749 } else {
2750 // Check to see if we have this array type already.
2751 bool Exists;
Jim Laskeyc03caef2006-07-17 17:38:29 +00002752 StructConstantsTy::MapTy::iterator I =
Chris Lattner69edc982006-09-28 00:35:06 +00002753 StructConstants->InsertOrGetItem(Lookup, Exists);
Chris Lattner8760ec72005-10-04 01:17:50 +00002754
2755 if (Exists) {
2756 Replacement = I->second;
2757 } else {
2758 // Okay, the new shape doesn't exist in the system yet. Instead of
2759 // creating a new constant struct, inserting it, replaceallusesof'ing the
2760 // old with the new, then deleting the old... just update the current one
2761 // in place!
Chris Lattner69edc982006-09-28 00:35:06 +00002762 StructConstants->MoveConstantToNewSlot(this, I);
Chris Lattner8760ec72005-10-04 01:17:50 +00002763
Chris Lattnerdff59112005-10-04 18:47:09 +00002764 // Update to the new value.
2765 setOperand(OperandToUpdate, ToC);
Chris Lattner8760ec72005-10-04 01:17:50 +00002766 return;
2767 }
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002768 }
2769
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002770 assert(Replacement != this && "I didn't contain From!");
2771
Chris Lattner7a1450d2005-10-04 18:13:04 +00002772 // Everyone using this now uses the replacement.
2773 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002774
2775 // Delete the old constant!
2776 destroyConstant();
2777}
2778
Reid Spencerd84d35b2007-02-15 02:26:10 +00002779void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002780 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002781 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2782
2783 std::vector<Constant*> Values;
2784 Values.reserve(getNumOperands()); // Build replacement array...
2785 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2786 Constant *Val = getOperand(i);
2787 if (Val == From) Val = cast<Constant>(To);
2788 Values.push_back(Val);
2789 }
2790
Reid Spencerd84d35b2007-02-15 02:26:10 +00002791 Constant *Replacement = ConstantVector::get(getType(), Values);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002792 assert(Replacement != this && "I didn't contain From!");
2793
Chris Lattner7a1450d2005-10-04 18:13:04 +00002794 // Everyone using this now uses the replacement.
2795 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002796
2797 // Delete the old constant!
2798 destroyConstant();
2799}
2800
2801void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002802 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002803 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2804 Constant *To = cast<Constant>(ToV);
2805
2806 Constant *Replacement = 0;
2807 if (getOpcode() == Instruction::GetElementPtr) {
Chris Lattnerb5d70302007-02-19 20:01:23 +00002808 SmallVector<Constant*, 8> Indices;
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002809 Constant *Pointer = getOperand(0);
2810 Indices.reserve(getNumOperands()-1);
2811 if (Pointer == From) Pointer = To;
2812
2813 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2814 Constant *Val = getOperand(i);
2815 if (Val == From) Val = To;
2816 Indices.push_back(Val);
2817 }
Chris Lattnerb5d70302007-02-19 20:01:23 +00002818 Replacement = ConstantExpr::getGetElementPtr(Pointer,
2819 &Indices[0], Indices.size());
Dan Gohman12fce772008-05-15 19:50:34 +00002820 } else if (getOpcode() == Instruction::ExtractValue) {
Dan Gohman12fce772008-05-15 19:50:34 +00002821 Constant *Agg = getOperand(0);
Dan Gohman12fce772008-05-15 19:50:34 +00002822 if (Agg == From) Agg = To;
2823
Dan Gohman1ecaf452008-05-31 00:58:22 +00002824 const SmallVector<unsigned, 4> &Indices = getIndices();
Dan Gohman12fce772008-05-15 19:50:34 +00002825 Replacement = ConstantExpr::getExtractValue(Agg,
2826 &Indices[0], Indices.size());
2827 } else if (getOpcode() == Instruction::InsertValue) {
Dan Gohman12fce772008-05-15 19:50:34 +00002828 Constant *Agg = getOperand(0);
2829 Constant *Val = getOperand(1);
Dan Gohman12fce772008-05-15 19:50:34 +00002830 if (Agg == From) Agg = To;
2831 if (Val == From) Val = To;
2832
Dan Gohman1ecaf452008-05-31 00:58:22 +00002833 const SmallVector<unsigned, 4> &Indices = getIndices();
Dan Gohman12fce772008-05-15 19:50:34 +00002834 Replacement = ConstantExpr::getInsertValue(Agg, Val,
2835 &Indices[0], Indices.size());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002836 } else if (isCast()) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002837 assert(getOperand(0) == From && "Cast only has one use!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002838 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002839 } else if (getOpcode() == Instruction::Select) {
2840 Constant *C1 = getOperand(0);
2841 Constant *C2 = getOperand(1);
2842 Constant *C3 = getOperand(2);
2843 if (C1 == From) C1 = To;
2844 if (C2 == From) C2 = To;
2845 if (C3 == From) C3 = To;
2846 Replacement = ConstantExpr::getSelect(C1, C2, C3);
Robert Bocchino23004482006-01-10 19:05:34 +00002847 } else if (getOpcode() == Instruction::ExtractElement) {
2848 Constant *C1 = getOperand(0);
2849 Constant *C2 = getOperand(1);
2850 if (C1 == From) C1 = To;
2851 if (C2 == From) C2 = To;
2852 Replacement = ConstantExpr::getExtractElement(C1, C2);
Chris Lattnera93b4b52006-04-08 05:09:48 +00002853 } else if (getOpcode() == Instruction::InsertElement) {
2854 Constant *C1 = getOperand(0);
2855 Constant *C2 = getOperand(1);
2856 Constant *C3 = getOperand(1);
2857 if (C1 == From) C1 = To;
2858 if (C2 == From) C2 = To;
2859 if (C3 == From) C3 = To;
2860 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2861 } else if (getOpcode() == Instruction::ShuffleVector) {
2862 Constant *C1 = getOperand(0);
2863 Constant *C2 = getOperand(1);
2864 Constant *C3 = getOperand(2);
2865 if (C1 == From) C1 = To;
2866 if (C2 == From) C2 = To;
2867 if (C3 == From) C3 = To;
2868 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
Reid Spenceree3c9912006-12-04 05:19:50 +00002869 } else if (isCompare()) {
2870 Constant *C1 = getOperand(0);
2871 Constant *C2 = getOperand(1);
2872 if (C1 == From) C1 = To;
2873 if (C2 == From) C2 = To;
2874 if (getOpcode() == Instruction::ICmp)
2875 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
Chris Lattnereab49262008-07-14 05:17:31 +00002876 else if (getOpcode() == Instruction::FCmp)
Reid Spenceree3c9912006-12-04 05:19:50 +00002877 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
Chris Lattnereab49262008-07-14 05:17:31 +00002878 else if (getOpcode() == Instruction::VICmp)
2879 Replacement = ConstantExpr::getVICmp(getPredicate(), C1, C2);
2880 else {
2881 assert(getOpcode() == Instruction::VFCmp);
2882 Replacement = ConstantExpr::getVFCmp(getPredicate(), C1, C2);
2883 }
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002884 } else if (getNumOperands() == 2) {
2885 Constant *C1 = getOperand(0);
2886 Constant *C2 = getOperand(1);
2887 if (C1 == From) C1 = To;
2888 if (C2 == From) C2 = To;
2889 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2890 } else {
2891 assert(0 && "Unknown ConstantExpr type!");
2892 return;
2893 }
2894
2895 assert(Replacement != this && "I didn't contain From!");
2896
Chris Lattner7a1450d2005-10-04 18:13:04 +00002897 // Everyone using this now uses the replacement.
2898 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002899
2900 // Delete the old constant!
2901 destroyConstant();
Matthijs Kooijmanba5d7ef2008-07-03 07:46:41 +00002902}
Nick Lewycky49f89192009-04-04 07:22:01 +00002903
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00002904void MDNode::replaceElement(Value *From, Value *To) {
2905 SmallVector<Value*, 4> Values;
2906 Values.reserve(getNumElements()); // Build replacement array...
2907 for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
2908 Value *Val = getElement(i);
2909 if (Val == From) Val = To;
Nick Lewycky49f89192009-04-04 07:22:01 +00002910 Values.push_back(Val);
2911 }
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00002912
2913 MDNode *Replacement = MDNode::get(&Values[0], Values.size());
Nick Lewycky49f89192009-04-04 07:22:01 +00002914 assert(Replacement != this && "I didn't contain From!");
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00002915
Nick Lewycky49f89192009-04-04 07:22:01 +00002916 uncheckedReplaceAllUsesWith(Replacement);
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00002917
Nick Lewycky49f89192009-04-04 07:22:01 +00002918 destroyConstant();
2919}