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,
543 const std::vector<Constant*>&IdxList,
544 const Type *DestTy) {
545 return new(IdxList.size() + 1)
546 GetElementPtrConstantExpr(C, IdxList, DestTy);
548 /// Transparently provide more efficient getOperand methods.
549 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
552 // CompareConstantExpr - This class is private to Constants.cpp, and is used
553 // behind the scenes to implement ICmp and FCmp constant expressions. This is
554 // needed in order to store the predicate value for these instructions.
555 struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
556 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
557 // allocate space for exactly two operands
558 void *operator new(size_t s) {
559 return User::operator new(s, 2);
561 unsigned short predicate;
562 CompareConstantExpr(const Type *ty, Instruction::OtherOps opc,
563 unsigned short pred, Constant* LHS, Constant* RHS)
564 : ConstantExpr(ty, opc, &Op<0>(), 2), predicate(pred) {
565 Op<0>().init(LHS, this);
566 Op<1>().init(RHS, this);
568 /// Transparently provide more efficient getOperand methods.
569 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
572 } // end anonymous namespace
575 struct OperandTraits<UnaryConstantExpr> : FixedNumOperandTraits<1> {
577 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(UnaryConstantExpr, Value)
580 struct OperandTraits<BinaryConstantExpr> : FixedNumOperandTraits<2> {
582 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BinaryConstantExpr, Value)
585 struct OperandTraits<SelectConstantExpr> : FixedNumOperandTraits<3> {
587 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectConstantExpr, Value)
590 struct OperandTraits<ExtractElementConstantExpr> : FixedNumOperandTraits<2> {
592 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementConstantExpr, Value)
595 struct OperandTraits<InsertElementConstantExpr> : FixedNumOperandTraits<3> {
597 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementConstantExpr, Value)
600 struct OperandTraits<ShuffleVectorConstantExpr> : FixedNumOperandTraits<3> {
602 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorConstantExpr, Value)
606 struct OperandTraits<GetElementPtrConstantExpr> : VariadicOperandTraits<1> {
609 GetElementPtrConstantExpr::GetElementPtrConstantExpr
611 const std::vector<Constant*> &IdxList,
613 : ConstantExpr(DestTy, Instruction::GetElementPtr,
614 OperandTraits<GetElementPtrConstantExpr>::op_end(this)
615 - (IdxList.size()+1),
617 OperandList[0].init(C, this);
618 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
619 OperandList[i+1].init(IdxList[i], this);
622 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrConstantExpr, Value)
626 struct OperandTraits<CompareConstantExpr> : FixedNumOperandTraits<2> {
628 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CompareConstantExpr, Value)
631 } // End llvm namespace
634 // Utility function for determining if a ConstantExpr is a CastOp or not. This
635 // can't be inline because we don't want to #include Instruction.h into
637 bool ConstantExpr::isCast() const {
638 return Instruction::isCast(getOpcode());
641 bool ConstantExpr::isCompare() const {
642 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
645 /// ConstantExpr::get* - Return some common constants without having to
646 /// specify the full Instruction::OPCODE identifier.
648 Constant *ConstantExpr::getNeg(Constant *C) {
649 return get(Instruction::Sub,
650 ConstantExpr::getZeroValueForNegationExpr(C->getType()),
653 Constant *ConstantExpr::getNot(Constant *C) {
654 assert(isa<IntegerType>(C->getType()) && "Cannot NOT a nonintegral value!");
655 return get(Instruction::Xor, C,
656 ConstantInt::getAllOnesValue(C->getType()));
658 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
659 return get(Instruction::Add, C1, C2);
661 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
662 return get(Instruction::Sub, C1, C2);
664 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
665 return get(Instruction::Mul, C1, C2);
667 Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2) {
668 return get(Instruction::UDiv, C1, C2);
670 Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2) {
671 return get(Instruction::SDiv, C1, C2);
673 Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
674 return get(Instruction::FDiv, C1, C2);
676 Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
677 return get(Instruction::URem, C1, C2);
679 Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
680 return get(Instruction::SRem, C1, C2);
682 Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
683 return get(Instruction::FRem, C1, C2);
685 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
686 return get(Instruction::And, C1, C2);
688 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
689 return get(Instruction::Or, C1, C2);
691 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
692 return get(Instruction::Xor, C1, C2);
694 unsigned ConstantExpr::getPredicate() const {
695 assert(getOpcode() == Instruction::FCmp ||
696 getOpcode() == Instruction::ICmp ||
697 getOpcode() == Instruction::VFCmp ||
698 getOpcode() == Instruction::VICmp);
699 return ((const CompareConstantExpr*)this)->predicate;
701 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
702 return get(Instruction::Shl, C1, C2);
704 Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2) {
705 return get(Instruction::LShr, C1, C2);
707 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2) {
708 return get(Instruction::AShr, C1, C2);
711 /// getWithOperandReplaced - Return a constant expression identical to this
712 /// one, but with the specified operand set to the specified value.
714 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
715 assert(OpNo < getNumOperands() && "Operand num is out of range!");
716 assert(Op->getType() == getOperand(OpNo)->getType() &&
717 "Replacing operand with value of different type!");
718 if (getOperand(OpNo) == Op)
719 return const_cast<ConstantExpr*>(this);
721 Constant *Op0, *Op1, *Op2;
722 switch (getOpcode()) {
723 case Instruction::Trunc:
724 case Instruction::ZExt:
725 case Instruction::SExt:
726 case Instruction::FPTrunc:
727 case Instruction::FPExt:
728 case Instruction::UIToFP:
729 case Instruction::SIToFP:
730 case Instruction::FPToUI:
731 case Instruction::FPToSI:
732 case Instruction::PtrToInt:
733 case Instruction::IntToPtr:
734 case Instruction::BitCast:
735 return ConstantExpr::getCast(getOpcode(), Op, getType());
736 case Instruction::Select:
737 Op0 = (OpNo == 0) ? Op : getOperand(0);
738 Op1 = (OpNo == 1) ? Op : getOperand(1);
739 Op2 = (OpNo == 2) ? Op : getOperand(2);
740 return ConstantExpr::getSelect(Op0, Op1, Op2);
741 case Instruction::InsertElement:
742 Op0 = (OpNo == 0) ? Op : getOperand(0);
743 Op1 = (OpNo == 1) ? Op : getOperand(1);
744 Op2 = (OpNo == 2) ? Op : getOperand(2);
745 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
746 case Instruction::ExtractElement:
747 Op0 = (OpNo == 0) ? Op : getOperand(0);
748 Op1 = (OpNo == 1) ? Op : getOperand(1);
749 return ConstantExpr::getExtractElement(Op0, Op1);
750 case Instruction::ShuffleVector:
751 Op0 = (OpNo == 0) ? Op : getOperand(0);
752 Op1 = (OpNo == 1) ? Op : getOperand(1);
753 Op2 = (OpNo == 2) ? Op : getOperand(2);
754 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
755 case Instruction::GetElementPtr: {
756 SmallVector<Constant*, 8> Ops;
757 Ops.resize(getNumOperands());
758 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
759 Ops[i] = getOperand(i);
761 return ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
763 return ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
766 assert(getNumOperands() == 2 && "Must be binary operator?");
767 Op0 = (OpNo == 0) ? Op : getOperand(0);
768 Op1 = (OpNo == 1) ? Op : getOperand(1);
769 return ConstantExpr::get(getOpcode(), Op0, Op1);
773 /// getWithOperands - This returns the current constant expression with the
774 /// operands replaced with the specified values. The specified operands must
775 /// match count and type with the existing ones.
776 Constant *ConstantExpr::
777 getWithOperands(const std::vector<Constant*> &Ops) const {
778 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
779 bool AnyChange = false;
780 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
781 assert(Ops[i]->getType() == getOperand(i)->getType() &&
782 "Operand type mismatch!");
783 AnyChange |= Ops[i] != getOperand(i);
785 if (!AnyChange) // No operands changed, return self.
786 return const_cast<ConstantExpr*>(this);
788 switch (getOpcode()) {
789 case Instruction::Trunc:
790 case Instruction::ZExt:
791 case Instruction::SExt:
792 case Instruction::FPTrunc:
793 case Instruction::FPExt:
794 case Instruction::UIToFP:
795 case Instruction::SIToFP:
796 case Instruction::FPToUI:
797 case Instruction::FPToSI:
798 case Instruction::PtrToInt:
799 case Instruction::IntToPtr:
800 case Instruction::BitCast:
801 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
802 case Instruction::Select:
803 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
804 case Instruction::InsertElement:
805 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
806 case Instruction::ExtractElement:
807 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
808 case Instruction::ShuffleVector:
809 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
810 case Instruction::GetElementPtr:
811 return ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], Ops.size()-1);
812 case Instruction::ICmp:
813 case Instruction::FCmp:
814 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
816 assert(getNumOperands() == 2 && "Must be binary operator?");
817 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
822 //===----------------------------------------------------------------------===//
823 // isValueValidForType implementations
825 bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
826 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
827 if (Ty == Type::Int1Ty)
828 return Val == 0 || Val == 1;
830 return true; // always true, has to fit in largest type
831 uint64_t Max = (1ll << NumBits) - 1;
835 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
836 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
837 if (Ty == Type::Int1Ty)
838 return Val == 0 || Val == 1 || Val == -1;
840 return true; // always true, has to fit in largest type
841 int64_t Min = -(1ll << (NumBits-1));
842 int64_t Max = (1ll << (NumBits-1)) - 1;
843 return (Val >= Min && Val <= Max);
846 bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
847 // convert modifies in place, so make a copy.
848 APFloat Val2 = APFloat(Val);
849 switch (Ty->getTypeID()) {
851 return false; // These can't be represented as floating point!
853 // FIXME rounding mode needs to be more flexible
854 case Type::FloatTyID:
855 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
856 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven) ==
858 case Type::DoubleTyID:
859 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
860 &Val2.getSemantics() == &APFloat::IEEEdouble ||
861 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven) ==
863 case Type::X86_FP80TyID:
864 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
865 &Val2.getSemantics() == &APFloat::IEEEdouble ||
866 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
867 case Type::FP128TyID:
868 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
869 &Val2.getSemantics() == &APFloat::IEEEdouble ||
870 &Val2.getSemantics() == &APFloat::IEEEquad;
871 case Type::PPC_FP128TyID:
872 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
873 &Val2.getSemantics() == &APFloat::IEEEdouble ||
874 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
878 //===----------------------------------------------------------------------===//
879 // Factory Function Implementation
882 // The number of operands for each ConstantCreator::create method is
883 // determined by the ConstantTraits template.
884 // ConstantCreator - A class that is used to create constants by
885 // ValueMap*. This class should be partially specialized if there is
886 // something strange that needs to be done to interface to the ctor for the
890 template<class ValType>
891 struct ConstantTraits;
893 template<typename T, typename Alloc>
894 struct VISIBILITY_HIDDEN ConstantTraits< std::vector<T, Alloc> > {
895 static unsigned uses(const std::vector<T, Alloc>& v) {
900 template<class ConstantClass, class TypeClass, class ValType>
901 struct VISIBILITY_HIDDEN ConstantCreator {
902 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
903 return new(ConstantTraits<ValType>::uses(V)) ConstantClass(Ty, V);
907 template<class ConstantClass, class TypeClass>
908 struct VISIBILITY_HIDDEN ConvertConstantType {
909 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
910 assert(0 && "This type cannot be converted!\n");
915 template<class ValType, class TypeClass, class ConstantClass,
916 bool HasLargeKey = false /*true for arrays and structs*/ >
917 class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
919 typedef std::pair<const Type*, ValType> MapKey;
920 typedef std::map<MapKey, Constant *> MapTy;
921 typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
922 typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
924 /// Map - This is the main map from the element descriptor to the Constants.
925 /// This is the primary way we avoid creating two of the same shape
929 /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
930 /// from the constants to their element in Map. This is important for
931 /// removal of constants from the array, which would otherwise have to scan
932 /// through the map with very large keys.
933 InverseMapTy InverseMap;
935 /// AbstractTypeMap - Map for abstract type constants.
937 AbstractTypeMapTy AbstractTypeMap;
940 typename MapTy::iterator map_end() { return Map.end(); }
942 /// InsertOrGetItem - Return an iterator for the specified element.
943 /// If the element exists in the map, the returned iterator points to the
944 /// entry and Exists=true. If not, the iterator points to the newly
945 /// inserted entry and returns Exists=false. Newly inserted entries have
946 /// I->second == 0, and should be filled in.
947 typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
950 std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
956 typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
958 typename InverseMapTy::iterator IMI = InverseMap.find(CP);
959 assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
960 IMI->second->second == CP &&
961 "InverseMap corrupt!");
965 typename MapTy::iterator I =
966 Map.find(MapKey((TypeClass*)CP->getRawType(), getValType(CP)));
967 if (I == Map.end() || I->second != CP) {
968 // FIXME: This should not use a linear scan. If this gets to be a
969 // performance problem, someone should look at this.
970 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
977 /// getOrCreate - Return the specified constant from the map, creating it if
979 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
980 MapKey Lookup(Ty, V);
981 typename MapTy::iterator I = Map.lower_bound(Lookup);
983 if (I != Map.end() && I->first == Lookup)
984 return static_cast<ConstantClass *>(I->second);
986 // If no preexisting value, create one now...
987 ConstantClass *Result =
988 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
990 /// FIXME: why does this assert fail when loading 176.gcc?
991 //assert(Result->getType() == Ty && "Type specified is not correct!");
992 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
994 if (HasLargeKey) // Remember the reverse mapping if needed.
995 InverseMap.insert(std::make_pair(Result, I));
997 // If the type of the constant is abstract, make sure that an entry exists
998 // for it in the AbstractTypeMap.
999 if (Ty->isAbstract()) {
1000 typename AbstractTypeMapTy::iterator TI =
1001 AbstractTypeMap.lower_bound(Ty);
1003 if (TI == AbstractTypeMap.end() || TI->first != Ty) {
1004 // Add ourselves to the ATU list of the type.
1005 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
1007 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
1013 void remove(ConstantClass *CP) {
1014 typename MapTy::iterator I = FindExistingElement(CP);
1015 assert(I != Map.end() && "Constant not found in constant table!");
1016 assert(I->second == CP && "Didn't find correct element?");
1018 if (HasLargeKey) // Remember the reverse mapping if needed.
1019 InverseMap.erase(CP);
1021 // Now that we found the entry, make sure this isn't the entry that
1022 // the AbstractTypeMap points to.
1023 const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
1024 if (Ty->isAbstract()) {
1025 assert(AbstractTypeMap.count(Ty) &&
1026 "Abstract type not in AbstractTypeMap?");
1027 typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
1028 if (ATMEntryIt == I) {
1029 // Yes, we are removing the representative entry for this type.
1030 // See if there are any other entries of the same type.
1031 typename MapTy::iterator TmpIt = ATMEntryIt;
1033 // First check the entry before this one...
1034 if (TmpIt != Map.begin()) {
1036 if (TmpIt->first.first != Ty) // Not the same type, move back...
1040 // If we didn't find the same type, try to move forward...
1041 if (TmpIt == ATMEntryIt) {
1043 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
1044 --TmpIt; // No entry afterwards with the same type
1047 // If there is another entry in the map of the same abstract type,
1048 // update the AbstractTypeMap entry now.
1049 if (TmpIt != ATMEntryIt) {
1052 // Otherwise, we are removing the last instance of this type
1053 // from the table. Remove from the ATM, and from user list.
1054 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
1055 AbstractTypeMap.erase(Ty);
1064 /// MoveConstantToNewSlot - If we are about to change C to be the element
1065 /// specified by I, update our internal data structures to reflect this
1067 void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
1068 // First, remove the old location of the specified constant in the map.
1069 typename MapTy::iterator OldI = FindExistingElement(C);
1070 assert(OldI != Map.end() && "Constant not found in constant table!");
1071 assert(OldI->second == C && "Didn't find correct element?");
1073 // If this constant is the representative element for its abstract type,
1074 // update the AbstractTypeMap so that the representative element is I.
1075 if (C->getType()->isAbstract()) {
1076 typename AbstractTypeMapTy::iterator ATI =
1077 AbstractTypeMap.find(C->getType());
1078 assert(ATI != AbstractTypeMap.end() &&
1079 "Abstract type not in AbstractTypeMap?");
1080 if (ATI->second == OldI)
1084 // Remove the old entry from the map.
1087 // Update the inverse map so that we know that this constant is now
1088 // located at descriptor I.
1090 assert(I->second == C && "Bad inversemap entry!");
1095 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
1096 typename AbstractTypeMapTy::iterator I =
1097 AbstractTypeMap.find(cast<Type>(OldTy));
1099 assert(I != AbstractTypeMap.end() &&
1100 "Abstract type not in AbstractTypeMap?");
1102 // Convert a constant at a time until the last one is gone. The last one
1103 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
1104 // eliminated eventually.
1106 ConvertConstantType<ConstantClass,
1107 TypeClass>::convert(
1108 static_cast<ConstantClass *>(I->second->second),
1109 cast<TypeClass>(NewTy));
1111 I = AbstractTypeMap.find(cast<Type>(OldTy));
1112 } while (I != AbstractTypeMap.end());
1115 // If the type became concrete without being refined to any other existing
1116 // type, we just remove ourselves from the ATU list.
1117 void typeBecameConcrete(const DerivedType *AbsTy) {
1118 AbsTy->removeAbstractTypeUser(this);
1122 DOUT << "Constant.cpp: ValueMap\n";
1129 //---- ConstantAggregateZero::get() implementation...
1132 // ConstantAggregateZero does not take extra "value" argument...
1133 template<class ValType>
1134 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
1135 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
1136 return new ConstantAggregateZero(Ty);
1141 struct ConvertConstantType<ConstantAggregateZero, Type> {
1142 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
1143 // Make everyone now use a constant of the new type...
1144 Constant *New = ConstantAggregateZero::get(NewTy);
1145 assert(New != OldC && "Didn't replace constant??");
1146 OldC->uncheckedReplaceAllUsesWith(New);
1147 OldC->destroyConstant(); // This constant is now dead, destroy it.
1152 static ManagedStatic<ValueMap<char, Type,
1153 ConstantAggregateZero> > AggZeroConstants;
1155 static char getValType(ConstantAggregateZero *CPZ) { return 0; }
1157 Constant *ConstantAggregateZero::get(const Type *Ty) {
1158 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) &&
1159 "Cannot create an aggregate zero of non-aggregate type!");
1160 return AggZeroConstants->getOrCreate(Ty, 0);
1163 // destroyConstant - Remove the constant from the constant table...
1165 void ConstantAggregateZero::destroyConstant() {
1166 AggZeroConstants->remove(this);
1167 destroyConstantImpl();
1170 //---- ConstantArray::get() implementation...
1174 struct ConvertConstantType<ConstantArray, ArrayType> {
1175 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
1176 // Make everyone now use a constant of the new type...
1177 std::vector<Constant*> C;
1178 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1179 C.push_back(cast<Constant>(OldC->getOperand(i)));
1180 Constant *New = ConstantArray::get(NewTy, C);
1181 assert(New != OldC && "Didn't replace constant??");
1182 OldC->uncheckedReplaceAllUsesWith(New);
1183 OldC->destroyConstant(); // This constant is now dead, destroy it.
1188 static std::vector<Constant*> getValType(ConstantArray *CA) {
1189 std::vector<Constant*> Elements;
1190 Elements.reserve(CA->getNumOperands());
1191 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1192 Elements.push_back(cast<Constant>(CA->getOperand(i)));
1196 typedef ValueMap<std::vector<Constant*>, ArrayType,
1197 ConstantArray, true /*largekey*/> ArrayConstantsTy;
1198 static ManagedStatic<ArrayConstantsTy> ArrayConstants;
1200 Constant *ConstantArray::get(const ArrayType *Ty,
1201 const std::vector<Constant*> &V) {
1202 // If this is an all-zero array, return a ConstantAggregateZero object
1205 if (!C->isNullValue())
1206 return ArrayConstants->getOrCreate(Ty, V);
1207 for (unsigned i = 1, e = V.size(); i != e; ++i)
1209 return ArrayConstants->getOrCreate(Ty, V);
1211 return ConstantAggregateZero::get(Ty);
1214 // destroyConstant - Remove the constant from the constant table...
1216 void ConstantArray::destroyConstant() {
1217 ArrayConstants->remove(this);
1218 destroyConstantImpl();
1221 /// ConstantArray::get(const string&) - Return an array that is initialized to
1222 /// contain the specified string. If length is zero then a null terminator is
1223 /// added to the specified string so that it may be used in a natural way.
1224 /// Otherwise, the length parameter specifies how much of the string to use
1225 /// and it won't be null terminated.
1227 Constant *ConstantArray::get(const std::string &Str, bool AddNull) {
1228 std::vector<Constant*> ElementVals;
1229 for (unsigned i = 0; i < Str.length(); ++i)
1230 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, Str[i]));
1232 // Add a null terminator to the string...
1234 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, 0));
1237 ArrayType *ATy = ArrayType::get(Type::Int8Ty, ElementVals.size());
1238 return ConstantArray::get(ATy, ElementVals);
1241 /// isString - This method returns true if the array is an array of i8, and
1242 /// if the elements of the array are all ConstantInt's.
1243 bool ConstantArray::isString() const {
1244 // Check the element type for i8...
1245 if (getType()->getElementType() != Type::Int8Ty)
1247 // Check the elements to make sure they are all integers, not constant
1249 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1250 if (!isa<ConstantInt>(getOperand(i)))
1255 /// isCString - This method returns true if the array is a string (see
1256 /// isString) and it ends in a null byte \0 and does not contains any other
1257 /// null bytes except its terminator.
1258 bool ConstantArray::isCString() const {
1259 // Check the element type for i8...
1260 if (getType()->getElementType() != Type::Int8Ty)
1262 Constant *Zero = Constant::getNullValue(getOperand(0)->getType());
1263 // Last element must be a null.
1264 if (getOperand(getNumOperands()-1) != Zero)
1266 // Other elements must be non-null integers.
1267 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1268 if (!isa<ConstantInt>(getOperand(i)))
1270 if (getOperand(i) == Zero)
1277 // getAsString - If the sub-element type of this array is i8
1278 // then this method converts the array to an std::string and returns it.
1279 // Otherwise, it asserts out.
1281 std::string ConstantArray::getAsString() const {
1282 assert(isString() && "Not a string!");
1284 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1285 Result += (char)cast<ConstantInt>(getOperand(i))->getZExtValue();
1290 //---- ConstantStruct::get() implementation...
1295 struct ConvertConstantType<ConstantStruct, StructType> {
1296 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1297 // Make everyone now use a constant of the new type...
1298 std::vector<Constant*> C;
1299 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1300 C.push_back(cast<Constant>(OldC->getOperand(i)));
1301 Constant *New = ConstantStruct::get(NewTy, C);
1302 assert(New != OldC && "Didn't replace constant??");
1304 OldC->uncheckedReplaceAllUsesWith(New);
1305 OldC->destroyConstant(); // This constant is now dead, destroy it.
1310 typedef ValueMap<std::vector<Constant*>, StructType,
1311 ConstantStruct, true /*largekey*/> StructConstantsTy;
1312 static ManagedStatic<StructConstantsTy> StructConstants;
1314 static std::vector<Constant*> getValType(ConstantStruct *CS) {
1315 std::vector<Constant*> Elements;
1316 Elements.reserve(CS->getNumOperands());
1317 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1318 Elements.push_back(cast<Constant>(CS->getOperand(i)));
1322 Constant *ConstantStruct::get(const StructType *Ty,
1323 const std::vector<Constant*> &V) {
1324 // Create a ConstantAggregateZero value if all elements are zeros...
1325 for (unsigned i = 0, e = V.size(); i != e; ++i)
1326 if (!V[i]->isNullValue())
1327 return StructConstants->getOrCreate(Ty, V);
1329 return ConstantAggregateZero::get(Ty);
1332 Constant *ConstantStruct::get(const std::vector<Constant*> &V, bool packed) {
1333 std::vector<const Type*> StructEls;
1334 StructEls.reserve(V.size());
1335 for (unsigned i = 0, e = V.size(); i != e; ++i)
1336 StructEls.push_back(V[i]->getType());
1337 return get(StructType::get(StructEls, packed), V);
1340 // destroyConstant - Remove the constant from the constant table...
1342 void ConstantStruct::destroyConstant() {
1343 StructConstants->remove(this);
1344 destroyConstantImpl();
1347 //---- ConstantVector::get() implementation...
1351 struct ConvertConstantType<ConstantVector, VectorType> {
1352 static void convert(ConstantVector *OldC, const VectorType *NewTy) {
1353 // Make everyone now use a constant of the new type...
1354 std::vector<Constant*> C;
1355 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1356 C.push_back(cast<Constant>(OldC->getOperand(i)));
1357 Constant *New = ConstantVector::get(NewTy, C);
1358 assert(New != OldC && "Didn't replace constant??");
1359 OldC->uncheckedReplaceAllUsesWith(New);
1360 OldC->destroyConstant(); // This constant is now dead, destroy it.
1365 static std::vector<Constant*> getValType(ConstantVector *CP) {
1366 std::vector<Constant*> Elements;
1367 Elements.reserve(CP->getNumOperands());
1368 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1369 Elements.push_back(CP->getOperand(i));
1373 static ManagedStatic<ValueMap<std::vector<Constant*>, VectorType,
1374 ConstantVector> > VectorConstants;
1376 Constant *ConstantVector::get(const VectorType *Ty,
1377 const std::vector<Constant*> &V) {
1378 // If this is an all-zero vector, return a ConstantAggregateZero object
1381 if (!C->isNullValue())
1382 return VectorConstants->getOrCreate(Ty, V);
1383 for (unsigned i = 1, e = V.size(); i != e; ++i)
1385 return VectorConstants->getOrCreate(Ty, V);
1387 return ConstantAggregateZero::get(Ty);
1390 Constant *ConstantVector::get(const std::vector<Constant*> &V) {
1391 assert(!V.empty() && "Cannot infer type if V is empty");
1392 return get(VectorType::get(V.front()->getType(),V.size()), V);
1395 // destroyConstant - Remove the constant from the constant table...
1397 void ConstantVector::destroyConstant() {
1398 VectorConstants->remove(this);
1399 destroyConstantImpl();
1402 /// This function will return true iff every element in this vector constant
1403 /// is set to all ones.
1404 /// @returns true iff this constant's emements are all set to all ones.
1405 /// @brief Determine if the value is all ones.
1406 bool ConstantVector::isAllOnesValue() const {
1407 // Check out first element.
1408 const Constant *Elt = getOperand(0);
1409 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1410 if (!CI || !CI->isAllOnesValue()) return false;
1411 // Then make sure all remaining elements point to the same value.
1412 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1413 if (getOperand(I) != Elt) return false;
1418 /// getSplatValue - If this is a splat constant, where all of the
1419 /// elements have the same value, return that value. Otherwise return null.
1420 Constant *ConstantVector::getSplatValue() {
1421 // Check out first element.
1422 Constant *Elt = getOperand(0);
1423 // Then make sure all remaining elements point to the same value.
1424 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1425 if (getOperand(I) != Elt) return 0;
1429 //---- ConstantPointerNull::get() implementation...
1433 // ConstantPointerNull does not take extra "value" argument...
1434 template<class ValType>
1435 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1436 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1437 return new ConstantPointerNull(Ty);
1442 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1443 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1444 // Make everyone now use a constant of the new type...
1445 Constant *New = ConstantPointerNull::get(NewTy);
1446 assert(New != OldC && "Didn't replace constant??");
1447 OldC->uncheckedReplaceAllUsesWith(New);
1448 OldC->destroyConstant(); // This constant is now dead, destroy it.
1453 static ManagedStatic<ValueMap<char, PointerType,
1454 ConstantPointerNull> > NullPtrConstants;
1456 static char getValType(ConstantPointerNull *) {
1461 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1462 return NullPtrConstants->getOrCreate(Ty, 0);
1465 // destroyConstant - Remove the constant from the constant table...
1467 void ConstantPointerNull::destroyConstant() {
1468 NullPtrConstants->remove(this);
1469 destroyConstantImpl();
1473 //---- UndefValue::get() implementation...
1477 // UndefValue does not take extra "value" argument...
1478 template<class ValType>
1479 struct ConstantCreator<UndefValue, Type, ValType> {
1480 static UndefValue *create(const Type *Ty, const ValType &V) {
1481 return new UndefValue(Ty);
1486 struct ConvertConstantType<UndefValue, Type> {
1487 static void convert(UndefValue *OldC, const Type *NewTy) {
1488 // Make everyone now use a constant of the new type.
1489 Constant *New = UndefValue::get(NewTy);
1490 assert(New != OldC && "Didn't replace constant??");
1491 OldC->uncheckedReplaceAllUsesWith(New);
1492 OldC->destroyConstant(); // This constant is now dead, destroy it.
1497 static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
1499 static char getValType(UndefValue *) {
1504 UndefValue *UndefValue::get(const Type *Ty) {
1505 return UndefValueConstants->getOrCreate(Ty, 0);
1508 // destroyConstant - Remove the constant from the constant table.
1510 void UndefValue::destroyConstant() {
1511 UndefValueConstants->remove(this);
1512 destroyConstantImpl();
1516 //---- ConstantExpr::get() implementations...
1521 struct ExprMapKeyType {
1522 explicit ExprMapKeyType(unsigned opc, std::vector<Constant*> ops,
1523 unsigned short pred = 0) : opcode(opc), predicate(pred), operands(ops) { }
1526 std::vector<Constant*> operands;
1527 bool operator==(const ExprMapKeyType& that) const {
1528 return this->opcode == that.opcode &&
1529 this->predicate == that.predicate &&
1530 this->operands == that.operands;
1532 bool operator<(const ExprMapKeyType & that) const {
1533 return this->opcode < that.opcode ||
1534 (this->opcode == that.opcode && this->predicate < that.predicate) ||
1535 (this->opcode == that.opcode && this->predicate == that.predicate &&
1536 this->operands < that.operands);
1539 bool operator!=(const ExprMapKeyType& that) const {
1540 return !(*this == that);
1548 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1549 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1550 unsigned short pred = 0) {
1551 if (Instruction::isCast(V.opcode))
1552 return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1553 if ((V.opcode >= Instruction::BinaryOpsBegin &&
1554 V.opcode < Instruction::BinaryOpsEnd))
1555 return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1556 if (V.opcode == Instruction::Select)
1557 return new SelectConstantExpr(V.operands[0], V.operands[1],
1559 if (V.opcode == Instruction::ExtractElement)
1560 return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1561 if (V.opcode == Instruction::InsertElement)
1562 return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1564 if (V.opcode == Instruction::ShuffleVector)
1565 return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1567 if (V.opcode == Instruction::GetElementPtr) {
1568 std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
1569 return GetElementPtrConstantExpr::Create(V.operands[0], IdxList, Ty);
1572 // The compare instructions are weird. We have to encode the predicate
1573 // value and it is combined with the instruction opcode by multiplying
1574 // the opcode by one hundred. We must decode this to get the predicate.
1575 if (V.opcode == Instruction::ICmp)
1576 return new CompareConstantExpr(Ty, Instruction::ICmp, V.predicate,
1577 V.operands[0], V.operands[1]);
1578 if (V.opcode == Instruction::FCmp)
1579 return new CompareConstantExpr(Ty, Instruction::FCmp, V.predicate,
1580 V.operands[0], V.operands[1]);
1581 if (V.opcode == Instruction::VICmp)
1582 return new CompareConstantExpr(Ty, Instruction::VICmp, V.predicate,
1583 V.operands[0], V.operands[1]);
1584 if (V.opcode == Instruction::VFCmp)
1585 return new CompareConstantExpr(Ty, Instruction::VFCmp, V.predicate,
1586 V.operands[0], V.operands[1]);
1587 assert(0 && "Invalid ConstantExpr!");
1593 struct ConvertConstantType<ConstantExpr, Type> {
1594 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1596 switch (OldC->getOpcode()) {
1597 case Instruction::Trunc:
1598 case Instruction::ZExt:
1599 case Instruction::SExt:
1600 case Instruction::FPTrunc:
1601 case Instruction::FPExt:
1602 case Instruction::UIToFP:
1603 case Instruction::SIToFP:
1604 case Instruction::FPToUI:
1605 case Instruction::FPToSI:
1606 case Instruction::PtrToInt:
1607 case Instruction::IntToPtr:
1608 case Instruction::BitCast:
1609 New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0),
1612 case Instruction::Select:
1613 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1614 OldC->getOperand(1),
1615 OldC->getOperand(2));
1618 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1619 OldC->getOpcode() < Instruction::BinaryOpsEnd);
1620 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1621 OldC->getOperand(1));
1623 case Instruction::GetElementPtr:
1624 // Make everyone now use a constant of the new type...
1625 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1626 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0),
1627 &Idx[0], Idx.size());
1631 assert(New != OldC && "Didn't replace constant??");
1632 OldC->uncheckedReplaceAllUsesWith(New);
1633 OldC->destroyConstant(); // This constant is now dead, destroy it.
1636 } // end namespace llvm
1639 static ExprMapKeyType getValType(ConstantExpr *CE) {
1640 std::vector<Constant*> Operands;
1641 Operands.reserve(CE->getNumOperands());
1642 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1643 Operands.push_back(cast<Constant>(CE->getOperand(i)));
1644 return ExprMapKeyType(CE->getOpcode(), Operands,
1645 CE->isCompare() ? CE->getPredicate() : 0);
1648 static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1649 ConstantExpr> > ExprConstants;
1651 /// This is a utility function to handle folding of casts and lookup of the
1652 /// cast in the ExprConstants map. It is used by the various get* methods below.
1653 static inline Constant *getFoldedCast(
1654 Instruction::CastOps opc, Constant *C, const Type *Ty) {
1655 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1656 // Fold a few common cases
1657 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1660 // Look up the constant in the table first to ensure uniqueness
1661 std::vector<Constant*> argVec(1, C);
1662 ExprMapKeyType Key(opc, argVec);
1663 return ExprConstants->getOrCreate(Ty, Key);
1666 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1667 Instruction::CastOps opc = Instruction::CastOps(oc);
1668 assert(Instruction::isCast(opc) && "opcode out of range");
1669 assert(C && Ty && "Null arguments to getCast");
1670 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1674 assert(0 && "Invalid cast opcode");
1676 case Instruction::Trunc: return getTrunc(C, Ty);
1677 case Instruction::ZExt: return getZExt(C, Ty);
1678 case Instruction::SExt: return getSExt(C, Ty);
1679 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1680 case Instruction::FPExt: return getFPExtend(C, Ty);
1681 case Instruction::UIToFP: return getUIToFP(C, Ty);
1682 case Instruction::SIToFP: return getSIToFP(C, Ty);
1683 case Instruction::FPToUI: return getFPToUI(C, Ty);
1684 case Instruction::FPToSI: return getFPToSI(C, Ty);
1685 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1686 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1687 case Instruction::BitCast: return getBitCast(C, Ty);
1692 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1693 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1694 return getCast(Instruction::BitCast, C, Ty);
1695 return getCast(Instruction::ZExt, C, Ty);
1698 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1699 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1700 return getCast(Instruction::BitCast, C, Ty);
1701 return getCast(Instruction::SExt, C, Ty);
1704 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1705 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1706 return getCast(Instruction::BitCast, C, Ty);
1707 return getCast(Instruction::Trunc, C, Ty);
1710 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1711 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1712 assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
1714 if (Ty->isInteger())
1715 return getCast(Instruction::PtrToInt, S, Ty);
1716 return getCast(Instruction::BitCast, S, Ty);
1719 Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
1721 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1722 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1723 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1724 Instruction::CastOps opcode =
1725 (SrcBits == DstBits ? Instruction::BitCast :
1726 (SrcBits > DstBits ? Instruction::Trunc :
1727 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1728 return getCast(opcode, C, Ty);
1731 Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1732 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1734 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1735 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1736 if (SrcBits == DstBits)
1737 return C; // Avoid a useless cast
1738 Instruction::CastOps opcode =
1739 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1740 return getCast(opcode, C, Ty);
1743 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
1744 assert(C->getType()->isInteger() && "Trunc operand must be integer");
1745 assert(Ty->isInteger() && "Trunc produces only integral");
1746 assert(C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1747 "SrcTy must be larger than DestTy for Trunc!");
1749 return getFoldedCast(Instruction::Trunc, C, Ty);
1752 Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
1753 assert(C->getType()->isInteger() && "SEXt operand must be integral");
1754 assert(Ty->isInteger() && "SExt produces only integer");
1755 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1756 "SrcTy must be smaller than DestTy for SExt!");
1758 return getFoldedCast(Instruction::SExt, C, Ty);
1761 Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
1762 assert(C->getType()->isInteger() && "ZEXt operand must be integral");
1763 assert(Ty->isInteger() && "ZExt produces only integer");
1764 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1765 "SrcTy must be smaller than DestTy for ZExt!");
1767 return getFoldedCast(Instruction::ZExt, C, Ty);
1770 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1771 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1772 C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1773 "This is an illegal floating point truncation!");
1774 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1777 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1778 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1779 C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1780 "This is an illegal floating point extension!");
1781 return getFoldedCast(Instruction::FPExt, C, Ty);
1784 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
1785 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1786 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1787 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1788 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1789 "This is an illegal uint to floating point cast!");
1790 return getFoldedCast(Instruction::UIToFP, C, Ty);
1793 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
1794 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1795 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1796 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1797 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1798 "This is an illegal sint to floating point cast!");
1799 return getFoldedCast(Instruction::SIToFP, C, Ty);
1802 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
1803 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1804 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1805 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1806 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1807 "This is an illegal floating point to uint cast!");
1808 return getFoldedCast(Instruction::FPToUI, C, Ty);
1811 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
1812 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1813 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1814 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1815 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1816 "This is an illegal floating point to sint cast!");
1817 return getFoldedCast(Instruction::FPToSI, C, Ty);
1820 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1821 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
1822 assert(DstTy->isInteger() && "PtrToInt destination must be integral");
1823 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1826 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
1827 assert(C->getType()->isInteger() && "IntToPtr source must be integral");
1828 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
1829 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1832 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1833 // BitCast implies a no-op cast of type only. No bits change. However, you
1834 // can't cast pointers to anything but pointers.
1835 const Type *SrcTy = C->getType();
1836 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
1837 "BitCast cannot cast pointer to non-pointer and vice versa");
1839 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
1840 // or nonptr->ptr). For all the other types, the cast is okay if source and
1841 // destination bit widths are identical.
1842 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1843 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
1844 assert(SrcBitSize == DstBitSize && "BitCast requies types of same width");
1845 return getFoldedCast(Instruction::BitCast, C, DstTy);
1848 Constant *ConstantExpr::getSizeOf(const Type *Ty) {
1849 // sizeof is implemented as: (i64) gep (Ty*)null, 1
1850 Constant *GEPIdx = ConstantInt::get(Type::Int32Ty, 1);
1852 getGetElementPtr(getNullValue(PointerType::getUnqual(Ty)), &GEPIdx, 1);
1853 return getCast(Instruction::PtrToInt, GEP, Type::Int64Ty);
1856 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1857 Constant *C1, Constant *C2) {
1858 // Check the operands for consistency first
1859 assert(Opcode >= Instruction::BinaryOpsBegin &&
1860 Opcode < Instruction::BinaryOpsEnd &&
1861 "Invalid opcode in binary constant expression");
1862 assert(C1->getType() == C2->getType() &&
1863 "Operand types in binary constant expression should match");
1865 if (ReqTy == C1->getType() || ReqTy == Type::Int1Ty)
1866 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1867 return FC; // Fold a few common cases...
1869 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1870 ExprMapKeyType Key(Opcode, argVec);
1871 return ExprConstants->getOrCreate(ReqTy, Key);
1874 Constant *ConstantExpr::getCompareTy(unsigned short predicate,
1875 Constant *C1, Constant *C2) {
1876 switch (predicate) {
1877 default: assert(0 && "Invalid CmpInst predicate");
1878 case FCmpInst::FCMP_FALSE: case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_OGT:
1879 case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OLE:
1880 case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_ORD: case FCmpInst::FCMP_UNO:
1881 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UGT: case FCmpInst::FCMP_UGE:
1882 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_ULE: case FCmpInst::FCMP_UNE:
1883 case FCmpInst::FCMP_TRUE:
1884 return getFCmp(predicate, C1, C2);
1885 case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGT:
1886 case ICmpInst::ICMP_UGE: case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE:
1887 case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_SGE: case ICmpInst::ICMP_SLT:
1888 case ICmpInst::ICMP_SLE:
1889 return getICmp(predicate, C1, C2);
1893 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
1896 case Instruction::Add:
1897 case Instruction::Sub:
1898 case Instruction::Mul:
1899 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1900 assert((C1->getType()->isInteger() || C1->getType()->isFloatingPoint() ||
1901 isa<VectorType>(C1->getType())) &&
1902 "Tried to create an arithmetic operation on a non-arithmetic type!");
1904 case Instruction::UDiv:
1905 case Instruction::SDiv:
1906 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1907 assert((C1->getType()->isInteger() || (isa<VectorType>(C1->getType()) &&
1908 cast<VectorType>(C1->getType())->getElementType()->isInteger())) &&
1909 "Tried to create an arithmetic operation on a non-arithmetic type!");
1911 case Instruction::FDiv:
1912 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1913 assert((C1->getType()->isFloatingPoint() || (isa<VectorType>(C1->getType())
1914 && cast<VectorType>(C1->getType())->getElementType()->isFloatingPoint()))
1915 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1917 case Instruction::URem:
1918 case Instruction::SRem:
1919 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1920 assert((C1->getType()->isInteger() || (isa<VectorType>(C1->getType()) &&
1921 cast<VectorType>(C1->getType())->getElementType()->isInteger())) &&
1922 "Tried to create an arithmetic operation on a non-arithmetic type!");
1924 case Instruction::FRem:
1925 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1926 assert((C1->getType()->isFloatingPoint() || (isa<VectorType>(C1->getType())
1927 && cast<VectorType>(C1->getType())->getElementType()->isFloatingPoint()))
1928 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1930 case Instruction::And:
1931 case Instruction::Or:
1932 case Instruction::Xor:
1933 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1934 assert((C1->getType()->isInteger() || isa<VectorType>(C1->getType())) &&
1935 "Tried to create a logical operation on a non-integral type!");
1937 case Instruction::Shl:
1938 case Instruction::LShr:
1939 case Instruction::AShr:
1940 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1941 assert(C1->getType()->isInteger() &&
1942 "Tried to create a shift operation on a non-integer type!");
1949 return getTy(C1->getType(), Opcode, C1, C2);
1952 Constant *ConstantExpr::getCompare(unsigned short pred,
1953 Constant *C1, Constant *C2) {
1954 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1955 return getCompareTy(pred, C1, C2);
1958 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1959 Constant *V1, Constant *V2) {
1960 assert(C->getType() == Type::Int1Ty && "Select condition must be i1!");
1961 assert(V1->getType() == V2->getType() && "Select value types must match!");
1962 assert(V1->getType()->isFirstClassType() && "Cannot select aggregate type!");
1964 if (ReqTy == V1->getType())
1965 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1966 return SC; // Fold common cases
1968 std::vector<Constant*> argVec(3, C);
1971 ExprMapKeyType Key(Instruction::Select, argVec);
1972 return ExprConstants->getOrCreate(ReqTy, Key);
1975 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1978 assert(GetElementPtrInst::getIndexedType(C->getType(),
1979 Idxs, Idxs+NumIdx, true)
1980 && "GEP indices invalid!");
1982 if (Constant *FC = ConstantFoldGetElementPtr(C, (Constant**)Idxs, NumIdx))
1983 return FC; // Fold a few common cases...
1985 assert(isa<PointerType>(C->getType()) &&
1986 "Non-pointer type for constant GetElementPtr expression");
1987 // Look up the constant in the table first to ensure uniqueness
1988 std::vector<Constant*> ArgVec;
1989 ArgVec.reserve(NumIdx+1);
1990 ArgVec.push_back(C);
1991 for (unsigned i = 0; i != NumIdx; ++i)
1992 ArgVec.push_back(cast<Constant>(Idxs[i]));
1993 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
1994 return ExprConstants->getOrCreate(ReqTy, Key);
1997 Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
1999 // Get the result type of the getelementptr!
2001 GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx, true);
2002 assert(Ty && "GEP indices invalid!");
2003 unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
2004 return getGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx);
2007 Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
2009 return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
2014 ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2015 assert(LHS->getType() == RHS->getType());
2016 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
2017 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
2019 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
2020 return FC; // Fold a few common cases...
2022 // Look up the constant in the table first to ensure uniqueness
2023 std::vector<Constant*> ArgVec;
2024 ArgVec.push_back(LHS);
2025 ArgVec.push_back(RHS);
2026 // Get the key type with both the opcode and predicate
2027 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
2028 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
2032 ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2033 assert(LHS->getType() == RHS->getType());
2034 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
2036 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
2037 return FC; // Fold a few common cases...
2039 // Look up the constant in the table first to ensure uniqueness
2040 std::vector<Constant*> ArgVec;
2041 ArgVec.push_back(LHS);
2042 ArgVec.push_back(RHS);
2043 // Get the key type with both the opcode and predicate
2044 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
2045 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
2049 ConstantExpr::getVICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2050 assert(isa<VectorType>(LHS->getType()) &&
2051 "Tried to create vicmp operation on non-vector type!");
2052 assert(LHS->getType() == RHS->getType());
2053 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
2054 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid VICmp Predicate");
2056 const VectorType *VTy = cast<VectorType>(LHS->getType());
2057 const Type *EltTy = VTy->getElementType();
2058 unsigned NumElts = VTy->getNumElements();
2060 SmallVector<Constant *, 8> Elts;
2061 for (unsigned i = 0; i != NumElts; ++i) {
2062 Constant *FC = ConstantFoldCompareInstruction(pred, LHS->getOperand(i),
2063 RHS->getOperand(i));
2065 uint64_t Val = cast<ConstantInt>(FC)->getZExtValue();
2067 Elts.push_back(ConstantInt::getAllOnesValue(EltTy));
2069 Elts.push_back(ConstantInt::get(EltTy, 0ULL));
2072 if (Elts.size() == NumElts)
2073 return ConstantVector::get(&Elts[0], Elts.size());
2075 // Look up the constant in the table first to ensure uniqueness
2076 std::vector<Constant*> ArgVec;
2077 ArgVec.push_back(LHS);
2078 ArgVec.push_back(RHS);
2079 // Get the key type with both the opcode and predicate
2080 const ExprMapKeyType Key(Instruction::VICmp, ArgVec, pred);
2081 return ExprConstants->getOrCreate(LHS->getType(), Key);
2085 ConstantExpr::getVFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2086 assert(isa<VectorType>(LHS->getType()) &&
2087 "Tried to create vfcmp operation on non-vector type!");
2088 assert(LHS->getType() == RHS->getType());
2089 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid VFCmp Predicate");
2091 const VectorType *VTy = cast<VectorType>(LHS->getType());
2092 unsigned NumElts = VTy->getNumElements();
2093 const Type *EltTy = VTy->getElementType();
2094 const Type *REltTy = IntegerType::get(EltTy->getPrimitiveSizeInBits());
2095 const Type *ResultTy = VectorType::get(REltTy, NumElts);
2097 SmallVector<Constant *, 8> Elts;
2098 for (unsigned i = 0; i != NumElts; ++i) {
2099 Constant *FC = ConstantFoldCompareInstruction(pred, LHS->getOperand(i),
2100 RHS->getOperand(i));
2102 uint64_t Val = cast<ConstantInt>(FC)->getZExtValue();
2104 Elts.push_back(ConstantInt::getAllOnesValue(REltTy));
2106 Elts.push_back(ConstantInt::get(REltTy, 0ULL));
2109 if (Elts.size() == NumElts)
2110 return ConstantVector::get(&Elts[0], Elts.size());
2112 // Look up the constant in the table first to ensure uniqueness
2113 std::vector<Constant*> ArgVec;
2114 ArgVec.push_back(LHS);
2115 ArgVec.push_back(RHS);
2116 // Get the key type with both the opcode and predicate
2117 const ExprMapKeyType Key(Instruction::VFCmp, ArgVec, pred);
2118 return ExprConstants->getOrCreate(ResultTy, Key);
2121 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
2123 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
2124 return FC; // Fold a few common cases...
2125 // Look up the constant in the table first to ensure uniqueness
2126 std::vector<Constant*> ArgVec(1, Val);
2127 ArgVec.push_back(Idx);
2128 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
2129 return ExprConstants->getOrCreate(ReqTy, Key);
2132 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
2133 assert(isa<VectorType>(Val->getType()) &&
2134 "Tried to create extractelement operation on non-vector type!");
2135 assert(Idx->getType() == Type::Int32Ty &&
2136 "Extractelement index must be i32 type!");
2137 return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
2141 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
2142 Constant *Elt, Constant *Idx) {
2143 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
2144 return FC; // Fold a few common cases...
2145 // Look up the constant in the table first to ensure uniqueness
2146 std::vector<Constant*> ArgVec(1, Val);
2147 ArgVec.push_back(Elt);
2148 ArgVec.push_back(Idx);
2149 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
2150 return ExprConstants->getOrCreate(ReqTy, Key);
2153 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
2155 assert(isa<VectorType>(Val->getType()) &&
2156 "Tried to create insertelement operation on non-vector type!");
2157 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
2158 && "Insertelement types must match!");
2159 assert(Idx->getType() == Type::Int32Ty &&
2160 "Insertelement index must be i32 type!");
2161 return getInsertElementTy(cast<VectorType>(Val->getType())->getElementType(),
2165 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
2166 Constant *V2, Constant *Mask) {
2167 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
2168 return FC; // Fold a few common cases...
2169 // Look up the constant in the table first to ensure uniqueness
2170 std::vector<Constant*> ArgVec(1, V1);
2171 ArgVec.push_back(V2);
2172 ArgVec.push_back(Mask);
2173 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
2174 return ExprConstants->getOrCreate(ReqTy, Key);
2177 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
2179 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
2180 "Invalid shuffle vector constant expr operands!");
2181 return getShuffleVectorTy(V1->getType(), V1, V2, Mask);
2184 Constant *ConstantExpr::getZeroValueForNegationExpr(const Type *Ty) {
2185 if (const VectorType *PTy = dyn_cast<VectorType>(Ty))
2186 if (PTy->getElementType()->isFloatingPoint()) {
2187 std::vector<Constant*> zeros(PTy->getNumElements(),
2188 ConstantFP::getNegativeZero(PTy->getElementType()));
2189 return ConstantVector::get(PTy, zeros);
2192 if (Ty->isFloatingPoint())
2193 return ConstantFP::getNegativeZero(Ty);
2195 return Constant::getNullValue(Ty);
2198 // destroyConstant - Remove the constant from the constant table...
2200 void ConstantExpr::destroyConstant() {
2201 ExprConstants->remove(this);
2202 destroyConstantImpl();
2205 const char *ConstantExpr::getOpcodeName() const {
2206 return Instruction::getOpcodeName(getOpcode());
2209 //===----------------------------------------------------------------------===//
2210 // replaceUsesOfWithOnConstant implementations
2212 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
2213 /// 'From' to be uses of 'To'. This must update the uniquing data structures
2216 /// Note that we intentionally replace all uses of From with To here. Consider
2217 /// a large array that uses 'From' 1000 times. By handling this case all here,
2218 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
2219 /// single invocation handles all 1000 uses. Handling them one at a time would
2220 /// work, but would be really slow because it would have to unique each updated
2222 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
2224 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2225 Constant *ToC = cast<Constant>(To);
2227 std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
2228 Lookup.first.first = getType();
2229 Lookup.second = this;
2231 std::vector<Constant*> &Values = Lookup.first.second;
2232 Values.reserve(getNumOperands()); // Build replacement array.
2234 // Fill values with the modified operands of the constant array. Also,
2235 // compute whether this turns into an all-zeros array.
2236 bool isAllZeros = false;
2237 unsigned NumUpdated = 0;
2238 if (!ToC->isNullValue()) {
2239 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2240 Constant *Val = cast<Constant>(O->get());
2245 Values.push_back(Val);
2249 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2250 Constant *Val = cast<Constant>(O->get());
2255 Values.push_back(Val);
2256 if (isAllZeros) isAllZeros = Val->isNullValue();
2260 Constant *Replacement = 0;
2262 Replacement = ConstantAggregateZero::get(getType());
2264 // Check to see if we have this array type already.
2266 ArrayConstantsTy::MapTy::iterator I =
2267 ArrayConstants->InsertOrGetItem(Lookup, Exists);
2270 Replacement = I->second;
2272 // Okay, the new shape doesn't exist in the system yet. Instead of
2273 // creating a new constant array, inserting it, replaceallusesof'ing the
2274 // old with the new, then deleting the old... just update the current one
2276 ArrayConstants->MoveConstantToNewSlot(this, I);
2278 // Update to the new value. Optimize for the case when we have a single
2279 // operand that we're changing, but handle bulk updates efficiently.
2280 if (NumUpdated == 1) {
2281 unsigned OperandToUpdate = U-OperandList;
2282 assert(getOperand(OperandToUpdate) == From &&
2283 "ReplaceAllUsesWith broken!");
2284 setOperand(OperandToUpdate, ToC);
2286 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2287 if (getOperand(i) == From)
2294 // Otherwise, I do need to replace this with an existing value.
2295 assert(Replacement != this && "I didn't contain From!");
2297 // Everyone using this now uses the replacement.
2298 uncheckedReplaceAllUsesWith(Replacement);
2300 // Delete the old constant!
2304 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
2306 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2307 Constant *ToC = cast<Constant>(To);
2309 unsigned OperandToUpdate = U-OperandList;
2310 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2312 std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
2313 Lookup.first.first = getType();
2314 Lookup.second = this;
2315 std::vector<Constant*> &Values = Lookup.first.second;
2316 Values.reserve(getNumOperands()); // Build replacement struct.
2319 // Fill values with the modified operands of the constant struct. Also,
2320 // compute whether this turns into an all-zeros struct.
2321 bool isAllZeros = false;
2322 if (!ToC->isNullValue()) {
2323 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
2324 Values.push_back(cast<Constant>(O->get()));
2327 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2328 Constant *Val = cast<Constant>(O->get());
2329 Values.push_back(Val);
2330 if (isAllZeros) isAllZeros = Val->isNullValue();
2333 Values[OperandToUpdate] = ToC;
2335 Constant *Replacement = 0;
2337 Replacement = ConstantAggregateZero::get(getType());
2339 // Check to see if we have this array type already.
2341 StructConstantsTy::MapTy::iterator I =
2342 StructConstants->InsertOrGetItem(Lookup, Exists);
2345 Replacement = I->second;
2347 // Okay, the new shape doesn't exist in the system yet. Instead of
2348 // creating a new constant struct, inserting it, replaceallusesof'ing the
2349 // old with the new, then deleting the old... just update the current one
2351 StructConstants->MoveConstantToNewSlot(this, I);
2353 // Update to the new value.
2354 setOperand(OperandToUpdate, ToC);
2359 assert(Replacement != this && "I didn't contain From!");
2361 // Everyone using this now uses the replacement.
2362 uncheckedReplaceAllUsesWith(Replacement);
2364 // Delete the old constant!
2368 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
2370 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2372 std::vector<Constant*> Values;
2373 Values.reserve(getNumOperands()); // Build replacement array...
2374 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2375 Constant *Val = getOperand(i);
2376 if (Val == From) Val = cast<Constant>(To);
2377 Values.push_back(Val);
2380 Constant *Replacement = ConstantVector::get(getType(), Values);
2381 assert(Replacement != this && "I didn't contain From!");
2383 // Everyone using this now uses the replacement.
2384 uncheckedReplaceAllUsesWith(Replacement);
2386 // Delete the old constant!
2390 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2392 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2393 Constant *To = cast<Constant>(ToV);
2395 Constant *Replacement = 0;
2396 if (getOpcode() == Instruction::GetElementPtr) {
2397 SmallVector<Constant*, 8> Indices;
2398 Constant *Pointer = getOperand(0);
2399 Indices.reserve(getNumOperands()-1);
2400 if (Pointer == From) Pointer = To;
2402 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2403 Constant *Val = getOperand(i);
2404 if (Val == From) Val = To;
2405 Indices.push_back(Val);
2407 Replacement = ConstantExpr::getGetElementPtr(Pointer,
2408 &Indices[0], Indices.size());
2409 } else if (isCast()) {
2410 assert(getOperand(0) == From && "Cast only has one use!");
2411 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
2412 } else if (getOpcode() == Instruction::Select) {
2413 Constant *C1 = getOperand(0);
2414 Constant *C2 = getOperand(1);
2415 Constant *C3 = getOperand(2);
2416 if (C1 == From) C1 = To;
2417 if (C2 == From) C2 = To;
2418 if (C3 == From) C3 = To;
2419 Replacement = ConstantExpr::getSelect(C1, C2, C3);
2420 } else if (getOpcode() == Instruction::ExtractElement) {
2421 Constant *C1 = getOperand(0);
2422 Constant *C2 = getOperand(1);
2423 if (C1 == From) C1 = To;
2424 if (C2 == From) C2 = To;
2425 Replacement = ConstantExpr::getExtractElement(C1, C2);
2426 } else if (getOpcode() == Instruction::InsertElement) {
2427 Constant *C1 = getOperand(0);
2428 Constant *C2 = getOperand(1);
2429 Constant *C3 = getOperand(1);
2430 if (C1 == From) C1 = To;
2431 if (C2 == From) C2 = To;
2432 if (C3 == From) C3 = To;
2433 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2434 } else if (getOpcode() == Instruction::ShuffleVector) {
2435 Constant *C1 = getOperand(0);
2436 Constant *C2 = getOperand(1);
2437 Constant *C3 = getOperand(2);
2438 if (C1 == From) C1 = To;
2439 if (C2 == From) C2 = To;
2440 if (C3 == From) C3 = To;
2441 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2442 } else if (isCompare()) {
2443 Constant *C1 = getOperand(0);
2444 Constant *C2 = getOperand(1);
2445 if (C1 == From) C1 = To;
2446 if (C2 == From) C2 = To;
2447 if (getOpcode() == Instruction::ICmp)
2448 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2450 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2451 } else if (getNumOperands() == 2) {
2452 Constant *C1 = getOperand(0);
2453 Constant *C2 = getOperand(1);
2454 if (C1 == From) C1 = To;
2455 if (C2 == From) C2 = To;
2456 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2458 assert(0 && "Unknown ConstantExpr type!");
2462 assert(Replacement != this && "I didn't contain From!");
2464 // Everyone using this now uses the replacement.
2465 uncheckedReplaceAllUsesWith(Replacement);
2467 // Delete the old constant!
2472 /// getStringValue - Turn an LLVM constant pointer that eventually points to a
2473 /// global into a string value. Return an empty string if we can't do it.
2474 /// Parameter Chop determines if the result is chopped at the first null
2477 std::string Constant::getStringValue(bool Chop, unsigned Offset) {
2478 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(this)) {
2479 if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
2480 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
2481 if (Init->isString()) {
2482 std::string Result = Init->getAsString();
2483 if (Offset < Result.size()) {
2484 // If we are pointing INTO The string, erase the beginning...
2485 Result.erase(Result.begin(), Result.begin()+Offset);
2487 // Take off the null terminator, and any string fragments after it.
2489 std::string::size_type NullPos = Result.find_first_of((char)0);
2490 if (NullPos != std::string::npos)
2491 Result.erase(Result.begin()+NullPos, Result.end());
2497 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(this)) {
2498 if (CE->getOpcode() == Instruction::GetElementPtr) {
2499 // Turn a gep into the specified offset.
2500 if (CE->getNumOperands() == 3 &&
2501 cast<Constant>(CE->getOperand(1))->isNullValue() &&
2502 isa<ConstantInt>(CE->getOperand(2))) {
2503 Offset += cast<ConstantInt>(CE->getOperand(2))->getZExtValue();
2504 return CE->getOperand(0)->getStringValue(Chop, Offset);