blob: cb61b0b5c5f7603be3ceeae6a592d80b23509084 [file] [log] [blame]
Chris Lattner2b383d2e2003-05-13 21:37:02 +00001//===-- Constants.cpp - Implement Constant nodes --------------------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner2f7c9632001-06-06 20:29:01 +00009//
Chris Lattner3462ae32001-12-03 22:26:30 +000010// This file implements the Constant* classes...
Chris Lattner2f7c9632001-06-06 20:29:01 +000011//
12//===----------------------------------------------------------------------===//
13
Chris Lattnerca142372002-04-28 19:55:58 +000014#include "llvm/Constants.h"
Chris Lattner5a945e32004-01-12 21:13:12 +000015#include "ConstantFolding.h"
Chris Lattner2f7c9632001-06-06 20:29:01 +000016#include "llvm/DerivedTypes.h"
Reid Spencer1ebe1ab2004-07-17 23:48:33 +000017#include "llvm/GlobalValue.h"
Misha Brukman63b38bd2004-07-29 17:30:56 +000018#include "llvm/Instructions.h"
Chris Lattnerd7a73302001-10-13 06:57:33 +000019#include "llvm/Module.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000020#include "llvm/ADT/StringExtras.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000021#include "llvm/Support/Compiler.h"
Bill Wendling6a462f12006-11-17 08:03:48 +000022#include "llvm/Support/Debug.h"
Chris Lattner69edc982006-09-28 00:35:06 +000023#include "llvm/Support/ManagedStatic.h"
Bill Wendling6a462f12006-11-17 08:03:48 +000024#include "llvm/Support/MathExtras.h"
Chris Lattnera80bf0b2007-02-20 06:39:57 +000025#include "llvm/ADT/DenseMap.h"
Chris Lattnerb5d70302007-02-19 20:01:23 +000026#include "llvm/ADT/SmallVector.h"
Chris Lattner2f7c9632001-06-06 20:29:01 +000027#include <algorithm>
Reid Spencer3aaaa0b2007-02-05 20:47:22 +000028#include <map>
Chris Lattner189d19f2003-11-21 20:23:48 +000029using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000030
Chris Lattner2f7c9632001-06-06 20:29:01 +000031//===----------------------------------------------------------------------===//
Chris Lattner3462ae32001-12-03 22:26:30 +000032// Constant Class
Chris Lattner2f7c9632001-06-06 20:29:01 +000033//===----------------------------------------------------------------------===//
34
Chris Lattner3462ae32001-12-03 22:26:30 +000035void Constant::destroyConstantImpl() {
36 // When a Constant is destroyed, there may be lingering
Chris Lattnerd7a73302001-10-13 06:57:33 +000037 // references to the constant by other constants in the constant pool. These
Misha Brukmanbe372b92003-08-21 22:14:26 +000038 // constants are implicitly dependent on the module that is being deleted,
Chris Lattnerd7a73302001-10-13 06:57:33 +000039 // but they don't know that. Because we only find out when the CPV is
40 // deleted, we must now notify all of our users (that should only be
Chris Lattner3462ae32001-12-03 22:26:30 +000041 // Constants) that they are, in fact, invalid now and should be deleted.
Chris Lattnerd7a73302001-10-13 06:57:33 +000042 //
43 while (!use_empty()) {
44 Value *V = use_back();
45#ifndef NDEBUG // Only in -g mode...
Chris Lattnerd9f4ac662002-07-18 00:14:50 +000046 if (!isa<Constant>(V))
Bill Wendling6a462f12006-11-17 08:03:48 +000047 DOUT << "While deleting: " << *this
48 << "\n\nUse still stuck around after Def is destroyed: "
49 << *V << "\n\n";
Chris Lattnerd7a73302001-10-13 06:57:33 +000050#endif
Vikram S. Adve4e537b22002-07-14 23:13:17 +000051 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
Reid Spencer1ebe1ab2004-07-17 23:48:33 +000052 Constant *CV = cast<Constant>(V);
53 CV->destroyConstant();
Chris Lattnerd7a73302001-10-13 06:57:33 +000054
55 // The constant should remove itself from our use list...
Vikram S. Adve4e537b22002-07-14 23:13:17 +000056 assert((use_empty() || use_back() != V) && "Constant not removed!");
Chris Lattnerd7a73302001-10-13 06:57:33 +000057 }
58
59 // Value has no outstanding references it is safe to delete it now...
60 delete this;
Chris Lattner38569342001-10-01 20:11:19 +000061}
Chris Lattner2f7c9632001-06-06 20:29:01 +000062
Chris Lattner23dd1f62006-10-20 00:27:06 +000063/// canTrap - Return true if evaluation of this constant could trap. This is
64/// true for things like constant expressions that could divide by zero.
65bool Constant::canTrap() const {
66 assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
67 // The only thing that could possibly trap are constant exprs.
68 const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
69 if (!CE) return false;
70
71 // ConstantExpr traps if any operands can trap.
72 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
73 if (getOperand(i)->canTrap())
74 return true;
75
76 // Otherwise, only specific operations can trap.
77 switch (CE->getOpcode()) {
78 default:
79 return false;
Reid Spencer7e80b0b2006-10-26 06:15:43 +000080 case Instruction::UDiv:
81 case Instruction::SDiv:
82 case Instruction::FDiv:
Reid Spencer7eb55b32006-11-02 01:53:59 +000083 case Instruction::URem:
84 case Instruction::SRem:
85 case Instruction::FRem:
Chris Lattner23dd1f62006-10-20 00:27:06 +000086 // Div and rem can trap if the RHS is not known to be non-zero.
87 if (!isa<ConstantInt>(getOperand(1)) || getOperand(1)->isNullValue())
88 return true;
89 return false;
90 }
91}
92
Chris Lattnerb1585a92002-08-13 17:50:20 +000093// Static constructor to create a '0' constant of arbitrary type...
94Constant *Constant::getNullValue(const Type *Ty) {
Chris Lattner6b727592004-06-17 18:19:28 +000095 switch (Ty->getTypeID()) {
Chris Lattnerdbcb0d32007-02-20 05:46:39 +000096 case Type::IntegerTyID:
97 return ConstantInt::get(Ty, 0);
98 case Type::FloatTyID:
99 case Type::DoubleTyID:
100 return ConstantFP::get(Ty, 0.0);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000101 case Type::PointerTyID:
Chris Lattnerb1585a92002-08-13 17:50:20 +0000102 return ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattner9fba3da2004-02-15 05:53:04 +0000103 case Type::StructTyID:
104 case Type::ArrayTyID:
Reid Spencerd84d35b2007-02-15 02:26:10 +0000105 case Type::VectorTyID:
Chris Lattner9fba3da2004-02-15 05:53:04 +0000106 return ConstantAggregateZero::get(Ty);
Chris Lattnerb1585a92002-08-13 17:50:20 +0000107 default:
Reid Spencercf394bf2004-07-04 11:51:24 +0000108 // Function, Label, or Opaque type?
109 assert(!"Cannot create a null constant of that type!");
Chris Lattnerb1585a92002-08-13 17:50:20 +0000110 return 0;
111 }
112}
113
Chris Lattnerb1585a92002-08-13 17:50:20 +0000114
115// Static constructor to create an integral constant with all bits set
Zhou Sheng75b871f2007-01-11 12:24:14 +0000116ConstantInt *ConstantInt::getAllOnesValue(const Type *Ty) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000117 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
118 if (ITy->getBitWidth() == 1)
119 return ConstantInt::getTrue();
120 else
121 return ConstantInt::get(Ty, int64_t(-1));
122 return 0;
Chris Lattnerb1585a92002-08-13 17:50:20 +0000123}
124
Chris Lattnerecab54c2007-01-04 01:49:26 +0000125/// @returns the value for an packed integer constant of the given type that
126/// has all its bits set to true.
127/// @brief Get the all ones value
Reid Spencerd84d35b2007-02-15 02:26:10 +0000128ConstantVector *ConstantVector::getAllOnesValue(const VectorType *Ty) {
Chris Lattnerecab54c2007-01-04 01:49:26 +0000129 std::vector<Constant*> Elts;
130 Elts.resize(Ty->getNumElements(),
Zhou Sheng75b871f2007-01-11 12:24:14 +0000131 ConstantInt::getAllOnesValue(Ty->getElementType()));
Chris Lattnerecab54c2007-01-04 01:49:26 +0000132 assert(Elts[0] && "Not a packed integer type!");
Reid Spencerd84d35b2007-02-15 02:26:10 +0000133 return cast<ConstantVector>(ConstantVector::get(Elts));
Chris Lattnerecab54c2007-01-04 01:49:26 +0000134}
135
136
Chris Lattner2f7c9632001-06-06 20:29:01 +0000137//===----------------------------------------------------------------------===//
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000138// ConstantInt
Chris Lattner2f7c9632001-06-06 20:29:01 +0000139//===----------------------------------------------------------------------===//
140
Chris Lattner5db2f472007-02-20 05:55:46 +0000141ConstantInt::ConstantInt(const IntegerType *Ty, uint64_t V)
142 : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
Chris Lattner2f7c9632001-06-06 20:29:01 +0000143}
144
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000145ConstantInt *ConstantInt::TheTrueVal = 0;
146ConstantInt *ConstantInt::TheFalseVal = 0;
147
148namespace llvm {
149 void CleanupTrueFalse(void *) {
150 ConstantInt::ResetTrueFalse();
151 }
152}
153
154static ManagedCleanup<llvm::CleanupTrueFalse> TrueFalseCleanup;
155
156ConstantInt *ConstantInt::CreateTrueFalseVals(bool WhichOne) {
157 assert(TheTrueVal == 0 && TheFalseVal == 0);
158 TheTrueVal = get(Type::Int1Ty, 1);
159 TheFalseVal = get(Type::Int1Ty, 0);
160
161 // Ensure that llvm_shutdown nulls out TheTrueVal/TheFalseVal.
162 TrueFalseCleanup.Register();
163
164 return WhichOne ? TheTrueVal : TheFalseVal;
165}
166
167
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000168namespace {
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000169 struct DenseMapInt64KeyInfo {
170 typedef std::pair<uint64_t, const Type*> KeyTy;
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000171 static inline KeyTy getEmptyKey() { return KeyTy(0, 0); }
172 static inline KeyTy getTombstoneKey() { return KeyTy(1, 0); }
173 static unsigned getHashValue(const KeyTy &Key) {
174 return DenseMapKeyInfo<void*>::getHashValue(Key.second) ^ Key.first;
175 }
176 static bool isPod() { return true; }
177 };
178}
179
180
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000181typedef DenseMap<DenseMapInt64KeyInfo::KeyTy, ConstantInt*,
182 DenseMapInt64KeyInfo> IntMapTy;
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000183static ManagedStatic<IntMapTy> IntConstants;
184
185// Get a ConstantInt from an int64_t. Note here that we canoncialize the value
186// to a uint64_t value that has been zero extended down to the size of the
187// integer type of the ConstantInt. This allows the getZExtValue method to
188// just return the stored value while getSExtValue has to convert back to sign
189// extended. getZExtValue is more common in LLVM than getSExtValue().
190ConstantInt *ConstantInt::get(const Type *Ty, int64_t V) {
191 const IntegerType *ITy = cast<IntegerType>(Ty);
192 V &= ITy->getBitMask();
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000193 ConstantInt *&Slot = (*IntConstants)[std::make_pair(uint64_t(V), Ty)];
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000194 if (Slot) return Slot;
195 return Slot = new ConstantInt(ITy, V);
196}
197
198//===----------------------------------------------------------------------===//
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000199// ConstantFP
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000200//===----------------------------------------------------------------------===//
201
202
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000203ConstantFP::ConstantFP(const Type *Ty, double V)
Chris Lattnere7e139e2005-09-27 06:09:08 +0000204 : Constant(Ty, ConstantFPVal, 0, 0) {
Chris Lattner2f7c9632001-06-06 20:29:01 +0000205 Val = V;
206}
207
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000208bool ConstantFP::isNullValue() const {
209 return DoubleToBits(Val) == 0;
210}
211
212bool ConstantFP::isExactlyValue(double V) const {
213 return DoubleToBits(V) == DoubleToBits(Val);
214}
215
216
217namespace {
218 struct DenseMapInt32KeyInfo {
219 typedef std::pair<uint32_t, const Type*> KeyTy;
220 static inline KeyTy getEmptyKey() { return KeyTy(0, 0); }
221 static inline KeyTy getTombstoneKey() { return KeyTy(1, 0); }
222 static unsigned getHashValue(const KeyTy &Key) {
223 return DenseMapKeyInfo<void*>::getHashValue(Key.second) ^ Key.first;
224 }
225 static bool isPod() { return true; }
226 };
227}
228
229//---- ConstantFP::get() implementation...
230//
231typedef DenseMap<DenseMapInt32KeyInfo::KeyTy, ConstantFP*,
232 DenseMapInt32KeyInfo> FloatMapTy;
233typedef DenseMap<DenseMapInt64KeyInfo::KeyTy, ConstantFP*,
234 DenseMapInt64KeyInfo> DoubleMapTy;
235
236static ManagedStatic<FloatMapTy> FloatConstants;
237static ManagedStatic<DoubleMapTy> DoubleConstants;
238
239ConstantFP *ConstantFP::get(const Type *Ty, double V) {
240 if (Ty == Type::FloatTy) {
241 uint32_t IntVal = FloatToBits((float)V);
242
243 ConstantFP *&Slot = (*FloatConstants)[std::make_pair(IntVal, Ty)];
244 if (Slot) return Slot;
245 return Slot = new ConstantFP(Ty, (float)V);
246 } else {
247 assert(Ty == Type::DoubleTy);
248 uint64_t IntVal = DoubleToBits(V);
249 ConstantFP *&Slot = (*DoubleConstants)[std::make_pair(IntVal, Ty)];
250 if (Slot) return Slot;
251 return Slot = new ConstantFP(Ty, (float)V);
252 }
253}
254
255
256//===----------------------------------------------------------------------===//
257// ConstantXXX Classes
258//===----------------------------------------------------------------------===//
259
260
Chris Lattner3462ae32001-12-03 22:26:30 +0000261ConstantArray::ConstantArray(const ArrayType *T,
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000262 const std::vector<Constant*> &V)
Chris Lattnere7e139e2005-09-27 06:09:08 +0000263 : Constant(T, ConstantArrayVal, new Use[V.size()], V.size()) {
Alkis Evlogimenos0507ffe2004-09-15 02:32:15 +0000264 assert(V.size() == T->getNumElements() &&
265 "Invalid initializer vector for constant array");
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000266 Use *OL = OperandList;
Chris Lattner0144fad2005-10-03 21:56:24 +0000267 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
268 I != E; ++I, ++OL) {
Chris Lattner20a24452005-10-07 05:23:36 +0000269 Constant *C = *I;
270 assert((C->getType() == T->getElementType() ||
Alkis Evlogimenoscb031d92004-09-10 04:16:59 +0000271 (T->isAbstract() &&
Chris Lattner20a24452005-10-07 05:23:36 +0000272 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
Alkis Evlogimenoscb031d92004-09-10 04:16:59 +0000273 "Initializer for array element doesn't match array element type!");
Chris Lattner20a24452005-10-07 05:23:36 +0000274 OL->init(C, this);
Chris Lattner2f7c9632001-06-06 20:29:01 +0000275 }
276}
277
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000278ConstantArray::~ConstantArray() {
279 delete [] OperandList;
280}
281
Chris Lattner3462ae32001-12-03 22:26:30 +0000282ConstantStruct::ConstantStruct(const StructType *T,
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000283 const std::vector<Constant*> &V)
Chris Lattnere7e139e2005-09-27 06:09:08 +0000284 : Constant(T, ConstantStructVal, new Use[V.size()], V.size()) {
Chris Lattnerac6db752004-02-09 04:37:31 +0000285 assert(V.size() == T->getNumElements() &&
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000286 "Invalid initializer vector for constant structure");
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000287 Use *OL = OperandList;
Chris Lattner0144fad2005-10-03 21:56:24 +0000288 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
289 I != E; ++I, ++OL) {
Chris Lattner20a24452005-10-07 05:23:36 +0000290 Constant *C = *I;
291 assert((C->getType() == T->getElementType(I-V.begin()) ||
Chris Lattner0144fad2005-10-03 21:56:24 +0000292 ((T->getElementType(I-V.begin())->isAbstract() ||
Chris Lattner20a24452005-10-07 05:23:36 +0000293 C->getType()->isAbstract()) &&
Chris Lattner0144fad2005-10-03 21:56:24 +0000294 T->getElementType(I-V.begin())->getTypeID() ==
Chris Lattner20a24452005-10-07 05:23:36 +0000295 C->getType()->getTypeID())) &&
Chris Lattner93c8f142003-06-02 17:42:47 +0000296 "Initializer for struct element doesn't match struct element type!");
Chris Lattner20a24452005-10-07 05:23:36 +0000297 OL->init(C, this);
Chris Lattner2f7c9632001-06-06 20:29:01 +0000298 }
299}
300
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000301ConstantStruct::~ConstantStruct() {
302 delete [] OperandList;
303}
304
305
Reid Spencerd84d35b2007-02-15 02:26:10 +0000306ConstantVector::ConstantVector(const VectorType *T,
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000307 const std::vector<Constant*> &V)
Reid Spencerd84d35b2007-02-15 02:26:10 +0000308 : Constant(T, ConstantVectorVal, new Use[V.size()], V.size()) {
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000309 Use *OL = OperandList;
Chris Lattner0144fad2005-10-03 21:56:24 +0000310 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
311 I != E; ++I, ++OL) {
Chris Lattner20a24452005-10-07 05:23:36 +0000312 Constant *C = *I;
313 assert((C->getType() == T->getElementType() ||
Alkis Evlogimenoscb031d92004-09-10 04:16:59 +0000314 (T->isAbstract() &&
Chris Lattner20a24452005-10-07 05:23:36 +0000315 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
Alkis Evlogimenoscb031d92004-09-10 04:16:59 +0000316 "Initializer for packed element doesn't match packed element type!");
Chris Lattner20a24452005-10-07 05:23:36 +0000317 OL->init(C, this);
Brian Gaeke02209042004-08-20 06:00:58 +0000318 }
319}
320
Reid Spencerd84d35b2007-02-15 02:26:10 +0000321ConstantVector::~ConstantVector() {
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000322 delete [] OperandList;
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000323}
324
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000325// We declare several classes private to this file, so use an anonymous
326// namespace
327namespace {
328
329/// UnaryConstantExpr - This class is private to Constants.cpp, and is used
330/// behind the scenes to implement unary constant exprs.
331class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
332 Use Op;
333public:
334 UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
335 : ConstantExpr(Ty, Opcode, &Op, 1), Op(C, this) {}
336};
337
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000338/// BinaryConstantExpr - This class is private to Constants.cpp, and is used
339/// behind the scenes to implement binary constant exprs.
Chris Lattner02157b02006-06-28 21:38:54 +0000340class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000341 Use Ops[2];
342public:
343 BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
Reid Spencer266e42b2006-12-23 06:05:41 +0000344 : ConstantExpr(C1->getType(), Opcode, Ops, 2) {
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000345 Ops[0].init(C1, this);
346 Ops[1].init(C2, this);
347 }
348};
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000349
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000350/// SelectConstantExpr - This class is private to Constants.cpp, and is used
351/// behind the scenes to implement select constant exprs.
Chris Lattner02157b02006-06-28 21:38:54 +0000352class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000353 Use Ops[3];
354public:
355 SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
356 : ConstantExpr(C2->getType(), Instruction::Select, Ops, 3) {
357 Ops[0].init(C1, this);
358 Ops[1].init(C2, this);
359 Ops[2].init(C3, this);
360 }
361};
362
Robert Bocchinoca27f032006-01-17 20:07:22 +0000363/// ExtractElementConstantExpr - This class is private to
364/// Constants.cpp, and is used behind the scenes to implement
365/// extractelement constant exprs.
Chris Lattner02157b02006-06-28 21:38:54 +0000366class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
Robert Bocchino23004482006-01-10 19:05:34 +0000367 Use Ops[2];
368public:
369 ExtractElementConstantExpr(Constant *C1, Constant *C2)
Reid Spencerd84d35b2007-02-15 02:26:10 +0000370 : ConstantExpr(cast<VectorType>(C1->getType())->getElementType(),
Robert Bocchino23004482006-01-10 19:05:34 +0000371 Instruction::ExtractElement, Ops, 2) {
372 Ops[0].init(C1, this);
373 Ops[1].init(C2, this);
374 }
375};
376
Robert Bocchinoca27f032006-01-17 20:07:22 +0000377/// InsertElementConstantExpr - This class is private to
378/// Constants.cpp, and is used behind the scenes to implement
379/// insertelement constant exprs.
Chris Lattner02157b02006-06-28 21:38:54 +0000380class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
Robert Bocchinoca27f032006-01-17 20:07:22 +0000381 Use Ops[3];
382public:
383 InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
384 : ConstantExpr(C1->getType(), Instruction::InsertElement,
385 Ops, 3) {
386 Ops[0].init(C1, this);
387 Ops[1].init(C2, this);
388 Ops[2].init(C3, this);
389 }
390};
391
Chris Lattnerbbe0a422006-04-08 01:18:18 +0000392/// ShuffleVectorConstantExpr - This class is private to
393/// Constants.cpp, and is used behind the scenes to implement
394/// shufflevector constant exprs.
Chris Lattner02157b02006-06-28 21:38:54 +0000395class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
Chris Lattnerbbe0a422006-04-08 01:18:18 +0000396 Use Ops[3];
397public:
398 ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
399 : ConstantExpr(C1->getType(), Instruction::ShuffleVector,
400 Ops, 3) {
401 Ops[0].init(C1, this);
402 Ops[1].init(C2, this);
403 Ops[2].init(C3, this);
404 }
405};
406
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000407/// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
408/// used behind the scenes to implement getelementpr constant exprs.
Chris Lattner02157b02006-06-28 21:38:54 +0000409struct VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000410 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
411 const Type *DestTy)
412 : ConstantExpr(DestTy, Instruction::GetElementPtr,
413 new Use[IdxList.size()+1], IdxList.size()+1) {
414 OperandList[0].init(C, this);
415 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
416 OperandList[i+1].init(IdxList[i], this);
417 }
418 ~GetElementPtrConstantExpr() {
Misha Brukmanb1c93172005-04-21 23:48:37 +0000419 delete [] OperandList;
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000420 }
421};
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000422
423// CompareConstantExpr - This class is private to Constants.cpp, and is used
424// behind the scenes to implement ICmp and FCmp constant expressions. This is
425// needed in order to store the predicate value for these instructions.
426struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
427 unsigned short predicate;
428 Use Ops[2];
429 CompareConstantExpr(Instruction::OtherOps opc, unsigned short pred,
430 Constant* LHS, Constant* RHS)
Reid Spencer542964f2007-01-11 18:21:29 +0000431 : ConstantExpr(Type::Int1Ty, opc, Ops, 2), predicate(pred) {
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000432 OperandList[0].init(LHS, this);
433 OperandList[1].init(RHS, this);
434 }
435};
436
437} // end anonymous namespace
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000438
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000439
440// Utility function for determining if a ConstantExpr is a CastOp or not. This
441// can't be inline because we don't want to #include Instruction.h into
442// Constant.h
443bool ConstantExpr::isCast() const {
444 return Instruction::isCast(getOpcode());
445}
446
Reid Spenceree3c9912006-12-04 05:19:50 +0000447bool ConstantExpr::isCompare() const {
448 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
449}
450
Chris Lattner817175f2004-03-29 02:37:53 +0000451/// ConstantExpr::get* - Return some common constants without having to
452/// specify the full Instruction::OPCODE identifier.
453///
454Constant *ConstantExpr::getNeg(Constant *C) {
Reid Spencer2eadb532007-01-21 00:29:26 +0000455 return get(Instruction::Sub,
456 ConstantExpr::getZeroValueForNegationExpr(C->getType()),
457 C);
Chris Lattner817175f2004-03-29 02:37:53 +0000458}
459Constant *ConstantExpr::getNot(Constant *C) {
Zhou Sheng75b871f2007-01-11 12:24:14 +0000460 assert(isa<ConstantInt>(C) && "Cannot NOT a nonintegral type!");
Chris Lattner817175f2004-03-29 02:37:53 +0000461 return get(Instruction::Xor, C,
Zhou Sheng75b871f2007-01-11 12:24:14 +0000462 ConstantInt::getAllOnesValue(C->getType()));
Chris Lattner817175f2004-03-29 02:37:53 +0000463}
464Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
465 return get(Instruction::Add, C1, C2);
466}
467Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
468 return get(Instruction::Sub, C1, C2);
469}
470Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
471 return get(Instruction::Mul, C1, C2);
472}
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000473Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2) {
474 return get(Instruction::UDiv, C1, C2);
475}
476Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2) {
477 return get(Instruction::SDiv, C1, C2);
478}
479Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
480 return get(Instruction::FDiv, C1, C2);
Chris Lattner817175f2004-03-29 02:37:53 +0000481}
Reid Spencer7eb55b32006-11-02 01:53:59 +0000482Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
483 return get(Instruction::URem, C1, C2);
484}
485Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
486 return get(Instruction::SRem, C1, C2);
487}
488Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
489 return get(Instruction::FRem, C1, C2);
Chris Lattner817175f2004-03-29 02:37:53 +0000490}
491Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
492 return get(Instruction::And, C1, C2);
493}
494Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
495 return get(Instruction::Or, C1, C2);
496}
497Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
498 return get(Instruction::Xor, C1, C2);
499}
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000500unsigned ConstantExpr::getPredicate() const {
501 assert(getOpcode() == Instruction::FCmp || getOpcode() == Instruction::ICmp);
502 return dynamic_cast<const CompareConstantExpr*>(this)->predicate;
503}
Chris Lattner817175f2004-03-29 02:37:53 +0000504Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
505 return get(Instruction::Shl, C1, C2);
506}
Reid Spencerfdff9382006-11-08 06:47:33 +0000507Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2) {
508 return get(Instruction::LShr, C1, C2);
Chris Lattner817175f2004-03-29 02:37:53 +0000509}
Reid Spencerfdff9382006-11-08 06:47:33 +0000510Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2) {
511 return get(Instruction::AShr, C1, C2);
Chris Lattnerdb8bdba2004-05-25 05:32:43 +0000512}
Chris Lattner60e0dd72001-10-03 06:12:09 +0000513
Chris Lattner7c1018a2006-07-14 19:37:40 +0000514/// getWithOperandReplaced - Return a constant expression identical to this
515/// one, but with the specified operand set to the specified value.
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000516Constant *
517ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
Chris Lattner7c1018a2006-07-14 19:37:40 +0000518 assert(OpNo < getNumOperands() && "Operand num is out of range!");
519 assert(Op->getType() == getOperand(OpNo)->getType() &&
520 "Replacing operand with value of different type!");
Chris Lattner227816342006-07-14 22:20:01 +0000521 if (getOperand(OpNo) == Op)
522 return const_cast<ConstantExpr*>(this);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000523
Chris Lattner227816342006-07-14 22:20:01 +0000524 Constant *Op0, *Op1, *Op2;
Chris Lattner7c1018a2006-07-14 19:37:40 +0000525 switch (getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000526 case Instruction::Trunc:
527 case Instruction::ZExt:
528 case Instruction::SExt:
529 case Instruction::FPTrunc:
530 case Instruction::FPExt:
531 case Instruction::UIToFP:
532 case Instruction::SIToFP:
533 case Instruction::FPToUI:
534 case Instruction::FPToSI:
535 case Instruction::PtrToInt:
536 case Instruction::IntToPtr:
537 case Instruction::BitCast:
538 return ConstantExpr::getCast(getOpcode(), Op, getType());
Chris Lattner227816342006-07-14 22:20:01 +0000539 case Instruction::Select:
540 Op0 = (OpNo == 0) ? Op : getOperand(0);
541 Op1 = (OpNo == 1) ? Op : getOperand(1);
542 Op2 = (OpNo == 2) ? Op : getOperand(2);
543 return ConstantExpr::getSelect(Op0, Op1, Op2);
544 case Instruction::InsertElement:
545 Op0 = (OpNo == 0) ? Op : getOperand(0);
546 Op1 = (OpNo == 1) ? Op : getOperand(1);
547 Op2 = (OpNo == 2) ? Op : getOperand(2);
548 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
549 case Instruction::ExtractElement:
550 Op0 = (OpNo == 0) ? Op : getOperand(0);
551 Op1 = (OpNo == 1) ? Op : getOperand(1);
552 return ConstantExpr::getExtractElement(Op0, Op1);
553 case Instruction::ShuffleVector:
554 Op0 = (OpNo == 0) ? Op : getOperand(0);
555 Op1 = (OpNo == 1) ? Op : getOperand(1);
556 Op2 = (OpNo == 2) ? Op : getOperand(2);
557 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000558 case Instruction::GetElementPtr: {
Chris Lattnerb5d70302007-02-19 20:01:23 +0000559 SmallVector<Constant*, 8> Ops;
560 Ops.resize(getNumOperands());
Chris Lattner7c1018a2006-07-14 19:37:40 +0000561 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
Chris Lattnerb5d70302007-02-19 20:01:23 +0000562 Ops[i] = getOperand(i);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000563 if (OpNo == 0)
Chris Lattnerb5d70302007-02-19 20:01:23 +0000564 return ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
Chris Lattner7c1018a2006-07-14 19:37:40 +0000565 Ops[OpNo-1] = Op;
Chris Lattnerb5d70302007-02-19 20:01:23 +0000566 return ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
Chris Lattner7c1018a2006-07-14 19:37:40 +0000567 }
Chris Lattner7c1018a2006-07-14 19:37:40 +0000568 default:
569 assert(getNumOperands() == 2 && "Must be binary operator?");
Chris Lattner227816342006-07-14 22:20:01 +0000570 Op0 = (OpNo == 0) ? Op : getOperand(0);
571 Op1 = (OpNo == 1) ? Op : getOperand(1);
572 return ConstantExpr::get(getOpcode(), Op0, Op1);
573 }
574}
575
576/// getWithOperands - This returns the current constant expression with the
577/// operands replaced with the specified values. The specified operands must
578/// match count and type with the existing ones.
579Constant *ConstantExpr::
580getWithOperands(const std::vector<Constant*> &Ops) const {
581 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
582 bool AnyChange = false;
583 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
584 assert(Ops[i]->getType() == getOperand(i)->getType() &&
585 "Operand type mismatch!");
586 AnyChange |= Ops[i] != getOperand(i);
587 }
588 if (!AnyChange) // No operands changed, return self.
589 return const_cast<ConstantExpr*>(this);
590
591 switch (getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000592 case Instruction::Trunc:
593 case Instruction::ZExt:
594 case Instruction::SExt:
595 case Instruction::FPTrunc:
596 case Instruction::FPExt:
597 case Instruction::UIToFP:
598 case Instruction::SIToFP:
599 case Instruction::FPToUI:
600 case Instruction::FPToSI:
601 case Instruction::PtrToInt:
602 case Instruction::IntToPtr:
603 case Instruction::BitCast:
604 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
Chris Lattner227816342006-07-14 22:20:01 +0000605 case Instruction::Select:
606 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
607 case Instruction::InsertElement:
608 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
609 case Instruction::ExtractElement:
610 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
611 case Instruction::ShuffleVector:
612 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
Chris Lattnerb5d70302007-02-19 20:01:23 +0000613 case Instruction::GetElementPtr:
614 return ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], Ops.size()-1);
Reid Spencer266e42b2006-12-23 06:05:41 +0000615 case Instruction::ICmp:
616 case Instruction::FCmp:
617 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
Chris Lattner227816342006-07-14 22:20:01 +0000618 default:
619 assert(getNumOperands() == 2 && "Must be binary operator?");
620 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000621 }
622}
623
Chris Lattner2f7c9632001-06-06 20:29:01 +0000624
625//===----------------------------------------------------------------------===//
Chris Lattner2f7c9632001-06-06 20:29:01 +0000626// isValueValidForType implementations
627
Reid Spencere7334722006-12-19 01:28:19 +0000628bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000629 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000630 if (Ty == Type::Int1Ty)
631 return Val == 0 || Val == 1;
Reid Spencerd7a00d72007-02-05 23:47:56 +0000632 if (NumBits >= 64)
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000633 return true; // always true, has to fit in largest type
634 uint64_t Max = (1ll << NumBits) - 1;
635 return Val <= Max;
Reid Spencere7334722006-12-19 01:28:19 +0000636}
637
Reid Spencere0fc4df2006-10-20 07:07:24 +0000638bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000639 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000640 if (Ty == Type::Int1Ty)
Reid Spencera94d3942007-01-19 21:13:56 +0000641 return Val == 0 || Val == 1 || Val == -1;
Reid Spencerd7a00d72007-02-05 23:47:56 +0000642 if (NumBits >= 64)
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000643 return true; // always true, has to fit in largest type
644 int64_t Min = -(1ll << (NumBits-1));
645 int64_t Max = (1ll << (NumBits-1)) - 1;
646 return (Val >= Min && Val <= Max);
Chris Lattner2f7c9632001-06-06 20:29:01 +0000647}
648
Chris Lattner3462ae32001-12-03 22:26:30 +0000649bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
Chris Lattner6b727592004-06-17 18:19:28 +0000650 switch (Ty->getTypeID()) {
Chris Lattner2f7c9632001-06-06 20:29:01 +0000651 default:
652 return false; // These can't be represented as floating point!
653
Reid Spencerb95f8ab2004-12-07 07:38:08 +0000654 // TODO: Figure out how to test if a double can be cast to a float!
Chris Lattner2f7c9632001-06-06 20:29:01 +0000655 case Type::FloatTyID:
Chris Lattner2f7c9632001-06-06 20:29:01 +0000656 case Type::DoubleTyID:
657 return true; // This is the largest type...
658 }
Chris Lattneraa2372562006-05-24 17:04:05 +0000659}
Chris Lattner9655e542001-07-20 19:16:02 +0000660
Chris Lattner49d855c2001-09-07 16:46:31 +0000661//===----------------------------------------------------------------------===//
Chris Lattner49d855c2001-09-07 16:46:31 +0000662// Factory Function Implementation
663
Chris Lattner98fa07b2003-05-23 20:03:32 +0000664// ConstantCreator - A class that is used to create constants by
665// ValueMap*. This class should be partially specialized if there is
666// something strange that needs to be done to interface to the ctor for the
667// constant.
668//
Chris Lattner189d19f2003-11-21 20:23:48 +0000669namespace llvm {
670 template<class ConstantClass, class TypeClass, class ValType>
Chris Lattner02157b02006-06-28 21:38:54 +0000671 struct VISIBILITY_HIDDEN ConstantCreator {
Chris Lattner189d19f2003-11-21 20:23:48 +0000672 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
673 return new ConstantClass(Ty, V);
674 }
675 };
Misha Brukmanb1c93172005-04-21 23:48:37 +0000676
Chris Lattner189d19f2003-11-21 20:23:48 +0000677 template<class ConstantClass, class TypeClass>
Chris Lattner02157b02006-06-28 21:38:54 +0000678 struct VISIBILITY_HIDDEN ConvertConstantType {
Chris Lattner189d19f2003-11-21 20:23:48 +0000679 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
680 assert(0 && "This type cannot be converted!\n");
681 abort();
682 }
683 };
Chris Lattnerb50d1352003-10-05 00:17:43 +0000684
Chris Lattner935aa922005-10-04 17:48:46 +0000685 template<class ValType, class TypeClass, class ConstantClass,
686 bool HasLargeKey = false /*true for arrays and structs*/ >
Chris Lattner02157b02006-06-28 21:38:54 +0000687 class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
Chris Lattnerb64419a2005-10-03 22:51:37 +0000688 public:
Jim Laskeyc03caef2006-07-17 17:38:29 +0000689 typedef std::pair<const Type*, ValType> MapKey;
690 typedef std::map<MapKey, Constant *> MapTy;
691 typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
692 typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
Chris Lattnerb64419a2005-10-03 22:51:37 +0000693 private:
Chris Lattner5bbf60a52005-10-04 16:52:46 +0000694 /// Map - This is the main map from the element descriptor to the Constants.
695 /// This is the primary way we avoid creating two of the same shape
696 /// constant.
Chris Lattnerb50d1352003-10-05 00:17:43 +0000697 MapTy Map;
Chris Lattner935aa922005-10-04 17:48:46 +0000698
699 /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
700 /// from the constants to their element in Map. This is important for
701 /// removal of constants from the array, which would otherwise have to scan
702 /// through the map with very large keys.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000703 InverseMapTy InverseMap;
Chris Lattnerb50d1352003-10-05 00:17:43 +0000704
Jim Laskeyc03caef2006-07-17 17:38:29 +0000705 /// AbstractTypeMap - Map for abstract type constants.
706 ///
Chris Lattnerb50d1352003-10-05 00:17:43 +0000707 AbstractTypeMapTy AbstractTypeMap;
Chris Lattner99a669b2004-11-19 16:39:44 +0000708
Chris Lattner98fa07b2003-05-23 20:03:32 +0000709 public:
Jim Laskeyc03caef2006-07-17 17:38:29 +0000710 typename MapTy::iterator map_end() { return Map.end(); }
Chris Lattnerb64419a2005-10-03 22:51:37 +0000711
712 /// InsertOrGetItem - Return an iterator for the specified element.
713 /// If the element exists in the map, the returned iterator points to the
714 /// entry and Exists=true. If not, the iterator points to the newly
715 /// inserted entry and returns Exists=false. Newly inserted entries have
716 /// I->second == 0, and should be filled in.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000717 typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
718 &InsertVal,
Chris Lattnerb64419a2005-10-03 22:51:37 +0000719 bool &Exists) {
Jim Laskeyc03caef2006-07-17 17:38:29 +0000720 std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
Chris Lattnerb64419a2005-10-03 22:51:37 +0000721 Exists = !IP.second;
722 return IP.first;
723 }
Chris Lattner5bbf60a52005-10-04 16:52:46 +0000724
Chris Lattner935aa922005-10-04 17:48:46 +0000725private:
Jim Laskeyc03caef2006-07-17 17:38:29 +0000726 typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
Chris Lattner935aa922005-10-04 17:48:46 +0000727 if (HasLargeKey) {
Jim Laskeyc03caef2006-07-17 17:38:29 +0000728 typename InverseMapTy::iterator IMI = InverseMap.find(CP);
Chris Lattner935aa922005-10-04 17:48:46 +0000729 assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
730 IMI->second->second == CP &&
731 "InverseMap corrupt!");
732 return IMI->second;
733 }
734
Jim Laskeyc03caef2006-07-17 17:38:29 +0000735 typename MapTy::iterator I =
Chris Lattner935aa922005-10-04 17:48:46 +0000736 Map.find(MapKey((TypeClass*)CP->getRawType(), getValType(CP)));
Chris Lattner5bbf60a52005-10-04 16:52:46 +0000737 if (I == Map.end() || I->second != CP) {
738 // FIXME: This should not use a linear scan. If this gets to be a
739 // performance problem, someone should look at this.
740 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
741 /* empty */;
742 }
Chris Lattner935aa922005-10-04 17:48:46 +0000743 return I;
744 }
745public:
746
Chris Lattnerb64419a2005-10-03 22:51:37 +0000747 /// getOrCreate - Return the specified constant from the map, creating it if
748 /// necessary.
Chris Lattner98fa07b2003-05-23 20:03:32 +0000749 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
Chris Lattnerb50d1352003-10-05 00:17:43 +0000750 MapKey Lookup(Ty, V);
Jim Laskeyc03caef2006-07-17 17:38:29 +0000751 typename MapTy::iterator I = Map.lower_bound(Lookup);
Reid Spencere0fc4df2006-10-20 07:07:24 +0000752 // Is it in the map?
Chris Lattner98fa07b2003-05-23 20:03:32 +0000753 if (I != Map.end() && I->first == Lookup)
Reid Spencere0fc4df2006-10-20 07:07:24 +0000754 return static_cast<ConstantClass *>(I->second);
Chris Lattner98fa07b2003-05-23 20:03:32 +0000755
756 // If no preexisting value, create one now...
757 ConstantClass *Result =
758 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
759
Chris Lattnerb50d1352003-10-05 00:17:43 +0000760 /// FIXME: why does this assert fail when loading 176.gcc?
761 //assert(Result->getType() == Ty && "Type specified is not correct!");
762 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
763
Chris Lattner935aa922005-10-04 17:48:46 +0000764 if (HasLargeKey) // Remember the reverse mapping if needed.
765 InverseMap.insert(std::make_pair(Result, I));
766
Chris Lattnerb50d1352003-10-05 00:17:43 +0000767 // If the type of the constant is abstract, make sure that an entry exists
768 // for it in the AbstractTypeMap.
769 if (Ty->isAbstract()) {
770 typename AbstractTypeMapTy::iterator TI =
771 AbstractTypeMap.lower_bound(Ty);
772
773 if (TI == AbstractTypeMap.end() || TI->first != Ty) {
774 // Add ourselves to the ATU list of the type.
775 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
776
777 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
778 }
779 }
Chris Lattner98fa07b2003-05-23 20:03:32 +0000780 return Result;
781 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000782
Chris Lattner98fa07b2003-05-23 20:03:32 +0000783 void remove(ConstantClass *CP) {
Jim Laskeyc03caef2006-07-17 17:38:29 +0000784 typename MapTy::iterator I = FindExistingElement(CP);
Chris Lattnerb50d1352003-10-05 00:17:43 +0000785 assert(I != Map.end() && "Constant not found in constant table!");
Chris Lattner3e650af2004-08-04 04:48:01 +0000786 assert(I->second == CP && "Didn't find correct element?");
Chris Lattnerb50d1352003-10-05 00:17:43 +0000787
Chris Lattner935aa922005-10-04 17:48:46 +0000788 if (HasLargeKey) // Remember the reverse mapping if needed.
789 InverseMap.erase(CP);
790
Chris Lattnerb50d1352003-10-05 00:17:43 +0000791 // Now that we found the entry, make sure this isn't the entry that
792 // the AbstractTypeMap points to.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000793 const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
Chris Lattnerb50d1352003-10-05 00:17:43 +0000794 if (Ty->isAbstract()) {
795 assert(AbstractTypeMap.count(Ty) &&
796 "Abstract type not in AbstractTypeMap?");
Jim Laskeyc03caef2006-07-17 17:38:29 +0000797 typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
Chris Lattnerb50d1352003-10-05 00:17:43 +0000798 if (ATMEntryIt == I) {
799 // Yes, we are removing the representative entry for this type.
800 // See if there are any other entries of the same type.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000801 typename MapTy::iterator TmpIt = ATMEntryIt;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000802
Chris Lattnerb50d1352003-10-05 00:17:43 +0000803 // First check the entry before this one...
804 if (TmpIt != Map.begin()) {
805 --TmpIt;
806 if (TmpIt->first.first != Ty) // Not the same type, move back...
807 ++TmpIt;
808 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000809
Chris Lattnerb50d1352003-10-05 00:17:43 +0000810 // If we didn't find the same type, try to move forward...
811 if (TmpIt == ATMEntryIt) {
812 ++TmpIt;
813 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
814 --TmpIt; // No entry afterwards with the same type
815 }
816
817 // If there is another entry in the map of the same abstract type,
818 // update the AbstractTypeMap entry now.
819 if (TmpIt != ATMEntryIt) {
820 ATMEntryIt = TmpIt;
821 } else {
822 // Otherwise, we are removing the last instance of this type
823 // from the table. Remove from the ATM, and from user list.
824 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
825 AbstractTypeMap.erase(Ty);
826 }
Chris Lattner98fa07b2003-05-23 20:03:32 +0000827 }
Chris Lattnerb50d1352003-10-05 00:17:43 +0000828 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000829
Chris Lattnerb50d1352003-10-05 00:17:43 +0000830 Map.erase(I);
831 }
832
Chris Lattner3b793c62005-10-04 21:35:50 +0000833
834 /// MoveConstantToNewSlot - If we are about to change C to be the element
835 /// specified by I, update our internal data structures to reflect this
836 /// fact.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000837 void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
Chris Lattner3b793c62005-10-04 21:35:50 +0000838 // First, remove the old location of the specified constant in the map.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000839 typename MapTy::iterator OldI = FindExistingElement(C);
Chris Lattner3b793c62005-10-04 21:35:50 +0000840 assert(OldI != Map.end() && "Constant not found in constant table!");
841 assert(OldI->second == C && "Didn't find correct element?");
842
843 // If this constant is the representative element for its abstract type,
844 // update the AbstractTypeMap so that the representative element is I.
845 if (C->getType()->isAbstract()) {
846 typename AbstractTypeMapTy::iterator ATI =
847 AbstractTypeMap.find(C->getType());
848 assert(ATI != AbstractTypeMap.end() &&
849 "Abstract type not in AbstractTypeMap?");
850 if (ATI->second == OldI)
851 ATI->second = I;
852 }
853
854 // Remove the old entry from the map.
855 Map.erase(OldI);
856
857 // Update the inverse map so that we know that this constant is now
858 // located at descriptor I.
859 if (HasLargeKey) {
860 assert(I->second == C && "Bad inversemap entry!");
861 InverseMap[C] = I;
862 }
863 }
864
Chris Lattnerb50d1352003-10-05 00:17:43 +0000865 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
Misha Brukmanb1c93172005-04-21 23:48:37 +0000866 typename AbstractTypeMapTy::iterator I =
Jim Laskeyc03caef2006-07-17 17:38:29 +0000867 AbstractTypeMap.find(cast<Type>(OldTy));
Chris Lattnerb50d1352003-10-05 00:17:43 +0000868
869 assert(I != AbstractTypeMap.end() &&
870 "Abstract type not in AbstractTypeMap?");
871
872 // Convert a constant at a time until the last one is gone. The last one
873 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
874 // eliminated eventually.
875 do {
876 ConvertConstantType<ConstantClass,
Jim Laskeyc03caef2006-07-17 17:38:29 +0000877 TypeClass>::convert(
878 static_cast<ConstantClass *>(I->second->second),
Chris Lattnerb50d1352003-10-05 00:17:43 +0000879 cast<TypeClass>(NewTy));
880
Jim Laskeyc03caef2006-07-17 17:38:29 +0000881 I = AbstractTypeMap.find(cast<Type>(OldTy));
Chris Lattnerb50d1352003-10-05 00:17:43 +0000882 } while (I != AbstractTypeMap.end());
883 }
884
885 // If the type became concrete without being refined to any other existing
886 // type, we just remove ourselves from the ATU list.
887 void typeBecameConcrete(const DerivedType *AbsTy) {
888 AbsTy->removeAbstractTypeUser(this);
889 }
890
891 void dump() const {
Bill Wendling6a462f12006-11-17 08:03:48 +0000892 DOUT << "Constant.cpp: ValueMap\n";
Chris Lattner98fa07b2003-05-23 20:03:32 +0000893 }
894 };
895}
896
Chris Lattnera84df0a22006-09-28 23:36:21 +0000897
Chris Lattner28173502007-02-20 06:11:36 +0000898
Chris Lattner9fba3da2004-02-15 05:53:04 +0000899//---- ConstantAggregateZero::get() implementation...
900//
901namespace llvm {
902 // ConstantAggregateZero does not take extra "value" argument...
903 template<class ValType>
904 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
905 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
906 return new ConstantAggregateZero(Ty);
907 }
908 };
909
910 template<>
911 struct ConvertConstantType<ConstantAggregateZero, Type> {
912 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
913 // Make everyone now use a constant of the new type...
914 Constant *New = ConstantAggregateZero::get(NewTy);
915 assert(New != OldC && "Didn't replace constant??");
916 OldC->uncheckedReplaceAllUsesWith(New);
917 OldC->destroyConstant(); // This constant is now dead, destroy it.
918 }
919 };
920}
921
Chris Lattner69edc982006-09-28 00:35:06 +0000922static ManagedStatic<ValueMap<char, Type,
923 ConstantAggregateZero> > AggZeroConstants;
Chris Lattner9fba3da2004-02-15 05:53:04 +0000924
Chris Lattner3e650af2004-08-04 04:48:01 +0000925static char getValType(ConstantAggregateZero *CPZ) { return 0; }
926
Chris Lattner9fba3da2004-02-15 05:53:04 +0000927Constant *ConstantAggregateZero::get(const Type *Ty) {
Reid Spencerd84d35b2007-02-15 02:26:10 +0000928 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) &&
Chris Lattnerbfd0b6d2006-06-10 04:16:23 +0000929 "Cannot create an aggregate zero of non-aggregate type!");
Chris Lattner69edc982006-09-28 00:35:06 +0000930 return AggZeroConstants->getOrCreate(Ty, 0);
Chris Lattner9fba3da2004-02-15 05:53:04 +0000931}
932
933// destroyConstant - Remove the constant from the constant table...
934//
935void ConstantAggregateZero::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +0000936 AggZeroConstants->remove(this);
Chris Lattner9fba3da2004-02-15 05:53:04 +0000937 destroyConstantImpl();
938}
939
Chris Lattner3462ae32001-12-03 22:26:30 +0000940//---- ConstantArray::get() implementation...
Chris Lattner49d855c2001-09-07 16:46:31 +0000941//
Chris Lattner189d19f2003-11-21 20:23:48 +0000942namespace llvm {
943 template<>
944 struct ConvertConstantType<ConstantArray, ArrayType> {
945 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
946 // Make everyone now use a constant of the new type...
947 std::vector<Constant*> C;
948 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
949 C.push_back(cast<Constant>(OldC->getOperand(i)));
950 Constant *New = ConstantArray::get(NewTy, C);
951 assert(New != OldC && "Didn't replace constant??");
952 OldC->uncheckedReplaceAllUsesWith(New);
953 OldC->destroyConstant(); // This constant is now dead, destroy it.
954 }
955 };
956}
Chris Lattnerb50d1352003-10-05 00:17:43 +0000957
Chris Lattner3e650af2004-08-04 04:48:01 +0000958static std::vector<Constant*> getValType(ConstantArray *CA) {
959 std::vector<Constant*> Elements;
960 Elements.reserve(CA->getNumOperands());
961 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
962 Elements.push_back(cast<Constant>(CA->getOperand(i)));
963 return Elements;
964}
965
Chris Lattnerb64419a2005-10-03 22:51:37 +0000966typedef ValueMap<std::vector<Constant*>, ArrayType,
Chris Lattner935aa922005-10-04 17:48:46 +0000967 ConstantArray, true /*largekey*/> ArrayConstantsTy;
Chris Lattner69edc982006-09-28 00:35:06 +0000968static ManagedStatic<ArrayConstantsTy> ArrayConstants;
Chris Lattner49d855c2001-09-07 16:46:31 +0000969
Chris Lattner015e8212004-02-15 04:14:47 +0000970Constant *ConstantArray::get(const ArrayType *Ty,
Chris Lattner9fba3da2004-02-15 05:53:04 +0000971 const std::vector<Constant*> &V) {
972 // If this is an all-zero array, return a ConstantAggregateZero object
973 if (!V.empty()) {
974 Constant *C = V[0];
975 if (!C->isNullValue())
Chris Lattner69edc982006-09-28 00:35:06 +0000976 return ArrayConstants->getOrCreate(Ty, V);
Chris Lattner9fba3da2004-02-15 05:53:04 +0000977 for (unsigned i = 1, e = V.size(); i != e; ++i)
978 if (V[i] != C)
Chris Lattner69edc982006-09-28 00:35:06 +0000979 return ArrayConstants->getOrCreate(Ty, V);
Chris Lattner9fba3da2004-02-15 05:53:04 +0000980 }
981 return ConstantAggregateZero::get(Ty);
Chris Lattner49d855c2001-09-07 16:46:31 +0000982}
983
Chris Lattner98fa07b2003-05-23 20:03:32 +0000984// destroyConstant - Remove the constant from the constant table...
985//
986void ConstantArray::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +0000987 ArrayConstants->remove(this);
Chris Lattner98fa07b2003-05-23 20:03:32 +0000988 destroyConstantImpl();
989}
990
Reid Spencer6f614532006-05-30 08:23:18 +0000991/// ConstantArray::get(const string&) - Return an array that is initialized to
992/// contain the specified string. If length is zero then a null terminator is
993/// added to the specified string so that it may be used in a natural way.
994/// Otherwise, the length parameter specifies how much of the string to use
995/// and it won't be null terminated.
996///
Reid Spencer82ebaba2006-05-30 18:15:07 +0000997Constant *ConstantArray::get(const std::string &Str, bool AddNull) {
Chris Lattner7f74a562002-01-20 22:54:45 +0000998 std::vector<Constant*> ElementVals;
Reid Spencer82ebaba2006-05-30 18:15:07 +0000999 for (unsigned i = 0; i < Str.length(); ++i)
Reid Spencer8d9336d2006-12-31 05:26:44 +00001000 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, Str[i]));
Chris Lattner8f80fe02001-10-14 23:54:12 +00001001
1002 // Add a null terminator to the string...
Reid Spencer82ebaba2006-05-30 18:15:07 +00001003 if (AddNull) {
Reid Spencer8d9336d2006-12-31 05:26:44 +00001004 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, 0));
Reid Spencer6f614532006-05-30 08:23:18 +00001005 }
Chris Lattner8f80fe02001-10-14 23:54:12 +00001006
Reid Spencer8d9336d2006-12-31 05:26:44 +00001007 ArrayType *ATy = ArrayType::get(Type::Int8Ty, ElementVals.size());
Chris Lattner3462ae32001-12-03 22:26:30 +00001008 return ConstantArray::get(ATy, ElementVals);
Vikram S. Adve34410432001-10-14 23:17:20 +00001009}
1010
Reid Spencer2546b762007-01-26 07:37:34 +00001011/// isString - This method returns true if the array is an array of i8, and
1012/// if the elements of the array are all ConstantInt's.
Chris Lattnere8dfcca2004-01-14 17:06:38 +00001013bool ConstantArray::isString() const {
Reid Spencer2546b762007-01-26 07:37:34 +00001014 // Check the element type for i8...
Reid Spencer8d9336d2006-12-31 05:26:44 +00001015 if (getType()->getElementType() != Type::Int8Ty)
Chris Lattnere8dfcca2004-01-14 17:06:38 +00001016 return false;
1017 // Check the elements to make sure they are all integers, not constant
1018 // expressions.
1019 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1020 if (!isa<ConstantInt>(getOperand(i)))
1021 return false;
1022 return true;
1023}
1024
Evan Cheng3763c5b2006-10-26 19:15:05 +00001025/// isCString - This method returns true if the array is a string (see
1026/// isString) and it ends in a null byte \0 and does not contains any other
1027/// null bytes except its terminator.
1028bool ConstantArray::isCString() const {
Reid Spencer2546b762007-01-26 07:37:34 +00001029 // Check the element type for i8...
Reid Spencer8d9336d2006-12-31 05:26:44 +00001030 if (getType()->getElementType() != Type::Int8Ty)
Evan Chenge974da62006-10-26 21:48:03 +00001031 return false;
1032 Constant *Zero = Constant::getNullValue(getOperand(0)->getType());
1033 // Last element must be a null.
1034 if (getOperand(getNumOperands()-1) != Zero)
1035 return false;
1036 // Other elements must be non-null integers.
1037 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1038 if (!isa<ConstantInt>(getOperand(i)))
Evan Cheng3763c5b2006-10-26 19:15:05 +00001039 return false;
Evan Chenge974da62006-10-26 21:48:03 +00001040 if (getOperand(i) == Zero)
1041 return false;
1042 }
Evan Cheng3763c5b2006-10-26 19:15:05 +00001043 return true;
1044}
1045
1046
Reid Spencer2546b762007-01-26 07:37:34 +00001047// getAsString - If the sub-element type of this array is i8
Chris Lattner81fabb02002-08-26 17:53:56 +00001048// then this method converts the array to an std::string and returns it.
1049// Otherwise, it asserts out.
1050//
1051std::string ConstantArray::getAsString() const {
Chris Lattnere8dfcca2004-01-14 17:06:38 +00001052 assert(isString() && "Not a string!");
Chris Lattner81fabb02002-08-26 17:53:56 +00001053 std::string Result;
Chris Lattner6077c312003-07-23 15:22:26 +00001054 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
Reid Spencere0fc4df2006-10-20 07:07:24 +00001055 Result += (char)cast<ConstantInt>(getOperand(i))->getZExtValue();
Chris Lattner81fabb02002-08-26 17:53:56 +00001056 return Result;
1057}
1058
1059
Chris Lattner3462ae32001-12-03 22:26:30 +00001060//---- ConstantStruct::get() implementation...
Chris Lattner49d855c2001-09-07 16:46:31 +00001061//
Chris Lattnerb50d1352003-10-05 00:17:43 +00001062
Chris Lattner189d19f2003-11-21 20:23:48 +00001063namespace llvm {
1064 template<>
1065 struct ConvertConstantType<ConstantStruct, StructType> {
1066 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1067 // Make everyone now use a constant of the new type...
1068 std::vector<Constant*> C;
1069 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1070 C.push_back(cast<Constant>(OldC->getOperand(i)));
1071 Constant *New = ConstantStruct::get(NewTy, C);
1072 assert(New != OldC && "Didn't replace constant??");
Misha Brukmanb1c93172005-04-21 23:48:37 +00001073
Chris Lattner189d19f2003-11-21 20:23:48 +00001074 OldC->uncheckedReplaceAllUsesWith(New);
1075 OldC->destroyConstant(); // This constant is now dead, destroy it.
1076 }
1077 };
1078}
Chris Lattnerb50d1352003-10-05 00:17:43 +00001079
Chris Lattner8760ec72005-10-04 01:17:50 +00001080typedef ValueMap<std::vector<Constant*>, StructType,
Chris Lattner935aa922005-10-04 17:48:46 +00001081 ConstantStruct, true /*largekey*/> StructConstantsTy;
Chris Lattner69edc982006-09-28 00:35:06 +00001082static ManagedStatic<StructConstantsTy> StructConstants;
Chris Lattner49d855c2001-09-07 16:46:31 +00001083
Chris Lattner3e650af2004-08-04 04:48:01 +00001084static std::vector<Constant*> getValType(ConstantStruct *CS) {
1085 std::vector<Constant*> Elements;
1086 Elements.reserve(CS->getNumOperands());
1087 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1088 Elements.push_back(cast<Constant>(CS->getOperand(i)));
1089 return Elements;
1090}
1091
Chris Lattner015e8212004-02-15 04:14:47 +00001092Constant *ConstantStruct::get(const StructType *Ty,
1093 const std::vector<Constant*> &V) {
Chris Lattner9fba3da2004-02-15 05:53:04 +00001094 // Create a ConstantAggregateZero value if all elements are zeros...
1095 for (unsigned i = 0, e = V.size(); i != e; ++i)
1096 if (!V[i]->isNullValue())
Chris Lattner69edc982006-09-28 00:35:06 +00001097 return StructConstants->getOrCreate(Ty, V);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001098
1099 return ConstantAggregateZero::get(Ty);
Chris Lattner49d855c2001-09-07 16:46:31 +00001100}
Chris Lattner883ad0b2001-10-03 15:39:36 +00001101
Andrew Lenharthdcb3c972006-12-08 18:06:16 +00001102Constant *ConstantStruct::get(const std::vector<Constant*> &V, bool packed) {
Chris Lattnerd6108ca2004-07-12 20:35:11 +00001103 std::vector<const Type*> StructEls;
1104 StructEls.reserve(V.size());
1105 for (unsigned i = 0, e = V.size(); i != e; ++i)
1106 StructEls.push_back(V[i]->getType());
Andrew Lenharthdcb3c972006-12-08 18:06:16 +00001107 return get(StructType::get(StructEls, packed), V);
Chris Lattnerd6108ca2004-07-12 20:35:11 +00001108}
1109
Chris Lattnerd7a73302001-10-13 06:57:33 +00001110// destroyConstant - Remove the constant from the constant table...
Chris Lattner883ad0b2001-10-03 15:39:36 +00001111//
Chris Lattner3462ae32001-12-03 22:26:30 +00001112void ConstantStruct::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001113 StructConstants->remove(this);
Chris Lattnerd7a73302001-10-13 06:57:33 +00001114 destroyConstantImpl();
1115}
Chris Lattner883ad0b2001-10-03 15:39:36 +00001116
Reid Spencerd84d35b2007-02-15 02:26:10 +00001117//---- ConstantVector::get() implementation...
Brian Gaeke02209042004-08-20 06:00:58 +00001118//
1119namespace llvm {
1120 template<>
Reid Spencerd84d35b2007-02-15 02:26:10 +00001121 struct ConvertConstantType<ConstantVector, VectorType> {
1122 static void convert(ConstantVector *OldC, const VectorType *NewTy) {
Brian Gaeke02209042004-08-20 06:00:58 +00001123 // Make everyone now use a constant of the new type...
1124 std::vector<Constant*> C;
1125 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1126 C.push_back(cast<Constant>(OldC->getOperand(i)));
Reid Spencerd84d35b2007-02-15 02:26:10 +00001127 Constant *New = ConstantVector::get(NewTy, C);
Brian Gaeke02209042004-08-20 06:00:58 +00001128 assert(New != OldC && "Didn't replace constant??");
1129 OldC->uncheckedReplaceAllUsesWith(New);
1130 OldC->destroyConstant(); // This constant is now dead, destroy it.
1131 }
1132 };
1133}
1134
Reid Spencerd84d35b2007-02-15 02:26:10 +00001135static std::vector<Constant*> getValType(ConstantVector *CP) {
Brian Gaeke02209042004-08-20 06:00:58 +00001136 std::vector<Constant*> Elements;
1137 Elements.reserve(CP->getNumOperands());
1138 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1139 Elements.push_back(CP->getOperand(i));
1140 return Elements;
1141}
1142
Reid Spencerd84d35b2007-02-15 02:26:10 +00001143static ManagedStatic<ValueMap<std::vector<Constant*>, VectorType,
Reid Spencer09575ba2007-02-15 03:39:18 +00001144 ConstantVector> > VectorConstants;
Brian Gaeke02209042004-08-20 06:00:58 +00001145
Reid Spencerd84d35b2007-02-15 02:26:10 +00001146Constant *ConstantVector::get(const VectorType *Ty,
Brian Gaeke02209042004-08-20 06:00:58 +00001147 const std::vector<Constant*> &V) {
1148 // If this is an all-zero packed, return a ConstantAggregateZero object
1149 if (!V.empty()) {
1150 Constant *C = V[0];
1151 if (!C->isNullValue())
Reid Spencer09575ba2007-02-15 03:39:18 +00001152 return VectorConstants->getOrCreate(Ty, V);
Brian Gaeke02209042004-08-20 06:00:58 +00001153 for (unsigned i = 1, e = V.size(); i != e; ++i)
1154 if (V[i] != C)
Reid Spencer09575ba2007-02-15 03:39:18 +00001155 return VectorConstants->getOrCreate(Ty, V);
Brian Gaeke02209042004-08-20 06:00:58 +00001156 }
1157 return ConstantAggregateZero::get(Ty);
1158}
1159
Reid Spencerd84d35b2007-02-15 02:26:10 +00001160Constant *ConstantVector::get(const std::vector<Constant*> &V) {
Brian Gaeke02209042004-08-20 06:00:58 +00001161 assert(!V.empty() && "Cannot infer type if V is empty");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001162 return get(VectorType::get(V.front()->getType(),V.size()), V);
Brian Gaeke02209042004-08-20 06:00:58 +00001163}
1164
1165// destroyConstant - Remove the constant from the constant table...
1166//
Reid Spencerd84d35b2007-02-15 02:26:10 +00001167void ConstantVector::destroyConstant() {
Reid Spencer09575ba2007-02-15 03:39:18 +00001168 VectorConstants->remove(this);
Brian Gaeke02209042004-08-20 06:00:58 +00001169 destroyConstantImpl();
1170}
1171
Jim Laskeyf0478822007-01-12 22:39:14 +00001172/// This function will return true iff every element in this packed constant
1173/// is set to all ones.
1174/// @returns true iff this constant's emements are all set to all ones.
1175/// @brief Determine if the value is all ones.
Reid Spencerd84d35b2007-02-15 02:26:10 +00001176bool ConstantVector::isAllOnesValue() const {
Jim Laskeyf0478822007-01-12 22:39:14 +00001177 // Check out first element.
1178 const Constant *Elt = getOperand(0);
1179 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1180 if (!CI || !CI->isAllOnesValue()) return false;
1181 // Then make sure all remaining elements point to the same value.
1182 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1183 if (getOperand(I) != Elt) return false;
1184 }
1185 return true;
1186}
1187
Chris Lattner3462ae32001-12-03 22:26:30 +00001188//---- ConstantPointerNull::get() implementation...
Chris Lattnerd7a73302001-10-13 06:57:33 +00001189//
Chris Lattner98fa07b2003-05-23 20:03:32 +00001190
Chris Lattner189d19f2003-11-21 20:23:48 +00001191namespace llvm {
1192 // ConstantPointerNull does not take extra "value" argument...
1193 template<class ValType>
1194 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1195 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1196 return new ConstantPointerNull(Ty);
1197 }
1198 };
Chris Lattner98fa07b2003-05-23 20:03:32 +00001199
Chris Lattner189d19f2003-11-21 20:23:48 +00001200 template<>
1201 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1202 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1203 // Make everyone now use a constant of the new type...
1204 Constant *New = ConstantPointerNull::get(NewTy);
1205 assert(New != OldC && "Didn't replace constant??");
1206 OldC->uncheckedReplaceAllUsesWith(New);
1207 OldC->destroyConstant(); // This constant is now dead, destroy it.
1208 }
1209 };
1210}
Chris Lattnerb50d1352003-10-05 00:17:43 +00001211
Chris Lattner69edc982006-09-28 00:35:06 +00001212static ManagedStatic<ValueMap<char, PointerType,
1213 ConstantPointerNull> > NullPtrConstants;
Chris Lattnerd7a73302001-10-13 06:57:33 +00001214
Chris Lattner3e650af2004-08-04 04:48:01 +00001215static char getValType(ConstantPointerNull *) {
1216 return 0;
1217}
1218
1219
Chris Lattner3462ae32001-12-03 22:26:30 +00001220ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
Chris Lattner69edc982006-09-28 00:35:06 +00001221 return NullPtrConstants->getOrCreate(Ty, 0);
Chris Lattner883ad0b2001-10-03 15:39:36 +00001222}
1223
Chris Lattner0c6e0b92002-08-18 00:40:04 +00001224// destroyConstant - Remove the constant from the constant table...
1225//
1226void ConstantPointerNull::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001227 NullPtrConstants->remove(this);
Chris Lattner0c6e0b92002-08-18 00:40:04 +00001228 destroyConstantImpl();
1229}
1230
1231
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001232//---- UndefValue::get() implementation...
1233//
1234
1235namespace llvm {
1236 // UndefValue does not take extra "value" argument...
1237 template<class ValType>
1238 struct ConstantCreator<UndefValue, Type, ValType> {
1239 static UndefValue *create(const Type *Ty, const ValType &V) {
1240 return new UndefValue(Ty);
1241 }
1242 };
1243
1244 template<>
1245 struct ConvertConstantType<UndefValue, Type> {
1246 static void convert(UndefValue *OldC, const Type *NewTy) {
1247 // Make everyone now use a constant of the new type.
1248 Constant *New = UndefValue::get(NewTy);
1249 assert(New != OldC && "Didn't replace constant??");
1250 OldC->uncheckedReplaceAllUsesWith(New);
1251 OldC->destroyConstant(); // This constant is now dead, destroy it.
1252 }
1253 };
1254}
1255
Chris Lattner69edc982006-09-28 00:35:06 +00001256static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001257
1258static char getValType(UndefValue *) {
1259 return 0;
1260}
1261
1262
1263UndefValue *UndefValue::get(const Type *Ty) {
Chris Lattner69edc982006-09-28 00:35:06 +00001264 return UndefValueConstants->getOrCreate(Ty, 0);
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001265}
1266
1267// destroyConstant - Remove the constant from the constant table.
1268//
1269void UndefValue::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001270 UndefValueConstants->remove(this);
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001271 destroyConstantImpl();
1272}
1273
1274
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001275//---- ConstantExpr::get() implementations...
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001276//
Reid Spencer8d9336d2006-12-31 05:26:44 +00001277
Reid Spenceree3c9912006-12-04 05:19:50 +00001278struct ExprMapKeyType {
1279 explicit ExprMapKeyType(unsigned opc, std::vector<Constant*> ops,
Reid Spencerdba6aa42006-12-04 18:38:05 +00001280 unsigned short pred = 0) : opcode(opc), predicate(pred), operands(ops) { }
1281 uint16_t opcode;
1282 uint16_t predicate;
Reid Spenceree3c9912006-12-04 05:19:50 +00001283 std::vector<Constant*> operands;
Reid Spenceree3c9912006-12-04 05:19:50 +00001284 bool operator==(const ExprMapKeyType& that) const {
1285 return this->opcode == that.opcode &&
1286 this->predicate == that.predicate &&
1287 this->operands == that.operands;
1288 }
1289 bool operator<(const ExprMapKeyType & that) const {
1290 return this->opcode < that.opcode ||
1291 (this->opcode == that.opcode && this->predicate < that.predicate) ||
1292 (this->opcode == that.opcode && this->predicate == that.predicate &&
1293 this->operands < that.operands);
1294 }
1295
1296 bool operator!=(const ExprMapKeyType& that) const {
1297 return !(*this == that);
1298 }
1299};
Chris Lattner98fa07b2003-05-23 20:03:32 +00001300
Chris Lattner189d19f2003-11-21 20:23:48 +00001301namespace llvm {
1302 template<>
1303 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
Reid Spencer10fbf0e2006-12-03 05:48:19 +00001304 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1305 unsigned short pred = 0) {
Reid Spenceree3c9912006-12-04 05:19:50 +00001306 if (Instruction::isCast(V.opcode))
1307 return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1308 if ((V.opcode >= Instruction::BinaryOpsBegin &&
Reid Spencer2341c222007-02-02 02:16:23 +00001309 V.opcode < Instruction::BinaryOpsEnd))
Reid Spenceree3c9912006-12-04 05:19:50 +00001310 return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1311 if (V.opcode == Instruction::Select)
1312 return new SelectConstantExpr(V.operands[0], V.operands[1],
1313 V.operands[2]);
1314 if (V.opcode == Instruction::ExtractElement)
1315 return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1316 if (V.opcode == Instruction::InsertElement)
1317 return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1318 V.operands[2]);
1319 if (V.opcode == Instruction::ShuffleVector)
1320 return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1321 V.operands[2]);
1322 if (V.opcode == Instruction::GetElementPtr) {
1323 std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
1324 return new GetElementPtrConstantExpr(V.operands[0], IdxList, Ty);
1325 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001326
Reid Spenceree3c9912006-12-04 05:19:50 +00001327 // The compare instructions are weird. We have to encode the predicate
1328 // value and it is combined with the instruction opcode by multiplying
1329 // the opcode by one hundred. We must decode this to get the predicate.
1330 if (V.opcode == Instruction::ICmp)
1331 return new CompareConstantExpr(Instruction::ICmp, V.predicate,
1332 V.operands[0], V.operands[1]);
1333 if (V.opcode == Instruction::FCmp)
1334 return new CompareConstantExpr(Instruction::FCmp, V.predicate,
1335 V.operands[0], V.operands[1]);
1336 assert(0 && "Invalid ConstantExpr!");
Jeff Cohen9f469632006-12-15 21:47:01 +00001337 return 0;
Chris Lattnerb50d1352003-10-05 00:17:43 +00001338 }
Chris Lattner189d19f2003-11-21 20:23:48 +00001339 };
Chris Lattnerb50d1352003-10-05 00:17:43 +00001340
Chris Lattner189d19f2003-11-21 20:23:48 +00001341 template<>
1342 struct ConvertConstantType<ConstantExpr, Type> {
1343 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1344 Constant *New;
1345 switch (OldC->getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001346 case Instruction::Trunc:
1347 case Instruction::ZExt:
1348 case Instruction::SExt:
1349 case Instruction::FPTrunc:
1350 case Instruction::FPExt:
1351 case Instruction::UIToFP:
1352 case Instruction::SIToFP:
1353 case Instruction::FPToUI:
1354 case Instruction::FPToSI:
1355 case Instruction::PtrToInt:
1356 case Instruction::IntToPtr:
1357 case Instruction::BitCast:
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001358 New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0),
1359 NewTy);
Chris Lattner189d19f2003-11-21 20:23:48 +00001360 break;
Chris Lattner6e415c02004-03-12 05:54:04 +00001361 case Instruction::Select:
1362 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1363 OldC->getOperand(1),
1364 OldC->getOperand(2));
1365 break;
Chris Lattner189d19f2003-11-21 20:23:48 +00001366 default:
1367 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
Reid Spencer7eb55b32006-11-02 01:53:59 +00001368 OldC->getOpcode() < Instruction::BinaryOpsEnd);
Chris Lattner189d19f2003-11-21 20:23:48 +00001369 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1370 OldC->getOperand(1));
1371 break;
1372 case Instruction::GetElementPtr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00001373 // Make everyone now use a constant of the new type...
Chris Lattner13128ab2004-10-11 22:52:25 +00001374 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
Chris Lattner302116a2007-01-31 04:40:28 +00001375 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0),
1376 &Idx[0], Idx.size());
Chris Lattner189d19f2003-11-21 20:23:48 +00001377 break;
1378 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001379
Chris Lattner189d19f2003-11-21 20:23:48 +00001380 assert(New != OldC && "Didn't replace constant??");
1381 OldC->uncheckedReplaceAllUsesWith(New);
1382 OldC->destroyConstant(); // This constant is now dead, destroy it.
1383 }
1384 };
1385} // end namespace llvm
Chris Lattnerb50d1352003-10-05 00:17:43 +00001386
1387
Chris Lattner3e650af2004-08-04 04:48:01 +00001388static ExprMapKeyType getValType(ConstantExpr *CE) {
1389 std::vector<Constant*> Operands;
1390 Operands.reserve(CE->getNumOperands());
1391 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1392 Operands.push_back(cast<Constant>(CE->getOperand(i)));
Reid Spenceree3c9912006-12-04 05:19:50 +00001393 return ExprMapKeyType(CE->getOpcode(), Operands,
1394 CE->isCompare() ? CE->getPredicate() : 0);
Chris Lattner3e650af2004-08-04 04:48:01 +00001395}
1396
Chris Lattner69edc982006-09-28 00:35:06 +00001397static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1398 ConstantExpr> > ExprConstants;
Vikram S. Adve4c485332002-07-15 18:19:33 +00001399
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001400/// This is a utility function to handle folding of casts and lookup of the
1401/// cast in the ExprConstants map. It is usedby the various get* methods below.
1402static inline Constant *getFoldedCast(
1403 Instruction::CastOps opc, Constant *C, const Type *Ty) {
Chris Lattner815ae2b2003-10-07 22:19:19 +00001404 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001405 // Fold a few common cases
1406 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1407 return FC;
Chris Lattneracdbe712003-04-17 19:24:48 +00001408
Vikram S. Adve4c485332002-07-15 18:19:33 +00001409 // Look up the constant in the table first to ensure uniqueness
Chris Lattner2b383d2e2003-05-13 21:37:02 +00001410 std::vector<Constant*> argVec(1, C);
Reid Spenceree3c9912006-12-04 05:19:50 +00001411 ExprMapKeyType Key(opc, argVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001412 return ExprConstants->getOrCreate(Ty, Key);
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001413}
Reid Spencerf37dc652006-12-05 19:14:13 +00001414
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001415Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1416 Instruction::CastOps opc = Instruction::CastOps(oc);
1417 assert(Instruction::isCast(opc) && "opcode out of range");
1418 assert(C && Ty && "Null arguments to getCast");
1419 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1420
1421 switch (opc) {
1422 default:
1423 assert(0 && "Invalid cast opcode");
1424 break;
1425 case Instruction::Trunc: return getTrunc(C, Ty);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001426 case Instruction::ZExt: return getZExt(C, Ty);
1427 case Instruction::SExt: return getSExt(C, Ty);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001428 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1429 case Instruction::FPExt: return getFPExtend(C, Ty);
1430 case Instruction::UIToFP: return getUIToFP(C, Ty);
1431 case Instruction::SIToFP: return getSIToFP(C, Ty);
1432 case Instruction::FPToUI: return getFPToUI(C, Ty);
1433 case Instruction::FPToSI: return getFPToSI(C, Ty);
1434 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1435 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1436 case Instruction::BitCast: return getBitCast(C, Ty);
Chris Lattner1ece6f82005-01-01 15:59:57 +00001437 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001438 return 0;
Reid Spencerf37dc652006-12-05 19:14:13 +00001439}
1440
Reid Spencer5c140882006-12-04 20:17:56 +00001441Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1442 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1443 return getCast(Instruction::BitCast, C, Ty);
1444 return getCast(Instruction::ZExt, C, Ty);
1445}
1446
1447Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1448 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1449 return getCast(Instruction::BitCast, C, Ty);
1450 return getCast(Instruction::SExt, C, Ty);
1451}
1452
1453Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1454 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1455 return getCast(Instruction::BitCast, C, Ty);
1456 return getCast(Instruction::Trunc, C, Ty);
1457}
1458
Reid Spencerbc245a02006-12-05 03:25:26 +00001459Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1460 assert(isa<PointerType>(S->getType()) && "Invalid cast");
Chris Lattner03c49532007-01-15 02:27:26 +00001461 assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
Reid Spencerbc245a02006-12-05 03:25:26 +00001462
Chris Lattner03c49532007-01-15 02:27:26 +00001463 if (Ty->isInteger())
Reid Spencerbc245a02006-12-05 03:25:26 +00001464 return getCast(Instruction::PtrToInt, S, Ty);
1465 return getCast(Instruction::BitCast, S, Ty);
1466}
1467
Reid Spencer56521c42006-12-12 00:51:07 +00001468Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
1469 bool isSigned) {
Chris Lattner03c49532007-01-15 02:27:26 +00001470 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
Reid Spencer56521c42006-12-12 00:51:07 +00001471 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1472 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1473 Instruction::CastOps opcode =
1474 (SrcBits == DstBits ? Instruction::BitCast :
1475 (SrcBits > DstBits ? Instruction::Trunc :
1476 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1477 return getCast(opcode, C, Ty);
1478}
1479
1480Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1481 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1482 "Invalid cast");
1483 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1484 unsigned DstBits = Ty->getPrimitiveSizeInBits();
Reid Spencerca104e82006-12-12 05:38:50 +00001485 if (SrcBits == DstBits)
1486 return C; // Avoid a useless cast
Reid Spencer56521c42006-12-12 00:51:07 +00001487 Instruction::CastOps opcode =
Reid Spencerca104e82006-12-12 05:38:50 +00001488 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
Reid Spencer56521c42006-12-12 00:51:07 +00001489 return getCast(opcode, C, Ty);
1490}
1491
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001492Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
Chris Lattner03c49532007-01-15 02:27:26 +00001493 assert(C->getType()->isInteger() && "Trunc operand must be integer");
1494 assert(Ty->isInteger() && "Trunc produces only integral");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001495 assert(C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1496 "SrcTy must be larger than DestTy for Trunc!");
1497
1498 return getFoldedCast(Instruction::Trunc, C, Ty);
1499}
1500
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001501Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
Chris Lattner03c49532007-01-15 02:27:26 +00001502 assert(C->getType()->isInteger() && "SEXt operand must be integral");
1503 assert(Ty->isInteger() && "SExt produces only integer");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001504 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1505 "SrcTy must be smaller than DestTy for SExt!");
1506
1507 return getFoldedCast(Instruction::SExt, C, Ty);
Chris Lattnerdd284742004-04-04 23:20:30 +00001508}
1509
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001510Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
Chris Lattner03c49532007-01-15 02:27:26 +00001511 assert(C->getType()->isInteger() && "ZEXt operand must be integral");
1512 assert(Ty->isInteger() && "ZExt produces only integer");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001513 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1514 "SrcTy must be smaller than DestTy for ZExt!");
1515
1516 return getFoldedCast(Instruction::ZExt, C, Ty);
1517}
1518
1519Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1520 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1521 C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1522 "This is an illegal floating point truncation!");
1523 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1524}
1525
1526Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1527 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1528 C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1529 "This is an illegal floating point extension!");
1530 return getFoldedCast(Instruction::FPExt, C, Ty);
1531}
1532
1533Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
Chris Lattner03c49532007-01-15 02:27:26 +00001534 assert(C->getType()->isInteger() && Ty->isFloatingPoint() &&
Reid Spencer2546b762007-01-26 07:37:34 +00001535 "This is an illegal i32 to floating point cast!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001536 return getFoldedCast(Instruction::UIToFP, C, Ty);
1537}
1538
1539Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
Chris Lattner03c49532007-01-15 02:27:26 +00001540 assert(C->getType()->isInteger() && Ty->isFloatingPoint() &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001541 "This is an illegal sint to floating point cast!");
1542 return getFoldedCast(Instruction::SIToFP, C, Ty);
1543}
1544
1545Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
Chris Lattner03c49532007-01-15 02:27:26 +00001546 assert(C->getType()->isFloatingPoint() && Ty->isInteger() &&
Reid Spencer2546b762007-01-26 07:37:34 +00001547 "This is an illegal floating point to i32 cast!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001548 return getFoldedCast(Instruction::FPToUI, C, Ty);
1549}
1550
1551Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
Chris Lattner03c49532007-01-15 02:27:26 +00001552 assert(C->getType()->isFloatingPoint() && Ty->isInteger() &&
Reid Spencer2546b762007-01-26 07:37:34 +00001553 "This is an illegal floating point to i32 cast!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001554 return getFoldedCast(Instruction::FPToSI, C, Ty);
1555}
1556
1557Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1558 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
Chris Lattner03c49532007-01-15 02:27:26 +00001559 assert(DstTy->isInteger() && "PtrToInt destination must be integral");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001560 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1561}
1562
1563Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
Chris Lattner03c49532007-01-15 02:27:26 +00001564 assert(C->getType()->isInteger() && "IntToPtr source must be integral");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001565 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
1566 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1567}
1568
1569Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1570 // BitCast implies a no-op cast of type only. No bits change. However, you
1571 // can't cast pointers to anything but pointers.
1572 const Type *SrcTy = C->getType();
1573 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
Reid Spencer5c140882006-12-04 20:17:56 +00001574 "BitCast cannot cast pointer to non-pointer and vice versa");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001575
1576 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
1577 // or nonptr->ptr). For all the other types, the cast is okay if source and
1578 // destination bit widths are identical.
1579 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1580 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
Reid Spencer5c140882006-12-04 20:17:56 +00001581 assert(SrcBitSize == DstBitSize && "BitCast requies types of same width");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001582 return getFoldedCast(Instruction::BitCast, C, DstTy);
Chris Lattnerdd284742004-04-04 23:20:30 +00001583}
1584
Alkis Evlogimenosda5de052004-10-24 01:41:10 +00001585Constant *ConstantExpr::getSizeOf(const Type *Ty) {
Chris Lattneracc4e542004-12-13 19:48:51 +00001586 // sizeof is implemented as: (ulong) gep (Ty*)null, 1
Chris Lattnerb5d70302007-02-19 20:01:23 +00001587 Constant *GEPIdx = ConstantInt::get(Type::Int32Ty, 1);
1588 Constant *GEP =
1589 getGetElementPtr(getNullValue(PointerType::get(Ty)), &GEPIdx, 1);
1590 return getCast(Instruction::PtrToInt, GEP, Type::Int64Ty);
Alkis Evlogimenos9160d5f2005-03-19 11:40:31 +00001591}
1592
Chris Lattnerb50d1352003-10-05 00:17:43 +00001593Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
Reid Spencera009d0d2006-12-04 21:35:24 +00001594 Constant *C1, Constant *C2) {
Chris Lattner38a9bcd2003-05-21 17:49:25 +00001595 // Check the operands for consistency first
Reid Spencer7eb55b32006-11-02 01:53:59 +00001596 assert(Opcode >= Instruction::BinaryOpsBegin &&
1597 Opcode < Instruction::BinaryOpsEnd &&
Chris Lattner38a9bcd2003-05-21 17:49:25 +00001598 "Invalid opcode in binary constant expression");
1599 assert(C1->getType() == C2->getType() &&
1600 "Operand types in binary constant expression should match");
Chris Lattnerb50d1352003-10-05 00:17:43 +00001601
Reid Spencer542964f2007-01-11 18:21:29 +00001602 if (ReqTy == C1->getType() || ReqTy == Type::Int1Ty)
Chris Lattnerb50d1352003-10-05 00:17:43 +00001603 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1604 return FC; // Fold a few common cases...
Chris Lattneracdbe712003-04-17 19:24:48 +00001605
Chris Lattner2b383d2e2003-05-13 21:37:02 +00001606 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
Reid Spencera009d0d2006-12-04 21:35:24 +00001607 ExprMapKeyType Key(Opcode, argVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001608 return ExprConstants->getOrCreate(ReqTy, Key);
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001609}
1610
Reid Spencer266e42b2006-12-23 06:05:41 +00001611Constant *ConstantExpr::getCompareTy(unsigned short predicate,
Reid Spencera009d0d2006-12-04 21:35:24 +00001612 Constant *C1, Constant *C2) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001613 switch (predicate) {
1614 default: assert(0 && "Invalid CmpInst predicate");
1615 case FCmpInst::FCMP_FALSE: case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_OGT:
1616 case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OLE:
1617 case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_ORD: case FCmpInst::FCMP_UNO:
1618 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UGT: case FCmpInst::FCMP_UGE:
1619 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_ULE: case FCmpInst::FCMP_UNE:
1620 case FCmpInst::FCMP_TRUE:
1621 return getFCmp(predicate, C1, C2);
1622 case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGT:
1623 case ICmpInst::ICMP_UGE: case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE:
1624 case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_SGE: case ICmpInst::ICMP_SLT:
1625 case ICmpInst::ICMP_SLE:
1626 return getICmp(predicate, C1, C2);
1627 }
Reid Spencera009d0d2006-12-04 21:35:24 +00001628}
1629
1630Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001631#ifndef NDEBUG
1632 switch (Opcode) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00001633 case Instruction::Add:
1634 case Instruction::Sub:
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001635 case Instruction::Mul:
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001636 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Chris Lattner03c49532007-01-15 02:27:26 +00001637 assert((C1->getType()->isInteger() || C1->getType()->isFloatingPoint() ||
Reid Spencerd84d35b2007-02-15 02:26:10 +00001638 isa<VectorType>(C1->getType())) &&
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001639 "Tried to create an arithmetic operation on a non-arithmetic type!");
1640 break;
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001641 case Instruction::UDiv:
1642 case Instruction::SDiv:
1643 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001644 assert((C1->getType()->isInteger() || (isa<VectorType>(C1->getType()) &&
1645 cast<VectorType>(C1->getType())->getElementType()->isInteger())) &&
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001646 "Tried to create an arithmetic operation on a non-arithmetic type!");
1647 break;
1648 case Instruction::FDiv:
1649 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001650 assert((C1->getType()->isFloatingPoint() || (isa<VectorType>(C1->getType())
1651 && cast<VectorType>(C1->getType())->getElementType()->isFloatingPoint()))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001652 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1653 break;
Reid Spencer7eb55b32006-11-02 01:53:59 +00001654 case Instruction::URem:
1655 case Instruction::SRem:
1656 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001657 assert((C1->getType()->isInteger() || (isa<VectorType>(C1->getType()) &&
1658 cast<VectorType>(C1->getType())->getElementType()->isInteger())) &&
Reid Spencer7eb55b32006-11-02 01:53:59 +00001659 "Tried to create an arithmetic operation on a non-arithmetic type!");
1660 break;
1661 case Instruction::FRem:
1662 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001663 assert((C1->getType()->isFloatingPoint() || (isa<VectorType>(C1->getType())
1664 && cast<VectorType>(C1->getType())->getElementType()->isFloatingPoint()))
Reid Spencer7eb55b32006-11-02 01:53:59 +00001665 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1666 break;
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001667 case Instruction::And:
1668 case Instruction::Or:
1669 case Instruction::Xor:
1670 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001671 assert((C1->getType()->isInteger() || isa<VectorType>(C1->getType())) &&
Misha Brukman3852f652005-01-27 06:46:38 +00001672 "Tried to create a logical operation on a non-integral type!");
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001673 break;
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001674 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00001675 case Instruction::LShr:
1676 case Instruction::AShr:
Reid Spencer2341c222007-02-02 02:16:23 +00001677 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Chris Lattner03c49532007-01-15 02:27:26 +00001678 assert(C1->getType()->isInteger() &&
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001679 "Tried to create a shift operation on a non-integer type!");
1680 break;
1681 default:
1682 break;
1683 }
1684#endif
1685
Reid Spencera009d0d2006-12-04 21:35:24 +00001686 return getTy(C1->getType(), Opcode, C1, C2);
1687}
1688
Reid Spencer266e42b2006-12-23 06:05:41 +00001689Constant *ConstantExpr::getCompare(unsigned short pred,
Reid Spencera009d0d2006-12-04 21:35:24 +00001690 Constant *C1, Constant *C2) {
1691 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencer266e42b2006-12-23 06:05:41 +00001692 return getCompareTy(pred, C1, C2);
Chris Lattner29ca2c62004-08-04 18:50:09 +00001693}
1694
Chris Lattner6e415c02004-03-12 05:54:04 +00001695Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1696 Constant *V1, Constant *V2) {
Reid Spencer2546b762007-01-26 07:37:34 +00001697 assert(C->getType() == Type::Int1Ty && "Select condition must be i1!");
Chris Lattner6e415c02004-03-12 05:54:04 +00001698 assert(V1->getType() == V2->getType() && "Select value types must match!");
1699 assert(V1->getType()->isFirstClassType() && "Cannot select aggregate type!");
1700
1701 if (ReqTy == V1->getType())
1702 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1703 return SC; // Fold common cases
1704
1705 std::vector<Constant*> argVec(3, C);
1706 argVec[1] = V1;
1707 argVec[2] = V2;
Reid Spenceree3c9912006-12-04 05:19:50 +00001708 ExprMapKeyType Key(Instruction::Select, argVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001709 return ExprConstants->getOrCreate(ReqTy, Key);
Chris Lattner6e415c02004-03-12 05:54:04 +00001710}
1711
Chris Lattnerb50d1352003-10-05 00:17:43 +00001712Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
Chris Lattner302116a2007-01-31 04:40:28 +00001713 Value* const *Idxs,
1714 unsigned NumIdx) {
1715 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs, NumIdx, true) &&
Chris Lattner04b60fe2004-02-16 20:46:13 +00001716 "GEP indices invalid!");
1717
Chris Lattner302116a2007-01-31 04:40:28 +00001718 if (Constant *FC = ConstantFoldGetElementPtr(C, (Constant**)Idxs, NumIdx))
Chris Lattneracdbe712003-04-17 19:24:48 +00001719 return FC; // Fold a few common cases...
Chris Lattner04b60fe2004-02-16 20:46:13 +00001720
Chris Lattnerb50d1352003-10-05 00:17:43 +00001721 assert(isa<PointerType>(C->getType()) &&
Chris Lattner98fa07b2003-05-23 20:03:32 +00001722 "Non-pointer type for constant GetElementPtr expression");
Vikram S. Adve4c485332002-07-15 18:19:33 +00001723 // Look up the constant in the table first to ensure uniqueness
Chris Lattner13128ab2004-10-11 22:52:25 +00001724 std::vector<Constant*> ArgVec;
Chris Lattner302116a2007-01-31 04:40:28 +00001725 ArgVec.reserve(NumIdx+1);
Chris Lattner13128ab2004-10-11 22:52:25 +00001726 ArgVec.push_back(C);
Chris Lattner302116a2007-01-31 04:40:28 +00001727 for (unsigned i = 0; i != NumIdx; ++i)
1728 ArgVec.push_back(cast<Constant>(Idxs[i]));
1729 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001730 return ExprConstants->getOrCreate(ReqTy, Key);
Vikram S. Adve4c485332002-07-15 18:19:33 +00001731}
1732
Chris Lattner302116a2007-01-31 04:40:28 +00001733Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
1734 unsigned NumIdx) {
Chris Lattnerb50d1352003-10-05 00:17:43 +00001735 // Get the result type of the getelementptr!
Chris Lattner302116a2007-01-31 04:40:28 +00001736 const Type *Ty =
1737 GetElementPtrInst::getIndexedType(C->getType(), Idxs, NumIdx, true);
Chris Lattnerb50d1352003-10-05 00:17:43 +00001738 assert(Ty && "GEP indices invalid!");
Chris Lattner302116a2007-01-31 04:40:28 +00001739 return getGetElementPtrTy(PointerType::get(Ty), C, Idxs, NumIdx);
Chris Lattner13128ab2004-10-11 22:52:25 +00001740}
1741
Chris Lattner302116a2007-01-31 04:40:28 +00001742Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
1743 unsigned NumIdx) {
1744 return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
Chris Lattnerb50d1352003-10-05 00:17:43 +00001745}
1746
Chris Lattner302116a2007-01-31 04:40:28 +00001747
Reid Spenceree3c9912006-12-04 05:19:50 +00001748Constant *
1749ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1750 assert(LHS->getType() == RHS->getType());
1751 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
1752 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1753
Reid Spencer266e42b2006-12-23 06:05:41 +00001754 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
Reid Spenceree3c9912006-12-04 05:19:50 +00001755 return FC; // Fold a few common cases...
1756
1757 // Look up the constant in the table first to ensure uniqueness
1758 std::vector<Constant*> ArgVec;
1759 ArgVec.push_back(LHS);
1760 ArgVec.push_back(RHS);
Reid Spencerb1537492006-12-24 18:42:29 +00001761 // Get the key type with both the opcode and predicate
Reid Spenceree3c9912006-12-04 05:19:50 +00001762 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
Reid Spencer542964f2007-01-11 18:21:29 +00001763 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
Reid Spenceree3c9912006-12-04 05:19:50 +00001764}
1765
1766Constant *
1767ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1768 assert(LHS->getType() == RHS->getType());
1769 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1770
Reid Spencer266e42b2006-12-23 06:05:41 +00001771 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
Reid Spenceree3c9912006-12-04 05:19:50 +00001772 return FC; // Fold a few common cases...
1773
1774 // Look up the constant in the table first to ensure uniqueness
1775 std::vector<Constant*> ArgVec;
1776 ArgVec.push_back(LHS);
1777 ArgVec.push_back(RHS);
Reid Spencerb1537492006-12-24 18:42:29 +00001778 // Get the key type with both the opcode and predicate
Reid Spenceree3c9912006-12-04 05:19:50 +00001779 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
Reid Spencer542964f2007-01-11 18:21:29 +00001780 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
Reid Spenceree3c9912006-12-04 05:19:50 +00001781}
1782
Robert Bocchino23004482006-01-10 19:05:34 +00001783Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
1784 Constant *Idx) {
Robert Bocchinode7f1c92006-01-10 20:03:46 +00001785 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
1786 return FC; // Fold a few common cases...
Robert Bocchino23004482006-01-10 19:05:34 +00001787 // Look up the constant in the table first to ensure uniqueness
1788 std::vector<Constant*> ArgVec(1, Val);
1789 ArgVec.push_back(Idx);
Reid Spenceree3c9912006-12-04 05:19:50 +00001790 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001791 return ExprConstants->getOrCreate(ReqTy, Key);
Robert Bocchino23004482006-01-10 19:05:34 +00001792}
1793
1794Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001795 assert(isa<VectorType>(Val->getType()) &&
Reid Spencer09575ba2007-02-15 03:39:18 +00001796 "Tried to create extractelement operation on non-vector type!");
Reid Spencer8d9336d2006-12-31 05:26:44 +00001797 assert(Idx->getType() == Type::Int32Ty &&
Reid Spencer2546b762007-01-26 07:37:34 +00001798 "Extractelement index must be i32 type!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001799 return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
Robert Bocchino23004482006-01-10 19:05:34 +00001800 Val, Idx);
1801}
Chris Lattnerb50d1352003-10-05 00:17:43 +00001802
Robert Bocchinoca27f032006-01-17 20:07:22 +00001803Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
1804 Constant *Elt, Constant *Idx) {
1805 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
1806 return FC; // Fold a few common cases...
1807 // Look up the constant in the table first to ensure uniqueness
1808 std::vector<Constant*> ArgVec(1, Val);
1809 ArgVec.push_back(Elt);
1810 ArgVec.push_back(Idx);
Reid Spenceree3c9912006-12-04 05:19:50 +00001811 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001812 return ExprConstants->getOrCreate(ReqTy, Key);
Robert Bocchinoca27f032006-01-17 20:07:22 +00001813}
1814
1815Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1816 Constant *Idx) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001817 assert(isa<VectorType>(Val->getType()) &&
Reid Spencer09575ba2007-02-15 03:39:18 +00001818 "Tried to create insertelement operation on non-vector type!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001819 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
Robert Bocchinoca27f032006-01-17 20:07:22 +00001820 && "Insertelement types must match!");
Reid Spencer8d9336d2006-12-31 05:26:44 +00001821 assert(Idx->getType() == Type::Int32Ty &&
Reid Spencer2546b762007-01-26 07:37:34 +00001822 "Insertelement index must be i32 type!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001823 return getInsertElementTy(cast<VectorType>(Val->getType())->getElementType(),
Robert Bocchinoca27f032006-01-17 20:07:22 +00001824 Val, Elt, Idx);
1825}
1826
Chris Lattnerbbe0a422006-04-08 01:18:18 +00001827Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
1828 Constant *V2, Constant *Mask) {
1829 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
1830 return FC; // Fold a few common cases...
1831 // Look up the constant in the table first to ensure uniqueness
1832 std::vector<Constant*> ArgVec(1, V1);
1833 ArgVec.push_back(V2);
1834 ArgVec.push_back(Mask);
Reid Spenceree3c9912006-12-04 05:19:50 +00001835 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001836 return ExprConstants->getOrCreate(ReqTy, Key);
Chris Lattnerbbe0a422006-04-08 01:18:18 +00001837}
1838
1839Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
1840 Constant *Mask) {
1841 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1842 "Invalid shuffle vector constant expr operands!");
1843 return getShuffleVectorTy(V1->getType(), V1, V2, Mask);
1844}
1845
Reid Spencer2eadb532007-01-21 00:29:26 +00001846Constant *ConstantExpr::getZeroValueForNegationExpr(const Type *Ty) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001847 if (const VectorType *PTy = dyn_cast<VectorType>(Ty))
Reid Spencer6598ca82007-01-21 02:29:10 +00001848 if (PTy->getElementType()->isFloatingPoint()) {
1849 std::vector<Constant*> zeros(PTy->getNumElements(),
1850 ConstantFP::get(PTy->getElementType(),-0.0));
Reid Spencerd84d35b2007-02-15 02:26:10 +00001851 return ConstantVector::get(PTy, zeros);
Reid Spencer6598ca82007-01-21 02:29:10 +00001852 }
Reid Spencer2eadb532007-01-21 00:29:26 +00001853
1854 if (Ty->isFloatingPoint())
1855 return ConstantFP::get(Ty, -0.0);
1856
1857 return Constant::getNullValue(Ty);
1858}
1859
Vikram S. Adve4c485332002-07-15 18:19:33 +00001860// destroyConstant - Remove the constant from the constant table...
1861//
1862void ConstantExpr::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001863 ExprConstants->remove(this);
Vikram S. Adve4c485332002-07-15 18:19:33 +00001864 destroyConstantImpl();
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001865}
1866
Chris Lattner3cd8c562002-07-30 18:54:25 +00001867const char *ConstantExpr::getOpcodeName() const {
1868 return Instruction::getOpcodeName(getOpcode());
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001869}
Reid Spencer1ebe1ab2004-07-17 23:48:33 +00001870
Chris Lattnerc4062ba2005-10-03 21:58:36 +00001871//===----------------------------------------------------------------------===//
1872// replaceUsesOfWithOnConstant implementations
1873
1874void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattner7a1450d2005-10-04 18:13:04 +00001875 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00001876 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
Chris Lattner8760ec72005-10-04 01:17:50 +00001877 Constant *ToC = cast<Constant>(To);
Chris Lattnerdff59112005-10-04 18:47:09 +00001878
1879 unsigned OperandToUpdate = U-OperandList;
1880 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
1881
Jim Laskeyc03caef2006-07-17 17:38:29 +00001882 std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
Chris Lattnerb64419a2005-10-03 22:51:37 +00001883 Lookup.first.first = getType();
1884 Lookup.second = this;
Chris Lattnerdff59112005-10-04 18:47:09 +00001885
Chris Lattnerb64419a2005-10-03 22:51:37 +00001886 std::vector<Constant*> &Values = Lookup.first.second;
1887 Values.reserve(getNumOperands()); // Build replacement array.
Chris Lattnerdff59112005-10-04 18:47:09 +00001888
Chris Lattner8760ec72005-10-04 01:17:50 +00001889 // Fill values with the modified operands of the constant array. Also,
1890 // compute whether this turns into an all-zeros array.
Chris Lattnerdff59112005-10-04 18:47:09 +00001891 bool isAllZeros = false;
1892 if (!ToC->isNullValue()) {
1893 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
1894 Values.push_back(cast<Constant>(O->get()));
1895 } else {
1896 isAllZeros = true;
1897 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1898 Constant *Val = cast<Constant>(O->get());
1899 Values.push_back(Val);
1900 if (isAllZeros) isAllZeros = Val->isNullValue();
1901 }
Chris Lattnerc4062ba2005-10-03 21:58:36 +00001902 }
Chris Lattnerdff59112005-10-04 18:47:09 +00001903 Values[OperandToUpdate] = ToC;
Chris Lattnerc4062ba2005-10-03 21:58:36 +00001904
Chris Lattnerb64419a2005-10-03 22:51:37 +00001905 Constant *Replacement = 0;
1906 if (isAllZeros) {
1907 Replacement = ConstantAggregateZero::get(getType());
1908 } else {
1909 // Check to see if we have this array type already.
1910 bool Exists;
Jim Laskeyc03caef2006-07-17 17:38:29 +00001911 ArrayConstantsTy::MapTy::iterator I =
Chris Lattner69edc982006-09-28 00:35:06 +00001912 ArrayConstants->InsertOrGetItem(Lookup, Exists);
Chris Lattnerb64419a2005-10-03 22:51:37 +00001913
1914 if (Exists) {
1915 Replacement = I->second;
1916 } else {
1917 // Okay, the new shape doesn't exist in the system yet. Instead of
1918 // creating a new constant array, inserting it, replaceallusesof'ing the
1919 // old with the new, then deleting the old... just update the current one
1920 // in place!
Chris Lattner69edc982006-09-28 00:35:06 +00001921 ArrayConstants->MoveConstantToNewSlot(this, I);
Chris Lattnerb64419a2005-10-03 22:51:37 +00001922
Chris Lattnerdff59112005-10-04 18:47:09 +00001923 // Update to the new value.
1924 setOperand(OperandToUpdate, ToC);
Chris Lattnerb64419a2005-10-03 22:51:37 +00001925 return;
1926 }
1927 }
1928
1929 // Otherwise, I do need to replace this with an existing value.
Chris Lattnerc4062ba2005-10-03 21:58:36 +00001930 assert(Replacement != this && "I didn't contain From!");
1931
Chris Lattner7a1450d2005-10-04 18:13:04 +00001932 // Everyone using this now uses the replacement.
1933 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00001934
1935 // Delete the old constant!
1936 destroyConstant();
1937}
1938
1939void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattner7a1450d2005-10-04 18:13:04 +00001940 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00001941 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
Chris Lattner8760ec72005-10-04 01:17:50 +00001942 Constant *ToC = cast<Constant>(To);
1943
Chris Lattnerdff59112005-10-04 18:47:09 +00001944 unsigned OperandToUpdate = U-OperandList;
1945 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
1946
Jim Laskeyc03caef2006-07-17 17:38:29 +00001947 std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
Chris Lattner8760ec72005-10-04 01:17:50 +00001948 Lookup.first.first = getType();
1949 Lookup.second = this;
1950 std::vector<Constant*> &Values = Lookup.first.second;
1951 Values.reserve(getNumOperands()); // Build replacement struct.
Chris Lattnerc4062ba2005-10-03 21:58:36 +00001952
Chris Lattnerdff59112005-10-04 18:47:09 +00001953
Chris Lattner8760ec72005-10-04 01:17:50 +00001954 // Fill values with the modified operands of the constant struct. Also,
1955 // compute whether this turns into an all-zeros struct.
Chris Lattnerdff59112005-10-04 18:47:09 +00001956 bool isAllZeros = false;
1957 if (!ToC->isNullValue()) {
1958 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
1959 Values.push_back(cast<Constant>(O->get()));
1960 } else {
1961 isAllZeros = true;
1962 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1963 Constant *Val = cast<Constant>(O->get());
1964 Values.push_back(Val);
1965 if (isAllZeros) isAllZeros = Val->isNullValue();
1966 }
Chris Lattner8760ec72005-10-04 01:17:50 +00001967 }
Chris Lattnerdff59112005-10-04 18:47:09 +00001968 Values[OperandToUpdate] = ToC;
1969
Chris Lattner8760ec72005-10-04 01:17:50 +00001970 Constant *Replacement = 0;
1971 if (isAllZeros) {
1972 Replacement = ConstantAggregateZero::get(getType());
1973 } else {
1974 // Check to see if we have this array type already.
1975 bool Exists;
Jim Laskeyc03caef2006-07-17 17:38:29 +00001976 StructConstantsTy::MapTy::iterator I =
Chris Lattner69edc982006-09-28 00:35:06 +00001977 StructConstants->InsertOrGetItem(Lookup, Exists);
Chris Lattner8760ec72005-10-04 01:17:50 +00001978
1979 if (Exists) {
1980 Replacement = I->second;
1981 } else {
1982 // Okay, the new shape doesn't exist in the system yet. Instead of
1983 // creating a new constant struct, inserting it, replaceallusesof'ing the
1984 // old with the new, then deleting the old... just update the current one
1985 // in place!
Chris Lattner69edc982006-09-28 00:35:06 +00001986 StructConstants->MoveConstantToNewSlot(this, I);
Chris Lattner8760ec72005-10-04 01:17:50 +00001987
Chris Lattnerdff59112005-10-04 18:47:09 +00001988 // Update to the new value.
1989 setOperand(OperandToUpdate, ToC);
Chris Lattner8760ec72005-10-04 01:17:50 +00001990 return;
1991 }
Chris Lattnerc4062ba2005-10-03 21:58:36 +00001992 }
1993
Chris Lattnerc4062ba2005-10-03 21:58:36 +00001994 assert(Replacement != this && "I didn't contain From!");
1995
Chris Lattner7a1450d2005-10-04 18:13:04 +00001996 // Everyone using this now uses the replacement.
1997 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00001998
1999 // Delete the old constant!
2000 destroyConstant();
2001}
2002
Reid Spencerd84d35b2007-02-15 02:26:10 +00002003void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002004 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002005 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2006
2007 std::vector<Constant*> Values;
2008 Values.reserve(getNumOperands()); // Build replacement array...
2009 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2010 Constant *Val = getOperand(i);
2011 if (Val == From) Val = cast<Constant>(To);
2012 Values.push_back(Val);
2013 }
2014
Reid Spencerd84d35b2007-02-15 02:26:10 +00002015 Constant *Replacement = ConstantVector::get(getType(), Values);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002016 assert(Replacement != this && "I didn't contain From!");
2017
Chris Lattner7a1450d2005-10-04 18:13:04 +00002018 // Everyone using this now uses the replacement.
2019 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002020
2021 // Delete the old constant!
2022 destroyConstant();
2023}
2024
2025void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002026 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002027 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2028 Constant *To = cast<Constant>(ToV);
2029
2030 Constant *Replacement = 0;
2031 if (getOpcode() == Instruction::GetElementPtr) {
Chris Lattnerb5d70302007-02-19 20:01:23 +00002032 SmallVector<Constant*, 8> Indices;
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002033 Constant *Pointer = getOperand(0);
2034 Indices.reserve(getNumOperands()-1);
2035 if (Pointer == From) Pointer = To;
2036
2037 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2038 Constant *Val = getOperand(i);
2039 if (Val == From) Val = To;
2040 Indices.push_back(Val);
2041 }
Chris Lattnerb5d70302007-02-19 20:01:23 +00002042 Replacement = ConstantExpr::getGetElementPtr(Pointer,
2043 &Indices[0], Indices.size());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002044 } else if (isCast()) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002045 assert(getOperand(0) == From && "Cast only has one use!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002046 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002047 } else if (getOpcode() == Instruction::Select) {
2048 Constant *C1 = getOperand(0);
2049 Constant *C2 = getOperand(1);
2050 Constant *C3 = getOperand(2);
2051 if (C1 == From) C1 = To;
2052 if (C2 == From) C2 = To;
2053 if (C3 == From) C3 = To;
2054 Replacement = ConstantExpr::getSelect(C1, C2, C3);
Robert Bocchino23004482006-01-10 19:05:34 +00002055 } else if (getOpcode() == Instruction::ExtractElement) {
2056 Constant *C1 = getOperand(0);
2057 Constant *C2 = getOperand(1);
2058 if (C1 == From) C1 = To;
2059 if (C2 == From) C2 = To;
2060 Replacement = ConstantExpr::getExtractElement(C1, C2);
Chris Lattnera93b4b52006-04-08 05:09:48 +00002061 } else if (getOpcode() == Instruction::InsertElement) {
2062 Constant *C1 = getOperand(0);
2063 Constant *C2 = getOperand(1);
2064 Constant *C3 = getOperand(1);
2065 if (C1 == From) C1 = To;
2066 if (C2 == From) C2 = To;
2067 if (C3 == From) C3 = To;
2068 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2069 } else if (getOpcode() == Instruction::ShuffleVector) {
2070 Constant *C1 = getOperand(0);
2071 Constant *C2 = getOperand(1);
2072 Constant *C3 = getOperand(2);
2073 if (C1 == From) C1 = To;
2074 if (C2 == From) C2 = To;
2075 if (C3 == From) C3 = To;
2076 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
Reid Spenceree3c9912006-12-04 05:19:50 +00002077 } else if (isCompare()) {
2078 Constant *C1 = getOperand(0);
2079 Constant *C2 = getOperand(1);
2080 if (C1 == From) C1 = To;
2081 if (C2 == From) C2 = To;
2082 if (getOpcode() == Instruction::ICmp)
2083 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2084 else
2085 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002086 } else if (getNumOperands() == 2) {
2087 Constant *C1 = getOperand(0);
2088 Constant *C2 = getOperand(1);
2089 if (C1 == From) C1 = To;
2090 if (C2 == From) C2 = To;
2091 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2092 } else {
2093 assert(0 && "Unknown ConstantExpr type!");
2094 return;
2095 }
2096
2097 assert(Replacement != this && "I didn't contain From!");
2098
Chris Lattner7a1450d2005-10-04 18:13:04 +00002099 // Everyone using this now uses the replacement.
2100 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002101
2102 // Delete the old constant!
2103 destroyConstant();
2104}
2105
2106
Jim Laskey2698f0d2006-03-08 18:11:07 +00002107/// getStringValue - Turn an LLVM constant pointer that eventually points to a
2108/// global into a string value. Return an empty string if we can't do it.
Evan Cheng38280c02006-03-10 23:52:03 +00002109/// Parameter Chop determines if the result is chopped at the first null
2110/// terminator.
Jim Laskey2698f0d2006-03-08 18:11:07 +00002111///
Evan Cheng38280c02006-03-10 23:52:03 +00002112std::string Constant::getStringValue(bool Chop, unsigned Offset) {
Jim Laskey2698f0d2006-03-08 18:11:07 +00002113 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(this)) {
2114 if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
2115 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
2116 if (Init->isString()) {
2117 std::string Result = Init->getAsString();
2118 if (Offset < Result.size()) {
2119 // If we are pointing INTO The string, erase the beginning...
2120 Result.erase(Result.begin(), Result.begin()+Offset);
2121
2122 // Take off the null terminator, and any string fragments after it.
Evan Cheng38280c02006-03-10 23:52:03 +00002123 if (Chop) {
2124 std::string::size_type NullPos = Result.find_first_of((char)0);
2125 if (NullPos != std::string::npos)
2126 Result.erase(Result.begin()+NullPos, Result.end());
2127 }
Jim Laskey2698f0d2006-03-08 18:11:07 +00002128 return Result;
2129 }
2130 }
2131 }
2132 } else if (Constant *C = dyn_cast<Constant>(this)) {
2133 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
Evan Cheng2c5e5302006-03-11 00:13:10 +00002134 return GV->getStringValue(Chop, Offset);
Jim Laskey2698f0d2006-03-08 18:11:07 +00002135 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2136 if (CE->getOpcode() == Instruction::GetElementPtr) {
2137 // Turn a gep into the specified offset.
2138 if (CE->getNumOperands() == 3 &&
2139 cast<Constant>(CE->getOperand(1))->isNullValue() &&
2140 isa<ConstantInt>(CE->getOperand(2))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002141 Offset += cast<ConstantInt>(CE->getOperand(2))->getZExtValue();
Evan Cheng2c5e5302006-03-11 00:13:10 +00002142 return CE->getOperand(0)->getStringValue(Chop, Offset);
Jim Laskey2698f0d2006-03-08 18:11:07 +00002143 }
2144 }
2145 }
2146 }
2147 return "";
2148}