1 //===-- Constants.cpp - Implement Constant nodes --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Constant* classes...
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Constants.h"
15 #include "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 // Static constructor to create a '0' constant of arbitrary type...
94 Constant *Constant::getNullValue(const Type *Ty) {
95 switch (Ty->getTypeID()) {
96 case Type::IntegerTyID:
97 return ConstantInt::get(Ty, 0);
99 case Type::DoubleTyID:
100 return ConstantFP::get(Ty, 0.0);
101 case Type::PointerTyID:
102 return ConstantPointerNull::get(cast<PointerType>(Ty));
103 case Type::StructTyID:
104 case Type::ArrayTyID:
105 case Type::VectorTyID:
106 return ConstantAggregateZero::get(Ty);
108 // Function, Label, or Opaque type?
109 assert(!"Cannot create a null constant of that type!");
115 // Static constructor to create an integral constant with all bits set
116 ConstantInt *ConstantInt::getAllOnesValue(const Type *Ty) {
117 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
118 return ConstantInt::get(Ty, APInt::getAllOnesValue(ITy->getBitWidth()));
122 /// @returns the value for an packed integer constant of the given type that
123 /// has all its bits set to true.
124 /// @brief Get the all ones value
125 ConstantVector *ConstantVector::getAllOnesValue(const VectorType *Ty) {
126 std::vector<Constant*> Elts;
127 Elts.resize(Ty->getNumElements(),
128 ConstantInt::getAllOnesValue(Ty->getElementType()));
129 assert(Elts[0] && "Not a packed integer type!");
130 return cast<ConstantVector>(ConstantVector::get(Elts));
134 //===----------------------------------------------------------------------===//
136 //===----------------------------------------------------------------------===//
138 ConstantInt::ConstantInt(const IntegerType *Ty, const APInt& V)
139 : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
140 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
143 ConstantInt *ConstantInt::TheTrueVal = 0;
144 ConstantInt *ConstantInt::TheFalseVal = 0;
147 void CleanupTrueFalse(void *) {
148 ConstantInt::ResetTrueFalse();
152 static ManagedCleanup<llvm::CleanupTrueFalse> TrueFalseCleanup;
154 ConstantInt *ConstantInt::CreateTrueFalseVals(bool WhichOne) {
155 assert(TheTrueVal == 0 && TheFalseVal == 0);
156 TheTrueVal = get(Type::Int1Ty, 1);
157 TheFalseVal = get(Type::Int1Ty, 0);
159 // Ensure that llvm_shutdown nulls out TheTrueVal/TheFalseVal.
160 TrueFalseCleanup.Register();
162 return WhichOne ? TheTrueVal : TheFalseVal;
167 struct DenseMapAPIntKeyInfo {
171 KeyTy(const APInt& V, const Type* Ty) : val(V), type(Ty) {}
172 KeyTy(const KeyTy& that) : val(that.val), type(that.type) {}
173 bool operator==(const KeyTy& that) const {
174 return type == that.type && this->val == that.val;
176 bool operator!=(const KeyTy& that) const {
177 return !this->operator==(that);
180 static inline KeyTy getEmptyKey() { return KeyTy(APInt(1,0), 0); }
181 static inline KeyTy getTombstoneKey() { return KeyTy(APInt(1,1), 0); }
182 static unsigned getHashValue(const KeyTy &Key) {
183 return DenseMapKeyInfo<void*>::getHashValue(Key.type) ^
184 Key.val.getHashValue();
186 static bool isPod() { return true; }
191 typedef DenseMap<DenseMapAPIntKeyInfo::KeyTy, ConstantInt*,
192 DenseMapAPIntKeyInfo> IntMapTy;
193 static ManagedStatic<IntMapTy> IntConstants;
195 ConstantInt *ConstantInt::get(const Type *Ty, int64_t V) {
196 const IntegerType *ITy = cast<IntegerType>(Ty);
197 APInt Tmp(ITy->getBitWidth(), V);
201 // Get a ConstantInt from a Type and APInt. Note that the value stored in
202 // the DenseMap as the key is a DensMapAPIntKeyInfo::KeyTy which has provided
203 // operator== and operator!= to ensure that the DenseMap doesn't attempt to
204 // compare APInt's of different widths, which would violate an APInt class
205 // invariant which generates an assertion.
206 ConstantInt *ConstantInt::get(const Type *Ty, const APInt& V) {
207 const IntegerType *ITy = cast<IntegerType>(Ty);
208 assert(ITy->getBitWidth() == V.getBitWidth() && "Invalid type for constant");
209 // get an existing value or the insertion position
210 DenseMapAPIntKeyInfo::KeyTy Key(V, Ty);
211 ConstantInt *&Slot = (*IntConstants)[Key];
212 // if it exists, return it.
215 // otherwise create a new one, insert it, and return it.
216 return Slot = new ConstantInt(ITy, V);
219 ConstantInt *ConstantInt::get(const APInt &V) {
220 return ConstantInt::get(IntegerType::get(V.getBitWidth()), V);
223 //===----------------------------------------------------------------------===//
225 //===----------------------------------------------------------------------===//
228 ConstantFP::ConstantFP(const Type *Ty, double V)
229 : Constant(Ty, ConstantFPVal, 0, 0) {
233 bool ConstantFP::isNullValue() const {
234 return DoubleToBits(Val) == 0;
237 bool ConstantFP::isExactlyValue(double V) const {
238 return DoubleToBits(V) == DoubleToBits(Val);
243 struct DenseMapInt64KeyInfo {
244 typedef std::pair<uint64_t, const Type*> KeyTy;
245 static inline KeyTy getEmptyKey() { return KeyTy(0, 0); }
246 static inline KeyTy getTombstoneKey() { return KeyTy(1, 0); }
247 static unsigned getHashValue(const KeyTy &Key) {
248 return DenseMapKeyInfo<void*>::getHashValue(Key.second) ^ Key.first;
250 static bool isPod() { return true; }
252 struct DenseMapInt32KeyInfo {
253 typedef std::pair<uint32_t, const Type*> KeyTy;
254 static inline KeyTy getEmptyKey() { return KeyTy(0, 0); }
255 static inline KeyTy getTombstoneKey() { return KeyTy(1, 0); }
256 static unsigned getHashValue(const KeyTy &Key) {
257 return DenseMapKeyInfo<void*>::getHashValue(Key.second) ^ Key.first;
259 static bool isPod() { return true; }
263 //---- ConstantFP::get() implementation...
265 typedef DenseMap<DenseMapInt32KeyInfo::KeyTy, ConstantFP*,
266 DenseMapInt32KeyInfo> FloatMapTy;
267 typedef DenseMap<DenseMapInt64KeyInfo::KeyTy, ConstantFP*,
268 DenseMapInt64KeyInfo> DoubleMapTy;
270 static ManagedStatic<FloatMapTy> FloatConstants;
271 static ManagedStatic<DoubleMapTy> DoubleConstants;
273 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
274 if (Ty == Type::FloatTy) {
275 uint32_t IntVal = FloatToBits((float)V);
277 ConstantFP *&Slot = (*FloatConstants)[std::make_pair(IntVal, Ty)];
278 if (Slot) return Slot;
279 return Slot = new ConstantFP(Ty, (float)V);
281 assert(Ty == Type::DoubleTy);
282 uint64_t IntVal = DoubleToBits(V);
283 ConstantFP *&Slot = (*DoubleConstants)[std::make_pair(IntVal, Ty)];
284 if (Slot) return Slot;
285 return Slot = new ConstantFP(Ty, V);
290 //===----------------------------------------------------------------------===//
291 // ConstantXXX Classes
292 //===----------------------------------------------------------------------===//
295 ConstantArray::ConstantArray(const ArrayType *T,
296 const std::vector<Constant*> &V)
297 : Constant(T, ConstantArrayVal, new Use[V.size()], V.size()) {
298 assert(V.size() == T->getNumElements() &&
299 "Invalid initializer vector for constant array");
300 Use *OL = OperandList;
301 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
304 assert((C->getType() == T->getElementType() ||
306 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
307 "Initializer for array element doesn't match array element type!");
312 ConstantArray::~ConstantArray() {
313 delete [] OperandList;
316 ConstantStruct::ConstantStruct(const StructType *T,
317 const std::vector<Constant*> &V)
318 : Constant(T, ConstantStructVal, new Use[V.size()], V.size()) {
319 assert(V.size() == T->getNumElements() &&
320 "Invalid initializer vector for constant structure");
321 Use *OL = OperandList;
322 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
325 assert((C->getType() == T->getElementType(I-V.begin()) ||
326 ((T->getElementType(I-V.begin())->isAbstract() ||
327 C->getType()->isAbstract()) &&
328 T->getElementType(I-V.begin())->getTypeID() ==
329 C->getType()->getTypeID())) &&
330 "Initializer for struct element doesn't match struct element type!");
335 ConstantStruct::~ConstantStruct() {
336 delete [] OperandList;
340 ConstantVector::ConstantVector(const VectorType *T,
341 const std::vector<Constant*> &V)
342 : Constant(T, ConstantVectorVal, new Use[V.size()], V.size()) {
343 Use *OL = OperandList;
344 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
347 assert((C->getType() == T->getElementType() ||
349 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
350 "Initializer for packed element doesn't match packed element type!");
355 ConstantVector::~ConstantVector() {
356 delete [] OperandList;
359 // We declare several classes private to this file, so use an anonymous
363 /// UnaryConstantExpr - This class is private to Constants.cpp, and is used
364 /// behind the scenes to implement unary constant exprs.
365 class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
368 UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
369 : ConstantExpr(Ty, Opcode, &Op, 1), Op(C, this) {}
372 /// BinaryConstantExpr - This class is private to Constants.cpp, and is used
373 /// behind the scenes to implement binary constant exprs.
374 class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
377 BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
378 : ConstantExpr(C1->getType(), Opcode, Ops, 2) {
379 Ops[0].init(C1, this);
380 Ops[1].init(C2, this);
384 /// SelectConstantExpr - This class is private to Constants.cpp, and is used
385 /// behind the scenes to implement select constant exprs.
386 class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
389 SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
390 : ConstantExpr(C2->getType(), Instruction::Select, Ops, 3) {
391 Ops[0].init(C1, this);
392 Ops[1].init(C2, this);
393 Ops[2].init(C3, this);
397 /// ExtractElementConstantExpr - This class is private to
398 /// Constants.cpp, and is used behind the scenes to implement
399 /// extractelement constant exprs.
400 class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
403 ExtractElementConstantExpr(Constant *C1, Constant *C2)
404 : ConstantExpr(cast<VectorType>(C1->getType())->getElementType(),
405 Instruction::ExtractElement, Ops, 2) {
406 Ops[0].init(C1, this);
407 Ops[1].init(C2, this);
411 /// InsertElementConstantExpr - This class is private to
412 /// Constants.cpp, and is used behind the scenes to implement
413 /// insertelement constant exprs.
414 class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
417 InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
418 : ConstantExpr(C1->getType(), Instruction::InsertElement,
420 Ops[0].init(C1, this);
421 Ops[1].init(C2, this);
422 Ops[2].init(C3, this);
426 /// ShuffleVectorConstantExpr - This class is private to
427 /// Constants.cpp, and is used behind the scenes to implement
428 /// shufflevector constant exprs.
429 class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
432 ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
433 : ConstantExpr(C1->getType(), Instruction::ShuffleVector,
435 Ops[0].init(C1, this);
436 Ops[1].init(C2, this);
437 Ops[2].init(C3, this);
441 /// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
442 /// used behind the scenes to implement getelementpr constant exprs.
443 struct VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
444 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
446 : ConstantExpr(DestTy, Instruction::GetElementPtr,
447 new Use[IdxList.size()+1], IdxList.size()+1) {
448 OperandList[0].init(C, this);
449 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
450 OperandList[i+1].init(IdxList[i], this);
452 ~GetElementPtrConstantExpr() {
453 delete [] OperandList;
457 // CompareConstantExpr - This class is private to Constants.cpp, and is used
458 // behind the scenes to implement ICmp and FCmp constant expressions. This is
459 // needed in order to store the predicate value for these instructions.
460 struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
461 unsigned short predicate;
463 CompareConstantExpr(Instruction::OtherOps opc, unsigned short pred,
464 Constant* LHS, Constant* RHS)
465 : ConstantExpr(Type::Int1Ty, opc, Ops, 2), predicate(pred) {
466 OperandList[0].init(LHS, this);
467 OperandList[1].init(RHS, this);
471 } // end anonymous namespace
474 // Utility function for determining if a ConstantExpr is a CastOp or not. This
475 // can't be inline because we don't want to #include Instruction.h into
477 bool ConstantExpr::isCast() const {
478 return Instruction::isCast(getOpcode());
481 bool ConstantExpr::isCompare() const {
482 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
485 /// ConstantExpr::get* - Return some common constants without having to
486 /// specify the full Instruction::OPCODE identifier.
488 Constant *ConstantExpr::getNeg(Constant *C) {
489 return get(Instruction::Sub,
490 ConstantExpr::getZeroValueForNegationExpr(C->getType()),
493 Constant *ConstantExpr::getNot(Constant *C) {
494 assert(isa<ConstantInt>(C) && "Cannot NOT a nonintegral type!");
495 return get(Instruction::Xor, C,
496 ConstantInt::getAllOnesValue(C->getType()));
498 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
499 return get(Instruction::Add, C1, C2);
501 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
502 return get(Instruction::Sub, C1, C2);
504 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
505 return get(Instruction::Mul, C1, C2);
507 Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2) {
508 return get(Instruction::UDiv, C1, C2);
510 Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2) {
511 return get(Instruction::SDiv, C1, C2);
513 Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
514 return get(Instruction::FDiv, C1, C2);
516 Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
517 return get(Instruction::URem, C1, C2);
519 Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
520 return get(Instruction::SRem, C1, C2);
522 Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
523 return get(Instruction::FRem, C1, C2);
525 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
526 return get(Instruction::And, C1, C2);
528 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
529 return get(Instruction::Or, C1, C2);
531 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
532 return get(Instruction::Xor, C1, C2);
534 unsigned ConstantExpr::getPredicate() const {
535 assert(getOpcode() == Instruction::FCmp || getOpcode() == Instruction::ICmp);
536 return dynamic_cast<const CompareConstantExpr*>(this)->predicate;
538 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
539 return get(Instruction::Shl, C1, C2);
541 Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2) {
542 return get(Instruction::LShr, C1, C2);
544 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2) {
545 return get(Instruction::AShr, C1, C2);
548 /// getWithOperandReplaced - Return a constant expression identical to this
549 /// one, but with the specified operand set to the specified value.
551 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
552 assert(OpNo < getNumOperands() && "Operand num is out of range!");
553 assert(Op->getType() == getOperand(OpNo)->getType() &&
554 "Replacing operand with value of different type!");
555 if (getOperand(OpNo) == Op)
556 return const_cast<ConstantExpr*>(this);
558 Constant *Op0, *Op1, *Op2;
559 switch (getOpcode()) {
560 case Instruction::Trunc:
561 case Instruction::ZExt:
562 case Instruction::SExt:
563 case Instruction::FPTrunc:
564 case Instruction::FPExt:
565 case Instruction::UIToFP:
566 case Instruction::SIToFP:
567 case Instruction::FPToUI:
568 case Instruction::FPToSI:
569 case Instruction::PtrToInt:
570 case Instruction::IntToPtr:
571 case Instruction::BitCast:
572 return ConstantExpr::getCast(getOpcode(), Op, getType());
573 case Instruction::Select:
574 Op0 = (OpNo == 0) ? Op : getOperand(0);
575 Op1 = (OpNo == 1) ? Op : getOperand(1);
576 Op2 = (OpNo == 2) ? Op : getOperand(2);
577 return ConstantExpr::getSelect(Op0, Op1, Op2);
578 case Instruction::InsertElement:
579 Op0 = (OpNo == 0) ? Op : getOperand(0);
580 Op1 = (OpNo == 1) ? Op : getOperand(1);
581 Op2 = (OpNo == 2) ? Op : getOperand(2);
582 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
583 case Instruction::ExtractElement:
584 Op0 = (OpNo == 0) ? Op : getOperand(0);
585 Op1 = (OpNo == 1) ? Op : getOperand(1);
586 return ConstantExpr::getExtractElement(Op0, Op1);
587 case Instruction::ShuffleVector:
588 Op0 = (OpNo == 0) ? Op : getOperand(0);
589 Op1 = (OpNo == 1) ? Op : getOperand(1);
590 Op2 = (OpNo == 2) ? Op : getOperand(2);
591 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
592 case Instruction::GetElementPtr: {
593 SmallVector<Constant*, 8> Ops;
594 Ops.resize(getNumOperands());
595 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
596 Ops[i] = getOperand(i);
598 return ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
600 return ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
603 assert(getNumOperands() == 2 && "Must be binary operator?");
604 Op0 = (OpNo == 0) ? Op : getOperand(0);
605 Op1 = (OpNo == 1) ? Op : getOperand(1);
606 return ConstantExpr::get(getOpcode(), Op0, Op1);
610 /// getWithOperands - This returns the current constant expression with the
611 /// operands replaced with the specified values. The specified operands must
612 /// match count and type with the existing ones.
613 Constant *ConstantExpr::
614 getWithOperands(const std::vector<Constant*> &Ops) const {
615 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
616 bool AnyChange = false;
617 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
618 assert(Ops[i]->getType() == getOperand(i)->getType() &&
619 "Operand type mismatch!");
620 AnyChange |= Ops[i] != getOperand(i);
622 if (!AnyChange) // No operands changed, return self.
623 return const_cast<ConstantExpr*>(this);
625 switch (getOpcode()) {
626 case Instruction::Trunc:
627 case Instruction::ZExt:
628 case Instruction::SExt:
629 case Instruction::FPTrunc:
630 case Instruction::FPExt:
631 case Instruction::UIToFP:
632 case Instruction::SIToFP:
633 case Instruction::FPToUI:
634 case Instruction::FPToSI:
635 case Instruction::PtrToInt:
636 case Instruction::IntToPtr:
637 case Instruction::BitCast:
638 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
639 case Instruction::Select:
640 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
641 case Instruction::InsertElement:
642 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
643 case Instruction::ExtractElement:
644 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
645 case Instruction::ShuffleVector:
646 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
647 case Instruction::GetElementPtr:
648 return ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], Ops.size()-1);
649 case Instruction::ICmp:
650 case Instruction::FCmp:
651 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
653 assert(getNumOperands() == 2 && "Must be binary operator?");
654 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
659 //===----------------------------------------------------------------------===//
660 // isValueValidForType implementations
662 bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
663 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
664 if (Ty == Type::Int1Ty)
665 return Val == 0 || Val == 1;
667 return true; // always true, has to fit in largest type
668 uint64_t Max = (1ll << NumBits) - 1;
672 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
673 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
674 if (Ty == Type::Int1Ty)
675 return Val == 0 || Val == 1 || Val == -1;
677 return true; // always true, has to fit in largest type
678 int64_t Min = -(1ll << (NumBits-1));
679 int64_t Max = (1ll << (NumBits-1)) - 1;
680 return (Val >= Min && Val <= Max);
683 bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
684 switch (Ty->getTypeID()) {
686 return false; // These can't be represented as floating point!
688 // TODO: Figure out how to test if a double can be cast to a float!
689 case Type::FloatTyID:
690 case Type::DoubleTyID:
691 return true; // This is the largest type...
695 //===----------------------------------------------------------------------===//
696 // Factory Function Implementation
698 // ConstantCreator - A class that is used to create constants by
699 // ValueMap*. This class should be partially specialized if there is
700 // something strange that needs to be done to interface to the ctor for the
704 template<class ConstantClass, class TypeClass, class ValType>
705 struct VISIBILITY_HIDDEN ConstantCreator {
706 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
707 return new ConstantClass(Ty, V);
711 template<class ConstantClass, class TypeClass>
712 struct VISIBILITY_HIDDEN ConvertConstantType {
713 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
714 assert(0 && "This type cannot be converted!\n");
719 template<class ValType, class TypeClass, class ConstantClass,
720 bool HasLargeKey = false /*true for arrays and structs*/ >
721 class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
723 typedef std::pair<const Type*, ValType> MapKey;
724 typedef std::map<MapKey, Constant *> MapTy;
725 typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
726 typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
728 /// Map - This is the main map from the element descriptor to the Constants.
729 /// This is the primary way we avoid creating two of the same shape
733 /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
734 /// from the constants to their element in Map. This is important for
735 /// removal of constants from the array, which would otherwise have to scan
736 /// through the map with very large keys.
737 InverseMapTy InverseMap;
739 /// AbstractTypeMap - Map for abstract type constants.
741 AbstractTypeMapTy AbstractTypeMap;
744 typename MapTy::iterator map_end() { return Map.end(); }
746 /// InsertOrGetItem - Return an iterator for the specified element.
747 /// If the element exists in the map, the returned iterator points to the
748 /// entry and Exists=true. If not, the iterator points to the newly
749 /// inserted entry and returns Exists=false. Newly inserted entries have
750 /// I->second == 0, and should be filled in.
751 typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
754 std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
760 typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
762 typename InverseMapTy::iterator IMI = InverseMap.find(CP);
763 assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
764 IMI->second->second == CP &&
765 "InverseMap corrupt!");
769 typename MapTy::iterator I =
770 Map.find(MapKey((TypeClass*)CP->getRawType(), getValType(CP)));
771 if (I == Map.end() || I->second != CP) {
772 // FIXME: This should not use a linear scan. If this gets to be a
773 // performance problem, someone should look at this.
774 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
781 /// getOrCreate - Return the specified constant from the map, creating it if
783 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
784 MapKey Lookup(Ty, V);
785 typename MapTy::iterator I = Map.lower_bound(Lookup);
787 if (I != Map.end() && I->first == Lookup)
788 return static_cast<ConstantClass *>(I->second);
790 // If no preexisting value, create one now...
791 ConstantClass *Result =
792 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
794 /// FIXME: why does this assert fail when loading 176.gcc?
795 //assert(Result->getType() == Ty && "Type specified is not correct!");
796 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
798 if (HasLargeKey) // Remember the reverse mapping if needed.
799 InverseMap.insert(std::make_pair(Result, I));
801 // If the type of the constant is abstract, make sure that an entry exists
802 // for it in the AbstractTypeMap.
803 if (Ty->isAbstract()) {
804 typename AbstractTypeMapTy::iterator TI =
805 AbstractTypeMap.lower_bound(Ty);
807 if (TI == AbstractTypeMap.end() || TI->first != Ty) {
808 // Add ourselves to the ATU list of the type.
809 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
811 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
817 void remove(ConstantClass *CP) {
818 typename MapTy::iterator I = FindExistingElement(CP);
819 assert(I != Map.end() && "Constant not found in constant table!");
820 assert(I->second == CP && "Didn't find correct element?");
822 if (HasLargeKey) // Remember the reverse mapping if needed.
823 InverseMap.erase(CP);
825 // Now that we found the entry, make sure this isn't the entry that
826 // the AbstractTypeMap points to.
827 const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
828 if (Ty->isAbstract()) {
829 assert(AbstractTypeMap.count(Ty) &&
830 "Abstract type not in AbstractTypeMap?");
831 typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
832 if (ATMEntryIt == I) {
833 // Yes, we are removing the representative entry for this type.
834 // See if there are any other entries of the same type.
835 typename MapTy::iterator TmpIt = ATMEntryIt;
837 // First check the entry before this one...
838 if (TmpIt != Map.begin()) {
840 if (TmpIt->first.first != Ty) // Not the same type, move back...
844 // If we didn't find the same type, try to move forward...
845 if (TmpIt == ATMEntryIt) {
847 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
848 --TmpIt; // No entry afterwards with the same type
851 // If there is another entry in the map of the same abstract type,
852 // update the AbstractTypeMap entry now.
853 if (TmpIt != ATMEntryIt) {
856 // Otherwise, we are removing the last instance of this type
857 // from the table. Remove from the ATM, and from user list.
858 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
859 AbstractTypeMap.erase(Ty);
868 /// MoveConstantToNewSlot - If we are about to change C to be the element
869 /// specified by I, update our internal data structures to reflect this
871 void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
872 // First, remove the old location of the specified constant in the map.
873 typename MapTy::iterator OldI = FindExistingElement(C);
874 assert(OldI != Map.end() && "Constant not found in constant table!");
875 assert(OldI->second == C && "Didn't find correct element?");
877 // If this constant is the representative element for its abstract type,
878 // update the AbstractTypeMap so that the representative element is I.
879 if (C->getType()->isAbstract()) {
880 typename AbstractTypeMapTy::iterator ATI =
881 AbstractTypeMap.find(C->getType());
882 assert(ATI != AbstractTypeMap.end() &&
883 "Abstract type not in AbstractTypeMap?");
884 if (ATI->second == OldI)
888 // Remove the old entry from the map.
891 // Update the inverse map so that we know that this constant is now
892 // located at descriptor I.
894 assert(I->second == C && "Bad inversemap entry!");
899 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
900 typename AbstractTypeMapTy::iterator I =
901 AbstractTypeMap.find(cast<Type>(OldTy));
903 assert(I != AbstractTypeMap.end() &&
904 "Abstract type not in AbstractTypeMap?");
906 // Convert a constant at a time until the last one is gone. The last one
907 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
908 // eliminated eventually.
910 ConvertConstantType<ConstantClass,
912 static_cast<ConstantClass *>(I->second->second),
913 cast<TypeClass>(NewTy));
915 I = AbstractTypeMap.find(cast<Type>(OldTy));
916 } while (I != AbstractTypeMap.end());
919 // If the type became concrete without being refined to any other existing
920 // type, we just remove ourselves from the ATU list.
921 void typeBecameConcrete(const DerivedType *AbsTy) {
922 AbsTy->removeAbstractTypeUser(this);
926 DOUT << "Constant.cpp: ValueMap\n";
933 //---- ConstantAggregateZero::get() implementation...
936 // ConstantAggregateZero does not take extra "value" argument...
937 template<class ValType>
938 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
939 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
940 return new ConstantAggregateZero(Ty);
945 struct ConvertConstantType<ConstantAggregateZero, Type> {
946 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
947 // Make everyone now use a constant of the new type...
948 Constant *New = ConstantAggregateZero::get(NewTy);
949 assert(New != OldC && "Didn't replace constant??");
950 OldC->uncheckedReplaceAllUsesWith(New);
951 OldC->destroyConstant(); // This constant is now dead, destroy it.
956 static ManagedStatic<ValueMap<char, Type,
957 ConstantAggregateZero> > AggZeroConstants;
959 static char getValType(ConstantAggregateZero *CPZ) { return 0; }
961 Constant *ConstantAggregateZero::get(const Type *Ty) {
962 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) &&
963 "Cannot create an aggregate zero of non-aggregate type!");
964 return AggZeroConstants->getOrCreate(Ty, 0);
967 // destroyConstant - Remove the constant from the constant table...
969 void ConstantAggregateZero::destroyConstant() {
970 AggZeroConstants->remove(this);
971 destroyConstantImpl();
974 //---- ConstantArray::get() implementation...
978 struct ConvertConstantType<ConstantArray, ArrayType> {
979 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
980 // Make everyone now use a constant of the new type...
981 std::vector<Constant*> C;
982 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
983 C.push_back(cast<Constant>(OldC->getOperand(i)));
984 Constant *New = ConstantArray::get(NewTy, C);
985 assert(New != OldC && "Didn't replace constant??");
986 OldC->uncheckedReplaceAllUsesWith(New);
987 OldC->destroyConstant(); // This constant is now dead, destroy it.
992 static std::vector<Constant*> getValType(ConstantArray *CA) {
993 std::vector<Constant*> Elements;
994 Elements.reserve(CA->getNumOperands());
995 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
996 Elements.push_back(cast<Constant>(CA->getOperand(i)));
1000 typedef ValueMap<std::vector<Constant*>, ArrayType,
1001 ConstantArray, true /*largekey*/> ArrayConstantsTy;
1002 static ManagedStatic<ArrayConstantsTy> ArrayConstants;
1004 Constant *ConstantArray::get(const ArrayType *Ty,
1005 const std::vector<Constant*> &V) {
1006 // If this is an all-zero array, return a ConstantAggregateZero object
1009 if (!C->isNullValue())
1010 return ArrayConstants->getOrCreate(Ty, V);
1011 for (unsigned i = 1, e = V.size(); i != e; ++i)
1013 return ArrayConstants->getOrCreate(Ty, V);
1015 return ConstantAggregateZero::get(Ty);
1018 // destroyConstant - Remove the constant from the constant table...
1020 void ConstantArray::destroyConstant() {
1021 ArrayConstants->remove(this);
1022 destroyConstantImpl();
1025 /// ConstantArray::get(const string&) - Return an array that is initialized to
1026 /// contain the specified string. If length is zero then a null terminator is
1027 /// added to the specified string so that it may be used in a natural way.
1028 /// Otherwise, the length parameter specifies how much of the string to use
1029 /// and it won't be null terminated.
1031 Constant *ConstantArray::get(const std::string &Str, bool AddNull) {
1032 std::vector<Constant*> ElementVals;
1033 for (unsigned i = 0; i < Str.length(); ++i)
1034 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, Str[i]));
1036 // Add a null terminator to the string...
1038 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, 0));
1041 ArrayType *ATy = ArrayType::get(Type::Int8Ty, ElementVals.size());
1042 return ConstantArray::get(ATy, ElementVals);
1045 /// isString - This method returns true if the array is an array of i8, and
1046 /// if the elements of the array are all ConstantInt's.
1047 bool ConstantArray::isString() const {
1048 // Check the element type for i8...
1049 if (getType()->getElementType() != Type::Int8Ty)
1051 // Check the elements to make sure they are all integers, not constant
1053 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1054 if (!isa<ConstantInt>(getOperand(i)))
1059 /// isCString - This method returns true if the array is a string (see
1060 /// isString) and it ends in a null byte \0 and does not contains any other
1061 /// null bytes except its terminator.
1062 bool ConstantArray::isCString() const {
1063 // Check the element type for i8...
1064 if (getType()->getElementType() != Type::Int8Ty)
1066 Constant *Zero = Constant::getNullValue(getOperand(0)->getType());
1067 // Last element must be a null.
1068 if (getOperand(getNumOperands()-1) != Zero)
1070 // Other elements must be non-null integers.
1071 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1072 if (!isa<ConstantInt>(getOperand(i)))
1074 if (getOperand(i) == Zero)
1081 // getAsString - If the sub-element type of this array is i8
1082 // then this method converts the array to an std::string and returns it.
1083 // Otherwise, it asserts out.
1085 std::string ConstantArray::getAsString() const {
1086 assert(isString() && "Not a string!");
1088 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1089 Result += (char)cast<ConstantInt>(getOperand(i))->getZExtValue();
1094 //---- ConstantStruct::get() implementation...
1099 struct ConvertConstantType<ConstantStruct, StructType> {
1100 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1101 // Make everyone now use a constant of the new type...
1102 std::vector<Constant*> C;
1103 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1104 C.push_back(cast<Constant>(OldC->getOperand(i)));
1105 Constant *New = ConstantStruct::get(NewTy, C);
1106 assert(New != OldC && "Didn't replace constant??");
1108 OldC->uncheckedReplaceAllUsesWith(New);
1109 OldC->destroyConstant(); // This constant is now dead, destroy it.
1114 typedef ValueMap<std::vector<Constant*>, StructType,
1115 ConstantStruct, true /*largekey*/> StructConstantsTy;
1116 static ManagedStatic<StructConstantsTy> StructConstants;
1118 static std::vector<Constant*> getValType(ConstantStruct *CS) {
1119 std::vector<Constant*> Elements;
1120 Elements.reserve(CS->getNumOperands());
1121 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1122 Elements.push_back(cast<Constant>(CS->getOperand(i)));
1126 Constant *ConstantStruct::get(const StructType *Ty,
1127 const std::vector<Constant*> &V) {
1128 // Create a ConstantAggregateZero value if all elements are zeros...
1129 for (unsigned i = 0, e = V.size(); i != e; ++i)
1130 if (!V[i]->isNullValue())
1131 return StructConstants->getOrCreate(Ty, V);
1133 return ConstantAggregateZero::get(Ty);
1136 Constant *ConstantStruct::get(const std::vector<Constant*> &V, bool packed) {
1137 std::vector<const Type*> StructEls;
1138 StructEls.reserve(V.size());
1139 for (unsigned i = 0, e = V.size(); i != e; ++i)
1140 StructEls.push_back(V[i]->getType());
1141 return get(StructType::get(StructEls, packed), V);
1144 // destroyConstant - Remove the constant from the constant table...
1146 void ConstantStruct::destroyConstant() {
1147 StructConstants->remove(this);
1148 destroyConstantImpl();
1151 //---- ConstantVector::get() implementation...
1155 struct ConvertConstantType<ConstantVector, VectorType> {
1156 static void convert(ConstantVector *OldC, const VectorType *NewTy) {
1157 // Make everyone now use a constant of the new type...
1158 std::vector<Constant*> C;
1159 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1160 C.push_back(cast<Constant>(OldC->getOperand(i)));
1161 Constant *New = ConstantVector::get(NewTy, C);
1162 assert(New != OldC && "Didn't replace constant??");
1163 OldC->uncheckedReplaceAllUsesWith(New);
1164 OldC->destroyConstant(); // This constant is now dead, destroy it.
1169 static std::vector<Constant*> getValType(ConstantVector *CP) {
1170 std::vector<Constant*> Elements;
1171 Elements.reserve(CP->getNumOperands());
1172 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1173 Elements.push_back(CP->getOperand(i));
1177 static ManagedStatic<ValueMap<std::vector<Constant*>, VectorType,
1178 ConstantVector> > VectorConstants;
1180 Constant *ConstantVector::get(const VectorType *Ty,
1181 const std::vector<Constant*> &V) {
1182 // If this is an all-zero packed, return a ConstantAggregateZero object
1185 if (!C->isNullValue())
1186 return VectorConstants->getOrCreate(Ty, V);
1187 for (unsigned i = 1, e = V.size(); i != e; ++i)
1189 return VectorConstants->getOrCreate(Ty, V);
1191 return ConstantAggregateZero::get(Ty);
1194 Constant *ConstantVector::get(const std::vector<Constant*> &V) {
1195 assert(!V.empty() && "Cannot infer type if V is empty");
1196 return get(VectorType::get(V.front()->getType(),V.size()), V);
1199 // destroyConstant - Remove the constant from the constant table...
1201 void ConstantVector::destroyConstant() {
1202 VectorConstants->remove(this);
1203 destroyConstantImpl();
1206 /// This function will return true iff every element in this packed constant
1207 /// is set to all ones.
1208 /// @returns true iff this constant's emements are all set to all ones.
1209 /// @brief Determine if the value is all ones.
1210 bool ConstantVector::isAllOnesValue() const {
1211 // Check out first element.
1212 const Constant *Elt = getOperand(0);
1213 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1214 if (!CI || !CI->isAllOnesValue()) return false;
1215 // Then make sure all remaining elements point to the same value.
1216 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1217 if (getOperand(I) != Elt) return false;
1222 //---- ConstantPointerNull::get() implementation...
1226 // ConstantPointerNull does not take extra "value" argument...
1227 template<class ValType>
1228 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1229 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1230 return new ConstantPointerNull(Ty);
1235 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1236 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1237 // Make everyone now use a constant of the new type...
1238 Constant *New = ConstantPointerNull::get(NewTy);
1239 assert(New != OldC && "Didn't replace constant??");
1240 OldC->uncheckedReplaceAllUsesWith(New);
1241 OldC->destroyConstant(); // This constant is now dead, destroy it.
1246 static ManagedStatic<ValueMap<char, PointerType,
1247 ConstantPointerNull> > NullPtrConstants;
1249 static char getValType(ConstantPointerNull *) {
1254 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1255 return NullPtrConstants->getOrCreate(Ty, 0);
1258 // destroyConstant - Remove the constant from the constant table...
1260 void ConstantPointerNull::destroyConstant() {
1261 NullPtrConstants->remove(this);
1262 destroyConstantImpl();
1266 //---- UndefValue::get() implementation...
1270 // UndefValue does not take extra "value" argument...
1271 template<class ValType>
1272 struct ConstantCreator<UndefValue, Type, ValType> {
1273 static UndefValue *create(const Type *Ty, const ValType &V) {
1274 return new UndefValue(Ty);
1279 struct ConvertConstantType<UndefValue, Type> {
1280 static void convert(UndefValue *OldC, const Type *NewTy) {
1281 // Make everyone now use a constant of the new type.
1282 Constant *New = UndefValue::get(NewTy);
1283 assert(New != OldC && "Didn't replace constant??");
1284 OldC->uncheckedReplaceAllUsesWith(New);
1285 OldC->destroyConstant(); // This constant is now dead, destroy it.
1290 static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
1292 static char getValType(UndefValue *) {
1297 UndefValue *UndefValue::get(const Type *Ty) {
1298 return UndefValueConstants->getOrCreate(Ty, 0);
1301 // destroyConstant - Remove the constant from the constant table.
1303 void UndefValue::destroyConstant() {
1304 UndefValueConstants->remove(this);
1305 destroyConstantImpl();
1309 //---- ConstantExpr::get() implementations...
1312 struct ExprMapKeyType {
1313 explicit ExprMapKeyType(unsigned opc, std::vector<Constant*> ops,
1314 unsigned short pred = 0) : opcode(opc), predicate(pred), operands(ops) { }
1317 std::vector<Constant*> operands;
1318 bool operator==(const ExprMapKeyType& that) const {
1319 return this->opcode == that.opcode &&
1320 this->predicate == that.predicate &&
1321 this->operands == that.operands;
1323 bool operator<(const ExprMapKeyType & that) const {
1324 return this->opcode < that.opcode ||
1325 (this->opcode == that.opcode && this->predicate < that.predicate) ||
1326 (this->opcode == that.opcode && this->predicate == that.predicate &&
1327 this->operands < that.operands);
1330 bool operator!=(const ExprMapKeyType& that) const {
1331 return !(*this == that);
1337 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1338 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1339 unsigned short pred = 0) {
1340 if (Instruction::isCast(V.opcode))
1341 return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1342 if ((V.opcode >= Instruction::BinaryOpsBegin &&
1343 V.opcode < Instruction::BinaryOpsEnd))
1344 return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1345 if (V.opcode == Instruction::Select)
1346 return new SelectConstantExpr(V.operands[0], V.operands[1],
1348 if (V.opcode == Instruction::ExtractElement)
1349 return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1350 if (V.opcode == Instruction::InsertElement)
1351 return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1353 if (V.opcode == Instruction::ShuffleVector)
1354 return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1356 if (V.opcode == Instruction::GetElementPtr) {
1357 std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
1358 return new GetElementPtrConstantExpr(V.operands[0], IdxList, Ty);
1361 // The compare instructions are weird. We have to encode the predicate
1362 // value and it is combined with the instruction opcode by multiplying
1363 // the opcode by one hundred. We must decode this to get the predicate.
1364 if (V.opcode == Instruction::ICmp)
1365 return new CompareConstantExpr(Instruction::ICmp, V.predicate,
1366 V.operands[0], V.operands[1]);
1367 if (V.opcode == Instruction::FCmp)
1368 return new CompareConstantExpr(Instruction::FCmp, V.predicate,
1369 V.operands[0], V.operands[1]);
1370 assert(0 && "Invalid ConstantExpr!");
1376 struct ConvertConstantType<ConstantExpr, Type> {
1377 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1379 switch (OldC->getOpcode()) {
1380 case Instruction::Trunc:
1381 case Instruction::ZExt:
1382 case Instruction::SExt:
1383 case Instruction::FPTrunc:
1384 case Instruction::FPExt:
1385 case Instruction::UIToFP:
1386 case Instruction::SIToFP:
1387 case Instruction::FPToUI:
1388 case Instruction::FPToSI:
1389 case Instruction::PtrToInt:
1390 case Instruction::IntToPtr:
1391 case Instruction::BitCast:
1392 New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0),
1395 case Instruction::Select:
1396 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1397 OldC->getOperand(1),
1398 OldC->getOperand(2));
1401 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1402 OldC->getOpcode() < Instruction::BinaryOpsEnd);
1403 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1404 OldC->getOperand(1));
1406 case Instruction::GetElementPtr:
1407 // Make everyone now use a constant of the new type...
1408 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1409 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0),
1410 &Idx[0], Idx.size());
1414 assert(New != OldC && "Didn't replace constant??");
1415 OldC->uncheckedReplaceAllUsesWith(New);
1416 OldC->destroyConstant(); // This constant is now dead, destroy it.
1419 } // end namespace llvm
1422 static ExprMapKeyType getValType(ConstantExpr *CE) {
1423 std::vector<Constant*> Operands;
1424 Operands.reserve(CE->getNumOperands());
1425 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1426 Operands.push_back(cast<Constant>(CE->getOperand(i)));
1427 return ExprMapKeyType(CE->getOpcode(), Operands,
1428 CE->isCompare() ? CE->getPredicate() : 0);
1431 static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1432 ConstantExpr> > ExprConstants;
1434 /// This is a utility function to handle folding of casts and lookup of the
1435 /// cast in the ExprConstants map. It is usedby the various get* methods below.
1436 static inline Constant *getFoldedCast(
1437 Instruction::CastOps opc, Constant *C, const Type *Ty) {
1438 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1439 // Fold a few common cases
1440 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1443 // Look up the constant in the table first to ensure uniqueness
1444 std::vector<Constant*> argVec(1, C);
1445 ExprMapKeyType Key(opc, argVec);
1446 return ExprConstants->getOrCreate(Ty, Key);
1449 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1450 Instruction::CastOps opc = Instruction::CastOps(oc);
1451 assert(Instruction::isCast(opc) && "opcode out of range");
1452 assert(C && Ty && "Null arguments to getCast");
1453 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1457 assert(0 && "Invalid cast opcode");
1459 case Instruction::Trunc: return getTrunc(C, Ty);
1460 case Instruction::ZExt: return getZExt(C, Ty);
1461 case Instruction::SExt: return getSExt(C, Ty);
1462 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1463 case Instruction::FPExt: return getFPExtend(C, Ty);
1464 case Instruction::UIToFP: return getUIToFP(C, Ty);
1465 case Instruction::SIToFP: return getSIToFP(C, Ty);
1466 case Instruction::FPToUI: return getFPToUI(C, Ty);
1467 case Instruction::FPToSI: return getFPToSI(C, Ty);
1468 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1469 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1470 case Instruction::BitCast: return getBitCast(C, Ty);
1475 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1476 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1477 return getCast(Instruction::BitCast, C, Ty);
1478 return getCast(Instruction::ZExt, C, Ty);
1481 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1482 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1483 return getCast(Instruction::BitCast, C, Ty);
1484 return getCast(Instruction::SExt, C, Ty);
1487 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1488 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1489 return getCast(Instruction::BitCast, C, Ty);
1490 return getCast(Instruction::Trunc, C, Ty);
1493 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1494 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1495 assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
1497 if (Ty->isInteger())
1498 return getCast(Instruction::PtrToInt, S, Ty);
1499 return getCast(Instruction::BitCast, S, Ty);
1502 Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
1504 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1505 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1506 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1507 Instruction::CastOps opcode =
1508 (SrcBits == DstBits ? Instruction::BitCast :
1509 (SrcBits > DstBits ? Instruction::Trunc :
1510 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1511 return getCast(opcode, C, Ty);
1514 Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1515 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1517 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1518 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1519 if (SrcBits == DstBits)
1520 return C; // Avoid a useless cast
1521 Instruction::CastOps opcode =
1522 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1523 return getCast(opcode, C, Ty);
1526 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
1527 assert(C->getType()->isInteger() && "Trunc operand must be integer");
1528 assert(Ty->isInteger() && "Trunc produces only integral");
1529 assert(C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1530 "SrcTy must be larger than DestTy for Trunc!");
1532 return getFoldedCast(Instruction::Trunc, C, Ty);
1535 Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
1536 assert(C->getType()->isInteger() && "SEXt operand must be integral");
1537 assert(Ty->isInteger() && "SExt produces only integer");
1538 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1539 "SrcTy must be smaller than DestTy for SExt!");
1541 return getFoldedCast(Instruction::SExt, C, Ty);
1544 Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
1545 assert(C->getType()->isInteger() && "ZEXt operand must be integral");
1546 assert(Ty->isInteger() && "ZExt produces only integer");
1547 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1548 "SrcTy must be smaller than DestTy for ZExt!");
1550 return getFoldedCast(Instruction::ZExt, C, Ty);
1553 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1554 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1555 C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1556 "This is an illegal floating point truncation!");
1557 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1560 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1561 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1562 C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1563 "This is an illegal floating point extension!");
1564 return getFoldedCast(Instruction::FPExt, C, Ty);
1567 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
1568 assert(C->getType()->isInteger() && Ty->isFloatingPoint() &&
1569 "This is an illegal i32 to floating point cast!");
1570 return getFoldedCast(Instruction::UIToFP, C, Ty);
1573 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
1574 assert(C->getType()->isInteger() && Ty->isFloatingPoint() &&
1575 "This is an illegal sint to floating point cast!");
1576 return getFoldedCast(Instruction::SIToFP, C, Ty);
1579 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
1580 assert(C->getType()->isFloatingPoint() && Ty->isInteger() &&
1581 "This is an illegal floating point to i32 cast!");
1582 return getFoldedCast(Instruction::FPToUI, C, Ty);
1585 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
1586 assert(C->getType()->isFloatingPoint() && Ty->isInteger() &&
1587 "This is an illegal floating point to i32 cast!");
1588 return getFoldedCast(Instruction::FPToSI, C, Ty);
1591 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1592 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
1593 assert(DstTy->isInteger() && "PtrToInt destination must be integral");
1594 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1597 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
1598 assert(C->getType()->isInteger() && "IntToPtr source must be integral");
1599 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
1600 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1603 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1604 // BitCast implies a no-op cast of type only. No bits change. However, you
1605 // can't cast pointers to anything but pointers.
1606 const Type *SrcTy = C->getType();
1607 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
1608 "BitCast cannot cast pointer to non-pointer and vice versa");
1610 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
1611 // or nonptr->ptr). For all the other types, the cast is okay if source and
1612 // destination bit widths are identical.
1613 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1614 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
1615 assert(SrcBitSize == DstBitSize && "BitCast requies types of same width");
1616 return getFoldedCast(Instruction::BitCast, C, DstTy);
1619 Constant *ConstantExpr::getSizeOf(const Type *Ty) {
1620 // sizeof is implemented as: (ulong) gep (Ty*)null, 1
1621 Constant *GEPIdx = ConstantInt::get(Type::Int32Ty, 1);
1623 getGetElementPtr(getNullValue(PointerType::get(Ty)), &GEPIdx, 1);
1624 return getCast(Instruction::PtrToInt, GEP, Type::Int64Ty);
1627 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1628 Constant *C1, Constant *C2) {
1629 // Check the operands for consistency first
1630 assert(Opcode >= Instruction::BinaryOpsBegin &&
1631 Opcode < Instruction::BinaryOpsEnd &&
1632 "Invalid opcode in binary constant expression");
1633 assert(C1->getType() == C2->getType() &&
1634 "Operand types in binary constant expression should match");
1636 if (ReqTy == C1->getType() || ReqTy == Type::Int1Ty)
1637 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1638 return FC; // Fold a few common cases...
1640 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1641 ExprMapKeyType Key(Opcode, argVec);
1642 return ExprConstants->getOrCreate(ReqTy, Key);
1645 Constant *ConstantExpr::getCompareTy(unsigned short predicate,
1646 Constant *C1, Constant *C2) {
1647 switch (predicate) {
1648 default: assert(0 && "Invalid CmpInst predicate");
1649 case FCmpInst::FCMP_FALSE: case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_OGT:
1650 case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OLE:
1651 case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_ORD: case FCmpInst::FCMP_UNO:
1652 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UGT: case FCmpInst::FCMP_UGE:
1653 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_ULE: case FCmpInst::FCMP_UNE:
1654 case FCmpInst::FCMP_TRUE:
1655 return getFCmp(predicate, C1, C2);
1656 case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGT:
1657 case ICmpInst::ICMP_UGE: case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE:
1658 case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_SGE: case ICmpInst::ICMP_SLT:
1659 case ICmpInst::ICMP_SLE:
1660 return getICmp(predicate, C1, C2);
1664 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
1667 case Instruction::Add:
1668 case Instruction::Sub:
1669 case Instruction::Mul:
1670 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1671 assert((C1->getType()->isInteger() || C1->getType()->isFloatingPoint() ||
1672 isa<VectorType>(C1->getType())) &&
1673 "Tried to create an arithmetic operation on a non-arithmetic type!");
1675 case Instruction::UDiv:
1676 case Instruction::SDiv:
1677 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1678 assert((C1->getType()->isInteger() || (isa<VectorType>(C1->getType()) &&
1679 cast<VectorType>(C1->getType())->getElementType()->isInteger())) &&
1680 "Tried to create an arithmetic operation on a non-arithmetic type!");
1682 case Instruction::FDiv:
1683 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1684 assert((C1->getType()->isFloatingPoint() || (isa<VectorType>(C1->getType())
1685 && cast<VectorType>(C1->getType())->getElementType()->isFloatingPoint()))
1686 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1688 case Instruction::URem:
1689 case Instruction::SRem:
1690 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1691 assert((C1->getType()->isInteger() || (isa<VectorType>(C1->getType()) &&
1692 cast<VectorType>(C1->getType())->getElementType()->isInteger())) &&
1693 "Tried to create an arithmetic operation on a non-arithmetic type!");
1695 case Instruction::FRem:
1696 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1697 assert((C1->getType()->isFloatingPoint() || (isa<VectorType>(C1->getType())
1698 && cast<VectorType>(C1->getType())->getElementType()->isFloatingPoint()))
1699 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1701 case Instruction::And:
1702 case Instruction::Or:
1703 case Instruction::Xor:
1704 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1705 assert((C1->getType()->isInteger() || isa<VectorType>(C1->getType())) &&
1706 "Tried to create a logical operation on a non-integral type!");
1708 case Instruction::Shl:
1709 case Instruction::LShr:
1710 case Instruction::AShr:
1711 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1712 assert(C1->getType()->isInteger() &&
1713 "Tried to create a shift operation on a non-integer type!");
1720 return getTy(C1->getType(), Opcode, C1, C2);
1723 Constant *ConstantExpr::getCompare(unsigned short pred,
1724 Constant *C1, Constant *C2) {
1725 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1726 return getCompareTy(pred, C1, C2);
1729 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1730 Constant *V1, Constant *V2) {
1731 assert(C->getType() == Type::Int1Ty && "Select condition must be i1!");
1732 assert(V1->getType() == V2->getType() && "Select value types must match!");
1733 assert(V1->getType()->isFirstClassType() && "Cannot select aggregate type!");
1735 if (ReqTy == V1->getType())
1736 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1737 return SC; // Fold common cases
1739 std::vector<Constant*> argVec(3, C);
1742 ExprMapKeyType Key(Instruction::Select, argVec);
1743 return ExprConstants->getOrCreate(ReqTy, Key);
1746 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1749 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs, NumIdx, true) &&
1750 "GEP indices invalid!");
1752 if (Constant *FC = ConstantFoldGetElementPtr(C, (Constant**)Idxs, NumIdx))
1753 return FC; // Fold a few common cases...
1755 assert(isa<PointerType>(C->getType()) &&
1756 "Non-pointer type for constant GetElementPtr expression");
1757 // Look up the constant in the table first to ensure uniqueness
1758 std::vector<Constant*> ArgVec;
1759 ArgVec.reserve(NumIdx+1);
1760 ArgVec.push_back(C);
1761 for (unsigned i = 0; i != NumIdx; ++i)
1762 ArgVec.push_back(cast<Constant>(Idxs[i]));
1763 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
1764 return ExprConstants->getOrCreate(ReqTy, Key);
1767 Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
1769 // Get the result type of the getelementptr!
1771 GetElementPtrInst::getIndexedType(C->getType(), Idxs, NumIdx, true);
1772 assert(Ty && "GEP indices invalid!");
1773 return getGetElementPtrTy(PointerType::get(Ty), C, Idxs, NumIdx);
1776 Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
1778 return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
1783 ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1784 assert(LHS->getType() == RHS->getType());
1785 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
1786 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1788 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1789 return FC; // Fold a few common cases...
1791 // Look up the constant in the table first to ensure uniqueness
1792 std::vector<Constant*> ArgVec;
1793 ArgVec.push_back(LHS);
1794 ArgVec.push_back(RHS);
1795 // Get the key type with both the opcode and predicate
1796 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
1797 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
1801 ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1802 assert(LHS->getType() == RHS->getType());
1803 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1805 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1806 return FC; // Fold a few common cases...
1808 // Look up the constant in the table first to ensure uniqueness
1809 std::vector<Constant*> ArgVec;
1810 ArgVec.push_back(LHS);
1811 ArgVec.push_back(RHS);
1812 // Get the key type with both the opcode and predicate
1813 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
1814 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
1817 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
1819 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
1820 return FC; // Fold a few common cases...
1821 // Look up the constant in the table first to ensure uniqueness
1822 std::vector<Constant*> ArgVec(1, Val);
1823 ArgVec.push_back(Idx);
1824 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
1825 return ExprConstants->getOrCreate(ReqTy, Key);
1828 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
1829 assert(isa<VectorType>(Val->getType()) &&
1830 "Tried to create extractelement operation on non-vector type!");
1831 assert(Idx->getType() == Type::Int32Ty &&
1832 "Extractelement index must be i32 type!");
1833 return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
1837 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
1838 Constant *Elt, Constant *Idx) {
1839 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
1840 return FC; // Fold a few common cases...
1841 // Look up the constant in the table first to ensure uniqueness
1842 std::vector<Constant*> ArgVec(1, Val);
1843 ArgVec.push_back(Elt);
1844 ArgVec.push_back(Idx);
1845 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
1846 return ExprConstants->getOrCreate(ReqTy, Key);
1849 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1851 assert(isa<VectorType>(Val->getType()) &&
1852 "Tried to create insertelement operation on non-vector type!");
1853 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
1854 && "Insertelement types must match!");
1855 assert(Idx->getType() == Type::Int32Ty &&
1856 "Insertelement index must be i32 type!");
1857 return getInsertElementTy(cast<VectorType>(Val->getType())->getElementType(),
1861 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
1862 Constant *V2, Constant *Mask) {
1863 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
1864 return FC; // Fold a few common cases...
1865 // Look up the constant in the table first to ensure uniqueness
1866 std::vector<Constant*> ArgVec(1, V1);
1867 ArgVec.push_back(V2);
1868 ArgVec.push_back(Mask);
1869 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
1870 return ExprConstants->getOrCreate(ReqTy, Key);
1873 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
1875 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1876 "Invalid shuffle vector constant expr operands!");
1877 return getShuffleVectorTy(V1->getType(), V1, V2, Mask);
1880 Constant *ConstantExpr::getZeroValueForNegationExpr(const Type *Ty) {
1881 if (const VectorType *PTy = dyn_cast<VectorType>(Ty))
1882 if (PTy->getElementType()->isFloatingPoint()) {
1883 std::vector<Constant*> zeros(PTy->getNumElements(),
1884 ConstantFP::get(PTy->getElementType(),-0.0));
1885 return ConstantVector::get(PTy, zeros);
1888 if (Ty->isFloatingPoint())
1889 return ConstantFP::get(Ty, -0.0);
1891 return Constant::getNullValue(Ty);
1894 // destroyConstant - Remove the constant from the constant table...
1896 void ConstantExpr::destroyConstant() {
1897 ExprConstants->remove(this);
1898 destroyConstantImpl();
1901 const char *ConstantExpr::getOpcodeName() const {
1902 return Instruction::getOpcodeName(getOpcode());
1905 //===----------------------------------------------------------------------===//
1906 // replaceUsesOfWithOnConstant implementations
1908 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
1910 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1911 Constant *ToC = cast<Constant>(To);
1913 unsigned OperandToUpdate = U-OperandList;
1914 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
1916 std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
1917 Lookup.first.first = getType();
1918 Lookup.second = this;
1920 std::vector<Constant*> &Values = Lookup.first.second;
1921 Values.reserve(getNumOperands()); // Build replacement array.
1923 // Fill values with the modified operands of the constant array. Also,
1924 // compute whether this turns into an all-zeros array.
1925 bool isAllZeros = false;
1926 if (!ToC->isNullValue()) {
1927 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
1928 Values.push_back(cast<Constant>(O->get()));
1931 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1932 Constant *Val = cast<Constant>(O->get());
1933 Values.push_back(Val);
1934 if (isAllZeros) isAllZeros = Val->isNullValue();
1937 Values[OperandToUpdate] = ToC;
1939 Constant *Replacement = 0;
1941 Replacement = ConstantAggregateZero::get(getType());
1943 // Check to see if we have this array type already.
1945 ArrayConstantsTy::MapTy::iterator I =
1946 ArrayConstants->InsertOrGetItem(Lookup, Exists);
1949 Replacement = I->second;
1951 // Okay, the new shape doesn't exist in the system yet. Instead of
1952 // creating a new constant array, inserting it, replaceallusesof'ing the
1953 // old with the new, then deleting the old... just update the current one
1955 ArrayConstants->MoveConstantToNewSlot(this, I);
1957 // Update to the new value.
1958 setOperand(OperandToUpdate, ToC);
1963 // Otherwise, I do need to replace this with an existing value.
1964 assert(Replacement != this && "I didn't contain From!");
1966 // Everyone using this now uses the replacement.
1967 uncheckedReplaceAllUsesWith(Replacement);
1969 // Delete the old constant!
1973 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
1975 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1976 Constant *ToC = cast<Constant>(To);
1978 unsigned OperandToUpdate = U-OperandList;
1979 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
1981 std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
1982 Lookup.first.first = getType();
1983 Lookup.second = this;
1984 std::vector<Constant*> &Values = Lookup.first.second;
1985 Values.reserve(getNumOperands()); // Build replacement struct.
1988 // Fill values with the modified operands of the constant struct. Also,
1989 // compute whether this turns into an all-zeros struct.
1990 bool isAllZeros = false;
1991 if (!ToC->isNullValue()) {
1992 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
1993 Values.push_back(cast<Constant>(O->get()));
1996 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1997 Constant *Val = cast<Constant>(O->get());
1998 Values.push_back(Val);
1999 if (isAllZeros) isAllZeros = Val->isNullValue();
2002 Values[OperandToUpdate] = ToC;
2004 Constant *Replacement = 0;
2006 Replacement = ConstantAggregateZero::get(getType());
2008 // Check to see if we have this array type already.
2010 StructConstantsTy::MapTy::iterator I =
2011 StructConstants->InsertOrGetItem(Lookup, Exists);
2014 Replacement = I->second;
2016 // Okay, the new shape doesn't exist in the system yet. Instead of
2017 // creating a new constant struct, inserting it, replaceallusesof'ing the
2018 // old with the new, then deleting the old... just update the current one
2020 StructConstants->MoveConstantToNewSlot(this, I);
2022 // Update to the new value.
2023 setOperand(OperandToUpdate, ToC);
2028 assert(Replacement != this && "I didn't contain From!");
2030 // Everyone using this now uses the replacement.
2031 uncheckedReplaceAllUsesWith(Replacement);
2033 // Delete the old constant!
2037 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
2039 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2041 std::vector<Constant*> Values;
2042 Values.reserve(getNumOperands()); // Build replacement array...
2043 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2044 Constant *Val = getOperand(i);
2045 if (Val == From) Val = cast<Constant>(To);
2046 Values.push_back(Val);
2049 Constant *Replacement = ConstantVector::get(getType(), Values);
2050 assert(Replacement != this && "I didn't contain From!");
2052 // Everyone using this now uses the replacement.
2053 uncheckedReplaceAllUsesWith(Replacement);
2055 // Delete the old constant!
2059 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2061 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2062 Constant *To = cast<Constant>(ToV);
2064 Constant *Replacement = 0;
2065 if (getOpcode() == Instruction::GetElementPtr) {
2066 SmallVector<Constant*, 8> Indices;
2067 Constant *Pointer = getOperand(0);
2068 Indices.reserve(getNumOperands()-1);
2069 if (Pointer == From) Pointer = To;
2071 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2072 Constant *Val = getOperand(i);
2073 if (Val == From) Val = To;
2074 Indices.push_back(Val);
2076 Replacement = ConstantExpr::getGetElementPtr(Pointer,
2077 &Indices[0], Indices.size());
2078 } else if (isCast()) {
2079 assert(getOperand(0) == From && "Cast only has one use!");
2080 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
2081 } else if (getOpcode() == Instruction::Select) {
2082 Constant *C1 = getOperand(0);
2083 Constant *C2 = getOperand(1);
2084 Constant *C3 = getOperand(2);
2085 if (C1 == From) C1 = To;
2086 if (C2 == From) C2 = To;
2087 if (C3 == From) C3 = To;
2088 Replacement = ConstantExpr::getSelect(C1, C2, C3);
2089 } else if (getOpcode() == Instruction::ExtractElement) {
2090 Constant *C1 = getOperand(0);
2091 Constant *C2 = getOperand(1);
2092 if (C1 == From) C1 = To;
2093 if (C2 == From) C2 = To;
2094 Replacement = ConstantExpr::getExtractElement(C1, C2);
2095 } else if (getOpcode() == Instruction::InsertElement) {
2096 Constant *C1 = getOperand(0);
2097 Constant *C2 = getOperand(1);
2098 Constant *C3 = getOperand(1);
2099 if (C1 == From) C1 = To;
2100 if (C2 == From) C2 = To;
2101 if (C3 == From) C3 = To;
2102 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2103 } else if (getOpcode() == Instruction::ShuffleVector) {
2104 Constant *C1 = getOperand(0);
2105 Constant *C2 = getOperand(1);
2106 Constant *C3 = getOperand(2);
2107 if (C1 == From) C1 = To;
2108 if (C2 == From) C2 = To;
2109 if (C3 == From) C3 = To;
2110 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2111 } else if (isCompare()) {
2112 Constant *C1 = getOperand(0);
2113 Constant *C2 = getOperand(1);
2114 if (C1 == From) C1 = To;
2115 if (C2 == From) C2 = To;
2116 if (getOpcode() == Instruction::ICmp)
2117 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2119 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2120 } else if (getNumOperands() == 2) {
2121 Constant *C1 = getOperand(0);
2122 Constant *C2 = getOperand(1);
2123 if (C1 == From) C1 = To;
2124 if (C2 == From) C2 = To;
2125 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2127 assert(0 && "Unknown ConstantExpr type!");
2131 assert(Replacement != this && "I didn't contain From!");
2133 // Everyone using this now uses the replacement.
2134 uncheckedReplaceAllUsesWith(Replacement);
2136 // Delete the old constant!
2141 /// getStringValue - Turn an LLVM constant pointer that eventually points to a
2142 /// global into a string value. Return an empty string if we can't do it.
2143 /// Parameter Chop determines if the result is chopped at the first null
2146 std::string Constant::getStringValue(bool Chop, unsigned Offset) {
2147 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(this)) {
2148 if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
2149 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
2150 if (Init->isString()) {
2151 std::string Result = Init->getAsString();
2152 if (Offset < Result.size()) {
2153 // If we are pointing INTO The string, erase the beginning...
2154 Result.erase(Result.begin(), Result.begin()+Offset);
2156 // Take off the null terminator, and any string fragments after it.
2158 std::string::size_type NullPos = Result.find_first_of((char)0);
2159 if (NullPos != std::string::npos)
2160 Result.erase(Result.begin()+NullPos, Result.end());
2166 } else if (Constant *C = dyn_cast<Constant>(this)) {
2167 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
2168 return GV->getStringValue(Chop, Offset);
2169 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2170 if (CE->getOpcode() == Instruction::GetElementPtr) {
2171 // Turn a gep into the specified offset.
2172 if (CE->getNumOperands() == 3 &&
2173 cast<Constant>(CE->getOperand(1))->isNullValue() &&
2174 isa<ConstantInt>(CE->getOperand(2))) {
2175 Offset += cast<ConstantInt>(CE->getOperand(2))->getZExtValue();
2176 return CE->getOperand(0)->getStringValue(Chop, Offset);