blob: f9271178a4d139a6a896d6a465db7e8e492d3f58 [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
Chris Lattner22ced562003-06-22 20:48:30 +0000268static bool isSetCC(unsigned Opcode) {
269 return Opcode == Instruction::SetEQ || Opcode == Instruction::SetNE ||
270 Opcode == Instruction::SetLT || Opcode == Instruction::SetGT ||
271 Opcode == Instruction::SetLE || Opcode == Instruction::SetGE;
272}
273
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000274// We declare several classes private to this file, so use an anonymous
275// namespace
276namespace {
277
278/// UnaryConstantExpr - This class is private to Constants.cpp, and is used
279/// behind the scenes to implement unary constant exprs.
280class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
281 Use Op;
282public:
283 UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
284 : ConstantExpr(Ty, Opcode, &Op, 1), Op(C, this) {}
285};
286
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000287/// BinaryConstantExpr - This class is private to Constants.cpp, and is used
288/// behind the scenes to implement binary constant exprs.
Chris Lattner02157b02006-06-28 21:38:54 +0000289class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000290 Use Ops[2];
291public:
292 BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
293 : ConstantExpr(isSetCC(Opcode) ? Type::BoolTy : C1->getType(),
294 Opcode, Ops, 2) {
295 Ops[0].init(C1, this);
296 Ops[1].init(C2, this);
297 }
298};
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000299
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000300/// SelectConstantExpr - This class is private to Constants.cpp, and is used
301/// behind the scenes to implement select constant exprs.
Chris Lattner02157b02006-06-28 21:38:54 +0000302class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000303 Use Ops[3];
304public:
305 SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
306 : ConstantExpr(C2->getType(), Instruction::Select, Ops, 3) {
307 Ops[0].init(C1, this);
308 Ops[1].init(C2, this);
309 Ops[2].init(C3, this);
310 }
311};
312
Robert Bocchinoca27f032006-01-17 20:07:22 +0000313/// ExtractElementConstantExpr - This class is private to
314/// Constants.cpp, and is used behind the scenes to implement
315/// extractelement constant exprs.
Chris Lattner02157b02006-06-28 21:38:54 +0000316class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
Robert Bocchino23004482006-01-10 19:05:34 +0000317 Use Ops[2];
318public:
319 ExtractElementConstantExpr(Constant *C1, Constant *C2)
320 : ConstantExpr(cast<PackedType>(C1->getType())->getElementType(),
321 Instruction::ExtractElement, Ops, 2) {
322 Ops[0].init(C1, this);
323 Ops[1].init(C2, this);
324 }
325};
326
Robert Bocchinoca27f032006-01-17 20:07:22 +0000327/// InsertElementConstantExpr - This class is private to
328/// Constants.cpp, and is used behind the scenes to implement
329/// insertelement constant exprs.
Chris Lattner02157b02006-06-28 21:38:54 +0000330class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
Robert Bocchinoca27f032006-01-17 20:07:22 +0000331 Use Ops[3];
332public:
333 InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
334 : ConstantExpr(C1->getType(), Instruction::InsertElement,
335 Ops, 3) {
336 Ops[0].init(C1, this);
337 Ops[1].init(C2, this);
338 Ops[2].init(C3, this);
339 }
340};
341
Chris Lattnerbbe0a422006-04-08 01:18:18 +0000342/// ShuffleVectorConstantExpr - This class is private to
343/// Constants.cpp, and is used behind the scenes to implement
344/// shufflevector constant exprs.
Chris Lattner02157b02006-06-28 21:38:54 +0000345class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
Chris Lattnerbbe0a422006-04-08 01:18:18 +0000346 Use Ops[3];
347public:
348 ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
349 : ConstantExpr(C1->getType(), Instruction::ShuffleVector,
350 Ops, 3) {
351 Ops[0].init(C1, this);
352 Ops[1].init(C2, this);
353 Ops[2].init(C3, this);
354 }
355};
356
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000357/// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
358/// used behind the scenes to implement getelementpr constant exprs.
Chris Lattner02157b02006-06-28 21:38:54 +0000359struct VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000360 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
361 const Type *DestTy)
362 : ConstantExpr(DestTy, Instruction::GetElementPtr,
363 new Use[IdxList.size()+1], IdxList.size()+1) {
364 OperandList[0].init(C, this);
365 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
366 OperandList[i+1].init(IdxList[i], this);
367 }
368 ~GetElementPtrConstantExpr() {
Misha Brukmanb1c93172005-04-21 23:48:37 +0000369 delete [] OperandList;
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000370 }
371};
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000372
373// CompareConstantExpr - This class is private to Constants.cpp, and is used
374// behind the scenes to implement ICmp and FCmp constant expressions. This is
375// needed in order to store the predicate value for these instructions.
376struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
377 unsigned short predicate;
378 Use Ops[2];
379 CompareConstantExpr(Instruction::OtherOps opc, unsigned short pred,
380 Constant* LHS, Constant* RHS)
381 : ConstantExpr(Type::BoolTy, Instruction::OtherOps(opc), Ops, 2),
382 predicate(pred) {
383 OperandList[0].init(LHS, this);
384 OperandList[1].init(RHS, this);
385 }
386};
387
388} // end anonymous namespace
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000389
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000390
391// Utility function for determining if a ConstantExpr is a CastOp or not. This
392// can't be inline because we don't want to #include Instruction.h into
393// Constant.h
394bool ConstantExpr::isCast() const {
395 return Instruction::isCast(getOpcode());
396}
397
Reid Spenceree3c9912006-12-04 05:19:50 +0000398bool ConstantExpr::isCompare() const {
399 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
400}
401
Chris Lattner817175f2004-03-29 02:37:53 +0000402/// ConstantExpr::get* - Return some common constants without having to
403/// specify the full Instruction::OPCODE identifier.
404///
405Constant *ConstantExpr::getNeg(Constant *C) {
Chris Lattner3cdc27c2004-03-29 19:51:24 +0000406 if (!C->getType()->isFloatingPoint())
407 return get(Instruction::Sub, getNullValue(C->getType()), C);
408 else
409 return get(Instruction::Sub, ConstantFP::get(C->getType(), -0.0), C);
Chris Lattner817175f2004-03-29 02:37:53 +0000410}
411Constant *ConstantExpr::getNot(Constant *C) {
412 assert(isa<ConstantIntegral>(C) && "Cannot NOT a nonintegral type!");
413 return get(Instruction::Xor, C,
414 ConstantIntegral::getAllOnesValue(C->getType()));
415}
416Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
417 return get(Instruction::Add, C1, C2);
418}
419Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
420 return get(Instruction::Sub, C1, C2);
421}
422Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
423 return get(Instruction::Mul, C1, C2);
424}
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000425Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2) {
426 return get(Instruction::UDiv, C1, C2);
427}
428Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2) {
429 return get(Instruction::SDiv, C1, C2);
430}
431Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
432 return get(Instruction::FDiv, C1, C2);
Chris Lattner817175f2004-03-29 02:37:53 +0000433}
Reid Spencer7eb55b32006-11-02 01:53:59 +0000434Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
435 return get(Instruction::URem, C1, C2);
436}
437Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
438 return get(Instruction::SRem, C1, C2);
439}
440Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
441 return get(Instruction::FRem, C1, C2);
Chris Lattner817175f2004-03-29 02:37:53 +0000442}
443Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
444 return get(Instruction::And, C1, C2);
445}
446Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
447 return get(Instruction::Or, C1, C2);
448}
449Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
450 return get(Instruction::Xor, C1, C2);
451}
452Constant *ConstantExpr::getSetEQ(Constant *C1, Constant *C2) {
453 return get(Instruction::SetEQ, C1, C2);
454}
455Constant *ConstantExpr::getSetNE(Constant *C1, Constant *C2) {
456 return get(Instruction::SetNE, C1, C2);
457}
458Constant *ConstantExpr::getSetLT(Constant *C1, Constant *C2) {
459 return get(Instruction::SetLT, C1, C2);
460}
461Constant *ConstantExpr::getSetGT(Constant *C1, Constant *C2) {
462 return get(Instruction::SetGT, C1, C2);
463}
464Constant *ConstantExpr::getSetLE(Constant *C1, Constant *C2) {
465 return get(Instruction::SetLE, C1, C2);
466}
467Constant *ConstantExpr::getSetGE(Constant *C1, Constant *C2) {
468 return get(Instruction::SetGE, C1, C2);
469}
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000470unsigned ConstantExpr::getPredicate() const {
471 assert(getOpcode() == Instruction::FCmp || getOpcode() == Instruction::ICmp);
472 return dynamic_cast<const CompareConstantExpr*>(this)->predicate;
473}
Chris Lattner817175f2004-03-29 02:37:53 +0000474Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
475 return get(Instruction::Shl, C1, C2);
476}
Reid Spencerfdff9382006-11-08 06:47:33 +0000477Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2) {
478 return get(Instruction::LShr, C1, C2);
Chris Lattner817175f2004-03-29 02:37:53 +0000479}
Reid Spencerfdff9382006-11-08 06:47:33 +0000480Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2) {
481 return get(Instruction::AShr, C1, C2);
Chris Lattnerdb8bdba2004-05-25 05:32:43 +0000482}
Chris Lattner60e0dd72001-10-03 06:12:09 +0000483
Chris Lattner7c1018a2006-07-14 19:37:40 +0000484/// getWithOperandReplaced - Return a constant expression identical to this
485/// one, but with the specified operand set to the specified value.
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000486Constant *
487ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
Chris Lattner7c1018a2006-07-14 19:37:40 +0000488 assert(OpNo < getNumOperands() && "Operand num is out of range!");
489 assert(Op->getType() == getOperand(OpNo)->getType() &&
490 "Replacing operand with value of different type!");
Chris Lattner227816342006-07-14 22:20:01 +0000491 if (getOperand(OpNo) == Op)
492 return const_cast<ConstantExpr*>(this);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000493
Chris Lattner227816342006-07-14 22:20:01 +0000494 Constant *Op0, *Op1, *Op2;
Chris Lattner7c1018a2006-07-14 19:37:40 +0000495 switch (getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000496 case Instruction::Trunc:
497 case Instruction::ZExt:
498 case Instruction::SExt:
499 case Instruction::FPTrunc:
500 case Instruction::FPExt:
501 case Instruction::UIToFP:
502 case Instruction::SIToFP:
503 case Instruction::FPToUI:
504 case Instruction::FPToSI:
505 case Instruction::PtrToInt:
506 case Instruction::IntToPtr:
507 case Instruction::BitCast:
508 return ConstantExpr::getCast(getOpcode(), Op, getType());
Chris Lattner227816342006-07-14 22:20:01 +0000509 case Instruction::Select:
510 Op0 = (OpNo == 0) ? Op : getOperand(0);
511 Op1 = (OpNo == 1) ? Op : getOperand(1);
512 Op2 = (OpNo == 2) ? Op : getOperand(2);
513 return ConstantExpr::getSelect(Op0, Op1, Op2);
514 case Instruction::InsertElement:
515 Op0 = (OpNo == 0) ? Op : getOperand(0);
516 Op1 = (OpNo == 1) ? Op : getOperand(1);
517 Op2 = (OpNo == 2) ? Op : getOperand(2);
518 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
519 case Instruction::ExtractElement:
520 Op0 = (OpNo == 0) ? Op : getOperand(0);
521 Op1 = (OpNo == 1) ? Op : getOperand(1);
522 return ConstantExpr::getExtractElement(Op0, Op1);
523 case Instruction::ShuffleVector:
524 Op0 = (OpNo == 0) ? Op : getOperand(0);
525 Op1 = (OpNo == 1) ? Op : getOperand(1);
526 Op2 = (OpNo == 2) ? Op : getOperand(2);
527 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000528 case Instruction::GetElementPtr: {
529 std::vector<Constant*> Ops;
530 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
531 Ops.push_back(getOperand(i));
532 if (OpNo == 0)
533 return ConstantExpr::getGetElementPtr(Op, Ops);
534 Ops[OpNo-1] = Op;
535 return ConstantExpr::getGetElementPtr(getOperand(0), Ops);
536 }
Chris Lattner7c1018a2006-07-14 19:37:40 +0000537 default:
538 assert(getNumOperands() == 2 && "Must be binary operator?");
Chris Lattner227816342006-07-14 22:20:01 +0000539 Op0 = (OpNo == 0) ? Op : getOperand(0);
540 Op1 = (OpNo == 1) ? Op : getOperand(1);
541 return ConstantExpr::get(getOpcode(), Op0, Op1);
542 }
543}
544
545/// getWithOperands - This returns the current constant expression with the
546/// operands replaced with the specified values. The specified operands must
547/// match count and type with the existing ones.
548Constant *ConstantExpr::
549getWithOperands(const std::vector<Constant*> &Ops) const {
550 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
551 bool AnyChange = false;
552 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
553 assert(Ops[i]->getType() == getOperand(i)->getType() &&
554 "Operand type mismatch!");
555 AnyChange |= Ops[i] != getOperand(i);
556 }
557 if (!AnyChange) // No operands changed, return self.
558 return const_cast<ConstantExpr*>(this);
559
560 switch (getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000561 case Instruction::Trunc:
562 case Instruction::ZExt:
563 case Instruction::SExt:
564 case Instruction::FPTrunc:
565 case Instruction::FPExt:
566 case Instruction::UIToFP:
567 case Instruction::SIToFP:
568 case Instruction::FPToUI:
569 case Instruction::FPToSI:
570 case Instruction::PtrToInt:
571 case Instruction::IntToPtr:
572 case Instruction::BitCast:
573 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
Chris Lattner227816342006-07-14 22:20:01 +0000574 case Instruction::Select:
575 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
576 case Instruction::InsertElement:
577 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
578 case Instruction::ExtractElement:
579 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
580 case Instruction::ShuffleVector:
581 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
582 case Instruction::GetElementPtr: {
583 std::vector<Constant*> ActualOps(Ops.begin()+1, Ops.end());
584 return ConstantExpr::getGetElementPtr(Ops[0], ActualOps);
585 }
586 default:
587 assert(getNumOperands() == 2 && "Must be binary operator?");
588 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000589 }
590}
591
Chris Lattner2f7c9632001-06-06 20:29:01 +0000592
593//===----------------------------------------------------------------------===//
Chris Lattner2f7c9632001-06-06 20:29:01 +0000594// isValueValidForType implementations
595
Reid Spencere0fc4df2006-10-20 07:07:24 +0000596bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
Chris Lattner6b727592004-06-17 18:19:28 +0000597 switch (Ty->getTypeID()) {
Chris Lattner2f7c9632001-06-06 20:29:01 +0000598 default:
599 return false; // These can't be represented as integers!!!
Chris Lattner2f7c9632001-06-06 20:29:01 +0000600 // Signed types...
601 case Type::SByteTyID:
602 return (Val <= INT8_MAX && Val >= INT8_MIN);
Reid Spencere0fc4df2006-10-20 07:07:24 +0000603 case Type::UByteTyID:
604 return (Val >= 0) && (Val <= UINT8_MAX);
Chris Lattner2f7c9632001-06-06 20:29:01 +0000605 case Type::ShortTyID:
606 return (Val <= INT16_MAX && Val >= INT16_MIN);
Reid Spencere0fc4df2006-10-20 07:07:24 +0000607 case Type::UShortTyID:
608 return (Val >= 0) && (Val <= UINT16_MAX);
Chris Lattner2f7c9632001-06-06 20:29:01 +0000609 case Type::IntTyID:
Chris Lattner74248512004-06-08 23:21:39 +0000610 return (Val <= int(INT32_MAX) && Val >= int(INT32_MIN));
Chris Lattner2f7c9632001-06-06 20:29:01 +0000611 case Type::UIntTyID:
Reid Spencere0fc4df2006-10-20 07:07:24 +0000612 return (Val >= 0) && (Val <= UINT32_MAX);
613 case Type::LongTyID:
Chris Lattner2f7c9632001-06-06 20:29:01 +0000614 case Type::ULongTyID:
Reid Spencere0fc4df2006-10-20 07:07:24 +0000615 return true; // always true, has to fit in largest type
Chris Lattner2f7c9632001-06-06 20:29:01 +0000616 }
Chris Lattner2f7c9632001-06-06 20:29:01 +0000617}
618
Chris Lattner3462ae32001-12-03 22:26:30 +0000619bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
Chris Lattner6b727592004-06-17 18:19:28 +0000620 switch (Ty->getTypeID()) {
Chris Lattner2f7c9632001-06-06 20:29:01 +0000621 default:
622 return false; // These can't be represented as floating point!
623
Reid Spencerb95f8ab2004-12-07 07:38:08 +0000624 // TODO: Figure out how to test if a double can be cast to a float!
Chris Lattner2f7c9632001-06-06 20:29:01 +0000625 case Type::FloatTyID:
Chris Lattner2f7c9632001-06-06 20:29:01 +0000626 case Type::DoubleTyID:
627 return true; // This is the largest type...
628 }
Chris Lattneraa2372562006-05-24 17:04:05 +0000629}
Chris Lattner9655e542001-07-20 19:16:02 +0000630
Chris Lattner49d855c2001-09-07 16:46:31 +0000631//===----------------------------------------------------------------------===//
Chris Lattner49d855c2001-09-07 16:46:31 +0000632// Factory Function Implementation
633
Chris Lattner98fa07b2003-05-23 20:03:32 +0000634// ConstantCreator - A class that is used to create constants by
635// ValueMap*. This class should be partially specialized if there is
636// something strange that needs to be done to interface to the ctor for the
637// constant.
638//
Chris Lattner189d19f2003-11-21 20:23:48 +0000639namespace llvm {
640 template<class ConstantClass, class TypeClass, class ValType>
Chris Lattner02157b02006-06-28 21:38:54 +0000641 struct VISIBILITY_HIDDEN ConstantCreator {
Chris Lattner189d19f2003-11-21 20:23:48 +0000642 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
643 return new ConstantClass(Ty, V);
644 }
645 };
Misha Brukmanb1c93172005-04-21 23:48:37 +0000646
Chris Lattner189d19f2003-11-21 20:23:48 +0000647 template<class ConstantClass, class TypeClass>
Chris Lattner02157b02006-06-28 21:38:54 +0000648 struct VISIBILITY_HIDDEN ConvertConstantType {
Chris Lattner189d19f2003-11-21 20:23:48 +0000649 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
650 assert(0 && "This type cannot be converted!\n");
651 abort();
652 }
653 };
Chris Lattnerb50d1352003-10-05 00:17:43 +0000654
Chris Lattner935aa922005-10-04 17:48:46 +0000655 template<class ValType, class TypeClass, class ConstantClass,
656 bool HasLargeKey = false /*true for arrays and structs*/ >
Chris Lattner02157b02006-06-28 21:38:54 +0000657 class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
Chris Lattnerb64419a2005-10-03 22:51:37 +0000658 public:
Jim Laskeyc03caef2006-07-17 17:38:29 +0000659 typedef std::pair<const Type*, ValType> MapKey;
660 typedef std::map<MapKey, Constant *> MapTy;
661 typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
662 typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
Chris Lattnerb64419a2005-10-03 22:51:37 +0000663 private:
Chris Lattner5bbf60a52005-10-04 16:52:46 +0000664 /// Map - This is the main map from the element descriptor to the Constants.
665 /// This is the primary way we avoid creating two of the same shape
666 /// constant.
Chris Lattnerb50d1352003-10-05 00:17:43 +0000667 MapTy Map;
Chris Lattner935aa922005-10-04 17:48:46 +0000668
669 /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
670 /// from the constants to their element in Map. This is important for
671 /// removal of constants from the array, which would otherwise have to scan
672 /// through the map with very large keys.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000673 InverseMapTy InverseMap;
Chris Lattnerb50d1352003-10-05 00:17:43 +0000674
Jim Laskeyc03caef2006-07-17 17:38:29 +0000675 /// AbstractTypeMap - Map for abstract type constants.
676 ///
Chris Lattnerb50d1352003-10-05 00:17:43 +0000677 AbstractTypeMapTy AbstractTypeMap;
Chris Lattner99a669b2004-11-19 16:39:44 +0000678
Chris Lattner99a669b2004-11-19 16:39:44 +0000679 private:
680 void clear(std::vector<Constant *> &Constants) {
Jim Laskeyc03caef2006-07-17 17:38:29 +0000681 for(typename MapTy::iterator I = Map.begin(); I != Map.end(); ++I)
Chris Lattner99a669b2004-11-19 16:39:44 +0000682 Constants.push_back(I->second);
683 Map.clear();
684 AbstractTypeMap.clear();
Chris Lattner935aa922005-10-04 17:48:46 +0000685 InverseMap.clear();
Chris Lattner99a669b2004-11-19 16:39:44 +0000686 }
687
Chris Lattner98fa07b2003-05-23 20:03:32 +0000688 public:
Jim Laskeyc03caef2006-07-17 17:38:29 +0000689 typename MapTy::iterator map_end() { return Map.end(); }
Chris Lattnerb64419a2005-10-03 22:51:37 +0000690
691 /// InsertOrGetItem - Return an iterator for the specified element.
692 /// If the element exists in the map, the returned iterator points to the
693 /// entry and Exists=true. If not, the iterator points to the newly
694 /// inserted entry and returns Exists=false. Newly inserted entries have
695 /// I->second == 0, and should be filled in.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000696 typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
697 &InsertVal,
Chris Lattnerb64419a2005-10-03 22:51:37 +0000698 bool &Exists) {
Jim Laskeyc03caef2006-07-17 17:38:29 +0000699 std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
Chris Lattnerb64419a2005-10-03 22:51:37 +0000700 Exists = !IP.second;
701 return IP.first;
702 }
Chris Lattner5bbf60a52005-10-04 16:52:46 +0000703
Chris Lattner935aa922005-10-04 17:48:46 +0000704private:
Jim Laskeyc03caef2006-07-17 17:38:29 +0000705 typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
Chris Lattner935aa922005-10-04 17:48:46 +0000706 if (HasLargeKey) {
Jim Laskeyc03caef2006-07-17 17:38:29 +0000707 typename InverseMapTy::iterator IMI = InverseMap.find(CP);
Chris Lattner935aa922005-10-04 17:48:46 +0000708 assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
709 IMI->second->second == CP &&
710 "InverseMap corrupt!");
711 return IMI->second;
712 }
713
Jim Laskeyc03caef2006-07-17 17:38:29 +0000714 typename MapTy::iterator I =
Chris Lattner935aa922005-10-04 17:48:46 +0000715 Map.find(MapKey((TypeClass*)CP->getRawType(), getValType(CP)));
Chris Lattner5bbf60a52005-10-04 16:52:46 +0000716 if (I == Map.end() || I->second != CP) {
717 // FIXME: This should not use a linear scan. If this gets to be a
718 // performance problem, someone should look at this.
719 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
720 /* empty */;
721 }
Chris Lattner935aa922005-10-04 17:48:46 +0000722 return I;
723 }
724public:
725
Chris Lattnerb64419a2005-10-03 22:51:37 +0000726 /// getOrCreate - Return the specified constant from the map, creating it if
727 /// necessary.
Chris Lattner98fa07b2003-05-23 20:03:32 +0000728 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
Chris Lattnerb50d1352003-10-05 00:17:43 +0000729 MapKey Lookup(Ty, V);
Jim Laskeyc03caef2006-07-17 17:38:29 +0000730 typename MapTy::iterator I = Map.lower_bound(Lookup);
Reid Spencere0fc4df2006-10-20 07:07:24 +0000731 // Is it in the map?
Chris Lattner98fa07b2003-05-23 20:03:32 +0000732 if (I != Map.end() && I->first == Lookup)
Reid Spencere0fc4df2006-10-20 07:07:24 +0000733 return static_cast<ConstantClass *>(I->second);
Chris Lattner98fa07b2003-05-23 20:03:32 +0000734
735 // If no preexisting value, create one now...
736 ConstantClass *Result =
737 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
738
Chris Lattnerb50d1352003-10-05 00:17:43 +0000739 /// FIXME: why does this assert fail when loading 176.gcc?
740 //assert(Result->getType() == Ty && "Type specified is not correct!");
741 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
742
Chris Lattner935aa922005-10-04 17:48:46 +0000743 if (HasLargeKey) // Remember the reverse mapping if needed.
744 InverseMap.insert(std::make_pair(Result, I));
745
Chris Lattnerb50d1352003-10-05 00:17:43 +0000746 // If the type of the constant is abstract, make sure that an entry exists
747 // for it in the AbstractTypeMap.
748 if (Ty->isAbstract()) {
749 typename AbstractTypeMapTy::iterator TI =
750 AbstractTypeMap.lower_bound(Ty);
751
752 if (TI == AbstractTypeMap.end() || TI->first != Ty) {
753 // Add ourselves to the ATU list of the type.
754 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
755
756 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
757 }
758 }
Chris Lattner98fa07b2003-05-23 20:03:32 +0000759 return Result;
760 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000761
Chris Lattner98fa07b2003-05-23 20:03:32 +0000762 void remove(ConstantClass *CP) {
Jim Laskeyc03caef2006-07-17 17:38:29 +0000763 typename MapTy::iterator I = FindExistingElement(CP);
Chris Lattnerb50d1352003-10-05 00:17:43 +0000764 assert(I != Map.end() && "Constant not found in constant table!");
Chris Lattner3e650af2004-08-04 04:48:01 +0000765 assert(I->second == CP && "Didn't find correct element?");
Chris Lattnerb50d1352003-10-05 00:17:43 +0000766
Chris Lattner935aa922005-10-04 17:48:46 +0000767 if (HasLargeKey) // Remember the reverse mapping if needed.
768 InverseMap.erase(CP);
769
Chris Lattnerb50d1352003-10-05 00:17:43 +0000770 // Now that we found the entry, make sure this isn't the entry that
771 // the AbstractTypeMap points to.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000772 const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
Chris Lattnerb50d1352003-10-05 00:17:43 +0000773 if (Ty->isAbstract()) {
774 assert(AbstractTypeMap.count(Ty) &&
775 "Abstract type not in AbstractTypeMap?");
Jim Laskeyc03caef2006-07-17 17:38:29 +0000776 typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
Chris Lattnerb50d1352003-10-05 00:17:43 +0000777 if (ATMEntryIt == I) {
778 // Yes, we are removing the representative entry for this type.
779 // See if there are any other entries of the same type.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000780 typename MapTy::iterator TmpIt = ATMEntryIt;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000781
Chris Lattnerb50d1352003-10-05 00:17:43 +0000782 // First check the entry before this one...
783 if (TmpIt != Map.begin()) {
784 --TmpIt;
785 if (TmpIt->first.first != Ty) // Not the same type, move back...
786 ++TmpIt;
787 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000788
Chris Lattnerb50d1352003-10-05 00:17:43 +0000789 // If we didn't find the same type, try to move forward...
790 if (TmpIt == ATMEntryIt) {
791 ++TmpIt;
792 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
793 --TmpIt; // No entry afterwards with the same type
794 }
795
796 // If there is another entry in the map of the same abstract type,
797 // update the AbstractTypeMap entry now.
798 if (TmpIt != ATMEntryIt) {
799 ATMEntryIt = TmpIt;
800 } else {
801 // Otherwise, we are removing the last instance of this type
802 // from the table. Remove from the ATM, and from user list.
803 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
804 AbstractTypeMap.erase(Ty);
805 }
Chris Lattner98fa07b2003-05-23 20:03:32 +0000806 }
Chris Lattnerb50d1352003-10-05 00:17:43 +0000807 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000808
Chris Lattnerb50d1352003-10-05 00:17:43 +0000809 Map.erase(I);
810 }
811
Chris Lattner3b793c62005-10-04 21:35:50 +0000812
813 /// MoveConstantToNewSlot - If we are about to change C to be the element
814 /// specified by I, update our internal data structures to reflect this
815 /// fact.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000816 void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
Chris Lattner3b793c62005-10-04 21:35:50 +0000817 // First, remove the old location of the specified constant in the map.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000818 typename MapTy::iterator OldI = FindExistingElement(C);
Chris Lattner3b793c62005-10-04 21:35:50 +0000819 assert(OldI != Map.end() && "Constant not found in constant table!");
820 assert(OldI->second == C && "Didn't find correct element?");
821
822 // If this constant is the representative element for its abstract type,
823 // update the AbstractTypeMap so that the representative element is I.
824 if (C->getType()->isAbstract()) {
825 typename AbstractTypeMapTy::iterator ATI =
826 AbstractTypeMap.find(C->getType());
827 assert(ATI != AbstractTypeMap.end() &&
828 "Abstract type not in AbstractTypeMap?");
829 if (ATI->second == OldI)
830 ATI->second = I;
831 }
832
833 // Remove the old entry from the map.
834 Map.erase(OldI);
835
836 // Update the inverse map so that we know that this constant is now
837 // located at descriptor I.
838 if (HasLargeKey) {
839 assert(I->second == C && "Bad inversemap entry!");
840 InverseMap[C] = I;
841 }
842 }
843
Chris Lattnerb50d1352003-10-05 00:17:43 +0000844 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
Misha Brukmanb1c93172005-04-21 23:48:37 +0000845 typename AbstractTypeMapTy::iterator I =
Jim Laskeyc03caef2006-07-17 17:38:29 +0000846 AbstractTypeMap.find(cast<Type>(OldTy));
Chris Lattnerb50d1352003-10-05 00:17:43 +0000847
848 assert(I != AbstractTypeMap.end() &&
849 "Abstract type not in AbstractTypeMap?");
850
851 // Convert a constant at a time until the last one is gone. The last one
852 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
853 // eliminated eventually.
854 do {
855 ConvertConstantType<ConstantClass,
Jim Laskeyc03caef2006-07-17 17:38:29 +0000856 TypeClass>::convert(
857 static_cast<ConstantClass *>(I->second->second),
Chris Lattnerb50d1352003-10-05 00:17:43 +0000858 cast<TypeClass>(NewTy));
859
Jim Laskeyc03caef2006-07-17 17:38:29 +0000860 I = AbstractTypeMap.find(cast<Type>(OldTy));
Chris Lattnerb50d1352003-10-05 00:17:43 +0000861 } while (I != AbstractTypeMap.end());
862 }
863
864 // If the type became concrete without being refined to any other existing
865 // type, we just remove ourselves from the ATU list.
866 void typeBecameConcrete(const DerivedType *AbsTy) {
867 AbsTy->removeAbstractTypeUser(this);
868 }
869
870 void dump() const {
Bill Wendling6a462f12006-11-17 08:03:48 +0000871 DOUT << "Constant.cpp: ValueMap\n";
Chris Lattner98fa07b2003-05-23 20:03:32 +0000872 }
873 };
874}
875
Chris Lattnera84df0a22006-09-28 23:36:21 +0000876
877//---- ConstantBool::get*() implementation.
878
879ConstantBool *ConstantBool::getTrue() {
880 static ConstantBool *T = 0;
881 if (T) return T;
882 return T = new ConstantBool(true);
883}
884ConstantBool *ConstantBool::getFalse() {
885 static ConstantBool *F = 0;
886 if (F) return F;
887 return F = new ConstantBool(false);
888}
889
Reid Spencere0fc4df2006-10-20 07:07:24 +0000890//---- ConstantInt::get() implementations...
Chris Lattner49d855c2001-09-07 16:46:31 +0000891//
Reid Spencere0fc4df2006-10-20 07:07:24 +0000892static ManagedStatic<ValueMap<uint64_t, Type, ConstantInt> > IntConstants;
Chris Lattner49d855c2001-09-07 16:46:31 +0000893
Reid Spencere0fc4df2006-10-20 07:07:24 +0000894// Get a ConstantInt from an int64_t. Note here that we canoncialize the value
895// to a uint64_t value that has been zero extended down to the size of the
896// integer type of the ConstantInt. This allows the getZExtValue method to
897// just return the stored value while getSExtValue has to convert back to sign
898// extended. getZExtValue is more common in LLVM than getSExtValue().
899ConstantInt *ConstantInt::get(const Type *Ty, int64_t V) {
Chris Lattnerf16661c2006-12-01 19:20:02 +0000900 return IntConstants->getOrCreate(Ty, V & Ty->getIntegralTypeMask());
901}
902
903ConstantIntegral *ConstantIntegral::get(const Type *Ty, int64_t V) {
904 if (Ty == Type::BoolTy) return ConstantBool::get(V&1);
905 return IntConstants->getOrCreate(Ty, V & Ty->getIntegralTypeMask());
Chris Lattner49d855c2001-09-07 16:46:31 +0000906}
907
Chris Lattner3462ae32001-12-03 22:26:30 +0000908//---- ConstantFP::get() implementation...
Chris Lattner49d855c2001-09-07 16:46:31 +0000909//
Chris Lattnerac80ea42004-02-01 22:49:04 +0000910namespace llvm {
911 template<>
912 struct ConstantCreator<ConstantFP, Type, uint64_t> {
913 static ConstantFP *create(const Type *Ty, uint64_t V) {
914 assert(Ty == Type::DoubleTy);
Jim Laskeyb74c6662005-08-17 19:34:49 +0000915 return new ConstantFP(Ty, BitsToDouble(V));
Chris Lattnerac80ea42004-02-01 22:49:04 +0000916 }
917 };
918 template<>
919 struct ConstantCreator<ConstantFP, Type, uint32_t> {
920 static ConstantFP *create(const Type *Ty, uint32_t V) {
921 assert(Ty == Type::FloatTy);
Jim Laskeyb74c6662005-08-17 19:34:49 +0000922 return new ConstantFP(Ty, BitsToFloat(V));
Chris Lattnerac80ea42004-02-01 22:49:04 +0000923 }
924 };
925}
926
Chris Lattner69edc982006-09-28 00:35:06 +0000927static ManagedStatic<ValueMap<uint64_t, Type, ConstantFP> > DoubleConstants;
928static ManagedStatic<ValueMap<uint32_t, Type, ConstantFP> > FloatConstants;
Chris Lattner49d855c2001-09-07 16:46:31 +0000929
Jim Laskey8ad8f712005-08-17 20:06:22 +0000930bool ConstantFP::isNullValue() const {
931 return DoubleToBits(Val) == 0;
932}
933
934bool ConstantFP::isExactlyValue(double V) const {
935 return DoubleToBits(V) == DoubleToBits(Val);
936}
937
938
Chris Lattner3462ae32001-12-03 22:26:30 +0000939ConstantFP *ConstantFP::get(const Type *Ty, double V) {
Chris Lattner241ed4c2004-01-23 00:55:21 +0000940 if (Ty == Type::FloatTy) {
941 // Force the value through memory to normalize it.
Chris Lattner69edc982006-09-28 00:35:06 +0000942 return FloatConstants->getOrCreate(Ty, FloatToBits(V));
Chris Lattnerac80ea42004-02-01 22:49:04 +0000943 } else {
944 assert(Ty == Type::DoubleTy);
Chris Lattner69edc982006-09-28 00:35:06 +0000945 return DoubleConstants->getOrCreate(Ty, DoubleToBits(V));
Chris Lattner241ed4c2004-01-23 00:55:21 +0000946 }
Chris Lattner49d855c2001-09-07 16:46:31 +0000947}
948
Chris Lattner9fba3da2004-02-15 05:53:04 +0000949//---- ConstantAggregateZero::get() implementation...
950//
951namespace llvm {
952 // ConstantAggregateZero does not take extra "value" argument...
953 template<class ValType>
954 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
955 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
956 return new ConstantAggregateZero(Ty);
957 }
958 };
959
960 template<>
961 struct ConvertConstantType<ConstantAggregateZero, Type> {
962 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
963 // Make everyone now use a constant of the new type...
964 Constant *New = ConstantAggregateZero::get(NewTy);
965 assert(New != OldC && "Didn't replace constant??");
966 OldC->uncheckedReplaceAllUsesWith(New);
967 OldC->destroyConstant(); // This constant is now dead, destroy it.
968 }
969 };
970}
971
Chris Lattner69edc982006-09-28 00:35:06 +0000972static ManagedStatic<ValueMap<char, Type,
973 ConstantAggregateZero> > AggZeroConstants;
Chris Lattner9fba3da2004-02-15 05:53:04 +0000974
Chris Lattner3e650af2004-08-04 04:48:01 +0000975static char getValType(ConstantAggregateZero *CPZ) { return 0; }
976
Chris Lattner9fba3da2004-02-15 05:53:04 +0000977Constant *ConstantAggregateZero::get(const Type *Ty) {
Chris Lattnerbfd0b6d2006-06-10 04:16:23 +0000978 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<PackedType>(Ty)) &&
979 "Cannot create an aggregate zero of non-aggregate type!");
Chris Lattner69edc982006-09-28 00:35:06 +0000980 return AggZeroConstants->getOrCreate(Ty, 0);
Chris Lattner9fba3da2004-02-15 05:53:04 +0000981}
982
983// destroyConstant - Remove the constant from the constant table...
984//
985void ConstantAggregateZero::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +0000986 AggZeroConstants->remove(this);
Chris Lattner9fba3da2004-02-15 05:53:04 +0000987 destroyConstantImpl();
988}
989
Chris Lattner3462ae32001-12-03 22:26:30 +0000990//---- ConstantArray::get() implementation...
Chris Lattner49d855c2001-09-07 16:46:31 +0000991//
Chris Lattner189d19f2003-11-21 20:23:48 +0000992namespace llvm {
993 template<>
994 struct ConvertConstantType<ConstantArray, ArrayType> {
995 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
996 // Make everyone now use a constant of the new type...
997 std::vector<Constant*> C;
998 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
999 C.push_back(cast<Constant>(OldC->getOperand(i)));
1000 Constant *New = ConstantArray::get(NewTy, C);
1001 assert(New != OldC && "Didn't replace constant??");
1002 OldC->uncheckedReplaceAllUsesWith(New);
1003 OldC->destroyConstant(); // This constant is now dead, destroy it.
1004 }
1005 };
1006}
Chris Lattnerb50d1352003-10-05 00:17:43 +00001007
Chris Lattner3e650af2004-08-04 04:48:01 +00001008static std::vector<Constant*> getValType(ConstantArray *CA) {
1009 std::vector<Constant*> Elements;
1010 Elements.reserve(CA->getNumOperands());
1011 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1012 Elements.push_back(cast<Constant>(CA->getOperand(i)));
1013 return Elements;
1014}
1015
Chris Lattnerb64419a2005-10-03 22:51:37 +00001016typedef ValueMap<std::vector<Constant*>, ArrayType,
Chris Lattner935aa922005-10-04 17:48:46 +00001017 ConstantArray, true /*largekey*/> ArrayConstantsTy;
Chris Lattner69edc982006-09-28 00:35:06 +00001018static ManagedStatic<ArrayConstantsTy> ArrayConstants;
Chris Lattner49d855c2001-09-07 16:46:31 +00001019
Chris Lattner015e8212004-02-15 04:14:47 +00001020Constant *ConstantArray::get(const ArrayType *Ty,
Chris Lattner9fba3da2004-02-15 05:53:04 +00001021 const std::vector<Constant*> &V) {
1022 // If this is an all-zero array, return a ConstantAggregateZero object
1023 if (!V.empty()) {
1024 Constant *C = V[0];
1025 if (!C->isNullValue())
Chris Lattner69edc982006-09-28 00:35:06 +00001026 return ArrayConstants->getOrCreate(Ty, V);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001027 for (unsigned i = 1, e = V.size(); i != e; ++i)
1028 if (V[i] != C)
Chris Lattner69edc982006-09-28 00:35:06 +00001029 return ArrayConstants->getOrCreate(Ty, V);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001030 }
1031 return ConstantAggregateZero::get(Ty);
Chris Lattner49d855c2001-09-07 16:46:31 +00001032}
1033
Chris Lattner98fa07b2003-05-23 20:03:32 +00001034// destroyConstant - Remove the constant from the constant table...
1035//
1036void ConstantArray::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001037 ArrayConstants->remove(this);
Chris Lattner98fa07b2003-05-23 20:03:32 +00001038 destroyConstantImpl();
1039}
1040
Reid Spencer6f614532006-05-30 08:23:18 +00001041/// ConstantArray::get(const string&) - Return an array that is initialized to
1042/// contain the specified string. If length is zero then a null terminator is
1043/// added to the specified string so that it may be used in a natural way.
1044/// Otherwise, the length parameter specifies how much of the string to use
1045/// and it won't be null terminated.
1046///
Reid Spencer82ebaba2006-05-30 18:15:07 +00001047Constant *ConstantArray::get(const std::string &Str, bool AddNull) {
Chris Lattner7f74a562002-01-20 22:54:45 +00001048 std::vector<Constant*> ElementVals;
Reid Spencer82ebaba2006-05-30 18:15:07 +00001049 for (unsigned i = 0; i < Str.length(); ++i)
Reid Spencere0fc4df2006-10-20 07:07:24 +00001050 ElementVals.push_back(ConstantInt::get(Type::SByteTy, Str[i]));
Chris Lattner8f80fe02001-10-14 23:54:12 +00001051
1052 // Add a null terminator to the string...
Reid Spencer82ebaba2006-05-30 18:15:07 +00001053 if (AddNull) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00001054 ElementVals.push_back(ConstantInt::get(Type::SByteTy, 0));
Reid Spencer6f614532006-05-30 08:23:18 +00001055 }
Chris Lattner8f80fe02001-10-14 23:54:12 +00001056
Reid Spencer82ebaba2006-05-30 18:15:07 +00001057 ArrayType *ATy = ArrayType::get(Type::SByteTy, ElementVals.size());
Chris Lattner3462ae32001-12-03 22:26:30 +00001058 return ConstantArray::get(ATy, ElementVals);
Vikram S. Adve34410432001-10-14 23:17:20 +00001059}
1060
Chris Lattnere8dfcca2004-01-14 17:06:38 +00001061/// isString - This method returns true if the array is an array of sbyte or
1062/// ubyte, and if the elements of the array are all ConstantInt's.
1063bool ConstantArray::isString() const {
1064 // Check the element type for sbyte or ubyte...
Chris Lattnere8701f62004-01-14 17:51:53 +00001065 if (getType()->getElementType() != Type::UByteTy &&
Chris Lattnere8dfcca2004-01-14 17:06:38 +00001066 getType()->getElementType() != Type::SByteTy)
1067 return false;
1068 // Check the elements to make sure they are all integers, not constant
1069 // expressions.
1070 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1071 if (!isa<ConstantInt>(getOperand(i)))
1072 return false;
1073 return true;
1074}
1075
Evan Cheng3763c5b2006-10-26 19:15:05 +00001076/// isCString - This method returns true if the array is a string (see
1077/// isString) and it ends in a null byte \0 and does not contains any other
1078/// null bytes except its terminator.
1079bool ConstantArray::isCString() const {
Evan Chenge974da62006-10-26 21:48:03 +00001080 // Check the element type for sbyte or ubyte...
1081 if (getType()->getElementType() != Type::UByteTy &&
1082 getType()->getElementType() != Type::SByteTy)
1083 return false;
1084 Constant *Zero = Constant::getNullValue(getOperand(0)->getType());
1085 // Last element must be a null.
1086 if (getOperand(getNumOperands()-1) != Zero)
1087 return false;
1088 // Other elements must be non-null integers.
1089 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1090 if (!isa<ConstantInt>(getOperand(i)))
Evan Cheng3763c5b2006-10-26 19:15:05 +00001091 return false;
Evan Chenge974da62006-10-26 21:48:03 +00001092 if (getOperand(i) == Zero)
1093 return false;
1094 }
Evan Cheng3763c5b2006-10-26 19:15:05 +00001095 return true;
1096}
1097
1098
Chris Lattner81fabb02002-08-26 17:53:56 +00001099// getAsString - If the sub-element type of this array is either sbyte or ubyte,
1100// then this method converts the array to an std::string and returns it.
1101// Otherwise, it asserts out.
1102//
1103std::string ConstantArray::getAsString() const {
Chris Lattnere8dfcca2004-01-14 17:06:38 +00001104 assert(isString() && "Not a string!");
Chris Lattner81fabb02002-08-26 17:53:56 +00001105 std::string Result;
Chris Lattner6077c312003-07-23 15:22:26 +00001106 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
Reid Spencere0fc4df2006-10-20 07:07:24 +00001107 Result += (char)cast<ConstantInt>(getOperand(i))->getZExtValue();
Chris Lattner81fabb02002-08-26 17:53:56 +00001108 return Result;
1109}
1110
1111
Chris Lattner3462ae32001-12-03 22:26:30 +00001112//---- ConstantStruct::get() implementation...
Chris Lattner49d855c2001-09-07 16:46:31 +00001113//
Chris Lattnerb50d1352003-10-05 00:17:43 +00001114
Chris Lattner189d19f2003-11-21 20:23:48 +00001115namespace llvm {
1116 template<>
1117 struct ConvertConstantType<ConstantStruct, StructType> {
1118 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1119 // Make everyone now use a constant of the new type...
1120 std::vector<Constant*> C;
1121 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1122 C.push_back(cast<Constant>(OldC->getOperand(i)));
1123 Constant *New = ConstantStruct::get(NewTy, C);
1124 assert(New != OldC && "Didn't replace constant??");
Misha Brukmanb1c93172005-04-21 23:48:37 +00001125
Chris Lattner189d19f2003-11-21 20:23:48 +00001126 OldC->uncheckedReplaceAllUsesWith(New);
1127 OldC->destroyConstant(); // This constant is now dead, destroy it.
1128 }
1129 };
1130}
Chris Lattnerb50d1352003-10-05 00:17:43 +00001131
Chris Lattner8760ec72005-10-04 01:17:50 +00001132typedef ValueMap<std::vector<Constant*>, StructType,
Chris Lattner935aa922005-10-04 17:48:46 +00001133 ConstantStruct, true /*largekey*/> StructConstantsTy;
Chris Lattner69edc982006-09-28 00:35:06 +00001134static ManagedStatic<StructConstantsTy> StructConstants;
Chris Lattner49d855c2001-09-07 16:46:31 +00001135
Chris Lattner3e650af2004-08-04 04:48:01 +00001136static std::vector<Constant*> getValType(ConstantStruct *CS) {
1137 std::vector<Constant*> Elements;
1138 Elements.reserve(CS->getNumOperands());
1139 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1140 Elements.push_back(cast<Constant>(CS->getOperand(i)));
1141 return Elements;
1142}
1143
Chris Lattner015e8212004-02-15 04:14:47 +00001144Constant *ConstantStruct::get(const StructType *Ty,
1145 const std::vector<Constant*> &V) {
Chris Lattner9fba3da2004-02-15 05:53:04 +00001146 // Create a ConstantAggregateZero value if all elements are zeros...
1147 for (unsigned i = 0, e = V.size(); i != e; ++i)
1148 if (!V[i]->isNullValue())
Chris Lattner69edc982006-09-28 00:35:06 +00001149 return StructConstants->getOrCreate(Ty, V);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001150
1151 return ConstantAggregateZero::get(Ty);
Chris Lattner49d855c2001-09-07 16:46:31 +00001152}
Chris Lattner883ad0b2001-10-03 15:39:36 +00001153
Chris Lattnerd6108ca2004-07-12 20:35:11 +00001154Constant *ConstantStruct::get(const std::vector<Constant*> &V) {
1155 std::vector<const Type*> StructEls;
1156 StructEls.reserve(V.size());
1157 for (unsigned i = 0, e = V.size(); i != e; ++i)
1158 StructEls.push_back(V[i]->getType());
1159 return get(StructType::get(StructEls), V);
1160}
1161
Chris Lattnerd7a73302001-10-13 06:57:33 +00001162// destroyConstant - Remove the constant from the constant table...
Chris Lattner883ad0b2001-10-03 15:39:36 +00001163//
Chris Lattner3462ae32001-12-03 22:26:30 +00001164void ConstantStruct::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001165 StructConstants->remove(this);
Chris Lattnerd7a73302001-10-13 06:57:33 +00001166 destroyConstantImpl();
1167}
Chris Lattner883ad0b2001-10-03 15:39:36 +00001168
Brian Gaeke02209042004-08-20 06:00:58 +00001169//---- ConstantPacked::get() implementation...
1170//
1171namespace llvm {
1172 template<>
1173 struct ConvertConstantType<ConstantPacked, PackedType> {
1174 static void convert(ConstantPacked *OldC, const PackedType *NewTy) {
1175 // Make everyone now use a constant of the new type...
1176 std::vector<Constant*> C;
1177 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1178 C.push_back(cast<Constant>(OldC->getOperand(i)));
1179 Constant *New = ConstantPacked::get(NewTy, C);
1180 assert(New != OldC && "Didn't replace constant??");
1181 OldC->uncheckedReplaceAllUsesWith(New);
1182 OldC->destroyConstant(); // This constant is now dead, destroy it.
1183 }
1184 };
1185}
1186
1187static std::vector<Constant*> getValType(ConstantPacked *CP) {
1188 std::vector<Constant*> Elements;
1189 Elements.reserve(CP->getNumOperands());
1190 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1191 Elements.push_back(CP->getOperand(i));
1192 return Elements;
1193}
1194
Chris Lattner69edc982006-09-28 00:35:06 +00001195static ManagedStatic<ValueMap<std::vector<Constant*>, PackedType,
1196 ConstantPacked> > PackedConstants;
Brian Gaeke02209042004-08-20 06:00:58 +00001197
1198Constant *ConstantPacked::get(const PackedType *Ty,
1199 const std::vector<Constant*> &V) {
1200 // If this is an all-zero packed, return a ConstantAggregateZero object
1201 if (!V.empty()) {
1202 Constant *C = V[0];
1203 if (!C->isNullValue())
Chris Lattner69edc982006-09-28 00:35:06 +00001204 return PackedConstants->getOrCreate(Ty, V);
Brian Gaeke02209042004-08-20 06:00:58 +00001205 for (unsigned i = 1, e = V.size(); i != e; ++i)
1206 if (V[i] != C)
Chris Lattner69edc982006-09-28 00:35:06 +00001207 return PackedConstants->getOrCreate(Ty, V);
Brian Gaeke02209042004-08-20 06:00:58 +00001208 }
1209 return ConstantAggregateZero::get(Ty);
1210}
1211
1212Constant *ConstantPacked::get(const std::vector<Constant*> &V) {
1213 assert(!V.empty() && "Cannot infer type if V is empty");
1214 return get(PackedType::get(V.front()->getType(),V.size()), V);
1215}
1216
1217// destroyConstant - Remove the constant from the constant table...
1218//
1219void ConstantPacked::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001220 PackedConstants->remove(this);
Brian Gaeke02209042004-08-20 06:00:58 +00001221 destroyConstantImpl();
1222}
1223
Chris Lattner3462ae32001-12-03 22:26:30 +00001224//---- ConstantPointerNull::get() implementation...
Chris Lattnerd7a73302001-10-13 06:57:33 +00001225//
Chris Lattner98fa07b2003-05-23 20:03:32 +00001226
Chris Lattner189d19f2003-11-21 20:23:48 +00001227namespace llvm {
1228 // ConstantPointerNull does not take extra "value" argument...
1229 template<class ValType>
1230 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1231 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1232 return new ConstantPointerNull(Ty);
1233 }
1234 };
Chris Lattner98fa07b2003-05-23 20:03:32 +00001235
Chris Lattner189d19f2003-11-21 20:23:48 +00001236 template<>
1237 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1238 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1239 // Make everyone now use a constant of the new type...
1240 Constant *New = ConstantPointerNull::get(NewTy);
1241 assert(New != OldC && "Didn't replace constant??");
1242 OldC->uncheckedReplaceAllUsesWith(New);
1243 OldC->destroyConstant(); // This constant is now dead, destroy it.
1244 }
1245 };
1246}
Chris Lattnerb50d1352003-10-05 00:17:43 +00001247
Chris Lattner69edc982006-09-28 00:35:06 +00001248static ManagedStatic<ValueMap<char, PointerType,
1249 ConstantPointerNull> > NullPtrConstants;
Chris Lattnerd7a73302001-10-13 06:57:33 +00001250
Chris Lattner3e650af2004-08-04 04:48:01 +00001251static char getValType(ConstantPointerNull *) {
1252 return 0;
1253}
1254
1255
Chris Lattner3462ae32001-12-03 22:26:30 +00001256ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
Chris Lattner69edc982006-09-28 00:35:06 +00001257 return NullPtrConstants->getOrCreate(Ty, 0);
Chris Lattner883ad0b2001-10-03 15:39:36 +00001258}
1259
Chris Lattner0c6e0b92002-08-18 00:40:04 +00001260// destroyConstant - Remove the constant from the constant table...
1261//
1262void ConstantPointerNull::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001263 NullPtrConstants->remove(this);
Chris Lattner0c6e0b92002-08-18 00:40:04 +00001264 destroyConstantImpl();
1265}
1266
1267
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001268//---- UndefValue::get() implementation...
1269//
1270
1271namespace llvm {
1272 // UndefValue does not take extra "value" argument...
1273 template<class ValType>
1274 struct ConstantCreator<UndefValue, Type, ValType> {
1275 static UndefValue *create(const Type *Ty, const ValType &V) {
1276 return new UndefValue(Ty);
1277 }
1278 };
1279
1280 template<>
1281 struct ConvertConstantType<UndefValue, Type> {
1282 static void convert(UndefValue *OldC, const Type *NewTy) {
1283 // Make everyone now use a constant of the new type.
1284 Constant *New = UndefValue::get(NewTy);
1285 assert(New != OldC && "Didn't replace constant??");
1286 OldC->uncheckedReplaceAllUsesWith(New);
1287 OldC->destroyConstant(); // This constant is now dead, destroy it.
1288 }
1289 };
1290}
1291
Chris Lattner69edc982006-09-28 00:35:06 +00001292static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001293
1294static char getValType(UndefValue *) {
1295 return 0;
1296}
1297
1298
1299UndefValue *UndefValue::get(const Type *Ty) {
Chris Lattner69edc982006-09-28 00:35:06 +00001300 return UndefValueConstants->getOrCreate(Ty, 0);
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001301}
1302
1303// destroyConstant - Remove the constant from the constant table.
1304//
1305void UndefValue::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001306 UndefValueConstants->remove(this);
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001307 destroyConstantImpl();
1308}
1309
1310
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001311//---- ConstantExpr::get() implementations...
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001312//
Reid Spenceree3c9912006-12-04 05:19:50 +00001313struct ExprMapKeyType {
1314 explicit ExprMapKeyType(unsigned opc, std::vector<Constant*> ops,
Reid Spencerdba6aa42006-12-04 18:38:05 +00001315 unsigned short pred = 0) : opcode(opc), predicate(pred), operands(ops) { }
1316 uint16_t opcode;
1317 uint16_t predicate;
Reid Spenceree3c9912006-12-04 05:19:50 +00001318 std::vector<Constant*> operands;
Reid Spenceree3c9912006-12-04 05:19:50 +00001319 bool operator==(const ExprMapKeyType& that) const {
1320 return this->opcode == that.opcode &&
1321 this->predicate == that.predicate &&
1322 this->operands == that.operands;
1323 }
1324 bool operator<(const ExprMapKeyType & that) const {
1325 return this->opcode < that.opcode ||
1326 (this->opcode == that.opcode && this->predicate < that.predicate) ||
1327 (this->opcode == that.opcode && this->predicate == that.predicate &&
1328 this->operands < that.operands);
1329 }
1330
1331 bool operator!=(const ExprMapKeyType& that) const {
1332 return !(*this == that);
1333 }
1334};
Chris Lattner98fa07b2003-05-23 20:03:32 +00001335
Chris Lattner189d19f2003-11-21 20:23:48 +00001336namespace llvm {
1337 template<>
1338 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
Reid Spencer10fbf0e2006-12-03 05:48:19 +00001339 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1340 unsigned short pred = 0) {
Reid Spenceree3c9912006-12-04 05:19:50 +00001341 if (Instruction::isCast(V.opcode))
1342 return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1343 if ((V.opcode >= Instruction::BinaryOpsBegin &&
1344 V.opcode < Instruction::BinaryOpsEnd) ||
1345 V.opcode == Instruction::Shl ||
1346 V.opcode == Instruction::LShr ||
1347 V.opcode == Instruction::AShr)
1348 return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1349 if (V.opcode == Instruction::Select)
1350 return new SelectConstantExpr(V.operands[0], V.operands[1],
1351 V.operands[2]);
1352 if (V.opcode == Instruction::ExtractElement)
1353 return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1354 if (V.opcode == Instruction::InsertElement)
1355 return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1356 V.operands[2]);
1357 if (V.opcode == Instruction::ShuffleVector)
1358 return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1359 V.operands[2]);
1360 if (V.opcode == Instruction::GetElementPtr) {
1361 std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
1362 return new GetElementPtrConstantExpr(V.operands[0], IdxList, Ty);
1363 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001364
Reid Spenceree3c9912006-12-04 05:19:50 +00001365 // The compare instructions are weird. We have to encode the predicate
1366 // value and it is combined with the instruction opcode by multiplying
1367 // the opcode by one hundred. We must decode this to get the predicate.
1368 if (V.opcode == Instruction::ICmp)
1369 return new CompareConstantExpr(Instruction::ICmp, V.predicate,
1370 V.operands[0], V.operands[1]);
1371 if (V.opcode == Instruction::FCmp)
1372 return new CompareConstantExpr(Instruction::FCmp, V.predicate,
1373 V.operands[0], V.operands[1]);
1374 assert(0 && "Invalid ConstantExpr!");
Chris Lattnerb50d1352003-10-05 00:17:43 +00001375 }
Chris Lattner189d19f2003-11-21 20:23:48 +00001376 };
Chris Lattnerb50d1352003-10-05 00:17:43 +00001377
Chris Lattner189d19f2003-11-21 20:23:48 +00001378 template<>
1379 struct ConvertConstantType<ConstantExpr, Type> {
1380 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1381 Constant *New;
1382 switch (OldC->getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001383 case Instruction::Trunc:
1384 case Instruction::ZExt:
1385 case Instruction::SExt:
1386 case Instruction::FPTrunc:
1387 case Instruction::FPExt:
1388 case Instruction::UIToFP:
1389 case Instruction::SIToFP:
1390 case Instruction::FPToUI:
1391 case Instruction::FPToSI:
1392 case Instruction::PtrToInt:
1393 case Instruction::IntToPtr:
1394 case Instruction::BitCast:
1395 New = ConstantExpr::getCast(
1396 OldC->getOpcode(), OldC->getOperand(0), NewTy);
Chris Lattner189d19f2003-11-21 20:23:48 +00001397 break;
Chris Lattner6e415c02004-03-12 05:54:04 +00001398 case Instruction::Select:
1399 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1400 OldC->getOperand(1),
1401 OldC->getOperand(2));
1402 break;
Chris Lattner189d19f2003-11-21 20:23:48 +00001403 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00001404 case Instruction::LShr:
1405 case Instruction::AShr:
Chris Lattner189d19f2003-11-21 20:23:48 +00001406 New = ConstantExpr::getShiftTy(NewTy, OldC->getOpcode(),
1407 OldC->getOperand(0), OldC->getOperand(1));
1408 break;
1409 default:
1410 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
Reid Spencer7eb55b32006-11-02 01:53:59 +00001411 OldC->getOpcode() < Instruction::BinaryOpsEnd);
Chris Lattner189d19f2003-11-21 20:23:48 +00001412 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1413 OldC->getOperand(1));
1414 break;
1415 case Instruction::GetElementPtr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00001416 // Make everyone now use a constant of the new type...
Chris Lattner13128ab2004-10-11 22:52:25 +00001417 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1418 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0), Idx);
Chris Lattner189d19f2003-11-21 20:23:48 +00001419 break;
1420 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001421
Chris Lattner189d19f2003-11-21 20:23:48 +00001422 assert(New != OldC && "Didn't replace constant??");
1423 OldC->uncheckedReplaceAllUsesWith(New);
1424 OldC->destroyConstant(); // This constant is now dead, destroy it.
1425 }
1426 };
1427} // end namespace llvm
Chris Lattnerb50d1352003-10-05 00:17:43 +00001428
1429
Chris Lattner3e650af2004-08-04 04:48:01 +00001430static ExprMapKeyType getValType(ConstantExpr *CE) {
1431 std::vector<Constant*> Operands;
1432 Operands.reserve(CE->getNumOperands());
1433 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1434 Operands.push_back(cast<Constant>(CE->getOperand(i)));
Reid Spenceree3c9912006-12-04 05:19:50 +00001435 return ExprMapKeyType(CE->getOpcode(), Operands,
1436 CE->isCompare() ? CE->getPredicate() : 0);
Chris Lattner3e650af2004-08-04 04:48:01 +00001437}
1438
Chris Lattner69edc982006-09-28 00:35:06 +00001439static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1440 ConstantExpr> > ExprConstants;
Vikram S. Adve4c485332002-07-15 18:19:33 +00001441
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001442/// This is a utility function to handle folding of casts and lookup of the
1443/// cast in the ExprConstants map. It is usedby the various get* methods below.
1444static inline Constant *getFoldedCast(
1445 Instruction::CastOps opc, Constant *C, const Type *Ty) {
Chris Lattner815ae2b2003-10-07 22:19:19 +00001446 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001447 // Fold a few common cases
1448 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1449 return FC;
Chris Lattneracdbe712003-04-17 19:24:48 +00001450
Vikram S. Adve4c485332002-07-15 18:19:33 +00001451 // Look up the constant in the table first to ensure uniqueness
Chris Lattner2b383d2e2003-05-13 21:37:02 +00001452 std::vector<Constant*> argVec(1, C);
Reid Spenceree3c9912006-12-04 05:19:50 +00001453 ExprMapKeyType Key(opc, argVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001454 return ExprConstants->getOrCreate(Ty, Key);
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001455}
Reid Spencerf37dc652006-12-05 19:14:13 +00001456
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001457Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1458 Instruction::CastOps opc = Instruction::CastOps(oc);
1459 assert(Instruction::isCast(opc) && "opcode out of range");
1460 assert(C && Ty && "Null arguments to getCast");
1461 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1462
1463 switch (opc) {
1464 default:
1465 assert(0 && "Invalid cast opcode");
1466 break;
1467 case Instruction::Trunc: return getTrunc(C, Ty);
1468 case Instruction::ZExt: return getZeroExtend(C, Ty);
1469 case Instruction::SExt: return getSignExtend(C, Ty);
1470 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1471 case Instruction::FPExt: return getFPExtend(C, Ty);
1472 case Instruction::UIToFP: return getUIToFP(C, Ty);
1473 case Instruction::SIToFP: return getSIToFP(C, Ty);
1474 case Instruction::FPToUI: return getFPToUI(C, Ty);
1475 case Instruction::FPToSI: return getFPToSI(C, Ty);
1476 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1477 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1478 case Instruction::BitCast: return getBitCast(C, Ty);
Chris Lattner1ece6f82005-01-01 15:59:57 +00001479 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001480 return 0;
Reid Spencerf37dc652006-12-05 19:14:13 +00001481}
1482
1483Constant *ConstantExpr::getCast(Constant *C, const Type *Ty) {
1484 // Note: we can't inline this because it requires the Instructions.h header
1485 return getCast(CastInst::getCastOpcode(
1486 C, C->getType()->isSigned(), Ty, Ty->isSigned()), C, Ty);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001487}
1488
Reid Spencerf37dc652006-12-05 19:14:13 +00001489
Reid Spencer5c140882006-12-04 20:17:56 +00001490Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1491 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1492 return getCast(Instruction::BitCast, C, Ty);
1493 return getCast(Instruction::ZExt, C, Ty);
1494}
1495
1496Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1497 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1498 return getCast(Instruction::BitCast, C, Ty);
1499 return getCast(Instruction::SExt, C, Ty);
1500}
1501
1502Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1503 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1504 return getCast(Instruction::BitCast, C, Ty);
1505 return getCast(Instruction::Trunc, C, Ty);
1506}
1507
Reid Spencerbc245a02006-12-05 03:25:26 +00001508Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1509 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1510 assert((Ty->isIntegral() || Ty->getTypeID() == Type::PointerTyID) &&
1511 "Invalid cast");
1512
1513 if (Ty->isIntegral())
1514 return getCast(Instruction::PtrToInt, S, Ty);
1515 return getCast(Instruction::BitCast, S, 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
1527Constant *ConstantExpr::getSignExtend(Constant *C, const Type *Ty) {
1528 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
1536Constant *ConstantExpr::getZeroExtend(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
Chris Lattnere1496fb2006-09-17 19:14:47 +00001638 if (ReqTy == C1->getType() || (Instruction::isComparison(Opcode) &&
Chris Lattner29ca2c62004-08-04 18:50:09 +00001639 ReqTy == Type::BoolTy))
Chris Lattnerb50d1352003-10-05 00:17:43 +00001640 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1641 return FC; // Fold a few common cases...
Chris Lattneracdbe712003-04-17 19:24:48 +00001642
Chris Lattner2b383d2e2003-05-13 21:37:02 +00001643 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
Reid Spencera009d0d2006-12-04 21:35:24 +00001644 ExprMapKeyType Key(Opcode, argVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001645 return ExprConstants->getOrCreate(ReqTy, Key);
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001646}
1647
Reid Spencera009d0d2006-12-04 21:35:24 +00001648Constant *ConstantExpr::getCompareTy(unsigned Opcode, unsigned short predicate,
1649 Constant *C1, Constant *C2) {
1650 if (Opcode == Instruction::ICmp)
1651 return getICmp(predicate, C1, C2);
1652 return getFCmp(predicate, C1, C2);
1653}
1654
1655Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001656#ifndef NDEBUG
1657 switch (Opcode) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00001658 case Instruction::Add:
1659 case Instruction::Sub:
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001660 case Instruction::Mul:
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001661 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Chris Lattnerc421a262006-01-04 01:01:04 +00001662 assert((C1->getType()->isInteger() || C1->getType()->isFloatingPoint() ||
1663 isa<PackedType>(C1->getType())) &&
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001664 "Tried to create an arithmetic operation on a non-arithmetic type!");
1665 break;
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001666 case Instruction::UDiv:
1667 case Instruction::SDiv:
1668 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1669 assert((C1->getType()->isInteger() || (isa<PackedType>(C1->getType()) &&
1670 cast<PackedType>(C1->getType())->getElementType()->isInteger())) &&
1671 "Tried to create an arithmetic operation on a non-arithmetic type!");
1672 break;
1673 case Instruction::FDiv:
1674 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1675 assert((C1->getType()->isFloatingPoint() || (isa<PackedType>(C1->getType())
1676 && cast<PackedType>(C1->getType())->getElementType()->isFloatingPoint()))
1677 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1678 break;
Reid Spencer7eb55b32006-11-02 01:53:59 +00001679 case Instruction::URem:
1680 case Instruction::SRem:
1681 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1682 assert((C1->getType()->isInteger() || (isa<PackedType>(C1->getType()) &&
1683 cast<PackedType>(C1->getType())->getElementType()->isInteger())) &&
1684 "Tried to create an arithmetic operation on a non-arithmetic type!");
1685 break;
1686 case Instruction::FRem:
1687 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1688 assert((C1->getType()->isFloatingPoint() || (isa<PackedType>(C1->getType())
1689 && cast<PackedType>(C1->getType())->getElementType()->isFloatingPoint()))
1690 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1691 break;
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001692 case Instruction::And:
1693 case Instruction::Or:
1694 case Instruction::Xor:
1695 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Chris Lattnerc421a262006-01-04 01:01:04 +00001696 assert((C1->getType()->isIntegral() || isa<PackedType>(C1->getType())) &&
Misha Brukman3852f652005-01-27 06:46:38 +00001697 "Tried to create a logical operation on a non-integral type!");
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001698 break;
1699 case Instruction::SetLT: case Instruction::SetGT: case Instruction::SetLE:
1700 case Instruction::SetGE: case Instruction::SetEQ: case Instruction::SetNE:
1701 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1702 break;
1703 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00001704 case Instruction::LShr:
1705 case Instruction::AShr:
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001706 assert(C2->getType() == Type::UByteTy && "Shift should be by ubyte!");
Reid Spencerfdff9382006-11-08 06:47:33 +00001707 assert(C1->getType()->isInteger() &&
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001708 "Tried to create a shift operation on a non-integer type!");
1709 break;
1710 default:
1711 break;
1712 }
1713#endif
1714
Reid Spencera009d0d2006-12-04 21:35:24 +00001715 return getTy(C1->getType(), Opcode, C1, C2);
1716}
1717
1718Constant *ConstantExpr::getCompare(unsigned Opcode, unsigned short pred,
1719 Constant *C1, Constant *C2) {
1720 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1721 return getCompareTy(Opcode, pred, C1, C2);
Chris Lattner29ca2c62004-08-04 18:50:09 +00001722}
1723
Chris Lattner6e415c02004-03-12 05:54:04 +00001724Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1725 Constant *V1, Constant *V2) {
1726 assert(C->getType() == Type::BoolTy && "Select condition must be bool!");
1727 assert(V1->getType() == V2->getType() && "Select value types must match!");
1728 assert(V1->getType()->isFirstClassType() && "Cannot select aggregate type!");
1729
1730 if (ReqTy == V1->getType())
1731 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1732 return SC; // Fold common cases
1733
1734 std::vector<Constant*> argVec(3, C);
1735 argVec[1] = V1;
1736 argVec[2] = V2;
Reid Spenceree3c9912006-12-04 05:19:50 +00001737 ExprMapKeyType Key(Instruction::Select, argVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001738 return ExprConstants->getOrCreate(ReqTy, Key);
Chris Lattner6e415c02004-03-12 05:54:04 +00001739}
1740
Chris Lattner9eb2b522004-01-12 19:12:58 +00001741/// getShiftTy - Return a shift left or shift right constant expr
Chris Lattnerb50d1352003-10-05 00:17:43 +00001742Constant *ConstantExpr::getShiftTy(const Type *ReqTy, unsigned Opcode,
1743 Constant *C1, Constant *C2) {
Chris Lattner38a9bcd2003-05-21 17:49:25 +00001744 // Check the operands for consistency first
Reid Spencerfdff9382006-11-08 06:47:33 +00001745 assert((Opcode == Instruction::Shl ||
1746 Opcode == Instruction::LShr ||
1747 Opcode == Instruction::AShr) &&
Chris Lattner38a9bcd2003-05-21 17:49:25 +00001748 "Invalid opcode in binary constant expression");
1749 assert(C1->getType()->isIntegral() && C2->getType() == Type::UByteTy &&
1750 "Invalid operand types for Shift constant expr!");
1751
Chris Lattner0bba7712004-01-12 20:40:42 +00001752 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
Chris Lattner38a9bcd2003-05-21 17:49:25 +00001753 return FC; // Fold a few common cases...
1754
1755 // Look up the constant in the table first to ensure uniqueness
1756 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
Reid Spenceree3c9912006-12-04 05:19:50 +00001757 ExprMapKeyType Key(Opcode, argVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001758 return ExprConstants->getOrCreate(ReqTy, Key);
Chris Lattner38a9bcd2003-05-21 17:49:25 +00001759}
1760
Chris Lattnerb50d1352003-10-05 00:17:43 +00001761Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
Chris Lattner13128ab2004-10-11 22:52:25 +00001762 const std::vector<Value*> &IdxList) {
1763 assert(GetElementPtrInst::getIndexedType(C->getType(), IdxList, true) &&
Chris Lattner04b60fe2004-02-16 20:46:13 +00001764 "GEP indices invalid!");
1765
Chris Lattneracdbe712003-04-17 19:24:48 +00001766 if (Constant *FC = ConstantFoldGetElementPtr(C, IdxList))
1767 return FC; // Fold a few common cases...
Chris Lattner04b60fe2004-02-16 20:46:13 +00001768
Chris Lattnerb50d1352003-10-05 00:17:43 +00001769 assert(isa<PointerType>(C->getType()) &&
Chris Lattner98fa07b2003-05-23 20:03:32 +00001770 "Non-pointer type for constant GetElementPtr expression");
Vikram S. Adve4c485332002-07-15 18:19:33 +00001771 // Look up the constant in the table first to ensure uniqueness
Chris Lattner13128ab2004-10-11 22:52:25 +00001772 std::vector<Constant*> ArgVec;
1773 ArgVec.reserve(IdxList.size()+1);
1774 ArgVec.push_back(C);
1775 for (unsigned i = 0, e = IdxList.size(); i != e; ++i)
1776 ArgVec.push_back(cast<Constant>(IdxList[i]));
Reid Spenceree3c9912006-12-04 05:19:50 +00001777 const ExprMapKeyType Key(Instruction::GetElementPtr,ArgVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001778 return ExprConstants->getOrCreate(ReqTy, Key);
Vikram S. Adve4c485332002-07-15 18:19:33 +00001779}
1780
Chris Lattnerb50d1352003-10-05 00:17:43 +00001781Constant *ConstantExpr::getGetElementPtr(Constant *C,
1782 const std::vector<Constant*> &IdxList){
1783 // Get the result type of the getelementptr!
1784 std::vector<Value*> VIdxList(IdxList.begin(), IdxList.end());
1785
1786 const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), VIdxList,
1787 true);
1788 assert(Ty && "GEP indices invalid!");
Chris Lattner13128ab2004-10-11 22:52:25 +00001789 return getGetElementPtrTy(PointerType::get(Ty), C, VIdxList);
1790}
1791
1792Constant *ConstantExpr::getGetElementPtr(Constant *C,
1793 const std::vector<Value*> &IdxList) {
1794 // Get the result type of the getelementptr!
1795 const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), IdxList,
1796 true);
1797 assert(Ty && "GEP indices invalid!");
Chris Lattnerb50d1352003-10-05 00:17:43 +00001798 return getGetElementPtrTy(PointerType::get(Ty), C, IdxList);
1799}
1800
Reid Spenceree3c9912006-12-04 05:19:50 +00001801Constant *
1802ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1803 assert(LHS->getType() == RHS->getType());
1804 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
1805 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1806
1807 if (Constant *FC = ConstantFoldCompare(Instruction::ICmp, LHS, RHS, pred))
1808 return FC; // Fold a few common cases...
1809
1810 // Look up the constant in the table first to ensure uniqueness
1811 std::vector<Constant*> ArgVec;
1812 ArgVec.push_back(LHS);
1813 ArgVec.push_back(RHS);
1814 // Fake up an opcode value that encodes both the opcode and predicate
1815 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
1816 return ExprConstants->getOrCreate(Type::BoolTy, Key);
1817}
1818
1819Constant *
1820ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1821 assert(LHS->getType() == RHS->getType());
1822 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1823
1824 if (Constant *FC = ConstantFoldCompare(Instruction::FCmp, LHS, RHS, pred))
1825 return FC; // Fold a few common cases...
1826
1827 // Look up the constant in the table first to ensure uniqueness
1828 std::vector<Constant*> ArgVec;
1829 ArgVec.push_back(LHS);
1830 ArgVec.push_back(RHS);
1831 // Fake up an opcode value that encodes both the opcode and predicate
1832 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
1833 return ExprConstants->getOrCreate(Type::BoolTy, Key);
1834}
1835
Robert Bocchino23004482006-01-10 19:05:34 +00001836Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
1837 Constant *Idx) {
Robert Bocchinode7f1c92006-01-10 20:03:46 +00001838 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
1839 return FC; // Fold a few common cases...
Robert Bocchino23004482006-01-10 19:05:34 +00001840 // Look up the constant in the table first to ensure uniqueness
1841 std::vector<Constant*> ArgVec(1, Val);
1842 ArgVec.push_back(Idx);
Reid Spenceree3c9912006-12-04 05:19:50 +00001843 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001844 return ExprConstants->getOrCreate(ReqTy, Key);
Robert Bocchino23004482006-01-10 19:05:34 +00001845}
1846
1847Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
1848 assert(isa<PackedType>(Val->getType()) &&
1849 "Tried to create extractelement operation on non-packed type!");
1850 assert(Idx->getType() == Type::UIntTy &&
Robert Bocchinoca27f032006-01-17 20:07:22 +00001851 "Extractelement index must be uint type!");
Robert Bocchino23004482006-01-10 19:05:34 +00001852 return getExtractElementTy(cast<PackedType>(Val->getType())->getElementType(),
1853 Val, Idx);
1854}
Chris Lattnerb50d1352003-10-05 00:17:43 +00001855
Robert Bocchinoca27f032006-01-17 20:07:22 +00001856Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
1857 Constant *Elt, Constant *Idx) {
1858 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
1859 return FC; // Fold a few common cases...
1860 // Look up the constant in the table first to ensure uniqueness
1861 std::vector<Constant*> ArgVec(1, Val);
1862 ArgVec.push_back(Elt);
1863 ArgVec.push_back(Idx);
Reid Spenceree3c9912006-12-04 05:19:50 +00001864 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001865 return ExprConstants->getOrCreate(ReqTy, Key);
Robert Bocchinoca27f032006-01-17 20:07:22 +00001866}
1867
1868Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1869 Constant *Idx) {
1870 assert(isa<PackedType>(Val->getType()) &&
1871 "Tried to create insertelement operation on non-packed type!");
1872 assert(Elt->getType() == cast<PackedType>(Val->getType())->getElementType()
1873 && "Insertelement types must match!");
1874 assert(Idx->getType() == Type::UIntTy &&
1875 "Insertelement index must be uint type!");
1876 return getInsertElementTy(cast<PackedType>(Val->getType())->getElementType(),
1877 Val, Elt, Idx);
1878}
1879
Chris Lattnerbbe0a422006-04-08 01:18:18 +00001880Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
1881 Constant *V2, Constant *Mask) {
1882 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
1883 return FC; // Fold a few common cases...
1884 // Look up the constant in the table first to ensure uniqueness
1885 std::vector<Constant*> ArgVec(1, V1);
1886 ArgVec.push_back(V2);
1887 ArgVec.push_back(Mask);
Reid Spenceree3c9912006-12-04 05:19:50 +00001888 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001889 return ExprConstants->getOrCreate(ReqTy, Key);
Chris Lattnerbbe0a422006-04-08 01:18:18 +00001890}
1891
1892Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
1893 Constant *Mask) {
1894 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1895 "Invalid shuffle vector constant expr operands!");
1896 return getShuffleVectorTy(V1->getType(), V1, V2, Mask);
1897}
1898
Vikram S. Adve4c485332002-07-15 18:19:33 +00001899// destroyConstant - Remove the constant from the constant table...
1900//
1901void ConstantExpr::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001902 ExprConstants->remove(this);
Vikram S. Adve4c485332002-07-15 18:19:33 +00001903 destroyConstantImpl();
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001904}
1905
Chris Lattner3cd8c562002-07-30 18:54:25 +00001906const char *ConstantExpr::getOpcodeName() const {
1907 return Instruction::getOpcodeName(getOpcode());
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001908}
Reid Spencer1ebe1ab2004-07-17 23:48:33 +00001909
Chris Lattnerc4062ba2005-10-03 21:58:36 +00001910//===----------------------------------------------------------------------===//
1911// replaceUsesOfWithOnConstant implementations
1912
1913void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattner7a1450d2005-10-04 18:13:04 +00001914 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00001915 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
Chris Lattner8760ec72005-10-04 01:17:50 +00001916 Constant *ToC = cast<Constant>(To);
Chris Lattnerdff59112005-10-04 18:47:09 +00001917
1918 unsigned OperandToUpdate = U-OperandList;
1919 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
1920
Jim Laskeyc03caef2006-07-17 17:38:29 +00001921 std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
Chris Lattnerb64419a2005-10-03 22:51:37 +00001922 Lookup.first.first = getType();
1923 Lookup.second = this;
Chris Lattnerdff59112005-10-04 18:47:09 +00001924
Chris Lattnerb64419a2005-10-03 22:51:37 +00001925 std::vector<Constant*> &Values = Lookup.first.second;
1926 Values.reserve(getNumOperands()); // Build replacement array.
Chris Lattnerdff59112005-10-04 18:47:09 +00001927
Chris Lattner8760ec72005-10-04 01:17:50 +00001928 // Fill values with the modified operands of the constant array. Also,
1929 // compute whether this turns into an all-zeros array.
Chris Lattnerdff59112005-10-04 18:47:09 +00001930 bool isAllZeros = false;
1931 if (!ToC->isNullValue()) {
1932 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
1933 Values.push_back(cast<Constant>(O->get()));
1934 } else {
1935 isAllZeros = true;
1936 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1937 Constant *Val = cast<Constant>(O->get());
1938 Values.push_back(Val);
1939 if (isAllZeros) isAllZeros = Val->isNullValue();
1940 }
Chris Lattnerc4062ba2005-10-03 21:58:36 +00001941 }
Chris Lattnerdff59112005-10-04 18:47:09 +00001942 Values[OperandToUpdate] = ToC;
Chris Lattnerc4062ba2005-10-03 21:58:36 +00001943
Chris Lattnerb64419a2005-10-03 22:51:37 +00001944 Constant *Replacement = 0;
1945 if (isAllZeros) {
1946 Replacement = ConstantAggregateZero::get(getType());
1947 } else {
1948 // Check to see if we have this array type already.
1949 bool Exists;
Jim Laskeyc03caef2006-07-17 17:38:29 +00001950 ArrayConstantsTy::MapTy::iterator I =
Chris Lattner69edc982006-09-28 00:35:06 +00001951 ArrayConstants->InsertOrGetItem(Lookup, Exists);
Chris Lattnerb64419a2005-10-03 22:51:37 +00001952
1953 if (Exists) {
1954 Replacement = I->second;
1955 } else {
1956 // Okay, the new shape doesn't exist in the system yet. Instead of
1957 // creating a new constant array, inserting it, replaceallusesof'ing the
1958 // old with the new, then deleting the old... just update the current one
1959 // in place!
Chris Lattner69edc982006-09-28 00:35:06 +00001960 ArrayConstants->MoveConstantToNewSlot(this, I);
Chris Lattnerb64419a2005-10-03 22:51:37 +00001961
Chris Lattnerdff59112005-10-04 18:47:09 +00001962 // Update to the new value.
1963 setOperand(OperandToUpdate, ToC);
Chris Lattnerb64419a2005-10-03 22:51:37 +00001964 return;
1965 }
1966 }
1967
1968 // Otherwise, I do need to replace this with an existing value.
Chris Lattnerc4062ba2005-10-03 21:58:36 +00001969 assert(Replacement != this && "I didn't contain From!");
1970
Chris Lattner7a1450d2005-10-04 18:13:04 +00001971 // Everyone using this now uses the replacement.
1972 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00001973
1974 // Delete the old constant!
1975 destroyConstant();
1976}
1977
1978void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattner7a1450d2005-10-04 18:13:04 +00001979 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00001980 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
Chris Lattner8760ec72005-10-04 01:17:50 +00001981 Constant *ToC = cast<Constant>(To);
1982
Chris Lattnerdff59112005-10-04 18:47:09 +00001983 unsigned OperandToUpdate = U-OperandList;
1984 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
1985
Jim Laskeyc03caef2006-07-17 17:38:29 +00001986 std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
Chris Lattner8760ec72005-10-04 01:17:50 +00001987 Lookup.first.first = getType();
1988 Lookup.second = this;
1989 std::vector<Constant*> &Values = Lookup.first.second;
1990 Values.reserve(getNumOperands()); // Build replacement struct.
Chris Lattnerc4062ba2005-10-03 21:58:36 +00001991
Chris Lattnerdff59112005-10-04 18:47:09 +00001992
Chris Lattner8760ec72005-10-04 01:17:50 +00001993 // Fill values with the modified operands of the constant struct. Also,
1994 // compute whether this turns into an all-zeros struct.
Chris Lattnerdff59112005-10-04 18:47:09 +00001995 bool isAllZeros = false;
1996 if (!ToC->isNullValue()) {
1997 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
1998 Values.push_back(cast<Constant>(O->get()));
1999 } else {
2000 isAllZeros = true;
2001 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2002 Constant *Val = cast<Constant>(O->get());
2003 Values.push_back(Val);
2004 if (isAllZeros) isAllZeros = Val->isNullValue();
2005 }
Chris Lattner8760ec72005-10-04 01:17:50 +00002006 }
Chris Lattnerdff59112005-10-04 18:47:09 +00002007 Values[OperandToUpdate] = ToC;
2008
Chris Lattner8760ec72005-10-04 01:17:50 +00002009 Constant *Replacement = 0;
2010 if (isAllZeros) {
2011 Replacement = ConstantAggregateZero::get(getType());
2012 } else {
2013 // Check to see if we have this array type already.
2014 bool Exists;
Jim Laskeyc03caef2006-07-17 17:38:29 +00002015 StructConstantsTy::MapTy::iterator I =
Chris Lattner69edc982006-09-28 00:35:06 +00002016 StructConstants->InsertOrGetItem(Lookup, Exists);
Chris Lattner8760ec72005-10-04 01:17:50 +00002017
2018 if (Exists) {
2019 Replacement = I->second;
2020 } else {
2021 // Okay, the new shape doesn't exist in the system yet. Instead of
2022 // creating a new constant struct, inserting it, replaceallusesof'ing the
2023 // old with the new, then deleting the old... just update the current one
2024 // in place!
Chris Lattner69edc982006-09-28 00:35:06 +00002025 StructConstants->MoveConstantToNewSlot(this, I);
Chris Lattner8760ec72005-10-04 01:17:50 +00002026
Chris Lattnerdff59112005-10-04 18:47:09 +00002027 // Update to the new value.
2028 setOperand(OperandToUpdate, ToC);
Chris Lattner8760ec72005-10-04 01:17:50 +00002029 return;
2030 }
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002031 }
2032
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002033 assert(Replacement != this && "I didn't contain From!");
2034
Chris Lattner7a1450d2005-10-04 18:13:04 +00002035 // Everyone using this now uses the replacement.
2036 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002037
2038 // Delete the old constant!
2039 destroyConstant();
2040}
2041
2042void ConstantPacked::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002043 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002044 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2045
2046 std::vector<Constant*> Values;
2047 Values.reserve(getNumOperands()); // Build replacement array...
2048 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2049 Constant *Val = getOperand(i);
2050 if (Val == From) Val = cast<Constant>(To);
2051 Values.push_back(Val);
2052 }
2053
2054 Constant *Replacement = ConstantPacked::get(getType(), Values);
2055 assert(Replacement != this && "I didn't contain From!");
2056
Chris Lattner7a1450d2005-10-04 18:13:04 +00002057 // Everyone using this now uses the replacement.
2058 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002059
2060 // Delete the old constant!
2061 destroyConstant();
2062}
2063
2064void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002065 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002066 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2067 Constant *To = cast<Constant>(ToV);
2068
2069 Constant *Replacement = 0;
2070 if (getOpcode() == Instruction::GetElementPtr) {
2071 std::vector<Constant*> Indices;
2072 Constant *Pointer = getOperand(0);
2073 Indices.reserve(getNumOperands()-1);
2074 if (Pointer == From) Pointer = To;
2075
2076 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2077 Constant *Val = getOperand(i);
2078 if (Val == From) Val = To;
2079 Indices.push_back(Val);
2080 }
2081 Replacement = ConstantExpr::getGetElementPtr(Pointer, Indices);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002082 } else if (isCast()) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002083 assert(getOperand(0) == From && "Cast only has one use!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002084 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002085 } else if (getOpcode() == Instruction::Select) {
2086 Constant *C1 = getOperand(0);
2087 Constant *C2 = getOperand(1);
2088 Constant *C3 = getOperand(2);
2089 if (C1 == From) C1 = To;
2090 if (C2 == From) C2 = To;
2091 if (C3 == From) C3 = To;
2092 Replacement = ConstantExpr::getSelect(C1, C2, C3);
Robert Bocchino23004482006-01-10 19:05:34 +00002093 } else if (getOpcode() == Instruction::ExtractElement) {
2094 Constant *C1 = getOperand(0);
2095 Constant *C2 = getOperand(1);
2096 if (C1 == From) C1 = To;
2097 if (C2 == From) C2 = To;
2098 Replacement = ConstantExpr::getExtractElement(C1, C2);
Chris Lattnera93b4b52006-04-08 05:09:48 +00002099 } else if (getOpcode() == Instruction::InsertElement) {
2100 Constant *C1 = getOperand(0);
2101 Constant *C2 = getOperand(1);
2102 Constant *C3 = getOperand(1);
2103 if (C1 == From) C1 = To;
2104 if (C2 == From) C2 = To;
2105 if (C3 == From) C3 = To;
2106 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2107 } else if (getOpcode() == Instruction::ShuffleVector) {
2108 Constant *C1 = getOperand(0);
2109 Constant *C2 = getOperand(1);
2110 Constant *C3 = getOperand(2);
2111 if (C1 == From) C1 = To;
2112 if (C2 == From) C2 = To;
2113 if (C3 == From) C3 = To;
2114 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
Reid Spenceree3c9912006-12-04 05:19:50 +00002115 } else if (isCompare()) {
2116 Constant *C1 = getOperand(0);
2117 Constant *C2 = getOperand(1);
2118 if (C1 == From) C1 = To;
2119 if (C2 == From) C2 = To;
2120 if (getOpcode() == Instruction::ICmp)
2121 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2122 else
2123 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002124 } else if (getNumOperands() == 2) {
2125 Constant *C1 = getOperand(0);
2126 Constant *C2 = getOperand(1);
2127 if (C1 == From) C1 = To;
2128 if (C2 == From) C2 = To;
2129 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2130 } else {
2131 assert(0 && "Unknown ConstantExpr type!");
2132 return;
2133 }
2134
2135 assert(Replacement != this && "I didn't contain From!");
2136
Chris Lattner7a1450d2005-10-04 18:13:04 +00002137 // Everyone using this now uses the replacement.
2138 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002139
2140 // Delete the old constant!
2141 destroyConstant();
2142}
2143
2144
Jim Laskey2698f0d2006-03-08 18:11:07 +00002145/// getStringValue - Turn an LLVM constant pointer that eventually points to a
2146/// global into a string value. Return an empty string if we can't do it.
Evan Cheng38280c02006-03-10 23:52:03 +00002147/// Parameter Chop determines if the result is chopped at the first null
2148/// terminator.
Jim Laskey2698f0d2006-03-08 18:11:07 +00002149///
Evan Cheng38280c02006-03-10 23:52:03 +00002150std::string Constant::getStringValue(bool Chop, unsigned Offset) {
Jim Laskey2698f0d2006-03-08 18:11:07 +00002151 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(this)) {
2152 if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
2153 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
2154 if (Init->isString()) {
2155 std::string Result = Init->getAsString();
2156 if (Offset < Result.size()) {
2157 // If we are pointing INTO The string, erase the beginning...
2158 Result.erase(Result.begin(), Result.begin()+Offset);
2159
2160 // Take off the null terminator, and any string fragments after it.
Evan Cheng38280c02006-03-10 23:52:03 +00002161 if (Chop) {
2162 std::string::size_type NullPos = Result.find_first_of((char)0);
2163 if (NullPos != std::string::npos)
2164 Result.erase(Result.begin()+NullPos, Result.end());
2165 }
Jim Laskey2698f0d2006-03-08 18:11:07 +00002166 return Result;
2167 }
2168 }
2169 }
2170 } else if (Constant *C = dyn_cast<Constant>(this)) {
2171 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
Evan Cheng2c5e5302006-03-11 00:13:10 +00002172 return GV->getStringValue(Chop, Offset);
Jim Laskey2698f0d2006-03-08 18:11:07 +00002173 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2174 if (CE->getOpcode() == Instruction::GetElementPtr) {
2175 // Turn a gep into the specified offset.
2176 if (CE->getNumOperands() == 3 &&
2177 cast<Constant>(CE->getOperand(1))->isNullValue() &&
2178 isa<ConstantInt>(CE->getOperand(2))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002179 Offset += cast<ConstantInt>(CE->getOperand(2))->getZExtValue();
Evan Cheng2c5e5302006-03-11 00:13:10 +00002180 return CE->getOperand(0)->getStringValue(Chop, Offset);
Jim Laskey2698f0d2006-03-08 18:11:07 +00002181 }
2182 }
2183 }
2184 }
2185 return "";
2186}
2187