blob: 2aa0524dfd0565abb0827e8326dec291a558269c [file] [log] [blame]
Chris Lattner9bc02a42003-05-13 21:37:02 +00001//===-- Constants.cpp - Implement Constant nodes --------------------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-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 Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner00950542001-06-06 20:29:01 +00009//
Chris Lattnere9bb2df2001-12-03 22:26:30 +000010// This file implements the Constant* classes...
Chris Lattner00950542001-06-06 20:29:01 +000011//
12//===----------------------------------------------------------------------===//
13
Chris Lattner31bcdb82002-04-28 19:55:58 +000014#include "llvm/Constants.h"
Chris Lattnercbfd4062004-01-12 21:13:12 +000015#include "ConstantFolding.h"
Chris Lattner00950542001-06-06 20:29:01 +000016#include "llvm/DerivedTypes.h"
Reid Spencer1c9c8e62004-07-17 23:48:33 +000017#include "llvm/GlobalValue.h"
Misha Brukman47b14a42004-07-29 17:30:56 +000018#include "llvm/Instructions.h"
Chris Lattner00950542001-06-06 20:29:01 +000019#include "llvm/SymbolTable.h"
Chris Lattnerf5ec48d2001-10-13 06:57:33 +000020#include "llvm/Module.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000021#include "llvm/ADT/StringExtras.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000022#include "llvm/Support/Compiler.h"
Bill Wendling2e3def12006-11-17 08:03:48 +000023#include "llvm/Support/Debug.h"
Chris Lattner8a94bf12006-09-28 00:35:06 +000024#include "llvm/Support/ManagedStatic.h"
Bill Wendling2e3def12006-11-17 08:03:48 +000025#include "llvm/Support/MathExtras.h"
Chris Lattner00950542001-06-06 20:29:01 +000026#include <algorithm>
Chris Lattner31f84992003-11-21 20:23:48 +000027using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000028
Chris Lattner00950542001-06-06 20:29:01 +000029//===----------------------------------------------------------------------===//
Chris Lattnere9bb2df2001-12-03 22:26:30 +000030// Constant Class
Chris Lattner00950542001-06-06 20:29:01 +000031//===----------------------------------------------------------------------===//
32
Chris Lattnere9bb2df2001-12-03 22:26:30 +000033void Constant::destroyConstantImpl() {
34 // When a Constant is destroyed, there may be lingering
Chris Lattnerf5ec48d2001-10-13 06:57:33 +000035 // references to the constant by other constants in the constant pool. These
Misha Brukmanef6a6a62003-08-21 22:14:26 +000036 // constants are implicitly dependent on the module that is being deleted,
Chris Lattnerf5ec48d2001-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 Lattnere9bb2df2001-12-03 22:26:30 +000039 // Constants) that they are, in fact, invalid now and should be deleted.
Chris Lattnerf5ec48d2001-10-13 06:57:33 +000040 //
41 while (!use_empty()) {
42 Value *V = use_back();
43#ifndef NDEBUG // Only in -g mode...
Chris Lattner6183b922002-07-18 00:14:50 +000044 if (!isa<Constant>(V))
Bill Wendling2e3def12006-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 Lattnerf5ec48d2001-10-13 06:57:33 +000048#endif
Vikram S. Adve345e0cf2002-07-14 23:13:17 +000049 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
Reid Spencer1c9c8e62004-07-17 23:48:33 +000050 Constant *CV = cast<Constant>(V);
51 CV->destroyConstant();
Chris Lattnerf5ec48d2001-10-13 06:57:33 +000052
53 // The constant should remove itself from our use list...
Vikram S. Adve345e0cf2002-07-14 23:13:17 +000054 assert((use_empty() || use_back() != V) && "Constant not removed!");
Chris Lattnerf5ec48d2001-10-13 06:57:33 +000055 }
56
57 // Value has no outstanding references it is safe to delete it now...
58 delete this;
Chris Lattner1d87bcf2001-10-01 20:11:19 +000059}
Chris Lattner00950542001-06-06 20:29:01 +000060
Chris Lattner35b89fa2006-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 Spencer1628cec2006-10-26 06:15:43 +000078 case Instruction::UDiv:
79 case Instruction::SDiv:
80 case Instruction::FDiv:
Reid Spencer0a783f72006-11-02 01:53:59 +000081 case Instruction::URem:
82 case Instruction::SRem:
83 case Instruction::FRem:
Chris Lattner35b89fa2006-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 Lattner9fb96412002-08-13 17:50:20 +000092// Static constructor to create a '0' constant of arbitrary type...
93Constant *Constant::getNullValue(const Type *Ty) {
Chris Lattnerf70c22b2004-06-17 18:19:28 +000094 switch (Ty->getTypeID()) {
Chris Lattner70b06fc2003-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 Spencerb83eb642006-10-20 07:07:24 +0000100 static Constant *NullSByte = ConstantInt::get(Type::SByteTy, 0);
Chris Lattner70b06fc2003-10-03 19:34:51 +0000101 return NullSByte;
102 }
103 case Type::UByteTyID: {
Reid Spencerb83eb642006-10-20 07:07:24 +0000104 static Constant *NullUByte = ConstantInt::get(Type::UByteTy, 0);
Chris Lattner70b06fc2003-10-03 19:34:51 +0000105 return NullUByte;
106 }
107 case Type::ShortTyID: {
Reid Spencerb83eb642006-10-20 07:07:24 +0000108 static Constant *NullShort = ConstantInt::get(Type::ShortTy, 0);
Chris Lattner70b06fc2003-10-03 19:34:51 +0000109 return NullShort;
110 }
111 case Type::UShortTyID: {
Reid Spencerb83eb642006-10-20 07:07:24 +0000112 static Constant *NullUShort = ConstantInt::get(Type::UShortTy, 0);
Chris Lattner70b06fc2003-10-03 19:34:51 +0000113 return NullUShort;
114 }
115 case Type::IntTyID: {
Reid Spencerb83eb642006-10-20 07:07:24 +0000116 static Constant *NullInt = ConstantInt::get(Type::IntTy, 0);
Chris Lattner70b06fc2003-10-03 19:34:51 +0000117 return NullInt;
118 }
119 case Type::UIntTyID: {
Reid Spencerb83eb642006-10-20 07:07:24 +0000120 static Constant *NullUInt = ConstantInt::get(Type::UIntTy, 0);
Chris Lattner70b06fc2003-10-03 19:34:51 +0000121 return NullUInt;
122 }
123 case Type::LongTyID: {
Reid Spencerb83eb642006-10-20 07:07:24 +0000124 static Constant *NullLong = ConstantInt::get(Type::LongTy, 0);
Chris Lattner70b06fc2003-10-03 19:34:51 +0000125 return NullLong;
126 }
127 case Type::ULongTyID: {
Reid Spencerb83eb642006-10-20 07:07:24 +0000128 static Constant *NullULong = ConstantInt::get(Type::ULongTy, 0);
Chris Lattner70b06fc2003-10-03 19:34:51 +0000129 return NullULong;
130 }
Chris Lattner9fb96412002-08-13 17:50:20 +0000131
Chris Lattner70b06fc2003-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 Lattner9fb96412002-08-13 17:50:20 +0000140
Misha Brukmanfd939082005-04-21 23:48:37 +0000141 case Type::PointerTyID:
Chris Lattner9fb96412002-08-13 17:50:20 +0000142 return ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattner70b06fc2003-10-03 19:34:51 +0000143
Chris Lattner40bbeb52004-02-15 05:53:04 +0000144 case Type::StructTyID:
145 case Type::ArrayTyID:
Brian Gaeke715c90b2004-08-20 06:00:58 +0000146 case Type::PackedTyID:
Chris Lattner40bbeb52004-02-15 05:53:04 +0000147 return ConstantAggregateZero::get(Ty);
Chris Lattner9fb96412002-08-13 17:50:20 +0000148 default:
Reid Spencer57f6efc2004-07-04 11:51:24 +0000149 // Function, Label, or Opaque type?
150 assert(!"Cannot create a null constant of that type!");
Chris Lattner9fb96412002-08-13 17:50:20 +0000151 return 0;
152 }
153}
154
Chris Lattner9fb96412002-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 Lattnerf70c22b2004-06-17 18:19:28 +0000158 switch (Ty->getTypeID()) {
Chris Lattner003cbf32006-09-28 23:36:21 +0000159 case Type::BoolTyID: return ConstantBool::getTrue();
Chris Lattner9fb96412002-08-13 17:50:20 +0000160 case Type::SByteTyID:
161 case Type::ShortTyID:
162 case Type::IntTyID:
Reid Spencerb83eb642006-10-20 07:07:24 +0000163 case Type::LongTyID: return ConstantInt::get(Ty, -1);
Chris Lattner9fb96412002-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 Spencerb83eb642006-10-20 07:07:24 +0000173 return ConstantInt::get(Ty, Val);
Chris Lattner9fb96412002-08-13 17:50:20 +0000174 }
Chris Lattner227b86c2002-08-14 17:12:13 +0000175 default: return 0;
Chris Lattner9fb96412002-08-13 17:50:20 +0000176 }
177}
178
Chris Lattner00950542001-06-06 20:29:01 +0000179//===----------------------------------------------------------------------===//
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000180// ConstantXXX Classes
Chris Lattner00950542001-06-06 20:29:01 +0000181//===----------------------------------------------------------------------===//
182
183//===----------------------------------------------------------------------===//
184// Normal Constructors
185
Chris Lattnerdf0ef1d2005-09-27 06:09:08 +0000186ConstantIntegral::ConstantIntegral(const Type *Ty, ValueTy VT, uint64_t V)
Reid Spencerb83eb642006-10-20 07:07:24 +0000187 : Constant(Ty, VT, 0, 0), Val(V) {
Chris Lattner00950542001-06-06 20:29:01 +0000188}
Chris Lattner531daef2001-09-07 16:46:31 +0000189
Chris Lattnerdf0ef1d2005-09-27 06:09:08 +0000190ConstantBool::ConstantBool(bool V)
Reid Spencerb83eb642006-10-20 07:07:24 +0000191 : ConstantIntegral(Type::BoolTy, ConstantBoolVal, uint64_t(V)) {
Chris Lattnerc2dfb8b2004-06-21 12:12:12 +0000192}
193
Reid Spencerb83eb642006-10-20 07:07:24 +0000194ConstantInt::ConstantInt(const Type *Ty, uint64_t V)
195 : ConstantIntegral(Ty, ConstantIntVal, V) {
Chris Lattner00950542001-06-06 20:29:01 +0000196}
197
Chris Lattnere4671472005-01-29 00:34:39 +0000198ConstantFP::ConstantFP(const Type *Ty, double V)
Chris Lattnerdf0ef1d2005-09-27 06:09:08 +0000199 : Constant(Ty, ConstantFPVal, 0, 0) {
Chris Lattner37bf6302001-07-20 19:16:02 +0000200 assert(isValueValidForType(Ty, V) && "Value too large for type!");
Chris Lattner00950542001-06-06 20:29:01 +0000201 Val = V;
202}
203
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000204ConstantArray::ConstantArray(const ArrayType *T,
Chris Lattnere4671472005-01-29 00:34:39 +0000205 const std::vector<Constant*> &V)
Chris Lattnerdf0ef1d2005-09-27 06:09:08 +0000206 : Constant(T, ConstantArrayVal, new Use[V.size()], V.size()) {
Alkis Evlogimenose0de1d62004-09-15 02:32:15 +0000207 assert(V.size() == T->getNumElements() &&
208 "Invalid initializer vector for constant array");
Chris Lattnere4671472005-01-29 00:34:39 +0000209 Use *OL = OperandList;
Chris Lattnerdfdd6c52005-10-03 21:56:24 +0000210 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
211 I != E; ++I, ++OL) {
Chris Lattner71abaab2005-10-07 05:23:36 +0000212 Constant *C = *I;
213 assert((C->getType() == T->getElementType() ||
Alkis Evlogimenoscad90ad2004-09-10 04:16:59 +0000214 (T->isAbstract() &&
Chris Lattner71abaab2005-10-07 05:23:36 +0000215 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
Alkis Evlogimenoscad90ad2004-09-10 04:16:59 +0000216 "Initializer for array element doesn't match array element type!");
Chris Lattner71abaab2005-10-07 05:23:36 +0000217 OL->init(C, this);
Chris Lattner00950542001-06-06 20:29:01 +0000218 }
219}
220
Chris Lattnere4671472005-01-29 00:34:39 +0000221ConstantArray::~ConstantArray() {
222 delete [] OperandList;
223}
224
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000225ConstantStruct::ConstantStruct(const StructType *T,
Chris Lattnere4671472005-01-29 00:34:39 +0000226 const std::vector<Constant*> &V)
Chris Lattnerdf0ef1d2005-09-27 06:09:08 +0000227 : Constant(T, ConstantStructVal, new Use[V.size()], V.size()) {
Chris Lattnerd21cd802004-02-09 04:37:31 +0000228 assert(V.size() == T->getNumElements() &&
Vikram S. Adve345e0cf2002-07-14 23:13:17 +0000229 "Invalid initializer vector for constant structure");
Chris Lattnere4671472005-01-29 00:34:39 +0000230 Use *OL = OperandList;
Chris Lattnerdfdd6c52005-10-03 21:56:24 +0000231 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
232 I != E; ++I, ++OL) {
Chris Lattner71abaab2005-10-07 05:23:36 +0000233 Constant *C = *I;
234 assert((C->getType() == T->getElementType(I-V.begin()) ||
Chris Lattnerdfdd6c52005-10-03 21:56:24 +0000235 ((T->getElementType(I-V.begin())->isAbstract() ||
Chris Lattner71abaab2005-10-07 05:23:36 +0000236 C->getType()->isAbstract()) &&
Chris Lattnerdfdd6c52005-10-03 21:56:24 +0000237 T->getElementType(I-V.begin())->getTypeID() ==
Chris Lattner71abaab2005-10-07 05:23:36 +0000238 C->getType()->getTypeID())) &&
Chris Lattnerb8438892003-06-02 17:42:47 +0000239 "Initializer for struct element doesn't match struct element type!");
Chris Lattner71abaab2005-10-07 05:23:36 +0000240 OL->init(C, this);
Chris Lattner00950542001-06-06 20:29:01 +0000241 }
242}
243
Chris Lattnere4671472005-01-29 00:34:39 +0000244ConstantStruct::~ConstantStruct() {
245 delete [] OperandList;
246}
247
248
Brian Gaeke715c90b2004-08-20 06:00:58 +0000249ConstantPacked::ConstantPacked(const PackedType *T,
Chris Lattnere4671472005-01-29 00:34:39 +0000250 const std::vector<Constant*> &V)
Chris Lattnerdf0ef1d2005-09-27 06:09:08 +0000251 : Constant(T, ConstantPackedVal, new Use[V.size()], V.size()) {
Chris Lattnere4671472005-01-29 00:34:39 +0000252 Use *OL = OperandList;
Chris Lattnerdfdd6c52005-10-03 21:56:24 +0000253 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
254 I != E; ++I, ++OL) {
Chris Lattner71abaab2005-10-07 05:23:36 +0000255 Constant *C = *I;
256 assert((C->getType() == T->getElementType() ||
Alkis Evlogimenoscad90ad2004-09-10 04:16:59 +0000257 (T->isAbstract() &&
Chris Lattner71abaab2005-10-07 05:23:36 +0000258 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
Alkis Evlogimenoscad90ad2004-09-10 04:16:59 +0000259 "Initializer for packed element doesn't match packed element type!");
Chris Lattner71abaab2005-10-07 05:23:36 +0000260 OL->init(C, this);
Brian Gaeke715c90b2004-08-20 06:00:58 +0000261 }
262}
263
Chris Lattnere4671472005-01-29 00:34:39 +0000264ConstantPacked::~ConstantPacked() {
265 delete [] OperandList;
Vikram S. Adve345e0cf2002-07-14 23:13:17 +0000266}
267
Chris Lattner037d2582003-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 Spencer728b6db2006-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 Lattnere4671472005-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 Lattnerf190d382006-06-28 21:38:54 +0000289class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
Chris Lattnere4671472005-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. Adve345e0cf2002-07-14 23:13:17 +0000299
Chris Lattnere4671472005-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 Lattnerf190d382006-06-28 21:38:54 +0000302class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
Chris Lattnere4671472005-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 Bocchinoc152f9c2006-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 Lattnerf190d382006-06-28 21:38:54 +0000316class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
Robert Bocchinob52ee7f2006-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 Bocchinoc152f9c2006-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 Lattnerf190d382006-06-28 21:38:54 +0000330class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
Robert Bocchinoc152f9c2006-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 Lattner00f10232006-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 Lattnerf190d382006-06-28 21:38:54 +0000345class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
Chris Lattner00f10232006-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 Lattnere4671472005-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 Lattnerf190d382006-06-28 21:38:54 +0000359struct VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
Chris Lattnere4671472005-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 Brukmanfd939082005-04-21 23:48:37 +0000369 delete [] OperandList;
Chris Lattnere4671472005-01-29 00:34:39 +0000370 }
371};
Reid Spencer728b6db2006-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)
Reid Spencer6b538cf2006-12-07 04:18:31 +0000381 : ConstantExpr(Type::BoolTy, opc, Ops, 2), predicate(pred) {
Reid Spencer728b6db2006-12-03 05:48:19 +0000382 OperandList[0].init(LHS, this);
383 OperandList[1].init(RHS, this);
384 }
385};
386
387} // end anonymous namespace
Vikram S. Adve345e0cf2002-07-14 23:13:17 +0000388
Reid Spencer3da59db2006-11-27 01:05:10 +0000389
390// Utility function for determining if a ConstantExpr is a CastOp or not. This
391// can't be inline because we don't want to #include Instruction.h into
392// Constant.h
393bool ConstantExpr::isCast() const {
394 return Instruction::isCast(getOpcode());
395}
396
Reid Spencer077d0eb2006-12-04 05:19:50 +0000397bool ConstantExpr::isCompare() const {
398 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
399}
400
Chris Lattner4dcb5402004-03-29 02:37:53 +0000401/// ConstantExpr::get* - Return some common constants without having to
402/// specify the full Instruction::OPCODE identifier.
403///
404Constant *ConstantExpr::getNeg(Constant *C) {
Chris Lattnerd25e3ec2004-03-29 19:51:24 +0000405 if (!C->getType()->isFloatingPoint())
406 return get(Instruction::Sub, getNullValue(C->getType()), C);
407 else
408 return get(Instruction::Sub, ConstantFP::get(C->getType(), -0.0), C);
Chris Lattner4dcb5402004-03-29 02:37:53 +0000409}
410Constant *ConstantExpr::getNot(Constant *C) {
411 assert(isa<ConstantIntegral>(C) && "Cannot NOT a nonintegral type!");
412 return get(Instruction::Xor, C,
413 ConstantIntegral::getAllOnesValue(C->getType()));
414}
415Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
416 return get(Instruction::Add, C1, C2);
417}
418Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
419 return get(Instruction::Sub, C1, C2);
420}
421Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
422 return get(Instruction::Mul, C1, C2);
423}
Reid Spencer1628cec2006-10-26 06:15:43 +0000424Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2) {
425 return get(Instruction::UDiv, C1, C2);
426}
427Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2) {
428 return get(Instruction::SDiv, C1, C2);
429}
430Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
431 return get(Instruction::FDiv, C1, C2);
Chris Lattner4dcb5402004-03-29 02:37:53 +0000432}
Reid Spencer0a783f72006-11-02 01:53:59 +0000433Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
434 return get(Instruction::URem, C1, C2);
435}
436Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
437 return get(Instruction::SRem, C1, C2);
438}
439Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
440 return get(Instruction::FRem, C1, C2);
Chris Lattner4dcb5402004-03-29 02:37:53 +0000441}
442Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
443 return get(Instruction::And, C1, C2);
444}
445Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
446 return get(Instruction::Or, C1, C2);
447}
448Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
449 return get(Instruction::Xor, C1, C2);
450}
451Constant *ConstantExpr::getSetEQ(Constant *C1, Constant *C2) {
452 return get(Instruction::SetEQ, C1, C2);
453}
454Constant *ConstantExpr::getSetNE(Constant *C1, Constant *C2) {
455 return get(Instruction::SetNE, C1, C2);
456}
457Constant *ConstantExpr::getSetLT(Constant *C1, Constant *C2) {
458 return get(Instruction::SetLT, C1, C2);
459}
460Constant *ConstantExpr::getSetGT(Constant *C1, Constant *C2) {
461 return get(Instruction::SetGT, C1, C2);
462}
463Constant *ConstantExpr::getSetLE(Constant *C1, Constant *C2) {
464 return get(Instruction::SetLE, C1, C2);
465}
466Constant *ConstantExpr::getSetGE(Constant *C1, Constant *C2) {
467 return get(Instruction::SetGE, C1, C2);
468}
Reid Spencer728b6db2006-12-03 05:48:19 +0000469unsigned ConstantExpr::getPredicate() const {
470 assert(getOpcode() == Instruction::FCmp || getOpcode() == Instruction::ICmp);
471 return dynamic_cast<const CompareConstantExpr*>(this)->predicate;
472}
Chris Lattner4dcb5402004-03-29 02:37:53 +0000473Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
474 return get(Instruction::Shl, C1, C2);
475}
Reid Spencer3822ff52006-11-08 06:47:33 +0000476Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2) {
477 return get(Instruction::LShr, C1, C2);
Chris Lattner4dcb5402004-03-29 02:37:53 +0000478}
Reid Spencer3822ff52006-11-08 06:47:33 +0000479Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2) {
480 return get(Instruction::AShr, C1, C2);
Chris Lattnerc9710252004-05-25 05:32:43 +0000481}
Chris Lattnerf4ba6c72001-10-03 06:12:09 +0000482
Chris Lattner1fe8f6b2006-07-14 19:37:40 +0000483/// getWithOperandReplaced - Return a constant expression identical to this
484/// one, but with the specified operand set to the specified value.
Reid Spencer3da59db2006-11-27 01:05:10 +0000485Constant *
486ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
Chris Lattner1fe8f6b2006-07-14 19:37:40 +0000487 assert(OpNo < getNumOperands() && "Operand num is out of range!");
488 assert(Op->getType() == getOperand(OpNo)->getType() &&
489 "Replacing operand with value of different type!");
Chris Lattnerb88a7fb2006-07-14 22:20:01 +0000490 if (getOperand(OpNo) == Op)
491 return const_cast<ConstantExpr*>(this);
Chris Lattner1fe8f6b2006-07-14 19:37:40 +0000492
Chris Lattnerb88a7fb2006-07-14 22:20:01 +0000493 Constant *Op0, *Op1, *Op2;
Chris Lattner1fe8f6b2006-07-14 19:37:40 +0000494 switch (getOpcode()) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000495 case Instruction::Trunc:
496 case Instruction::ZExt:
497 case Instruction::SExt:
498 case Instruction::FPTrunc:
499 case Instruction::FPExt:
500 case Instruction::UIToFP:
501 case Instruction::SIToFP:
502 case Instruction::FPToUI:
503 case Instruction::FPToSI:
504 case Instruction::PtrToInt:
505 case Instruction::IntToPtr:
506 case Instruction::BitCast:
507 return ConstantExpr::getCast(getOpcode(), Op, getType());
Chris Lattnerb88a7fb2006-07-14 22:20:01 +0000508 case Instruction::Select:
509 Op0 = (OpNo == 0) ? Op : getOperand(0);
510 Op1 = (OpNo == 1) ? Op : getOperand(1);
511 Op2 = (OpNo == 2) ? Op : getOperand(2);
512 return ConstantExpr::getSelect(Op0, Op1, Op2);
513 case Instruction::InsertElement:
514 Op0 = (OpNo == 0) ? Op : getOperand(0);
515 Op1 = (OpNo == 1) ? Op : getOperand(1);
516 Op2 = (OpNo == 2) ? Op : getOperand(2);
517 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
518 case Instruction::ExtractElement:
519 Op0 = (OpNo == 0) ? Op : getOperand(0);
520 Op1 = (OpNo == 1) ? Op : getOperand(1);
521 return ConstantExpr::getExtractElement(Op0, Op1);
522 case Instruction::ShuffleVector:
523 Op0 = (OpNo == 0) ? Op : getOperand(0);
524 Op1 = (OpNo == 1) ? Op : getOperand(1);
525 Op2 = (OpNo == 2) ? Op : getOperand(2);
526 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattner1fe8f6b2006-07-14 19:37:40 +0000527 case Instruction::GetElementPtr: {
528 std::vector<Constant*> Ops;
529 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
530 Ops.push_back(getOperand(i));
531 if (OpNo == 0)
532 return ConstantExpr::getGetElementPtr(Op, Ops);
533 Ops[OpNo-1] = Op;
534 return ConstantExpr::getGetElementPtr(getOperand(0), Ops);
535 }
Chris Lattner1fe8f6b2006-07-14 19:37:40 +0000536 default:
537 assert(getNumOperands() == 2 && "Must be binary operator?");
Chris Lattnerb88a7fb2006-07-14 22:20:01 +0000538 Op0 = (OpNo == 0) ? Op : getOperand(0);
539 Op1 = (OpNo == 1) ? Op : getOperand(1);
540 return ConstantExpr::get(getOpcode(), Op0, Op1);
541 }
542}
543
544/// getWithOperands - This returns the current constant expression with the
545/// operands replaced with the specified values. The specified operands must
546/// match count and type with the existing ones.
547Constant *ConstantExpr::
548getWithOperands(const std::vector<Constant*> &Ops) const {
549 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
550 bool AnyChange = false;
551 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
552 assert(Ops[i]->getType() == getOperand(i)->getType() &&
553 "Operand type mismatch!");
554 AnyChange |= Ops[i] != getOperand(i);
555 }
556 if (!AnyChange) // No operands changed, return self.
557 return const_cast<ConstantExpr*>(this);
558
559 switch (getOpcode()) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000560 case Instruction::Trunc:
561 case Instruction::ZExt:
562 case Instruction::SExt:
563 case Instruction::FPTrunc:
564 case Instruction::FPExt:
565 case Instruction::UIToFP:
566 case Instruction::SIToFP:
567 case Instruction::FPToUI:
568 case Instruction::FPToSI:
569 case Instruction::PtrToInt:
570 case Instruction::IntToPtr:
571 case Instruction::BitCast:
572 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
Chris Lattnerb88a7fb2006-07-14 22:20:01 +0000573 case Instruction::Select:
574 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
575 case Instruction::InsertElement:
576 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
577 case Instruction::ExtractElement:
578 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
579 case Instruction::ShuffleVector:
580 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
581 case Instruction::GetElementPtr: {
582 std::vector<Constant*> ActualOps(Ops.begin()+1, Ops.end());
583 return ConstantExpr::getGetElementPtr(Ops[0], ActualOps);
584 }
585 default:
586 assert(getNumOperands() == 2 && "Must be binary operator?");
587 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
Chris Lattner1fe8f6b2006-07-14 19:37:40 +0000588 }
589}
590
Chris Lattner00950542001-06-06 20:29:01 +0000591
592//===----------------------------------------------------------------------===//
Chris Lattner00950542001-06-06 20:29:01 +0000593// isValueValidForType implementations
594
Reid Spencerb83eb642006-10-20 07:07:24 +0000595bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000596 switch (Ty->getTypeID()) {
Chris Lattner00950542001-06-06 20:29:01 +0000597 default:
598 return false; // These can't be represented as integers!!!
Chris Lattner00950542001-06-06 20:29:01 +0000599 // Signed types...
600 case Type::SByteTyID:
601 return (Val <= INT8_MAX && Val >= INT8_MIN);
Reid Spencerb83eb642006-10-20 07:07:24 +0000602 case Type::UByteTyID:
603 return (Val >= 0) && (Val <= UINT8_MAX);
Chris Lattner00950542001-06-06 20:29:01 +0000604 case Type::ShortTyID:
605 return (Val <= INT16_MAX && Val >= INT16_MIN);
Reid Spencerb83eb642006-10-20 07:07:24 +0000606 case Type::UShortTyID:
607 return (Val >= 0) && (Val <= UINT16_MAX);
Chris Lattner00950542001-06-06 20:29:01 +0000608 case Type::IntTyID:
Chris Lattner2a502012004-06-08 23:21:39 +0000609 return (Val <= int(INT32_MAX) && Val >= int(INT32_MIN));
Chris Lattner00950542001-06-06 20:29:01 +0000610 case Type::UIntTyID:
Reid Spencerb83eb642006-10-20 07:07:24 +0000611 return (Val >= 0) && (Val <= UINT32_MAX);
612 case Type::LongTyID:
Chris Lattner00950542001-06-06 20:29:01 +0000613 case Type::ULongTyID:
Reid Spencerb83eb642006-10-20 07:07:24 +0000614 return true; // always true, has to fit in largest type
Chris Lattner00950542001-06-06 20:29:01 +0000615 }
Chris Lattner00950542001-06-06 20:29:01 +0000616}
617
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000618bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000619 switch (Ty->getTypeID()) {
Chris Lattner00950542001-06-06 20:29:01 +0000620 default:
621 return false; // These can't be represented as floating point!
622
Reid Spencer574cdb32004-12-07 07:38:08 +0000623 // TODO: Figure out how to test if a double can be cast to a float!
Chris Lattner00950542001-06-06 20:29:01 +0000624 case Type::FloatTyID:
Chris Lattner00950542001-06-06 20:29:01 +0000625 case Type::DoubleTyID:
626 return true; // This is the largest type...
627 }
Chris Lattnerd74ea2b2006-05-24 17:04:05 +0000628}
Chris Lattner37bf6302001-07-20 19:16:02 +0000629
Chris Lattner531daef2001-09-07 16:46:31 +0000630//===----------------------------------------------------------------------===//
Chris Lattner531daef2001-09-07 16:46:31 +0000631// Factory Function Implementation
632
Chris Lattner02ec5ed2003-05-23 20:03:32 +0000633// ConstantCreator - A class that is used to create constants by
634// ValueMap*. This class should be partially specialized if there is
635// something strange that needs to be done to interface to the ctor for the
636// constant.
637//
Chris Lattner31f84992003-11-21 20:23:48 +0000638namespace llvm {
639 template<class ConstantClass, class TypeClass, class ValType>
Chris Lattnerf190d382006-06-28 21:38:54 +0000640 struct VISIBILITY_HIDDEN ConstantCreator {
Chris Lattner31f84992003-11-21 20:23:48 +0000641 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
642 return new ConstantClass(Ty, V);
643 }
644 };
Misha Brukmanfd939082005-04-21 23:48:37 +0000645
Chris Lattner31f84992003-11-21 20:23:48 +0000646 template<class ConstantClass, class TypeClass>
Chris Lattnerf190d382006-06-28 21:38:54 +0000647 struct VISIBILITY_HIDDEN ConvertConstantType {
Chris Lattner31f84992003-11-21 20:23:48 +0000648 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
649 assert(0 && "This type cannot be converted!\n");
650 abort();
651 }
652 };
Chris Lattnered468e372003-10-05 00:17:43 +0000653
Chris Lattnera55b30a2005-10-04 17:48:46 +0000654 template<class ValType, class TypeClass, class ConstantClass,
655 bool HasLargeKey = false /*true for arrays and structs*/ >
Chris Lattnerf190d382006-06-28 21:38:54 +0000656 class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
Chris Lattnercea141f2005-10-03 22:51:37 +0000657 public:
Jim Laskeyede5aa42006-07-17 17:38:29 +0000658 typedef std::pair<const Type*, ValType> MapKey;
659 typedef std::map<MapKey, Constant *> MapTy;
660 typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
661 typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
Chris Lattnercea141f2005-10-03 22:51:37 +0000662 private:
Chris Lattnerd7a3fc62005-10-04 16:52:46 +0000663 /// Map - This is the main map from the element descriptor to the Constants.
664 /// This is the primary way we avoid creating two of the same shape
665 /// constant.
Chris Lattnered468e372003-10-05 00:17:43 +0000666 MapTy Map;
Chris Lattnera55b30a2005-10-04 17:48:46 +0000667
668 /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
669 /// from the constants to their element in Map. This is important for
670 /// removal of constants from the array, which would otherwise have to scan
671 /// through the map with very large keys.
Jim Laskeyede5aa42006-07-17 17:38:29 +0000672 InverseMapTy InverseMap;
Chris Lattnered468e372003-10-05 00:17:43 +0000673
Jim Laskeyede5aa42006-07-17 17:38:29 +0000674 /// AbstractTypeMap - Map for abstract type constants.
675 ///
Chris Lattnered468e372003-10-05 00:17:43 +0000676 AbstractTypeMapTy AbstractTypeMap;
Chris Lattner8a7ad2d2004-11-19 16:39:44 +0000677
Chris Lattner8a7ad2d2004-11-19 16:39:44 +0000678 private:
679 void clear(std::vector<Constant *> &Constants) {
Jim Laskeyede5aa42006-07-17 17:38:29 +0000680 for(typename MapTy::iterator I = Map.begin(); I != Map.end(); ++I)
Chris Lattner8a7ad2d2004-11-19 16:39:44 +0000681 Constants.push_back(I->second);
682 Map.clear();
683 AbstractTypeMap.clear();
Chris Lattnera55b30a2005-10-04 17:48:46 +0000684 InverseMap.clear();
Chris Lattner8a7ad2d2004-11-19 16:39:44 +0000685 }
686
Chris Lattner02ec5ed2003-05-23 20:03:32 +0000687 public:
Jim Laskeyede5aa42006-07-17 17:38:29 +0000688 typename MapTy::iterator map_end() { return Map.end(); }
Chris Lattnercea141f2005-10-03 22:51:37 +0000689
690 /// InsertOrGetItem - Return an iterator for the specified element.
691 /// If the element exists in the map, the returned iterator points to the
692 /// entry and Exists=true. If not, the iterator points to the newly
693 /// inserted entry and returns Exists=false. Newly inserted entries have
694 /// I->second == 0, and should be filled in.
Jim Laskeyede5aa42006-07-17 17:38:29 +0000695 typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
696 &InsertVal,
Chris Lattnercea141f2005-10-03 22:51:37 +0000697 bool &Exists) {
Jim Laskeyede5aa42006-07-17 17:38:29 +0000698 std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
Chris Lattnercea141f2005-10-03 22:51:37 +0000699 Exists = !IP.second;
700 return IP.first;
701 }
Chris Lattnerd7a3fc62005-10-04 16:52:46 +0000702
Chris Lattnera55b30a2005-10-04 17:48:46 +0000703private:
Jim Laskeyede5aa42006-07-17 17:38:29 +0000704 typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
Chris Lattnera55b30a2005-10-04 17:48:46 +0000705 if (HasLargeKey) {
Jim Laskeyede5aa42006-07-17 17:38:29 +0000706 typename InverseMapTy::iterator IMI = InverseMap.find(CP);
Chris Lattnera55b30a2005-10-04 17:48:46 +0000707 assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
708 IMI->second->second == CP &&
709 "InverseMap corrupt!");
710 return IMI->second;
711 }
712
Jim Laskeyede5aa42006-07-17 17:38:29 +0000713 typename MapTy::iterator I =
Chris Lattnera55b30a2005-10-04 17:48:46 +0000714 Map.find(MapKey((TypeClass*)CP->getRawType(), getValType(CP)));
Chris Lattnerd7a3fc62005-10-04 16:52:46 +0000715 if (I == Map.end() || I->second != CP) {
716 // FIXME: This should not use a linear scan. If this gets to be a
717 // performance problem, someone should look at this.
718 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
719 /* empty */;
720 }
Chris Lattnera55b30a2005-10-04 17:48:46 +0000721 return I;
722 }
723public:
724
Chris Lattnercea141f2005-10-03 22:51:37 +0000725 /// getOrCreate - Return the specified constant from the map, creating it if
726 /// necessary.
Chris Lattner02ec5ed2003-05-23 20:03:32 +0000727 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
Chris Lattnered468e372003-10-05 00:17:43 +0000728 MapKey Lookup(Ty, V);
Jim Laskeyede5aa42006-07-17 17:38:29 +0000729 typename MapTy::iterator I = Map.lower_bound(Lookup);
Reid Spencerb83eb642006-10-20 07:07:24 +0000730 // Is it in the map?
Chris Lattner02ec5ed2003-05-23 20:03:32 +0000731 if (I != Map.end() && I->first == Lookup)
Reid Spencerb83eb642006-10-20 07:07:24 +0000732 return static_cast<ConstantClass *>(I->second);
Chris Lattner02ec5ed2003-05-23 20:03:32 +0000733
734 // If no preexisting value, create one now...
735 ConstantClass *Result =
736 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
737
Chris Lattnered468e372003-10-05 00:17:43 +0000738 /// FIXME: why does this assert fail when loading 176.gcc?
739 //assert(Result->getType() == Ty && "Type specified is not correct!");
740 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
741
Chris Lattnera55b30a2005-10-04 17:48:46 +0000742 if (HasLargeKey) // Remember the reverse mapping if needed.
743 InverseMap.insert(std::make_pair(Result, I));
744
Chris Lattnered468e372003-10-05 00:17:43 +0000745 // If the type of the constant is abstract, make sure that an entry exists
746 // for it in the AbstractTypeMap.
747 if (Ty->isAbstract()) {
748 typename AbstractTypeMapTy::iterator TI =
749 AbstractTypeMap.lower_bound(Ty);
750
751 if (TI == AbstractTypeMap.end() || TI->first != Ty) {
752 // Add ourselves to the ATU list of the type.
753 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
754
755 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
756 }
757 }
Chris Lattner02ec5ed2003-05-23 20:03:32 +0000758 return Result;
759 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000760
Chris Lattner02ec5ed2003-05-23 20:03:32 +0000761 void remove(ConstantClass *CP) {
Jim Laskeyede5aa42006-07-17 17:38:29 +0000762 typename MapTy::iterator I = FindExistingElement(CP);
Chris Lattnered468e372003-10-05 00:17:43 +0000763 assert(I != Map.end() && "Constant not found in constant table!");
Chris Lattner6823c9f2004-08-04 04:48:01 +0000764 assert(I->second == CP && "Didn't find correct element?");
Chris Lattnered468e372003-10-05 00:17:43 +0000765
Chris Lattnera55b30a2005-10-04 17:48:46 +0000766 if (HasLargeKey) // Remember the reverse mapping if needed.
767 InverseMap.erase(CP);
768
Chris Lattnered468e372003-10-05 00:17:43 +0000769 // Now that we found the entry, make sure this isn't the entry that
770 // the AbstractTypeMap points to.
Jim Laskeyede5aa42006-07-17 17:38:29 +0000771 const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
Chris Lattnered468e372003-10-05 00:17:43 +0000772 if (Ty->isAbstract()) {
773 assert(AbstractTypeMap.count(Ty) &&
774 "Abstract type not in AbstractTypeMap?");
Jim Laskeyede5aa42006-07-17 17:38:29 +0000775 typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
Chris Lattnered468e372003-10-05 00:17:43 +0000776 if (ATMEntryIt == I) {
777 // Yes, we are removing the representative entry for this type.
778 // See if there are any other entries of the same type.
Jim Laskeyede5aa42006-07-17 17:38:29 +0000779 typename MapTy::iterator TmpIt = ATMEntryIt;
Misha Brukmanfd939082005-04-21 23:48:37 +0000780
Chris Lattnered468e372003-10-05 00:17:43 +0000781 // First check the entry before this one...
782 if (TmpIt != Map.begin()) {
783 --TmpIt;
784 if (TmpIt->first.first != Ty) // Not the same type, move back...
785 ++TmpIt;
786 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000787
Chris Lattnered468e372003-10-05 00:17:43 +0000788 // If we didn't find the same type, try to move forward...
789 if (TmpIt == ATMEntryIt) {
790 ++TmpIt;
791 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
792 --TmpIt; // No entry afterwards with the same type
793 }
794
795 // If there is another entry in the map of the same abstract type,
796 // update the AbstractTypeMap entry now.
797 if (TmpIt != ATMEntryIt) {
798 ATMEntryIt = TmpIt;
799 } else {
800 // Otherwise, we are removing the last instance of this type
801 // from the table. Remove from the ATM, and from user list.
802 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
803 AbstractTypeMap.erase(Ty);
804 }
Chris Lattner02ec5ed2003-05-23 20:03:32 +0000805 }
Chris Lattnered468e372003-10-05 00:17:43 +0000806 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000807
Chris Lattnered468e372003-10-05 00:17:43 +0000808 Map.erase(I);
809 }
810
Chris Lattnera1e3f542005-10-04 21:35:50 +0000811
812 /// MoveConstantToNewSlot - If we are about to change C to be the element
813 /// specified by I, update our internal data structures to reflect this
814 /// fact.
Jim Laskeyede5aa42006-07-17 17:38:29 +0000815 void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
Chris Lattnera1e3f542005-10-04 21:35:50 +0000816 // First, remove the old location of the specified constant in the map.
Jim Laskeyede5aa42006-07-17 17:38:29 +0000817 typename MapTy::iterator OldI = FindExistingElement(C);
Chris Lattnera1e3f542005-10-04 21:35:50 +0000818 assert(OldI != Map.end() && "Constant not found in constant table!");
819 assert(OldI->second == C && "Didn't find correct element?");
820
821 // If this constant is the representative element for its abstract type,
822 // update the AbstractTypeMap so that the representative element is I.
823 if (C->getType()->isAbstract()) {
824 typename AbstractTypeMapTy::iterator ATI =
825 AbstractTypeMap.find(C->getType());
826 assert(ATI != AbstractTypeMap.end() &&
827 "Abstract type not in AbstractTypeMap?");
828 if (ATI->second == OldI)
829 ATI->second = I;
830 }
831
832 // Remove the old entry from the map.
833 Map.erase(OldI);
834
835 // Update the inverse map so that we know that this constant is now
836 // located at descriptor I.
837 if (HasLargeKey) {
838 assert(I->second == C && "Bad inversemap entry!");
839 InverseMap[C] = I;
840 }
841 }
842
Chris Lattnered468e372003-10-05 00:17:43 +0000843 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
Misha Brukmanfd939082005-04-21 23:48:37 +0000844 typename AbstractTypeMapTy::iterator I =
Jim Laskeyede5aa42006-07-17 17:38:29 +0000845 AbstractTypeMap.find(cast<Type>(OldTy));
Chris Lattnered468e372003-10-05 00:17:43 +0000846
847 assert(I != AbstractTypeMap.end() &&
848 "Abstract type not in AbstractTypeMap?");
849
850 // Convert a constant at a time until the last one is gone. The last one
851 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
852 // eliminated eventually.
853 do {
854 ConvertConstantType<ConstantClass,
Jim Laskeyede5aa42006-07-17 17:38:29 +0000855 TypeClass>::convert(
856 static_cast<ConstantClass *>(I->second->second),
Chris Lattnered468e372003-10-05 00:17:43 +0000857 cast<TypeClass>(NewTy));
858
Jim Laskeyede5aa42006-07-17 17:38:29 +0000859 I = AbstractTypeMap.find(cast<Type>(OldTy));
Chris Lattnered468e372003-10-05 00:17:43 +0000860 } while (I != AbstractTypeMap.end());
861 }
862
863 // If the type became concrete without being refined to any other existing
864 // type, we just remove ourselves from the ATU list.
865 void typeBecameConcrete(const DerivedType *AbsTy) {
866 AbsTy->removeAbstractTypeUser(this);
867 }
868
869 void dump() const {
Bill Wendling2e3def12006-11-17 08:03:48 +0000870 DOUT << "Constant.cpp: ValueMap\n";
Chris Lattner02ec5ed2003-05-23 20:03:32 +0000871 }
872 };
873}
874
Chris Lattner003cbf32006-09-28 23:36:21 +0000875
876//---- ConstantBool::get*() implementation.
877
878ConstantBool *ConstantBool::getTrue() {
879 static ConstantBool *T = 0;
880 if (T) return T;
881 return T = new ConstantBool(true);
882}
883ConstantBool *ConstantBool::getFalse() {
884 static ConstantBool *F = 0;
885 if (F) return F;
886 return F = new ConstantBool(false);
887}
888
Reid Spencerb83eb642006-10-20 07:07:24 +0000889//---- ConstantInt::get() implementations...
Chris Lattner531daef2001-09-07 16:46:31 +0000890//
Reid Spencerb83eb642006-10-20 07:07:24 +0000891static ManagedStatic<ValueMap<uint64_t, Type, ConstantInt> > IntConstants;
Chris Lattner531daef2001-09-07 16:46:31 +0000892
Reid Spencerb83eb642006-10-20 07:07:24 +0000893// Get a ConstantInt from an int64_t. Note here that we canoncialize the value
894// to a uint64_t value that has been zero extended down to the size of the
895// integer type of the ConstantInt. This allows the getZExtValue method to
896// just return the stored value while getSExtValue has to convert back to sign
897// extended. getZExtValue is more common in LLVM than getSExtValue().
898ConstantInt *ConstantInt::get(const Type *Ty, int64_t V) {
Chris Lattner68329b22006-12-01 19:20:02 +0000899 return IntConstants->getOrCreate(Ty, V & Ty->getIntegralTypeMask());
900}
901
902ConstantIntegral *ConstantIntegral::get(const Type *Ty, int64_t V) {
903 if (Ty == Type::BoolTy) return ConstantBool::get(V&1);
904 return IntConstants->getOrCreate(Ty, V & Ty->getIntegralTypeMask());
Chris Lattner531daef2001-09-07 16:46:31 +0000905}
906
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000907//---- ConstantFP::get() implementation...
Chris Lattner531daef2001-09-07 16:46:31 +0000908//
Chris Lattnercfdf2412004-02-01 22:49:04 +0000909namespace llvm {
910 template<>
911 struct ConstantCreator<ConstantFP, Type, uint64_t> {
912 static ConstantFP *create(const Type *Ty, uint64_t V) {
913 assert(Ty == Type::DoubleTy);
Jim Laskeycb6682f2005-08-17 19:34:49 +0000914 return new ConstantFP(Ty, BitsToDouble(V));
Chris Lattnercfdf2412004-02-01 22:49:04 +0000915 }
916 };
917 template<>
918 struct ConstantCreator<ConstantFP, Type, uint32_t> {
919 static ConstantFP *create(const Type *Ty, uint32_t V) {
920 assert(Ty == Type::FloatTy);
Jim Laskeycb6682f2005-08-17 19:34:49 +0000921 return new ConstantFP(Ty, BitsToFloat(V));
Chris Lattnercfdf2412004-02-01 22:49:04 +0000922 }
923 };
924}
925
Chris Lattner8a94bf12006-09-28 00:35:06 +0000926static ManagedStatic<ValueMap<uint64_t, Type, ConstantFP> > DoubleConstants;
927static ManagedStatic<ValueMap<uint32_t, Type, ConstantFP> > FloatConstants;
Chris Lattner531daef2001-09-07 16:46:31 +0000928
Jim Laskey3a1eff72005-08-17 20:06:22 +0000929bool ConstantFP::isNullValue() const {
930 return DoubleToBits(Val) == 0;
931}
932
933bool ConstantFP::isExactlyValue(double V) const {
934 return DoubleToBits(V) == DoubleToBits(Val);
935}
936
937
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000938ConstantFP *ConstantFP::get(const Type *Ty, double V) {
Chris Lattner90fb19e2004-01-23 00:55:21 +0000939 if (Ty == Type::FloatTy) {
940 // Force the value through memory to normalize it.
Chris Lattner8a94bf12006-09-28 00:35:06 +0000941 return FloatConstants->getOrCreate(Ty, FloatToBits(V));
Chris Lattnercfdf2412004-02-01 22:49:04 +0000942 } else {
943 assert(Ty == Type::DoubleTy);
Chris Lattner8a94bf12006-09-28 00:35:06 +0000944 return DoubleConstants->getOrCreate(Ty, DoubleToBits(V));
Chris Lattner90fb19e2004-01-23 00:55:21 +0000945 }
Chris Lattner531daef2001-09-07 16:46:31 +0000946}
947
Chris Lattner40bbeb52004-02-15 05:53:04 +0000948//---- ConstantAggregateZero::get() implementation...
949//
950namespace llvm {
951 // ConstantAggregateZero does not take extra "value" argument...
952 template<class ValType>
953 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
954 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
955 return new ConstantAggregateZero(Ty);
956 }
957 };
958
959 template<>
960 struct ConvertConstantType<ConstantAggregateZero, Type> {
961 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
962 // Make everyone now use a constant of the new type...
963 Constant *New = ConstantAggregateZero::get(NewTy);
964 assert(New != OldC && "Didn't replace constant??");
965 OldC->uncheckedReplaceAllUsesWith(New);
966 OldC->destroyConstant(); // This constant is now dead, destroy it.
967 }
968 };
969}
970
Chris Lattner8a94bf12006-09-28 00:35:06 +0000971static ManagedStatic<ValueMap<char, Type,
972 ConstantAggregateZero> > AggZeroConstants;
Chris Lattner40bbeb52004-02-15 05:53:04 +0000973
Chris Lattner6823c9f2004-08-04 04:48:01 +0000974static char getValType(ConstantAggregateZero *CPZ) { return 0; }
975
Chris Lattner40bbeb52004-02-15 05:53:04 +0000976Constant *ConstantAggregateZero::get(const Type *Ty) {
Chris Lattner31d1a2c2006-06-10 04:16:23 +0000977 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<PackedType>(Ty)) &&
978 "Cannot create an aggregate zero of non-aggregate type!");
Chris Lattner8a94bf12006-09-28 00:35:06 +0000979 return AggZeroConstants->getOrCreate(Ty, 0);
Chris Lattner40bbeb52004-02-15 05:53:04 +0000980}
981
982// destroyConstant - Remove the constant from the constant table...
983//
984void ConstantAggregateZero::destroyConstant() {
Chris Lattner8a94bf12006-09-28 00:35:06 +0000985 AggZeroConstants->remove(this);
Chris Lattner40bbeb52004-02-15 05:53:04 +0000986 destroyConstantImpl();
987}
988
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000989//---- ConstantArray::get() implementation...
Chris Lattner531daef2001-09-07 16:46:31 +0000990//
Chris Lattner31f84992003-11-21 20:23:48 +0000991namespace llvm {
992 template<>
993 struct ConvertConstantType<ConstantArray, ArrayType> {
994 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
995 // Make everyone now use a constant of the new type...
996 std::vector<Constant*> C;
997 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
998 C.push_back(cast<Constant>(OldC->getOperand(i)));
999 Constant *New = ConstantArray::get(NewTy, C);
1000 assert(New != OldC && "Didn't replace constant??");
1001 OldC->uncheckedReplaceAllUsesWith(New);
1002 OldC->destroyConstant(); // This constant is now dead, destroy it.
1003 }
1004 };
1005}
Chris Lattnered468e372003-10-05 00:17:43 +00001006
Chris Lattner6823c9f2004-08-04 04:48:01 +00001007static std::vector<Constant*> getValType(ConstantArray *CA) {
1008 std::vector<Constant*> Elements;
1009 Elements.reserve(CA->getNumOperands());
1010 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1011 Elements.push_back(cast<Constant>(CA->getOperand(i)));
1012 return Elements;
1013}
1014
Chris Lattnercea141f2005-10-03 22:51:37 +00001015typedef ValueMap<std::vector<Constant*>, ArrayType,
Chris Lattnera55b30a2005-10-04 17:48:46 +00001016 ConstantArray, true /*largekey*/> ArrayConstantsTy;
Chris Lattner8a94bf12006-09-28 00:35:06 +00001017static ManagedStatic<ArrayConstantsTy> ArrayConstants;
Chris Lattner531daef2001-09-07 16:46:31 +00001018
Chris Lattnerca705fa2004-02-15 04:14:47 +00001019Constant *ConstantArray::get(const ArrayType *Ty,
Chris Lattner40bbeb52004-02-15 05:53:04 +00001020 const std::vector<Constant*> &V) {
1021 // If this is an all-zero array, return a ConstantAggregateZero object
1022 if (!V.empty()) {
1023 Constant *C = V[0];
1024 if (!C->isNullValue())
Chris Lattner8a94bf12006-09-28 00:35:06 +00001025 return ArrayConstants->getOrCreate(Ty, V);
Chris Lattner40bbeb52004-02-15 05:53:04 +00001026 for (unsigned i = 1, e = V.size(); i != e; ++i)
1027 if (V[i] != C)
Chris Lattner8a94bf12006-09-28 00:35:06 +00001028 return ArrayConstants->getOrCreate(Ty, V);
Chris Lattner40bbeb52004-02-15 05:53:04 +00001029 }
1030 return ConstantAggregateZero::get(Ty);
Chris Lattner531daef2001-09-07 16:46:31 +00001031}
1032
Chris Lattner02ec5ed2003-05-23 20:03:32 +00001033// destroyConstant - Remove the constant from the constant table...
1034//
1035void ConstantArray::destroyConstant() {
Chris Lattner8a94bf12006-09-28 00:35:06 +00001036 ArrayConstants->remove(this);
Chris Lattner02ec5ed2003-05-23 20:03:32 +00001037 destroyConstantImpl();
1038}
1039
Reid Spencer89494772006-05-30 08:23:18 +00001040/// ConstantArray::get(const string&) - Return an array that is initialized to
1041/// contain the specified string. If length is zero then a null terminator is
1042/// added to the specified string so that it may be used in a natural way.
1043/// Otherwise, the length parameter specifies how much of the string to use
1044/// and it won't be null terminated.
1045///
Reid Spencer461bed22006-05-30 18:15:07 +00001046Constant *ConstantArray::get(const std::string &Str, bool AddNull) {
Chris Lattner697954c2002-01-20 22:54:45 +00001047 std::vector<Constant*> ElementVals;
Reid Spencer461bed22006-05-30 18:15:07 +00001048 for (unsigned i = 0; i < Str.length(); ++i)
Reid Spencerb83eb642006-10-20 07:07:24 +00001049 ElementVals.push_back(ConstantInt::get(Type::SByteTy, Str[i]));
Chris Lattnerc5bdb242001-10-14 23:54:12 +00001050
1051 // Add a null terminator to the string...
Reid Spencer461bed22006-05-30 18:15:07 +00001052 if (AddNull) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001053 ElementVals.push_back(ConstantInt::get(Type::SByteTy, 0));
Reid Spencer89494772006-05-30 08:23:18 +00001054 }
Chris Lattnerc5bdb242001-10-14 23:54:12 +00001055
Reid Spencer461bed22006-05-30 18:15:07 +00001056 ArrayType *ATy = ArrayType::get(Type::SByteTy, ElementVals.size());
Chris Lattnere9bb2df2001-12-03 22:26:30 +00001057 return ConstantArray::get(ATy, ElementVals);
Vikram S. Advedb2da492001-10-14 23:17:20 +00001058}
1059
Chris Lattner13cfdea2004-01-14 17:06:38 +00001060/// isString - This method returns true if the array is an array of sbyte or
1061/// ubyte, and if the elements of the array are all ConstantInt's.
1062bool ConstantArray::isString() const {
1063 // Check the element type for sbyte or ubyte...
Chris Lattner7aa162b2004-01-14 17:51:53 +00001064 if (getType()->getElementType() != Type::UByteTy &&
Chris Lattner13cfdea2004-01-14 17:06:38 +00001065 getType()->getElementType() != Type::SByteTy)
1066 return false;
1067 // Check the elements to make sure they are all integers, not constant
1068 // expressions.
1069 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1070 if (!isa<ConstantInt>(getOperand(i)))
1071 return false;
1072 return true;
1073}
1074
Evan Cheng22c70302006-10-26 19:15:05 +00001075/// isCString - This method returns true if the array is a string (see
1076/// isString) and it ends in a null byte \0 and does not contains any other
1077/// null bytes except its terminator.
1078bool ConstantArray::isCString() const {
Evan Chengabf63452006-10-26 21:48:03 +00001079 // Check the element type for sbyte or ubyte...
1080 if (getType()->getElementType() != Type::UByteTy &&
1081 getType()->getElementType() != Type::SByteTy)
1082 return false;
1083 Constant *Zero = Constant::getNullValue(getOperand(0)->getType());
1084 // Last element must be a null.
1085 if (getOperand(getNumOperands()-1) != Zero)
1086 return false;
1087 // Other elements must be non-null integers.
1088 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1089 if (!isa<ConstantInt>(getOperand(i)))
Evan Cheng22c70302006-10-26 19:15:05 +00001090 return false;
Evan Chengabf63452006-10-26 21:48:03 +00001091 if (getOperand(i) == Zero)
1092 return false;
1093 }
Evan Cheng22c70302006-10-26 19:15:05 +00001094 return true;
1095}
1096
1097
Chris Lattner93aeea32002-08-26 17:53:56 +00001098// getAsString - If the sub-element type of this array is either sbyte or ubyte,
1099// then this method converts the array to an std::string and returns it.
1100// Otherwise, it asserts out.
1101//
1102std::string ConstantArray::getAsString() const {
Chris Lattner13cfdea2004-01-14 17:06:38 +00001103 assert(isString() && "Not a string!");
Chris Lattner93aeea32002-08-26 17:53:56 +00001104 std::string Result;
Chris Lattnerc07736a2003-07-23 15:22:26 +00001105 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
Reid Spencerb83eb642006-10-20 07:07:24 +00001106 Result += (char)cast<ConstantInt>(getOperand(i))->getZExtValue();
Chris Lattner93aeea32002-08-26 17:53:56 +00001107 return Result;
1108}
1109
1110
Chris Lattnere9bb2df2001-12-03 22:26:30 +00001111//---- ConstantStruct::get() implementation...
Chris Lattner531daef2001-09-07 16:46:31 +00001112//
Chris Lattnered468e372003-10-05 00:17:43 +00001113
Chris Lattner31f84992003-11-21 20:23:48 +00001114namespace llvm {
1115 template<>
1116 struct ConvertConstantType<ConstantStruct, StructType> {
1117 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1118 // Make everyone now use a constant of the new type...
1119 std::vector<Constant*> C;
1120 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1121 C.push_back(cast<Constant>(OldC->getOperand(i)));
1122 Constant *New = ConstantStruct::get(NewTy, C);
1123 assert(New != OldC && "Didn't replace constant??");
Misha Brukmanfd939082005-04-21 23:48:37 +00001124
Chris Lattner31f84992003-11-21 20:23:48 +00001125 OldC->uncheckedReplaceAllUsesWith(New);
1126 OldC->destroyConstant(); // This constant is now dead, destroy it.
1127 }
1128 };
1129}
Chris Lattnered468e372003-10-05 00:17:43 +00001130
Chris Lattnerc182a882005-10-04 01:17:50 +00001131typedef ValueMap<std::vector<Constant*>, StructType,
Chris Lattnera55b30a2005-10-04 17:48:46 +00001132 ConstantStruct, true /*largekey*/> StructConstantsTy;
Chris Lattner8a94bf12006-09-28 00:35:06 +00001133static ManagedStatic<StructConstantsTy> StructConstants;
Chris Lattner531daef2001-09-07 16:46:31 +00001134
Chris Lattner6823c9f2004-08-04 04:48:01 +00001135static std::vector<Constant*> getValType(ConstantStruct *CS) {
1136 std::vector<Constant*> Elements;
1137 Elements.reserve(CS->getNumOperands());
1138 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1139 Elements.push_back(cast<Constant>(CS->getOperand(i)));
1140 return Elements;
1141}
1142
Chris Lattnerca705fa2004-02-15 04:14:47 +00001143Constant *ConstantStruct::get(const StructType *Ty,
1144 const std::vector<Constant*> &V) {
Chris Lattner40bbeb52004-02-15 05:53:04 +00001145 // Create a ConstantAggregateZero value if all elements are zeros...
1146 for (unsigned i = 0, e = V.size(); i != e; ++i)
1147 if (!V[i]->isNullValue())
Chris Lattner8a94bf12006-09-28 00:35:06 +00001148 return StructConstants->getOrCreate(Ty, V);
Chris Lattner40bbeb52004-02-15 05:53:04 +00001149
1150 return ConstantAggregateZero::get(Ty);
Chris Lattner531daef2001-09-07 16:46:31 +00001151}
Chris Lattner6a57baa2001-10-03 15:39:36 +00001152
Andrew Lenharth38ecbf12006-12-08 18:06:16 +00001153Constant *ConstantStruct::get(const std::vector<Constant*> &V, bool packed) {
Chris Lattnerb370c7a2004-07-12 20:35:11 +00001154 std::vector<const Type*> StructEls;
1155 StructEls.reserve(V.size());
1156 for (unsigned i = 0, e = V.size(); i != e; ++i)
1157 StructEls.push_back(V[i]->getType());
Andrew Lenharth38ecbf12006-12-08 18:06:16 +00001158 return get(StructType::get(StructEls, packed), V);
Chris Lattnerb370c7a2004-07-12 20:35:11 +00001159}
1160
Chris Lattnerf5ec48d2001-10-13 06:57:33 +00001161// destroyConstant - Remove the constant from the constant table...
Chris Lattner6a57baa2001-10-03 15:39:36 +00001162//
Chris Lattnere9bb2df2001-12-03 22:26:30 +00001163void ConstantStruct::destroyConstant() {
Chris Lattner8a94bf12006-09-28 00:35:06 +00001164 StructConstants->remove(this);
Chris Lattnerf5ec48d2001-10-13 06:57:33 +00001165 destroyConstantImpl();
1166}
Chris Lattner6a57baa2001-10-03 15:39:36 +00001167
Brian Gaeke715c90b2004-08-20 06:00:58 +00001168//---- ConstantPacked::get() implementation...
1169//
1170namespace llvm {
1171 template<>
1172 struct ConvertConstantType<ConstantPacked, PackedType> {
1173 static void convert(ConstantPacked *OldC, const PackedType *NewTy) {
1174 // Make everyone now use a constant of the new type...
1175 std::vector<Constant*> C;
1176 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1177 C.push_back(cast<Constant>(OldC->getOperand(i)));
1178 Constant *New = ConstantPacked::get(NewTy, C);
1179 assert(New != OldC && "Didn't replace constant??");
1180 OldC->uncheckedReplaceAllUsesWith(New);
1181 OldC->destroyConstant(); // This constant is now dead, destroy it.
1182 }
1183 };
1184}
1185
1186static std::vector<Constant*> getValType(ConstantPacked *CP) {
1187 std::vector<Constant*> Elements;
1188 Elements.reserve(CP->getNumOperands());
1189 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1190 Elements.push_back(CP->getOperand(i));
1191 return Elements;
1192}
1193
Chris Lattner8a94bf12006-09-28 00:35:06 +00001194static ManagedStatic<ValueMap<std::vector<Constant*>, PackedType,
1195 ConstantPacked> > PackedConstants;
Brian Gaeke715c90b2004-08-20 06:00:58 +00001196
1197Constant *ConstantPacked::get(const PackedType *Ty,
1198 const std::vector<Constant*> &V) {
1199 // If this is an all-zero packed, return a ConstantAggregateZero object
1200 if (!V.empty()) {
1201 Constant *C = V[0];
1202 if (!C->isNullValue())
Chris Lattner8a94bf12006-09-28 00:35:06 +00001203 return PackedConstants->getOrCreate(Ty, V);
Brian Gaeke715c90b2004-08-20 06:00:58 +00001204 for (unsigned i = 1, e = V.size(); i != e; ++i)
1205 if (V[i] != C)
Chris Lattner8a94bf12006-09-28 00:35:06 +00001206 return PackedConstants->getOrCreate(Ty, V);
Brian Gaeke715c90b2004-08-20 06:00:58 +00001207 }
1208 return ConstantAggregateZero::get(Ty);
1209}
1210
1211Constant *ConstantPacked::get(const std::vector<Constant*> &V) {
1212 assert(!V.empty() && "Cannot infer type if V is empty");
1213 return get(PackedType::get(V.front()->getType(),V.size()), V);
1214}
1215
1216// destroyConstant - Remove the constant from the constant table...
1217//
1218void ConstantPacked::destroyConstant() {
Chris Lattner8a94bf12006-09-28 00:35:06 +00001219 PackedConstants->remove(this);
Brian Gaeke715c90b2004-08-20 06:00:58 +00001220 destroyConstantImpl();
1221}
1222
Chris Lattnere9bb2df2001-12-03 22:26:30 +00001223//---- ConstantPointerNull::get() implementation...
Chris Lattnerf5ec48d2001-10-13 06:57:33 +00001224//
Chris Lattner02ec5ed2003-05-23 20:03:32 +00001225
Chris Lattner31f84992003-11-21 20:23:48 +00001226namespace llvm {
1227 // ConstantPointerNull does not take extra "value" argument...
1228 template<class ValType>
1229 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1230 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1231 return new ConstantPointerNull(Ty);
1232 }
1233 };
Chris Lattner02ec5ed2003-05-23 20:03:32 +00001234
Chris Lattner31f84992003-11-21 20:23:48 +00001235 template<>
1236 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1237 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1238 // Make everyone now use a constant of the new type...
1239 Constant *New = ConstantPointerNull::get(NewTy);
1240 assert(New != OldC && "Didn't replace constant??");
1241 OldC->uncheckedReplaceAllUsesWith(New);
1242 OldC->destroyConstant(); // This constant is now dead, destroy it.
1243 }
1244 };
1245}
Chris Lattnered468e372003-10-05 00:17:43 +00001246
Chris Lattner8a94bf12006-09-28 00:35:06 +00001247static ManagedStatic<ValueMap<char, PointerType,
1248 ConstantPointerNull> > NullPtrConstants;
Chris Lattnerf5ec48d2001-10-13 06:57:33 +00001249
Chris Lattner6823c9f2004-08-04 04:48:01 +00001250static char getValType(ConstantPointerNull *) {
1251 return 0;
1252}
1253
1254
Chris Lattnere9bb2df2001-12-03 22:26:30 +00001255ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
Chris Lattner8a94bf12006-09-28 00:35:06 +00001256 return NullPtrConstants->getOrCreate(Ty, 0);
Chris Lattner6a57baa2001-10-03 15:39:36 +00001257}
1258
Chris Lattner41661fd2002-08-18 00:40:04 +00001259// destroyConstant - Remove the constant from the constant table...
1260//
1261void ConstantPointerNull::destroyConstant() {
Chris Lattner8a94bf12006-09-28 00:35:06 +00001262 NullPtrConstants->remove(this);
Chris Lattner41661fd2002-08-18 00:40:04 +00001263 destroyConstantImpl();
1264}
1265
1266
Chris Lattnerb9f18592004-10-16 18:07:16 +00001267//---- UndefValue::get() implementation...
1268//
1269
1270namespace llvm {
1271 // UndefValue does not take extra "value" argument...
1272 template<class ValType>
1273 struct ConstantCreator<UndefValue, Type, ValType> {
1274 static UndefValue *create(const Type *Ty, const ValType &V) {
1275 return new UndefValue(Ty);
1276 }
1277 };
1278
1279 template<>
1280 struct ConvertConstantType<UndefValue, Type> {
1281 static void convert(UndefValue *OldC, const Type *NewTy) {
1282 // Make everyone now use a constant of the new type.
1283 Constant *New = UndefValue::get(NewTy);
1284 assert(New != OldC && "Didn't replace constant??");
1285 OldC->uncheckedReplaceAllUsesWith(New);
1286 OldC->destroyConstant(); // This constant is now dead, destroy it.
1287 }
1288 };
1289}
1290
Chris Lattner8a94bf12006-09-28 00:35:06 +00001291static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
Chris Lattnerb9f18592004-10-16 18:07:16 +00001292
1293static char getValType(UndefValue *) {
1294 return 0;
1295}
1296
1297
1298UndefValue *UndefValue::get(const Type *Ty) {
Chris Lattner8a94bf12006-09-28 00:35:06 +00001299 return UndefValueConstants->getOrCreate(Ty, 0);
Chris Lattnerb9f18592004-10-16 18:07:16 +00001300}
1301
1302// destroyConstant - Remove the constant from the constant table.
1303//
1304void UndefValue::destroyConstant() {
Chris Lattner8a94bf12006-09-28 00:35:06 +00001305 UndefValueConstants->remove(this);
Chris Lattnerb9f18592004-10-16 18:07:16 +00001306 destroyConstantImpl();
1307}
1308
1309
Vikram S. Adve345e0cf2002-07-14 23:13:17 +00001310//---- ConstantExpr::get() implementations...
Vikram S. Adve345e0cf2002-07-14 23:13:17 +00001311//
Reid Spencer077d0eb2006-12-04 05:19:50 +00001312struct ExprMapKeyType {
1313 explicit ExprMapKeyType(unsigned opc, std::vector<Constant*> ops,
Reid Spencer8d5a6ae2006-12-04 18:38:05 +00001314 unsigned short pred = 0) : opcode(opc), predicate(pred), operands(ops) { }
1315 uint16_t opcode;
1316 uint16_t predicate;
Reid Spencer077d0eb2006-12-04 05:19:50 +00001317 std::vector<Constant*> operands;
Reid Spencer077d0eb2006-12-04 05:19:50 +00001318 bool operator==(const ExprMapKeyType& that) const {
1319 return this->opcode == that.opcode &&
1320 this->predicate == that.predicate &&
1321 this->operands == that.operands;
1322 }
1323 bool operator<(const ExprMapKeyType & that) const {
1324 return this->opcode < that.opcode ||
1325 (this->opcode == that.opcode && this->predicate < that.predicate) ||
1326 (this->opcode == that.opcode && this->predicate == that.predicate &&
1327 this->operands < that.operands);
1328 }
1329
1330 bool operator!=(const ExprMapKeyType& that) const {
1331 return !(*this == that);
1332 }
1333};
Chris Lattner02ec5ed2003-05-23 20:03:32 +00001334
Chris Lattner31f84992003-11-21 20:23:48 +00001335namespace llvm {
1336 template<>
1337 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
Reid Spencer728b6db2006-12-03 05:48:19 +00001338 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1339 unsigned short pred = 0) {
Reid Spencer077d0eb2006-12-04 05:19:50 +00001340 if (Instruction::isCast(V.opcode))
1341 return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1342 if ((V.opcode >= Instruction::BinaryOpsBegin &&
1343 V.opcode < Instruction::BinaryOpsEnd) ||
1344 V.opcode == Instruction::Shl ||
1345 V.opcode == Instruction::LShr ||
1346 V.opcode == Instruction::AShr)
1347 return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1348 if (V.opcode == Instruction::Select)
1349 return new SelectConstantExpr(V.operands[0], V.operands[1],
1350 V.operands[2]);
1351 if (V.opcode == Instruction::ExtractElement)
1352 return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1353 if (V.opcode == Instruction::InsertElement)
1354 return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1355 V.operands[2]);
1356 if (V.opcode == Instruction::ShuffleVector)
1357 return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1358 V.operands[2]);
1359 if (V.opcode == Instruction::GetElementPtr) {
1360 std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
1361 return new GetElementPtrConstantExpr(V.operands[0], IdxList, Ty);
1362 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001363
Reid Spencer077d0eb2006-12-04 05:19:50 +00001364 // The compare instructions are weird. We have to encode the predicate
1365 // value and it is combined with the instruction opcode by multiplying
1366 // the opcode by one hundred. We must decode this to get the predicate.
1367 if (V.opcode == Instruction::ICmp)
1368 return new CompareConstantExpr(Instruction::ICmp, V.predicate,
1369 V.operands[0], V.operands[1]);
1370 if (V.opcode == Instruction::FCmp)
1371 return new CompareConstantExpr(Instruction::FCmp, V.predicate,
1372 V.operands[0], V.operands[1]);
1373 assert(0 && "Invalid ConstantExpr!");
Chris Lattnered468e372003-10-05 00:17:43 +00001374 }
Chris Lattner31f84992003-11-21 20:23:48 +00001375 };
Chris Lattnered468e372003-10-05 00:17:43 +00001376
Chris Lattner31f84992003-11-21 20:23:48 +00001377 template<>
1378 struct ConvertConstantType<ConstantExpr, Type> {
1379 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1380 Constant *New;
1381 switch (OldC->getOpcode()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001382 case Instruction::Trunc:
1383 case Instruction::ZExt:
1384 case Instruction::SExt:
1385 case Instruction::FPTrunc:
1386 case Instruction::FPExt:
1387 case Instruction::UIToFP:
1388 case Instruction::SIToFP:
1389 case Instruction::FPToUI:
1390 case Instruction::FPToSI:
1391 case Instruction::PtrToInt:
1392 case Instruction::IntToPtr:
1393 case Instruction::BitCast:
1394 New = ConstantExpr::getCast(
1395 OldC->getOpcode(), OldC->getOperand(0), NewTy);
Chris Lattner31f84992003-11-21 20:23:48 +00001396 break;
Chris Lattner08a45cc2004-03-12 05:54:04 +00001397 case Instruction::Select:
1398 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1399 OldC->getOperand(1),
1400 OldC->getOperand(2));
1401 break;
Chris Lattner31f84992003-11-21 20:23:48 +00001402 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00001403 case Instruction::LShr:
1404 case Instruction::AShr:
Chris Lattner31f84992003-11-21 20:23:48 +00001405 New = ConstantExpr::getShiftTy(NewTy, OldC->getOpcode(),
1406 OldC->getOperand(0), OldC->getOperand(1));
1407 break;
1408 default:
1409 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
Reid Spencer0a783f72006-11-02 01:53:59 +00001410 OldC->getOpcode() < Instruction::BinaryOpsEnd);
Chris Lattner31f84992003-11-21 20:23:48 +00001411 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1412 OldC->getOperand(1));
1413 break;
1414 case Instruction::GetElementPtr:
Misha Brukmanfd939082005-04-21 23:48:37 +00001415 // Make everyone now use a constant of the new type...
Chris Lattner7fa6e662004-10-11 22:52:25 +00001416 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1417 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0), Idx);
Chris Lattner31f84992003-11-21 20:23:48 +00001418 break;
1419 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001420
Chris Lattner31f84992003-11-21 20:23:48 +00001421 assert(New != OldC && "Didn't replace constant??");
1422 OldC->uncheckedReplaceAllUsesWith(New);
1423 OldC->destroyConstant(); // This constant is now dead, destroy it.
1424 }
1425 };
1426} // end namespace llvm
Chris Lattnered468e372003-10-05 00:17:43 +00001427
1428
Chris Lattner6823c9f2004-08-04 04:48:01 +00001429static ExprMapKeyType getValType(ConstantExpr *CE) {
1430 std::vector<Constant*> Operands;
1431 Operands.reserve(CE->getNumOperands());
1432 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1433 Operands.push_back(cast<Constant>(CE->getOperand(i)));
Reid Spencer077d0eb2006-12-04 05:19:50 +00001434 return ExprMapKeyType(CE->getOpcode(), Operands,
1435 CE->isCompare() ? CE->getPredicate() : 0);
Chris Lattner6823c9f2004-08-04 04:48:01 +00001436}
1437
Chris Lattner8a94bf12006-09-28 00:35:06 +00001438static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1439 ConstantExpr> > ExprConstants;
Vikram S. Adved0b1bb02002-07-15 18:19:33 +00001440
Reid Spencer3da59db2006-11-27 01:05:10 +00001441/// This is a utility function to handle folding of casts and lookup of the
1442/// cast in the ExprConstants map. It is usedby the various get* methods below.
1443static inline Constant *getFoldedCast(
1444 Instruction::CastOps opc, Constant *C, const Type *Ty) {
Chris Lattner9eacf8a2003-10-07 22:19:19 +00001445 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
Reid Spencer3da59db2006-11-27 01:05:10 +00001446 // Fold a few common cases
1447 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1448 return FC;
Chris Lattnerd628f6a2003-04-17 19:24:48 +00001449
Vikram S. Adved0b1bb02002-07-15 18:19:33 +00001450 // Look up the constant in the table first to ensure uniqueness
Chris Lattner9bc02a42003-05-13 21:37:02 +00001451 std::vector<Constant*> argVec(1, C);
Reid Spencer077d0eb2006-12-04 05:19:50 +00001452 ExprMapKeyType Key(opc, argVec);
Chris Lattner8a94bf12006-09-28 00:35:06 +00001453 return ExprConstants->getOrCreate(Ty, Key);
Vikram S. Adve345e0cf2002-07-14 23:13:17 +00001454}
Reid Spencer7858b332006-12-05 19:14:13 +00001455
Reid Spencer3da59db2006-11-27 01:05:10 +00001456Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1457 Instruction::CastOps opc = Instruction::CastOps(oc);
1458 assert(Instruction::isCast(opc) && "opcode out of range");
1459 assert(C && Ty && "Null arguments to getCast");
1460 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1461
1462 switch (opc) {
1463 default:
1464 assert(0 && "Invalid cast opcode");
1465 break;
1466 case Instruction::Trunc: return getTrunc(C, Ty);
1467 case Instruction::ZExt: return getZeroExtend(C, Ty);
1468 case Instruction::SExt: return getSignExtend(C, Ty);
1469 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1470 case Instruction::FPExt: return getFPExtend(C, Ty);
1471 case Instruction::UIToFP: return getUIToFP(C, Ty);
1472 case Instruction::SIToFP: return getSIToFP(C, Ty);
1473 case Instruction::FPToUI: return getFPToUI(C, Ty);
1474 case Instruction::FPToSI: return getFPToSI(C, Ty);
1475 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1476 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1477 case Instruction::BitCast: return getBitCast(C, Ty);
Chris Lattnerf5ac6c22005-01-01 15:59:57 +00001478 }
Reid Spencer3da59db2006-11-27 01:05:10 +00001479 return 0;
Reid Spencer7858b332006-12-05 19:14:13 +00001480}
1481
1482Constant *ConstantExpr::getCast(Constant *C, const Type *Ty) {
1483 // Note: we can't inline this because it requires the Instructions.h header
1484 return getCast(CastInst::getCastOpcode(
1485 C, C->getType()->isSigned(), Ty, Ty->isSigned()), C, Ty);
Reid Spencer3da59db2006-11-27 01:05:10 +00001486}
1487
Reid Spencer7858b332006-12-05 19:14:13 +00001488
Reid Spencer848414e2006-12-04 20:17:56 +00001489Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1490 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1491 return getCast(Instruction::BitCast, C, Ty);
1492 return getCast(Instruction::ZExt, C, Ty);
1493}
1494
1495Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1496 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1497 return getCast(Instruction::BitCast, C, Ty);
1498 return getCast(Instruction::SExt, C, Ty);
1499}
1500
1501Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1502 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1503 return getCast(Instruction::BitCast, C, Ty);
1504 return getCast(Instruction::Trunc, C, Ty);
1505}
1506
Reid Spencerc0459fb2006-12-05 03:25:26 +00001507Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1508 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1509 assert((Ty->isIntegral() || Ty->getTypeID() == Type::PointerTyID) &&
1510 "Invalid cast");
1511
1512 if (Ty->isIntegral())
1513 return getCast(Instruction::PtrToInt, S, Ty);
1514 return getCast(Instruction::BitCast, S, Ty);
1515}
1516
Reid Spencer84f3eab2006-12-12 00:51:07 +00001517Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
1518 bool isSigned) {
1519 assert(C->getType()->isIntegral() && Ty->isIntegral() && "Invalid cast");
1520 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1521 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1522 Instruction::CastOps opcode =
1523 (SrcBits == DstBits ? Instruction::BitCast :
1524 (SrcBits > DstBits ? Instruction::Trunc :
1525 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1526 return getCast(opcode, C, Ty);
1527}
1528
1529Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1530 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1531 "Invalid cast");
1532 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1533 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1534 Instruction::CastOps opcode =
1535 (SrcBits == DstBits ? Instruction::BitCast :
1536 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
1537 return getCast(opcode, C, Ty);
1538}
1539
Reid Spencer3da59db2006-11-27 01:05:10 +00001540Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
1541 assert(C->getType()->isInteger() && "Trunc operand must be integer");
1542 assert(Ty->isIntegral() && "Trunc produces only integral");
1543 assert(C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1544 "SrcTy must be larger than DestTy for Trunc!");
1545
1546 return getFoldedCast(Instruction::Trunc, C, Ty);
1547}
1548
1549Constant *ConstantExpr::getSignExtend(Constant *C, const Type *Ty) {
1550 assert(C->getType()->isIntegral() && "SEXt operand must be integral");
1551 assert(Ty->isInteger() && "SExt produces only integer");
1552 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1553 "SrcTy must be smaller than DestTy for SExt!");
1554
1555 return getFoldedCast(Instruction::SExt, C, Ty);
Chris Lattnerd144f422004-04-04 23:20:30 +00001556}
1557
1558Constant *ConstantExpr::getZeroExtend(Constant *C, const Type *Ty) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001559 assert(C->getType()->isIntegral() && "ZEXt operand must be integral");
1560 assert(Ty->isInteger() && "ZExt produces only integer");
1561 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1562 "SrcTy must be smaller than DestTy for ZExt!");
1563
1564 return getFoldedCast(Instruction::ZExt, C, Ty);
1565}
1566
1567Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1568 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1569 C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1570 "This is an illegal floating point truncation!");
1571 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1572}
1573
1574Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1575 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1576 C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1577 "This is an illegal floating point extension!");
1578 return getFoldedCast(Instruction::FPExt, C, Ty);
1579}
1580
1581Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
1582 assert(C->getType()->isIntegral() && Ty->isFloatingPoint() &&
1583 "This is an illegal uint to floating point cast!");
1584 return getFoldedCast(Instruction::UIToFP, C, Ty);
1585}
1586
1587Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
1588 assert(C->getType()->isIntegral() && Ty->isFloatingPoint() &&
1589 "This is an illegal sint to floating point cast!");
1590 return getFoldedCast(Instruction::SIToFP, C, Ty);
1591}
1592
1593Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
1594 assert(C->getType()->isFloatingPoint() && Ty->isIntegral() &&
1595 "This is an illegal floating point to uint cast!");
1596 return getFoldedCast(Instruction::FPToUI, C, Ty);
1597}
1598
1599Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
1600 assert(C->getType()->isFloatingPoint() && Ty->isIntegral() &&
1601 "This is an illegal floating point to sint cast!");
1602 return getFoldedCast(Instruction::FPToSI, C, Ty);
1603}
1604
1605Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1606 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
1607 assert(DstTy->isIntegral() && "PtrToInt destination must be integral");
1608 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1609}
1610
1611Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
1612 assert(C->getType()->isIntegral() && "IntToPtr source must be integral");
1613 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
1614 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1615}
1616
1617Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1618 // BitCast implies a no-op cast of type only. No bits change. However, you
1619 // can't cast pointers to anything but pointers.
1620 const Type *SrcTy = C->getType();
1621 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
Reid Spencer848414e2006-12-04 20:17:56 +00001622 "BitCast cannot cast pointer to non-pointer and vice versa");
Reid Spencer3da59db2006-11-27 01:05:10 +00001623
1624 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
1625 // or nonptr->ptr). For all the other types, the cast is okay if source and
1626 // destination bit widths are identical.
1627 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1628 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
Reid Spencer848414e2006-12-04 20:17:56 +00001629 assert(SrcBitSize == DstBitSize && "BitCast requies types of same width");
Reid Spencer3da59db2006-11-27 01:05:10 +00001630 return getFoldedCast(Instruction::BitCast, C, DstTy);
Chris Lattnerd144f422004-04-04 23:20:30 +00001631}
1632
Alkis Evlogimenos60ab1402004-10-24 01:41:10 +00001633Constant *ConstantExpr::getSizeOf(const Type *Ty) {
Chris Lattnerfcdd82e2004-12-13 19:48:51 +00001634 // sizeof is implemented as: (ulong) gep (Ty*)null, 1
Reid Spencer56667122006-12-04 02:43:42 +00001635 return getCast(Instruction::PtrToInt, getGetElementPtr(getNullValue(
1636 PointerType::get(Ty)), std::vector<Constant*>(1,
1637 ConstantInt::get(Type::UIntTy, 1))), Type::ULongTy);
Alkis Evlogimenos60ab1402004-10-24 01:41:10 +00001638}
1639
Alkis Evlogimenos1cecd3a2005-03-19 11:40:31 +00001640Constant *ConstantExpr::getPtrPtrFromArrayPtr(Constant *C) {
1641 // pointer from array is implemented as: getelementptr arr ptr, 0, 0
Reid Spencerb83eb642006-10-20 07:07:24 +00001642 static std::vector<Constant*> Indices(2, ConstantInt::get(Type::UIntTy, 0));
Alkis Evlogimenos1cecd3a2005-03-19 11:40:31 +00001643
1644 return ConstantExpr::getGetElementPtr(C, Indices);
1645}
1646
Chris Lattnered468e372003-10-05 00:17:43 +00001647Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
Reid Spencer67263fe2006-12-04 21:35:24 +00001648 Constant *C1, Constant *C2) {
Reid Spencer3822ff52006-11-08 06:47:33 +00001649 if (Opcode == Instruction::Shl || Opcode == Instruction::LShr ||
1650 Opcode == Instruction::AShr)
Chris Lattner3edd3972004-01-12 19:04:55 +00001651 return getShiftTy(ReqTy, Opcode, C1, C2);
Reid Spencer077d0eb2006-12-04 05:19:50 +00001652
Chris Lattnerf31f5832003-05-21 17:49:25 +00001653 // Check the operands for consistency first
Reid Spencer0a783f72006-11-02 01:53:59 +00001654 assert(Opcode >= Instruction::BinaryOpsBegin &&
1655 Opcode < Instruction::BinaryOpsEnd &&
Chris Lattnerf31f5832003-05-21 17:49:25 +00001656 "Invalid opcode in binary constant expression");
1657 assert(C1->getType() == C2->getType() &&
1658 "Operand types in binary constant expression should match");
Chris Lattnered468e372003-10-05 00:17:43 +00001659
Chris Lattnera5b07402006-09-17 19:14:47 +00001660 if (ReqTy == C1->getType() || (Instruction::isComparison(Opcode) &&
Chris Lattnerc3d12f02004-08-04 18:50:09 +00001661 ReqTy == Type::BoolTy))
Chris Lattnered468e372003-10-05 00:17:43 +00001662 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1663 return FC; // Fold a few common cases...
Chris Lattnerd628f6a2003-04-17 19:24:48 +00001664
Chris Lattner9bc02a42003-05-13 21:37:02 +00001665 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
Reid Spencer67263fe2006-12-04 21:35:24 +00001666 ExprMapKeyType Key(Opcode, argVec);
Chris Lattner8a94bf12006-09-28 00:35:06 +00001667 return ExprConstants->getOrCreate(ReqTy, Key);
Vikram S. Adve345e0cf2002-07-14 23:13:17 +00001668}
1669
Reid Spencer67263fe2006-12-04 21:35:24 +00001670Constant *ConstantExpr::getCompareTy(unsigned Opcode, unsigned short predicate,
1671 Constant *C1, Constant *C2) {
1672 if (Opcode == Instruction::ICmp)
1673 return getICmp(predicate, C1, C2);
1674 return getFCmp(predicate, C1, C2);
1675}
1676
1677Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
Chris Lattner91b362b2004-08-17 17:28:46 +00001678#ifndef NDEBUG
1679 switch (Opcode) {
Reid Spencer0a783f72006-11-02 01:53:59 +00001680 case Instruction::Add:
1681 case Instruction::Sub:
Reid Spencer1628cec2006-10-26 06:15:43 +00001682 case Instruction::Mul:
Chris Lattner91b362b2004-08-17 17:28:46 +00001683 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Chris Lattner20542952006-01-04 01:01:04 +00001684 assert((C1->getType()->isInteger() || C1->getType()->isFloatingPoint() ||
1685 isa<PackedType>(C1->getType())) &&
Chris Lattner91b362b2004-08-17 17:28:46 +00001686 "Tried to create an arithmetic operation on a non-arithmetic type!");
1687 break;
Reid Spencer1628cec2006-10-26 06:15:43 +00001688 case Instruction::UDiv:
1689 case Instruction::SDiv:
1690 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1691 assert((C1->getType()->isInteger() || (isa<PackedType>(C1->getType()) &&
1692 cast<PackedType>(C1->getType())->getElementType()->isInteger())) &&
1693 "Tried to create an arithmetic operation on a non-arithmetic type!");
1694 break;
1695 case Instruction::FDiv:
1696 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1697 assert((C1->getType()->isFloatingPoint() || (isa<PackedType>(C1->getType())
1698 && cast<PackedType>(C1->getType())->getElementType()->isFloatingPoint()))
1699 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1700 break;
Reid Spencer0a783f72006-11-02 01:53:59 +00001701 case Instruction::URem:
1702 case Instruction::SRem:
1703 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1704 assert((C1->getType()->isInteger() || (isa<PackedType>(C1->getType()) &&
1705 cast<PackedType>(C1->getType())->getElementType()->isInteger())) &&
1706 "Tried to create an arithmetic operation on a non-arithmetic type!");
1707 break;
1708 case Instruction::FRem:
1709 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1710 assert((C1->getType()->isFloatingPoint() || (isa<PackedType>(C1->getType())
1711 && cast<PackedType>(C1->getType())->getElementType()->isFloatingPoint()))
1712 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1713 break;
Chris Lattner91b362b2004-08-17 17:28:46 +00001714 case Instruction::And:
1715 case Instruction::Or:
1716 case Instruction::Xor:
1717 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Chris Lattner20542952006-01-04 01:01:04 +00001718 assert((C1->getType()->isIntegral() || isa<PackedType>(C1->getType())) &&
Misha Brukman1bae2912005-01-27 06:46:38 +00001719 "Tried to create a logical operation on a non-integral type!");
Chris Lattner91b362b2004-08-17 17:28:46 +00001720 break;
1721 case Instruction::SetLT: case Instruction::SetGT: case Instruction::SetLE:
1722 case Instruction::SetGE: case Instruction::SetEQ: case Instruction::SetNE:
1723 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1724 break;
1725 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00001726 case Instruction::LShr:
1727 case Instruction::AShr:
Chris Lattner91b362b2004-08-17 17:28:46 +00001728 assert(C2->getType() == Type::UByteTy && "Shift should be by ubyte!");
Reid Spencer3822ff52006-11-08 06:47:33 +00001729 assert(C1->getType()->isInteger() &&
Chris Lattner91b362b2004-08-17 17:28:46 +00001730 "Tried to create a shift operation on a non-integer type!");
1731 break;
1732 default:
1733 break;
1734 }
1735#endif
1736
Reid Spencer67263fe2006-12-04 21:35:24 +00001737 return getTy(C1->getType(), Opcode, C1, C2);
1738}
1739
1740Constant *ConstantExpr::getCompare(unsigned Opcode, unsigned short pred,
1741 Constant *C1, Constant *C2) {
1742 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1743 return getCompareTy(Opcode, pred, C1, C2);
Chris Lattnerc3d12f02004-08-04 18:50:09 +00001744}
1745
Chris Lattner08a45cc2004-03-12 05:54:04 +00001746Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1747 Constant *V1, Constant *V2) {
1748 assert(C->getType() == Type::BoolTy && "Select condition must be bool!");
1749 assert(V1->getType() == V2->getType() && "Select value types must match!");
1750 assert(V1->getType()->isFirstClassType() && "Cannot select aggregate type!");
1751
1752 if (ReqTy == V1->getType())
1753 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1754 return SC; // Fold common cases
1755
1756 std::vector<Constant*> argVec(3, C);
1757 argVec[1] = V1;
1758 argVec[2] = V2;
Reid Spencer077d0eb2006-12-04 05:19:50 +00001759 ExprMapKeyType Key(Instruction::Select, argVec);
Chris Lattner8a94bf12006-09-28 00:35:06 +00001760 return ExprConstants->getOrCreate(ReqTy, Key);
Chris Lattner08a45cc2004-03-12 05:54:04 +00001761}
1762
Chris Lattner69b9e892004-01-12 19:12:58 +00001763/// getShiftTy - Return a shift left or shift right constant expr
Chris Lattnered468e372003-10-05 00:17:43 +00001764Constant *ConstantExpr::getShiftTy(const Type *ReqTy, unsigned Opcode,
1765 Constant *C1, Constant *C2) {
Chris Lattnerf31f5832003-05-21 17:49:25 +00001766 // Check the operands for consistency first
Reid Spencer3822ff52006-11-08 06:47:33 +00001767 assert((Opcode == Instruction::Shl ||
1768 Opcode == Instruction::LShr ||
1769 Opcode == Instruction::AShr) &&
Chris Lattnerf31f5832003-05-21 17:49:25 +00001770 "Invalid opcode in binary constant expression");
1771 assert(C1->getType()->isIntegral() && C2->getType() == Type::UByteTy &&
1772 "Invalid operand types for Shift constant expr!");
1773
Chris Lattnerd4403b42004-01-12 20:40:42 +00001774 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
Chris Lattnerf31f5832003-05-21 17:49:25 +00001775 return FC; // Fold a few common cases...
1776
1777 // Look up the constant in the table first to ensure uniqueness
1778 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
Reid Spencer077d0eb2006-12-04 05:19:50 +00001779 ExprMapKeyType Key(Opcode, argVec);
Chris Lattner8a94bf12006-09-28 00:35:06 +00001780 return ExprConstants->getOrCreate(ReqTy, Key);
Chris Lattnerf31f5832003-05-21 17:49:25 +00001781}
1782
Chris Lattnered468e372003-10-05 00:17:43 +00001783Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
Chris Lattner7fa6e662004-10-11 22:52:25 +00001784 const std::vector<Value*> &IdxList) {
1785 assert(GetElementPtrInst::getIndexedType(C->getType(), IdxList, true) &&
Chris Lattner2e9bb1a2004-02-16 20:46:13 +00001786 "GEP indices invalid!");
1787
Chris Lattnerd628f6a2003-04-17 19:24:48 +00001788 if (Constant *FC = ConstantFoldGetElementPtr(C, IdxList))
1789 return FC; // Fold a few common cases...
Chris Lattner2e9bb1a2004-02-16 20:46:13 +00001790
Chris Lattnered468e372003-10-05 00:17:43 +00001791 assert(isa<PointerType>(C->getType()) &&
Chris Lattner02ec5ed2003-05-23 20:03:32 +00001792 "Non-pointer type for constant GetElementPtr expression");
Vikram S. Adved0b1bb02002-07-15 18:19:33 +00001793 // Look up the constant in the table first to ensure uniqueness
Chris Lattner7fa6e662004-10-11 22:52:25 +00001794 std::vector<Constant*> ArgVec;
1795 ArgVec.reserve(IdxList.size()+1);
1796 ArgVec.push_back(C);
1797 for (unsigned i = 0, e = IdxList.size(); i != e; ++i)
1798 ArgVec.push_back(cast<Constant>(IdxList[i]));
Reid Spencer077d0eb2006-12-04 05:19:50 +00001799 const ExprMapKeyType Key(Instruction::GetElementPtr,ArgVec);
Chris Lattner8a94bf12006-09-28 00:35:06 +00001800 return ExprConstants->getOrCreate(ReqTy, Key);
Vikram S. Adved0b1bb02002-07-15 18:19:33 +00001801}
1802
Chris Lattnered468e372003-10-05 00:17:43 +00001803Constant *ConstantExpr::getGetElementPtr(Constant *C,
1804 const std::vector<Constant*> &IdxList){
1805 // Get the result type of the getelementptr!
1806 std::vector<Value*> VIdxList(IdxList.begin(), IdxList.end());
1807
1808 const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), VIdxList,
1809 true);
1810 assert(Ty && "GEP indices invalid!");
Chris Lattner7fa6e662004-10-11 22:52:25 +00001811 return getGetElementPtrTy(PointerType::get(Ty), C, VIdxList);
1812}
1813
1814Constant *ConstantExpr::getGetElementPtr(Constant *C,
1815 const std::vector<Value*> &IdxList) {
1816 // Get the result type of the getelementptr!
1817 const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), IdxList,
1818 true);
1819 assert(Ty && "GEP indices invalid!");
Chris Lattnered468e372003-10-05 00:17:43 +00001820 return getGetElementPtrTy(PointerType::get(Ty), C, IdxList);
1821}
1822
Reid Spencer077d0eb2006-12-04 05:19:50 +00001823Constant *
1824ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1825 assert(LHS->getType() == RHS->getType());
1826 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
1827 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1828
1829 if (Constant *FC = ConstantFoldCompare(Instruction::ICmp, LHS, RHS, pred))
1830 return FC; // Fold a few common cases...
1831
1832 // Look up the constant in the table first to ensure uniqueness
1833 std::vector<Constant*> ArgVec;
1834 ArgVec.push_back(LHS);
1835 ArgVec.push_back(RHS);
1836 // Fake up an opcode value that encodes both the opcode and predicate
1837 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
1838 return ExprConstants->getOrCreate(Type::BoolTy, Key);
1839}
1840
1841Constant *
1842ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1843 assert(LHS->getType() == RHS->getType());
1844 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1845
1846 if (Constant *FC = ConstantFoldCompare(Instruction::FCmp, LHS, RHS, pred))
1847 return FC; // Fold a few common cases...
1848
1849 // Look up the constant in the table first to ensure uniqueness
1850 std::vector<Constant*> ArgVec;
1851 ArgVec.push_back(LHS);
1852 ArgVec.push_back(RHS);
1853 // Fake up an opcode value that encodes both the opcode and predicate
1854 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
1855 return ExprConstants->getOrCreate(Type::BoolTy, Key);
1856}
1857
Robert Bocchinob52ee7f2006-01-10 19:05:34 +00001858Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
1859 Constant *Idx) {
Robert Bocchinobb90a7a2006-01-10 20:03:46 +00001860 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
1861 return FC; // Fold a few common cases...
Robert Bocchinob52ee7f2006-01-10 19:05:34 +00001862 // Look up the constant in the table first to ensure uniqueness
1863 std::vector<Constant*> ArgVec(1, Val);
1864 ArgVec.push_back(Idx);
Reid Spencer077d0eb2006-12-04 05:19:50 +00001865 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
Chris Lattner8a94bf12006-09-28 00:35:06 +00001866 return ExprConstants->getOrCreate(ReqTy, Key);
Robert Bocchinob52ee7f2006-01-10 19:05:34 +00001867}
1868
1869Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
1870 assert(isa<PackedType>(Val->getType()) &&
1871 "Tried to create extractelement operation on non-packed type!");
1872 assert(Idx->getType() == Type::UIntTy &&
Robert Bocchinoc152f9c2006-01-17 20:07:22 +00001873 "Extractelement index must be uint type!");
Robert Bocchinob52ee7f2006-01-10 19:05:34 +00001874 return getExtractElementTy(cast<PackedType>(Val->getType())->getElementType(),
1875 Val, Idx);
1876}
Chris Lattnered468e372003-10-05 00:17:43 +00001877
Robert Bocchinoc152f9c2006-01-17 20:07:22 +00001878Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
1879 Constant *Elt, Constant *Idx) {
1880 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
1881 return FC; // Fold a few common cases...
1882 // Look up the constant in the table first to ensure uniqueness
1883 std::vector<Constant*> ArgVec(1, Val);
1884 ArgVec.push_back(Elt);
1885 ArgVec.push_back(Idx);
Reid Spencer077d0eb2006-12-04 05:19:50 +00001886 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
Chris Lattner8a94bf12006-09-28 00:35:06 +00001887 return ExprConstants->getOrCreate(ReqTy, Key);
Robert Bocchinoc152f9c2006-01-17 20:07:22 +00001888}
1889
1890Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1891 Constant *Idx) {
1892 assert(isa<PackedType>(Val->getType()) &&
1893 "Tried to create insertelement operation on non-packed type!");
1894 assert(Elt->getType() == cast<PackedType>(Val->getType())->getElementType()
1895 && "Insertelement types must match!");
1896 assert(Idx->getType() == Type::UIntTy &&
1897 "Insertelement index must be uint type!");
1898 return getInsertElementTy(cast<PackedType>(Val->getType())->getElementType(),
1899 Val, Elt, Idx);
1900}
1901
Chris Lattner00f10232006-04-08 01:18:18 +00001902Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
1903 Constant *V2, Constant *Mask) {
1904 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
1905 return FC; // Fold a few common cases...
1906 // Look up the constant in the table first to ensure uniqueness
1907 std::vector<Constant*> ArgVec(1, V1);
1908 ArgVec.push_back(V2);
1909 ArgVec.push_back(Mask);
Reid Spencer077d0eb2006-12-04 05:19:50 +00001910 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
Chris Lattner8a94bf12006-09-28 00:35:06 +00001911 return ExprConstants->getOrCreate(ReqTy, Key);
Chris Lattner00f10232006-04-08 01:18:18 +00001912}
1913
1914Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
1915 Constant *Mask) {
1916 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1917 "Invalid shuffle vector constant expr operands!");
1918 return getShuffleVectorTy(V1->getType(), V1, V2, Mask);
1919}
1920
Vikram S. Adved0b1bb02002-07-15 18:19:33 +00001921// destroyConstant - Remove the constant from the constant table...
1922//
1923void ConstantExpr::destroyConstant() {
Chris Lattner8a94bf12006-09-28 00:35:06 +00001924 ExprConstants->remove(this);
Vikram S. Adved0b1bb02002-07-15 18:19:33 +00001925 destroyConstantImpl();
Vikram S. Adve345e0cf2002-07-14 23:13:17 +00001926}
1927
Chris Lattnerc188eeb2002-07-30 18:54:25 +00001928const char *ConstantExpr::getOpcodeName() const {
1929 return Instruction::getOpcodeName(getOpcode());
Vikram S. Adve345e0cf2002-07-14 23:13:17 +00001930}
Reid Spencer1c9c8e62004-07-17 23:48:33 +00001931
Chris Lattner5cbade92005-10-03 21:58:36 +00001932//===----------------------------------------------------------------------===//
1933// replaceUsesOfWithOnConstant implementations
1934
1935void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattnerd0ff1ad2005-10-04 18:13:04 +00001936 Use *U) {
Chris Lattner5cbade92005-10-03 21:58:36 +00001937 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
Chris Lattnerc182a882005-10-04 01:17:50 +00001938 Constant *ToC = cast<Constant>(To);
Chris Lattner23ec01f2005-10-04 18:47:09 +00001939
1940 unsigned OperandToUpdate = U-OperandList;
1941 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
1942
Jim Laskeyede5aa42006-07-17 17:38:29 +00001943 std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
Chris Lattnercea141f2005-10-03 22:51:37 +00001944 Lookup.first.first = getType();
1945 Lookup.second = this;
Chris Lattner23ec01f2005-10-04 18:47:09 +00001946
Chris Lattnercea141f2005-10-03 22:51:37 +00001947 std::vector<Constant*> &Values = Lookup.first.second;
1948 Values.reserve(getNumOperands()); // Build replacement array.
Chris Lattner23ec01f2005-10-04 18:47:09 +00001949
Chris Lattnerc182a882005-10-04 01:17:50 +00001950 // Fill values with the modified operands of the constant array. Also,
1951 // compute whether this turns into an all-zeros array.
Chris Lattner23ec01f2005-10-04 18:47:09 +00001952 bool isAllZeros = false;
1953 if (!ToC->isNullValue()) {
1954 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
1955 Values.push_back(cast<Constant>(O->get()));
1956 } else {
1957 isAllZeros = true;
1958 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1959 Constant *Val = cast<Constant>(O->get());
1960 Values.push_back(Val);
1961 if (isAllZeros) isAllZeros = Val->isNullValue();
1962 }
Chris Lattner5cbade92005-10-03 21:58:36 +00001963 }
Chris Lattner23ec01f2005-10-04 18:47:09 +00001964 Values[OperandToUpdate] = ToC;
Chris Lattner5cbade92005-10-03 21:58:36 +00001965
Chris Lattnercea141f2005-10-03 22:51:37 +00001966 Constant *Replacement = 0;
1967 if (isAllZeros) {
1968 Replacement = ConstantAggregateZero::get(getType());
1969 } else {
1970 // Check to see if we have this array type already.
1971 bool Exists;
Jim Laskeyede5aa42006-07-17 17:38:29 +00001972 ArrayConstantsTy::MapTy::iterator I =
Chris Lattner8a94bf12006-09-28 00:35:06 +00001973 ArrayConstants->InsertOrGetItem(Lookup, Exists);
Chris Lattnercea141f2005-10-03 22:51:37 +00001974
1975 if (Exists) {
1976 Replacement = I->second;
1977 } else {
1978 // Okay, the new shape doesn't exist in the system yet. Instead of
1979 // creating a new constant array, inserting it, replaceallusesof'ing the
1980 // old with the new, then deleting the old... just update the current one
1981 // in place!
Chris Lattner8a94bf12006-09-28 00:35:06 +00001982 ArrayConstants->MoveConstantToNewSlot(this, I);
Chris Lattnercea141f2005-10-03 22:51:37 +00001983
Chris Lattner23ec01f2005-10-04 18:47:09 +00001984 // Update to the new value.
1985 setOperand(OperandToUpdate, ToC);
Chris Lattnercea141f2005-10-03 22:51:37 +00001986 return;
1987 }
1988 }
1989
1990 // Otherwise, I do need to replace this with an existing value.
Chris Lattner5cbade92005-10-03 21:58:36 +00001991 assert(Replacement != this && "I didn't contain From!");
1992
Chris Lattnerd0ff1ad2005-10-04 18:13:04 +00001993 // Everyone using this now uses the replacement.
1994 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattner5cbade92005-10-03 21:58:36 +00001995
1996 // Delete the old constant!
1997 destroyConstant();
1998}
1999
2000void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattnerd0ff1ad2005-10-04 18:13:04 +00002001 Use *U) {
Chris Lattner5cbade92005-10-03 21:58:36 +00002002 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
Chris Lattnerc182a882005-10-04 01:17:50 +00002003 Constant *ToC = cast<Constant>(To);
2004
Chris Lattner23ec01f2005-10-04 18:47:09 +00002005 unsigned OperandToUpdate = U-OperandList;
2006 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2007
Jim Laskeyede5aa42006-07-17 17:38:29 +00002008 std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
Chris Lattnerc182a882005-10-04 01:17:50 +00002009 Lookup.first.first = getType();
2010 Lookup.second = this;
2011 std::vector<Constant*> &Values = Lookup.first.second;
2012 Values.reserve(getNumOperands()); // Build replacement struct.
Chris Lattner5cbade92005-10-03 21:58:36 +00002013
Chris Lattner23ec01f2005-10-04 18:47:09 +00002014
Chris Lattnerc182a882005-10-04 01:17:50 +00002015 // Fill values with the modified operands of the constant struct. Also,
2016 // compute whether this turns into an all-zeros struct.
Chris Lattner23ec01f2005-10-04 18:47:09 +00002017 bool isAllZeros = false;
2018 if (!ToC->isNullValue()) {
2019 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
2020 Values.push_back(cast<Constant>(O->get()));
2021 } else {
2022 isAllZeros = true;
2023 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2024 Constant *Val = cast<Constant>(O->get());
2025 Values.push_back(Val);
2026 if (isAllZeros) isAllZeros = Val->isNullValue();
2027 }
Chris Lattnerc182a882005-10-04 01:17:50 +00002028 }
Chris Lattner23ec01f2005-10-04 18:47:09 +00002029 Values[OperandToUpdate] = ToC;
2030
Chris Lattnerc182a882005-10-04 01:17:50 +00002031 Constant *Replacement = 0;
2032 if (isAllZeros) {
2033 Replacement = ConstantAggregateZero::get(getType());
2034 } else {
2035 // Check to see if we have this array type already.
2036 bool Exists;
Jim Laskeyede5aa42006-07-17 17:38:29 +00002037 StructConstantsTy::MapTy::iterator I =
Chris Lattner8a94bf12006-09-28 00:35:06 +00002038 StructConstants->InsertOrGetItem(Lookup, Exists);
Chris Lattnerc182a882005-10-04 01:17:50 +00002039
2040 if (Exists) {
2041 Replacement = I->second;
2042 } else {
2043 // Okay, the new shape doesn't exist in the system yet. Instead of
2044 // creating a new constant struct, inserting it, replaceallusesof'ing the
2045 // old with the new, then deleting the old... just update the current one
2046 // in place!
Chris Lattner8a94bf12006-09-28 00:35:06 +00002047 StructConstants->MoveConstantToNewSlot(this, I);
Chris Lattnerc182a882005-10-04 01:17:50 +00002048
Chris Lattner23ec01f2005-10-04 18:47:09 +00002049 // Update to the new value.
2050 setOperand(OperandToUpdate, ToC);
Chris Lattnerc182a882005-10-04 01:17:50 +00002051 return;
2052 }
Chris Lattner5cbade92005-10-03 21:58:36 +00002053 }
2054
Chris Lattner5cbade92005-10-03 21:58:36 +00002055 assert(Replacement != this && "I didn't contain From!");
2056
Chris Lattnerd0ff1ad2005-10-04 18:13:04 +00002057 // Everyone using this now uses the replacement.
2058 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattner5cbade92005-10-03 21:58:36 +00002059
2060 // Delete the old constant!
2061 destroyConstant();
2062}
2063
2064void ConstantPacked::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattnerd0ff1ad2005-10-04 18:13:04 +00002065 Use *U) {
Chris Lattner5cbade92005-10-03 21:58:36 +00002066 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2067
2068 std::vector<Constant*> Values;
2069 Values.reserve(getNumOperands()); // Build replacement array...
2070 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2071 Constant *Val = getOperand(i);
2072 if (Val == From) Val = cast<Constant>(To);
2073 Values.push_back(Val);
2074 }
2075
2076 Constant *Replacement = ConstantPacked::get(getType(), Values);
2077 assert(Replacement != this && "I didn't contain From!");
2078
Chris Lattnerd0ff1ad2005-10-04 18:13:04 +00002079 // Everyone using this now uses the replacement.
2080 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattner5cbade92005-10-03 21:58:36 +00002081
2082 // Delete the old constant!
2083 destroyConstant();
2084}
2085
2086void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
Chris Lattnerd0ff1ad2005-10-04 18:13:04 +00002087 Use *U) {
Chris Lattner5cbade92005-10-03 21:58:36 +00002088 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2089 Constant *To = cast<Constant>(ToV);
2090
2091 Constant *Replacement = 0;
2092 if (getOpcode() == Instruction::GetElementPtr) {
2093 std::vector<Constant*> Indices;
2094 Constant *Pointer = getOperand(0);
2095 Indices.reserve(getNumOperands()-1);
2096 if (Pointer == From) Pointer = To;
2097
2098 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2099 Constant *Val = getOperand(i);
2100 if (Val == From) Val = To;
2101 Indices.push_back(Val);
2102 }
2103 Replacement = ConstantExpr::getGetElementPtr(Pointer, Indices);
Reid Spencer3da59db2006-11-27 01:05:10 +00002104 } else if (isCast()) {
Chris Lattner5cbade92005-10-03 21:58:36 +00002105 assert(getOperand(0) == From && "Cast only has one use!");
Reid Spencer3da59db2006-11-27 01:05:10 +00002106 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
Chris Lattner5cbade92005-10-03 21:58:36 +00002107 } else if (getOpcode() == Instruction::Select) {
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::getSelect(C1, C2, C3);
Robert Bocchinob52ee7f2006-01-10 19:05:34 +00002115 } else if (getOpcode() == Instruction::ExtractElement) {
2116 Constant *C1 = getOperand(0);
2117 Constant *C2 = getOperand(1);
2118 if (C1 == From) C1 = To;
2119 if (C2 == From) C2 = To;
2120 Replacement = ConstantExpr::getExtractElement(C1, C2);
Chris Lattner42b55802006-04-08 05:09:48 +00002121 } else if (getOpcode() == Instruction::InsertElement) {
2122 Constant *C1 = getOperand(0);
2123 Constant *C2 = getOperand(1);
2124 Constant *C3 = getOperand(1);
2125 if (C1 == From) C1 = To;
2126 if (C2 == From) C2 = To;
2127 if (C3 == From) C3 = To;
2128 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2129 } else if (getOpcode() == Instruction::ShuffleVector) {
2130 Constant *C1 = getOperand(0);
2131 Constant *C2 = getOperand(1);
2132 Constant *C3 = getOperand(2);
2133 if (C1 == From) C1 = To;
2134 if (C2 == From) C2 = To;
2135 if (C3 == From) C3 = To;
2136 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
Reid Spencer077d0eb2006-12-04 05:19:50 +00002137 } else if (isCompare()) {
2138 Constant *C1 = getOperand(0);
2139 Constant *C2 = getOperand(1);
2140 if (C1 == From) C1 = To;
2141 if (C2 == From) C2 = To;
2142 if (getOpcode() == Instruction::ICmp)
2143 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2144 else
2145 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
Chris Lattner5cbade92005-10-03 21:58:36 +00002146 } else if (getNumOperands() == 2) {
2147 Constant *C1 = getOperand(0);
2148 Constant *C2 = getOperand(1);
2149 if (C1 == From) C1 = To;
2150 if (C2 == From) C2 = To;
2151 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2152 } else {
2153 assert(0 && "Unknown ConstantExpr type!");
2154 return;
2155 }
2156
2157 assert(Replacement != this && "I didn't contain From!");
2158
Chris Lattnerd0ff1ad2005-10-04 18:13:04 +00002159 // Everyone using this now uses the replacement.
2160 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattner5cbade92005-10-03 21:58:36 +00002161
2162 // Delete the old constant!
2163 destroyConstant();
2164}
2165
2166
Jim Laskey21b6c9d2006-03-08 18:11:07 +00002167/// getStringValue - Turn an LLVM constant pointer that eventually points to a
2168/// global into a string value. Return an empty string if we can't do it.
Evan Cheng09371032006-03-10 23:52:03 +00002169/// Parameter Chop determines if the result is chopped at the first null
2170/// terminator.
Jim Laskey21b6c9d2006-03-08 18:11:07 +00002171///
Evan Cheng09371032006-03-10 23:52:03 +00002172std::string Constant::getStringValue(bool Chop, unsigned Offset) {
Jim Laskey21b6c9d2006-03-08 18:11:07 +00002173 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(this)) {
2174 if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
2175 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
2176 if (Init->isString()) {
2177 std::string Result = Init->getAsString();
2178 if (Offset < Result.size()) {
2179 // If we are pointing INTO The string, erase the beginning...
2180 Result.erase(Result.begin(), Result.begin()+Offset);
2181
2182 // Take off the null terminator, and any string fragments after it.
Evan Cheng09371032006-03-10 23:52:03 +00002183 if (Chop) {
2184 std::string::size_type NullPos = Result.find_first_of((char)0);
2185 if (NullPos != std::string::npos)
2186 Result.erase(Result.begin()+NullPos, Result.end());
2187 }
Jim Laskey21b6c9d2006-03-08 18:11:07 +00002188 return Result;
2189 }
2190 }
2191 }
2192 } else if (Constant *C = dyn_cast<Constant>(this)) {
2193 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
Evan Cheng2352ce92006-03-11 00:13:10 +00002194 return GV->getStringValue(Chop, Offset);
Jim Laskey21b6c9d2006-03-08 18:11:07 +00002195 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2196 if (CE->getOpcode() == Instruction::GetElementPtr) {
2197 // Turn a gep into the specified offset.
2198 if (CE->getNumOperands() == 3 &&
2199 cast<Constant>(CE->getOperand(1))->isNullValue() &&
2200 isa<ConstantInt>(CE->getOperand(2))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002201 Offset += cast<ConstantInt>(CE->getOperand(2))->getZExtValue();
Evan Cheng2352ce92006-03-11 00:13:10 +00002202 return CE->getOperand(0)->getStringValue(Chop, Offset);
Jim Laskey21b6c9d2006-03-08 18:11:07 +00002203 }
2204 }
2205 }
2206 }
2207 return "";
2208}