blob: 3e09bc6245c571a0e75e35e8f406e9879297ae26 [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/Support/Threading.h"
29#include "llvm/System/RWMutex.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) {
309 ConstantsLock->writer_acquire();
310 ConstantInt *&Slot = (*IntConstants)[Key];
311 if (!Slot) {
312 Slot = new ConstantInt(ITy, V);
313 }
314 ConstantsLock->writer_release();
315 }
316
Reid Spencerb31bffe2007-02-26 23:54:03 +0000317 return Slot;
Owen Anderson2d7231d2009-06-17 18:40:29 +0000318 } else {
319 ConstantInt *&Slot = (*IntConstants)[Key];
320 // if it exists, return it.
321 if (Slot)
322 return Slot;
323 // otherwise create a new one, insert it, and return it.
324 return Slot = new ConstantInt(ITy, V);
325 }
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000326}
327
Dan Gohman7ccc52f2009-06-15 22:12:54 +0000328Constant *ConstantInt::get(const Type *Ty, const APInt &V) {
329 ConstantInt *C = ConstantInt::get(V);
330 assert(C->getType() == Ty->getScalarType() &&
331 "ConstantInt type doesn't match the type implied by its value!");
332
333 // For vectors, broadcast the value.
334 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
335 return
336 ConstantVector::get(std::vector<Constant *>(VTy->getNumElements(), C));
337
338 return C;
339}
340
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000341//===----------------------------------------------------------------------===//
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000342// ConstantFP
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000343//===----------------------------------------------------------------------===//
344
Chris Lattner98bd9392008-04-09 06:38:30 +0000345static const fltSemantics *TypeToFloatSemantics(const Type *Ty) {
346 if (Ty == Type::FloatTy)
347 return &APFloat::IEEEsingle;
348 if (Ty == Type::DoubleTy)
349 return &APFloat::IEEEdouble;
350 if (Ty == Type::X86_FP80Ty)
351 return &APFloat::x87DoubleExtended;
352 else if (Ty == Type::FP128Ty)
353 return &APFloat::IEEEquad;
354
355 assert(Ty == Type::PPC_FP128Ty && "Unknown FP format");
356 return &APFloat::PPCDoubleDouble;
357}
358
Dale Johannesend246b2c2007-08-30 00:23:21 +0000359ConstantFP::ConstantFP(const Type *Ty, const APFloat& V)
360 : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
Chris Lattner98bd9392008-04-09 06:38:30 +0000361 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
362 "FP type Mismatch");
Chris Lattner2f7c9632001-06-06 20:29:01 +0000363}
364
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000365bool ConstantFP::isNullValue() const {
Dale Johannesena719a602007-08-24 00:56:33 +0000366 return Val.isZero() && !Val.isNegative();
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000367}
368
Dale Johannesen98d3a082007-09-14 22:26:36 +0000369ConstantFP *ConstantFP::getNegativeZero(const Type *Ty) {
370 APFloat apf = cast <ConstantFP>(Constant::getNullValue(Ty))->getValueAPF();
371 apf.changeSign();
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000372 return ConstantFP::get(apf);
Dale Johannesen98d3a082007-09-14 22:26:36 +0000373}
374
Dale Johannesend246b2c2007-08-30 00:23:21 +0000375bool ConstantFP::isExactlyValue(const APFloat& V) const {
376 return Val.bitwiseIsEqual(V);
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000377}
378
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000379namespace {
Dale Johannesena719a602007-08-24 00:56:33 +0000380 struct DenseMapAPFloatKeyInfo {
Dale Johannesenbdea32d2007-08-24 22:09:56 +0000381 struct KeyTy {
382 APFloat val;
383 KeyTy(const APFloat& V) : val(V){}
384 KeyTy(const KeyTy& that) : val(that.val) {}
385 bool operator==(const KeyTy& that) const {
386 return this->val.bitwiseIsEqual(that.val);
387 }
388 bool operator!=(const KeyTy& that) const {
389 return !this->operator==(that);
390 }
391 };
392 static inline KeyTy getEmptyKey() {
393 return KeyTy(APFloat(APFloat::Bogus,1));
Reid Spencerb31bffe2007-02-26 23:54:03 +0000394 }
Dale Johannesenbdea32d2007-08-24 22:09:56 +0000395 static inline KeyTy getTombstoneKey() {
396 return KeyTy(APFloat(APFloat::Bogus,2));
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000397 }
Dale Johannesenbdea32d2007-08-24 22:09:56 +0000398 static unsigned getHashValue(const KeyTy &Key) {
399 return Key.val.getHashValue();
Dale Johannesena719a602007-08-24 00:56:33 +0000400 }
Chris Lattner0625bd62007-09-17 18:34:04 +0000401 static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
402 return LHS == RHS;
403 }
Dale Johannesena719a602007-08-24 00:56:33 +0000404 static bool isPod() { return false; }
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000405 };
406}
407
408//---- ConstantFP::get() implementation...
409//
Dale Johannesenbdea32d2007-08-24 22:09:56 +0000410typedef DenseMap<DenseMapAPFloatKeyInfo::KeyTy, ConstantFP*,
Dale Johannesena719a602007-08-24 00:56:33 +0000411 DenseMapAPFloatKeyInfo> FPMapTy;
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000412
Dale Johannesena719a602007-08-24 00:56:33 +0000413static ManagedStatic<FPMapTy> FPConstants;
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000414
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000415ConstantFP *ConstantFP::get(const APFloat &V) {
Dale Johannesend246b2c2007-08-30 00:23:21 +0000416 DenseMapAPFloatKeyInfo::KeyTy Key(V);
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000417
Owen Anderson2d7231d2009-06-17 18:40:29 +0000418 if (llvm_is_multithreaded()) {
419 ConstantsLock->reader_acquire();
420 ConstantFP *&Slot = (*FPConstants)[Key];
421 ConstantsLock->reader_release();
422
423 if (!Slot) {
424 ConstantsLock->writer_acquire();
425 Slot = (*FPConstants)[Key];
426 if (!Slot) {
427 const Type *Ty;
428 if (&V.getSemantics() == &APFloat::IEEEsingle)
429 Ty = Type::FloatTy;
430 else if (&V.getSemantics() == &APFloat::IEEEdouble)
431 Ty = Type::DoubleTy;
432 else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
433 Ty = Type::X86_FP80Ty;
434 else if (&V.getSemantics() == &APFloat::IEEEquad)
435 Ty = Type::FP128Ty;
436 else {
437 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble &&
438 "Unknown FP format");
439 Ty = Type::PPC_FP128Ty;
440 }
441
442 Slot = new ConstantFP(Ty, V);
443 }
444 ConstantsLock->writer_release();
445 }
446
447 return Slot;
448 } else {
449 ConstantFP *&Slot = (*FPConstants)[Key];
450 if (Slot) return Slot;
451
452 const Type *Ty;
453 if (&V.getSemantics() == &APFloat::IEEEsingle)
454 Ty = Type::FloatTy;
455 else if (&V.getSemantics() == &APFloat::IEEEdouble)
456 Ty = Type::DoubleTy;
457 else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
458 Ty = Type::X86_FP80Ty;
459 else if (&V.getSemantics() == &APFloat::IEEEquad)
460 Ty = Type::FP128Ty;
461 else {
462 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble &&
463 "Unknown FP format");
464 Ty = Type::PPC_FP128Ty;
465 }
466
467 return Slot = new ConstantFP(Ty, V);
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000468 }
Dale Johannesend246b2c2007-08-30 00:23:21 +0000469}
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000470
Chris Lattner98bd9392008-04-09 06:38:30 +0000471/// get() - This returns a constant fp for the specified value in the
472/// specified type. This should only be used for simple constant values like
473/// 2.0/1.0 etc, that are known-valid both as double and as the target format.
Dan Gohman7ccc52f2009-06-15 22:12:54 +0000474Constant *ConstantFP::get(const Type *Ty, double V) {
Chris Lattner98bd9392008-04-09 06:38:30 +0000475 APFloat FV(V);
Dale Johannesen4f0bd682008-10-09 23:00:39 +0000476 bool ignored;
Dan Gohman7ccc52f2009-06-15 22:12:54 +0000477 FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
478 APFloat::rmNearestTiesToEven, &ignored);
479 Constant *C = get(FV);
480
481 // For vectors, broadcast the value.
482 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
483 return
484 ConstantVector::get(std::vector<Constant *>(VTy->getNumElements(), C));
485
486 return C;
Chris Lattner98bd9392008-04-09 06:38:30 +0000487}
488
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000489//===----------------------------------------------------------------------===//
490// ConstantXXX Classes
491//===----------------------------------------------------------------------===//
492
493
Chris Lattner3462ae32001-12-03 22:26:30 +0000494ConstantArray::ConstantArray(const ArrayType *T,
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000495 const std::vector<Constant*> &V)
Gabor Greiff6caff662008-05-10 08:32:32 +0000496 : Constant(T, ConstantArrayVal,
497 OperandTraits<ConstantArray>::op_end(this) - V.size(),
498 V.size()) {
Alkis Evlogimenos0507ffe2004-09-15 02:32:15 +0000499 assert(V.size() == T->getNumElements() &&
500 "Invalid initializer vector for constant array");
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000501 Use *OL = OperandList;
Chris Lattner0144fad2005-10-03 21:56:24 +0000502 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
503 I != E; ++I, ++OL) {
Chris Lattner20a24452005-10-07 05:23:36 +0000504 Constant *C = *I;
505 assert((C->getType() == T->getElementType() ||
Alkis Evlogimenoscb031d92004-09-10 04:16:59 +0000506 (T->isAbstract() &&
Chris Lattner20a24452005-10-07 05:23:36 +0000507 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
Alkis Evlogimenoscb031d92004-09-10 04:16:59 +0000508 "Initializer for array element doesn't match array element type!");
Gabor Greif2d3024d2008-05-26 21:33:52 +0000509 *OL = C;
Chris Lattner2f7c9632001-06-06 20:29:01 +0000510 }
511}
512
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000513
Chris Lattner3462ae32001-12-03 22:26:30 +0000514ConstantStruct::ConstantStruct(const StructType *T,
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000515 const std::vector<Constant*> &V)
Gabor Greiff6caff662008-05-10 08:32:32 +0000516 : Constant(T, ConstantStructVal,
517 OperandTraits<ConstantStruct>::op_end(this) - V.size(),
518 V.size()) {
Chris Lattnerac6db752004-02-09 04:37:31 +0000519 assert(V.size() == T->getNumElements() &&
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000520 "Invalid initializer vector for constant structure");
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000521 Use *OL = OperandList;
Chris Lattner0144fad2005-10-03 21:56:24 +0000522 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
523 I != E; ++I, ++OL) {
Chris Lattner20a24452005-10-07 05:23:36 +0000524 Constant *C = *I;
525 assert((C->getType() == T->getElementType(I-V.begin()) ||
Chris Lattner0144fad2005-10-03 21:56:24 +0000526 ((T->getElementType(I-V.begin())->isAbstract() ||
Chris Lattner20a24452005-10-07 05:23:36 +0000527 C->getType()->isAbstract()) &&
Chris Lattner0144fad2005-10-03 21:56:24 +0000528 T->getElementType(I-V.begin())->getTypeID() ==
Chris Lattner20a24452005-10-07 05:23:36 +0000529 C->getType()->getTypeID())) &&
Chris Lattner93c8f142003-06-02 17:42:47 +0000530 "Initializer for struct element doesn't match struct element type!");
Gabor Greif2d3024d2008-05-26 21:33:52 +0000531 *OL = C;
Chris Lattner2f7c9632001-06-06 20:29:01 +0000532 }
533}
534
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000535
Reid Spencerd84d35b2007-02-15 02:26:10 +0000536ConstantVector::ConstantVector(const VectorType *T,
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000537 const std::vector<Constant*> &V)
Gabor Greiff6caff662008-05-10 08:32:32 +0000538 : Constant(T, ConstantVectorVal,
539 OperandTraits<ConstantVector>::op_end(this) - V.size(),
540 V.size()) {
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000541 Use *OL = OperandList;
Chris Lattner0144fad2005-10-03 21:56:24 +0000542 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
543 I != E; ++I, ++OL) {
Chris Lattner20a24452005-10-07 05:23:36 +0000544 Constant *C = *I;
545 assert((C->getType() == T->getElementType() ||
Alkis Evlogimenoscb031d92004-09-10 04:16:59 +0000546 (T->isAbstract() &&
Chris Lattner20a24452005-10-07 05:23:36 +0000547 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
Dan Gohman30978072007-05-24 14:36:04 +0000548 "Initializer for vector element doesn't match vector element type!");
Gabor Greif2d3024d2008-05-26 21:33:52 +0000549 *OL = C;
Brian Gaeke02209042004-08-20 06:00:58 +0000550 }
551}
552
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000553
Gabor Greiff6caff662008-05-10 08:32:32 +0000554namespace llvm {
Gordon Henriksen14a55692007-12-10 02:14:30 +0000555// We declare several classes private to this file, so use an anonymous
556// namespace
557namespace {
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000558
Gordon Henriksen14a55692007-12-10 02:14:30 +0000559/// UnaryConstantExpr - This class is private to Constants.cpp, and is used
560/// behind the scenes to implement unary constant exprs.
561class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
Gabor Greife9ecc682008-04-06 20:25:17 +0000562 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Gordon Henriksen14a55692007-12-10 02:14:30 +0000563public:
Gabor Greife9ecc682008-04-06 20:25:17 +0000564 // allocate space for exactly one operand
565 void *operator new(size_t s) {
566 return User::operator new(s, 1);
567 }
Gordon Henriksen14a55692007-12-10 02:14:30 +0000568 UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
Gabor Greiff6caff662008-05-10 08:32:32 +0000569 : ConstantExpr(Ty, Opcode, &Op<0>(), 1) {
570 Op<0>() = C;
571 }
572 /// Transparently provide more efficient getOperand methods.
573 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000574};
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000575
Gordon Henriksen14a55692007-12-10 02:14:30 +0000576/// BinaryConstantExpr - This class is private to Constants.cpp, and is used
577/// behind the scenes to implement binary constant exprs.
578class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
Gabor Greife9ecc682008-04-06 20:25:17 +0000579 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Gordon Henriksen14a55692007-12-10 02:14:30 +0000580public:
Gabor Greife9ecc682008-04-06 20:25:17 +0000581 // allocate space for exactly two operands
582 void *operator new(size_t s) {
583 return User::operator new(s, 2);
584 }
Gordon Henriksen14a55692007-12-10 02:14:30 +0000585 BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
Gabor Greiff6caff662008-05-10 08:32:32 +0000586 : ConstantExpr(C1->getType(), Opcode, &Op<0>(), 2) {
Gabor Greif2d3024d2008-05-26 21:33:52 +0000587 Op<0>() = C1;
588 Op<1>() = C2;
Gordon Henriksen14a55692007-12-10 02:14:30 +0000589 }
Gabor Greiff6caff662008-05-10 08:32:32 +0000590 /// Transparently provide more efficient getOperand methods.
591 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000592};
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000593
Gordon Henriksen14a55692007-12-10 02:14:30 +0000594/// SelectConstantExpr - This class is private to Constants.cpp, and is used
595/// behind the scenes to implement select constant exprs.
596class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
Gabor Greife9ecc682008-04-06 20:25:17 +0000597 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Gordon Henriksen14a55692007-12-10 02:14:30 +0000598public:
Gabor Greife9ecc682008-04-06 20:25:17 +0000599 // allocate space for exactly three operands
600 void *operator new(size_t s) {
601 return User::operator new(s, 3);
602 }
Gordon Henriksen14a55692007-12-10 02:14:30 +0000603 SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
Gabor Greiff6caff662008-05-10 08:32:32 +0000604 : ConstantExpr(C2->getType(), Instruction::Select, &Op<0>(), 3) {
Gabor Greif2d3024d2008-05-26 21:33:52 +0000605 Op<0>() = C1;
606 Op<1>() = C2;
607 Op<2>() = C3;
Gordon Henriksen14a55692007-12-10 02:14:30 +0000608 }
Gabor Greiff6caff662008-05-10 08:32:32 +0000609 /// Transparently provide more efficient getOperand methods.
610 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000611};
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000612
Gordon Henriksen14a55692007-12-10 02:14:30 +0000613/// ExtractElementConstantExpr - This class is private to
614/// Constants.cpp, and is used behind the scenes to implement
615/// extractelement constant exprs.
616class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
Gabor Greife9ecc682008-04-06 20:25:17 +0000617 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Gordon Henriksen14a55692007-12-10 02:14:30 +0000618public:
Gabor Greife9ecc682008-04-06 20:25:17 +0000619 // allocate space for exactly two operands
620 void *operator new(size_t s) {
621 return User::operator new(s, 2);
622 }
Gordon Henriksen14a55692007-12-10 02:14:30 +0000623 ExtractElementConstantExpr(Constant *C1, Constant *C2)
624 : ConstantExpr(cast<VectorType>(C1->getType())->getElementType(),
Gabor Greiff6caff662008-05-10 08:32:32 +0000625 Instruction::ExtractElement, &Op<0>(), 2) {
Gabor Greif2d3024d2008-05-26 21:33:52 +0000626 Op<0>() = C1;
627 Op<1>() = C2;
Gordon Henriksen14a55692007-12-10 02:14:30 +0000628 }
Gabor Greiff6caff662008-05-10 08:32:32 +0000629 /// Transparently provide more efficient getOperand methods.
630 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000631};
Robert Bocchino23004482006-01-10 19:05:34 +0000632
Gordon Henriksen14a55692007-12-10 02:14:30 +0000633/// InsertElementConstantExpr - This class is private to
634/// Constants.cpp, and is used behind the scenes to implement
635/// insertelement constant exprs.
636class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
Gabor Greife9ecc682008-04-06 20:25:17 +0000637 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Gordon Henriksen14a55692007-12-10 02:14:30 +0000638public:
Gabor Greife9ecc682008-04-06 20:25:17 +0000639 // allocate space for exactly three operands
640 void *operator new(size_t s) {
641 return User::operator new(s, 3);
642 }
Gordon Henriksen14a55692007-12-10 02:14:30 +0000643 InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
644 : ConstantExpr(C1->getType(), Instruction::InsertElement,
Gabor Greiff6caff662008-05-10 08:32:32 +0000645 &Op<0>(), 3) {
Gabor Greif2d3024d2008-05-26 21:33:52 +0000646 Op<0>() = C1;
647 Op<1>() = C2;
648 Op<2>() = C3;
Gordon Henriksen14a55692007-12-10 02:14:30 +0000649 }
Gabor Greiff6caff662008-05-10 08:32:32 +0000650 /// Transparently provide more efficient getOperand methods.
651 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000652};
Robert Bocchinoca27f032006-01-17 20:07:22 +0000653
Gordon Henriksen14a55692007-12-10 02:14:30 +0000654/// ShuffleVectorConstantExpr - This class is private to
655/// Constants.cpp, and is used behind the scenes to implement
656/// shufflevector constant exprs.
657class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
Gabor Greife9ecc682008-04-06 20:25:17 +0000658 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Gordon Henriksen14a55692007-12-10 02:14:30 +0000659public:
Gabor Greife9ecc682008-04-06 20:25:17 +0000660 // allocate space for exactly three operands
661 void *operator new(size_t s) {
662 return User::operator new(s, 3);
663 }
Gordon Henriksen14a55692007-12-10 02:14:30 +0000664 ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
Nate Begeman94aa38d2009-02-12 21:28:33 +0000665 : ConstantExpr(VectorType::get(
666 cast<VectorType>(C1->getType())->getElementType(),
667 cast<VectorType>(C3->getType())->getNumElements()),
668 Instruction::ShuffleVector,
Gabor Greiff6caff662008-05-10 08:32:32 +0000669 &Op<0>(), 3) {
Gabor Greif2d3024d2008-05-26 21:33:52 +0000670 Op<0>() = C1;
671 Op<1>() = C2;
672 Op<2>() = C3;
Gordon Henriksen14a55692007-12-10 02:14:30 +0000673 }
Gabor Greiff6caff662008-05-10 08:32:32 +0000674 /// Transparently provide more efficient getOperand methods.
675 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000676};
677
Dan Gohman12fce772008-05-15 19:50:34 +0000678/// ExtractValueConstantExpr - This class is private to
679/// Constants.cpp, and is used behind the scenes to implement
680/// extractvalue constant exprs.
681class VISIBILITY_HIDDEN ExtractValueConstantExpr : public ConstantExpr {
Dan Gohman1ecaf452008-05-31 00:58:22 +0000682 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Dan Gohman12fce772008-05-15 19:50:34 +0000683public:
Dan Gohman1ecaf452008-05-31 00:58:22 +0000684 // allocate space for exactly one operand
685 void *operator new(size_t s) {
686 return User::operator new(s, 1);
Dan Gohman12fce772008-05-15 19:50:34 +0000687 }
Dan Gohman1ecaf452008-05-31 00:58:22 +0000688 ExtractValueConstantExpr(Constant *Agg,
689 const SmallVector<unsigned, 4> &IdxList,
690 const Type *DestTy)
691 : ConstantExpr(DestTy, Instruction::ExtractValue, &Op<0>(), 1),
692 Indices(IdxList) {
693 Op<0>() = Agg;
694 }
695
Dan Gohman7bb04502008-05-31 19:09:08 +0000696 /// Indices - These identify which value to extract.
Dan Gohman1ecaf452008-05-31 00:58:22 +0000697 const SmallVector<unsigned, 4> Indices;
698
Dan Gohman12fce772008-05-15 19:50:34 +0000699 /// Transparently provide more efficient getOperand methods.
700 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
701};
702
703/// InsertValueConstantExpr - This class is private to
704/// Constants.cpp, and is used behind the scenes to implement
705/// insertvalue constant exprs.
706class VISIBILITY_HIDDEN InsertValueConstantExpr : public ConstantExpr {
Dan Gohman1ecaf452008-05-31 00:58:22 +0000707 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Dan Gohman12fce772008-05-15 19:50:34 +0000708public:
Dan Gohman1ecaf452008-05-31 00:58:22 +0000709 // allocate space for exactly one operand
710 void *operator new(size_t s) {
711 return User::operator new(s, 2);
Dan Gohman12fce772008-05-15 19:50:34 +0000712 }
Dan Gohman1ecaf452008-05-31 00:58:22 +0000713 InsertValueConstantExpr(Constant *Agg, Constant *Val,
714 const SmallVector<unsigned, 4> &IdxList,
715 const Type *DestTy)
716 : ConstantExpr(DestTy, Instruction::InsertValue, &Op<0>(), 2),
717 Indices(IdxList) {
718 Op<0>() = Agg;
719 Op<1>() = Val;
720 }
721
Dan Gohman7bb04502008-05-31 19:09:08 +0000722 /// Indices - These identify the position for the insertion.
Dan Gohman1ecaf452008-05-31 00:58:22 +0000723 const SmallVector<unsigned, 4> Indices;
724
Dan Gohman12fce772008-05-15 19:50:34 +0000725 /// Transparently provide more efficient getOperand methods.
726 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
727};
728
729
Gordon Henriksen14a55692007-12-10 02:14:30 +0000730/// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
731/// used behind the scenes to implement getelementpr constant exprs.
Gabor Greife9ecc682008-04-06 20:25:17 +0000732class VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
Gordon Henriksen14a55692007-12-10 02:14:30 +0000733 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
Gabor Greiff6caff662008-05-10 08:32:32 +0000734 const Type *DestTy);
Gabor Greife9ecc682008-04-06 20:25:17 +0000735public:
Gabor Greif697e94c2008-05-15 10:04:30 +0000736 static GetElementPtrConstantExpr *Create(Constant *C,
737 const std::vector<Constant*>&IdxList,
Gabor Greiff6caff662008-05-10 08:32:32 +0000738 const Type *DestTy) {
Gabor Greif697e94c2008-05-15 10:04:30 +0000739 return new(IdxList.size() + 1)
740 GetElementPtrConstantExpr(C, IdxList, DestTy);
Gabor Greife9ecc682008-04-06 20:25:17 +0000741 }
Gabor Greiff6caff662008-05-10 08:32:32 +0000742 /// Transparently provide more efficient getOperand methods.
743 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000744};
745
746// CompareConstantExpr - This class is private to Constants.cpp, and is used
747// behind the scenes to implement ICmp and FCmp constant expressions. This is
748// needed in order to store the predicate value for these instructions.
749struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
Gabor Greife9ecc682008-04-06 20:25:17 +0000750 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
751 // allocate space for exactly two operands
752 void *operator new(size_t s) {
753 return User::operator new(s, 2);
754 }
Gordon Henriksen14a55692007-12-10 02:14:30 +0000755 unsigned short predicate;
Nate Begemand2195702008-05-12 19:01:56 +0000756 CompareConstantExpr(const Type *ty, Instruction::OtherOps opc,
757 unsigned short pred, Constant* LHS, Constant* RHS)
758 : ConstantExpr(ty, opc, &Op<0>(), 2), predicate(pred) {
Gabor Greif2d3024d2008-05-26 21:33:52 +0000759 Op<0>() = LHS;
760 Op<1>() = RHS;
Gordon Henriksen14a55692007-12-10 02:14:30 +0000761 }
Gabor Greiff6caff662008-05-10 08:32:32 +0000762 /// Transparently provide more efficient getOperand methods.
763 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000764};
765
766} // end anonymous namespace
767
Gabor Greiff6caff662008-05-10 08:32:32 +0000768template <>
769struct OperandTraits<UnaryConstantExpr> : FixedNumOperandTraits<1> {
770};
771DEFINE_TRANSPARENT_OPERAND_ACCESSORS(UnaryConstantExpr, Value)
772
773template <>
774struct OperandTraits<BinaryConstantExpr> : FixedNumOperandTraits<2> {
775};
776DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BinaryConstantExpr, Value)
777
778template <>
779struct OperandTraits<SelectConstantExpr> : FixedNumOperandTraits<3> {
780};
781DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectConstantExpr, Value)
782
783template <>
784struct OperandTraits<ExtractElementConstantExpr> : FixedNumOperandTraits<2> {
785};
786DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementConstantExpr, Value)
787
788template <>
789struct OperandTraits<InsertElementConstantExpr> : FixedNumOperandTraits<3> {
790};
791DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementConstantExpr, Value)
792
793template <>
794struct OperandTraits<ShuffleVectorConstantExpr> : FixedNumOperandTraits<3> {
795};
796DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorConstantExpr, Value)
797
Dan Gohman12fce772008-05-15 19:50:34 +0000798template <>
Dan Gohman1ecaf452008-05-31 00:58:22 +0000799struct OperandTraits<ExtractValueConstantExpr> : FixedNumOperandTraits<1> {
Dan Gohman12fce772008-05-15 19:50:34 +0000800};
Dan Gohman12fce772008-05-15 19:50:34 +0000801DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractValueConstantExpr, Value)
802
803template <>
Dan Gohman1ecaf452008-05-31 00:58:22 +0000804struct OperandTraits<InsertValueConstantExpr> : FixedNumOperandTraits<2> {
Dan Gohman12fce772008-05-15 19:50:34 +0000805};
Dan Gohman12fce772008-05-15 19:50:34 +0000806DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueConstantExpr, Value)
807
Gabor Greiff6caff662008-05-10 08:32:32 +0000808template <>
809struct OperandTraits<GetElementPtrConstantExpr> : VariadicOperandTraits<1> {
810};
811
812GetElementPtrConstantExpr::GetElementPtrConstantExpr
813 (Constant *C,
814 const std::vector<Constant*> &IdxList,
815 const Type *DestTy)
816 : ConstantExpr(DestTy, Instruction::GetElementPtr,
817 OperandTraits<GetElementPtrConstantExpr>::op_end(this)
818 - (IdxList.size()+1),
819 IdxList.size()+1) {
Gabor Greif2d3024d2008-05-26 21:33:52 +0000820 OperandList[0] = C;
Gabor Greiff6caff662008-05-10 08:32:32 +0000821 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
Gabor Greif2d3024d2008-05-26 21:33:52 +0000822 OperandList[i+1] = IdxList[i];
Gabor Greiff6caff662008-05-10 08:32:32 +0000823}
824
825DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrConstantExpr, Value)
826
827
828template <>
829struct OperandTraits<CompareConstantExpr> : FixedNumOperandTraits<2> {
830};
831DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CompareConstantExpr, Value)
832
833
834} // End llvm namespace
835
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000836
837// Utility function for determining if a ConstantExpr is a CastOp or not. This
838// can't be inline because we don't want to #include Instruction.h into
839// Constant.h
840bool ConstantExpr::isCast() const {
841 return Instruction::isCast(getOpcode());
842}
843
Reid Spenceree3c9912006-12-04 05:19:50 +0000844bool ConstantExpr::isCompare() const {
Chris Lattnereab49262008-07-14 05:17:31 +0000845 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp ||
846 getOpcode() == Instruction::VICmp || getOpcode() == Instruction::VFCmp;
Reid Spenceree3c9912006-12-04 05:19:50 +0000847}
848
Dan Gohman1ecaf452008-05-31 00:58:22 +0000849bool ConstantExpr::hasIndices() const {
850 return getOpcode() == Instruction::ExtractValue ||
851 getOpcode() == Instruction::InsertValue;
852}
853
854const SmallVector<unsigned, 4> &ConstantExpr::getIndices() const {
855 if (const ExtractValueConstantExpr *EVCE =
856 dyn_cast<ExtractValueConstantExpr>(this))
857 return EVCE->Indices;
Dan Gohmana469bdb2008-06-23 16:39:44 +0000858
859 return cast<InsertValueConstantExpr>(this)->Indices;
Dan Gohman1ecaf452008-05-31 00:58:22 +0000860}
861
Chris Lattner817175f2004-03-29 02:37:53 +0000862/// ConstantExpr::get* - Return some common constants without having to
863/// specify the full Instruction::OPCODE identifier.
864///
865Constant *ConstantExpr::getNeg(Constant *C) {
Dan Gohmana5b96452009-06-04 22:49:04 +0000866 // API compatibility: Adjust integer opcodes to floating-point opcodes.
867 if (C->getType()->isFPOrFPVector())
868 return getFNeg(C);
869 assert(C->getType()->isIntOrIntVector() &&
870 "Cannot NEG a nonintegral value!");
Reid Spencer2eadb532007-01-21 00:29:26 +0000871 return get(Instruction::Sub,
872 ConstantExpr::getZeroValueForNegationExpr(C->getType()),
873 C);
Chris Lattner817175f2004-03-29 02:37:53 +0000874}
Dan Gohmana5b96452009-06-04 22:49:04 +0000875Constant *ConstantExpr::getFNeg(Constant *C) {
876 assert(C->getType()->isFPOrFPVector() &&
877 "Cannot FNEG a non-floating-point value!");
878 return get(Instruction::FSub,
879 ConstantExpr::getZeroValueForNegationExpr(C->getType()),
880 C);
881}
Chris Lattner817175f2004-03-29 02:37:53 +0000882Constant *ConstantExpr::getNot(Constant *C) {
Dan Gohmana5b96452009-06-04 22:49:04 +0000883 assert(C->getType()->isIntOrIntVector() &&
884 "Cannot NOT a nonintegral value!");
Chris Lattner817175f2004-03-29 02:37:53 +0000885 return get(Instruction::Xor, C,
Dale Johannesen47a5ef32008-08-21 21:20:09 +0000886 Constant::getAllOnesValue(C->getType()));
Chris Lattner817175f2004-03-29 02:37:53 +0000887}
888Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
889 return get(Instruction::Add, C1, C2);
890}
Dan Gohmana5b96452009-06-04 22:49:04 +0000891Constant *ConstantExpr::getFAdd(Constant *C1, Constant *C2) {
892 return get(Instruction::FAdd, C1, C2);
893}
Chris Lattner817175f2004-03-29 02:37:53 +0000894Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
895 return get(Instruction::Sub, C1, C2);
896}
Dan Gohmana5b96452009-06-04 22:49:04 +0000897Constant *ConstantExpr::getFSub(Constant *C1, Constant *C2) {
898 return get(Instruction::FSub, C1, C2);
899}
Chris Lattner817175f2004-03-29 02:37:53 +0000900Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
901 return get(Instruction::Mul, C1, C2);
902}
Dan Gohmana5b96452009-06-04 22:49:04 +0000903Constant *ConstantExpr::getFMul(Constant *C1, Constant *C2) {
904 return get(Instruction::FMul, C1, C2);
905}
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000906Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2) {
907 return get(Instruction::UDiv, C1, C2);
908}
909Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2) {
910 return get(Instruction::SDiv, C1, C2);
911}
912Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
913 return get(Instruction::FDiv, C1, C2);
Chris Lattner817175f2004-03-29 02:37:53 +0000914}
Reid Spencer7eb55b32006-11-02 01:53:59 +0000915Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
916 return get(Instruction::URem, C1, C2);
917}
918Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
919 return get(Instruction::SRem, C1, C2);
920}
921Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
922 return get(Instruction::FRem, C1, C2);
Chris Lattner817175f2004-03-29 02:37:53 +0000923}
924Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
925 return get(Instruction::And, C1, C2);
926}
927Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
928 return get(Instruction::Or, C1, C2);
929}
930Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
931 return get(Instruction::Xor, C1, C2);
932}
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000933unsigned ConstantExpr::getPredicate() const {
Nate Begemand2195702008-05-12 19:01:56 +0000934 assert(getOpcode() == Instruction::FCmp ||
935 getOpcode() == Instruction::ICmp ||
936 getOpcode() == Instruction::VFCmp ||
937 getOpcode() == Instruction::VICmp);
Chris Lattneref650092007-10-18 16:26:24 +0000938 return ((const CompareConstantExpr*)this)->predicate;
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000939}
Chris Lattner817175f2004-03-29 02:37:53 +0000940Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
941 return get(Instruction::Shl, C1, C2);
942}
Reid Spencerfdff9382006-11-08 06:47:33 +0000943Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2) {
944 return get(Instruction::LShr, C1, C2);
Chris Lattner817175f2004-03-29 02:37:53 +0000945}
Reid Spencerfdff9382006-11-08 06:47:33 +0000946Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2) {
947 return get(Instruction::AShr, C1, C2);
Chris Lattnerdb8bdba2004-05-25 05:32:43 +0000948}
Chris Lattner60e0dd72001-10-03 06:12:09 +0000949
Chris Lattner7c1018a2006-07-14 19:37:40 +0000950/// getWithOperandReplaced - Return a constant expression identical to this
951/// one, but with the specified operand set to the specified value.
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000952Constant *
953ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
Chris Lattner7c1018a2006-07-14 19:37:40 +0000954 assert(OpNo < getNumOperands() && "Operand num is out of range!");
955 assert(Op->getType() == getOperand(OpNo)->getType() &&
956 "Replacing operand with value of different type!");
Chris Lattner227816342006-07-14 22:20:01 +0000957 if (getOperand(OpNo) == Op)
958 return const_cast<ConstantExpr*>(this);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000959
Chris Lattner227816342006-07-14 22:20:01 +0000960 Constant *Op0, *Op1, *Op2;
Chris Lattner7c1018a2006-07-14 19:37:40 +0000961 switch (getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000962 case Instruction::Trunc:
963 case Instruction::ZExt:
964 case Instruction::SExt:
965 case Instruction::FPTrunc:
966 case Instruction::FPExt:
967 case Instruction::UIToFP:
968 case Instruction::SIToFP:
969 case Instruction::FPToUI:
970 case Instruction::FPToSI:
971 case Instruction::PtrToInt:
972 case Instruction::IntToPtr:
973 case Instruction::BitCast:
974 return ConstantExpr::getCast(getOpcode(), Op, getType());
Chris Lattner227816342006-07-14 22:20:01 +0000975 case Instruction::Select:
976 Op0 = (OpNo == 0) ? Op : getOperand(0);
977 Op1 = (OpNo == 1) ? Op : getOperand(1);
978 Op2 = (OpNo == 2) ? Op : getOperand(2);
979 return ConstantExpr::getSelect(Op0, Op1, Op2);
980 case Instruction::InsertElement:
981 Op0 = (OpNo == 0) ? Op : getOperand(0);
982 Op1 = (OpNo == 1) ? Op : getOperand(1);
983 Op2 = (OpNo == 2) ? Op : getOperand(2);
984 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
985 case Instruction::ExtractElement:
986 Op0 = (OpNo == 0) ? Op : getOperand(0);
987 Op1 = (OpNo == 1) ? Op : getOperand(1);
988 return ConstantExpr::getExtractElement(Op0, Op1);
989 case Instruction::ShuffleVector:
990 Op0 = (OpNo == 0) ? Op : getOperand(0);
991 Op1 = (OpNo == 1) ? Op : getOperand(1);
992 Op2 = (OpNo == 2) ? Op : getOperand(2);
993 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000994 case Instruction::GetElementPtr: {
Chris Lattnerb5d70302007-02-19 20:01:23 +0000995 SmallVector<Constant*, 8> Ops;
Dan Gohman12fce772008-05-15 19:50:34 +0000996 Ops.resize(getNumOperands()-1);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000997 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
Dan Gohman12fce772008-05-15 19:50:34 +0000998 Ops[i-1] = getOperand(i);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000999 if (OpNo == 0)
Chris Lattnerb5d70302007-02-19 20:01:23 +00001000 return ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
Chris Lattner7c1018a2006-07-14 19:37:40 +00001001 Ops[OpNo-1] = Op;
Chris Lattnerb5d70302007-02-19 20:01:23 +00001002 return ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
Chris Lattner7c1018a2006-07-14 19:37:40 +00001003 }
Chris Lattner7c1018a2006-07-14 19:37:40 +00001004 default:
1005 assert(getNumOperands() == 2 && "Must be binary operator?");
Chris Lattner227816342006-07-14 22:20:01 +00001006 Op0 = (OpNo == 0) ? Op : getOperand(0);
1007 Op1 = (OpNo == 1) ? Op : getOperand(1);
1008 return ConstantExpr::get(getOpcode(), Op0, Op1);
1009 }
1010}
1011
1012/// getWithOperands - This returns the current constant expression with the
1013/// operands replaced with the specified values. The specified operands must
1014/// match count and type with the existing ones.
1015Constant *ConstantExpr::
Chris Lattnerb078e282008-08-20 22:27:40 +00001016getWithOperands(Constant* const *Ops, unsigned NumOps) const {
1017 assert(NumOps == getNumOperands() && "Operand count mismatch!");
Chris Lattner227816342006-07-14 22:20:01 +00001018 bool AnyChange = false;
Chris Lattnerb078e282008-08-20 22:27:40 +00001019 for (unsigned i = 0; i != NumOps; ++i) {
Chris Lattner227816342006-07-14 22:20:01 +00001020 assert(Ops[i]->getType() == getOperand(i)->getType() &&
1021 "Operand type mismatch!");
1022 AnyChange |= Ops[i] != getOperand(i);
1023 }
1024 if (!AnyChange) // No operands changed, return self.
1025 return const_cast<ConstantExpr*>(this);
1026
1027 switch (getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001028 case Instruction::Trunc:
1029 case Instruction::ZExt:
1030 case Instruction::SExt:
1031 case Instruction::FPTrunc:
1032 case Instruction::FPExt:
1033 case Instruction::UIToFP:
1034 case Instruction::SIToFP:
1035 case Instruction::FPToUI:
1036 case Instruction::FPToSI:
1037 case Instruction::PtrToInt:
1038 case Instruction::IntToPtr:
1039 case Instruction::BitCast:
1040 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
Chris Lattner227816342006-07-14 22:20:01 +00001041 case Instruction::Select:
1042 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
1043 case Instruction::InsertElement:
1044 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
1045 case Instruction::ExtractElement:
1046 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
1047 case Instruction::ShuffleVector:
1048 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
Chris Lattnerb5d70302007-02-19 20:01:23 +00001049 case Instruction::GetElementPtr:
Chris Lattnerb078e282008-08-20 22:27:40 +00001050 return ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], NumOps-1);
Reid Spencer266e42b2006-12-23 06:05:41 +00001051 case Instruction::ICmp:
1052 case Instruction::FCmp:
Nate Begeman098cc6f2008-07-25 17:56:27 +00001053 case Instruction::VICmp:
1054 case Instruction::VFCmp:
Reid Spencer266e42b2006-12-23 06:05:41 +00001055 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
Chris Lattner227816342006-07-14 22:20:01 +00001056 default:
1057 assert(getNumOperands() == 2 && "Must be binary operator?");
1058 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
Chris Lattner7c1018a2006-07-14 19:37:40 +00001059 }
1060}
1061
Chris Lattner2f7c9632001-06-06 20:29:01 +00001062
1063//===----------------------------------------------------------------------===//
Chris Lattner2f7c9632001-06-06 20:29:01 +00001064// isValueValidForType implementations
1065
Reid Spencere7334722006-12-19 01:28:19 +00001066bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001067 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001068 if (Ty == Type::Int1Ty)
1069 return Val == 0 || Val == 1;
Reid Spencerd7a00d72007-02-05 23:47:56 +00001070 if (NumBits >= 64)
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001071 return true; // always true, has to fit in largest type
1072 uint64_t Max = (1ll << NumBits) - 1;
1073 return Val <= Max;
Reid Spencere7334722006-12-19 01:28:19 +00001074}
1075
Reid Spencere0fc4df2006-10-20 07:07:24 +00001076bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001077 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001078 if (Ty == Type::Int1Ty)
Reid Spencera94d3942007-01-19 21:13:56 +00001079 return Val == 0 || Val == 1 || Val == -1;
Reid Spencerd7a00d72007-02-05 23:47:56 +00001080 if (NumBits >= 64)
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001081 return true; // always true, has to fit in largest type
1082 int64_t Min = -(1ll << (NumBits-1));
1083 int64_t Max = (1ll << (NumBits-1)) - 1;
1084 return (Val >= Min && Val <= Max);
Chris Lattner2f7c9632001-06-06 20:29:01 +00001085}
1086
Dale Johannesend246b2c2007-08-30 00:23:21 +00001087bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
1088 // convert modifies in place, so make a copy.
1089 APFloat Val2 = APFloat(Val);
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001090 bool losesInfo;
Chris Lattner6b727592004-06-17 18:19:28 +00001091 switch (Ty->getTypeID()) {
Chris Lattner2f7c9632001-06-06 20:29:01 +00001092 default:
1093 return false; // These can't be represented as floating point!
1094
Dale Johannesend246b2c2007-08-30 00:23:21 +00001095 // FIXME rounding mode needs to be more flexible
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001096 case Type::FloatTyID: {
1097 if (&Val2.getSemantics() == &APFloat::IEEEsingle)
1098 return true;
1099 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
1100 return !losesInfo;
1101 }
1102 case Type::DoubleTyID: {
1103 if (&Val2.getSemantics() == &APFloat::IEEEsingle ||
1104 &Val2.getSemantics() == &APFloat::IEEEdouble)
1105 return true;
1106 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
1107 return !losesInfo;
1108 }
Dale Johannesenbdad8092007-08-09 22:51:36 +00001109 case Type::X86_FP80TyID:
Dale Johannesen028084e2007-09-12 03:30:33 +00001110 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
1111 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1112 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
Dale Johannesenbdad8092007-08-09 22:51:36 +00001113 case Type::FP128TyID:
Dale Johannesen028084e2007-09-12 03:30:33 +00001114 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
1115 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1116 &Val2.getSemantics() == &APFloat::IEEEquad;
Dale Johannesen007aa372007-10-11 18:07:22 +00001117 case Type::PPC_FP128TyID:
1118 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
1119 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1120 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
Chris Lattner2f7c9632001-06-06 20:29:01 +00001121 }
Chris Lattneraa2372562006-05-24 17:04:05 +00001122}
Chris Lattner9655e542001-07-20 19:16:02 +00001123
Chris Lattner49d855c2001-09-07 16:46:31 +00001124//===----------------------------------------------------------------------===//
Chris Lattner49d855c2001-09-07 16:46:31 +00001125// Factory Function Implementation
1126
Gabor Greiff6caff662008-05-10 08:32:32 +00001127
1128// The number of operands for each ConstantCreator::create method is
1129// determined by the ConstantTraits template.
Chris Lattner98fa07b2003-05-23 20:03:32 +00001130// ConstantCreator - A class that is used to create constants by
1131// ValueMap*. This class should be partially specialized if there is
1132// something strange that needs to be done to interface to the ctor for the
1133// constant.
1134//
Chris Lattner189d19f2003-11-21 20:23:48 +00001135namespace llvm {
Gabor Greiff6caff662008-05-10 08:32:32 +00001136 template<class ValType>
1137 struct ConstantTraits;
1138
1139 template<typename T, typename Alloc>
1140 struct VISIBILITY_HIDDEN ConstantTraits< std::vector<T, Alloc> > {
1141 static unsigned uses(const std::vector<T, Alloc>& v) {
1142 return v.size();
1143 }
1144 };
1145
Chris Lattner189d19f2003-11-21 20:23:48 +00001146 template<class ConstantClass, class TypeClass, class ValType>
Chris Lattner02157b02006-06-28 21:38:54 +00001147 struct VISIBILITY_HIDDEN ConstantCreator {
Chris Lattner189d19f2003-11-21 20:23:48 +00001148 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
Gabor Greiff6caff662008-05-10 08:32:32 +00001149 return new(ConstantTraits<ValType>::uses(V)) ConstantClass(Ty, V);
Chris Lattner189d19f2003-11-21 20:23:48 +00001150 }
1151 };
Misha Brukmanb1c93172005-04-21 23:48:37 +00001152
Chris Lattner189d19f2003-11-21 20:23:48 +00001153 template<class ConstantClass, class TypeClass>
Chris Lattner02157b02006-06-28 21:38:54 +00001154 struct VISIBILITY_HIDDEN ConvertConstantType {
Chris Lattner189d19f2003-11-21 20:23:48 +00001155 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
1156 assert(0 && "This type cannot be converted!\n");
1157 abort();
1158 }
1159 };
Chris Lattnerb50d1352003-10-05 00:17:43 +00001160
Chris Lattner935aa922005-10-04 17:48:46 +00001161 template<class ValType, class TypeClass, class ConstantClass,
1162 bool HasLargeKey = false /*true for arrays and structs*/ >
Chris Lattner02157b02006-06-28 21:38:54 +00001163 class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
Chris Lattnerb64419a2005-10-03 22:51:37 +00001164 public:
Jim Laskeyc03caef2006-07-17 17:38:29 +00001165 typedef std::pair<const Type*, ValType> MapKey;
1166 typedef std::map<MapKey, Constant *> MapTy;
1167 typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
1168 typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
Chris Lattnerb64419a2005-10-03 22:51:37 +00001169 private:
Chris Lattner5bbf60a52005-10-04 16:52:46 +00001170 /// Map - This is the main map from the element descriptor to the Constants.
1171 /// This is the primary way we avoid creating two of the same shape
1172 /// constant.
Chris Lattnerb50d1352003-10-05 00:17:43 +00001173 MapTy Map;
Chris Lattner935aa922005-10-04 17:48:46 +00001174
1175 /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
1176 /// from the constants to their element in Map. This is important for
1177 /// removal of constants from the array, which would otherwise have to scan
1178 /// through the map with very large keys.
Jim Laskeyc03caef2006-07-17 17:38:29 +00001179 InverseMapTy InverseMap;
Chris Lattnerb50d1352003-10-05 00:17:43 +00001180
Jim Laskeyc03caef2006-07-17 17:38:29 +00001181 /// AbstractTypeMap - Map for abstract type constants.
1182 ///
Chris Lattnerb50d1352003-10-05 00:17:43 +00001183 AbstractTypeMapTy AbstractTypeMap;
Chris Lattner99a669b2004-11-19 16:39:44 +00001184
Chris Lattner98fa07b2003-05-23 20:03:32 +00001185 public:
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.
Jim Laskeyc03caef2006-07-17 17:38:29 +00001193 typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
1194 &InsertVal,
Chris Lattnerb64419a2005-10-03 22:51:37 +00001195 bool &Exists) {
Jim Laskeyc03caef2006-07-17 17:38:29 +00001196 std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
Chris Lattnerb64419a2005-10-03 22:51:37 +00001197 Exists = !IP.second;
1198 return IP.first;
1199 }
Chris Lattner5bbf60a52005-10-04 16:52:46 +00001200
Chris Lattner935aa922005-10-04 17:48:46 +00001201private:
Jim Laskeyc03caef2006-07-17 17:38:29 +00001202 typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
Chris Lattner935aa922005-10-04 17:48:46 +00001203 if (HasLargeKey) {
Jim Laskeyc03caef2006-07-17 17:38:29 +00001204 typename InverseMapTy::iterator IMI = InverseMap.find(CP);
Chris Lattner935aa922005-10-04 17:48:46 +00001205 assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
1206 IMI->second->second == CP &&
1207 "InverseMap corrupt!");
1208 return IMI->second;
1209 }
1210
Jim Laskeyc03caef2006-07-17 17:38:29 +00001211 typename MapTy::iterator I =
Dan Gohmane955c482008-08-05 14:45:15 +00001212 Map.find(MapKey(static_cast<const TypeClass*>(CP->getRawType()),
1213 getValType(CP)));
Chris Lattner5bbf60a52005-10-04 16:52:46 +00001214 if (I == Map.end() || I->second != CP) {
1215 // FIXME: This should not use a linear scan. If this gets to be a
1216 // performance problem, someone should look at this.
1217 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
1218 /* empty */;
1219 }
Chris Lattner935aa922005-10-04 17:48:46 +00001220 return I;
1221 }
1222public:
1223
Chris Lattnerb64419a2005-10-03 22:51:37 +00001224 /// getOrCreate - Return the specified constant from the map, creating it if
1225 /// necessary.
Chris Lattner98fa07b2003-05-23 20:03:32 +00001226 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
Chris Lattnerb50d1352003-10-05 00:17:43 +00001227 MapKey Lookup(Ty, V);
Dan Gohman3707f1d2008-07-11 20:58:19 +00001228 typename MapTy::iterator I = Map.find(Lookup);
Reid Spencere0fc4df2006-10-20 07:07:24 +00001229 // Is it in the map?
Dan Gohman3707f1d2008-07-11 20:58:19 +00001230 if (I != Map.end())
Reid Spencere0fc4df2006-10-20 07:07:24 +00001231 return static_cast<ConstantClass *>(I->second);
Chris Lattner98fa07b2003-05-23 20:03:32 +00001232
1233 // If no preexisting value, create one now...
1234 ConstantClass *Result =
1235 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
1236
Chris Lattnerf97ab6d2008-08-23 03:48:35 +00001237 assert(Result->getType() == Ty && "Type specified is not correct!");
Chris Lattnerb50d1352003-10-05 00:17:43 +00001238 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
1239
Chris Lattner935aa922005-10-04 17:48:46 +00001240 if (HasLargeKey) // Remember the reverse mapping if needed.
1241 InverseMap.insert(std::make_pair(Result, I));
1242
Chris Lattnerb50d1352003-10-05 00:17:43 +00001243 // If the type of the constant is abstract, make sure that an entry exists
1244 // for it in the AbstractTypeMap.
1245 if (Ty->isAbstract()) {
Dan Gohman3707f1d2008-07-11 20:58:19 +00001246 typename AbstractTypeMapTy::iterator TI = AbstractTypeMap.find(Ty);
Chris Lattnerb50d1352003-10-05 00:17:43 +00001247
Dan Gohman3707f1d2008-07-11 20:58:19 +00001248 if (TI == AbstractTypeMap.end()) {
Chris Lattnerb50d1352003-10-05 00:17:43 +00001249 // Add ourselves to the ATU list of the type.
1250 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
1251
1252 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
1253 }
1254 }
Chris Lattner98fa07b2003-05-23 20:03:32 +00001255 return Result;
1256 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001257
Chris Lattner98fa07b2003-05-23 20:03:32 +00001258 void remove(ConstantClass *CP) {
Jim Laskeyc03caef2006-07-17 17:38:29 +00001259 typename MapTy::iterator I = FindExistingElement(CP);
Chris Lattnerb50d1352003-10-05 00:17:43 +00001260 assert(I != Map.end() && "Constant not found in constant table!");
Chris Lattner3e650af2004-08-04 04:48:01 +00001261 assert(I->second == CP && "Didn't find correct element?");
Chris Lattnerb50d1352003-10-05 00:17:43 +00001262
Chris Lattner935aa922005-10-04 17:48:46 +00001263 if (HasLargeKey) // Remember the reverse mapping if needed.
1264 InverseMap.erase(CP);
1265
Chris Lattnerb50d1352003-10-05 00:17:43 +00001266 // Now that we found the entry, make sure this isn't the entry that
1267 // the AbstractTypeMap points to.
Jim Laskeyc03caef2006-07-17 17:38:29 +00001268 const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
Chris Lattnerb50d1352003-10-05 00:17:43 +00001269 if (Ty->isAbstract()) {
1270 assert(AbstractTypeMap.count(Ty) &&
1271 "Abstract type not in AbstractTypeMap?");
Jim Laskeyc03caef2006-07-17 17:38:29 +00001272 typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
Chris Lattnerb50d1352003-10-05 00:17:43 +00001273 if (ATMEntryIt == I) {
1274 // Yes, we are removing the representative entry for this type.
1275 // See if there are any other entries of the same type.
Jim Laskeyc03caef2006-07-17 17:38:29 +00001276 typename MapTy::iterator TmpIt = ATMEntryIt;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001277
Chris Lattnerb50d1352003-10-05 00:17:43 +00001278 // First check the entry before this one...
1279 if (TmpIt != Map.begin()) {
1280 --TmpIt;
1281 if (TmpIt->first.first != Ty) // Not the same type, move back...
1282 ++TmpIt;
1283 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001284
Chris Lattnerb50d1352003-10-05 00:17:43 +00001285 // If we didn't find the same type, try to move forward...
1286 if (TmpIt == ATMEntryIt) {
1287 ++TmpIt;
1288 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
1289 --TmpIt; // No entry afterwards with the same type
1290 }
1291
1292 // If there is another entry in the map of the same abstract type,
1293 // update the AbstractTypeMap entry now.
1294 if (TmpIt != ATMEntryIt) {
1295 ATMEntryIt = TmpIt;
1296 } else {
1297 // Otherwise, we are removing the last instance of this type
1298 // from the table. Remove from the ATM, and from user list.
1299 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
1300 AbstractTypeMap.erase(Ty);
1301 }
Chris Lattner98fa07b2003-05-23 20:03:32 +00001302 }
Chris Lattnerb50d1352003-10-05 00:17:43 +00001303 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001304
Chris Lattnerb50d1352003-10-05 00:17:43 +00001305 Map.erase(I);
1306 }
1307
Chris Lattner3b793c62005-10-04 21:35:50 +00001308
1309 /// MoveConstantToNewSlot - If we are about to change C to be the element
1310 /// specified by I, update our internal data structures to reflect this
1311 /// fact.
Jim Laskeyc03caef2006-07-17 17:38:29 +00001312 void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
Chris Lattner3b793c62005-10-04 21:35:50 +00001313 // First, remove the old location of the specified constant in the map.
Jim Laskeyc03caef2006-07-17 17:38:29 +00001314 typename MapTy::iterator OldI = FindExistingElement(C);
Chris Lattner3b793c62005-10-04 21:35:50 +00001315 assert(OldI != Map.end() && "Constant not found in constant table!");
1316 assert(OldI->second == C && "Didn't find correct element?");
1317
1318 // If this constant is the representative element for its abstract type,
1319 // update the AbstractTypeMap so that the representative element is I.
1320 if (C->getType()->isAbstract()) {
1321 typename AbstractTypeMapTy::iterator ATI =
1322 AbstractTypeMap.find(C->getType());
1323 assert(ATI != AbstractTypeMap.end() &&
1324 "Abstract type not in AbstractTypeMap?");
1325 if (ATI->second == OldI)
1326 ATI->second = I;
1327 }
1328
1329 // Remove the old entry from the map.
1330 Map.erase(OldI);
1331
1332 // Update the inverse map so that we know that this constant is now
1333 // located at descriptor I.
1334 if (HasLargeKey) {
1335 assert(I->second == C && "Bad inversemap entry!");
1336 InverseMap[C] = I;
1337 }
1338 }
1339
Chris Lattnerb50d1352003-10-05 00:17:43 +00001340 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00001341 typename AbstractTypeMapTy::iterator I =
Jim Laskeyc03caef2006-07-17 17:38:29 +00001342 AbstractTypeMap.find(cast<Type>(OldTy));
Chris Lattnerb50d1352003-10-05 00:17:43 +00001343
1344 assert(I != AbstractTypeMap.end() &&
1345 "Abstract type not in AbstractTypeMap?");
1346
1347 // Convert a constant at a time until the last one is gone. The last one
1348 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
1349 // eliminated eventually.
1350 do {
1351 ConvertConstantType<ConstantClass,
Jim Laskeyc03caef2006-07-17 17:38:29 +00001352 TypeClass>::convert(
1353 static_cast<ConstantClass *>(I->second->second),
Chris Lattnerb50d1352003-10-05 00:17:43 +00001354 cast<TypeClass>(NewTy));
1355
Jim Laskeyc03caef2006-07-17 17:38:29 +00001356 I = AbstractTypeMap.find(cast<Type>(OldTy));
Chris Lattnerb50d1352003-10-05 00:17:43 +00001357 } while (I != AbstractTypeMap.end());
1358 }
1359
1360 // If the type became concrete without being refined to any other existing
1361 // type, we just remove ourselves from the ATU list.
1362 void typeBecameConcrete(const DerivedType *AbsTy) {
1363 AbsTy->removeAbstractTypeUser(this);
1364 }
1365
1366 void dump() const {
Bill Wendling6a462f12006-11-17 08:03:48 +00001367 DOUT << "Constant.cpp: ValueMap\n";
Chris Lattner98fa07b2003-05-23 20:03:32 +00001368 }
1369 };
1370}
1371
Chris Lattnera84df0a22006-09-28 23:36:21 +00001372
Chris Lattner28173502007-02-20 06:11:36 +00001373
Chris Lattner9fba3da2004-02-15 05:53:04 +00001374//---- ConstantAggregateZero::get() implementation...
1375//
1376namespace llvm {
1377 // ConstantAggregateZero does not take extra "value" argument...
1378 template<class ValType>
1379 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
1380 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
1381 return new ConstantAggregateZero(Ty);
1382 }
1383 };
1384
1385 template<>
1386 struct ConvertConstantType<ConstantAggregateZero, Type> {
1387 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
1388 // Make everyone now use a constant of the new type...
1389 Constant *New = ConstantAggregateZero::get(NewTy);
1390 assert(New != OldC && "Didn't replace constant??");
1391 OldC->uncheckedReplaceAllUsesWith(New);
1392 OldC->destroyConstant(); // This constant is now dead, destroy it.
1393 }
1394 };
1395}
1396
Chris Lattner69edc982006-09-28 00:35:06 +00001397static ManagedStatic<ValueMap<char, Type,
1398 ConstantAggregateZero> > AggZeroConstants;
Chris Lattner9fba3da2004-02-15 05:53:04 +00001399
Chris Lattner3e650af2004-08-04 04:48:01 +00001400static char getValType(ConstantAggregateZero *CPZ) { return 0; }
1401
Dan Gohman8214fc12008-12-08 07:10:54 +00001402ConstantAggregateZero *ConstantAggregateZero::get(const Type *Ty) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001403 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) &&
Chris Lattnerbfd0b6d2006-06-10 04:16:23 +00001404 "Cannot create an aggregate zero of non-aggregate type!");
Owen Anderson2d7231d2009-06-17 18:40:29 +00001405 ConstantAggregateZero* result = 0;
1406 if (llvm_is_multithreaded()) ConstantsLock->writer_acquire();
1407 result = AggZeroConstants->getOrCreate(Ty, 0);
1408 if (llvm_is_multithreaded()) ConstantsLock->writer_release();
1409 return result;
Chris Lattner9fba3da2004-02-15 05:53:04 +00001410}
1411
Dan Gohman92b551b2009-03-03 02:55:14 +00001412/// destroyConstant - Remove the constant from the constant table...
1413///
Chris Lattner9fba3da2004-02-15 05:53:04 +00001414void ConstantAggregateZero::destroyConstant() {
Owen Anderson2d7231d2009-06-17 18:40:29 +00001415 if (llvm_is_multithreaded()) ConstantsLock->writer_acquire();
Chris Lattner69edc982006-09-28 00:35:06 +00001416 AggZeroConstants->remove(this);
Owen Anderson2d7231d2009-06-17 18:40:29 +00001417 if (llvm_is_multithreaded()) ConstantsLock->writer_release();
Chris Lattner9fba3da2004-02-15 05:53:04 +00001418 destroyConstantImpl();
1419}
1420
Chris Lattner3462ae32001-12-03 22:26:30 +00001421//---- ConstantArray::get() implementation...
Chris Lattner49d855c2001-09-07 16:46:31 +00001422//
Chris Lattner189d19f2003-11-21 20:23:48 +00001423namespace llvm {
1424 template<>
1425 struct ConvertConstantType<ConstantArray, ArrayType> {
1426 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
1427 // Make everyone now use a constant of the new type...
1428 std::vector<Constant*> C;
1429 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1430 C.push_back(cast<Constant>(OldC->getOperand(i)));
1431 Constant *New = ConstantArray::get(NewTy, C);
1432 assert(New != OldC && "Didn't replace constant??");
1433 OldC->uncheckedReplaceAllUsesWith(New);
1434 OldC->destroyConstant(); // This constant is now dead, destroy it.
1435 }
1436 };
1437}
Chris Lattnerb50d1352003-10-05 00:17:43 +00001438
Chris Lattner3e650af2004-08-04 04:48:01 +00001439static std::vector<Constant*> getValType(ConstantArray *CA) {
1440 std::vector<Constant*> Elements;
1441 Elements.reserve(CA->getNumOperands());
1442 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1443 Elements.push_back(cast<Constant>(CA->getOperand(i)));
1444 return Elements;
1445}
1446
Chris Lattnerb64419a2005-10-03 22:51:37 +00001447typedef ValueMap<std::vector<Constant*>, ArrayType,
Chris Lattner935aa922005-10-04 17:48:46 +00001448 ConstantArray, true /*largekey*/> ArrayConstantsTy;
Chris Lattner69edc982006-09-28 00:35:06 +00001449static ManagedStatic<ArrayConstantsTy> ArrayConstants;
Chris Lattner49d855c2001-09-07 16:46:31 +00001450
Chris Lattner015e8212004-02-15 04:14:47 +00001451Constant *ConstantArray::get(const ArrayType *Ty,
Chris Lattner9fba3da2004-02-15 05:53:04 +00001452 const std::vector<Constant*> &V) {
1453 // If this is an all-zero array, return a ConstantAggregateZero object
Owen Anderson2d7231d2009-06-17 18:40:29 +00001454 if (llvm_is_multithreaded()) ConstantsLock->writer_acquire();
Chris Lattner9fba3da2004-02-15 05:53:04 +00001455 if (!V.empty()) {
1456 Constant *C = V[0];
Owen Anderson2d7231d2009-06-17 18:40:29 +00001457 if (!C->isNullValue()) {
1458 if (llvm_is_multithreaded()) ConstantsLock->writer_release();
Chris Lattner69edc982006-09-28 00:35:06 +00001459 return ArrayConstants->getOrCreate(Ty, V);
Owen Anderson2d7231d2009-06-17 18:40:29 +00001460 }
Chris Lattner9fba3da2004-02-15 05:53:04 +00001461 for (unsigned i = 1, e = V.size(); i != e; ++i)
Owen Anderson2d7231d2009-06-17 18:40:29 +00001462 if (V[i] != C) {
1463 if (llvm_is_multithreaded()) ConstantsLock->writer_release();
Chris Lattner69edc982006-09-28 00:35:06 +00001464 return ArrayConstants->getOrCreate(Ty, V);
Owen Anderson2d7231d2009-06-17 18:40:29 +00001465 }
Chris Lattner9fba3da2004-02-15 05:53:04 +00001466 }
Owen Anderson2d7231d2009-06-17 18:40:29 +00001467 if (llvm_is_multithreaded()) ConstantsLock->writer_release();
1468
Chris Lattner9fba3da2004-02-15 05:53:04 +00001469 return ConstantAggregateZero::get(Ty);
Chris Lattner49d855c2001-09-07 16:46:31 +00001470}
1471
Dan Gohman92b551b2009-03-03 02:55:14 +00001472/// destroyConstant - Remove the constant from the constant table...
1473///
Chris Lattner98fa07b2003-05-23 20:03:32 +00001474void ConstantArray::destroyConstant() {
Owen Anderson2d7231d2009-06-17 18:40:29 +00001475 if (llvm_is_multithreaded()) ConstantsLock->writer_acquire();
Chris Lattner69edc982006-09-28 00:35:06 +00001476 ArrayConstants->remove(this);
Owen Anderson2d7231d2009-06-17 18:40:29 +00001477 if (llvm_is_multithreaded()) ConstantsLock->writer_release();
Chris Lattner98fa07b2003-05-23 20:03:32 +00001478 destroyConstantImpl();
1479}
1480
Reid Spencer6f614532006-05-30 08:23:18 +00001481/// ConstantArray::get(const string&) - Return an array that is initialized to
1482/// contain the specified string. If length is zero then a null terminator is
1483/// added to the specified string so that it may be used in a natural way.
1484/// Otherwise, the length parameter specifies how much of the string to use
1485/// and it won't be null terminated.
1486///
Reid Spencer82ebaba2006-05-30 18:15:07 +00001487Constant *ConstantArray::get(const std::string &Str, bool AddNull) {
Chris Lattner7f74a562002-01-20 22:54:45 +00001488 std::vector<Constant*> ElementVals;
Reid Spencer82ebaba2006-05-30 18:15:07 +00001489 for (unsigned i = 0; i < Str.length(); ++i)
Reid Spencer8d9336d2006-12-31 05:26:44 +00001490 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, Str[i]));
Chris Lattner8f80fe02001-10-14 23:54:12 +00001491
1492 // Add a null terminator to the string...
Reid Spencer82ebaba2006-05-30 18:15:07 +00001493 if (AddNull) {
Reid Spencer8d9336d2006-12-31 05:26:44 +00001494 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, 0));
Reid Spencer6f614532006-05-30 08:23:18 +00001495 }
Chris Lattner8f80fe02001-10-14 23:54:12 +00001496
Reid Spencer8d9336d2006-12-31 05:26:44 +00001497 ArrayType *ATy = ArrayType::get(Type::Int8Ty, ElementVals.size());
Chris Lattner3462ae32001-12-03 22:26:30 +00001498 return ConstantArray::get(ATy, ElementVals);
Vikram S. Adve34410432001-10-14 23:17:20 +00001499}
1500
Reid Spencer2546b762007-01-26 07:37:34 +00001501/// isString - This method returns true if the array is an array of i8, and
1502/// if the elements of the array are all ConstantInt's.
Chris Lattnere8dfcca2004-01-14 17:06:38 +00001503bool ConstantArray::isString() const {
Reid Spencer2546b762007-01-26 07:37:34 +00001504 // Check the element type for i8...
Reid Spencer8d9336d2006-12-31 05:26:44 +00001505 if (getType()->getElementType() != Type::Int8Ty)
Chris Lattnere8dfcca2004-01-14 17:06:38 +00001506 return false;
1507 // Check the elements to make sure they are all integers, not constant
1508 // expressions.
1509 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1510 if (!isa<ConstantInt>(getOperand(i)))
1511 return false;
1512 return true;
1513}
1514
Evan Cheng3763c5b2006-10-26 19:15:05 +00001515/// isCString - This method returns true if the array is a string (see
Dan Gohman92b551b2009-03-03 02:55:14 +00001516/// isString) and it ends in a null byte \\0 and does not contains any other
Evan Cheng3763c5b2006-10-26 19:15:05 +00001517/// null bytes except its terminator.
1518bool ConstantArray::isCString() const {
Reid Spencer2546b762007-01-26 07:37:34 +00001519 // Check the element type for i8...
Reid Spencer8d9336d2006-12-31 05:26:44 +00001520 if (getType()->getElementType() != Type::Int8Ty)
Evan Chenge974da62006-10-26 21:48:03 +00001521 return false;
1522 Constant *Zero = Constant::getNullValue(getOperand(0)->getType());
1523 // Last element must be a null.
1524 if (getOperand(getNumOperands()-1) != Zero)
1525 return false;
1526 // Other elements must be non-null integers.
1527 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1528 if (!isa<ConstantInt>(getOperand(i)))
Evan Cheng3763c5b2006-10-26 19:15:05 +00001529 return false;
Evan Chenge974da62006-10-26 21:48:03 +00001530 if (getOperand(i) == Zero)
1531 return false;
1532 }
Evan Cheng3763c5b2006-10-26 19:15:05 +00001533 return true;
1534}
1535
1536
Dan Gohman92b551b2009-03-03 02:55:14 +00001537/// getAsString - If the sub-element type of this array is i8
1538/// then this method converts the array to an std::string and returns it.
1539/// Otherwise, it asserts out.
1540///
Chris Lattner81fabb02002-08-26 17:53:56 +00001541std::string ConstantArray::getAsString() const {
Chris Lattnere8dfcca2004-01-14 17:06:38 +00001542 assert(isString() && "Not a string!");
Chris Lattner81fabb02002-08-26 17:53:56 +00001543 std::string Result;
Owen Anderson79c69bc2008-06-24 21:58:29 +00001544 Result.reserve(getNumOperands());
Chris Lattner6077c312003-07-23 15:22:26 +00001545 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
Owen Andersonee9c30d2008-06-25 01:05:05 +00001546 Result.push_back((char)cast<ConstantInt>(getOperand(i))->getZExtValue());
Chris Lattner81fabb02002-08-26 17:53:56 +00001547 return Result;
1548}
1549
1550
Chris Lattner3462ae32001-12-03 22:26:30 +00001551//---- ConstantStruct::get() implementation...
Chris Lattner49d855c2001-09-07 16:46:31 +00001552//
Chris Lattnerb50d1352003-10-05 00:17:43 +00001553
Chris Lattner189d19f2003-11-21 20:23:48 +00001554namespace llvm {
1555 template<>
1556 struct ConvertConstantType<ConstantStruct, StructType> {
1557 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1558 // Make everyone now use a constant of the new type...
1559 std::vector<Constant*> C;
1560 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1561 C.push_back(cast<Constant>(OldC->getOperand(i)));
1562 Constant *New = ConstantStruct::get(NewTy, C);
1563 assert(New != OldC && "Didn't replace constant??");
Misha Brukmanb1c93172005-04-21 23:48:37 +00001564
Chris Lattner189d19f2003-11-21 20:23:48 +00001565 OldC->uncheckedReplaceAllUsesWith(New);
1566 OldC->destroyConstant(); // This constant is now dead, destroy it.
1567 }
1568 };
1569}
Chris Lattnerb50d1352003-10-05 00:17:43 +00001570
Chris Lattner8760ec72005-10-04 01:17:50 +00001571typedef ValueMap<std::vector<Constant*>, StructType,
Chris Lattner935aa922005-10-04 17:48:46 +00001572 ConstantStruct, true /*largekey*/> StructConstantsTy;
Chris Lattner69edc982006-09-28 00:35:06 +00001573static ManagedStatic<StructConstantsTy> StructConstants;
Chris Lattner49d855c2001-09-07 16:46:31 +00001574
Chris Lattner3e650af2004-08-04 04:48:01 +00001575static std::vector<Constant*> getValType(ConstantStruct *CS) {
1576 std::vector<Constant*> Elements;
1577 Elements.reserve(CS->getNumOperands());
1578 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1579 Elements.push_back(cast<Constant>(CS->getOperand(i)));
1580 return Elements;
1581}
1582
Chris Lattner015e8212004-02-15 04:14:47 +00001583Constant *ConstantStruct::get(const StructType *Ty,
1584 const std::vector<Constant*> &V) {
Chris Lattner9fba3da2004-02-15 05:53:04 +00001585 // Create a ConstantAggregateZero value if all elements are zeros...
Owen Anderson2d7231d2009-06-17 18:40:29 +00001586 if (llvm_is_multithreaded()) ConstantsLock->writer_acquire();
Chris Lattner9fba3da2004-02-15 05:53:04 +00001587 for (unsigned i = 0, e = V.size(); i != e; ++i)
Owen Anderson2d7231d2009-06-17 18:40:29 +00001588 if (!V[i]->isNullValue()) {
1589 Constant* result = StructConstants->getOrCreate(Ty, V);
1590 if (llvm_is_multithreaded()) ConstantsLock->writer_release();
1591 return result;
1592 }
1593 if (llvm_is_multithreaded()) ConstantsLock->writer_release();
Chris Lattner9fba3da2004-02-15 05:53:04 +00001594
1595 return ConstantAggregateZero::get(Ty);
Chris Lattner49d855c2001-09-07 16:46:31 +00001596}
Chris Lattner883ad0b2001-10-03 15:39:36 +00001597
Andrew Lenharthdcb3c972006-12-08 18:06:16 +00001598Constant *ConstantStruct::get(const std::vector<Constant*> &V, bool packed) {
Chris Lattnerd6108ca2004-07-12 20:35:11 +00001599 std::vector<const Type*> StructEls;
1600 StructEls.reserve(V.size());
1601 for (unsigned i = 0, e = V.size(); i != e; ++i)
1602 StructEls.push_back(V[i]->getType());
Andrew Lenharthdcb3c972006-12-08 18:06:16 +00001603 return get(StructType::get(StructEls, packed), V);
Chris Lattnerd6108ca2004-07-12 20:35:11 +00001604}
1605
Chris Lattnerd7a73302001-10-13 06:57:33 +00001606// destroyConstant - Remove the constant from the constant table...
Chris Lattner883ad0b2001-10-03 15:39:36 +00001607//
Chris Lattner3462ae32001-12-03 22:26:30 +00001608void ConstantStruct::destroyConstant() {
Owen Anderson2d7231d2009-06-17 18:40:29 +00001609 if (llvm_is_multithreaded()) ConstantsLock->writer_acquire();
Chris Lattner69edc982006-09-28 00:35:06 +00001610 StructConstants->remove(this);
Owen Anderson2d7231d2009-06-17 18:40:29 +00001611 if (llvm_is_multithreaded()) ConstantsLock->writer_acquire();
Chris Lattnerd7a73302001-10-13 06:57:33 +00001612 destroyConstantImpl();
1613}
Chris Lattner883ad0b2001-10-03 15:39:36 +00001614
Reid Spencerd84d35b2007-02-15 02:26:10 +00001615//---- ConstantVector::get() implementation...
Brian Gaeke02209042004-08-20 06:00:58 +00001616//
1617namespace llvm {
1618 template<>
Reid Spencerd84d35b2007-02-15 02:26:10 +00001619 struct ConvertConstantType<ConstantVector, VectorType> {
1620 static void convert(ConstantVector *OldC, const VectorType *NewTy) {
Brian Gaeke02209042004-08-20 06:00:58 +00001621 // Make everyone now use a constant of the new type...
1622 std::vector<Constant*> C;
1623 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1624 C.push_back(cast<Constant>(OldC->getOperand(i)));
Reid Spencerd84d35b2007-02-15 02:26:10 +00001625 Constant *New = ConstantVector::get(NewTy, C);
Brian Gaeke02209042004-08-20 06:00:58 +00001626 assert(New != OldC && "Didn't replace constant??");
1627 OldC->uncheckedReplaceAllUsesWith(New);
1628 OldC->destroyConstant(); // This constant is now dead, destroy it.
1629 }
1630 };
1631}
1632
Reid Spencerd84d35b2007-02-15 02:26:10 +00001633static std::vector<Constant*> getValType(ConstantVector *CP) {
Brian Gaeke02209042004-08-20 06:00:58 +00001634 std::vector<Constant*> Elements;
1635 Elements.reserve(CP->getNumOperands());
1636 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1637 Elements.push_back(CP->getOperand(i));
1638 return Elements;
1639}
1640
Reid Spencerd84d35b2007-02-15 02:26:10 +00001641static ManagedStatic<ValueMap<std::vector<Constant*>, VectorType,
Reid Spencer09575ba2007-02-15 03:39:18 +00001642 ConstantVector> > VectorConstants;
Brian Gaeke02209042004-08-20 06:00:58 +00001643
Reid Spencerd84d35b2007-02-15 02:26:10 +00001644Constant *ConstantVector::get(const VectorType *Ty,
Brian Gaeke02209042004-08-20 06:00:58 +00001645 const std::vector<Constant*> &V) {
Chris Lattnerd977c072008-07-10 00:44:03 +00001646 assert(!V.empty() && "Vectors can't be empty");
1647 // If this is an all-undef or alll-zero vector, return a
1648 // ConstantAggregateZero or UndefValue.
1649 Constant *C = V[0];
1650 bool isZero = C->isNullValue();
1651 bool isUndef = isa<UndefValue>(C);
1652
1653 if (isZero || isUndef) {
Brian Gaeke02209042004-08-20 06:00:58 +00001654 for (unsigned i = 1, e = V.size(); i != e; ++i)
Chris Lattnerd977c072008-07-10 00:44:03 +00001655 if (V[i] != C) {
1656 isZero = isUndef = false;
1657 break;
1658 }
Brian Gaeke02209042004-08-20 06:00:58 +00001659 }
Chris Lattnerd977c072008-07-10 00:44:03 +00001660
1661 if (isZero)
1662 return ConstantAggregateZero::get(Ty);
1663 if (isUndef)
1664 return UndefValue::get(Ty);
Owen Anderson2d7231d2009-06-17 18:40:29 +00001665 if (llvm_is_multithreaded()) ConstantsLock->writer_acquire();
1666 Constant* result = VectorConstants->getOrCreate(Ty, V);
1667 if (llvm_is_multithreaded()) ConstantsLock->writer_release();
1668 return result;
Brian Gaeke02209042004-08-20 06:00:58 +00001669}
1670
Reid Spencerd84d35b2007-02-15 02:26:10 +00001671Constant *ConstantVector::get(const std::vector<Constant*> &V) {
Brian Gaeke02209042004-08-20 06:00:58 +00001672 assert(!V.empty() && "Cannot infer type if V is empty");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001673 return get(VectorType::get(V.front()->getType(),V.size()), V);
Brian Gaeke02209042004-08-20 06:00:58 +00001674}
1675
1676// destroyConstant - Remove the constant from the constant table...
1677//
Reid Spencerd84d35b2007-02-15 02:26:10 +00001678void ConstantVector::destroyConstant() {
Owen Anderson2d7231d2009-06-17 18:40:29 +00001679 if (llvm_is_multithreaded()) ConstantsLock->writer_acquire();
Reid Spencer09575ba2007-02-15 03:39:18 +00001680 VectorConstants->remove(this);
Owen Anderson2d7231d2009-06-17 18:40:29 +00001681 if (llvm_is_multithreaded()) ConstantsLock->writer_release();
Brian Gaeke02209042004-08-20 06:00:58 +00001682 destroyConstantImpl();
1683}
1684
Dan Gohman30978072007-05-24 14:36:04 +00001685/// This function will return true iff every element in this vector constant
Jim Laskeyf0478822007-01-12 22:39:14 +00001686/// is set to all ones.
1687/// @returns true iff this constant's emements are all set to all ones.
1688/// @brief Determine if the value is all ones.
Reid Spencerd84d35b2007-02-15 02:26:10 +00001689bool ConstantVector::isAllOnesValue() const {
Jim Laskeyf0478822007-01-12 22:39:14 +00001690 // Check out first element.
1691 const Constant *Elt = getOperand(0);
1692 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1693 if (!CI || !CI->isAllOnesValue()) return false;
1694 // Then make sure all remaining elements point to the same value.
1695 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1696 if (getOperand(I) != Elt) return false;
1697 }
1698 return true;
1699}
1700
Dan Gohman07159202007-10-17 17:51:30 +00001701/// getSplatValue - If this is a splat constant, where all of the
1702/// elements have the same value, return that value. Otherwise return null.
1703Constant *ConstantVector::getSplatValue() {
1704 // Check out first element.
1705 Constant *Elt = getOperand(0);
1706 // Then make sure all remaining elements point to the same value.
1707 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1708 if (getOperand(I) != Elt) return 0;
1709 return Elt;
1710}
1711
Chris Lattner3462ae32001-12-03 22:26:30 +00001712//---- ConstantPointerNull::get() implementation...
Chris Lattnerd7a73302001-10-13 06:57:33 +00001713//
Chris Lattner98fa07b2003-05-23 20:03:32 +00001714
Chris Lattner189d19f2003-11-21 20:23:48 +00001715namespace llvm {
1716 // ConstantPointerNull does not take extra "value" argument...
1717 template<class ValType>
1718 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1719 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1720 return new ConstantPointerNull(Ty);
1721 }
1722 };
Chris Lattner98fa07b2003-05-23 20:03:32 +00001723
Chris Lattner189d19f2003-11-21 20:23:48 +00001724 template<>
1725 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1726 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1727 // Make everyone now use a constant of the new type...
1728 Constant *New = ConstantPointerNull::get(NewTy);
1729 assert(New != OldC && "Didn't replace constant??");
1730 OldC->uncheckedReplaceAllUsesWith(New);
1731 OldC->destroyConstant(); // This constant is now dead, destroy it.
1732 }
1733 };
1734}
Chris Lattnerb50d1352003-10-05 00:17:43 +00001735
Chris Lattner69edc982006-09-28 00:35:06 +00001736static ManagedStatic<ValueMap<char, PointerType,
1737 ConstantPointerNull> > NullPtrConstants;
Chris Lattnerd7a73302001-10-13 06:57:33 +00001738
Chris Lattner3e650af2004-08-04 04:48:01 +00001739static char getValType(ConstantPointerNull *) {
1740 return 0;
1741}
1742
1743
Chris Lattner3462ae32001-12-03 22:26:30 +00001744ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
Owen Anderson2d7231d2009-06-17 18:40:29 +00001745 if (llvm_is_multithreaded()) ConstantsLock->writer_acquire();
1746 ConstantPointerNull* result = NullPtrConstants->getOrCreate(Ty, 0);
1747 if (llvm_is_multithreaded()) ConstantsLock->writer_release();
1748 return result;
Chris Lattner883ad0b2001-10-03 15:39:36 +00001749}
1750
Chris Lattner0c6e0b92002-08-18 00:40:04 +00001751// destroyConstant - Remove the constant from the constant table...
1752//
1753void ConstantPointerNull::destroyConstant() {
Owen Anderson2d7231d2009-06-17 18:40:29 +00001754 if (llvm_is_multithreaded()) ConstantsLock->writer_acquire();
Chris Lattner69edc982006-09-28 00:35:06 +00001755 NullPtrConstants->remove(this);
Owen Anderson2d7231d2009-06-17 18:40:29 +00001756 if (llvm_is_multithreaded()) ConstantsLock->writer_release();
Chris Lattner0c6e0b92002-08-18 00:40:04 +00001757 destroyConstantImpl();
1758}
1759
1760
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001761//---- UndefValue::get() implementation...
1762//
1763
1764namespace llvm {
1765 // UndefValue does not take extra "value" argument...
1766 template<class ValType>
1767 struct ConstantCreator<UndefValue, Type, ValType> {
1768 static UndefValue *create(const Type *Ty, const ValType &V) {
1769 return new UndefValue(Ty);
1770 }
1771 };
1772
1773 template<>
1774 struct ConvertConstantType<UndefValue, Type> {
1775 static void convert(UndefValue *OldC, const Type *NewTy) {
1776 // Make everyone now use a constant of the new type.
1777 Constant *New = UndefValue::get(NewTy);
1778 assert(New != OldC && "Didn't replace constant??");
1779 OldC->uncheckedReplaceAllUsesWith(New);
1780 OldC->destroyConstant(); // This constant is now dead, destroy it.
1781 }
1782 };
1783}
1784
Chris Lattner69edc982006-09-28 00:35:06 +00001785static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001786
1787static char getValType(UndefValue *) {
1788 return 0;
1789}
1790
1791
1792UndefValue *UndefValue::get(const Type *Ty) {
Owen Anderson2d7231d2009-06-17 18:40:29 +00001793 if (llvm_is_multithreaded()) ConstantsLock->writer_acquire();
1794 UndefValue* result = UndefValueConstants->getOrCreate(Ty, 0);
1795 if (llvm_is_multithreaded()) ConstantsLock->writer_release();
1796 return result;
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001797}
1798
1799// destroyConstant - Remove the constant from the constant table.
1800//
1801void UndefValue::destroyConstant() {
Owen Anderson2d7231d2009-06-17 18:40:29 +00001802 if (llvm_is_multithreaded()) ConstantsLock->writer_acquire();
Chris Lattner69edc982006-09-28 00:35:06 +00001803 UndefValueConstants->remove(this);
Owen Anderson2d7231d2009-06-17 18:40:29 +00001804 if (llvm_is_multithreaded()) ConstantsLock->writer_release();
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001805 destroyConstantImpl();
1806}
1807
Nick Lewycky49f89192009-04-04 07:22:01 +00001808//---- MDString::get() implementation
1809//
1810
1811MDString::MDString(const char *begin, const char *end)
Nick Lewyckyadbc2842009-05-30 05:06:04 +00001812 : Constant(Type::MetadataTy, MDStringVal, 0, 0),
Nick Lewycky49f89192009-04-04 07:22:01 +00001813 StrBegin(begin), StrEnd(end) {}
1814
1815static ManagedStatic<StringMap<MDString*> > MDStringCache;
1816
1817MDString *MDString::get(const char *StrBegin, const char *StrEnd) {
Owen Anderson2d7231d2009-06-17 18:40:29 +00001818 if (llvm_is_multithreaded()) ConstantsLock->writer_acquire();
Nick Lewycky49f89192009-04-04 07:22:01 +00001819 StringMapEntry<MDString *> &Entry = MDStringCache->GetOrCreateValue(StrBegin,
1820 StrEnd);
1821 MDString *&S = Entry.getValue();
1822 if (!S) S = new MDString(Entry.getKeyData(),
1823 Entry.getKeyData() + Entry.getKeyLength());
Owen Anderson2d7231d2009-06-17 18:40:29 +00001824
1825 if (llvm_is_multithreaded()) ConstantsLock->writer_release();
Nick Lewycky49f89192009-04-04 07:22:01 +00001826 return S;
1827}
1828
1829void MDString::destroyConstant() {
Owen Anderson2d7231d2009-06-17 18:40:29 +00001830 if (llvm_is_multithreaded()) ConstantsLock->writer_acquire();
Nick Lewycky49f89192009-04-04 07:22:01 +00001831 MDStringCache->erase(MDStringCache->find(StrBegin, StrEnd));
Owen Anderson2d7231d2009-06-17 18:40:29 +00001832 if (llvm_is_multithreaded()) ConstantsLock->writer_release();
Nick Lewycky49f89192009-04-04 07:22:01 +00001833 destroyConstantImpl();
1834}
1835
1836//---- MDNode::get() implementation
1837//
1838
1839static ManagedStatic<FoldingSet<MDNode> > MDNodeSet;
1840
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00001841MDNode::MDNode(Value*const* Vals, unsigned NumVals)
Nick Lewyckyadbc2842009-05-30 05:06:04 +00001842 : Constant(Type::MetadataTy, MDNodeVal, 0, 0) {
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00001843 for (unsigned i = 0; i != NumVals; ++i)
1844 Node.push_back(ElementVH(Vals[i], this));
Nick Lewycky49f89192009-04-04 07:22:01 +00001845}
1846
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00001847void MDNode::Profile(FoldingSetNodeID &ID) const {
1848 for (const_elem_iterator I = elem_begin(), E = elem_end(); I != E; ++I)
Nick Lewycky49f89192009-04-04 07:22:01 +00001849 ID.AddPointer(*I);
1850}
1851
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00001852MDNode *MDNode::get(Value*const* Vals, unsigned NumVals) {
Nick Lewycky49f89192009-04-04 07:22:01 +00001853 FoldingSetNodeID ID;
1854 for (unsigned i = 0; i != NumVals; ++i)
1855 ID.AddPointer(Vals[i]);
1856
Owen Anderson2d7231d2009-06-17 18:40:29 +00001857 if (llvm_is_multithreaded()) {
1858 ConstantsLock->reader_acquire();
1859 void *InsertPoint;
1860 MDNode *N = MDNodeSet->FindNodeOrInsertPos(ID, InsertPoint);
1861 ConstantsLock->reader_release();
1862
1863 if (!N) {
1864 ConstantsLock->writer_acquire();
1865 N = MDNodeSet->FindNodeOrInsertPos(ID, InsertPoint);
1866 if (!N) {
1867 // InsertPoint will have been set by the FindNodeOrInsertPos call.
1868 MDNode *N = new(0) MDNode(Vals, NumVals);
1869 MDNodeSet->InsertNode(N, InsertPoint);
1870 }
1871 ConstantsLock->writer_release();
1872 }
1873
Nick Lewycky49f89192009-04-04 07:22:01 +00001874 return N;
Owen Anderson2d7231d2009-06-17 18:40:29 +00001875 } else {
1876 void *InsertPoint;
1877 if (MDNode *N = MDNodeSet->FindNodeOrInsertPos(ID, InsertPoint))
1878 return N;
Nick Lewycky49f89192009-04-04 07:22:01 +00001879
Owen Anderson2d7231d2009-06-17 18:40:29 +00001880 // InsertPoint will have been set by the FindNodeOrInsertPos call.
1881 MDNode *N = new(0) MDNode(Vals, NumVals);
1882 MDNodeSet->InsertNode(N, InsertPoint);
1883 return N;
1884 }
Nick Lewycky49f89192009-04-04 07:22:01 +00001885}
1886
1887void MDNode::destroyConstant() {
Owen Anderson2d7231d2009-06-17 18:40:29 +00001888 if (llvm_is_multithreaded()) ConstantsLock->writer_acquire();
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00001889 MDNodeSet->RemoveNode(this);
Owen Anderson2d7231d2009-06-17 18:40:29 +00001890 if (llvm_is_multithreaded()) ConstantsLock->writer_release();
Nick Lewycky49f89192009-04-04 07:22:01 +00001891 destroyConstantImpl();
1892}
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001893
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001894//---- ConstantExpr::get() implementations...
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001895//
Reid Spencer8d9336d2006-12-31 05:26:44 +00001896
Dan Gohmand78c4002008-05-13 00:00:25 +00001897namespace {
1898
Reid Spenceree3c9912006-12-04 05:19:50 +00001899struct ExprMapKeyType {
Dan Gohman1ecaf452008-05-31 00:58:22 +00001900 typedef SmallVector<unsigned, 4> IndexList;
1901
1902 ExprMapKeyType(unsigned opc,
1903 const std::vector<Constant*> &ops,
1904 unsigned short pred = 0,
1905 const IndexList &inds = IndexList())
1906 : opcode(opc), predicate(pred), operands(ops), indices(inds) {}
Reid Spencerdba6aa42006-12-04 18:38:05 +00001907 uint16_t opcode;
1908 uint16_t predicate;
Reid Spenceree3c9912006-12-04 05:19:50 +00001909 std::vector<Constant*> operands;
Dan Gohman1ecaf452008-05-31 00:58:22 +00001910 IndexList indices;
Reid Spenceree3c9912006-12-04 05:19:50 +00001911 bool operator==(const ExprMapKeyType& that) const {
1912 return this->opcode == that.opcode &&
1913 this->predicate == that.predicate &&
Bill Wendling97f7de82008-10-26 00:19:56 +00001914 this->operands == that.operands &&
Dan Gohman1ecaf452008-05-31 00:58:22 +00001915 this->indices == that.indices;
Reid Spenceree3c9912006-12-04 05:19:50 +00001916 }
1917 bool operator<(const ExprMapKeyType & that) const {
1918 return this->opcode < that.opcode ||
1919 (this->opcode == that.opcode && this->predicate < that.predicate) ||
1920 (this->opcode == that.opcode && this->predicate == that.predicate &&
Dan Gohman1ecaf452008-05-31 00:58:22 +00001921 this->operands < that.operands) ||
1922 (this->opcode == that.opcode && this->predicate == that.predicate &&
1923 this->operands == that.operands && this->indices < that.indices);
Reid Spenceree3c9912006-12-04 05:19:50 +00001924 }
1925
1926 bool operator!=(const ExprMapKeyType& that) const {
1927 return !(*this == that);
1928 }
1929};
Chris Lattner98fa07b2003-05-23 20:03:32 +00001930
Dan Gohmand78c4002008-05-13 00:00:25 +00001931}
1932
Chris Lattner189d19f2003-11-21 20:23:48 +00001933namespace llvm {
1934 template<>
1935 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
Reid Spencer10fbf0e2006-12-03 05:48:19 +00001936 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1937 unsigned short pred = 0) {
Reid Spenceree3c9912006-12-04 05:19:50 +00001938 if (Instruction::isCast(V.opcode))
1939 return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1940 if ((V.opcode >= Instruction::BinaryOpsBegin &&
Reid Spencer2341c222007-02-02 02:16:23 +00001941 V.opcode < Instruction::BinaryOpsEnd))
Reid Spenceree3c9912006-12-04 05:19:50 +00001942 return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1943 if (V.opcode == Instruction::Select)
1944 return new SelectConstantExpr(V.operands[0], V.operands[1],
1945 V.operands[2]);
1946 if (V.opcode == Instruction::ExtractElement)
1947 return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1948 if (V.opcode == Instruction::InsertElement)
1949 return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1950 V.operands[2]);
1951 if (V.opcode == Instruction::ShuffleVector)
1952 return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1953 V.operands[2]);
Dan Gohman1ecaf452008-05-31 00:58:22 +00001954 if (V.opcode == Instruction::InsertValue)
1955 return new InsertValueConstantExpr(V.operands[0], V.operands[1],
1956 V.indices, Ty);
1957 if (V.opcode == Instruction::ExtractValue)
1958 return new ExtractValueConstantExpr(V.operands[0], V.indices, Ty);
Reid Spenceree3c9912006-12-04 05:19:50 +00001959 if (V.opcode == Instruction::GetElementPtr) {
1960 std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
Gabor Greife9ecc682008-04-06 20:25:17 +00001961 return GetElementPtrConstantExpr::Create(V.operands[0], IdxList, Ty);
Reid Spenceree3c9912006-12-04 05:19:50 +00001962 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001963
Reid Spenceree3c9912006-12-04 05:19:50 +00001964 // The compare instructions are weird. We have to encode the predicate
1965 // value and it is combined with the instruction opcode by multiplying
1966 // the opcode by one hundred. We must decode this to get the predicate.
1967 if (V.opcode == Instruction::ICmp)
Nate Begemand2195702008-05-12 19:01:56 +00001968 return new CompareConstantExpr(Ty, Instruction::ICmp, V.predicate,
Reid Spenceree3c9912006-12-04 05:19:50 +00001969 V.operands[0], V.operands[1]);
1970 if (V.opcode == Instruction::FCmp)
Nate Begemand2195702008-05-12 19:01:56 +00001971 return new CompareConstantExpr(Ty, Instruction::FCmp, V.predicate,
1972 V.operands[0], V.operands[1]);
1973 if (V.opcode == Instruction::VICmp)
1974 return new CompareConstantExpr(Ty, Instruction::VICmp, V.predicate,
1975 V.operands[0], V.operands[1]);
1976 if (V.opcode == Instruction::VFCmp)
1977 return new CompareConstantExpr(Ty, Instruction::VFCmp, V.predicate,
Reid Spenceree3c9912006-12-04 05:19:50 +00001978 V.operands[0], V.operands[1]);
1979 assert(0 && "Invalid ConstantExpr!");
Jeff Cohen9f469632006-12-15 21:47:01 +00001980 return 0;
Chris Lattnerb50d1352003-10-05 00:17:43 +00001981 }
Chris Lattner189d19f2003-11-21 20:23:48 +00001982 };
Chris Lattnerb50d1352003-10-05 00:17:43 +00001983
Chris Lattner189d19f2003-11-21 20:23:48 +00001984 template<>
1985 struct ConvertConstantType<ConstantExpr, Type> {
1986 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1987 Constant *New;
1988 switch (OldC->getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001989 case Instruction::Trunc:
1990 case Instruction::ZExt:
1991 case Instruction::SExt:
1992 case Instruction::FPTrunc:
1993 case Instruction::FPExt:
1994 case Instruction::UIToFP:
1995 case Instruction::SIToFP:
1996 case Instruction::FPToUI:
1997 case Instruction::FPToSI:
1998 case Instruction::PtrToInt:
1999 case Instruction::IntToPtr:
2000 case Instruction::BitCast:
Reid Spencerbb65ebf2006-12-12 23:36:14 +00002001 New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0),
2002 NewTy);
Chris Lattner189d19f2003-11-21 20:23:48 +00002003 break;
Chris Lattner6e415c02004-03-12 05:54:04 +00002004 case Instruction::Select:
2005 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
2006 OldC->getOperand(1),
2007 OldC->getOperand(2));
2008 break;
Chris Lattner189d19f2003-11-21 20:23:48 +00002009 default:
2010 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
Reid Spencer7eb55b32006-11-02 01:53:59 +00002011 OldC->getOpcode() < Instruction::BinaryOpsEnd);
Chris Lattner189d19f2003-11-21 20:23:48 +00002012 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
2013 OldC->getOperand(1));
2014 break;
2015 case Instruction::GetElementPtr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00002016 // Make everyone now use a constant of the new type...
Chris Lattner13128ab2004-10-11 22:52:25 +00002017 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
Chris Lattner302116a2007-01-31 04:40:28 +00002018 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0),
2019 &Idx[0], Idx.size());
Chris Lattner189d19f2003-11-21 20:23:48 +00002020 break;
2021 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002022
Chris Lattner189d19f2003-11-21 20:23:48 +00002023 assert(New != OldC && "Didn't replace constant??");
2024 OldC->uncheckedReplaceAllUsesWith(New);
2025 OldC->destroyConstant(); // This constant is now dead, destroy it.
2026 }
2027 };
2028} // end namespace llvm
Chris Lattnerb50d1352003-10-05 00:17:43 +00002029
2030
Chris Lattner3e650af2004-08-04 04:48:01 +00002031static ExprMapKeyType getValType(ConstantExpr *CE) {
2032 std::vector<Constant*> Operands;
2033 Operands.reserve(CE->getNumOperands());
2034 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
2035 Operands.push_back(cast<Constant>(CE->getOperand(i)));
Reid Spenceree3c9912006-12-04 05:19:50 +00002036 return ExprMapKeyType(CE->getOpcode(), Operands,
Dan Gohman1ecaf452008-05-31 00:58:22 +00002037 CE->isCompare() ? CE->getPredicate() : 0,
2038 CE->hasIndices() ?
2039 CE->getIndices() : SmallVector<unsigned, 4>());
Chris Lattner3e650af2004-08-04 04:48:01 +00002040}
2041
Chris Lattner69edc982006-09-28 00:35:06 +00002042static ManagedStatic<ValueMap<ExprMapKeyType, Type,
2043 ConstantExpr> > ExprConstants;
Vikram S. Adve4c485332002-07-15 18:19:33 +00002044
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002045/// This is a utility function to handle folding of casts and lookup of the
Duncan Sands7d6c8ae2008-03-30 19:38:55 +00002046/// cast in the ExprConstants map. It is used by the various get* methods below.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002047static inline Constant *getFoldedCast(
2048 Instruction::CastOps opc, Constant *C, const Type *Ty) {
Chris Lattner815ae2b2003-10-07 22:19:19 +00002049 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002050 // Fold a few common cases
2051 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
2052 return FC;
Chris Lattneracdbe712003-04-17 19:24:48 +00002053
Vikram S. Adve4c485332002-07-15 18:19:33 +00002054 // Look up the constant in the table first to ensure uniqueness
Chris Lattner2b383d2e2003-05-13 21:37:02 +00002055 std::vector<Constant*> argVec(1, C);
Reid Spenceree3c9912006-12-04 05:19:50 +00002056 ExprMapKeyType Key(opc, argVec);
Owen Anderson2d7231d2009-06-17 18:40:29 +00002057
2058 if (llvm_is_multithreaded()) ConstantsLock->writer_acquire();
2059 Constant* result = ExprConstants->getOrCreate(Ty, Key);
2060 if (llvm_is_multithreaded()) ConstantsLock->writer_release();
2061 return result;
Vikram S. Adve4e537b22002-07-14 23:13:17 +00002062}
Reid Spencerf37dc652006-12-05 19:14:13 +00002063
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002064Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
2065 Instruction::CastOps opc = Instruction::CastOps(oc);
2066 assert(Instruction::isCast(opc) && "opcode out of range");
2067 assert(C && Ty && "Null arguments to getCast");
2068 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
2069
2070 switch (opc) {
2071 default:
2072 assert(0 && "Invalid cast opcode");
2073 break;
2074 case Instruction::Trunc: return getTrunc(C, Ty);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00002075 case Instruction::ZExt: return getZExt(C, Ty);
2076 case Instruction::SExt: return getSExt(C, Ty);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002077 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
2078 case Instruction::FPExt: return getFPExtend(C, Ty);
2079 case Instruction::UIToFP: return getUIToFP(C, Ty);
2080 case Instruction::SIToFP: return getSIToFP(C, Ty);
2081 case Instruction::FPToUI: return getFPToUI(C, Ty);
2082 case Instruction::FPToSI: return getFPToSI(C, Ty);
2083 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
2084 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
2085 case Instruction::BitCast: return getBitCast(C, Ty);
Chris Lattner1ece6f82005-01-01 15:59:57 +00002086 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002087 return 0;
Reid Spencerf37dc652006-12-05 19:14:13 +00002088}
2089
Reid Spencer5c140882006-12-04 20:17:56 +00002090Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00002091 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
Reid Spencer5c140882006-12-04 20:17:56 +00002092 return getCast(Instruction::BitCast, C, Ty);
2093 return getCast(Instruction::ZExt, C, Ty);
2094}
2095
2096Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00002097 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
Reid Spencer5c140882006-12-04 20:17:56 +00002098 return getCast(Instruction::BitCast, C, Ty);
2099 return getCast(Instruction::SExt, C, Ty);
2100}
2101
2102Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00002103 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
Reid Spencer5c140882006-12-04 20:17:56 +00002104 return getCast(Instruction::BitCast, C, Ty);
2105 return getCast(Instruction::Trunc, C, Ty);
2106}
2107
Reid Spencerbc245a02006-12-05 03:25:26 +00002108Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
2109 assert(isa<PointerType>(S->getType()) && "Invalid cast");
Chris Lattner03c49532007-01-15 02:27:26 +00002110 assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
Reid Spencerbc245a02006-12-05 03:25:26 +00002111
Chris Lattner03c49532007-01-15 02:27:26 +00002112 if (Ty->isInteger())
Reid Spencerbc245a02006-12-05 03:25:26 +00002113 return getCast(Instruction::PtrToInt, S, Ty);
2114 return getCast(Instruction::BitCast, S, Ty);
2115}
2116
Reid Spencer56521c42006-12-12 00:51:07 +00002117Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
2118 bool isSigned) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00002119 assert(C->getType()->isIntOrIntVector() &&
2120 Ty->isIntOrIntVector() && "Invalid cast");
2121 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2122 unsigned DstBits = Ty->getScalarSizeInBits();
Reid Spencer56521c42006-12-12 00:51:07 +00002123 Instruction::CastOps opcode =
2124 (SrcBits == DstBits ? Instruction::BitCast :
2125 (SrcBits > DstBits ? Instruction::Trunc :
2126 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2127 return getCast(opcode, C, Ty);
2128}
2129
2130Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00002131 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
Reid Spencer56521c42006-12-12 00:51:07 +00002132 "Invalid cast");
Dan Gohman7ccc52f2009-06-15 22:12:54 +00002133 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2134 unsigned DstBits = Ty->getScalarSizeInBits();
Reid Spencerca104e82006-12-12 05:38:50 +00002135 if (SrcBits == DstBits)
2136 return C; // Avoid a useless cast
Reid Spencer56521c42006-12-12 00:51:07 +00002137 Instruction::CastOps opcode =
Reid Spencerca104e82006-12-12 05:38:50 +00002138 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
Reid Spencer56521c42006-12-12 00:51:07 +00002139 return getCast(opcode, C, Ty);
2140}
2141
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002142Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00002143#ifndef NDEBUG
2144 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2145 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2146#endif
2147 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2148 assert(C->getType()->isIntOrIntVector() && "Trunc operand must be integer");
2149 assert(Ty->isIntOrIntVector() && "Trunc produces only integral");
2150 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002151 "SrcTy must be larger than DestTy for Trunc!");
2152
2153 return getFoldedCast(Instruction::Trunc, C, Ty);
2154}
2155
Reid Spencerbb65ebf2006-12-12 23:36:14 +00002156Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00002157#ifndef NDEBUG
2158 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2159 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2160#endif
2161 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2162 assert(C->getType()->isIntOrIntVector() && "SExt operand must be integral");
2163 assert(Ty->isIntOrIntVector() && "SExt produces only integer");
2164 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002165 "SrcTy must be smaller than DestTy for SExt!");
2166
2167 return getFoldedCast(Instruction::SExt, C, Ty);
Chris Lattnerdd284742004-04-04 23:20:30 +00002168}
2169
Reid Spencerbb65ebf2006-12-12 23:36:14 +00002170Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00002171#ifndef NDEBUG
2172 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2173 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2174#endif
2175 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2176 assert(C->getType()->isIntOrIntVector() && "ZEXt operand must be integral");
2177 assert(Ty->isIntOrIntVector() && "ZExt produces only integer");
2178 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002179 "SrcTy must be smaller than DestTy for ZExt!");
2180
2181 return getFoldedCast(Instruction::ZExt, C, Ty);
2182}
2183
2184Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00002185#ifndef NDEBUG
2186 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2187 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2188#endif
2189 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2190 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
2191 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002192 "This is an illegal floating point truncation!");
2193 return getFoldedCast(Instruction::FPTrunc, C, Ty);
2194}
2195
2196Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00002197#ifndef NDEBUG
2198 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2199 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2200#endif
2201 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2202 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
2203 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002204 "This is an illegal floating point extension!");
2205 return getFoldedCast(Instruction::FPExt, C, Ty);
2206}
2207
2208Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
Devang Pateld26344d2008-11-03 23:20:04 +00002209#ifndef NDEBUG
Nate Begemand4d45c22007-11-17 03:58:34 +00002210 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2211 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Pateld26344d2008-11-03 23:20:04 +00002212#endif
Nate Begemand4d45c22007-11-17 03:58:34 +00002213 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2214 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
2215 "This is an illegal uint to floating point cast!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002216 return getFoldedCast(Instruction::UIToFP, C, Ty);
2217}
2218
2219Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
Devang Pateld26344d2008-11-03 23:20:04 +00002220#ifndef NDEBUG
Nate Begemand4d45c22007-11-17 03:58:34 +00002221 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2222 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Pateld26344d2008-11-03 23:20:04 +00002223#endif
Nate Begemand4d45c22007-11-17 03:58:34 +00002224 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2225 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002226 "This is an illegal sint to floating point cast!");
2227 return getFoldedCast(Instruction::SIToFP, C, Ty);
2228}
2229
2230Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
Devang Pateld26344d2008-11-03 23:20:04 +00002231#ifndef NDEBUG
Nate Begemand4d45c22007-11-17 03:58:34 +00002232 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2233 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Pateld26344d2008-11-03 23:20:04 +00002234#endif
Nate Begemand4d45c22007-11-17 03:58:34 +00002235 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2236 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
2237 "This is an illegal floating point to uint cast!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002238 return getFoldedCast(Instruction::FPToUI, C, Ty);
2239}
2240
2241Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
Devang Pateld26344d2008-11-03 23:20:04 +00002242#ifndef NDEBUG
Nate Begemand4d45c22007-11-17 03:58:34 +00002243 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2244 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Pateld26344d2008-11-03 23:20:04 +00002245#endif
Nate Begemand4d45c22007-11-17 03:58:34 +00002246 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2247 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
2248 "This is an illegal floating point to sint cast!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002249 return getFoldedCast(Instruction::FPToSI, C, Ty);
2250}
2251
2252Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
2253 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
Chris Lattner03c49532007-01-15 02:27:26 +00002254 assert(DstTy->isInteger() && "PtrToInt destination must be integral");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002255 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
2256}
2257
2258Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
Chris Lattner03c49532007-01-15 02:27:26 +00002259 assert(C->getType()->isInteger() && "IntToPtr source must be integral");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002260 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
2261 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
2262}
2263
2264Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
2265 // BitCast implies a no-op cast of type only. No bits change. However, you
2266 // can't cast pointers to anything but pointers.
Devang Pateld26344d2008-11-03 23:20:04 +00002267#ifndef NDEBUG
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002268 const Type *SrcTy = C->getType();
2269 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
Reid Spencer5c140882006-12-04 20:17:56 +00002270 "BitCast cannot cast pointer to non-pointer and vice versa");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002271
2272 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
2273 // or nonptr->ptr). For all the other types, the cast is okay if source and
2274 // destination bit widths are identical.
2275 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
2276 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
Devang Pateld26344d2008-11-03 23:20:04 +00002277#endif
Chris Lattnere4086012009-03-08 04:06:26 +00002278 assert(SrcBitSize == DstBitSize && "BitCast requires types of same width");
Chris Lattnercbeda872009-03-21 06:55:54 +00002279
2280 // It is common to ask for a bitcast of a value to its own type, handle this
2281 // speedily.
2282 if (C->getType() == DstTy) return C;
2283
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002284 return getFoldedCast(Instruction::BitCast, C, DstTy);
Chris Lattnerdd284742004-04-04 23:20:30 +00002285}
2286
Duncan Sandsd334aca2009-05-21 15:52:21 +00002287Constant *ConstantExpr::getAlignOf(const Type *Ty) {
2288 // alignof is implemented as: (i64) gep ({i8,Ty}*)null, 0, 1
2289 const Type *AligningTy = StructType::get(Type::Int8Ty, Ty, NULL);
2290 Constant *NullPtr = getNullValue(AligningTy->getPointerTo());
2291 Constant *Zero = ConstantInt::get(Type::Int32Ty, 0);
2292 Constant *One = ConstantInt::get(Type::Int32Ty, 1);
2293 Constant *Indices[2] = { Zero, One };
2294 Constant *GEP = getGetElementPtr(NullPtr, Indices, 2);
2295 return getCast(Instruction::PtrToInt, GEP, Type::Int32Ty);
2296}
2297
Alkis Evlogimenosda5de052004-10-24 01:41:10 +00002298Constant *ConstantExpr::getSizeOf(const Type *Ty) {
Gordon Henriksen7ce31762007-10-06 14:29:36 +00002299 // sizeof is implemented as: (i64) gep (Ty*)null, 1
Chris Lattnerb5d70302007-02-19 20:01:23 +00002300 Constant *GEPIdx = ConstantInt::get(Type::Int32Ty, 1);
2301 Constant *GEP =
Christopher Lambedf07882007-12-17 01:12:55 +00002302 getGetElementPtr(getNullValue(PointerType::getUnqual(Ty)), &GEPIdx, 1);
Chris Lattnerb5d70302007-02-19 20:01:23 +00002303 return getCast(Instruction::PtrToInt, GEP, Type::Int64Ty);
Alkis Evlogimenos9160d5f2005-03-19 11:40:31 +00002304}
2305
Chris Lattnerb50d1352003-10-05 00:17:43 +00002306Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
Reid Spencera009d0d2006-12-04 21:35:24 +00002307 Constant *C1, Constant *C2) {
Chris Lattner38a9bcd2003-05-21 17:49:25 +00002308 // Check the operands for consistency first
Reid Spencer7eb55b32006-11-02 01:53:59 +00002309 assert(Opcode >= Instruction::BinaryOpsBegin &&
2310 Opcode < Instruction::BinaryOpsEnd &&
Chris Lattner38a9bcd2003-05-21 17:49:25 +00002311 "Invalid opcode in binary constant expression");
2312 assert(C1->getType() == C2->getType() &&
2313 "Operand types in binary constant expression should match");
Chris Lattnerb50d1352003-10-05 00:17:43 +00002314
Reid Spencer542964f2007-01-11 18:21:29 +00002315 if (ReqTy == C1->getType() || ReqTy == Type::Int1Ty)
Chris Lattnerb50d1352003-10-05 00:17:43 +00002316 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
2317 return FC; // Fold a few common cases...
Chris Lattneracdbe712003-04-17 19:24:48 +00002318
Chris Lattner2b383d2e2003-05-13 21:37:02 +00002319 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
Reid Spencera009d0d2006-12-04 21:35:24 +00002320 ExprMapKeyType Key(Opcode, argVec);
Owen Anderson2d7231d2009-06-17 18:40:29 +00002321 if (llvm_is_multithreaded()) ConstantsLock->writer_acquire();
2322 Constant* result = ExprConstants->getOrCreate(ReqTy, Key);
2323 if (llvm_is_multithreaded()) ConstantsLock->writer_release();
2324 return result;
Vikram S. Adve4e537b22002-07-14 23:13:17 +00002325}
2326
Reid Spencer266e42b2006-12-23 06:05:41 +00002327Constant *ConstantExpr::getCompareTy(unsigned short predicate,
Nate Begeman098cc6f2008-07-25 17:56:27 +00002328 Constant *C1, Constant *C2) {
2329 bool isVectorType = C1->getType()->getTypeID() == Type::VectorTyID;
Reid Spencer266e42b2006-12-23 06:05:41 +00002330 switch (predicate) {
2331 default: assert(0 && "Invalid CmpInst predicate");
Nate Begemanc96e2e42008-07-25 17:35:37 +00002332 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
2333 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
2334 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
2335 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
2336 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
2337 case CmpInst::FCMP_TRUE:
Nate Begeman098cc6f2008-07-25 17:56:27 +00002338 return isVectorType ? getVFCmp(predicate, C1, C2)
2339 : getFCmp(predicate, C1, C2);
Nate Begemanc96e2e42008-07-25 17:35:37 +00002340 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
2341 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
2342 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
2343 case CmpInst::ICMP_SLE:
Nate Begeman098cc6f2008-07-25 17:56:27 +00002344 return isVectorType ? getVICmp(predicate, C1, C2)
2345 : getICmp(predicate, C1, C2);
Reid Spencer266e42b2006-12-23 06:05:41 +00002346 }
Reid Spencera009d0d2006-12-04 21:35:24 +00002347}
2348
2349Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
Dan Gohmana5b96452009-06-04 22:49:04 +00002350 // API compatibility: Adjust integer opcodes to floating-point opcodes.
2351 if (C1->getType()->isFPOrFPVector()) {
2352 if (Opcode == Instruction::Add) Opcode = Instruction::FAdd;
2353 else if (Opcode == Instruction::Sub) Opcode = Instruction::FSub;
2354 else if (Opcode == Instruction::Mul) Opcode = Instruction::FMul;
2355 }
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00002356#ifndef NDEBUG
2357 switch (Opcode) {
Dan Gohmana5b96452009-06-04 22:49:04 +00002358 case Instruction::Add:
Reid Spencer7eb55b32006-11-02 01:53:59 +00002359 case Instruction::Sub:
Dan Gohmana5b96452009-06-04 22:49:04 +00002360 case Instruction::Mul:
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00002361 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Dan Gohmana5b96452009-06-04 22:49:04 +00002362 assert(C1->getType()->isIntOrIntVector() &&
2363 "Tried to create an integer operation on a non-integer type!");
2364 break;
2365 case Instruction::FAdd:
2366 case Instruction::FSub:
2367 case Instruction::FMul:
2368 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2369 assert(C1->getType()->isFPOrFPVector() &&
2370 "Tried to create a floating-point operation on a "
2371 "non-floating-point type!");
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00002372 break;
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002373 case Instruction::UDiv:
2374 case Instruction::SDiv:
2375 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Dan Gohman7889f2b2009-06-15 22:25:12 +00002376 assert(C1->getType()->isIntOrIntVector() &&
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002377 "Tried to create an arithmetic operation on a non-arithmetic type!");
2378 break;
2379 case Instruction::FDiv:
2380 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Dan Gohman7889f2b2009-06-15 22:25:12 +00002381 assert(C1->getType()->isFPOrFPVector() &&
2382 "Tried to create an arithmetic operation on a non-arithmetic type!");
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002383 break;
Reid Spencer7eb55b32006-11-02 01:53:59 +00002384 case Instruction::URem:
2385 case Instruction::SRem:
2386 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Dan Gohman7889f2b2009-06-15 22:25:12 +00002387 assert(C1->getType()->isIntOrIntVector() &&
Reid Spencer7eb55b32006-11-02 01:53:59 +00002388 "Tried to create an arithmetic operation on a non-arithmetic type!");
2389 break;
2390 case Instruction::FRem:
2391 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Dan Gohman7889f2b2009-06-15 22:25:12 +00002392 assert(C1->getType()->isFPOrFPVector() &&
2393 "Tried to create an arithmetic operation on a non-arithmetic type!");
Reid Spencer7eb55b32006-11-02 01:53:59 +00002394 break;
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00002395 case Instruction::And:
2396 case Instruction::Or:
2397 case Instruction::Xor:
2398 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Dan Gohman7889f2b2009-06-15 22:25:12 +00002399 assert(C1->getType()->isIntOrIntVector() &&
Misha Brukman3852f652005-01-27 06:46:38 +00002400 "Tried to create a logical operation on a non-integral type!");
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00002401 break;
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00002402 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00002403 case Instruction::LShr:
2404 case Instruction::AShr:
Reid Spencer2341c222007-02-02 02:16:23 +00002405 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Dan Gohman79975d52009-03-14 17:09:17 +00002406 assert(C1->getType()->isIntOrIntVector() &&
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00002407 "Tried to create a shift operation on a non-integer type!");
2408 break;
2409 default:
2410 break;
2411 }
2412#endif
2413
Reid Spencera009d0d2006-12-04 21:35:24 +00002414 return getTy(C1->getType(), Opcode, C1, C2);
2415}
2416
Reid Spencer266e42b2006-12-23 06:05:41 +00002417Constant *ConstantExpr::getCompare(unsigned short pred,
Reid Spencera009d0d2006-12-04 21:35:24 +00002418 Constant *C1, Constant *C2) {
2419 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencer266e42b2006-12-23 06:05:41 +00002420 return getCompareTy(pred, C1, C2);
Chris Lattner29ca2c62004-08-04 18:50:09 +00002421}
2422
Chris Lattner6e415c02004-03-12 05:54:04 +00002423Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
2424 Constant *V1, Constant *V2) {
Chris Lattner41632132008-12-29 00:16:12 +00002425 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
Chris Lattner6e415c02004-03-12 05:54:04 +00002426
2427 if (ReqTy == V1->getType())
2428 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
2429 return SC; // Fold common cases
2430
2431 std::vector<Constant*> argVec(3, C);
2432 argVec[1] = V1;
2433 argVec[2] = V2;
Reid Spenceree3c9912006-12-04 05:19:50 +00002434 ExprMapKeyType Key(Instruction::Select, argVec);
Owen Anderson2d7231d2009-06-17 18:40:29 +00002435 if (llvm_is_multithreaded()) ConstantsLock->writer_acquire();
2436 Constant* result = ExprConstants->getOrCreate(ReqTy, Key);
2437 if (llvm_is_multithreaded()) ConstantsLock->writer_release();
2438 return result;
Chris Lattner6e415c02004-03-12 05:54:04 +00002439}
2440
Chris Lattnerb50d1352003-10-05 00:17:43 +00002441Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
Chris Lattner302116a2007-01-31 04:40:28 +00002442 Value* const *Idxs,
2443 unsigned NumIdx) {
Dan Gohman12fce772008-05-15 19:50:34 +00002444 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs,
2445 Idxs+NumIdx) ==
2446 cast<PointerType>(ReqTy)->getElementType() &&
2447 "GEP indices invalid!");
Chris Lattner04b60fe2004-02-16 20:46:13 +00002448
Chris Lattner302116a2007-01-31 04:40:28 +00002449 if (Constant *FC = ConstantFoldGetElementPtr(C, (Constant**)Idxs, NumIdx))
Chris Lattneracdbe712003-04-17 19:24:48 +00002450 return FC; // Fold a few common cases...
Chris Lattner04b60fe2004-02-16 20:46:13 +00002451
Chris Lattnerb50d1352003-10-05 00:17:43 +00002452 assert(isa<PointerType>(C->getType()) &&
Chris Lattner98fa07b2003-05-23 20:03:32 +00002453 "Non-pointer type for constant GetElementPtr expression");
Vikram S. Adve4c485332002-07-15 18:19:33 +00002454 // Look up the constant in the table first to ensure uniqueness
Chris Lattner13128ab2004-10-11 22:52:25 +00002455 std::vector<Constant*> ArgVec;
Chris Lattner302116a2007-01-31 04:40:28 +00002456 ArgVec.reserve(NumIdx+1);
Chris Lattner13128ab2004-10-11 22:52:25 +00002457 ArgVec.push_back(C);
Chris Lattner302116a2007-01-31 04:40:28 +00002458 for (unsigned i = 0; i != NumIdx; ++i)
2459 ArgVec.push_back(cast<Constant>(Idxs[i]));
2460 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
Owen Anderson2d7231d2009-06-17 18:40:29 +00002461 if (llvm_is_multithreaded()) ConstantsLock->writer_acquire();
2462 Constant *result = ExprConstants->getOrCreate(ReqTy, Key);
2463 if (llvm_is_multithreaded()) ConstantsLock->writer_release();
2464 return result;
Vikram S. Adve4c485332002-07-15 18:19:33 +00002465}
2466
Chris Lattner302116a2007-01-31 04:40:28 +00002467Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
2468 unsigned NumIdx) {
Chris Lattnerb50d1352003-10-05 00:17:43 +00002469 // Get the result type of the getelementptr!
Chris Lattner302116a2007-01-31 04:40:28 +00002470 const Type *Ty =
Dan Gohman12fce772008-05-15 19:50:34 +00002471 GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx);
Chris Lattnerb50d1352003-10-05 00:17:43 +00002472 assert(Ty && "GEP indices invalid!");
Christopher Lamb54dd24c2007-12-11 08:59:05 +00002473 unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
2474 return getGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx);
Chris Lattner13128ab2004-10-11 22:52:25 +00002475}
2476
Chris Lattner302116a2007-01-31 04:40:28 +00002477Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
2478 unsigned NumIdx) {
2479 return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
Chris Lattnerb50d1352003-10-05 00:17:43 +00002480}
2481
Chris Lattner302116a2007-01-31 04:40:28 +00002482
Reid Spenceree3c9912006-12-04 05:19:50 +00002483Constant *
2484ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2485 assert(LHS->getType() == RHS->getType());
2486 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
2487 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
2488
Reid Spencer266e42b2006-12-23 06:05:41 +00002489 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
Reid Spenceree3c9912006-12-04 05:19:50 +00002490 return FC; // Fold a few common cases...
2491
2492 // Look up the constant in the table first to ensure uniqueness
2493 std::vector<Constant*> ArgVec;
2494 ArgVec.push_back(LHS);
2495 ArgVec.push_back(RHS);
Reid Spencerb1537492006-12-24 18:42:29 +00002496 // Get the key type with both the opcode and predicate
Reid Spenceree3c9912006-12-04 05:19:50 +00002497 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
Owen Anderson2d7231d2009-06-17 18:40:29 +00002498 if (llvm_is_multithreaded()) ConstantsLock->writer_acquire();
2499 Constant* result = ExprConstants->getOrCreate(Type::Int1Ty, Key);
2500 if (llvm_is_multithreaded()) ConstantsLock->writer_release();
2501 return result;
Reid Spenceree3c9912006-12-04 05:19:50 +00002502}
2503
2504Constant *
2505ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2506 assert(LHS->getType() == RHS->getType());
2507 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
2508
Reid Spencer266e42b2006-12-23 06:05:41 +00002509 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
Reid Spenceree3c9912006-12-04 05:19:50 +00002510 return FC; // Fold a few common cases...
2511
2512 // Look up the constant in the table first to ensure uniqueness
2513 std::vector<Constant*> ArgVec;
2514 ArgVec.push_back(LHS);
2515 ArgVec.push_back(RHS);
Reid Spencerb1537492006-12-24 18:42:29 +00002516 // Get the key type with both the opcode and predicate
Reid Spenceree3c9912006-12-04 05:19:50 +00002517 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
Owen Anderson2d7231d2009-06-17 18:40:29 +00002518 if (llvm_is_multithreaded()) ConstantsLock->writer_acquire();
2519 Constant* result = ExprConstants->getOrCreate(Type::Int1Ty, Key);
2520 if (llvm_is_multithreaded()) ConstantsLock->writer_release();
2521 return result;
Reid Spenceree3c9912006-12-04 05:19:50 +00002522}
2523
Nate Begemand2195702008-05-12 19:01:56 +00002524Constant *
2525ConstantExpr::getVICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
Chris Lattnereab49262008-07-14 05:17:31 +00002526 assert(isa<VectorType>(LHS->getType()) && LHS->getType() == RHS->getType() &&
Nate Begemand2195702008-05-12 19:01:56 +00002527 "Tried to create vicmp operation on non-vector type!");
Nate Begemand2195702008-05-12 19:01:56 +00002528 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
2529 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid VICmp Predicate");
2530
Nate Begemanac7f3d92008-05-12 19:23:22 +00002531 const VectorType *VTy = cast<VectorType>(LHS->getType());
Nate Begemand2195702008-05-12 19:01:56 +00002532 const Type *EltTy = VTy->getElementType();
2533 unsigned NumElts = VTy->getNumElements();
2534
Chris Lattnereab49262008-07-14 05:17:31 +00002535 // See if we can fold the element-wise comparison of the LHS and RHS.
2536 SmallVector<Constant *, 16> LHSElts, RHSElts;
2537 LHS->getVectorElements(LHSElts);
2538 RHS->getVectorElements(RHSElts);
2539
2540 if (!LHSElts.empty() && !RHSElts.empty()) {
2541 SmallVector<Constant *, 16> Elts;
2542 for (unsigned i = 0; i != NumElts; ++i) {
2543 Constant *FC = ConstantFoldCompareInstruction(pred, LHSElts[i],
2544 RHSElts[i]);
2545 if (ConstantInt *FCI = dyn_cast_or_null<ConstantInt>(FC)) {
2546 if (FCI->getZExtValue())
2547 Elts.push_back(ConstantInt::getAllOnesValue(EltTy));
2548 else
2549 Elts.push_back(ConstantInt::get(EltTy, 0ULL));
2550 } else if (FC && isa<UndefValue>(FC)) {
2551 Elts.push_back(UndefValue::get(EltTy));
2552 } else {
2553 break;
2554 }
Nate Begemand2195702008-05-12 19:01:56 +00002555 }
Chris Lattnereab49262008-07-14 05:17:31 +00002556 if (Elts.size() == NumElts)
2557 return ConstantVector::get(&Elts[0], Elts.size());
Nate Begemand2195702008-05-12 19:01:56 +00002558 }
Nate Begemand2195702008-05-12 19:01:56 +00002559
2560 // Look up the constant in the table first to ensure uniqueness
2561 std::vector<Constant*> ArgVec;
2562 ArgVec.push_back(LHS);
2563 ArgVec.push_back(RHS);
2564 // Get the key type with both the opcode and predicate
2565 const ExprMapKeyType Key(Instruction::VICmp, ArgVec, pred);
Owen Anderson2d7231d2009-06-17 18:40:29 +00002566 if (llvm_is_multithreaded()) ConstantsLock->writer_acquire();
2567 Constant* result = ExprConstants->getOrCreate(LHS->getType(), Key);
2568 if (llvm_is_multithreaded()) ConstantsLock->writer_release();
2569 return result;
Nate Begemand2195702008-05-12 19:01:56 +00002570}
2571
2572Constant *
2573ConstantExpr::getVFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2574 assert(isa<VectorType>(LHS->getType()) &&
2575 "Tried to create vfcmp operation on non-vector type!");
2576 assert(LHS->getType() == RHS->getType());
2577 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid VFCmp Predicate");
2578
2579 const VectorType *VTy = cast<VectorType>(LHS->getType());
2580 unsigned NumElts = VTy->getNumElements();
2581 const Type *EltTy = VTy->getElementType();
2582 const Type *REltTy = IntegerType::get(EltTy->getPrimitiveSizeInBits());
2583 const Type *ResultTy = VectorType::get(REltTy, NumElts);
2584
Chris Lattnereab49262008-07-14 05:17:31 +00002585 // See if we can fold the element-wise comparison of the LHS and RHS.
2586 SmallVector<Constant *, 16> LHSElts, RHSElts;
2587 LHS->getVectorElements(LHSElts);
2588 RHS->getVectorElements(RHSElts);
2589
2590 if (!LHSElts.empty() && !RHSElts.empty()) {
2591 SmallVector<Constant *, 16> Elts;
2592 for (unsigned i = 0; i != NumElts; ++i) {
2593 Constant *FC = ConstantFoldCompareInstruction(pred, LHSElts[i],
2594 RHSElts[i]);
2595 if (ConstantInt *FCI = dyn_cast_or_null<ConstantInt>(FC)) {
2596 if (FCI->getZExtValue())
2597 Elts.push_back(ConstantInt::getAllOnesValue(REltTy));
2598 else
2599 Elts.push_back(ConstantInt::get(REltTy, 0ULL));
2600 } else if (FC && isa<UndefValue>(FC)) {
2601 Elts.push_back(UndefValue::get(REltTy));
2602 } else {
2603 break;
2604 }
Nate Begemand2195702008-05-12 19:01:56 +00002605 }
Chris Lattnereab49262008-07-14 05:17:31 +00002606 if (Elts.size() == NumElts)
2607 return ConstantVector::get(&Elts[0], Elts.size());
Nate Begemand2195702008-05-12 19:01:56 +00002608 }
Nate Begemand2195702008-05-12 19:01:56 +00002609
2610 // Look up the constant in the table first to ensure uniqueness
2611 std::vector<Constant*> ArgVec;
2612 ArgVec.push_back(LHS);
2613 ArgVec.push_back(RHS);
2614 // Get the key type with both the opcode and predicate
2615 const ExprMapKeyType Key(Instruction::VFCmp, ArgVec, pred);
Owen Anderson2d7231d2009-06-17 18:40:29 +00002616 if (llvm_is_multithreaded()) ConstantsLock->writer_acquire();
2617 Constant* result = ExprConstants->getOrCreate(ResultTy, Key);
2618 if (llvm_is_multithreaded()) ConstantsLock->writer_release();
2619 return result;
Nate Begemand2195702008-05-12 19:01:56 +00002620}
2621
Robert Bocchino23004482006-01-10 19:05:34 +00002622Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
2623 Constant *Idx) {
Robert Bocchinode7f1c92006-01-10 20:03:46 +00002624 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
2625 return FC; // Fold a few common cases...
Robert Bocchino23004482006-01-10 19:05:34 +00002626 // Look up the constant in the table first to ensure uniqueness
2627 std::vector<Constant*> ArgVec(1, Val);
2628 ArgVec.push_back(Idx);
Reid Spenceree3c9912006-12-04 05:19:50 +00002629 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
Owen Anderson2d7231d2009-06-17 18:40:29 +00002630 if (llvm_is_multithreaded()) ConstantsLock->writer_acquire();
2631 Constant* result = ExprConstants->getOrCreate(ReqTy, Key);
2632 if (llvm_is_multithreaded()) ConstantsLock->writer_release();
2633 return result;
Robert Bocchino23004482006-01-10 19:05:34 +00002634}
2635
2636Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00002637 assert(isa<VectorType>(Val->getType()) &&
Reid Spencer09575ba2007-02-15 03:39:18 +00002638 "Tried to create extractelement operation on non-vector type!");
Reid Spencer8d9336d2006-12-31 05:26:44 +00002639 assert(Idx->getType() == Type::Int32Ty &&
Reid Spencer2546b762007-01-26 07:37:34 +00002640 "Extractelement index must be i32 type!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00002641 return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
Robert Bocchino23004482006-01-10 19:05:34 +00002642 Val, Idx);
2643}
Chris Lattnerb50d1352003-10-05 00:17:43 +00002644
Robert Bocchinoca27f032006-01-17 20:07:22 +00002645Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
2646 Constant *Elt, Constant *Idx) {
2647 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
2648 return FC; // Fold a few common cases...
2649 // Look up the constant in the table first to ensure uniqueness
2650 std::vector<Constant*> ArgVec(1, Val);
2651 ArgVec.push_back(Elt);
2652 ArgVec.push_back(Idx);
Reid Spenceree3c9912006-12-04 05:19:50 +00002653 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
Owen Anderson2d7231d2009-06-17 18:40:29 +00002654 if (llvm_is_multithreaded()) ConstantsLock->writer_acquire();
2655 Constant* result = ExprConstants->getOrCreate(ReqTy, Key);
2656 if (llvm_is_multithreaded()) ConstantsLock->writer_release();
2657 return result;
Robert Bocchinoca27f032006-01-17 20:07:22 +00002658}
2659
2660Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
2661 Constant *Idx) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00002662 assert(isa<VectorType>(Val->getType()) &&
Reid Spencer09575ba2007-02-15 03:39:18 +00002663 "Tried to create insertelement operation on non-vector type!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00002664 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
Robert Bocchinoca27f032006-01-17 20:07:22 +00002665 && "Insertelement types must match!");
Reid Spencer8d9336d2006-12-31 05:26:44 +00002666 assert(Idx->getType() == Type::Int32Ty &&
Reid Spencer2546b762007-01-26 07:37:34 +00002667 "Insertelement index must be i32 type!");
Gordon Henriksenb52d1ed2008-08-30 15:41:51 +00002668 return getInsertElementTy(Val->getType(), Val, Elt, Idx);
Robert Bocchinoca27f032006-01-17 20:07:22 +00002669}
2670
Chris Lattnerbbe0a422006-04-08 01:18:18 +00002671Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
2672 Constant *V2, Constant *Mask) {
2673 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
2674 return FC; // Fold a few common cases...
2675 // Look up the constant in the table first to ensure uniqueness
2676 std::vector<Constant*> ArgVec(1, V1);
2677 ArgVec.push_back(V2);
2678 ArgVec.push_back(Mask);
Reid Spenceree3c9912006-12-04 05:19:50 +00002679 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
Owen Anderson2d7231d2009-06-17 18:40:29 +00002680 if (llvm_is_multithreaded()) ConstantsLock->writer_acquire();
2681 Constant* result = ExprConstants->getOrCreate(ReqTy, Key);
2682 if (llvm_is_multithreaded()) ConstantsLock->writer_release();
2683 return result;
Chris Lattnerbbe0a422006-04-08 01:18:18 +00002684}
2685
2686Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
2687 Constant *Mask) {
2688 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
2689 "Invalid shuffle vector constant expr operands!");
Nate Begeman94aa38d2009-02-12 21:28:33 +00002690
2691 unsigned NElts = cast<VectorType>(Mask->getType())->getNumElements();
2692 const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
2693 const Type *ShufTy = VectorType::get(EltTy, NElts);
2694 return getShuffleVectorTy(ShufTy, V1, V2, Mask);
Chris Lattnerbbe0a422006-04-08 01:18:18 +00002695}
2696
Dan Gohman12fce772008-05-15 19:50:34 +00002697Constant *ConstantExpr::getInsertValueTy(const Type *ReqTy, Constant *Agg,
2698 Constant *Val,
Dan Gohman1ecaf452008-05-31 00:58:22 +00002699 const unsigned *Idxs, unsigned NumIdx) {
Dan Gohman12fce772008-05-15 19:50:34 +00002700 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
2701 Idxs+NumIdx) == Val->getType() &&
2702 "insertvalue indices invalid!");
2703 assert(Agg->getType() == ReqTy &&
2704 "insertvalue type invalid!");
Dan Gohman0752bff2008-05-23 00:36:11 +00002705 assert(Agg->getType()->isFirstClassType() &&
2706 "Non-first-class type for constant InsertValue expression");
Dan Gohmand5d24f62008-07-21 23:30:30 +00002707 Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs, NumIdx);
2708 assert(FC && "InsertValue constant expr couldn't be folded!");
2709 return FC;
Dan Gohman12fce772008-05-15 19:50:34 +00002710}
2711
2712Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
Dan Gohman1ecaf452008-05-31 00:58:22 +00002713 const unsigned *IdxList, unsigned NumIdx) {
Dan Gohman0752bff2008-05-23 00:36:11 +00002714 assert(Agg->getType()->isFirstClassType() &&
2715 "Tried to create insertelement operation on non-first-class type!");
Dan Gohman12fce772008-05-15 19:50:34 +00002716
Dan Gohman0752bff2008-05-23 00:36:11 +00002717 const Type *ReqTy = Agg->getType();
Devang Pateld26344d2008-11-03 23:20:04 +00002718#ifndef NDEBUG
Dan Gohman0752bff2008-05-23 00:36:11 +00002719 const Type *ValTy =
Dan Gohman12fce772008-05-15 19:50:34 +00002720 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
Devang Pateld26344d2008-11-03 23:20:04 +00002721#endif
Dan Gohman0752bff2008-05-23 00:36:11 +00002722 assert(ValTy == Val->getType() && "insertvalue indices invalid!");
Dan Gohman12fce772008-05-15 19:50:34 +00002723 return getInsertValueTy(ReqTy, Agg, Val, IdxList, NumIdx);
2724}
2725
2726Constant *ConstantExpr::getExtractValueTy(const Type *ReqTy, Constant *Agg,
Dan Gohman1ecaf452008-05-31 00:58:22 +00002727 const unsigned *Idxs, unsigned NumIdx) {
Dan Gohman12fce772008-05-15 19:50:34 +00002728 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
2729 Idxs+NumIdx) == ReqTy &&
2730 "extractvalue indices invalid!");
Dan Gohman0752bff2008-05-23 00:36:11 +00002731 assert(Agg->getType()->isFirstClassType() &&
2732 "Non-first-class type for constant extractvalue expression");
Dan Gohmand5d24f62008-07-21 23:30:30 +00002733 Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs, NumIdx);
2734 assert(FC && "ExtractValue constant expr couldn't be folded!");
2735 return FC;
Dan Gohman12fce772008-05-15 19:50:34 +00002736}
2737
2738Constant *ConstantExpr::getExtractValue(Constant *Agg,
Dan Gohman1ecaf452008-05-31 00:58:22 +00002739 const unsigned *IdxList, unsigned NumIdx) {
Dan Gohman0752bff2008-05-23 00:36:11 +00002740 assert(Agg->getType()->isFirstClassType() &&
2741 "Tried to create extractelement operation on non-first-class type!");
Dan Gohman12fce772008-05-15 19:50:34 +00002742
2743 const Type *ReqTy =
2744 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
2745 assert(ReqTy && "extractvalue indices invalid!");
2746 return getExtractValueTy(ReqTy, Agg, IdxList, NumIdx);
2747}
2748
Reid Spencer2eadb532007-01-21 00:29:26 +00002749Constant *ConstantExpr::getZeroValueForNegationExpr(const Type *Ty) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00002750 if (const VectorType *PTy = dyn_cast<VectorType>(Ty))
Reid Spencer6598ca82007-01-21 02:29:10 +00002751 if (PTy->getElementType()->isFloatingPoint()) {
2752 std::vector<Constant*> zeros(PTy->getNumElements(),
Dale Johannesen98d3a082007-09-14 22:26:36 +00002753 ConstantFP::getNegativeZero(PTy->getElementType()));
Reid Spencerd84d35b2007-02-15 02:26:10 +00002754 return ConstantVector::get(PTy, zeros);
Reid Spencer6598ca82007-01-21 02:29:10 +00002755 }
Reid Spencer2eadb532007-01-21 00:29:26 +00002756
Dale Johannesen98d3a082007-09-14 22:26:36 +00002757 if (Ty->isFloatingPoint())
2758 return ConstantFP::getNegativeZero(Ty);
Reid Spencer2eadb532007-01-21 00:29:26 +00002759
2760 return Constant::getNullValue(Ty);
2761}
2762
Vikram S. Adve4c485332002-07-15 18:19:33 +00002763// destroyConstant - Remove the constant from the constant table...
2764//
2765void ConstantExpr::destroyConstant() {
Owen Anderson2d7231d2009-06-17 18:40:29 +00002766 if (llvm_is_multithreaded()) ConstantsLock->writer_acquire();
Chris Lattner69edc982006-09-28 00:35:06 +00002767 ExprConstants->remove(this);
Owen Anderson2d7231d2009-06-17 18:40:29 +00002768 if (llvm_is_multithreaded()) ConstantsLock->writer_release();
Vikram S. Adve4c485332002-07-15 18:19:33 +00002769 destroyConstantImpl();
Vikram S. Adve4e537b22002-07-14 23:13:17 +00002770}
2771
Chris Lattner3cd8c562002-07-30 18:54:25 +00002772const char *ConstantExpr::getOpcodeName() const {
2773 return Instruction::getOpcodeName(getOpcode());
Vikram S. Adve4e537b22002-07-14 23:13:17 +00002774}
Reid Spencer1ebe1ab2004-07-17 23:48:33 +00002775
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002776//===----------------------------------------------------------------------===//
2777// replaceUsesOfWithOnConstant implementations
2778
Chris Lattner913849b2007-08-21 00:55:23 +00002779/// replaceUsesOfWithOnConstant - Update this constant array to change uses of
2780/// 'From' to be uses of 'To'. This must update the uniquing data structures
2781/// etc.
2782///
2783/// Note that we intentionally replace all uses of From with To here. Consider
2784/// a large array that uses 'From' 1000 times. By handling this case all here,
2785/// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
2786/// single invocation handles all 1000 uses. Handling them one at a time would
2787/// work, but would be really slow because it would have to unique each updated
2788/// array instance.
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002789void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002790 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002791 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
Chris Lattner8760ec72005-10-04 01:17:50 +00002792 Constant *ToC = cast<Constant>(To);
Chris Lattnerdff59112005-10-04 18:47:09 +00002793
Jim Laskeyc03caef2006-07-17 17:38:29 +00002794 std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
Chris Lattnerb64419a2005-10-03 22:51:37 +00002795 Lookup.first.first = getType();
2796 Lookup.second = this;
Chris Lattnerdff59112005-10-04 18:47:09 +00002797
Chris Lattnerb64419a2005-10-03 22:51:37 +00002798 std::vector<Constant*> &Values = Lookup.first.second;
2799 Values.reserve(getNumOperands()); // Build replacement array.
Chris Lattnerdff59112005-10-04 18:47:09 +00002800
Chris Lattner8760ec72005-10-04 01:17:50 +00002801 // Fill values with the modified operands of the constant array. Also,
2802 // compute whether this turns into an all-zeros array.
Chris Lattnerdff59112005-10-04 18:47:09 +00002803 bool isAllZeros = false;
Chris Lattner913849b2007-08-21 00:55:23 +00002804 unsigned NumUpdated = 0;
Chris Lattnerdff59112005-10-04 18:47:09 +00002805 if (!ToC->isNullValue()) {
Chris Lattner913849b2007-08-21 00:55:23 +00002806 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2807 Constant *Val = cast<Constant>(O->get());
2808 if (Val == From) {
2809 Val = ToC;
2810 ++NumUpdated;
2811 }
2812 Values.push_back(Val);
2813 }
Chris Lattnerdff59112005-10-04 18:47:09 +00002814 } else {
2815 isAllZeros = true;
2816 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2817 Constant *Val = cast<Constant>(O->get());
Chris Lattner913849b2007-08-21 00:55:23 +00002818 if (Val == From) {
2819 Val = ToC;
2820 ++NumUpdated;
2821 }
Chris Lattnerdff59112005-10-04 18:47:09 +00002822 Values.push_back(Val);
2823 if (isAllZeros) isAllZeros = Val->isNullValue();
2824 }
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002825 }
2826
Chris Lattnerb64419a2005-10-03 22:51:37 +00002827 Constant *Replacement = 0;
2828 if (isAllZeros) {
2829 Replacement = ConstantAggregateZero::get(getType());
2830 } else {
2831 // Check to see if we have this array type already.
Owen Anderson2d7231d2009-06-17 18:40:29 +00002832 if (llvm_is_multithreaded()) ConstantsLock->writer_acquire();
Chris Lattnerb64419a2005-10-03 22:51:37 +00002833 bool Exists;
Jim Laskeyc03caef2006-07-17 17:38:29 +00002834 ArrayConstantsTy::MapTy::iterator I =
Chris Lattner69edc982006-09-28 00:35:06 +00002835 ArrayConstants->InsertOrGetItem(Lookup, Exists);
Chris Lattnerb64419a2005-10-03 22:51:37 +00002836
2837 if (Exists) {
2838 Replacement = I->second;
2839 } else {
2840 // Okay, the new shape doesn't exist in the system yet. Instead of
2841 // creating a new constant array, inserting it, replaceallusesof'ing the
2842 // old with the new, then deleting the old... just update the current one
2843 // in place!
Chris Lattner69edc982006-09-28 00:35:06 +00002844 ArrayConstants->MoveConstantToNewSlot(this, I);
Chris Lattnerb64419a2005-10-03 22:51:37 +00002845
Chris Lattner913849b2007-08-21 00:55:23 +00002846 // Update to the new value. Optimize for the case when we have a single
2847 // operand that we're changing, but handle bulk updates efficiently.
2848 if (NumUpdated == 1) {
2849 unsigned OperandToUpdate = U-OperandList;
2850 assert(getOperand(OperandToUpdate) == From &&
2851 "ReplaceAllUsesWith broken!");
2852 setOperand(OperandToUpdate, ToC);
2853 } else {
2854 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2855 if (getOperand(i) == From)
2856 setOperand(i, ToC);
2857 }
Owen Anderson2d7231d2009-06-17 18:40:29 +00002858 if (llvm_is_multithreaded()) ConstantsLock->writer_release();
Chris Lattnerb64419a2005-10-03 22:51:37 +00002859 return;
2860 }
Owen Anderson2d7231d2009-06-17 18:40:29 +00002861 if (llvm_is_multithreaded()) ConstantsLock->writer_release();
Chris Lattnerb64419a2005-10-03 22:51:37 +00002862 }
2863
2864 // Otherwise, I do need to replace this with an existing value.
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002865 assert(Replacement != this && "I didn't contain From!");
2866
Chris Lattner7a1450d2005-10-04 18:13:04 +00002867 // Everyone using this now uses the replacement.
2868 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002869
2870 // Delete the old constant!
2871 destroyConstant();
2872}
2873
2874void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002875 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002876 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
Chris Lattner8760ec72005-10-04 01:17:50 +00002877 Constant *ToC = cast<Constant>(To);
2878
Chris Lattnerdff59112005-10-04 18:47:09 +00002879 unsigned OperandToUpdate = U-OperandList;
2880 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2881
Jim Laskeyc03caef2006-07-17 17:38:29 +00002882 std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
Chris Lattner8760ec72005-10-04 01:17:50 +00002883 Lookup.first.first = getType();
2884 Lookup.second = this;
2885 std::vector<Constant*> &Values = Lookup.first.second;
2886 Values.reserve(getNumOperands()); // Build replacement struct.
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002887
Chris Lattnerdff59112005-10-04 18:47:09 +00002888
Chris Lattner8760ec72005-10-04 01:17:50 +00002889 // Fill values with the modified operands of the constant struct. Also,
2890 // compute whether this turns into an all-zeros struct.
Chris Lattnerdff59112005-10-04 18:47:09 +00002891 bool isAllZeros = false;
2892 if (!ToC->isNullValue()) {
2893 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
2894 Values.push_back(cast<Constant>(O->get()));
2895 } else {
2896 isAllZeros = true;
2897 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2898 Constant *Val = cast<Constant>(O->get());
2899 Values.push_back(Val);
2900 if (isAllZeros) isAllZeros = Val->isNullValue();
2901 }
Chris Lattner8760ec72005-10-04 01:17:50 +00002902 }
Chris Lattnerdff59112005-10-04 18:47:09 +00002903 Values[OperandToUpdate] = ToC;
2904
Chris Lattner8760ec72005-10-04 01:17:50 +00002905 Constant *Replacement = 0;
2906 if (isAllZeros) {
2907 Replacement = ConstantAggregateZero::get(getType());
2908 } else {
2909 // Check to see if we have this array type already.
Owen Anderson2d7231d2009-06-17 18:40:29 +00002910 if (llvm_is_multithreaded()) ConstantsLock->writer_acquire();
Chris Lattner8760ec72005-10-04 01:17:50 +00002911 bool Exists;
Jim Laskeyc03caef2006-07-17 17:38:29 +00002912 StructConstantsTy::MapTy::iterator I =
Chris Lattner69edc982006-09-28 00:35:06 +00002913 StructConstants->InsertOrGetItem(Lookup, Exists);
Chris Lattner8760ec72005-10-04 01:17:50 +00002914
2915 if (Exists) {
2916 Replacement = I->second;
2917 } else {
2918 // Okay, the new shape doesn't exist in the system yet. Instead of
2919 // creating a new constant struct, inserting it, replaceallusesof'ing the
2920 // old with the new, then deleting the old... just update the current one
2921 // in place!
Chris Lattner69edc982006-09-28 00:35:06 +00002922 StructConstants->MoveConstantToNewSlot(this, I);
Chris Lattner8760ec72005-10-04 01:17:50 +00002923
Chris Lattnerdff59112005-10-04 18:47:09 +00002924 // Update to the new value.
2925 setOperand(OperandToUpdate, ToC);
Owen Anderson2d7231d2009-06-17 18:40:29 +00002926 if (llvm_is_multithreaded()) ConstantsLock->writer_release();
Chris Lattner8760ec72005-10-04 01:17:50 +00002927 return;
2928 }
Owen Anderson2d7231d2009-06-17 18:40:29 +00002929 if (llvm_is_multithreaded()) ConstantsLock->writer_release();
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002930 }
2931
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002932 assert(Replacement != this && "I didn't contain From!");
2933
Chris Lattner7a1450d2005-10-04 18:13:04 +00002934 // Everyone using this now uses the replacement.
2935 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002936
2937 // Delete the old constant!
2938 destroyConstant();
2939}
2940
Reid Spencerd84d35b2007-02-15 02:26:10 +00002941void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002942 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002943 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2944
2945 std::vector<Constant*> Values;
2946 Values.reserve(getNumOperands()); // Build replacement array...
2947 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2948 Constant *Val = getOperand(i);
2949 if (Val == From) Val = cast<Constant>(To);
2950 Values.push_back(Val);
2951 }
2952
Reid Spencerd84d35b2007-02-15 02:26:10 +00002953 Constant *Replacement = ConstantVector::get(getType(), Values);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002954 assert(Replacement != this && "I didn't contain From!");
2955
Chris Lattner7a1450d2005-10-04 18:13:04 +00002956 // Everyone using this now uses the replacement.
2957 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002958
2959 // Delete the old constant!
2960 destroyConstant();
2961}
2962
2963void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002964 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002965 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2966 Constant *To = cast<Constant>(ToV);
2967
2968 Constant *Replacement = 0;
2969 if (getOpcode() == Instruction::GetElementPtr) {
Chris Lattnerb5d70302007-02-19 20:01:23 +00002970 SmallVector<Constant*, 8> Indices;
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002971 Constant *Pointer = getOperand(0);
2972 Indices.reserve(getNumOperands()-1);
2973 if (Pointer == From) Pointer = To;
2974
2975 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2976 Constant *Val = getOperand(i);
2977 if (Val == From) Val = To;
2978 Indices.push_back(Val);
2979 }
Chris Lattnerb5d70302007-02-19 20:01:23 +00002980 Replacement = ConstantExpr::getGetElementPtr(Pointer,
2981 &Indices[0], Indices.size());
Dan Gohman12fce772008-05-15 19:50:34 +00002982 } else if (getOpcode() == Instruction::ExtractValue) {
Dan Gohman12fce772008-05-15 19:50:34 +00002983 Constant *Agg = getOperand(0);
Dan Gohman12fce772008-05-15 19:50:34 +00002984 if (Agg == From) Agg = To;
2985
Dan Gohman1ecaf452008-05-31 00:58:22 +00002986 const SmallVector<unsigned, 4> &Indices = getIndices();
Dan Gohman12fce772008-05-15 19:50:34 +00002987 Replacement = ConstantExpr::getExtractValue(Agg,
2988 &Indices[0], Indices.size());
2989 } else if (getOpcode() == Instruction::InsertValue) {
Dan Gohman12fce772008-05-15 19:50:34 +00002990 Constant *Agg = getOperand(0);
2991 Constant *Val = getOperand(1);
Dan Gohman12fce772008-05-15 19:50:34 +00002992 if (Agg == From) Agg = To;
2993 if (Val == From) Val = To;
2994
Dan Gohman1ecaf452008-05-31 00:58:22 +00002995 const SmallVector<unsigned, 4> &Indices = getIndices();
Dan Gohman12fce772008-05-15 19:50:34 +00002996 Replacement = ConstantExpr::getInsertValue(Agg, Val,
2997 &Indices[0], Indices.size());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002998 } else if (isCast()) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002999 assert(getOperand(0) == From && "Cast only has one use!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003000 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
Chris Lattnerc4062ba2005-10-03 21:58:36 +00003001 } else if (getOpcode() == Instruction::Select) {
3002 Constant *C1 = getOperand(0);
3003 Constant *C2 = getOperand(1);
3004 Constant *C3 = getOperand(2);
3005 if (C1 == From) C1 = To;
3006 if (C2 == From) C2 = To;
3007 if (C3 == From) C3 = To;
3008 Replacement = ConstantExpr::getSelect(C1, C2, C3);
Robert Bocchino23004482006-01-10 19:05:34 +00003009 } else if (getOpcode() == Instruction::ExtractElement) {
3010 Constant *C1 = getOperand(0);
3011 Constant *C2 = getOperand(1);
3012 if (C1 == From) C1 = To;
3013 if (C2 == From) C2 = To;
3014 Replacement = ConstantExpr::getExtractElement(C1, C2);
Chris Lattnera93b4b52006-04-08 05:09:48 +00003015 } else if (getOpcode() == Instruction::InsertElement) {
3016 Constant *C1 = getOperand(0);
3017 Constant *C2 = getOperand(1);
3018 Constant *C3 = getOperand(1);
3019 if (C1 == From) C1 = To;
3020 if (C2 == From) C2 = To;
3021 if (C3 == From) C3 = To;
3022 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
3023 } else if (getOpcode() == Instruction::ShuffleVector) {
3024 Constant *C1 = getOperand(0);
3025 Constant *C2 = getOperand(1);
3026 Constant *C3 = getOperand(2);
3027 if (C1 == From) C1 = To;
3028 if (C2 == From) C2 = To;
3029 if (C3 == From) C3 = To;
3030 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
Reid Spenceree3c9912006-12-04 05:19:50 +00003031 } else if (isCompare()) {
3032 Constant *C1 = getOperand(0);
3033 Constant *C2 = getOperand(1);
3034 if (C1 == From) C1 = To;
3035 if (C2 == From) C2 = To;
3036 if (getOpcode() == Instruction::ICmp)
3037 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
Chris Lattnereab49262008-07-14 05:17:31 +00003038 else if (getOpcode() == Instruction::FCmp)
Reid Spenceree3c9912006-12-04 05:19:50 +00003039 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
Chris Lattnereab49262008-07-14 05:17:31 +00003040 else if (getOpcode() == Instruction::VICmp)
3041 Replacement = ConstantExpr::getVICmp(getPredicate(), C1, C2);
3042 else {
3043 assert(getOpcode() == Instruction::VFCmp);
3044 Replacement = ConstantExpr::getVFCmp(getPredicate(), C1, C2);
3045 }
Chris Lattnerc4062ba2005-10-03 21:58:36 +00003046 } else if (getNumOperands() == 2) {
3047 Constant *C1 = getOperand(0);
3048 Constant *C2 = getOperand(1);
3049 if (C1 == From) C1 = To;
3050 if (C2 == From) C2 = To;
3051 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
3052 } else {
3053 assert(0 && "Unknown ConstantExpr type!");
3054 return;
3055 }
3056
3057 assert(Replacement != this && "I didn't contain From!");
3058
Chris Lattner7a1450d2005-10-04 18:13:04 +00003059 // Everyone using this now uses the replacement.
3060 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00003061
3062 // Delete the old constant!
3063 destroyConstant();
Matthijs Kooijmanba5d7ef2008-07-03 07:46:41 +00003064}
Nick Lewycky49f89192009-04-04 07:22:01 +00003065
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00003066void MDNode::replaceElement(Value *From, Value *To) {
3067 SmallVector<Value*, 4> Values;
3068 Values.reserve(getNumElements()); // Build replacement array...
3069 for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
3070 Value *Val = getElement(i);
3071 if (Val == From) Val = To;
Nick Lewycky49f89192009-04-04 07:22:01 +00003072 Values.push_back(Val);
3073 }
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00003074
3075 MDNode *Replacement = MDNode::get(&Values[0], Values.size());
Nick Lewycky49f89192009-04-04 07:22:01 +00003076 assert(Replacement != this && "I didn't contain From!");
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00003077
Nick Lewycky49f89192009-04-04 07:22:01 +00003078 uncheckedReplaceAllUsesWith(Replacement);
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00003079
Nick Lewycky49f89192009-04-04 07:22:01 +00003080 destroyConstant();
3081}