1 //===-- Constants.cpp - Implement Constant nodes --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Constant* classes...
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Constants.h"
15 #include "ConstantFolding.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/GlobalValue.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/SymbolTable.h"
20 #include "llvm/Module.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/Support/Compiler.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/ManagedStatic.h"
25 #include "llvm/Support/MathExtras.h"
29 //===----------------------------------------------------------------------===//
31 //===----------------------------------------------------------------------===//
33 void Constant::destroyConstantImpl() {
34 // When a Constant is destroyed, there may be lingering
35 // references to the constant by other constants in the constant pool. These
36 // constants are implicitly dependent on the module that is being deleted,
37 // but they don't know that. Because we only find out when the CPV is
38 // deleted, we must now notify all of our users (that should only be
39 // Constants) that they are, in fact, invalid now and should be deleted.
41 while (!use_empty()) {
42 Value *V = use_back();
43 #ifndef NDEBUG // Only in -g mode...
44 if (!isa<Constant>(V))
45 DOUT << "While deleting: " << *this
46 << "\n\nUse still stuck around after Def is destroyed: "
49 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
50 Constant *CV = cast<Constant>(V);
51 CV->destroyConstant();
53 // The constant should remove itself from our use list...
54 assert((use_empty() || use_back() != V) && "Constant not removed!");
57 // Value has no outstanding references it is safe to delete it now...
61 /// canTrap - Return true if evaluation of this constant could trap. This is
62 /// true for things like constant expressions that could divide by zero.
63 bool Constant::canTrap() const {
64 assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
65 // The only thing that could possibly trap are constant exprs.
66 const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
67 if (!CE) return false;
69 // ConstantExpr traps if any operands can trap.
70 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
71 if (getOperand(i)->canTrap())
74 // Otherwise, only specific operations can trap.
75 switch (CE->getOpcode()) {
78 case Instruction::UDiv:
79 case Instruction::SDiv:
80 case Instruction::FDiv:
81 case Instruction::URem:
82 case Instruction::SRem:
83 case Instruction::FRem:
84 // Div and rem can trap if the RHS is not known to be non-zero.
85 if (!isa<ConstantInt>(getOperand(1)) || getOperand(1)->isNullValue())
92 // Static constructor to create a '0' constant of arbitrary type...
93 Constant *Constant::getNullValue(const Type *Ty) {
94 switch (Ty->getTypeID()) {
95 case Type::BoolTyID: {
96 static Constant *NullBool = ConstantBool::get(false);
99 case Type::Int8TyID: {
100 static Constant *NullInt8 = ConstantInt::get(Type::Int8Ty, 0);
103 case Type::Int16TyID: {
104 static Constant *NullInt16 = ConstantInt::get(Type::Int16Ty, 0);
107 case Type::Int32TyID: {
108 static Constant *NullInt32 = ConstantInt::get(Type::Int32Ty, 0);
111 case Type::Int64TyID: {
112 static Constant *NullInt64 = ConstantInt::get(Type::Int64Ty, 0);
115 case Type::FloatTyID: {
116 static Constant *NullFloat = ConstantFP::get(Type::FloatTy, 0);
119 case Type::DoubleTyID: {
120 static Constant *NullDouble = ConstantFP::get(Type::DoubleTy, 0);
123 case Type::PointerTyID:
124 return ConstantPointerNull::get(cast<PointerType>(Ty));
125 case Type::StructTyID:
126 case Type::ArrayTyID:
127 case Type::PackedTyID:
128 return ConstantAggregateZero::get(Ty);
130 // Function, Label, or Opaque type?
131 assert(!"Cannot create a null constant of that type!");
137 // Static constructor to create an integral constant with all bits set
138 ConstantIntegral *ConstantIntegral::getAllOnesValue(const Type *Ty) {
139 switch (Ty->getTypeID()) {
140 case Type::BoolTyID: return ConstantBool::getTrue();
142 case Type::Int16TyID:
143 case Type::Int32TyID:
144 case Type::Int64TyID: return ConstantInt::get(Ty, int64_t(-1));
149 //===----------------------------------------------------------------------===//
150 // ConstantXXX Classes
151 //===----------------------------------------------------------------------===//
153 //===----------------------------------------------------------------------===//
154 // Normal Constructors
156 ConstantIntegral::ConstantIntegral(const Type *Ty, ValueTy VT, uint64_t V)
157 : Constant(Ty, VT, 0, 0), Val(V) {
160 ConstantBool::ConstantBool(bool V)
161 : ConstantIntegral(Type::BoolTy, ConstantBoolVal, uint64_t(V)) {
164 ConstantInt::ConstantInt(const Type *Ty, uint64_t V)
165 : ConstantIntegral(Ty, ConstantIntVal, V) {
168 ConstantFP::ConstantFP(const Type *Ty, double V)
169 : Constant(Ty, ConstantFPVal, 0, 0) {
170 assert(isValueValidForType(Ty, V) && "Value too large for type!");
174 ConstantArray::ConstantArray(const ArrayType *T,
175 const std::vector<Constant*> &V)
176 : Constant(T, ConstantArrayVal, new Use[V.size()], V.size()) {
177 assert(V.size() == T->getNumElements() &&
178 "Invalid initializer vector for constant array");
179 Use *OL = OperandList;
180 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
183 assert((C->getType() == T->getElementType() ||
185 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
186 "Initializer for array element doesn't match array element type!");
191 ConstantArray::~ConstantArray() {
192 delete [] OperandList;
195 ConstantStruct::ConstantStruct(const StructType *T,
196 const std::vector<Constant*> &V)
197 : Constant(T, ConstantStructVal, new Use[V.size()], V.size()) {
198 assert(V.size() == T->getNumElements() &&
199 "Invalid initializer vector for constant structure");
200 Use *OL = OperandList;
201 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
204 assert((C->getType() == T->getElementType(I-V.begin()) ||
205 ((T->getElementType(I-V.begin())->isAbstract() ||
206 C->getType()->isAbstract()) &&
207 T->getElementType(I-V.begin())->getTypeID() ==
208 C->getType()->getTypeID())) &&
209 "Initializer for struct element doesn't match struct element type!");
214 ConstantStruct::~ConstantStruct() {
215 delete [] OperandList;
219 ConstantPacked::ConstantPacked(const PackedType *T,
220 const std::vector<Constant*> &V)
221 : Constant(T, ConstantPackedVal, new Use[V.size()], V.size()) {
222 Use *OL = OperandList;
223 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
226 assert((C->getType() == T->getElementType() ||
228 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
229 "Initializer for packed element doesn't match packed element type!");
234 ConstantPacked::~ConstantPacked() {
235 delete [] OperandList;
238 // We declare several classes private to this file, so use an anonymous
242 /// UnaryConstantExpr - This class is private to Constants.cpp, and is used
243 /// behind the scenes to implement unary constant exprs.
244 class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
247 UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
248 : ConstantExpr(Ty, Opcode, &Op, 1), Op(C, this) {}
251 /// BinaryConstantExpr - This class is private to Constants.cpp, and is used
252 /// behind the scenes to implement binary constant exprs.
253 class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
256 BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
257 : ConstantExpr(C1->getType(), Opcode, Ops, 2) {
258 Ops[0].init(C1, this);
259 Ops[1].init(C2, this);
263 /// SelectConstantExpr - This class is private to Constants.cpp, and is used
264 /// behind the scenes to implement select constant exprs.
265 class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
268 SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
269 : ConstantExpr(C2->getType(), Instruction::Select, Ops, 3) {
270 Ops[0].init(C1, this);
271 Ops[1].init(C2, this);
272 Ops[2].init(C3, this);
276 /// ExtractElementConstantExpr - This class is private to
277 /// Constants.cpp, and is used behind the scenes to implement
278 /// extractelement constant exprs.
279 class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
282 ExtractElementConstantExpr(Constant *C1, Constant *C2)
283 : ConstantExpr(cast<PackedType>(C1->getType())->getElementType(),
284 Instruction::ExtractElement, Ops, 2) {
285 Ops[0].init(C1, this);
286 Ops[1].init(C2, this);
290 /// InsertElementConstantExpr - This class is private to
291 /// Constants.cpp, and is used behind the scenes to implement
292 /// insertelement constant exprs.
293 class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
296 InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
297 : ConstantExpr(C1->getType(), Instruction::InsertElement,
299 Ops[0].init(C1, this);
300 Ops[1].init(C2, this);
301 Ops[2].init(C3, this);
305 /// ShuffleVectorConstantExpr - This class is private to
306 /// Constants.cpp, and is used behind the scenes to implement
307 /// shufflevector constant exprs.
308 class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
311 ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
312 : ConstantExpr(C1->getType(), Instruction::ShuffleVector,
314 Ops[0].init(C1, this);
315 Ops[1].init(C2, this);
316 Ops[2].init(C3, this);
320 /// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
321 /// used behind the scenes to implement getelementpr constant exprs.
322 struct VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
323 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
325 : ConstantExpr(DestTy, Instruction::GetElementPtr,
326 new Use[IdxList.size()+1], IdxList.size()+1) {
327 OperandList[0].init(C, this);
328 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
329 OperandList[i+1].init(IdxList[i], this);
331 ~GetElementPtrConstantExpr() {
332 delete [] OperandList;
336 // CompareConstantExpr - This class is private to Constants.cpp, and is used
337 // behind the scenes to implement ICmp and FCmp constant expressions. This is
338 // needed in order to store the predicate value for these instructions.
339 struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
340 unsigned short predicate;
342 CompareConstantExpr(Instruction::OtherOps opc, unsigned short pred,
343 Constant* LHS, Constant* RHS)
344 : ConstantExpr(Type::BoolTy, opc, Ops, 2), predicate(pred) {
345 OperandList[0].init(LHS, this);
346 OperandList[1].init(RHS, this);
350 } // end anonymous namespace
353 // Utility function for determining if a ConstantExpr is a CastOp or not. This
354 // can't be inline because we don't want to #include Instruction.h into
356 bool ConstantExpr::isCast() const {
357 return Instruction::isCast(getOpcode());
360 bool ConstantExpr::isCompare() const {
361 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
364 /// ConstantExpr::get* - Return some common constants without having to
365 /// specify the full Instruction::OPCODE identifier.
367 Constant *ConstantExpr::getNeg(Constant *C) {
368 if (!C->getType()->isFloatingPoint())
369 return get(Instruction::Sub, getNullValue(C->getType()), C);
371 return get(Instruction::Sub, ConstantFP::get(C->getType(), -0.0), C);
373 Constant *ConstantExpr::getNot(Constant *C) {
374 assert(isa<ConstantIntegral>(C) && "Cannot NOT a nonintegral type!");
375 return get(Instruction::Xor, C,
376 ConstantIntegral::getAllOnesValue(C->getType()));
378 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
379 return get(Instruction::Add, C1, C2);
381 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
382 return get(Instruction::Sub, C1, C2);
384 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
385 return get(Instruction::Mul, C1, C2);
387 Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2) {
388 return get(Instruction::UDiv, C1, C2);
390 Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2) {
391 return get(Instruction::SDiv, C1, C2);
393 Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
394 return get(Instruction::FDiv, C1, C2);
396 Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
397 return get(Instruction::URem, C1, C2);
399 Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
400 return get(Instruction::SRem, C1, C2);
402 Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
403 return get(Instruction::FRem, C1, C2);
405 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
406 return get(Instruction::And, C1, C2);
408 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
409 return get(Instruction::Or, C1, C2);
411 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
412 return get(Instruction::Xor, C1, C2);
414 unsigned ConstantExpr::getPredicate() const {
415 assert(getOpcode() == Instruction::FCmp || getOpcode() == Instruction::ICmp);
416 return dynamic_cast<const CompareConstantExpr*>(this)->predicate;
418 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
419 return get(Instruction::Shl, C1, C2);
421 Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2) {
422 return get(Instruction::LShr, C1, C2);
424 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2) {
425 return get(Instruction::AShr, C1, C2);
428 /// getWithOperandReplaced - Return a constant expression identical to this
429 /// one, but with the specified operand set to the specified value.
431 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
432 assert(OpNo < getNumOperands() && "Operand num is out of range!");
433 assert(Op->getType() == getOperand(OpNo)->getType() &&
434 "Replacing operand with value of different type!");
435 if (getOperand(OpNo) == Op)
436 return const_cast<ConstantExpr*>(this);
438 Constant *Op0, *Op1, *Op2;
439 switch (getOpcode()) {
440 case Instruction::Trunc:
441 case Instruction::ZExt:
442 case Instruction::SExt:
443 case Instruction::FPTrunc:
444 case Instruction::FPExt:
445 case Instruction::UIToFP:
446 case Instruction::SIToFP:
447 case Instruction::FPToUI:
448 case Instruction::FPToSI:
449 case Instruction::PtrToInt:
450 case Instruction::IntToPtr:
451 case Instruction::BitCast:
452 return ConstantExpr::getCast(getOpcode(), Op, getType());
453 case Instruction::Select:
454 Op0 = (OpNo == 0) ? Op : getOperand(0);
455 Op1 = (OpNo == 1) ? Op : getOperand(1);
456 Op2 = (OpNo == 2) ? Op : getOperand(2);
457 return ConstantExpr::getSelect(Op0, Op1, Op2);
458 case Instruction::InsertElement:
459 Op0 = (OpNo == 0) ? Op : getOperand(0);
460 Op1 = (OpNo == 1) ? Op : getOperand(1);
461 Op2 = (OpNo == 2) ? Op : getOperand(2);
462 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
463 case Instruction::ExtractElement:
464 Op0 = (OpNo == 0) ? Op : getOperand(0);
465 Op1 = (OpNo == 1) ? Op : getOperand(1);
466 return ConstantExpr::getExtractElement(Op0, Op1);
467 case Instruction::ShuffleVector:
468 Op0 = (OpNo == 0) ? Op : getOperand(0);
469 Op1 = (OpNo == 1) ? Op : getOperand(1);
470 Op2 = (OpNo == 2) ? Op : getOperand(2);
471 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
472 case Instruction::GetElementPtr: {
473 std::vector<Constant*> Ops;
474 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
475 Ops.push_back(getOperand(i));
477 return ConstantExpr::getGetElementPtr(Op, Ops);
479 return ConstantExpr::getGetElementPtr(getOperand(0), Ops);
482 assert(getNumOperands() == 2 && "Must be binary operator?");
483 Op0 = (OpNo == 0) ? Op : getOperand(0);
484 Op1 = (OpNo == 1) ? Op : getOperand(1);
485 return ConstantExpr::get(getOpcode(), Op0, Op1);
489 /// getWithOperands - This returns the current constant expression with the
490 /// operands replaced with the specified values. The specified operands must
491 /// match count and type with the existing ones.
492 Constant *ConstantExpr::
493 getWithOperands(const std::vector<Constant*> &Ops) const {
494 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
495 bool AnyChange = false;
496 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
497 assert(Ops[i]->getType() == getOperand(i)->getType() &&
498 "Operand type mismatch!");
499 AnyChange |= Ops[i] != getOperand(i);
501 if (!AnyChange) // No operands changed, return self.
502 return const_cast<ConstantExpr*>(this);
504 switch (getOpcode()) {
505 case Instruction::Trunc:
506 case Instruction::ZExt:
507 case Instruction::SExt:
508 case Instruction::FPTrunc:
509 case Instruction::FPExt:
510 case Instruction::UIToFP:
511 case Instruction::SIToFP:
512 case Instruction::FPToUI:
513 case Instruction::FPToSI:
514 case Instruction::PtrToInt:
515 case Instruction::IntToPtr:
516 case Instruction::BitCast:
517 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
518 case Instruction::Select:
519 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
520 case Instruction::InsertElement:
521 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
522 case Instruction::ExtractElement:
523 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
524 case Instruction::ShuffleVector:
525 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
526 case Instruction::GetElementPtr: {
527 std::vector<Constant*> ActualOps(Ops.begin()+1, Ops.end());
528 return ConstantExpr::getGetElementPtr(Ops[0], ActualOps);
530 case Instruction::ICmp:
531 case Instruction::FCmp:
532 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
534 assert(getNumOperands() == 2 && "Must be binary operator?");
535 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
540 //===----------------------------------------------------------------------===//
541 // isValueValidForType implementations
543 bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
544 switch (Ty->getTypeID()) {
545 default: return false; // These can't be represented as integers!
546 case Type::Int8TyID: return Val <= UINT8_MAX;
547 case Type::Int16TyID: return Val <= UINT16_MAX;
548 case Type::Int32TyID: return Val <= UINT32_MAX;
549 case Type::Int64TyID: return true; // always true, has to fit in largest type
553 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
554 switch (Ty->getTypeID()) {
555 default: return false; // These can't be represented as integers!
556 case Type::Int8TyID: return (Val >= INT8_MIN && Val <= INT8_MAX);
557 case Type::Int16TyID: return (Val >= INT16_MIN && Val <= UINT16_MAX);
558 case Type::Int32TyID: return (Val >= INT32_MIN && Val <= UINT32_MAX);
559 case Type::Int64TyID: return true; // always true, has to fit in largest type
563 bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
564 switch (Ty->getTypeID()) {
566 return false; // These can't be represented as floating point!
568 // TODO: Figure out how to test if a double can be cast to a float!
569 case Type::FloatTyID:
570 case Type::DoubleTyID:
571 return true; // This is the largest type...
575 //===----------------------------------------------------------------------===//
576 // Factory Function Implementation
578 // ConstantCreator - A class that is used to create constants by
579 // ValueMap*. This class should be partially specialized if there is
580 // something strange that needs to be done to interface to the ctor for the
584 template<class ConstantClass, class TypeClass, class ValType>
585 struct VISIBILITY_HIDDEN ConstantCreator {
586 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
587 return new ConstantClass(Ty, V);
591 template<class ConstantClass, class TypeClass>
592 struct VISIBILITY_HIDDEN ConvertConstantType {
593 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
594 assert(0 && "This type cannot be converted!\n");
599 template<class ValType, class TypeClass, class ConstantClass,
600 bool HasLargeKey = false /*true for arrays and structs*/ >
601 class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
603 typedef std::pair<const Type*, ValType> MapKey;
604 typedef std::map<MapKey, Constant *> MapTy;
605 typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
606 typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
608 /// Map - This is the main map from the element descriptor to the Constants.
609 /// This is the primary way we avoid creating two of the same shape
613 /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
614 /// from the constants to their element in Map. This is important for
615 /// removal of constants from the array, which would otherwise have to scan
616 /// through the map with very large keys.
617 InverseMapTy InverseMap;
619 /// AbstractTypeMap - Map for abstract type constants.
621 AbstractTypeMapTy AbstractTypeMap;
624 void clear(std::vector<Constant *> &Constants) {
625 for(typename MapTy::iterator I = Map.begin(); I != Map.end(); ++I)
626 Constants.push_back(I->second);
628 AbstractTypeMap.clear();
633 typename MapTy::iterator map_end() { return Map.end(); }
635 /// InsertOrGetItem - Return an iterator for the specified element.
636 /// If the element exists in the map, the returned iterator points to the
637 /// entry and Exists=true. If not, the iterator points to the newly
638 /// inserted entry and returns Exists=false. Newly inserted entries have
639 /// I->second == 0, and should be filled in.
640 typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
643 std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
649 typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
651 typename InverseMapTy::iterator IMI = InverseMap.find(CP);
652 assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
653 IMI->second->second == CP &&
654 "InverseMap corrupt!");
658 typename MapTy::iterator I =
659 Map.find(MapKey((TypeClass*)CP->getRawType(), getValType(CP)));
660 if (I == Map.end() || I->second != CP) {
661 // FIXME: This should not use a linear scan. If this gets to be a
662 // performance problem, someone should look at this.
663 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
670 /// getOrCreate - Return the specified constant from the map, creating it if
672 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
673 MapKey Lookup(Ty, V);
674 typename MapTy::iterator I = Map.lower_bound(Lookup);
676 if (I != Map.end() && I->first == Lookup)
677 return static_cast<ConstantClass *>(I->second);
679 // If no preexisting value, create one now...
680 ConstantClass *Result =
681 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
683 /// FIXME: why does this assert fail when loading 176.gcc?
684 //assert(Result->getType() == Ty && "Type specified is not correct!");
685 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
687 if (HasLargeKey) // Remember the reverse mapping if needed.
688 InverseMap.insert(std::make_pair(Result, I));
690 // If the type of the constant is abstract, make sure that an entry exists
691 // for it in the AbstractTypeMap.
692 if (Ty->isAbstract()) {
693 typename AbstractTypeMapTy::iterator TI =
694 AbstractTypeMap.lower_bound(Ty);
696 if (TI == AbstractTypeMap.end() || TI->first != Ty) {
697 // Add ourselves to the ATU list of the type.
698 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
700 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
706 void remove(ConstantClass *CP) {
707 typename MapTy::iterator I = FindExistingElement(CP);
708 assert(I != Map.end() && "Constant not found in constant table!");
709 assert(I->second == CP && "Didn't find correct element?");
711 if (HasLargeKey) // Remember the reverse mapping if needed.
712 InverseMap.erase(CP);
714 // Now that we found the entry, make sure this isn't the entry that
715 // the AbstractTypeMap points to.
716 const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
717 if (Ty->isAbstract()) {
718 assert(AbstractTypeMap.count(Ty) &&
719 "Abstract type not in AbstractTypeMap?");
720 typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
721 if (ATMEntryIt == I) {
722 // Yes, we are removing the representative entry for this type.
723 // See if there are any other entries of the same type.
724 typename MapTy::iterator TmpIt = ATMEntryIt;
726 // First check the entry before this one...
727 if (TmpIt != Map.begin()) {
729 if (TmpIt->first.first != Ty) // Not the same type, move back...
733 // If we didn't find the same type, try to move forward...
734 if (TmpIt == ATMEntryIt) {
736 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
737 --TmpIt; // No entry afterwards with the same type
740 // If there is another entry in the map of the same abstract type,
741 // update the AbstractTypeMap entry now.
742 if (TmpIt != ATMEntryIt) {
745 // Otherwise, we are removing the last instance of this type
746 // from the table. Remove from the ATM, and from user list.
747 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
748 AbstractTypeMap.erase(Ty);
757 /// MoveConstantToNewSlot - If we are about to change C to be the element
758 /// specified by I, update our internal data structures to reflect this
760 void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
761 // First, remove the old location of the specified constant in the map.
762 typename MapTy::iterator OldI = FindExistingElement(C);
763 assert(OldI != Map.end() && "Constant not found in constant table!");
764 assert(OldI->second == C && "Didn't find correct element?");
766 // If this constant is the representative element for its abstract type,
767 // update the AbstractTypeMap so that the representative element is I.
768 if (C->getType()->isAbstract()) {
769 typename AbstractTypeMapTy::iterator ATI =
770 AbstractTypeMap.find(C->getType());
771 assert(ATI != AbstractTypeMap.end() &&
772 "Abstract type not in AbstractTypeMap?");
773 if (ATI->second == OldI)
777 // Remove the old entry from the map.
780 // Update the inverse map so that we know that this constant is now
781 // located at descriptor I.
783 assert(I->second == C && "Bad inversemap entry!");
788 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
789 typename AbstractTypeMapTy::iterator I =
790 AbstractTypeMap.find(cast<Type>(OldTy));
792 assert(I != AbstractTypeMap.end() &&
793 "Abstract type not in AbstractTypeMap?");
795 // Convert a constant at a time until the last one is gone. The last one
796 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
797 // eliminated eventually.
799 ConvertConstantType<ConstantClass,
801 static_cast<ConstantClass *>(I->second->second),
802 cast<TypeClass>(NewTy));
804 I = AbstractTypeMap.find(cast<Type>(OldTy));
805 } while (I != AbstractTypeMap.end());
808 // If the type became concrete without being refined to any other existing
809 // type, we just remove ourselves from the ATU list.
810 void typeBecameConcrete(const DerivedType *AbsTy) {
811 AbsTy->removeAbstractTypeUser(this);
815 DOUT << "Constant.cpp: ValueMap\n";
821 //---- ConstantBool::get*() implementation.
823 ConstantBool *ConstantBool::getTrue() {
824 static ConstantBool *T = 0;
826 return T = new ConstantBool(true);
828 ConstantBool *ConstantBool::getFalse() {
829 static ConstantBool *F = 0;
831 return F = new ConstantBool(false);
834 //---- ConstantInt::get() implementations...
836 static ManagedStatic<ValueMap<uint64_t, Type, ConstantInt> > IntConstants;
838 // Get a ConstantInt from an int64_t. Note here that we canoncialize the value
839 // to a uint64_t value that has been zero extended down to the size of the
840 // integer type of the ConstantInt. This allows the getZExtValue method to
841 // just return the stored value while getSExtValue has to convert back to sign
842 // extended. getZExtValue is more common in LLVM than getSExtValue().
843 ConstantInt *ConstantInt::get(const Type *Ty, int64_t V) {
844 return IntConstants->getOrCreate(Ty, V & Ty->getIntegralTypeMask());
847 ConstantIntegral *ConstantIntegral::get(const Type *Ty, int64_t V) {
848 if (Ty == Type::BoolTy) return ConstantBool::get(V&1);
849 return IntConstants->getOrCreate(Ty, V & Ty->getIntegralTypeMask());
852 //---- ConstantFP::get() implementation...
856 struct ConstantCreator<ConstantFP, Type, uint64_t> {
857 static ConstantFP *create(const Type *Ty, uint64_t V) {
858 assert(Ty == Type::DoubleTy);
859 return new ConstantFP(Ty, BitsToDouble(V));
863 struct ConstantCreator<ConstantFP, Type, uint32_t> {
864 static ConstantFP *create(const Type *Ty, uint32_t V) {
865 assert(Ty == Type::FloatTy);
866 return new ConstantFP(Ty, BitsToFloat(V));
871 static ManagedStatic<ValueMap<uint64_t, Type, ConstantFP> > DoubleConstants;
872 static ManagedStatic<ValueMap<uint32_t, Type, ConstantFP> > FloatConstants;
874 bool ConstantFP::isNullValue() const {
875 return DoubleToBits(Val) == 0;
878 bool ConstantFP::isExactlyValue(double V) const {
879 return DoubleToBits(V) == DoubleToBits(Val);
883 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
884 if (Ty == Type::FloatTy) {
885 // Force the value through memory to normalize it.
886 return FloatConstants->getOrCreate(Ty, FloatToBits(V));
888 assert(Ty == Type::DoubleTy);
889 return DoubleConstants->getOrCreate(Ty, DoubleToBits(V));
893 //---- ConstantAggregateZero::get() implementation...
896 // ConstantAggregateZero does not take extra "value" argument...
897 template<class ValType>
898 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
899 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
900 return new ConstantAggregateZero(Ty);
905 struct ConvertConstantType<ConstantAggregateZero, Type> {
906 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
907 // Make everyone now use a constant of the new type...
908 Constant *New = ConstantAggregateZero::get(NewTy);
909 assert(New != OldC && "Didn't replace constant??");
910 OldC->uncheckedReplaceAllUsesWith(New);
911 OldC->destroyConstant(); // This constant is now dead, destroy it.
916 static ManagedStatic<ValueMap<char, Type,
917 ConstantAggregateZero> > AggZeroConstants;
919 static char getValType(ConstantAggregateZero *CPZ) { return 0; }
921 Constant *ConstantAggregateZero::get(const Type *Ty) {
922 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<PackedType>(Ty)) &&
923 "Cannot create an aggregate zero of non-aggregate type!");
924 return AggZeroConstants->getOrCreate(Ty, 0);
927 // destroyConstant - Remove the constant from the constant table...
929 void ConstantAggregateZero::destroyConstant() {
930 AggZeroConstants->remove(this);
931 destroyConstantImpl();
934 //---- ConstantArray::get() implementation...
938 struct ConvertConstantType<ConstantArray, ArrayType> {
939 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
940 // Make everyone now use a constant of the new type...
941 std::vector<Constant*> C;
942 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
943 C.push_back(cast<Constant>(OldC->getOperand(i)));
944 Constant *New = ConstantArray::get(NewTy, C);
945 assert(New != OldC && "Didn't replace constant??");
946 OldC->uncheckedReplaceAllUsesWith(New);
947 OldC->destroyConstant(); // This constant is now dead, destroy it.
952 static std::vector<Constant*> getValType(ConstantArray *CA) {
953 std::vector<Constant*> Elements;
954 Elements.reserve(CA->getNumOperands());
955 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
956 Elements.push_back(cast<Constant>(CA->getOperand(i)));
960 typedef ValueMap<std::vector<Constant*>, ArrayType,
961 ConstantArray, true /*largekey*/> ArrayConstantsTy;
962 static ManagedStatic<ArrayConstantsTy> ArrayConstants;
964 Constant *ConstantArray::get(const ArrayType *Ty,
965 const std::vector<Constant*> &V) {
966 // If this is an all-zero array, return a ConstantAggregateZero object
969 if (!C->isNullValue())
970 return ArrayConstants->getOrCreate(Ty, V);
971 for (unsigned i = 1, e = V.size(); i != e; ++i)
973 return ArrayConstants->getOrCreate(Ty, V);
975 return ConstantAggregateZero::get(Ty);
978 // destroyConstant - Remove the constant from the constant table...
980 void ConstantArray::destroyConstant() {
981 ArrayConstants->remove(this);
982 destroyConstantImpl();
985 /// ConstantArray::get(const string&) - Return an array that is initialized to
986 /// contain the specified string. If length is zero then a null terminator is
987 /// added to the specified string so that it may be used in a natural way.
988 /// Otherwise, the length parameter specifies how much of the string to use
989 /// and it won't be null terminated.
991 Constant *ConstantArray::get(const std::string &Str, bool AddNull) {
992 std::vector<Constant*> ElementVals;
993 for (unsigned i = 0; i < Str.length(); ++i)
994 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, Str[i]));
996 // Add a null terminator to the string...
998 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, 0));
1001 ArrayType *ATy = ArrayType::get(Type::Int8Ty, ElementVals.size());
1002 return ConstantArray::get(ATy, ElementVals);
1005 /// isString - This method returns true if the array is an array of sbyte or
1006 /// ubyte, and if the elements of the array are all ConstantInt's.
1007 bool ConstantArray::isString() const {
1008 // Check the element type for sbyte or ubyte...
1009 if (getType()->getElementType() != Type::Int8Ty)
1011 // Check the elements to make sure they are all integers, not constant
1013 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1014 if (!isa<ConstantInt>(getOperand(i)))
1019 /// isCString - This method returns true if the array is a string (see
1020 /// isString) and it ends in a null byte \0 and does not contains any other
1021 /// null bytes except its terminator.
1022 bool ConstantArray::isCString() const {
1023 // Check the element type for sbyte or ubyte...
1024 if (getType()->getElementType() != Type::Int8Ty)
1026 Constant *Zero = Constant::getNullValue(getOperand(0)->getType());
1027 // Last element must be a null.
1028 if (getOperand(getNumOperands()-1) != Zero)
1030 // Other elements must be non-null integers.
1031 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1032 if (!isa<ConstantInt>(getOperand(i)))
1034 if (getOperand(i) == Zero)
1041 // getAsString - If the sub-element type of this array is either sbyte or ubyte,
1042 // then this method converts the array to an std::string and returns it.
1043 // Otherwise, it asserts out.
1045 std::string ConstantArray::getAsString() const {
1046 assert(isString() && "Not a string!");
1048 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1049 Result += (char)cast<ConstantInt>(getOperand(i))->getZExtValue();
1054 //---- ConstantStruct::get() implementation...
1059 struct ConvertConstantType<ConstantStruct, StructType> {
1060 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1061 // Make everyone now use a constant of the new type...
1062 std::vector<Constant*> C;
1063 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1064 C.push_back(cast<Constant>(OldC->getOperand(i)));
1065 Constant *New = ConstantStruct::get(NewTy, C);
1066 assert(New != OldC && "Didn't replace constant??");
1068 OldC->uncheckedReplaceAllUsesWith(New);
1069 OldC->destroyConstant(); // This constant is now dead, destroy it.
1074 typedef ValueMap<std::vector<Constant*>, StructType,
1075 ConstantStruct, true /*largekey*/> StructConstantsTy;
1076 static ManagedStatic<StructConstantsTy> StructConstants;
1078 static std::vector<Constant*> getValType(ConstantStruct *CS) {
1079 std::vector<Constant*> Elements;
1080 Elements.reserve(CS->getNumOperands());
1081 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1082 Elements.push_back(cast<Constant>(CS->getOperand(i)));
1086 Constant *ConstantStruct::get(const StructType *Ty,
1087 const std::vector<Constant*> &V) {
1088 // Create a ConstantAggregateZero value if all elements are zeros...
1089 for (unsigned i = 0, e = V.size(); i != e; ++i)
1090 if (!V[i]->isNullValue())
1091 return StructConstants->getOrCreate(Ty, V);
1093 return ConstantAggregateZero::get(Ty);
1096 Constant *ConstantStruct::get(const std::vector<Constant*> &V, bool packed) {
1097 std::vector<const Type*> StructEls;
1098 StructEls.reserve(V.size());
1099 for (unsigned i = 0, e = V.size(); i != e; ++i)
1100 StructEls.push_back(V[i]->getType());
1101 return get(StructType::get(StructEls, packed), V);
1104 // destroyConstant - Remove the constant from the constant table...
1106 void ConstantStruct::destroyConstant() {
1107 StructConstants->remove(this);
1108 destroyConstantImpl();
1111 //---- ConstantPacked::get() implementation...
1115 struct ConvertConstantType<ConstantPacked, PackedType> {
1116 static void convert(ConstantPacked *OldC, const PackedType *NewTy) {
1117 // Make everyone now use a constant of the new type...
1118 std::vector<Constant*> C;
1119 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1120 C.push_back(cast<Constant>(OldC->getOperand(i)));
1121 Constant *New = ConstantPacked::get(NewTy, C);
1122 assert(New != OldC && "Didn't replace constant??");
1123 OldC->uncheckedReplaceAllUsesWith(New);
1124 OldC->destroyConstant(); // This constant is now dead, destroy it.
1129 static std::vector<Constant*> getValType(ConstantPacked *CP) {
1130 std::vector<Constant*> Elements;
1131 Elements.reserve(CP->getNumOperands());
1132 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1133 Elements.push_back(CP->getOperand(i));
1137 static ManagedStatic<ValueMap<std::vector<Constant*>, PackedType,
1138 ConstantPacked> > PackedConstants;
1140 Constant *ConstantPacked::get(const PackedType *Ty,
1141 const std::vector<Constant*> &V) {
1142 // If this is an all-zero packed, return a ConstantAggregateZero object
1145 if (!C->isNullValue())
1146 return PackedConstants->getOrCreate(Ty, V);
1147 for (unsigned i = 1, e = V.size(); i != e; ++i)
1149 return PackedConstants->getOrCreate(Ty, V);
1151 return ConstantAggregateZero::get(Ty);
1154 Constant *ConstantPacked::get(const std::vector<Constant*> &V) {
1155 assert(!V.empty() && "Cannot infer type if V is empty");
1156 return get(PackedType::get(V.front()->getType(),V.size()), V);
1159 // destroyConstant - Remove the constant from the constant table...
1161 void ConstantPacked::destroyConstant() {
1162 PackedConstants->remove(this);
1163 destroyConstantImpl();
1166 //---- ConstantPointerNull::get() implementation...
1170 // ConstantPointerNull does not take extra "value" argument...
1171 template<class ValType>
1172 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1173 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1174 return new ConstantPointerNull(Ty);
1179 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1180 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1181 // Make everyone now use a constant of the new type...
1182 Constant *New = ConstantPointerNull::get(NewTy);
1183 assert(New != OldC && "Didn't replace constant??");
1184 OldC->uncheckedReplaceAllUsesWith(New);
1185 OldC->destroyConstant(); // This constant is now dead, destroy it.
1190 static ManagedStatic<ValueMap<char, PointerType,
1191 ConstantPointerNull> > NullPtrConstants;
1193 static char getValType(ConstantPointerNull *) {
1198 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1199 return NullPtrConstants->getOrCreate(Ty, 0);
1202 // destroyConstant - Remove the constant from the constant table...
1204 void ConstantPointerNull::destroyConstant() {
1205 NullPtrConstants->remove(this);
1206 destroyConstantImpl();
1210 //---- UndefValue::get() implementation...
1214 // UndefValue does not take extra "value" argument...
1215 template<class ValType>
1216 struct ConstantCreator<UndefValue, Type, ValType> {
1217 static UndefValue *create(const Type *Ty, const ValType &V) {
1218 return new UndefValue(Ty);
1223 struct ConvertConstantType<UndefValue, Type> {
1224 static void convert(UndefValue *OldC, const Type *NewTy) {
1225 // Make everyone now use a constant of the new type.
1226 Constant *New = UndefValue::get(NewTy);
1227 assert(New != OldC && "Didn't replace constant??");
1228 OldC->uncheckedReplaceAllUsesWith(New);
1229 OldC->destroyConstant(); // This constant is now dead, destroy it.
1234 static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
1236 static char getValType(UndefValue *) {
1241 UndefValue *UndefValue::get(const Type *Ty) {
1242 return UndefValueConstants->getOrCreate(Ty, 0);
1245 // destroyConstant - Remove the constant from the constant table.
1247 void UndefValue::destroyConstant() {
1248 UndefValueConstants->remove(this);
1249 destroyConstantImpl();
1253 //---- ConstantExpr::get() implementations...
1256 struct ExprMapKeyType {
1257 explicit ExprMapKeyType(unsigned opc, std::vector<Constant*> ops,
1258 unsigned short pred = 0) : opcode(opc), predicate(pred), operands(ops) { }
1261 std::vector<Constant*> operands;
1262 bool operator==(const ExprMapKeyType& that) const {
1263 return this->opcode == that.opcode &&
1264 this->predicate == that.predicate &&
1265 this->operands == that.operands;
1267 bool operator<(const ExprMapKeyType & that) const {
1268 return this->opcode < that.opcode ||
1269 (this->opcode == that.opcode && this->predicate < that.predicate) ||
1270 (this->opcode == that.opcode && this->predicate == that.predicate &&
1271 this->operands < that.operands);
1274 bool operator!=(const ExprMapKeyType& that) const {
1275 return !(*this == that);
1281 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1282 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1283 unsigned short pred = 0) {
1284 if (Instruction::isCast(V.opcode))
1285 return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1286 if ((V.opcode >= Instruction::BinaryOpsBegin &&
1287 V.opcode < Instruction::BinaryOpsEnd) ||
1288 V.opcode == Instruction::Shl ||
1289 V.opcode == Instruction::LShr ||
1290 V.opcode == Instruction::AShr)
1291 return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1292 if (V.opcode == Instruction::Select)
1293 return new SelectConstantExpr(V.operands[0], V.operands[1],
1295 if (V.opcode == Instruction::ExtractElement)
1296 return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1297 if (V.opcode == Instruction::InsertElement)
1298 return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1300 if (V.opcode == Instruction::ShuffleVector)
1301 return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1303 if (V.opcode == Instruction::GetElementPtr) {
1304 std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
1305 return new GetElementPtrConstantExpr(V.operands[0], IdxList, Ty);
1308 // The compare instructions are weird. We have to encode the predicate
1309 // value and it is combined with the instruction opcode by multiplying
1310 // the opcode by one hundred. We must decode this to get the predicate.
1311 if (V.opcode == Instruction::ICmp)
1312 return new CompareConstantExpr(Instruction::ICmp, V.predicate,
1313 V.operands[0], V.operands[1]);
1314 if (V.opcode == Instruction::FCmp)
1315 return new CompareConstantExpr(Instruction::FCmp, V.predicate,
1316 V.operands[0], V.operands[1]);
1317 assert(0 && "Invalid ConstantExpr!");
1323 struct ConvertConstantType<ConstantExpr, Type> {
1324 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1326 switch (OldC->getOpcode()) {
1327 case Instruction::Trunc:
1328 case Instruction::ZExt:
1329 case Instruction::SExt:
1330 case Instruction::FPTrunc:
1331 case Instruction::FPExt:
1332 case Instruction::UIToFP:
1333 case Instruction::SIToFP:
1334 case Instruction::FPToUI:
1335 case Instruction::FPToSI:
1336 case Instruction::PtrToInt:
1337 case Instruction::IntToPtr:
1338 case Instruction::BitCast:
1339 New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0),
1342 case Instruction::Select:
1343 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1344 OldC->getOperand(1),
1345 OldC->getOperand(2));
1347 case Instruction::Shl:
1348 case Instruction::LShr:
1349 case Instruction::AShr:
1350 New = ConstantExpr::getShiftTy(NewTy, OldC->getOpcode(),
1351 OldC->getOperand(0), OldC->getOperand(1));
1354 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1355 OldC->getOpcode() < Instruction::BinaryOpsEnd);
1356 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1357 OldC->getOperand(1));
1359 case Instruction::GetElementPtr:
1360 // Make everyone now use a constant of the new type...
1361 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1362 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0), Idx);
1366 assert(New != OldC && "Didn't replace constant??");
1367 OldC->uncheckedReplaceAllUsesWith(New);
1368 OldC->destroyConstant(); // This constant is now dead, destroy it.
1371 } // end namespace llvm
1374 static ExprMapKeyType getValType(ConstantExpr *CE) {
1375 std::vector<Constant*> Operands;
1376 Operands.reserve(CE->getNumOperands());
1377 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1378 Operands.push_back(cast<Constant>(CE->getOperand(i)));
1379 return ExprMapKeyType(CE->getOpcode(), Operands,
1380 CE->isCompare() ? CE->getPredicate() : 0);
1383 static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1384 ConstantExpr> > ExprConstants;
1386 /// This is a utility function to handle folding of casts and lookup of the
1387 /// cast in the ExprConstants map. It is usedby the various get* methods below.
1388 static inline Constant *getFoldedCast(
1389 Instruction::CastOps opc, Constant *C, const Type *Ty) {
1390 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1391 // Fold a few common cases
1392 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1395 // Look up the constant in the table first to ensure uniqueness
1396 std::vector<Constant*> argVec(1, C);
1397 ExprMapKeyType Key(opc, argVec);
1398 return ExprConstants->getOrCreate(Ty, Key);
1401 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1402 Instruction::CastOps opc = Instruction::CastOps(oc);
1403 assert(Instruction::isCast(opc) && "opcode out of range");
1404 assert(C && Ty && "Null arguments to getCast");
1405 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1409 assert(0 && "Invalid cast opcode");
1411 case Instruction::Trunc: return getTrunc(C, Ty);
1412 case Instruction::ZExt: return getZExt(C, Ty);
1413 case Instruction::SExt: return getSExt(C, Ty);
1414 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1415 case Instruction::FPExt: return getFPExtend(C, Ty);
1416 case Instruction::UIToFP: return getUIToFP(C, Ty);
1417 case Instruction::SIToFP: return getSIToFP(C, Ty);
1418 case Instruction::FPToUI: return getFPToUI(C, Ty);
1419 case Instruction::FPToSI: return getFPToSI(C, Ty);
1420 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1421 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1422 case Instruction::BitCast: return getBitCast(C, Ty);
1427 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1428 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1429 return getCast(Instruction::BitCast, C, Ty);
1430 return getCast(Instruction::ZExt, C, Ty);
1433 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1434 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1435 return getCast(Instruction::BitCast, C, Ty);
1436 return getCast(Instruction::SExt, C, Ty);
1439 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1440 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1441 return getCast(Instruction::BitCast, C, Ty);
1442 return getCast(Instruction::Trunc, C, Ty);
1445 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1446 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1447 assert((Ty->isIntegral() || Ty->getTypeID() == Type::PointerTyID) &&
1450 if (Ty->isIntegral())
1451 return getCast(Instruction::PtrToInt, S, Ty);
1452 return getCast(Instruction::BitCast, S, Ty);
1455 Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
1457 assert(C->getType()->isIntegral() && Ty->isIntegral() && "Invalid cast");
1458 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1459 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1460 Instruction::CastOps opcode =
1461 (SrcBits == DstBits ? Instruction::BitCast :
1462 (SrcBits > DstBits ? Instruction::Trunc :
1463 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1464 return getCast(opcode, C, Ty);
1467 Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1468 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1470 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1471 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1472 if (SrcBits == DstBits)
1473 return C; // Avoid a useless cast
1474 Instruction::CastOps opcode =
1475 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1476 return getCast(opcode, C, Ty);
1479 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
1480 assert(C->getType()->isInteger() && "Trunc operand must be integer");
1481 assert(Ty->isIntegral() && "Trunc produces only integral");
1482 assert(C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1483 "SrcTy must be larger than DestTy for Trunc!");
1485 return getFoldedCast(Instruction::Trunc, C, Ty);
1488 Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
1489 assert(C->getType()->isIntegral() && "SEXt operand must be integral");
1490 assert(Ty->isInteger() && "SExt produces only integer");
1491 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1492 "SrcTy must be smaller than DestTy for SExt!");
1494 return getFoldedCast(Instruction::SExt, C, Ty);
1497 Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
1498 assert(C->getType()->isIntegral() && "ZEXt operand must be integral");
1499 assert(Ty->isInteger() && "ZExt produces only integer");
1500 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1501 "SrcTy must be smaller than DestTy for ZExt!");
1503 return getFoldedCast(Instruction::ZExt, C, Ty);
1506 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1507 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1508 C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1509 "This is an illegal floating point truncation!");
1510 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1513 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1514 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1515 C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1516 "This is an illegal floating point extension!");
1517 return getFoldedCast(Instruction::FPExt, C, Ty);
1520 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
1521 assert(C->getType()->isIntegral() && Ty->isFloatingPoint() &&
1522 "This is an illegal uint to floating point cast!");
1523 return getFoldedCast(Instruction::UIToFP, C, Ty);
1526 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
1527 assert(C->getType()->isIntegral() && Ty->isFloatingPoint() &&
1528 "This is an illegal sint to floating point cast!");
1529 return getFoldedCast(Instruction::SIToFP, C, Ty);
1532 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
1533 assert(C->getType()->isFloatingPoint() && Ty->isIntegral() &&
1534 "This is an illegal floating point to uint cast!");
1535 return getFoldedCast(Instruction::FPToUI, C, Ty);
1538 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
1539 assert(C->getType()->isFloatingPoint() && Ty->isIntegral() &&
1540 "This is an illegal floating point to sint cast!");
1541 return getFoldedCast(Instruction::FPToSI, C, Ty);
1544 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1545 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
1546 assert(DstTy->isIntegral() && "PtrToInt destination must be integral");
1547 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1550 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
1551 assert(C->getType()->isIntegral() && "IntToPtr source must be integral");
1552 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
1553 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1556 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1557 // BitCast implies a no-op cast of type only. No bits change. However, you
1558 // can't cast pointers to anything but pointers.
1559 const Type *SrcTy = C->getType();
1560 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
1561 "BitCast cannot cast pointer to non-pointer and vice versa");
1563 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
1564 // or nonptr->ptr). For all the other types, the cast is okay if source and
1565 // destination bit widths are identical.
1566 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1567 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
1568 assert(SrcBitSize == DstBitSize && "BitCast requies types of same width");
1569 return getFoldedCast(Instruction::BitCast, C, DstTy);
1572 Constant *ConstantExpr::getSizeOf(const Type *Ty) {
1573 // sizeof is implemented as: (ulong) gep (Ty*)null, 1
1574 return getCast(Instruction::PtrToInt, getGetElementPtr(getNullValue(
1575 PointerType::get(Ty)), std::vector<Constant*>(1,
1576 ConstantInt::get(Type::Int32Ty, 1))), Type::Int64Ty);
1579 Constant *ConstantExpr::getPtrPtrFromArrayPtr(Constant *C) {
1580 // pointer from array is implemented as: getelementptr arr ptr, 0, 0
1581 static std::vector<Constant*> Indices(2, ConstantInt::get(Type::Int32Ty, 0));
1583 return ConstantExpr::getGetElementPtr(C, Indices);
1586 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1587 Constant *C1, Constant *C2) {
1588 if (Opcode == Instruction::Shl || Opcode == Instruction::LShr ||
1589 Opcode == Instruction::AShr)
1590 return getShiftTy(ReqTy, Opcode, C1, C2);
1592 // Check the operands for consistency first
1593 assert(Opcode >= Instruction::BinaryOpsBegin &&
1594 Opcode < Instruction::BinaryOpsEnd &&
1595 "Invalid opcode in binary constant expression");
1596 assert(C1->getType() == C2->getType() &&
1597 "Operand types in binary constant expression should match");
1599 if (ReqTy == C1->getType() || ReqTy == Type::BoolTy)
1600 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1601 return FC; // Fold a few common cases...
1603 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1604 ExprMapKeyType Key(Opcode, argVec);
1605 return ExprConstants->getOrCreate(ReqTy, Key);
1608 Constant *ConstantExpr::getCompareTy(unsigned short predicate,
1609 Constant *C1, Constant *C2) {
1610 switch (predicate) {
1611 default: assert(0 && "Invalid CmpInst predicate");
1612 case FCmpInst::FCMP_FALSE: case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_OGT:
1613 case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OLE:
1614 case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_ORD: case FCmpInst::FCMP_UNO:
1615 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UGT: case FCmpInst::FCMP_UGE:
1616 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_ULE: case FCmpInst::FCMP_UNE:
1617 case FCmpInst::FCMP_TRUE:
1618 return getFCmp(predicate, C1, C2);
1619 case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGT:
1620 case ICmpInst::ICMP_UGE: case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE:
1621 case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_SGE: case ICmpInst::ICMP_SLT:
1622 case ICmpInst::ICMP_SLE:
1623 return getICmp(predicate, C1, C2);
1627 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
1630 case Instruction::Add:
1631 case Instruction::Sub:
1632 case Instruction::Mul:
1633 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1634 assert((C1->getType()->isInteger() || C1->getType()->isFloatingPoint() ||
1635 isa<PackedType>(C1->getType())) &&
1636 "Tried to create an arithmetic operation on a non-arithmetic type!");
1638 case Instruction::UDiv:
1639 case Instruction::SDiv:
1640 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1641 assert((C1->getType()->isInteger() || (isa<PackedType>(C1->getType()) &&
1642 cast<PackedType>(C1->getType())->getElementType()->isInteger())) &&
1643 "Tried to create an arithmetic operation on a non-arithmetic type!");
1645 case Instruction::FDiv:
1646 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1647 assert((C1->getType()->isFloatingPoint() || (isa<PackedType>(C1->getType())
1648 && cast<PackedType>(C1->getType())->getElementType()->isFloatingPoint()))
1649 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1651 case Instruction::URem:
1652 case Instruction::SRem:
1653 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1654 assert((C1->getType()->isInteger() || (isa<PackedType>(C1->getType()) &&
1655 cast<PackedType>(C1->getType())->getElementType()->isInteger())) &&
1656 "Tried to create an arithmetic operation on a non-arithmetic type!");
1658 case Instruction::FRem:
1659 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1660 assert((C1->getType()->isFloatingPoint() || (isa<PackedType>(C1->getType())
1661 && cast<PackedType>(C1->getType())->getElementType()->isFloatingPoint()))
1662 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1664 case Instruction::And:
1665 case Instruction::Or:
1666 case Instruction::Xor:
1667 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1668 assert((C1->getType()->isIntegral() || isa<PackedType>(C1->getType())) &&
1669 "Tried to create a logical operation on a non-integral type!");
1671 case Instruction::Shl:
1672 case Instruction::LShr:
1673 case Instruction::AShr:
1674 assert(C2->getType() == Type::Int8Ty && "Shift should be by ubyte!");
1675 assert(C1->getType()->isInteger() &&
1676 "Tried to create a shift operation on a non-integer type!");
1683 return getTy(C1->getType(), Opcode, C1, C2);
1686 Constant *ConstantExpr::getCompare(unsigned short pred,
1687 Constant *C1, Constant *C2) {
1688 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1689 return getCompareTy(pred, C1, C2);
1692 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1693 Constant *V1, Constant *V2) {
1694 assert(C->getType() == Type::BoolTy && "Select condition must be bool!");
1695 assert(V1->getType() == V2->getType() && "Select value types must match!");
1696 assert(V1->getType()->isFirstClassType() && "Cannot select aggregate type!");
1698 if (ReqTy == V1->getType())
1699 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1700 return SC; // Fold common cases
1702 std::vector<Constant*> argVec(3, C);
1705 ExprMapKeyType Key(Instruction::Select, argVec);
1706 return ExprConstants->getOrCreate(ReqTy, Key);
1709 /// getShiftTy - Return a shift left or shift right constant expr
1710 Constant *ConstantExpr::getShiftTy(const Type *ReqTy, unsigned Opcode,
1711 Constant *C1, Constant *C2) {
1712 // Check the operands for consistency first
1713 assert((Opcode == Instruction::Shl ||
1714 Opcode == Instruction::LShr ||
1715 Opcode == Instruction::AShr) &&
1716 "Invalid opcode in binary constant expression");
1717 assert(C1->getType()->isIntegral() && C2->getType() == Type::Int8Ty &&
1718 "Invalid operand types for Shift constant expr!");
1720 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1721 return FC; // Fold a few common cases...
1723 // Look up the constant in the table first to ensure uniqueness
1724 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1725 ExprMapKeyType Key(Opcode, argVec);
1726 return ExprConstants->getOrCreate(ReqTy, Key);
1729 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1730 const std::vector<Value*> &IdxList) {
1731 assert(GetElementPtrInst::getIndexedType(C->getType(), IdxList, true) &&
1732 "GEP indices invalid!");
1734 if (Constant *FC = ConstantFoldGetElementPtr(C, IdxList))
1735 return FC; // Fold a few common cases...
1737 assert(isa<PointerType>(C->getType()) &&
1738 "Non-pointer type for constant GetElementPtr expression");
1739 // Look up the constant in the table first to ensure uniqueness
1740 std::vector<Constant*> ArgVec;
1741 ArgVec.reserve(IdxList.size()+1);
1742 ArgVec.push_back(C);
1743 for (unsigned i = 0, e = IdxList.size(); i != e; ++i)
1744 ArgVec.push_back(cast<Constant>(IdxList[i]));
1745 const ExprMapKeyType Key(Instruction::GetElementPtr,ArgVec);
1746 return ExprConstants->getOrCreate(ReqTy, Key);
1749 Constant *ConstantExpr::getGetElementPtr(Constant *C,
1750 const std::vector<Constant*> &IdxList){
1751 // Get the result type of the getelementptr!
1752 std::vector<Value*> VIdxList(IdxList.begin(), IdxList.end());
1754 const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), VIdxList,
1756 assert(Ty && "GEP indices invalid!");
1757 return getGetElementPtrTy(PointerType::get(Ty), C, VIdxList);
1760 Constant *ConstantExpr::getGetElementPtr(Constant *C,
1761 const std::vector<Value*> &IdxList) {
1762 // Get the result type of the getelementptr!
1763 const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), IdxList,
1765 assert(Ty && "GEP indices invalid!");
1766 return getGetElementPtrTy(PointerType::get(Ty), C, IdxList);
1770 ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1771 assert(LHS->getType() == RHS->getType());
1772 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
1773 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1775 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1776 return FC; // Fold a few common cases...
1778 // Look up the constant in the table first to ensure uniqueness
1779 std::vector<Constant*> ArgVec;
1780 ArgVec.push_back(LHS);
1781 ArgVec.push_back(RHS);
1782 // Get the key type with both the opcode and predicate
1783 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
1784 return ExprConstants->getOrCreate(Type::BoolTy, Key);
1788 ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1789 assert(LHS->getType() == RHS->getType());
1790 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1792 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1793 return FC; // Fold a few common cases...
1795 // Look up the constant in the table first to ensure uniqueness
1796 std::vector<Constant*> ArgVec;
1797 ArgVec.push_back(LHS);
1798 ArgVec.push_back(RHS);
1799 // Get the key type with both the opcode and predicate
1800 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
1801 return ExprConstants->getOrCreate(Type::BoolTy, Key);
1804 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
1806 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
1807 return FC; // Fold a few common cases...
1808 // Look up the constant in the table first to ensure uniqueness
1809 std::vector<Constant*> ArgVec(1, Val);
1810 ArgVec.push_back(Idx);
1811 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
1812 return ExprConstants->getOrCreate(ReqTy, Key);
1815 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
1816 assert(isa<PackedType>(Val->getType()) &&
1817 "Tried to create extractelement operation on non-packed type!");
1818 assert(Idx->getType() == Type::Int32Ty &&
1819 "Extractelement index must be uint type!");
1820 return getExtractElementTy(cast<PackedType>(Val->getType())->getElementType(),
1824 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
1825 Constant *Elt, Constant *Idx) {
1826 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
1827 return FC; // Fold a few common cases...
1828 // Look up the constant in the table first to ensure uniqueness
1829 std::vector<Constant*> ArgVec(1, Val);
1830 ArgVec.push_back(Elt);
1831 ArgVec.push_back(Idx);
1832 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
1833 return ExprConstants->getOrCreate(ReqTy, Key);
1836 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1838 assert(isa<PackedType>(Val->getType()) &&
1839 "Tried to create insertelement operation on non-packed type!");
1840 assert(Elt->getType() == cast<PackedType>(Val->getType())->getElementType()
1841 && "Insertelement types must match!");
1842 assert(Idx->getType() == Type::Int32Ty &&
1843 "Insertelement index must be uint type!");
1844 return getInsertElementTy(cast<PackedType>(Val->getType())->getElementType(),
1848 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
1849 Constant *V2, Constant *Mask) {
1850 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
1851 return FC; // Fold a few common cases...
1852 // Look up the constant in the table first to ensure uniqueness
1853 std::vector<Constant*> ArgVec(1, V1);
1854 ArgVec.push_back(V2);
1855 ArgVec.push_back(Mask);
1856 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
1857 return ExprConstants->getOrCreate(ReqTy, Key);
1860 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
1862 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1863 "Invalid shuffle vector constant expr operands!");
1864 return getShuffleVectorTy(V1->getType(), V1, V2, Mask);
1867 // destroyConstant - Remove the constant from the constant table...
1869 void ConstantExpr::destroyConstant() {
1870 ExprConstants->remove(this);
1871 destroyConstantImpl();
1874 const char *ConstantExpr::getOpcodeName() const {
1875 return Instruction::getOpcodeName(getOpcode());
1878 //===----------------------------------------------------------------------===//
1879 // replaceUsesOfWithOnConstant implementations
1881 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
1883 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1884 Constant *ToC = cast<Constant>(To);
1886 unsigned OperandToUpdate = U-OperandList;
1887 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
1889 std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
1890 Lookup.first.first = getType();
1891 Lookup.second = this;
1893 std::vector<Constant*> &Values = Lookup.first.second;
1894 Values.reserve(getNumOperands()); // Build replacement array.
1896 // Fill values with the modified operands of the constant array. Also,
1897 // compute whether this turns into an all-zeros array.
1898 bool isAllZeros = false;
1899 if (!ToC->isNullValue()) {
1900 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
1901 Values.push_back(cast<Constant>(O->get()));
1904 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1905 Constant *Val = cast<Constant>(O->get());
1906 Values.push_back(Val);
1907 if (isAllZeros) isAllZeros = Val->isNullValue();
1910 Values[OperandToUpdate] = ToC;
1912 Constant *Replacement = 0;
1914 Replacement = ConstantAggregateZero::get(getType());
1916 // Check to see if we have this array type already.
1918 ArrayConstantsTy::MapTy::iterator I =
1919 ArrayConstants->InsertOrGetItem(Lookup, Exists);
1922 Replacement = I->second;
1924 // Okay, the new shape doesn't exist in the system yet. Instead of
1925 // creating a new constant array, inserting it, replaceallusesof'ing the
1926 // old with the new, then deleting the old... just update the current one
1928 ArrayConstants->MoveConstantToNewSlot(this, I);
1930 // Update to the new value.
1931 setOperand(OperandToUpdate, ToC);
1936 // Otherwise, I do need to replace this with an existing value.
1937 assert(Replacement != this && "I didn't contain From!");
1939 // Everyone using this now uses the replacement.
1940 uncheckedReplaceAllUsesWith(Replacement);
1942 // Delete the old constant!
1946 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
1948 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1949 Constant *ToC = cast<Constant>(To);
1951 unsigned OperandToUpdate = U-OperandList;
1952 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
1954 std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
1955 Lookup.first.first = getType();
1956 Lookup.second = this;
1957 std::vector<Constant*> &Values = Lookup.first.second;
1958 Values.reserve(getNumOperands()); // Build replacement struct.
1961 // Fill values with the modified operands of the constant struct. Also,
1962 // compute whether this turns into an all-zeros struct.
1963 bool isAllZeros = false;
1964 if (!ToC->isNullValue()) {
1965 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
1966 Values.push_back(cast<Constant>(O->get()));
1969 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1970 Constant *Val = cast<Constant>(O->get());
1971 Values.push_back(Val);
1972 if (isAllZeros) isAllZeros = Val->isNullValue();
1975 Values[OperandToUpdate] = ToC;
1977 Constant *Replacement = 0;
1979 Replacement = ConstantAggregateZero::get(getType());
1981 // Check to see if we have this array type already.
1983 StructConstantsTy::MapTy::iterator I =
1984 StructConstants->InsertOrGetItem(Lookup, Exists);
1987 Replacement = I->second;
1989 // Okay, the new shape doesn't exist in the system yet. Instead of
1990 // creating a new constant struct, inserting it, replaceallusesof'ing the
1991 // old with the new, then deleting the old... just update the current one
1993 StructConstants->MoveConstantToNewSlot(this, I);
1995 // Update to the new value.
1996 setOperand(OperandToUpdate, ToC);
2001 assert(Replacement != this && "I didn't contain From!");
2003 // Everyone using this now uses the replacement.
2004 uncheckedReplaceAllUsesWith(Replacement);
2006 // Delete the old constant!
2010 void ConstantPacked::replaceUsesOfWithOnConstant(Value *From, Value *To,
2012 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2014 std::vector<Constant*> Values;
2015 Values.reserve(getNumOperands()); // Build replacement array...
2016 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2017 Constant *Val = getOperand(i);
2018 if (Val == From) Val = cast<Constant>(To);
2019 Values.push_back(Val);
2022 Constant *Replacement = ConstantPacked::get(getType(), Values);
2023 assert(Replacement != this && "I didn't contain From!");
2025 // Everyone using this now uses the replacement.
2026 uncheckedReplaceAllUsesWith(Replacement);
2028 // Delete the old constant!
2032 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2034 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2035 Constant *To = cast<Constant>(ToV);
2037 Constant *Replacement = 0;
2038 if (getOpcode() == Instruction::GetElementPtr) {
2039 std::vector<Constant*> Indices;
2040 Constant *Pointer = getOperand(0);
2041 Indices.reserve(getNumOperands()-1);
2042 if (Pointer == From) Pointer = To;
2044 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2045 Constant *Val = getOperand(i);
2046 if (Val == From) Val = To;
2047 Indices.push_back(Val);
2049 Replacement = ConstantExpr::getGetElementPtr(Pointer, Indices);
2050 } else if (isCast()) {
2051 assert(getOperand(0) == From && "Cast only has one use!");
2052 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
2053 } else if (getOpcode() == Instruction::Select) {
2054 Constant *C1 = getOperand(0);
2055 Constant *C2 = getOperand(1);
2056 Constant *C3 = getOperand(2);
2057 if (C1 == From) C1 = To;
2058 if (C2 == From) C2 = To;
2059 if (C3 == From) C3 = To;
2060 Replacement = ConstantExpr::getSelect(C1, C2, C3);
2061 } else if (getOpcode() == Instruction::ExtractElement) {
2062 Constant *C1 = getOperand(0);
2063 Constant *C2 = getOperand(1);
2064 if (C1 == From) C1 = To;
2065 if (C2 == From) C2 = To;
2066 Replacement = ConstantExpr::getExtractElement(C1, C2);
2067 } else if (getOpcode() == Instruction::InsertElement) {
2068 Constant *C1 = getOperand(0);
2069 Constant *C2 = getOperand(1);
2070 Constant *C3 = getOperand(1);
2071 if (C1 == From) C1 = To;
2072 if (C2 == From) C2 = To;
2073 if (C3 == From) C3 = To;
2074 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2075 } else if (getOpcode() == Instruction::ShuffleVector) {
2076 Constant *C1 = getOperand(0);
2077 Constant *C2 = getOperand(1);
2078 Constant *C3 = getOperand(2);
2079 if (C1 == From) C1 = To;
2080 if (C2 == From) C2 = To;
2081 if (C3 == From) C3 = To;
2082 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2083 } else if (isCompare()) {
2084 Constant *C1 = getOperand(0);
2085 Constant *C2 = getOperand(1);
2086 if (C1 == From) C1 = To;
2087 if (C2 == From) C2 = To;
2088 if (getOpcode() == Instruction::ICmp)
2089 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2091 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2092 } else if (getNumOperands() == 2) {
2093 Constant *C1 = getOperand(0);
2094 Constant *C2 = getOperand(1);
2095 if (C1 == From) C1 = To;
2096 if (C2 == From) C2 = To;
2097 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2099 assert(0 && "Unknown ConstantExpr type!");
2103 assert(Replacement != this && "I didn't contain From!");
2105 // Everyone using this now uses the replacement.
2106 uncheckedReplaceAllUsesWith(Replacement);
2108 // Delete the old constant!
2113 /// getStringValue - Turn an LLVM constant pointer that eventually points to a
2114 /// global into a string value. Return an empty string if we can't do it.
2115 /// Parameter Chop determines if the result is chopped at the first null
2118 std::string Constant::getStringValue(bool Chop, unsigned Offset) {
2119 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(this)) {
2120 if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
2121 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
2122 if (Init->isString()) {
2123 std::string Result = Init->getAsString();
2124 if (Offset < Result.size()) {
2125 // If we are pointing INTO The string, erase the beginning...
2126 Result.erase(Result.begin(), Result.begin()+Offset);
2128 // Take off the null terminator, and any string fragments after it.
2130 std::string::size_type NullPos = Result.find_first_of((char)0);
2131 if (NullPos != std::string::npos)
2132 Result.erase(Result.begin()+NullPos, Result.end());
2138 } else if (Constant *C = dyn_cast<Constant>(this)) {
2139 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
2140 return GV->getStringValue(Chop, Offset);
2141 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2142 if (CE->getOpcode() == Instruction::GetElementPtr) {
2143 // Turn a gep into the specified offset.
2144 if (CE->getNumOperands() == 3 &&
2145 cast<Constant>(CE->getOperand(1))->isNullValue() &&
2146 isa<ConstantInt>(CE->getOperand(2))) {
2147 Offset += cast<ConstantInt>(CE->getOperand(2))->getZExtValue();
2148 return CE->getOperand(0)->getStringValue(Chop, Offset);