1 //===-- Constants.cpp - Implement Constant nodes --------------------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Constant* classes...
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Constants.h"
15 #include "ConstantFolding.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/GlobalValue.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/SymbolTable.h"
20 #include "llvm/Module.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/Support/Compiler.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/ManagedStatic.h"
25 #include "llvm/Support/MathExtras.h"
29 //===----------------------------------------------------------------------===//
31 //===----------------------------------------------------------------------===//
33 void Constant::destroyConstantImpl() {
34 // When a Constant is destroyed, there may be lingering
35 // references to the constant by other constants in the constant pool. These
36 // constants are implicitly dependent on the module that is being deleted,
37 // 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
39 // Constants) that they are, in fact, invalid now and should be deleted.
41 while (!use_empty()) {
42 Value *V = use_back();
43 #ifndef NDEBUG // Only in -g mode...
44 if (!isa<Constant>(V))
45 DOUT << "While deleting: " << *this
46 << "\n\nUse still stuck around after Def is destroyed: "
49 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
50 Constant *CV = cast<Constant>(V);
51 CV->destroyConstant();
53 // The constant should remove itself from our use list...
54 assert((use_empty() || use_back() != V) && "Constant not removed!");
57 // Value has no outstanding references it is safe to delete it now...
61 /// canTrap - Return true if evaluation of this constant could trap. This is
62 /// true for things like constant expressions that could divide by zero.
63 bool 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;
69 // ConstantExpr traps if any operands can trap.
70 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
71 if (getOperand(i)->canTrap())
74 // Otherwise, only specific operations can trap.
75 switch (CE->getOpcode()) {
78 case Instruction::UDiv:
79 case Instruction::SDiv:
80 case Instruction::FDiv:
81 case Instruction::URem:
82 case Instruction::SRem:
83 case Instruction::FRem:
84 // Div and rem can trap if the RHS is not known to be non-zero.
85 if (!isa<ConstantInt>(getOperand(1)) || getOperand(1)->isNullValue())
92 // Static constructor to create a '0' constant of arbitrary type...
93 Constant *Constant::getNullValue(const Type *Ty) {
94 switch (Ty->getTypeID()) {
95 case Type::BoolTyID: {
96 static Constant *NullBool = ConstantBool::get(false);
99 case Type::SByteTyID: {
100 static Constant *NullSByte = ConstantInt::get(Type::SByteTy, 0);
103 case Type::UByteTyID: {
104 static Constant *NullUByte = ConstantInt::get(Type::UByteTy, 0);
107 case Type::ShortTyID: {
108 static Constant *NullShort = ConstantInt::get(Type::ShortTy, 0);
111 case Type::UShortTyID: {
112 static Constant *NullUShort = ConstantInt::get(Type::UShortTy, 0);
115 case Type::IntTyID: {
116 static Constant *NullInt = ConstantInt::get(Type::IntTy, 0);
119 case Type::UIntTyID: {
120 static Constant *NullUInt = ConstantInt::get(Type::UIntTy, 0);
123 case Type::LongTyID: {
124 static Constant *NullLong = ConstantInt::get(Type::LongTy, 0);
127 case Type::ULongTyID: {
128 static Constant *NullULong = ConstantInt::get(Type::ULongTy, 0);
132 case Type::FloatTyID: {
133 static Constant *NullFloat = ConstantFP::get(Type::FloatTy, 0);
136 case Type::DoubleTyID: {
137 static Constant *NullDouble = ConstantFP::get(Type::DoubleTy, 0);
141 case Type::PointerTyID:
142 return ConstantPointerNull::get(cast<PointerType>(Ty));
144 case Type::StructTyID:
145 case Type::ArrayTyID:
146 case Type::PackedTyID:
147 return ConstantAggregateZero::get(Ty);
149 // Function, Label, or Opaque type?
150 assert(!"Cannot create a null constant of that type!");
156 // Static constructor to create an integral constant with all bits set
157 ConstantIntegral *ConstantIntegral::getAllOnesValue(const Type *Ty) {
158 switch (Ty->getTypeID()) {
159 case Type::BoolTyID: return ConstantBool::getTrue();
160 case Type::SByteTyID:
161 case Type::ShortTyID:
163 case Type::LongTyID: return ConstantInt::get(Ty, -1);
165 case Type::UByteTyID:
166 case Type::UShortTyID:
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...
173 return ConstantInt::get(Ty, Val);
179 //===----------------------------------------------------------------------===//
180 // ConstantXXX Classes
181 //===----------------------------------------------------------------------===//
183 //===----------------------------------------------------------------------===//
184 // Normal Constructors
186 ConstantIntegral::ConstantIntegral(const Type *Ty, ValueTy VT, uint64_t V)
187 : Constant(Ty, VT, 0, 0), Val(V) {
190 ConstantBool::ConstantBool(bool V)
191 : ConstantIntegral(Type::BoolTy, ConstantBoolVal, uint64_t(V)) {
194 ConstantInt::ConstantInt(const Type *Ty, uint64_t V)
195 : ConstantIntegral(Ty, ConstantIntVal, V) {
198 ConstantFP::ConstantFP(const Type *Ty, double V)
199 : Constant(Ty, ConstantFPVal, 0, 0) {
200 assert(isValueValidForType(Ty, V) && "Value too large for type!");
204 ConstantArray::ConstantArray(const ArrayType *T,
205 const std::vector<Constant*> &V)
206 : Constant(T, ConstantArrayVal, new Use[V.size()], V.size()) {
207 assert(V.size() == T->getNumElements() &&
208 "Invalid initializer vector for constant array");
209 Use *OL = OperandList;
210 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
213 assert((C->getType() == T->getElementType() ||
215 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
216 "Initializer for array element doesn't match array element type!");
221 ConstantArray::~ConstantArray() {
222 delete [] OperandList;
225 ConstantStruct::ConstantStruct(const StructType *T,
226 const std::vector<Constant*> &V)
227 : Constant(T, ConstantStructVal, new Use[V.size()], V.size()) {
228 assert(V.size() == T->getNumElements() &&
229 "Invalid initializer vector for constant structure");
230 Use *OL = OperandList;
231 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
234 assert((C->getType() == T->getElementType(I-V.begin()) ||
235 ((T->getElementType(I-V.begin())->isAbstract() ||
236 C->getType()->isAbstract()) &&
237 T->getElementType(I-V.begin())->getTypeID() ==
238 C->getType()->getTypeID())) &&
239 "Initializer for struct element doesn't match struct element type!");
244 ConstantStruct::~ConstantStruct() {
245 delete [] OperandList;
249 ConstantPacked::ConstantPacked(const PackedType *T,
250 const std::vector<Constant*> &V)
251 : Constant(T, ConstantPackedVal, new Use[V.size()], V.size()) {
252 Use *OL = OperandList;
253 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
256 assert((C->getType() == T->getElementType() ||
258 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
259 "Initializer for packed element doesn't match packed element type!");
264 ConstantPacked::~ConstantPacked() {
265 delete [] OperandList;
268 // We declare several classes private to this file, so use an anonymous
272 /// UnaryConstantExpr - This class is private to Constants.cpp, and is used
273 /// behind the scenes to implement unary constant exprs.
274 class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
277 UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
278 : ConstantExpr(Ty, Opcode, &Op, 1), Op(C, this) {}
281 /// BinaryConstantExpr - This class is private to Constants.cpp, and is used
282 /// behind the scenes to implement binary constant exprs.
283 class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
286 BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
287 : ConstantExpr(C1->getType(), Opcode, Ops, 2) {
288 Ops[0].init(C1, this);
289 Ops[1].init(C2, this);
293 /// SelectConstantExpr - This class is private to Constants.cpp, and is used
294 /// behind the scenes to implement select constant exprs.
295 class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
298 SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
299 : ConstantExpr(C2->getType(), Instruction::Select, Ops, 3) {
300 Ops[0].init(C1, this);
301 Ops[1].init(C2, this);
302 Ops[2].init(C3, this);
306 /// ExtractElementConstantExpr - This class is private to
307 /// Constants.cpp, and is used behind the scenes to implement
308 /// extractelement constant exprs.
309 class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
312 ExtractElementConstantExpr(Constant *C1, Constant *C2)
313 : ConstantExpr(cast<PackedType>(C1->getType())->getElementType(),
314 Instruction::ExtractElement, Ops, 2) {
315 Ops[0].init(C1, this);
316 Ops[1].init(C2, this);
320 /// InsertElementConstantExpr - This class is private to
321 /// Constants.cpp, and is used behind the scenes to implement
322 /// insertelement constant exprs.
323 class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
326 InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
327 : ConstantExpr(C1->getType(), Instruction::InsertElement,
329 Ops[0].init(C1, this);
330 Ops[1].init(C2, this);
331 Ops[2].init(C3, this);
335 /// ShuffleVectorConstantExpr - This class is private to
336 /// Constants.cpp, and is used behind the scenes to implement
337 /// shufflevector constant exprs.
338 class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
341 ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
342 : ConstantExpr(C1->getType(), Instruction::ShuffleVector,
344 Ops[0].init(C1, this);
345 Ops[1].init(C2, this);
346 Ops[2].init(C3, this);
350 /// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
351 /// used behind the scenes to implement getelementpr constant exprs.
352 struct VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
353 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
355 : ConstantExpr(DestTy, Instruction::GetElementPtr,
356 new Use[IdxList.size()+1], IdxList.size()+1) {
357 OperandList[0].init(C, this);
358 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
359 OperandList[i+1].init(IdxList[i], this);
361 ~GetElementPtrConstantExpr() {
362 delete [] OperandList;
366 // CompareConstantExpr - This class is private to Constants.cpp, and is used
367 // behind the scenes to implement ICmp and FCmp constant expressions. This is
368 // needed in order to store the predicate value for these instructions.
369 struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
370 unsigned short predicate;
372 CompareConstantExpr(Instruction::OtherOps opc, unsigned short pred,
373 Constant* LHS, Constant* RHS)
374 : ConstantExpr(Type::BoolTy, opc, Ops, 2), predicate(pred) {
375 OperandList[0].init(LHS, this);
376 OperandList[1].init(RHS, this);
380 } // end anonymous namespace
383 // Utility function for determining if a ConstantExpr is a CastOp or not. This
384 // can't be inline because we don't want to #include Instruction.h into
386 bool ConstantExpr::isCast() const {
387 return Instruction::isCast(getOpcode());
390 bool ConstantExpr::isCompare() const {
391 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
394 /// ConstantExpr::get* - Return some common constants without having to
395 /// specify the full Instruction::OPCODE identifier.
397 Constant *ConstantExpr::getNeg(Constant *C) {
398 if (!C->getType()->isFloatingPoint())
399 return get(Instruction::Sub, getNullValue(C->getType()), C);
401 return get(Instruction::Sub, ConstantFP::get(C->getType(), -0.0), C);
403 Constant *ConstantExpr::getNot(Constant *C) {
404 assert(isa<ConstantIntegral>(C) && "Cannot NOT a nonintegral type!");
405 return get(Instruction::Xor, C,
406 ConstantIntegral::getAllOnesValue(C->getType()));
408 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
409 return get(Instruction::Add, C1, C2);
411 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
412 return get(Instruction::Sub, C1, C2);
414 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
415 return get(Instruction::Mul, C1, C2);
417 Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2) {
418 return get(Instruction::UDiv, C1, C2);
420 Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2) {
421 return get(Instruction::SDiv, C1, C2);
423 Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
424 return get(Instruction::FDiv, C1, C2);
426 Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
427 return get(Instruction::URem, C1, C2);
429 Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
430 return get(Instruction::SRem, C1, C2);
432 Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
433 return get(Instruction::FRem, C1, C2);
435 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
436 return get(Instruction::And, C1, C2);
438 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
439 return get(Instruction::Or, C1, C2);
441 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
442 return get(Instruction::Xor, C1, C2);
444 unsigned ConstantExpr::getPredicate() const {
445 assert(getOpcode() == Instruction::FCmp || getOpcode() == Instruction::ICmp);
446 return dynamic_cast<const CompareConstantExpr*>(this)->predicate;
448 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
449 return get(Instruction::Shl, C1, C2);
451 Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2) {
452 return get(Instruction::LShr, C1, C2);
454 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2) {
455 return get(Instruction::AShr, C1, C2);
458 /// getWithOperandReplaced - Return a constant expression identical to this
459 /// one, but with the specified operand set to the specified value.
461 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
462 assert(OpNo < getNumOperands() && "Operand num is out of range!");
463 assert(Op->getType() == getOperand(OpNo)->getType() &&
464 "Replacing operand with value of different type!");
465 if (getOperand(OpNo) == Op)
466 return const_cast<ConstantExpr*>(this);
468 Constant *Op0, *Op1, *Op2;
469 switch (getOpcode()) {
470 case Instruction::Trunc:
471 case Instruction::ZExt:
472 case Instruction::SExt:
473 case Instruction::FPTrunc:
474 case Instruction::FPExt:
475 case Instruction::UIToFP:
476 case Instruction::SIToFP:
477 case Instruction::FPToUI:
478 case Instruction::FPToSI:
479 case Instruction::PtrToInt:
480 case Instruction::IntToPtr:
481 case Instruction::BitCast:
482 return ConstantExpr::getCast(getOpcode(), Op, getType());
483 case Instruction::Select:
484 Op0 = (OpNo == 0) ? Op : getOperand(0);
485 Op1 = (OpNo == 1) ? Op : getOperand(1);
486 Op2 = (OpNo == 2) ? Op : getOperand(2);
487 return ConstantExpr::getSelect(Op0, Op1, Op2);
488 case Instruction::InsertElement:
489 Op0 = (OpNo == 0) ? Op : getOperand(0);
490 Op1 = (OpNo == 1) ? Op : getOperand(1);
491 Op2 = (OpNo == 2) ? Op : getOperand(2);
492 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
493 case Instruction::ExtractElement:
494 Op0 = (OpNo == 0) ? Op : getOperand(0);
495 Op1 = (OpNo == 1) ? Op : getOperand(1);
496 return ConstantExpr::getExtractElement(Op0, Op1);
497 case Instruction::ShuffleVector:
498 Op0 = (OpNo == 0) ? Op : getOperand(0);
499 Op1 = (OpNo == 1) ? Op : getOperand(1);
500 Op2 = (OpNo == 2) ? Op : getOperand(2);
501 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
502 case Instruction::GetElementPtr: {
503 std::vector<Constant*> Ops;
504 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
505 Ops.push_back(getOperand(i));
507 return ConstantExpr::getGetElementPtr(Op, Ops);
509 return ConstantExpr::getGetElementPtr(getOperand(0), Ops);
512 assert(getNumOperands() == 2 && "Must be binary operator?");
513 Op0 = (OpNo == 0) ? Op : getOperand(0);
514 Op1 = (OpNo == 1) ? Op : getOperand(1);
515 return ConstantExpr::get(getOpcode(), Op0, Op1);
519 /// getWithOperands - This returns the current constant expression with the
520 /// operands replaced with the specified values. The specified operands must
521 /// match count and type with the existing ones.
522 Constant *ConstantExpr::
523 getWithOperands(const std::vector<Constant*> &Ops) const {
524 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
525 bool AnyChange = false;
526 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
527 assert(Ops[i]->getType() == getOperand(i)->getType() &&
528 "Operand type mismatch!");
529 AnyChange |= Ops[i] != getOperand(i);
531 if (!AnyChange) // No operands changed, return self.
532 return const_cast<ConstantExpr*>(this);
534 switch (getOpcode()) {
535 case Instruction::Trunc:
536 case Instruction::ZExt:
537 case Instruction::SExt:
538 case Instruction::FPTrunc:
539 case Instruction::FPExt:
540 case Instruction::UIToFP:
541 case Instruction::SIToFP:
542 case Instruction::FPToUI:
543 case Instruction::FPToSI:
544 case Instruction::PtrToInt:
545 case Instruction::IntToPtr:
546 case Instruction::BitCast:
547 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
548 case Instruction::Select:
549 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
550 case Instruction::InsertElement:
551 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
552 case Instruction::ExtractElement:
553 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
554 case Instruction::ShuffleVector:
555 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
556 case Instruction::GetElementPtr: {
557 std::vector<Constant*> ActualOps(Ops.begin()+1, Ops.end());
558 return ConstantExpr::getGetElementPtr(Ops[0], ActualOps);
560 case Instruction::ICmp:
561 case Instruction::FCmp:
562 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
564 assert(getNumOperands() == 2 && "Must be binary operator?");
565 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
570 //===----------------------------------------------------------------------===//
571 // isValueValidForType implementations
573 bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
574 switch (Ty->getTypeID()) {
575 default: return false; // These can't be represented as integers!
576 case Type::SByteTyID:
577 case Type::UByteTyID: return Val <= UINT8_MAX;
578 case Type::ShortTyID:
579 case Type::UShortTyID:return Val <= UINT16_MAX;
581 case Type::UIntTyID: return Val <= UINT32_MAX;
583 case Type::ULongTyID: return true; // always true, has to fit in largest type
587 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
588 switch (Ty->getTypeID()) {
589 default: return false; // These can't be represented as integers!
590 case Type::SByteTyID:
591 case Type::UByteTyID: return (Val >= INT8_MIN && Val <= INT8_MAX);
592 case Type::ShortTyID:
593 case Type::UShortTyID:return (Val >= INT16_MIN && Val <= UINT16_MAX);
595 case Type::UIntTyID: return (Val >= INT32_MIN && Val <= UINT32_MAX);
597 case Type::ULongTyID: return true; // always true, has to fit in largest type
601 bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
602 switch (Ty->getTypeID()) {
604 return false; // These can't be represented as floating point!
606 // TODO: Figure out how to test if a double can be cast to a float!
607 case Type::FloatTyID:
608 case Type::DoubleTyID:
609 return true; // This is the largest type...
613 //===----------------------------------------------------------------------===//
614 // Factory Function Implementation
616 // ConstantCreator - A class that is used to create constants by
617 // ValueMap*. This class should be partially specialized if there is
618 // something strange that needs to be done to interface to the ctor for the
622 template<class ConstantClass, class TypeClass, class ValType>
623 struct VISIBILITY_HIDDEN ConstantCreator {
624 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
625 return new ConstantClass(Ty, V);
629 template<class ConstantClass, class TypeClass>
630 struct VISIBILITY_HIDDEN ConvertConstantType {
631 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
632 assert(0 && "This type cannot be converted!\n");
637 template<class ValType, class TypeClass, class ConstantClass,
638 bool HasLargeKey = false /*true for arrays and structs*/ >
639 class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
641 typedef std::pair<const Type*, ValType> MapKey;
642 typedef std::map<MapKey, Constant *> MapTy;
643 typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
644 typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
646 /// Map - This is the main map from the element descriptor to the Constants.
647 /// This is the primary way we avoid creating two of the same shape
651 /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
652 /// from the constants to their element in Map. This is important for
653 /// removal of constants from the array, which would otherwise have to scan
654 /// through the map with very large keys.
655 InverseMapTy InverseMap;
657 /// AbstractTypeMap - Map for abstract type constants.
659 AbstractTypeMapTy AbstractTypeMap;
662 void clear(std::vector<Constant *> &Constants) {
663 for(typename MapTy::iterator I = Map.begin(); I != Map.end(); ++I)
664 Constants.push_back(I->second);
666 AbstractTypeMap.clear();
671 typename MapTy::iterator map_end() { return Map.end(); }
673 /// InsertOrGetItem - Return an iterator for the specified element.
674 /// If the element exists in the map, the returned iterator points to the
675 /// entry and Exists=true. If not, the iterator points to the newly
676 /// inserted entry and returns Exists=false. Newly inserted entries have
677 /// I->second == 0, and should be filled in.
678 typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
681 std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
687 typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
689 typename InverseMapTy::iterator IMI = InverseMap.find(CP);
690 assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
691 IMI->second->second == CP &&
692 "InverseMap corrupt!");
696 typename MapTy::iterator I =
697 Map.find(MapKey((TypeClass*)CP->getRawType(), getValType(CP)));
698 if (I == Map.end() || I->second != CP) {
699 // FIXME: This should not use a linear scan. If this gets to be a
700 // performance problem, someone should look at this.
701 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
708 /// getOrCreate - Return the specified constant from the map, creating it if
710 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
711 MapKey Lookup(Ty, V);
712 typename MapTy::iterator I = Map.lower_bound(Lookup);
714 if (I != Map.end() && I->first == Lookup)
715 return static_cast<ConstantClass *>(I->second);
717 // If no preexisting value, create one now...
718 ConstantClass *Result =
719 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
721 /// FIXME: why does this assert fail when loading 176.gcc?
722 //assert(Result->getType() == Ty && "Type specified is not correct!");
723 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
725 if (HasLargeKey) // Remember the reverse mapping if needed.
726 InverseMap.insert(std::make_pair(Result, I));
728 // If the type of the constant is abstract, make sure that an entry exists
729 // for it in the AbstractTypeMap.
730 if (Ty->isAbstract()) {
731 typename AbstractTypeMapTy::iterator TI =
732 AbstractTypeMap.lower_bound(Ty);
734 if (TI == AbstractTypeMap.end() || TI->first != Ty) {
735 // Add ourselves to the ATU list of the type.
736 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
738 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
744 void remove(ConstantClass *CP) {
745 typename MapTy::iterator I = FindExistingElement(CP);
746 assert(I != Map.end() && "Constant not found in constant table!");
747 assert(I->second == CP && "Didn't find correct element?");
749 if (HasLargeKey) // Remember the reverse mapping if needed.
750 InverseMap.erase(CP);
752 // Now that we found the entry, make sure this isn't the entry that
753 // the AbstractTypeMap points to.
754 const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
755 if (Ty->isAbstract()) {
756 assert(AbstractTypeMap.count(Ty) &&
757 "Abstract type not in AbstractTypeMap?");
758 typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
759 if (ATMEntryIt == I) {
760 // Yes, we are removing the representative entry for this type.
761 // See if there are any other entries of the same type.
762 typename MapTy::iterator TmpIt = ATMEntryIt;
764 // First check the entry before this one...
765 if (TmpIt != Map.begin()) {
767 if (TmpIt->first.first != Ty) // Not the same type, move back...
771 // If we didn't find the same type, try to move forward...
772 if (TmpIt == ATMEntryIt) {
774 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
775 --TmpIt; // No entry afterwards with the same type
778 // If there is another entry in the map of the same abstract type,
779 // update the AbstractTypeMap entry now.
780 if (TmpIt != ATMEntryIt) {
783 // Otherwise, we are removing the last instance of this type
784 // from the table. Remove from the ATM, and from user list.
785 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
786 AbstractTypeMap.erase(Ty);
795 /// MoveConstantToNewSlot - If we are about to change C to be the element
796 /// specified by I, update our internal data structures to reflect this
798 void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
799 // First, remove the old location of the specified constant in the map.
800 typename MapTy::iterator OldI = FindExistingElement(C);
801 assert(OldI != Map.end() && "Constant not found in constant table!");
802 assert(OldI->second == C && "Didn't find correct element?");
804 // If this constant is the representative element for its abstract type,
805 // update the AbstractTypeMap so that the representative element is I.
806 if (C->getType()->isAbstract()) {
807 typename AbstractTypeMapTy::iterator ATI =
808 AbstractTypeMap.find(C->getType());
809 assert(ATI != AbstractTypeMap.end() &&
810 "Abstract type not in AbstractTypeMap?");
811 if (ATI->second == OldI)
815 // Remove the old entry from the map.
818 // Update the inverse map so that we know that this constant is now
819 // located at descriptor I.
821 assert(I->second == C && "Bad inversemap entry!");
826 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
827 typename AbstractTypeMapTy::iterator I =
828 AbstractTypeMap.find(cast<Type>(OldTy));
830 assert(I != AbstractTypeMap.end() &&
831 "Abstract type not in AbstractTypeMap?");
833 // Convert a constant at a time until the last one is gone. The last one
834 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
835 // eliminated eventually.
837 ConvertConstantType<ConstantClass,
839 static_cast<ConstantClass *>(I->second->second),
840 cast<TypeClass>(NewTy));
842 I = AbstractTypeMap.find(cast<Type>(OldTy));
843 } while (I != AbstractTypeMap.end());
846 // If the type became concrete without being refined to any other existing
847 // type, we just remove ourselves from the ATU list.
848 void typeBecameConcrete(const DerivedType *AbsTy) {
849 AbsTy->removeAbstractTypeUser(this);
853 DOUT << "Constant.cpp: ValueMap\n";
859 //---- ConstantBool::get*() implementation.
861 ConstantBool *ConstantBool::getTrue() {
862 static ConstantBool *T = 0;
864 return T = new ConstantBool(true);
866 ConstantBool *ConstantBool::getFalse() {
867 static ConstantBool *F = 0;
869 return F = new ConstantBool(false);
872 //---- ConstantInt::get() implementations...
874 static ManagedStatic<ValueMap<uint64_t, Type, ConstantInt> > IntConstants;
876 // Get a ConstantInt from an int64_t. Note here that we canoncialize the value
877 // to a uint64_t value that has been zero extended down to the size of the
878 // integer type of the ConstantInt. This allows the getZExtValue method to
879 // just return the stored value while getSExtValue has to convert back to sign
880 // extended. getZExtValue is more common in LLVM than getSExtValue().
881 ConstantInt *ConstantInt::get(const Type *Ty, int64_t V) {
882 return IntConstants->getOrCreate(Ty, V & Ty->getIntegralTypeMask());
885 ConstantIntegral *ConstantIntegral::get(const Type *Ty, int64_t V) {
886 if (Ty == Type::BoolTy) return ConstantBool::get(V&1);
887 return IntConstants->getOrCreate(Ty, V & Ty->getIntegralTypeMask());
890 //---- ConstantFP::get() implementation...
894 struct ConstantCreator<ConstantFP, Type, uint64_t> {
895 static ConstantFP *create(const Type *Ty, uint64_t V) {
896 assert(Ty == Type::DoubleTy);
897 return new ConstantFP(Ty, BitsToDouble(V));
901 struct ConstantCreator<ConstantFP, Type, uint32_t> {
902 static ConstantFP *create(const Type *Ty, uint32_t V) {
903 assert(Ty == Type::FloatTy);
904 return new ConstantFP(Ty, BitsToFloat(V));
909 static ManagedStatic<ValueMap<uint64_t, Type, ConstantFP> > DoubleConstants;
910 static ManagedStatic<ValueMap<uint32_t, Type, ConstantFP> > FloatConstants;
912 bool ConstantFP::isNullValue() const {
913 return DoubleToBits(Val) == 0;
916 bool ConstantFP::isExactlyValue(double V) const {
917 return DoubleToBits(V) == DoubleToBits(Val);
921 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
922 if (Ty == Type::FloatTy) {
923 // Force the value through memory to normalize it.
924 return FloatConstants->getOrCreate(Ty, FloatToBits(V));
926 assert(Ty == Type::DoubleTy);
927 return DoubleConstants->getOrCreate(Ty, DoubleToBits(V));
931 //---- ConstantAggregateZero::get() implementation...
934 // ConstantAggregateZero does not take extra "value" argument...
935 template<class ValType>
936 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
937 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
938 return new ConstantAggregateZero(Ty);
943 struct ConvertConstantType<ConstantAggregateZero, Type> {
944 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
945 // Make everyone now use a constant of the new type...
946 Constant *New = ConstantAggregateZero::get(NewTy);
947 assert(New != OldC && "Didn't replace constant??");
948 OldC->uncheckedReplaceAllUsesWith(New);
949 OldC->destroyConstant(); // This constant is now dead, destroy it.
954 static ManagedStatic<ValueMap<char, Type,
955 ConstantAggregateZero> > AggZeroConstants;
957 static char getValType(ConstantAggregateZero *CPZ) { return 0; }
959 Constant *ConstantAggregateZero::get(const Type *Ty) {
960 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<PackedType>(Ty)) &&
961 "Cannot create an aggregate zero of non-aggregate type!");
962 return AggZeroConstants->getOrCreate(Ty, 0);
965 // destroyConstant - Remove the constant from the constant table...
967 void ConstantAggregateZero::destroyConstant() {
968 AggZeroConstants->remove(this);
969 destroyConstantImpl();
972 //---- ConstantArray::get() implementation...
976 struct ConvertConstantType<ConstantArray, ArrayType> {
977 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
978 // Make everyone now use a constant of the new type...
979 std::vector<Constant*> C;
980 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
981 C.push_back(cast<Constant>(OldC->getOperand(i)));
982 Constant *New = ConstantArray::get(NewTy, C);
983 assert(New != OldC && "Didn't replace constant??");
984 OldC->uncheckedReplaceAllUsesWith(New);
985 OldC->destroyConstant(); // This constant is now dead, destroy it.
990 static std::vector<Constant*> getValType(ConstantArray *CA) {
991 std::vector<Constant*> Elements;
992 Elements.reserve(CA->getNumOperands());
993 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
994 Elements.push_back(cast<Constant>(CA->getOperand(i)));
998 typedef ValueMap<std::vector<Constant*>, ArrayType,
999 ConstantArray, true /*largekey*/> ArrayConstantsTy;
1000 static ManagedStatic<ArrayConstantsTy> ArrayConstants;
1002 Constant *ConstantArray::get(const ArrayType *Ty,
1003 const std::vector<Constant*> &V) {
1004 // If this is an all-zero array, return a ConstantAggregateZero object
1007 if (!C->isNullValue())
1008 return ArrayConstants->getOrCreate(Ty, V);
1009 for (unsigned i = 1, e = V.size(); i != e; ++i)
1011 return ArrayConstants->getOrCreate(Ty, V);
1013 return ConstantAggregateZero::get(Ty);
1016 // destroyConstant - Remove the constant from the constant table...
1018 void ConstantArray::destroyConstant() {
1019 ArrayConstants->remove(this);
1020 destroyConstantImpl();
1023 /// ConstantArray::get(const string&) - Return an array that is initialized to
1024 /// contain the specified string. If length is zero then a null terminator is
1025 /// added to the specified string so that it may be used in a natural way.
1026 /// Otherwise, the length parameter specifies how much of the string to use
1027 /// and it won't be null terminated.
1029 Constant *ConstantArray::get(const std::string &Str, bool AddNull) {
1030 std::vector<Constant*> ElementVals;
1031 for (unsigned i = 0; i < Str.length(); ++i)
1032 ElementVals.push_back(ConstantInt::get(Type::SByteTy, Str[i]));
1034 // Add a null terminator to the string...
1036 ElementVals.push_back(ConstantInt::get(Type::SByteTy, 0));
1039 ArrayType *ATy = ArrayType::get(Type::SByteTy, ElementVals.size());
1040 return ConstantArray::get(ATy, ElementVals);
1043 /// isString - This method returns true if the array is an array of sbyte or
1044 /// ubyte, and if the elements of the array are all ConstantInt's.
1045 bool ConstantArray::isString() const {
1046 // Check the element type for sbyte or ubyte...
1047 if (getType()->getElementType() != Type::UByteTy &&
1048 getType()->getElementType() != Type::SByteTy)
1050 // Check the elements to make sure they are all integers, not constant
1052 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1053 if (!isa<ConstantInt>(getOperand(i)))
1058 /// isCString - This method returns true if the array is a string (see
1059 /// isString) and it ends in a null byte \0 and does not contains any other
1060 /// null bytes except its terminator.
1061 bool ConstantArray::isCString() const {
1062 // Check the element type for sbyte or ubyte...
1063 if (getType()->getElementType() != Type::UByteTy &&
1064 getType()->getElementType() != Type::SByteTy)
1066 Constant *Zero = Constant::getNullValue(getOperand(0)->getType());
1067 // Last element must be a null.
1068 if (getOperand(getNumOperands()-1) != Zero)
1070 // Other elements must be non-null integers.
1071 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1072 if (!isa<ConstantInt>(getOperand(i)))
1074 if (getOperand(i) == Zero)
1081 // getAsString - If the sub-element type of this array is either sbyte or ubyte,
1082 // then this method converts the array to an std::string and returns it.
1083 // Otherwise, it asserts out.
1085 std::string ConstantArray::getAsString() const {
1086 assert(isString() && "Not a string!");
1088 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1089 Result += (char)cast<ConstantInt>(getOperand(i))->getZExtValue();
1094 //---- ConstantStruct::get() implementation...
1099 struct ConvertConstantType<ConstantStruct, StructType> {
1100 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1101 // Make everyone now use a constant of the new type...
1102 std::vector<Constant*> C;
1103 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1104 C.push_back(cast<Constant>(OldC->getOperand(i)));
1105 Constant *New = ConstantStruct::get(NewTy, C);
1106 assert(New != OldC && "Didn't replace constant??");
1108 OldC->uncheckedReplaceAllUsesWith(New);
1109 OldC->destroyConstant(); // This constant is now dead, destroy it.
1114 typedef ValueMap<std::vector<Constant*>, StructType,
1115 ConstantStruct, true /*largekey*/> StructConstantsTy;
1116 static ManagedStatic<StructConstantsTy> StructConstants;
1118 static std::vector<Constant*> getValType(ConstantStruct *CS) {
1119 std::vector<Constant*> Elements;
1120 Elements.reserve(CS->getNumOperands());
1121 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1122 Elements.push_back(cast<Constant>(CS->getOperand(i)));
1126 Constant *ConstantStruct::get(const StructType *Ty,
1127 const std::vector<Constant*> &V) {
1128 // Create a ConstantAggregateZero value if all elements are zeros...
1129 for (unsigned i = 0, e = V.size(); i != e; ++i)
1130 if (!V[i]->isNullValue())
1131 return StructConstants->getOrCreate(Ty, V);
1133 return ConstantAggregateZero::get(Ty);
1136 Constant *ConstantStruct::get(const std::vector<Constant*> &V, bool packed) {
1137 std::vector<const Type*> StructEls;
1138 StructEls.reserve(V.size());
1139 for (unsigned i = 0, e = V.size(); i != e; ++i)
1140 StructEls.push_back(V[i]->getType());
1141 return get(StructType::get(StructEls, packed), V);
1144 // destroyConstant - Remove the constant from the constant table...
1146 void ConstantStruct::destroyConstant() {
1147 StructConstants->remove(this);
1148 destroyConstantImpl();
1151 //---- ConstantPacked::get() implementation...
1155 struct ConvertConstantType<ConstantPacked, PackedType> {
1156 static void convert(ConstantPacked *OldC, const PackedType *NewTy) {
1157 // Make everyone now use a constant of the new type...
1158 std::vector<Constant*> C;
1159 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1160 C.push_back(cast<Constant>(OldC->getOperand(i)));
1161 Constant *New = ConstantPacked::get(NewTy, C);
1162 assert(New != OldC && "Didn't replace constant??");
1163 OldC->uncheckedReplaceAllUsesWith(New);
1164 OldC->destroyConstant(); // This constant is now dead, destroy it.
1169 static std::vector<Constant*> getValType(ConstantPacked *CP) {
1170 std::vector<Constant*> Elements;
1171 Elements.reserve(CP->getNumOperands());
1172 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1173 Elements.push_back(CP->getOperand(i));
1177 static ManagedStatic<ValueMap<std::vector<Constant*>, PackedType,
1178 ConstantPacked> > PackedConstants;
1180 Constant *ConstantPacked::get(const PackedType *Ty,
1181 const std::vector<Constant*> &V) {
1182 // If this is an all-zero packed, return a ConstantAggregateZero object
1185 if (!C->isNullValue())
1186 return PackedConstants->getOrCreate(Ty, V);
1187 for (unsigned i = 1, e = V.size(); i != e; ++i)
1189 return PackedConstants->getOrCreate(Ty, V);
1191 return ConstantAggregateZero::get(Ty);
1194 Constant *ConstantPacked::get(const std::vector<Constant*> &V) {
1195 assert(!V.empty() && "Cannot infer type if V is empty");
1196 return get(PackedType::get(V.front()->getType(),V.size()), V);
1199 // destroyConstant - Remove the constant from the constant table...
1201 void ConstantPacked::destroyConstant() {
1202 PackedConstants->remove(this);
1203 destroyConstantImpl();
1206 //---- ConstantPointerNull::get() implementation...
1210 // ConstantPointerNull does not take extra "value" argument...
1211 template<class ValType>
1212 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1213 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1214 return new ConstantPointerNull(Ty);
1219 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1220 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1221 // Make everyone now use a constant of the new type...
1222 Constant *New = ConstantPointerNull::get(NewTy);
1223 assert(New != OldC && "Didn't replace constant??");
1224 OldC->uncheckedReplaceAllUsesWith(New);
1225 OldC->destroyConstant(); // This constant is now dead, destroy it.
1230 static ManagedStatic<ValueMap<char, PointerType,
1231 ConstantPointerNull> > NullPtrConstants;
1233 static char getValType(ConstantPointerNull *) {
1238 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1239 return NullPtrConstants->getOrCreate(Ty, 0);
1242 // destroyConstant - Remove the constant from the constant table...
1244 void ConstantPointerNull::destroyConstant() {
1245 NullPtrConstants->remove(this);
1246 destroyConstantImpl();
1250 //---- UndefValue::get() implementation...
1254 // UndefValue does not take extra "value" argument...
1255 template<class ValType>
1256 struct ConstantCreator<UndefValue, Type, ValType> {
1257 static UndefValue *create(const Type *Ty, const ValType &V) {
1258 return new UndefValue(Ty);
1263 struct ConvertConstantType<UndefValue, Type> {
1264 static void convert(UndefValue *OldC, const Type *NewTy) {
1265 // Make everyone now use a constant of the new type.
1266 Constant *New = UndefValue::get(NewTy);
1267 assert(New != OldC && "Didn't replace constant??");
1268 OldC->uncheckedReplaceAllUsesWith(New);
1269 OldC->destroyConstant(); // This constant is now dead, destroy it.
1274 static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
1276 static char getValType(UndefValue *) {
1281 UndefValue *UndefValue::get(const Type *Ty) {
1282 return UndefValueConstants->getOrCreate(Ty, 0);
1285 // destroyConstant - Remove the constant from the constant table.
1287 void UndefValue::destroyConstant() {
1288 UndefValueConstants->remove(this);
1289 destroyConstantImpl();
1293 //---- ConstantExpr::get() implementations...
1295 struct ExprMapKeyType {
1296 explicit ExprMapKeyType(unsigned opc, std::vector<Constant*> ops,
1297 unsigned short pred = 0) : opcode(opc), predicate(pred), operands(ops) { }
1300 std::vector<Constant*> operands;
1301 bool operator==(const ExprMapKeyType& that) const {
1302 return this->opcode == that.opcode &&
1303 this->predicate == that.predicate &&
1304 this->operands == that.operands;
1306 bool operator<(const ExprMapKeyType & that) const {
1307 return this->opcode < that.opcode ||
1308 (this->opcode == that.opcode && this->predicate < that.predicate) ||
1309 (this->opcode == that.opcode && this->predicate == that.predicate &&
1310 this->operands < that.operands);
1313 bool operator!=(const ExprMapKeyType& that) const {
1314 return !(*this == that);
1320 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1321 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1322 unsigned short pred = 0) {
1323 if (Instruction::isCast(V.opcode))
1324 return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1325 if ((V.opcode >= Instruction::BinaryOpsBegin &&
1326 V.opcode < Instruction::BinaryOpsEnd) ||
1327 V.opcode == Instruction::Shl ||
1328 V.opcode == Instruction::LShr ||
1329 V.opcode == Instruction::AShr)
1330 return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1331 if (V.opcode == Instruction::Select)
1332 return new SelectConstantExpr(V.operands[0], V.operands[1],
1334 if (V.opcode == Instruction::ExtractElement)
1335 return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1336 if (V.opcode == Instruction::InsertElement)
1337 return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1339 if (V.opcode == Instruction::ShuffleVector)
1340 return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1342 if (V.opcode == Instruction::GetElementPtr) {
1343 std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
1344 return new GetElementPtrConstantExpr(V.operands[0], IdxList, Ty);
1347 // The compare instructions are weird. We have to encode the predicate
1348 // value and it is combined with the instruction opcode by multiplying
1349 // the opcode by one hundred. We must decode this to get the predicate.
1350 if (V.opcode == Instruction::ICmp)
1351 return new CompareConstantExpr(Instruction::ICmp, V.predicate,
1352 V.operands[0], V.operands[1]);
1353 if (V.opcode == Instruction::FCmp)
1354 return new CompareConstantExpr(Instruction::FCmp, V.predicate,
1355 V.operands[0], V.operands[1]);
1356 assert(0 && "Invalid ConstantExpr!");
1362 struct ConvertConstantType<ConstantExpr, Type> {
1363 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1365 switch (OldC->getOpcode()) {
1366 case Instruction::Trunc:
1367 case Instruction::ZExt:
1368 case Instruction::SExt:
1369 case Instruction::FPTrunc:
1370 case Instruction::FPExt:
1371 case Instruction::UIToFP:
1372 case Instruction::SIToFP:
1373 case Instruction::FPToUI:
1374 case Instruction::FPToSI:
1375 case Instruction::PtrToInt:
1376 case Instruction::IntToPtr:
1377 case Instruction::BitCast:
1378 New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0),
1381 case Instruction::Select:
1382 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1383 OldC->getOperand(1),
1384 OldC->getOperand(2));
1386 case Instruction::Shl:
1387 case Instruction::LShr:
1388 case Instruction::AShr:
1389 New = ConstantExpr::getShiftTy(NewTy, OldC->getOpcode(),
1390 OldC->getOperand(0), OldC->getOperand(1));
1393 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1394 OldC->getOpcode() < Instruction::BinaryOpsEnd);
1395 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1396 OldC->getOperand(1));
1398 case Instruction::GetElementPtr:
1399 // Make everyone now use a constant of the new type...
1400 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1401 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0), Idx);
1405 assert(New != OldC && "Didn't replace constant??");
1406 OldC->uncheckedReplaceAllUsesWith(New);
1407 OldC->destroyConstant(); // This constant is now dead, destroy it.
1410 } // end namespace llvm
1413 static ExprMapKeyType getValType(ConstantExpr *CE) {
1414 std::vector<Constant*> Operands;
1415 Operands.reserve(CE->getNumOperands());
1416 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1417 Operands.push_back(cast<Constant>(CE->getOperand(i)));
1418 return ExprMapKeyType(CE->getOpcode(), Operands,
1419 CE->isCompare() ? CE->getPredicate() : 0);
1422 static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1423 ConstantExpr> > ExprConstants;
1425 /// This is a utility function to handle folding of casts and lookup of the
1426 /// cast in the ExprConstants map. It is usedby the various get* methods below.
1427 static inline Constant *getFoldedCast(
1428 Instruction::CastOps opc, Constant *C, const Type *Ty) {
1429 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1430 // Fold a few common cases
1431 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1434 // Look up the constant in the table first to ensure uniqueness
1435 std::vector<Constant*> argVec(1, C);
1436 ExprMapKeyType Key(opc, argVec);
1437 return ExprConstants->getOrCreate(Ty, Key);
1440 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1441 Instruction::CastOps opc = Instruction::CastOps(oc);
1442 assert(Instruction::isCast(opc) && "opcode out of range");
1443 assert(C && Ty && "Null arguments to getCast");
1444 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1448 assert(0 && "Invalid cast opcode");
1450 case Instruction::Trunc: return getTrunc(C, Ty);
1451 case Instruction::ZExt: return getZExt(C, Ty);
1452 case Instruction::SExt: return getSExt(C, Ty);
1453 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1454 case Instruction::FPExt: return getFPExtend(C, Ty);
1455 case Instruction::UIToFP: return getUIToFP(C, Ty);
1456 case Instruction::SIToFP: return getSIToFP(C, Ty);
1457 case Instruction::FPToUI: return getFPToUI(C, Ty);
1458 case Instruction::FPToSI: return getFPToSI(C, Ty);
1459 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1460 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1461 case Instruction::BitCast: return getBitCast(C, Ty);
1466 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1467 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1468 return getCast(Instruction::BitCast, C, Ty);
1469 return getCast(Instruction::ZExt, C, Ty);
1472 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1473 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1474 return getCast(Instruction::BitCast, C, Ty);
1475 return getCast(Instruction::SExt, C, Ty);
1478 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1479 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1480 return getCast(Instruction::BitCast, C, Ty);
1481 return getCast(Instruction::Trunc, C, Ty);
1484 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1485 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1486 assert((Ty->isIntegral() || Ty->getTypeID() == Type::PointerTyID) &&
1489 if (Ty->isIntegral())
1490 return getCast(Instruction::PtrToInt, S, Ty);
1491 return getCast(Instruction::BitCast, S, Ty);
1494 Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
1496 assert(C->getType()->isIntegral() && Ty->isIntegral() && "Invalid cast");
1497 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1498 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1499 Instruction::CastOps opcode =
1500 (SrcBits == DstBits ? Instruction::BitCast :
1501 (SrcBits > DstBits ? Instruction::Trunc :
1502 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1503 return getCast(opcode, C, Ty);
1506 Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1507 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1509 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1510 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1511 if (SrcBits == DstBits)
1512 return C; // Avoid a useless cast
1513 Instruction::CastOps opcode =
1514 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1515 return getCast(opcode, C, Ty);
1518 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
1519 assert(C->getType()->isInteger() && "Trunc operand must be integer");
1520 assert(Ty->isIntegral() && "Trunc produces only integral");
1521 assert(C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1522 "SrcTy must be larger than DestTy for Trunc!");
1524 return getFoldedCast(Instruction::Trunc, C, Ty);
1527 Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
1528 assert(C->getType()->isIntegral() && "SEXt operand must be integral");
1529 assert(Ty->isInteger() && "SExt produces only integer");
1530 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1531 "SrcTy must be smaller than DestTy for SExt!");
1533 return getFoldedCast(Instruction::SExt, C, Ty);
1536 Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
1537 assert(C->getType()->isIntegral() && "ZEXt operand must be integral");
1538 assert(Ty->isInteger() && "ZExt produces only integer");
1539 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1540 "SrcTy must be smaller than DestTy for ZExt!");
1542 return getFoldedCast(Instruction::ZExt, C, Ty);
1545 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1546 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1547 C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1548 "This is an illegal floating point truncation!");
1549 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1552 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1553 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1554 C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1555 "This is an illegal floating point extension!");
1556 return getFoldedCast(Instruction::FPExt, C, Ty);
1559 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
1560 assert(C->getType()->isIntegral() && Ty->isFloatingPoint() &&
1561 "This is an illegal uint to floating point cast!");
1562 return getFoldedCast(Instruction::UIToFP, C, Ty);
1565 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
1566 assert(C->getType()->isIntegral() && Ty->isFloatingPoint() &&
1567 "This is an illegal sint to floating point cast!");
1568 return getFoldedCast(Instruction::SIToFP, C, Ty);
1571 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
1572 assert(C->getType()->isFloatingPoint() && Ty->isIntegral() &&
1573 "This is an illegal floating point to uint cast!");
1574 return getFoldedCast(Instruction::FPToUI, C, Ty);
1577 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
1578 assert(C->getType()->isFloatingPoint() && Ty->isIntegral() &&
1579 "This is an illegal floating point to sint cast!");
1580 return getFoldedCast(Instruction::FPToSI, C, Ty);
1583 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1584 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
1585 assert(DstTy->isIntegral() && "PtrToInt destination must be integral");
1586 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1589 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
1590 assert(C->getType()->isIntegral() && "IntToPtr source must be integral");
1591 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
1592 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1595 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1596 // BitCast implies a no-op cast of type only. No bits change. However, you
1597 // can't cast pointers to anything but pointers.
1598 const Type *SrcTy = C->getType();
1599 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
1600 "BitCast cannot cast pointer to non-pointer and vice versa");
1602 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
1603 // or nonptr->ptr). For all the other types, the cast is okay if source and
1604 // destination bit widths are identical.
1605 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1606 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
1607 assert(SrcBitSize == DstBitSize && "BitCast requies types of same width");
1608 return getFoldedCast(Instruction::BitCast, C, DstTy);
1611 Constant *ConstantExpr::getSizeOf(const Type *Ty) {
1612 // sizeof is implemented as: (ulong) gep (Ty*)null, 1
1613 return getCast(Instruction::PtrToInt, getGetElementPtr(getNullValue(
1614 PointerType::get(Ty)), std::vector<Constant*>(1,
1615 ConstantInt::get(Type::UIntTy, 1))), Type::ULongTy);
1618 Constant *ConstantExpr::getPtrPtrFromArrayPtr(Constant *C) {
1619 // pointer from array is implemented as: getelementptr arr ptr, 0, 0
1620 static std::vector<Constant*> Indices(2, ConstantInt::get(Type::UIntTy, 0));
1622 return ConstantExpr::getGetElementPtr(C, Indices);
1625 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1626 Constant *C1, Constant *C2) {
1627 if (Opcode == Instruction::Shl || Opcode == Instruction::LShr ||
1628 Opcode == Instruction::AShr)
1629 return getShiftTy(ReqTy, Opcode, C1, C2);
1631 // Check the operands for consistency first
1632 assert(Opcode >= Instruction::BinaryOpsBegin &&
1633 Opcode < Instruction::BinaryOpsEnd &&
1634 "Invalid opcode in binary constant expression");
1635 assert(C1->getType() == C2->getType() &&
1636 "Operand types in binary constant expression should match");
1638 if (ReqTy == C1->getType() || ReqTy == Type::BoolTy)
1639 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1640 return FC; // Fold a few common cases...
1642 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1643 ExprMapKeyType Key(Opcode, argVec);
1644 return ExprConstants->getOrCreate(ReqTy, Key);
1647 Constant *ConstantExpr::getCompareTy(unsigned short predicate,
1648 Constant *C1, Constant *C2) {
1649 switch (predicate) {
1650 default: assert(0 && "Invalid CmpInst predicate");
1651 case FCmpInst::FCMP_FALSE: case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_OGT:
1652 case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OLE:
1653 case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_ORD: case FCmpInst::FCMP_UNO:
1654 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UGT: case FCmpInst::FCMP_UGE:
1655 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_ULE: case FCmpInst::FCMP_UNE:
1656 case FCmpInst::FCMP_TRUE:
1657 return getFCmp(predicate, C1, C2);
1658 case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGT:
1659 case ICmpInst::ICMP_UGE: case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE:
1660 case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_SGE: case ICmpInst::ICMP_SLT:
1661 case ICmpInst::ICMP_SLE:
1662 return getICmp(predicate, C1, C2);
1666 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
1669 case Instruction::Add:
1670 case Instruction::Sub:
1671 case Instruction::Mul:
1672 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1673 assert((C1->getType()->isInteger() || C1->getType()->isFloatingPoint() ||
1674 isa<PackedType>(C1->getType())) &&
1675 "Tried to create an arithmetic operation on a non-arithmetic type!");
1677 case Instruction::UDiv:
1678 case Instruction::SDiv:
1679 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1680 assert((C1->getType()->isInteger() || (isa<PackedType>(C1->getType()) &&
1681 cast<PackedType>(C1->getType())->getElementType()->isInteger())) &&
1682 "Tried to create an arithmetic operation on a non-arithmetic type!");
1684 case Instruction::FDiv:
1685 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1686 assert((C1->getType()->isFloatingPoint() || (isa<PackedType>(C1->getType())
1687 && cast<PackedType>(C1->getType())->getElementType()->isFloatingPoint()))
1688 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1690 case Instruction::URem:
1691 case Instruction::SRem:
1692 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1693 assert((C1->getType()->isInteger() || (isa<PackedType>(C1->getType()) &&
1694 cast<PackedType>(C1->getType())->getElementType()->isInteger())) &&
1695 "Tried to create an arithmetic operation on a non-arithmetic type!");
1697 case Instruction::FRem:
1698 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1699 assert((C1->getType()->isFloatingPoint() || (isa<PackedType>(C1->getType())
1700 && cast<PackedType>(C1->getType())->getElementType()->isFloatingPoint()))
1701 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1703 case Instruction::And:
1704 case Instruction::Or:
1705 case Instruction::Xor:
1706 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1707 assert((C1->getType()->isIntegral() || isa<PackedType>(C1->getType())) &&
1708 "Tried to create a logical operation on a non-integral type!");
1710 case Instruction::Shl:
1711 case Instruction::LShr:
1712 case Instruction::AShr:
1713 assert(C2->getType() == Type::UByteTy && "Shift should be by ubyte!");
1714 assert(C1->getType()->isInteger() &&
1715 "Tried to create a shift operation on a non-integer type!");
1722 return getTy(C1->getType(), Opcode, C1, C2);
1725 Constant *ConstantExpr::getCompare(unsigned short pred,
1726 Constant *C1, Constant *C2) {
1727 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1728 return getCompareTy(pred, C1, C2);
1731 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1732 Constant *V1, Constant *V2) {
1733 assert(C->getType() == Type::BoolTy && "Select condition must be bool!");
1734 assert(V1->getType() == V2->getType() && "Select value types must match!");
1735 assert(V1->getType()->isFirstClassType() && "Cannot select aggregate type!");
1737 if (ReqTy == V1->getType())
1738 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1739 return SC; // Fold common cases
1741 std::vector<Constant*> argVec(3, C);
1744 ExprMapKeyType Key(Instruction::Select, argVec);
1745 return ExprConstants->getOrCreate(ReqTy, Key);
1748 /// getShiftTy - Return a shift left or shift right constant expr
1749 Constant *ConstantExpr::getShiftTy(const Type *ReqTy, unsigned Opcode,
1750 Constant *C1, Constant *C2) {
1751 // Check the operands for consistency first
1752 assert((Opcode == Instruction::Shl ||
1753 Opcode == Instruction::LShr ||
1754 Opcode == Instruction::AShr) &&
1755 "Invalid opcode in binary constant expression");
1756 assert(C1->getType()->isIntegral() && C2->getType() == Type::UByteTy &&
1757 "Invalid operand types for Shift constant expr!");
1759 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1760 return FC; // Fold a few common cases...
1762 // Look up the constant in the table first to ensure uniqueness
1763 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1764 ExprMapKeyType Key(Opcode, argVec);
1765 return ExprConstants->getOrCreate(ReqTy, Key);
1768 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1769 const std::vector<Value*> &IdxList) {
1770 assert(GetElementPtrInst::getIndexedType(C->getType(), IdxList, true) &&
1771 "GEP indices invalid!");
1773 if (Constant *FC = ConstantFoldGetElementPtr(C, IdxList))
1774 return FC; // Fold a few common cases...
1776 assert(isa<PointerType>(C->getType()) &&
1777 "Non-pointer type for constant GetElementPtr expression");
1778 // Look up the constant in the table first to ensure uniqueness
1779 std::vector<Constant*> ArgVec;
1780 ArgVec.reserve(IdxList.size()+1);
1781 ArgVec.push_back(C);
1782 for (unsigned i = 0, e = IdxList.size(); i != e; ++i)
1783 ArgVec.push_back(cast<Constant>(IdxList[i]));
1784 const ExprMapKeyType Key(Instruction::GetElementPtr,ArgVec);
1785 return ExprConstants->getOrCreate(ReqTy, Key);
1788 Constant *ConstantExpr::getGetElementPtr(Constant *C,
1789 const std::vector<Constant*> &IdxList){
1790 // Get the result type of the getelementptr!
1791 std::vector<Value*> VIdxList(IdxList.begin(), IdxList.end());
1793 const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), VIdxList,
1795 assert(Ty && "GEP indices invalid!");
1796 return getGetElementPtrTy(PointerType::get(Ty), C, VIdxList);
1799 Constant *ConstantExpr::getGetElementPtr(Constant *C,
1800 const std::vector<Value*> &IdxList) {
1801 // Get the result type of the getelementptr!
1802 const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), IdxList,
1804 assert(Ty && "GEP indices invalid!");
1805 return getGetElementPtrTy(PointerType::get(Ty), C, IdxList);
1809 ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1810 assert(LHS->getType() == RHS->getType());
1811 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
1812 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1814 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1815 return FC; // Fold a few common cases...
1817 // Look up the constant in the table first to ensure uniqueness
1818 std::vector<Constant*> ArgVec;
1819 ArgVec.push_back(LHS);
1820 ArgVec.push_back(RHS);
1821 // Fake up an opcode value that encodes both the opcode and predicate
1822 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
1823 return ExprConstants->getOrCreate(Type::BoolTy, Key);
1827 ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1828 assert(LHS->getType() == RHS->getType());
1829 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1831 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1832 return FC; // Fold a few common cases...
1834 // Look up the constant in the table first to ensure uniqueness
1835 std::vector<Constant*> ArgVec;
1836 ArgVec.push_back(LHS);
1837 ArgVec.push_back(RHS);
1838 // Fake up an opcode value that encodes both the opcode and predicate
1839 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
1840 return ExprConstants->getOrCreate(Type::BoolTy, Key);
1843 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
1845 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
1846 return FC; // Fold a few common cases...
1847 // Look up the constant in the table first to ensure uniqueness
1848 std::vector<Constant*> ArgVec(1, Val);
1849 ArgVec.push_back(Idx);
1850 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
1851 return ExprConstants->getOrCreate(ReqTy, Key);
1854 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
1855 assert(isa<PackedType>(Val->getType()) &&
1856 "Tried to create extractelement operation on non-packed type!");
1857 assert(Idx->getType() == Type::UIntTy &&
1858 "Extractelement index must be uint type!");
1859 return getExtractElementTy(cast<PackedType>(Val->getType())->getElementType(),
1863 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
1864 Constant *Elt, Constant *Idx) {
1865 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
1866 return FC; // Fold a few common cases...
1867 // Look up the constant in the table first to ensure uniqueness
1868 std::vector<Constant*> ArgVec(1, Val);
1869 ArgVec.push_back(Elt);
1870 ArgVec.push_back(Idx);
1871 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
1872 return ExprConstants->getOrCreate(ReqTy, Key);
1875 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1877 assert(isa<PackedType>(Val->getType()) &&
1878 "Tried to create insertelement operation on non-packed type!");
1879 assert(Elt->getType() == cast<PackedType>(Val->getType())->getElementType()
1880 && "Insertelement types must match!");
1881 assert(Idx->getType() == Type::UIntTy &&
1882 "Insertelement index must be uint type!");
1883 return getInsertElementTy(cast<PackedType>(Val->getType())->getElementType(),
1887 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
1888 Constant *V2, Constant *Mask) {
1889 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
1890 return FC; // Fold a few common cases...
1891 // Look up the constant in the table first to ensure uniqueness
1892 std::vector<Constant*> ArgVec(1, V1);
1893 ArgVec.push_back(V2);
1894 ArgVec.push_back(Mask);
1895 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
1896 return ExprConstants->getOrCreate(ReqTy, Key);
1899 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
1901 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1902 "Invalid shuffle vector constant expr operands!");
1903 return getShuffleVectorTy(V1->getType(), V1, V2, Mask);
1906 // destroyConstant - Remove the constant from the constant table...
1908 void ConstantExpr::destroyConstant() {
1909 ExprConstants->remove(this);
1910 destroyConstantImpl();
1913 const char *ConstantExpr::getOpcodeName() const {
1914 return Instruction::getOpcodeName(getOpcode());
1917 //===----------------------------------------------------------------------===//
1918 // replaceUsesOfWithOnConstant implementations
1920 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
1922 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1923 Constant *ToC = cast<Constant>(To);
1925 unsigned OperandToUpdate = U-OperandList;
1926 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
1928 std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
1929 Lookup.first.first = getType();
1930 Lookup.second = this;
1932 std::vector<Constant*> &Values = Lookup.first.second;
1933 Values.reserve(getNumOperands()); // Build replacement array.
1935 // Fill values with the modified operands of the constant array. Also,
1936 // compute whether this turns into an all-zeros array.
1937 bool isAllZeros = false;
1938 if (!ToC->isNullValue()) {
1939 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
1940 Values.push_back(cast<Constant>(O->get()));
1943 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1944 Constant *Val = cast<Constant>(O->get());
1945 Values.push_back(Val);
1946 if (isAllZeros) isAllZeros = Val->isNullValue();
1949 Values[OperandToUpdate] = ToC;
1951 Constant *Replacement = 0;
1953 Replacement = ConstantAggregateZero::get(getType());
1955 // Check to see if we have this array type already.
1957 ArrayConstantsTy::MapTy::iterator I =
1958 ArrayConstants->InsertOrGetItem(Lookup, Exists);
1961 Replacement = I->second;
1963 // Okay, the new shape doesn't exist in the system yet. Instead of
1964 // creating a new constant array, inserting it, replaceallusesof'ing the
1965 // old with the new, then deleting the old... just update the current one
1967 ArrayConstants->MoveConstantToNewSlot(this, I);
1969 // Update to the new value.
1970 setOperand(OperandToUpdate, ToC);
1975 // Otherwise, I do need to replace this with an existing value.
1976 assert(Replacement != this && "I didn't contain From!");
1978 // Everyone using this now uses the replacement.
1979 uncheckedReplaceAllUsesWith(Replacement);
1981 // Delete the old constant!
1985 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
1987 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1988 Constant *ToC = cast<Constant>(To);
1990 unsigned OperandToUpdate = U-OperandList;
1991 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
1993 std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
1994 Lookup.first.first = getType();
1995 Lookup.second = this;
1996 std::vector<Constant*> &Values = Lookup.first.second;
1997 Values.reserve(getNumOperands()); // Build replacement struct.
2000 // Fill values with the modified operands of the constant struct. Also,
2001 // compute whether this turns into an all-zeros struct.
2002 bool isAllZeros = false;
2003 if (!ToC->isNullValue()) {
2004 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
2005 Values.push_back(cast<Constant>(O->get()));
2008 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2009 Constant *Val = cast<Constant>(O->get());
2010 Values.push_back(Val);
2011 if (isAllZeros) isAllZeros = Val->isNullValue();
2014 Values[OperandToUpdate] = ToC;
2016 Constant *Replacement = 0;
2018 Replacement = ConstantAggregateZero::get(getType());
2020 // Check to see if we have this array type already.
2022 StructConstantsTy::MapTy::iterator I =
2023 StructConstants->InsertOrGetItem(Lookup, Exists);
2026 Replacement = I->second;
2028 // Okay, the new shape doesn't exist in the system yet. Instead of
2029 // creating a new constant struct, inserting it, replaceallusesof'ing the
2030 // old with the new, then deleting the old... just update the current one
2032 StructConstants->MoveConstantToNewSlot(this, I);
2034 // Update to the new value.
2035 setOperand(OperandToUpdate, ToC);
2040 assert(Replacement != this && "I didn't contain From!");
2042 // Everyone using this now uses the replacement.
2043 uncheckedReplaceAllUsesWith(Replacement);
2045 // Delete the old constant!
2049 void ConstantPacked::replaceUsesOfWithOnConstant(Value *From, Value *To,
2051 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2053 std::vector<Constant*> Values;
2054 Values.reserve(getNumOperands()); // Build replacement array...
2055 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2056 Constant *Val = getOperand(i);
2057 if (Val == From) Val = cast<Constant>(To);
2058 Values.push_back(Val);
2061 Constant *Replacement = ConstantPacked::get(getType(), Values);
2062 assert(Replacement != this && "I didn't contain From!");
2064 // Everyone using this now uses the replacement.
2065 uncheckedReplaceAllUsesWith(Replacement);
2067 // Delete the old constant!
2071 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2073 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2074 Constant *To = cast<Constant>(ToV);
2076 Constant *Replacement = 0;
2077 if (getOpcode() == Instruction::GetElementPtr) {
2078 std::vector<Constant*> Indices;
2079 Constant *Pointer = getOperand(0);
2080 Indices.reserve(getNumOperands()-1);
2081 if (Pointer == From) Pointer = To;
2083 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2084 Constant *Val = getOperand(i);
2085 if (Val == From) Val = To;
2086 Indices.push_back(Val);
2088 Replacement = ConstantExpr::getGetElementPtr(Pointer, Indices);
2089 } else if (isCast()) {
2090 assert(getOperand(0) == From && "Cast only has one use!");
2091 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
2092 } else if (getOpcode() == Instruction::Select) {
2093 Constant *C1 = getOperand(0);
2094 Constant *C2 = getOperand(1);
2095 Constant *C3 = getOperand(2);
2096 if (C1 == From) C1 = To;
2097 if (C2 == From) C2 = To;
2098 if (C3 == From) C3 = To;
2099 Replacement = ConstantExpr::getSelect(C1, C2, C3);
2100 } else if (getOpcode() == Instruction::ExtractElement) {
2101 Constant *C1 = getOperand(0);
2102 Constant *C2 = getOperand(1);
2103 if (C1 == From) C1 = To;
2104 if (C2 == From) C2 = To;
2105 Replacement = ConstantExpr::getExtractElement(C1, C2);
2106 } else if (getOpcode() == Instruction::InsertElement) {
2107 Constant *C1 = getOperand(0);
2108 Constant *C2 = getOperand(1);
2109 Constant *C3 = getOperand(1);
2110 if (C1 == From) C1 = To;
2111 if (C2 == From) C2 = To;
2112 if (C3 == From) C3 = To;
2113 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2114 } else if (getOpcode() == Instruction::ShuffleVector) {
2115 Constant *C1 = getOperand(0);
2116 Constant *C2 = getOperand(1);
2117 Constant *C3 = getOperand(2);
2118 if (C1 == From) C1 = To;
2119 if (C2 == From) C2 = To;
2120 if (C3 == From) C3 = To;
2121 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2122 } else if (isCompare()) {
2123 Constant *C1 = getOperand(0);
2124 Constant *C2 = getOperand(1);
2125 if (C1 == From) C1 = To;
2126 if (C2 == From) C2 = To;
2127 if (getOpcode() == Instruction::ICmp)
2128 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2130 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2131 } else if (getNumOperands() == 2) {
2132 Constant *C1 = getOperand(0);
2133 Constant *C2 = getOperand(1);
2134 if (C1 == From) C1 = To;
2135 if (C2 == From) C2 = To;
2136 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2138 assert(0 && "Unknown ConstantExpr type!");
2142 assert(Replacement != this && "I didn't contain From!");
2144 // Everyone using this now uses the replacement.
2145 uncheckedReplaceAllUsesWith(Replacement);
2147 // Delete the old constant!
2152 /// getStringValue - Turn an LLVM constant pointer that eventually points to a
2153 /// global into a string value. Return an empty string if we can't do it.
2154 /// Parameter Chop determines if the result is chopped at the first null
2157 std::string Constant::getStringValue(bool Chop, unsigned Offset) {
2158 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(this)) {
2159 if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
2160 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
2161 if (Init->isString()) {
2162 std::string Result = Init->getAsString();
2163 if (Offset < Result.size()) {
2164 // If we are pointing INTO The string, erase the beginning...
2165 Result.erase(Result.begin(), Result.begin()+Offset);
2167 // Take off the null terminator, and any string fragments after it.
2169 std::string::size_type NullPos = Result.find_first_of((char)0);
2170 if (NullPos != std::string::npos)
2171 Result.erase(Result.begin()+NullPos, Result.end());
2177 } else if (Constant *C = dyn_cast<Constant>(this)) {
2178 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
2179 return GV->getStringValue(Chop, Offset);
2180 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2181 if (CE->getOpcode() == Instruction::GetElementPtr) {
2182 // Turn a gep into the specified offset.
2183 if (CE->getNumOperands() == 3 &&
2184 cast<Constant>(CE->getOperand(1))->isNullValue() &&
2185 isa<ConstantInt>(CE->getOperand(2))) {
2186 Offset += cast<ConstantInt>(CE->getOperand(2))->getZExtValue();
2187 return CE->getOperand(0)->getStringValue(Chop, Offset);