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 /// @returns the value for an packed integer constant of the given type that
150 /// has all its bits set to true.
151 /// @brief Get the all ones value
152 ConstantPacked *ConstantPacked::getAllOnesValue(const PackedType *Ty) {
153 std::vector<Constant*> Elts;
154 Elts.resize(Ty->getNumElements(),
155 ConstantIntegral::getAllOnesValue(Ty->getElementType()));
156 assert(Elts[0] && "Not a packed integer type!");
157 return cast<ConstantPacked>(ConstantPacked::get(Elts));
161 //===----------------------------------------------------------------------===//
162 // ConstantXXX Classes
163 //===----------------------------------------------------------------------===//
165 //===----------------------------------------------------------------------===//
166 // Normal Constructors
168 ConstantIntegral::ConstantIntegral(const Type *Ty, ValueTy VT, uint64_t V)
169 : Constant(Ty, VT, 0, 0), Val(V) {
172 ConstantBool::ConstantBool(bool V)
173 : ConstantIntegral(Type::BoolTy, ConstantBoolVal, uint64_t(V)) {
176 ConstantInt::ConstantInt(const Type *Ty, uint64_t V)
177 : ConstantIntegral(Ty, ConstantIntVal, V) {
180 ConstantFP::ConstantFP(const Type *Ty, double V)
181 : Constant(Ty, ConstantFPVal, 0, 0) {
182 assert(isValueValidForType(Ty, V) && "Value too large for type!");
186 ConstantArray::ConstantArray(const ArrayType *T,
187 const std::vector<Constant*> &V)
188 : Constant(T, ConstantArrayVal, new Use[V.size()], V.size()) {
189 assert(V.size() == T->getNumElements() &&
190 "Invalid initializer vector for constant array");
191 Use *OL = OperandList;
192 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
195 assert((C->getType() == T->getElementType() ||
197 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
198 "Initializer for array element doesn't match array element type!");
203 ConstantArray::~ConstantArray() {
204 delete [] OperandList;
207 ConstantStruct::ConstantStruct(const StructType *T,
208 const std::vector<Constant*> &V)
209 : Constant(T, ConstantStructVal, new Use[V.size()], V.size()) {
210 assert(V.size() == T->getNumElements() &&
211 "Invalid initializer vector for constant structure");
212 Use *OL = OperandList;
213 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
216 assert((C->getType() == T->getElementType(I-V.begin()) ||
217 ((T->getElementType(I-V.begin())->isAbstract() ||
218 C->getType()->isAbstract()) &&
219 T->getElementType(I-V.begin())->getTypeID() ==
220 C->getType()->getTypeID())) &&
221 "Initializer for struct element doesn't match struct element type!");
226 ConstantStruct::~ConstantStruct() {
227 delete [] OperandList;
231 ConstantPacked::ConstantPacked(const PackedType *T,
232 const std::vector<Constant*> &V)
233 : Constant(T, ConstantPackedVal, new Use[V.size()], V.size()) {
234 Use *OL = OperandList;
235 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
238 assert((C->getType() == T->getElementType() ||
240 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
241 "Initializer for packed element doesn't match packed element type!");
246 ConstantPacked::~ConstantPacked() {
247 delete [] OperandList;
250 // We declare several classes private to this file, so use an anonymous
254 /// UnaryConstantExpr - This class is private to Constants.cpp, and is used
255 /// behind the scenes to implement unary constant exprs.
256 class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
259 UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
260 : ConstantExpr(Ty, Opcode, &Op, 1), Op(C, this) {}
263 /// BinaryConstantExpr - This class is private to Constants.cpp, and is used
264 /// behind the scenes to implement binary constant exprs.
265 class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
268 BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
269 : ConstantExpr(C1->getType(), Opcode, Ops, 2) {
270 Ops[0].init(C1, this);
271 Ops[1].init(C2, this);
275 /// SelectConstantExpr - This class is private to Constants.cpp, and is used
276 /// behind the scenes to implement select constant exprs.
277 class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
280 SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
281 : ConstantExpr(C2->getType(), Instruction::Select, Ops, 3) {
282 Ops[0].init(C1, this);
283 Ops[1].init(C2, this);
284 Ops[2].init(C3, this);
288 /// ExtractElementConstantExpr - This class is private to
289 /// Constants.cpp, and is used behind the scenes to implement
290 /// extractelement constant exprs.
291 class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
294 ExtractElementConstantExpr(Constant *C1, Constant *C2)
295 : ConstantExpr(cast<PackedType>(C1->getType())->getElementType(),
296 Instruction::ExtractElement, Ops, 2) {
297 Ops[0].init(C1, this);
298 Ops[1].init(C2, this);
302 /// InsertElementConstantExpr - This class is private to
303 /// Constants.cpp, and is used behind the scenes to implement
304 /// insertelement constant exprs.
305 class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
308 InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
309 : ConstantExpr(C1->getType(), Instruction::InsertElement,
311 Ops[0].init(C1, this);
312 Ops[1].init(C2, this);
313 Ops[2].init(C3, this);
317 /// ShuffleVectorConstantExpr - This class is private to
318 /// Constants.cpp, and is used behind the scenes to implement
319 /// shufflevector constant exprs.
320 class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
323 ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
324 : ConstantExpr(C1->getType(), Instruction::ShuffleVector,
326 Ops[0].init(C1, this);
327 Ops[1].init(C2, this);
328 Ops[2].init(C3, this);
332 /// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
333 /// used behind the scenes to implement getelementpr constant exprs.
334 struct VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
335 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
337 : ConstantExpr(DestTy, Instruction::GetElementPtr,
338 new Use[IdxList.size()+1], IdxList.size()+1) {
339 OperandList[0].init(C, this);
340 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
341 OperandList[i+1].init(IdxList[i], this);
343 ~GetElementPtrConstantExpr() {
344 delete [] OperandList;
348 // CompareConstantExpr - This class is private to Constants.cpp, and is used
349 // behind the scenes to implement ICmp and FCmp constant expressions. This is
350 // needed in order to store the predicate value for these instructions.
351 struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
352 unsigned short predicate;
354 CompareConstantExpr(Instruction::OtherOps opc, unsigned short pred,
355 Constant* LHS, Constant* RHS)
356 : ConstantExpr(Type::BoolTy, opc, Ops, 2), predicate(pred) {
357 OperandList[0].init(LHS, this);
358 OperandList[1].init(RHS, this);
362 } // end anonymous namespace
365 // Utility function for determining if a ConstantExpr is a CastOp or not. This
366 // can't be inline because we don't want to #include Instruction.h into
368 bool ConstantExpr::isCast() const {
369 return Instruction::isCast(getOpcode());
372 bool ConstantExpr::isCompare() const {
373 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
376 /// ConstantExpr::get* - Return some common constants without having to
377 /// specify the full Instruction::OPCODE identifier.
379 Constant *ConstantExpr::getNeg(Constant *C) {
380 if (!C->getType()->isFloatingPoint())
381 return get(Instruction::Sub, getNullValue(C->getType()), C);
383 return get(Instruction::Sub, ConstantFP::get(C->getType(), -0.0), C);
385 Constant *ConstantExpr::getNot(Constant *C) {
386 assert(isa<ConstantIntegral>(C) && "Cannot NOT a nonintegral type!");
387 return get(Instruction::Xor, C,
388 ConstantIntegral::getAllOnesValue(C->getType()));
390 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
391 return get(Instruction::Add, C1, C2);
393 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
394 return get(Instruction::Sub, C1, C2);
396 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
397 return get(Instruction::Mul, C1, C2);
399 Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2) {
400 return get(Instruction::UDiv, C1, C2);
402 Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2) {
403 return get(Instruction::SDiv, C1, C2);
405 Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
406 return get(Instruction::FDiv, C1, C2);
408 Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
409 return get(Instruction::URem, C1, C2);
411 Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
412 return get(Instruction::SRem, C1, C2);
414 Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
415 return get(Instruction::FRem, C1, C2);
417 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
418 return get(Instruction::And, C1, C2);
420 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
421 return get(Instruction::Or, C1, C2);
423 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
424 return get(Instruction::Xor, C1, C2);
426 unsigned ConstantExpr::getPredicate() const {
427 assert(getOpcode() == Instruction::FCmp || getOpcode() == Instruction::ICmp);
428 return dynamic_cast<const CompareConstantExpr*>(this)->predicate;
430 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
431 return get(Instruction::Shl, C1, C2);
433 Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2) {
434 return get(Instruction::LShr, C1, C2);
436 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2) {
437 return get(Instruction::AShr, C1, C2);
440 /// getWithOperandReplaced - Return a constant expression identical to this
441 /// one, but with the specified operand set to the specified value.
443 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
444 assert(OpNo < getNumOperands() && "Operand num is out of range!");
445 assert(Op->getType() == getOperand(OpNo)->getType() &&
446 "Replacing operand with value of different type!");
447 if (getOperand(OpNo) == Op)
448 return const_cast<ConstantExpr*>(this);
450 Constant *Op0, *Op1, *Op2;
451 switch (getOpcode()) {
452 case Instruction::Trunc:
453 case Instruction::ZExt:
454 case Instruction::SExt:
455 case Instruction::FPTrunc:
456 case Instruction::FPExt:
457 case Instruction::UIToFP:
458 case Instruction::SIToFP:
459 case Instruction::FPToUI:
460 case Instruction::FPToSI:
461 case Instruction::PtrToInt:
462 case Instruction::IntToPtr:
463 case Instruction::BitCast:
464 return ConstantExpr::getCast(getOpcode(), Op, getType());
465 case Instruction::Select:
466 Op0 = (OpNo == 0) ? Op : getOperand(0);
467 Op1 = (OpNo == 1) ? Op : getOperand(1);
468 Op2 = (OpNo == 2) ? Op : getOperand(2);
469 return ConstantExpr::getSelect(Op0, Op1, Op2);
470 case Instruction::InsertElement:
471 Op0 = (OpNo == 0) ? Op : getOperand(0);
472 Op1 = (OpNo == 1) ? Op : getOperand(1);
473 Op2 = (OpNo == 2) ? Op : getOperand(2);
474 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
475 case Instruction::ExtractElement:
476 Op0 = (OpNo == 0) ? Op : getOperand(0);
477 Op1 = (OpNo == 1) ? Op : getOperand(1);
478 return ConstantExpr::getExtractElement(Op0, Op1);
479 case Instruction::ShuffleVector:
480 Op0 = (OpNo == 0) ? Op : getOperand(0);
481 Op1 = (OpNo == 1) ? Op : getOperand(1);
482 Op2 = (OpNo == 2) ? Op : getOperand(2);
483 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
484 case Instruction::GetElementPtr: {
485 std::vector<Constant*> Ops;
486 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
487 Ops.push_back(getOperand(i));
489 return ConstantExpr::getGetElementPtr(Op, Ops);
491 return ConstantExpr::getGetElementPtr(getOperand(0), Ops);
494 assert(getNumOperands() == 2 && "Must be binary operator?");
495 Op0 = (OpNo == 0) ? Op : getOperand(0);
496 Op1 = (OpNo == 1) ? Op : getOperand(1);
497 return ConstantExpr::get(getOpcode(), Op0, Op1);
501 /// getWithOperands - This returns the current constant expression with the
502 /// operands replaced with the specified values. The specified operands must
503 /// match count and type with the existing ones.
504 Constant *ConstantExpr::
505 getWithOperands(const std::vector<Constant*> &Ops) const {
506 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
507 bool AnyChange = false;
508 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
509 assert(Ops[i]->getType() == getOperand(i)->getType() &&
510 "Operand type mismatch!");
511 AnyChange |= Ops[i] != getOperand(i);
513 if (!AnyChange) // No operands changed, return self.
514 return const_cast<ConstantExpr*>(this);
516 switch (getOpcode()) {
517 case Instruction::Trunc:
518 case Instruction::ZExt:
519 case Instruction::SExt:
520 case Instruction::FPTrunc:
521 case Instruction::FPExt:
522 case Instruction::UIToFP:
523 case Instruction::SIToFP:
524 case Instruction::FPToUI:
525 case Instruction::FPToSI:
526 case Instruction::PtrToInt:
527 case Instruction::IntToPtr:
528 case Instruction::BitCast:
529 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
530 case Instruction::Select:
531 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
532 case Instruction::InsertElement:
533 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
534 case Instruction::ExtractElement:
535 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
536 case Instruction::ShuffleVector:
537 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
538 case Instruction::GetElementPtr: {
539 std::vector<Constant*> ActualOps(Ops.begin()+1, Ops.end());
540 return ConstantExpr::getGetElementPtr(Ops[0], ActualOps);
542 case Instruction::ICmp:
543 case Instruction::FCmp:
544 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
546 assert(getNumOperands() == 2 && "Must be binary operator?");
547 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
552 //===----------------------------------------------------------------------===//
553 // isValueValidForType implementations
555 bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
556 switch (Ty->getTypeID()) {
557 default: return false; // These can't be represented as integers!
558 case Type::Int8TyID: return Val <= UINT8_MAX;
559 case Type::Int16TyID: return Val <= UINT16_MAX;
560 case Type::Int32TyID: return Val <= UINT32_MAX;
561 case Type::Int64TyID: return true; // always true, has to fit in largest type
565 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
566 switch (Ty->getTypeID()) {
567 default: return false; // These can't be represented as integers!
568 case Type::Int8TyID: return (Val >= INT8_MIN && Val <= INT8_MAX);
569 case Type::Int16TyID: return (Val >= INT16_MIN && Val <= UINT16_MAX);
570 case Type::Int32TyID: return (Val >= INT32_MIN && Val <= UINT32_MAX);
571 case Type::Int64TyID: return true; // always true, has to fit in largest type
575 bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
576 switch (Ty->getTypeID()) {
578 return false; // These can't be represented as floating point!
580 // TODO: Figure out how to test if a double can be cast to a float!
581 case Type::FloatTyID:
582 case Type::DoubleTyID:
583 return true; // This is the largest type...
587 //===----------------------------------------------------------------------===//
588 // Factory Function Implementation
590 // ConstantCreator - A class that is used to create constants by
591 // ValueMap*. This class should be partially specialized if there is
592 // something strange that needs to be done to interface to the ctor for the
596 template<class ConstantClass, class TypeClass, class ValType>
597 struct VISIBILITY_HIDDEN ConstantCreator {
598 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
599 return new ConstantClass(Ty, V);
603 template<class ConstantClass, class TypeClass>
604 struct VISIBILITY_HIDDEN ConvertConstantType {
605 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
606 assert(0 && "This type cannot be converted!\n");
611 template<class ValType, class TypeClass, class ConstantClass,
612 bool HasLargeKey = false /*true for arrays and structs*/ >
613 class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
615 typedef std::pair<const Type*, ValType> MapKey;
616 typedef std::map<MapKey, Constant *> MapTy;
617 typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
618 typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
620 /// Map - This is the main map from the element descriptor to the Constants.
621 /// This is the primary way we avoid creating two of the same shape
625 /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
626 /// from the constants to their element in Map. This is important for
627 /// removal of constants from the array, which would otherwise have to scan
628 /// through the map with very large keys.
629 InverseMapTy InverseMap;
631 /// AbstractTypeMap - Map for abstract type constants.
633 AbstractTypeMapTy AbstractTypeMap;
636 void clear(std::vector<Constant *> &Constants) {
637 for(typename MapTy::iterator I = Map.begin(); I != Map.end(); ++I)
638 Constants.push_back(I->second);
640 AbstractTypeMap.clear();
645 typename MapTy::iterator map_end() { return Map.end(); }
647 /// InsertOrGetItem - Return an iterator for the specified element.
648 /// If the element exists in the map, the returned iterator points to the
649 /// entry and Exists=true. If not, the iterator points to the newly
650 /// inserted entry and returns Exists=false. Newly inserted entries have
651 /// I->second == 0, and should be filled in.
652 typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
655 std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
661 typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
663 typename InverseMapTy::iterator IMI = InverseMap.find(CP);
664 assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
665 IMI->second->second == CP &&
666 "InverseMap corrupt!");
670 typename MapTy::iterator I =
671 Map.find(MapKey((TypeClass*)CP->getRawType(), getValType(CP)));
672 if (I == Map.end() || I->second != CP) {
673 // FIXME: This should not use a linear scan. If this gets to be a
674 // performance problem, someone should look at this.
675 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
682 /// getOrCreate - Return the specified constant from the map, creating it if
684 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
685 MapKey Lookup(Ty, V);
686 typename MapTy::iterator I = Map.lower_bound(Lookup);
688 if (I != Map.end() && I->first == Lookup)
689 return static_cast<ConstantClass *>(I->second);
691 // If no preexisting value, create one now...
692 ConstantClass *Result =
693 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
695 /// FIXME: why does this assert fail when loading 176.gcc?
696 //assert(Result->getType() == Ty && "Type specified is not correct!");
697 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
699 if (HasLargeKey) // Remember the reverse mapping if needed.
700 InverseMap.insert(std::make_pair(Result, I));
702 // If the type of the constant is abstract, make sure that an entry exists
703 // for it in the AbstractTypeMap.
704 if (Ty->isAbstract()) {
705 typename AbstractTypeMapTy::iterator TI =
706 AbstractTypeMap.lower_bound(Ty);
708 if (TI == AbstractTypeMap.end() || TI->first != Ty) {
709 // Add ourselves to the ATU list of the type.
710 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
712 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
718 void remove(ConstantClass *CP) {
719 typename MapTy::iterator I = FindExistingElement(CP);
720 assert(I != Map.end() && "Constant not found in constant table!");
721 assert(I->second == CP && "Didn't find correct element?");
723 if (HasLargeKey) // Remember the reverse mapping if needed.
724 InverseMap.erase(CP);
726 // Now that we found the entry, make sure this isn't the entry that
727 // the AbstractTypeMap points to.
728 const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
729 if (Ty->isAbstract()) {
730 assert(AbstractTypeMap.count(Ty) &&
731 "Abstract type not in AbstractTypeMap?");
732 typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
733 if (ATMEntryIt == I) {
734 // Yes, we are removing the representative entry for this type.
735 // See if there are any other entries of the same type.
736 typename MapTy::iterator TmpIt = ATMEntryIt;
738 // First check the entry before this one...
739 if (TmpIt != Map.begin()) {
741 if (TmpIt->first.first != Ty) // Not the same type, move back...
745 // If we didn't find the same type, try to move forward...
746 if (TmpIt == ATMEntryIt) {
748 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
749 --TmpIt; // No entry afterwards with the same type
752 // If there is another entry in the map of the same abstract type,
753 // update the AbstractTypeMap entry now.
754 if (TmpIt != ATMEntryIt) {
757 // Otherwise, we are removing the last instance of this type
758 // from the table. Remove from the ATM, and from user list.
759 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
760 AbstractTypeMap.erase(Ty);
769 /// MoveConstantToNewSlot - If we are about to change C to be the element
770 /// specified by I, update our internal data structures to reflect this
772 void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
773 // First, remove the old location of the specified constant in the map.
774 typename MapTy::iterator OldI = FindExistingElement(C);
775 assert(OldI != Map.end() && "Constant not found in constant table!");
776 assert(OldI->second == C && "Didn't find correct element?");
778 // If this constant is the representative element for its abstract type,
779 // update the AbstractTypeMap so that the representative element is I.
780 if (C->getType()->isAbstract()) {
781 typename AbstractTypeMapTy::iterator ATI =
782 AbstractTypeMap.find(C->getType());
783 assert(ATI != AbstractTypeMap.end() &&
784 "Abstract type not in AbstractTypeMap?");
785 if (ATI->second == OldI)
789 // Remove the old entry from the map.
792 // Update the inverse map so that we know that this constant is now
793 // located at descriptor I.
795 assert(I->second == C && "Bad inversemap entry!");
800 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
801 typename AbstractTypeMapTy::iterator I =
802 AbstractTypeMap.find(cast<Type>(OldTy));
804 assert(I != AbstractTypeMap.end() &&
805 "Abstract type not in AbstractTypeMap?");
807 // Convert a constant at a time until the last one is gone. The last one
808 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
809 // eliminated eventually.
811 ConvertConstantType<ConstantClass,
813 static_cast<ConstantClass *>(I->second->second),
814 cast<TypeClass>(NewTy));
816 I = AbstractTypeMap.find(cast<Type>(OldTy));
817 } while (I != AbstractTypeMap.end());
820 // If the type became concrete without being refined to any other existing
821 // type, we just remove ourselves from the ATU list.
822 void typeBecameConcrete(const DerivedType *AbsTy) {
823 AbsTy->removeAbstractTypeUser(this);
827 DOUT << "Constant.cpp: ValueMap\n";
833 //---- ConstantBool::get*() implementation.
835 ConstantBool *ConstantBool::getTrue() {
836 static ConstantBool *T = 0;
838 return T = new ConstantBool(true);
840 ConstantBool *ConstantBool::getFalse() {
841 static ConstantBool *F = 0;
843 return F = new ConstantBool(false);
846 //---- ConstantInt::get() implementations...
848 static ManagedStatic<ValueMap<uint64_t, Type, ConstantInt> > IntConstants;
850 // Get a ConstantInt from an int64_t. Note here that we canoncialize the value
851 // to a uint64_t value that has been zero extended down to the size of the
852 // integer type of the ConstantInt. This allows the getZExtValue method to
853 // just return the stored value while getSExtValue has to convert back to sign
854 // extended. getZExtValue is more common in LLVM than getSExtValue().
855 ConstantInt *ConstantInt::get(const Type *Ty, int64_t V) {
856 return IntConstants->getOrCreate(Ty, V & Ty->getIntegralTypeMask());
859 ConstantIntegral *ConstantIntegral::get(const Type *Ty, int64_t V) {
860 if (Ty == Type::BoolTy) return ConstantBool::get(V&1);
861 return IntConstants->getOrCreate(Ty, V & Ty->getIntegralTypeMask());
864 //---- ConstantFP::get() implementation...
868 struct ConstantCreator<ConstantFP, Type, uint64_t> {
869 static ConstantFP *create(const Type *Ty, uint64_t V) {
870 assert(Ty == Type::DoubleTy);
871 return new ConstantFP(Ty, BitsToDouble(V));
875 struct ConstantCreator<ConstantFP, Type, uint32_t> {
876 static ConstantFP *create(const Type *Ty, uint32_t V) {
877 assert(Ty == Type::FloatTy);
878 return new ConstantFP(Ty, BitsToFloat(V));
883 static ManagedStatic<ValueMap<uint64_t, Type, ConstantFP> > DoubleConstants;
884 static ManagedStatic<ValueMap<uint32_t, Type, ConstantFP> > FloatConstants;
886 bool ConstantFP::isNullValue() const {
887 return DoubleToBits(Val) == 0;
890 bool ConstantFP::isExactlyValue(double V) const {
891 return DoubleToBits(V) == DoubleToBits(Val);
895 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
896 if (Ty == Type::FloatTy) {
897 // Force the value through memory to normalize it.
898 return FloatConstants->getOrCreate(Ty, FloatToBits(V));
900 assert(Ty == Type::DoubleTy);
901 return DoubleConstants->getOrCreate(Ty, DoubleToBits(V));
905 //---- ConstantAggregateZero::get() implementation...
908 // ConstantAggregateZero does not take extra "value" argument...
909 template<class ValType>
910 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
911 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
912 return new ConstantAggregateZero(Ty);
917 struct ConvertConstantType<ConstantAggregateZero, Type> {
918 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
919 // Make everyone now use a constant of the new type...
920 Constant *New = ConstantAggregateZero::get(NewTy);
921 assert(New != OldC && "Didn't replace constant??");
922 OldC->uncheckedReplaceAllUsesWith(New);
923 OldC->destroyConstant(); // This constant is now dead, destroy it.
928 static ManagedStatic<ValueMap<char, Type,
929 ConstantAggregateZero> > AggZeroConstants;
931 static char getValType(ConstantAggregateZero *CPZ) { return 0; }
933 Constant *ConstantAggregateZero::get(const Type *Ty) {
934 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<PackedType>(Ty)) &&
935 "Cannot create an aggregate zero of non-aggregate type!");
936 return AggZeroConstants->getOrCreate(Ty, 0);
939 // destroyConstant - Remove the constant from the constant table...
941 void ConstantAggregateZero::destroyConstant() {
942 AggZeroConstants->remove(this);
943 destroyConstantImpl();
946 //---- ConstantArray::get() implementation...
950 struct ConvertConstantType<ConstantArray, ArrayType> {
951 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
952 // Make everyone now use a constant of the new type...
953 std::vector<Constant*> C;
954 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
955 C.push_back(cast<Constant>(OldC->getOperand(i)));
956 Constant *New = ConstantArray::get(NewTy, C);
957 assert(New != OldC && "Didn't replace constant??");
958 OldC->uncheckedReplaceAllUsesWith(New);
959 OldC->destroyConstant(); // This constant is now dead, destroy it.
964 static std::vector<Constant*> getValType(ConstantArray *CA) {
965 std::vector<Constant*> Elements;
966 Elements.reserve(CA->getNumOperands());
967 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
968 Elements.push_back(cast<Constant>(CA->getOperand(i)));
972 typedef ValueMap<std::vector<Constant*>, ArrayType,
973 ConstantArray, true /*largekey*/> ArrayConstantsTy;
974 static ManagedStatic<ArrayConstantsTy> ArrayConstants;
976 Constant *ConstantArray::get(const ArrayType *Ty,
977 const std::vector<Constant*> &V) {
978 // If this is an all-zero array, return a ConstantAggregateZero object
981 if (!C->isNullValue())
982 return ArrayConstants->getOrCreate(Ty, V);
983 for (unsigned i = 1, e = V.size(); i != e; ++i)
985 return ArrayConstants->getOrCreate(Ty, V);
987 return ConstantAggregateZero::get(Ty);
990 // destroyConstant - Remove the constant from the constant table...
992 void ConstantArray::destroyConstant() {
993 ArrayConstants->remove(this);
994 destroyConstantImpl();
997 /// ConstantArray::get(const string&) - Return an array that is initialized to
998 /// contain the specified string. If length is zero then a null terminator is
999 /// added to the specified string so that it may be used in a natural way.
1000 /// Otherwise, the length parameter specifies how much of the string to use
1001 /// and it won't be null terminated.
1003 Constant *ConstantArray::get(const std::string &Str, bool AddNull) {
1004 std::vector<Constant*> ElementVals;
1005 for (unsigned i = 0; i < Str.length(); ++i)
1006 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, Str[i]));
1008 // Add a null terminator to the string...
1010 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, 0));
1013 ArrayType *ATy = ArrayType::get(Type::Int8Ty, ElementVals.size());
1014 return ConstantArray::get(ATy, ElementVals);
1017 /// isString - This method returns true if the array is an array of sbyte or
1018 /// ubyte, and if the elements of the array are all ConstantInt's.
1019 bool ConstantArray::isString() const {
1020 // Check the element type for sbyte or ubyte...
1021 if (getType()->getElementType() != Type::Int8Ty)
1023 // Check the elements to make sure they are all integers, not constant
1025 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1026 if (!isa<ConstantInt>(getOperand(i)))
1031 /// isCString - This method returns true if the array is a string (see
1032 /// isString) and it ends in a null byte \0 and does not contains any other
1033 /// null bytes except its terminator.
1034 bool ConstantArray::isCString() const {
1035 // Check the element type for sbyte or ubyte...
1036 if (getType()->getElementType() != Type::Int8Ty)
1038 Constant *Zero = Constant::getNullValue(getOperand(0)->getType());
1039 // Last element must be a null.
1040 if (getOperand(getNumOperands()-1) != Zero)
1042 // Other elements must be non-null integers.
1043 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1044 if (!isa<ConstantInt>(getOperand(i)))
1046 if (getOperand(i) == Zero)
1053 // getAsString - If the sub-element type of this array is either sbyte or ubyte,
1054 // then this method converts the array to an std::string and returns it.
1055 // Otherwise, it asserts out.
1057 std::string ConstantArray::getAsString() const {
1058 assert(isString() && "Not a string!");
1060 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1061 Result += (char)cast<ConstantInt>(getOperand(i))->getZExtValue();
1066 //---- ConstantStruct::get() implementation...
1071 struct ConvertConstantType<ConstantStruct, StructType> {
1072 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1073 // Make everyone now use a constant of the new type...
1074 std::vector<Constant*> C;
1075 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1076 C.push_back(cast<Constant>(OldC->getOperand(i)));
1077 Constant *New = ConstantStruct::get(NewTy, C);
1078 assert(New != OldC && "Didn't replace constant??");
1080 OldC->uncheckedReplaceAllUsesWith(New);
1081 OldC->destroyConstant(); // This constant is now dead, destroy it.
1086 typedef ValueMap<std::vector<Constant*>, StructType,
1087 ConstantStruct, true /*largekey*/> StructConstantsTy;
1088 static ManagedStatic<StructConstantsTy> StructConstants;
1090 static std::vector<Constant*> getValType(ConstantStruct *CS) {
1091 std::vector<Constant*> Elements;
1092 Elements.reserve(CS->getNumOperands());
1093 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1094 Elements.push_back(cast<Constant>(CS->getOperand(i)));
1098 Constant *ConstantStruct::get(const StructType *Ty,
1099 const std::vector<Constant*> &V) {
1100 // Create a ConstantAggregateZero value if all elements are zeros...
1101 for (unsigned i = 0, e = V.size(); i != e; ++i)
1102 if (!V[i]->isNullValue())
1103 return StructConstants->getOrCreate(Ty, V);
1105 return ConstantAggregateZero::get(Ty);
1108 Constant *ConstantStruct::get(const std::vector<Constant*> &V, bool packed) {
1109 std::vector<const Type*> StructEls;
1110 StructEls.reserve(V.size());
1111 for (unsigned i = 0, e = V.size(); i != e; ++i)
1112 StructEls.push_back(V[i]->getType());
1113 return get(StructType::get(StructEls, packed), V);
1116 // destroyConstant - Remove the constant from the constant table...
1118 void ConstantStruct::destroyConstant() {
1119 StructConstants->remove(this);
1120 destroyConstantImpl();
1123 //---- ConstantPacked::get() implementation...
1127 struct ConvertConstantType<ConstantPacked, PackedType> {
1128 static void convert(ConstantPacked *OldC, const PackedType *NewTy) {
1129 // Make everyone now use a constant of the new type...
1130 std::vector<Constant*> C;
1131 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1132 C.push_back(cast<Constant>(OldC->getOperand(i)));
1133 Constant *New = ConstantPacked::get(NewTy, C);
1134 assert(New != OldC && "Didn't replace constant??");
1135 OldC->uncheckedReplaceAllUsesWith(New);
1136 OldC->destroyConstant(); // This constant is now dead, destroy it.
1141 static std::vector<Constant*> getValType(ConstantPacked *CP) {
1142 std::vector<Constant*> Elements;
1143 Elements.reserve(CP->getNumOperands());
1144 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1145 Elements.push_back(CP->getOperand(i));
1149 static ManagedStatic<ValueMap<std::vector<Constant*>, PackedType,
1150 ConstantPacked> > PackedConstants;
1152 Constant *ConstantPacked::get(const PackedType *Ty,
1153 const std::vector<Constant*> &V) {
1154 // If this is an all-zero packed, return a ConstantAggregateZero object
1157 if (!C->isNullValue())
1158 return PackedConstants->getOrCreate(Ty, V);
1159 for (unsigned i = 1, e = V.size(); i != e; ++i)
1161 return PackedConstants->getOrCreate(Ty, V);
1163 return ConstantAggregateZero::get(Ty);
1166 Constant *ConstantPacked::get(const std::vector<Constant*> &V) {
1167 assert(!V.empty() && "Cannot infer type if V is empty");
1168 return get(PackedType::get(V.front()->getType(),V.size()), V);
1171 // destroyConstant - Remove the constant from the constant table...
1173 void ConstantPacked::destroyConstant() {
1174 PackedConstants->remove(this);
1175 destroyConstantImpl();
1178 //---- ConstantPointerNull::get() implementation...
1182 // ConstantPointerNull does not take extra "value" argument...
1183 template<class ValType>
1184 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1185 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1186 return new ConstantPointerNull(Ty);
1191 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1192 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1193 // Make everyone now use a constant of the new type...
1194 Constant *New = ConstantPointerNull::get(NewTy);
1195 assert(New != OldC && "Didn't replace constant??");
1196 OldC->uncheckedReplaceAllUsesWith(New);
1197 OldC->destroyConstant(); // This constant is now dead, destroy it.
1202 static ManagedStatic<ValueMap<char, PointerType,
1203 ConstantPointerNull> > NullPtrConstants;
1205 static char getValType(ConstantPointerNull *) {
1210 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1211 return NullPtrConstants->getOrCreate(Ty, 0);
1214 // destroyConstant - Remove the constant from the constant table...
1216 void ConstantPointerNull::destroyConstant() {
1217 NullPtrConstants->remove(this);
1218 destroyConstantImpl();
1222 //---- UndefValue::get() implementation...
1226 // UndefValue does not take extra "value" argument...
1227 template<class ValType>
1228 struct ConstantCreator<UndefValue, Type, ValType> {
1229 static UndefValue *create(const Type *Ty, const ValType &V) {
1230 return new UndefValue(Ty);
1235 struct ConvertConstantType<UndefValue, Type> {
1236 static void convert(UndefValue *OldC, const Type *NewTy) {
1237 // Make everyone now use a constant of the new type.
1238 Constant *New = UndefValue::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, Type, UndefValue> > UndefValueConstants;
1248 static char getValType(UndefValue *) {
1253 UndefValue *UndefValue::get(const Type *Ty) {
1254 return UndefValueConstants->getOrCreate(Ty, 0);
1257 // destroyConstant - Remove the constant from the constant table.
1259 void UndefValue::destroyConstant() {
1260 UndefValueConstants->remove(this);
1261 destroyConstantImpl();
1265 //---- ConstantExpr::get() implementations...
1268 struct ExprMapKeyType {
1269 explicit ExprMapKeyType(unsigned opc, std::vector<Constant*> ops,
1270 unsigned short pred = 0) : opcode(opc), predicate(pred), operands(ops) { }
1273 std::vector<Constant*> operands;
1274 bool operator==(const ExprMapKeyType& that) const {
1275 return this->opcode == that.opcode &&
1276 this->predicate == that.predicate &&
1277 this->operands == that.operands;
1279 bool operator<(const ExprMapKeyType & that) const {
1280 return this->opcode < that.opcode ||
1281 (this->opcode == that.opcode && this->predicate < that.predicate) ||
1282 (this->opcode == that.opcode && this->predicate == that.predicate &&
1283 this->operands < that.operands);
1286 bool operator!=(const ExprMapKeyType& that) const {
1287 return !(*this == that);
1293 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1294 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1295 unsigned short pred = 0) {
1296 if (Instruction::isCast(V.opcode))
1297 return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1298 if ((V.opcode >= Instruction::BinaryOpsBegin &&
1299 V.opcode < Instruction::BinaryOpsEnd) ||
1300 V.opcode == Instruction::Shl ||
1301 V.opcode == Instruction::LShr ||
1302 V.opcode == Instruction::AShr)
1303 return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1304 if (V.opcode == Instruction::Select)
1305 return new SelectConstantExpr(V.operands[0], V.operands[1],
1307 if (V.opcode == Instruction::ExtractElement)
1308 return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1309 if (V.opcode == Instruction::InsertElement)
1310 return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1312 if (V.opcode == Instruction::ShuffleVector)
1313 return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1315 if (V.opcode == Instruction::GetElementPtr) {
1316 std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
1317 return new GetElementPtrConstantExpr(V.operands[0], IdxList, Ty);
1320 // The compare instructions are weird. We have to encode the predicate
1321 // value and it is combined with the instruction opcode by multiplying
1322 // the opcode by one hundred. We must decode this to get the predicate.
1323 if (V.opcode == Instruction::ICmp)
1324 return new CompareConstantExpr(Instruction::ICmp, V.predicate,
1325 V.operands[0], V.operands[1]);
1326 if (V.opcode == Instruction::FCmp)
1327 return new CompareConstantExpr(Instruction::FCmp, V.predicate,
1328 V.operands[0], V.operands[1]);
1329 assert(0 && "Invalid ConstantExpr!");
1335 struct ConvertConstantType<ConstantExpr, Type> {
1336 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1338 switch (OldC->getOpcode()) {
1339 case Instruction::Trunc:
1340 case Instruction::ZExt:
1341 case Instruction::SExt:
1342 case Instruction::FPTrunc:
1343 case Instruction::FPExt:
1344 case Instruction::UIToFP:
1345 case Instruction::SIToFP:
1346 case Instruction::FPToUI:
1347 case Instruction::FPToSI:
1348 case Instruction::PtrToInt:
1349 case Instruction::IntToPtr:
1350 case Instruction::BitCast:
1351 New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0),
1354 case Instruction::Select:
1355 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1356 OldC->getOperand(1),
1357 OldC->getOperand(2));
1359 case Instruction::Shl:
1360 case Instruction::LShr:
1361 case Instruction::AShr:
1362 New = ConstantExpr::getShiftTy(NewTy, OldC->getOpcode(),
1363 OldC->getOperand(0), OldC->getOperand(1));
1366 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1367 OldC->getOpcode() < Instruction::BinaryOpsEnd);
1368 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1369 OldC->getOperand(1));
1371 case Instruction::GetElementPtr:
1372 // Make everyone now use a constant of the new type...
1373 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1374 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0), Idx);
1378 assert(New != OldC && "Didn't replace constant??");
1379 OldC->uncheckedReplaceAllUsesWith(New);
1380 OldC->destroyConstant(); // This constant is now dead, destroy it.
1383 } // end namespace llvm
1386 static ExprMapKeyType getValType(ConstantExpr *CE) {
1387 std::vector<Constant*> Operands;
1388 Operands.reserve(CE->getNumOperands());
1389 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1390 Operands.push_back(cast<Constant>(CE->getOperand(i)));
1391 return ExprMapKeyType(CE->getOpcode(), Operands,
1392 CE->isCompare() ? CE->getPredicate() : 0);
1395 static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1396 ConstantExpr> > ExprConstants;
1398 /// This is a utility function to handle folding of casts and lookup of the
1399 /// cast in the ExprConstants map. It is usedby the various get* methods below.
1400 static inline Constant *getFoldedCast(
1401 Instruction::CastOps opc, Constant *C, const Type *Ty) {
1402 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1403 // Fold a few common cases
1404 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1407 // Look up the constant in the table first to ensure uniqueness
1408 std::vector<Constant*> argVec(1, C);
1409 ExprMapKeyType Key(opc, argVec);
1410 return ExprConstants->getOrCreate(Ty, Key);
1413 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1414 Instruction::CastOps opc = Instruction::CastOps(oc);
1415 assert(Instruction::isCast(opc) && "opcode out of range");
1416 assert(C && Ty && "Null arguments to getCast");
1417 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1421 assert(0 && "Invalid cast opcode");
1423 case Instruction::Trunc: return getTrunc(C, Ty);
1424 case Instruction::ZExt: return getZExt(C, Ty);
1425 case Instruction::SExt: return getSExt(C, Ty);
1426 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1427 case Instruction::FPExt: return getFPExtend(C, Ty);
1428 case Instruction::UIToFP: return getUIToFP(C, Ty);
1429 case Instruction::SIToFP: return getSIToFP(C, Ty);
1430 case Instruction::FPToUI: return getFPToUI(C, Ty);
1431 case Instruction::FPToSI: return getFPToSI(C, Ty);
1432 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1433 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1434 case Instruction::BitCast: return getBitCast(C, Ty);
1439 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1440 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1441 return getCast(Instruction::BitCast, C, Ty);
1442 return getCast(Instruction::ZExt, C, Ty);
1445 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1446 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1447 return getCast(Instruction::BitCast, C, Ty);
1448 return getCast(Instruction::SExt, C, Ty);
1451 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1452 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1453 return getCast(Instruction::BitCast, C, Ty);
1454 return getCast(Instruction::Trunc, C, Ty);
1457 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1458 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1459 assert((Ty->isIntegral() || Ty->getTypeID() == Type::PointerTyID) &&
1462 if (Ty->isIntegral())
1463 return getCast(Instruction::PtrToInt, S, Ty);
1464 return getCast(Instruction::BitCast, S, Ty);
1467 Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
1469 assert(C->getType()->isIntegral() && Ty->isIntegral() && "Invalid cast");
1470 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1471 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1472 Instruction::CastOps opcode =
1473 (SrcBits == DstBits ? Instruction::BitCast :
1474 (SrcBits > DstBits ? Instruction::Trunc :
1475 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1476 return getCast(opcode, C, Ty);
1479 Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1480 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1482 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1483 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1484 if (SrcBits == DstBits)
1485 return C; // Avoid a useless cast
1486 Instruction::CastOps opcode =
1487 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1488 return getCast(opcode, C, Ty);
1491 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
1492 assert(C->getType()->isInteger() && "Trunc operand must be integer");
1493 assert(Ty->isIntegral() && "Trunc produces only integral");
1494 assert(C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1495 "SrcTy must be larger than DestTy for Trunc!");
1497 return getFoldedCast(Instruction::Trunc, C, Ty);
1500 Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
1501 assert(C->getType()->isIntegral() && "SEXt operand must be integral");
1502 assert(Ty->isInteger() && "SExt produces only integer");
1503 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1504 "SrcTy must be smaller than DestTy for SExt!");
1506 return getFoldedCast(Instruction::SExt, C, Ty);
1509 Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
1510 assert(C->getType()->isIntegral() && "ZEXt operand must be integral");
1511 assert(Ty->isInteger() && "ZExt produces only integer");
1512 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1513 "SrcTy must be smaller than DestTy for ZExt!");
1515 return getFoldedCast(Instruction::ZExt, C, Ty);
1518 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1519 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1520 C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1521 "This is an illegal floating point truncation!");
1522 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1525 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1526 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1527 C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1528 "This is an illegal floating point extension!");
1529 return getFoldedCast(Instruction::FPExt, C, Ty);
1532 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
1533 assert(C->getType()->isIntegral() && Ty->isFloatingPoint() &&
1534 "This is an illegal uint to floating point cast!");
1535 return getFoldedCast(Instruction::UIToFP, C, Ty);
1538 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
1539 assert(C->getType()->isIntegral() && Ty->isFloatingPoint() &&
1540 "This is an illegal sint to floating point cast!");
1541 return getFoldedCast(Instruction::SIToFP, C, Ty);
1544 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
1545 assert(C->getType()->isFloatingPoint() && Ty->isIntegral() &&
1546 "This is an illegal floating point to uint cast!");
1547 return getFoldedCast(Instruction::FPToUI, C, Ty);
1550 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
1551 assert(C->getType()->isFloatingPoint() && Ty->isIntegral() &&
1552 "This is an illegal floating point to sint cast!");
1553 return getFoldedCast(Instruction::FPToSI, C, Ty);
1556 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1557 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
1558 assert(DstTy->isIntegral() && "PtrToInt destination must be integral");
1559 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1562 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
1563 assert(C->getType()->isIntegral() && "IntToPtr source must be integral");
1564 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
1565 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1568 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1569 // BitCast implies a no-op cast of type only. No bits change. However, you
1570 // can't cast pointers to anything but pointers.
1571 const Type *SrcTy = C->getType();
1572 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
1573 "BitCast cannot cast pointer to non-pointer and vice versa");
1575 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
1576 // or nonptr->ptr). For all the other types, the cast is okay if source and
1577 // destination bit widths are identical.
1578 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1579 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
1580 assert(SrcBitSize == DstBitSize && "BitCast requies types of same width");
1581 return getFoldedCast(Instruction::BitCast, C, DstTy);
1584 Constant *ConstantExpr::getSizeOf(const Type *Ty) {
1585 // sizeof is implemented as: (ulong) gep (Ty*)null, 1
1586 return getCast(Instruction::PtrToInt, getGetElementPtr(getNullValue(
1587 PointerType::get(Ty)), std::vector<Constant*>(1,
1588 ConstantInt::get(Type::Int32Ty, 1))), Type::Int64Ty);
1591 Constant *ConstantExpr::getPtrPtrFromArrayPtr(Constant *C) {
1592 // pointer from array is implemented as: getelementptr arr ptr, 0, 0
1593 static std::vector<Constant*> Indices(2, ConstantInt::get(Type::Int32Ty, 0));
1595 return ConstantExpr::getGetElementPtr(C, Indices);
1598 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1599 Constant *C1, Constant *C2) {
1600 if (Opcode == Instruction::Shl || Opcode == Instruction::LShr ||
1601 Opcode == Instruction::AShr)
1602 return getShiftTy(ReqTy, Opcode, C1, C2);
1604 // Check the operands for consistency first
1605 assert(Opcode >= Instruction::BinaryOpsBegin &&
1606 Opcode < Instruction::BinaryOpsEnd &&
1607 "Invalid opcode in binary constant expression");
1608 assert(C1->getType() == C2->getType() &&
1609 "Operand types in binary constant expression should match");
1611 if (ReqTy == C1->getType() || ReqTy == Type::BoolTy)
1612 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1613 return FC; // Fold a few common cases...
1615 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1616 ExprMapKeyType Key(Opcode, argVec);
1617 return ExprConstants->getOrCreate(ReqTy, Key);
1620 Constant *ConstantExpr::getCompareTy(unsigned short predicate,
1621 Constant *C1, Constant *C2) {
1622 switch (predicate) {
1623 default: assert(0 && "Invalid CmpInst predicate");
1624 case FCmpInst::FCMP_FALSE: case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_OGT:
1625 case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OLE:
1626 case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_ORD: case FCmpInst::FCMP_UNO:
1627 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UGT: case FCmpInst::FCMP_UGE:
1628 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_ULE: case FCmpInst::FCMP_UNE:
1629 case FCmpInst::FCMP_TRUE:
1630 return getFCmp(predicate, C1, C2);
1631 case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGT:
1632 case ICmpInst::ICMP_UGE: case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE:
1633 case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_SGE: case ICmpInst::ICMP_SLT:
1634 case ICmpInst::ICMP_SLE:
1635 return getICmp(predicate, C1, C2);
1639 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
1642 case Instruction::Add:
1643 case Instruction::Sub:
1644 case Instruction::Mul:
1645 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1646 assert((C1->getType()->isInteger() || C1->getType()->isFloatingPoint() ||
1647 isa<PackedType>(C1->getType())) &&
1648 "Tried to create an arithmetic operation on a non-arithmetic type!");
1650 case Instruction::UDiv:
1651 case Instruction::SDiv:
1652 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1653 assert((C1->getType()->isInteger() || (isa<PackedType>(C1->getType()) &&
1654 cast<PackedType>(C1->getType())->getElementType()->isInteger())) &&
1655 "Tried to create an arithmetic operation on a non-arithmetic type!");
1657 case Instruction::FDiv:
1658 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1659 assert((C1->getType()->isFloatingPoint() || (isa<PackedType>(C1->getType())
1660 && cast<PackedType>(C1->getType())->getElementType()->isFloatingPoint()))
1661 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1663 case Instruction::URem:
1664 case Instruction::SRem:
1665 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1666 assert((C1->getType()->isInteger() || (isa<PackedType>(C1->getType()) &&
1667 cast<PackedType>(C1->getType())->getElementType()->isInteger())) &&
1668 "Tried to create an arithmetic operation on a non-arithmetic type!");
1670 case Instruction::FRem:
1671 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1672 assert((C1->getType()->isFloatingPoint() || (isa<PackedType>(C1->getType())
1673 && cast<PackedType>(C1->getType())->getElementType()->isFloatingPoint()))
1674 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1676 case Instruction::And:
1677 case Instruction::Or:
1678 case Instruction::Xor:
1679 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1680 assert((C1->getType()->isIntegral() || isa<PackedType>(C1->getType())) &&
1681 "Tried to create a logical operation on a non-integral type!");
1683 case Instruction::Shl:
1684 case Instruction::LShr:
1685 case Instruction::AShr:
1686 assert(C2->getType() == Type::Int8Ty && "Shift should be by ubyte!");
1687 assert(C1->getType()->isInteger() &&
1688 "Tried to create a shift operation on a non-integer type!");
1695 return getTy(C1->getType(), Opcode, C1, C2);
1698 Constant *ConstantExpr::getCompare(unsigned short pred,
1699 Constant *C1, Constant *C2) {
1700 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1701 return getCompareTy(pred, C1, C2);
1704 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1705 Constant *V1, Constant *V2) {
1706 assert(C->getType() == Type::BoolTy && "Select condition must be bool!");
1707 assert(V1->getType() == V2->getType() && "Select value types must match!");
1708 assert(V1->getType()->isFirstClassType() && "Cannot select aggregate type!");
1710 if (ReqTy == V1->getType())
1711 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1712 return SC; // Fold common cases
1714 std::vector<Constant*> argVec(3, C);
1717 ExprMapKeyType Key(Instruction::Select, argVec);
1718 return ExprConstants->getOrCreate(ReqTy, Key);
1721 /// getShiftTy - Return a shift left or shift right constant expr
1722 Constant *ConstantExpr::getShiftTy(const Type *ReqTy, unsigned Opcode,
1723 Constant *C1, Constant *C2) {
1724 // Check the operands for consistency first
1725 assert((Opcode == Instruction::Shl ||
1726 Opcode == Instruction::LShr ||
1727 Opcode == Instruction::AShr) &&
1728 "Invalid opcode in binary constant expression");
1729 assert(C1->getType()->isIntegral() && C2->getType() == Type::Int8Ty &&
1730 "Invalid operand types for Shift constant expr!");
1732 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1733 return FC; // Fold a few common cases...
1735 // Look up the constant in the table first to ensure uniqueness
1736 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1737 ExprMapKeyType Key(Opcode, argVec);
1738 return ExprConstants->getOrCreate(ReqTy, Key);
1741 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1742 const std::vector<Value*> &IdxList) {
1743 assert(GetElementPtrInst::getIndexedType(C->getType(), IdxList, true) &&
1744 "GEP indices invalid!");
1746 if (Constant *FC = ConstantFoldGetElementPtr(C, IdxList))
1747 return FC; // Fold a few common cases...
1749 assert(isa<PointerType>(C->getType()) &&
1750 "Non-pointer type for constant GetElementPtr expression");
1751 // Look up the constant in the table first to ensure uniqueness
1752 std::vector<Constant*> ArgVec;
1753 ArgVec.reserve(IdxList.size()+1);
1754 ArgVec.push_back(C);
1755 for (unsigned i = 0, e = IdxList.size(); i != e; ++i)
1756 ArgVec.push_back(cast<Constant>(IdxList[i]));
1757 const ExprMapKeyType Key(Instruction::GetElementPtr,ArgVec);
1758 return ExprConstants->getOrCreate(ReqTy, Key);
1761 Constant *ConstantExpr::getGetElementPtr(Constant *C,
1762 const std::vector<Constant*> &IdxList){
1763 // Get the result type of the getelementptr!
1764 std::vector<Value*> VIdxList(IdxList.begin(), IdxList.end());
1766 const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), VIdxList,
1768 assert(Ty && "GEP indices invalid!");
1769 return getGetElementPtrTy(PointerType::get(Ty), C, VIdxList);
1772 Constant *ConstantExpr::getGetElementPtr(Constant *C,
1773 const std::vector<Value*> &IdxList) {
1774 // Get the result type of the getelementptr!
1775 const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), IdxList,
1777 assert(Ty && "GEP indices invalid!");
1778 return getGetElementPtrTy(PointerType::get(Ty), C, IdxList);
1782 ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1783 assert(LHS->getType() == RHS->getType());
1784 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
1785 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1787 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1788 return FC; // Fold a few common cases...
1790 // Look up the constant in the table first to ensure uniqueness
1791 std::vector<Constant*> ArgVec;
1792 ArgVec.push_back(LHS);
1793 ArgVec.push_back(RHS);
1794 // Get the key type with both the opcode and predicate
1795 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
1796 return ExprConstants->getOrCreate(Type::BoolTy, Key);
1800 ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1801 assert(LHS->getType() == RHS->getType());
1802 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1804 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1805 return FC; // Fold a few common cases...
1807 // Look up the constant in the table first to ensure uniqueness
1808 std::vector<Constant*> ArgVec;
1809 ArgVec.push_back(LHS);
1810 ArgVec.push_back(RHS);
1811 // Get the key type with both the opcode and predicate
1812 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
1813 return ExprConstants->getOrCreate(Type::BoolTy, Key);
1816 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
1818 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
1819 return FC; // Fold a few common cases...
1820 // Look up the constant in the table first to ensure uniqueness
1821 std::vector<Constant*> ArgVec(1, Val);
1822 ArgVec.push_back(Idx);
1823 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
1824 return ExprConstants->getOrCreate(ReqTy, Key);
1827 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
1828 assert(isa<PackedType>(Val->getType()) &&
1829 "Tried to create extractelement operation on non-packed type!");
1830 assert(Idx->getType() == Type::Int32Ty &&
1831 "Extractelement index must be uint type!");
1832 return getExtractElementTy(cast<PackedType>(Val->getType())->getElementType(),
1836 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
1837 Constant *Elt, Constant *Idx) {
1838 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
1839 return FC; // Fold a few common cases...
1840 // Look up the constant in the table first to ensure uniqueness
1841 std::vector<Constant*> ArgVec(1, Val);
1842 ArgVec.push_back(Elt);
1843 ArgVec.push_back(Idx);
1844 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
1845 return ExprConstants->getOrCreate(ReqTy, Key);
1848 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1850 assert(isa<PackedType>(Val->getType()) &&
1851 "Tried to create insertelement operation on non-packed type!");
1852 assert(Elt->getType() == cast<PackedType>(Val->getType())->getElementType()
1853 && "Insertelement types must match!");
1854 assert(Idx->getType() == Type::Int32Ty &&
1855 "Insertelement index must be uint type!");
1856 return getInsertElementTy(cast<PackedType>(Val->getType())->getElementType(),
1860 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
1861 Constant *V2, Constant *Mask) {
1862 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
1863 return FC; // Fold a few common cases...
1864 // Look up the constant in the table first to ensure uniqueness
1865 std::vector<Constant*> ArgVec(1, V1);
1866 ArgVec.push_back(V2);
1867 ArgVec.push_back(Mask);
1868 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
1869 return ExprConstants->getOrCreate(ReqTy, Key);
1872 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
1874 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1875 "Invalid shuffle vector constant expr operands!");
1876 return getShuffleVectorTy(V1->getType(), V1, V2, Mask);
1879 // destroyConstant - Remove the constant from the constant table...
1881 void ConstantExpr::destroyConstant() {
1882 ExprConstants->remove(this);
1883 destroyConstantImpl();
1886 const char *ConstantExpr::getOpcodeName() const {
1887 return Instruction::getOpcodeName(getOpcode());
1890 //===----------------------------------------------------------------------===//
1891 // replaceUsesOfWithOnConstant implementations
1893 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
1895 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1896 Constant *ToC = cast<Constant>(To);
1898 unsigned OperandToUpdate = U-OperandList;
1899 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
1901 std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
1902 Lookup.first.first = getType();
1903 Lookup.second = this;
1905 std::vector<Constant*> &Values = Lookup.first.second;
1906 Values.reserve(getNumOperands()); // Build replacement array.
1908 // Fill values with the modified operands of the constant array. Also,
1909 // compute whether this turns into an all-zeros array.
1910 bool isAllZeros = false;
1911 if (!ToC->isNullValue()) {
1912 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
1913 Values.push_back(cast<Constant>(O->get()));
1916 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1917 Constant *Val = cast<Constant>(O->get());
1918 Values.push_back(Val);
1919 if (isAllZeros) isAllZeros = Val->isNullValue();
1922 Values[OperandToUpdate] = ToC;
1924 Constant *Replacement = 0;
1926 Replacement = ConstantAggregateZero::get(getType());
1928 // Check to see if we have this array type already.
1930 ArrayConstantsTy::MapTy::iterator I =
1931 ArrayConstants->InsertOrGetItem(Lookup, Exists);
1934 Replacement = I->second;
1936 // Okay, the new shape doesn't exist in the system yet. Instead of
1937 // creating a new constant array, inserting it, replaceallusesof'ing the
1938 // old with the new, then deleting the old... just update the current one
1940 ArrayConstants->MoveConstantToNewSlot(this, I);
1942 // Update to the new value.
1943 setOperand(OperandToUpdate, ToC);
1948 // Otherwise, I do need to replace this with an existing value.
1949 assert(Replacement != this && "I didn't contain From!");
1951 // Everyone using this now uses the replacement.
1952 uncheckedReplaceAllUsesWith(Replacement);
1954 // Delete the old constant!
1958 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
1960 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1961 Constant *ToC = cast<Constant>(To);
1963 unsigned OperandToUpdate = U-OperandList;
1964 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
1966 std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
1967 Lookup.first.first = getType();
1968 Lookup.second = this;
1969 std::vector<Constant*> &Values = Lookup.first.second;
1970 Values.reserve(getNumOperands()); // Build replacement struct.
1973 // Fill values with the modified operands of the constant struct. Also,
1974 // compute whether this turns into an all-zeros struct.
1975 bool isAllZeros = false;
1976 if (!ToC->isNullValue()) {
1977 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
1978 Values.push_back(cast<Constant>(O->get()));
1981 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1982 Constant *Val = cast<Constant>(O->get());
1983 Values.push_back(Val);
1984 if (isAllZeros) isAllZeros = Val->isNullValue();
1987 Values[OperandToUpdate] = ToC;
1989 Constant *Replacement = 0;
1991 Replacement = ConstantAggregateZero::get(getType());
1993 // Check to see if we have this array type already.
1995 StructConstantsTy::MapTy::iterator I =
1996 StructConstants->InsertOrGetItem(Lookup, Exists);
1999 Replacement = I->second;
2001 // Okay, the new shape doesn't exist in the system yet. Instead of
2002 // creating a new constant struct, inserting it, replaceallusesof'ing the
2003 // old with the new, then deleting the old... just update the current one
2005 StructConstants->MoveConstantToNewSlot(this, I);
2007 // Update to the new value.
2008 setOperand(OperandToUpdate, ToC);
2013 assert(Replacement != this && "I didn't contain From!");
2015 // Everyone using this now uses the replacement.
2016 uncheckedReplaceAllUsesWith(Replacement);
2018 // Delete the old constant!
2022 void ConstantPacked::replaceUsesOfWithOnConstant(Value *From, Value *To,
2024 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2026 std::vector<Constant*> Values;
2027 Values.reserve(getNumOperands()); // Build replacement array...
2028 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2029 Constant *Val = getOperand(i);
2030 if (Val == From) Val = cast<Constant>(To);
2031 Values.push_back(Val);
2034 Constant *Replacement = ConstantPacked::get(getType(), Values);
2035 assert(Replacement != this && "I didn't contain From!");
2037 // Everyone using this now uses the replacement.
2038 uncheckedReplaceAllUsesWith(Replacement);
2040 // Delete the old constant!
2044 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2046 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2047 Constant *To = cast<Constant>(ToV);
2049 Constant *Replacement = 0;
2050 if (getOpcode() == Instruction::GetElementPtr) {
2051 std::vector<Constant*> Indices;
2052 Constant *Pointer = getOperand(0);
2053 Indices.reserve(getNumOperands()-1);
2054 if (Pointer == From) Pointer = To;
2056 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2057 Constant *Val = getOperand(i);
2058 if (Val == From) Val = To;
2059 Indices.push_back(Val);
2061 Replacement = ConstantExpr::getGetElementPtr(Pointer, Indices);
2062 } else if (isCast()) {
2063 assert(getOperand(0) == From && "Cast only has one use!");
2064 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
2065 } else if (getOpcode() == Instruction::Select) {
2066 Constant *C1 = getOperand(0);
2067 Constant *C2 = getOperand(1);
2068 Constant *C3 = getOperand(2);
2069 if (C1 == From) C1 = To;
2070 if (C2 == From) C2 = To;
2071 if (C3 == From) C3 = To;
2072 Replacement = ConstantExpr::getSelect(C1, C2, C3);
2073 } else if (getOpcode() == Instruction::ExtractElement) {
2074 Constant *C1 = getOperand(0);
2075 Constant *C2 = getOperand(1);
2076 if (C1 == From) C1 = To;
2077 if (C2 == From) C2 = To;
2078 Replacement = ConstantExpr::getExtractElement(C1, C2);
2079 } else if (getOpcode() == Instruction::InsertElement) {
2080 Constant *C1 = getOperand(0);
2081 Constant *C2 = getOperand(1);
2082 Constant *C3 = getOperand(1);
2083 if (C1 == From) C1 = To;
2084 if (C2 == From) C2 = To;
2085 if (C3 == From) C3 = To;
2086 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2087 } else if (getOpcode() == Instruction::ShuffleVector) {
2088 Constant *C1 = getOperand(0);
2089 Constant *C2 = getOperand(1);
2090 Constant *C3 = getOperand(2);
2091 if (C1 == From) C1 = To;
2092 if (C2 == From) C2 = To;
2093 if (C3 == From) C3 = To;
2094 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2095 } else if (isCompare()) {
2096 Constant *C1 = getOperand(0);
2097 Constant *C2 = getOperand(1);
2098 if (C1 == From) C1 = To;
2099 if (C2 == From) C2 = To;
2100 if (getOpcode() == Instruction::ICmp)
2101 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2103 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2104 } else if (getNumOperands() == 2) {
2105 Constant *C1 = getOperand(0);
2106 Constant *C2 = getOperand(1);
2107 if (C1 == From) C1 = To;
2108 if (C2 == From) C2 = To;
2109 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2111 assert(0 && "Unknown ConstantExpr type!");
2115 assert(Replacement != this && "I didn't contain From!");
2117 // Everyone using this now uses the replacement.
2118 uncheckedReplaceAllUsesWith(Replacement);
2120 // Delete the old constant!
2125 /// getStringValue - Turn an LLVM constant pointer that eventually points to a
2126 /// global into a string value. Return an empty string if we can't do it.
2127 /// Parameter Chop determines if the result is chopped at the first null
2130 std::string Constant::getStringValue(bool Chop, unsigned Offset) {
2131 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(this)) {
2132 if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
2133 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
2134 if (Init->isString()) {
2135 std::string Result = Init->getAsString();
2136 if (Offset < Result.size()) {
2137 // If we are pointing INTO The string, erase the beginning...
2138 Result.erase(Result.begin(), Result.begin()+Offset);
2140 // Take off the null terminator, and any string fragments after it.
2142 std::string::size_type NullPos = Result.find_first_of((char)0);
2143 if (NullPos != std::string::npos)
2144 Result.erase(Result.begin()+NullPos, Result.end());
2150 } else if (Constant *C = dyn_cast<Constant>(this)) {
2151 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
2152 return GV->getStringValue(Chop, Offset);
2153 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2154 if (CE->getOpcode() == Instruction::GetElementPtr) {
2155 // Turn a gep into the specified offset.
2156 if (CE->getNumOperands() == 3 &&
2157 cast<Constant>(CE->getOperand(1))->isNullValue() &&
2158 isa<ConstantInt>(CE->getOperand(2))) {
2159 Offset += cast<ConstantInt>(CE->getOperand(2))->getZExtValue();
2160 return CE->getOperand(0)->getStringValue(Chop, Offset);