1 //===-- Constants.cpp - Implement Constant nodes -----------------*- C++ -*--=//
3 // This file implements the Constant* classes...
5 //===----------------------------------------------------------------------===//
7 #define __STDC_LIMIT_MACROS // Get defs for INT64_MAX and friends...
8 #include "llvm/Constants.h"
9 #include "llvm/DerivedTypes.h"
10 #include "llvm/iMemory.h"
11 #include "llvm/SymbolTable.h"
12 #include "llvm/Module.h"
13 #include "llvm/SlotCalculator.h"
14 #include "Support/StringExtras.h"
22 ConstantBool *ConstantBool::True = new ConstantBool(true);
23 ConstantBool *ConstantBool::False = new ConstantBool(false);
26 //===----------------------------------------------------------------------===//
28 //===----------------------------------------------------------------------===//
30 // Specialize setName to take care of symbol table majik
31 void Constant::setName(const std::string &Name, SymbolTable *ST) {
32 assert(ST && "Type::setName - Must provide symbol table argument!");
34 if (Name.size()) ST->insert(Name, this);
37 // Static constructor to create a '0' constant of arbitrary type...
38 Constant *Constant::getNullValue(const Type *Ty) {
39 switch (Ty->getPrimitiveID()) {
40 case Type::BoolTyID: return ConstantBool::get(false);
44 case Type::LongTyID: return ConstantSInt::get(Ty, 0);
47 case Type::UShortTyID:
49 case Type::ULongTyID: return ConstantUInt::get(Ty, 0);
52 case Type::DoubleTyID: return ConstantFP::get(Ty, 0);
54 case Type::PointerTyID:
55 return ConstantPointerNull::get(cast<PointerType>(Ty));
61 void Constant::destroyConstantImpl() {
62 // When a Constant is destroyed, there may be lingering
63 // references to the constant by other constants in the constant pool. These
64 // constants are implicitly dependant on the module that is being deleted,
65 // but they don't know that. Because we only find out when the CPV is
66 // deleted, we must now notify all of our users (that should only be
67 // Constants) that they are, in fact, invalid now and should be deleted.
69 while (!use_empty()) {
70 Value *V = use_back();
71 #ifndef NDEBUG // Only in -g mode...
72 if (!isa<Constant>(V))
73 std::cerr << "While deleting: " << *this
74 << "\n\nUse still stuck around after Def is destroyed: "
77 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
78 Constant *CPV = cast<Constant>(V);
79 CPV->destroyConstant();
81 // The constant should remove itself from our use list...
82 assert((use_empty() || use_back() != V) && "Constant not removed!");
85 // Value has no outstanding references it is safe to delete it now...
89 //===----------------------------------------------------------------------===//
90 // ConstantXXX Classes
91 //===----------------------------------------------------------------------===//
93 //===----------------------------------------------------------------------===//
94 // Normal Constructors
96 ConstantBool::ConstantBool(bool V) : ConstantGenericIntegral(Type::BoolTy) {
100 ConstantInt::ConstantInt(const Type *Ty, uint64_t V)
101 : ConstantGenericIntegral(Ty) {
105 ConstantSInt::ConstantSInt(const Type *Ty, int64_t V) : ConstantInt(Ty, V) {
106 assert(isValueValidForType(Ty, V) && "Value too large for type!");
109 ConstantUInt::ConstantUInt(const Type *Ty, uint64_t V) : ConstantInt(Ty, V) {
110 assert(isValueValidForType(Ty, V) && "Value too large for type!");
113 ConstantFP::ConstantFP(const Type *Ty, double V) : Constant(Ty) {
114 assert(isValueValidForType(Ty, V) && "Value too large for type!");
118 ConstantArray::ConstantArray(const ArrayType *T,
119 const std::vector<Constant*> &V) : Constant(T) {
120 for (unsigned i = 0; i < V.size(); i++) {
121 assert(V[i]->getType() == T->getElementType());
122 Operands.push_back(Use(V[i], this));
126 ConstantStruct::ConstantStruct(const StructType *T,
127 const std::vector<Constant*> &V) : Constant(T) {
128 const StructType::ElementTypes &ETypes = T->getElementTypes();
129 assert(V.size() == ETypes.size() &&
130 "Invalid initializer vector for constant structure");
131 for (unsigned i = 0; i < V.size(); i++) {
132 assert(V[i]->getType() == ETypes[i]);
133 Operands.push_back(Use(V[i], this));
137 ConstantPointerRef::ConstantPointerRef(GlobalValue *GV)
138 : ConstantPointer(GV->getType()) {
139 Operands.push_back(Use(GV, this));
142 ConstantExpr::ConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
143 : Constant(Ty), iType(Opcode) {
144 Operands.push_back(Use(C, this));
147 ConstantExpr::ConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
148 : Constant(C1->getType()), iType(Opcode) {
149 Operands.push_back(Use(C1, this));
150 Operands.push_back(Use(C2, this));
153 ConstantExpr::ConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
155 : Constant(DestTy), iType(Instruction::GetElementPtr) {
156 Operands.reserve(1+IdxList.size());
157 Operands.push_back(Use(C, this));
158 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
159 Operands.push_back(Use(IdxList[i], this));
164 //===----------------------------------------------------------------------===//
165 // classof implementations
167 bool ConstantGenericIntegral::classof(const Constant *CPV) {
168 return (CPV->getType()->isIntegral() || CPV->getType() == Type::BoolTy) &&
169 !isa<ConstantExpr>(CPV);
172 bool ConstantInt::classof(const Constant *CPV) {
173 return CPV->getType()->isIntegral() && !isa<ConstantExpr>(CPV);
175 bool ConstantSInt::classof(const Constant *CPV) {
176 return CPV->getType()->isSigned() && !isa<ConstantExpr>(CPV);
178 bool ConstantUInt::classof(const Constant *CPV) {
179 return CPV->getType()->isUnsigned() && !isa<ConstantExpr>(CPV);
181 bool ConstantFP::classof(const Constant *CPV) {
182 const Type *Ty = CPV->getType();
183 return ((Ty == Type::FloatTy || Ty == Type::DoubleTy) &&
184 !isa<ConstantExpr>(CPV));
186 bool ConstantArray::classof(const Constant *CPV) {
187 return isa<ArrayType>(CPV->getType()) && !isa<ConstantExpr>(CPV);
189 bool ConstantStruct::classof(const Constant *CPV) {
190 return isa<StructType>(CPV->getType()) && !isa<ConstantExpr>(CPV);
192 bool ConstantPointer::classof(const Constant *CPV) {
193 return (isa<PointerType>(CPV->getType()) && !isa<ConstantExpr>(CPV));
198 //===----------------------------------------------------------------------===//
199 // isValueValidForType implementations
201 bool ConstantSInt::isValueValidForType(const Type *Ty, int64_t Val) {
202 switch (Ty->getPrimitiveID()) {
204 return false; // These can't be represented as integers!!!
207 case Type::SByteTyID:
208 return (Val <= INT8_MAX && Val >= INT8_MIN);
209 case Type::ShortTyID:
210 return (Val <= INT16_MAX && Val >= INT16_MIN);
212 return (Val <= INT32_MAX && Val >= INT32_MIN);
214 return true; // This is the largest type...
220 bool ConstantUInt::isValueValidForType(const Type *Ty, uint64_t Val) {
221 switch (Ty->getPrimitiveID()) {
223 return false; // These can't be represented as integers!!!
226 case Type::UByteTyID:
227 return (Val <= UINT8_MAX);
228 case Type::UShortTyID:
229 return (Val <= UINT16_MAX);
231 return (Val <= UINT32_MAX);
232 case Type::ULongTyID:
233 return true; // This is the largest type...
239 bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
240 switch (Ty->getPrimitiveID()) {
242 return false; // These can't be represented as floating point!
244 // TODO: Figure out how to test if a double can be cast to a float!
245 case Type::FloatTyID:
247 return (Val <= UINT8_MAX);
249 case Type::DoubleTyID:
250 return true; // This is the largest type...
254 //===----------------------------------------------------------------------===//
255 // Factory Function Implementation
257 template<class ValType, class ConstantClass>
259 typedef pair<const Type*, ValType> ConstHashKey;
260 map<ConstHashKey, ConstantClass *> Map;
262 inline ConstantClass *get(const Type *Ty, ValType V) {
263 typename map<ConstHashKey,ConstantClass *>::iterator I =
264 Map.find(ConstHashKey(Ty, V));
265 return (I != Map.end()) ? I->second : 0;
268 inline void add(const Type *Ty, ValType V, ConstantClass *CP) {
269 Map.insert(make_pair(ConstHashKey(Ty, V), CP));
272 inline void remove(ConstantClass *CP) {
273 for (typename map<ConstHashKey,ConstantClass *>::iterator I = Map.begin(),
274 E = Map.end(); I != E;++I)
275 if (I->second == CP) {
282 //---- ConstantUInt::get() and ConstantSInt::get() implementations...
284 static ValueMap<uint64_t, ConstantInt> IntConstants;
286 ConstantSInt *ConstantSInt::get(const Type *Ty, int64_t V) {
287 ConstantSInt *Result = (ConstantSInt*)IntConstants.get(Ty, (uint64_t)V);
288 if (!Result) // If no preexisting value, create one now...
289 IntConstants.add(Ty, V, Result = new ConstantSInt(Ty, V));
293 ConstantUInt *ConstantUInt::get(const Type *Ty, uint64_t V) {
294 ConstantUInt *Result = (ConstantUInt*)IntConstants.get(Ty, V);
295 if (!Result) // If no preexisting value, create one now...
296 IntConstants.add(Ty, V, Result = new ConstantUInt(Ty, V));
300 ConstantInt *ConstantInt::get(const Type *Ty, unsigned char V) {
301 assert(V <= 127 && "Can only be used with very small positive constants!");
302 if (Ty->isSigned()) return ConstantSInt::get(Ty, V);
303 return ConstantUInt::get(Ty, V);
306 //---- ConstantFP::get() implementation...
308 static ValueMap<double, ConstantFP> FPConstants;
310 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
311 ConstantFP *Result = FPConstants.get(Ty, V);
312 if (!Result) // If no preexisting value, create one now...
313 FPConstants.add(Ty, V, Result = new ConstantFP(Ty, V));
317 //---- ConstantArray::get() implementation...
319 static ValueMap<std::vector<Constant*>, ConstantArray> ArrayConstants;
321 ConstantArray *ConstantArray::get(const ArrayType *Ty,
322 const std::vector<Constant*> &V) {
323 ConstantArray *Result = ArrayConstants.get(Ty, V);
324 if (!Result) // If no preexisting value, create one now...
325 ArrayConstants.add(Ty, V, Result = new ConstantArray(Ty, V));
329 // ConstantArray::get(const string&) - Return an array that is initialized to
330 // contain the specified string. A null terminator is added to the specified
331 // string so that it may be used in a natural way...
333 ConstantArray *ConstantArray::get(const std::string &Str) {
334 std::vector<Constant*> ElementVals;
336 for (unsigned i = 0; i < Str.length(); ++i)
337 ElementVals.push_back(ConstantSInt::get(Type::SByteTy, Str[i]));
339 // Add a null terminator to the string...
340 ElementVals.push_back(ConstantSInt::get(Type::SByteTy, 0));
342 ArrayType *ATy = ArrayType::get(Type::SByteTy, Str.length()+1);
343 return ConstantArray::get(ATy, ElementVals);
347 // destroyConstant - Remove the constant from the constant table...
349 void ConstantArray::destroyConstant() {
350 ArrayConstants.remove(this);
351 destroyConstantImpl();
354 //---- ConstantStruct::get() implementation...
356 static ValueMap<std::vector<Constant*>, ConstantStruct> StructConstants;
358 ConstantStruct *ConstantStruct::get(const StructType *Ty,
359 const std::vector<Constant*> &V) {
360 ConstantStruct *Result = StructConstants.get(Ty, V);
361 if (!Result) // If no preexisting value, create one now...
362 StructConstants.add(Ty, V, Result = new ConstantStruct(Ty, V));
366 // destroyConstant - Remove the constant from the constant table...
368 void ConstantStruct::destroyConstant() {
369 StructConstants.remove(this);
370 destroyConstantImpl();
373 //---- ConstantPointerNull::get() implementation...
375 static ValueMap<char, ConstantPointerNull> NullPtrConstants;
377 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
378 ConstantPointerNull *Result = NullPtrConstants.get(Ty, 0);
379 if (!Result) // If no preexisting value, create one now...
380 NullPtrConstants.add(Ty, 0, Result = new ConstantPointerNull(Ty));
384 //---- ConstantPointerRef::get() implementation...
386 ConstantPointerRef *ConstantPointerRef::get(GlobalValue *GV) {
387 assert(GV->getParent() && "Global Value must be attached to a module!");
389 // The Module handles the pointer reference sharing...
390 return GV->getParent()->getConstantPointerRef(GV);
393 //---- ConstantExpr::get() implementations...
395 typedef pair<unsigned, vector<Constant*> > ExprMapKeyType;
396 static ValueMap<const ExprMapKeyType, ConstantExpr> ExprConstants;
398 ConstantExpr *ConstantExpr::get(unsigned Opcode, Constant *C, const Type *Ty) {
400 // Look up the constant in the table first to ensure uniqueness
401 vector<Constant*> argVec(1, C);
402 const ExprMapKeyType &Key = make_pair(Opcode, argVec);
403 ConstantExpr *Result = ExprConstants.get(Ty, Key);
404 if (Result) return Result;
406 // Its not in the table so create a new one and put it in the table.
407 // Check the operands for consistency first
408 assert(Opcode == Instruction::Cast ||
409 (Opcode >= Instruction::FirstUnaryOp &&
410 Opcode < Instruction::NumUnaryOps) &&
411 "Invalid opcode in unary ConstantExpr!");
413 // type of operand will not match result for Cast operation
414 assert((Opcode == Instruction::Cast || Ty == C->getType()) &&
415 "Type of operand in unary constant expression should match result");
417 Result = new ConstantExpr(Opcode, C, Ty);
418 ExprConstants.add(Ty, Key, Result);
422 ConstantExpr *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
423 // Look up the constant in the table first to ensure uniqueness
424 vector<Constant*> argVec(1, C1); argVec.push_back(C2);
425 const ExprMapKeyType &Key = make_pair(Opcode, argVec);
426 ConstantExpr *Result = ExprConstants.get(C1->getType(), Key);
427 if (Result) return Result;
429 // Its not in the table so create a new one and put it in the table.
430 // Check the operands for consistency first
431 assert((Opcode >= Instruction::FirstBinaryOp &&
432 Opcode < Instruction::NumBinaryOps) &&
433 "Invalid opcode in binary constant expression");
435 assert(C1->getType() == C2->getType() &&
436 "Operand types in binary constant expression should match");
438 Result = new ConstantExpr(Opcode, C1, C2);
439 ExprConstants.add(C1->getType(), Key, Result);
443 ConstantExpr *ConstantExpr::getGetElementPtr(Constant *C,
444 const std::vector<Constant*> &IdxList) {
445 const Type *Ty = C->getType();
447 // Look up the constant in the table first to ensure uniqueness
448 vector<Constant*> argVec(1, C);
449 argVec.insert(argVec.end(), IdxList.begin(), IdxList.end());
451 const ExprMapKeyType &Key = make_pair(Instruction::GetElementPtr, argVec);
452 ConstantExpr *Result = ExprConstants.get(Ty, Key);
453 if (Result) return Result;
455 // Its not in the table so create a new one and put it in the table.
456 // Check the operands for consistency first
458 assert(isa<PointerType>(Ty) &&
459 "Non-pointer type for constant GelElementPtr expression");
461 // Check that the indices list is valid...
462 std::vector<Value*> ValIdxList(IdxList.begin(), IdxList.end());
463 const Type *DestTy = GetElementPtrInst::getIndexedType(Ty, ValIdxList, true);
464 assert(DestTy && "Invalid index list for constant GelElementPtr expression");
466 Result = new ConstantExpr(C, IdxList, PointerType::get(DestTy));
467 ExprConstants.add(Ty, Key, Result);
471 // destroyConstant - Remove the constant from the constant table...
473 void ConstantExpr::destroyConstant() {
474 ExprConstants.remove(this);
475 destroyConstantImpl();
478 const char *ConstantExpr::getOpcodeName() const {
479 return Instruction::getOpcodeName(getOpcode());
483 //---- ConstantPointerRef::mutateReferences() implementation...
485 unsigned ConstantPointerRef::mutateReferences(Value *OldV, Value *NewV) {
486 assert(getValue() == OldV && "Cannot mutate old value if I'm not using it!");
487 GlobalValue *NewGV = cast<GlobalValue>(NewV);
488 getValue()->getParent()->mutateConstantPointerRef(getValue(), NewGV);
494 //---- ConstantPointerExpr::mutateReferences() implementation...
496 unsigned ConstantExpr::mutateReferences(Value* OldV, Value *NewV) {
497 unsigned NumReplaced = 0;
498 Constant *NewC = cast<Constant>(NewV);
499 for (unsigned i = 0, N = getNumOperands(); i != N; ++i)
500 if (Operands[i] == OldV) {