blob: 4375bf1eb1619b4a9c458fa1df5815fe2445be6a [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 Lattner2f7c9632001-06-06 20:29:01 +000019#include "llvm/SymbolTable.h"
Chris Lattnerd7a73302001-10-13 06:57:33 +000020#include "llvm/Module.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000021#include "llvm/ADT/StringExtras.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000022#include "llvm/Support/Compiler.h"
Bill Wendling6a462f12006-11-17 08:03:48 +000023#include "llvm/Support/Debug.h"
Chris Lattner69edc982006-09-28 00:35:06 +000024#include "llvm/Support/ManagedStatic.h"
Bill Wendling6a462f12006-11-17 08:03:48 +000025#include "llvm/Support/MathExtras.h"
Chris Lattner2f7c9632001-06-06 20:29:01 +000026#include <algorithm>
Chris Lattner189d19f2003-11-21 20:23:48 +000027using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000028
Chris Lattner2f7c9632001-06-06 20:29:01 +000029//===----------------------------------------------------------------------===//
Chris Lattner3462ae32001-12-03 22:26:30 +000030// Constant Class
Chris Lattner2f7c9632001-06-06 20:29:01 +000031//===----------------------------------------------------------------------===//
32
Chris Lattner3462ae32001-12-03 22:26:30 +000033void Constant::destroyConstantImpl() {
34 // When a Constant is destroyed, there may be lingering
Chris Lattnerd7a73302001-10-13 06:57:33 +000035 // references to the constant by other constants in the constant pool. These
Misha Brukmanbe372b92003-08-21 22:14:26 +000036 // constants are implicitly dependent on the module that is being deleted,
Chris Lattnerd7a73302001-10-13 06:57:33 +000037 // but they don't know that. Because we only find out when the CPV is
38 // deleted, we must now notify all of our users (that should only be
Chris Lattner3462ae32001-12-03 22:26:30 +000039 // Constants) that they are, in fact, invalid now and should be deleted.
Chris Lattnerd7a73302001-10-13 06:57:33 +000040 //
41 while (!use_empty()) {
42 Value *V = use_back();
43#ifndef NDEBUG // Only in -g mode...
Chris Lattnerd9f4ac662002-07-18 00:14:50 +000044 if (!isa<Constant>(V))
Bill Wendling6a462f12006-11-17 08:03:48 +000045 DOUT << "While deleting: " << *this
46 << "\n\nUse still stuck around after Def is destroyed: "
47 << *V << "\n\n";
Chris Lattnerd7a73302001-10-13 06:57:33 +000048#endif
Vikram S. Adve4e537b22002-07-14 23:13:17 +000049 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
Reid Spencer1ebe1ab2004-07-17 23:48:33 +000050 Constant *CV = cast<Constant>(V);
51 CV->destroyConstant();
Chris Lattnerd7a73302001-10-13 06:57:33 +000052
53 // The constant should remove itself from our use list...
Vikram S. Adve4e537b22002-07-14 23:13:17 +000054 assert((use_empty() || use_back() != V) && "Constant not removed!");
Chris Lattnerd7a73302001-10-13 06:57:33 +000055 }
56
57 // Value has no outstanding references it is safe to delete it now...
58 delete this;
Chris Lattner38569342001-10-01 20:11:19 +000059}
Chris Lattner2f7c9632001-06-06 20:29:01 +000060
Chris Lattner23dd1f62006-10-20 00:27:06 +000061/// canTrap - Return true if evaluation of this constant could trap. This is
62/// true for things like constant expressions that could divide by zero.
63bool Constant::canTrap() const {
64 assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
65 // The only thing that could possibly trap are constant exprs.
66 const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
67 if (!CE) return false;
68
69 // ConstantExpr traps if any operands can trap.
70 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
71 if (getOperand(i)->canTrap())
72 return true;
73
74 // Otherwise, only specific operations can trap.
75 switch (CE->getOpcode()) {
76 default:
77 return false;
Reid Spencer7e80b0b2006-10-26 06:15:43 +000078 case Instruction::UDiv:
79 case Instruction::SDiv:
80 case Instruction::FDiv:
Reid Spencer7eb55b32006-11-02 01:53:59 +000081 case Instruction::URem:
82 case Instruction::SRem:
83 case Instruction::FRem:
Chris Lattner23dd1f62006-10-20 00:27:06 +000084 // Div and rem can trap if the RHS is not known to be non-zero.
85 if (!isa<ConstantInt>(getOperand(1)) || getOperand(1)->isNullValue())
86 return true;
87 return false;
88 }
89}
90
91
Chris Lattnerb1585a92002-08-13 17:50:20 +000092// Static constructor to create a '0' constant of arbitrary type...
93Constant *Constant::getNullValue(const Type *Ty) {
Chris Lattner6b727592004-06-17 18:19:28 +000094 switch (Ty->getTypeID()) {
Chris Lattner3e88ef92003-10-03 19:34:51 +000095 case Type::BoolTyID: {
96 static Constant *NullBool = ConstantBool::get(false);
97 return NullBool;
98 }
99 case Type::SByteTyID: {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000100 static Constant *NullSByte = ConstantInt::get(Type::SByteTy, 0);
Chris Lattner3e88ef92003-10-03 19:34:51 +0000101 return NullSByte;
102 }
103 case Type::UByteTyID: {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000104 static Constant *NullUByte = ConstantInt::get(Type::UByteTy, 0);
Chris Lattner3e88ef92003-10-03 19:34:51 +0000105 return NullUByte;
106 }
107 case Type::ShortTyID: {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000108 static Constant *NullShort = ConstantInt::get(Type::ShortTy, 0);
Chris Lattner3e88ef92003-10-03 19:34:51 +0000109 return NullShort;
110 }
111 case Type::UShortTyID: {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000112 static Constant *NullUShort = ConstantInt::get(Type::UShortTy, 0);
Chris Lattner3e88ef92003-10-03 19:34:51 +0000113 return NullUShort;
114 }
115 case Type::IntTyID: {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000116 static Constant *NullInt = ConstantInt::get(Type::IntTy, 0);
Chris Lattner3e88ef92003-10-03 19:34:51 +0000117 return NullInt;
118 }
119 case Type::UIntTyID: {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000120 static Constant *NullUInt = ConstantInt::get(Type::UIntTy, 0);
Chris Lattner3e88ef92003-10-03 19:34:51 +0000121 return NullUInt;
122 }
123 case Type::LongTyID: {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000124 static Constant *NullLong = ConstantInt::get(Type::LongTy, 0);
Chris Lattner3e88ef92003-10-03 19:34:51 +0000125 return NullLong;
126 }
127 case Type::ULongTyID: {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000128 static Constant *NullULong = ConstantInt::get(Type::ULongTy, 0);
Chris Lattner3e88ef92003-10-03 19:34:51 +0000129 return NullULong;
130 }
Chris Lattnerb1585a92002-08-13 17:50:20 +0000131
Chris Lattner3e88ef92003-10-03 19:34:51 +0000132 case Type::FloatTyID: {
133 static Constant *NullFloat = ConstantFP::get(Type::FloatTy, 0);
134 return NullFloat;
135 }
136 case Type::DoubleTyID: {
137 static Constant *NullDouble = ConstantFP::get(Type::DoubleTy, 0);
138 return NullDouble;
139 }
Chris Lattnerb1585a92002-08-13 17:50:20 +0000140
Misha Brukmanb1c93172005-04-21 23:48:37 +0000141 case Type::PointerTyID:
Chris Lattnerb1585a92002-08-13 17:50:20 +0000142 return ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattner3e88ef92003-10-03 19:34:51 +0000143
Chris Lattner9fba3da2004-02-15 05:53:04 +0000144 case Type::StructTyID:
145 case Type::ArrayTyID:
Brian Gaeke02209042004-08-20 06:00:58 +0000146 case Type::PackedTyID:
Chris Lattner9fba3da2004-02-15 05:53:04 +0000147 return ConstantAggregateZero::get(Ty);
Chris Lattnerb1585a92002-08-13 17:50:20 +0000148 default:
Reid Spencercf394bf2004-07-04 11:51:24 +0000149 // Function, Label, or Opaque type?
150 assert(!"Cannot create a null constant of that type!");
Chris Lattnerb1585a92002-08-13 17:50:20 +0000151 return 0;
152 }
153}
154
Chris Lattnerb1585a92002-08-13 17:50:20 +0000155
156// Static constructor to create an integral constant with all bits set
157ConstantIntegral *ConstantIntegral::getAllOnesValue(const Type *Ty) {
Chris Lattner6b727592004-06-17 18:19:28 +0000158 switch (Ty->getTypeID()) {
Chris Lattnera84df0a22006-09-28 23:36:21 +0000159 case Type::BoolTyID: return ConstantBool::getTrue();
Chris Lattnerb1585a92002-08-13 17:50:20 +0000160 case Type::SByteTyID:
161 case Type::ShortTyID:
162 case Type::IntTyID:
Reid Spencere0fc4df2006-10-20 07:07:24 +0000163 case Type::LongTyID: return ConstantInt::get(Ty, -1);
Chris Lattnerb1585a92002-08-13 17:50:20 +0000164
165 case Type::UByteTyID:
166 case Type::UShortTyID:
167 case Type::UIntTyID:
168 case Type::ULongTyID: {
169 // Calculate ~0 of the right type...
170 unsigned TypeBits = Ty->getPrimitiveSize()*8;
171 uint64_t Val = ~0ULL; // All ones
172 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
Reid Spencere0fc4df2006-10-20 07:07:24 +0000173 return ConstantInt::get(Ty, Val);
Chris Lattnerb1585a92002-08-13 17:50:20 +0000174 }
Chris Lattner31408f72002-08-14 17:12:13 +0000175 default: return 0;
Chris Lattnerb1585a92002-08-13 17:50:20 +0000176 }
177}
178
Chris Lattner2f7c9632001-06-06 20:29:01 +0000179//===----------------------------------------------------------------------===//
Chris Lattner3462ae32001-12-03 22:26:30 +0000180// ConstantXXX Classes
Chris Lattner2f7c9632001-06-06 20:29:01 +0000181//===----------------------------------------------------------------------===//
182
183//===----------------------------------------------------------------------===//
184// Normal Constructors
185
Chris Lattnere7e139e2005-09-27 06:09:08 +0000186ConstantIntegral::ConstantIntegral(const Type *Ty, ValueTy VT, uint64_t V)
Reid Spencere0fc4df2006-10-20 07:07:24 +0000187 : Constant(Ty, VT, 0, 0), Val(V) {
Chris Lattner2f7c9632001-06-06 20:29:01 +0000188}
Chris Lattner49d855c2001-09-07 16:46:31 +0000189
Chris Lattnere7e139e2005-09-27 06:09:08 +0000190ConstantBool::ConstantBool(bool V)
Reid Spencere0fc4df2006-10-20 07:07:24 +0000191 : ConstantIntegral(Type::BoolTy, ConstantBoolVal, uint64_t(V)) {
Chris Lattner265eb642004-06-21 12:12:12 +0000192}
193
Reid Spencere0fc4df2006-10-20 07:07:24 +0000194ConstantInt::ConstantInt(const Type *Ty, uint64_t V)
195 : ConstantIntegral(Ty, ConstantIntVal, V) {
Chris Lattner2f7c9632001-06-06 20:29:01 +0000196}
197
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000198ConstantFP::ConstantFP(const Type *Ty, double V)
Chris Lattnere7e139e2005-09-27 06:09:08 +0000199 : Constant(Ty, ConstantFPVal, 0, 0) {
Chris Lattner9655e542001-07-20 19:16:02 +0000200 assert(isValueValidForType(Ty, V) && "Value too large for type!");
Chris Lattner2f7c9632001-06-06 20:29:01 +0000201 Val = V;
202}
203
Chris Lattner3462ae32001-12-03 22:26:30 +0000204ConstantArray::ConstantArray(const ArrayType *T,
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000205 const std::vector<Constant*> &V)
Chris Lattnere7e139e2005-09-27 06:09:08 +0000206 : Constant(T, ConstantArrayVal, new Use[V.size()], V.size()) {
Alkis Evlogimenos0507ffe2004-09-15 02:32:15 +0000207 assert(V.size() == T->getNumElements() &&
208 "Invalid initializer vector for constant array");
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000209 Use *OL = OperandList;
Chris Lattner0144fad2005-10-03 21:56:24 +0000210 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
211 I != E; ++I, ++OL) {
Chris Lattner20a24452005-10-07 05:23:36 +0000212 Constant *C = *I;
213 assert((C->getType() == T->getElementType() ||
Alkis Evlogimenoscb031d92004-09-10 04:16:59 +0000214 (T->isAbstract() &&
Chris Lattner20a24452005-10-07 05:23:36 +0000215 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
Alkis Evlogimenoscb031d92004-09-10 04:16:59 +0000216 "Initializer for array element doesn't match array element type!");
Chris Lattner20a24452005-10-07 05:23:36 +0000217 OL->init(C, this);
Chris Lattner2f7c9632001-06-06 20:29:01 +0000218 }
219}
220
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000221ConstantArray::~ConstantArray() {
222 delete [] OperandList;
223}
224
Chris Lattner3462ae32001-12-03 22:26:30 +0000225ConstantStruct::ConstantStruct(const StructType *T,
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000226 const std::vector<Constant*> &V)
Chris Lattnere7e139e2005-09-27 06:09:08 +0000227 : Constant(T, ConstantStructVal, new Use[V.size()], V.size()) {
Chris Lattnerac6db752004-02-09 04:37:31 +0000228 assert(V.size() == T->getNumElements() &&
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000229 "Invalid initializer vector for constant structure");
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000230 Use *OL = OperandList;
Chris Lattner0144fad2005-10-03 21:56:24 +0000231 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
232 I != E; ++I, ++OL) {
Chris Lattner20a24452005-10-07 05:23:36 +0000233 Constant *C = *I;
234 assert((C->getType() == T->getElementType(I-V.begin()) ||
Chris Lattner0144fad2005-10-03 21:56:24 +0000235 ((T->getElementType(I-V.begin())->isAbstract() ||
Chris Lattner20a24452005-10-07 05:23:36 +0000236 C->getType()->isAbstract()) &&
Chris Lattner0144fad2005-10-03 21:56:24 +0000237 T->getElementType(I-V.begin())->getTypeID() ==
Chris Lattner20a24452005-10-07 05:23:36 +0000238 C->getType()->getTypeID())) &&
Chris Lattner93c8f142003-06-02 17:42:47 +0000239 "Initializer for struct element doesn't match struct element type!");
Chris Lattner20a24452005-10-07 05:23:36 +0000240 OL->init(C, this);
Chris Lattner2f7c9632001-06-06 20:29:01 +0000241 }
242}
243
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000244ConstantStruct::~ConstantStruct() {
245 delete [] OperandList;
246}
247
248
Brian Gaeke02209042004-08-20 06:00:58 +0000249ConstantPacked::ConstantPacked(const PackedType *T,
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000250 const std::vector<Constant*> &V)
Chris Lattnere7e139e2005-09-27 06:09:08 +0000251 : Constant(T, ConstantPackedVal, new Use[V.size()], V.size()) {
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000252 Use *OL = OperandList;
Chris Lattner0144fad2005-10-03 21:56:24 +0000253 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
254 I != E; ++I, ++OL) {
Chris Lattner20a24452005-10-07 05:23:36 +0000255 Constant *C = *I;
256 assert((C->getType() == T->getElementType() ||
Alkis Evlogimenoscb031d92004-09-10 04:16:59 +0000257 (T->isAbstract() &&
Chris Lattner20a24452005-10-07 05:23:36 +0000258 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
Alkis Evlogimenoscb031d92004-09-10 04:16:59 +0000259 "Initializer for packed element doesn't match packed element type!");
Chris Lattner20a24452005-10-07 05:23:36 +0000260 OL->init(C, this);
Brian Gaeke02209042004-08-20 06:00:58 +0000261 }
262}
263
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000264ConstantPacked::~ConstantPacked() {
265 delete [] OperandList;
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000266}
267
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000268// We declare several classes private to this file, so use an anonymous
269// namespace
270namespace {
271
272/// UnaryConstantExpr - This class is private to Constants.cpp, and is used
273/// behind the scenes to implement unary constant exprs.
274class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
275 Use Op;
276public:
277 UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
278 : ConstantExpr(Ty, Opcode, &Op, 1), Op(C, this) {}
279};
280
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000281/// BinaryConstantExpr - This class is private to Constants.cpp, and is used
282/// behind the scenes to implement binary constant exprs.
Chris Lattner02157b02006-06-28 21:38:54 +0000283class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000284 Use Ops[2];
285public:
286 BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
Reid Spencer266e42b2006-12-23 06:05:41 +0000287 : ConstantExpr(C1->getType(), Opcode, Ops, 2) {
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000288 Ops[0].init(C1, this);
289 Ops[1].init(C2, this);
290 }
291};
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000292
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000293/// SelectConstantExpr - This class is private to Constants.cpp, and is used
294/// behind the scenes to implement select constant exprs.
Chris Lattner02157b02006-06-28 21:38:54 +0000295class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000296 Use Ops[3];
297public:
298 SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
299 : ConstantExpr(C2->getType(), Instruction::Select, Ops, 3) {
300 Ops[0].init(C1, this);
301 Ops[1].init(C2, this);
302 Ops[2].init(C3, this);
303 }
304};
305
Robert Bocchinoca27f032006-01-17 20:07:22 +0000306/// ExtractElementConstantExpr - This class is private to
307/// Constants.cpp, and is used behind the scenes to implement
308/// extractelement constant exprs.
Chris Lattner02157b02006-06-28 21:38:54 +0000309class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
Robert Bocchino23004482006-01-10 19:05:34 +0000310 Use Ops[2];
311public:
312 ExtractElementConstantExpr(Constant *C1, Constant *C2)
313 : ConstantExpr(cast<PackedType>(C1->getType())->getElementType(),
314 Instruction::ExtractElement, Ops, 2) {
315 Ops[0].init(C1, this);
316 Ops[1].init(C2, this);
317 }
318};
319
Robert Bocchinoca27f032006-01-17 20:07:22 +0000320/// InsertElementConstantExpr - This class is private to
321/// Constants.cpp, and is used behind the scenes to implement
322/// insertelement constant exprs.
Chris Lattner02157b02006-06-28 21:38:54 +0000323class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
Robert Bocchinoca27f032006-01-17 20:07:22 +0000324 Use Ops[3];
325public:
326 InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
327 : ConstantExpr(C1->getType(), Instruction::InsertElement,
328 Ops, 3) {
329 Ops[0].init(C1, this);
330 Ops[1].init(C2, this);
331 Ops[2].init(C3, this);
332 }
333};
334
Chris Lattnerbbe0a422006-04-08 01:18:18 +0000335/// ShuffleVectorConstantExpr - This class is private to
336/// Constants.cpp, and is used behind the scenes to implement
337/// shufflevector constant exprs.
Chris Lattner02157b02006-06-28 21:38:54 +0000338class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
Chris Lattnerbbe0a422006-04-08 01:18:18 +0000339 Use Ops[3];
340public:
341 ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
342 : ConstantExpr(C1->getType(), Instruction::ShuffleVector,
343 Ops, 3) {
344 Ops[0].init(C1, this);
345 Ops[1].init(C2, this);
346 Ops[2].init(C3, this);
347 }
348};
349
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000350/// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
351/// used behind the scenes to implement getelementpr constant exprs.
Chris Lattner02157b02006-06-28 21:38:54 +0000352struct VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000353 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
354 const Type *DestTy)
355 : ConstantExpr(DestTy, Instruction::GetElementPtr,
356 new Use[IdxList.size()+1], IdxList.size()+1) {
357 OperandList[0].init(C, this);
358 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
359 OperandList[i+1].init(IdxList[i], this);
360 }
361 ~GetElementPtrConstantExpr() {
Misha Brukmanb1c93172005-04-21 23:48:37 +0000362 delete [] OperandList;
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000363 }
364};
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000365
366// CompareConstantExpr - This class is private to Constants.cpp, and is used
367// behind the scenes to implement ICmp and FCmp constant expressions. This is
368// needed in order to store the predicate value for these instructions.
369struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
370 unsigned short predicate;
371 Use Ops[2];
372 CompareConstantExpr(Instruction::OtherOps opc, unsigned short pred,
373 Constant* LHS, Constant* RHS)
Reid Spencerfcb0dd32006-12-07 04:18:31 +0000374 : ConstantExpr(Type::BoolTy, opc, Ops, 2), predicate(pred) {
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000375 OperandList[0].init(LHS, this);
376 OperandList[1].init(RHS, this);
377 }
378};
379
380} // end anonymous namespace
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000381
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000382
383// Utility function for determining if a ConstantExpr is a CastOp or not. This
384// can't be inline because we don't want to #include Instruction.h into
385// Constant.h
386bool ConstantExpr::isCast() const {
387 return Instruction::isCast(getOpcode());
388}
389
Reid Spenceree3c9912006-12-04 05:19:50 +0000390bool ConstantExpr::isCompare() const {
391 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
392}
393
Chris Lattner817175f2004-03-29 02:37:53 +0000394/// ConstantExpr::get* - Return some common constants without having to
395/// specify the full Instruction::OPCODE identifier.
396///
397Constant *ConstantExpr::getNeg(Constant *C) {
Chris Lattner3cdc27c2004-03-29 19:51:24 +0000398 if (!C->getType()->isFloatingPoint())
399 return get(Instruction::Sub, getNullValue(C->getType()), C);
400 else
401 return get(Instruction::Sub, ConstantFP::get(C->getType(), -0.0), C);
Chris Lattner817175f2004-03-29 02:37:53 +0000402}
403Constant *ConstantExpr::getNot(Constant *C) {
404 assert(isa<ConstantIntegral>(C) && "Cannot NOT a nonintegral type!");
405 return get(Instruction::Xor, C,
406 ConstantIntegral::getAllOnesValue(C->getType()));
407}
408Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
409 return get(Instruction::Add, C1, C2);
410}
411Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
412 return get(Instruction::Sub, C1, C2);
413}
414Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
415 return get(Instruction::Mul, C1, C2);
416}
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000417Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2) {
418 return get(Instruction::UDiv, C1, C2);
419}
420Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2) {
421 return get(Instruction::SDiv, C1, C2);
422}
423Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
424 return get(Instruction::FDiv, C1, C2);
Chris Lattner817175f2004-03-29 02:37:53 +0000425}
Reid Spencer7eb55b32006-11-02 01:53:59 +0000426Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
427 return get(Instruction::URem, C1, C2);
428}
429Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
430 return get(Instruction::SRem, C1, C2);
431}
432Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
433 return get(Instruction::FRem, C1, C2);
Chris Lattner817175f2004-03-29 02:37:53 +0000434}
435Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
436 return get(Instruction::And, C1, C2);
437}
438Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
439 return get(Instruction::Or, C1, C2);
440}
441Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
442 return get(Instruction::Xor, C1, C2);
443}
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000444unsigned ConstantExpr::getPredicate() const {
445 assert(getOpcode() == Instruction::FCmp || getOpcode() == Instruction::ICmp);
446 return dynamic_cast<const CompareConstantExpr*>(this)->predicate;
447}
Chris Lattner817175f2004-03-29 02:37:53 +0000448Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
449 return get(Instruction::Shl, C1, C2);
450}
Reid Spencerfdff9382006-11-08 06:47:33 +0000451Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2) {
452 return get(Instruction::LShr, C1, C2);
Chris Lattner817175f2004-03-29 02:37:53 +0000453}
Reid Spencerfdff9382006-11-08 06:47:33 +0000454Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2) {
455 return get(Instruction::AShr, C1, C2);
Chris Lattnerdb8bdba2004-05-25 05:32:43 +0000456}
Chris Lattner60e0dd72001-10-03 06:12:09 +0000457
Chris Lattner7c1018a2006-07-14 19:37:40 +0000458/// getWithOperandReplaced - Return a constant expression identical to this
459/// one, but with the specified operand set to the specified value.
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000460Constant *
461ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
Chris Lattner7c1018a2006-07-14 19:37:40 +0000462 assert(OpNo < getNumOperands() && "Operand num is out of range!");
463 assert(Op->getType() == getOperand(OpNo)->getType() &&
464 "Replacing operand with value of different type!");
Chris Lattner227816342006-07-14 22:20:01 +0000465 if (getOperand(OpNo) == Op)
466 return const_cast<ConstantExpr*>(this);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000467
Chris Lattner227816342006-07-14 22:20:01 +0000468 Constant *Op0, *Op1, *Op2;
Chris Lattner7c1018a2006-07-14 19:37:40 +0000469 switch (getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000470 case Instruction::Trunc:
471 case Instruction::ZExt:
472 case Instruction::SExt:
473 case Instruction::FPTrunc:
474 case Instruction::FPExt:
475 case Instruction::UIToFP:
476 case Instruction::SIToFP:
477 case Instruction::FPToUI:
478 case Instruction::FPToSI:
479 case Instruction::PtrToInt:
480 case Instruction::IntToPtr:
481 case Instruction::BitCast:
482 return ConstantExpr::getCast(getOpcode(), Op, getType());
Chris Lattner227816342006-07-14 22:20:01 +0000483 case Instruction::Select:
484 Op0 = (OpNo == 0) ? Op : getOperand(0);
485 Op1 = (OpNo == 1) ? Op : getOperand(1);
486 Op2 = (OpNo == 2) ? Op : getOperand(2);
487 return ConstantExpr::getSelect(Op0, Op1, Op2);
488 case Instruction::InsertElement:
489 Op0 = (OpNo == 0) ? Op : getOperand(0);
490 Op1 = (OpNo == 1) ? Op : getOperand(1);
491 Op2 = (OpNo == 2) ? Op : getOperand(2);
492 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
493 case Instruction::ExtractElement:
494 Op0 = (OpNo == 0) ? Op : getOperand(0);
495 Op1 = (OpNo == 1) ? Op : getOperand(1);
496 return ConstantExpr::getExtractElement(Op0, Op1);
497 case Instruction::ShuffleVector:
498 Op0 = (OpNo == 0) ? Op : getOperand(0);
499 Op1 = (OpNo == 1) ? Op : getOperand(1);
500 Op2 = (OpNo == 2) ? Op : getOperand(2);
501 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000502 case Instruction::GetElementPtr: {
503 std::vector<Constant*> Ops;
504 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
505 Ops.push_back(getOperand(i));
506 if (OpNo == 0)
507 return ConstantExpr::getGetElementPtr(Op, Ops);
508 Ops[OpNo-1] = Op;
509 return ConstantExpr::getGetElementPtr(getOperand(0), Ops);
510 }
Chris Lattner7c1018a2006-07-14 19:37:40 +0000511 default:
512 assert(getNumOperands() == 2 && "Must be binary operator?");
Chris Lattner227816342006-07-14 22:20:01 +0000513 Op0 = (OpNo == 0) ? Op : getOperand(0);
514 Op1 = (OpNo == 1) ? Op : getOperand(1);
515 return ConstantExpr::get(getOpcode(), Op0, Op1);
516 }
517}
518
519/// getWithOperands - This returns the current constant expression with the
520/// operands replaced with the specified values. The specified operands must
521/// match count and type with the existing ones.
522Constant *ConstantExpr::
523getWithOperands(const std::vector<Constant*> &Ops) const {
524 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
525 bool AnyChange = false;
526 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
527 assert(Ops[i]->getType() == getOperand(i)->getType() &&
528 "Operand type mismatch!");
529 AnyChange |= Ops[i] != getOperand(i);
530 }
531 if (!AnyChange) // No operands changed, return self.
532 return const_cast<ConstantExpr*>(this);
533
534 switch (getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000535 case Instruction::Trunc:
536 case Instruction::ZExt:
537 case Instruction::SExt:
538 case Instruction::FPTrunc:
539 case Instruction::FPExt:
540 case Instruction::UIToFP:
541 case Instruction::SIToFP:
542 case Instruction::FPToUI:
543 case Instruction::FPToSI:
544 case Instruction::PtrToInt:
545 case Instruction::IntToPtr:
546 case Instruction::BitCast:
547 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
Chris Lattner227816342006-07-14 22:20:01 +0000548 case Instruction::Select:
549 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
550 case Instruction::InsertElement:
551 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
552 case Instruction::ExtractElement:
553 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
554 case Instruction::ShuffleVector:
555 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
556 case Instruction::GetElementPtr: {
557 std::vector<Constant*> ActualOps(Ops.begin()+1, Ops.end());
558 return ConstantExpr::getGetElementPtr(Ops[0], ActualOps);
559 }
Reid Spencer266e42b2006-12-23 06:05:41 +0000560 case Instruction::ICmp:
561 case Instruction::FCmp:
562 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
Chris Lattner227816342006-07-14 22:20:01 +0000563 default:
564 assert(getNumOperands() == 2 && "Must be binary operator?");
565 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000566 }
567}
568
Chris Lattner2f7c9632001-06-06 20:29:01 +0000569
570//===----------------------------------------------------------------------===//
Chris Lattner2f7c9632001-06-06 20:29:01 +0000571// isValueValidForType implementations
572
Reid Spencere7334722006-12-19 01:28:19 +0000573bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
574 switch (Ty->getTypeID()) {
575 default: return false; // These can't be represented as integers!
576 case Type::SByteTyID:
577 case Type::UByteTyID: return Val <= UINT8_MAX;
578 case Type::ShortTyID:
579 case Type::UShortTyID:return Val <= UINT16_MAX;
580 case Type::IntTyID:
581 case Type::UIntTyID: return Val <= UINT32_MAX;
582 case Type::LongTyID:
583 case Type::ULongTyID: return true; // always true, has to fit in largest type
584 }
585}
586
Reid Spencere0fc4df2006-10-20 07:07:24 +0000587bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
Chris Lattner6b727592004-06-17 18:19:28 +0000588 switch (Ty->getTypeID()) {
Reid Spencere7334722006-12-19 01:28:19 +0000589 default: return false; // These can't be represented as integers!
Chris Lattner2f7c9632001-06-06 20:29:01 +0000590 case Type::SByteTyID:
Reid Spencere7334722006-12-19 01:28:19 +0000591 case Type::UByteTyID: return (Val >= INT8_MIN && Val <= INT8_MAX);
Chris Lattner2f7c9632001-06-06 20:29:01 +0000592 case Type::ShortTyID:
Reid Spencere7334722006-12-19 01:28:19 +0000593 case Type::UShortTyID:return (Val >= INT16_MIN && Val <= UINT16_MAX);
Chris Lattner2f7c9632001-06-06 20:29:01 +0000594 case Type::IntTyID:
Reid Spencere7334722006-12-19 01:28:19 +0000595 case Type::UIntTyID: return (Val >= INT32_MIN && Val <= UINT32_MAX);
Reid Spencere0fc4df2006-10-20 07:07:24 +0000596 case Type::LongTyID:
Reid Spencere7334722006-12-19 01:28:19 +0000597 case Type::ULongTyID: return true; // always true, has to fit in largest type
Chris Lattner2f7c9632001-06-06 20:29:01 +0000598 }
Chris Lattner2f7c9632001-06-06 20:29:01 +0000599}
600
Chris Lattner3462ae32001-12-03 22:26:30 +0000601bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
Chris Lattner6b727592004-06-17 18:19:28 +0000602 switch (Ty->getTypeID()) {
Chris Lattner2f7c9632001-06-06 20:29:01 +0000603 default:
604 return false; // These can't be represented as floating point!
605
Reid Spencerb95f8ab2004-12-07 07:38:08 +0000606 // TODO: Figure out how to test if a double can be cast to a float!
Chris Lattner2f7c9632001-06-06 20:29:01 +0000607 case Type::FloatTyID:
Chris Lattner2f7c9632001-06-06 20:29:01 +0000608 case Type::DoubleTyID:
609 return true; // This is the largest type...
610 }
Chris Lattneraa2372562006-05-24 17:04:05 +0000611}
Chris Lattner9655e542001-07-20 19:16:02 +0000612
Chris Lattner49d855c2001-09-07 16:46:31 +0000613//===----------------------------------------------------------------------===//
Chris Lattner49d855c2001-09-07 16:46:31 +0000614// Factory Function Implementation
615
Chris Lattner98fa07b2003-05-23 20:03:32 +0000616// ConstantCreator - A class that is used to create constants by
617// ValueMap*. This class should be partially specialized if there is
618// something strange that needs to be done to interface to the ctor for the
619// constant.
620//
Chris Lattner189d19f2003-11-21 20:23:48 +0000621namespace llvm {
622 template<class ConstantClass, class TypeClass, class ValType>
Chris Lattner02157b02006-06-28 21:38:54 +0000623 struct VISIBILITY_HIDDEN ConstantCreator {
Chris Lattner189d19f2003-11-21 20:23:48 +0000624 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
625 return new ConstantClass(Ty, V);
626 }
627 };
Misha Brukmanb1c93172005-04-21 23:48:37 +0000628
Chris Lattner189d19f2003-11-21 20:23:48 +0000629 template<class ConstantClass, class TypeClass>
Chris Lattner02157b02006-06-28 21:38:54 +0000630 struct VISIBILITY_HIDDEN ConvertConstantType {
Chris Lattner189d19f2003-11-21 20:23:48 +0000631 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
632 assert(0 && "This type cannot be converted!\n");
633 abort();
634 }
635 };
Chris Lattnerb50d1352003-10-05 00:17:43 +0000636
Chris Lattner935aa922005-10-04 17:48:46 +0000637 template<class ValType, class TypeClass, class ConstantClass,
638 bool HasLargeKey = false /*true for arrays and structs*/ >
Chris Lattner02157b02006-06-28 21:38:54 +0000639 class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
Chris Lattnerb64419a2005-10-03 22:51:37 +0000640 public:
Jim Laskeyc03caef2006-07-17 17:38:29 +0000641 typedef std::pair<const Type*, ValType> MapKey;
642 typedef std::map<MapKey, Constant *> MapTy;
643 typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
644 typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
Chris Lattnerb64419a2005-10-03 22:51:37 +0000645 private:
Chris Lattner5bbf60a52005-10-04 16:52:46 +0000646 /// Map - This is the main map from the element descriptor to the Constants.
647 /// This is the primary way we avoid creating two of the same shape
648 /// constant.
Chris Lattnerb50d1352003-10-05 00:17:43 +0000649 MapTy Map;
Chris Lattner935aa922005-10-04 17:48:46 +0000650
651 /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
652 /// from the constants to their element in Map. This is important for
653 /// removal of constants from the array, which would otherwise have to scan
654 /// through the map with very large keys.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000655 InverseMapTy InverseMap;
Chris Lattnerb50d1352003-10-05 00:17:43 +0000656
Jim Laskeyc03caef2006-07-17 17:38:29 +0000657 /// AbstractTypeMap - Map for abstract type constants.
658 ///
Chris Lattnerb50d1352003-10-05 00:17:43 +0000659 AbstractTypeMapTy AbstractTypeMap;
Chris Lattner99a669b2004-11-19 16:39:44 +0000660
Chris Lattner99a669b2004-11-19 16:39:44 +0000661 private:
662 void clear(std::vector<Constant *> &Constants) {
Jim Laskeyc03caef2006-07-17 17:38:29 +0000663 for(typename MapTy::iterator I = Map.begin(); I != Map.end(); ++I)
Chris Lattner99a669b2004-11-19 16:39:44 +0000664 Constants.push_back(I->second);
665 Map.clear();
666 AbstractTypeMap.clear();
Chris Lattner935aa922005-10-04 17:48:46 +0000667 InverseMap.clear();
Chris Lattner99a669b2004-11-19 16:39:44 +0000668 }
669
Chris Lattner98fa07b2003-05-23 20:03:32 +0000670 public:
Jim Laskeyc03caef2006-07-17 17:38:29 +0000671 typename MapTy::iterator map_end() { return Map.end(); }
Chris Lattnerb64419a2005-10-03 22:51:37 +0000672
673 /// InsertOrGetItem - Return an iterator for the specified element.
674 /// If the element exists in the map, the returned iterator points to the
675 /// entry and Exists=true. If not, the iterator points to the newly
676 /// inserted entry and returns Exists=false. Newly inserted entries have
677 /// I->second == 0, and should be filled in.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000678 typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
679 &InsertVal,
Chris Lattnerb64419a2005-10-03 22:51:37 +0000680 bool &Exists) {
Jim Laskeyc03caef2006-07-17 17:38:29 +0000681 std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
Chris Lattnerb64419a2005-10-03 22:51:37 +0000682 Exists = !IP.second;
683 return IP.first;
684 }
Chris Lattner5bbf60a52005-10-04 16:52:46 +0000685
Chris Lattner935aa922005-10-04 17:48:46 +0000686private:
Jim Laskeyc03caef2006-07-17 17:38:29 +0000687 typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
Chris Lattner935aa922005-10-04 17:48:46 +0000688 if (HasLargeKey) {
Jim Laskeyc03caef2006-07-17 17:38:29 +0000689 typename InverseMapTy::iterator IMI = InverseMap.find(CP);
Chris Lattner935aa922005-10-04 17:48:46 +0000690 assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
691 IMI->second->second == CP &&
692 "InverseMap corrupt!");
693 return IMI->second;
694 }
695
Jim Laskeyc03caef2006-07-17 17:38:29 +0000696 typename MapTy::iterator I =
Chris Lattner935aa922005-10-04 17:48:46 +0000697 Map.find(MapKey((TypeClass*)CP->getRawType(), getValType(CP)));
Chris Lattner5bbf60a52005-10-04 16:52:46 +0000698 if (I == Map.end() || I->second != CP) {
699 // FIXME: This should not use a linear scan. If this gets to be a
700 // performance problem, someone should look at this.
701 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
702 /* empty */;
703 }
Chris Lattner935aa922005-10-04 17:48:46 +0000704 return I;
705 }
706public:
707
Chris Lattnerb64419a2005-10-03 22:51:37 +0000708 /// getOrCreate - Return the specified constant from the map, creating it if
709 /// necessary.
Chris Lattner98fa07b2003-05-23 20:03:32 +0000710 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
Chris Lattnerb50d1352003-10-05 00:17:43 +0000711 MapKey Lookup(Ty, V);
Jim Laskeyc03caef2006-07-17 17:38:29 +0000712 typename MapTy::iterator I = Map.lower_bound(Lookup);
Reid Spencere0fc4df2006-10-20 07:07:24 +0000713 // Is it in the map?
Chris Lattner98fa07b2003-05-23 20:03:32 +0000714 if (I != Map.end() && I->first == Lookup)
Reid Spencere0fc4df2006-10-20 07:07:24 +0000715 return static_cast<ConstantClass *>(I->second);
Chris Lattner98fa07b2003-05-23 20:03:32 +0000716
717 // If no preexisting value, create one now...
718 ConstantClass *Result =
719 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
720
Chris Lattnerb50d1352003-10-05 00:17:43 +0000721 /// FIXME: why does this assert fail when loading 176.gcc?
722 //assert(Result->getType() == Ty && "Type specified is not correct!");
723 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
724
Chris Lattner935aa922005-10-04 17:48:46 +0000725 if (HasLargeKey) // Remember the reverse mapping if needed.
726 InverseMap.insert(std::make_pair(Result, I));
727
Chris Lattnerb50d1352003-10-05 00:17:43 +0000728 // If the type of the constant is abstract, make sure that an entry exists
729 // for it in the AbstractTypeMap.
730 if (Ty->isAbstract()) {
731 typename AbstractTypeMapTy::iterator TI =
732 AbstractTypeMap.lower_bound(Ty);
733
734 if (TI == AbstractTypeMap.end() || TI->first != Ty) {
735 // Add ourselves to the ATU list of the type.
736 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
737
738 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
739 }
740 }
Chris Lattner98fa07b2003-05-23 20:03:32 +0000741 return Result;
742 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000743
Chris Lattner98fa07b2003-05-23 20:03:32 +0000744 void remove(ConstantClass *CP) {
Jim Laskeyc03caef2006-07-17 17:38:29 +0000745 typename MapTy::iterator I = FindExistingElement(CP);
Chris Lattnerb50d1352003-10-05 00:17:43 +0000746 assert(I != Map.end() && "Constant not found in constant table!");
Chris Lattner3e650af2004-08-04 04:48:01 +0000747 assert(I->second == CP && "Didn't find correct element?");
Chris Lattnerb50d1352003-10-05 00:17:43 +0000748
Chris Lattner935aa922005-10-04 17:48:46 +0000749 if (HasLargeKey) // Remember the reverse mapping if needed.
750 InverseMap.erase(CP);
751
Chris Lattnerb50d1352003-10-05 00:17:43 +0000752 // Now that we found the entry, make sure this isn't the entry that
753 // the AbstractTypeMap points to.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000754 const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
Chris Lattnerb50d1352003-10-05 00:17:43 +0000755 if (Ty->isAbstract()) {
756 assert(AbstractTypeMap.count(Ty) &&
757 "Abstract type not in AbstractTypeMap?");
Jim Laskeyc03caef2006-07-17 17:38:29 +0000758 typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
Chris Lattnerb50d1352003-10-05 00:17:43 +0000759 if (ATMEntryIt == I) {
760 // Yes, we are removing the representative entry for this type.
761 // See if there are any other entries of the same type.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000762 typename MapTy::iterator TmpIt = ATMEntryIt;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000763
Chris Lattnerb50d1352003-10-05 00:17:43 +0000764 // First check the entry before this one...
765 if (TmpIt != Map.begin()) {
766 --TmpIt;
767 if (TmpIt->first.first != Ty) // Not the same type, move back...
768 ++TmpIt;
769 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000770
Chris Lattnerb50d1352003-10-05 00:17:43 +0000771 // If we didn't find the same type, try to move forward...
772 if (TmpIt == ATMEntryIt) {
773 ++TmpIt;
774 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
775 --TmpIt; // No entry afterwards with the same type
776 }
777
778 // If there is another entry in the map of the same abstract type,
779 // update the AbstractTypeMap entry now.
780 if (TmpIt != ATMEntryIt) {
781 ATMEntryIt = TmpIt;
782 } else {
783 // Otherwise, we are removing the last instance of this type
784 // from the table. Remove from the ATM, and from user list.
785 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
786 AbstractTypeMap.erase(Ty);
787 }
Chris Lattner98fa07b2003-05-23 20:03:32 +0000788 }
Chris Lattnerb50d1352003-10-05 00:17:43 +0000789 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000790
Chris Lattnerb50d1352003-10-05 00:17:43 +0000791 Map.erase(I);
792 }
793
Chris Lattner3b793c62005-10-04 21:35:50 +0000794
795 /// MoveConstantToNewSlot - If we are about to change C to be the element
796 /// specified by I, update our internal data structures to reflect this
797 /// fact.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000798 void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
Chris Lattner3b793c62005-10-04 21:35:50 +0000799 // First, remove the old location of the specified constant in the map.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000800 typename MapTy::iterator OldI = FindExistingElement(C);
Chris Lattner3b793c62005-10-04 21:35:50 +0000801 assert(OldI != Map.end() && "Constant not found in constant table!");
802 assert(OldI->second == C && "Didn't find correct element?");
803
804 // If this constant is the representative element for its abstract type,
805 // update the AbstractTypeMap so that the representative element is I.
806 if (C->getType()->isAbstract()) {
807 typename AbstractTypeMapTy::iterator ATI =
808 AbstractTypeMap.find(C->getType());
809 assert(ATI != AbstractTypeMap.end() &&
810 "Abstract type not in AbstractTypeMap?");
811 if (ATI->second == OldI)
812 ATI->second = I;
813 }
814
815 // Remove the old entry from the map.
816 Map.erase(OldI);
817
818 // Update the inverse map so that we know that this constant is now
819 // located at descriptor I.
820 if (HasLargeKey) {
821 assert(I->second == C && "Bad inversemap entry!");
822 InverseMap[C] = I;
823 }
824 }
825
Chris Lattnerb50d1352003-10-05 00:17:43 +0000826 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
Misha Brukmanb1c93172005-04-21 23:48:37 +0000827 typename AbstractTypeMapTy::iterator I =
Jim Laskeyc03caef2006-07-17 17:38:29 +0000828 AbstractTypeMap.find(cast<Type>(OldTy));
Chris Lattnerb50d1352003-10-05 00:17:43 +0000829
830 assert(I != AbstractTypeMap.end() &&
831 "Abstract type not in AbstractTypeMap?");
832
833 // Convert a constant at a time until the last one is gone. The last one
834 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
835 // eliminated eventually.
836 do {
837 ConvertConstantType<ConstantClass,
Jim Laskeyc03caef2006-07-17 17:38:29 +0000838 TypeClass>::convert(
839 static_cast<ConstantClass *>(I->second->second),
Chris Lattnerb50d1352003-10-05 00:17:43 +0000840 cast<TypeClass>(NewTy));
841
Jim Laskeyc03caef2006-07-17 17:38:29 +0000842 I = AbstractTypeMap.find(cast<Type>(OldTy));
Chris Lattnerb50d1352003-10-05 00:17:43 +0000843 } while (I != AbstractTypeMap.end());
844 }
845
846 // If the type became concrete without being refined to any other existing
847 // type, we just remove ourselves from the ATU list.
848 void typeBecameConcrete(const DerivedType *AbsTy) {
849 AbsTy->removeAbstractTypeUser(this);
850 }
851
852 void dump() const {
Bill Wendling6a462f12006-11-17 08:03:48 +0000853 DOUT << "Constant.cpp: ValueMap\n";
Chris Lattner98fa07b2003-05-23 20:03:32 +0000854 }
855 };
856}
857
Chris Lattnera84df0a22006-09-28 23:36:21 +0000858
859//---- ConstantBool::get*() implementation.
860
861ConstantBool *ConstantBool::getTrue() {
862 static ConstantBool *T = 0;
863 if (T) return T;
864 return T = new ConstantBool(true);
865}
866ConstantBool *ConstantBool::getFalse() {
867 static ConstantBool *F = 0;
868 if (F) return F;
869 return F = new ConstantBool(false);
870}
871
Reid Spencere0fc4df2006-10-20 07:07:24 +0000872//---- ConstantInt::get() implementations...
Chris Lattner49d855c2001-09-07 16:46:31 +0000873//
Reid Spencere0fc4df2006-10-20 07:07:24 +0000874static ManagedStatic<ValueMap<uint64_t, Type, ConstantInt> > IntConstants;
Chris Lattner49d855c2001-09-07 16:46:31 +0000875
Reid Spencere0fc4df2006-10-20 07:07:24 +0000876// Get a ConstantInt from an int64_t. Note here that we canoncialize the value
877// to a uint64_t value that has been zero extended down to the size of the
878// integer type of the ConstantInt. This allows the getZExtValue method to
879// just return the stored value while getSExtValue has to convert back to sign
880// extended. getZExtValue is more common in LLVM than getSExtValue().
881ConstantInt *ConstantInt::get(const Type *Ty, int64_t V) {
Chris Lattnerf16661c2006-12-01 19:20:02 +0000882 return IntConstants->getOrCreate(Ty, V & Ty->getIntegralTypeMask());
883}
884
885ConstantIntegral *ConstantIntegral::get(const Type *Ty, int64_t V) {
886 if (Ty == Type::BoolTy) return ConstantBool::get(V&1);
887 return IntConstants->getOrCreate(Ty, V & Ty->getIntegralTypeMask());
Chris Lattner49d855c2001-09-07 16:46:31 +0000888}
889
Chris Lattner3462ae32001-12-03 22:26:30 +0000890//---- ConstantFP::get() implementation...
Chris Lattner49d855c2001-09-07 16:46:31 +0000891//
Chris Lattnerac80ea42004-02-01 22:49:04 +0000892namespace llvm {
893 template<>
894 struct ConstantCreator<ConstantFP, Type, uint64_t> {
895 static ConstantFP *create(const Type *Ty, uint64_t V) {
896 assert(Ty == Type::DoubleTy);
Jim Laskeyb74c6662005-08-17 19:34:49 +0000897 return new ConstantFP(Ty, BitsToDouble(V));
Chris Lattnerac80ea42004-02-01 22:49:04 +0000898 }
899 };
900 template<>
901 struct ConstantCreator<ConstantFP, Type, uint32_t> {
902 static ConstantFP *create(const Type *Ty, uint32_t V) {
903 assert(Ty == Type::FloatTy);
Jim Laskeyb74c6662005-08-17 19:34:49 +0000904 return new ConstantFP(Ty, BitsToFloat(V));
Chris Lattnerac80ea42004-02-01 22:49:04 +0000905 }
906 };
907}
908
Chris Lattner69edc982006-09-28 00:35:06 +0000909static ManagedStatic<ValueMap<uint64_t, Type, ConstantFP> > DoubleConstants;
910static ManagedStatic<ValueMap<uint32_t, Type, ConstantFP> > FloatConstants;
Chris Lattner49d855c2001-09-07 16:46:31 +0000911
Jim Laskey8ad8f712005-08-17 20:06:22 +0000912bool ConstantFP::isNullValue() const {
913 return DoubleToBits(Val) == 0;
914}
915
916bool ConstantFP::isExactlyValue(double V) const {
917 return DoubleToBits(V) == DoubleToBits(Val);
918}
919
920
Chris Lattner3462ae32001-12-03 22:26:30 +0000921ConstantFP *ConstantFP::get(const Type *Ty, double V) {
Chris Lattner241ed4c2004-01-23 00:55:21 +0000922 if (Ty == Type::FloatTy) {
923 // Force the value through memory to normalize it.
Chris Lattner69edc982006-09-28 00:35:06 +0000924 return FloatConstants->getOrCreate(Ty, FloatToBits(V));
Chris Lattnerac80ea42004-02-01 22:49:04 +0000925 } else {
926 assert(Ty == Type::DoubleTy);
Chris Lattner69edc982006-09-28 00:35:06 +0000927 return DoubleConstants->getOrCreate(Ty, DoubleToBits(V));
Chris Lattner241ed4c2004-01-23 00:55:21 +0000928 }
Chris Lattner49d855c2001-09-07 16:46:31 +0000929}
930
Chris Lattner9fba3da2004-02-15 05:53:04 +0000931//---- ConstantAggregateZero::get() implementation...
932//
933namespace llvm {
934 // ConstantAggregateZero does not take extra "value" argument...
935 template<class ValType>
936 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
937 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
938 return new ConstantAggregateZero(Ty);
939 }
940 };
941
942 template<>
943 struct ConvertConstantType<ConstantAggregateZero, Type> {
944 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
945 // Make everyone now use a constant of the new type...
946 Constant *New = ConstantAggregateZero::get(NewTy);
947 assert(New != OldC && "Didn't replace constant??");
948 OldC->uncheckedReplaceAllUsesWith(New);
949 OldC->destroyConstant(); // This constant is now dead, destroy it.
950 }
951 };
952}
953
Chris Lattner69edc982006-09-28 00:35:06 +0000954static ManagedStatic<ValueMap<char, Type,
955 ConstantAggregateZero> > AggZeroConstants;
Chris Lattner9fba3da2004-02-15 05:53:04 +0000956
Chris Lattner3e650af2004-08-04 04:48:01 +0000957static char getValType(ConstantAggregateZero *CPZ) { return 0; }
958
Chris Lattner9fba3da2004-02-15 05:53:04 +0000959Constant *ConstantAggregateZero::get(const Type *Ty) {
Chris Lattnerbfd0b6d2006-06-10 04:16:23 +0000960 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<PackedType>(Ty)) &&
961 "Cannot create an aggregate zero of non-aggregate type!");
Chris Lattner69edc982006-09-28 00:35:06 +0000962 return AggZeroConstants->getOrCreate(Ty, 0);
Chris Lattner9fba3da2004-02-15 05:53:04 +0000963}
964
965// destroyConstant - Remove the constant from the constant table...
966//
967void ConstantAggregateZero::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +0000968 AggZeroConstants->remove(this);
Chris Lattner9fba3da2004-02-15 05:53:04 +0000969 destroyConstantImpl();
970}
971
Chris Lattner3462ae32001-12-03 22:26:30 +0000972//---- ConstantArray::get() implementation...
Chris Lattner49d855c2001-09-07 16:46:31 +0000973//
Chris Lattner189d19f2003-11-21 20:23:48 +0000974namespace llvm {
975 template<>
976 struct ConvertConstantType<ConstantArray, ArrayType> {
977 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
978 // Make everyone now use a constant of the new type...
979 std::vector<Constant*> C;
980 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
981 C.push_back(cast<Constant>(OldC->getOperand(i)));
982 Constant *New = ConstantArray::get(NewTy, C);
983 assert(New != OldC && "Didn't replace constant??");
984 OldC->uncheckedReplaceAllUsesWith(New);
985 OldC->destroyConstant(); // This constant is now dead, destroy it.
986 }
987 };
988}
Chris Lattnerb50d1352003-10-05 00:17:43 +0000989
Chris Lattner3e650af2004-08-04 04:48:01 +0000990static std::vector<Constant*> getValType(ConstantArray *CA) {
991 std::vector<Constant*> Elements;
992 Elements.reserve(CA->getNumOperands());
993 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
994 Elements.push_back(cast<Constant>(CA->getOperand(i)));
995 return Elements;
996}
997
Chris Lattnerb64419a2005-10-03 22:51:37 +0000998typedef ValueMap<std::vector<Constant*>, ArrayType,
Chris Lattner935aa922005-10-04 17:48:46 +0000999 ConstantArray, true /*largekey*/> ArrayConstantsTy;
Chris Lattner69edc982006-09-28 00:35:06 +00001000static ManagedStatic<ArrayConstantsTy> ArrayConstants;
Chris Lattner49d855c2001-09-07 16:46:31 +00001001
Chris Lattner015e8212004-02-15 04:14:47 +00001002Constant *ConstantArray::get(const ArrayType *Ty,
Chris Lattner9fba3da2004-02-15 05:53:04 +00001003 const std::vector<Constant*> &V) {
1004 // If this is an all-zero array, return a ConstantAggregateZero object
1005 if (!V.empty()) {
1006 Constant *C = V[0];
1007 if (!C->isNullValue())
Chris Lattner69edc982006-09-28 00:35:06 +00001008 return ArrayConstants->getOrCreate(Ty, V);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001009 for (unsigned i = 1, e = V.size(); i != e; ++i)
1010 if (V[i] != C)
Chris Lattner69edc982006-09-28 00:35:06 +00001011 return ArrayConstants->getOrCreate(Ty, V);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001012 }
1013 return ConstantAggregateZero::get(Ty);
Chris Lattner49d855c2001-09-07 16:46:31 +00001014}
1015
Chris Lattner98fa07b2003-05-23 20:03:32 +00001016// destroyConstant - Remove the constant from the constant table...
1017//
1018void ConstantArray::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001019 ArrayConstants->remove(this);
Chris Lattner98fa07b2003-05-23 20:03:32 +00001020 destroyConstantImpl();
1021}
1022
Reid Spencer6f614532006-05-30 08:23:18 +00001023/// ConstantArray::get(const string&) - Return an array that is initialized to
1024/// contain the specified string. If length is zero then a null terminator is
1025/// added to the specified string so that it may be used in a natural way.
1026/// Otherwise, the length parameter specifies how much of the string to use
1027/// and it won't be null terminated.
1028///
Reid Spencer82ebaba2006-05-30 18:15:07 +00001029Constant *ConstantArray::get(const std::string &Str, bool AddNull) {
Chris Lattner7f74a562002-01-20 22:54:45 +00001030 std::vector<Constant*> ElementVals;
Reid Spencer82ebaba2006-05-30 18:15:07 +00001031 for (unsigned i = 0; i < Str.length(); ++i)
Reid Spencere0fc4df2006-10-20 07:07:24 +00001032 ElementVals.push_back(ConstantInt::get(Type::SByteTy, Str[i]));
Chris Lattner8f80fe02001-10-14 23:54:12 +00001033
1034 // Add a null terminator to the string...
Reid Spencer82ebaba2006-05-30 18:15:07 +00001035 if (AddNull) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00001036 ElementVals.push_back(ConstantInt::get(Type::SByteTy, 0));
Reid Spencer6f614532006-05-30 08:23:18 +00001037 }
Chris Lattner8f80fe02001-10-14 23:54:12 +00001038
Reid Spencer82ebaba2006-05-30 18:15:07 +00001039 ArrayType *ATy = ArrayType::get(Type::SByteTy, ElementVals.size());
Chris Lattner3462ae32001-12-03 22:26:30 +00001040 return ConstantArray::get(ATy, ElementVals);
Vikram S. Adve34410432001-10-14 23:17:20 +00001041}
1042
Chris Lattnere8dfcca2004-01-14 17:06:38 +00001043/// isString - This method returns true if the array is an array of sbyte or
1044/// ubyte, and if the elements of the array are all ConstantInt's.
1045bool ConstantArray::isString() const {
1046 // Check the element type for sbyte or ubyte...
Chris Lattnere8701f62004-01-14 17:51:53 +00001047 if (getType()->getElementType() != Type::UByteTy &&
Chris Lattnere8dfcca2004-01-14 17:06:38 +00001048 getType()->getElementType() != Type::SByteTy)
1049 return false;
1050 // Check the elements to make sure they are all integers, not constant
1051 // expressions.
1052 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1053 if (!isa<ConstantInt>(getOperand(i)))
1054 return false;
1055 return true;
1056}
1057
Evan Cheng3763c5b2006-10-26 19:15:05 +00001058/// isCString - This method returns true if the array is a string (see
1059/// isString) and it ends in a null byte \0 and does not contains any other
1060/// null bytes except its terminator.
1061bool ConstantArray::isCString() const {
Evan Chenge974da62006-10-26 21:48:03 +00001062 // Check the element type for sbyte or ubyte...
1063 if (getType()->getElementType() != Type::UByteTy &&
1064 getType()->getElementType() != Type::SByteTy)
1065 return false;
1066 Constant *Zero = Constant::getNullValue(getOperand(0)->getType());
1067 // Last element must be a null.
1068 if (getOperand(getNumOperands()-1) != Zero)
1069 return false;
1070 // Other elements must be non-null integers.
1071 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1072 if (!isa<ConstantInt>(getOperand(i)))
Evan Cheng3763c5b2006-10-26 19:15:05 +00001073 return false;
Evan Chenge974da62006-10-26 21:48:03 +00001074 if (getOperand(i) == Zero)
1075 return false;
1076 }
Evan Cheng3763c5b2006-10-26 19:15:05 +00001077 return true;
1078}
1079
1080
Chris Lattner81fabb02002-08-26 17:53:56 +00001081// getAsString - If the sub-element type of this array is either sbyte or ubyte,
1082// then this method converts the array to an std::string and returns it.
1083// Otherwise, it asserts out.
1084//
1085std::string ConstantArray::getAsString() const {
Chris Lattnere8dfcca2004-01-14 17:06:38 +00001086 assert(isString() && "Not a string!");
Chris Lattner81fabb02002-08-26 17:53:56 +00001087 std::string Result;
Chris Lattner6077c312003-07-23 15:22:26 +00001088 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
Reid Spencere0fc4df2006-10-20 07:07:24 +00001089 Result += (char)cast<ConstantInt>(getOperand(i))->getZExtValue();
Chris Lattner81fabb02002-08-26 17:53:56 +00001090 return Result;
1091}
1092
1093
Chris Lattner3462ae32001-12-03 22:26:30 +00001094//---- ConstantStruct::get() implementation...
Chris Lattner49d855c2001-09-07 16:46:31 +00001095//
Chris Lattnerb50d1352003-10-05 00:17:43 +00001096
Chris Lattner189d19f2003-11-21 20:23:48 +00001097namespace llvm {
1098 template<>
1099 struct ConvertConstantType<ConstantStruct, StructType> {
1100 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1101 // Make everyone now use a constant of the new type...
1102 std::vector<Constant*> C;
1103 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1104 C.push_back(cast<Constant>(OldC->getOperand(i)));
1105 Constant *New = ConstantStruct::get(NewTy, C);
1106 assert(New != OldC && "Didn't replace constant??");
Misha Brukmanb1c93172005-04-21 23:48:37 +00001107
Chris Lattner189d19f2003-11-21 20:23:48 +00001108 OldC->uncheckedReplaceAllUsesWith(New);
1109 OldC->destroyConstant(); // This constant is now dead, destroy it.
1110 }
1111 };
1112}
Chris Lattnerb50d1352003-10-05 00:17:43 +00001113
Chris Lattner8760ec72005-10-04 01:17:50 +00001114typedef ValueMap<std::vector<Constant*>, StructType,
Chris Lattner935aa922005-10-04 17:48:46 +00001115 ConstantStruct, true /*largekey*/> StructConstantsTy;
Chris Lattner69edc982006-09-28 00:35:06 +00001116static ManagedStatic<StructConstantsTy> StructConstants;
Chris Lattner49d855c2001-09-07 16:46:31 +00001117
Chris Lattner3e650af2004-08-04 04:48:01 +00001118static std::vector<Constant*> getValType(ConstantStruct *CS) {
1119 std::vector<Constant*> Elements;
1120 Elements.reserve(CS->getNumOperands());
1121 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1122 Elements.push_back(cast<Constant>(CS->getOperand(i)));
1123 return Elements;
1124}
1125
Chris Lattner015e8212004-02-15 04:14:47 +00001126Constant *ConstantStruct::get(const StructType *Ty,
1127 const std::vector<Constant*> &V) {
Chris Lattner9fba3da2004-02-15 05:53:04 +00001128 // Create a ConstantAggregateZero value if all elements are zeros...
1129 for (unsigned i = 0, e = V.size(); i != e; ++i)
1130 if (!V[i]->isNullValue())
Chris Lattner69edc982006-09-28 00:35:06 +00001131 return StructConstants->getOrCreate(Ty, V);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001132
1133 return ConstantAggregateZero::get(Ty);
Chris Lattner49d855c2001-09-07 16:46:31 +00001134}
Chris Lattner883ad0b2001-10-03 15:39:36 +00001135
Andrew Lenharthdcb3c972006-12-08 18:06:16 +00001136Constant *ConstantStruct::get(const std::vector<Constant*> &V, bool packed) {
Chris Lattnerd6108ca2004-07-12 20:35:11 +00001137 std::vector<const Type*> StructEls;
1138 StructEls.reserve(V.size());
1139 for (unsigned i = 0, e = V.size(); i != e; ++i)
1140 StructEls.push_back(V[i]->getType());
Andrew Lenharthdcb3c972006-12-08 18:06:16 +00001141 return get(StructType::get(StructEls, packed), V);
Chris Lattnerd6108ca2004-07-12 20:35:11 +00001142}
1143
Chris Lattnerd7a73302001-10-13 06:57:33 +00001144// destroyConstant - Remove the constant from the constant table...
Chris Lattner883ad0b2001-10-03 15:39:36 +00001145//
Chris Lattner3462ae32001-12-03 22:26:30 +00001146void ConstantStruct::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001147 StructConstants->remove(this);
Chris Lattnerd7a73302001-10-13 06:57:33 +00001148 destroyConstantImpl();
1149}
Chris Lattner883ad0b2001-10-03 15:39:36 +00001150
Brian Gaeke02209042004-08-20 06:00:58 +00001151//---- ConstantPacked::get() implementation...
1152//
1153namespace llvm {
1154 template<>
1155 struct ConvertConstantType<ConstantPacked, PackedType> {
1156 static void convert(ConstantPacked *OldC, const PackedType *NewTy) {
1157 // Make everyone now use a constant of the new type...
1158 std::vector<Constant*> C;
1159 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1160 C.push_back(cast<Constant>(OldC->getOperand(i)));
1161 Constant *New = ConstantPacked::get(NewTy, C);
1162 assert(New != OldC && "Didn't replace constant??");
1163 OldC->uncheckedReplaceAllUsesWith(New);
1164 OldC->destroyConstant(); // This constant is now dead, destroy it.
1165 }
1166 };
1167}
1168
1169static std::vector<Constant*> getValType(ConstantPacked *CP) {
1170 std::vector<Constant*> Elements;
1171 Elements.reserve(CP->getNumOperands());
1172 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1173 Elements.push_back(CP->getOperand(i));
1174 return Elements;
1175}
1176
Chris Lattner69edc982006-09-28 00:35:06 +00001177static ManagedStatic<ValueMap<std::vector<Constant*>, PackedType,
1178 ConstantPacked> > PackedConstants;
Brian Gaeke02209042004-08-20 06:00:58 +00001179
1180Constant *ConstantPacked::get(const PackedType *Ty,
1181 const std::vector<Constant*> &V) {
1182 // If this is an all-zero packed, return a ConstantAggregateZero object
1183 if (!V.empty()) {
1184 Constant *C = V[0];
1185 if (!C->isNullValue())
Chris Lattner69edc982006-09-28 00:35:06 +00001186 return PackedConstants->getOrCreate(Ty, V);
Brian Gaeke02209042004-08-20 06:00:58 +00001187 for (unsigned i = 1, e = V.size(); i != e; ++i)
1188 if (V[i] != C)
Chris Lattner69edc982006-09-28 00:35:06 +00001189 return PackedConstants->getOrCreate(Ty, V);
Brian Gaeke02209042004-08-20 06:00:58 +00001190 }
1191 return ConstantAggregateZero::get(Ty);
1192}
1193
1194Constant *ConstantPacked::get(const std::vector<Constant*> &V) {
1195 assert(!V.empty() && "Cannot infer type if V is empty");
1196 return get(PackedType::get(V.front()->getType(),V.size()), V);
1197}
1198
1199// destroyConstant - Remove the constant from the constant table...
1200//
1201void ConstantPacked::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001202 PackedConstants->remove(this);
Brian Gaeke02209042004-08-20 06:00:58 +00001203 destroyConstantImpl();
1204}
1205
Chris Lattner3462ae32001-12-03 22:26:30 +00001206//---- ConstantPointerNull::get() implementation...
Chris Lattnerd7a73302001-10-13 06:57:33 +00001207//
Chris Lattner98fa07b2003-05-23 20:03:32 +00001208
Chris Lattner189d19f2003-11-21 20:23:48 +00001209namespace llvm {
1210 // ConstantPointerNull does not take extra "value" argument...
1211 template<class ValType>
1212 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1213 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1214 return new ConstantPointerNull(Ty);
1215 }
1216 };
Chris Lattner98fa07b2003-05-23 20:03:32 +00001217
Chris Lattner189d19f2003-11-21 20:23:48 +00001218 template<>
1219 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1220 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1221 // Make everyone now use a constant of the new type...
1222 Constant *New = ConstantPointerNull::get(NewTy);
1223 assert(New != OldC && "Didn't replace constant??");
1224 OldC->uncheckedReplaceAllUsesWith(New);
1225 OldC->destroyConstant(); // This constant is now dead, destroy it.
1226 }
1227 };
1228}
Chris Lattnerb50d1352003-10-05 00:17:43 +00001229
Chris Lattner69edc982006-09-28 00:35:06 +00001230static ManagedStatic<ValueMap<char, PointerType,
1231 ConstantPointerNull> > NullPtrConstants;
Chris Lattnerd7a73302001-10-13 06:57:33 +00001232
Chris Lattner3e650af2004-08-04 04:48:01 +00001233static char getValType(ConstantPointerNull *) {
1234 return 0;
1235}
1236
1237
Chris Lattner3462ae32001-12-03 22:26:30 +00001238ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
Chris Lattner69edc982006-09-28 00:35:06 +00001239 return NullPtrConstants->getOrCreate(Ty, 0);
Chris Lattner883ad0b2001-10-03 15:39:36 +00001240}
1241
Chris Lattner0c6e0b92002-08-18 00:40:04 +00001242// destroyConstant - Remove the constant from the constant table...
1243//
1244void ConstantPointerNull::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001245 NullPtrConstants->remove(this);
Chris Lattner0c6e0b92002-08-18 00:40:04 +00001246 destroyConstantImpl();
1247}
1248
1249
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001250//---- UndefValue::get() implementation...
1251//
1252
1253namespace llvm {
1254 // UndefValue does not take extra "value" argument...
1255 template<class ValType>
1256 struct ConstantCreator<UndefValue, Type, ValType> {
1257 static UndefValue *create(const Type *Ty, const ValType &V) {
1258 return new UndefValue(Ty);
1259 }
1260 };
1261
1262 template<>
1263 struct ConvertConstantType<UndefValue, Type> {
1264 static void convert(UndefValue *OldC, const Type *NewTy) {
1265 // Make everyone now use a constant of the new type.
1266 Constant *New = UndefValue::get(NewTy);
1267 assert(New != OldC && "Didn't replace constant??");
1268 OldC->uncheckedReplaceAllUsesWith(New);
1269 OldC->destroyConstant(); // This constant is now dead, destroy it.
1270 }
1271 };
1272}
1273
Chris Lattner69edc982006-09-28 00:35:06 +00001274static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001275
1276static char getValType(UndefValue *) {
1277 return 0;
1278}
1279
1280
1281UndefValue *UndefValue::get(const Type *Ty) {
Chris Lattner69edc982006-09-28 00:35:06 +00001282 return UndefValueConstants->getOrCreate(Ty, 0);
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001283}
1284
1285// destroyConstant - Remove the constant from the constant table.
1286//
1287void UndefValue::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001288 UndefValueConstants->remove(this);
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001289 destroyConstantImpl();
1290}
1291
1292
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001293//---- ConstantExpr::get() implementations...
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001294//
Reid Spenceree3c9912006-12-04 05:19:50 +00001295struct ExprMapKeyType {
1296 explicit ExprMapKeyType(unsigned opc, std::vector<Constant*> ops,
Reid Spencerdba6aa42006-12-04 18:38:05 +00001297 unsigned short pred = 0) : opcode(opc), predicate(pred), operands(ops) { }
1298 uint16_t opcode;
1299 uint16_t predicate;
Reid Spenceree3c9912006-12-04 05:19:50 +00001300 std::vector<Constant*> operands;
Reid Spenceree3c9912006-12-04 05:19:50 +00001301 bool operator==(const ExprMapKeyType& that) const {
1302 return this->opcode == that.opcode &&
1303 this->predicate == that.predicate &&
1304 this->operands == that.operands;
1305 }
1306 bool operator<(const ExprMapKeyType & that) const {
1307 return this->opcode < that.opcode ||
1308 (this->opcode == that.opcode && this->predicate < that.predicate) ||
1309 (this->opcode == that.opcode && this->predicate == that.predicate &&
1310 this->operands < that.operands);
1311 }
1312
1313 bool operator!=(const ExprMapKeyType& that) const {
1314 return !(*this == that);
1315 }
1316};
Chris Lattner98fa07b2003-05-23 20:03:32 +00001317
Chris Lattner189d19f2003-11-21 20:23:48 +00001318namespace llvm {
1319 template<>
1320 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
Reid Spencer10fbf0e2006-12-03 05:48:19 +00001321 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1322 unsigned short pred = 0) {
Reid Spenceree3c9912006-12-04 05:19:50 +00001323 if (Instruction::isCast(V.opcode))
1324 return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1325 if ((V.opcode >= Instruction::BinaryOpsBegin &&
1326 V.opcode < Instruction::BinaryOpsEnd) ||
1327 V.opcode == Instruction::Shl ||
1328 V.opcode == Instruction::LShr ||
1329 V.opcode == Instruction::AShr)
1330 return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1331 if (V.opcode == Instruction::Select)
1332 return new SelectConstantExpr(V.operands[0], V.operands[1],
1333 V.operands[2]);
1334 if (V.opcode == Instruction::ExtractElement)
1335 return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1336 if (V.opcode == Instruction::InsertElement)
1337 return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1338 V.operands[2]);
1339 if (V.opcode == Instruction::ShuffleVector)
1340 return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1341 V.operands[2]);
1342 if (V.opcode == Instruction::GetElementPtr) {
1343 std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
1344 return new GetElementPtrConstantExpr(V.operands[0], IdxList, Ty);
1345 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001346
Reid Spenceree3c9912006-12-04 05:19:50 +00001347 // The compare instructions are weird. We have to encode the predicate
1348 // value and it is combined with the instruction opcode by multiplying
1349 // the opcode by one hundred. We must decode this to get the predicate.
1350 if (V.opcode == Instruction::ICmp)
1351 return new CompareConstantExpr(Instruction::ICmp, V.predicate,
1352 V.operands[0], V.operands[1]);
1353 if (V.opcode == Instruction::FCmp)
1354 return new CompareConstantExpr(Instruction::FCmp, V.predicate,
1355 V.operands[0], V.operands[1]);
1356 assert(0 && "Invalid ConstantExpr!");
Jeff Cohen9f469632006-12-15 21:47:01 +00001357 return 0;
Chris Lattnerb50d1352003-10-05 00:17:43 +00001358 }
Chris Lattner189d19f2003-11-21 20:23:48 +00001359 };
Chris Lattnerb50d1352003-10-05 00:17:43 +00001360
Chris Lattner189d19f2003-11-21 20:23:48 +00001361 template<>
1362 struct ConvertConstantType<ConstantExpr, Type> {
1363 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1364 Constant *New;
1365 switch (OldC->getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001366 case Instruction::Trunc:
1367 case Instruction::ZExt:
1368 case Instruction::SExt:
1369 case Instruction::FPTrunc:
1370 case Instruction::FPExt:
1371 case Instruction::UIToFP:
1372 case Instruction::SIToFP:
1373 case Instruction::FPToUI:
1374 case Instruction::FPToSI:
1375 case Instruction::PtrToInt:
1376 case Instruction::IntToPtr:
1377 case Instruction::BitCast:
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001378 New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0),
1379 NewTy);
Chris Lattner189d19f2003-11-21 20:23:48 +00001380 break;
Chris Lattner6e415c02004-03-12 05:54:04 +00001381 case Instruction::Select:
1382 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1383 OldC->getOperand(1),
1384 OldC->getOperand(2));
1385 break;
Chris Lattner189d19f2003-11-21 20:23:48 +00001386 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00001387 case Instruction::LShr:
1388 case Instruction::AShr:
Chris Lattner189d19f2003-11-21 20:23:48 +00001389 New = ConstantExpr::getShiftTy(NewTy, OldC->getOpcode(),
1390 OldC->getOperand(0), OldC->getOperand(1));
1391 break;
1392 default:
1393 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
Reid Spencer7eb55b32006-11-02 01:53:59 +00001394 OldC->getOpcode() < Instruction::BinaryOpsEnd);
Chris Lattner189d19f2003-11-21 20:23:48 +00001395 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1396 OldC->getOperand(1));
1397 break;
1398 case Instruction::GetElementPtr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00001399 // Make everyone now use a constant of the new type...
Chris Lattner13128ab2004-10-11 22:52:25 +00001400 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1401 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0), Idx);
Chris Lattner189d19f2003-11-21 20:23:48 +00001402 break;
1403 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001404
Chris Lattner189d19f2003-11-21 20:23:48 +00001405 assert(New != OldC && "Didn't replace constant??");
1406 OldC->uncheckedReplaceAllUsesWith(New);
1407 OldC->destroyConstant(); // This constant is now dead, destroy it.
1408 }
1409 };
1410} // end namespace llvm
Chris Lattnerb50d1352003-10-05 00:17:43 +00001411
1412
Chris Lattner3e650af2004-08-04 04:48:01 +00001413static ExprMapKeyType getValType(ConstantExpr *CE) {
1414 std::vector<Constant*> Operands;
1415 Operands.reserve(CE->getNumOperands());
1416 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1417 Operands.push_back(cast<Constant>(CE->getOperand(i)));
Reid Spenceree3c9912006-12-04 05:19:50 +00001418 return ExprMapKeyType(CE->getOpcode(), Operands,
1419 CE->isCompare() ? CE->getPredicate() : 0);
Chris Lattner3e650af2004-08-04 04:48:01 +00001420}
1421
Chris Lattner69edc982006-09-28 00:35:06 +00001422static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1423 ConstantExpr> > ExprConstants;
Vikram S. Adve4c485332002-07-15 18:19:33 +00001424
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001425/// This is a utility function to handle folding of casts and lookup of the
1426/// cast in the ExprConstants map. It is usedby the various get* methods below.
1427static inline Constant *getFoldedCast(
1428 Instruction::CastOps opc, Constant *C, const Type *Ty) {
Chris Lattner815ae2b2003-10-07 22:19:19 +00001429 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001430 // Fold a few common cases
1431 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1432 return FC;
Chris Lattneracdbe712003-04-17 19:24:48 +00001433
Vikram S. Adve4c485332002-07-15 18:19:33 +00001434 // Look up the constant in the table first to ensure uniqueness
Chris Lattner2b383d2e2003-05-13 21:37:02 +00001435 std::vector<Constant*> argVec(1, C);
Reid Spenceree3c9912006-12-04 05:19:50 +00001436 ExprMapKeyType Key(opc, argVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001437 return ExprConstants->getOrCreate(Ty, Key);
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001438}
Reid Spencerf37dc652006-12-05 19:14:13 +00001439
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001440Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1441 Instruction::CastOps opc = Instruction::CastOps(oc);
1442 assert(Instruction::isCast(opc) && "opcode out of range");
1443 assert(C && Ty && "Null arguments to getCast");
1444 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1445
1446 switch (opc) {
1447 default:
1448 assert(0 && "Invalid cast opcode");
1449 break;
1450 case Instruction::Trunc: return getTrunc(C, Ty);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001451 case Instruction::ZExt: return getZExt(C, Ty);
1452 case Instruction::SExt: return getSExt(C, Ty);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001453 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1454 case Instruction::FPExt: return getFPExtend(C, Ty);
1455 case Instruction::UIToFP: return getUIToFP(C, Ty);
1456 case Instruction::SIToFP: return getSIToFP(C, Ty);
1457 case Instruction::FPToUI: return getFPToUI(C, Ty);
1458 case Instruction::FPToSI: return getFPToSI(C, Ty);
1459 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1460 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1461 case Instruction::BitCast: return getBitCast(C, Ty);
Chris Lattner1ece6f82005-01-01 15:59:57 +00001462 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001463 return 0;
Reid Spencerf37dc652006-12-05 19:14:13 +00001464}
1465
Reid Spencer5c140882006-12-04 20:17:56 +00001466Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1467 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1468 return getCast(Instruction::BitCast, C, Ty);
1469 return getCast(Instruction::ZExt, C, Ty);
1470}
1471
1472Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1473 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1474 return getCast(Instruction::BitCast, C, Ty);
1475 return getCast(Instruction::SExt, C, Ty);
1476}
1477
1478Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1479 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1480 return getCast(Instruction::BitCast, C, Ty);
1481 return getCast(Instruction::Trunc, C, Ty);
1482}
1483
Reid Spencerbc245a02006-12-05 03:25:26 +00001484Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1485 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1486 assert((Ty->isIntegral() || Ty->getTypeID() == Type::PointerTyID) &&
1487 "Invalid cast");
1488
1489 if (Ty->isIntegral())
1490 return getCast(Instruction::PtrToInt, S, Ty);
1491 return getCast(Instruction::BitCast, S, Ty);
1492}
1493
Reid Spencer56521c42006-12-12 00:51:07 +00001494Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
1495 bool isSigned) {
1496 assert(C->getType()->isIntegral() && Ty->isIntegral() && "Invalid cast");
1497 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1498 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1499 Instruction::CastOps opcode =
1500 (SrcBits == DstBits ? Instruction::BitCast :
1501 (SrcBits > DstBits ? Instruction::Trunc :
1502 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1503 return getCast(opcode, C, Ty);
1504}
1505
1506Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1507 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1508 "Invalid cast");
1509 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1510 unsigned DstBits = Ty->getPrimitiveSizeInBits();
Reid Spencerca104e82006-12-12 05:38:50 +00001511 if (SrcBits == DstBits)
1512 return C; // Avoid a useless cast
Reid Spencer56521c42006-12-12 00:51:07 +00001513 Instruction::CastOps opcode =
Reid Spencerca104e82006-12-12 05:38:50 +00001514 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
Reid Spencer56521c42006-12-12 00:51:07 +00001515 return getCast(opcode, C, Ty);
1516}
1517
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001518Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
1519 assert(C->getType()->isInteger() && "Trunc operand must be integer");
1520 assert(Ty->isIntegral() && "Trunc produces only integral");
1521 assert(C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1522 "SrcTy must be larger than DestTy for Trunc!");
1523
1524 return getFoldedCast(Instruction::Trunc, C, Ty);
1525}
1526
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001527Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001528 assert(C->getType()->isIntegral() && "SEXt operand must be integral");
1529 assert(Ty->isInteger() && "SExt produces only integer");
1530 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1531 "SrcTy must be smaller than DestTy for SExt!");
1532
1533 return getFoldedCast(Instruction::SExt, C, Ty);
Chris Lattnerdd284742004-04-04 23:20:30 +00001534}
1535
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001536Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001537 assert(C->getType()->isIntegral() && "ZEXt operand must be integral");
1538 assert(Ty->isInteger() && "ZExt produces only integer");
1539 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1540 "SrcTy must be smaller than DestTy for ZExt!");
1541
1542 return getFoldedCast(Instruction::ZExt, C, Ty);
1543}
1544
1545Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1546 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1547 C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1548 "This is an illegal floating point truncation!");
1549 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1550}
1551
1552Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1553 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1554 C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1555 "This is an illegal floating point extension!");
1556 return getFoldedCast(Instruction::FPExt, C, Ty);
1557}
1558
1559Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
1560 assert(C->getType()->isIntegral() && Ty->isFloatingPoint() &&
1561 "This is an illegal uint to floating point cast!");
1562 return getFoldedCast(Instruction::UIToFP, C, Ty);
1563}
1564
1565Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
1566 assert(C->getType()->isIntegral() && Ty->isFloatingPoint() &&
1567 "This is an illegal sint to floating point cast!");
1568 return getFoldedCast(Instruction::SIToFP, C, Ty);
1569}
1570
1571Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
1572 assert(C->getType()->isFloatingPoint() && Ty->isIntegral() &&
1573 "This is an illegal floating point to uint cast!");
1574 return getFoldedCast(Instruction::FPToUI, C, Ty);
1575}
1576
1577Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
1578 assert(C->getType()->isFloatingPoint() && Ty->isIntegral() &&
1579 "This is an illegal floating point to sint cast!");
1580 return getFoldedCast(Instruction::FPToSI, C, Ty);
1581}
1582
1583Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1584 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
1585 assert(DstTy->isIntegral() && "PtrToInt destination must be integral");
1586 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1587}
1588
1589Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
1590 assert(C->getType()->isIntegral() && "IntToPtr source must be integral");
1591 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
1592 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1593}
1594
1595Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1596 // BitCast implies a no-op cast of type only. No bits change. However, you
1597 // can't cast pointers to anything but pointers.
1598 const Type *SrcTy = C->getType();
1599 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
Reid Spencer5c140882006-12-04 20:17:56 +00001600 "BitCast cannot cast pointer to non-pointer and vice versa");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001601
1602 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
1603 // or nonptr->ptr). For all the other types, the cast is okay if source and
1604 // destination bit widths are identical.
1605 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1606 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
Reid Spencer5c140882006-12-04 20:17:56 +00001607 assert(SrcBitSize == DstBitSize && "BitCast requies types of same width");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001608 return getFoldedCast(Instruction::BitCast, C, DstTy);
Chris Lattnerdd284742004-04-04 23:20:30 +00001609}
1610
Alkis Evlogimenosda5de052004-10-24 01:41:10 +00001611Constant *ConstantExpr::getSizeOf(const Type *Ty) {
Chris Lattneracc4e542004-12-13 19:48:51 +00001612 // sizeof is implemented as: (ulong) gep (Ty*)null, 1
Reid Spencerc4dacf22006-12-04 02:43:42 +00001613 return getCast(Instruction::PtrToInt, getGetElementPtr(getNullValue(
1614 PointerType::get(Ty)), std::vector<Constant*>(1,
1615 ConstantInt::get(Type::UIntTy, 1))), Type::ULongTy);
Alkis Evlogimenosda5de052004-10-24 01:41:10 +00001616}
1617
Alkis Evlogimenos9160d5f2005-03-19 11:40:31 +00001618Constant *ConstantExpr::getPtrPtrFromArrayPtr(Constant *C) {
1619 // pointer from array is implemented as: getelementptr arr ptr, 0, 0
Reid Spencere0fc4df2006-10-20 07:07:24 +00001620 static std::vector<Constant*> Indices(2, ConstantInt::get(Type::UIntTy, 0));
Alkis Evlogimenos9160d5f2005-03-19 11:40:31 +00001621
1622 return ConstantExpr::getGetElementPtr(C, Indices);
1623}
1624
Chris Lattnerb50d1352003-10-05 00:17:43 +00001625Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
Reid Spencera009d0d2006-12-04 21:35:24 +00001626 Constant *C1, Constant *C2) {
Reid Spencerfdff9382006-11-08 06:47:33 +00001627 if (Opcode == Instruction::Shl || Opcode == Instruction::LShr ||
1628 Opcode == Instruction::AShr)
Chris Lattner5645e8a2004-01-12 19:04:55 +00001629 return getShiftTy(ReqTy, Opcode, C1, C2);
Reid Spenceree3c9912006-12-04 05:19:50 +00001630
Chris Lattner38a9bcd2003-05-21 17:49:25 +00001631 // Check the operands for consistency first
Reid Spencer7eb55b32006-11-02 01:53:59 +00001632 assert(Opcode >= Instruction::BinaryOpsBegin &&
1633 Opcode < Instruction::BinaryOpsEnd &&
Chris Lattner38a9bcd2003-05-21 17:49:25 +00001634 "Invalid opcode in binary constant expression");
1635 assert(C1->getType() == C2->getType() &&
1636 "Operand types in binary constant expression should match");
Chris Lattnerb50d1352003-10-05 00:17:43 +00001637
Reid Spencer266e42b2006-12-23 06:05:41 +00001638 if (ReqTy == C1->getType() || ReqTy == Type::BoolTy)
Chris Lattnerb50d1352003-10-05 00:17:43 +00001639 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1640 return FC; // Fold a few common cases...
Chris Lattneracdbe712003-04-17 19:24:48 +00001641
Chris Lattner2b383d2e2003-05-13 21:37:02 +00001642 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
Reid Spencera009d0d2006-12-04 21:35:24 +00001643 ExprMapKeyType Key(Opcode, argVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001644 return ExprConstants->getOrCreate(ReqTy, Key);
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001645}
1646
Reid Spencer266e42b2006-12-23 06:05:41 +00001647Constant *ConstantExpr::getCompareTy(unsigned short predicate,
Reid Spencera009d0d2006-12-04 21:35:24 +00001648 Constant *C1, Constant *C2) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001649 switch (predicate) {
1650 default: assert(0 && "Invalid CmpInst predicate");
1651 case FCmpInst::FCMP_FALSE: case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_OGT:
1652 case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OLE:
1653 case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_ORD: case FCmpInst::FCMP_UNO:
1654 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UGT: case FCmpInst::FCMP_UGE:
1655 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_ULE: case FCmpInst::FCMP_UNE:
1656 case FCmpInst::FCMP_TRUE:
1657 return getFCmp(predicate, C1, C2);
1658 case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGT:
1659 case ICmpInst::ICMP_UGE: case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE:
1660 case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_SGE: case ICmpInst::ICMP_SLT:
1661 case ICmpInst::ICMP_SLE:
1662 return getICmp(predicate, C1, C2);
1663 }
Reid Spencera009d0d2006-12-04 21:35:24 +00001664}
1665
1666Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001667#ifndef NDEBUG
1668 switch (Opcode) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00001669 case Instruction::Add:
1670 case Instruction::Sub:
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001671 case Instruction::Mul:
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001672 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Chris Lattnerc421a262006-01-04 01:01:04 +00001673 assert((C1->getType()->isInteger() || C1->getType()->isFloatingPoint() ||
1674 isa<PackedType>(C1->getType())) &&
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001675 "Tried to create an arithmetic operation on a non-arithmetic type!");
1676 break;
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001677 case Instruction::UDiv:
1678 case Instruction::SDiv:
1679 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1680 assert((C1->getType()->isInteger() || (isa<PackedType>(C1->getType()) &&
1681 cast<PackedType>(C1->getType())->getElementType()->isInteger())) &&
1682 "Tried to create an arithmetic operation on a non-arithmetic type!");
1683 break;
1684 case Instruction::FDiv:
1685 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1686 assert((C1->getType()->isFloatingPoint() || (isa<PackedType>(C1->getType())
1687 && cast<PackedType>(C1->getType())->getElementType()->isFloatingPoint()))
1688 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1689 break;
Reid Spencer7eb55b32006-11-02 01:53:59 +00001690 case Instruction::URem:
1691 case Instruction::SRem:
1692 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1693 assert((C1->getType()->isInteger() || (isa<PackedType>(C1->getType()) &&
1694 cast<PackedType>(C1->getType())->getElementType()->isInteger())) &&
1695 "Tried to create an arithmetic operation on a non-arithmetic type!");
1696 break;
1697 case Instruction::FRem:
1698 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1699 assert((C1->getType()->isFloatingPoint() || (isa<PackedType>(C1->getType())
1700 && cast<PackedType>(C1->getType())->getElementType()->isFloatingPoint()))
1701 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1702 break;
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001703 case Instruction::And:
1704 case Instruction::Or:
1705 case Instruction::Xor:
1706 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Chris Lattnerc421a262006-01-04 01:01:04 +00001707 assert((C1->getType()->isIntegral() || isa<PackedType>(C1->getType())) &&
Misha Brukman3852f652005-01-27 06:46:38 +00001708 "Tried to create a logical operation on a non-integral type!");
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001709 break;
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001710 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00001711 case Instruction::LShr:
1712 case Instruction::AShr:
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001713 assert(C2->getType() == Type::UByteTy && "Shift should be by ubyte!");
Reid Spencerfdff9382006-11-08 06:47:33 +00001714 assert(C1->getType()->isInteger() &&
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001715 "Tried to create a shift operation on a non-integer type!");
1716 break;
1717 default:
1718 break;
1719 }
1720#endif
1721
Reid Spencera009d0d2006-12-04 21:35:24 +00001722 return getTy(C1->getType(), Opcode, C1, C2);
1723}
1724
Reid Spencer266e42b2006-12-23 06:05:41 +00001725Constant *ConstantExpr::getCompare(unsigned short pred,
Reid Spencera009d0d2006-12-04 21:35:24 +00001726 Constant *C1, Constant *C2) {
1727 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencer266e42b2006-12-23 06:05:41 +00001728 return getCompareTy(pred, C1, C2);
Chris Lattner29ca2c62004-08-04 18:50:09 +00001729}
1730
Chris Lattner6e415c02004-03-12 05:54:04 +00001731Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1732 Constant *V1, Constant *V2) {
1733 assert(C->getType() == Type::BoolTy && "Select condition must be bool!");
1734 assert(V1->getType() == V2->getType() && "Select value types must match!");
1735 assert(V1->getType()->isFirstClassType() && "Cannot select aggregate type!");
1736
1737 if (ReqTy == V1->getType())
1738 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1739 return SC; // Fold common cases
1740
1741 std::vector<Constant*> argVec(3, C);
1742 argVec[1] = V1;
1743 argVec[2] = V2;
Reid Spenceree3c9912006-12-04 05:19:50 +00001744 ExprMapKeyType Key(Instruction::Select, argVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001745 return ExprConstants->getOrCreate(ReqTy, Key);
Chris Lattner6e415c02004-03-12 05:54:04 +00001746}
1747
Chris Lattner9eb2b522004-01-12 19:12:58 +00001748/// getShiftTy - Return a shift left or shift right constant expr
Chris Lattnerb50d1352003-10-05 00:17:43 +00001749Constant *ConstantExpr::getShiftTy(const Type *ReqTy, unsigned Opcode,
1750 Constant *C1, Constant *C2) {
Chris Lattner38a9bcd2003-05-21 17:49:25 +00001751 // Check the operands for consistency first
Reid Spencerfdff9382006-11-08 06:47:33 +00001752 assert((Opcode == Instruction::Shl ||
1753 Opcode == Instruction::LShr ||
1754 Opcode == Instruction::AShr) &&
Chris Lattner38a9bcd2003-05-21 17:49:25 +00001755 "Invalid opcode in binary constant expression");
1756 assert(C1->getType()->isIntegral() && C2->getType() == Type::UByteTy &&
1757 "Invalid operand types for Shift constant expr!");
1758
Chris Lattner0bba7712004-01-12 20:40:42 +00001759 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
Chris Lattner38a9bcd2003-05-21 17:49:25 +00001760 return FC; // Fold a few common cases...
1761
1762 // Look up the constant in the table first to ensure uniqueness
1763 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
Reid Spenceree3c9912006-12-04 05:19:50 +00001764 ExprMapKeyType Key(Opcode, argVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001765 return ExprConstants->getOrCreate(ReqTy, Key);
Chris Lattner38a9bcd2003-05-21 17:49:25 +00001766}
1767
Chris Lattnerb50d1352003-10-05 00:17:43 +00001768Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
Chris Lattner13128ab2004-10-11 22:52:25 +00001769 const std::vector<Value*> &IdxList) {
1770 assert(GetElementPtrInst::getIndexedType(C->getType(), IdxList, true) &&
Chris Lattner04b60fe2004-02-16 20:46:13 +00001771 "GEP indices invalid!");
1772
Chris Lattneracdbe712003-04-17 19:24:48 +00001773 if (Constant *FC = ConstantFoldGetElementPtr(C, IdxList))
1774 return FC; // Fold a few common cases...
Chris Lattner04b60fe2004-02-16 20:46:13 +00001775
Chris Lattnerb50d1352003-10-05 00:17:43 +00001776 assert(isa<PointerType>(C->getType()) &&
Chris Lattner98fa07b2003-05-23 20:03:32 +00001777 "Non-pointer type for constant GetElementPtr expression");
Vikram S. Adve4c485332002-07-15 18:19:33 +00001778 // Look up the constant in the table first to ensure uniqueness
Chris Lattner13128ab2004-10-11 22:52:25 +00001779 std::vector<Constant*> ArgVec;
1780 ArgVec.reserve(IdxList.size()+1);
1781 ArgVec.push_back(C);
1782 for (unsigned i = 0, e = IdxList.size(); i != e; ++i)
1783 ArgVec.push_back(cast<Constant>(IdxList[i]));
Reid Spenceree3c9912006-12-04 05:19:50 +00001784 const ExprMapKeyType Key(Instruction::GetElementPtr,ArgVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001785 return ExprConstants->getOrCreate(ReqTy, Key);
Vikram S. Adve4c485332002-07-15 18:19:33 +00001786}
1787
Chris Lattnerb50d1352003-10-05 00:17:43 +00001788Constant *ConstantExpr::getGetElementPtr(Constant *C,
1789 const std::vector<Constant*> &IdxList){
1790 // Get the result type of the getelementptr!
1791 std::vector<Value*> VIdxList(IdxList.begin(), IdxList.end());
1792
1793 const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), VIdxList,
1794 true);
1795 assert(Ty && "GEP indices invalid!");
Chris Lattner13128ab2004-10-11 22:52:25 +00001796 return getGetElementPtrTy(PointerType::get(Ty), C, VIdxList);
1797}
1798
1799Constant *ConstantExpr::getGetElementPtr(Constant *C,
1800 const std::vector<Value*> &IdxList) {
1801 // Get the result type of the getelementptr!
1802 const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), IdxList,
1803 true);
1804 assert(Ty && "GEP indices invalid!");
Chris Lattnerb50d1352003-10-05 00:17:43 +00001805 return getGetElementPtrTy(PointerType::get(Ty), C, IdxList);
1806}
1807
Reid Spenceree3c9912006-12-04 05:19:50 +00001808Constant *
1809ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1810 assert(LHS->getType() == RHS->getType());
1811 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
1812 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1813
Reid Spencer266e42b2006-12-23 06:05:41 +00001814 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
Reid Spenceree3c9912006-12-04 05:19:50 +00001815 return FC; // Fold a few common cases...
1816
1817 // Look up the constant in the table first to ensure uniqueness
1818 std::vector<Constant*> ArgVec;
1819 ArgVec.push_back(LHS);
1820 ArgVec.push_back(RHS);
Reid Spencerb1537492006-12-24 18:42:29 +00001821 // Get the key type with both the opcode and predicate
Reid Spenceree3c9912006-12-04 05:19:50 +00001822 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
1823 return ExprConstants->getOrCreate(Type::BoolTy, Key);
1824}
1825
1826Constant *
1827ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1828 assert(LHS->getType() == RHS->getType());
1829 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1830
Reid Spencer266e42b2006-12-23 06:05:41 +00001831 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
Reid Spenceree3c9912006-12-04 05:19:50 +00001832 return FC; // Fold a few common cases...
1833
1834 // Look up the constant in the table first to ensure uniqueness
1835 std::vector<Constant*> ArgVec;
1836 ArgVec.push_back(LHS);
1837 ArgVec.push_back(RHS);
Reid Spencerb1537492006-12-24 18:42:29 +00001838 // Get the key type with both the opcode and predicate
Reid Spenceree3c9912006-12-04 05:19:50 +00001839 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
1840 return ExprConstants->getOrCreate(Type::BoolTy, Key);
1841}
1842
Robert Bocchino23004482006-01-10 19:05:34 +00001843Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
1844 Constant *Idx) {
Robert Bocchinode7f1c92006-01-10 20:03:46 +00001845 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
1846 return FC; // Fold a few common cases...
Robert Bocchino23004482006-01-10 19:05:34 +00001847 // Look up the constant in the table first to ensure uniqueness
1848 std::vector<Constant*> ArgVec(1, Val);
1849 ArgVec.push_back(Idx);
Reid Spenceree3c9912006-12-04 05:19:50 +00001850 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001851 return ExprConstants->getOrCreate(ReqTy, Key);
Robert Bocchino23004482006-01-10 19:05:34 +00001852}
1853
1854Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
1855 assert(isa<PackedType>(Val->getType()) &&
1856 "Tried to create extractelement operation on non-packed type!");
1857 assert(Idx->getType() == Type::UIntTy &&
Robert Bocchinoca27f032006-01-17 20:07:22 +00001858 "Extractelement index must be uint type!");
Robert Bocchino23004482006-01-10 19:05:34 +00001859 return getExtractElementTy(cast<PackedType>(Val->getType())->getElementType(),
1860 Val, Idx);
1861}
Chris Lattnerb50d1352003-10-05 00:17:43 +00001862
Robert Bocchinoca27f032006-01-17 20:07:22 +00001863Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
1864 Constant *Elt, Constant *Idx) {
1865 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
1866 return FC; // Fold a few common cases...
1867 // Look up the constant in the table first to ensure uniqueness
1868 std::vector<Constant*> ArgVec(1, Val);
1869 ArgVec.push_back(Elt);
1870 ArgVec.push_back(Idx);
Reid Spenceree3c9912006-12-04 05:19:50 +00001871 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001872 return ExprConstants->getOrCreate(ReqTy, Key);
Robert Bocchinoca27f032006-01-17 20:07:22 +00001873}
1874
1875Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1876 Constant *Idx) {
1877 assert(isa<PackedType>(Val->getType()) &&
1878 "Tried to create insertelement operation on non-packed type!");
1879 assert(Elt->getType() == cast<PackedType>(Val->getType())->getElementType()
1880 && "Insertelement types must match!");
1881 assert(Idx->getType() == Type::UIntTy &&
1882 "Insertelement index must be uint type!");
1883 return getInsertElementTy(cast<PackedType>(Val->getType())->getElementType(),
1884 Val, Elt, Idx);
1885}
1886
Chris Lattnerbbe0a422006-04-08 01:18:18 +00001887Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
1888 Constant *V2, Constant *Mask) {
1889 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
1890 return FC; // Fold a few common cases...
1891 // Look up the constant in the table first to ensure uniqueness
1892 std::vector<Constant*> ArgVec(1, V1);
1893 ArgVec.push_back(V2);
1894 ArgVec.push_back(Mask);
Reid Spenceree3c9912006-12-04 05:19:50 +00001895 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001896 return ExprConstants->getOrCreate(ReqTy, Key);
Chris Lattnerbbe0a422006-04-08 01:18:18 +00001897}
1898
1899Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
1900 Constant *Mask) {
1901 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1902 "Invalid shuffle vector constant expr operands!");
1903 return getShuffleVectorTy(V1->getType(), V1, V2, Mask);
1904}
1905
Vikram S. Adve4c485332002-07-15 18:19:33 +00001906// destroyConstant - Remove the constant from the constant table...
1907//
1908void ConstantExpr::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001909 ExprConstants->remove(this);
Vikram S. Adve4c485332002-07-15 18:19:33 +00001910 destroyConstantImpl();
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001911}
1912
Chris Lattner3cd8c562002-07-30 18:54:25 +00001913const char *ConstantExpr::getOpcodeName() const {
1914 return Instruction::getOpcodeName(getOpcode());
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001915}
Reid Spencer1ebe1ab2004-07-17 23:48:33 +00001916
Chris Lattnerc4062ba2005-10-03 21:58:36 +00001917//===----------------------------------------------------------------------===//
1918// replaceUsesOfWithOnConstant implementations
1919
1920void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattner7a1450d2005-10-04 18:13:04 +00001921 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00001922 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
Chris Lattner8760ec72005-10-04 01:17:50 +00001923 Constant *ToC = cast<Constant>(To);
Chris Lattnerdff59112005-10-04 18:47:09 +00001924
1925 unsigned OperandToUpdate = U-OperandList;
1926 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
1927
Jim Laskeyc03caef2006-07-17 17:38:29 +00001928 std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
Chris Lattnerb64419a2005-10-03 22:51:37 +00001929 Lookup.first.first = getType();
1930 Lookup.second = this;
Chris Lattnerdff59112005-10-04 18:47:09 +00001931
Chris Lattnerb64419a2005-10-03 22:51:37 +00001932 std::vector<Constant*> &Values = Lookup.first.second;
1933 Values.reserve(getNumOperands()); // Build replacement array.
Chris Lattnerdff59112005-10-04 18:47:09 +00001934
Chris Lattner8760ec72005-10-04 01:17:50 +00001935 // Fill values with the modified operands of the constant array. Also,
1936 // compute whether this turns into an all-zeros array.
Chris Lattnerdff59112005-10-04 18:47:09 +00001937 bool isAllZeros = false;
1938 if (!ToC->isNullValue()) {
1939 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
1940 Values.push_back(cast<Constant>(O->get()));
1941 } else {
1942 isAllZeros = true;
1943 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1944 Constant *Val = cast<Constant>(O->get());
1945 Values.push_back(Val);
1946 if (isAllZeros) isAllZeros = Val->isNullValue();
1947 }
Chris Lattnerc4062ba2005-10-03 21:58:36 +00001948 }
Chris Lattnerdff59112005-10-04 18:47:09 +00001949 Values[OperandToUpdate] = ToC;
Chris Lattnerc4062ba2005-10-03 21:58:36 +00001950
Chris Lattnerb64419a2005-10-03 22:51:37 +00001951 Constant *Replacement = 0;
1952 if (isAllZeros) {
1953 Replacement = ConstantAggregateZero::get(getType());
1954 } else {
1955 // Check to see if we have this array type already.
1956 bool Exists;
Jim Laskeyc03caef2006-07-17 17:38:29 +00001957 ArrayConstantsTy::MapTy::iterator I =
Chris Lattner69edc982006-09-28 00:35:06 +00001958 ArrayConstants->InsertOrGetItem(Lookup, Exists);
Chris Lattnerb64419a2005-10-03 22:51:37 +00001959
1960 if (Exists) {
1961 Replacement = I->second;
1962 } else {
1963 // Okay, the new shape doesn't exist in the system yet. Instead of
1964 // creating a new constant array, inserting it, replaceallusesof'ing the
1965 // old with the new, then deleting the old... just update the current one
1966 // in place!
Chris Lattner69edc982006-09-28 00:35:06 +00001967 ArrayConstants->MoveConstantToNewSlot(this, I);
Chris Lattnerb64419a2005-10-03 22:51:37 +00001968
Chris Lattnerdff59112005-10-04 18:47:09 +00001969 // Update to the new value.
1970 setOperand(OperandToUpdate, ToC);
Chris Lattnerb64419a2005-10-03 22:51:37 +00001971 return;
1972 }
1973 }
1974
1975 // Otherwise, I do need to replace this with an existing value.
Chris Lattnerc4062ba2005-10-03 21:58:36 +00001976 assert(Replacement != this && "I didn't contain From!");
1977
Chris Lattner7a1450d2005-10-04 18:13:04 +00001978 // Everyone using this now uses the replacement.
1979 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00001980
1981 // Delete the old constant!
1982 destroyConstant();
1983}
1984
1985void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattner7a1450d2005-10-04 18:13:04 +00001986 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00001987 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
Chris Lattner8760ec72005-10-04 01:17:50 +00001988 Constant *ToC = cast<Constant>(To);
1989
Chris Lattnerdff59112005-10-04 18:47:09 +00001990 unsigned OperandToUpdate = U-OperandList;
1991 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
1992
Jim Laskeyc03caef2006-07-17 17:38:29 +00001993 std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
Chris Lattner8760ec72005-10-04 01:17:50 +00001994 Lookup.first.first = getType();
1995 Lookup.second = this;
1996 std::vector<Constant*> &Values = Lookup.first.second;
1997 Values.reserve(getNumOperands()); // Build replacement struct.
Chris Lattnerc4062ba2005-10-03 21:58:36 +00001998
Chris Lattnerdff59112005-10-04 18:47:09 +00001999
Chris Lattner8760ec72005-10-04 01:17:50 +00002000 // Fill values with the modified operands of the constant struct. Also,
2001 // compute whether this turns into an all-zeros struct.
Chris Lattnerdff59112005-10-04 18:47:09 +00002002 bool isAllZeros = false;
2003 if (!ToC->isNullValue()) {
2004 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
2005 Values.push_back(cast<Constant>(O->get()));
2006 } else {
2007 isAllZeros = true;
2008 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2009 Constant *Val = cast<Constant>(O->get());
2010 Values.push_back(Val);
2011 if (isAllZeros) isAllZeros = Val->isNullValue();
2012 }
Chris Lattner8760ec72005-10-04 01:17:50 +00002013 }
Chris Lattnerdff59112005-10-04 18:47:09 +00002014 Values[OperandToUpdate] = ToC;
2015
Chris Lattner8760ec72005-10-04 01:17:50 +00002016 Constant *Replacement = 0;
2017 if (isAllZeros) {
2018 Replacement = ConstantAggregateZero::get(getType());
2019 } else {
2020 // Check to see if we have this array type already.
2021 bool Exists;
Jim Laskeyc03caef2006-07-17 17:38:29 +00002022 StructConstantsTy::MapTy::iterator I =
Chris Lattner69edc982006-09-28 00:35:06 +00002023 StructConstants->InsertOrGetItem(Lookup, Exists);
Chris Lattner8760ec72005-10-04 01:17:50 +00002024
2025 if (Exists) {
2026 Replacement = I->second;
2027 } else {
2028 // Okay, the new shape doesn't exist in the system yet. Instead of
2029 // creating a new constant struct, inserting it, replaceallusesof'ing the
2030 // old with the new, then deleting the old... just update the current one
2031 // in place!
Chris Lattner69edc982006-09-28 00:35:06 +00002032 StructConstants->MoveConstantToNewSlot(this, I);
Chris Lattner8760ec72005-10-04 01:17:50 +00002033
Chris Lattnerdff59112005-10-04 18:47:09 +00002034 // Update to the new value.
2035 setOperand(OperandToUpdate, ToC);
Chris Lattner8760ec72005-10-04 01:17:50 +00002036 return;
2037 }
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002038 }
2039
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002040 assert(Replacement != this && "I didn't contain From!");
2041
Chris Lattner7a1450d2005-10-04 18:13:04 +00002042 // Everyone using this now uses the replacement.
2043 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002044
2045 // Delete the old constant!
2046 destroyConstant();
2047}
2048
2049void ConstantPacked::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002050 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002051 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2052
2053 std::vector<Constant*> Values;
2054 Values.reserve(getNumOperands()); // Build replacement array...
2055 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2056 Constant *Val = getOperand(i);
2057 if (Val == From) Val = cast<Constant>(To);
2058 Values.push_back(Val);
2059 }
2060
2061 Constant *Replacement = ConstantPacked::get(getType(), Values);
2062 assert(Replacement != this && "I didn't contain From!");
2063
Chris Lattner7a1450d2005-10-04 18:13:04 +00002064 // Everyone using this now uses the replacement.
2065 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002066
2067 // Delete the old constant!
2068 destroyConstant();
2069}
2070
2071void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002072 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002073 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2074 Constant *To = cast<Constant>(ToV);
2075
2076 Constant *Replacement = 0;
2077 if (getOpcode() == Instruction::GetElementPtr) {
2078 std::vector<Constant*> Indices;
2079 Constant *Pointer = getOperand(0);
2080 Indices.reserve(getNumOperands()-1);
2081 if (Pointer == From) Pointer = To;
2082
2083 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2084 Constant *Val = getOperand(i);
2085 if (Val == From) Val = To;
2086 Indices.push_back(Val);
2087 }
2088 Replacement = ConstantExpr::getGetElementPtr(Pointer, Indices);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002089 } else if (isCast()) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002090 assert(getOperand(0) == From && "Cast only has one use!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002091 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002092 } else if (getOpcode() == Instruction::Select) {
2093 Constant *C1 = getOperand(0);
2094 Constant *C2 = getOperand(1);
2095 Constant *C3 = getOperand(2);
2096 if (C1 == From) C1 = To;
2097 if (C2 == From) C2 = To;
2098 if (C3 == From) C3 = To;
2099 Replacement = ConstantExpr::getSelect(C1, C2, C3);
Robert Bocchino23004482006-01-10 19:05:34 +00002100 } else if (getOpcode() == Instruction::ExtractElement) {
2101 Constant *C1 = getOperand(0);
2102 Constant *C2 = getOperand(1);
2103 if (C1 == From) C1 = To;
2104 if (C2 == From) C2 = To;
2105 Replacement = ConstantExpr::getExtractElement(C1, C2);
Chris Lattnera93b4b52006-04-08 05:09:48 +00002106 } else if (getOpcode() == Instruction::InsertElement) {
2107 Constant *C1 = getOperand(0);
2108 Constant *C2 = getOperand(1);
2109 Constant *C3 = getOperand(1);
2110 if (C1 == From) C1 = To;
2111 if (C2 == From) C2 = To;
2112 if (C3 == From) C3 = To;
2113 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2114 } else if (getOpcode() == Instruction::ShuffleVector) {
2115 Constant *C1 = getOperand(0);
2116 Constant *C2 = getOperand(1);
2117 Constant *C3 = getOperand(2);
2118 if (C1 == From) C1 = To;
2119 if (C2 == From) C2 = To;
2120 if (C3 == From) C3 = To;
2121 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
Reid Spenceree3c9912006-12-04 05:19:50 +00002122 } else if (isCompare()) {
2123 Constant *C1 = getOperand(0);
2124 Constant *C2 = getOperand(1);
2125 if (C1 == From) C1 = To;
2126 if (C2 == From) C2 = To;
2127 if (getOpcode() == Instruction::ICmp)
2128 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2129 else
2130 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002131 } else if (getNumOperands() == 2) {
2132 Constant *C1 = getOperand(0);
2133 Constant *C2 = getOperand(1);
2134 if (C1 == From) C1 = To;
2135 if (C2 == From) C2 = To;
2136 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2137 } else {
2138 assert(0 && "Unknown ConstantExpr type!");
2139 return;
2140 }
2141
2142 assert(Replacement != this && "I didn't contain From!");
2143
Chris Lattner7a1450d2005-10-04 18:13:04 +00002144 // Everyone using this now uses the replacement.
2145 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002146
2147 // Delete the old constant!
2148 destroyConstant();
2149}
2150
2151
Jim Laskey2698f0d2006-03-08 18:11:07 +00002152/// getStringValue - Turn an LLVM constant pointer that eventually points to a
2153/// global into a string value. Return an empty string if we can't do it.
Evan Cheng38280c02006-03-10 23:52:03 +00002154/// Parameter Chop determines if the result is chopped at the first null
2155/// terminator.
Jim Laskey2698f0d2006-03-08 18:11:07 +00002156///
Evan Cheng38280c02006-03-10 23:52:03 +00002157std::string Constant::getStringValue(bool Chop, unsigned Offset) {
Jim Laskey2698f0d2006-03-08 18:11:07 +00002158 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(this)) {
2159 if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
2160 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
2161 if (Init->isString()) {
2162 std::string Result = Init->getAsString();
2163 if (Offset < Result.size()) {
2164 // If we are pointing INTO The string, erase the beginning...
2165 Result.erase(Result.begin(), Result.begin()+Offset);
2166
2167 // Take off the null terminator, and any string fragments after it.
Evan Cheng38280c02006-03-10 23:52:03 +00002168 if (Chop) {
2169 std::string::size_type NullPos = Result.find_first_of((char)0);
2170 if (NullPos != std::string::npos)
2171 Result.erase(Result.begin()+NullPos, Result.end());
2172 }
Jim Laskey2698f0d2006-03-08 18:11:07 +00002173 return Result;
2174 }
2175 }
2176 }
2177 } else if (Constant *C = dyn_cast<Constant>(this)) {
2178 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
Evan Cheng2c5e5302006-03-11 00:13:10 +00002179 return GV->getStringValue(Chop, Offset);
Jim Laskey2698f0d2006-03-08 18:11:07 +00002180 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2181 if (CE->getOpcode() == Instruction::GetElementPtr) {
2182 // Turn a gep into the specified offset.
2183 if (CE->getNumOperands() == 3 &&
2184 cast<Constant>(CE->getOperand(1))->isNullValue() &&
2185 isa<ConstantInt>(CE->getOperand(2))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002186 Offset += cast<ConstantInt>(CE->getOperand(2))->getZExtValue();
Evan Cheng2c5e5302006-03-11 00:13:10 +00002187 return CE->getOperand(0)->getStringValue(Chop, Offset);
Jim Laskey2698f0d2006-03-08 18:11:07 +00002188 }
2189 }
2190 }
2191 }
2192 return "";
2193}