1 //===-- Constants.cpp - Implement Constant nodes --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Constant* classes...
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Constants.h"
15 #include "ConstantFold.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/GlobalValue.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Module.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/Support/Compiler.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Support/ManagedStatic.h"
24 #include "llvm/Support/MathExtras.h"
25 #include "llvm/ADT/DenseMap.h"
26 #include "llvm/ADT/SmallVector.h"
31 //===----------------------------------------------------------------------===//
33 //===----------------------------------------------------------------------===//
35 void Constant::destroyConstantImpl() {
36 // When a Constant is destroyed, there may be lingering
37 // references to the constant by other constants in the constant pool. These
38 // constants are implicitly dependent on the module that is being deleted,
39 // but they don't know that. Because we only find out when the CPV is
40 // deleted, we must now notify all of our users (that should only be
41 // Constants) that they are, in fact, invalid now and should be deleted.
43 while (!use_empty()) {
44 Value *V = use_back();
45 #ifndef NDEBUG // Only in -g mode...
46 if (!isa<Constant>(V))
47 DOUT << "While deleting: " << *this
48 << "\n\nUse still stuck around after Def is destroyed: "
51 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
52 Constant *CV = cast<Constant>(V);
53 CV->destroyConstant();
55 // The constant should remove itself from our use list...
56 assert((use_empty() || use_back() != V) && "Constant not removed!");
59 // Value has no outstanding references it is safe to delete it now...
63 /// canTrap - Return true if evaluation of this constant could trap. This is
64 /// true for things like constant expressions that could divide by zero.
65 bool Constant::canTrap() const {
66 assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
67 // The only thing that could possibly trap are constant exprs.
68 const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
69 if (!CE) return false;
71 // ConstantExpr traps if any operands can trap.
72 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
73 if (getOperand(i)->canTrap())
76 // Otherwise, only specific operations can trap.
77 switch (CE->getOpcode()) {
80 case Instruction::UDiv:
81 case Instruction::SDiv:
82 case Instruction::FDiv:
83 case Instruction::URem:
84 case Instruction::SRem:
85 case Instruction::FRem:
86 // Div and rem can trap if the RHS is not known to be non-zero.
87 if (!isa<ConstantInt>(getOperand(1)) || getOperand(1)->isNullValue())
93 /// ContaintsRelocations - Return true if the constant value contains
94 /// relocations which cannot be resolved at compile time.
95 bool Constant::ContainsRelocations() const {
96 if (isa<GlobalValue>(this))
98 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
99 if (getOperand(i)->ContainsRelocations())
104 // Static constructor to create a '0' constant of arbitrary type...
105 Constant *Constant::getNullValue(const Type *Ty) {
106 static uint64_t zero[2] = {0, 0};
107 switch (Ty->getTypeID()) {
108 case Type::IntegerTyID:
109 return ConstantInt::get(Ty, 0);
110 case Type::FloatTyID:
111 return ConstantFP::get(APFloat(APInt(32, 0)));
112 case Type::DoubleTyID:
113 return ConstantFP::get(APFloat(APInt(64, 0)));
114 case Type::X86_FP80TyID:
115 return ConstantFP::get(APFloat(APInt(80, 2, zero)));
116 case Type::FP128TyID:
117 return ConstantFP::get(APFloat(APInt(128, 2, zero), true));
118 case Type::PPC_FP128TyID:
119 return ConstantFP::get(APFloat(APInt(128, 2, zero)));
120 case Type::PointerTyID:
121 return ConstantPointerNull::get(cast<PointerType>(Ty));
122 case Type::StructTyID:
123 case Type::ArrayTyID:
124 case Type::VectorTyID:
125 return ConstantAggregateZero::get(Ty);
127 // Function, Label, or Opaque type?
128 assert(!"Cannot create a null constant of that type!");
133 Constant *Constant::getAllOnesValue(const Type *Ty) {
134 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
135 return ConstantInt::get(APInt::getAllOnesValue(ITy->getBitWidth()));
136 return ConstantVector::getAllOnesValue(cast<VectorType>(Ty));
139 // Static constructor to create an integral constant with all bits set
140 ConstantInt *ConstantInt::getAllOnesValue(const Type *Ty) {
141 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
142 return ConstantInt::get(APInt::getAllOnesValue(ITy->getBitWidth()));
146 /// @returns the value for a vector integer constant of the given type that
147 /// has all its bits set to true.
148 /// @brief Get the all ones value
149 ConstantVector *ConstantVector::getAllOnesValue(const VectorType *Ty) {
150 std::vector<Constant*> Elts;
151 Elts.resize(Ty->getNumElements(),
152 ConstantInt::getAllOnesValue(Ty->getElementType()));
153 assert(Elts[0] && "Not a vector integer type!");
154 return cast<ConstantVector>(ConstantVector::get(Elts));
158 //===----------------------------------------------------------------------===//
160 //===----------------------------------------------------------------------===//
162 ConstantInt::ConstantInt(const IntegerType *Ty, const APInt& V)
163 : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
164 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
167 ConstantInt *ConstantInt::TheTrueVal = 0;
168 ConstantInt *ConstantInt::TheFalseVal = 0;
171 void CleanupTrueFalse(void *) {
172 ConstantInt::ResetTrueFalse();
176 static ManagedCleanup<llvm::CleanupTrueFalse> TrueFalseCleanup;
178 ConstantInt *ConstantInt::CreateTrueFalseVals(bool WhichOne) {
179 assert(TheTrueVal == 0 && TheFalseVal == 0);
180 TheTrueVal = get(Type::Int1Ty, 1);
181 TheFalseVal = get(Type::Int1Ty, 0);
183 // Ensure that llvm_shutdown nulls out TheTrueVal/TheFalseVal.
184 TrueFalseCleanup.Register();
186 return WhichOne ? TheTrueVal : TheFalseVal;
191 struct DenseMapAPIntKeyInfo {
195 KeyTy(const APInt& V, const Type* Ty) : val(V), type(Ty) {}
196 KeyTy(const KeyTy& that) : val(that.val), type(that.type) {}
197 bool operator==(const KeyTy& that) const {
198 return type == that.type && this->val == that.val;
200 bool operator!=(const KeyTy& that) const {
201 return !this->operator==(that);
204 static inline KeyTy getEmptyKey() { return KeyTy(APInt(1,0), 0); }
205 static inline KeyTy getTombstoneKey() { return KeyTy(APInt(1,1), 0); }
206 static unsigned getHashValue(const KeyTy &Key) {
207 return DenseMapInfo<void*>::getHashValue(Key.type) ^
208 Key.val.getHashValue();
210 static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
213 static bool isPod() { return false; }
218 typedef DenseMap<DenseMapAPIntKeyInfo::KeyTy, ConstantInt*,
219 DenseMapAPIntKeyInfo> IntMapTy;
220 static ManagedStatic<IntMapTy> IntConstants;
222 ConstantInt *ConstantInt::get(const Type *Ty, uint64_t V, bool isSigned) {
223 const IntegerType *ITy = cast<IntegerType>(Ty);
224 return get(APInt(ITy->getBitWidth(), V, isSigned));
227 // Get a ConstantInt from an APInt. Note that the value stored in the DenseMap
228 // as the key, is a DenseMapAPIntKeyInfo::KeyTy which has provided the
229 // operator== and operator!= to ensure that the DenseMap doesn't attempt to
230 // compare APInt's of different widths, which would violate an APInt class
231 // invariant which generates an assertion.
232 ConstantInt *ConstantInt::get(const APInt& V) {
233 // Get the corresponding integer type for the bit width of the value.
234 const IntegerType *ITy = IntegerType::get(V.getBitWidth());
235 // get an existing value or the insertion position
236 DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
237 ConstantInt *&Slot = (*IntConstants)[Key];
238 // if it exists, return it.
241 // otherwise create a new one, insert it, and return it.
242 return Slot = new ConstantInt(ITy, V);
245 //===----------------------------------------------------------------------===//
247 //===----------------------------------------------------------------------===//
249 static const fltSemantics *TypeToFloatSemantics(const Type *Ty) {
250 if (Ty == Type::FloatTy)
251 return &APFloat::IEEEsingle;
252 if (Ty == Type::DoubleTy)
253 return &APFloat::IEEEdouble;
254 if (Ty == Type::X86_FP80Ty)
255 return &APFloat::x87DoubleExtended;
256 else if (Ty == Type::FP128Ty)
257 return &APFloat::IEEEquad;
259 assert(Ty == Type::PPC_FP128Ty && "Unknown FP format");
260 return &APFloat::PPCDoubleDouble;
263 ConstantFP::ConstantFP(const Type *Ty, const APFloat& V)
264 : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
265 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
269 bool ConstantFP::isNullValue() const {
270 return Val.isZero() && !Val.isNegative();
273 ConstantFP *ConstantFP::getNegativeZero(const Type *Ty) {
274 APFloat apf = cast <ConstantFP>(Constant::getNullValue(Ty))->getValueAPF();
276 return ConstantFP::get(apf);
279 bool ConstantFP::isExactlyValue(const APFloat& V) const {
280 return Val.bitwiseIsEqual(V);
284 struct DenseMapAPFloatKeyInfo {
287 KeyTy(const APFloat& V) : val(V){}
288 KeyTy(const KeyTy& that) : val(that.val) {}
289 bool operator==(const KeyTy& that) const {
290 return this->val.bitwiseIsEqual(that.val);
292 bool operator!=(const KeyTy& that) const {
293 return !this->operator==(that);
296 static inline KeyTy getEmptyKey() {
297 return KeyTy(APFloat(APFloat::Bogus,1));
299 static inline KeyTy getTombstoneKey() {
300 return KeyTy(APFloat(APFloat::Bogus,2));
302 static unsigned getHashValue(const KeyTy &Key) {
303 return Key.val.getHashValue();
305 static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
308 static bool isPod() { return false; }
312 //---- ConstantFP::get() implementation...
314 typedef DenseMap<DenseMapAPFloatKeyInfo::KeyTy, ConstantFP*,
315 DenseMapAPFloatKeyInfo> FPMapTy;
317 static ManagedStatic<FPMapTy> FPConstants;
319 ConstantFP *ConstantFP::get(const APFloat &V) {
320 DenseMapAPFloatKeyInfo::KeyTy Key(V);
321 ConstantFP *&Slot = (*FPConstants)[Key];
322 if (Slot) return Slot;
325 if (&V.getSemantics() == &APFloat::IEEEsingle)
327 else if (&V.getSemantics() == &APFloat::IEEEdouble)
329 else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
330 Ty = Type::X86_FP80Ty;
331 else if (&V.getSemantics() == &APFloat::IEEEquad)
334 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble&&"Unknown FP format");
335 Ty = Type::PPC_FP128Ty;
338 return Slot = new ConstantFP(Ty, V);
341 /// get() - This returns a constant fp for the specified value in the
342 /// specified type. This should only be used for simple constant values like
343 /// 2.0/1.0 etc, that are known-valid both as double and as the target format.
344 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
346 FV.convert(*TypeToFloatSemantics(Ty), APFloat::rmNearestTiesToEven);
350 //===----------------------------------------------------------------------===//
351 // ConstantXXX Classes
352 //===----------------------------------------------------------------------===//
355 ConstantArray::ConstantArray(const ArrayType *T,
356 const std::vector<Constant*> &V)
357 : Constant(T, ConstantArrayVal,
358 OperandTraits<ConstantArray>::op_end(this) - V.size(),
360 assert(V.size() == T->getNumElements() &&
361 "Invalid initializer vector for constant array");
362 Use *OL = OperandList;
363 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
366 assert((C->getType() == T->getElementType() ||
368 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
369 "Initializer for array element doesn't match array element type!");
375 ConstantStruct::ConstantStruct(const StructType *T,
376 const std::vector<Constant*> &V)
377 : Constant(T, ConstantStructVal,
378 OperandTraits<ConstantStruct>::op_end(this) - V.size(),
380 assert(V.size() == T->getNumElements() &&
381 "Invalid initializer vector for constant structure");
382 Use *OL = OperandList;
383 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
386 assert((C->getType() == T->getElementType(I-V.begin()) ||
387 ((T->getElementType(I-V.begin())->isAbstract() ||
388 C->getType()->isAbstract()) &&
389 T->getElementType(I-V.begin())->getTypeID() ==
390 C->getType()->getTypeID())) &&
391 "Initializer for struct element doesn't match struct element type!");
397 ConstantVector::ConstantVector(const VectorType *T,
398 const std::vector<Constant*> &V)
399 : Constant(T, ConstantVectorVal,
400 OperandTraits<ConstantVector>::op_end(this) - V.size(),
402 Use *OL = OperandList;
403 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
406 assert((C->getType() == T->getElementType() ||
408 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
409 "Initializer for vector element doesn't match vector element type!");
416 // We declare several classes private to this file, so use an anonymous
420 /// UnaryConstantExpr - This class is private to Constants.cpp, and is used
421 /// behind the scenes to implement unary constant exprs.
422 class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
423 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
425 // allocate space for exactly one operand
426 void *operator new(size_t s) {
427 return User::operator new(s, 1);
429 UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
430 : ConstantExpr(Ty, Opcode, &Op<0>(), 1) {
433 /// Transparently provide more efficient getOperand methods.
434 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
437 /// BinaryConstantExpr - This class is private to Constants.cpp, and is used
438 /// behind the scenes to implement binary constant exprs.
439 class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
440 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
442 // allocate space for exactly two operands
443 void *operator new(size_t s) {
444 return User::operator new(s, 2);
446 BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
447 : ConstantExpr(C1->getType(), Opcode, &Op<0>(), 2) {
448 Op<0>().init(C1, this);
449 Op<1>().init(C2, this);
451 /// Transparently provide more efficient getOperand methods.
452 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
455 /// SelectConstantExpr - This class is private to Constants.cpp, and is used
456 /// behind the scenes to implement select constant exprs.
457 class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
458 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
460 // allocate space for exactly three operands
461 void *operator new(size_t s) {
462 return User::operator new(s, 3);
464 SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
465 : ConstantExpr(C2->getType(), Instruction::Select, &Op<0>(), 3) {
466 Op<0>().init(C1, this);
467 Op<1>().init(C2, this);
468 Op<2>().init(C3, this);
470 /// Transparently provide more efficient getOperand methods.
471 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
474 /// ExtractElementConstantExpr - This class is private to
475 /// Constants.cpp, and is used behind the scenes to implement
476 /// extractelement constant exprs.
477 class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
478 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
480 // allocate space for exactly two operands
481 void *operator new(size_t s) {
482 return User::operator new(s, 2);
484 ExtractElementConstantExpr(Constant *C1, Constant *C2)
485 : ConstantExpr(cast<VectorType>(C1->getType())->getElementType(),
486 Instruction::ExtractElement, &Op<0>(), 2) {
487 Op<0>().init(C1, this);
488 Op<1>().init(C2, this);
490 /// Transparently provide more efficient getOperand methods.
491 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
494 /// InsertElementConstantExpr - This class is private to
495 /// Constants.cpp, and is used behind the scenes to implement
496 /// insertelement constant exprs.
497 class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
498 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
500 // allocate space for exactly three operands
501 void *operator new(size_t s) {
502 return User::operator new(s, 3);
504 InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
505 : ConstantExpr(C1->getType(), Instruction::InsertElement,
507 Op<0>().init(C1, this);
508 Op<1>().init(C2, this);
509 Op<2>().init(C3, this);
511 /// Transparently provide more efficient getOperand methods.
512 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
515 /// ShuffleVectorConstantExpr - This class is private to
516 /// Constants.cpp, and is used behind the scenes to implement
517 /// shufflevector constant exprs.
518 class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
519 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
521 // allocate space for exactly three operands
522 void *operator new(size_t s) {
523 return User::operator new(s, 3);
525 ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
526 : ConstantExpr(C1->getType(), Instruction::ShuffleVector,
528 Op<0>().init(C1, this);
529 Op<1>().init(C2, this);
530 Op<2>().init(C3, this);
532 /// Transparently provide more efficient getOperand methods.
533 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
536 /// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
537 /// used behind the scenes to implement getelementpr constant exprs.
538 class VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
539 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
542 static GetElementPtrConstantExpr *Create(Constant *C, const std::vector<Constant*> &IdxList,
543 const Type *DestTy) {
544 return new(IdxList.size() + 1) GetElementPtrConstantExpr(C, IdxList, DestTy);
546 /// Transparently provide more efficient getOperand methods.
547 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
550 // CompareConstantExpr - This class is private to Constants.cpp, and is used
551 // behind the scenes to implement ICmp and FCmp constant expressions. This is
552 // needed in order to store the predicate value for these instructions.
553 struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
554 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
555 // allocate space for exactly two operands
556 void *operator new(size_t s) {
557 return User::operator new(s, 2);
559 unsigned short predicate;
560 CompareConstantExpr(Instruction::OtherOps opc, unsigned short pred,
561 Constant* LHS, Constant* RHS)
562 : ConstantExpr(Type::Int1Ty, opc, &Op<0>(), 2), predicate(pred) {
563 Op<0>().init(LHS, this);
564 Op<1>().init(RHS, this);
566 /// Transparently provide more efficient getOperand methods.
567 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
570 } // end anonymous namespace
573 struct OperandTraits<UnaryConstantExpr> : FixedNumOperandTraits<1> {
575 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(UnaryConstantExpr, Value)
578 struct OperandTraits<BinaryConstantExpr> : FixedNumOperandTraits<2> {
580 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BinaryConstantExpr, Value)
583 struct OperandTraits<SelectConstantExpr> : FixedNumOperandTraits<3> {
585 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectConstantExpr, Value)
588 struct OperandTraits<ExtractElementConstantExpr> : FixedNumOperandTraits<2> {
590 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementConstantExpr, Value)
593 struct OperandTraits<InsertElementConstantExpr> : FixedNumOperandTraits<3> {
595 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementConstantExpr, Value)
598 struct OperandTraits<ShuffleVectorConstantExpr> : FixedNumOperandTraits<3> {
600 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorConstantExpr, Value)
604 struct OperandTraits<GetElementPtrConstantExpr> : VariadicOperandTraits<1> {
607 GetElementPtrConstantExpr::GetElementPtrConstantExpr
609 const std::vector<Constant*> &IdxList,
611 : ConstantExpr(DestTy, Instruction::GetElementPtr,
612 OperandTraits<GetElementPtrConstantExpr>::op_end(this)
613 - (IdxList.size()+1),
615 OperandList[0].init(C, this);
616 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
617 OperandList[i+1].init(IdxList[i], this);
620 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrConstantExpr, Value)
624 struct OperandTraits<CompareConstantExpr> : FixedNumOperandTraits<2> {
626 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CompareConstantExpr, Value)
629 } // End llvm namespace
632 // Utility function for determining if a ConstantExpr is a CastOp or not. This
633 // can't be inline because we don't want to #include Instruction.h into
635 bool ConstantExpr::isCast() const {
636 return Instruction::isCast(getOpcode());
639 bool ConstantExpr::isCompare() const {
640 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
643 /// ConstantExpr::get* - Return some common constants without having to
644 /// specify the full Instruction::OPCODE identifier.
646 Constant *ConstantExpr::getNeg(Constant *C) {
647 return get(Instruction::Sub,
648 ConstantExpr::getZeroValueForNegationExpr(C->getType()),
651 Constant *ConstantExpr::getNot(Constant *C) {
652 assert(isa<IntegerType>(C->getType()) && "Cannot NOT a nonintegral value!");
653 return get(Instruction::Xor, C,
654 ConstantInt::getAllOnesValue(C->getType()));
656 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
657 return get(Instruction::Add, C1, C2);
659 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
660 return get(Instruction::Sub, C1, C2);
662 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
663 return get(Instruction::Mul, C1, C2);
665 Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2) {
666 return get(Instruction::UDiv, C1, C2);
668 Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2) {
669 return get(Instruction::SDiv, C1, C2);
671 Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
672 return get(Instruction::FDiv, C1, C2);
674 Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
675 return get(Instruction::URem, C1, C2);
677 Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
678 return get(Instruction::SRem, C1, C2);
680 Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
681 return get(Instruction::FRem, C1, C2);
683 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
684 return get(Instruction::And, C1, C2);
686 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
687 return get(Instruction::Or, C1, C2);
689 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
690 return get(Instruction::Xor, C1, C2);
692 unsigned ConstantExpr::getPredicate() const {
693 assert(getOpcode() == Instruction::FCmp || getOpcode() == Instruction::ICmp);
694 return ((const CompareConstantExpr*)this)->predicate;
696 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
697 return get(Instruction::Shl, C1, C2);
699 Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2) {
700 return get(Instruction::LShr, C1, C2);
702 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2) {
703 return get(Instruction::AShr, C1, C2);
706 /// getWithOperandReplaced - Return a constant expression identical to this
707 /// one, but with the specified operand set to the specified value.
709 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
710 assert(OpNo < getNumOperands() && "Operand num is out of range!");
711 assert(Op->getType() == getOperand(OpNo)->getType() &&
712 "Replacing operand with value of different type!");
713 if (getOperand(OpNo) == Op)
714 return const_cast<ConstantExpr*>(this);
716 Constant *Op0, *Op1, *Op2;
717 switch (getOpcode()) {
718 case Instruction::Trunc:
719 case Instruction::ZExt:
720 case Instruction::SExt:
721 case Instruction::FPTrunc:
722 case Instruction::FPExt:
723 case Instruction::UIToFP:
724 case Instruction::SIToFP:
725 case Instruction::FPToUI:
726 case Instruction::FPToSI:
727 case Instruction::PtrToInt:
728 case Instruction::IntToPtr:
729 case Instruction::BitCast:
730 return ConstantExpr::getCast(getOpcode(), Op, getType());
731 case Instruction::Select:
732 Op0 = (OpNo == 0) ? Op : getOperand(0);
733 Op1 = (OpNo == 1) ? Op : getOperand(1);
734 Op2 = (OpNo == 2) ? Op : getOperand(2);
735 return ConstantExpr::getSelect(Op0, Op1, Op2);
736 case Instruction::InsertElement:
737 Op0 = (OpNo == 0) ? Op : getOperand(0);
738 Op1 = (OpNo == 1) ? Op : getOperand(1);
739 Op2 = (OpNo == 2) ? Op : getOperand(2);
740 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
741 case Instruction::ExtractElement:
742 Op0 = (OpNo == 0) ? Op : getOperand(0);
743 Op1 = (OpNo == 1) ? Op : getOperand(1);
744 return ConstantExpr::getExtractElement(Op0, Op1);
745 case Instruction::ShuffleVector:
746 Op0 = (OpNo == 0) ? Op : getOperand(0);
747 Op1 = (OpNo == 1) ? Op : getOperand(1);
748 Op2 = (OpNo == 2) ? Op : getOperand(2);
749 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
750 case Instruction::GetElementPtr: {
751 SmallVector<Constant*, 8> Ops;
752 Ops.resize(getNumOperands());
753 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
754 Ops[i] = getOperand(i);
756 return ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
758 return ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
761 assert(getNumOperands() == 2 && "Must be binary operator?");
762 Op0 = (OpNo == 0) ? Op : getOperand(0);
763 Op1 = (OpNo == 1) ? Op : getOperand(1);
764 return ConstantExpr::get(getOpcode(), Op0, Op1);
768 /// getWithOperands - This returns the current constant expression with the
769 /// operands replaced with the specified values. The specified operands must
770 /// match count and type with the existing ones.
771 Constant *ConstantExpr::
772 getWithOperands(const std::vector<Constant*> &Ops) const {
773 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
774 bool AnyChange = false;
775 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
776 assert(Ops[i]->getType() == getOperand(i)->getType() &&
777 "Operand type mismatch!");
778 AnyChange |= Ops[i] != getOperand(i);
780 if (!AnyChange) // No operands changed, return self.
781 return const_cast<ConstantExpr*>(this);
783 switch (getOpcode()) {
784 case Instruction::Trunc:
785 case Instruction::ZExt:
786 case Instruction::SExt:
787 case Instruction::FPTrunc:
788 case Instruction::FPExt:
789 case Instruction::UIToFP:
790 case Instruction::SIToFP:
791 case Instruction::FPToUI:
792 case Instruction::FPToSI:
793 case Instruction::PtrToInt:
794 case Instruction::IntToPtr:
795 case Instruction::BitCast:
796 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
797 case Instruction::Select:
798 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
799 case Instruction::InsertElement:
800 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
801 case Instruction::ExtractElement:
802 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
803 case Instruction::ShuffleVector:
804 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
805 case Instruction::GetElementPtr:
806 return ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], Ops.size()-1);
807 case Instruction::ICmp:
808 case Instruction::FCmp:
809 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
811 assert(getNumOperands() == 2 && "Must be binary operator?");
812 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
817 //===----------------------------------------------------------------------===//
818 // isValueValidForType implementations
820 bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
821 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
822 if (Ty == Type::Int1Ty)
823 return Val == 0 || Val == 1;
825 return true; // always true, has to fit in largest type
826 uint64_t Max = (1ll << NumBits) - 1;
830 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
831 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
832 if (Ty == Type::Int1Ty)
833 return Val == 0 || Val == 1 || Val == -1;
835 return true; // always true, has to fit in largest type
836 int64_t Min = -(1ll << (NumBits-1));
837 int64_t Max = (1ll << (NumBits-1)) - 1;
838 return (Val >= Min && Val <= Max);
841 bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
842 // convert modifies in place, so make a copy.
843 APFloat Val2 = APFloat(Val);
844 switch (Ty->getTypeID()) {
846 return false; // These can't be represented as floating point!
848 // FIXME rounding mode needs to be more flexible
849 case Type::FloatTyID:
850 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
851 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven) ==
853 case Type::DoubleTyID:
854 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
855 &Val2.getSemantics() == &APFloat::IEEEdouble ||
856 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven) ==
858 case Type::X86_FP80TyID:
859 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
860 &Val2.getSemantics() == &APFloat::IEEEdouble ||
861 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
862 case Type::FP128TyID:
863 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
864 &Val2.getSemantics() == &APFloat::IEEEdouble ||
865 &Val2.getSemantics() == &APFloat::IEEEquad;
866 case Type::PPC_FP128TyID:
867 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
868 &Val2.getSemantics() == &APFloat::IEEEdouble ||
869 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
873 //===----------------------------------------------------------------------===//
874 // Factory Function Implementation
877 // The number of operands for each ConstantCreator::create method is
878 // determined by the ConstantTraits template.
879 // ConstantCreator - A class that is used to create constants by
880 // ValueMap*. This class should be partially specialized if there is
881 // something strange that needs to be done to interface to the ctor for the
885 template<class ValType>
886 struct ConstantTraits;
888 template<typename T, typename Alloc>
889 struct VISIBILITY_HIDDEN ConstantTraits< std::vector<T, Alloc> > {
890 static unsigned uses(const std::vector<T, Alloc>& v) {
895 template<class ConstantClass, class TypeClass, class ValType>
896 struct VISIBILITY_HIDDEN ConstantCreator {
897 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
898 return new(ConstantTraits<ValType>::uses(V)) ConstantClass(Ty, V);
902 template<class ConstantClass, class TypeClass>
903 struct VISIBILITY_HIDDEN ConvertConstantType {
904 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
905 assert(0 && "This type cannot be converted!\n");
910 template<class ValType, class TypeClass, class ConstantClass,
911 bool HasLargeKey = false /*true for arrays and structs*/ >
912 class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
914 typedef std::pair<const Type*, ValType> MapKey;
915 typedef std::map<MapKey, Constant *> MapTy;
916 typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
917 typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
919 /// Map - This is the main map from the element descriptor to the Constants.
920 /// This is the primary way we avoid creating two of the same shape
924 /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
925 /// from the constants to their element in Map. This is important for
926 /// removal of constants from the array, which would otherwise have to scan
927 /// through the map with very large keys.
928 InverseMapTy InverseMap;
930 /// AbstractTypeMap - Map for abstract type constants.
932 AbstractTypeMapTy AbstractTypeMap;
935 typename MapTy::iterator map_end() { return Map.end(); }
937 /// InsertOrGetItem - Return an iterator for the specified element.
938 /// If the element exists in the map, the returned iterator points to the
939 /// entry and Exists=true. If not, the iterator points to the newly
940 /// inserted entry and returns Exists=false. Newly inserted entries have
941 /// I->second == 0, and should be filled in.
942 typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
945 std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
951 typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
953 typename InverseMapTy::iterator IMI = InverseMap.find(CP);
954 assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
955 IMI->second->second == CP &&
956 "InverseMap corrupt!");
960 typename MapTy::iterator I =
961 Map.find(MapKey((TypeClass*)CP->getRawType(), getValType(CP)));
962 if (I == Map.end() || I->second != CP) {
963 // FIXME: This should not use a linear scan. If this gets to be a
964 // performance problem, someone should look at this.
965 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
972 /// getOrCreate - Return the specified constant from the map, creating it if
974 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
975 MapKey Lookup(Ty, V);
976 typename MapTy::iterator I = Map.lower_bound(Lookup);
978 if (I != Map.end() && I->first == Lookup)
979 return static_cast<ConstantClass *>(I->second);
981 // If no preexisting value, create one now...
982 ConstantClass *Result =
983 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
985 /// FIXME: why does this assert fail when loading 176.gcc?
986 //assert(Result->getType() == Ty && "Type specified is not correct!");
987 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
989 if (HasLargeKey) // Remember the reverse mapping if needed.
990 InverseMap.insert(std::make_pair(Result, I));
992 // If the type of the constant is abstract, make sure that an entry exists
993 // for it in the AbstractTypeMap.
994 if (Ty->isAbstract()) {
995 typename AbstractTypeMapTy::iterator TI =
996 AbstractTypeMap.lower_bound(Ty);
998 if (TI == AbstractTypeMap.end() || TI->first != Ty) {
999 // Add ourselves to the ATU list of the type.
1000 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
1002 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
1008 void remove(ConstantClass *CP) {
1009 typename MapTy::iterator I = FindExistingElement(CP);
1010 assert(I != Map.end() && "Constant not found in constant table!");
1011 assert(I->second == CP && "Didn't find correct element?");
1013 if (HasLargeKey) // Remember the reverse mapping if needed.
1014 InverseMap.erase(CP);
1016 // Now that we found the entry, make sure this isn't the entry that
1017 // the AbstractTypeMap points to.
1018 const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
1019 if (Ty->isAbstract()) {
1020 assert(AbstractTypeMap.count(Ty) &&
1021 "Abstract type not in AbstractTypeMap?");
1022 typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
1023 if (ATMEntryIt == I) {
1024 // Yes, we are removing the representative entry for this type.
1025 // See if there are any other entries of the same type.
1026 typename MapTy::iterator TmpIt = ATMEntryIt;
1028 // First check the entry before this one...
1029 if (TmpIt != Map.begin()) {
1031 if (TmpIt->first.first != Ty) // Not the same type, move back...
1035 // If we didn't find the same type, try to move forward...
1036 if (TmpIt == ATMEntryIt) {
1038 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
1039 --TmpIt; // No entry afterwards with the same type
1042 // If there is another entry in the map of the same abstract type,
1043 // update the AbstractTypeMap entry now.
1044 if (TmpIt != ATMEntryIt) {
1047 // Otherwise, we are removing the last instance of this type
1048 // from the table. Remove from the ATM, and from user list.
1049 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
1050 AbstractTypeMap.erase(Ty);
1059 /// MoveConstantToNewSlot - If we are about to change C to be the element
1060 /// specified by I, update our internal data structures to reflect this
1062 void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
1063 // First, remove the old location of the specified constant in the map.
1064 typename MapTy::iterator OldI = FindExistingElement(C);
1065 assert(OldI != Map.end() && "Constant not found in constant table!");
1066 assert(OldI->second == C && "Didn't find correct element?");
1068 // If this constant is the representative element for its abstract type,
1069 // update the AbstractTypeMap so that the representative element is I.
1070 if (C->getType()->isAbstract()) {
1071 typename AbstractTypeMapTy::iterator ATI =
1072 AbstractTypeMap.find(C->getType());
1073 assert(ATI != AbstractTypeMap.end() &&
1074 "Abstract type not in AbstractTypeMap?");
1075 if (ATI->second == OldI)
1079 // Remove the old entry from the map.
1082 // Update the inverse map so that we know that this constant is now
1083 // located at descriptor I.
1085 assert(I->second == C && "Bad inversemap entry!");
1090 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
1091 typename AbstractTypeMapTy::iterator I =
1092 AbstractTypeMap.find(cast<Type>(OldTy));
1094 assert(I != AbstractTypeMap.end() &&
1095 "Abstract type not in AbstractTypeMap?");
1097 // Convert a constant at a time until the last one is gone. The last one
1098 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
1099 // eliminated eventually.
1101 ConvertConstantType<ConstantClass,
1102 TypeClass>::convert(
1103 static_cast<ConstantClass *>(I->second->second),
1104 cast<TypeClass>(NewTy));
1106 I = AbstractTypeMap.find(cast<Type>(OldTy));
1107 } while (I != AbstractTypeMap.end());
1110 // If the type became concrete without being refined to any other existing
1111 // type, we just remove ourselves from the ATU list.
1112 void typeBecameConcrete(const DerivedType *AbsTy) {
1113 AbsTy->removeAbstractTypeUser(this);
1117 DOUT << "Constant.cpp: ValueMap\n";
1124 //---- ConstantAggregateZero::get() implementation...
1127 // ConstantAggregateZero does not take extra "value" argument...
1128 template<class ValType>
1129 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
1130 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
1131 return new ConstantAggregateZero(Ty);
1136 struct ConvertConstantType<ConstantAggregateZero, Type> {
1137 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
1138 // Make everyone now use a constant of the new type...
1139 Constant *New = ConstantAggregateZero::get(NewTy);
1140 assert(New != OldC && "Didn't replace constant??");
1141 OldC->uncheckedReplaceAllUsesWith(New);
1142 OldC->destroyConstant(); // This constant is now dead, destroy it.
1147 static ManagedStatic<ValueMap<char, Type,
1148 ConstantAggregateZero> > AggZeroConstants;
1150 static char getValType(ConstantAggregateZero *CPZ) { return 0; }
1152 Constant *ConstantAggregateZero::get(const Type *Ty) {
1153 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) &&
1154 "Cannot create an aggregate zero of non-aggregate type!");
1155 return AggZeroConstants->getOrCreate(Ty, 0);
1158 // destroyConstant - Remove the constant from the constant table...
1160 void ConstantAggregateZero::destroyConstant() {
1161 AggZeroConstants->remove(this);
1162 destroyConstantImpl();
1165 //---- ConstantArray::get() implementation...
1169 struct ConvertConstantType<ConstantArray, ArrayType> {
1170 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
1171 // Make everyone now use a constant of the new type...
1172 std::vector<Constant*> C;
1173 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1174 C.push_back(cast<Constant>(OldC->getOperand(i)));
1175 Constant *New = ConstantArray::get(NewTy, C);
1176 assert(New != OldC && "Didn't replace constant??");
1177 OldC->uncheckedReplaceAllUsesWith(New);
1178 OldC->destroyConstant(); // This constant is now dead, destroy it.
1183 static std::vector<Constant*> getValType(ConstantArray *CA) {
1184 std::vector<Constant*> Elements;
1185 Elements.reserve(CA->getNumOperands());
1186 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1187 Elements.push_back(cast<Constant>(CA->getOperand(i)));
1191 typedef ValueMap<std::vector<Constant*>, ArrayType,
1192 ConstantArray, true /*largekey*/> ArrayConstantsTy;
1193 static ManagedStatic<ArrayConstantsTy> ArrayConstants;
1195 Constant *ConstantArray::get(const ArrayType *Ty,
1196 const std::vector<Constant*> &V) {
1197 // If this is an all-zero array, return a ConstantAggregateZero object
1200 if (!C->isNullValue())
1201 return ArrayConstants->getOrCreate(Ty, V);
1202 for (unsigned i = 1, e = V.size(); i != e; ++i)
1204 return ArrayConstants->getOrCreate(Ty, V);
1206 return ConstantAggregateZero::get(Ty);
1209 // destroyConstant - Remove the constant from the constant table...
1211 void ConstantArray::destroyConstant() {
1212 ArrayConstants->remove(this);
1213 destroyConstantImpl();
1216 /// ConstantArray::get(const string&) - Return an array that is initialized to
1217 /// contain the specified string. If length is zero then a null terminator is
1218 /// added to the specified string so that it may be used in a natural way.
1219 /// Otherwise, the length parameter specifies how much of the string to use
1220 /// and it won't be null terminated.
1222 Constant *ConstantArray::get(const std::string &Str, bool AddNull) {
1223 std::vector<Constant*> ElementVals;
1224 for (unsigned i = 0; i < Str.length(); ++i)
1225 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, Str[i]));
1227 // Add a null terminator to the string...
1229 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, 0));
1232 ArrayType *ATy = ArrayType::get(Type::Int8Ty, ElementVals.size());
1233 return ConstantArray::get(ATy, ElementVals);
1236 /// isString - This method returns true if the array is an array of i8, and
1237 /// if the elements of the array are all ConstantInt's.
1238 bool ConstantArray::isString() const {
1239 // Check the element type for i8...
1240 if (getType()->getElementType() != Type::Int8Ty)
1242 // Check the elements to make sure they are all integers, not constant
1244 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1245 if (!isa<ConstantInt>(getOperand(i)))
1250 /// isCString - This method returns true if the array is a string (see
1251 /// isString) and it ends in a null byte \0 and does not contains any other
1252 /// null bytes except its terminator.
1253 bool ConstantArray::isCString() const {
1254 // Check the element type for i8...
1255 if (getType()->getElementType() != Type::Int8Ty)
1257 Constant *Zero = Constant::getNullValue(getOperand(0)->getType());
1258 // Last element must be a null.
1259 if (getOperand(getNumOperands()-1) != Zero)
1261 // Other elements must be non-null integers.
1262 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1263 if (!isa<ConstantInt>(getOperand(i)))
1265 if (getOperand(i) == Zero)
1272 // getAsString - If the sub-element type of this array is i8
1273 // then this method converts the array to an std::string and returns it.
1274 // Otherwise, it asserts out.
1276 std::string ConstantArray::getAsString() const {
1277 assert(isString() && "Not a string!");
1279 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1280 Result += (char)cast<ConstantInt>(getOperand(i))->getZExtValue();
1285 //---- ConstantStruct::get() implementation...
1290 struct ConvertConstantType<ConstantStruct, StructType> {
1291 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1292 // Make everyone now use a constant of the new type...
1293 std::vector<Constant*> C;
1294 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1295 C.push_back(cast<Constant>(OldC->getOperand(i)));
1296 Constant *New = ConstantStruct::get(NewTy, C);
1297 assert(New != OldC && "Didn't replace constant??");
1299 OldC->uncheckedReplaceAllUsesWith(New);
1300 OldC->destroyConstant(); // This constant is now dead, destroy it.
1305 typedef ValueMap<std::vector<Constant*>, StructType,
1306 ConstantStruct, true /*largekey*/> StructConstantsTy;
1307 static ManagedStatic<StructConstantsTy> StructConstants;
1309 static std::vector<Constant*> getValType(ConstantStruct *CS) {
1310 std::vector<Constant*> Elements;
1311 Elements.reserve(CS->getNumOperands());
1312 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1313 Elements.push_back(cast<Constant>(CS->getOperand(i)));
1317 Constant *ConstantStruct::get(const StructType *Ty,
1318 const std::vector<Constant*> &V) {
1319 // Create a ConstantAggregateZero value if all elements are zeros...
1320 for (unsigned i = 0, e = V.size(); i != e; ++i)
1321 if (!V[i]->isNullValue())
1322 return StructConstants->getOrCreate(Ty, V);
1324 return ConstantAggregateZero::get(Ty);
1327 Constant *ConstantStruct::get(const std::vector<Constant*> &V, bool packed) {
1328 std::vector<const Type*> StructEls;
1329 StructEls.reserve(V.size());
1330 for (unsigned i = 0, e = V.size(); i != e; ++i)
1331 StructEls.push_back(V[i]->getType());
1332 return get(StructType::get(StructEls, packed), V);
1335 // destroyConstant - Remove the constant from the constant table...
1337 void ConstantStruct::destroyConstant() {
1338 StructConstants->remove(this);
1339 destroyConstantImpl();
1342 //---- ConstantVector::get() implementation...
1346 struct ConvertConstantType<ConstantVector, VectorType> {
1347 static void convert(ConstantVector *OldC, const VectorType *NewTy) {
1348 // Make everyone now use a constant of the new type...
1349 std::vector<Constant*> C;
1350 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1351 C.push_back(cast<Constant>(OldC->getOperand(i)));
1352 Constant *New = ConstantVector::get(NewTy, C);
1353 assert(New != OldC && "Didn't replace constant??");
1354 OldC->uncheckedReplaceAllUsesWith(New);
1355 OldC->destroyConstant(); // This constant is now dead, destroy it.
1360 static std::vector<Constant*> getValType(ConstantVector *CP) {
1361 std::vector<Constant*> Elements;
1362 Elements.reserve(CP->getNumOperands());
1363 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1364 Elements.push_back(CP->getOperand(i));
1368 static ManagedStatic<ValueMap<std::vector<Constant*>, VectorType,
1369 ConstantVector> > VectorConstants;
1371 Constant *ConstantVector::get(const VectorType *Ty,
1372 const std::vector<Constant*> &V) {
1373 // If this is an all-zero vector, return a ConstantAggregateZero object
1376 if (!C->isNullValue())
1377 return VectorConstants->getOrCreate(Ty, V);
1378 for (unsigned i = 1, e = V.size(); i != e; ++i)
1380 return VectorConstants->getOrCreate(Ty, V);
1382 return ConstantAggregateZero::get(Ty);
1385 Constant *ConstantVector::get(const std::vector<Constant*> &V) {
1386 assert(!V.empty() && "Cannot infer type if V is empty");
1387 return get(VectorType::get(V.front()->getType(),V.size()), V);
1390 // destroyConstant - Remove the constant from the constant table...
1392 void ConstantVector::destroyConstant() {
1393 VectorConstants->remove(this);
1394 destroyConstantImpl();
1397 /// This function will return true iff every element in this vector constant
1398 /// is set to all ones.
1399 /// @returns true iff this constant's emements are all set to all ones.
1400 /// @brief Determine if the value is all ones.
1401 bool ConstantVector::isAllOnesValue() const {
1402 // Check out first element.
1403 const Constant *Elt = getOperand(0);
1404 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1405 if (!CI || !CI->isAllOnesValue()) return false;
1406 // Then make sure all remaining elements point to the same value.
1407 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1408 if (getOperand(I) != Elt) return false;
1413 /// getSplatValue - If this is a splat constant, where all of the
1414 /// elements have the same value, return that value. Otherwise return null.
1415 Constant *ConstantVector::getSplatValue() {
1416 // Check out first element.
1417 Constant *Elt = getOperand(0);
1418 // Then make sure all remaining elements point to the same value.
1419 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1420 if (getOperand(I) != Elt) return 0;
1424 //---- ConstantPointerNull::get() implementation...
1428 // ConstantPointerNull does not take extra "value" argument...
1429 template<class ValType>
1430 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1431 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1432 return new ConstantPointerNull(Ty);
1437 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1438 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1439 // Make everyone now use a constant of the new type...
1440 Constant *New = ConstantPointerNull::get(NewTy);
1441 assert(New != OldC && "Didn't replace constant??");
1442 OldC->uncheckedReplaceAllUsesWith(New);
1443 OldC->destroyConstant(); // This constant is now dead, destroy it.
1448 static ManagedStatic<ValueMap<char, PointerType,
1449 ConstantPointerNull> > NullPtrConstants;
1451 static char getValType(ConstantPointerNull *) {
1456 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1457 return NullPtrConstants->getOrCreate(Ty, 0);
1460 // destroyConstant - Remove the constant from the constant table...
1462 void ConstantPointerNull::destroyConstant() {
1463 NullPtrConstants->remove(this);
1464 destroyConstantImpl();
1468 //---- UndefValue::get() implementation...
1472 // UndefValue does not take extra "value" argument...
1473 template<class ValType>
1474 struct ConstantCreator<UndefValue, Type, ValType> {
1475 static UndefValue *create(const Type *Ty, const ValType &V) {
1476 return new UndefValue(Ty);
1481 struct ConvertConstantType<UndefValue, Type> {
1482 static void convert(UndefValue *OldC, const Type *NewTy) {
1483 // Make everyone now use a constant of the new type.
1484 Constant *New = UndefValue::get(NewTy);
1485 assert(New != OldC && "Didn't replace constant??");
1486 OldC->uncheckedReplaceAllUsesWith(New);
1487 OldC->destroyConstant(); // This constant is now dead, destroy it.
1492 static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
1494 static char getValType(UndefValue *) {
1499 UndefValue *UndefValue::get(const Type *Ty) {
1500 return UndefValueConstants->getOrCreate(Ty, 0);
1503 // destroyConstant - Remove the constant from the constant table.
1505 void UndefValue::destroyConstant() {
1506 UndefValueConstants->remove(this);
1507 destroyConstantImpl();
1511 //---- ConstantExpr::get() implementations...
1514 struct ExprMapKeyType {
1515 explicit ExprMapKeyType(unsigned opc, std::vector<Constant*> ops,
1516 unsigned short pred = 0) : opcode(opc), predicate(pred), operands(ops) { }
1519 std::vector<Constant*> operands;
1520 bool operator==(const ExprMapKeyType& that) const {
1521 return this->opcode == that.opcode &&
1522 this->predicate == that.predicate &&
1523 this->operands == that.operands;
1525 bool operator<(const ExprMapKeyType & that) const {
1526 return this->opcode < that.opcode ||
1527 (this->opcode == that.opcode && this->predicate < that.predicate) ||
1528 (this->opcode == that.opcode && this->predicate == that.predicate &&
1529 this->operands < that.operands);
1532 bool operator!=(const ExprMapKeyType& that) const {
1533 return !(*this == that);
1539 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1540 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1541 unsigned short pred = 0) {
1542 if (Instruction::isCast(V.opcode))
1543 return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1544 if ((V.opcode >= Instruction::BinaryOpsBegin &&
1545 V.opcode < Instruction::BinaryOpsEnd))
1546 return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1547 if (V.opcode == Instruction::Select)
1548 return new SelectConstantExpr(V.operands[0], V.operands[1],
1550 if (V.opcode == Instruction::ExtractElement)
1551 return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1552 if (V.opcode == Instruction::InsertElement)
1553 return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1555 if (V.opcode == Instruction::ShuffleVector)
1556 return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1558 if (V.opcode == Instruction::GetElementPtr) {
1559 std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
1560 return GetElementPtrConstantExpr::Create(V.operands[0], IdxList, Ty);
1563 // The compare instructions are weird. We have to encode the predicate
1564 // value and it is combined with the instruction opcode by multiplying
1565 // the opcode by one hundred. We must decode this to get the predicate.
1566 if (V.opcode == Instruction::ICmp)
1567 return new CompareConstantExpr(Instruction::ICmp, V.predicate,
1568 V.operands[0], V.operands[1]);
1569 if (V.opcode == Instruction::FCmp)
1570 return new CompareConstantExpr(Instruction::FCmp, V.predicate,
1571 V.operands[0], V.operands[1]);
1572 assert(0 && "Invalid ConstantExpr!");
1578 struct ConvertConstantType<ConstantExpr, Type> {
1579 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1581 switch (OldC->getOpcode()) {
1582 case Instruction::Trunc:
1583 case Instruction::ZExt:
1584 case Instruction::SExt:
1585 case Instruction::FPTrunc:
1586 case Instruction::FPExt:
1587 case Instruction::UIToFP:
1588 case Instruction::SIToFP:
1589 case Instruction::FPToUI:
1590 case Instruction::FPToSI:
1591 case Instruction::PtrToInt:
1592 case Instruction::IntToPtr:
1593 case Instruction::BitCast:
1594 New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0),
1597 case Instruction::Select:
1598 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1599 OldC->getOperand(1),
1600 OldC->getOperand(2));
1603 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1604 OldC->getOpcode() < Instruction::BinaryOpsEnd);
1605 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1606 OldC->getOperand(1));
1608 case Instruction::GetElementPtr:
1609 // Make everyone now use a constant of the new type...
1610 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1611 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0),
1612 &Idx[0], Idx.size());
1616 assert(New != OldC && "Didn't replace constant??");
1617 OldC->uncheckedReplaceAllUsesWith(New);
1618 OldC->destroyConstant(); // This constant is now dead, destroy it.
1621 } // end namespace llvm
1624 static ExprMapKeyType getValType(ConstantExpr *CE) {
1625 std::vector<Constant*> Operands;
1626 Operands.reserve(CE->getNumOperands());
1627 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1628 Operands.push_back(cast<Constant>(CE->getOperand(i)));
1629 return ExprMapKeyType(CE->getOpcode(), Operands,
1630 CE->isCompare() ? CE->getPredicate() : 0);
1633 static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1634 ConstantExpr> > ExprConstants;
1636 /// This is a utility function to handle folding of casts and lookup of the
1637 /// cast in the ExprConstants map. It is used by the various get* methods below.
1638 static inline Constant *getFoldedCast(
1639 Instruction::CastOps opc, Constant *C, const Type *Ty) {
1640 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1641 // Fold a few common cases
1642 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1645 // Look up the constant in the table first to ensure uniqueness
1646 std::vector<Constant*> argVec(1, C);
1647 ExprMapKeyType Key(opc, argVec);
1648 return ExprConstants->getOrCreate(Ty, Key);
1651 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1652 Instruction::CastOps opc = Instruction::CastOps(oc);
1653 assert(Instruction::isCast(opc) && "opcode out of range");
1654 assert(C && Ty && "Null arguments to getCast");
1655 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1659 assert(0 && "Invalid cast opcode");
1661 case Instruction::Trunc: return getTrunc(C, Ty);
1662 case Instruction::ZExt: return getZExt(C, Ty);
1663 case Instruction::SExt: return getSExt(C, Ty);
1664 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1665 case Instruction::FPExt: return getFPExtend(C, Ty);
1666 case Instruction::UIToFP: return getUIToFP(C, Ty);
1667 case Instruction::SIToFP: return getSIToFP(C, Ty);
1668 case Instruction::FPToUI: return getFPToUI(C, Ty);
1669 case Instruction::FPToSI: return getFPToSI(C, Ty);
1670 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1671 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1672 case Instruction::BitCast: return getBitCast(C, Ty);
1677 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1678 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1679 return getCast(Instruction::BitCast, C, Ty);
1680 return getCast(Instruction::ZExt, C, Ty);
1683 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1684 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1685 return getCast(Instruction::BitCast, C, Ty);
1686 return getCast(Instruction::SExt, C, Ty);
1689 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1690 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1691 return getCast(Instruction::BitCast, C, Ty);
1692 return getCast(Instruction::Trunc, C, Ty);
1695 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1696 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1697 assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
1699 if (Ty->isInteger())
1700 return getCast(Instruction::PtrToInt, S, Ty);
1701 return getCast(Instruction::BitCast, S, Ty);
1704 Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
1706 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1707 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1708 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1709 Instruction::CastOps opcode =
1710 (SrcBits == DstBits ? Instruction::BitCast :
1711 (SrcBits > DstBits ? Instruction::Trunc :
1712 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1713 return getCast(opcode, C, Ty);
1716 Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1717 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1719 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1720 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1721 if (SrcBits == DstBits)
1722 return C; // Avoid a useless cast
1723 Instruction::CastOps opcode =
1724 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1725 return getCast(opcode, C, Ty);
1728 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
1729 assert(C->getType()->isInteger() && "Trunc operand must be integer");
1730 assert(Ty->isInteger() && "Trunc produces only integral");
1731 assert(C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1732 "SrcTy must be larger than DestTy for Trunc!");
1734 return getFoldedCast(Instruction::Trunc, C, Ty);
1737 Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
1738 assert(C->getType()->isInteger() && "SEXt operand must be integral");
1739 assert(Ty->isInteger() && "SExt produces only integer");
1740 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1741 "SrcTy must be smaller than DestTy for SExt!");
1743 return getFoldedCast(Instruction::SExt, C, Ty);
1746 Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
1747 assert(C->getType()->isInteger() && "ZEXt operand must be integral");
1748 assert(Ty->isInteger() && "ZExt produces only integer");
1749 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1750 "SrcTy must be smaller than DestTy for ZExt!");
1752 return getFoldedCast(Instruction::ZExt, C, Ty);
1755 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1756 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1757 C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1758 "This is an illegal floating point truncation!");
1759 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1762 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1763 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1764 C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1765 "This is an illegal floating point extension!");
1766 return getFoldedCast(Instruction::FPExt, C, Ty);
1769 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
1770 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1771 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1772 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1773 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1774 "This is an illegal uint to floating point cast!");
1775 return getFoldedCast(Instruction::UIToFP, C, Ty);
1778 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
1779 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1780 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1781 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1782 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1783 "This is an illegal sint to floating point cast!");
1784 return getFoldedCast(Instruction::SIToFP, C, Ty);
1787 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
1788 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1789 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1790 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1791 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1792 "This is an illegal floating point to uint cast!");
1793 return getFoldedCast(Instruction::FPToUI, C, Ty);
1796 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
1797 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1798 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1799 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1800 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1801 "This is an illegal floating point to sint cast!");
1802 return getFoldedCast(Instruction::FPToSI, C, Ty);
1805 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1806 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
1807 assert(DstTy->isInteger() && "PtrToInt destination must be integral");
1808 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1811 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
1812 assert(C->getType()->isInteger() && "IntToPtr source must be integral");
1813 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
1814 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1817 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1818 // BitCast implies a no-op cast of type only. No bits change. However, you
1819 // can't cast pointers to anything but pointers.
1820 const Type *SrcTy = C->getType();
1821 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
1822 "BitCast cannot cast pointer to non-pointer and vice versa");
1824 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
1825 // or nonptr->ptr). For all the other types, the cast is okay if source and
1826 // destination bit widths are identical.
1827 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1828 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
1829 assert(SrcBitSize == DstBitSize && "BitCast requies types of same width");
1830 return getFoldedCast(Instruction::BitCast, C, DstTy);
1833 Constant *ConstantExpr::getSizeOf(const Type *Ty) {
1834 // sizeof is implemented as: (i64) gep (Ty*)null, 1
1835 Constant *GEPIdx = ConstantInt::get(Type::Int32Ty, 1);
1837 getGetElementPtr(getNullValue(PointerType::getUnqual(Ty)), &GEPIdx, 1);
1838 return getCast(Instruction::PtrToInt, GEP, Type::Int64Ty);
1841 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1842 Constant *C1, Constant *C2) {
1843 // Check the operands for consistency first
1844 assert(Opcode >= Instruction::BinaryOpsBegin &&
1845 Opcode < Instruction::BinaryOpsEnd &&
1846 "Invalid opcode in binary constant expression");
1847 assert(C1->getType() == C2->getType() &&
1848 "Operand types in binary constant expression should match");
1850 if (ReqTy == C1->getType() || ReqTy == Type::Int1Ty)
1851 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1852 return FC; // Fold a few common cases...
1854 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1855 ExprMapKeyType Key(Opcode, argVec);
1856 return ExprConstants->getOrCreate(ReqTy, Key);
1859 Constant *ConstantExpr::getCompareTy(unsigned short predicate,
1860 Constant *C1, Constant *C2) {
1861 switch (predicate) {
1862 default: assert(0 && "Invalid CmpInst predicate");
1863 case FCmpInst::FCMP_FALSE: case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_OGT:
1864 case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OLE:
1865 case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_ORD: case FCmpInst::FCMP_UNO:
1866 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UGT: case FCmpInst::FCMP_UGE:
1867 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_ULE: case FCmpInst::FCMP_UNE:
1868 case FCmpInst::FCMP_TRUE:
1869 return getFCmp(predicate, C1, C2);
1870 case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGT:
1871 case ICmpInst::ICMP_UGE: case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE:
1872 case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_SGE: case ICmpInst::ICMP_SLT:
1873 case ICmpInst::ICMP_SLE:
1874 return getICmp(predicate, C1, C2);
1878 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
1881 case Instruction::Add:
1882 case Instruction::Sub:
1883 case Instruction::Mul:
1884 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1885 assert((C1->getType()->isInteger() || C1->getType()->isFloatingPoint() ||
1886 isa<VectorType>(C1->getType())) &&
1887 "Tried to create an arithmetic operation on a non-arithmetic type!");
1889 case Instruction::UDiv:
1890 case Instruction::SDiv:
1891 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1892 assert((C1->getType()->isInteger() || (isa<VectorType>(C1->getType()) &&
1893 cast<VectorType>(C1->getType())->getElementType()->isInteger())) &&
1894 "Tried to create an arithmetic operation on a non-arithmetic type!");
1896 case Instruction::FDiv:
1897 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1898 assert((C1->getType()->isFloatingPoint() || (isa<VectorType>(C1->getType())
1899 && cast<VectorType>(C1->getType())->getElementType()->isFloatingPoint()))
1900 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1902 case Instruction::URem:
1903 case Instruction::SRem:
1904 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1905 assert((C1->getType()->isInteger() || (isa<VectorType>(C1->getType()) &&
1906 cast<VectorType>(C1->getType())->getElementType()->isInteger())) &&
1907 "Tried to create an arithmetic operation on a non-arithmetic type!");
1909 case Instruction::FRem:
1910 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1911 assert((C1->getType()->isFloatingPoint() || (isa<VectorType>(C1->getType())
1912 && cast<VectorType>(C1->getType())->getElementType()->isFloatingPoint()))
1913 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1915 case Instruction::And:
1916 case Instruction::Or:
1917 case Instruction::Xor:
1918 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1919 assert((C1->getType()->isInteger() || isa<VectorType>(C1->getType())) &&
1920 "Tried to create a logical operation on a non-integral type!");
1922 case Instruction::Shl:
1923 case Instruction::LShr:
1924 case Instruction::AShr:
1925 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1926 assert(C1->getType()->isInteger() &&
1927 "Tried to create a shift operation on a non-integer type!");
1934 return getTy(C1->getType(), Opcode, C1, C2);
1937 Constant *ConstantExpr::getCompare(unsigned short pred,
1938 Constant *C1, Constant *C2) {
1939 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1940 return getCompareTy(pred, C1, C2);
1943 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1944 Constant *V1, Constant *V2) {
1945 assert(C->getType() == Type::Int1Ty && "Select condition must be i1!");
1946 assert(V1->getType() == V2->getType() && "Select value types must match!");
1947 assert(V1->getType()->isFirstClassType() && "Cannot select aggregate type!");
1949 if (ReqTy == V1->getType())
1950 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1951 return SC; // Fold common cases
1953 std::vector<Constant*> argVec(3, C);
1956 ExprMapKeyType Key(Instruction::Select, argVec);
1957 return ExprConstants->getOrCreate(ReqTy, Key);
1960 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1963 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx, true) &&
1964 "GEP indices invalid!");
1966 if (Constant *FC = ConstantFoldGetElementPtr(C, (Constant**)Idxs, NumIdx))
1967 return FC; // Fold a few common cases...
1969 assert(isa<PointerType>(C->getType()) &&
1970 "Non-pointer type for constant GetElementPtr expression");
1971 // Look up the constant in the table first to ensure uniqueness
1972 std::vector<Constant*> ArgVec;
1973 ArgVec.reserve(NumIdx+1);
1974 ArgVec.push_back(C);
1975 for (unsigned i = 0; i != NumIdx; ++i)
1976 ArgVec.push_back(cast<Constant>(Idxs[i]));
1977 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
1978 return ExprConstants->getOrCreate(ReqTy, Key);
1981 Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
1983 // Get the result type of the getelementptr!
1985 GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx, true);
1986 assert(Ty && "GEP indices invalid!");
1987 unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
1988 return getGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx);
1991 Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
1993 return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
1998 ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1999 assert(LHS->getType() == RHS->getType());
2000 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
2001 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
2003 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
2004 return FC; // Fold a few common cases...
2006 // Look up the constant in the table first to ensure uniqueness
2007 std::vector<Constant*> ArgVec;
2008 ArgVec.push_back(LHS);
2009 ArgVec.push_back(RHS);
2010 // Get the key type with both the opcode and predicate
2011 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
2012 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
2016 ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2017 assert(LHS->getType() == RHS->getType());
2018 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
2020 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
2021 return FC; // Fold a few common cases...
2023 // Look up the constant in the table first to ensure uniqueness
2024 std::vector<Constant*> ArgVec;
2025 ArgVec.push_back(LHS);
2026 ArgVec.push_back(RHS);
2027 // Get the key type with both the opcode and predicate
2028 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
2029 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
2032 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
2034 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
2035 return FC; // Fold a few common cases...
2036 // Look up the constant in the table first to ensure uniqueness
2037 std::vector<Constant*> ArgVec(1, Val);
2038 ArgVec.push_back(Idx);
2039 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
2040 return ExprConstants->getOrCreate(ReqTy, Key);
2043 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
2044 assert(isa<VectorType>(Val->getType()) &&
2045 "Tried to create extractelement operation on non-vector type!");
2046 assert(Idx->getType() == Type::Int32Ty &&
2047 "Extractelement index must be i32 type!");
2048 return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
2052 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
2053 Constant *Elt, Constant *Idx) {
2054 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
2055 return FC; // Fold a few common cases...
2056 // Look up the constant in the table first to ensure uniqueness
2057 std::vector<Constant*> ArgVec(1, Val);
2058 ArgVec.push_back(Elt);
2059 ArgVec.push_back(Idx);
2060 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
2061 return ExprConstants->getOrCreate(ReqTy, Key);
2064 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
2066 assert(isa<VectorType>(Val->getType()) &&
2067 "Tried to create insertelement operation on non-vector type!");
2068 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
2069 && "Insertelement types must match!");
2070 assert(Idx->getType() == Type::Int32Ty &&
2071 "Insertelement index must be i32 type!");
2072 return getInsertElementTy(cast<VectorType>(Val->getType())->getElementType(),
2076 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
2077 Constant *V2, Constant *Mask) {
2078 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
2079 return FC; // Fold a few common cases...
2080 // Look up the constant in the table first to ensure uniqueness
2081 std::vector<Constant*> ArgVec(1, V1);
2082 ArgVec.push_back(V2);
2083 ArgVec.push_back(Mask);
2084 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
2085 return ExprConstants->getOrCreate(ReqTy, Key);
2088 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
2090 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
2091 "Invalid shuffle vector constant expr operands!");
2092 return getShuffleVectorTy(V1->getType(), V1, V2, Mask);
2095 Constant *ConstantExpr::getZeroValueForNegationExpr(const Type *Ty) {
2096 if (const VectorType *PTy = dyn_cast<VectorType>(Ty))
2097 if (PTy->getElementType()->isFloatingPoint()) {
2098 std::vector<Constant*> zeros(PTy->getNumElements(),
2099 ConstantFP::getNegativeZero(PTy->getElementType()));
2100 return ConstantVector::get(PTy, zeros);
2103 if (Ty->isFloatingPoint())
2104 return ConstantFP::getNegativeZero(Ty);
2106 return Constant::getNullValue(Ty);
2109 // destroyConstant - Remove the constant from the constant table...
2111 void ConstantExpr::destroyConstant() {
2112 ExprConstants->remove(this);
2113 destroyConstantImpl();
2116 const char *ConstantExpr::getOpcodeName() const {
2117 return Instruction::getOpcodeName(getOpcode());
2120 //===----------------------------------------------------------------------===//
2121 // replaceUsesOfWithOnConstant implementations
2123 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
2124 /// 'From' to be uses of 'To'. This must update the uniquing data structures
2127 /// Note that we intentionally replace all uses of From with To here. Consider
2128 /// a large array that uses 'From' 1000 times. By handling this case all here,
2129 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
2130 /// single invocation handles all 1000 uses. Handling them one at a time would
2131 /// work, but would be really slow because it would have to unique each updated
2133 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
2135 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2136 Constant *ToC = cast<Constant>(To);
2138 std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
2139 Lookup.first.first = getType();
2140 Lookup.second = this;
2142 std::vector<Constant*> &Values = Lookup.first.second;
2143 Values.reserve(getNumOperands()); // Build replacement array.
2145 // Fill values with the modified operands of the constant array. Also,
2146 // compute whether this turns into an all-zeros array.
2147 bool isAllZeros = false;
2148 unsigned NumUpdated = 0;
2149 if (!ToC->isNullValue()) {
2150 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2151 Constant *Val = cast<Constant>(O->get());
2156 Values.push_back(Val);
2160 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2161 Constant *Val = cast<Constant>(O->get());
2166 Values.push_back(Val);
2167 if (isAllZeros) isAllZeros = Val->isNullValue();
2171 Constant *Replacement = 0;
2173 Replacement = ConstantAggregateZero::get(getType());
2175 // Check to see if we have this array type already.
2177 ArrayConstantsTy::MapTy::iterator I =
2178 ArrayConstants->InsertOrGetItem(Lookup, Exists);
2181 Replacement = I->second;
2183 // Okay, the new shape doesn't exist in the system yet. Instead of
2184 // creating a new constant array, inserting it, replaceallusesof'ing the
2185 // old with the new, then deleting the old... just update the current one
2187 ArrayConstants->MoveConstantToNewSlot(this, I);
2189 // Update to the new value. Optimize for the case when we have a single
2190 // operand that we're changing, but handle bulk updates efficiently.
2191 if (NumUpdated == 1) {
2192 unsigned OperandToUpdate = U-OperandList;
2193 assert(getOperand(OperandToUpdate) == From &&
2194 "ReplaceAllUsesWith broken!");
2195 setOperand(OperandToUpdate, ToC);
2197 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2198 if (getOperand(i) == From)
2205 // Otherwise, I do need to replace this with an existing value.
2206 assert(Replacement != this && "I didn't contain From!");
2208 // Everyone using this now uses the replacement.
2209 uncheckedReplaceAllUsesWith(Replacement);
2211 // Delete the old constant!
2215 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
2217 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2218 Constant *ToC = cast<Constant>(To);
2220 unsigned OperandToUpdate = U-OperandList;
2221 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2223 std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
2224 Lookup.first.first = getType();
2225 Lookup.second = this;
2226 std::vector<Constant*> &Values = Lookup.first.second;
2227 Values.reserve(getNumOperands()); // Build replacement struct.
2230 // Fill values with the modified operands of the constant struct. Also,
2231 // compute whether this turns into an all-zeros struct.
2232 bool isAllZeros = false;
2233 if (!ToC->isNullValue()) {
2234 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
2235 Values.push_back(cast<Constant>(O->get()));
2238 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2239 Constant *Val = cast<Constant>(O->get());
2240 Values.push_back(Val);
2241 if (isAllZeros) isAllZeros = Val->isNullValue();
2244 Values[OperandToUpdate] = ToC;
2246 Constant *Replacement = 0;
2248 Replacement = ConstantAggregateZero::get(getType());
2250 // Check to see if we have this array type already.
2252 StructConstantsTy::MapTy::iterator I =
2253 StructConstants->InsertOrGetItem(Lookup, Exists);
2256 Replacement = I->second;
2258 // Okay, the new shape doesn't exist in the system yet. Instead of
2259 // creating a new constant struct, inserting it, replaceallusesof'ing the
2260 // old with the new, then deleting the old... just update the current one
2262 StructConstants->MoveConstantToNewSlot(this, I);
2264 // Update to the new value.
2265 setOperand(OperandToUpdate, ToC);
2270 assert(Replacement != this && "I didn't contain From!");
2272 // Everyone using this now uses the replacement.
2273 uncheckedReplaceAllUsesWith(Replacement);
2275 // Delete the old constant!
2279 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
2281 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2283 std::vector<Constant*> Values;
2284 Values.reserve(getNumOperands()); // Build replacement array...
2285 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2286 Constant *Val = getOperand(i);
2287 if (Val == From) Val = cast<Constant>(To);
2288 Values.push_back(Val);
2291 Constant *Replacement = ConstantVector::get(getType(), Values);
2292 assert(Replacement != this && "I didn't contain From!");
2294 // Everyone using this now uses the replacement.
2295 uncheckedReplaceAllUsesWith(Replacement);
2297 // Delete the old constant!
2301 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2303 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2304 Constant *To = cast<Constant>(ToV);
2306 Constant *Replacement = 0;
2307 if (getOpcode() == Instruction::GetElementPtr) {
2308 SmallVector<Constant*, 8> Indices;
2309 Constant *Pointer = getOperand(0);
2310 Indices.reserve(getNumOperands()-1);
2311 if (Pointer == From) Pointer = To;
2313 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2314 Constant *Val = getOperand(i);
2315 if (Val == From) Val = To;
2316 Indices.push_back(Val);
2318 Replacement = ConstantExpr::getGetElementPtr(Pointer,
2319 &Indices[0], Indices.size());
2320 } else if (isCast()) {
2321 assert(getOperand(0) == From && "Cast only has one use!");
2322 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
2323 } else if (getOpcode() == Instruction::Select) {
2324 Constant *C1 = getOperand(0);
2325 Constant *C2 = getOperand(1);
2326 Constant *C3 = getOperand(2);
2327 if (C1 == From) C1 = To;
2328 if (C2 == From) C2 = To;
2329 if (C3 == From) C3 = To;
2330 Replacement = ConstantExpr::getSelect(C1, C2, C3);
2331 } else if (getOpcode() == Instruction::ExtractElement) {
2332 Constant *C1 = getOperand(0);
2333 Constant *C2 = getOperand(1);
2334 if (C1 == From) C1 = To;
2335 if (C2 == From) C2 = To;
2336 Replacement = ConstantExpr::getExtractElement(C1, C2);
2337 } else if (getOpcode() == Instruction::InsertElement) {
2338 Constant *C1 = getOperand(0);
2339 Constant *C2 = getOperand(1);
2340 Constant *C3 = getOperand(1);
2341 if (C1 == From) C1 = To;
2342 if (C2 == From) C2 = To;
2343 if (C3 == From) C3 = To;
2344 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2345 } else if (getOpcode() == Instruction::ShuffleVector) {
2346 Constant *C1 = getOperand(0);
2347 Constant *C2 = getOperand(1);
2348 Constant *C3 = getOperand(2);
2349 if (C1 == From) C1 = To;
2350 if (C2 == From) C2 = To;
2351 if (C3 == From) C3 = To;
2352 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2353 } else if (isCompare()) {
2354 Constant *C1 = getOperand(0);
2355 Constant *C2 = getOperand(1);
2356 if (C1 == From) C1 = To;
2357 if (C2 == From) C2 = To;
2358 if (getOpcode() == Instruction::ICmp)
2359 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2361 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2362 } else if (getNumOperands() == 2) {
2363 Constant *C1 = getOperand(0);
2364 Constant *C2 = getOperand(1);
2365 if (C1 == From) C1 = To;
2366 if (C2 == From) C2 = To;
2367 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2369 assert(0 && "Unknown ConstantExpr type!");
2373 assert(Replacement != this && "I didn't contain From!");
2375 // Everyone using this now uses the replacement.
2376 uncheckedReplaceAllUsesWith(Replacement);
2378 // Delete the old constant!
2383 /// getStringValue - Turn an LLVM constant pointer that eventually points to a
2384 /// global into a string value. Return an empty string if we can't do it.
2385 /// Parameter Chop determines if the result is chopped at the first null
2388 std::string Constant::getStringValue(bool Chop, unsigned Offset) {
2389 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(this)) {
2390 if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
2391 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
2392 if (Init->isString()) {
2393 std::string Result = Init->getAsString();
2394 if (Offset < Result.size()) {
2395 // If we are pointing INTO The string, erase the beginning...
2396 Result.erase(Result.begin(), Result.begin()+Offset);
2398 // Take off the null terminator, and any string fragments after it.
2400 std::string::size_type NullPos = Result.find_first_of((char)0);
2401 if (NullPos != std::string::npos)
2402 Result.erase(Result.begin()+NullPos, Result.end());
2408 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(this)) {
2409 if (CE->getOpcode() == Instruction::GetElementPtr) {
2410 // Turn a gep into the specified offset.
2411 if (CE->getNumOperands() == 3 &&
2412 cast<Constant>(CE->getOperand(1))->isNullValue() &&
2413 isa<ConstantInt>(CE->getOperand(2))) {
2414 Offset += cast<ConstantInt>(CE->getOperand(2))->getZExtValue();
2415 return CE->getOperand(0)->getStringValue(Chop, Offset);