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/Module.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/Support/Compiler.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Support/ManagedStatic.h"
24 #include "llvm/Support/MathExtras.h"
25 #include "llvm/ADT/SmallVector.h"
30 //===----------------------------------------------------------------------===//
32 //===----------------------------------------------------------------------===//
34 void Constant::destroyConstantImpl() {
35 // When a Constant is destroyed, there may be lingering
36 // references to the constant by other constants in the constant pool. These
37 // constants are implicitly dependent on the module that is being deleted,
38 // but they don't know that. Because we only find out when the CPV is
39 // deleted, we must now notify all of our users (that should only be
40 // Constants) that they are, in fact, invalid now and should be deleted.
42 while (!use_empty()) {
43 Value *V = use_back();
44 #ifndef NDEBUG // Only in -g mode...
45 if (!isa<Constant>(V))
46 DOUT << "While deleting: " << *this
47 << "\n\nUse still stuck around after Def is destroyed: "
50 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
51 Constant *CV = cast<Constant>(V);
52 CV->destroyConstant();
54 // The constant should remove itself from our use list...
55 assert((use_empty() || use_back() != V) && "Constant not removed!");
58 // Value has no outstanding references it is safe to delete it now...
62 /// canTrap - Return true if evaluation of this constant could trap. This is
63 /// true for things like constant expressions that could divide by zero.
64 bool Constant::canTrap() const {
65 assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
66 // The only thing that could possibly trap are constant exprs.
67 const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
68 if (!CE) return false;
70 // ConstantExpr traps if any operands can trap.
71 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
72 if (getOperand(i)->canTrap())
75 // Otherwise, only specific operations can trap.
76 switch (CE->getOpcode()) {
79 case Instruction::UDiv:
80 case Instruction::SDiv:
81 case Instruction::FDiv:
82 case Instruction::URem:
83 case Instruction::SRem:
84 case Instruction::FRem:
85 // Div and rem can trap if the RHS is not known to be non-zero.
86 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::IntegerTyID:
96 return ConstantInt::get(Ty, 0);
98 case Type::DoubleTyID:
99 return ConstantFP::get(Ty, 0.0);
100 case Type::PointerTyID:
101 return ConstantPointerNull::get(cast<PointerType>(Ty));
102 case Type::StructTyID:
103 case Type::ArrayTyID:
104 case Type::VectorTyID:
105 return ConstantAggregateZero::get(Ty);
107 // Function, Label, or Opaque type?
108 assert(!"Cannot create a null constant of that type!");
114 // Static constructor to create an integral constant with all bits set
115 ConstantInt *ConstantInt::getAllOnesValue(const Type *Ty) {
116 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
117 if (ITy->getBitWidth() == 1)
118 return ConstantInt::getTrue();
120 return ConstantInt::get(Ty, int64_t(-1));
124 /// @returns the value for an packed integer constant of the given type that
125 /// has all its bits set to true.
126 /// @brief Get the all ones value
127 ConstantVector *ConstantVector::getAllOnesValue(const VectorType *Ty) {
128 std::vector<Constant*> Elts;
129 Elts.resize(Ty->getNumElements(),
130 ConstantInt::getAllOnesValue(Ty->getElementType()));
131 assert(Elts[0] && "Not a packed integer type!");
132 return cast<ConstantVector>(ConstantVector::get(Elts));
136 //===----------------------------------------------------------------------===//
137 // ConstantXXX Classes
138 //===----------------------------------------------------------------------===//
140 //===----------------------------------------------------------------------===//
141 // Normal Constructors
143 ConstantInt::ConstantInt(const IntegerType *Ty, uint64_t V)
144 : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
147 ConstantFP::ConstantFP(const Type *Ty, double V)
148 : Constant(Ty, ConstantFPVal, 0, 0) {
149 assert(isValueValidForType(Ty, V) && "Value too large for type!");
153 ConstantArray::ConstantArray(const ArrayType *T,
154 const std::vector<Constant*> &V)
155 : Constant(T, ConstantArrayVal, new Use[V.size()], V.size()) {
156 assert(V.size() == T->getNumElements() &&
157 "Invalid initializer vector for constant array");
158 Use *OL = OperandList;
159 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
162 assert((C->getType() == T->getElementType() ||
164 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
165 "Initializer for array element doesn't match array element type!");
170 ConstantArray::~ConstantArray() {
171 delete [] OperandList;
174 ConstantStruct::ConstantStruct(const StructType *T,
175 const std::vector<Constant*> &V)
176 : Constant(T, ConstantStructVal, new Use[V.size()], V.size()) {
177 assert(V.size() == T->getNumElements() &&
178 "Invalid initializer vector for constant structure");
179 Use *OL = OperandList;
180 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
183 assert((C->getType() == T->getElementType(I-V.begin()) ||
184 ((T->getElementType(I-V.begin())->isAbstract() ||
185 C->getType()->isAbstract()) &&
186 T->getElementType(I-V.begin())->getTypeID() ==
187 C->getType()->getTypeID())) &&
188 "Initializer for struct element doesn't match struct element type!");
193 ConstantStruct::~ConstantStruct() {
194 delete [] OperandList;
198 ConstantVector::ConstantVector(const VectorType *T,
199 const std::vector<Constant*> &V)
200 : Constant(T, ConstantVectorVal, new Use[V.size()], V.size()) {
201 Use *OL = OperandList;
202 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
205 assert((C->getType() == T->getElementType() ||
207 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
208 "Initializer for packed element doesn't match packed element type!");
213 ConstantVector::~ConstantVector() {
214 delete [] OperandList;
217 // We declare several classes private to this file, so use an anonymous
221 /// UnaryConstantExpr - This class is private to Constants.cpp, and is used
222 /// behind the scenes to implement unary constant exprs.
223 class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
226 UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
227 : ConstantExpr(Ty, Opcode, &Op, 1), Op(C, this) {}
230 /// BinaryConstantExpr - This class is private to Constants.cpp, and is used
231 /// behind the scenes to implement binary constant exprs.
232 class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
235 BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
236 : ConstantExpr(C1->getType(), Opcode, Ops, 2) {
237 Ops[0].init(C1, this);
238 Ops[1].init(C2, this);
242 /// SelectConstantExpr - This class is private to Constants.cpp, and is used
243 /// behind the scenes to implement select constant exprs.
244 class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
247 SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
248 : ConstantExpr(C2->getType(), Instruction::Select, Ops, 3) {
249 Ops[0].init(C1, this);
250 Ops[1].init(C2, this);
251 Ops[2].init(C3, this);
255 /// ExtractElementConstantExpr - This class is private to
256 /// Constants.cpp, and is used behind the scenes to implement
257 /// extractelement constant exprs.
258 class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
261 ExtractElementConstantExpr(Constant *C1, Constant *C2)
262 : ConstantExpr(cast<VectorType>(C1->getType())->getElementType(),
263 Instruction::ExtractElement, Ops, 2) {
264 Ops[0].init(C1, this);
265 Ops[1].init(C2, this);
269 /// InsertElementConstantExpr - This class is private to
270 /// Constants.cpp, and is used behind the scenes to implement
271 /// insertelement constant exprs.
272 class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
275 InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
276 : ConstantExpr(C1->getType(), Instruction::InsertElement,
278 Ops[0].init(C1, this);
279 Ops[1].init(C2, this);
280 Ops[2].init(C3, this);
284 /// ShuffleVectorConstantExpr - This class is private to
285 /// Constants.cpp, and is used behind the scenes to implement
286 /// shufflevector constant exprs.
287 class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
290 ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
291 : ConstantExpr(C1->getType(), Instruction::ShuffleVector,
293 Ops[0].init(C1, this);
294 Ops[1].init(C2, this);
295 Ops[2].init(C3, this);
299 /// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
300 /// used behind the scenes to implement getelementpr constant exprs.
301 struct VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
302 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
304 : ConstantExpr(DestTy, Instruction::GetElementPtr,
305 new Use[IdxList.size()+1], IdxList.size()+1) {
306 OperandList[0].init(C, this);
307 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
308 OperandList[i+1].init(IdxList[i], this);
310 ~GetElementPtrConstantExpr() {
311 delete [] OperandList;
315 // CompareConstantExpr - This class is private to Constants.cpp, and is used
316 // behind the scenes to implement ICmp and FCmp constant expressions. This is
317 // needed in order to store the predicate value for these instructions.
318 struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
319 unsigned short predicate;
321 CompareConstantExpr(Instruction::OtherOps opc, unsigned short pred,
322 Constant* LHS, Constant* RHS)
323 : ConstantExpr(Type::Int1Ty, opc, Ops, 2), predicate(pred) {
324 OperandList[0].init(LHS, this);
325 OperandList[1].init(RHS, this);
329 } // end anonymous namespace
332 // Utility function for determining if a ConstantExpr is a CastOp or not. This
333 // can't be inline because we don't want to #include Instruction.h into
335 bool ConstantExpr::isCast() const {
336 return Instruction::isCast(getOpcode());
339 bool ConstantExpr::isCompare() const {
340 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
343 /// ConstantExpr::get* - Return some common constants without having to
344 /// specify the full Instruction::OPCODE identifier.
346 Constant *ConstantExpr::getNeg(Constant *C) {
347 return get(Instruction::Sub,
348 ConstantExpr::getZeroValueForNegationExpr(C->getType()),
351 Constant *ConstantExpr::getNot(Constant *C) {
352 assert(isa<ConstantInt>(C) && "Cannot NOT a nonintegral type!");
353 return get(Instruction::Xor, C,
354 ConstantInt::getAllOnesValue(C->getType()));
356 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
357 return get(Instruction::Add, C1, C2);
359 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
360 return get(Instruction::Sub, C1, C2);
362 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
363 return get(Instruction::Mul, C1, C2);
365 Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2) {
366 return get(Instruction::UDiv, C1, C2);
368 Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2) {
369 return get(Instruction::SDiv, C1, C2);
371 Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
372 return get(Instruction::FDiv, C1, C2);
374 Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
375 return get(Instruction::URem, C1, C2);
377 Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
378 return get(Instruction::SRem, C1, C2);
380 Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
381 return get(Instruction::FRem, C1, C2);
383 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
384 return get(Instruction::And, C1, C2);
386 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
387 return get(Instruction::Or, C1, C2);
389 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
390 return get(Instruction::Xor, C1, C2);
392 unsigned ConstantExpr::getPredicate() const {
393 assert(getOpcode() == Instruction::FCmp || getOpcode() == Instruction::ICmp);
394 return dynamic_cast<const CompareConstantExpr*>(this)->predicate;
396 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
397 return get(Instruction::Shl, C1, C2);
399 Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2) {
400 return get(Instruction::LShr, C1, C2);
402 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2) {
403 return get(Instruction::AShr, C1, C2);
406 /// getWithOperandReplaced - Return a constant expression identical to this
407 /// one, but with the specified operand set to the specified value.
409 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
410 assert(OpNo < getNumOperands() && "Operand num is out of range!");
411 assert(Op->getType() == getOperand(OpNo)->getType() &&
412 "Replacing operand with value of different type!");
413 if (getOperand(OpNo) == Op)
414 return const_cast<ConstantExpr*>(this);
416 Constant *Op0, *Op1, *Op2;
417 switch (getOpcode()) {
418 case Instruction::Trunc:
419 case Instruction::ZExt:
420 case Instruction::SExt:
421 case Instruction::FPTrunc:
422 case Instruction::FPExt:
423 case Instruction::UIToFP:
424 case Instruction::SIToFP:
425 case Instruction::FPToUI:
426 case Instruction::FPToSI:
427 case Instruction::PtrToInt:
428 case Instruction::IntToPtr:
429 case Instruction::BitCast:
430 return ConstantExpr::getCast(getOpcode(), Op, getType());
431 case Instruction::Select:
432 Op0 = (OpNo == 0) ? Op : getOperand(0);
433 Op1 = (OpNo == 1) ? Op : getOperand(1);
434 Op2 = (OpNo == 2) ? Op : getOperand(2);
435 return ConstantExpr::getSelect(Op0, Op1, Op2);
436 case Instruction::InsertElement:
437 Op0 = (OpNo == 0) ? Op : getOperand(0);
438 Op1 = (OpNo == 1) ? Op : getOperand(1);
439 Op2 = (OpNo == 2) ? Op : getOperand(2);
440 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
441 case Instruction::ExtractElement:
442 Op0 = (OpNo == 0) ? Op : getOperand(0);
443 Op1 = (OpNo == 1) ? Op : getOperand(1);
444 return ConstantExpr::getExtractElement(Op0, Op1);
445 case Instruction::ShuffleVector:
446 Op0 = (OpNo == 0) ? Op : getOperand(0);
447 Op1 = (OpNo == 1) ? Op : getOperand(1);
448 Op2 = (OpNo == 2) ? Op : getOperand(2);
449 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
450 case Instruction::GetElementPtr: {
451 SmallVector<Constant*, 8> Ops;
452 Ops.resize(getNumOperands());
453 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
454 Ops[i] = getOperand(i);
456 return ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
458 return ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
461 assert(getNumOperands() == 2 && "Must be binary operator?");
462 Op0 = (OpNo == 0) ? Op : getOperand(0);
463 Op1 = (OpNo == 1) ? Op : getOperand(1);
464 return ConstantExpr::get(getOpcode(), Op0, Op1);
468 /// getWithOperands - This returns the current constant expression with the
469 /// operands replaced with the specified values. The specified operands must
470 /// match count and type with the existing ones.
471 Constant *ConstantExpr::
472 getWithOperands(const std::vector<Constant*> &Ops) const {
473 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
474 bool AnyChange = false;
475 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
476 assert(Ops[i]->getType() == getOperand(i)->getType() &&
477 "Operand type mismatch!");
478 AnyChange |= Ops[i] != getOperand(i);
480 if (!AnyChange) // No operands changed, return self.
481 return const_cast<ConstantExpr*>(this);
483 switch (getOpcode()) {
484 case Instruction::Trunc:
485 case Instruction::ZExt:
486 case Instruction::SExt:
487 case Instruction::FPTrunc:
488 case Instruction::FPExt:
489 case Instruction::UIToFP:
490 case Instruction::SIToFP:
491 case Instruction::FPToUI:
492 case Instruction::FPToSI:
493 case Instruction::PtrToInt:
494 case Instruction::IntToPtr:
495 case Instruction::BitCast:
496 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
497 case Instruction::Select:
498 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
499 case Instruction::InsertElement:
500 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
501 case Instruction::ExtractElement:
502 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
503 case Instruction::ShuffleVector:
504 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
505 case Instruction::GetElementPtr:
506 return ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], Ops.size()-1);
507 case Instruction::ICmp:
508 case Instruction::FCmp:
509 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
511 assert(getNumOperands() == 2 && "Must be binary operator?");
512 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
517 //===----------------------------------------------------------------------===//
518 // isValueValidForType implementations
520 bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
521 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
522 if (Ty == Type::Int1Ty)
523 return Val == 0 || Val == 1;
525 return true; // always true, has to fit in largest type
526 uint64_t Max = (1ll << NumBits) - 1;
530 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
531 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
532 if (Ty == Type::Int1Ty)
533 return Val == 0 || Val == 1 || Val == -1;
535 return true; // always true, has to fit in largest type
536 int64_t Min = -(1ll << (NumBits-1));
537 int64_t Max = (1ll << (NumBits-1)) - 1;
538 return (Val >= Min && Val <= Max);
541 bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
542 switch (Ty->getTypeID()) {
544 return false; // These can't be represented as floating point!
546 // TODO: Figure out how to test if a double can be cast to a float!
547 case Type::FloatTyID:
548 case Type::DoubleTyID:
549 return true; // This is the largest type...
553 //===----------------------------------------------------------------------===//
554 // Factory Function Implementation
556 // ConstantCreator - A class that is used to create constants by
557 // ValueMap*. This class should be partially specialized if there is
558 // something strange that needs to be done to interface to the ctor for the
562 template<class ConstantClass, class TypeClass, class ValType>
563 struct VISIBILITY_HIDDEN ConstantCreator {
564 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
565 return new ConstantClass(Ty, V);
569 template<class ConstantClass, class TypeClass>
570 struct VISIBILITY_HIDDEN ConvertConstantType {
571 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
572 assert(0 && "This type cannot be converted!\n");
577 template<class ValType, class TypeClass, class ConstantClass,
578 bool HasLargeKey = false /*true for arrays and structs*/ >
579 class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
581 typedef std::pair<const Type*, ValType> MapKey;
582 typedef std::map<MapKey, Constant *> MapTy;
583 typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
584 typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
586 /// Map - This is the main map from the element descriptor to the Constants.
587 /// This is the primary way we avoid creating two of the same shape
591 /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
592 /// from the constants to their element in Map. This is important for
593 /// removal of constants from the array, which would otherwise have to scan
594 /// through the map with very large keys.
595 InverseMapTy InverseMap;
597 /// AbstractTypeMap - Map for abstract type constants.
599 AbstractTypeMapTy AbstractTypeMap;
602 void clear(std::vector<Constant *> &Constants) {
603 for(typename MapTy::iterator I = Map.begin(); I != Map.end(); ++I)
604 Constants.push_back(I->second);
606 AbstractTypeMap.clear();
611 typename MapTy::iterator map_end() { return Map.end(); }
613 /// InsertOrGetItem - Return an iterator for the specified element.
614 /// If the element exists in the map, the returned iterator points to the
615 /// entry and Exists=true. If not, the iterator points to the newly
616 /// inserted entry and returns Exists=false. Newly inserted entries have
617 /// I->second == 0, and should be filled in.
618 typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
621 std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
627 typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
629 typename InverseMapTy::iterator IMI = InverseMap.find(CP);
630 assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
631 IMI->second->second == CP &&
632 "InverseMap corrupt!");
636 typename MapTy::iterator I =
637 Map.find(MapKey((TypeClass*)CP->getRawType(), getValType(CP)));
638 if (I == Map.end() || I->second != CP) {
639 // FIXME: This should not use a linear scan. If this gets to be a
640 // performance problem, someone should look at this.
641 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
648 /// getOrCreate - Return the specified constant from the map, creating it if
650 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
651 MapKey Lookup(Ty, V);
652 typename MapTy::iterator I = Map.lower_bound(Lookup);
654 if (I != Map.end() && I->first == Lookup)
655 return static_cast<ConstantClass *>(I->second);
657 // If no preexisting value, create one now...
658 ConstantClass *Result =
659 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
661 /// FIXME: why does this assert fail when loading 176.gcc?
662 //assert(Result->getType() == Ty && "Type specified is not correct!");
663 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
665 if (HasLargeKey) // Remember the reverse mapping if needed.
666 InverseMap.insert(std::make_pair(Result, I));
668 // If the type of the constant is abstract, make sure that an entry exists
669 // for it in the AbstractTypeMap.
670 if (Ty->isAbstract()) {
671 typename AbstractTypeMapTy::iterator TI =
672 AbstractTypeMap.lower_bound(Ty);
674 if (TI == AbstractTypeMap.end() || TI->first != Ty) {
675 // Add ourselves to the ATU list of the type.
676 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
678 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
684 void remove(ConstantClass *CP) {
685 typename MapTy::iterator I = FindExistingElement(CP);
686 assert(I != Map.end() && "Constant not found in constant table!");
687 assert(I->second == CP && "Didn't find correct element?");
689 if (HasLargeKey) // Remember the reverse mapping if needed.
690 InverseMap.erase(CP);
692 // Now that we found the entry, make sure this isn't the entry that
693 // the AbstractTypeMap points to.
694 const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
695 if (Ty->isAbstract()) {
696 assert(AbstractTypeMap.count(Ty) &&
697 "Abstract type not in AbstractTypeMap?");
698 typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
699 if (ATMEntryIt == I) {
700 // Yes, we are removing the representative entry for this type.
701 // See if there are any other entries of the same type.
702 typename MapTy::iterator TmpIt = ATMEntryIt;
704 // First check the entry before this one...
705 if (TmpIt != Map.begin()) {
707 if (TmpIt->first.first != Ty) // Not the same type, move back...
711 // If we didn't find the same type, try to move forward...
712 if (TmpIt == ATMEntryIt) {
714 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
715 --TmpIt; // No entry afterwards with the same type
718 // If there is another entry in the map of the same abstract type,
719 // update the AbstractTypeMap entry now.
720 if (TmpIt != ATMEntryIt) {
723 // Otherwise, we are removing the last instance of this type
724 // from the table. Remove from the ATM, and from user list.
725 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
726 AbstractTypeMap.erase(Ty);
735 /// MoveConstantToNewSlot - If we are about to change C to be the element
736 /// specified by I, update our internal data structures to reflect this
738 void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
739 // First, remove the old location of the specified constant in the map.
740 typename MapTy::iterator OldI = FindExistingElement(C);
741 assert(OldI != Map.end() && "Constant not found in constant table!");
742 assert(OldI->second == C && "Didn't find correct element?");
744 // If this constant is the representative element for its abstract type,
745 // update the AbstractTypeMap so that the representative element is I.
746 if (C->getType()->isAbstract()) {
747 typename AbstractTypeMapTy::iterator ATI =
748 AbstractTypeMap.find(C->getType());
749 assert(ATI != AbstractTypeMap.end() &&
750 "Abstract type not in AbstractTypeMap?");
751 if (ATI->second == OldI)
755 // Remove the old entry from the map.
758 // Update the inverse map so that we know that this constant is now
759 // located at descriptor I.
761 assert(I->second == C && "Bad inversemap entry!");
766 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
767 typename AbstractTypeMapTy::iterator I =
768 AbstractTypeMap.find(cast<Type>(OldTy));
770 assert(I != AbstractTypeMap.end() &&
771 "Abstract type not in AbstractTypeMap?");
773 // Convert a constant at a time until the last one is gone. The last one
774 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
775 // eliminated eventually.
777 ConvertConstantType<ConstantClass,
779 static_cast<ConstantClass *>(I->second->second),
780 cast<TypeClass>(NewTy));
782 I = AbstractTypeMap.find(cast<Type>(OldTy));
783 } while (I != AbstractTypeMap.end());
786 // If the type became concrete without being refined to any other existing
787 // type, we just remove ourselves from the ATU list.
788 void typeBecameConcrete(const DerivedType *AbsTy) {
789 AbsTy->removeAbstractTypeUser(this);
793 DOUT << "Constant.cpp: ValueMap\n";
799 //---- ConstantInt::get() implementations...
801 static ManagedStatic<ValueMap<uint64_t, IntegerType, ConstantInt> >IntConstants;
804 // Get a ConstantInt from an int64_t. Note here that we canoncialize the value
805 // to a uint64_t value that has been zero extended down to the size of the
806 // integer type of the ConstantInt. This allows the getZExtValue method to
807 // just return the stored value while getSExtValue has to convert back to sign
808 // extended. getZExtValue is more common in LLVM than getSExtValue().
809 ConstantInt *ConstantInt::get(const Type *Ty, int64_t V) {
810 const IntegerType *ITy = cast<IntegerType>(Ty);
811 return IntConstants->getOrCreate(ITy, V & ITy->getBitMask());
814 ConstantInt *ConstantInt::TheTrueVal = 0;
815 ConstantInt *ConstantInt::TheFalseVal = 0;
817 void CleanupTrueFalse(void *) {
818 ConstantInt::ResetTrueFalse();
821 static ManagedCleanup<CleanupTrueFalse> TrueFalseCleanup;
823 ConstantInt *ConstantInt::CreateTrueFalseVals(bool WhichOne) {
824 assert(TheTrueVal == 0 && TheFalseVal == 0);
825 TheTrueVal = get(Type::Int1Ty, 1);
826 TheFalseVal = get(Type::Int1Ty, 0);
828 // Ensure that llvm_shutdown nulls out TheTrueVal/TheFalseVal.
829 TrueFalseCleanup.Register();
831 return WhichOne ? TheTrueVal : TheFalseVal;
837 //---- ConstantFP::get() implementation...
841 struct ConstantCreator<ConstantFP, Type, uint64_t> {
842 static ConstantFP *create(const Type *Ty, uint64_t V) {
843 assert(Ty == Type::DoubleTy);
844 return new ConstantFP(Ty, BitsToDouble(V));
848 struct ConstantCreator<ConstantFP, Type, uint32_t> {
849 static ConstantFP *create(const Type *Ty, uint32_t V) {
850 assert(Ty == Type::FloatTy);
851 return new ConstantFP(Ty, BitsToFloat(V));
856 static ManagedStatic<ValueMap<uint64_t, Type, ConstantFP> > DoubleConstants;
857 static ManagedStatic<ValueMap<uint32_t, Type, ConstantFP> > FloatConstants;
859 bool ConstantFP::isNullValue() const {
860 return DoubleToBits(Val) == 0;
863 bool ConstantFP::isExactlyValue(double V) const {
864 return DoubleToBits(V) == DoubleToBits(Val);
868 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
869 if (Ty == Type::FloatTy) {
870 // Force the value through memory to normalize it.
871 return FloatConstants->getOrCreate(Ty, FloatToBits(V));
873 assert(Ty == Type::DoubleTy);
874 return DoubleConstants->getOrCreate(Ty, DoubleToBits(V));
878 //---- ConstantAggregateZero::get() implementation...
881 // ConstantAggregateZero does not take extra "value" argument...
882 template<class ValType>
883 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
884 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
885 return new ConstantAggregateZero(Ty);
890 struct ConvertConstantType<ConstantAggregateZero, Type> {
891 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
892 // Make everyone now use a constant of the new type...
893 Constant *New = ConstantAggregateZero::get(NewTy);
894 assert(New != OldC && "Didn't replace constant??");
895 OldC->uncheckedReplaceAllUsesWith(New);
896 OldC->destroyConstant(); // This constant is now dead, destroy it.
901 static ManagedStatic<ValueMap<char, Type,
902 ConstantAggregateZero> > AggZeroConstants;
904 static char getValType(ConstantAggregateZero *CPZ) { return 0; }
906 Constant *ConstantAggregateZero::get(const Type *Ty) {
907 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) &&
908 "Cannot create an aggregate zero of non-aggregate type!");
909 return AggZeroConstants->getOrCreate(Ty, 0);
912 // destroyConstant - Remove the constant from the constant table...
914 void ConstantAggregateZero::destroyConstant() {
915 AggZeroConstants->remove(this);
916 destroyConstantImpl();
919 //---- ConstantArray::get() implementation...
923 struct ConvertConstantType<ConstantArray, ArrayType> {
924 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
925 // Make everyone now use a constant of the new type...
926 std::vector<Constant*> C;
927 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
928 C.push_back(cast<Constant>(OldC->getOperand(i)));
929 Constant *New = ConstantArray::get(NewTy, C);
930 assert(New != OldC && "Didn't replace constant??");
931 OldC->uncheckedReplaceAllUsesWith(New);
932 OldC->destroyConstant(); // This constant is now dead, destroy it.
937 static std::vector<Constant*> getValType(ConstantArray *CA) {
938 std::vector<Constant*> Elements;
939 Elements.reserve(CA->getNumOperands());
940 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
941 Elements.push_back(cast<Constant>(CA->getOperand(i)));
945 typedef ValueMap<std::vector<Constant*>, ArrayType,
946 ConstantArray, true /*largekey*/> ArrayConstantsTy;
947 static ManagedStatic<ArrayConstantsTy> ArrayConstants;
949 Constant *ConstantArray::get(const ArrayType *Ty,
950 const std::vector<Constant*> &V) {
951 // If this is an all-zero array, return a ConstantAggregateZero object
954 if (!C->isNullValue())
955 return ArrayConstants->getOrCreate(Ty, V);
956 for (unsigned i = 1, e = V.size(); i != e; ++i)
958 return ArrayConstants->getOrCreate(Ty, V);
960 return ConstantAggregateZero::get(Ty);
963 // destroyConstant - Remove the constant from the constant table...
965 void ConstantArray::destroyConstant() {
966 ArrayConstants->remove(this);
967 destroyConstantImpl();
970 /// ConstantArray::get(const string&) - Return an array that is initialized to
971 /// contain the specified string. If length is zero then a null terminator is
972 /// added to the specified string so that it may be used in a natural way.
973 /// Otherwise, the length parameter specifies how much of the string to use
974 /// and it won't be null terminated.
976 Constant *ConstantArray::get(const std::string &Str, bool AddNull) {
977 std::vector<Constant*> ElementVals;
978 for (unsigned i = 0; i < Str.length(); ++i)
979 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, Str[i]));
981 // Add a null terminator to the string...
983 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, 0));
986 ArrayType *ATy = ArrayType::get(Type::Int8Ty, ElementVals.size());
987 return ConstantArray::get(ATy, ElementVals);
990 /// isString - This method returns true if the array is an array of i8, and
991 /// if the elements of the array are all ConstantInt's.
992 bool ConstantArray::isString() const {
993 // Check the element type for i8...
994 if (getType()->getElementType() != Type::Int8Ty)
996 // Check the elements to make sure they are all integers, not constant
998 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
999 if (!isa<ConstantInt>(getOperand(i)))
1004 /// isCString - This method returns true if the array is a string (see
1005 /// isString) and it ends in a null byte \0 and does not contains any other
1006 /// null bytes except its terminator.
1007 bool ConstantArray::isCString() const {
1008 // Check the element type for i8...
1009 if (getType()->getElementType() != Type::Int8Ty)
1011 Constant *Zero = Constant::getNullValue(getOperand(0)->getType());
1012 // Last element must be a null.
1013 if (getOperand(getNumOperands()-1) != Zero)
1015 // Other elements must be non-null integers.
1016 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1017 if (!isa<ConstantInt>(getOperand(i)))
1019 if (getOperand(i) == Zero)
1026 // getAsString - If the sub-element type of this array is i8
1027 // then this method converts the array to an std::string and returns it.
1028 // Otherwise, it asserts out.
1030 std::string ConstantArray::getAsString() const {
1031 assert(isString() && "Not a string!");
1033 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1034 Result += (char)cast<ConstantInt>(getOperand(i))->getZExtValue();
1039 //---- ConstantStruct::get() implementation...
1044 struct ConvertConstantType<ConstantStruct, StructType> {
1045 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1046 // Make everyone now use a constant of the new type...
1047 std::vector<Constant*> C;
1048 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1049 C.push_back(cast<Constant>(OldC->getOperand(i)));
1050 Constant *New = ConstantStruct::get(NewTy, C);
1051 assert(New != OldC && "Didn't replace constant??");
1053 OldC->uncheckedReplaceAllUsesWith(New);
1054 OldC->destroyConstant(); // This constant is now dead, destroy it.
1059 typedef ValueMap<std::vector<Constant*>, StructType,
1060 ConstantStruct, true /*largekey*/> StructConstantsTy;
1061 static ManagedStatic<StructConstantsTy> StructConstants;
1063 static std::vector<Constant*> getValType(ConstantStruct *CS) {
1064 std::vector<Constant*> Elements;
1065 Elements.reserve(CS->getNumOperands());
1066 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1067 Elements.push_back(cast<Constant>(CS->getOperand(i)));
1071 Constant *ConstantStruct::get(const StructType *Ty,
1072 const std::vector<Constant*> &V) {
1073 // Create a ConstantAggregateZero value if all elements are zeros...
1074 for (unsigned i = 0, e = V.size(); i != e; ++i)
1075 if (!V[i]->isNullValue())
1076 return StructConstants->getOrCreate(Ty, V);
1078 return ConstantAggregateZero::get(Ty);
1081 Constant *ConstantStruct::get(const std::vector<Constant*> &V, bool packed) {
1082 std::vector<const Type*> StructEls;
1083 StructEls.reserve(V.size());
1084 for (unsigned i = 0, e = V.size(); i != e; ++i)
1085 StructEls.push_back(V[i]->getType());
1086 return get(StructType::get(StructEls, packed), V);
1089 // destroyConstant - Remove the constant from the constant table...
1091 void ConstantStruct::destroyConstant() {
1092 StructConstants->remove(this);
1093 destroyConstantImpl();
1096 //---- ConstantVector::get() implementation...
1100 struct ConvertConstantType<ConstantVector, VectorType> {
1101 static void convert(ConstantVector *OldC, const VectorType *NewTy) {
1102 // Make everyone now use a constant of the new type...
1103 std::vector<Constant*> C;
1104 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1105 C.push_back(cast<Constant>(OldC->getOperand(i)));
1106 Constant *New = ConstantVector::get(NewTy, C);
1107 assert(New != OldC && "Didn't replace constant??");
1108 OldC->uncheckedReplaceAllUsesWith(New);
1109 OldC->destroyConstant(); // This constant is now dead, destroy it.
1114 static std::vector<Constant*> getValType(ConstantVector *CP) {
1115 std::vector<Constant*> Elements;
1116 Elements.reserve(CP->getNumOperands());
1117 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1118 Elements.push_back(CP->getOperand(i));
1122 static ManagedStatic<ValueMap<std::vector<Constant*>, VectorType,
1123 ConstantVector> > VectorConstants;
1125 Constant *ConstantVector::get(const VectorType *Ty,
1126 const std::vector<Constant*> &V) {
1127 // If this is an all-zero packed, return a ConstantAggregateZero object
1130 if (!C->isNullValue())
1131 return VectorConstants->getOrCreate(Ty, V);
1132 for (unsigned i = 1, e = V.size(); i != e; ++i)
1134 return VectorConstants->getOrCreate(Ty, V);
1136 return ConstantAggregateZero::get(Ty);
1139 Constant *ConstantVector::get(const std::vector<Constant*> &V) {
1140 assert(!V.empty() && "Cannot infer type if V is empty");
1141 return get(VectorType::get(V.front()->getType(),V.size()), V);
1144 // destroyConstant - Remove the constant from the constant table...
1146 void ConstantVector::destroyConstant() {
1147 VectorConstants->remove(this);
1148 destroyConstantImpl();
1151 /// This function will return true iff every element in this packed constant
1152 /// is set to all ones.
1153 /// @returns true iff this constant's emements are all set to all ones.
1154 /// @brief Determine if the value is all ones.
1155 bool ConstantVector::isAllOnesValue() const {
1156 // Check out first element.
1157 const Constant *Elt = getOperand(0);
1158 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1159 if (!CI || !CI->isAllOnesValue()) return false;
1160 // Then make sure all remaining elements point to the same value.
1161 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1162 if (getOperand(I) != Elt) return false;
1167 //---- ConstantPointerNull::get() implementation...
1171 // ConstantPointerNull does not take extra "value" argument...
1172 template<class ValType>
1173 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1174 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1175 return new ConstantPointerNull(Ty);
1180 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1181 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1182 // Make everyone now use a constant of the new type...
1183 Constant *New = ConstantPointerNull::get(NewTy);
1184 assert(New != OldC && "Didn't replace constant??");
1185 OldC->uncheckedReplaceAllUsesWith(New);
1186 OldC->destroyConstant(); // This constant is now dead, destroy it.
1191 static ManagedStatic<ValueMap<char, PointerType,
1192 ConstantPointerNull> > NullPtrConstants;
1194 static char getValType(ConstantPointerNull *) {
1199 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1200 return NullPtrConstants->getOrCreate(Ty, 0);
1203 // destroyConstant - Remove the constant from the constant table...
1205 void ConstantPointerNull::destroyConstant() {
1206 NullPtrConstants->remove(this);
1207 destroyConstantImpl();
1211 //---- UndefValue::get() implementation...
1215 // UndefValue does not take extra "value" argument...
1216 template<class ValType>
1217 struct ConstantCreator<UndefValue, Type, ValType> {
1218 static UndefValue *create(const Type *Ty, const ValType &V) {
1219 return new UndefValue(Ty);
1224 struct ConvertConstantType<UndefValue, Type> {
1225 static void convert(UndefValue *OldC, const Type *NewTy) {
1226 // Make everyone now use a constant of the new type.
1227 Constant *New = UndefValue::get(NewTy);
1228 assert(New != OldC && "Didn't replace constant??");
1229 OldC->uncheckedReplaceAllUsesWith(New);
1230 OldC->destroyConstant(); // This constant is now dead, destroy it.
1235 static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
1237 static char getValType(UndefValue *) {
1242 UndefValue *UndefValue::get(const Type *Ty) {
1243 return UndefValueConstants->getOrCreate(Ty, 0);
1246 // destroyConstant - Remove the constant from the constant table.
1248 void UndefValue::destroyConstant() {
1249 UndefValueConstants->remove(this);
1250 destroyConstantImpl();
1254 //---- ConstantExpr::get() implementations...
1257 struct ExprMapKeyType {
1258 explicit ExprMapKeyType(unsigned opc, std::vector<Constant*> ops,
1259 unsigned short pred = 0) : opcode(opc), predicate(pred), operands(ops) { }
1262 std::vector<Constant*> operands;
1263 bool operator==(const ExprMapKeyType& that) const {
1264 return this->opcode == that.opcode &&
1265 this->predicate == that.predicate &&
1266 this->operands == that.operands;
1268 bool operator<(const ExprMapKeyType & that) const {
1269 return this->opcode < that.opcode ||
1270 (this->opcode == that.opcode && this->predicate < that.predicate) ||
1271 (this->opcode == that.opcode && this->predicate == that.predicate &&
1272 this->operands < that.operands);
1275 bool operator!=(const ExprMapKeyType& that) const {
1276 return !(*this == that);
1282 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1283 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1284 unsigned short pred = 0) {
1285 if (Instruction::isCast(V.opcode))
1286 return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1287 if ((V.opcode >= Instruction::BinaryOpsBegin &&
1288 V.opcode < Instruction::BinaryOpsEnd))
1289 return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1290 if (V.opcode == Instruction::Select)
1291 return new SelectConstantExpr(V.operands[0], V.operands[1],
1293 if (V.opcode == Instruction::ExtractElement)
1294 return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1295 if (V.opcode == Instruction::InsertElement)
1296 return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1298 if (V.opcode == Instruction::ShuffleVector)
1299 return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1301 if (V.opcode == Instruction::GetElementPtr) {
1302 std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
1303 return new GetElementPtrConstantExpr(V.operands[0], IdxList, Ty);
1306 // The compare instructions are weird. We have to encode the predicate
1307 // value and it is combined with the instruction opcode by multiplying
1308 // the opcode by one hundred. We must decode this to get the predicate.
1309 if (V.opcode == Instruction::ICmp)
1310 return new CompareConstantExpr(Instruction::ICmp, V.predicate,
1311 V.operands[0], V.operands[1]);
1312 if (V.opcode == Instruction::FCmp)
1313 return new CompareConstantExpr(Instruction::FCmp, V.predicate,
1314 V.operands[0], V.operands[1]);
1315 assert(0 && "Invalid ConstantExpr!");
1321 struct ConvertConstantType<ConstantExpr, Type> {
1322 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1324 switch (OldC->getOpcode()) {
1325 case Instruction::Trunc:
1326 case Instruction::ZExt:
1327 case Instruction::SExt:
1328 case Instruction::FPTrunc:
1329 case Instruction::FPExt:
1330 case Instruction::UIToFP:
1331 case Instruction::SIToFP:
1332 case Instruction::FPToUI:
1333 case Instruction::FPToSI:
1334 case Instruction::PtrToInt:
1335 case Instruction::IntToPtr:
1336 case Instruction::BitCast:
1337 New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0),
1340 case Instruction::Select:
1341 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1342 OldC->getOperand(1),
1343 OldC->getOperand(2));
1346 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1347 OldC->getOpcode() < Instruction::BinaryOpsEnd);
1348 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1349 OldC->getOperand(1));
1351 case Instruction::GetElementPtr:
1352 // Make everyone now use a constant of the new type...
1353 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1354 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0),
1355 &Idx[0], Idx.size());
1359 assert(New != OldC && "Didn't replace constant??");
1360 OldC->uncheckedReplaceAllUsesWith(New);
1361 OldC->destroyConstant(); // This constant is now dead, destroy it.
1364 } // end namespace llvm
1367 static ExprMapKeyType getValType(ConstantExpr *CE) {
1368 std::vector<Constant*> Operands;
1369 Operands.reserve(CE->getNumOperands());
1370 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1371 Operands.push_back(cast<Constant>(CE->getOperand(i)));
1372 return ExprMapKeyType(CE->getOpcode(), Operands,
1373 CE->isCompare() ? CE->getPredicate() : 0);
1376 static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1377 ConstantExpr> > ExprConstants;
1379 /// This is a utility function to handle folding of casts and lookup of the
1380 /// cast in the ExprConstants map. It is usedby the various get* methods below.
1381 static inline Constant *getFoldedCast(
1382 Instruction::CastOps opc, Constant *C, const Type *Ty) {
1383 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1384 // Fold a few common cases
1385 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1388 // Look up the constant in the table first to ensure uniqueness
1389 std::vector<Constant*> argVec(1, C);
1390 ExprMapKeyType Key(opc, argVec);
1391 return ExprConstants->getOrCreate(Ty, Key);
1394 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1395 Instruction::CastOps opc = Instruction::CastOps(oc);
1396 assert(Instruction::isCast(opc) && "opcode out of range");
1397 assert(C && Ty && "Null arguments to getCast");
1398 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1402 assert(0 && "Invalid cast opcode");
1404 case Instruction::Trunc: return getTrunc(C, Ty);
1405 case Instruction::ZExt: return getZExt(C, Ty);
1406 case Instruction::SExt: return getSExt(C, Ty);
1407 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1408 case Instruction::FPExt: return getFPExtend(C, Ty);
1409 case Instruction::UIToFP: return getUIToFP(C, Ty);
1410 case Instruction::SIToFP: return getSIToFP(C, Ty);
1411 case Instruction::FPToUI: return getFPToUI(C, Ty);
1412 case Instruction::FPToSI: return getFPToSI(C, Ty);
1413 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1414 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1415 case Instruction::BitCast: return getBitCast(C, Ty);
1420 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1421 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1422 return getCast(Instruction::BitCast, C, Ty);
1423 return getCast(Instruction::ZExt, C, Ty);
1426 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1427 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1428 return getCast(Instruction::BitCast, C, Ty);
1429 return getCast(Instruction::SExt, C, Ty);
1432 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1433 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1434 return getCast(Instruction::BitCast, C, Ty);
1435 return getCast(Instruction::Trunc, C, Ty);
1438 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1439 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1440 assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
1442 if (Ty->isInteger())
1443 return getCast(Instruction::PtrToInt, S, Ty);
1444 return getCast(Instruction::BitCast, S, Ty);
1447 Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
1449 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1450 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1451 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1452 Instruction::CastOps opcode =
1453 (SrcBits == DstBits ? Instruction::BitCast :
1454 (SrcBits > DstBits ? Instruction::Trunc :
1455 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1456 return getCast(opcode, C, Ty);
1459 Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1460 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1462 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1463 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1464 if (SrcBits == DstBits)
1465 return C; // Avoid a useless cast
1466 Instruction::CastOps opcode =
1467 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1468 return getCast(opcode, C, Ty);
1471 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
1472 assert(C->getType()->isInteger() && "Trunc operand must be integer");
1473 assert(Ty->isInteger() && "Trunc produces only integral");
1474 assert(C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1475 "SrcTy must be larger than DestTy for Trunc!");
1477 return getFoldedCast(Instruction::Trunc, C, Ty);
1480 Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
1481 assert(C->getType()->isInteger() && "SEXt operand must be integral");
1482 assert(Ty->isInteger() && "SExt produces only integer");
1483 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1484 "SrcTy must be smaller than DestTy for SExt!");
1486 return getFoldedCast(Instruction::SExt, C, Ty);
1489 Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
1490 assert(C->getType()->isInteger() && "ZEXt operand must be integral");
1491 assert(Ty->isInteger() && "ZExt produces only integer");
1492 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1493 "SrcTy must be smaller than DestTy for ZExt!");
1495 return getFoldedCast(Instruction::ZExt, C, Ty);
1498 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1499 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1500 C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1501 "This is an illegal floating point truncation!");
1502 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1505 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1506 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1507 C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1508 "This is an illegal floating point extension!");
1509 return getFoldedCast(Instruction::FPExt, C, Ty);
1512 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
1513 assert(C->getType()->isInteger() && Ty->isFloatingPoint() &&
1514 "This is an illegal i32 to floating point cast!");
1515 return getFoldedCast(Instruction::UIToFP, C, Ty);
1518 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
1519 assert(C->getType()->isInteger() && Ty->isFloatingPoint() &&
1520 "This is an illegal sint to floating point cast!");
1521 return getFoldedCast(Instruction::SIToFP, C, Ty);
1524 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
1525 assert(C->getType()->isFloatingPoint() && Ty->isInteger() &&
1526 "This is an illegal floating point to i32 cast!");
1527 return getFoldedCast(Instruction::FPToUI, C, Ty);
1530 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
1531 assert(C->getType()->isFloatingPoint() && Ty->isInteger() &&
1532 "This is an illegal floating point to i32 cast!");
1533 return getFoldedCast(Instruction::FPToSI, C, Ty);
1536 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1537 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
1538 assert(DstTy->isInteger() && "PtrToInt destination must be integral");
1539 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1542 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
1543 assert(C->getType()->isInteger() && "IntToPtr source must be integral");
1544 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
1545 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1548 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1549 // BitCast implies a no-op cast of type only. No bits change. However, you
1550 // can't cast pointers to anything but pointers.
1551 const Type *SrcTy = C->getType();
1552 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
1553 "BitCast cannot cast pointer to non-pointer and vice versa");
1555 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
1556 // or nonptr->ptr). For all the other types, the cast is okay if source and
1557 // destination bit widths are identical.
1558 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1559 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
1560 assert(SrcBitSize == DstBitSize && "BitCast requies types of same width");
1561 return getFoldedCast(Instruction::BitCast, C, DstTy);
1564 Constant *ConstantExpr::getSizeOf(const Type *Ty) {
1565 // sizeof is implemented as: (ulong) gep (Ty*)null, 1
1566 Constant *GEPIdx = ConstantInt::get(Type::Int32Ty, 1);
1568 getGetElementPtr(getNullValue(PointerType::get(Ty)), &GEPIdx, 1);
1569 return getCast(Instruction::PtrToInt, GEP, Type::Int64Ty);
1572 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1573 Constant *C1, Constant *C2) {
1574 // Check the operands for consistency first
1575 assert(Opcode >= Instruction::BinaryOpsBegin &&
1576 Opcode < Instruction::BinaryOpsEnd &&
1577 "Invalid opcode in binary constant expression");
1578 assert(C1->getType() == C2->getType() &&
1579 "Operand types in binary constant expression should match");
1581 if (ReqTy == C1->getType() || ReqTy == Type::Int1Ty)
1582 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1583 return FC; // Fold a few common cases...
1585 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1586 ExprMapKeyType Key(Opcode, argVec);
1587 return ExprConstants->getOrCreate(ReqTy, Key);
1590 Constant *ConstantExpr::getCompareTy(unsigned short predicate,
1591 Constant *C1, Constant *C2) {
1592 switch (predicate) {
1593 default: assert(0 && "Invalid CmpInst predicate");
1594 case FCmpInst::FCMP_FALSE: case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_OGT:
1595 case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OLE:
1596 case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_ORD: case FCmpInst::FCMP_UNO:
1597 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UGT: case FCmpInst::FCMP_UGE:
1598 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_ULE: case FCmpInst::FCMP_UNE:
1599 case FCmpInst::FCMP_TRUE:
1600 return getFCmp(predicate, C1, C2);
1601 case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGT:
1602 case ICmpInst::ICMP_UGE: case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE:
1603 case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_SGE: case ICmpInst::ICMP_SLT:
1604 case ICmpInst::ICMP_SLE:
1605 return getICmp(predicate, C1, C2);
1609 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
1612 case Instruction::Add:
1613 case Instruction::Sub:
1614 case Instruction::Mul:
1615 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1616 assert((C1->getType()->isInteger() || C1->getType()->isFloatingPoint() ||
1617 isa<VectorType>(C1->getType())) &&
1618 "Tried to create an arithmetic operation on a non-arithmetic type!");
1620 case Instruction::UDiv:
1621 case Instruction::SDiv:
1622 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1623 assert((C1->getType()->isInteger() || (isa<VectorType>(C1->getType()) &&
1624 cast<VectorType>(C1->getType())->getElementType()->isInteger())) &&
1625 "Tried to create an arithmetic operation on a non-arithmetic type!");
1627 case Instruction::FDiv:
1628 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1629 assert((C1->getType()->isFloatingPoint() || (isa<VectorType>(C1->getType())
1630 && cast<VectorType>(C1->getType())->getElementType()->isFloatingPoint()))
1631 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1633 case Instruction::URem:
1634 case Instruction::SRem:
1635 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1636 assert((C1->getType()->isInteger() || (isa<VectorType>(C1->getType()) &&
1637 cast<VectorType>(C1->getType())->getElementType()->isInteger())) &&
1638 "Tried to create an arithmetic operation on a non-arithmetic type!");
1640 case Instruction::FRem:
1641 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1642 assert((C1->getType()->isFloatingPoint() || (isa<VectorType>(C1->getType())
1643 && cast<VectorType>(C1->getType())->getElementType()->isFloatingPoint()))
1644 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1646 case Instruction::And:
1647 case Instruction::Or:
1648 case Instruction::Xor:
1649 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1650 assert((C1->getType()->isInteger() || isa<VectorType>(C1->getType())) &&
1651 "Tried to create a logical operation on a non-integral type!");
1653 case Instruction::Shl:
1654 case Instruction::LShr:
1655 case Instruction::AShr:
1656 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1657 assert(C1->getType()->isInteger() &&
1658 "Tried to create a shift operation on a non-integer type!");
1665 return getTy(C1->getType(), Opcode, C1, C2);
1668 Constant *ConstantExpr::getCompare(unsigned short pred,
1669 Constant *C1, Constant *C2) {
1670 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1671 return getCompareTy(pred, C1, C2);
1674 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1675 Constant *V1, Constant *V2) {
1676 assert(C->getType() == Type::Int1Ty && "Select condition must be i1!");
1677 assert(V1->getType() == V2->getType() && "Select value types must match!");
1678 assert(V1->getType()->isFirstClassType() && "Cannot select aggregate type!");
1680 if (ReqTy == V1->getType())
1681 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1682 return SC; // Fold common cases
1684 std::vector<Constant*> argVec(3, C);
1687 ExprMapKeyType Key(Instruction::Select, argVec);
1688 return ExprConstants->getOrCreate(ReqTy, Key);
1691 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1694 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs, NumIdx, true) &&
1695 "GEP indices invalid!");
1697 if (Constant *FC = ConstantFoldGetElementPtr(C, (Constant**)Idxs, NumIdx))
1698 return FC; // Fold a few common cases...
1700 assert(isa<PointerType>(C->getType()) &&
1701 "Non-pointer type for constant GetElementPtr expression");
1702 // Look up the constant in the table first to ensure uniqueness
1703 std::vector<Constant*> ArgVec;
1704 ArgVec.reserve(NumIdx+1);
1705 ArgVec.push_back(C);
1706 for (unsigned i = 0; i != NumIdx; ++i)
1707 ArgVec.push_back(cast<Constant>(Idxs[i]));
1708 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
1709 return ExprConstants->getOrCreate(ReqTy, Key);
1712 Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
1714 // Get the result type of the getelementptr!
1716 GetElementPtrInst::getIndexedType(C->getType(), Idxs, NumIdx, true);
1717 assert(Ty && "GEP indices invalid!");
1718 return getGetElementPtrTy(PointerType::get(Ty), C, Idxs, NumIdx);
1721 Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
1723 return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
1728 ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1729 assert(LHS->getType() == RHS->getType());
1730 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
1731 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1733 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1734 return FC; // Fold a few common cases...
1736 // Look up the constant in the table first to ensure uniqueness
1737 std::vector<Constant*> ArgVec;
1738 ArgVec.push_back(LHS);
1739 ArgVec.push_back(RHS);
1740 // Get the key type with both the opcode and predicate
1741 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
1742 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
1746 ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1747 assert(LHS->getType() == RHS->getType());
1748 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1750 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1751 return FC; // Fold a few common cases...
1753 // Look up the constant in the table first to ensure uniqueness
1754 std::vector<Constant*> ArgVec;
1755 ArgVec.push_back(LHS);
1756 ArgVec.push_back(RHS);
1757 // Get the key type with both the opcode and predicate
1758 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
1759 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
1762 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
1764 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
1765 return FC; // Fold a few common cases...
1766 // Look up the constant in the table first to ensure uniqueness
1767 std::vector<Constant*> ArgVec(1, Val);
1768 ArgVec.push_back(Idx);
1769 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
1770 return ExprConstants->getOrCreate(ReqTy, Key);
1773 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
1774 assert(isa<VectorType>(Val->getType()) &&
1775 "Tried to create extractelement operation on non-vector type!");
1776 assert(Idx->getType() == Type::Int32Ty &&
1777 "Extractelement index must be i32 type!");
1778 return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
1782 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
1783 Constant *Elt, Constant *Idx) {
1784 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
1785 return FC; // Fold a few common cases...
1786 // Look up the constant in the table first to ensure uniqueness
1787 std::vector<Constant*> ArgVec(1, Val);
1788 ArgVec.push_back(Elt);
1789 ArgVec.push_back(Idx);
1790 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
1791 return ExprConstants->getOrCreate(ReqTy, Key);
1794 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1796 assert(isa<VectorType>(Val->getType()) &&
1797 "Tried to create insertelement operation on non-vector type!");
1798 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
1799 && "Insertelement types must match!");
1800 assert(Idx->getType() == Type::Int32Ty &&
1801 "Insertelement index must be i32 type!");
1802 return getInsertElementTy(cast<VectorType>(Val->getType())->getElementType(),
1806 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
1807 Constant *V2, Constant *Mask) {
1808 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
1809 return FC; // Fold a few common cases...
1810 // Look up the constant in the table first to ensure uniqueness
1811 std::vector<Constant*> ArgVec(1, V1);
1812 ArgVec.push_back(V2);
1813 ArgVec.push_back(Mask);
1814 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
1815 return ExprConstants->getOrCreate(ReqTy, Key);
1818 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
1820 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1821 "Invalid shuffle vector constant expr operands!");
1822 return getShuffleVectorTy(V1->getType(), V1, V2, Mask);
1825 Constant *ConstantExpr::getZeroValueForNegationExpr(const Type *Ty) {
1826 if (const VectorType *PTy = dyn_cast<VectorType>(Ty))
1827 if (PTy->getElementType()->isFloatingPoint()) {
1828 std::vector<Constant*> zeros(PTy->getNumElements(),
1829 ConstantFP::get(PTy->getElementType(),-0.0));
1830 return ConstantVector::get(PTy, zeros);
1833 if (Ty->isFloatingPoint())
1834 return ConstantFP::get(Ty, -0.0);
1836 return Constant::getNullValue(Ty);
1839 // destroyConstant - Remove the constant from the constant table...
1841 void ConstantExpr::destroyConstant() {
1842 ExprConstants->remove(this);
1843 destroyConstantImpl();
1846 const char *ConstantExpr::getOpcodeName() const {
1847 return Instruction::getOpcodeName(getOpcode());
1850 //===----------------------------------------------------------------------===//
1851 // replaceUsesOfWithOnConstant implementations
1853 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
1855 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1856 Constant *ToC = cast<Constant>(To);
1858 unsigned OperandToUpdate = U-OperandList;
1859 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
1861 std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
1862 Lookup.first.first = getType();
1863 Lookup.second = this;
1865 std::vector<Constant*> &Values = Lookup.first.second;
1866 Values.reserve(getNumOperands()); // Build replacement array.
1868 // Fill values with the modified operands of the constant array. Also,
1869 // compute whether this turns into an all-zeros array.
1870 bool isAllZeros = false;
1871 if (!ToC->isNullValue()) {
1872 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
1873 Values.push_back(cast<Constant>(O->get()));
1876 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1877 Constant *Val = cast<Constant>(O->get());
1878 Values.push_back(Val);
1879 if (isAllZeros) isAllZeros = Val->isNullValue();
1882 Values[OperandToUpdate] = ToC;
1884 Constant *Replacement = 0;
1886 Replacement = ConstantAggregateZero::get(getType());
1888 // Check to see if we have this array type already.
1890 ArrayConstantsTy::MapTy::iterator I =
1891 ArrayConstants->InsertOrGetItem(Lookup, Exists);
1894 Replacement = I->second;
1896 // Okay, the new shape doesn't exist in the system yet. Instead of
1897 // creating a new constant array, inserting it, replaceallusesof'ing the
1898 // old with the new, then deleting the old... just update the current one
1900 ArrayConstants->MoveConstantToNewSlot(this, I);
1902 // Update to the new value.
1903 setOperand(OperandToUpdate, ToC);
1908 // Otherwise, I do need to replace this with an existing value.
1909 assert(Replacement != this && "I didn't contain From!");
1911 // Everyone using this now uses the replacement.
1912 uncheckedReplaceAllUsesWith(Replacement);
1914 // Delete the old constant!
1918 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
1920 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1921 Constant *ToC = cast<Constant>(To);
1923 unsigned OperandToUpdate = U-OperandList;
1924 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
1926 std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
1927 Lookup.first.first = getType();
1928 Lookup.second = this;
1929 std::vector<Constant*> &Values = Lookup.first.second;
1930 Values.reserve(getNumOperands()); // Build replacement struct.
1933 // Fill values with the modified operands of the constant struct. Also,
1934 // compute whether this turns into an all-zeros struct.
1935 bool isAllZeros = false;
1936 if (!ToC->isNullValue()) {
1937 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
1938 Values.push_back(cast<Constant>(O->get()));
1941 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1942 Constant *Val = cast<Constant>(O->get());
1943 Values.push_back(Val);
1944 if (isAllZeros) isAllZeros = Val->isNullValue();
1947 Values[OperandToUpdate] = ToC;
1949 Constant *Replacement = 0;
1951 Replacement = ConstantAggregateZero::get(getType());
1953 // Check to see if we have this array type already.
1955 StructConstantsTy::MapTy::iterator I =
1956 StructConstants->InsertOrGetItem(Lookup, Exists);
1959 Replacement = I->second;
1961 // Okay, the new shape doesn't exist in the system yet. Instead of
1962 // creating a new constant struct, inserting it, replaceallusesof'ing the
1963 // old with the new, then deleting the old... just update the current one
1965 StructConstants->MoveConstantToNewSlot(this, I);
1967 // Update to the new value.
1968 setOperand(OperandToUpdate, ToC);
1973 assert(Replacement != this && "I didn't contain From!");
1975 // Everyone using this now uses the replacement.
1976 uncheckedReplaceAllUsesWith(Replacement);
1978 // Delete the old constant!
1982 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
1984 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1986 std::vector<Constant*> Values;
1987 Values.reserve(getNumOperands()); // Build replacement array...
1988 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1989 Constant *Val = getOperand(i);
1990 if (Val == From) Val = cast<Constant>(To);
1991 Values.push_back(Val);
1994 Constant *Replacement = ConstantVector::get(getType(), Values);
1995 assert(Replacement != this && "I didn't contain From!");
1997 // Everyone using this now uses the replacement.
1998 uncheckedReplaceAllUsesWith(Replacement);
2000 // Delete the old constant!
2004 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2006 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2007 Constant *To = cast<Constant>(ToV);
2009 Constant *Replacement = 0;
2010 if (getOpcode() == Instruction::GetElementPtr) {
2011 SmallVector<Constant*, 8> Indices;
2012 Constant *Pointer = getOperand(0);
2013 Indices.reserve(getNumOperands()-1);
2014 if (Pointer == From) Pointer = To;
2016 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2017 Constant *Val = getOperand(i);
2018 if (Val == From) Val = To;
2019 Indices.push_back(Val);
2021 Replacement = ConstantExpr::getGetElementPtr(Pointer,
2022 &Indices[0], Indices.size());
2023 } else if (isCast()) {
2024 assert(getOperand(0) == From && "Cast only has one use!");
2025 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
2026 } else if (getOpcode() == Instruction::Select) {
2027 Constant *C1 = getOperand(0);
2028 Constant *C2 = getOperand(1);
2029 Constant *C3 = getOperand(2);
2030 if (C1 == From) C1 = To;
2031 if (C2 == From) C2 = To;
2032 if (C3 == From) C3 = To;
2033 Replacement = ConstantExpr::getSelect(C1, C2, C3);
2034 } else if (getOpcode() == Instruction::ExtractElement) {
2035 Constant *C1 = getOperand(0);
2036 Constant *C2 = getOperand(1);
2037 if (C1 == From) C1 = To;
2038 if (C2 == From) C2 = To;
2039 Replacement = ConstantExpr::getExtractElement(C1, C2);
2040 } else if (getOpcode() == Instruction::InsertElement) {
2041 Constant *C1 = getOperand(0);
2042 Constant *C2 = getOperand(1);
2043 Constant *C3 = getOperand(1);
2044 if (C1 == From) C1 = To;
2045 if (C2 == From) C2 = To;
2046 if (C3 == From) C3 = To;
2047 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2048 } else if (getOpcode() == Instruction::ShuffleVector) {
2049 Constant *C1 = getOperand(0);
2050 Constant *C2 = getOperand(1);
2051 Constant *C3 = getOperand(2);
2052 if (C1 == From) C1 = To;
2053 if (C2 == From) C2 = To;
2054 if (C3 == From) C3 = To;
2055 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2056 } else if (isCompare()) {
2057 Constant *C1 = getOperand(0);
2058 Constant *C2 = getOperand(1);
2059 if (C1 == From) C1 = To;
2060 if (C2 == From) C2 = To;
2061 if (getOpcode() == Instruction::ICmp)
2062 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2064 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2065 } else if (getNumOperands() == 2) {
2066 Constant *C1 = getOperand(0);
2067 Constant *C2 = getOperand(1);
2068 if (C1 == From) C1 = To;
2069 if (C2 == From) C2 = To;
2070 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2072 assert(0 && "Unknown ConstantExpr type!");
2076 assert(Replacement != this && "I didn't contain From!");
2078 // Everyone using this now uses the replacement.
2079 uncheckedReplaceAllUsesWith(Replacement);
2081 // Delete the old constant!
2086 /// getStringValue - Turn an LLVM constant pointer that eventually points to a
2087 /// global into a string value. Return an empty string if we can't do it.
2088 /// Parameter Chop determines if the result is chopped at the first null
2091 std::string Constant::getStringValue(bool Chop, unsigned Offset) {
2092 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(this)) {
2093 if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
2094 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
2095 if (Init->isString()) {
2096 std::string Result = Init->getAsString();
2097 if (Offset < Result.size()) {
2098 // If we are pointing INTO The string, erase the beginning...
2099 Result.erase(Result.begin(), Result.begin()+Offset);
2101 // Take off the null terminator, and any string fragments after it.
2103 std::string::size_type NullPos = Result.find_first_of((char)0);
2104 if (NullPos != std::string::npos)
2105 Result.erase(Result.begin()+NullPos, Result.end());
2111 } else if (Constant *C = dyn_cast<Constant>(this)) {
2112 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
2113 return GV->getStringValue(Chop, Offset);
2114 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2115 if (CE->getOpcode() == Instruction::GetElementPtr) {
2116 // Turn a gep into the specified offset.
2117 if (CE->getNumOperands() == 3 &&
2118 cast<Constant>(CE->getOperand(1))->isNullValue() &&
2119 isa<ConstantInt>(CE->getOperand(2))) {
2120 Offset += cast<ConstantInt>(CE->getOperand(2))->getZExtValue();
2121 return CE->getOperand(0)->getStringValue(Chop, Offset);