blob: 56c900293dd819fc146aeb5118c7f06b3a4571ce [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"
Owen Anderson2d7231d2009-06-17 18:40:29 +000028#include "llvm/System/RWMutex.h"
Owen Anderson7d42b952009-06-18 16:54:52 +000029#include "llvm/System/Threading.h"
Chris Lattnera80bf0b2007-02-20 06:39:57 +000030#include "llvm/ADT/DenseMap.h"
Chris Lattnerb5d70302007-02-19 20:01:23 +000031#include "llvm/ADT/SmallVector.h"
Chris Lattner2f7c9632001-06-06 20:29:01 +000032#include <algorithm>
Reid Spencer3aaaa0b2007-02-05 20:47:22 +000033#include <map>
Chris Lattner189d19f2003-11-21 20:23:48 +000034using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000035
Chris Lattner2f7c9632001-06-06 20:29:01 +000036//===----------------------------------------------------------------------===//
Chris Lattner3462ae32001-12-03 22:26:30 +000037// Constant Class
Chris Lattner2f7c9632001-06-06 20:29:01 +000038//===----------------------------------------------------------------------===//
39
Owen Andersond830eb82009-06-18 19:10:19 +000040// Becomes a no-op when multithreading is disabled.
41ManagedStatic<sys::SmartRWMutex<true> > ConstantsLock;
Owen Anderson2d7231d2009-06-17 18:40:29 +000042
Chris Lattner3462ae32001-12-03 22:26:30 +000043void Constant::destroyConstantImpl() {
44 // When a Constant is destroyed, there may be lingering
Chris Lattnerd7a73302001-10-13 06:57:33 +000045 // references to the constant by other constants in the constant pool. These
Misha Brukmanbe372b92003-08-21 22:14:26 +000046 // constants are implicitly dependent on the module that is being deleted,
Chris Lattnerd7a73302001-10-13 06:57:33 +000047 // but they don't know that. Because we only find out when the CPV is
48 // deleted, we must now notify all of our users (that should only be
Chris Lattner3462ae32001-12-03 22:26:30 +000049 // Constants) that they are, in fact, invalid now and should be deleted.
Chris Lattnerd7a73302001-10-13 06:57:33 +000050 //
51 while (!use_empty()) {
52 Value *V = use_back();
53#ifndef NDEBUG // Only in -g mode...
Chris Lattnerd9f4ac662002-07-18 00:14:50 +000054 if (!isa<Constant>(V))
Bill Wendling6a462f12006-11-17 08:03:48 +000055 DOUT << "While deleting: " << *this
56 << "\n\nUse still stuck around after Def is destroyed: "
57 << *V << "\n\n";
Chris Lattnerd7a73302001-10-13 06:57:33 +000058#endif
Vikram S. Adve4e537b22002-07-14 23:13:17 +000059 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
Reid Spencer1ebe1ab2004-07-17 23:48:33 +000060 Constant *CV = cast<Constant>(V);
61 CV->destroyConstant();
Chris Lattnerd7a73302001-10-13 06:57:33 +000062
63 // The constant should remove itself from our use list...
Vikram S. Adve4e537b22002-07-14 23:13:17 +000064 assert((use_empty() || use_back() != V) && "Constant not removed!");
Chris Lattnerd7a73302001-10-13 06:57:33 +000065 }
66
67 // Value has no outstanding references it is safe to delete it now...
68 delete this;
Chris Lattner38569342001-10-01 20:11:19 +000069}
Chris Lattner2f7c9632001-06-06 20:29:01 +000070
Chris Lattner23dd1f62006-10-20 00:27:06 +000071/// canTrap - Return true if evaluation of this constant could trap. This is
72/// true for things like constant expressions that could divide by zero.
73bool Constant::canTrap() const {
74 assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
75 // The only thing that could possibly trap are constant exprs.
76 const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
77 if (!CE) return false;
78
79 // ConstantExpr traps if any operands can trap.
80 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
81 if (getOperand(i)->canTrap())
82 return true;
83
84 // Otherwise, only specific operations can trap.
85 switch (CE->getOpcode()) {
86 default:
87 return false;
Reid Spencer7e80b0b2006-10-26 06:15:43 +000088 case Instruction::UDiv:
89 case Instruction::SDiv:
90 case Instruction::FDiv:
Reid Spencer7eb55b32006-11-02 01:53:59 +000091 case Instruction::URem:
92 case Instruction::SRem:
93 case Instruction::FRem:
Chris Lattner23dd1f62006-10-20 00:27:06 +000094 // Div and rem can trap if the RHS is not known to be non-zero.
95 if (!isa<ConstantInt>(getOperand(1)) || getOperand(1)->isNullValue())
96 return true;
97 return false;
98 }
99}
100
Anton Korobeynikov7437b592009-03-29 17:13:18 +0000101/// ContainsRelocations - Return true if the constant value contains relocations
102/// which cannot be resolved at compile time. Kind argument is used to filter
103/// only 'interesting' sorts of relocations.
104bool Constant::ContainsRelocations(unsigned Kind) const {
105 if (const GlobalValue* GV = dyn_cast<GlobalValue>(this)) {
106 bool isLocal = GV->hasLocalLinkage();
107 if ((Kind & Reloc::Local) && isLocal) {
108 // Global has local linkage and 'local' kind of relocations are
109 // requested
110 return true;
111 }
112
113 if ((Kind & Reloc::Global) && !isLocal) {
114 // Global has non-local linkage and 'global' kind of relocations are
115 // requested
116 return true;
117 }
Anton Korobeynikov255a3cb2009-03-30 15:28:21 +0000118
119 return false;
Anton Korobeynikov7437b592009-03-29 17:13:18 +0000120 }
121
Evan Chengf9e003b2007-03-08 00:59:12 +0000122 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
Anton Korobeynikovd5e8e932009-03-30 15:28:00 +0000123 if (getOperand(i)->ContainsRelocations(Kind))
Evan Chengf9e003b2007-03-08 00:59:12 +0000124 return true;
Anton Korobeynikov7437b592009-03-29 17:13:18 +0000125
Evan Chengf9e003b2007-03-08 00:59:12 +0000126 return false;
127}
128
Chris Lattnerb1585a92002-08-13 17:50:20 +0000129// Static constructor to create a '0' constant of arbitrary type...
130Constant *Constant::getNullValue(const Type *Ty) {
Dale Johannesen98d3a082007-09-14 22:26:36 +0000131 static uint64_t zero[2] = {0, 0};
Chris Lattner6b727592004-06-17 18:19:28 +0000132 switch (Ty->getTypeID()) {
Chris Lattnerdbcb0d32007-02-20 05:46:39 +0000133 case Type::IntegerTyID:
134 return ConstantInt::get(Ty, 0);
135 case Type::FloatTyID:
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000136 return ConstantFP::get(APFloat(APInt(32, 0)));
Chris Lattnerdbcb0d32007-02-20 05:46:39 +0000137 case Type::DoubleTyID:
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000138 return ConstantFP::get(APFloat(APInt(64, 0)));
Dale Johannesenbdad8092007-08-09 22:51:36 +0000139 case Type::X86_FP80TyID:
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000140 return ConstantFP::get(APFloat(APInt(80, 2, zero)));
Dale Johannesenbdad8092007-08-09 22:51:36 +0000141 case Type::FP128TyID:
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000142 return ConstantFP::get(APFloat(APInt(128, 2, zero), true));
Dale Johannesen98d3a082007-09-14 22:26:36 +0000143 case Type::PPC_FP128TyID:
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000144 return ConstantFP::get(APFloat(APInt(128, 2, zero)));
Misha Brukmanb1c93172005-04-21 23:48:37 +0000145 case Type::PointerTyID:
Chris Lattnerb1585a92002-08-13 17:50:20 +0000146 return ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattner9fba3da2004-02-15 05:53:04 +0000147 case Type::StructTyID:
148 case Type::ArrayTyID:
Reid Spencerd84d35b2007-02-15 02:26:10 +0000149 case Type::VectorTyID:
Chris Lattner9fba3da2004-02-15 05:53:04 +0000150 return ConstantAggregateZero::get(Ty);
Chris Lattnerb1585a92002-08-13 17:50:20 +0000151 default:
Reid Spencercf394bf2004-07-04 11:51:24 +0000152 // Function, Label, or Opaque type?
153 assert(!"Cannot create a null constant of that type!");
Chris Lattnerb1585a92002-08-13 17:50:20 +0000154 return 0;
155 }
156}
157
Chris Lattner72e39582007-06-15 06:10:53 +0000158Constant *Constant::getAllOnesValue(const Type *Ty) {
159 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
160 return ConstantInt::get(APInt::getAllOnesValue(ITy->getBitWidth()));
161 return ConstantVector::getAllOnesValue(cast<VectorType>(Ty));
162}
Chris Lattnerb1585a92002-08-13 17:50:20 +0000163
164// Static constructor to create an integral constant with all bits set
Zhou Sheng75b871f2007-01-11 12:24:14 +0000165ConstantInt *ConstantInt::getAllOnesValue(const Type *Ty) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000166 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
Reid Spencerd1bbfa52007-03-01 19:30:34 +0000167 return ConstantInt::get(APInt::getAllOnesValue(ITy->getBitWidth()));
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000168 return 0;
Chris Lattnerb1585a92002-08-13 17:50:20 +0000169}
170
Dan Gohman30978072007-05-24 14:36:04 +0000171/// @returns the value for a vector integer constant of the given type that
Chris Lattnerecab54c2007-01-04 01:49:26 +0000172/// has all its bits set to true.
173/// @brief Get the all ones value
Reid Spencerd84d35b2007-02-15 02:26:10 +0000174ConstantVector *ConstantVector::getAllOnesValue(const VectorType *Ty) {
Chris Lattnerecab54c2007-01-04 01:49:26 +0000175 std::vector<Constant*> Elts;
176 Elts.resize(Ty->getNumElements(),
Zhou Sheng75b871f2007-01-11 12:24:14 +0000177 ConstantInt::getAllOnesValue(Ty->getElementType()));
Dan Gohman30978072007-05-24 14:36:04 +0000178 assert(Elts[0] && "Not a vector integer type!");
Reid Spencerd84d35b2007-02-15 02:26:10 +0000179 return cast<ConstantVector>(ConstantVector::get(Elts));
Chris Lattnerecab54c2007-01-04 01:49:26 +0000180}
181
182
Chris Lattner2105d662008-07-10 00:28:11 +0000183/// getVectorElements - This method, which is only valid on constant of vector
184/// type, returns the elements of the vector in the specified smallvector.
Chris Lattnerc5098a22008-07-14 05:10:41 +0000185/// This handles breaking down a vector undef into undef elements, etc. For
186/// constant exprs and other cases we can't handle, we return an empty vector.
Chris Lattner2105d662008-07-10 00:28:11 +0000187void Constant::getVectorElements(SmallVectorImpl<Constant*> &Elts) const {
188 assert(isa<VectorType>(getType()) && "Not a vector constant!");
189
190 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this)) {
191 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i)
192 Elts.push_back(CV->getOperand(i));
193 return;
194 }
195
196 const VectorType *VT = cast<VectorType>(getType());
197 if (isa<ConstantAggregateZero>(this)) {
198 Elts.assign(VT->getNumElements(),
199 Constant::getNullValue(VT->getElementType()));
200 return;
201 }
202
Chris Lattnerc5098a22008-07-14 05:10:41 +0000203 if (isa<UndefValue>(this)) {
204 Elts.assign(VT->getNumElements(), UndefValue::get(VT->getElementType()));
205 return;
206 }
207
208 // Unknown type, must be constant expr etc.
Chris Lattner2105d662008-07-10 00:28:11 +0000209}
210
211
212
Chris Lattner2f7c9632001-06-06 20:29:01 +0000213//===----------------------------------------------------------------------===//
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000214// ConstantInt
Chris Lattner2f7c9632001-06-06 20:29:01 +0000215//===----------------------------------------------------------------------===//
216
Reid Spencerb31bffe2007-02-26 23:54:03 +0000217ConstantInt::ConstantInt(const IntegerType *Ty, const APInt& V)
Chris Lattner5db2f472007-02-20 05:55:46 +0000218 : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
Reid Spencerb31bffe2007-02-26 23:54:03 +0000219 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
Chris Lattner2f7c9632001-06-06 20:29:01 +0000220}
221
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000222ConstantInt *ConstantInt::TheTrueVal = 0;
223ConstantInt *ConstantInt::TheFalseVal = 0;
224
225namespace llvm {
226 void CleanupTrueFalse(void *) {
227 ConstantInt::ResetTrueFalse();
228 }
229}
230
231static ManagedCleanup<llvm::CleanupTrueFalse> TrueFalseCleanup;
232
233ConstantInt *ConstantInt::CreateTrueFalseVals(bool WhichOne) {
234 assert(TheTrueVal == 0 && TheFalseVal == 0);
235 TheTrueVal = get(Type::Int1Ty, 1);
236 TheFalseVal = get(Type::Int1Ty, 0);
237
238 // Ensure that llvm_shutdown nulls out TheTrueVal/TheFalseVal.
239 TrueFalseCleanup.Register();
240
241 return WhichOne ? TheTrueVal : TheFalseVal;
242}
243
244
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000245namespace {
Reid Spencerb31bffe2007-02-26 23:54:03 +0000246 struct DenseMapAPIntKeyInfo {
247 struct KeyTy {
248 APInt val;
249 const Type* type;
250 KeyTy(const APInt& V, const Type* Ty) : val(V), type(Ty) {}
251 KeyTy(const KeyTy& that) : val(that.val), type(that.type) {}
252 bool operator==(const KeyTy& that) const {
253 return type == that.type && this->val == that.val;
254 }
255 bool operator!=(const KeyTy& that) const {
256 return !this->operator==(that);
257 }
258 };
259 static inline KeyTy getEmptyKey() { return KeyTy(APInt(1,0), 0); }
260 static inline KeyTy getTombstoneKey() { return KeyTy(APInt(1,1), 0); }
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000261 static unsigned getHashValue(const KeyTy &Key) {
Chris Lattner0625bd62007-09-17 18:34:04 +0000262 return DenseMapInfo<void*>::getHashValue(Key.type) ^
Reid Spencerb31bffe2007-02-26 23:54:03 +0000263 Key.val.getHashValue();
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000264 }
Chris Lattner0625bd62007-09-17 18:34:04 +0000265 static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
266 return LHS == RHS;
267 }
Dale Johannesena719a602007-08-24 00:56:33 +0000268 static bool isPod() { return false; }
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000269 };
270}
271
272
Reid Spencerb31bffe2007-02-26 23:54:03 +0000273typedef DenseMap<DenseMapAPIntKeyInfo::KeyTy, ConstantInt*,
274 DenseMapAPIntKeyInfo> IntMapTy;
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000275static ManagedStatic<IntMapTy> IntConstants;
276
Dan Gohman7ccc52f2009-06-15 22:12:54 +0000277ConstantInt *ConstantInt::get(const IntegerType *Ty,
278 uint64_t V, bool isSigned) {
279 return get(APInt(Ty->getBitWidth(), V, isSigned));
280}
281
282Constant *ConstantInt::get(const Type *Ty, uint64_t V, bool isSigned) {
283 Constant *C = get(cast<IntegerType>(Ty->getScalarType()), V, isSigned);
284
285 // For vectors, broadcast the value.
286 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
287 return
288 ConstantVector::get(std::vector<Constant *>(VTy->getNumElements(), C));
289
290 return C;
Reid Spencerb31bffe2007-02-26 23:54:03 +0000291}
292
Reid Spencerd1bbfa52007-03-01 19:30:34 +0000293// Get a ConstantInt from an APInt. Note that the value stored in the DenseMap
Dan Gohmanb3efe032008-02-07 02:30:40 +0000294// as the key, is a DenseMapAPIntKeyInfo::KeyTy which has provided the
Reid Spencerb31bffe2007-02-26 23:54:03 +0000295// operator== and operator!= to ensure that the DenseMap doesn't attempt to
296// compare APInt's of different widths, which would violate an APInt class
297// invariant which generates an assertion.
Reid Spencerd1bbfa52007-03-01 19:30:34 +0000298ConstantInt *ConstantInt::get(const APInt& V) {
299 // Get the corresponding integer type for the bit width of the value.
300 const IntegerType *ITy = IntegerType::get(V.getBitWidth());
Reid Spencerb31bffe2007-02-26 23:54:03 +0000301 // get an existing value or the insertion position
Reid Spencerd1bbfa52007-03-01 19:30:34 +0000302 DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
Owen Anderson2d7231d2009-06-17 18:40:29 +0000303
Owen Andersond830eb82009-06-18 19:10:19 +0000304 ConstantsLock->reader_acquire();
305 ConstantInt *&Slot = (*IntConstants)[Key];
306 ConstantsLock->reader_release();
Owen Anderson2d7231d2009-06-17 18:40:29 +0000307
Owen Andersond830eb82009-06-18 19:10:19 +0000308 if (!Slot) {
309 sys::SmartScopedWriter<true> Writer(&*ConstantsLock);
310 ConstantInt *&NewSlot = (*IntConstants)[Key];
Owen Anderson2d7231d2009-06-17 18:40:29 +0000311 if (!Slot) {
Owen Andersond830eb82009-06-18 19:10:19 +0000312 NewSlot = new ConstantInt(ITy, V);
Owen Anderson2d7231d2009-06-17 18:40:29 +0000313 }
314
Owen Andersond830eb82009-06-18 19:10:19 +0000315 return NewSlot;
Owen Anderson2d7231d2009-06-17 18:40:29 +0000316 } else {
Owen Andersond830eb82009-06-18 19:10:19 +0000317 return Slot;
Owen Anderson2d7231d2009-06-17 18:40:29 +0000318 }
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000319}
320
Dan Gohman7ccc52f2009-06-15 22:12:54 +0000321Constant *ConstantInt::get(const Type *Ty, const APInt &V) {
322 ConstantInt *C = ConstantInt::get(V);
323 assert(C->getType() == Ty->getScalarType() &&
324 "ConstantInt type doesn't match the type implied by its value!");
325
326 // For vectors, broadcast the value.
327 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
328 return
329 ConstantVector::get(std::vector<Constant *>(VTy->getNumElements(), C));
330
331 return C;
332}
333
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000334//===----------------------------------------------------------------------===//
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000335// ConstantFP
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000336//===----------------------------------------------------------------------===//
337
Chris Lattner98bd9392008-04-09 06:38:30 +0000338static const fltSemantics *TypeToFloatSemantics(const Type *Ty) {
339 if (Ty == Type::FloatTy)
340 return &APFloat::IEEEsingle;
341 if (Ty == Type::DoubleTy)
342 return &APFloat::IEEEdouble;
343 if (Ty == Type::X86_FP80Ty)
344 return &APFloat::x87DoubleExtended;
345 else if (Ty == Type::FP128Ty)
346 return &APFloat::IEEEquad;
347
348 assert(Ty == Type::PPC_FP128Ty && "Unknown FP format");
349 return &APFloat::PPCDoubleDouble;
350}
351
Dale Johannesend246b2c2007-08-30 00:23:21 +0000352ConstantFP::ConstantFP(const Type *Ty, const APFloat& V)
353 : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
Chris Lattner98bd9392008-04-09 06:38:30 +0000354 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
355 "FP type Mismatch");
Chris Lattner2f7c9632001-06-06 20:29:01 +0000356}
357
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000358bool ConstantFP::isNullValue() const {
Dale Johannesena719a602007-08-24 00:56:33 +0000359 return Val.isZero() && !Val.isNegative();
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000360}
361
Dale Johannesen98d3a082007-09-14 22:26:36 +0000362ConstantFP *ConstantFP::getNegativeZero(const Type *Ty) {
363 APFloat apf = cast <ConstantFP>(Constant::getNullValue(Ty))->getValueAPF();
364 apf.changeSign();
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000365 return ConstantFP::get(apf);
Dale Johannesen98d3a082007-09-14 22:26:36 +0000366}
367
Dale Johannesend246b2c2007-08-30 00:23:21 +0000368bool ConstantFP::isExactlyValue(const APFloat& V) const {
369 return Val.bitwiseIsEqual(V);
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000370}
371
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000372namespace {
Dale Johannesena719a602007-08-24 00:56:33 +0000373 struct DenseMapAPFloatKeyInfo {
Dale Johannesenbdea32d2007-08-24 22:09:56 +0000374 struct KeyTy {
375 APFloat val;
376 KeyTy(const APFloat& V) : val(V){}
377 KeyTy(const KeyTy& that) : val(that.val) {}
378 bool operator==(const KeyTy& that) const {
379 return this->val.bitwiseIsEqual(that.val);
380 }
381 bool operator!=(const KeyTy& that) const {
382 return !this->operator==(that);
383 }
384 };
385 static inline KeyTy getEmptyKey() {
386 return KeyTy(APFloat(APFloat::Bogus,1));
Reid Spencerb31bffe2007-02-26 23:54:03 +0000387 }
Dale Johannesenbdea32d2007-08-24 22:09:56 +0000388 static inline KeyTy getTombstoneKey() {
389 return KeyTy(APFloat(APFloat::Bogus,2));
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000390 }
Dale Johannesenbdea32d2007-08-24 22:09:56 +0000391 static unsigned getHashValue(const KeyTy &Key) {
392 return Key.val.getHashValue();
Dale Johannesena719a602007-08-24 00:56:33 +0000393 }
Chris Lattner0625bd62007-09-17 18:34:04 +0000394 static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
395 return LHS == RHS;
396 }
Dale Johannesena719a602007-08-24 00:56:33 +0000397 static bool isPod() { return false; }
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000398 };
399}
400
401//---- ConstantFP::get() implementation...
402//
Dale Johannesenbdea32d2007-08-24 22:09:56 +0000403typedef DenseMap<DenseMapAPFloatKeyInfo::KeyTy, ConstantFP*,
Dale Johannesena719a602007-08-24 00:56:33 +0000404 DenseMapAPFloatKeyInfo> FPMapTy;
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000405
Dale Johannesena719a602007-08-24 00:56:33 +0000406static ManagedStatic<FPMapTy> FPConstants;
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000407
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000408ConstantFP *ConstantFP::get(const APFloat &V) {
Dale Johannesend246b2c2007-08-30 00:23:21 +0000409 DenseMapAPFloatKeyInfo::KeyTy Key(V);
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000410
Owen Andersond830eb82009-06-18 19:10:19 +0000411 ConstantsLock->reader_acquire();
412 ConstantFP *&Slot = (*FPConstants)[Key];
413 ConstantsLock->reader_release();
Owen Anderson2d7231d2009-06-17 18:40:29 +0000414
Owen Andersond830eb82009-06-18 19:10:19 +0000415 if (!Slot) {
416 sys::SmartScopedWriter<true> Writer(&*ConstantsLock);
417 ConstantFP *&NewSlot = (*FPConstants)[Key];
418 if (!NewSlot) {
419 const Type *Ty;
420 if (&V.getSemantics() == &APFloat::IEEEsingle)
421 Ty = Type::FloatTy;
422 else if (&V.getSemantics() == &APFloat::IEEEdouble)
423 Ty = Type::DoubleTy;
424 else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
425 Ty = Type::X86_FP80Ty;
426 else if (&V.getSemantics() == &APFloat::IEEEquad)
427 Ty = Type::FP128Ty;
428 else {
429 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble &&
430 "Unknown FP format");
431 Ty = Type::PPC_FP128Ty;
Owen Anderson2d7231d2009-06-17 18:40:29 +0000432 }
Owen Andersond830eb82009-06-18 19:10:19 +0000433 NewSlot = new ConstantFP(Ty, V);
Owen Anderson2d7231d2009-06-17 18:40:29 +0000434 }
435
Owen Andersond830eb82009-06-18 19:10:19 +0000436 return NewSlot;
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000437 }
Owen Andersond830eb82009-06-18 19:10:19 +0000438
439 return Slot;
Dale Johannesend246b2c2007-08-30 00:23:21 +0000440}
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000441
Chris Lattner98bd9392008-04-09 06:38:30 +0000442/// get() - This returns a constant fp for the specified value in the
443/// specified type. This should only be used for simple constant values like
444/// 2.0/1.0 etc, that are known-valid both as double and as the target format.
Dan Gohman7ccc52f2009-06-15 22:12:54 +0000445Constant *ConstantFP::get(const Type *Ty, double V) {
Chris Lattner98bd9392008-04-09 06:38:30 +0000446 APFloat FV(V);
Dale Johannesen4f0bd682008-10-09 23:00:39 +0000447 bool ignored;
Dan Gohman7ccc52f2009-06-15 22:12:54 +0000448 FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
449 APFloat::rmNearestTiesToEven, &ignored);
450 Constant *C = get(FV);
451
452 // For vectors, broadcast the value.
453 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
454 return
455 ConstantVector::get(std::vector<Constant *>(VTy->getNumElements(), C));
456
457 return C;
Chris Lattner98bd9392008-04-09 06:38:30 +0000458}
459
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000460//===----------------------------------------------------------------------===//
461// ConstantXXX Classes
462//===----------------------------------------------------------------------===//
463
464
Chris Lattner3462ae32001-12-03 22:26:30 +0000465ConstantArray::ConstantArray(const ArrayType *T,
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000466 const std::vector<Constant*> &V)
Gabor Greiff6caff662008-05-10 08:32:32 +0000467 : Constant(T, ConstantArrayVal,
468 OperandTraits<ConstantArray>::op_end(this) - V.size(),
469 V.size()) {
Alkis Evlogimenos0507ffe2004-09-15 02:32:15 +0000470 assert(V.size() == T->getNumElements() &&
471 "Invalid initializer vector for constant array");
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000472 Use *OL = OperandList;
Chris Lattner0144fad2005-10-03 21:56:24 +0000473 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
474 I != E; ++I, ++OL) {
Chris Lattner20a24452005-10-07 05:23:36 +0000475 Constant *C = *I;
476 assert((C->getType() == T->getElementType() ||
Alkis Evlogimenoscb031d92004-09-10 04:16:59 +0000477 (T->isAbstract() &&
Chris Lattner20a24452005-10-07 05:23:36 +0000478 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
Alkis Evlogimenoscb031d92004-09-10 04:16:59 +0000479 "Initializer for array element doesn't match array element type!");
Gabor Greif2d3024d2008-05-26 21:33:52 +0000480 *OL = C;
Chris Lattner2f7c9632001-06-06 20:29:01 +0000481 }
482}
483
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000484
Chris Lattner3462ae32001-12-03 22:26:30 +0000485ConstantStruct::ConstantStruct(const StructType *T,
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000486 const std::vector<Constant*> &V)
Gabor Greiff6caff662008-05-10 08:32:32 +0000487 : Constant(T, ConstantStructVal,
488 OperandTraits<ConstantStruct>::op_end(this) - V.size(),
489 V.size()) {
Chris Lattnerac6db752004-02-09 04:37:31 +0000490 assert(V.size() == T->getNumElements() &&
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000491 "Invalid initializer vector for constant structure");
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000492 Use *OL = OperandList;
Chris Lattner0144fad2005-10-03 21:56:24 +0000493 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
494 I != E; ++I, ++OL) {
Chris Lattner20a24452005-10-07 05:23:36 +0000495 Constant *C = *I;
496 assert((C->getType() == T->getElementType(I-V.begin()) ||
Chris Lattner0144fad2005-10-03 21:56:24 +0000497 ((T->getElementType(I-V.begin())->isAbstract() ||
Chris Lattner20a24452005-10-07 05:23:36 +0000498 C->getType()->isAbstract()) &&
Chris Lattner0144fad2005-10-03 21:56:24 +0000499 T->getElementType(I-V.begin())->getTypeID() ==
Chris Lattner20a24452005-10-07 05:23:36 +0000500 C->getType()->getTypeID())) &&
Chris Lattner93c8f142003-06-02 17:42:47 +0000501 "Initializer for struct element doesn't match struct element type!");
Gabor Greif2d3024d2008-05-26 21:33:52 +0000502 *OL = C;
Chris Lattner2f7c9632001-06-06 20:29:01 +0000503 }
504}
505
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000506
Reid Spencerd84d35b2007-02-15 02:26:10 +0000507ConstantVector::ConstantVector(const VectorType *T,
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000508 const std::vector<Constant*> &V)
Gabor Greiff6caff662008-05-10 08:32:32 +0000509 : Constant(T, ConstantVectorVal,
510 OperandTraits<ConstantVector>::op_end(this) - V.size(),
511 V.size()) {
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000512 Use *OL = OperandList;
Chris Lattner0144fad2005-10-03 21:56:24 +0000513 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
514 I != E; ++I, ++OL) {
Chris Lattner20a24452005-10-07 05:23:36 +0000515 Constant *C = *I;
516 assert((C->getType() == T->getElementType() ||
Alkis Evlogimenoscb031d92004-09-10 04:16:59 +0000517 (T->isAbstract() &&
Chris Lattner20a24452005-10-07 05:23:36 +0000518 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
Dan Gohman30978072007-05-24 14:36:04 +0000519 "Initializer for vector element doesn't match vector element type!");
Gabor Greif2d3024d2008-05-26 21:33:52 +0000520 *OL = C;
Brian Gaeke02209042004-08-20 06:00:58 +0000521 }
522}
523
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000524
Gabor Greiff6caff662008-05-10 08:32:32 +0000525namespace llvm {
Gordon Henriksen14a55692007-12-10 02:14:30 +0000526// We declare several classes private to this file, so use an anonymous
527// namespace
528namespace {
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000529
Gordon Henriksen14a55692007-12-10 02:14:30 +0000530/// UnaryConstantExpr - This class is private to Constants.cpp, and is used
531/// behind the scenes to implement unary constant exprs.
532class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
Gabor Greife9ecc682008-04-06 20:25:17 +0000533 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Gordon Henriksen14a55692007-12-10 02:14:30 +0000534public:
Gabor Greife9ecc682008-04-06 20:25:17 +0000535 // allocate space for exactly one operand
536 void *operator new(size_t s) {
537 return User::operator new(s, 1);
538 }
Gordon Henriksen14a55692007-12-10 02:14:30 +0000539 UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
Gabor Greiff6caff662008-05-10 08:32:32 +0000540 : ConstantExpr(Ty, Opcode, &Op<0>(), 1) {
541 Op<0>() = C;
542 }
543 /// Transparently provide more efficient getOperand methods.
544 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000545};
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000546
Gordon Henriksen14a55692007-12-10 02:14:30 +0000547/// BinaryConstantExpr - This class is private to Constants.cpp, and is used
548/// behind the scenes to implement binary constant exprs.
549class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
Gabor Greife9ecc682008-04-06 20:25:17 +0000550 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Gordon Henriksen14a55692007-12-10 02:14:30 +0000551public:
Gabor Greife9ecc682008-04-06 20:25:17 +0000552 // allocate space for exactly two operands
553 void *operator new(size_t s) {
554 return User::operator new(s, 2);
555 }
Gordon Henriksen14a55692007-12-10 02:14:30 +0000556 BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
Gabor Greiff6caff662008-05-10 08:32:32 +0000557 : ConstantExpr(C1->getType(), Opcode, &Op<0>(), 2) {
Gabor Greif2d3024d2008-05-26 21:33:52 +0000558 Op<0>() = C1;
559 Op<1>() = C2;
Gordon Henriksen14a55692007-12-10 02:14:30 +0000560 }
Gabor Greiff6caff662008-05-10 08:32:32 +0000561 /// Transparently provide more efficient getOperand methods.
562 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000563};
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000564
Gordon Henriksen14a55692007-12-10 02:14:30 +0000565/// SelectConstantExpr - This class is private to Constants.cpp, and is used
566/// behind the scenes to implement select constant exprs.
567class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
Gabor Greife9ecc682008-04-06 20:25:17 +0000568 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Gordon Henriksen14a55692007-12-10 02:14:30 +0000569public:
Gabor Greife9ecc682008-04-06 20:25:17 +0000570 // allocate space for exactly three operands
571 void *operator new(size_t s) {
572 return User::operator new(s, 3);
573 }
Gordon Henriksen14a55692007-12-10 02:14:30 +0000574 SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
Gabor Greiff6caff662008-05-10 08:32:32 +0000575 : ConstantExpr(C2->getType(), Instruction::Select, &Op<0>(), 3) {
Gabor Greif2d3024d2008-05-26 21:33:52 +0000576 Op<0>() = C1;
577 Op<1>() = C2;
578 Op<2>() = C3;
Gordon Henriksen14a55692007-12-10 02:14:30 +0000579 }
Gabor Greiff6caff662008-05-10 08:32:32 +0000580 /// Transparently provide more efficient getOperand methods.
581 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000582};
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000583
Gordon Henriksen14a55692007-12-10 02:14:30 +0000584/// ExtractElementConstantExpr - This class is private to
585/// Constants.cpp, and is used behind the scenes to implement
586/// extractelement constant exprs.
587class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
Gabor Greife9ecc682008-04-06 20:25:17 +0000588 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Gordon Henriksen14a55692007-12-10 02:14:30 +0000589public:
Gabor Greife9ecc682008-04-06 20:25:17 +0000590 // allocate space for exactly two operands
591 void *operator new(size_t s) {
592 return User::operator new(s, 2);
593 }
Gordon Henriksen14a55692007-12-10 02:14:30 +0000594 ExtractElementConstantExpr(Constant *C1, Constant *C2)
595 : ConstantExpr(cast<VectorType>(C1->getType())->getElementType(),
Gabor Greiff6caff662008-05-10 08:32:32 +0000596 Instruction::ExtractElement, &Op<0>(), 2) {
Gabor Greif2d3024d2008-05-26 21:33:52 +0000597 Op<0>() = C1;
598 Op<1>() = C2;
Gordon Henriksen14a55692007-12-10 02:14:30 +0000599 }
Gabor Greiff6caff662008-05-10 08:32:32 +0000600 /// Transparently provide more efficient getOperand methods.
601 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000602};
Robert Bocchino23004482006-01-10 19:05:34 +0000603
Gordon Henriksen14a55692007-12-10 02:14:30 +0000604/// InsertElementConstantExpr - This class is private to
605/// Constants.cpp, and is used behind the scenes to implement
606/// insertelement constant exprs.
607class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
Gabor Greife9ecc682008-04-06 20:25:17 +0000608 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Gordon Henriksen14a55692007-12-10 02:14:30 +0000609public:
Gabor Greife9ecc682008-04-06 20:25:17 +0000610 // allocate space for exactly three operands
611 void *operator new(size_t s) {
612 return User::operator new(s, 3);
613 }
Gordon Henriksen14a55692007-12-10 02:14:30 +0000614 InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
615 : ConstantExpr(C1->getType(), Instruction::InsertElement,
Gabor Greiff6caff662008-05-10 08:32:32 +0000616 &Op<0>(), 3) {
Gabor Greif2d3024d2008-05-26 21:33:52 +0000617 Op<0>() = C1;
618 Op<1>() = C2;
619 Op<2>() = C3;
Gordon Henriksen14a55692007-12-10 02:14:30 +0000620 }
Gabor Greiff6caff662008-05-10 08:32:32 +0000621 /// Transparently provide more efficient getOperand methods.
622 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000623};
Robert Bocchinoca27f032006-01-17 20:07:22 +0000624
Gordon Henriksen14a55692007-12-10 02:14:30 +0000625/// ShuffleVectorConstantExpr - This class is private to
626/// Constants.cpp, and is used behind the scenes to implement
627/// shufflevector constant exprs.
628class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
Gabor Greife9ecc682008-04-06 20:25:17 +0000629 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Gordon Henriksen14a55692007-12-10 02:14:30 +0000630public:
Gabor Greife9ecc682008-04-06 20:25:17 +0000631 // allocate space for exactly three operands
632 void *operator new(size_t s) {
633 return User::operator new(s, 3);
634 }
Gordon Henriksen14a55692007-12-10 02:14:30 +0000635 ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
Nate Begeman94aa38d2009-02-12 21:28:33 +0000636 : ConstantExpr(VectorType::get(
637 cast<VectorType>(C1->getType())->getElementType(),
638 cast<VectorType>(C3->getType())->getNumElements()),
639 Instruction::ShuffleVector,
Gabor Greiff6caff662008-05-10 08:32:32 +0000640 &Op<0>(), 3) {
Gabor Greif2d3024d2008-05-26 21:33:52 +0000641 Op<0>() = C1;
642 Op<1>() = C2;
643 Op<2>() = C3;
Gordon Henriksen14a55692007-12-10 02:14:30 +0000644 }
Gabor Greiff6caff662008-05-10 08:32:32 +0000645 /// Transparently provide more efficient getOperand methods.
646 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000647};
648
Dan Gohman12fce772008-05-15 19:50:34 +0000649/// ExtractValueConstantExpr - This class is private to
650/// Constants.cpp, and is used behind the scenes to implement
651/// extractvalue constant exprs.
652class VISIBILITY_HIDDEN ExtractValueConstantExpr : public ConstantExpr {
Dan Gohman1ecaf452008-05-31 00:58:22 +0000653 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Dan Gohman12fce772008-05-15 19:50:34 +0000654public:
Dan Gohman1ecaf452008-05-31 00:58:22 +0000655 // allocate space for exactly one operand
656 void *operator new(size_t s) {
657 return User::operator new(s, 1);
Dan Gohman12fce772008-05-15 19:50:34 +0000658 }
Dan Gohman1ecaf452008-05-31 00:58:22 +0000659 ExtractValueConstantExpr(Constant *Agg,
660 const SmallVector<unsigned, 4> &IdxList,
661 const Type *DestTy)
662 : ConstantExpr(DestTy, Instruction::ExtractValue, &Op<0>(), 1),
663 Indices(IdxList) {
664 Op<0>() = Agg;
665 }
666
Dan Gohman7bb04502008-05-31 19:09:08 +0000667 /// Indices - These identify which value to extract.
Dan Gohman1ecaf452008-05-31 00:58:22 +0000668 const SmallVector<unsigned, 4> Indices;
669
Dan Gohman12fce772008-05-15 19:50:34 +0000670 /// Transparently provide more efficient getOperand methods.
671 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
672};
673
674/// InsertValueConstantExpr - This class is private to
675/// Constants.cpp, and is used behind the scenes to implement
676/// insertvalue constant exprs.
677class VISIBILITY_HIDDEN InsertValueConstantExpr : public ConstantExpr {
Dan Gohman1ecaf452008-05-31 00:58:22 +0000678 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Dan Gohman12fce772008-05-15 19:50:34 +0000679public:
Dan Gohman1ecaf452008-05-31 00:58:22 +0000680 // allocate space for exactly one operand
681 void *operator new(size_t s) {
682 return User::operator new(s, 2);
Dan Gohman12fce772008-05-15 19:50:34 +0000683 }
Dan Gohman1ecaf452008-05-31 00:58:22 +0000684 InsertValueConstantExpr(Constant *Agg, Constant *Val,
685 const SmallVector<unsigned, 4> &IdxList,
686 const Type *DestTy)
687 : ConstantExpr(DestTy, Instruction::InsertValue, &Op<0>(), 2),
688 Indices(IdxList) {
689 Op<0>() = Agg;
690 Op<1>() = Val;
691 }
692
Dan Gohman7bb04502008-05-31 19:09:08 +0000693 /// Indices - These identify the position for the insertion.
Dan Gohman1ecaf452008-05-31 00:58:22 +0000694 const SmallVector<unsigned, 4> Indices;
695
Dan Gohman12fce772008-05-15 19:50:34 +0000696 /// Transparently provide more efficient getOperand methods.
697 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
698};
699
700
Gordon Henriksen14a55692007-12-10 02:14:30 +0000701/// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
702/// used behind the scenes to implement getelementpr constant exprs.
Gabor Greife9ecc682008-04-06 20:25:17 +0000703class VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
Gordon Henriksen14a55692007-12-10 02:14:30 +0000704 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
Gabor Greiff6caff662008-05-10 08:32:32 +0000705 const Type *DestTy);
Gabor Greife9ecc682008-04-06 20:25:17 +0000706public:
Gabor Greif697e94c2008-05-15 10:04:30 +0000707 static GetElementPtrConstantExpr *Create(Constant *C,
708 const std::vector<Constant*>&IdxList,
Gabor Greiff6caff662008-05-10 08:32:32 +0000709 const Type *DestTy) {
Gabor Greif697e94c2008-05-15 10:04:30 +0000710 return new(IdxList.size() + 1)
711 GetElementPtrConstantExpr(C, IdxList, DestTy);
Gabor Greife9ecc682008-04-06 20:25:17 +0000712 }
Gabor Greiff6caff662008-05-10 08:32:32 +0000713 /// Transparently provide more efficient getOperand methods.
714 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000715};
716
717// CompareConstantExpr - This class is private to Constants.cpp, and is used
718// behind the scenes to implement ICmp and FCmp constant expressions. This is
719// needed in order to store the predicate value for these instructions.
720struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
Gabor Greife9ecc682008-04-06 20:25:17 +0000721 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
722 // allocate space for exactly two operands
723 void *operator new(size_t s) {
724 return User::operator new(s, 2);
725 }
Gordon Henriksen14a55692007-12-10 02:14:30 +0000726 unsigned short predicate;
Nate Begemand2195702008-05-12 19:01:56 +0000727 CompareConstantExpr(const Type *ty, Instruction::OtherOps opc,
728 unsigned short pred, Constant* LHS, Constant* RHS)
729 : ConstantExpr(ty, opc, &Op<0>(), 2), predicate(pred) {
Gabor Greif2d3024d2008-05-26 21:33:52 +0000730 Op<0>() = LHS;
731 Op<1>() = RHS;
Gordon Henriksen14a55692007-12-10 02:14:30 +0000732 }
Gabor Greiff6caff662008-05-10 08:32:32 +0000733 /// Transparently provide more efficient getOperand methods.
734 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000735};
736
737} // end anonymous namespace
738
Gabor Greiff6caff662008-05-10 08:32:32 +0000739template <>
740struct OperandTraits<UnaryConstantExpr> : FixedNumOperandTraits<1> {
741};
742DEFINE_TRANSPARENT_OPERAND_ACCESSORS(UnaryConstantExpr, Value)
743
744template <>
745struct OperandTraits<BinaryConstantExpr> : FixedNumOperandTraits<2> {
746};
747DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BinaryConstantExpr, Value)
748
749template <>
750struct OperandTraits<SelectConstantExpr> : FixedNumOperandTraits<3> {
751};
752DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectConstantExpr, Value)
753
754template <>
755struct OperandTraits<ExtractElementConstantExpr> : FixedNumOperandTraits<2> {
756};
757DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementConstantExpr, Value)
758
759template <>
760struct OperandTraits<InsertElementConstantExpr> : FixedNumOperandTraits<3> {
761};
762DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementConstantExpr, Value)
763
764template <>
765struct OperandTraits<ShuffleVectorConstantExpr> : FixedNumOperandTraits<3> {
766};
767DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorConstantExpr, Value)
768
Dan Gohman12fce772008-05-15 19:50:34 +0000769template <>
Dan Gohman1ecaf452008-05-31 00:58:22 +0000770struct OperandTraits<ExtractValueConstantExpr> : FixedNumOperandTraits<1> {
Dan Gohman12fce772008-05-15 19:50:34 +0000771};
Dan Gohman12fce772008-05-15 19:50:34 +0000772DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractValueConstantExpr, Value)
773
774template <>
Dan Gohman1ecaf452008-05-31 00:58:22 +0000775struct OperandTraits<InsertValueConstantExpr> : FixedNumOperandTraits<2> {
Dan Gohman12fce772008-05-15 19:50:34 +0000776};
Dan Gohman12fce772008-05-15 19:50:34 +0000777DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueConstantExpr, Value)
778
Gabor Greiff6caff662008-05-10 08:32:32 +0000779template <>
780struct OperandTraits<GetElementPtrConstantExpr> : VariadicOperandTraits<1> {
781};
782
783GetElementPtrConstantExpr::GetElementPtrConstantExpr
784 (Constant *C,
785 const std::vector<Constant*> &IdxList,
786 const Type *DestTy)
787 : ConstantExpr(DestTy, Instruction::GetElementPtr,
788 OperandTraits<GetElementPtrConstantExpr>::op_end(this)
789 - (IdxList.size()+1),
790 IdxList.size()+1) {
Gabor Greif2d3024d2008-05-26 21:33:52 +0000791 OperandList[0] = C;
Gabor Greiff6caff662008-05-10 08:32:32 +0000792 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
Gabor Greif2d3024d2008-05-26 21:33:52 +0000793 OperandList[i+1] = IdxList[i];
Gabor Greiff6caff662008-05-10 08:32:32 +0000794}
795
796DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrConstantExpr, Value)
797
798
799template <>
800struct OperandTraits<CompareConstantExpr> : FixedNumOperandTraits<2> {
801};
802DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CompareConstantExpr, Value)
803
804
805} // End llvm namespace
806
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000807
808// Utility function for determining if a ConstantExpr is a CastOp or not. This
809// can't be inline because we don't want to #include Instruction.h into
810// Constant.h
811bool ConstantExpr::isCast() const {
812 return Instruction::isCast(getOpcode());
813}
814
Reid Spenceree3c9912006-12-04 05:19:50 +0000815bool ConstantExpr::isCompare() const {
Chris Lattnereab49262008-07-14 05:17:31 +0000816 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp ||
817 getOpcode() == Instruction::VICmp || getOpcode() == Instruction::VFCmp;
Reid Spenceree3c9912006-12-04 05:19:50 +0000818}
819
Dan Gohman1ecaf452008-05-31 00:58:22 +0000820bool ConstantExpr::hasIndices() const {
821 return getOpcode() == Instruction::ExtractValue ||
822 getOpcode() == Instruction::InsertValue;
823}
824
825const SmallVector<unsigned, 4> &ConstantExpr::getIndices() const {
826 if (const ExtractValueConstantExpr *EVCE =
827 dyn_cast<ExtractValueConstantExpr>(this))
828 return EVCE->Indices;
Dan Gohmana469bdb2008-06-23 16:39:44 +0000829
830 return cast<InsertValueConstantExpr>(this)->Indices;
Dan Gohman1ecaf452008-05-31 00:58:22 +0000831}
832
Chris Lattner817175f2004-03-29 02:37:53 +0000833/// ConstantExpr::get* - Return some common constants without having to
834/// specify the full Instruction::OPCODE identifier.
835///
836Constant *ConstantExpr::getNeg(Constant *C) {
Dan Gohmana5b96452009-06-04 22:49:04 +0000837 // API compatibility: Adjust integer opcodes to floating-point opcodes.
838 if (C->getType()->isFPOrFPVector())
839 return getFNeg(C);
840 assert(C->getType()->isIntOrIntVector() &&
841 "Cannot NEG a nonintegral value!");
Reid Spencer2eadb532007-01-21 00:29:26 +0000842 return get(Instruction::Sub,
843 ConstantExpr::getZeroValueForNegationExpr(C->getType()),
844 C);
Chris Lattner817175f2004-03-29 02:37:53 +0000845}
Dan Gohmana5b96452009-06-04 22:49:04 +0000846Constant *ConstantExpr::getFNeg(Constant *C) {
847 assert(C->getType()->isFPOrFPVector() &&
848 "Cannot FNEG a non-floating-point value!");
849 return get(Instruction::FSub,
850 ConstantExpr::getZeroValueForNegationExpr(C->getType()),
851 C);
852}
Chris Lattner817175f2004-03-29 02:37:53 +0000853Constant *ConstantExpr::getNot(Constant *C) {
Dan Gohmana5b96452009-06-04 22:49:04 +0000854 assert(C->getType()->isIntOrIntVector() &&
855 "Cannot NOT a nonintegral value!");
Chris Lattner817175f2004-03-29 02:37:53 +0000856 return get(Instruction::Xor, C,
Dale Johannesen47a5ef32008-08-21 21:20:09 +0000857 Constant::getAllOnesValue(C->getType()));
Chris Lattner817175f2004-03-29 02:37:53 +0000858}
859Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
860 return get(Instruction::Add, C1, C2);
861}
Dan Gohmana5b96452009-06-04 22:49:04 +0000862Constant *ConstantExpr::getFAdd(Constant *C1, Constant *C2) {
863 return get(Instruction::FAdd, C1, C2);
864}
Chris Lattner817175f2004-03-29 02:37:53 +0000865Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
866 return get(Instruction::Sub, C1, C2);
867}
Dan Gohmana5b96452009-06-04 22:49:04 +0000868Constant *ConstantExpr::getFSub(Constant *C1, Constant *C2) {
869 return get(Instruction::FSub, C1, C2);
870}
Chris Lattner817175f2004-03-29 02:37:53 +0000871Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
872 return get(Instruction::Mul, C1, C2);
873}
Dan Gohmana5b96452009-06-04 22:49:04 +0000874Constant *ConstantExpr::getFMul(Constant *C1, Constant *C2) {
875 return get(Instruction::FMul, C1, C2);
876}
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000877Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2) {
878 return get(Instruction::UDiv, C1, C2);
879}
880Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2) {
881 return get(Instruction::SDiv, C1, C2);
882}
883Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
884 return get(Instruction::FDiv, C1, C2);
Chris Lattner817175f2004-03-29 02:37:53 +0000885}
Reid Spencer7eb55b32006-11-02 01:53:59 +0000886Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
887 return get(Instruction::URem, C1, C2);
888}
889Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
890 return get(Instruction::SRem, C1, C2);
891}
892Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
893 return get(Instruction::FRem, C1, C2);
Chris Lattner817175f2004-03-29 02:37:53 +0000894}
895Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
896 return get(Instruction::And, C1, C2);
897}
898Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
899 return get(Instruction::Or, C1, C2);
900}
901Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
902 return get(Instruction::Xor, C1, C2);
903}
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000904unsigned ConstantExpr::getPredicate() const {
Nate Begemand2195702008-05-12 19:01:56 +0000905 assert(getOpcode() == Instruction::FCmp ||
906 getOpcode() == Instruction::ICmp ||
907 getOpcode() == Instruction::VFCmp ||
908 getOpcode() == Instruction::VICmp);
Chris Lattneref650092007-10-18 16:26:24 +0000909 return ((const CompareConstantExpr*)this)->predicate;
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000910}
Chris Lattner817175f2004-03-29 02:37:53 +0000911Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
912 return get(Instruction::Shl, C1, C2);
913}
Reid Spencerfdff9382006-11-08 06:47:33 +0000914Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2) {
915 return get(Instruction::LShr, C1, C2);
Chris Lattner817175f2004-03-29 02:37:53 +0000916}
Reid Spencerfdff9382006-11-08 06:47:33 +0000917Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2) {
918 return get(Instruction::AShr, C1, C2);
Chris Lattnerdb8bdba2004-05-25 05:32:43 +0000919}
Chris Lattner60e0dd72001-10-03 06:12:09 +0000920
Chris Lattner7c1018a2006-07-14 19:37:40 +0000921/// getWithOperandReplaced - Return a constant expression identical to this
922/// one, but with the specified operand set to the specified value.
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000923Constant *
924ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
Chris Lattner7c1018a2006-07-14 19:37:40 +0000925 assert(OpNo < getNumOperands() && "Operand num is out of range!");
926 assert(Op->getType() == getOperand(OpNo)->getType() &&
927 "Replacing operand with value of different type!");
Chris Lattner227816342006-07-14 22:20:01 +0000928 if (getOperand(OpNo) == Op)
929 return const_cast<ConstantExpr*>(this);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000930
Chris Lattner227816342006-07-14 22:20:01 +0000931 Constant *Op0, *Op1, *Op2;
Chris Lattner7c1018a2006-07-14 19:37:40 +0000932 switch (getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000933 case Instruction::Trunc:
934 case Instruction::ZExt:
935 case Instruction::SExt:
936 case Instruction::FPTrunc:
937 case Instruction::FPExt:
938 case Instruction::UIToFP:
939 case Instruction::SIToFP:
940 case Instruction::FPToUI:
941 case Instruction::FPToSI:
942 case Instruction::PtrToInt:
943 case Instruction::IntToPtr:
944 case Instruction::BitCast:
945 return ConstantExpr::getCast(getOpcode(), Op, getType());
Chris Lattner227816342006-07-14 22:20:01 +0000946 case Instruction::Select:
947 Op0 = (OpNo == 0) ? Op : getOperand(0);
948 Op1 = (OpNo == 1) ? Op : getOperand(1);
949 Op2 = (OpNo == 2) ? Op : getOperand(2);
950 return ConstantExpr::getSelect(Op0, Op1, Op2);
951 case Instruction::InsertElement:
952 Op0 = (OpNo == 0) ? Op : getOperand(0);
953 Op1 = (OpNo == 1) ? Op : getOperand(1);
954 Op2 = (OpNo == 2) ? Op : getOperand(2);
955 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
956 case Instruction::ExtractElement:
957 Op0 = (OpNo == 0) ? Op : getOperand(0);
958 Op1 = (OpNo == 1) ? Op : getOperand(1);
959 return ConstantExpr::getExtractElement(Op0, Op1);
960 case Instruction::ShuffleVector:
961 Op0 = (OpNo == 0) ? Op : getOperand(0);
962 Op1 = (OpNo == 1) ? Op : getOperand(1);
963 Op2 = (OpNo == 2) ? Op : getOperand(2);
964 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000965 case Instruction::GetElementPtr: {
Chris Lattnerb5d70302007-02-19 20:01:23 +0000966 SmallVector<Constant*, 8> Ops;
Dan Gohman12fce772008-05-15 19:50:34 +0000967 Ops.resize(getNumOperands()-1);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000968 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
Dan Gohman12fce772008-05-15 19:50:34 +0000969 Ops[i-1] = getOperand(i);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000970 if (OpNo == 0)
Chris Lattnerb5d70302007-02-19 20:01:23 +0000971 return ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
Chris Lattner7c1018a2006-07-14 19:37:40 +0000972 Ops[OpNo-1] = Op;
Chris Lattnerb5d70302007-02-19 20:01:23 +0000973 return ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
Chris Lattner7c1018a2006-07-14 19:37:40 +0000974 }
Chris Lattner7c1018a2006-07-14 19:37:40 +0000975 default:
976 assert(getNumOperands() == 2 && "Must be binary operator?");
Chris Lattner227816342006-07-14 22:20:01 +0000977 Op0 = (OpNo == 0) ? Op : getOperand(0);
978 Op1 = (OpNo == 1) ? Op : getOperand(1);
979 return ConstantExpr::get(getOpcode(), Op0, Op1);
980 }
981}
982
983/// getWithOperands - This returns the current constant expression with the
984/// operands replaced with the specified values. The specified operands must
985/// match count and type with the existing ones.
986Constant *ConstantExpr::
Chris Lattnerb078e282008-08-20 22:27:40 +0000987getWithOperands(Constant* const *Ops, unsigned NumOps) const {
988 assert(NumOps == getNumOperands() && "Operand count mismatch!");
Chris Lattner227816342006-07-14 22:20:01 +0000989 bool AnyChange = false;
Chris Lattnerb078e282008-08-20 22:27:40 +0000990 for (unsigned i = 0; i != NumOps; ++i) {
Chris Lattner227816342006-07-14 22:20:01 +0000991 assert(Ops[i]->getType() == getOperand(i)->getType() &&
992 "Operand type mismatch!");
993 AnyChange |= Ops[i] != getOperand(i);
994 }
995 if (!AnyChange) // No operands changed, return self.
996 return const_cast<ConstantExpr*>(this);
997
998 switch (getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000999 case Instruction::Trunc:
1000 case Instruction::ZExt:
1001 case Instruction::SExt:
1002 case Instruction::FPTrunc:
1003 case Instruction::FPExt:
1004 case Instruction::UIToFP:
1005 case Instruction::SIToFP:
1006 case Instruction::FPToUI:
1007 case Instruction::FPToSI:
1008 case Instruction::PtrToInt:
1009 case Instruction::IntToPtr:
1010 case Instruction::BitCast:
1011 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
Chris Lattner227816342006-07-14 22:20:01 +00001012 case Instruction::Select:
1013 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
1014 case Instruction::InsertElement:
1015 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
1016 case Instruction::ExtractElement:
1017 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
1018 case Instruction::ShuffleVector:
1019 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
Chris Lattnerb5d70302007-02-19 20:01:23 +00001020 case Instruction::GetElementPtr:
Chris Lattnerb078e282008-08-20 22:27:40 +00001021 return ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], NumOps-1);
Reid Spencer266e42b2006-12-23 06:05:41 +00001022 case Instruction::ICmp:
1023 case Instruction::FCmp:
Nate Begeman098cc6f2008-07-25 17:56:27 +00001024 case Instruction::VICmp:
1025 case Instruction::VFCmp:
Reid Spencer266e42b2006-12-23 06:05:41 +00001026 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
Chris Lattner227816342006-07-14 22:20:01 +00001027 default:
1028 assert(getNumOperands() == 2 && "Must be binary operator?");
1029 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
Chris Lattner7c1018a2006-07-14 19:37:40 +00001030 }
1031}
1032
Chris Lattner2f7c9632001-06-06 20:29:01 +00001033
1034//===----------------------------------------------------------------------===//
Chris Lattner2f7c9632001-06-06 20:29:01 +00001035// isValueValidForType implementations
1036
Reid Spencere7334722006-12-19 01:28:19 +00001037bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001038 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001039 if (Ty == Type::Int1Ty)
1040 return Val == 0 || Val == 1;
Reid Spencerd7a00d72007-02-05 23:47:56 +00001041 if (NumBits >= 64)
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001042 return true; // always true, has to fit in largest type
1043 uint64_t Max = (1ll << NumBits) - 1;
1044 return Val <= Max;
Reid Spencere7334722006-12-19 01:28:19 +00001045}
1046
Reid Spencere0fc4df2006-10-20 07:07:24 +00001047bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001048 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001049 if (Ty == Type::Int1Ty)
Reid Spencera94d3942007-01-19 21:13:56 +00001050 return Val == 0 || Val == 1 || Val == -1;
Reid Spencerd7a00d72007-02-05 23:47:56 +00001051 if (NumBits >= 64)
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001052 return true; // always true, has to fit in largest type
1053 int64_t Min = -(1ll << (NumBits-1));
1054 int64_t Max = (1ll << (NumBits-1)) - 1;
1055 return (Val >= Min && Val <= Max);
Chris Lattner2f7c9632001-06-06 20:29:01 +00001056}
1057
Dale Johannesend246b2c2007-08-30 00:23:21 +00001058bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
1059 // convert modifies in place, so make a copy.
1060 APFloat Val2 = APFloat(Val);
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001061 bool losesInfo;
Chris Lattner6b727592004-06-17 18:19:28 +00001062 switch (Ty->getTypeID()) {
Chris Lattner2f7c9632001-06-06 20:29:01 +00001063 default:
1064 return false; // These can't be represented as floating point!
1065
Dale Johannesend246b2c2007-08-30 00:23:21 +00001066 // FIXME rounding mode needs to be more flexible
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001067 case Type::FloatTyID: {
1068 if (&Val2.getSemantics() == &APFloat::IEEEsingle)
1069 return true;
1070 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
1071 return !losesInfo;
1072 }
1073 case Type::DoubleTyID: {
1074 if (&Val2.getSemantics() == &APFloat::IEEEsingle ||
1075 &Val2.getSemantics() == &APFloat::IEEEdouble)
1076 return true;
1077 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
1078 return !losesInfo;
1079 }
Dale Johannesenbdad8092007-08-09 22:51:36 +00001080 case Type::X86_FP80TyID:
Dale Johannesen028084e2007-09-12 03:30:33 +00001081 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
1082 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1083 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
Dale Johannesenbdad8092007-08-09 22:51:36 +00001084 case Type::FP128TyID:
Dale Johannesen028084e2007-09-12 03:30:33 +00001085 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
1086 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1087 &Val2.getSemantics() == &APFloat::IEEEquad;
Dale Johannesen007aa372007-10-11 18:07:22 +00001088 case Type::PPC_FP128TyID:
1089 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
1090 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1091 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
Chris Lattner2f7c9632001-06-06 20:29:01 +00001092 }
Chris Lattneraa2372562006-05-24 17:04:05 +00001093}
Chris Lattner9655e542001-07-20 19:16:02 +00001094
Chris Lattner49d855c2001-09-07 16:46:31 +00001095//===----------------------------------------------------------------------===//
Chris Lattner49d855c2001-09-07 16:46:31 +00001096// Factory Function Implementation
1097
Gabor Greiff6caff662008-05-10 08:32:32 +00001098
1099// The number of operands for each ConstantCreator::create method is
1100// determined by the ConstantTraits template.
Chris Lattner98fa07b2003-05-23 20:03:32 +00001101// ConstantCreator - A class that is used to create constants by
1102// ValueMap*. This class should be partially specialized if there is
1103// something strange that needs to be done to interface to the ctor for the
1104// constant.
1105//
Chris Lattner189d19f2003-11-21 20:23:48 +00001106namespace llvm {
Gabor Greiff6caff662008-05-10 08:32:32 +00001107 template<class ValType>
1108 struct ConstantTraits;
1109
1110 template<typename T, typename Alloc>
1111 struct VISIBILITY_HIDDEN ConstantTraits< std::vector<T, Alloc> > {
1112 static unsigned uses(const std::vector<T, Alloc>& v) {
1113 return v.size();
1114 }
1115 };
1116
Chris Lattner189d19f2003-11-21 20:23:48 +00001117 template<class ConstantClass, class TypeClass, class ValType>
Chris Lattner02157b02006-06-28 21:38:54 +00001118 struct VISIBILITY_HIDDEN ConstantCreator {
Chris Lattner189d19f2003-11-21 20:23:48 +00001119 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
Gabor Greiff6caff662008-05-10 08:32:32 +00001120 return new(ConstantTraits<ValType>::uses(V)) ConstantClass(Ty, V);
Chris Lattner189d19f2003-11-21 20:23:48 +00001121 }
1122 };
Misha Brukmanb1c93172005-04-21 23:48:37 +00001123
Chris Lattner189d19f2003-11-21 20:23:48 +00001124 template<class ConstantClass, class TypeClass>
Chris Lattner02157b02006-06-28 21:38:54 +00001125 struct VISIBILITY_HIDDEN ConvertConstantType {
Chris Lattner189d19f2003-11-21 20:23:48 +00001126 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
1127 assert(0 && "This type cannot be converted!\n");
1128 abort();
1129 }
1130 };
Chris Lattnerb50d1352003-10-05 00:17:43 +00001131
Chris Lattner935aa922005-10-04 17:48:46 +00001132 template<class ValType, class TypeClass, class ConstantClass,
1133 bool HasLargeKey = false /*true for arrays and structs*/ >
Chris Lattner02157b02006-06-28 21:38:54 +00001134 class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
Chris Lattnerb64419a2005-10-03 22:51:37 +00001135 public:
Jim Laskeyc03caef2006-07-17 17:38:29 +00001136 typedef std::pair<const Type*, ValType> MapKey;
1137 typedef std::map<MapKey, Constant *> MapTy;
1138 typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
1139 typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
Chris Lattnerb64419a2005-10-03 22:51:37 +00001140 private:
Chris Lattner5bbf60a52005-10-04 16:52:46 +00001141 /// Map - This is the main map from the element descriptor to the Constants.
1142 /// This is the primary way we avoid creating two of the same shape
1143 /// constant.
Chris Lattnerb50d1352003-10-05 00:17:43 +00001144 MapTy Map;
Chris Lattner935aa922005-10-04 17:48:46 +00001145
1146 /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
1147 /// from the constants to their element in Map. This is important for
1148 /// removal of constants from the array, which would otherwise have to scan
1149 /// through the map with very large keys.
Jim Laskeyc03caef2006-07-17 17:38:29 +00001150 InverseMapTy InverseMap;
Chris Lattnerb50d1352003-10-05 00:17:43 +00001151
Jim Laskeyc03caef2006-07-17 17:38:29 +00001152 /// AbstractTypeMap - Map for abstract type constants.
1153 ///
Chris Lattnerb50d1352003-10-05 00:17:43 +00001154 AbstractTypeMapTy AbstractTypeMap;
Chris Lattner99a669b2004-11-19 16:39:44 +00001155
Chris Lattner98fa07b2003-05-23 20:03:32 +00001156 public:
Owen Anderson61794042009-06-17 20:10:08 +00001157 // NOTE: This function is not locked. It is the caller's responsibility
1158 // to enforce proper synchronization.
Jim Laskeyc03caef2006-07-17 17:38:29 +00001159 typename MapTy::iterator map_end() { return Map.end(); }
Chris Lattnerb64419a2005-10-03 22:51:37 +00001160
1161 /// InsertOrGetItem - Return an iterator for the specified element.
1162 /// If the element exists in the map, the returned iterator points to the
1163 /// entry and Exists=true. If not, the iterator points to the newly
1164 /// inserted entry and returns Exists=false. Newly inserted entries have
1165 /// I->second == 0, and should be filled in.
Owen Anderson61794042009-06-17 20:10:08 +00001166 /// NOTE: This function is not locked. It is the caller's responsibility
1167 // to enforce proper synchronization.
Jim Laskeyc03caef2006-07-17 17:38:29 +00001168 typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
1169 &InsertVal,
Chris Lattnerb64419a2005-10-03 22:51:37 +00001170 bool &Exists) {
Jim Laskeyc03caef2006-07-17 17:38:29 +00001171 std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
Chris Lattnerb64419a2005-10-03 22:51:37 +00001172 Exists = !IP.second;
1173 return IP.first;
1174 }
Chris Lattner5bbf60a52005-10-04 16:52:46 +00001175
Chris Lattner935aa922005-10-04 17:48:46 +00001176private:
Jim Laskeyc03caef2006-07-17 17:38:29 +00001177 typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
Chris Lattner935aa922005-10-04 17:48:46 +00001178 if (HasLargeKey) {
Jim Laskeyc03caef2006-07-17 17:38:29 +00001179 typename InverseMapTy::iterator IMI = InverseMap.find(CP);
Chris Lattner935aa922005-10-04 17:48:46 +00001180 assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
1181 IMI->second->second == CP &&
1182 "InverseMap corrupt!");
1183 return IMI->second;
1184 }
1185
Jim Laskeyc03caef2006-07-17 17:38:29 +00001186 typename MapTy::iterator I =
Dan Gohmane955c482008-08-05 14:45:15 +00001187 Map.find(MapKey(static_cast<const TypeClass*>(CP->getRawType()),
1188 getValType(CP)));
Chris Lattner5bbf60a52005-10-04 16:52:46 +00001189 if (I == Map.end() || I->second != CP) {
1190 // FIXME: This should not use a linear scan. If this gets to be a
1191 // performance problem, someone should look at this.
1192 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
1193 /* empty */;
1194 }
Chris Lattner935aa922005-10-04 17:48:46 +00001195 return I;
1196 }
Owen Andersonf89c38c2009-06-17 20:43:39 +00001197
1198 ConstantClass* Create(const TypeClass *Ty, const ValType &V,
1199 typename MapTy::iterator I) {
1200 ConstantClass* Result =
1201 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
1202
1203 assert(Result->getType() == Ty && "Type specified is not correct!");
1204 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
1205
1206 if (HasLargeKey) // Remember the reverse mapping if needed.
1207 InverseMap.insert(std::make_pair(Result, I));
1208
1209 // If the type of the constant is abstract, make sure that an entry
1210 // exists for it in the AbstractTypeMap.
1211 if (Ty->isAbstract()) {
1212 typename AbstractTypeMapTy::iterator TI =
1213 AbstractTypeMap.find(Ty);
1214
1215 if (TI == AbstractTypeMap.end()) {
1216 // Add ourselves to the ATU list of the type.
1217 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
1218
1219 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
1220 }
1221 }
1222
1223 return Result;
1224 }
Chris Lattner935aa922005-10-04 17:48:46 +00001225public:
1226
Chris Lattnerb64419a2005-10-03 22:51:37 +00001227 /// getOrCreate - Return the specified constant from the map, creating it if
1228 /// necessary.
Chris Lattner98fa07b2003-05-23 20:03:32 +00001229 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
Chris Lattnerb50d1352003-10-05 00:17:43 +00001230 MapKey Lookup(Ty, V);
Owen Andersond830eb82009-06-18 19:10:19 +00001231 ConstantClass* Result = 0;
1232
1233 ConstantsLock->reader_acquire();
1234 typename MapTy::iterator I = Map.find(Lookup);
1235 // Is it in the map?
1236 if (I != Map.end())
1237 Result = static_cast<ConstantClass *>(I->second);
1238 ConstantsLock->reader_release();
Owen Anderson61794042009-06-17 20:10:08 +00001239
Owen Andersond830eb82009-06-18 19:10:19 +00001240 if (!Result) {
1241 sys::SmartScopedWriter<true> Writer(&*ConstantsLock);
1242 I = Map.find(Lookup);
Owen Anderson61794042009-06-17 20:10:08 +00001243 // Is it in the map?
1244 if (I != Map.end())
1245 Result = static_cast<ConstantClass *>(I->second);
Owen Anderson61794042009-06-17 20:10:08 +00001246 if (!Result) {
Owen Andersond830eb82009-06-18 19:10:19 +00001247 // If no preexisting value, create one now...
1248 Result = Create(Ty, V, I);
Chris Lattnerb50d1352003-10-05 00:17:43 +00001249 }
1250 }
Owen Andersond830eb82009-06-18 19:10:19 +00001251
1252 return Result;
Chris Lattner98fa07b2003-05-23 20:03:32 +00001253 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001254
Chris Lattner98fa07b2003-05-23 20:03:32 +00001255 void remove(ConstantClass *CP) {
Owen Andersond830eb82009-06-18 19:10:19 +00001256 ConstantsLock->writer_acquire();
Jim Laskeyc03caef2006-07-17 17:38:29 +00001257 typename MapTy::iterator I = FindExistingElement(CP);
Chris Lattnerb50d1352003-10-05 00:17:43 +00001258 assert(I != Map.end() && "Constant not found in constant table!");
Chris Lattner3e650af2004-08-04 04:48:01 +00001259 assert(I->second == CP && "Didn't find correct element?");
Chris Lattnerb50d1352003-10-05 00:17:43 +00001260
Chris Lattner935aa922005-10-04 17:48:46 +00001261 if (HasLargeKey) // Remember the reverse mapping if needed.
1262 InverseMap.erase(CP);
1263
Chris Lattnerb50d1352003-10-05 00:17:43 +00001264 // Now that we found the entry, make sure this isn't the entry that
1265 // the AbstractTypeMap points to.
Jim Laskeyc03caef2006-07-17 17:38:29 +00001266 const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
Chris Lattnerb50d1352003-10-05 00:17:43 +00001267 if (Ty->isAbstract()) {
1268 assert(AbstractTypeMap.count(Ty) &&
1269 "Abstract type not in AbstractTypeMap?");
Jim Laskeyc03caef2006-07-17 17:38:29 +00001270 typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
Chris Lattnerb50d1352003-10-05 00:17:43 +00001271 if (ATMEntryIt == I) {
1272 // Yes, we are removing the representative entry for this type.
1273 // See if there are any other entries of the same type.
Jim Laskeyc03caef2006-07-17 17:38:29 +00001274 typename MapTy::iterator TmpIt = ATMEntryIt;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001275
Chris Lattnerb50d1352003-10-05 00:17:43 +00001276 // First check the entry before this one...
1277 if (TmpIt != Map.begin()) {
1278 --TmpIt;
1279 if (TmpIt->first.first != Ty) // Not the same type, move back...
1280 ++TmpIt;
1281 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001282
Chris Lattnerb50d1352003-10-05 00:17:43 +00001283 // If we didn't find the same type, try to move forward...
1284 if (TmpIt == ATMEntryIt) {
1285 ++TmpIt;
1286 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
1287 --TmpIt; // No entry afterwards with the same type
1288 }
1289
1290 // If there is another entry in the map of the same abstract type,
1291 // update the AbstractTypeMap entry now.
1292 if (TmpIt != ATMEntryIt) {
1293 ATMEntryIt = TmpIt;
1294 } else {
1295 // Otherwise, we are removing the last instance of this type
1296 // from the table. Remove from the ATM, and from user list.
1297 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
1298 AbstractTypeMap.erase(Ty);
1299 }
Chris Lattner98fa07b2003-05-23 20:03:32 +00001300 }
Chris Lattnerb50d1352003-10-05 00:17:43 +00001301 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001302
Chris Lattnerb50d1352003-10-05 00:17:43 +00001303 Map.erase(I);
Owen Anderson61794042009-06-17 20:10:08 +00001304
Owen Andersond830eb82009-06-18 19:10:19 +00001305 ConstantsLock->writer_release();
Chris Lattnerb50d1352003-10-05 00:17:43 +00001306 }
1307
Chris Lattner3b793c62005-10-04 21:35:50 +00001308
1309 /// MoveConstantToNewSlot - If we are about to change C to be the element
1310 /// specified by I, update our internal data structures to reflect this
1311 /// fact.
Owen Anderson61794042009-06-17 20:10:08 +00001312 /// NOTE: This function is not locked. It is the responsibility of the
1313 /// caller to enforce proper synchronization if using this method.
Jim Laskeyc03caef2006-07-17 17:38:29 +00001314 void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
Chris Lattner3b793c62005-10-04 21:35:50 +00001315 // First, remove the old location of the specified constant in the map.
Jim Laskeyc03caef2006-07-17 17:38:29 +00001316 typename MapTy::iterator OldI = FindExistingElement(C);
Chris Lattner3b793c62005-10-04 21:35:50 +00001317 assert(OldI != Map.end() && "Constant not found in constant table!");
1318 assert(OldI->second == C && "Didn't find correct element?");
1319
1320 // If this constant is the representative element for its abstract type,
1321 // update the AbstractTypeMap so that the representative element is I.
1322 if (C->getType()->isAbstract()) {
1323 typename AbstractTypeMapTy::iterator ATI =
1324 AbstractTypeMap.find(C->getType());
1325 assert(ATI != AbstractTypeMap.end() &&
1326 "Abstract type not in AbstractTypeMap?");
1327 if (ATI->second == OldI)
1328 ATI->second = I;
1329 }
1330
1331 // Remove the old entry from the map.
1332 Map.erase(OldI);
1333
1334 // Update the inverse map so that we know that this constant is now
1335 // located at descriptor I.
1336 if (HasLargeKey) {
1337 assert(I->second == C && "Bad inversemap entry!");
1338 InverseMap[C] = I;
1339 }
1340 }
1341
Chris Lattnerb50d1352003-10-05 00:17:43 +00001342 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
Owen Andersond830eb82009-06-18 19:10:19 +00001343 ConstantsLock->writer_acquire();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001344 typename AbstractTypeMapTy::iterator I =
Jim Laskeyc03caef2006-07-17 17:38:29 +00001345 AbstractTypeMap.find(cast<Type>(OldTy));
Chris Lattnerb50d1352003-10-05 00:17:43 +00001346
1347 assert(I != AbstractTypeMap.end() &&
1348 "Abstract type not in AbstractTypeMap?");
1349
1350 // Convert a constant at a time until the last one is gone. The last one
1351 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
1352 // eliminated eventually.
1353 do {
1354 ConvertConstantType<ConstantClass,
Jim Laskeyc03caef2006-07-17 17:38:29 +00001355 TypeClass>::convert(
1356 static_cast<ConstantClass *>(I->second->second),
Chris Lattnerb50d1352003-10-05 00:17:43 +00001357 cast<TypeClass>(NewTy));
1358
Jim Laskeyc03caef2006-07-17 17:38:29 +00001359 I = AbstractTypeMap.find(cast<Type>(OldTy));
Chris Lattnerb50d1352003-10-05 00:17:43 +00001360 } while (I != AbstractTypeMap.end());
Owen Anderson61794042009-06-17 20:10:08 +00001361
Owen Andersond830eb82009-06-18 19:10:19 +00001362 ConstantsLock->writer_release();
Chris Lattnerb50d1352003-10-05 00:17:43 +00001363 }
1364
1365 // If the type became concrete without being refined to any other existing
1366 // type, we just remove ourselves from the ATU list.
1367 void typeBecameConcrete(const DerivedType *AbsTy) {
Owen Andersond830eb82009-06-18 19:10:19 +00001368 sys::SmartScopedWriter<true> Writer(&*ConstantsLock);
1369 AbsTy->removeAbstractTypeUser(this);
Chris Lattnerb50d1352003-10-05 00:17:43 +00001370 }
1371
1372 void dump() const {
Bill Wendling6a462f12006-11-17 08:03:48 +00001373 DOUT << "Constant.cpp: ValueMap\n";
Chris Lattner98fa07b2003-05-23 20:03:32 +00001374 }
1375 };
1376}
1377
Chris Lattnera84df0a22006-09-28 23:36:21 +00001378
Chris Lattner28173502007-02-20 06:11:36 +00001379
Chris Lattner9fba3da2004-02-15 05:53:04 +00001380//---- ConstantAggregateZero::get() implementation...
1381//
1382namespace llvm {
1383 // ConstantAggregateZero does not take extra "value" argument...
1384 template<class ValType>
1385 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
1386 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
1387 return new ConstantAggregateZero(Ty);
1388 }
1389 };
1390
1391 template<>
1392 struct ConvertConstantType<ConstantAggregateZero, Type> {
1393 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
1394 // Make everyone now use a constant of the new type...
1395 Constant *New = ConstantAggregateZero::get(NewTy);
1396 assert(New != OldC && "Didn't replace constant??");
1397 OldC->uncheckedReplaceAllUsesWith(New);
1398 OldC->destroyConstant(); // This constant is now dead, destroy it.
1399 }
1400 };
1401}
1402
Chris Lattner69edc982006-09-28 00:35:06 +00001403static ManagedStatic<ValueMap<char, Type,
1404 ConstantAggregateZero> > AggZeroConstants;
Chris Lattner9fba3da2004-02-15 05:53:04 +00001405
Chris Lattner3e650af2004-08-04 04:48:01 +00001406static char getValType(ConstantAggregateZero *CPZ) { return 0; }
1407
Dan Gohman8214fc12008-12-08 07:10:54 +00001408ConstantAggregateZero *ConstantAggregateZero::get(const Type *Ty) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001409 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) &&
Chris Lattnerbfd0b6d2006-06-10 04:16:23 +00001410 "Cannot create an aggregate zero of non-aggregate type!");
Owen Anderson61794042009-06-17 20:10:08 +00001411
1412 // Implicitly locked.
1413 return AggZeroConstants->getOrCreate(Ty, 0);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001414}
1415
Dan Gohman92b551b2009-03-03 02:55:14 +00001416/// destroyConstant - Remove the constant from the constant table...
1417///
Chris Lattner9fba3da2004-02-15 05:53:04 +00001418void ConstantAggregateZero::destroyConstant() {
Owen Anderson61794042009-06-17 20:10:08 +00001419 // Implicitly locked.
Chris Lattner69edc982006-09-28 00:35:06 +00001420 AggZeroConstants->remove(this);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001421 destroyConstantImpl();
1422}
1423
Chris Lattner3462ae32001-12-03 22:26:30 +00001424//---- ConstantArray::get() implementation...
Chris Lattner49d855c2001-09-07 16:46:31 +00001425//
Chris Lattner189d19f2003-11-21 20:23:48 +00001426namespace llvm {
1427 template<>
1428 struct ConvertConstantType<ConstantArray, ArrayType> {
1429 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
1430 // Make everyone now use a constant of the new type...
1431 std::vector<Constant*> C;
1432 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1433 C.push_back(cast<Constant>(OldC->getOperand(i)));
1434 Constant *New = ConstantArray::get(NewTy, C);
1435 assert(New != OldC && "Didn't replace constant??");
1436 OldC->uncheckedReplaceAllUsesWith(New);
1437 OldC->destroyConstant(); // This constant is now dead, destroy it.
1438 }
1439 };
1440}
Chris Lattnerb50d1352003-10-05 00:17:43 +00001441
Chris Lattner3e650af2004-08-04 04:48:01 +00001442static std::vector<Constant*> getValType(ConstantArray *CA) {
1443 std::vector<Constant*> Elements;
1444 Elements.reserve(CA->getNumOperands());
1445 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1446 Elements.push_back(cast<Constant>(CA->getOperand(i)));
1447 return Elements;
1448}
1449
Chris Lattnerb64419a2005-10-03 22:51:37 +00001450typedef ValueMap<std::vector<Constant*>, ArrayType,
Chris Lattner935aa922005-10-04 17:48:46 +00001451 ConstantArray, true /*largekey*/> ArrayConstantsTy;
Chris Lattner69edc982006-09-28 00:35:06 +00001452static ManagedStatic<ArrayConstantsTy> ArrayConstants;
Chris Lattner49d855c2001-09-07 16:46:31 +00001453
Chris Lattner015e8212004-02-15 04:14:47 +00001454Constant *ConstantArray::get(const ArrayType *Ty,
Chris Lattner9fba3da2004-02-15 05:53:04 +00001455 const std::vector<Constant*> &V) {
1456 // If this is an all-zero array, return a ConstantAggregateZero object
1457 if (!V.empty()) {
1458 Constant *C = V[0];
Owen Anderson2d7231d2009-06-17 18:40:29 +00001459 if (!C->isNullValue()) {
Owen Anderson61794042009-06-17 20:10:08 +00001460 // Implicitly locked.
Chris Lattner69edc982006-09-28 00:35:06 +00001461 return ArrayConstants->getOrCreate(Ty, V);
Owen Anderson2d7231d2009-06-17 18:40:29 +00001462 }
Chris Lattner9fba3da2004-02-15 05:53:04 +00001463 for (unsigned i = 1, e = V.size(); i != e; ++i)
Owen Anderson2d7231d2009-06-17 18:40:29 +00001464 if (V[i] != C) {
Owen Anderson61794042009-06-17 20:10:08 +00001465 // Implicitly locked.
Chris Lattner69edc982006-09-28 00:35:06 +00001466 return ArrayConstants->getOrCreate(Ty, V);
Owen Anderson2d7231d2009-06-17 18:40:29 +00001467 }
Chris Lattner9fba3da2004-02-15 05:53:04 +00001468 }
Owen Anderson2d7231d2009-06-17 18:40:29 +00001469
Chris Lattner9fba3da2004-02-15 05:53:04 +00001470 return ConstantAggregateZero::get(Ty);
Chris Lattner49d855c2001-09-07 16:46:31 +00001471}
1472
Dan Gohman92b551b2009-03-03 02:55:14 +00001473/// destroyConstant - Remove the constant from the constant table...
1474///
Chris Lattner98fa07b2003-05-23 20:03:32 +00001475void ConstantArray::destroyConstant() {
Owen Anderson59ba8142009-06-19 18:34:09 +00001476 // Implicitly locked.
Chris Lattner69edc982006-09-28 00:35:06 +00001477 ArrayConstants->remove(this);
Chris Lattner98fa07b2003-05-23 20:03:32 +00001478 destroyConstantImpl();
1479}
1480
Reid Spencer6f614532006-05-30 08:23:18 +00001481/// ConstantArray::get(const string&) - Return an array that is initialized to
1482/// contain the specified string. If length is zero then a null terminator is
1483/// added to the specified string so that it may be used in a natural way.
1484/// Otherwise, the length parameter specifies how much of the string to use
1485/// and it won't be null terminated.
1486///
Reid Spencer82ebaba2006-05-30 18:15:07 +00001487Constant *ConstantArray::get(const std::string &Str, bool AddNull) {
Chris Lattner7f74a562002-01-20 22:54:45 +00001488 std::vector<Constant*> ElementVals;
Reid Spencer82ebaba2006-05-30 18:15:07 +00001489 for (unsigned i = 0; i < Str.length(); ++i)
Reid Spencer8d9336d2006-12-31 05:26:44 +00001490 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, Str[i]));
Chris Lattner8f80fe02001-10-14 23:54:12 +00001491
1492 // Add a null terminator to the string...
Reid Spencer82ebaba2006-05-30 18:15:07 +00001493 if (AddNull) {
Reid Spencer8d9336d2006-12-31 05:26:44 +00001494 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, 0));
Reid Spencer6f614532006-05-30 08:23:18 +00001495 }
Chris Lattner8f80fe02001-10-14 23:54:12 +00001496
Reid Spencer8d9336d2006-12-31 05:26:44 +00001497 ArrayType *ATy = ArrayType::get(Type::Int8Ty, ElementVals.size());
Chris Lattner3462ae32001-12-03 22:26:30 +00001498 return ConstantArray::get(ATy, ElementVals);
Vikram S. Adve34410432001-10-14 23:17:20 +00001499}
1500
Reid Spencer2546b762007-01-26 07:37:34 +00001501/// isString - This method returns true if the array is an array of i8, and
1502/// if the elements of the array are all ConstantInt's.
Chris Lattnere8dfcca2004-01-14 17:06:38 +00001503bool ConstantArray::isString() const {
Reid Spencer2546b762007-01-26 07:37:34 +00001504 // Check the element type for i8...
Reid Spencer8d9336d2006-12-31 05:26:44 +00001505 if (getType()->getElementType() != Type::Int8Ty)
Chris Lattnere8dfcca2004-01-14 17:06:38 +00001506 return false;
1507 // Check the elements to make sure they are all integers, not constant
1508 // expressions.
1509 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1510 if (!isa<ConstantInt>(getOperand(i)))
1511 return false;
1512 return true;
1513}
1514
Evan Cheng3763c5b2006-10-26 19:15:05 +00001515/// isCString - This method returns true if the array is a string (see
Dan Gohman92b551b2009-03-03 02:55:14 +00001516/// isString) and it ends in a null byte \\0 and does not contains any other
Evan Cheng3763c5b2006-10-26 19:15:05 +00001517/// null bytes except its terminator.
1518bool ConstantArray::isCString() const {
Reid Spencer2546b762007-01-26 07:37:34 +00001519 // Check the element type for i8...
Reid Spencer8d9336d2006-12-31 05:26:44 +00001520 if (getType()->getElementType() != Type::Int8Ty)
Evan Chenge974da62006-10-26 21:48:03 +00001521 return false;
1522 Constant *Zero = Constant::getNullValue(getOperand(0)->getType());
1523 // Last element must be a null.
1524 if (getOperand(getNumOperands()-1) != Zero)
1525 return false;
1526 // Other elements must be non-null integers.
1527 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1528 if (!isa<ConstantInt>(getOperand(i)))
Evan Cheng3763c5b2006-10-26 19:15:05 +00001529 return false;
Evan Chenge974da62006-10-26 21:48:03 +00001530 if (getOperand(i) == Zero)
1531 return false;
1532 }
Evan Cheng3763c5b2006-10-26 19:15:05 +00001533 return true;
1534}
1535
1536
Dan Gohman92b551b2009-03-03 02:55:14 +00001537/// getAsString - If the sub-element type of this array is i8
1538/// then this method converts the array to an std::string and returns it.
1539/// Otherwise, it asserts out.
1540///
Chris Lattner81fabb02002-08-26 17:53:56 +00001541std::string ConstantArray::getAsString() const {
Chris Lattnere8dfcca2004-01-14 17:06:38 +00001542 assert(isString() && "Not a string!");
Chris Lattner81fabb02002-08-26 17:53:56 +00001543 std::string Result;
Owen Anderson79c69bc2008-06-24 21:58:29 +00001544 Result.reserve(getNumOperands());
Chris Lattner6077c312003-07-23 15:22:26 +00001545 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
Owen Andersonee9c30d2008-06-25 01:05:05 +00001546 Result.push_back((char)cast<ConstantInt>(getOperand(i))->getZExtValue());
Chris Lattner81fabb02002-08-26 17:53:56 +00001547 return Result;
1548}
1549
1550
Chris Lattner3462ae32001-12-03 22:26:30 +00001551//---- ConstantStruct::get() implementation...
Chris Lattner49d855c2001-09-07 16:46:31 +00001552//
Chris Lattnerb50d1352003-10-05 00:17:43 +00001553
Chris Lattner189d19f2003-11-21 20:23:48 +00001554namespace llvm {
1555 template<>
1556 struct ConvertConstantType<ConstantStruct, StructType> {
1557 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1558 // Make everyone now use a constant of the new type...
1559 std::vector<Constant*> C;
1560 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1561 C.push_back(cast<Constant>(OldC->getOperand(i)));
1562 Constant *New = ConstantStruct::get(NewTy, C);
1563 assert(New != OldC && "Didn't replace constant??");
Misha Brukmanb1c93172005-04-21 23:48:37 +00001564
Chris Lattner189d19f2003-11-21 20:23:48 +00001565 OldC->uncheckedReplaceAllUsesWith(New);
1566 OldC->destroyConstant(); // This constant is now dead, destroy it.
1567 }
1568 };
1569}
Chris Lattnerb50d1352003-10-05 00:17:43 +00001570
Chris Lattner8760ec72005-10-04 01:17:50 +00001571typedef ValueMap<std::vector<Constant*>, StructType,
Chris Lattner935aa922005-10-04 17:48:46 +00001572 ConstantStruct, true /*largekey*/> StructConstantsTy;
Chris Lattner69edc982006-09-28 00:35:06 +00001573static ManagedStatic<StructConstantsTy> StructConstants;
Chris Lattner49d855c2001-09-07 16:46:31 +00001574
Chris Lattner3e650af2004-08-04 04:48:01 +00001575static std::vector<Constant*> getValType(ConstantStruct *CS) {
1576 std::vector<Constant*> Elements;
1577 Elements.reserve(CS->getNumOperands());
1578 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1579 Elements.push_back(cast<Constant>(CS->getOperand(i)));
1580 return Elements;
1581}
1582
Chris Lattner015e8212004-02-15 04:14:47 +00001583Constant *ConstantStruct::get(const StructType *Ty,
1584 const std::vector<Constant*> &V) {
Chris Lattner9fba3da2004-02-15 05:53:04 +00001585 // Create a ConstantAggregateZero value if all elements are zeros...
1586 for (unsigned i = 0, e = V.size(); i != e; ++i)
Owen Anderson61794042009-06-17 20:10:08 +00001587 if (!V[i]->isNullValue())
1588 // Implicitly locked.
1589 return StructConstants->getOrCreate(Ty, V);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001590
1591 return ConstantAggregateZero::get(Ty);
Chris Lattner49d855c2001-09-07 16:46:31 +00001592}
Chris Lattner883ad0b2001-10-03 15:39:36 +00001593
Andrew Lenharthdcb3c972006-12-08 18:06:16 +00001594Constant *ConstantStruct::get(const std::vector<Constant*> &V, bool packed) {
Chris Lattnerd6108ca2004-07-12 20:35:11 +00001595 std::vector<const Type*> StructEls;
1596 StructEls.reserve(V.size());
1597 for (unsigned i = 0, e = V.size(); i != e; ++i)
1598 StructEls.push_back(V[i]->getType());
Andrew Lenharthdcb3c972006-12-08 18:06:16 +00001599 return get(StructType::get(StructEls, packed), V);
Chris Lattnerd6108ca2004-07-12 20:35:11 +00001600}
1601
Chris Lattnerd7a73302001-10-13 06:57:33 +00001602// destroyConstant - Remove the constant from the constant table...
Chris Lattner883ad0b2001-10-03 15:39:36 +00001603//
Chris Lattner3462ae32001-12-03 22:26:30 +00001604void ConstantStruct::destroyConstant() {
Owen Anderson59ba8142009-06-19 18:34:09 +00001605 // Implicitly locked.
Chris Lattner69edc982006-09-28 00:35:06 +00001606 StructConstants->remove(this);
Chris Lattnerd7a73302001-10-13 06:57:33 +00001607 destroyConstantImpl();
1608}
Chris Lattner883ad0b2001-10-03 15:39:36 +00001609
Reid Spencerd84d35b2007-02-15 02:26:10 +00001610//---- ConstantVector::get() implementation...
Brian Gaeke02209042004-08-20 06:00:58 +00001611//
1612namespace llvm {
1613 template<>
Reid Spencerd84d35b2007-02-15 02:26:10 +00001614 struct ConvertConstantType<ConstantVector, VectorType> {
1615 static void convert(ConstantVector *OldC, const VectorType *NewTy) {
Brian Gaeke02209042004-08-20 06:00:58 +00001616 // Make everyone now use a constant of the new type...
1617 std::vector<Constant*> C;
1618 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1619 C.push_back(cast<Constant>(OldC->getOperand(i)));
Reid Spencerd84d35b2007-02-15 02:26:10 +00001620 Constant *New = ConstantVector::get(NewTy, C);
Brian Gaeke02209042004-08-20 06:00:58 +00001621 assert(New != OldC && "Didn't replace constant??");
1622 OldC->uncheckedReplaceAllUsesWith(New);
1623 OldC->destroyConstant(); // This constant is now dead, destroy it.
1624 }
1625 };
1626}
1627
Reid Spencerd84d35b2007-02-15 02:26:10 +00001628static std::vector<Constant*> getValType(ConstantVector *CP) {
Brian Gaeke02209042004-08-20 06:00:58 +00001629 std::vector<Constant*> Elements;
1630 Elements.reserve(CP->getNumOperands());
1631 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1632 Elements.push_back(CP->getOperand(i));
1633 return Elements;
1634}
1635
Reid Spencerd84d35b2007-02-15 02:26:10 +00001636static ManagedStatic<ValueMap<std::vector<Constant*>, VectorType,
Reid Spencer09575ba2007-02-15 03:39:18 +00001637 ConstantVector> > VectorConstants;
Brian Gaeke02209042004-08-20 06:00:58 +00001638
Reid Spencerd84d35b2007-02-15 02:26:10 +00001639Constant *ConstantVector::get(const VectorType *Ty,
Brian Gaeke02209042004-08-20 06:00:58 +00001640 const std::vector<Constant*> &V) {
Chris Lattnerd977c072008-07-10 00:44:03 +00001641 assert(!V.empty() && "Vectors can't be empty");
1642 // If this is an all-undef or alll-zero vector, return a
1643 // ConstantAggregateZero or UndefValue.
1644 Constant *C = V[0];
1645 bool isZero = C->isNullValue();
1646 bool isUndef = isa<UndefValue>(C);
1647
1648 if (isZero || isUndef) {
Brian Gaeke02209042004-08-20 06:00:58 +00001649 for (unsigned i = 1, e = V.size(); i != e; ++i)
Chris Lattnerd977c072008-07-10 00:44:03 +00001650 if (V[i] != C) {
1651 isZero = isUndef = false;
1652 break;
1653 }
Brian Gaeke02209042004-08-20 06:00:58 +00001654 }
Chris Lattnerd977c072008-07-10 00:44:03 +00001655
1656 if (isZero)
1657 return ConstantAggregateZero::get(Ty);
1658 if (isUndef)
1659 return UndefValue::get(Ty);
Owen Anderson61794042009-06-17 20:10:08 +00001660
1661 // Implicitly locked.
1662 return VectorConstants->getOrCreate(Ty, V);
Brian Gaeke02209042004-08-20 06:00:58 +00001663}
1664
Reid Spencerd84d35b2007-02-15 02:26:10 +00001665Constant *ConstantVector::get(const std::vector<Constant*> &V) {
Brian Gaeke02209042004-08-20 06:00:58 +00001666 assert(!V.empty() && "Cannot infer type if V is empty");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001667 return get(VectorType::get(V.front()->getType(),V.size()), V);
Brian Gaeke02209042004-08-20 06:00:58 +00001668}
1669
1670// destroyConstant - Remove the constant from the constant table...
1671//
Reid Spencerd84d35b2007-02-15 02:26:10 +00001672void ConstantVector::destroyConstant() {
Owen Anderson59ba8142009-06-19 18:34:09 +00001673 // Implicitly locked.
Owen Andersond830eb82009-06-18 19:10:19 +00001674 VectorConstants->remove(this);
Brian Gaeke02209042004-08-20 06:00:58 +00001675 destroyConstantImpl();
1676}
1677
Dan Gohman30978072007-05-24 14:36:04 +00001678/// This function will return true iff every element in this vector constant
Jim Laskeyf0478822007-01-12 22:39:14 +00001679/// is set to all ones.
1680/// @returns true iff this constant's emements are all set to all ones.
1681/// @brief Determine if the value is all ones.
Reid Spencerd84d35b2007-02-15 02:26:10 +00001682bool ConstantVector::isAllOnesValue() const {
Jim Laskeyf0478822007-01-12 22:39:14 +00001683 // Check out first element.
1684 const Constant *Elt = getOperand(0);
1685 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1686 if (!CI || !CI->isAllOnesValue()) return false;
1687 // Then make sure all remaining elements point to the same value.
1688 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1689 if (getOperand(I) != Elt) return false;
1690 }
1691 return true;
1692}
1693
Dan Gohman07159202007-10-17 17:51:30 +00001694/// getSplatValue - If this is a splat constant, where all of the
1695/// elements have the same value, return that value. Otherwise return null.
1696Constant *ConstantVector::getSplatValue() {
1697 // Check out first element.
1698 Constant *Elt = getOperand(0);
1699 // Then make sure all remaining elements point to the same value.
1700 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1701 if (getOperand(I) != Elt) return 0;
1702 return Elt;
1703}
1704
Chris Lattner3462ae32001-12-03 22:26:30 +00001705//---- ConstantPointerNull::get() implementation...
Chris Lattnerd7a73302001-10-13 06:57:33 +00001706//
Chris Lattner98fa07b2003-05-23 20:03:32 +00001707
Chris Lattner189d19f2003-11-21 20:23:48 +00001708namespace llvm {
1709 // ConstantPointerNull does not take extra "value" argument...
1710 template<class ValType>
1711 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1712 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1713 return new ConstantPointerNull(Ty);
1714 }
1715 };
Chris Lattner98fa07b2003-05-23 20:03:32 +00001716
Chris Lattner189d19f2003-11-21 20:23:48 +00001717 template<>
1718 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1719 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1720 // Make everyone now use a constant of the new type...
1721 Constant *New = ConstantPointerNull::get(NewTy);
1722 assert(New != OldC && "Didn't replace constant??");
1723 OldC->uncheckedReplaceAllUsesWith(New);
1724 OldC->destroyConstant(); // This constant is now dead, destroy it.
1725 }
1726 };
1727}
Chris Lattnerb50d1352003-10-05 00:17:43 +00001728
Chris Lattner69edc982006-09-28 00:35:06 +00001729static ManagedStatic<ValueMap<char, PointerType,
1730 ConstantPointerNull> > NullPtrConstants;
Chris Lattnerd7a73302001-10-13 06:57:33 +00001731
Chris Lattner3e650af2004-08-04 04:48:01 +00001732static char getValType(ConstantPointerNull *) {
1733 return 0;
1734}
1735
1736
Chris Lattner3462ae32001-12-03 22:26:30 +00001737ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
Owen Anderson61794042009-06-17 20:10:08 +00001738 // Implicitly locked.
1739 return NullPtrConstants->getOrCreate(Ty, 0);
Chris Lattner883ad0b2001-10-03 15:39:36 +00001740}
1741
Chris Lattner0c6e0b92002-08-18 00:40:04 +00001742// destroyConstant - Remove the constant from the constant table...
1743//
1744void ConstantPointerNull::destroyConstant() {
Owen Anderson59ba8142009-06-19 18:34:09 +00001745 // Implicitly locked.
Owen Andersond830eb82009-06-18 19:10:19 +00001746 NullPtrConstants->remove(this);
Chris Lattner0c6e0b92002-08-18 00:40:04 +00001747 destroyConstantImpl();
1748}
1749
1750
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001751//---- UndefValue::get() implementation...
1752//
1753
1754namespace llvm {
1755 // UndefValue does not take extra "value" argument...
1756 template<class ValType>
1757 struct ConstantCreator<UndefValue, Type, ValType> {
1758 static UndefValue *create(const Type *Ty, const ValType &V) {
1759 return new UndefValue(Ty);
1760 }
1761 };
1762
1763 template<>
1764 struct ConvertConstantType<UndefValue, Type> {
1765 static void convert(UndefValue *OldC, const Type *NewTy) {
1766 // Make everyone now use a constant of the new type.
1767 Constant *New = UndefValue::get(NewTy);
1768 assert(New != OldC && "Didn't replace constant??");
1769 OldC->uncheckedReplaceAllUsesWith(New);
1770 OldC->destroyConstant(); // This constant is now dead, destroy it.
1771 }
1772 };
1773}
1774
Chris Lattner69edc982006-09-28 00:35:06 +00001775static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001776
1777static char getValType(UndefValue *) {
1778 return 0;
1779}
1780
1781
1782UndefValue *UndefValue::get(const Type *Ty) {
Owen Anderson61794042009-06-17 20:10:08 +00001783 // Implicitly locked.
1784 return UndefValueConstants->getOrCreate(Ty, 0);
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001785}
1786
1787// destroyConstant - Remove the constant from the constant table.
1788//
1789void UndefValue::destroyConstant() {
Owen Anderson61794042009-06-17 20:10:08 +00001790 // Implicitly locked.
Chris Lattner69edc982006-09-28 00:35:06 +00001791 UndefValueConstants->remove(this);
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001792 destroyConstantImpl();
1793}
1794
Nick Lewycky49f89192009-04-04 07:22:01 +00001795//---- MDString::get() implementation
1796//
1797
1798MDString::MDString(const char *begin, const char *end)
Nick Lewyckyadbc2842009-05-30 05:06:04 +00001799 : Constant(Type::MetadataTy, MDStringVal, 0, 0),
Nick Lewycky49f89192009-04-04 07:22:01 +00001800 StrBegin(begin), StrEnd(end) {}
1801
1802static ManagedStatic<StringMap<MDString*> > MDStringCache;
1803
1804MDString *MDString::get(const char *StrBegin, const char *StrEnd) {
Owen Andersond830eb82009-06-18 19:10:19 +00001805 sys::SmartScopedWriter<true> Writer(&*ConstantsLock);
1806 StringMapEntry<MDString *> &Entry = MDStringCache->GetOrCreateValue(
1807 StrBegin, StrEnd);
1808 MDString *&S = Entry.getValue();
1809 if (!S) S = new MDString(Entry.getKeyData(),
1810 Entry.getKeyData() + Entry.getKeyLength());
Owen Anderson65c5cd72009-06-17 20:34:43 +00001811
Owen Andersond830eb82009-06-18 19:10:19 +00001812 return S;
Nick Lewycky49f89192009-04-04 07:22:01 +00001813}
1814
1815void MDString::destroyConstant() {
Owen Andersond830eb82009-06-18 19:10:19 +00001816 sys::SmartScopedWriter<true> Writer(&*ConstantsLock);
1817 MDStringCache->erase(MDStringCache->find(StrBegin, StrEnd));
Nick Lewycky49f89192009-04-04 07:22:01 +00001818 destroyConstantImpl();
1819}
1820
1821//---- MDNode::get() implementation
1822//
1823
1824static ManagedStatic<FoldingSet<MDNode> > MDNodeSet;
1825
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00001826MDNode::MDNode(Value*const* Vals, unsigned NumVals)
Nick Lewyckyadbc2842009-05-30 05:06:04 +00001827 : Constant(Type::MetadataTy, MDNodeVal, 0, 0) {
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00001828 for (unsigned i = 0; i != NumVals; ++i)
1829 Node.push_back(ElementVH(Vals[i], this));
Nick Lewycky49f89192009-04-04 07:22:01 +00001830}
1831
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00001832void MDNode::Profile(FoldingSetNodeID &ID) const {
1833 for (const_elem_iterator I = elem_begin(), E = elem_end(); I != E; ++I)
Nick Lewycky49f89192009-04-04 07:22:01 +00001834 ID.AddPointer(*I);
1835}
1836
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00001837MDNode *MDNode::get(Value*const* Vals, unsigned NumVals) {
Nick Lewycky49f89192009-04-04 07:22:01 +00001838 FoldingSetNodeID ID;
1839 for (unsigned i = 0; i != NumVals; ++i)
1840 ID.AddPointer(Vals[i]);
1841
Owen Andersond830eb82009-06-18 19:10:19 +00001842 ConstantsLock->reader_acquire();
1843 void *InsertPoint;
1844 MDNode *N = MDNodeSet->FindNodeOrInsertPos(ID, InsertPoint);
1845 ConstantsLock->reader_release();
1846
1847 if (!N) {
1848 sys::SmartScopedWriter<true> Writer(&*ConstantsLock);
1849 N = MDNodeSet->FindNodeOrInsertPos(ID, InsertPoint);
Owen Anderson2d7231d2009-06-17 18:40:29 +00001850 if (!N) {
Owen Andersond830eb82009-06-18 19:10:19 +00001851 // InsertPoint will have been set by the FindNodeOrInsertPos call.
1852 N = new(0) MDNode(Vals, NumVals);
1853 MDNodeSet->InsertNode(N, InsertPoint);
Owen Anderson2d7231d2009-06-17 18:40:29 +00001854 }
Owen Anderson2d7231d2009-06-17 18:40:29 +00001855 }
Owen Andersond830eb82009-06-18 19:10:19 +00001856 return N;
Nick Lewycky49f89192009-04-04 07:22:01 +00001857}
1858
1859void MDNode::destroyConstant() {
Owen Andersond830eb82009-06-18 19:10:19 +00001860 sys::SmartScopedWriter<true> Writer(&*ConstantsLock);
1861 MDNodeSet->RemoveNode(this);
Owen Anderson65c5cd72009-06-17 20:34:43 +00001862
Nick Lewycky49f89192009-04-04 07:22:01 +00001863 destroyConstantImpl();
1864}
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001865
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001866//---- ConstantExpr::get() implementations...
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001867//
Reid Spencer8d9336d2006-12-31 05:26:44 +00001868
Dan Gohmand78c4002008-05-13 00:00:25 +00001869namespace {
1870
Reid Spenceree3c9912006-12-04 05:19:50 +00001871struct ExprMapKeyType {
Dan Gohman1ecaf452008-05-31 00:58:22 +00001872 typedef SmallVector<unsigned, 4> IndexList;
1873
1874 ExprMapKeyType(unsigned opc,
1875 const std::vector<Constant*> &ops,
1876 unsigned short pred = 0,
1877 const IndexList &inds = IndexList())
1878 : opcode(opc), predicate(pred), operands(ops), indices(inds) {}
Reid Spencerdba6aa42006-12-04 18:38:05 +00001879 uint16_t opcode;
1880 uint16_t predicate;
Reid Spenceree3c9912006-12-04 05:19:50 +00001881 std::vector<Constant*> operands;
Dan Gohman1ecaf452008-05-31 00:58:22 +00001882 IndexList indices;
Reid Spenceree3c9912006-12-04 05:19:50 +00001883 bool operator==(const ExprMapKeyType& that) const {
1884 return this->opcode == that.opcode &&
1885 this->predicate == that.predicate &&
Bill Wendling97f7de82008-10-26 00:19:56 +00001886 this->operands == that.operands &&
Dan Gohman1ecaf452008-05-31 00:58:22 +00001887 this->indices == that.indices;
Reid Spenceree3c9912006-12-04 05:19:50 +00001888 }
1889 bool operator<(const ExprMapKeyType & that) const {
1890 return this->opcode < that.opcode ||
1891 (this->opcode == that.opcode && this->predicate < that.predicate) ||
1892 (this->opcode == that.opcode && this->predicate == that.predicate &&
Dan Gohman1ecaf452008-05-31 00:58:22 +00001893 this->operands < that.operands) ||
1894 (this->opcode == that.opcode && this->predicate == that.predicate &&
1895 this->operands == that.operands && this->indices < that.indices);
Reid Spenceree3c9912006-12-04 05:19:50 +00001896 }
1897
1898 bool operator!=(const ExprMapKeyType& that) const {
1899 return !(*this == that);
1900 }
1901};
Chris Lattner98fa07b2003-05-23 20:03:32 +00001902
Dan Gohmand78c4002008-05-13 00:00:25 +00001903}
1904
Chris Lattner189d19f2003-11-21 20:23:48 +00001905namespace llvm {
1906 template<>
1907 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
Reid Spencer10fbf0e2006-12-03 05:48:19 +00001908 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1909 unsigned short pred = 0) {
Reid Spenceree3c9912006-12-04 05:19:50 +00001910 if (Instruction::isCast(V.opcode))
1911 return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1912 if ((V.opcode >= Instruction::BinaryOpsBegin &&
Reid Spencer2341c222007-02-02 02:16:23 +00001913 V.opcode < Instruction::BinaryOpsEnd))
Reid Spenceree3c9912006-12-04 05:19:50 +00001914 return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1915 if (V.opcode == Instruction::Select)
1916 return new SelectConstantExpr(V.operands[0], V.operands[1],
1917 V.operands[2]);
1918 if (V.opcode == Instruction::ExtractElement)
1919 return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1920 if (V.opcode == Instruction::InsertElement)
1921 return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1922 V.operands[2]);
1923 if (V.opcode == Instruction::ShuffleVector)
1924 return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1925 V.operands[2]);
Dan Gohman1ecaf452008-05-31 00:58:22 +00001926 if (V.opcode == Instruction::InsertValue)
1927 return new InsertValueConstantExpr(V.operands[0], V.operands[1],
1928 V.indices, Ty);
1929 if (V.opcode == Instruction::ExtractValue)
1930 return new ExtractValueConstantExpr(V.operands[0], V.indices, Ty);
Reid Spenceree3c9912006-12-04 05:19:50 +00001931 if (V.opcode == Instruction::GetElementPtr) {
1932 std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
Gabor Greife9ecc682008-04-06 20:25:17 +00001933 return GetElementPtrConstantExpr::Create(V.operands[0], IdxList, Ty);
Reid Spenceree3c9912006-12-04 05:19:50 +00001934 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001935
Reid Spenceree3c9912006-12-04 05:19:50 +00001936 // The compare instructions are weird. We have to encode the predicate
1937 // value and it is combined with the instruction opcode by multiplying
1938 // the opcode by one hundred. We must decode this to get the predicate.
1939 if (V.opcode == Instruction::ICmp)
Nate Begemand2195702008-05-12 19:01:56 +00001940 return new CompareConstantExpr(Ty, Instruction::ICmp, V.predicate,
Reid Spenceree3c9912006-12-04 05:19:50 +00001941 V.operands[0], V.operands[1]);
1942 if (V.opcode == Instruction::FCmp)
Nate Begemand2195702008-05-12 19:01:56 +00001943 return new CompareConstantExpr(Ty, Instruction::FCmp, V.predicate,
1944 V.operands[0], V.operands[1]);
1945 if (V.opcode == Instruction::VICmp)
1946 return new CompareConstantExpr(Ty, Instruction::VICmp, V.predicate,
1947 V.operands[0], V.operands[1]);
1948 if (V.opcode == Instruction::VFCmp)
1949 return new CompareConstantExpr(Ty, Instruction::VFCmp, V.predicate,
Reid Spenceree3c9912006-12-04 05:19:50 +00001950 V.operands[0], V.operands[1]);
1951 assert(0 && "Invalid ConstantExpr!");
Jeff Cohen9f469632006-12-15 21:47:01 +00001952 return 0;
Chris Lattnerb50d1352003-10-05 00:17:43 +00001953 }
Chris Lattner189d19f2003-11-21 20:23:48 +00001954 };
Chris Lattnerb50d1352003-10-05 00:17:43 +00001955
Chris Lattner189d19f2003-11-21 20:23:48 +00001956 template<>
1957 struct ConvertConstantType<ConstantExpr, Type> {
1958 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1959 Constant *New;
1960 switch (OldC->getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001961 case Instruction::Trunc:
1962 case Instruction::ZExt:
1963 case Instruction::SExt:
1964 case Instruction::FPTrunc:
1965 case Instruction::FPExt:
1966 case Instruction::UIToFP:
1967 case Instruction::SIToFP:
1968 case Instruction::FPToUI:
1969 case Instruction::FPToSI:
1970 case Instruction::PtrToInt:
1971 case Instruction::IntToPtr:
1972 case Instruction::BitCast:
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001973 New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0),
1974 NewTy);
Chris Lattner189d19f2003-11-21 20:23:48 +00001975 break;
Chris Lattner6e415c02004-03-12 05:54:04 +00001976 case Instruction::Select:
1977 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1978 OldC->getOperand(1),
1979 OldC->getOperand(2));
1980 break;
Chris Lattner189d19f2003-11-21 20:23:48 +00001981 default:
1982 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
Reid Spencer7eb55b32006-11-02 01:53:59 +00001983 OldC->getOpcode() < Instruction::BinaryOpsEnd);
Chris Lattner189d19f2003-11-21 20:23:48 +00001984 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1985 OldC->getOperand(1));
1986 break;
1987 case Instruction::GetElementPtr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00001988 // Make everyone now use a constant of the new type...
Chris Lattner13128ab2004-10-11 22:52:25 +00001989 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
Chris Lattner302116a2007-01-31 04:40:28 +00001990 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0),
1991 &Idx[0], Idx.size());
Chris Lattner189d19f2003-11-21 20:23:48 +00001992 break;
1993 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001994
Chris Lattner189d19f2003-11-21 20:23:48 +00001995 assert(New != OldC && "Didn't replace constant??");
1996 OldC->uncheckedReplaceAllUsesWith(New);
1997 OldC->destroyConstant(); // This constant is now dead, destroy it.
1998 }
1999 };
2000} // end namespace llvm
Chris Lattnerb50d1352003-10-05 00:17:43 +00002001
2002
Chris Lattner3e650af2004-08-04 04:48:01 +00002003static ExprMapKeyType getValType(ConstantExpr *CE) {
2004 std::vector<Constant*> Operands;
2005 Operands.reserve(CE->getNumOperands());
2006 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
2007 Operands.push_back(cast<Constant>(CE->getOperand(i)));
Reid Spenceree3c9912006-12-04 05:19:50 +00002008 return ExprMapKeyType(CE->getOpcode(), Operands,
Dan Gohman1ecaf452008-05-31 00:58:22 +00002009 CE->isCompare() ? CE->getPredicate() : 0,
2010 CE->hasIndices() ?
2011 CE->getIndices() : SmallVector<unsigned, 4>());
Chris Lattner3e650af2004-08-04 04:48:01 +00002012}
2013
Chris Lattner69edc982006-09-28 00:35:06 +00002014static ManagedStatic<ValueMap<ExprMapKeyType, Type,
2015 ConstantExpr> > ExprConstants;
Vikram S. Adve4c485332002-07-15 18:19:33 +00002016
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002017/// This is a utility function to handle folding of casts and lookup of the
Duncan Sands7d6c8ae2008-03-30 19:38:55 +00002018/// cast in the ExprConstants map. It is used by the various get* methods below.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002019static inline Constant *getFoldedCast(
2020 Instruction::CastOps opc, Constant *C, const Type *Ty) {
Chris Lattner815ae2b2003-10-07 22:19:19 +00002021 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002022 // Fold a few common cases
2023 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
2024 return FC;
Chris Lattneracdbe712003-04-17 19:24:48 +00002025
Vikram S. Adve4c485332002-07-15 18:19:33 +00002026 // Look up the constant in the table first to ensure uniqueness
Chris Lattner2b383d2e2003-05-13 21:37:02 +00002027 std::vector<Constant*> argVec(1, C);
Reid Spenceree3c9912006-12-04 05:19:50 +00002028 ExprMapKeyType Key(opc, argVec);
Owen Anderson2d7231d2009-06-17 18:40:29 +00002029
Owen Anderson61794042009-06-17 20:10:08 +00002030 // Implicitly locked.
2031 return ExprConstants->getOrCreate(Ty, Key);
Vikram S. Adve4e537b22002-07-14 23:13:17 +00002032}
Reid Spencerf37dc652006-12-05 19:14:13 +00002033
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002034Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
2035 Instruction::CastOps opc = Instruction::CastOps(oc);
2036 assert(Instruction::isCast(opc) && "opcode out of range");
2037 assert(C && Ty && "Null arguments to getCast");
2038 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
2039
2040 switch (opc) {
2041 default:
2042 assert(0 && "Invalid cast opcode");
2043 break;
2044 case Instruction::Trunc: return getTrunc(C, Ty);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00002045 case Instruction::ZExt: return getZExt(C, Ty);
2046 case Instruction::SExt: return getSExt(C, Ty);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002047 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
2048 case Instruction::FPExt: return getFPExtend(C, Ty);
2049 case Instruction::UIToFP: return getUIToFP(C, Ty);
2050 case Instruction::SIToFP: return getSIToFP(C, Ty);
2051 case Instruction::FPToUI: return getFPToUI(C, Ty);
2052 case Instruction::FPToSI: return getFPToSI(C, Ty);
2053 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
2054 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
2055 case Instruction::BitCast: return getBitCast(C, Ty);
Chris Lattner1ece6f82005-01-01 15:59:57 +00002056 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002057 return 0;
Reid Spencerf37dc652006-12-05 19:14:13 +00002058}
2059
Reid Spencer5c140882006-12-04 20:17:56 +00002060Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00002061 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
Reid Spencer5c140882006-12-04 20:17:56 +00002062 return getCast(Instruction::BitCast, C, Ty);
2063 return getCast(Instruction::ZExt, C, Ty);
2064}
2065
2066Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00002067 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
Reid Spencer5c140882006-12-04 20:17:56 +00002068 return getCast(Instruction::BitCast, C, Ty);
2069 return getCast(Instruction::SExt, C, Ty);
2070}
2071
2072Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00002073 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
Reid Spencer5c140882006-12-04 20:17:56 +00002074 return getCast(Instruction::BitCast, C, Ty);
2075 return getCast(Instruction::Trunc, C, Ty);
2076}
2077
Reid Spencerbc245a02006-12-05 03:25:26 +00002078Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
2079 assert(isa<PointerType>(S->getType()) && "Invalid cast");
Chris Lattner03c49532007-01-15 02:27:26 +00002080 assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
Reid Spencerbc245a02006-12-05 03:25:26 +00002081
Chris Lattner03c49532007-01-15 02:27:26 +00002082 if (Ty->isInteger())
Reid Spencerbc245a02006-12-05 03:25:26 +00002083 return getCast(Instruction::PtrToInt, S, Ty);
2084 return getCast(Instruction::BitCast, S, Ty);
2085}
2086
Reid Spencer56521c42006-12-12 00:51:07 +00002087Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
2088 bool isSigned) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00002089 assert(C->getType()->isIntOrIntVector() &&
2090 Ty->isIntOrIntVector() && "Invalid cast");
2091 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2092 unsigned DstBits = Ty->getScalarSizeInBits();
Reid Spencer56521c42006-12-12 00:51:07 +00002093 Instruction::CastOps opcode =
2094 (SrcBits == DstBits ? Instruction::BitCast :
2095 (SrcBits > DstBits ? Instruction::Trunc :
2096 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2097 return getCast(opcode, C, Ty);
2098}
2099
2100Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00002101 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
Reid Spencer56521c42006-12-12 00:51:07 +00002102 "Invalid cast");
Dan Gohman7ccc52f2009-06-15 22:12:54 +00002103 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2104 unsigned DstBits = Ty->getScalarSizeInBits();
Reid Spencerca104e82006-12-12 05:38:50 +00002105 if (SrcBits == DstBits)
2106 return C; // Avoid a useless cast
Reid Spencer56521c42006-12-12 00:51:07 +00002107 Instruction::CastOps opcode =
Reid Spencerca104e82006-12-12 05:38:50 +00002108 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
Reid Spencer56521c42006-12-12 00:51:07 +00002109 return getCast(opcode, C, Ty);
2110}
2111
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002112Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00002113#ifndef NDEBUG
2114 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2115 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2116#endif
2117 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2118 assert(C->getType()->isIntOrIntVector() && "Trunc operand must be integer");
2119 assert(Ty->isIntOrIntVector() && "Trunc produces only integral");
2120 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002121 "SrcTy must be larger than DestTy for Trunc!");
2122
2123 return getFoldedCast(Instruction::Trunc, C, Ty);
2124}
2125
Reid Spencerbb65ebf2006-12-12 23:36:14 +00002126Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00002127#ifndef NDEBUG
2128 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2129 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2130#endif
2131 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2132 assert(C->getType()->isIntOrIntVector() && "SExt operand must be integral");
2133 assert(Ty->isIntOrIntVector() && "SExt produces only integer");
2134 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002135 "SrcTy must be smaller than DestTy for SExt!");
2136
2137 return getFoldedCast(Instruction::SExt, C, Ty);
Chris Lattnerdd284742004-04-04 23:20:30 +00002138}
2139
Reid Spencerbb65ebf2006-12-12 23:36:14 +00002140Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00002141#ifndef NDEBUG
2142 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2143 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2144#endif
2145 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2146 assert(C->getType()->isIntOrIntVector() && "ZEXt operand must be integral");
2147 assert(Ty->isIntOrIntVector() && "ZExt produces only integer");
2148 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002149 "SrcTy must be smaller than DestTy for ZExt!");
2150
2151 return getFoldedCast(Instruction::ZExt, C, Ty);
2152}
2153
2154Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00002155#ifndef NDEBUG
2156 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2157 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2158#endif
2159 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2160 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
2161 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002162 "This is an illegal floating point truncation!");
2163 return getFoldedCast(Instruction::FPTrunc, C, Ty);
2164}
2165
2166Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00002167#ifndef NDEBUG
2168 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2169 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2170#endif
2171 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2172 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
2173 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002174 "This is an illegal floating point extension!");
2175 return getFoldedCast(Instruction::FPExt, C, Ty);
2176}
2177
2178Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
Devang Pateld26344d2008-11-03 23:20:04 +00002179#ifndef NDEBUG
Nate Begemand4d45c22007-11-17 03:58:34 +00002180 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2181 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Pateld26344d2008-11-03 23:20:04 +00002182#endif
Nate Begemand4d45c22007-11-17 03:58:34 +00002183 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2184 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
2185 "This is an illegal uint to floating point cast!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002186 return getFoldedCast(Instruction::UIToFP, C, Ty);
2187}
2188
2189Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
Devang Pateld26344d2008-11-03 23:20:04 +00002190#ifndef NDEBUG
Nate Begemand4d45c22007-11-17 03:58:34 +00002191 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2192 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Pateld26344d2008-11-03 23:20:04 +00002193#endif
Nate Begemand4d45c22007-11-17 03:58:34 +00002194 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2195 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002196 "This is an illegal sint to floating point cast!");
2197 return getFoldedCast(Instruction::SIToFP, C, Ty);
2198}
2199
2200Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
Devang Pateld26344d2008-11-03 23:20:04 +00002201#ifndef NDEBUG
Nate Begemand4d45c22007-11-17 03:58:34 +00002202 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2203 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Pateld26344d2008-11-03 23:20:04 +00002204#endif
Nate Begemand4d45c22007-11-17 03:58:34 +00002205 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2206 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
2207 "This is an illegal floating point to uint cast!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002208 return getFoldedCast(Instruction::FPToUI, C, Ty);
2209}
2210
2211Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
Devang Pateld26344d2008-11-03 23:20:04 +00002212#ifndef NDEBUG
Nate Begemand4d45c22007-11-17 03:58:34 +00002213 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2214 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Pateld26344d2008-11-03 23:20:04 +00002215#endif
Nate Begemand4d45c22007-11-17 03:58:34 +00002216 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2217 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
2218 "This is an illegal floating point to sint cast!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002219 return getFoldedCast(Instruction::FPToSI, C, Ty);
2220}
2221
2222Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
2223 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
Chris Lattner03c49532007-01-15 02:27:26 +00002224 assert(DstTy->isInteger() && "PtrToInt destination must be integral");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002225 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
2226}
2227
2228Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
Chris Lattner03c49532007-01-15 02:27:26 +00002229 assert(C->getType()->isInteger() && "IntToPtr source must be integral");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002230 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
2231 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
2232}
2233
2234Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
2235 // BitCast implies a no-op cast of type only. No bits change. However, you
2236 // can't cast pointers to anything but pointers.
Devang Pateld26344d2008-11-03 23:20:04 +00002237#ifndef NDEBUG
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002238 const Type *SrcTy = C->getType();
2239 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
Reid Spencer5c140882006-12-04 20:17:56 +00002240 "BitCast cannot cast pointer to non-pointer and vice versa");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002241
2242 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
2243 // or nonptr->ptr). For all the other types, the cast is okay if source and
2244 // destination bit widths are identical.
2245 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
2246 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
Devang Pateld26344d2008-11-03 23:20:04 +00002247#endif
Chris Lattnere4086012009-03-08 04:06:26 +00002248 assert(SrcBitSize == DstBitSize && "BitCast requires types of same width");
Chris Lattnercbeda872009-03-21 06:55:54 +00002249
2250 // It is common to ask for a bitcast of a value to its own type, handle this
2251 // speedily.
2252 if (C->getType() == DstTy) return C;
2253
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002254 return getFoldedCast(Instruction::BitCast, C, DstTy);
Chris Lattnerdd284742004-04-04 23:20:30 +00002255}
2256
Duncan Sandsd334aca2009-05-21 15:52:21 +00002257Constant *ConstantExpr::getAlignOf(const Type *Ty) {
2258 // alignof is implemented as: (i64) gep ({i8,Ty}*)null, 0, 1
2259 const Type *AligningTy = StructType::get(Type::Int8Ty, Ty, NULL);
2260 Constant *NullPtr = getNullValue(AligningTy->getPointerTo());
2261 Constant *Zero = ConstantInt::get(Type::Int32Ty, 0);
2262 Constant *One = ConstantInt::get(Type::Int32Ty, 1);
2263 Constant *Indices[2] = { Zero, One };
2264 Constant *GEP = getGetElementPtr(NullPtr, Indices, 2);
2265 return getCast(Instruction::PtrToInt, GEP, Type::Int32Ty);
2266}
2267
Alkis Evlogimenosda5de052004-10-24 01:41:10 +00002268Constant *ConstantExpr::getSizeOf(const Type *Ty) {
Gordon Henriksen7ce31762007-10-06 14:29:36 +00002269 // sizeof is implemented as: (i64) gep (Ty*)null, 1
Chris Lattnerb5d70302007-02-19 20:01:23 +00002270 Constant *GEPIdx = ConstantInt::get(Type::Int32Ty, 1);
2271 Constant *GEP =
Christopher Lambedf07882007-12-17 01:12:55 +00002272 getGetElementPtr(getNullValue(PointerType::getUnqual(Ty)), &GEPIdx, 1);
Chris Lattnerb5d70302007-02-19 20:01:23 +00002273 return getCast(Instruction::PtrToInt, GEP, Type::Int64Ty);
Alkis Evlogimenos9160d5f2005-03-19 11:40:31 +00002274}
2275
Chris Lattnerb50d1352003-10-05 00:17:43 +00002276Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
Reid Spencera009d0d2006-12-04 21:35:24 +00002277 Constant *C1, Constant *C2) {
Chris Lattner38a9bcd2003-05-21 17:49:25 +00002278 // Check the operands for consistency first
Reid Spencer7eb55b32006-11-02 01:53:59 +00002279 assert(Opcode >= Instruction::BinaryOpsBegin &&
2280 Opcode < Instruction::BinaryOpsEnd &&
Chris Lattner38a9bcd2003-05-21 17:49:25 +00002281 "Invalid opcode in binary constant expression");
2282 assert(C1->getType() == C2->getType() &&
2283 "Operand types in binary constant expression should match");
Chris Lattnerb50d1352003-10-05 00:17:43 +00002284
Reid Spencer542964f2007-01-11 18:21:29 +00002285 if (ReqTy == C1->getType() || ReqTy == Type::Int1Ty)
Chris Lattnerb50d1352003-10-05 00:17:43 +00002286 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
2287 return FC; // Fold a few common cases...
Chris Lattneracdbe712003-04-17 19:24:48 +00002288
Chris Lattner2b383d2e2003-05-13 21:37:02 +00002289 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
Reid Spencera009d0d2006-12-04 21:35:24 +00002290 ExprMapKeyType Key(Opcode, argVec);
Owen Anderson61794042009-06-17 20:10:08 +00002291
2292 // Implicitly locked.
2293 return ExprConstants->getOrCreate(ReqTy, Key);
Vikram S. Adve4e537b22002-07-14 23:13:17 +00002294}
2295
Reid Spencer266e42b2006-12-23 06:05:41 +00002296Constant *ConstantExpr::getCompareTy(unsigned short predicate,
Nate Begeman098cc6f2008-07-25 17:56:27 +00002297 Constant *C1, Constant *C2) {
2298 bool isVectorType = C1->getType()->getTypeID() == Type::VectorTyID;
Reid Spencer266e42b2006-12-23 06:05:41 +00002299 switch (predicate) {
2300 default: assert(0 && "Invalid CmpInst predicate");
Nate Begemanc96e2e42008-07-25 17:35:37 +00002301 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
2302 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
2303 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
2304 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
2305 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
2306 case CmpInst::FCMP_TRUE:
Nate Begeman098cc6f2008-07-25 17:56:27 +00002307 return isVectorType ? getVFCmp(predicate, C1, C2)
2308 : getFCmp(predicate, C1, C2);
Nate Begemanc96e2e42008-07-25 17:35:37 +00002309 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
2310 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
2311 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
2312 case CmpInst::ICMP_SLE:
Nate Begeman098cc6f2008-07-25 17:56:27 +00002313 return isVectorType ? getVICmp(predicate, C1, C2)
2314 : getICmp(predicate, C1, C2);
Reid Spencer266e42b2006-12-23 06:05:41 +00002315 }
Reid Spencera009d0d2006-12-04 21:35:24 +00002316}
2317
2318Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
Dan Gohmana5b96452009-06-04 22:49:04 +00002319 // API compatibility: Adjust integer opcodes to floating-point opcodes.
2320 if (C1->getType()->isFPOrFPVector()) {
2321 if (Opcode == Instruction::Add) Opcode = Instruction::FAdd;
2322 else if (Opcode == Instruction::Sub) Opcode = Instruction::FSub;
2323 else if (Opcode == Instruction::Mul) Opcode = Instruction::FMul;
2324 }
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00002325#ifndef NDEBUG
2326 switch (Opcode) {
Dan Gohmana5b96452009-06-04 22:49:04 +00002327 case Instruction::Add:
Reid Spencer7eb55b32006-11-02 01:53:59 +00002328 case Instruction::Sub:
Dan Gohmana5b96452009-06-04 22:49:04 +00002329 case Instruction::Mul:
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00002330 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Dan Gohmana5b96452009-06-04 22:49:04 +00002331 assert(C1->getType()->isIntOrIntVector() &&
2332 "Tried to create an integer operation on a non-integer type!");
2333 break;
2334 case Instruction::FAdd:
2335 case Instruction::FSub:
2336 case Instruction::FMul:
2337 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2338 assert(C1->getType()->isFPOrFPVector() &&
2339 "Tried to create a floating-point operation on a "
2340 "non-floating-point type!");
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00002341 break;
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002342 case Instruction::UDiv:
2343 case Instruction::SDiv:
2344 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Dan Gohman7889f2b2009-06-15 22:25:12 +00002345 assert(C1->getType()->isIntOrIntVector() &&
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002346 "Tried to create an arithmetic operation on a non-arithmetic type!");
2347 break;
2348 case Instruction::FDiv:
2349 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Dan Gohman7889f2b2009-06-15 22:25:12 +00002350 assert(C1->getType()->isFPOrFPVector() &&
2351 "Tried to create an arithmetic operation on a non-arithmetic type!");
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002352 break;
Reid Spencer7eb55b32006-11-02 01:53:59 +00002353 case Instruction::URem:
2354 case Instruction::SRem:
2355 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Dan Gohman7889f2b2009-06-15 22:25:12 +00002356 assert(C1->getType()->isIntOrIntVector() &&
Reid Spencer7eb55b32006-11-02 01:53:59 +00002357 "Tried to create an arithmetic operation on a non-arithmetic type!");
2358 break;
2359 case Instruction::FRem:
2360 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Dan Gohman7889f2b2009-06-15 22:25:12 +00002361 assert(C1->getType()->isFPOrFPVector() &&
2362 "Tried to create an arithmetic operation on a non-arithmetic type!");
Reid Spencer7eb55b32006-11-02 01:53:59 +00002363 break;
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00002364 case Instruction::And:
2365 case Instruction::Or:
2366 case Instruction::Xor:
2367 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Dan Gohman7889f2b2009-06-15 22:25:12 +00002368 assert(C1->getType()->isIntOrIntVector() &&
Misha Brukman3852f652005-01-27 06:46:38 +00002369 "Tried to create a logical operation on a non-integral type!");
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00002370 break;
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00002371 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00002372 case Instruction::LShr:
2373 case Instruction::AShr:
Reid Spencer2341c222007-02-02 02:16:23 +00002374 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Dan Gohman79975d52009-03-14 17:09:17 +00002375 assert(C1->getType()->isIntOrIntVector() &&
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00002376 "Tried to create a shift operation on a non-integer type!");
2377 break;
2378 default:
2379 break;
2380 }
2381#endif
2382
Reid Spencera009d0d2006-12-04 21:35:24 +00002383 return getTy(C1->getType(), Opcode, C1, C2);
2384}
2385
Reid Spencer266e42b2006-12-23 06:05:41 +00002386Constant *ConstantExpr::getCompare(unsigned short pred,
Reid Spencera009d0d2006-12-04 21:35:24 +00002387 Constant *C1, Constant *C2) {
2388 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencer266e42b2006-12-23 06:05:41 +00002389 return getCompareTy(pred, C1, C2);
Chris Lattner29ca2c62004-08-04 18:50:09 +00002390}
2391
Chris Lattner6e415c02004-03-12 05:54:04 +00002392Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
2393 Constant *V1, Constant *V2) {
Chris Lattner41632132008-12-29 00:16:12 +00002394 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
Chris Lattner6e415c02004-03-12 05:54:04 +00002395
2396 if (ReqTy == V1->getType())
2397 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
2398 return SC; // Fold common cases
2399
2400 std::vector<Constant*> argVec(3, C);
2401 argVec[1] = V1;
2402 argVec[2] = V2;
Reid Spenceree3c9912006-12-04 05:19:50 +00002403 ExprMapKeyType Key(Instruction::Select, argVec);
Owen Anderson61794042009-06-17 20:10:08 +00002404
2405 // Implicitly locked.
2406 return ExprConstants->getOrCreate(ReqTy, Key);
Chris Lattner6e415c02004-03-12 05:54:04 +00002407}
2408
Chris Lattnerb50d1352003-10-05 00:17:43 +00002409Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
Chris Lattner302116a2007-01-31 04:40:28 +00002410 Value* const *Idxs,
2411 unsigned NumIdx) {
Dan Gohman12fce772008-05-15 19:50:34 +00002412 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs,
2413 Idxs+NumIdx) ==
2414 cast<PointerType>(ReqTy)->getElementType() &&
2415 "GEP indices invalid!");
Chris Lattner04b60fe2004-02-16 20:46:13 +00002416
Chris Lattner302116a2007-01-31 04:40:28 +00002417 if (Constant *FC = ConstantFoldGetElementPtr(C, (Constant**)Idxs, NumIdx))
Chris Lattneracdbe712003-04-17 19:24:48 +00002418 return FC; // Fold a few common cases...
Chris Lattner04b60fe2004-02-16 20:46:13 +00002419
Chris Lattnerb50d1352003-10-05 00:17:43 +00002420 assert(isa<PointerType>(C->getType()) &&
Chris Lattner98fa07b2003-05-23 20:03:32 +00002421 "Non-pointer type for constant GetElementPtr expression");
Vikram S. Adve4c485332002-07-15 18:19:33 +00002422 // Look up the constant in the table first to ensure uniqueness
Chris Lattner13128ab2004-10-11 22:52:25 +00002423 std::vector<Constant*> ArgVec;
Chris Lattner302116a2007-01-31 04:40:28 +00002424 ArgVec.reserve(NumIdx+1);
Chris Lattner13128ab2004-10-11 22:52:25 +00002425 ArgVec.push_back(C);
Chris Lattner302116a2007-01-31 04:40:28 +00002426 for (unsigned i = 0; i != NumIdx; ++i)
2427 ArgVec.push_back(cast<Constant>(Idxs[i]));
2428 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
Owen Anderson61794042009-06-17 20:10:08 +00002429
2430 // Implicitly locked.
2431 return ExprConstants->getOrCreate(ReqTy, Key);
Vikram S. Adve4c485332002-07-15 18:19:33 +00002432}
2433
Chris Lattner302116a2007-01-31 04:40:28 +00002434Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
2435 unsigned NumIdx) {
Chris Lattnerb50d1352003-10-05 00:17:43 +00002436 // Get the result type of the getelementptr!
Chris Lattner302116a2007-01-31 04:40:28 +00002437 const Type *Ty =
Dan Gohman12fce772008-05-15 19:50:34 +00002438 GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx);
Chris Lattnerb50d1352003-10-05 00:17:43 +00002439 assert(Ty && "GEP indices invalid!");
Christopher Lamb54dd24c2007-12-11 08:59:05 +00002440 unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
2441 return getGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx);
Chris Lattner13128ab2004-10-11 22:52:25 +00002442}
2443
Chris Lattner302116a2007-01-31 04:40:28 +00002444Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
2445 unsigned NumIdx) {
2446 return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
Chris Lattnerb50d1352003-10-05 00:17:43 +00002447}
2448
Chris Lattner302116a2007-01-31 04:40:28 +00002449
Reid Spenceree3c9912006-12-04 05:19:50 +00002450Constant *
2451ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2452 assert(LHS->getType() == RHS->getType());
2453 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
2454 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
2455
Reid Spencer266e42b2006-12-23 06:05:41 +00002456 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
Reid Spenceree3c9912006-12-04 05:19:50 +00002457 return FC; // Fold a few common cases...
2458
2459 // Look up the constant in the table first to ensure uniqueness
2460 std::vector<Constant*> ArgVec;
2461 ArgVec.push_back(LHS);
2462 ArgVec.push_back(RHS);
Reid Spencerb1537492006-12-24 18:42:29 +00002463 // Get the key type with both the opcode and predicate
Reid Spenceree3c9912006-12-04 05:19:50 +00002464 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
Owen Anderson61794042009-06-17 20:10:08 +00002465
2466 // Implicitly locked.
2467 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
Reid Spenceree3c9912006-12-04 05:19:50 +00002468}
2469
2470Constant *
2471ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2472 assert(LHS->getType() == RHS->getType());
2473 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
2474
Reid Spencer266e42b2006-12-23 06:05:41 +00002475 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
Reid Spenceree3c9912006-12-04 05:19:50 +00002476 return FC; // Fold a few common cases...
2477
2478 // Look up the constant in the table first to ensure uniqueness
2479 std::vector<Constant*> ArgVec;
2480 ArgVec.push_back(LHS);
2481 ArgVec.push_back(RHS);
Reid Spencerb1537492006-12-24 18:42:29 +00002482 // Get the key type with both the opcode and predicate
Reid Spenceree3c9912006-12-04 05:19:50 +00002483 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
Owen Anderson61794042009-06-17 20:10:08 +00002484
2485 // Implicitly locked.
2486 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
Reid Spenceree3c9912006-12-04 05:19:50 +00002487}
2488
Nate Begemand2195702008-05-12 19:01:56 +00002489Constant *
2490ConstantExpr::getVICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
Chris Lattnereab49262008-07-14 05:17:31 +00002491 assert(isa<VectorType>(LHS->getType()) && LHS->getType() == RHS->getType() &&
Nate Begemand2195702008-05-12 19:01:56 +00002492 "Tried to create vicmp operation on non-vector type!");
Nate Begemand2195702008-05-12 19:01:56 +00002493 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
2494 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid VICmp Predicate");
2495
Nate Begemanac7f3d92008-05-12 19:23:22 +00002496 const VectorType *VTy = cast<VectorType>(LHS->getType());
Nate Begemand2195702008-05-12 19:01:56 +00002497 const Type *EltTy = VTy->getElementType();
2498 unsigned NumElts = VTy->getNumElements();
2499
Chris Lattnereab49262008-07-14 05:17:31 +00002500 // See if we can fold the element-wise comparison of the LHS and RHS.
2501 SmallVector<Constant *, 16> LHSElts, RHSElts;
2502 LHS->getVectorElements(LHSElts);
2503 RHS->getVectorElements(RHSElts);
2504
2505 if (!LHSElts.empty() && !RHSElts.empty()) {
2506 SmallVector<Constant *, 16> Elts;
2507 for (unsigned i = 0; i != NumElts; ++i) {
2508 Constant *FC = ConstantFoldCompareInstruction(pred, LHSElts[i],
2509 RHSElts[i]);
2510 if (ConstantInt *FCI = dyn_cast_or_null<ConstantInt>(FC)) {
2511 if (FCI->getZExtValue())
2512 Elts.push_back(ConstantInt::getAllOnesValue(EltTy));
2513 else
2514 Elts.push_back(ConstantInt::get(EltTy, 0ULL));
2515 } else if (FC && isa<UndefValue>(FC)) {
2516 Elts.push_back(UndefValue::get(EltTy));
2517 } else {
2518 break;
2519 }
Nate Begemand2195702008-05-12 19:01:56 +00002520 }
Chris Lattnereab49262008-07-14 05:17:31 +00002521 if (Elts.size() == NumElts)
2522 return ConstantVector::get(&Elts[0], Elts.size());
Nate Begemand2195702008-05-12 19:01:56 +00002523 }
Nate Begemand2195702008-05-12 19:01:56 +00002524
2525 // Look up the constant in the table first to ensure uniqueness
2526 std::vector<Constant*> ArgVec;
2527 ArgVec.push_back(LHS);
2528 ArgVec.push_back(RHS);
2529 // Get the key type with both the opcode and predicate
2530 const ExprMapKeyType Key(Instruction::VICmp, ArgVec, pred);
Owen Anderson61794042009-06-17 20:10:08 +00002531
2532 // Implicitly locked.
2533 return ExprConstants->getOrCreate(LHS->getType(), Key);
Nate Begemand2195702008-05-12 19:01:56 +00002534}
2535
2536Constant *
2537ConstantExpr::getVFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2538 assert(isa<VectorType>(LHS->getType()) &&
2539 "Tried to create vfcmp operation on non-vector type!");
2540 assert(LHS->getType() == RHS->getType());
2541 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid VFCmp Predicate");
2542
2543 const VectorType *VTy = cast<VectorType>(LHS->getType());
2544 unsigned NumElts = VTy->getNumElements();
2545 const Type *EltTy = VTy->getElementType();
2546 const Type *REltTy = IntegerType::get(EltTy->getPrimitiveSizeInBits());
2547 const Type *ResultTy = VectorType::get(REltTy, NumElts);
2548
Chris Lattnereab49262008-07-14 05:17:31 +00002549 // See if we can fold the element-wise comparison of the LHS and RHS.
2550 SmallVector<Constant *, 16> LHSElts, RHSElts;
2551 LHS->getVectorElements(LHSElts);
2552 RHS->getVectorElements(RHSElts);
2553
2554 if (!LHSElts.empty() && !RHSElts.empty()) {
2555 SmallVector<Constant *, 16> Elts;
2556 for (unsigned i = 0; i != NumElts; ++i) {
2557 Constant *FC = ConstantFoldCompareInstruction(pred, LHSElts[i],
2558 RHSElts[i]);
2559 if (ConstantInt *FCI = dyn_cast_or_null<ConstantInt>(FC)) {
2560 if (FCI->getZExtValue())
2561 Elts.push_back(ConstantInt::getAllOnesValue(REltTy));
2562 else
2563 Elts.push_back(ConstantInt::get(REltTy, 0ULL));
2564 } else if (FC && isa<UndefValue>(FC)) {
2565 Elts.push_back(UndefValue::get(REltTy));
2566 } else {
2567 break;
2568 }
Nate Begemand2195702008-05-12 19:01:56 +00002569 }
Chris Lattnereab49262008-07-14 05:17:31 +00002570 if (Elts.size() == NumElts)
2571 return ConstantVector::get(&Elts[0], Elts.size());
Nate Begemand2195702008-05-12 19:01:56 +00002572 }
Nate Begemand2195702008-05-12 19:01:56 +00002573
2574 // Look up the constant in the table first to ensure uniqueness
2575 std::vector<Constant*> ArgVec;
2576 ArgVec.push_back(LHS);
2577 ArgVec.push_back(RHS);
2578 // Get the key type with both the opcode and predicate
2579 const ExprMapKeyType Key(Instruction::VFCmp, ArgVec, pred);
Owen Anderson61794042009-06-17 20:10:08 +00002580
2581 // Implicitly locked.
2582 return ExprConstants->getOrCreate(ResultTy, Key);
Nate Begemand2195702008-05-12 19:01:56 +00002583}
2584
Robert Bocchino23004482006-01-10 19:05:34 +00002585Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
2586 Constant *Idx) {
Robert Bocchinode7f1c92006-01-10 20:03:46 +00002587 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
2588 return FC; // Fold a few common cases...
Robert Bocchino23004482006-01-10 19:05:34 +00002589 // Look up the constant in the table first to ensure uniqueness
2590 std::vector<Constant*> ArgVec(1, Val);
2591 ArgVec.push_back(Idx);
Reid Spenceree3c9912006-12-04 05:19:50 +00002592 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
Owen Anderson61794042009-06-17 20:10:08 +00002593
2594 // Implicitly locked.
2595 return ExprConstants->getOrCreate(ReqTy, Key);
Robert Bocchino23004482006-01-10 19:05:34 +00002596}
2597
2598Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00002599 assert(isa<VectorType>(Val->getType()) &&
Reid Spencer09575ba2007-02-15 03:39:18 +00002600 "Tried to create extractelement operation on non-vector type!");
Reid Spencer8d9336d2006-12-31 05:26:44 +00002601 assert(Idx->getType() == Type::Int32Ty &&
Reid Spencer2546b762007-01-26 07:37:34 +00002602 "Extractelement index must be i32 type!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00002603 return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
Robert Bocchino23004482006-01-10 19:05:34 +00002604 Val, Idx);
2605}
Chris Lattnerb50d1352003-10-05 00:17:43 +00002606
Robert Bocchinoca27f032006-01-17 20:07:22 +00002607Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
2608 Constant *Elt, Constant *Idx) {
2609 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
2610 return FC; // Fold a few common cases...
2611 // Look up the constant in the table first to ensure uniqueness
2612 std::vector<Constant*> ArgVec(1, Val);
2613 ArgVec.push_back(Elt);
2614 ArgVec.push_back(Idx);
Reid Spenceree3c9912006-12-04 05:19:50 +00002615 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
Owen Anderson61794042009-06-17 20:10:08 +00002616
2617 // Implicitly locked.
2618 return ExprConstants->getOrCreate(ReqTy, Key);
Robert Bocchinoca27f032006-01-17 20:07:22 +00002619}
2620
2621Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
2622 Constant *Idx) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00002623 assert(isa<VectorType>(Val->getType()) &&
Reid Spencer09575ba2007-02-15 03:39:18 +00002624 "Tried to create insertelement operation on non-vector type!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00002625 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
Robert Bocchinoca27f032006-01-17 20:07:22 +00002626 && "Insertelement types must match!");
Reid Spencer8d9336d2006-12-31 05:26:44 +00002627 assert(Idx->getType() == Type::Int32Ty &&
Reid Spencer2546b762007-01-26 07:37:34 +00002628 "Insertelement index must be i32 type!");
Gordon Henriksenb52d1ed2008-08-30 15:41:51 +00002629 return getInsertElementTy(Val->getType(), Val, Elt, Idx);
Robert Bocchinoca27f032006-01-17 20:07:22 +00002630}
2631
Chris Lattnerbbe0a422006-04-08 01:18:18 +00002632Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
2633 Constant *V2, Constant *Mask) {
2634 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
2635 return FC; // Fold a few common cases...
2636 // Look up the constant in the table first to ensure uniqueness
2637 std::vector<Constant*> ArgVec(1, V1);
2638 ArgVec.push_back(V2);
2639 ArgVec.push_back(Mask);
Reid Spenceree3c9912006-12-04 05:19:50 +00002640 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
Owen Anderson61794042009-06-17 20:10:08 +00002641
2642 // Implicitly locked.
2643 return ExprConstants->getOrCreate(ReqTy, Key);
Chris Lattnerbbe0a422006-04-08 01:18:18 +00002644}
2645
2646Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
2647 Constant *Mask) {
2648 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
2649 "Invalid shuffle vector constant expr operands!");
Nate Begeman94aa38d2009-02-12 21:28:33 +00002650
2651 unsigned NElts = cast<VectorType>(Mask->getType())->getNumElements();
2652 const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
2653 const Type *ShufTy = VectorType::get(EltTy, NElts);
2654 return getShuffleVectorTy(ShufTy, V1, V2, Mask);
Chris Lattnerbbe0a422006-04-08 01:18:18 +00002655}
2656
Dan Gohman12fce772008-05-15 19:50:34 +00002657Constant *ConstantExpr::getInsertValueTy(const Type *ReqTy, Constant *Agg,
2658 Constant *Val,
Dan Gohman1ecaf452008-05-31 00:58:22 +00002659 const unsigned *Idxs, unsigned NumIdx) {
Dan Gohman12fce772008-05-15 19:50:34 +00002660 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
2661 Idxs+NumIdx) == Val->getType() &&
2662 "insertvalue indices invalid!");
2663 assert(Agg->getType() == ReqTy &&
2664 "insertvalue type invalid!");
Dan Gohman0752bff2008-05-23 00:36:11 +00002665 assert(Agg->getType()->isFirstClassType() &&
2666 "Non-first-class type for constant InsertValue expression");
Dan Gohmand5d24f62008-07-21 23:30:30 +00002667 Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs, NumIdx);
2668 assert(FC && "InsertValue constant expr couldn't be folded!");
2669 return FC;
Dan Gohman12fce772008-05-15 19:50:34 +00002670}
2671
2672Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
Dan Gohman1ecaf452008-05-31 00:58:22 +00002673 const unsigned *IdxList, unsigned NumIdx) {
Dan Gohman0752bff2008-05-23 00:36:11 +00002674 assert(Agg->getType()->isFirstClassType() &&
2675 "Tried to create insertelement operation on non-first-class type!");
Dan Gohman12fce772008-05-15 19:50:34 +00002676
Dan Gohman0752bff2008-05-23 00:36:11 +00002677 const Type *ReqTy = Agg->getType();
Devang Pateld26344d2008-11-03 23:20:04 +00002678#ifndef NDEBUG
Dan Gohman0752bff2008-05-23 00:36:11 +00002679 const Type *ValTy =
Dan Gohman12fce772008-05-15 19:50:34 +00002680 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
Devang Pateld26344d2008-11-03 23:20:04 +00002681#endif
Dan Gohman0752bff2008-05-23 00:36:11 +00002682 assert(ValTy == Val->getType() && "insertvalue indices invalid!");
Dan Gohman12fce772008-05-15 19:50:34 +00002683 return getInsertValueTy(ReqTy, Agg, Val, IdxList, NumIdx);
2684}
2685
2686Constant *ConstantExpr::getExtractValueTy(const Type *ReqTy, Constant *Agg,
Dan Gohman1ecaf452008-05-31 00:58:22 +00002687 const unsigned *Idxs, unsigned NumIdx) {
Dan Gohman12fce772008-05-15 19:50:34 +00002688 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
2689 Idxs+NumIdx) == ReqTy &&
2690 "extractvalue indices invalid!");
Dan Gohman0752bff2008-05-23 00:36:11 +00002691 assert(Agg->getType()->isFirstClassType() &&
2692 "Non-first-class type for constant extractvalue expression");
Dan Gohmand5d24f62008-07-21 23:30:30 +00002693 Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs, NumIdx);
2694 assert(FC && "ExtractValue constant expr couldn't be folded!");
2695 return FC;
Dan Gohman12fce772008-05-15 19:50:34 +00002696}
2697
2698Constant *ConstantExpr::getExtractValue(Constant *Agg,
Dan Gohman1ecaf452008-05-31 00:58:22 +00002699 const unsigned *IdxList, unsigned NumIdx) {
Dan Gohman0752bff2008-05-23 00:36:11 +00002700 assert(Agg->getType()->isFirstClassType() &&
2701 "Tried to create extractelement operation on non-first-class type!");
Dan Gohman12fce772008-05-15 19:50:34 +00002702
2703 const Type *ReqTy =
2704 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
2705 assert(ReqTy && "extractvalue indices invalid!");
2706 return getExtractValueTy(ReqTy, Agg, IdxList, NumIdx);
2707}
2708
Reid Spencer2eadb532007-01-21 00:29:26 +00002709Constant *ConstantExpr::getZeroValueForNegationExpr(const Type *Ty) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00002710 if (const VectorType *PTy = dyn_cast<VectorType>(Ty))
Reid Spencer6598ca82007-01-21 02:29:10 +00002711 if (PTy->getElementType()->isFloatingPoint()) {
2712 std::vector<Constant*> zeros(PTy->getNumElements(),
Dale Johannesen98d3a082007-09-14 22:26:36 +00002713 ConstantFP::getNegativeZero(PTy->getElementType()));
Reid Spencerd84d35b2007-02-15 02:26:10 +00002714 return ConstantVector::get(PTy, zeros);
Reid Spencer6598ca82007-01-21 02:29:10 +00002715 }
Reid Spencer2eadb532007-01-21 00:29:26 +00002716
Dale Johannesen98d3a082007-09-14 22:26:36 +00002717 if (Ty->isFloatingPoint())
2718 return ConstantFP::getNegativeZero(Ty);
Reid Spencer2eadb532007-01-21 00:29:26 +00002719
2720 return Constant::getNullValue(Ty);
2721}
2722
Vikram S. Adve4c485332002-07-15 18:19:33 +00002723// destroyConstant - Remove the constant from the constant table...
2724//
2725void ConstantExpr::destroyConstant() {
Owen Anderson59ba8142009-06-19 18:34:09 +00002726 // Implicitly locked.
Owen Andersond830eb82009-06-18 19:10:19 +00002727 ExprConstants->remove(this);
Vikram S. Adve4c485332002-07-15 18:19:33 +00002728 destroyConstantImpl();
Vikram S. Adve4e537b22002-07-14 23:13:17 +00002729}
2730
Chris Lattner3cd8c562002-07-30 18:54:25 +00002731const char *ConstantExpr::getOpcodeName() const {
2732 return Instruction::getOpcodeName(getOpcode());
Vikram S. Adve4e537b22002-07-14 23:13:17 +00002733}
Reid Spencer1ebe1ab2004-07-17 23:48:33 +00002734
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002735//===----------------------------------------------------------------------===//
2736// replaceUsesOfWithOnConstant implementations
2737
Chris Lattner913849b2007-08-21 00:55:23 +00002738/// replaceUsesOfWithOnConstant - Update this constant array to change uses of
2739/// 'From' to be uses of 'To'. This must update the uniquing data structures
2740/// etc.
2741///
2742/// Note that we intentionally replace all uses of From with To here. Consider
2743/// a large array that uses 'From' 1000 times. By handling this case all here,
2744/// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
2745/// single invocation handles all 1000 uses. Handling them one at a time would
2746/// work, but would be really slow because it would have to unique each updated
2747/// array instance.
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002748void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002749 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002750 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
Chris Lattner8760ec72005-10-04 01:17:50 +00002751 Constant *ToC = cast<Constant>(To);
Chris Lattnerdff59112005-10-04 18:47:09 +00002752
Jim Laskeyc03caef2006-07-17 17:38:29 +00002753 std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
Chris Lattnerb64419a2005-10-03 22:51:37 +00002754 Lookup.first.first = getType();
2755 Lookup.second = this;
Chris Lattnerdff59112005-10-04 18:47:09 +00002756
Chris Lattnerb64419a2005-10-03 22:51:37 +00002757 std::vector<Constant*> &Values = Lookup.first.second;
2758 Values.reserve(getNumOperands()); // Build replacement array.
Chris Lattnerdff59112005-10-04 18:47:09 +00002759
Chris Lattner8760ec72005-10-04 01:17:50 +00002760 // Fill values with the modified operands of the constant array. Also,
2761 // compute whether this turns into an all-zeros array.
Chris Lattnerdff59112005-10-04 18:47:09 +00002762 bool isAllZeros = false;
Chris Lattner913849b2007-08-21 00:55:23 +00002763 unsigned NumUpdated = 0;
Chris Lattnerdff59112005-10-04 18:47:09 +00002764 if (!ToC->isNullValue()) {
Chris Lattner913849b2007-08-21 00:55:23 +00002765 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2766 Constant *Val = cast<Constant>(O->get());
2767 if (Val == From) {
2768 Val = ToC;
2769 ++NumUpdated;
2770 }
2771 Values.push_back(Val);
2772 }
Chris Lattnerdff59112005-10-04 18:47:09 +00002773 } else {
2774 isAllZeros = true;
2775 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2776 Constant *Val = cast<Constant>(O->get());
Chris Lattner913849b2007-08-21 00:55:23 +00002777 if (Val == From) {
2778 Val = ToC;
2779 ++NumUpdated;
2780 }
Chris Lattnerdff59112005-10-04 18:47:09 +00002781 Values.push_back(Val);
2782 if (isAllZeros) isAllZeros = Val->isNullValue();
2783 }
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002784 }
2785
Chris Lattnerb64419a2005-10-03 22:51:37 +00002786 Constant *Replacement = 0;
2787 if (isAllZeros) {
2788 Replacement = ConstantAggregateZero::get(getType());
2789 } else {
2790 // Check to see if we have this array type already.
Owen Andersond830eb82009-06-18 19:10:19 +00002791 sys::SmartScopedWriter<true> Writer(&*ConstantsLock);
Chris Lattnerb64419a2005-10-03 22:51:37 +00002792 bool Exists;
Jim Laskeyc03caef2006-07-17 17:38:29 +00002793 ArrayConstantsTy::MapTy::iterator I =
Chris Lattner69edc982006-09-28 00:35:06 +00002794 ArrayConstants->InsertOrGetItem(Lookup, Exists);
Chris Lattnerb64419a2005-10-03 22:51:37 +00002795
2796 if (Exists) {
2797 Replacement = I->second;
2798 } else {
2799 // Okay, the new shape doesn't exist in the system yet. Instead of
2800 // creating a new constant array, inserting it, replaceallusesof'ing the
2801 // old with the new, then deleting the old... just update the current one
2802 // in place!
Chris Lattner69edc982006-09-28 00:35:06 +00002803 ArrayConstants->MoveConstantToNewSlot(this, I);
Chris Lattnerb64419a2005-10-03 22:51:37 +00002804
Chris Lattner913849b2007-08-21 00:55:23 +00002805 // Update to the new value. Optimize for the case when we have a single
2806 // operand that we're changing, but handle bulk updates efficiently.
2807 if (NumUpdated == 1) {
2808 unsigned OperandToUpdate = U-OperandList;
2809 assert(getOperand(OperandToUpdate) == From &&
2810 "ReplaceAllUsesWith broken!");
2811 setOperand(OperandToUpdate, ToC);
2812 } else {
2813 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2814 if (getOperand(i) == From)
2815 setOperand(i, ToC);
2816 }
Chris Lattnerb64419a2005-10-03 22:51:37 +00002817 return;
2818 }
2819 }
2820
2821 // Otherwise, I do need to replace this with an existing value.
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002822 assert(Replacement != this && "I didn't contain From!");
2823
Chris Lattner7a1450d2005-10-04 18:13:04 +00002824 // Everyone using this now uses the replacement.
2825 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002826
2827 // Delete the old constant!
2828 destroyConstant();
2829}
2830
2831void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002832 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002833 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
Chris Lattner8760ec72005-10-04 01:17:50 +00002834 Constant *ToC = cast<Constant>(To);
2835
Chris Lattnerdff59112005-10-04 18:47:09 +00002836 unsigned OperandToUpdate = U-OperandList;
2837 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2838
Jim Laskeyc03caef2006-07-17 17:38:29 +00002839 std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
Chris Lattner8760ec72005-10-04 01:17:50 +00002840 Lookup.first.first = getType();
2841 Lookup.second = this;
2842 std::vector<Constant*> &Values = Lookup.first.second;
2843 Values.reserve(getNumOperands()); // Build replacement struct.
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002844
Chris Lattnerdff59112005-10-04 18:47:09 +00002845
Chris Lattner8760ec72005-10-04 01:17:50 +00002846 // Fill values with the modified operands of the constant struct. Also,
2847 // compute whether this turns into an all-zeros struct.
Chris Lattnerdff59112005-10-04 18:47:09 +00002848 bool isAllZeros = false;
2849 if (!ToC->isNullValue()) {
2850 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
2851 Values.push_back(cast<Constant>(O->get()));
2852 } else {
2853 isAllZeros = true;
2854 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2855 Constant *Val = cast<Constant>(O->get());
2856 Values.push_back(Val);
2857 if (isAllZeros) isAllZeros = Val->isNullValue();
2858 }
Chris Lattner8760ec72005-10-04 01:17:50 +00002859 }
Chris Lattnerdff59112005-10-04 18:47:09 +00002860 Values[OperandToUpdate] = ToC;
2861
Chris Lattner8760ec72005-10-04 01:17:50 +00002862 Constant *Replacement = 0;
2863 if (isAllZeros) {
2864 Replacement = ConstantAggregateZero::get(getType());
2865 } else {
2866 // Check to see if we have this array type already.
Owen Andersond830eb82009-06-18 19:10:19 +00002867 sys::SmartScopedWriter<true> Writer(&*ConstantsLock);
Chris Lattner8760ec72005-10-04 01:17:50 +00002868 bool Exists;
Jim Laskeyc03caef2006-07-17 17:38:29 +00002869 StructConstantsTy::MapTy::iterator I =
Chris Lattner69edc982006-09-28 00:35:06 +00002870 StructConstants->InsertOrGetItem(Lookup, Exists);
Chris Lattner8760ec72005-10-04 01:17:50 +00002871
2872 if (Exists) {
2873 Replacement = I->second;
2874 } else {
2875 // Okay, the new shape doesn't exist in the system yet. Instead of
2876 // creating a new constant struct, inserting it, replaceallusesof'ing the
2877 // old with the new, then deleting the old... just update the current one
2878 // in place!
Chris Lattner69edc982006-09-28 00:35:06 +00002879 StructConstants->MoveConstantToNewSlot(this, I);
Chris Lattner8760ec72005-10-04 01:17:50 +00002880
Chris Lattnerdff59112005-10-04 18:47:09 +00002881 // Update to the new value.
2882 setOperand(OperandToUpdate, ToC);
Chris Lattner8760ec72005-10-04 01:17:50 +00002883 return;
2884 }
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002885 }
2886
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002887 assert(Replacement != this && "I didn't contain From!");
2888
Chris Lattner7a1450d2005-10-04 18:13:04 +00002889 // Everyone using this now uses the replacement.
2890 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002891
2892 // Delete the old constant!
2893 destroyConstant();
2894}
2895
Reid Spencerd84d35b2007-02-15 02:26:10 +00002896void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002897 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002898 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2899
2900 std::vector<Constant*> Values;
2901 Values.reserve(getNumOperands()); // Build replacement array...
2902 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2903 Constant *Val = getOperand(i);
2904 if (Val == From) Val = cast<Constant>(To);
2905 Values.push_back(Val);
2906 }
2907
Reid Spencerd84d35b2007-02-15 02:26:10 +00002908 Constant *Replacement = ConstantVector::get(getType(), Values);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002909 assert(Replacement != this && "I didn't contain From!");
2910
Chris Lattner7a1450d2005-10-04 18:13:04 +00002911 // Everyone using this now uses the replacement.
2912 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002913
2914 // Delete the old constant!
2915 destroyConstant();
2916}
2917
2918void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002919 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002920 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2921 Constant *To = cast<Constant>(ToV);
2922
2923 Constant *Replacement = 0;
2924 if (getOpcode() == Instruction::GetElementPtr) {
Chris Lattnerb5d70302007-02-19 20:01:23 +00002925 SmallVector<Constant*, 8> Indices;
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002926 Constant *Pointer = getOperand(0);
2927 Indices.reserve(getNumOperands()-1);
2928 if (Pointer == From) Pointer = To;
2929
2930 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2931 Constant *Val = getOperand(i);
2932 if (Val == From) Val = To;
2933 Indices.push_back(Val);
2934 }
Chris Lattnerb5d70302007-02-19 20:01:23 +00002935 Replacement = ConstantExpr::getGetElementPtr(Pointer,
2936 &Indices[0], Indices.size());
Dan Gohman12fce772008-05-15 19:50:34 +00002937 } else if (getOpcode() == Instruction::ExtractValue) {
Dan Gohman12fce772008-05-15 19:50:34 +00002938 Constant *Agg = getOperand(0);
Dan Gohman12fce772008-05-15 19:50:34 +00002939 if (Agg == From) Agg = To;
2940
Dan Gohman1ecaf452008-05-31 00:58:22 +00002941 const SmallVector<unsigned, 4> &Indices = getIndices();
Dan Gohman12fce772008-05-15 19:50:34 +00002942 Replacement = ConstantExpr::getExtractValue(Agg,
2943 &Indices[0], Indices.size());
2944 } else if (getOpcode() == Instruction::InsertValue) {
Dan Gohman12fce772008-05-15 19:50:34 +00002945 Constant *Agg = getOperand(0);
2946 Constant *Val = getOperand(1);
Dan Gohman12fce772008-05-15 19:50:34 +00002947 if (Agg == From) Agg = To;
2948 if (Val == From) Val = To;
2949
Dan Gohman1ecaf452008-05-31 00:58:22 +00002950 const SmallVector<unsigned, 4> &Indices = getIndices();
Dan Gohman12fce772008-05-15 19:50:34 +00002951 Replacement = ConstantExpr::getInsertValue(Agg, Val,
2952 &Indices[0], Indices.size());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002953 } else if (isCast()) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002954 assert(getOperand(0) == From && "Cast only has one use!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002955 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002956 } else if (getOpcode() == Instruction::Select) {
2957 Constant *C1 = getOperand(0);
2958 Constant *C2 = getOperand(1);
2959 Constant *C3 = getOperand(2);
2960 if (C1 == From) C1 = To;
2961 if (C2 == From) C2 = To;
2962 if (C3 == From) C3 = To;
2963 Replacement = ConstantExpr::getSelect(C1, C2, C3);
Robert Bocchino23004482006-01-10 19:05:34 +00002964 } else if (getOpcode() == Instruction::ExtractElement) {
2965 Constant *C1 = getOperand(0);
2966 Constant *C2 = getOperand(1);
2967 if (C1 == From) C1 = To;
2968 if (C2 == From) C2 = To;
2969 Replacement = ConstantExpr::getExtractElement(C1, C2);
Chris Lattnera93b4b52006-04-08 05:09:48 +00002970 } else if (getOpcode() == Instruction::InsertElement) {
2971 Constant *C1 = getOperand(0);
2972 Constant *C2 = getOperand(1);
2973 Constant *C3 = getOperand(1);
2974 if (C1 == From) C1 = To;
2975 if (C2 == From) C2 = To;
2976 if (C3 == From) C3 = To;
2977 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2978 } else if (getOpcode() == Instruction::ShuffleVector) {
2979 Constant *C1 = getOperand(0);
2980 Constant *C2 = getOperand(1);
2981 Constant *C3 = getOperand(2);
2982 if (C1 == From) C1 = To;
2983 if (C2 == From) C2 = To;
2984 if (C3 == From) C3 = To;
2985 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
Reid Spenceree3c9912006-12-04 05:19:50 +00002986 } else if (isCompare()) {
2987 Constant *C1 = getOperand(0);
2988 Constant *C2 = getOperand(1);
2989 if (C1 == From) C1 = To;
2990 if (C2 == From) C2 = To;
2991 if (getOpcode() == Instruction::ICmp)
2992 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
Chris Lattnereab49262008-07-14 05:17:31 +00002993 else if (getOpcode() == Instruction::FCmp)
Reid Spenceree3c9912006-12-04 05:19:50 +00002994 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
Chris Lattnereab49262008-07-14 05:17:31 +00002995 else if (getOpcode() == Instruction::VICmp)
2996 Replacement = ConstantExpr::getVICmp(getPredicate(), C1, C2);
2997 else {
2998 assert(getOpcode() == Instruction::VFCmp);
2999 Replacement = ConstantExpr::getVFCmp(getPredicate(), C1, C2);
3000 }
Chris Lattnerc4062ba2005-10-03 21:58:36 +00003001 } else if (getNumOperands() == 2) {
3002 Constant *C1 = getOperand(0);
3003 Constant *C2 = getOperand(1);
3004 if (C1 == From) C1 = To;
3005 if (C2 == From) C2 = To;
3006 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
3007 } else {
3008 assert(0 && "Unknown ConstantExpr type!");
3009 return;
3010 }
3011
3012 assert(Replacement != this && "I didn't contain From!");
3013
Chris Lattner7a1450d2005-10-04 18:13:04 +00003014 // Everyone using this now uses the replacement.
3015 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00003016
3017 // Delete the old constant!
3018 destroyConstant();
Matthijs Kooijmanba5d7ef2008-07-03 07:46:41 +00003019}
Nick Lewycky49f89192009-04-04 07:22:01 +00003020
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00003021void MDNode::replaceElement(Value *From, Value *To) {
3022 SmallVector<Value*, 4> Values;
3023 Values.reserve(getNumElements()); // Build replacement array...
3024 for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
3025 Value *Val = getElement(i);
3026 if (Val == From) Val = To;
Nick Lewycky49f89192009-04-04 07:22:01 +00003027 Values.push_back(Val);
3028 }
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00003029
3030 MDNode *Replacement = MDNode::get(&Values[0], Values.size());
Nick Lewycky49f89192009-04-04 07:22:01 +00003031 assert(Replacement != this && "I didn't contain From!");
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00003032
Nick Lewycky49f89192009-04-04 07:22:01 +00003033 uncheckedReplaceAllUsesWith(Replacement);
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00003034
Nick Lewycky49f89192009-04-04 07:22:01 +00003035 destroyConstant();
3036}