blob: 8af5b037d110c70e510ac4570645227754ecd8e0 [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 Anderson2d7231d2009-06-17 18:40:29 +000040ManagedStatic<sys::RWMutex> ConstantsLock;
41
Chris Lattner3462ae32001-12-03 22:26:30 +000042void Constant::destroyConstantImpl() {
43 // When a Constant is destroyed, there may be lingering
Chris Lattnerd7a73302001-10-13 06:57:33 +000044 // references to the constant by other constants in the constant pool. These
Misha Brukmanbe372b92003-08-21 22:14:26 +000045 // constants are implicitly dependent on the module that is being deleted,
Chris Lattnerd7a73302001-10-13 06:57:33 +000046 // but they don't know that. Because we only find out when the CPV is
47 // deleted, we must now notify all of our users (that should only be
Chris Lattner3462ae32001-12-03 22:26:30 +000048 // Constants) that they are, in fact, invalid now and should be deleted.
Chris Lattnerd7a73302001-10-13 06:57:33 +000049 //
50 while (!use_empty()) {
51 Value *V = use_back();
52#ifndef NDEBUG // Only in -g mode...
Chris Lattnerd9f4ac662002-07-18 00:14:50 +000053 if (!isa<Constant>(V))
Bill Wendling6a462f12006-11-17 08:03:48 +000054 DOUT << "While deleting: " << *this
55 << "\n\nUse still stuck around after Def is destroyed: "
56 << *V << "\n\n";
Chris Lattnerd7a73302001-10-13 06:57:33 +000057#endif
Vikram S. Adve4e537b22002-07-14 23:13:17 +000058 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
Reid Spencer1ebe1ab2004-07-17 23:48:33 +000059 Constant *CV = cast<Constant>(V);
60 CV->destroyConstant();
Chris Lattnerd7a73302001-10-13 06:57:33 +000061
62 // The constant should remove itself from our use list...
Vikram S. Adve4e537b22002-07-14 23:13:17 +000063 assert((use_empty() || use_back() != V) && "Constant not removed!");
Chris Lattnerd7a73302001-10-13 06:57:33 +000064 }
65
66 // Value has no outstanding references it is safe to delete it now...
67 delete this;
Chris Lattner38569342001-10-01 20:11:19 +000068}
Chris Lattner2f7c9632001-06-06 20:29:01 +000069
Chris Lattner23dd1f62006-10-20 00:27:06 +000070/// canTrap - Return true if evaluation of this constant could trap. This is
71/// true for things like constant expressions that could divide by zero.
72bool Constant::canTrap() const {
73 assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
74 // The only thing that could possibly trap are constant exprs.
75 const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
76 if (!CE) return false;
77
78 // ConstantExpr traps if any operands can trap.
79 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
80 if (getOperand(i)->canTrap())
81 return true;
82
83 // Otherwise, only specific operations can trap.
84 switch (CE->getOpcode()) {
85 default:
86 return false;
Reid Spencer7e80b0b2006-10-26 06:15:43 +000087 case Instruction::UDiv:
88 case Instruction::SDiv:
89 case Instruction::FDiv:
Reid Spencer7eb55b32006-11-02 01:53:59 +000090 case Instruction::URem:
91 case Instruction::SRem:
92 case Instruction::FRem:
Chris Lattner23dd1f62006-10-20 00:27:06 +000093 // Div and rem can trap if the RHS is not known to be non-zero.
94 if (!isa<ConstantInt>(getOperand(1)) || getOperand(1)->isNullValue())
95 return true;
96 return false;
97 }
98}
99
Anton Korobeynikov7437b592009-03-29 17:13:18 +0000100/// ContainsRelocations - Return true if the constant value contains relocations
101/// which cannot be resolved at compile time. Kind argument is used to filter
102/// only 'interesting' sorts of relocations.
103bool Constant::ContainsRelocations(unsigned Kind) const {
104 if (const GlobalValue* GV = dyn_cast<GlobalValue>(this)) {
105 bool isLocal = GV->hasLocalLinkage();
106 if ((Kind & Reloc::Local) && isLocal) {
107 // Global has local linkage and 'local' kind of relocations are
108 // requested
109 return true;
110 }
111
112 if ((Kind & Reloc::Global) && !isLocal) {
113 // Global has non-local linkage and 'global' kind of relocations are
114 // requested
115 return true;
116 }
Anton Korobeynikov255a3cb2009-03-30 15:28:21 +0000117
118 return false;
Anton Korobeynikov7437b592009-03-29 17:13:18 +0000119 }
120
Evan Chengf9e003b2007-03-08 00:59:12 +0000121 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
Anton Korobeynikovd5e8e932009-03-30 15:28:00 +0000122 if (getOperand(i)->ContainsRelocations(Kind))
Evan Chengf9e003b2007-03-08 00:59:12 +0000123 return true;
Anton Korobeynikov7437b592009-03-29 17:13:18 +0000124
Evan Chengf9e003b2007-03-08 00:59:12 +0000125 return false;
126}
127
Chris Lattnerb1585a92002-08-13 17:50:20 +0000128// Static constructor to create a '0' constant of arbitrary type...
129Constant *Constant::getNullValue(const Type *Ty) {
Dale Johannesen98d3a082007-09-14 22:26:36 +0000130 static uint64_t zero[2] = {0, 0};
Chris Lattner6b727592004-06-17 18:19:28 +0000131 switch (Ty->getTypeID()) {
Chris Lattnerdbcb0d32007-02-20 05:46:39 +0000132 case Type::IntegerTyID:
133 return ConstantInt::get(Ty, 0);
134 case Type::FloatTyID:
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000135 return ConstantFP::get(APFloat(APInt(32, 0)));
Chris Lattnerdbcb0d32007-02-20 05:46:39 +0000136 case Type::DoubleTyID:
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000137 return ConstantFP::get(APFloat(APInt(64, 0)));
Dale Johannesenbdad8092007-08-09 22:51:36 +0000138 case Type::X86_FP80TyID:
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000139 return ConstantFP::get(APFloat(APInt(80, 2, zero)));
Dale Johannesenbdad8092007-08-09 22:51:36 +0000140 case Type::FP128TyID:
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000141 return ConstantFP::get(APFloat(APInt(128, 2, zero), true));
Dale Johannesen98d3a082007-09-14 22:26:36 +0000142 case Type::PPC_FP128TyID:
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000143 return ConstantFP::get(APFloat(APInt(128, 2, zero)));
Misha Brukmanb1c93172005-04-21 23:48:37 +0000144 case Type::PointerTyID:
Chris Lattnerb1585a92002-08-13 17:50:20 +0000145 return ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattner9fba3da2004-02-15 05:53:04 +0000146 case Type::StructTyID:
147 case Type::ArrayTyID:
Reid Spencerd84d35b2007-02-15 02:26:10 +0000148 case Type::VectorTyID:
Chris Lattner9fba3da2004-02-15 05:53:04 +0000149 return ConstantAggregateZero::get(Ty);
Chris Lattnerb1585a92002-08-13 17:50:20 +0000150 default:
Reid Spencercf394bf2004-07-04 11:51:24 +0000151 // Function, Label, or Opaque type?
152 assert(!"Cannot create a null constant of that type!");
Chris Lattnerb1585a92002-08-13 17:50:20 +0000153 return 0;
154 }
155}
156
Chris Lattner72e39582007-06-15 06:10:53 +0000157Constant *Constant::getAllOnesValue(const Type *Ty) {
158 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
159 return ConstantInt::get(APInt::getAllOnesValue(ITy->getBitWidth()));
160 return ConstantVector::getAllOnesValue(cast<VectorType>(Ty));
161}
Chris Lattnerb1585a92002-08-13 17:50:20 +0000162
163// Static constructor to create an integral constant with all bits set
Zhou Sheng75b871f2007-01-11 12:24:14 +0000164ConstantInt *ConstantInt::getAllOnesValue(const Type *Ty) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000165 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
Reid Spencerd1bbfa52007-03-01 19:30:34 +0000166 return ConstantInt::get(APInt::getAllOnesValue(ITy->getBitWidth()));
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000167 return 0;
Chris Lattnerb1585a92002-08-13 17:50:20 +0000168}
169
Dan Gohman30978072007-05-24 14:36:04 +0000170/// @returns the value for a vector integer constant of the given type that
Chris Lattnerecab54c2007-01-04 01:49:26 +0000171/// has all its bits set to true.
172/// @brief Get the all ones value
Reid Spencerd84d35b2007-02-15 02:26:10 +0000173ConstantVector *ConstantVector::getAllOnesValue(const VectorType *Ty) {
Chris Lattnerecab54c2007-01-04 01:49:26 +0000174 std::vector<Constant*> Elts;
175 Elts.resize(Ty->getNumElements(),
Zhou Sheng75b871f2007-01-11 12:24:14 +0000176 ConstantInt::getAllOnesValue(Ty->getElementType()));
Dan Gohman30978072007-05-24 14:36:04 +0000177 assert(Elts[0] && "Not a vector integer type!");
Reid Spencerd84d35b2007-02-15 02:26:10 +0000178 return cast<ConstantVector>(ConstantVector::get(Elts));
Chris Lattnerecab54c2007-01-04 01:49:26 +0000179}
180
181
Chris Lattner2105d662008-07-10 00:28:11 +0000182/// getVectorElements - This method, which is only valid on constant of vector
183/// type, returns the elements of the vector in the specified smallvector.
Chris Lattnerc5098a22008-07-14 05:10:41 +0000184/// This handles breaking down a vector undef into undef elements, etc. For
185/// constant exprs and other cases we can't handle, we return an empty vector.
Chris Lattner2105d662008-07-10 00:28:11 +0000186void Constant::getVectorElements(SmallVectorImpl<Constant*> &Elts) const {
187 assert(isa<VectorType>(getType()) && "Not a vector constant!");
188
189 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this)) {
190 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i)
191 Elts.push_back(CV->getOperand(i));
192 return;
193 }
194
195 const VectorType *VT = cast<VectorType>(getType());
196 if (isa<ConstantAggregateZero>(this)) {
197 Elts.assign(VT->getNumElements(),
198 Constant::getNullValue(VT->getElementType()));
199 return;
200 }
201
Chris Lattnerc5098a22008-07-14 05:10:41 +0000202 if (isa<UndefValue>(this)) {
203 Elts.assign(VT->getNumElements(), UndefValue::get(VT->getElementType()));
204 return;
205 }
206
207 // Unknown type, must be constant expr etc.
Chris Lattner2105d662008-07-10 00:28:11 +0000208}
209
210
211
Chris Lattner2f7c9632001-06-06 20:29:01 +0000212//===----------------------------------------------------------------------===//
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000213// ConstantInt
Chris Lattner2f7c9632001-06-06 20:29:01 +0000214//===----------------------------------------------------------------------===//
215
Reid Spencerb31bffe2007-02-26 23:54:03 +0000216ConstantInt::ConstantInt(const IntegerType *Ty, const APInt& V)
Chris Lattner5db2f472007-02-20 05:55:46 +0000217 : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
Reid Spencerb31bffe2007-02-26 23:54:03 +0000218 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
Chris Lattner2f7c9632001-06-06 20:29:01 +0000219}
220
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000221ConstantInt *ConstantInt::TheTrueVal = 0;
222ConstantInt *ConstantInt::TheFalseVal = 0;
223
224namespace llvm {
225 void CleanupTrueFalse(void *) {
226 ConstantInt::ResetTrueFalse();
227 }
228}
229
230static ManagedCleanup<llvm::CleanupTrueFalse> TrueFalseCleanup;
231
232ConstantInt *ConstantInt::CreateTrueFalseVals(bool WhichOne) {
233 assert(TheTrueVal == 0 && TheFalseVal == 0);
234 TheTrueVal = get(Type::Int1Ty, 1);
235 TheFalseVal = get(Type::Int1Ty, 0);
236
237 // Ensure that llvm_shutdown nulls out TheTrueVal/TheFalseVal.
238 TrueFalseCleanup.Register();
239
240 return WhichOne ? TheTrueVal : TheFalseVal;
241}
242
243
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000244namespace {
Reid Spencerb31bffe2007-02-26 23:54:03 +0000245 struct DenseMapAPIntKeyInfo {
246 struct KeyTy {
247 APInt val;
248 const Type* type;
249 KeyTy(const APInt& V, const Type* Ty) : val(V), type(Ty) {}
250 KeyTy(const KeyTy& that) : val(that.val), type(that.type) {}
251 bool operator==(const KeyTy& that) const {
252 return type == that.type && this->val == that.val;
253 }
254 bool operator!=(const KeyTy& that) const {
255 return !this->operator==(that);
256 }
257 };
258 static inline KeyTy getEmptyKey() { return KeyTy(APInt(1,0), 0); }
259 static inline KeyTy getTombstoneKey() { return KeyTy(APInt(1,1), 0); }
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000260 static unsigned getHashValue(const KeyTy &Key) {
Chris Lattner0625bd62007-09-17 18:34:04 +0000261 return DenseMapInfo<void*>::getHashValue(Key.type) ^
Reid Spencerb31bffe2007-02-26 23:54:03 +0000262 Key.val.getHashValue();
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000263 }
Chris Lattner0625bd62007-09-17 18:34:04 +0000264 static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
265 return LHS == RHS;
266 }
Dale Johannesena719a602007-08-24 00:56:33 +0000267 static bool isPod() { return false; }
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000268 };
269}
270
271
Reid Spencerb31bffe2007-02-26 23:54:03 +0000272typedef DenseMap<DenseMapAPIntKeyInfo::KeyTy, ConstantInt*,
273 DenseMapAPIntKeyInfo> IntMapTy;
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000274static ManagedStatic<IntMapTy> IntConstants;
275
Dan Gohman7ccc52f2009-06-15 22:12:54 +0000276ConstantInt *ConstantInt::get(const IntegerType *Ty,
277 uint64_t V, bool isSigned) {
278 return get(APInt(Ty->getBitWidth(), V, isSigned));
279}
280
281Constant *ConstantInt::get(const Type *Ty, uint64_t V, bool isSigned) {
282 Constant *C = get(cast<IntegerType>(Ty->getScalarType()), V, isSigned);
283
284 // For vectors, broadcast the value.
285 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
286 return
287 ConstantVector::get(std::vector<Constant *>(VTy->getNumElements(), C));
288
289 return C;
Reid Spencerb31bffe2007-02-26 23:54:03 +0000290}
291
Reid Spencerd1bbfa52007-03-01 19:30:34 +0000292// Get a ConstantInt from an APInt. Note that the value stored in the DenseMap
Dan Gohmanb3efe032008-02-07 02:30:40 +0000293// as the key, is a DenseMapAPIntKeyInfo::KeyTy which has provided the
Reid Spencerb31bffe2007-02-26 23:54:03 +0000294// operator== and operator!= to ensure that the DenseMap doesn't attempt to
295// compare APInt's of different widths, which would violate an APInt class
296// invariant which generates an assertion.
Reid Spencerd1bbfa52007-03-01 19:30:34 +0000297ConstantInt *ConstantInt::get(const APInt& V) {
298 // Get the corresponding integer type for the bit width of the value.
299 const IntegerType *ITy = IntegerType::get(V.getBitWidth());
Reid Spencerb31bffe2007-02-26 23:54:03 +0000300 // get an existing value or the insertion position
Reid Spencerd1bbfa52007-03-01 19:30:34 +0000301 DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
Owen Anderson2d7231d2009-06-17 18:40:29 +0000302
303 if (llvm_is_multithreaded()) {
304 ConstantsLock->reader_acquire();
305 ConstantInt *&Slot = (*IntConstants)[Key];
306 ConstantsLock->reader_release();
307
308 if (!Slot) {
Owen Anderson65c5cd72009-06-17 20:34:43 +0000309 sys::ScopedWriter Writer(&*ConstantsLock);
Owen Anderson2d7231d2009-06-17 18:40:29 +0000310 ConstantInt *&Slot = (*IntConstants)[Key];
311 if (!Slot) {
312 Slot = new ConstantInt(ITy, V);
313 }
Owen Anderson2d7231d2009-06-17 18:40:29 +0000314 }
315
Reid Spencerb31bffe2007-02-26 23:54:03 +0000316 return Slot;
Owen Anderson2d7231d2009-06-17 18:40:29 +0000317 } else {
318 ConstantInt *&Slot = (*IntConstants)[Key];
319 // if it exists, return it.
320 if (Slot)
321 return Slot;
322 // otherwise create a new one, insert it, and return it.
323 return Slot = new ConstantInt(ITy, V);
324 }
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000325}
326
Dan Gohman7ccc52f2009-06-15 22:12:54 +0000327Constant *ConstantInt::get(const Type *Ty, const APInt &V) {
328 ConstantInt *C = ConstantInt::get(V);
329 assert(C->getType() == Ty->getScalarType() &&
330 "ConstantInt type doesn't match the type implied by its value!");
331
332 // For vectors, broadcast the value.
333 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
334 return
335 ConstantVector::get(std::vector<Constant *>(VTy->getNumElements(), C));
336
337 return C;
338}
339
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000340//===----------------------------------------------------------------------===//
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000341// ConstantFP
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000342//===----------------------------------------------------------------------===//
343
Chris Lattner98bd9392008-04-09 06:38:30 +0000344static const fltSemantics *TypeToFloatSemantics(const Type *Ty) {
345 if (Ty == Type::FloatTy)
346 return &APFloat::IEEEsingle;
347 if (Ty == Type::DoubleTy)
348 return &APFloat::IEEEdouble;
349 if (Ty == Type::X86_FP80Ty)
350 return &APFloat::x87DoubleExtended;
351 else if (Ty == Type::FP128Ty)
352 return &APFloat::IEEEquad;
353
354 assert(Ty == Type::PPC_FP128Ty && "Unknown FP format");
355 return &APFloat::PPCDoubleDouble;
356}
357
Dale Johannesend246b2c2007-08-30 00:23:21 +0000358ConstantFP::ConstantFP(const Type *Ty, const APFloat& V)
359 : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
Chris Lattner98bd9392008-04-09 06:38:30 +0000360 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
361 "FP type Mismatch");
Chris Lattner2f7c9632001-06-06 20:29:01 +0000362}
363
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000364bool ConstantFP::isNullValue() const {
Dale Johannesena719a602007-08-24 00:56:33 +0000365 return Val.isZero() && !Val.isNegative();
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000366}
367
Dale Johannesen98d3a082007-09-14 22:26:36 +0000368ConstantFP *ConstantFP::getNegativeZero(const Type *Ty) {
369 APFloat apf = cast <ConstantFP>(Constant::getNullValue(Ty))->getValueAPF();
370 apf.changeSign();
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000371 return ConstantFP::get(apf);
Dale Johannesen98d3a082007-09-14 22:26:36 +0000372}
373
Dale Johannesend246b2c2007-08-30 00:23:21 +0000374bool ConstantFP::isExactlyValue(const APFloat& V) const {
375 return Val.bitwiseIsEqual(V);
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000376}
377
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000378namespace {
Dale Johannesena719a602007-08-24 00:56:33 +0000379 struct DenseMapAPFloatKeyInfo {
Dale Johannesenbdea32d2007-08-24 22:09:56 +0000380 struct KeyTy {
381 APFloat val;
382 KeyTy(const APFloat& V) : val(V){}
383 KeyTy(const KeyTy& that) : val(that.val) {}
384 bool operator==(const KeyTy& that) const {
385 return this->val.bitwiseIsEqual(that.val);
386 }
387 bool operator!=(const KeyTy& that) const {
388 return !this->operator==(that);
389 }
390 };
391 static inline KeyTy getEmptyKey() {
392 return KeyTy(APFloat(APFloat::Bogus,1));
Reid Spencerb31bffe2007-02-26 23:54:03 +0000393 }
Dale Johannesenbdea32d2007-08-24 22:09:56 +0000394 static inline KeyTy getTombstoneKey() {
395 return KeyTy(APFloat(APFloat::Bogus,2));
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000396 }
Dale Johannesenbdea32d2007-08-24 22:09:56 +0000397 static unsigned getHashValue(const KeyTy &Key) {
398 return Key.val.getHashValue();
Dale Johannesena719a602007-08-24 00:56:33 +0000399 }
Chris Lattner0625bd62007-09-17 18:34:04 +0000400 static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
401 return LHS == RHS;
402 }
Dale Johannesena719a602007-08-24 00:56:33 +0000403 static bool isPod() { return false; }
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000404 };
405}
406
407//---- ConstantFP::get() implementation...
408//
Dale Johannesenbdea32d2007-08-24 22:09:56 +0000409typedef DenseMap<DenseMapAPFloatKeyInfo::KeyTy, ConstantFP*,
Dale Johannesena719a602007-08-24 00:56:33 +0000410 DenseMapAPFloatKeyInfo> FPMapTy;
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000411
Dale Johannesena719a602007-08-24 00:56:33 +0000412static ManagedStatic<FPMapTy> FPConstants;
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000413
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000414ConstantFP *ConstantFP::get(const APFloat &V) {
Dale Johannesend246b2c2007-08-30 00:23:21 +0000415 DenseMapAPFloatKeyInfo::KeyTy Key(V);
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000416
Owen Anderson2d7231d2009-06-17 18:40:29 +0000417 if (llvm_is_multithreaded()) {
418 ConstantsLock->reader_acquire();
419 ConstantFP *&Slot = (*FPConstants)[Key];
420 ConstantsLock->reader_release();
421
422 if (!Slot) {
Owen Anderson65c5cd72009-06-17 20:34:43 +0000423 sys::ScopedWriter Writer(&*ConstantsLock);
Owen Anderson2d7231d2009-06-17 18:40:29 +0000424 Slot = (*FPConstants)[Key];
425 if (!Slot) {
426 const Type *Ty;
427 if (&V.getSemantics() == &APFloat::IEEEsingle)
428 Ty = Type::FloatTy;
429 else if (&V.getSemantics() == &APFloat::IEEEdouble)
430 Ty = Type::DoubleTy;
431 else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
432 Ty = Type::X86_FP80Ty;
433 else if (&V.getSemantics() == &APFloat::IEEEquad)
434 Ty = Type::FP128Ty;
435 else {
436 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble &&
437 "Unknown FP format");
438 Ty = Type::PPC_FP128Ty;
439 }
440
441 Slot = new ConstantFP(Ty, V);
442 }
Owen Anderson2d7231d2009-06-17 18:40:29 +0000443 }
444
445 return Slot;
446 } else {
447 ConstantFP *&Slot = (*FPConstants)[Key];
448 if (Slot) return Slot;
449
450 const Type *Ty;
451 if (&V.getSemantics() == &APFloat::IEEEsingle)
452 Ty = Type::FloatTy;
453 else if (&V.getSemantics() == &APFloat::IEEEdouble)
454 Ty = Type::DoubleTy;
455 else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
456 Ty = Type::X86_FP80Ty;
457 else if (&V.getSemantics() == &APFloat::IEEEquad)
458 Ty = Type::FP128Ty;
459 else {
460 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble &&
461 "Unknown FP format");
462 Ty = Type::PPC_FP128Ty;
463 }
464
465 return Slot = new ConstantFP(Ty, V);
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000466 }
Dale Johannesend246b2c2007-08-30 00:23:21 +0000467}
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000468
Chris Lattner98bd9392008-04-09 06:38:30 +0000469/// get() - This returns a constant fp for the specified value in the
470/// specified type. This should only be used for simple constant values like
471/// 2.0/1.0 etc, that are known-valid both as double and as the target format.
Dan Gohman7ccc52f2009-06-15 22:12:54 +0000472Constant *ConstantFP::get(const Type *Ty, double V) {
Chris Lattner98bd9392008-04-09 06:38:30 +0000473 APFloat FV(V);
Dale Johannesen4f0bd682008-10-09 23:00:39 +0000474 bool ignored;
Dan Gohman7ccc52f2009-06-15 22:12:54 +0000475 FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
476 APFloat::rmNearestTiesToEven, &ignored);
477 Constant *C = get(FV);
478
479 // For vectors, broadcast the value.
480 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
481 return
482 ConstantVector::get(std::vector<Constant *>(VTy->getNumElements(), C));
483
484 return C;
Chris Lattner98bd9392008-04-09 06:38:30 +0000485}
486
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000487//===----------------------------------------------------------------------===//
488// ConstantXXX Classes
489//===----------------------------------------------------------------------===//
490
491
Chris Lattner3462ae32001-12-03 22:26:30 +0000492ConstantArray::ConstantArray(const ArrayType *T,
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000493 const std::vector<Constant*> &V)
Gabor Greiff6caff662008-05-10 08:32:32 +0000494 : Constant(T, ConstantArrayVal,
495 OperandTraits<ConstantArray>::op_end(this) - V.size(),
496 V.size()) {
Alkis Evlogimenos0507ffe2004-09-15 02:32:15 +0000497 assert(V.size() == T->getNumElements() &&
498 "Invalid initializer vector for constant array");
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000499 Use *OL = OperandList;
Chris Lattner0144fad2005-10-03 21:56:24 +0000500 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
501 I != E; ++I, ++OL) {
Chris Lattner20a24452005-10-07 05:23:36 +0000502 Constant *C = *I;
503 assert((C->getType() == T->getElementType() ||
Alkis Evlogimenoscb031d92004-09-10 04:16:59 +0000504 (T->isAbstract() &&
Chris Lattner20a24452005-10-07 05:23:36 +0000505 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
Alkis Evlogimenoscb031d92004-09-10 04:16:59 +0000506 "Initializer for array element doesn't match array element type!");
Gabor Greif2d3024d2008-05-26 21:33:52 +0000507 *OL = C;
Chris Lattner2f7c9632001-06-06 20:29:01 +0000508 }
509}
510
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000511
Chris Lattner3462ae32001-12-03 22:26:30 +0000512ConstantStruct::ConstantStruct(const StructType *T,
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000513 const std::vector<Constant*> &V)
Gabor Greiff6caff662008-05-10 08:32:32 +0000514 : Constant(T, ConstantStructVal,
515 OperandTraits<ConstantStruct>::op_end(this) - V.size(),
516 V.size()) {
Chris Lattnerac6db752004-02-09 04:37:31 +0000517 assert(V.size() == T->getNumElements() &&
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000518 "Invalid initializer vector for constant structure");
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000519 Use *OL = OperandList;
Chris Lattner0144fad2005-10-03 21:56:24 +0000520 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
521 I != E; ++I, ++OL) {
Chris Lattner20a24452005-10-07 05:23:36 +0000522 Constant *C = *I;
523 assert((C->getType() == T->getElementType(I-V.begin()) ||
Chris Lattner0144fad2005-10-03 21:56:24 +0000524 ((T->getElementType(I-V.begin())->isAbstract() ||
Chris Lattner20a24452005-10-07 05:23:36 +0000525 C->getType()->isAbstract()) &&
Chris Lattner0144fad2005-10-03 21:56:24 +0000526 T->getElementType(I-V.begin())->getTypeID() ==
Chris Lattner20a24452005-10-07 05:23:36 +0000527 C->getType()->getTypeID())) &&
Chris Lattner93c8f142003-06-02 17:42:47 +0000528 "Initializer for struct element doesn't match struct element type!");
Gabor Greif2d3024d2008-05-26 21:33:52 +0000529 *OL = C;
Chris Lattner2f7c9632001-06-06 20:29:01 +0000530 }
531}
532
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000533
Reid Spencerd84d35b2007-02-15 02:26:10 +0000534ConstantVector::ConstantVector(const VectorType *T,
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000535 const std::vector<Constant*> &V)
Gabor Greiff6caff662008-05-10 08:32:32 +0000536 : Constant(T, ConstantVectorVal,
537 OperandTraits<ConstantVector>::op_end(this) - V.size(),
538 V.size()) {
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000539 Use *OL = OperandList;
Chris Lattner0144fad2005-10-03 21:56:24 +0000540 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
541 I != E; ++I, ++OL) {
Chris Lattner20a24452005-10-07 05:23:36 +0000542 Constant *C = *I;
543 assert((C->getType() == T->getElementType() ||
Alkis Evlogimenoscb031d92004-09-10 04:16:59 +0000544 (T->isAbstract() &&
Chris Lattner20a24452005-10-07 05:23:36 +0000545 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
Dan Gohman30978072007-05-24 14:36:04 +0000546 "Initializer for vector element doesn't match vector element type!");
Gabor Greif2d3024d2008-05-26 21:33:52 +0000547 *OL = C;
Brian Gaeke02209042004-08-20 06:00:58 +0000548 }
549}
550
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000551
Gabor Greiff6caff662008-05-10 08:32:32 +0000552namespace llvm {
Gordon Henriksen14a55692007-12-10 02:14:30 +0000553// We declare several classes private to this file, so use an anonymous
554// namespace
555namespace {
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000556
Gordon Henriksen14a55692007-12-10 02:14:30 +0000557/// UnaryConstantExpr - This class is private to Constants.cpp, and is used
558/// behind the scenes to implement unary constant exprs.
559class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
Gabor Greife9ecc682008-04-06 20:25:17 +0000560 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Gordon Henriksen14a55692007-12-10 02:14:30 +0000561public:
Gabor Greife9ecc682008-04-06 20:25:17 +0000562 // allocate space for exactly one operand
563 void *operator new(size_t s) {
564 return User::operator new(s, 1);
565 }
Gordon Henriksen14a55692007-12-10 02:14:30 +0000566 UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
Gabor Greiff6caff662008-05-10 08:32:32 +0000567 : ConstantExpr(Ty, Opcode, &Op<0>(), 1) {
568 Op<0>() = C;
569 }
570 /// Transparently provide more efficient getOperand methods.
571 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000572};
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000573
Gordon Henriksen14a55692007-12-10 02:14:30 +0000574/// BinaryConstantExpr - This class is private to Constants.cpp, and is used
575/// behind the scenes to implement binary constant exprs.
576class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
Gabor Greife9ecc682008-04-06 20:25:17 +0000577 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Gordon Henriksen14a55692007-12-10 02:14:30 +0000578public:
Gabor Greife9ecc682008-04-06 20:25:17 +0000579 // allocate space for exactly two operands
580 void *operator new(size_t s) {
581 return User::operator new(s, 2);
582 }
Gordon Henriksen14a55692007-12-10 02:14:30 +0000583 BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
Gabor Greiff6caff662008-05-10 08:32:32 +0000584 : ConstantExpr(C1->getType(), Opcode, &Op<0>(), 2) {
Gabor Greif2d3024d2008-05-26 21:33:52 +0000585 Op<0>() = C1;
586 Op<1>() = C2;
Gordon Henriksen14a55692007-12-10 02:14:30 +0000587 }
Gabor Greiff6caff662008-05-10 08:32:32 +0000588 /// Transparently provide more efficient getOperand methods.
589 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000590};
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000591
Gordon Henriksen14a55692007-12-10 02:14:30 +0000592/// SelectConstantExpr - This class is private to Constants.cpp, and is used
593/// behind the scenes to implement select constant exprs.
594class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
Gabor Greife9ecc682008-04-06 20:25:17 +0000595 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Gordon Henriksen14a55692007-12-10 02:14:30 +0000596public:
Gabor Greife9ecc682008-04-06 20:25:17 +0000597 // allocate space for exactly three operands
598 void *operator new(size_t s) {
599 return User::operator new(s, 3);
600 }
Gordon Henriksen14a55692007-12-10 02:14:30 +0000601 SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
Gabor Greiff6caff662008-05-10 08:32:32 +0000602 : ConstantExpr(C2->getType(), Instruction::Select, &Op<0>(), 3) {
Gabor Greif2d3024d2008-05-26 21:33:52 +0000603 Op<0>() = C1;
604 Op<1>() = C2;
605 Op<2>() = C3;
Gordon Henriksen14a55692007-12-10 02:14:30 +0000606 }
Gabor Greiff6caff662008-05-10 08:32:32 +0000607 /// Transparently provide more efficient getOperand methods.
608 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000609};
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000610
Gordon Henriksen14a55692007-12-10 02:14:30 +0000611/// ExtractElementConstantExpr - This class is private to
612/// Constants.cpp, and is used behind the scenes to implement
613/// extractelement constant exprs.
614class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
Gabor Greife9ecc682008-04-06 20:25:17 +0000615 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Gordon Henriksen14a55692007-12-10 02:14:30 +0000616public:
Gabor Greife9ecc682008-04-06 20:25:17 +0000617 // allocate space for exactly two operands
618 void *operator new(size_t s) {
619 return User::operator new(s, 2);
620 }
Gordon Henriksen14a55692007-12-10 02:14:30 +0000621 ExtractElementConstantExpr(Constant *C1, Constant *C2)
622 : ConstantExpr(cast<VectorType>(C1->getType())->getElementType(),
Gabor Greiff6caff662008-05-10 08:32:32 +0000623 Instruction::ExtractElement, &Op<0>(), 2) {
Gabor Greif2d3024d2008-05-26 21:33:52 +0000624 Op<0>() = C1;
625 Op<1>() = C2;
Gordon Henriksen14a55692007-12-10 02:14:30 +0000626 }
Gabor Greiff6caff662008-05-10 08:32:32 +0000627 /// Transparently provide more efficient getOperand methods.
628 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000629};
Robert Bocchino23004482006-01-10 19:05:34 +0000630
Gordon Henriksen14a55692007-12-10 02:14:30 +0000631/// InsertElementConstantExpr - This class is private to
632/// Constants.cpp, and is used behind the scenes to implement
633/// insertelement constant exprs.
634class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
Gabor Greife9ecc682008-04-06 20:25:17 +0000635 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Gordon Henriksen14a55692007-12-10 02:14:30 +0000636public:
Gabor Greife9ecc682008-04-06 20:25:17 +0000637 // allocate space for exactly three operands
638 void *operator new(size_t s) {
639 return User::operator new(s, 3);
640 }
Gordon Henriksen14a55692007-12-10 02:14:30 +0000641 InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
642 : ConstantExpr(C1->getType(), Instruction::InsertElement,
Gabor Greiff6caff662008-05-10 08:32:32 +0000643 &Op<0>(), 3) {
Gabor Greif2d3024d2008-05-26 21:33:52 +0000644 Op<0>() = C1;
645 Op<1>() = C2;
646 Op<2>() = C3;
Gordon Henriksen14a55692007-12-10 02:14:30 +0000647 }
Gabor Greiff6caff662008-05-10 08:32:32 +0000648 /// Transparently provide more efficient getOperand methods.
649 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000650};
Robert Bocchinoca27f032006-01-17 20:07:22 +0000651
Gordon Henriksen14a55692007-12-10 02:14:30 +0000652/// ShuffleVectorConstantExpr - This class is private to
653/// Constants.cpp, and is used behind the scenes to implement
654/// shufflevector constant exprs.
655class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
Gabor Greife9ecc682008-04-06 20:25:17 +0000656 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Gordon Henriksen14a55692007-12-10 02:14:30 +0000657public:
Gabor Greife9ecc682008-04-06 20:25:17 +0000658 // allocate space for exactly three operands
659 void *operator new(size_t s) {
660 return User::operator new(s, 3);
661 }
Gordon Henriksen14a55692007-12-10 02:14:30 +0000662 ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
Nate Begeman94aa38d2009-02-12 21:28:33 +0000663 : ConstantExpr(VectorType::get(
664 cast<VectorType>(C1->getType())->getElementType(),
665 cast<VectorType>(C3->getType())->getNumElements()),
666 Instruction::ShuffleVector,
Gabor Greiff6caff662008-05-10 08:32:32 +0000667 &Op<0>(), 3) {
Gabor Greif2d3024d2008-05-26 21:33:52 +0000668 Op<0>() = C1;
669 Op<1>() = C2;
670 Op<2>() = C3;
Gordon Henriksen14a55692007-12-10 02:14:30 +0000671 }
Gabor Greiff6caff662008-05-10 08:32:32 +0000672 /// Transparently provide more efficient getOperand methods.
673 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000674};
675
Dan Gohman12fce772008-05-15 19:50:34 +0000676/// ExtractValueConstantExpr - This class is private to
677/// Constants.cpp, and is used behind the scenes to implement
678/// extractvalue constant exprs.
679class VISIBILITY_HIDDEN ExtractValueConstantExpr : public ConstantExpr {
Dan Gohman1ecaf452008-05-31 00:58:22 +0000680 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Dan Gohman12fce772008-05-15 19:50:34 +0000681public:
Dan Gohman1ecaf452008-05-31 00:58:22 +0000682 // allocate space for exactly one operand
683 void *operator new(size_t s) {
684 return User::operator new(s, 1);
Dan Gohman12fce772008-05-15 19:50:34 +0000685 }
Dan Gohman1ecaf452008-05-31 00:58:22 +0000686 ExtractValueConstantExpr(Constant *Agg,
687 const SmallVector<unsigned, 4> &IdxList,
688 const Type *DestTy)
689 : ConstantExpr(DestTy, Instruction::ExtractValue, &Op<0>(), 1),
690 Indices(IdxList) {
691 Op<0>() = Agg;
692 }
693
Dan Gohman7bb04502008-05-31 19:09:08 +0000694 /// Indices - These identify which value to extract.
Dan Gohman1ecaf452008-05-31 00:58:22 +0000695 const SmallVector<unsigned, 4> Indices;
696
Dan Gohman12fce772008-05-15 19:50:34 +0000697 /// Transparently provide more efficient getOperand methods.
698 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
699};
700
701/// InsertValueConstantExpr - This class is private to
702/// Constants.cpp, and is used behind the scenes to implement
703/// insertvalue constant exprs.
704class VISIBILITY_HIDDEN InsertValueConstantExpr : public ConstantExpr {
Dan Gohman1ecaf452008-05-31 00:58:22 +0000705 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Dan Gohman12fce772008-05-15 19:50:34 +0000706public:
Dan Gohman1ecaf452008-05-31 00:58:22 +0000707 // allocate space for exactly one operand
708 void *operator new(size_t s) {
709 return User::operator new(s, 2);
Dan Gohman12fce772008-05-15 19:50:34 +0000710 }
Dan Gohman1ecaf452008-05-31 00:58:22 +0000711 InsertValueConstantExpr(Constant *Agg, Constant *Val,
712 const SmallVector<unsigned, 4> &IdxList,
713 const Type *DestTy)
714 : ConstantExpr(DestTy, Instruction::InsertValue, &Op<0>(), 2),
715 Indices(IdxList) {
716 Op<0>() = Agg;
717 Op<1>() = Val;
718 }
719
Dan Gohman7bb04502008-05-31 19:09:08 +0000720 /// Indices - These identify the position for the insertion.
Dan Gohman1ecaf452008-05-31 00:58:22 +0000721 const SmallVector<unsigned, 4> Indices;
722
Dan Gohman12fce772008-05-15 19:50:34 +0000723 /// Transparently provide more efficient getOperand methods.
724 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
725};
726
727
Gordon Henriksen14a55692007-12-10 02:14:30 +0000728/// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
729/// used behind the scenes to implement getelementpr constant exprs.
Gabor Greife9ecc682008-04-06 20:25:17 +0000730class VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
Gordon Henriksen14a55692007-12-10 02:14:30 +0000731 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
Gabor Greiff6caff662008-05-10 08:32:32 +0000732 const Type *DestTy);
Gabor Greife9ecc682008-04-06 20:25:17 +0000733public:
Gabor Greif697e94c2008-05-15 10:04:30 +0000734 static GetElementPtrConstantExpr *Create(Constant *C,
735 const std::vector<Constant*>&IdxList,
Gabor Greiff6caff662008-05-10 08:32:32 +0000736 const Type *DestTy) {
Gabor Greif697e94c2008-05-15 10:04:30 +0000737 return new(IdxList.size() + 1)
738 GetElementPtrConstantExpr(C, IdxList, DestTy);
Gabor Greife9ecc682008-04-06 20:25:17 +0000739 }
Gabor Greiff6caff662008-05-10 08:32:32 +0000740 /// Transparently provide more efficient getOperand methods.
741 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000742};
743
744// CompareConstantExpr - This class is private to Constants.cpp, and is used
745// behind the scenes to implement ICmp and FCmp constant expressions. This is
746// needed in order to store the predicate value for these instructions.
747struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
Gabor Greife9ecc682008-04-06 20:25:17 +0000748 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
749 // allocate space for exactly two operands
750 void *operator new(size_t s) {
751 return User::operator new(s, 2);
752 }
Gordon Henriksen14a55692007-12-10 02:14:30 +0000753 unsigned short predicate;
Nate Begemand2195702008-05-12 19:01:56 +0000754 CompareConstantExpr(const Type *ty, Instruction::OtherOps opc,
755 unsigned short pred, Constant* LHS, Constant* RHS)
756 : ConstantExpr(ty, opc, &Op<0>(), 2), predicate(pred) {
Gabor Greif2d3024d2008-05-26 21:33:52 +0000757 Op<0>() = LHS;
758 Op<1>() = RHS;
Gordon Henriksen14a55692007-12-10 02:14:30 +0000759 }
Gabor Greiff6caff662008-05-10 08:32:32 +0000760 /// Transparently provide more efficient getOperand methods.
761 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000762};
763
764} // end anonymous namespace
765
Gabor Greiff6caff662008-05-10 08:32:32 +0000766template <>
767struct OperandTraits<UnaryConstantExpr> : FixedNumOperandTraits<1> {
768};
769DEFINE_TRANSPARENT_OPERAND_ACCESSORS(UnaryConstantExpr, Value)
770
771template <>
772struct OperandTraits<BinaryConstantExpr> : FixedNumOperandTraits<2> {
773};
774DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BinaryConstantExpr, Value)
775
776template <>
777struct OperandTraits<SelectConstantExpr> : FixedNumOperandTraits<3> {
778};
779DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectConstantExpr, Value)
780
781template <>
782struct OperandTraits<ExtractElementConstantExpr> : FixedNumOperandTraits<2> {
783};
784DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementConstantExpr, Value)
785
786template <>
787struct OperandTraits<InsertElementConstantExpr> : FixedNumOperandTraits<3> {
788};
789DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementConstantExpr, Value)
790
791template <>
792struct OperandTraits<ShuffleVectorConstantExpr> : FixedNumOperandTraits<3> {
793};
794DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorConstantExpr, Value)
795
Dan Gohman12fce772008-05-15 19:50:34 +0000796template <>
Dan Gohman1ecaf452008-05-31 00:58:22 +0000797struct OperandTraits<ExtractValueConstantExpr> : FixedNumOperandTraits<1> {
Dan Gohman12fce772008-05-15 19:50:34 +0000798};
Dan Gohman12fce772008-05-15 19:50:34 +0000799DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractValueConstantExpr, Value)
800
801template <>
Dan Gohman1ecaf452008-05-31 00:58:22 +0000802struct OperandTraits<InsertValueConstantExpr> : FixedNumOperandTraits<2> {
Dan Gohman12fce772008-05-15 19:50:34 +0000803};
Dan Gohman12fce772008-05-15 19:50:34 +0000804DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueConstantExpr, Value)
805
Gabor Greiff6caff662008-05-10 08:32:32 +0000806template <>
807struct OperandTraits<GetElementPtrConstantExpr> : VariadicOperandTraits<1> {
808};
809
810GetElementPtrConstantExpr::GetElementPtrConstantExpr
811 (Constant *C,
812 const std::vector<Constant*> &IdxList,
813 const Type *DestTy)
814 : ConstantExpr(DestTy, Instruction::GetElementPtr,
815 OperandTraits<GetElementPtrConstantExpr>::op_end(this)
816 - (IdxList.size()+1),
817 IdxList.size()+1) {
Gabor Greif2d3024d2008-05-26 21:33:52 +0000818 OperandList[0] = C;
Gabor Greiff6caff662008-05-10 08:32:32 +0000819 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
Gabor Greif2d3024d2008-05-26 21:33:52 +0000820 OperandList[i+1] = IdxList[i];
Gabor Greiff6caff662008-05-10 08:32:32 +0000821}
822
823DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrConstantExpr, Value)
824
825
826template <>
827struct OperandTraits<CompareConstantExpr> : FixedNumOperandTraits<2> {
828};
829DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CompareConstantExpr, Value)
830
831
832} // End llvm namespace
833
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000834
835// Utility function for determining if a ConstantExpr is a CastOp or not. This
836// can't be inline because we don't want to #include Instruction.h into
837// Constant.h
838bool ConstantExpr::isCast() const {
839 return Instruction::isCast(getOpcode());
840}
841
Reid Spenceree3c9912006-12-04 05:19:50 +0000842bool ConstantExpr::isCompare() const {
Chris Lattnereab49262008-07-14 05:17:31 +0000843 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp ||
844 getOpcode() == Instruction::VICmp || getOpcode() == Instruction::VFCmp;
Reid Spenceree3c9912006-12-04 05:19:50 +0000845}
846
Dan Gohman1ecaf452008-05-31 00:58:22 +0000847bool ConstantExpr::hasIndices() const {
848 return getOpcode() == Instruction::ExtractValue ||
849 getOpcode() == Instruction::InsertValue;
850}
851
852const SmallVector<unsigned, 4> &ConstantExpr::getIndices() const {
853 if (const ExtractValueConstantExpr *EVCE =
854 dyn_cast<ExtractValueConstantExpr>(this))
855 return EVCE->Indices;
Dan Gohmana469bdb2008-06-23 16:39:44 +0000856
857 return cast<InsertValueConstantExpr>(this)->Indices;
Dan Gohman1ecaf452008-05-31 00:58:22 +0000858}
859
Chris Lattner817175f2004-03-29 02:37:53 +0000860/// ConstantExpr::get* - Return some common constants without having to
861/// specify the full Instruction::OPCODE identifier.
862///
863Constant *ConstantExpr::getNeg(Constant *C) {
Dan Gohmana5b96452009-06-04 22:49:04 +0000864 // API compatibility: Adjust integer opcodes to floating-point opcodes.
865 if (C->getType()->isFPOrFPVector())
866 return getFNeg(C);
867 assert(C->getType()->isIntOrIntVector() &&
868 "Cannot NEG a nonintegral value!");
Reid Spencer2eadb532007-01-21 00:29:26 +0000869 return get(Instruction::Sub,
870 ConstantExpr::getZeroValueForNegationExpr(C->getType()),
871 C);
Chris Lattner817175f2004-03-29 02:37:53 +0000872}
Dan Gohmana5b96452009-06-04 22:49:04 +0000873Constant *ConstantExpr::getFNeg(Constant *C) {
874 assert(C->getType()->isFPOrFPVector() &&
875 "Cannot FNEG a non-floating-point value!");
876 return get(Instruction::FSub,
877 ConstantExpr::getZeroValueForNegationExpr(C->getType()),
878 C);
879}
Chris Lattner817175f2004-03-29 02:37:53 +0000880Constant *ConstantExpr::getNot(Constant *C) {
Dan Gohmana5b96452009-06-04 22:49:04 +0000881 assert(C->getType()->isIntOrIntVector() &&
882 "Cannot NOT a nonintegral value!");
Chris Lattner817175f2004-03-29 02:37:53 +0000883 return get(Instruction::Xor, C,
Dale Johannesen47a5ef32008-08-21 21:20:09 +0000884 Constant::getAllOnesValue(C->getType()));
Chris Lattner817175f2004-03-29 02:37:53 +0000885}
886Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
887 return get(Instruction::Add, C1, C2);
888}
Dan Gohmana5b96452009-06-04 22:49:04 +0000889Constant *ConstantExpr::getFAdd(Constant *C1, Constant *C2) {
890 return get(Instruction::FAdd, C1, C2);
891}
Chris Lattner817175f2004-03-29 02:37:53 +0000892Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
893 return get(Instruction::Sub, C1, C2);
894}
Dan Gohmana5b96452009-06-04 22:49:04 +0000895Constant *ConstantExpr::getFSub(Constant *C1, Constant *C2) {
896 return get(Instruction::FSub, C1, C2);
897}
Chris Lattner817175f2004-03-29 02:37:53 +0000898Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
899 return get(Instruction::Mul, C1, C2);
900}
Dan Gohmana5b96452009-06-04 22:49:04 +0000901Constant *ConstantExpr::getFMul(Constant *C1, Constant *C2) {
902 return get(Instruction::FMul, C1, C2);
903}
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000904Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2) {
905 return get(Instruction::UDiv, C1, C2);
906}
907Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2) {
908 return get(Instruction::SDiv, C1, C2);
909}
910Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
911 return get(Instruction::FDiv, C1, C2);
Chris Lattner817175f2004-03-29 02:37:53 +0000912}
Reid Spencer7eb55b32006-11-02 01:53:59 +0000913Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
914 return get(Instruction::URem, C1, C2);
915}
916Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
917 return get(Instruction::SRem, C1, C2);
918}
919Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
920 return get(Instruction::FRem, C1, C2);
Chris Lattner817175f2004-03-29 02:37:53 +0000921}
922Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
923 return get(Instruction::And, C1, C2);
924}
925Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
926 return get(Instruction::Or, C1, C2);
927}
928Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
929 return get(Instruction::Xor, C1, C2);
930}
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000931unsigned ConstantExpr::getPredicate() const {
Nate Begemand2195702008-05-12 19:01:56 +0000932 assert(getOpcode() == Instruction::FCmp ||
933 getOpcode() == Instruction::ICmp ||
934 getOpcode() == Instruction::VFCmp ||
935 getOpcode() == Instruction::VICmp);
Chris Lattneref650092007-10-18 16:26:24 +0000936 return ((const CompareConstantExpr*)this)->predicate;
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000937}
Chris Lattner817175f2004-03-29 02:37:53 +0000938Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
939 return get(Instruction::Shl, C1, C2);
940}
Reid Spencerfdff9382006-11-08 06:47:33 +0000941Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2) {
942 return get(Instruction::LShr, C1, C2);
Chris Lattner817175f2004-03-29 02:37:53 +0000943}
Reid Spencerfdff9382006-11-08 06:47:33 +0000944Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2) {
945 return get(Instruction::AShr, C1, C2);
Chris Lattnerdb8bdba2004-05-25 05:32:43 +0000946}
Chris Lattner60e0dd72001-10-03 06:12:09 +0000947
Chris Lattner7c1018a2006-07-14 19:37:40 +0000948/// getWithOperandReplaced - Return a constant expression identical to this
949/// one, but with the specified operand set to the specified value.
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000950Constant *
951ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
Chris Lattner7c1018a2006-07-14 19:37:40 +0000952 assert(OpNo < getNumOperands() && "Operand num is out of range!");
953 assert(Op->getType() == getOperand(OpNo)->getType() &&
954 "Replacing operand with value of different type!");
Chris Lattner227816342006-07-14 22:20:01 +0000955 if (getOperand(OpNo) == Op)
956 return const_cast<ConstantExpr*>(this);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000957
Chris Lattner227816342006-07-14 22:20:01 +0000958 Constant *Op0, *Op1, *Op2;
Chris Lattner7c1018a2006-07-14 19:37:40 +0000959 switch (getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000960 case Instruction::Trunc:
961 case Instruction::ZExt:
962 case Instruction::SExt:
963 case Instruction::FPTrunc:
964 case Instruction::FPExt:
965 case Instruction::UIToFP:
966 case Instruction::SIToFP:
967 case Instruction::FPToUI:
968 case Instruction::FPToSI:
969 case Instruction::PtrToInt:
970 case Instruction::IntToPtr:
971 case Instruction::BitCast:
972 return ConstantExpr::getCast(getOpcode(), Op, getType());
Chris Lattner227816342006-07-14 22:20:01 +0000973 case Instruction::Select:
974 Op0 = (OpNo == 0) ? Op : getOperand(0);
975 Op1 = (OpNo == 1) ? Op : getOperand(1);
976 Op2 = (OpNo == 2) ? Op : getOperand(2);
977 return ConstantExpr::getSelect(Op0, Op1, Op2);
978 case Instruction::InsertElement:
979 Op0 = (OpNo == 0) ? Op : getOperand(0);
980 Op1 = (OpNo == 1) ? Op : getOperand(1);
981 Op2 = (OpNo == 2) ? Op : getOperand(2);
982 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
983 case Instruction::ExtractElement:
984 Op0 = (OpNo == 0) ? Op : getOperand(0);
985 Op1 = (OpNo == 1) ? Op : getOperand(1);
986 return ConstantExpr::getExtractElement(Op0, Op1);
987 case Instruction::ShuffleVector:
988 Op0 = (OpNo == 0) ? Op : getOperand(0);
989 Op1 = (OpNo == 1) ? Op : getOperand(1);
990 Op2 = (OpNo == 2) ? Op : getOperand(2);
991 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000992 case Instruction::GetElementPtr: {
Chris Lattnerb5d70302007-02-19 20:01:23 +0000993 SmallVector<Constant*, 8> Ops;
Dan Gohman12fce772008-05-15 19:50:34 +0000994 Ops.resize(getNumOperands()-1);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000995 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
Dan Gohman12fce772008-05-15 19:50:34 +0000996 Ops[i-1] = getOperand(i);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000997 if (OpNo == 0)
Chris Lattnerb5d70302007-02-19 20:01:23 +0000998 return ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
Chris Lattner7c1018a2006-07-14 19:37:40 +0000999 Ops[OpNo-1] = Op;
Chris Lattnerb5d70302007-02-19 20:01:23 +00001000 return ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
Chris Lattner7c1018a2006-07-14 19:37:40 +00001001 }
Chris Lattner7c1018a2006-07-14 19:37:40 +00001002 default:
1003 assert(getNumOperands() == 2 && "Must be binary operator?");
Chris Lattner227816342006-07-14 22:20:01 +00001004 Op0 = (OpNo == 0) ? Op : getOperand(0);
1005 Op1 = (OpNo == 1) ? Op : getOperand(1);
1006 return ConstantExpr::get(getOpcode(), Op0, Op1);
1007 }
1008}
1009
1010/// getWithOperands - This returns the current constant expression with the
1011/// operands replaced with the specified values. The specified operands must
1012/// match count and type with the existing ones.
1013Constant *ConstantExpr::
Chris Lattnerb078e282008-08-20 22:27:40 +00001014getWithOperands(Constant* const *Ops, unsigned NumOps) const {
1015 assert(NumOps == getNumOperands() && "Operand count mismatch!");
Chris Lattner227816342006-07-14 22:20:01 +00001016 bool AnyChange = false;
Chris Lattnerb078e282008-08-20 22:27:40 +00001017 for (unsigned i = 0; i != NumOps; ++i) {
Chris Lattner227816342006-07-14 22:20:01 +00001018 assert(Ops[i]->getType() == getOperand(i)->getType() &&
1019 "Operand type mismatch!");
1020 AnyChange |= Ops[i] != getOperand(i);
1021 }
1022 if (!AnyChange) // No operands changed, return self.
1023 return const_cast<ConstantExpr*>(this);
1024
1025 switch (getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001026 case Instruction::Trunc:
1027 case Instruction::ZExt:
1028 case Instruction::SExt:
1029 case Instruction::FPTrunc:
1030 case Instruction::FPExt:
1031 case Instruction::UIToFP:
1032 case Instruction::SIToFP:
1033 case Instruction::FPToUI:
1034 case Instruction::FPToSI:
1035 case Instruction::PtrToInt:
1036 case Instruction::IntToPtr:
1037 case Instruction::BitCast:
1038 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
Chris Lattner227816342006-07-14 22:20:01 +00001039 case Instruction::Select:
1040 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
1041 case Instruction::InsertElement:
1042 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
1043 case Instruction::ExtractElement:
1044 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
1045 case Instruction::ShuffleVector:
1046 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
Chris Lattnerb5d70302007-02-19 20:01:23 +00001047 case Instruction::GetElementPtr:
Chris Lattnerb078e282008-08-20 22:27:40 +00001048 return ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], NumOps-1);
Reid Spencer266e42b2006-12-23 06:05:41 +00001049 case Instruction::ICmp:
1050 case Instruction::FCmp:
Nate Begeman098cc6f2008-07-25 17:56:27 +00001051 case Instruction::VICmp:
1052 case Instruction::VFCmp:
Reid Spencer266e42b2006-12-23 06:05:41 +00001053 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
Chris Lattner227816342006-07-14 22:20:01 +00001054 default:
1055 assert(getNumOperands() == 2 && "Must be binary operator?");
1056 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
Chris Lattner7c1018a2006-07-14 19:37:40 +00001057 }
1058}
1059
Chris Lattner2f7c9632001-06-06 20:29:01 +00001060
1061//===----------------------------------------------------------------------===//
Chris Lattner2f7c9632001-06-06 20:29:01 +00001062// isValueValidForType implementations
1063
Reid Spencere7334722006-12-19 01:28:19 +00001064bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001065 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001066 if (Ty == Type::Int1Ty)
1067 return Val == 0 || Val == 1;
Reid Spencerd7a00d72007-02-05 23:47:56 +00001068 if (NumBits >= 64)
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001069 return true; // always true, has to fit in largest type
1070 uint64_t Max = (1ll << NumBits) - 1;
1071 return Val <= Max;
Reid Spencere7334722006-12-19 01:28:19 +00001072}
1073
Reid Spencere0fc4df2006-10-20 07:07:24 +00001074bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001075 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001076 if (Ty == Type::Int1Ty)
Reid Spencera94d3942007-01-19 21:13:56 +00001077 return Val == 0 || Val == 1 || Val == -1;
Reid Spencerd7a00d72007-02-05 23:47:56 +00001078 if (NumBits >= 64)
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001079 return true; // always true, has to fit in largest type
1080 int64_t Min = -(1ll << (NumBits-1));
1081 int64_t Max = (1ll << (NumBits-1)) - 1;
1082 return (Val >= Min && Val <= Max);
Chris Lattner2f7c9632001-06-06 20:29:01 +00001083}
1084
Dale Johannesend246b2c2007-08-30 00:23:21 +00001085bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
1086 // convert modifies in place, so make a copy.
1087 APFloat Val2 = APFloat(Val);
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001088 bool losesInfo;
Chris Lattner6b727592004-06-17 18:19:28 +00001089 switch (Ty->getTypeID()) {
Chris Lattner2f7c9632001-06-06 20:29:01 +00001090 default:
1091 return false; // These can't be represented as floating point!
1092
Dale Johannesend246b2c2007-08-30 00:23:21 +00001093 // FIXME rounding mode needs to be more flexible
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001094 case Type::FloatTyID: {
1095 if (&Val2.getSemantics() == &APFloat::IEEEsingle)
1096 return true;
1097 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
1098 return !losesInfo;
1099 }
1100 case Type::DoubleTyID: {
1101 if (&Val2.getSemantics() == &APFloat::IEEEsingle ||
1102 &Val2.getSemantics() == &APFloat::IEEEdouble)
1103 return true;
1104 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
1105 return !losesInfo;
1106 }
Dale Johannesenbdad8092007-08-09 22:51:36 +00001107 case Type::X86_FP80TyID:
Dale Johannesen028084e2007-09-12 03:30:33 +00001108 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
1109 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1110 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
Dale Johannesenbdad8092007-08-09 22:51:36 +00001111 case Type::FP128TyID:
Dale Johannesen028084e2007-09-12 03:30:33 +00001112 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
1113 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1114 &Val2.getSemantics() == &APFloat::IEEEquad;
Dale Johannesen007aa372007-10-11 18:07:22 +00001115 case Type::PPC_FP128TyID:
1116 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
1117 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1118 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
Chris Lattner2f7c9632001-06-06 20:29:01 +00001119 }
Chris Lattneraa2372562006-05-24 17:04:05 +00001120}
Chris Lattner9655e542001-07-20 19:16:02 +00001121
Chris Lattner49d855c2001-09-07 16:46:31 +00001122//===----------------------------------------------------------------------===//
Chris Lattner49d855c2001-09-07 16:46:31 +00001123// Factory Function Implementation
1124
Gabor Greiff6caff662008-05-10 08:32:32 +00001125
1126// The number of operands for each ConstantCreator::create method is
1127// determined by the ConstantTraits template.
Chris Lattner98fa07b2003-05-23 20:03:32 +00001128// ConstantCreator - A class that is used to create constants by
1129// ValueMap*. This class should be partially specialized if there is
1130// something strange that needs to be done to interface to the ctor for the
1131// constant.
1132//
Chris Lattner189d19f2003-11-21 20:23:48 +00001133namespace llvm {
Gabor Greiff6caff662008-05-10 08:32:32 +00001134 template<class ValType>
1135 struct ConstantTraits;
1136
1137 template<typename T, typename Alloc>
1138 struct VISIBILITY_HIDDEN ConstantTraits< std::vector<T, Alloc> > {
1139 static unsigned uses(const std::vector<T, Alloc>& v) {
1140 return v.size();
1141 }
1142 };
1143
Chris Lattner189d19f2003-11-21 20:23:48 +00001144 template<class ConstantClass, class TypeClass, class ValType>
Chris Lattner02157b02006-06-28 21:38:54 +00001145 struct VISIBILITY_HIDDEN ConstantCreator {
Chris Lattner189d19f2003-11-21 20:23:48 +00001146 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
Gabor Greiff6caff662008-05-10 08:32:32 +00001147 return new(ConstantTraits<ValType>::uses(V)) ConstantClass(Ty, V);
Chris Lattner189d19f2003-11-21 20:23:48 +00001148 }
1149 };
Misha Brukmanb1c93172005-04-21 23:48:37 +00001150
Chris Lattner189d19f2003-11-21 20:23:48 +00001151 template<class ConstantClass, class TypeClass>
Chris Lattner02157b02006-06-28 21:38:54 +00001152 struct VISIBILITY_HIDDEN ConvertConstantType {
Chris Lattner189d19f2003-11-21 20:23:48 +00001153 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
1154 assert(0 && "This type cannot be converted!\n");
1155 abort();
1156 }
1157 };
Chris Lattnerb50d1352003-10-05 00:17:43 +00001158
Chris Lattner935aa922005-10-04 17:48:46 +00001159 template<class ValType, class TypeClass, class ConstantClass,
1160 bool HasLargeKey = false /*true for arrays and structs*/ >
Chris Lattner02157b02006-06-28 21:38:54 +00001161 class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
Chris Lattnerb64419a2005-10-03 22:51:37 +00001162 public:
Jim Laskeyc03caef2006-07-17 17:38:29 +00001163 typedef std::pair<const Type*, ValType> MapKey;
1164 typedef std::map<MapKey, Constant *> MapTy;
1165 typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
1166 typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
Chris Lattnerb64419a2005-10-03 22:51:37 +00001167 private:
Chris Lattner5bbf60a52005-10-04 16:52:46 +00001168 /// Map - This is the main map from the element descriptor to the Constants.
1169 /// This is the primary way we avoid creating two of the same shape
1170 /// constant.
Chris Lattnerb50d1352003-10-05 00:17:43 +00001171 MapTy Map;
Chris Lattner935aa922005-10-04 17:48:46 +00001172
1173 /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
1174 /// from the constants to their element in Map. This is important for
1175 /// removal of constants from the array, which would otherwise have to scan
1176 /// through the map with very large keys.
Jim Laskeyc03caef2006-07-17 17:38:29 +00001177 InverseMapTy InverseMap;
Chris Lattnerb50d1352003-10-05 00:17:43 +00001178
Jim Laskeyc03caef2006-07-17 17:38:29 +00001179 /// AbstractTypeMap - Map for abstract type constants.
1180 ///
Chris Lattnerb50d1352003-10-05 00:17:43 +00001181 AbstractTypeMapTy AbstractTypeMap;
Chris Lattner99a669b2004-11-19 16:39:44 +00001182
Chris Lattner98fa07b2003-05-23 20:03:32 +00001183 public:
Owen Anderson61794042009-06-17 20:10:08 +00001184 // NOTE: This function is not locked. It is the caller's responsibility
1185 // to enforce proper synchronization.
Jim Laskeyc03caef2006-07-17 17:38:29 +00001186 typename MapTy::iterator map_end() { return Map.end(); }
Chris Lattnerb64419a2005-10-03 22:51:37 +00001187
1188 /// InsertOrGetItem - Return an iterator for the specified element.
1189 /// If the element exists in the map, the returned iterator points to the
1190 /// entry and Exists=true. If not, the iterator points to the newly
1191 /// inserted entry and returns Exists=false. Newly inserted entries have
1192 /// I->second == 0, and should be filled in.
Owen Anderson61794042009-06-17 20:10:08 +00001193 /// NOTE: This function is not locked. It is the caller's responsibility
1194 // to enforce proper synchronization.
Jim Laskeyc03caef2006-07-17 17:38:29 +00001195 typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
1196 &InsertVal,
Chris Lattnerb64419a2005-10-03 22:51:37 +00001197 bool &Exists) {
Jim Laskeyc03caef2006-07-17 17:38:29 +00001198 std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
Chris Lattnerb64419a2005-10-03 22:51:37 +00001199 Exists = !IP.second;
1200 return IP.first;
1201 }
Chris Lattner5bbf60a52005-10-04 16:52:46 +00001202
Chris Lattner935aa922005-10-04 17:48:46 +00001203private:
Jim Laskeyc03caef2006-07-17 17:38:29 +00001204 typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
Chris Lattner935aa922005-10-04 17:48:46 +00001205 if (HasLargeKey) {
Jim Laskeyc03caef2006-07-17 17:38:29 +00001206 typename InverseMapTy::iterator IMI = InverseMap.find(CP);
Chris Lattner935aa922005-10-04 17:48:46 +00001207 assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
1208 IMI->second->second == CP &&
1209 "InverseMap corrupt!");
1210 return IMI->second;
1211 }
1212
Jim Laskeyc03caef2006-07-17 17:38:29 +00001213 typename MapTy::iterator I =
Dan Gohmane955c482008-08-05 14:45:15 +00001214 Map.find(MapKey(static_cast<const TypeClass*>(CP->getRawType()),
1215 getValType(CP)));
Chris Lattner5bbf60a52005-10-04 16:52:46 +00001216 if (I == Map.end() || I->second != CP) {
1217 // FIXME: This should not use a linear scan. If this gets to be a
1218 // performance problem, someone should look at this.
1219 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
1220 /* empty */;
1221 }
Chris Lattner935aa922005-10-04 17:48:46 +00001222 return I;
1223 }
Owen Andersonf89c38c2009-06-17 20:43:39 +00001224
1225 ConstantClass* Create(const TypeClass *Ty, const ValType &V,
1226 typename MapTy::iterator I) {
1227 ConstantClass* Result =
1228 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
1229
1230 assert(Result->getType() == Ty && "Type specified is not correct!");
1231 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
1232
1233 if (HasLargeKey) // Remember the reverse mapping if needed.
1234 InverseMap.insert(std::make_pair(Result, I));
1235
1236 // If the type of the constant is abstract, make sure that an entry
1237 // exists for it in the AbstractTypeMap.
1238 if (Ty->isAbstract()) {
1239 typename AbstractTypeMapTy::iterator TI =
1240 AbstractTypeMap.find(Ty);
1241
1242 if (TI == AbstractTypeMap.end()) {
1243 // Add ourselves to the ATU list of the type.
1244 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
1245
1246 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
1247 }
1248 }
1249
1250 return Result;
1251 }
Chris Lattner935aa922005-10-04 17:48:46 +00001252public:
1253
Chris Lattnerb64419a2005-10-03 22:51:37 +00001254 /// getOrCreate - Return the specified constant from the map, creating it if
1255 /// necessary.
Chris Lattner98fa07b2003-05-23 20:03:32 +00001256 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
Chris Lattnerb50d1352003-10-05 00:17:43 +00001257 MapKey Lookup(Ty, V);
Owen Anderson61794042009-06-17 20:10:08 +00001258 if (llvm_is_multithreaded()) {
1259 ConstantClass* Result = 0;
1260
1261 ConstantsLock->reader_acquire();
1262 typename MapTy::iterator I = Map.find(Lookup);
1263 // Is it in the map?
1264 if (I != Map.end())
1265 Result = static_cast<ConstantClass *>(I->second);
1266 ConstantsLock->reader_release();
1267
1268 if (!Result) {
Owen Anderson65c5cd72009-06-17 20:34:43 +00001269 sys::ScopedWriter Writer(&*ConstantsLock);
Owen Anderson61794042009-06-17 20:10:08 +00001270 I = Map.find(Lookup);
1271 // Is it in the map?
1272 if (I != Map.end())
1273 Result = static_cast<ConstantClass *>(I->second);
1274 if (!Result) {
1275 // If no preexisting value, create one now...
Owen Andersonf89c38c2009-06-17 20:43:39 +00001276 Result = Create(Ty, V, I);
Owen Anderson61794042009-06-17 20:10:08 +00001277 }
Chris Lattnerb50d1352003-10-05 00:17:43 +00001278 }
Owen Anderson61794042009-06-17 20:10:08 +00001279
1280 return Result;
1281 } else {
1282 typename MapTy::iterator I = Map.find(Lookup);
1283 // Is it in the map?
1284 if (I != Map.end())
1285 return static_cast<ConstantClass *>(I->second);
1286
1287 // If no preexisting value, create one now...
Owen Andersonf89c38c2009-06-17 20:43:39 +00001288 return Create(Ty, V, I);
Chris Lattnerb50d1352003-10-05 00:17:43 +00001289 }
Chris Lattner98fa07b2003-05-23 20:03:32 +00001290 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001291
Chris Lattner98fa07b2003-05-23 20:03:32 +00001292 void remove(ConstantClass *CP) {
Owen Anderson61794042009-06-17 20:10:08 +00001293 if (llvm_is_multithreaded()) ConstantsLock->writer_acquire();
Jim Laskeyc03caef2006-07-17 17:38:29 +00001294 typename MapTy::iterator I = FindExistingElement(CP);
Chris Lattnerb50d1352003-10-05 00:17:43 +00001295 assert(I != Map.end() && "Constant not found in constant table!");
Chris Lattner3e650af2004-08-04 04:48:01 +00001296 assert(I->second == CP && "Didn't find correct element?");
Chris Lattnerb50d1352003-10-05 00:17:43 +00001297
Chris Lattner935aa922005-10-04 17:48:46 +00001298 if (HasLargeKey) // Remember the reverse mapping if needed.
1299 InverseMap.erase(CP);
1300
Chris Lattnerb50d1352003-10-05 00:17:43 +00001301 // Now that we found the entry, make sure this isn't the entry that
1302 // the AbstractTypeMap points to.
Jim Laskeyc03caef2006-07-17 17:38:29 +00001303 const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
Chris Lattnerb50d1352003-10-05 00:17:43 +00001304 if (Ty->isAbstract()) {
1305 assert(AbstractTypeMap.count(Ty) &&
1306 "Abstract type not in AbstractTypeMap?");
Jim Laskeyc03caef2006-07-17 17:38:29 +00001307 typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
Chris Lattnerb50d1352003-10-05 00:17:43 +00001308 if (ATMEntryIt == I) {
1309 // Yes, we are removing the representative entry for this type.
1310 // See if there are any other entries of the same type.
Jim Laskeyc03caef2006-07-17 17:38:29 +00001311 typename MapTy::iterator TmpIt = ATMEntryIt;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001312
Chris Lattnerb50d1352003-10-05 00:17:43 +00001313 // First check the entry before this one...
1314 if (TmpIt != Map.begin()) {
1315 --TmpIt;
1316 if (TmpIt->first.first != Ty) // Not the same type, move back...
1317 ++TmpIt;
1318 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001319
Chris Lattnerb50d1352003-10-05 00:17:43 +00001320 // If we didn't find the same type, try to move forward...
1321 if (TmpIt == ATMEntryIt) {
1322 ++TmpIt;
1323 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
1324 --TmpIt; // No entry afterwards with the same type
1325 }
1326
1327 // If there is another entry in the map of the same abstract type,
1328 // update the AbstractTypeMap entry now.
1329 if (TmpIt != ATMEntryIt) {
1330 ATMEntryIt = TmpIt;
1331 } else {
1332 // Otherwise, we are removing the last instance of this type
1333 // from the table. Remove from the ATM, and from user list.
1334 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
1335 AbstractTypeMap.erase(Ty);
1336 }
Chris Lattner98fa07b2003-05-23 20:03:32 +00001337 }
Chris Lattnerb50d1352003-10-05 00:17:43 +00001338 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001339
Chris Lattnerb50d1352003-10-05 00:17:43 +00001340 Map.erase(I);
Owen Anderson61794042009-06-17 20:10:08 +00001341
1342 if (llvm_is_multithreaded()) ConstantsLock->writer_release();
Chris Lattnerb50d1352003-10-05 00:17:43 +00001343 }
1344
Chris Lattner3b793c62005-10-04 21:35:50 +00001345
1346 /// MoveConstantToNewSlot - If we are about to change C to be the element
1347 /// specified by I, update our internal data structures to reflect this
1348 /// fact.
Owen Anderson61794042009-06-17 20:10:08 +00001349 /// NOTE: This function is not locked. It is the responsibility of the
1350 /// caller to enforce proper synchronization if using this method.
Jim Laskeyc03caef2006-07-17 17:38:29 +00001351 void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
Chris Lattner3b793c62005-10-04 21:35:50 +00001352 // First, remove the old location of the specified constant in the map.
Jim Laskeyc03caef2006-07-17 17:38:29 +00001353 typename MapTy::iterator OldI = FindExistingElement(C);
Chris Lattner3b793c62005-10-04 21:35:50 +00001354 assert(OldI != Map.end() && "Constant not found in constant table!");
1355 assert(OldI->second == C && "Didn't find correct element?");
1356
1357 // If this constant is the representative element for its abstract type,
1358 // update the AbstractTypeMap so that the representative element is I.
1359 if (C->getType()->isAbstract()) {
1360 typename AbstractTypeMapTy::iterator ATI =
1361 AbstractTypeMap.find(C->getType());
1362 assert(ATI != AbstractTypeMap.end() &&
1363 "Abstract type not in AbstractTypeMap?");
1364 if (ATI->second == OldI)
1365 ATI->second = I;
1366 }
1367
1368 // Remove the old entry from the map.
1369 Map.erase(OldI);
1370
1371 // Update the inverse map so that we know that this constant is now
1372 // located at descriptor I.
1373 if (HasLargeKey) {
1374 assert(I->second == C && "Bad inversemap entry!");
1375 InverseMap[C] = I;
1376 }
1377 }
1378
Chris Lattnerb50d1352003-10-05 00:17:43 +00001379 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
Owen Anderson61794042009-06-17 20:10:08 +00001380 if (llvm_is_multithreaded()) ConstantsLock->writer_acquire();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001381 typename AbstractTypeMapTy::iterator I =
Jim Laskeyc03caef2006-07-17 17:38:29 +00001382 AbstractTypeMap.find(cast<Type>(OldTy));
Chris Lattnerb50d1352003-10-05 00:17:43 +00001383
1384 assert(I != AbstractTypeMap.end() &&
1385 "Abstract type not in AbstractTypeMap?");
1386
1387 // Convert a constant at a time until the last one is gone. The last one
1388 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
1389 // eliminated eventually.
1390 do {
1391 ConvertConstantType<ConstantClass,
Jim Laskeyc03caef2006-07-17 17:38:29 +00001392 TypeClass>::convert(
1393 static_cast<ConstantClass *>(I->second->second),
Chris Lattnerb50d1352003-10-05 00:17:43 +00001394 cast<TypeClass>(NewTy));
1395
Jim Laskeyc03caef2006-07-17 17:38:29 +00001396 I = AbstractTypeMap.find(cast<Type>(OldTy));
Chris Lattnerb50d1352003-10-05 00:17:43 +00001397 } while (I != AbstractTypeMap.end());
Owen Anderson61794042009-06-17 20:10:08 +00001398
1399 if (llvm_is_multithreaded()) ConstantsLock->writer_release();
Chris Lattnerb50d1352003-10-05 00:17:43 +00001400 }
1401
1402 // If the type became concrete without being refined to any other existing
1403 // type, we just remove ourselves from the ATU list.
1404 void typeBecameConcrete(const DerivedType *AbsTy) {
Owen Anderson65c5cd72009-06-17 20:34:43 +00001405 if (llvm_is_multithreaded()) {
1406 sys::ScopedWriter Writer(&*ConstantsLock);
1407 AbsTy->removeAbstractTypeUser(this);
1408 } else
1409 AbsTy->removeAbstractTypeUser(this);
Chris Lattnerb50d1352003-10-05 00:17:43 +00001410 }
1411
1412 void dump() const {
Bill Wendling6a462f12006-11-17 08:03:48 +00001413 DOUT << "Constant.cpp: ValueMap\n";
Chris Lattner98fa07b2003-05-23 20:03:32 +00001414 }
1415 };
1416}
1417
Chris Lattnera84df0a22006-09-28 23:36:21 +00001418
Chris Lattner28173502007-02-20 06:11:36 +00001419
Chris Lattner9fba3da2004-02-15 05:53:04 +00001420//---- ConstantAggregateZero::get() implementation...
1421//
1422namespace llvm {
1423 // ConstantAggregateZero does not take extra "value" argument...
1424 template<class ValType>
1425 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
1426 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
1427 return new ConstantAggregateZero(Ty);
1428 }
1429 };
1430
1431 template<>
1432 struct ConvertConstantType<ConstantAggregateZero, Type> {
1433 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
1434 // Make everyone now use a constant of the new type...
1435 Constant *New = ConstantAggregateZero::get(NewTy);
1436 assert(New != OldC && "Didn't replace constant??");
1437 OldC->uncheckedReplaceAllUsesWith(New);
1438 OldC->destroyConstant(); // This constant is now dead, destroy it.
1439 }
1440 };
1441}
1442
Chris Lattner69edc982006-09-28 00:35:06 +00001443static ManagedStatic<ValueMap<char, Type,
1444 ConstantAggregateZero> > AggZeroConstants;
Chris Lattner9fba3da2004-02-15 05:53:04 +00001445
Chris Lattner3e650af2004-08-04 04:48:01 +00001446static char getValType(ConstantAggregateZero *CPZ) { return 0; }
1447
Dan Gohman8214fc12008-12-08 07:10:54 +00001448ConstantAggregateZero *ConstantAggregateZero::get(const Type *Ty) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001449 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) &&
Chris Lattnerbfd0b6d2006-06-10 04:16:23 +00001450 "Cannot create an aggregate zero of non-aggregate type!");
Owen Anderson61794042009-06-17 20:10:08 +00001451
1452 // Implicitly locked.
1453 return AggZeroConstants->getOrCreate(Ty, 0);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001454}
1455
Dan Gohman92b551b2009-03-03 02:55:14 +00001456/// destroyConstant - Remove the constant from the constant table...
1457///
Chris Lattner9fba3da2004-02-15 05:53:04 +00001458void ConstantAggregateZero::destroyConstant() {
Owen Anderson61794042009-06-17 20:10:08 +00001459 // Implicitly locked.
Chris Lattner69edc982006-09-28 00:35:06 +00001460 AggZeroConstants->remove(this);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001461 destroyConstantImpl();
1462}
1463
Chris Lattner3462ae32001-12-03 22:26:30 +00001464//---- ConstantArray::get() implementation...
Chris Lattner49d855c2001-09-07 16:46:31 +00001465//
Chris Lattner189d19f2003-11-21 20:23:48 +00001466namespace llvm {
1467 template<>
1468 struct ConvertConstantType<ConstantArray, ArrayType> {
1469 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
1470 // Make everyone now use a constant of the new type...
1471 std::vector<Constant*> C;
1472 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1473 C.push_back(cast<Constant>(OldC->getOperand(i)));
1474 Constant *New = ConstantArray::get(NewTy, C);
1475 assert(New != OldC && "Didn't replace constant??");
1476 OldC->uncheckedReplaceAllUsesWith(New);
1477 OldC->destroyConstant(); // This constant is now dead, destroy it.
1478 }
1479 };
1480}
Chris Lattnerb50d1352003-10-05 00:17:43 +00001481
Chris Lattner3e650af2004-08-04 04:48:01 +00001482static std::vector<Constant*> getValType(ConstantArray *CA) {
1483 std::vector<Constant*> Elements;
1484 Elements.reserve(CA->getNumOperands());
1485 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1486 Elements.push_back(cast<Constant>(CA->getOperand(i)));
1487 return Elements;
1488}
1489
Chris Lattnerb64419a2005-10-03 22:51:37 +00001490typedef ValueMap<std::vector<Constant*>, ArrayType,
Chris Lattner935aa922005-10-04 17:48:46 +00001491 ConstantArray, true /*largekey*/> ArrayConstantsTy;
Chris Lattner69edc982006-09-28 00:35:06 +00001492static ManagedStatic<ArrayConstantsTy> ArrayConstants;
Chris Lattner49d855c2001-09-07 16:46:31 +00001493
Chris Lattner015e8212004-02-15 04:14:47 +00001494Constant *ConstantArray::get(const ArrayType *Ty,
Chris Lattner9fba3da2004-02-15 05:53:04 +00001495 const std::vector<Constant*> &V) {
1496 // If this is an all-zero array, return a ConstantAggregateZero object
1497 if (!V.empty()) {
1498 Constant *C = V[0];
Owen Anderson2d7231d2009-06-17 18:40:29 +00001499 if (!C->isNullValue()) {
Owen Anderson61794042009-06-17 20:10:08 +00001500 // Implicitly locked.
Chris Lattner69edc982006-09-28 00:35:06 +00001501 return ArrayConstants->getOrCreate(Ty, V);
Owen Anderson2d7231d2009-06-17 18:40:29 +00001502 }
Chris Lattner9fba3da2004-02-15 05:53:04 +00001503 for (unsigned i = 1, e = V.size(); i != e; ++i)
Owen Anderson2d7231d2009-06-17 18:40:29 +00001504 if (V[i] != C) {
Owen Anderson61794042009-06-17 20:10:08 +00001505 // Implicitly locked.
Chris Lattner69edc982006-09-28 00:35:06 +00001506 return ArrayConstants->getOrCreate(Ty, V);
Owen Anderson2d7231d2009-06-17 18:40:29 +00001507 }
Chris Lattner9fba3da2004-02-15 05:53:04 +00001508 }
Owen Anderson2d7231d2009-06-17 18:40:29 +00001509
Chris Lattner9fba3da2004-02-15 05:53:04 +00001510 return ConstantAggregateZero::get(Ty);
Chris Lattner49d855c2001-09-07 16:46:31 +00001511}
1512
Dan Gohman92b551b2009-03-03 02:55:14 +00001513/// destroyConstant - Remove the constant from the constant table...
1514///
Chris Lattner98fa07b2003-05-23 20:03:32 +00001515void ConstantArray::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001516 ArrayConstants->remove(this);
Chris Lattner98fa07b2003-05-23 20:03:32 +00001517 destroyConstantImpl();
1518}
1519
Reid Spencer6f614532006-05-30 08:23:18 +00001520/// ConstantArray::get(const string&) - Return an array that is initialized to
1521/// contain the specified string. If length is zero then a null terminator is
1522/// added to the specified string so that it may be used in a natural way.
1523/// Otherwise, the length parameter specifies how much of the string to use
1524/// and it won't be null terminated.
1525///
Reid Spencer82ebaba2006-05-30 18:15:07 +00001526Constant *ConstantArray::get(const std::string &Str, bool AddNull) {
Chris Lattner7f74a562002-01-20 22:54:45 +00001527 std::vector<Constant*> ElementVals;
Reid Spencer82ebaba2006-05-30 18:15:07 +00001528 for (unsigned i = 0; i < Str.length(); ++i)
Reid Spencer8d9336d2006-12-31 05:26:44 +00001529 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, Str[i]));
Chris Lattner8f80fe02001-10-14 23:54:12 +00001530
1531 // Add a null terminator to the string...
Reid Spencer82ebaba2006-05-30 18:15:07 +00001532 if (AddNull) {
Reid Spencer8d9336d2006-12-31 05:26:44 +00001533 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, 0));
Reid Spencer6f614532006-05-30 08:23:18 +00001534 }
Chris Lattner8f80fe02001-10-14 23:54:12 +00001535
Reid Spencer8d9336d2006-12-31 05:26:44 +00001536 ArrayType *ATy = ArrayType::get(Type::Int8Ty, ElementVals.size());
Chris Lattner3462ae32001-12-03 22:26:30 +00001537 return ConstantArray::get(ATy, ElementVals);
Vikram S. Adve34410432001-10-14 23:17:20 +00001538}
1539
Reid Spencer2546b762007-01-26 07:37:34 +00001540/// isString - This method returns true if the array is an array of i8, and
1541/// if the elements of the array are all ConstantInt's.
Chris Lattnere8dfcca2004-01-14 17:06:38 +00001542bool ConstantArray::isString() const {
Reid Spencer2546b762007-01-26 07:37:34 +00001543 // Check the element type for i8...
Reid Spencer8d9336d2006-12-31 05:26:44 +00001544 if (getType()->getElementType() != Type::Int8Ty)
Chris Lattnere8dfcca2004-01-14 17:06:38 +00001545 return false;
1546 // Check the elements to make sure they are all integers, not constant
1547 // expressions.
1548 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1549 if (!isa<ConstantInt>(getOperand(i)))
1550 return false;
1551 return true;
1552}
1553
Evan Cheng3763c5b2006-10-26 19:15:05 +00001554/// isCString - This method returns true if the array is a string (see
Dan Gohman92b551b2009-03-03 02:55:14 +00001555/// isString) and it ends in a null byte \\0 and does not contains any other
Evan Cheng3763c5b2006-10-26 19:15:05 +00001556/// null bytes except its terminator.
1557bool ConstantArray::isCString() const {
Reid Spencer2546b762007-01-26 07:37:34 +00001558 // Check the element type for i8...
Reid Spencer8d9336d2006-12-31 05:26:44 +00001559 if (getType()->getElementType() != Type::Int8Ty)
Evan Chenge974da62006-10-26 21:48:03 +00001560 return false;
1561 Constant *Zero = Constant::getNullValue(getOperand(0)->getType());
1562 // Last element must be a null.
1563 if (getOperand(getNumOperands()-1) != Zero)
1564 return false;
1565 // Other elements must be non-null integers.
1566 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1567 if (!isa<ConstantInt>(getOperand(i)))
Evan Cheng3763c5b2006-10-26 19:15:05 +00001568 return false;
Evan Chenge974da62006-10-26 21:48:03 +00001569 if (getOperand(i) == Zero)
1570 return false;
1571 }
Evan Cheng3763c5b2006-10-26 19:15:05 +00001572 return true;
1573}
1574
1575
Dan Gohman92b551b2009-03-03 02:55:14 +00001576/// getAsString - If the sub-element type of this array is i8
1577/// then this method converts the array to an std::string and returns it.
1578/// Otherwise, it asserts out.
1579///
Chris Lattner81fabb02002-08-26 17:53:56 +00001580std::string ConstantArray::getAsString() const {
Chris Lattnere8dfcca2004-01-14 17:06:38 +00001581 assert(isString() && "Not a string!");
Chris Lattner81fabb02002-08-26 17:53:56 +00001582 std::string Result;
Owen Anderson79c69bc2008-06-24 21:58:29 +00001583 Result.reserve(getNumOperands());
Chris Lattner6077c312003-07-23 15:22:26 +00001584 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
Owen Andersonee9c30d2008-06-25 01:05:05 +00001585 Result.push_back((char)cast<ConstantInt>(getOperand(i))->getZExtValue());
Chris Lattner81fabb02002-08-26 17:53:56 +00001586 return Result;
1587}
1588
1589
Chris Lattner3462ae32001-12-03 22:26:30 +00001590//---- ConstantStruct::get() implementation...
Chris Lattner49d855c2001-09-07 16:46:31 +00001591//
Chris Lattnerb50d1352003-10-05 00:17:43 +00001592
Chris Lattner189d19f2003-11-21 20:23:48 +00001593namespace llvm {
1594 template<>
1595 struct ConvertConstantType<ConstantStruct, StructType> {
1596 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1597 // Make everyone now use a constant of the new type...
1598 std::vector<Constant*> C;
1599 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1600 C.push_back(cast<Constant>(OldC->getOperand(i)));
1601 Constant *New = ConstantStruct::get(NewTy, C);
1602 assert(New != OldC && "Didn't replace constant??");
Misha Brukmanb1c93172005-04-21 23:48:37 +00001603
Chris Lattner189d19f2003-11-21 20:23:48 +00001604 OldC->uncheckedReplaceAllUsesWith(New);
1605 OldC->destroyConstant(); // This constant is now dead, destroy it.
1606 }
1607 };
1608}
Chris Lattnerb50d1352003-10-05 00:17:43 +00001609
Chris Lattner8760ec72005-10-04 01:17:50 +00001610typedef ValueMap<std::vector<Constant*>, StructType,
Chris Lattner935aa922005-10-04 17:48:46 +00001611 ConstantStruct, true /*largekey*/> StructConstantsTy;
Chris Lattner69edc982006-09-28 00:35:06 +00001612static ManagedStatic<StructConstantsTy> StructConstants;
Chris Lattner49d855c2001-09-07 16:46:31 +00001613
Chris Lattner3e650af2004-08-04 04:48:01 +00001614static std::vector<Constant*> getValType(ConstantStruct *CS) {
1615 std::vector<Constant*> Elements;
1616 Elements.reserve(CS->getNumOperands());
1617 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1618 Elements.push_back(cast<Constant>(CS->getOperand(i)));
1619 return Elements;
1620}
1621
Chris Lattner015e8212004-02-15 04:14:47 +00001622Constant *ConstantStruct::get(const StructType *Ty,
1623 const std::vector<Constant*> &V) {
Chris Lattner9fba3da2004-02-15 05:53:04 +00001624 // Create a ConstantAggregateZero value if all elements are zeros...
1625 for (unsigned i = 0, e = V.size(); i != e; ++i)
Owen Anderson61794042009-06-17 20:10:08 +00001626 if (!V[i]->isNullValue())
1627 // Implicitly locked.
1628 return StructConstants->getOrCreate(Ty, V);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001629
1630 return ConstantAggregateZero::get(Ty);
Chris Lattner49d855c2001-09-07 16:46:31 +00001631}
Chris Lattner883ad0b2001-10-03 15:39:36 +00001632
Andrew Lenharthdcb3c972006-12-08 18:06:16 +00001633Constant *ConstantStruct::get(const std::vector<Constant*> &V, bool packed) {
Chris Lattnerd6108ca2004-07-12 20:35:11 +00001634 std::vector<const Type*> StructEls;
1635 StructEls.reserve(V.size());
1636 for (unsigned i = 0, e = V.size(); i != e; ++i)
1637 StructEls.push_back(V[i]->getType());
Andrew Lenharthdcb3c972006-12-08 18:06:16 +00001638 return get(StructType::get(StructEls, packed), V);
Chris Lattnerd6108ca2004-07-12 20:35:11 +00001639}
1640
Chris Lattnerd7a73302001-10-13 06:57:33 +00001641// destroyConstant - Remove the constant from the constant table...
Chris Lattner883ad0b2001-10-03 15:39:36 +00001642//
Chris Lattner3462ae32001-12-03 22:26:30 +00001643void ConstantStruct::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001644 StructConstants->remove(this);
Chris Lattnerd7a73302001-10-13 06:57:33 +00001645 destroyConstantImpl();
1646}
Chris Lattner883ad0b2001-10-03 15:39:36 +00001647
Reid Spencerd84d35b2007-02-15 02:26:10 +00001648//---- ConstantVector::get() implementation...
Brian Gaeke02209042004-08-20 06:00:58 +00001649//
1650namespace llvm {
1651 template<>
Reid Spencerd84d35b2007-02-15 02:26:10 +00001652 struct ConvertConstantType<ConstantVector, VectorType> {
1653 static void convert(ConstantVector *OldC, const VectorType *NewTy) {
Brian Gaeke02209042004-08-20 06:00:58 +00001654 // Make everyone now use a constant of the new type...
1655 std::vector<Constant*> C;
1656 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1657 C.push_back(cast<Constant>(OldC->getOperand(i)));
Reid Spencerd84d35b2007-02-15 02:26:10 +00001658 Constant *New = ConstantVector::get(NewTy, C);
Brian Gaeke02209042004-08-20 06:00:58 +00001659 assert(New != OldC && "Didn't replace constant??");
1660 OldC->uncheckedReplaceAllUsesWith(New);
1661 OldC->destroyConstant(); // This constant is now dead, destroy it.
1662 }
1663 };
1664}
1665
Reid Spencerd84d35b2007-02-15 02:26:10 +00001666static std::vector<Constant*> getValType(ConstantVector *CP) {
Brian Gaeke02209042004-08-20 06:00:58 +00001667 std::vector<Constant*> Elements;
1668 Elements.reserve(CP->getNumOperands());
1669 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1670 Elements.push_back(CP->getOperand(i));
1671 return Elements;
1672}
1673
Reid Spencerd84d35b2007-02-15 02:26:10 +00001674static ManagedStatic<ValueMap<std::vector<Constant*>, VectorType,
Reid Spencer09575ba2007-02-15 03:39:18 +00001675 ConstantVector> > VectorConstants;
Brian Gaeke02209042004-08-20 06:00:58 +00001676
Reid Spencerd84d35b2007-02-15 02:26:10 +00001677Constant *ConstantVector::get(const VectorType *Ty,
Brian Gaeke02209042004-08-20 06:00:58 +00001678 const std::vector<Constant*> &V) {
Chris Lattnerd977c072008-07-10 00:44:03 +00001679 assert(!V.empty() && "Vectors can't be empty");
1680 // If this is an all-undef or alll-zero vector, return a
1681 // ConstantAggregateZero or UndefValue.
1682 Constant *C = V[0];
1683 bool isZero = C->isNullValue();
1684 bool isUndef = isa<UndefValue>(C);
1685
1686 if (isZero || isUndef) {
Brian Gaeke02209042004-08-20 06:00:58 +00001687 for (unsigned i = 1, e = V.size(); i != e; ++i)
Chris Lattnerd977c072008-07-10 00:44:03 +00001688 if (V[i] != C) {
1689 isZero = isUndef = false;
1690 break;
1691 }
Brian Gaeke02209042004-08-20 06:00:58 +00001692 }
Chris Lattnerd977c072008-07-10 00:44:03 +00001693
1694 if (isZero)
1695 return ConstantAggregateZero::get(Ty);
1696 if (isUndef)
1697 return UndefValue::get(Ty);
Owen Anderson61794042009-06-17 20:10:08 +00001698
1699 // Implicitly locked.
1700 return VectorConstants->getOrCreate(Ty, V);
Brian Gaeke02209042004-08-20 06:00:58 +00001701}
1702
Reid Spencerd84d35b2007-02-15 02:26:10 +00001703Constant *ConstantVector::get(const std::vector<Constant*> &V) {
Brian Gaeke02209042004-08-20 06:00:58 +00001704 assert(!V.empty() && "Cannot infer type if V is empty");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001705 return get(VectorType::get(V.front()->getType(),V.size()), V);
Brian Gaeke02209042004-08-20 06:00:58 +00001706}
1707
1708// destroyConstant - Remove the constant from the constant table...
1709//
Reid Spencerd84d35b2007-02-15 02:26:10 +00001710void ConstantVector::destroyConstant() {
Owen Anderson65c5cd72009-06-17 20:34:43 +00001711
1712 if (llvm_is_multithreaded()) {
1713 sys::ScopedWriter Write(&*ConstantsLock);
1714 VectorConstants->remove(this);
1715 } else
1716 VectorConstants->remove(this);
Brian Gaeke02209042004-08-20 06:00:58 +00001717 destroyConstantImpl();
1718}
1719
Dan Gohman30978072007-05-24 14:36:04 +00001720/// This function will return true iff every element in this vector constant
Jim Laskeyf0478822007-01-12 22:39:14 +00001721/// is set to all ones.
1722/// @returns true iff this constant's emements are all set to all ones.
1723/// @brief Determine if the value is all ones.
Reid Spencerd84d35b2007-02-15 02:26:10 +00001724bool ConstantVector::isAllOnesValue() const {
Jim Laskeyf0478822007-01-12 22:39:14 +00001725 // Check out first element.
1726 const Constant *Elt = getOperand(0);
1727 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1728 if (!CI || !CI->isAllOnesValue()) return false;
1729 // Then make sure all remaining elements point to the same value.
1730 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1731 if (getOperand(I) != Elt) return false;
1732 }
1733 return true;
1734}
1735
Dan Gohman07159202007-10-17 17:51:30 +00001736/// getSplatValue - If this is a splat constant, where all of the
1737/// elements have the same value, return that value. Otherwise return null.
1738Constant *ConstantVector::getSplatValue() {
1739 // Check out first element.
1740 Constant *Elt = getOperand(0);
1741 // Then make sure all remaining elements point to the same value.
1742 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1743 if (getOperand(I) != Elt) return 0;
1744 return Elt;
1745}
1746
Chris Lattner3462ae32001-12-03 22:26:30 +00001747//---- ConstantPointerNull::get() implementation...
Chris Lattnerd7a73302001-10-13 06:57:33 +00001748//
Chris Lattner98fa07b2003-05-23 20:03:32 +00001749
Chris Lattner189d19f2003-11-21 20:23:48 +00001750namespace llvm {
1751 // ConstantPointerNull does not take extra "value" argument...
1752 template<class ValType>
1753 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1754 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1755 return new ConstantPointerNull(Ty);
1756 }
1757 };
Chris Lattner98fa07b2003-05-23 20:03:32 +00001758
Chris Lattner189d19f2003-11-21 20:23:48 +00001759 template<>
1760 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1761 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1762 // Make everyone now use a constant of the new type...
1763 Constant *New = ConstantPointerNull::get(NewTy);
1764 assert(New != OldC && "Didn't replace constant??");
1765 OldC->uncheckedReplaceAllUsesWith(New);
1766 OldC->destroyConstant(); // This constant is now dead, destroy it.
1767 }
1768 };
1769}
Chris Lattnerb50d1352003-10-05 00:17:43 +00001770
Chris Lattner69edc982006-09-28 00:35:06 +00001771static ManagedStatic<ValueMap<char, PointerType,
1772 ConstantPointerNull> > NullPtrConstants;
Chris Lattnerd7a73302001-10-13 06:57:33 +00001773
Chris Lattner3e650af2004-08-04 04:48:01 +00001774static char getValType(ConstantPointerNull *) {
1775 return 0;
1776}
1777
1778
Chris Lattner3462ae32001-12-03 22:26:30 +00001779ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
Owen Anderson61794042009-06-17 20:10:08 +00001780 // Implicitly locked.
1781 return NullPtrConstants->getOrCreate(Ty, 0);
Chris Lattner883ad0b2001-10-03 15:39:36 +00001782}
1783
Chris Lattner0c6e0b92002-08-18 00:40:04 +00001784// destroyConstant - Remove the constant from the constant table...
1785//
1786void ConstantPointerNull::destroyConstant() {
Owen Anderson65c5cd72009-06-17 20:34:43 +00001787 if (llvm_is_multithreaded()) {
1788 sys::ScopedWriter Writer(&*ConstantsLock);
1789 NullPtrConstants->remove(this);
1790 } else
1791 NullPtrConstants->remove(this);
Chris Lattner0c6e0b92002-08-18 00:40:04 +00001792 destroyConstantImpl();
1793}
1794
1795
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001796//---- UndefValue::get() implementation...
1797//
1798
1799namespace llvm {
1800 // UndefValue does not take extra "value" argument...
1801 template<class ValType>
1802 struct ConstantCreator<UndefValue, Type, ValType> {
1803 static UndefValue *create(const Type *Ty, const ValType &V) {
1804 return new UndefValue(Ty);
1805 }
1806 };
1807
1808 template<>
1809 struct ConvertConstantType<UndefValue, Type> {
1810 static void convert(UndefValue *OldC, const Type *NewTy) {
1811 // Make everyone now use a constant of the new type.
1812 Constant *New = UndefValue::get(NewTy);
1813 assert(New != OldC && "Didn't replace constant??");
1814 OldC->uncheckedReplaceAllUsesWith(New);
1815 OldC->destroyConstant(); // This constant is now dead, destroy it.
1816 }
1817 };
1818}
1819
Chris Lattner69edc982006-09-28 00:35:06 +00001820static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001821
1822static char getValType(UndefValue *) {
1823 return 0;
1824}
1825
1826
1827UndefValue *UndefValue::get(const Type *Ty) {
Owen Anderson61794042009-06-17 20:10:08 +00001828 // Implicitly locked.
1829 return UndefValueConstants->getOrCreate(Ty, 0);
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001830}
1831
1832// destroyConstant - Remove the constant from the constant table.
1833//
1834void UndefValue::destroyConstant() {
Owen Anderson61794042009-06-17 20:10:08 +00001835 // Implicitly locked.
Chris Lattner69edc982006-09-28 00:35:06 +00001836 UndefValueConstants->remove(this);
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001837 destroyConstantImpl();
1838}
1839
Nick Lewycky49f89192009-04-04 07:22:01 +00001840//---- MDString::get() implementation
1841//
1842
1843MDString::MDString(const char *begin, const char *end)
Nick Lewyckyadbc2842009-05-30 05:06:04 +00001844 : Constant(Type::MetadataTy, MDStringVal, 0, 0),
Nick Lewycky49f89192009-04-04 07:22:01 +00001845 StrBegin(begin), StrEnd(end) {}
1846
1847static ManagedStatic<StringMap<MDString*> > MDStringCache;
1848
1849MDString *MDString::get(const char *StrBegin, const char *StrEnd) {
Owen Anderson65c5cd72009-06-17 20:34:43 +00001850 if (llvm_is_multithreaded()) {
1851 sys::ScopedWriter Writer(&*ConstantsLock);
1852 StringMapEntry<MDString *> &Entry = MDStringCache->GetOrCreateValue(
1853 StrBegin, StrEnd);
1854 MDString *&S = Entry.getValue();
1855 if (!S) S = new MDString(Entry.getKeyData(),
1856 Entry.getKeyData() + Entry.getKeyLength());
1857
1858 return S;
1859 } else {
1860 StringMapEntry<MDString *> &Entry = MDStringCache->GetOrCreateValue(
1861 StrBegin, StrEnd);
1862 MDString *&S = Entry.getValue();
1863 if (!S) S = new MDString(Entry.getKeyData(),
1864 Entry.getKeyData() + Entry.getKeyLength());
1865
1866 return S;
1867 }
Nick Lewycky49f89192009-04-04 07:22:01 +00001868}
1869
1870void MDString::destroyConstant() {
Owen Anderson65c5cd72009-06-17 20:34:43 +00001871 if (llvm_is_multithreaded()) {
1872 sys::ScopedWriter Writer(&*ConstantsLock);
1873 MDStringCache->erase(MDStringCache->find(StrBegin, StrEnd));
1874 } else
1875 MDStringCache->erase(MDStringCache->find(StrBegin, StrEnd));
1876
Nick Lewycky49f89192009-04-04 07:22:01 +00001877 destroyConstantImpl();
1878}
1879
1880//---- MDNode::get() implementation
1881//
1882
1883static ManagedStatic<FoldingSet<MDNode> > MDNodeSet;
1884
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00001885MDNode::MDNode(Value*const* Vals, unsigned NumVals)
Nick Lewyckyadbc2842009-05-30 05:06:04 +00001886 : Constant(Type::MetadataTy, MDNodeVal, 0, 0) {
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00001887 for (unsigned i = 0; i != NumVals; ++i)
1888 Node.push_back(ElementVH(Vals[i], this));
Nick Lewycky49f89192009-04-04 07:22:01 +00001889}
1890
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00001891void MDNode::Profile(FoldingSetNodeID &ID) const {
1892 for (const_elem_iterator I = elem_begin(), E = elem_end(); I != E; ++I)
Nick Lewycky49f89192009-04-04 07:22:01 +00001893 ID.AddPointer(*I);
1894}
1895
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00001896MDNode *MDNode::get(Value*const* Vals, unsigned NumVals) {
Nick Lewycky49f89192009-04-04 07:22:01 +00001897 FoldingSetNodeID ID;
1898 for (unsigned i = 0; i != NumVals; ++i)
1899 ID.AddPointer(Vals[i]);
1900
Owen Anderson2d7231d2009-06-17 18:40:29 +00001901 if (llvm_is_multithreaded()) {
1902 ConstantsLock->reader_acquire();
1903 void *InsertPoint;
1904 MDNode *N = MDNodeSet->FindNodeOrInsertPos(ID, InsertPoint);
1905 ConstantsLock->reader_release();
1906
1907 if (!N) {
Owen Anderson65c5cd72009-06-17 20:34:43 +00001908 sys::ScopedWriter Writer(&*ConstantsLock);
Owen Anderson2d7231d2009-06-17 18:40:29 +00001909 N = MDNodeSet->FindNodeOrInsertPos(ID, InsertPoint);
1910 if (!N) {
1911 // InsertPoint will have been set by the FindNodeOrInsertPos call.
1912 MDNode *N = new(0) MDNode(Vals, NumVals);
1913 MDNodeSet->InsertNode(N, InsertPoint);
1914 }
Owen Anderson2d7231d2009-06-17 18:40:29 +00001915 }
1916
Nick Lewycky49f89192009-04-04 07:22:01 +00001917 return N;
Owen Anderson2d7231d2009-06-17 18:40:29 +00001918 } else {
1919 void *InsertPoint;
1920 if (MDNode *N = MDNodeSet->FindNodeOrInsertPos(ID, InsertPoint))
1921 return N;
Nick Lewycky49f89192009-04-04 07:22:01 +00001922
Owen Anderson2d7231d2009-06-17 18:40:29 +00001923 // InsertPoint will have been set by the FindNodeOrInsertPos call.
1924 MDNode *N = new(0) MDNode(Vals, NumVals);
1925 MDNodeSet->InsertNode(N, InsertPoint);
1926 return N;
1927 }
Nick Lewycky49f89192009-04-04 07:22:01 +00001928}
1929
1930void MDNode::destroyConstant() {
Owen Anderson65c5cd72009-06-17 20:34:43 +00001931 if (llvm_is_multithreaded()) {
1932 sys::ScopedWriter Writer(&*ConstantsLock);
1933 MDNodeSet->RemoveNode(this);
1934 } else
1935 MDNodeSet->RemoveNode(this);
1936
Nick Lewycky49f89192009-04-04 07:22:01 +00001937 destroyConstantImpl();
1938}
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001939
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001940//---- ConstantExpr::get() implementations...
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001941//
Reid Spencer8d9336d2006-12-31 05:26:44 +00001942
Dan Gohmand78c4002008-05-13 00:00:25 +00001943namespace {
1944
Reid Spenceree3c9912006-12-04 05:19:50 +00001945struct ExprMapKeyType {
Dan Gohman1ecaf452008-05-31 00:58:22 +00001946 typedef SmallVector<unsigned, 4> IndexList;
1947
1948 ExprMapKeyType(unsigned opc,
1949 const std::vector<Constant*> &ops,
1950 unsigned short pred = 0,
1951 const IndexList &inds = IndexList())
1952 : opcode(opc), predicate(pred), operands(ops), indices(inds) {}
Reid Spencerdba6aa42006-12-04 18:38:05 +00001953 uint16_t opcode;
1954 uint16_t predicate;
Reid Spenceree3c9912006-12-04 05:19:50 +00001955 std::vector<Constant*> operands;
Dan Gohman1ecaf452008-05-31 00:58:22 +00001956 IndexList indices;
Reid Spenceree3c9912006-12-04 05:19:50 +00001957 bool operator==(const ExprMapKeyType& that) const {
1958 return this->opcode == that.opcode &&
1959 this->predicate == that.predicate &&
Bill Wendling97f7de82008-10-26 00:19:56 +00001960 this->operands == that.operands &&
Dan Gohman1ecaf452008-05-31 00:58:22 +00001961 this->indices == that.indices;
Reid Spenceree3c9912006-12-04 05:19:50 +00001962 }
1963 bool operator<(const ExprMapKeyType & that) const {
1964 return this->opcode < that.opcode ||
1965 (this->opcode == that.opcode && this->predicate < that.predicate) ||
1966 (this->opcode == that.opcode && this->predicate == that.predicate &&
Dan Gohman1ecaf452008-05-31 00:58:22 +00001967 this->operands < that.operands) ||
1968 (this->opcode == that.opcode && this->predicate == that.predicate &&
1969 this->operands == that.operands && this->indices < that.indices);
Reid Spenceree3c9912006-12-04 05:19:50 +00001970 }
1971
1972 bool operator!=(const ExprMapKeyType& that) const {
1973 return !(*this == that);
1974 }
1975};
Chris Lattner98fa07b2003-05-23 20:03:32 +00001976
Dan Gohmand78c4002008-05-13 00:00:25 +00001977}
1978
Chris Lattner189d19f2003-11-21 20:23:48 +00001979namespace llvm {
1980 template<>
1981 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
Reid Spencer10fbf0e2006-12-03 05:48:19 +00001982 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1983 unsigned short pred = 0) {
Reid Spenceree3c9912006-12-04 05:19:50 +00001984 if (Instruction::isCast(V.opcode))
1985 return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1986 if ((V.opcode >= Instruction::BinaryOpsBegin &&
Reid Spencer2341c222007-02-02 02:16:23 +00001987 V.opcode < Instruction::BinaryOpsEnd))
Reid Spenceree3c9912006-12-04 05:19:50 +00001988 return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1989 if (V.opcode == Instruction::Select)
1990 return new SelectConstantExpr(V.operands[0], V.operands[1],
1991 V.operands[2]);
1992 if (V.opcode == Instruction::ExtractElement)
1993 return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1994 if (V.opcode == Instruction::InsertElement)
1995 return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1996 V.operands[2]);
1997 if (V.opcode == Instruction::ShuffleVector)
1998 return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1999 V.operands[2]);
Dan Gohman1ecaf452008-05-31 00:58:22 +00002000 if (V.opcode == Instruction::InsertValue)
2001 return new InsertValueConstantExpr(V.operands[0], V.operands[1],
2002 V.indices, Ty);
2003 if (V.opcode == Instruction::ExtractValue)
2004 return new ExtractValueConstantExpr(V.operands[0], V.indices, Ty);
Reid Spenceree3c9912006-12-04 05:19:50 +00002005 if (V.opcode == Instruction::GetElementPtr) {
2006 std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
Gabor Greife9ecc682008-04-06 20:25:17 +00002007 return GetElementPtrConstantExpr::Create(V.operands[0], IdxList, Ty);
Reid Spenceree3c9912006-12-04 05:19:50 +00002008 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002009
Reid Spenceree3c9912006-12-04 05:19:50 +00002010 // The compare instructions are weird. We have to encode the predicate
2011 // value and it is combined with the instruction opcode by multiplying
2012 // the opcode by one hundred. We must decode this to get the predicate.
2013 if (V.opcode == Instruction::ICmp)
Nate Begemand2195702008-05-12 19:01:56 +00002014 return new CompareConstantExpr(Ty, Instruction::ICmp, V.predicate,
Reid Spenceree3c9912006-12-04 05:19:50 +00002015 V.operands[0], V.operands[1]);
2016 if (V.opcode == Instruction::FCmp)
Nate Begemand2195702008-05-12 19:01:56 +00002017 return new CompareConstantExpr(Ty, Instruction::FCmp, V.predicate,
2018 V.operands[0], V.operands[1]);
2019 if (V.opcode == Instruction::VICmp)
2020 return new CompareConstantExpr(Ty, Instruction::VICmp, V.predicate,
2021 V.operands[0], V.operands[1]);
2022 if (V.opcode == Instruction::VFCmp)
2023 return new CompareConstantExpr(Ty, Instruction::VFCmp, V.predicate,
Reid Spenceree3c9912006-12-04 05:19:50 +00002024 V.operands[0], V.operands[1]);
2025 assert(0 && "Invalid ConstantExpr!");
Jeff Cohen9f469632006-12-15 21:47:01 +00002026 return 0;
Chris Lattnerb50d1352003-10-05 00:17:43 +00002027 }
Chris Lattner189d19f2003-11-21 20:23:48 +00002028 };
Chris Lattnerb50d1352003-10-05 00:17:43 +00002029
Chris Lattner189d19f2003-11-21 20:23:48 +00002030 template<>
2031 struct ConvertConstantType<ConstantExpr, Type> {
2032 static void convert(ConstantExpr *OldC, const Type *NewTy) {
2033 Constant *New;
2034 switch (OldC->getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002035 case Instruction::Trunc:
2036 case Instruction::ZExt:
2037 case Instruction::SExt:
2038 case Instruction::FPTrunc:
2039 case Instruction::FPExt:
2040 case Instruction::UIToFP:
2041 case Instruction::SIToFP:
2042 case Instruction::FPToUI:
2043 case Instruction::FPToSI:
2044 case Instruction::PtrToInt:
2045 case Instruction::IntToPtr:
2046 case Instruction::BitCast:
Reid Spencerbb65ebf2006-12-12 23:36:14 +00002047 New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0),
2048 NewTy);
Chris Lattner189d19f2003-11-21 20:23:48 +00002049 break;
Chris Lattner6e415c02004-03-12 05:54:04 +00002050 case Instruction::Select:
2051 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
2052 OldC->getOperand(1),
2053 OldC->getOperand(2));
2054 break;
Chris Lattner189d19f2003-11-21 20:23:48 +00002055 default:
2056 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
Reid Spencer7eb55b32006-11-02 01:53:59 +00002057 OldC->getOpcode() < Instruction::BinaryOpsEnd);
Chris Lattner189d19f2003-11-21 20:23:48 +00002058 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
2059 OldC->getOperand(1));
2060 break;
2061 case Instruction::GetElementPtr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00002062 // Make everyone now use a constant of the new type...
Chris Lattner13128ab2004-10-11 22:52:25 +00002063 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
Chris Lattner302116a2007-01-31 04:40:28 +00002064 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0),
2065 &Idx[0], Idx.size());
Chris Lattner189d19f2003-11-21 20:23:48 +00002066 break;
2067 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002068
Chris Lattner189d19f2003-11-21 20:23:48 +00002069 assert(New != OldC && "Didn't replace constant??");
2070 OldC->uncheckedReplaceAllUsesWith(New);
2071 OldC->destroyConstant(); // This constant is now dead, destroy it.
2072 }
2073 };
2074} // end namespace llvm
Chris Lattnerb50d1352003-10-05 00:17:43 +00002075
2076
Chris Lattner3e650af2004-08-04 04:48:01 +00002077static ExprMapKeyType getValType(ConstantExpr *CE) {
2078 std::vector<Constant*> Operands;
2079 Operands.reserve(CE->getNumOperands());
2080 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
2081 Operands.push_back(cast<Constant>(CE->getOperand(i)));
Reid Spenceree3c9912006-12-04 05:19:50 +00002082 return ExprMapKeyType(CE->getOpcode(), Operands,
Dan Gohman1ecaf452008-05-31 00:58:22 +00002083 CE->isCompare() ? CE->getPredicate() : 0,
2084 CE->hasIndices() ?
2085 CE->getIndices() : SmallVector<unsigned, 4>());
Chris Lattner3e650af2004-08-04 04:48:01 +00002086}
2087
Chris Lattner69edc982006-09-28 00:35:06 +00002088static ManagedStatic<ValueMap<ExprMapKeyType, Type,
2089 ConstantExpr> > ExprConstants;
Vikram S. Adve4c485332002-07-15 18:19:33 +00002090
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002091/// This is a utility function to handle folding of casts and lookup of the
Duncan Sands7d6c8ae2008-03-30 19:38:55 +00002092/// cast in the ExprConstants map. It is used by the various get* methods below.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002093static inline Constant *getFoldedCast(
2094 Instruction::CastOps opc, Constant *C, const Type *Ty) {
Chris Lattner815ae2b2003-10-07 22:19:19 +00002095 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002096 // Fold a few common cases
2097 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
2098 return FC;
Chris Lattneracdbe712003-04-17 19:24:48 +00002099
Vikram S. Adve4c485332002-07-15 18:19:33 +00002100 // Look up the constant in the table first to ensure uniqueness
Chris Lattner2b383d2e2003-05-13 21:37:02 +00002101 std::vector<Constant*> argVec(1, C);
Reid Spenceree3c9912006-12-04 05:19:50 +00002102 ExprMapKeyType Key(opc, argVec);
Owen Anderson2d7231d2009-06-17 18:40:29 +00002103
Owen Anderson61794042009-06-17 20:10:08 +00002104 // Implicitly locked.
2105 return ExprConstants->getOrCreate(Ty, Key);
Vikram S. Adve4e537b22002-07-14 23:13:17 +00002106}
Reid Spencerf37dc652006-12-05 19:14:13 +00002107
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002108Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
2109 Instruction::CastOps opc = Instruction::CastOps(oc);
2110 assert(Instruction::isCast(opc) && "opcode out of range");
2111 assert(C && Ty && "Null arguments to getCast");
2112 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
2113
2114 switch (opc) {
2115 default:
2116 assert(0 && "Invalid cast opcode");
2117 break;
2118 case Instruction::Trunc: return getTrunc(C, Ty);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00002119 case Instruction::ZExt: return getZExt(C, Ty);
2120 case Instruction::SExt: return getSExt(C, Ty);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002121 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
2122 case Instruction::FPExt: return getFPExtend(C, Ty);
2123 case Instruction::UIToFP: return getUIToFP(C, Ty);
2124 case Instruction::SIToFP: return getSIToFP(C, Ty);
2125 case Instruction::FPToUI: return getFPToUI(C, Ty);
2126 case Instruction::FPToSI: return getFPToSI(C, Ty);
2127 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
2128 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
2129 case Instruction::BitCast: return getBitCast(C, Ty);
Chris Lattner1ece6f82005-01-01 15:59:57 +00002130 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002131 return 0;
Reid Spencerf37dc652006-12-05 19:14:13 +00002132}
2133
Reid Spencer5c140882006-12-04 20:17:56 +00002134Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00002135 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
Reid Spencer5c140882006-12-04 20:17:56 +00002136 return getCast(Instruction::BitCast, C, Ty);
2137 return getCast(Instruction::ZExt, C, Ty);
2138}
2139
2140Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00002141 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
Reid Spencer5c140882006-12-04 20:17:56 +00002142 return getCast(Instruction::BitCast, C, Ty);
2143 return getCast(Instruction::SExt, C, Ty);
2144}
2145
2146Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00002147 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
Reid Spencer5c140882006-12-04 20:17:56 +00002148 return getCast(Instruction::BitCast, C, Ty);
2149 return getCast(Instruction::Trunc, C, Ty);
2150}
2151
Reid Spencerbc245a02006-12-05 03:25:26 +00002152Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
2153 assert(isa<PointerType>(S->getType()) && "Invalid cast");
Chris Lattner03c49532007-01-15 02:27:26 +00002154 assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
Reid Spencerbc245a02006-12-05 03:25:26 +00002155
Chris Lattner03c49532007-01-15 02:27:26 +00002156 if (Ty->isInteger())
Reid Spencerbc245a02006-12-05 03:25:26 +00002157 return getCast(Instruction::PtrToInt, S, Ty);
2158 return getCast(Instruction::BitCast, S, Ty);
2159}
2160
Reid Spencer56521c42006-12-12 00:51:07 +00002161Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
2162 bool isSigned) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00002163 assert(C->getType()->isIntOrIntVector() &&
2164 Ty->isIntOrIntVector() && "Invalid cast");
2165 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2166 unsigned DstBits = Ty->getScalarSizeInBits();
Reid Spencer56521c42006-12-12 00:51:07 +00002167 Instruction::CastOps opcode =
2168 (SrcBits == DstBits ? Instruction::BitCast :
2169 (SrcBits > DstBits ? Instruction::Trunc :
2170 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2171 return getCast(opcode, C, Ty);
2172}
2173
2174Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00002175 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
Reid Spencer56521c42006-12-12 00:51:07 +00002176 "Invalid cast");
Dan Gohman7ccc52f2009-06-15 22:12:54 +00002177 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2178 unsigned DstBits = Ty->getScalarSizeInBits();
Reid Spencerca104e82006-12-12 05:38:50 +00002179 if (SrcBits == DstBits)
2180 return C; // Avoid a useless cast
Reid Spencer56521c42006-12-12 00:51:07 +00002181 Instruction::CastOps opcode =
Reid Spencerca104e82006-12-12 05:38:50 +00002182 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
Reid Spencer56521c42006-12-12 00:51:07 +00002183 return getCast(opcode, C, Ty);
2184}
2185
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002186Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00002187#ifndef NDEBUG
2188 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2189 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2190#endif
2191 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2192 assert(C->getType()->isIntOrIntVector() && "Trunc operand must be integer");
2193 assert(Ty->isIntOrIntVector() && "Trunc produces only integral");
2194 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002195 "SrcTy must be larger than DestTy for Trunc!");
2196
2197 return getFoldedCast(Instruction::Trunc, C, Ty);
2198}
2199
Reid Spencerbb65ebf2006-12-12 23:36:14 +00002200Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00002201#ifndef NDEBUG
2202 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2203 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2204#endif
2205 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2206 assert(C->getType()->isIntOrIntVector() && "SExt operand must be integral");
2207 assert(Ty->isIntOrIntVector() && "SExt produces only integer");
2208 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002209 "SrcTy must be smaller than DestTy for SExt!");
2210
2211 return getFoldedCast(Instruction::SExt, C, Ty);
Chris Lattnerdd284742004-04-04 23:20:30 +00002212}
2213
Reid Spencerbb65ebf2006-12-12 23:36:14 +00002214Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00002215#ifndef NDEBUG
2216 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2217 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2218#endif
2219 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2220 assert(C->getType()->isIntOrIntVector() && "ZEXt operand must be integral");
2221 assert(Ty->isIntOrIntVector() && "ZExt produces only integer");
2222 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002223 "SrcTy must be smaller than DestTy for ZExt!");
2224
2225 return getFoldedCast(Instruction::ZExt, C, Ty);
2226}
2227
2228Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00002229#ifndef NDEBUG
2230 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2231 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2232#endif
2233 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2234 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
2235 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002236 "This is an illegal floating point truncation!");
2237 return getFoldedCast(Instruction::FPTrunc, C, Ty);
2238}
2239
2240Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00002241#ifndef NDEBUG
2242 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2243 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2244#endif
2245 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2246 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
2247 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002248 "This is an illegal floating point extension!");
2249 return getFoldedCast(Instruction::FPExt, C, Ty);
2250}
2251
2252Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
Devang Pateld26344d2008-11-03 23:20:04 +00002253#ifndef NDEBUG
Nate Begemand4d45c22007-11-17 03:58:34 +00002254 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2255 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Pateld26344d2008-11-03 23:20:04 +00002256#endif
Nate Begemand4d45c22007-11-17 03:58:34 +00002257 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2258 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
2259 "This is an illegal uint to floating point cast!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002260 return getFoldedCast(Instruction::UIToFP, C, Ty);
2261}
2262
2263Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
Devang Pateld26344d2008-11-03 23:20:04 +00002264#ifndef NDEBUG
Nate Begemand4d45c22007-11-17 03:58:34 +00002265 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2266 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Pateld26344d2008-11-03 23:20:04 +00002267#endif
Nate Begemand4d45c22007-11-17 03:58:34 +00002268 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2269 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002270 "This is an illegal sint to floating point cast!");
2271 return getFoldedCast(Instruction::SIToFP, C, Ty);
2272}
2273
2274Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
Devang Pateld26344d2008-11-03 23:20:04 +00002275#ifndef NDEBUG
Nate Begemand4d45c22007-11-17 03:58:34 +00002276 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2277 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Pateld26344d2008-11-03 23:20:04 +00002278#endif
Nate Begemand4d45c22007-11-17 03:58:34 +00002279 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2280 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
2281 "This is an illegal floating point to uint cast!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002282 return getFoldedCast(Instruction::FPToUI, C, Ty);
2283}
2284
2285Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
Devang Pateld26344d2008-11-03 23:20:04 +00002286#ifndef NDEBUG
Nate Begemand4d45c22007-11-17 03:58:34 +00002287 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2288 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Pateld26344d2008-11-03 23:20:04 +00002289#endif
Nate Begemand4d45c22007-11-17 03:58:34 +00002290 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2291 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
2292 "This is an illegal floating point to sint cast!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002293 return getFoldedCast(Instruction::FPToSI, C, Ty);
2294}
2295
2296Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
2297 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
Chris Lattner03c49532007-01-15 02:27:26 +00002298 assert(DstTy->isInteger() && "PtrToInt destination must be integral");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002299 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
2300}
2301
2302Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
Chris Lattner03c49532007-01-15 02:27:26 +00002303 assert(C->getType()->isInteger() && "IntToPtr source must be integral");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002304 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
2305 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
2306}
2307
2308Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
2309 // BitCast implies a no-op cast of type only. No bits change. However, you
2310 // can't cast pointers to anything but pointers.
Devang Pateld26344d2008-11-03 23:20:04 +00002311#ifndef NDEBUG
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002312 const Type *SrcTy = C->getType();
2313 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
Reid Spencer5c140882006-12-04 20:17:56 +00002314 "BitCast cannot cast pointer to non-pointer and vice versa");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002315
2316 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
2317 // or nonptr->ptr). For all the other types, the cast is okay if source and
2318 // destination bit widths are identical.
2319 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
2320 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
Devang Pateld26344d2008-11-03 23:20:04 +00002321#endif
Chris Lattnere4086012009-03-08 04:06:26 +00002322 assert(SrcBitSize == DstBitSize && "BitCast requires types of same width");
Chris Lattnercbeda872009-03-21 06:55:54 +00002323
2324 // It is common to ask for a bitcast of a value to its own type, handle this
2325 // speedily.
2326 if (C->getType() == DstTy) return C;
2327
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002328 return getFoldedCast(Instruction::BitCast, C, DstTy);
Chris Lattnerdd284742004-04-04 23:20:30 +00002329}
2330
Duncan Sandsd334aca2009-05-21 15:52:21 +00002331Constant *ConstantExpr::getAlignOf(const Type *Ty) {
2332 // alignof is implemented as: (i64) gep ({i8,Ty}*)null, 0, 1
2333 const Type *AligningTy = StructType::get(Type::Int8Ty, Ty, NULL);
2334 Constant *NullPtr = getNullValue(AligningTy->getPointerTo());
2335 Constant *Zero = ConstantInt::get(Type::Int32Ty, 0);
2336 Constant *One = ConstantInt::get(Type::Int32Ty, 1);
2337 Constant *Indices[2] = { Zero, One };
2338 Constant *GEP = getGetElementPtr(NullPtr, Indices, 2);
2339 return getCast(Instruction::PtrToInt, GEP, Type::Int32Ty);
2340}
2341
Alkis Evlogimenosda5de052004-10-24 01:41:10 +00002342Constant *ConstantExpr::getSizeOf(const Type *Ty) {
Gordon Henriksen7ce31762007-10-06 14:29:36 +00002343 // sizeof is implemented as: (i64) gep (Ty*)null, 1
Chris Lattnerb5d70302007-02-19 20:01:23 +00002344 Constant *GEPIdx = ConstantInt::get(Type::Int32Ty, 1);
2345 Constant *GEP =
Christopher Lambedf07882007-12-17 01:12:55 +00002346 getGetElementPtr(getNullValue(PointerType::getUnqual(Ty)), &GEPIdx, 1);
Chris Lattnerb5d70302007-02-19 20:01:23 +00002347 return getCast(Instruction::PtrToInt, GEP, Type::Int64Ty);
Alkis Evlogimenos9160d5f2005-03-19 11:40:31 +00002348}
2349
Chris Lattnerb50d1352003-10-05 00:17:43 +00002350Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
Reid Spencera009d0d2006-12-04 21:35:24 +00002351 Constant *C1, Constant *C2) {
Chris Lattner38a9bcd2003-05-21 17:49:25 +00002352 // Check the operands for consistency first
Reid Spencer7eb55b32006-11-02 01:53:59 +00002353 assert(Opcode >= Instruction::BinaryOpsBegin &&
2354 Opcode < Instruction::BinaryOpsEnd &&
Chris Lattner38a9bcd2003-05-21 17:49:25 +00002355 "Invalid opcode in binary constant expression");
2356 assert(C1->getType() == C2->getType() &&
2357 "Operand types in binary constant expression should match");
Chris Lattnerb50d1352003-10-05 00:17:43 +00002358
Reid Spencer542964f2007-01-11 18:21:29 +00002359 if (ReqTy == C1->getType() || ReqTy == Type::Int1Ty)
Chris Lattnerb50d1352003-10-05 00:17:43 +00002360 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
2361 return FC; // Fold a few common cases...
Chris Lattneracdbe712003-04-17 19:24:48 +00002362
Chris Lattner2b383d2e2003-05-13 21:37:02 +00002363 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
Reid Spencera009d0d2006-12-04 21:35:24 +00002364 ExprMapKeyType Key(Opcode, argVec);
Owen Anderson61794042009-06-17 20:10:08 +00002365
2366 // Implicitly locked.
2367 return ExprConstants->getOrCreate(ReqTy, Key);
Vikram S. Adve4e537b22002-07-14 23:13:17 +00002368}
2369
Reid Spencer266e42b2006-12-23 06:05:41 +00002370Constant *ConstantExpr::getCompareTy(unsigned short predicate,
Nate Begeman098cc6f2008-07-25 17:56:27 +00002371 Constant *C1, Constant *C2) {
2372 bool isVectorType = C1->getType()->getTypeID() == Type::VectorTyID;
Reid Spencer266e42b2006-12-23 06:05:41 +00002373 switch (predicate) {
2374 default: assert(0 && "Invalid CmpInst predicate");
Nate Begemanc96e2e42008-07-25 17:35:37 +00002375 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
2376 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
2377 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
2378 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
2379 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
2380 case CmpInst::FCMP_TRUE:
Nate Begeman098cc6f2008-07-25 17:56:27 +00002381 return isVectorType ? getVFCmp(predicate, C1, C2)
2382 : getFCmp(predicate, C1, C2);
Nate Begemanc96e2e42008-07-25 17:35:37 +00002383 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
2384 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
2385 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
2386 case CmpInst::ICMP_SLE:
Nate Begeman098cc6f2008-07-25 17:56:27 +00002387 return isVectorType ? getVICmp(predicate, C1, C2)
2388 : getICmp(predicate, C1, C2);
Reid Spencer266e42b2006-12-23 06:05:41 +00002389 }
Reid Spencera009d0d2006-12-04 21:35:24 +00002390}
2391
2392Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
Dan Gohmana5b96452009-06-04 22:49:04 +00002393 // API compatibility: Adjust integer opcodes to floating-point opcodes.
2394 if (C1->getType()->isFPOrFPVector()) {
2395 if (Opcode == Instruction::Add) Opcode = Instruction::FAdd;
2396 else if (Opcode == Instruction::Sub) Opcode = Instruction::FSub;
2397 else if (Opcode == Instruction::Mul) Opcode = Instruction::FMul;
2398 }
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00002399#ifndef NDEBUG
2400 switch (Opcode) {
Dan Gohmana5b96452009-06-04 22:49:04 +00002401 case Instruction::Add:
Reid Spencer7eb55b32006-11-02 01:53:59 +00002402 case Instruction::Sub:
Dan Gohmana5b96452009-06-04 22:49:04 +00002403 case Instruction::Mul:
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00002404 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Dan Gohmana5b96452009-06-04 22:49:04 +00002405 assert(C1->getType()->isIntOrIntVector() &&
2406 "Tried to create an integer operation on a non-integer type!");
2407 break;
2408 case Instruction::FAdd:
2409 case Instruction::FSub:
2410 case Instruction::FMul:
2411 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2412 assert(C1->getType()->isFPOrFPVector() &&
2413 "Tried to create a floating-point operation on a "
2414 "non-floating-point type!");
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00002415 break;
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002416 case Instruction::UDiv:
2417 case Instruction::SDiv:
2418 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Dan Gohman7889f2b2009-06-15 22:25:12 +00002419 assert(C1->getType()->isIntOrIntVector() &&
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002420 "Tried to create an arithmetic operation on a non-arithmetic type!");
2421 break;
2422 case Instruction::FDiv:
2423 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Dan Gohman7889f2b2009-06-15 22:25:12 +00002424 assert(C1->getType()->isFPOrFPVector() &&
2425 "Tried to create an arithmetic operation on a non-arithmetic type!");
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002426 break;
Reid Spencer7eb55b32006-11-02 01:53:59 +00002427 case Instruction::URem:
2428 case Instruction::SRem:
2429 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Dan Gohman7889f2b2009-06-15 22:25:12 +00002430 assert(C1->getType()->isIntOrIntVector() &&
Reid Spencer7eb55b32006-11-02 01:53:59 +00002431 "Tried to create an arithmetic operation on a non-arithmetic type!");
2432 break;
2433 case Instruction::FRem:
2434 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Dan Gohman7889f2b2009-06-15 22:25:12 +00002435 assert(C1->getType()->isFPOrFPVector() &&
2436 "Tried to create an arithmetic operation on a non-arithmetic type!");
Reid Spencer7eb55b32006-11-02 01:53:59 +00002437 break;
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00002438 case Instruction::And:
2439 case Instruction::Or:
2440 case Instruction::Xor:
2441 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Dan Gohman7889f2b2009-06-15 22:25:12 +00002442 assert(C1->getType()->isIntOrIntVector() &&
Misha Brukman3852f652005-01-27 06:46:38 +00002443 "Tried to create a logical operation on a non-integral type!");
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00002444 break;
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00002445 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00002446 case Instruction::LShr:
2447 case Instruction::AShr:
Reid Spencer2341c222007-02-02 02:16:23 +00002448 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Dan Gohman79975d52009-03-14 17:09:17 +00002449 assert(C1->getType()->isIntOrIntVector() &&
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00002450 "Tried to create a shift operation on a non-integer type!");
2451 break;
2452 default:
2453 break;
2454 }
2455#endif
2456
Reid Spencera009d0d2006-12-04 21:35:24 +00002457 return getTy(C1->getType(), Opcode, C1, C2);
2458}
2459
Reid Spencer266e42b2006-12-23 06:05:41 +00002460Constant *ConstantExpr::getCompare(unsigned short pred,
Reid Spencera009d0d2006-12-04 21:35:24 +00002461 Constant *C1, Constant *C2) {
2462 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencer266e42b2006-12-23 06:05:41 +00002463 return getCompareTy(pred, C1, C2);
Chris Lattner29ca2c62004-08-04 18:50:09 +00002464}
2465
Chris Lattner6e415c02004-03-12 05:54:04 +00002466Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
2467 Constant *V1, Constant *V2) {
Chris Lattner41632132008-12-29 00:16:12 +00002468 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
Chris Lattner6e415c02004-03-12 05:54:04 +00002469
2470 if (ReqTy == V1->getType())
2471 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
2472 return SC; // Fold common cases
2473
2474 std::vector<Constant*> argVec(3, C);
2475 argVec[1] = V1;
2476 argVec[2] = V2;
Reid Spenceree3c9912006-12-04 05:19:50 +00002477 ExprMapKeyType Key(Instruction::Select, argVec);
Owen Anderson61794042009-06-17 20:10:08 +00002478
2479 // Implicitly locked.
2480 return ExprConstants->getOrCreate(ReqTy, Key);
Chris Lattner6e415c02004-03-12 05:54:04 +00002481}
2482
Chris Lattnerb50d1352003-10-05 00:17:43 +00002483Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
Chris Lattner302116a2007-01-31 04:40:28 +00002484 Value* const *Idxs,
2485 unsigned NumIdx) {
Dan Gohman12fce772008-05-15 19:50:34 +00002486 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs,
2487 Idxs+NumIdx) ==
2488 cast<PointerType>(ReqTy)->getElementType() &&
2489 "GEP indices invalid!");
Chris Lattner04b60fe2004-02-16 20:46:13 +00002490
Chris Lattner302116a2007-01-31 04:40:28 +00002491 if (Constant *FC = ConstantFoldGetElementPtr(C, (Constant**)Idxs, NumIdx))
Chris Lattneracdbe712003-04-17 19:24:48 +00002492 return FC; // Fold a few common cases...
Chris Lattner04b60fe2004-02-16 20:46:13 +00002493
Chris Lattnerb50d1352003-10-05 00:17:43 +00002494 assert(isa<PointerType>(C->getType()) &&
Chris Lattner98fa07b2003-05-23 20:03:32 +00002495 "Non-pointer type for constant GetElementPtr expression");
Vikram S. Adve4c485332002-07-15 18:19:33 +00002496 // Look up the constant in the table first to ensure uniqueness
Chris Lattner13128ab2004-10-11 22:52:25 +00002497 std::vector<Constant*> ArgVec;
Chris Lattner302116a2007-01-31 04:40:28 +00002498 ArgVec.reserve(NumIdx+1);
Chris Lattner13128ab2004-10-11 22:52:25 +00002499 ArgVec.push_back(C);
Chris Lattner302116a2007-01-31 04:40:28 +00002500 for (unsigned i = 0; i != NumIdx; ++i)
2501 ArgVec.push_back(cast<Constant>(Idxs[i]));
2502 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
Owen Anderson61794042009-06-17 20:10:08 +00002503
2504 // Implicitly locked.
2505 return ExprConstants->getOrCreate(ReqTy, Key);
Vikram S. Adve4c485332002-07-15 18:19:33 +00002506}
2507
Chris Lattner302116a2007-01-31 04:40:28 +00002508Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
2509 unsigned NumIdx) {
Chris Lattnerb50d1352003-10-05 00:17:43 +00002510 // Get the result type of the getelementptr!
Chris Lattner302116a2007-01-31 04:40:28 +00002511 const Type *Ty =
Dan Gohman12fce772008-05-15 19:50:34 +00002512 GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx);
Chris Lattnerb50d1352003-10-05 00:17:43 +00002513 assert(Ty && "GEP indices invalid!");
Christopher Lamb54dd24c2007-12-11 08:59:05 +00002514 unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
2515 return getGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx);
Chris Lattner13128ab2004-10-11 22:52:25 +00002516}
2517
Chris Lattner302116a2007-01-31 04:40:28 +00002518Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
2519 unsigned NumIdx) {
2520 return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
Chris Lattnerb50d1352003-10-05 00:17:43 +00002521}
2522
Chris Lattner302116a2007-01-31 04:40:28 +00002523
Reid Spenceree3c9912006-12-04 05:19:50 +00002524Constant *
2525ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2526 assert(LHS->getType() == RHS->getType());
2527 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
2528 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
2529
Reid Spencer266e42b2006-12-23 06:05:41 +00002530 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
Reid Spenceree3c9912006-12-04 05:19:50 +00002531 return FC; // Fold a few common cases...
2532
2533 // Look up the constant in the table first to ensure uniqueness
2534 std::vector<Constant*> ArgVec;
2535 ArgVec.push_back(LHS);
2536 ArgVec.push_back(RHS);
Reid Spencerb1537492006-12-24 18:42:29 +00002537 // Get the key type with both the opcode and predicate
Reid Spenceree3c9912006-12-04 05:19:50 +00002538 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
Owen Anderson61794042009-06-17 20:10:08 +00002539
2540 // Implicitly locked.
2541 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
Reid Spenceree3c9912006-12-04 05:19:50 +00002542}
2543
2544Constant *
2545ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2546 assert(LHS->getType() == RHS->getType());
2547 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
2548
Reid Spencer266e42b2006-12-23 06:05:41 +00002549 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
Reid Spenceree3c9912006-12-04 05:19:50 +00002550 return FC; // Fold a few common cases...
2551
2552 // Look up the constant in the table first to ensure uniqueness
2553 std::vector<Constant*> ArgVec;
2554 ArgVec.push_back(LHS);
2555 ArgVec.push_back(RHS);
Reid Spencerb1537492006-12-24 18:42:29 +00002556 // Get the key type with both the opcode and predicate
Reid Spenceree3c9912006-12-04 05:19:50 +00002557 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
Owen Anderson61794042009-06-17 20:10:08 +00002558
2559 // Implicitly locked.
2560 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
Reid Spenceree3c9912006-12-04 05:19:50 +00002561}
2562
Nate Begemand2195702008-05-12 19:01:56 +00002563Constant *
2564ConstantExpr::getVICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
Chris Lattnereab49262008-07-14 05:17:31 +00002565 assert(isa<VectorType>(LHS->getType()) && LHS->getType() == RHS->getType() &&
Nate Begemand2195702008-05-12 19:01:56 +00002566 "Tried to create vicmp operation on non-vector type!");
Nate Begemand2195702008-05-12 19:01:56 +00002567 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
2568 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid VICmp Predicate");
2569
Nate Begemanac7f3d92008-05-12 19:23:22 +00002570 const VectorType *VTy = cast<VectorType>(LHS->getType());
Nate Begemand2195702008-05-12 19:01:56 +00002571 const Type *EltTy = VTy->getElementType();
2572 unsigned NumElts = VTy->getNumElements();
2573
Chris Lattnereab49262008-07-14 05:17:31 +00002574 // See if we can fold the element-wise comparison of the LHS and RHS.
2575 SmallVector<Constant *, 16> LHSElts, RHSElts;
2576 LHS->getVectorElements(LHSElts);
2577 RHS->getVectorElements(RHSElts);
2578
2579 if (!LHSElts.empty() && !RHSElts.empty()) {
2580 SmallVector<Constant *, 16> Elts;
2581 for (unsigned i = 0; i != NumElts; ++i) {
2582 Constant *FC = ConstantFoldCompareInstruction(pred, LHSElts[i],
2583 RHSElts[i]);
2584 if (ConstantInt *FCI = dyn_cast_or_null<ConstantInt>(FC)) {
2585 if (FCI->getZExtValue())
2586 Elts.push_back(ConstantInt::getAllOnesValue(EltTy));
2587 else
2588 Elts.push_back(ConstantInt::get(EltTy, 0ULL));
2589 } else if (FC && isa<UndefValue>(FC)) {
2590 Elts.push_back(UndefValue::get(EltTy));
2591 } else {
2592 break;
2593 }
Nate Begemand2195702008-05-12 19:01:56 +00002594 }
Chris Lattnereab49262008-07-14 05:17:31 +00002595 if (Elts.size() == NumElts)
2596 return ConstantVector::get(&Elts[0], Elts.size());
Nate Begemand2195702008-05-12 19:01:56 +00002597 }
Nate Begemand2195702008-05-12 19:01:56 +00002598
2599 // Look up the constant in the table first to ensure uniqueness
2600 std::vector<Constant*> ArgVec;
2601 ArgVec.push_back(LHS);
2602 ArgVec.push_back(RHS);
2603 // Get the key type with both the opcode and predicate
2604 const ExprMapKeyType Key(Instruction::VICmp, ArgVec, pred);
Owen Anderson61794042009-06-17 20:10:08 +00002605
2606 // Implicitly locked.
2607 return ExprConstants->getOrCreate(LHS->getType(), Key);
Nate Begemand2195702008-05-12 19:01:56 +00002608}
2609
2610Constant *
2611ConstantExpr::getVFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2612 assert(isa<VectorType>(LHS->getType()) &&
2613 "Tried to create vfcmp operation on non-vector type!");
2614 assert(LHS->getType() == RHS->getType());
2615 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid VFCmp Predicate");
2616
2617 const VectorType *VTy = cast<VectorType>(LHS->getType());
2618 unsigned NumElts = VTy->getNumElements();
2619 const Type *EltTy = VTy->getElementType();
2620 const Type *REltTy = IntegerType::get(EltTy->getPrimitiveSizeInBits());
2621 const Type *ResultTy = VectorType::get(REltTy, NumElts);
2622
Chris Lattnereab49262008-07-14 05:17:31 +00002623 // See if we can fold the element-wise comparison of the LHS and RHS.
2624 SmallVector<Constant *, 16> LHSElts, RHSElts;
2625 LHS->getVectorElements(LHSElts);
2626 RHS->getVectorElements(RHSElts);
2627
2628 if (!LHSElts.empty() && !RHSElts.empty()) {
2629 SmallVector<Constant *, 16> Elts;
2630 for (unsigned i = 0; i != NumElts; ++i) {
2631 Constant *FC = ConstantFoldCompareInstruction(pred, LHSElts[i],
2632 RHSElts[i]);
2633 if (ConstantInt *FCI = dyn_cast_or_null<ConstantInt>(FC)) {
2634 if (FCI->getZExtValue())
2635 Elts.push_back(ConstantInt::getAllOnesValue(REltTy));
2636 else
2637 Elts.push_back(ConstantInt::get(REltTy, 0ULL));
2638 } else if (FC && isa<UndefValue>(FC)) {
2639 Elts.push_back(UndefValue::get(REltTy));
2640 } else {
2641 break;
2642 }
Nate Begemand2195702008-05-12 19:01:56 +00002643 }
Chris Lattnereab49262008-07-14 05:17:31 +00002644 if (Elts.size() == NumElts)
2645 return ConstantVector::get(&Elts[0], Elts.size());
Nate Begemand2195702008-05-12 19:01:56 +00002646 }
Nate Begemand2195702008-05-12 19:01:56 +00002647
2648 // Look up the constant in the table first to ensure uniqueness
2649 std::vector<Constant*> ArgVec;
2650 ArgVec.push_back(LHS);
2651 ArgVec.push_back(RHS);
2652 // Get the key type with both the opcode and predicate
2653 const ExprMapKeyType Key(Instruction::VFCmp, ArgVec, pred);
Owen Anderson61794042009-06-17 20:10:08 +00002654
2655 // Implicitly locked.
2656 return ExprConstants->getOrCreate(ResultTy, Key);
Nate Begemand2195702008-05-12 19:01:56 +00002657}
2658
Robert Bocchino23004482006-01-10 19:05:34 +00002659Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
2660 Constant *Idx) {
Robert Bocchinode7f1c92006-01-10 20:03:46 +00002661 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
2662 return FC; // Fold a few common cases...
Robert Bocchino23004482006-01-10 19:05:34 +00002663 // Look up the constant in the table first to ensure uniqueness
2664 std::vector<Constant*> ArgVec(1, Val);
2665 ArgVec.push_back(Idx);
Reid Spenceree3c9912006-12-04 05:19:50 +00002666 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
Owen Anderson61794042009-06-17 20:10:08 +00002667
2668 // Implicitly locked.
2669 return ExprConstants->getOrCreate(ReqTy, Key);
Robert Bocchino23004482006-01-10 19:05:34 +00002670}
2671
2672Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00002673 assert(isa<VectorType>(Val->getType()) &&
Reid Spencer09575ba2007-02-15 03:39:18 +00002674 "Tried to create extractelement operation on non-vector type!");
Reid Spencer8d9336d2006-12-31 05:26:44 +00002675 assert(Idx->getType() == Type::Int32Ty &&
Reid Spencer2546b762007-01-26 07:37:34 +00002676 "Extractelement index must be i32 type!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00002677 return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
Robert Bocchino23004482006-01-10 19:05:34 +00002678 Val, Idx);
2679}
Chris Lattnerb50d1352003-10-05 00:17:43 +00002680
Robert Bocchinoca27f032006-01-17 20:07:22 +00002681Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
2682 Constant *Elt, Constant *Idx) {
2683 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
2684 return FC; // Fold a few common cases...
2685 // Look up the constant in the table first to ensure uniqueness
2686 std::vector<Constant*> ArgVec(1, Val);
2687 ArgVec.push_back(Elt);
2688 ArgVec.push_back(Idx);
Reid Spenceree3c9912006-12-04 05:19:50 +00002689 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
Owen Anderson61794042009-06-17 20:10:08 +00002690
2691 // Implicitly locked.
2692 return ExprConstants->getOrCreate(ReqTy, Key);
Robert Bocchinoca27f032006-01-17 20:07:22 +00002693}
2694
2695Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
2696 Constant *Idx) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00002697 assert(isa<VectorType>(Val->getType()) &&
Reid Spencer09575ba2007-02-15 03:39:18 +00002698 "Tried to create insertelement operation on non-vector type!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00002699 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
Robert Bocchinoca27f032006-01-17 20:07:22 +00002700 && "Insertelement types must match!");
Reid Spencer8d9336d2006-12-31 05:26:44 +00002701 assert(Idx->getType() == Type::Int32Ty &&
Reid Spencer2546b762007-01-26 07:37:34 +00002702 "Insertelement index must be i32 type!");
Gordon Henriksenb52d1ed2008-08-30 15:41:51 +00002703 return getInsertElementTy(Val->getType(), Val, Elt, Idx);
Robert Bocchinoca27f032006-01-17 20:07:22 +00002704}
2705
Chris Lattnerbbe0a422006-04-08 01:18:18 +00002706Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
2707 Constant *V2, Constant *Mask) {
2708 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
2709 return FC; // Fold a few common cases...
2710 // Look up the constant in the table first to ensure uniqueness
2711 std::vector<Constant*> ArgVec(1, V1);
2712 ArgVec.push_back(V2);
2713 ArgVec.push_back(Mask);
Reid Spenceree3c9912006-12-04 05:19:50 +00002714 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
Owen Anderson61794042009-06-17 20:10:08 +00002715
2716 // Implicitly locked.
2717 return ExprConstants->getOrCreate(ReqTy, Key);
Chris Lattnerbbe0a422006-04-08 01:18:18 +00002718}
2719
2720Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
2721 Constant *Mask) {
2722 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
2723 "Invalid shuffle vector constant expr operands!");
Nate Begeman94aa38d2009-02-12 21:28:33 +00002724
2725 unsigned NElts = cast<VectorType>(Mask->getType())->getNumElements();
2726 const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
2727 const Type *ShufTy = VectorType::get(EltTy, NElts);
2728 return getShuffleVectorTy(ShufTy, V1, V2, Mask);
Chris Lattnerbbe0a422006-04-08 01:18:18 +00002729}
2730
Dan Gohman12fce772008-05-15 19:50:34 +00002731Constant *ConstantExpr::getInsertValueTy(const Type *ReqTy, Constant *Agg,
2732 Constant *Val,
Dan Gohman1ecaf452008-05-31 00:58:22 +00002733 const unsigned *Idxs, unsigned NumIdx) {
Dan Gohman12fce772008-05-15 19:50:34 +00002734 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
2735 Idxs+NumIdx) == Val->getType() &&
2736 "insertvalue indices invalid!");
2737 assert(Agg->getType() == ReqTy &&
2738 "insertvalue type invalid!");
Dan Gohman0752bff2008-05-23 00:36:11 +00002739 assert(Agg->getType()->isFirstClassType() &&
2740 "Non-first-class type for constant InsertValue expression");
Dan Gohmand5d24f62008-07-21 23:30:30 +00002741 Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs, NumIdx);
2742 assert(FC && "InsertValue constant expr couldn't be folded!");
2743 return FC;
Dan Gohman12fce772008-05-15 19:50:34 +00002744}
2745
2746Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
Dan Gohman1ecaf452008-05-31 00:58:22 +00002747 const unsigned *IdxList, unsigned NumIdx) {
Dan Gohman0752bff2008-05-23 00:36:11 +00002748 assert(Agg->getType()->isFirstClassType() &&
2749 "Tried to create insertelement operation on non-first-class type!");
Dan Gohman12fce772008-05-15 19:50:34 +00002750
Dan Gohman0752bff2008-05-23 00:36:11 +00002751 const Type *ReqTy = Agg->getType();
Devang Pateld26344d2008-11-03 23:20:04 +00002752#ifndef NDEBUG
Dan Gohman0752bff2008-05-23 00:36:11 +00002753 const Type *ValTy =
Dan Gohman12fce772008-05-15 19:50:34 +00002754 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
Devang Pateld26344d2008-11-03 23:20:04 +00002755#endif
Dan Gohman0752bff2008-05-23 00:36:11 +00002756 assert(ValTy == Val->getType() && "insertvalue indices invalid!");
Dan Gohman12fce772008-05-15 19:50:34 +00002757 return getInsertValueTy(ReqTy, Agg, Val, IdxList, NumIdx);
2758}
2759
2760Constant *ConstantExpr::getExtractValueTy(const Type *ReqTy, Constant *Agg,
Dan Gohman1ecaf452008-05-31 00:58:22 +00002761 const unsigned *Idxs, unsigned NumIdx) {
Dan Gohman12fce772008-05-15 19:50:34 +00002762 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
2763 Idxs+NumIdx) == ReqTy &&
2764 "extractvalue indices invalid!");
Dan Gohman0752bff2008-05-23 00:36:11 +00002765 assert(Agg->getType()->isFirstClassType() &&
2766 "Non-first-class type for constant extractvalue expression");
Dan Gohmand5d24f62008-07-21 23:30:30 +00002767 Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs, NumIdx);
2768 assert(FC && "ExtractValue constant expr couldn't be folded!");
2769 return FC;
Dan Gohman12fce772008-05-15 19:50:34 +00002770}
2771
2772Constant *ConstantExpr::getExtractValue(Constant *Agg,
Dan Gohman1ecaf452008-05-31 00:58:22 +00002773 const unsigned *IdxList, unsigned NumIdx) {
Dan Gohman0752bff2008-05-23 00:36:11 +00002774 assert(Agg->getType()->isFirstClassType() &&
2775 "Tried to create extractelement operation on non-first-class type!");
Dan Gohman12fce772008-05-15 19:50:34 +00002776
2777 const Type *ReqTy =
2778 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
2779 assert(ReqTy && "extractvalue indices invalid!");
2780 return getExtractValueTy(ReqTy, Agg, IdxList, NumIdx);
2781}
2782
Reid Spencer2eadb532007-01-21 00:29:26 +00002783Constant *ConstantExpr::getZeroValueForNegationExpr(const Type *Ty) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00002784 if (const VectorType *PTy = dyn_cast<VectorType>(Ty))
Reid Spencer6598ca82007-01-21 02:29:10 +00002785 if (PTy->getElementType()->isFloatingPoint()) {
2786 std::vector<Constant*> zeros(PTy->getNumElements(),
Dale Johannesen98d3a082007-09-14 22:26:36 +00002787 ConstantFP::getNegativeZero(PTy->getElementType()));
Reid Spencerd84d35b2007-02-15 02:26:10 +00002788 return ConstantVector::get(PTy, zeros);
Reid Spencer6598ca82007-01-21 02:29:10 +00002789 }
Reid Spencer2eadb532007-01-21 00:29:26 +00002790
Dale Johannesen98d3a082007-09-14 22:26:36 +00002791 if (Ty->isFloatingPoint())
2792 return ConstantFP::getNegativeZero(Ty);
Reid Spencer2eadb532007-01-21 00:29:26 +00002793
2794 return Constant::getNullValue(Ty);
2795}
2796
Vikram S. Adve4c485332002-07-15 18:19:33 +00002797// destroyConstant - Remove the constant from the constant table...
2798//
2799void ConstantExpr::destroyConstant() {
Owen Anderson65c5cd72009-06-17 20:34:43 +00002800 if (llvm_is_multithreaded()) {
2801 sys::ScopedWriter Writer(&*ConstantsLock);
2802 ExprConstants->remove(this);
2803 } else
2804 ExprConstants->remove(this);
2805
Vikram S. Adve4c485332002-07-15 18:19:33 +00002806 destroyConstantImpl();
Vikram S. Adve4e537b22002-07-14 23:13:17 +00002807}
2808
Chris Lattner3cd8c562002-07-30 18:54:25 +00002809const char *ConstantExpr::getOpcodeName() const {
2810 return Instruction::getOpcodeName(getOpcode());
Vikram S. Adve4e537b22002-07-14 23:13:17 +00002811}
Reid Spencer1ebe1ab2004-07-17 23:48:33 +00002812
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002813//===----------------------------------------------------------------------===//
2814// replaceUsesOfWithOnConstant implementations
2815
Chris Lattner913849b2007-08-21 00:55:23 +00002816/// replaceUsesOfWithOnConstant - Update this constant array to change uses of
2817/// 'From' to be uses of 'To'. This must update the uniquing data structures
2818/// etc.
2819///
2820/// Note that we intentionally replace all uses of From with To here. Consider
2821/// a large array that uses 'From' 1000 times. By handling this case all here,
2822/// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
2823/// single invocation handles all 1000 uses. Handling them one at a time would
2824/// work, but would be really slow because it would have to unique each updated
2825/// array instance.
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002826void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002827 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002828 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
Chris Lattner8760ec72005-10-04 01:17:50 +00002829 Constant *ToC = cast<Constant>(To);
Chris Lattnerdff59112005-10-04 18:47:09 +00002830
Jim Laskeyc03caef2006-07-17 17:38:29 +00002831 std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
Chris Lattnerb64419a2005-10-03 22:51:37 +00002832 Lookup.first.first = getType();
2833 Lookup.second = this;
Chris Lattnerdff59112005-10-04 18:47:09 +00002834
Chris Lattnerb64419a2005-10-03 22:51:37 +00002835 std::vector<Constant*> &Values = Lookup.first.second;
2836 Values.reserve(getNumOperands()); // Build replacement array.
Chris Lattnerdff59112005-10-04 18:47:09 +00002837
Chris Lattner8760ec72005-10-04 01:17:50 +00002838 // Fill values with the modified operands of the constant array. Also,
2839 // compute whether this turns into an all-zeros array.
Chris Lattnerdff59112005-10-04 18:47:09 +00002840 bool isAllZeros = false;
Chris Lattner913849b2007-08-21 00:55:23 +00002841 unsigned NumUpdated = 0;
Chris Lattnerdff59112005-10-04 18:47:09 +00002842 if (!ToC->isNullValue()) {
Chris Lattner913849b2007-08-21 00:55:23 +00002843 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2844 Constant *Val = cast<Constant>(O->get());
2845 if (Val == From) {
2846 Val = ToC;
2847 ++NumUpdated;
2848 }
2849 Values.push_back(Val);
2850 }
Chris Lattnerdff59112005-10-04 18:47:09 +00002851 } else {
2852 isAllZeros = true;
2853 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2854 Constant *Val = cast<Constant>(O->get());
Chris Lattner913849b2007-08-21 00:55:23 +00002855 if (Val == From) {
2856 Val = ToC;
2857 ++NumUpdated;
2858 }
Chris Lattnerdff59112005-10-04 18:47:09 +00002859 Values.push_back(Val);
2860 if (isAllZeros) isAllZeros = Val->isNullValue();
2861 }
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002862 }
2863
Chris Lattnerb64419a2005-10-03 22:51:37 +00002864 Constant *Replacement = 0;
2865 if (isAllZeros) {
2866 Replacement = ConstantAggregateZero::get(getType());
2867 } else {
2868 // Check to see if we have this array type already.
Owen Anderson65c5cd72009-06-17 20:34:43 +00002869 sys::ScopedWriter Writer(&*ConstantsLock);
Chris Lattnerb64419a2005-10-03 22:51:37 +00002870 bool Exists;
Jim Laskeyc03caef2006-07-17 17:38:29 +00002871 ArrayConstantsTy::MapTy::iterator I =
Chris Lattner69edc982006-09-28 00:35:06 +00002872 ArrayConstants->InsertOrGetItem(Lookup, Exists);
Chris Lattnerb64419a2005-10-03 22:51:37 +00002873
2874 if (Exists) {
2875 Replacement = I->second;
2876 } else {
2877 // Okay, the new shape doesn't exist in the system yet. Instead of
2878 // creating a new constant array, inserting it, replaceallusesof'ing the
2879 // old with the new, then deleting the old... just update the current one
2880 // in place!
Chris Lattner69edc982006-09-28 00:35:06 +00002881 ArrayConstants->MoveConstantToNewSlot(this, I);
Chris Lattnerb64419a2005-10-03 22:51:37 +00002882
Chris Lattner913849b2007-08-21 00:55:23 +00002883 // Update to the new value. Optimize for the case when we have a single
2884 // operand that we're changing, but handle bulk updates efficiently.
2885 if (NumUpdated == 1) {
2886 unsigned OperandToUpdate = U-OperandList;
2887 assert(getOperand(OperandToUpdate) == From &&
2888 "ReplaceAllUsesWith broken!");
2889 setOperand(OperandToUpdate, ToC);
2890 } else {
2891 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2892 if (getOperand(i) == From)
2893 setOperand(i, ToC);
2894 }
Chris Lattnerb64419a2005-10-03 22:51:37 +00002895 return;
2896 }
2897 }
2898
2899 // Otherwise, I do need to replace this with an existing value.
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002900 assert(Replacement != this && "I didn't contain From!");
2901
Chris Lattner7a1450d2005-10-04 18:13:04 +00002902 // Everyone using this now uses the replacement.
2903 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002904
2905 // Delete the old constant!
2906 destroyConstant();
2907}
2908
2909void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002910 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002911 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
Chris Lattner8760ec72005-10-04 01:17:50 +00002912 Constant *ToC = cast<Constant>(To);
2913
Chris Lattnerdff59112005-10-04 18:47:09 +00002914 unsigned OperandToUpdate = U-OperandList;
2915 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2916
Jim Laskeyc03caef2006-07-17 17:38:29 +00002917 std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
Chris Lattner8760ec72005-10-04 01:17:50 +00002918 Lookup.first.first = getType();
2919 Lookup.second = this;
2920 std::vector<Constant*> &Values = Lookup.first.second;
2921 Values.reserve(getNumOperands()); // Build replacement struct.
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002922
Chris Lattnerdff59112005-10-04 18:47:09 +00002923
Chris Lattner8760ec72005-10-04 01:17:50 +00002924 // Fill values with the modified operands of the constant struct. Also,
2925 // compute whether this turns into an all-zeros struct.
Chris Lattnerdff59112005-10-04 18:47:09 +00002926 bool isAllZeros = false;
2927 if (!ToC->isNullValue()) {
2928 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
2929 Values.push_back(cast<Constant>(O->get()));
2930 } else {
2931 isAllZeros = true;
2932 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2933 Constant *Val = cast<Constant>(O->get());
2934 Values.push_back(Val);
2935 if (isAllZeros) isAllZeros = Val->isNullValue();
2936 }
Chris Lattner8760ec72005-10-04 01:17:50 +00002937 }
Chris Lattnerdff59112005-10-04 18:47:09 +00002938 Values[OperandToUpdate] = ToC;
2939
Chris Lattner8760ec72005-10-04 01:17:50 +00002940 Constant *Replacement = 0;
2941 if (isAllZeros) {
2942 Replacement = ConstantAggregateZero::get(getType());
2943 } else {
2944 // Check to see if we have this array type already.
Owen Anderson65c5cd72009-06-17 20:34:43 +00002945 sys::ScopedWriter Writer(&*ConstantsLock);
Chris Lattner8760ec72005-10-04 01:17:50 +00002946 bool Exists;
Jim Laskeyc03caef2006-07-17 17:38:29 +00002947 StructConstantsTy::MapTy::iterator I =
Chris Lattner69edc982006-09-28 00:35:06 +00002948 StructConstants->InsertOrGetItem(Lookup, Exists);
Chris Lattner8760ec72005-10-04 01:17:50 +00002949
2950 if (Exists) {
2951 Replacement = I->second;
2952 } else {
2953 // Okay, the new shape doesn't exist in the system yet. Instead of
2954 // creating a new constant struct, inserting it, replaceallusesof'ing the
2955 // old with the new, then deleting the old... just update the current one
2956 // in place!
Chris Lattner69edc982006-09-28 00:35:06 +00002957 StructConstants->MoveConstantToNewSlot(this, I);
Chris Lattner8760ec72005-10-04 01:17:50 +00002958
Chris Lattnerdff59112005-10-04 18:47:09 +00002959 // Update to the new value.
2960 setOperand(OperandToUpdate, ToC);
Chris Lattner8760ec72005-10-04 01:17:50 +00002961 return;
2962 }
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002963 }
2964
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002965 assert(Replacement != this && "I didn't contain From!");
2966
Chris Lattner7a1450d2005-10-04 18:13:04 +00002967 // Everyone using this now uses the replacement.
2968 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002969
2970 // Delete the old constant!
2971 destroyConstant();
2972}
2973
Reid Spencerd84d35b2007-02-15 02:26:10 +00002974void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002975 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002976 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2977
2978 std::vector<Constant*> Values;
2979 Values.reserve(getNumOperands()); // Build replacement array...
2980 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2981 Constant *Val = getOperand(i);
2982 if (Val == From) Val = cast<Constant>(To);
2983 Values.push_back(Val);
2984 }
2985
Reid Spencerd84d35b2007-02-15 02:26:10 +00002986 Constant *Replacement = ConstantVector::get(getType(), Values);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002987 assert(Replacement != this && "I didn't contain From!");
2988
Chris Lattner7a1450d2005-10-04 18:13:04 +00002989 // Everyone using this now uses the replacement.
2990 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002991
2992 // Delete the old constant!
2993 destroyConstant();
2994}
2995
2996void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002997 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002998 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2999 Constant *To = cast<Constant>(ToV);
3000
3001 Constant *Replacement = 0;
3002 if (getOpcode() == Instruction::GetElementPtr) {
Chris Lattnerb5d70302007-02-19 20:01:23 +00003003 SmallVector<Constant*, 8> Indices;
Chris Lattnerc4062ba2005-10-03 21:58:36 +00003004 Constant *Pointer = getOperand(0);
3005 Indices.reserve(getNumOperands()-1);
3006 if (Pointer == From) Pointer = To;
3007
3008 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
3009 Constant *Val = getOperand(i);
3010 if (Val == From) Val = To;
3011 Indices.push_back(Val);
3012 }
Chris Lattnerb5d70302007-02-19 20:01:23 +00003013 Replacement = ConstantExpr::getGetElementPtr(Pointer,
3014 &Indices[0], Indices.size());
Dan Gohman12fce772008-05-15 19:50:34 +00003015 } else if (getOpcode() == Instruction::ExtractValue) {
Dan Gohman12fce772008-05-15 19:50:34 +00003016 Constant *Agg = getOperand(0);
Dan Gohman12fce772008-05-15 19:50:34 +00003017 if (Agg == From) Agg = To;
3018
Dan Gohman1ecaf452008-05-31 00:58:22 +00003019 const SmallVector<unsigned, 4> &Indices = getIndices();
Dan Gohman12fce772008-05-15 19:50:34 +00003020 Replacement = ConstantExpr::getExtractValue(Agg,
3021 &Indices[0], Indices.size());
3022 } else if (getOpcode() == Instruction::InsertValue) {
Dan Gohman12fce772008-05-15 19:50:34 +00003023 Constant *Agg = getOperand(0);
3024 Constant *Val = getOperand(1);
Dan Gohman12fce772008-05-15 19:50:34 +00003025 if (Agg == From) Agg = To;
3026 if (Val == From) Val = To;
3027
Dan Gohman1ecaf452008-05-31 00:58:22 +00003028 const SmallVector<unsigned, 4> &Indices = getIndices();
Dan Gohman12fce772008-05-15 19:50:34 +00003029 Replacement = ConstantExpr::getInsertValue(Agg, Val,
3030 &Indices[0], Indices.size());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003031 } else if (isCast()) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00003032 assert(getOperand(0) == From && "Cast only has one use!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003033 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
Chris Lattnerc4062ba2005-10-03 21:58:36 +00003034 } else if (getOpcode() == Instruction::Select) {
3035 Constant *C1 = getOperand(0);
3036 Constant *C2 = getOperand(1);
3037 Constant *C3 = getOperand(2);
3038 if (C1 == From) C1 = To;
3039 if (C2 == From) C2 = To;
3040 if (C3 == From) C3 = To;
3041 Replacement = ConstantExpr::getSelect(C1, C2, C3);
Robert Bocchino23004482006-01-10 19:05:34 +00003042 } else if (getOpcode() == Instruction::ExtractElement) {
3043 Constant *C1 = getOperand(0);
3044 Constant *C2 = getOperand(1);
3045 if (C1 == From) C1 = To;
3046 if (C2 == From) C2 = To;
3047 Replacement = ConstantExpr::getExtractElement(C1, C2);
Chris Lattnera93b4b52006-04-08 05:09:48 +00003048 } else if (getOpcode() == Instruction::InsertElement) {
3049 Constant *C1 = getOperand(0);
3050 Constant *C2 = getOperand(1);
3051 Constant *C3 = getOperand(1);
3052 if (C1 == From) C1 = To;
3053 if (C2 == From) C2 = To;
3054 if (C3 == From) C3 = To;
3055 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
3056 } else if (getOpcode() == Instruction::ShuffleVector) {
3057 Constant *C1 = getOperand(0);
3058 Constant *C2 = getOperand(1);
3059 Constant *C3 = getOperand(2);
3060 if (C1 == From) C1 = To;
3061 if (C2 == From) C2 = To;
3062 if (C3 == From) C3 = To;
3063 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
Reid Spenceree3c9912006-12-04 05:19:50 +00003064 } else if (isCompare()) {
3065 Constant *C1 = getOperand(0);
3066 Constant *C2 = getOperand(1);
3067 if (C1 == From) C1 = To;
3068 if (C2 == From) C2 = To;
3069 if (getOpcode() == Instruction::ICmp)
3070 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
Chris Lattnereab49262008-07-14 05:17:31 +00003071 else if (getOpcode() == Instruction::FCmp)
Reid Spenceree3c9912006-12-04 05:19:50 +00003072 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
Chris Lattnereab49262008-07-14 05:17:31 +00003073 else if (getOpcode() == Instruction::VICmp)
3074 Replacement = ConstantExpr::getVICmp(getPredicate(), C1, C2);
3075 else {
3076 assert(getOpcode() == Instruction::VFCmp);
3077 Replacement = ConstantExpr::getVFCmp(getPredicate(), C1, C2);
3078 }
Chris Lattnerc4062ba2005-10-03 21:58:36 +00003079 } else if (getNumOperands() == 2) {
3080 Constant *C1 = getOperand(0);
3081 Constant *C2 = getOperand(1);
3082 if (C1 == From) C1 = To;
3083 if (C2 == From) C2 = To;
3084 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
3085 } else {
3086 assert(0 && "Unknown ConstantExpr type!");
3087 return;
3088 }
3089
3090 assert(Replacement != this && "I didn't contain From!");
3091
Chris Lattner7a1450d2005-10-04 18:13:04 +00003092 // Everyone using this now uses the replacement.
3093 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00003094
3095 // Delete the old constant!
3096 destroyConstant();
Matthijs Kooijmanba5d7ef2008-07-03 07:46:41 +00003097}
Nick Lewycky49f89192009-04-04 07:22:01 +00003098
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00003099void MDNode::replaceElement(Value *From, Value *To) {
3100 SmallVector<Value*, 4> Values;
3101 Values.reserve(getNumElements()); // Build replacement array...
3102 for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
3103 Value *Val = getElement(i);
3104 if (Val == From) Val = To;
Nick Lewycky49f89192009-04-04 07:22:01 +00003105 Values.push_back(Val);
3106 }
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00003107
3108 MDNode *Replacement = MDNode::get(&Values[0], Values.size());
Nick Lewycky49f89192009-04-04 07:22:01 +00003109 assert(Replacement != this && "I didn't contain From!");
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00003110
Nick Lewycky49f89192009-04-04 07:22:01 +00003111 uncheckedReplaceAllUsesWith(Replacement);
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00003112
Nick Lewycky49f89192009-04-04 07:22:01 +00003113 destroyConstant();
3114}