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::IntegerTyID: {
96 const IntegerType *ITy = dyn_cast<IntegerType>(Ty);
97 switch (ITy->getBitWidth()) {
99 static Constant *NullBool = ConstantInt::get(Ty, false);
103 static Constant *NullInt8 = ConstantInt::get(Ty, 0);
107 static Constant *NullInt16 = ConstantInt::get(Ty, 0);
111 static Constant *NullInt32 = ConstantInt::get(Ty, 0);
115 static Constant *NullInt64 = ConstantInt::get(Ty, 0);
119 return ConstantInt::get(Ty, 0);
122 case Type::FloatTyID: {
123 static Constant *NullFloat = ConstantFP::get(Type::FloatTy, 0);
126 case Type::DoubleTyID: {
127 static Constant *NullDouble = ConstantFP::get(Type::DoubleTy, 0);
130 case Type::PointerTyID:
131 return ConstantPointerNull::get(cast<PointerType>(Ty));
132 case Type::StructTyID:
133 case Type::ArrayTyID:
134 case Type::PackedTyID:
135 return ConstantAggregateZero::get(Ty);
137 // Function, Label, or Opaque type?
138 assert(!"Cannot create a null constant of that type!");
144 // Static constructor to create an integral constant with all bits set
145 ConstantInt *ConstantInt::getAllOnesValue(const Type *Ty) {
146 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
147 if (ITy->getBitWidth() == 1)
148 return ConstantInt::getTrue();
150 return ConstantInt::get(Ty, int64_t(-1));
154 /// @returns the value for an packed integer constant of the given type that
155 /// has all its bits set to true.
156 /// @brief Get the all ones value
157 ConstantPacked *ConstantPacked::getAllOnesValue(const PackedType *Ty) {
158 std::vector<Constant*> Elts;
159 Elts.resize(Ty->getNumElements(),
160 ConstantInt::getAllOnesValue(Ty->getElementType()));
161 assert(Elts[0] && "Not a packed integer type!");
162 return cast<ConstantPacked>(ConstantPacked::get(Elts));
166 //===----------------------------------------------------------------------===//
167 // ConstantXXX Classes
168 //===----------------------------------------------------------------------===//
170 //===----------------------------------------------------------------------===//
171 // Normal Constructors
173 ConstantInt::ConstantInt(bool V)
174 : Constant(Type::Int1Ty, ConstantIntVal, 0, 0), Val(uint64_t(V)) {
177 ConstantInt::ConstantInt(const Type *Ty, uint64_t V)
178 : Constant(Ty, ConstantIntVal, 0, 0), Val(Ty == Type::Int1Ty ? bool(V) : V) {
181 ConstantFP::ConstantFP(const Type *Ty, double V)
182 : Constant(Ty, ConstantFPVal, 0, 0) {
183 assert(isValueValidForType(Ty, V) && "Value too large for type!");
187 ConstantArray::ConstantArray(const ArrayType *T,
188 const std::vector<Constant*> &V)
189 : Constant(T, ConstantArrayVal, new Use[V.size()], V.size()) {
190 assert(V.size() == T->getNumElements() &&
191 "Invalid initializer vector for constant array");
192 Use *OL = OperandList;
193 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
196 assert((C->getType() == T->getElementType() ||
198 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
199 "Initializer for array element doesn't match array element type!");
204 ConstantArray::~ConstantArray() {
205 delete [] OperandList;
208 ConstantStruct::ConstantStruct(const StructType *T,
209 const std::vector<Constant*> &V)
210 : Constant(T, ConstantStructVal, new Use[V.size()], V.size()) {
211 assert(V.size() == T->getNumElements() &&
212 "Invalid initializer vector for constant structure");
213 Use *OL = OperandList;
214 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
217 assert((C->getType() == T->getElementType(I-V.begin()) ||
218 ((T->getElementType(I-V.begin())->isAbstract() ||
219 C->getType()->isAbstract()) &&
220 T->getElementType(I-V.begin())->getTypeID() ==
221 C->getType()->getTypeID())) &&
222 "Initializer for struct element doesn't match struct element type!");
227 ConstantStruct::~ConstantStruct() {
228 delete [] OperandList;
232 ConstantPacked::ConstantPacked(const PackedType *T,
233 const std::vector<Constant*> &V)
234 : Constant(T, ConstantPackedVal, new Use[V.size()], V.size()) {
235 Use *OL = OperandList;
236 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
239 assert((C->getType() == T->getElementType() ||
241 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
242 "Initializer for packed element doesn't match packed element type!");
247 ConstantPacked::~ConstantPacked() {
248 delete [] OperandList;
251 // We declare several classes private to this file, so use an anonymous
255 /// UnaryConstantExpr - This class is private to Constants.cpp, and is used
256 /// behind the scenes to implement unary constant exprs.
257 class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
260 UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
261 : ConstantExpr(Ty, Opcode, &Op, 1), Op(C, this) {}
264 /// BinaryConstantExpr - This class is private to Constants.cpp, and is used
265 /// behind the scenes to implement binary constant exprs.
266 class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
269 BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
270 : ConstantExpr(C1->getType(), Opcode, Ops, 2) {
271 Ops[0].init(C1, this);
272 Ops[1].init(C2, this);
276 /// SelectConstantExpr - This class is private to Constants.cpp, and is used
277 /// behind the scenes to implement select constant exprs.
278 class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
281 SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
282 : ConstantExpr(C2->getType(), Instruction::Select, Ops, 3) {
283 Ops[0].init(C1, this);
284 Ops[1].init(C2, this);
285 Ops[2].init(C3, this);
289 /// ExtractElementConstantExpr - This class is private to
290 /// Constants.cpp, and is used behind the scenes to implement
291 /// extractelement constant exprs.
292 class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
295 ExtractElementConstantExpr(Constant *C1, Constant *C2)
296 : ConstantExpr(cast<PackedType>(C1->getType())->getElementType(),
297 Instruction::ExtractElement, Ops, 2) {
298 Ops[0].init(C1, this);
299 Ops[1].init(C2, this);
303 /// InsertElementConstantExpr - This class is private to
304 /// Constants.cpp, and is used behind the scenes to implement
305 /// insertelement constant exprs.
306 class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
309 InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
310 : ConstantExpr(C1->getType(), Instruction::InsertElement,
312 Ops[0].init(C1, this);
313 Ops[1].init(C2, this);
314 Ops[2].init(C3, this);
318 /// ShuffleVectorConstantExpr - This class is private to
319 /// Constants.cpp, and is used behind the scenes to implement
320 /// shufflevector constant exprs.
321 class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
324 ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
325 : ConstantExpr(C1->getType(), Instruction::ShuffleVector,
327 Ops[0].init(C1, this);
328 Ops[1].init(C2, this);
329 Ops[2].init(C3, this);
333 /// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
334 /// used behind the scenes to implement getelementpr constant exprs.
335 struct VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
336 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
338 : ConstantExpr(DestTy, Instruction::GetElementPtr,
339 new Use[IdxList.size()+1], IdxList.size()+1) {
340 OperandList[0].init(C, this);
341 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
342 OperandList[i+1].init(IdxList[i], this);
344 ~GetElementPtrConstantExpr() {
345 delete [] OperandList;
349 // CompareConstantExpr - This class is private to Constants.cpp, and is used
350 // behind the scenes to implement ICmp and FCmp constant expressions. This is
351 // needed in order to store the predicate value for these instructions.
352 struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
353 unsigned short predicate;
355 CompareConstantExpr(Instruction::OtherOps opc, unsigned short pred,
356 Constant* LHS, Constant* RHS)
357 : ConstantExpr(Type::Int1Ty, opc, Ops, 2), predicate(pred) {
358 OperandList[0].init(LHS, this);
359 OperandList[1].init(RHS, this);
363 } // end anonymous namespace
366 // Utility function for determining if a ConstantExpr is a CastOp or not. This
367 // can't be inline because we don't want to #include Instruction.h into
369 bool ConstantExpr::isCast() const {
370 return Instruction::isCast(getOpcode());
373 bool ConstantExpr::isCompare() const {
374 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
377 /// ConstantExpr::get* - Return some common constants without having to
378 /// specify the full Instruction::OPCODE identifier.
380 Constant *ConstantExpr::getNeg(Constant *C) {
381 if (!C->getType()->isFloatingPoint())
382 return get(Instruction::Sub, getNullValue(C->getType()), C);
384 return get(Instruction::Sub, ConstantFP::get(C->getType(), -0.0), C);
386 Constant *ConstantExpr::getNot(Constant *C) {
387 assert(isa<ConstantInt>(C) && "Cannot NOT a nonintegral type!");
388 return get(Instruction::Xor, C,
389 ConstantInt::getAllOnesValue(C->getType()));
391 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
392 return get(Instruction::Add, C1, C2);
394 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
395 return get(Instruction::Sub, C1, C2);
397 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
398 return get(Instruction::Mul, C1, C2);
400 Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2) {
401 return get(Instruction::UDiv, C1, C2);
403 Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2) {
404 return get(Instruction::SDiv, C1, C2);
406 Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
407 return get(Instruction::FDiv, C1, C2);
409 Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
410 return get(Instruction::URem, C1, C2);
412 Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
413 return get(Instruction::SRem, C1, C2);
415 Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
416 return get(Instruction::FRem, C1, C2);
418 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
419 return get(Instruction::And, C1, C2);
421 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
422 return get(Instruction::Or, C1, C2);
424 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
425 return get(Instruction::Xor, C1, C2);
427 unsigned ConstantExpr::getPredicate() const {
428 assert(getOpcode() == Instruction::FCmp || getOpcode() == Instruction::ICmp);
429 return dynamic_cast<const CompareConstantExpr*>(this)->predicate;
431 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
432 return get(Instruction::Shl, C1, C2);
434 Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2) {
435 return get(Instruction::LShr, C1, C2);
437 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2) {
438 return get(Instruction::AShr, C1, C2);
441 /// getWithOperandReplaced - Return a constant expression identical to this
442 /// one, but with the specified operand set to the specified value.
444 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
445 assert(OpNo < getNumOperands() && "Operand num is out of range!");
446 assert(Op->getType() == getOperand(OpNo)->getType() &&
447 "Replacing operand with value of different type!");
448 if (getOperand(OpNo) == Op)
449 return const_cast<ConstantExpr*>(this);
451 Constant *Op0, *Op1, *Op2;
452 switch (getOpcode()) {
453 case Instruction::Trunc:
454 case Instruction::ZExt:
455 case Instruction::SExt:
456 case Instruction::FPTrunc:
457 case Instruction::FPExt:
458 case Instruction::UIToFP:
459 case Instruction::SIToFP:
460 case Instruction::FPToUI:
461 case Instruction::FPToSI:
462 case Instruction::PtrToInt:
463 case Instruction::IntToPtr:
464 case Instruction::BitCast:
465 return ConstantExpr::getCast(getOpcode(), Op, getType());
466 case Instruction::Select:
467 Op0 = (OpNo == 0) ? Op : getOperand(0);
468 Op1 = (OpNo == 1) ? Op : getOperand(1);
469 Op2 = (OpNo == 2) ? Op : getOperand(2);
470 return ConstantExpr::getSelect(Op0, Op1, Op2);
471 case Instruction::InsertElement:
472 Op0 = (OpNo == 0) ? Op : getOperand(0);
473 Op1 = (OpNo == 1) ? Op : getOperand(1);
474 Op2 = (OpNo == 2) ? Op : getOperand(2);
475 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
476 case Instruction::ExtractElement:
477 Op0 = (OpNo == 0) ? Op : getOperand(0);
478 Op1 = (OpNo == 1) ? Op : getOperand(1);
479 return ConstantExpr::getExtractElement(Op0, Op1);
480 case Instruction::ShuffleVector:
481 Op0 = (OpNo == 0) ? Op : getOperand(0);
482 Op1 = (OpNo == 1) ? Op : getOperand(1);
483 Op2 = (OpNo == 2) ? Op : getOperand(2);
484 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
485 case Instruction::GetElementPtr: {
486 std::vector<Constant*> Ops;
487 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
488 Ops.push_back(getOperand(i));
490 return ConstantExpr::getGetElementPtr(Op, Ops);
492 return ConstantExpr::getGetElementPtr(getOperand(0), Ops);
495 assert(getNumOperands() == 2 && "Must be binary operator?");
496 Op0 = (OpNo == 0) ? Op : getOperand(0);
497 Op1 = (OpNo == 1) ? Op : getOperand(1);
498 return ConstantExpr::get(getOpcode(), Op0, Op1);
502 /// getWithOperands - This returns the current constant expression with the
503 /// operands replaced with the specified values. The specified operands must
504 /// match count and type with the existing ones.
505 Constant *ConstantExpr::
506 getWithOperands(const std::vector<Constant*> &Ops) const {
507 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
508 bool AnyChange = false;
509 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
510 assert(Ops[i]->getType() == getOperand(i)->getType() &&
511 "Operand type mismatch!");
512 AnyChange |= Ops[i] != getOperand(i);
514 if (!AnyChange) // No operands changed, return self.
515 return const_cast<ConstantExpr*>(this);
517 switch (getOpcode()) {
518 case Instruction::Trunc:
519 case Instruction::ZExt:
520 case Instruction::SExt:
521 case Instruction::FPTrunc:
522 case Instruction::FPExt:
523 case Instruction::UIToFP:
524 case Instruction::SIToFP:
525 case Instruction::FPToUI:
526 case Instruction::FPToSI:
527 case Instruction::PtrToInt:
528 case Instruction::IntToPtr:
529 case Instruction::BitCast:
530 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
531 case Instruction::Select:
532 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
533 case Instruction::InsertElement:
534 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
535 case Instruction::ExtractElement:
536 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
537 case Instruction::ShuffleVector:
538 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
539 case Instruction::GetElementPtr: {
540 std::vector<Constant*> ActualOps(Ops.begin()+1, Ops.end());
541 return ConstantExpr::getGetElementPtr(Ops[0], ActualOps);
543 case Instruction::ICmp:
544 case Instruction::FCmp:
545 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
547 assert(getNumOperands() == 2 && "Must be binary operator?");
548 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
553 //===----------------------------------------------------------------------===//
554 // isValueValidForType implementations
556 bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
557 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
558 assert(NumBits <= 64 && "Not implemented: integers > 64-bits");
559 if (Ty == Type::Int1Ty)
560 return Val == 0 || Val == 1;
562 return true; // always true, has to fit in largest type
563 uint64_t Max = (1ll << NumBits) - 1;
567 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
568 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
569 assert(NumBits <= 64 && "Not implemented: integers > 64-bits");
570 if (Ty == Type::Int1Ty)
571 return Val == 0 || Val == 1;
573 return true; // always true, has to fit in largest type
574 int64_t Min = -(1ll << (NumBits-1));
575 int64_t Max = (1ll << (NumBits-1)) - 1;
576 return (Val >= Min && Val <= Max);
579 bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
580 switch (Ty->getTypeID()) {
582 return false; // These can't be represented as floating point!
584 // TODO: Figure out how to test if a double can be cast to a float!
585 case Type::FloatTyID:
586 case Type::DoubleTyID:
587 return true; // This is the largest type...
591 //===----------------------------------------------------------------------===//
592 // Factory Function Implementation
594 // ConstantCreator - A class that is used to create constants by
595 // ValueMap*. This class should be partially specialized if there is
596 // something strange that needs to be done to interface to the ctor for the
600 template<class ConstantClass, class TypeClass, class ValType>
601 struct VISIBILITY_HIDDEN ConstantCreator {
602 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
603 return new ConstantClass(Ty, V);
607 template<class ConstantClass, class TypeClass>
608 struct VISIBILITY_HIDDEN ConvertConstantType {
609 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
610 assert(0 && "This type cannot be converted!\n");
615 template<class ValType, class TypeClass, class ConstantClass,
616 bool HasLargeKey = false /*true for arrays and structs*/ >
617 class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
619 typedef std::pair<const Type*, ValType> MapKey;
620 typedef std::map<MapKey, Constant *> MapTy;
621 typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
622 typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
624 /// Map - This is the main map from the element descriptor to the Constants.
625 /// This is the primary way we avoid creating two of the same shape
629 /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
630 /// from the constants to their element in Map. This is important for
631 /// removal of constants from the array, which would otherwise have to scan
632 /// through the map with very large keys.
633 InverseMapTy InverseMap;
635 /// AbstractTypeMap - Map for abstract type constants.
637 AbstractTypeMapTy AbstractTypeMap;
640 void clear(std::vector<Constant *> &Constants) {
641 for(typename MapTy::iterator I = Map.begin(); I != Map.end(); ++I)
642 Constants.push_back(I->second);
644 AbstractTypeMap.clear();
649 typename MapTy::iterator map_end() { return Map.end(); }
651 /// InsertOrGetItem - Return an iterator for the specified element.
652 /// If the element exists in the map, the returned iterator points to the
653 /// entry and Exists=true. If not, the iterator points to the newly
654 /// inserted entry and returns Exists=false. Newly inserted entries have
655 /// I->second == 0, and should be filled in.
656 typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
659 std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
665 typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
667 typename InverseMapTy::iterator IMI = InverseMap.find(CP);
668 assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
669 IMI->second->second == CP &&
670 "InverseMap corrupt!");
674 typename MapTy::iterator I =
675 Map.find(MapKey((TypeClass*)CP->getRawType(), getValType(CP)));
676 if (I == Map.end() || I->second != CP) {
677 // FIXME: This should not use a linear scan. If this gets to be a
678 // performance problem, someone should look at this.
679 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
686 /// getOrCreate - Return the specified constant from the map, creating it if
688 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
689 MapKey Lookup(Ty, V);
690 typename MapTy::iterator I = Map.lower_bound(Lookup);
692 if (I != Map.end() && I->first == Lookup)
693 return static_cast<ConstantClass *>(I->second);
695 // If no preexisting value, create one now...
696 ConstantClass *Result =
697 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
699 /// FIXME: why does this assert fail when loading 176.gcc?
700 //assert(Result->getType() == Ty && "Type specified is not correct!");
701 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
703 if (HasLargeKey) // Remember the reverse mapping if needed.
704 InverseMap.insert(std::make_pair(Result, I));
706 // If the type of the constant is abstract, make sure that an entry exists
707 // for it in the AbstractTypeMap.
708 if (Ty->isAbstract()) {
709 typename AbstractTypeMapTy::iterator TI =
710 AbstractTypeMap.lower_bound(Ty);
712 if (TI == AbstractTypeMap.end() || TI->first != Ty) {
713 // Add ourselves to the ATU list of the type.
714 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
716 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
722 void remove(ConstantClass *CP) {
723 typename MapTy::iterator I = FindExistingElement(CP);
724 assert(I != Map.end() && "Constant not found in constant table!");
725 assert(I->second == CP && "Didn't find correct element?");
727 if (HasLargeKey) // Remember the reverse mapping if needed.
728 InverseMap.erase(CP);
730 // Now that we found the entry, make sure this isn't the entry that
731 // the AbstractTypeMap points to.
732 const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
733 if (Ty->isAbstract()) {
734 assert(AbstractTypeMap.count(Ty) &&
735 "Abstract type not in AbstractTypeMap?");
736 typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
737 if (ATMEntryIt == I) {
738 // Yes, we are removing the representative entry for this type.
739 // See if there are any other entries of the same type.
740 typename MapTy::iterator TmpIt = ATMEntryIt;
742 // First check the entry before this one...
743 if (TmpIt != Map.begin()) {
745 if (TmpIt->first.first != Ty) // Not the same type, move back...
749 // If we didn't find the same type, try to move forward...
750 if (TmpIt == ATMEntryIt) {
752 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
753 --TmpIt; // No entry afterwards with the same type
756 // If there is another entry in the map of the same abstract type,
757 // update the AbstractTypeMap entry now.
758 if (TmpIt != ATMEntryIt) {
761 // Otherwise, we are removing the last instance of this type
762 // from the table. Remove from the ATM, and from user list.
763 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
764 AbstractTypeMap.erase(Ty);
773 /// MoveConstantToNewSlot - If we are about to change C to be the element
774 /// specified by I, update our internal data structures to reflect this
776 void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
777 // First, remove the old location of the specified constant in the map.
778 typename MapTy::iterator OldI = FindExistingElement(C);
779 assert(OldI != Map.end() && "Constant not found in constant table!");
780 assert(OldI->second == C && "Didn't find correct element?");
782 // If this constant is the representative element for its abstract type,
783 // update the AbstractTypeMap so that the representative element is I.
784 if (C->getType()->isAbstract()) {
785 typename AbstractTypeMapTy::iterator ATI =
786 AbstractTypeMap.find(C->getType());
787 assert(ATI != AbstractTypeMap.end() &&
788 "Abstract type not in AbstractTypeMap?");
789 if (ATI->second == OldI)
793 // Remove the old entry from the map.
796 // Update the inverse map so that we know that this constant is now
797 // located at descriptor I.
799 assert(I->second == C && "Bad inversemap entry!");
804 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
805 typename AbstractTypeMapTy::iterator I =
806 AbstractTypeMap.find(cast<Type>(OldTy));
808 assert(I != AbstractTypeMap.end() &&
809 "Abstract type not in AbstractTypeMap?");
811 // Convert a constant at a time until the last one is gone. The last one
812 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
813 // eliminated eventually.
815 ConvertConstantType<ConstantClass,
817 static_cast<ConstantClass *>(I->second->second),
818 cast<TypeClass>(NewTy));
820 I = AbstractTypeMap.find(cast<Type>(OldTy));
821 } while (I != AbstractTypeMap.end());
824 // If the type became concrete without being refined to any other existing
825 // type, we just remove ourselves from the ATU list.
826 void typeBecameConcrete(const DerivedType *AbsTy) {
827 AbsTy->removeAbstractTypeUser(this);
831 DOUT << "Constant.cpp: ValueMap\n";
837 //---- ConstantInt::get() implementations...
839 static ManagedStatic<ValueMap<uint64_t, Type, ConstantInt> > IntConstants;
841 // Get a ConstantInt from an int64_t. Note here that we canoncialize the value
842 // to a uint64_t value that has been zero extended down to the size of the
843 // integer type of the ConstantInt. This allows the getZExtValue method to
844 // just return the stored value while getSExtValue has to convert back to sign
845 // extended. getZExtValue is more common in LLVM than getSExtValue().
846 ConstantInt *ConstantInt::get(const Type *Ty, int64_t V) {
847 if (Ty == Type::Int1Ty)
852 return IntConstants->getOrCreate(Ty, V & Ty->getIntegralTypeMask());
855 //---- ConstantFP::get() implementation...
859 struct ConstantCreator<ConstantFP, Type, uint64_t> {
860 static ConstantFP *create(const Type *Ty, uint64_t V) {
861 assert(Ty == Type::DoubleTy);
862 return new ConstantFP(Ty, BitsToDouble(V));
866 struct ConstantCreator<ConstantFP, Type, uint32_t> {
867 static ConstantFP *create(const Type *Ty, uint32_t V) {
868 assert(Ty == Type::FloatTy);
869 return new ConstantFP(Ty, BitsToFloat(V));
874 static ManagedStatic<ValueMap<uint64_t, Type, ConstantFP> > DoubleConstants;
875 static ManagedStatic<ValueMap<uint32_t, Type, ConstantFP> > FloatConstants;
877 bool ConstantFP::isNullValue() const {
878 return DoubleToBits(Val) == 0;
881 bool ConstantFP::isExactlyValue(double V) const {
882 return DoubleToBits(V) == DoubleToBits(Val);
886 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
887 if (Ty == Type::FloatTy) {
888 // Force the value through memory to normalize it.
889 return FloatConstants->getOrCreate(Ty, FloatToBits(V));
891 assert(Ty == Type::DoubleTy);
892 return DoubleConstants->getOrCreate(Ty, DoubleToBits(V));
896 //---- ConstantAggregateZero::get() implementation...
899 // ConstantAggregateZero does not take extra "value" argument...
900 template<class ValType>
901 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
902 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
903 return new ConstantAggregateZero(Ty);
908 struct ConvertConstantType<ConstantAggregateZero, Type> {
909 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
910 // Make everyone now use a constant of the new type...
911 Constant *New = ConstantAggregateZero::get(NewTy);
912 assert(New != OldC && "Didn't replace constant??");
913 OldC->uncheckedReplaceAllUsesWith(New);
914 OldC->destroyConstant(); // This constant is now dead, destroy it.
919 static ManagedStatic<ValueMap<char, Type,
920 ConstantAggregateZero> > AggZeroConstants;
922 static char getValType(ConstantAggregateZero *CPZ) { return 0; }
924 Constant *ConstantAggregateZero::get(const Type *Ty) {
925 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<PackedType>(Ty)) &&
926 "Cannot create an aggregate zero of non-aggregate type!");
927 return AggZeroConstants->getOrCreate(Ty, 0);
930 // destroyConstant - Remove the constant from the constant table...
932 void ConstantAggregateZero::destroyConstant() {
933 AggZeroConstants->remove(this);
934 destroyConstantImpl();
937 //---- ConstantArray::get() implementation...
941 struct ConvertConstantType<ConstantArray, ArrayType> {
942 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
943 // Make everyone now use a constant of the new type...
944 std::vector<Constant*> C;
945 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
946 C.push_back(cast<Constant>(OldC->getOperand(i)));
947 Constant *New = ConstantArray::get(NewTy, C);
948 assert(New != OldC && "Didn't replace constant??");
949 OldC->uncheckedReplaceAllUsesWith(New);
950 OldC->destroyConstant(); // This constant is now dead, destroy it.
955 static std::vector<Constant*> getValType(ConstantArray *CA) {
956 std::vector<Constant*> Elements;
957 Elements.reserve(CA->getNumOperands());
958 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
959 Elements.push_back(cast<Constant>(CA->getOperand(i)));
963 typedef ValueMap<std::vector<Constant*>, ArrayType,
964 ConstantArray, true /*largekey*/> ArrayConstantsTy;
965 static ManagedStatic<ArrayConstantsTy> ArrayConstants;
967 Constant *ConstantArray::get(const ArrayType *Ty,
968 const std::vector<Constant*> &V) {
969 // If this is an all-zero array, return a ConstantAggregateZero object
972 if (!C->isNullValue())
973 return ArrayConstants->getOrCreate(Ty, V);
974 for (unsigned i = 1, e = V.size(); i != e; ++i)
976 return ArrayConstants->getOrCreate(Ty, V);
978 return ConstantAggregateZero::get(Ty);
981 // destroyConstant - Remove the constant from the constant table...
983 void ConstantArray::destroyConstant() {
984 ArrayConstants->remove(this);
985 destroyConstantImpl();
988 /// ConstantArray::get(const string&) - Return an array that is initialized to
989 /// contain the specified string. If length is zero then a null terminator is
990 /// added to the specified string so that it may be used in a natural way.
991 /// Otherwise, the length parameter specifies how much of the string to use
992 /// and it won't be null terminated.
994 Constant *ConstantArray::get(const std::string &Str, bool AddNull) {
995 std::vector<Constant*> ElementVals;
996 for (unsigned i = 0; i < Str.length(); ++i)
997 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, Str[i]));
999 // Add a null terminator to the string...
1001 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, 0));
1004 ArrayType *ATy = ArrayType::get(Type::Int8Ty, ElementVals.size());
1005 return ConstantArray::get(ATy, ElementVals);
1008 /// isString - This method returns true if the array is an array of sbyte or
1009 /// ubyte, and if the elements of the array are all ConstantInt's.
1010 bool ConstantArray::isString() const {
1011 // Check the element type for sbyte or ubyte...
1012 if (getType()->getElementType() != Type::Int8Ty)
1014 // Check the elements to make sure they are all integers, not constant
1016 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1017 if (!isa<ConstantInt>(getOperand(i)))
1022 /// isCString - This method returns true if the array is a string (see
1023 /// isString) and it ends in a null byte \0 and does not contains any other
1024 /// null bytes except its terminator.
1025 bool ConstantArray::isCString() const {
1026 // Check the element type for sbyte or ubyte...
1027 if (getType()->getElementType() != Type::Int8Ty)
1029 Constant *Zero = Constant::getNullValue(getOperand(0)->getType());
1030 // Last element must be a null.
1031 if (getOperand(getNumOperands()-1) != Zero)
1033 // Other elements must be non-null integers.
1034 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1035 if (!isa<ConstantInt>(getOperand(i)))
1037 if (getOperand(i) == Zero)
1044 // getAsString - If the sub-element type of this array is either sbyte or ubyte,
1045 // then this method converts the array to an std::string and returns it.
1046 // Otherwise, it asserts out.
1048 std::string ConstantArray::getAsString() const {
1049 assert(isString() && "Not a string!");
1051 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1052 Result += (char)cast<ConstantInt>(getOperand(i))->getZExtValue();
1057 //---- ConstantStruct::get() implementation...
1062 struct ConvertConstantType<ConstantStruct, StructType> {
1063 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1064 // Make everyone now use a constant of the new type...
1065 std::vector<Constant*> C;
1066 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1067 C.push_back(cast<Constant>(OldC->getOperand(i)));
1068 Constant *New = ConstantStruct::get(NewTy, C);
1069 assert(New != OldC && "Didn't replace constant??");
1071 OldC->uncheckedReplaceAllUsesWith(New);
1072 OldC->destroyConstant(); // This constant is now dead, destroy it.
1077 typedef ValueMap<std::vector<Constant*>, StructType,
1078 ConstantStruct, true /*largekey*/> StructConstantsTy;
1079 static ManagedStatic<StructConstantsTy> StructConstants;
1081 static std::vector<Constant*> getValType(ConstantStruct *CS) {
1082 std::vector<Constant*> Elements;
1083 Elements.reserve(CS->getNumOperands());
1084 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1085 Elements.push_back(cast<Constant>(CS->getOperand(i)));
1089 Constant *ConstantStruct::get(const StructType *Ty,
1090 const std::vector<Constant*> &V) {
1091 // Create a ConstantAggregateZero value if all elements are zeros...
1092 for (unsigned i = 0, e = V.size(); i != e; ++i)
1093 if (!V[i]->isNullValue())
1094 return StructConstants->getOrCreate(Ty, V);
1096 return ConstantAggregateZero::get(Ty);
1099 Constant *ConstantStruct::get(const std::vector<Constant*> &V, bool packed) {
1100 std::vector<const Type*> StructEls;
1101 StructEls.reserve(V.size());
1102 for (unsigned i = 0, e = V.size(); i != e; ++i)
1103 StructEls.push_back(V[i]->getType());
1104 return get(StructType::get(StructEls, packed), V);
1107 // destroyConstant - Remove the constant from the constant table...
1109 void ConstantStruct::destroyConstant() {
1110 StructConstants->remove(this);
1111 destroyConstantImpl();
1114 //---- ConstantPacked::get() implementation...
1118 struct ConvertConstantType<ConstantPacked, PackedType> {
1119 static void convert(ConstantPacked *OldC, const PackedType *NewTy) {
1120 // Make everyone now use a constant of the new type...
1121 std::vector<Constant*> C;
1122 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1123 C.push_back(cast<Constant>(OldC->getOperand(i)));
1124 Constant *New = ConstantPacked::get(NewTy, C);
1125 assert(New != OldC && "Didn't replace constant??");
1126 OldC->uncheckedReplaceAllUsesWith(New);
1127 OldC->destroyConstant(); // This constant is now dead, destroy it.
1132 static std::vector<Constant*> getValType(ConstantPacked *CP) {
1133 std::vector<Constant*> Elements;
1134 Elements.reserve(CP->getNumOperands());
1135 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1136 Elements.push_back(CP->getOperand(i));
1140 static ManagedStatic<ValueMap<std::vector<Constant*>, PackedType,
1141 ConstantPacked> > PackedConstants;
1143 Constant *ConstantPacked::get(const PackedType *Ty,
1144 const std::vector<Constant*> &V) {
1145 // If this is an all-zero packed, return a ConstantAggregateZero object
1148 if (!C->isNullValue())
1149 return PackedConstants->getOrCreate(Ty, V);
1150 for (unsigned i = 1, e = V.size(); i != e; ++i)
1152 return PackedConstants->getOrCreate(Ty, V);
1154 return ConstantAggregateZero::get(Ty);
1157 Constant *ConstantPacked::get(const std::vector<Constant*> &V) {
1158 assert(!V.empty() && "Cannot infer type if V is empty");
1159 return get(PackedType::get(V.front()->getType(),V.size()), V);
1162 // destroyConstant - Remove the constant from the constant table...
1164 void ConstantPacked::destroyConstant() {
1165 PackedConstants->remove(this);
1166 destroyConstantImpl();
1169 /// This function will return true iff every element in this packed constant
1170 /// is set to all ones.
1171 /// @returns true iff this constant's emements are all set to all ones.
1172 /// @brief Determine if the value is all ones.
1173 bool ConstantPacked::isAllOnesValue() const {
1174 // Check out first element.
1175 const Constant *Elt = getOperand(0);
1176 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1177 if (!CI || !CI->isAllOnesValue()) return false;
1178 // Then make sure all remaining elements point to the same value.
1179 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1180 if (getOperand(I) != Elt) return false;
1185 //---- ConstantPointerNull::get() implementation...
1189 // ConstantPointerNull does not take extra "value" argument...
1190 template<class ValType>
1191 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1192 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1193 return new ConstantPointerNull(Ty);
1198 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1199 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1200 // Make everyone now use a constant of the new type...
1201 Constant *New = ConstantPointerNull::get(NewTy);
1202 assert(New != OldC && "Didn't replace constant??");
1203 OldC->uncheckedReplaceAllUsesWith(New);
1204 OldC->destroyConstant(); // This constant is now dead, destroy it.
1209 static ManagedStatic<ValueMap<char, PointerType,
1210 ConstantPointerNull> > NullPtrConstants;
1212 static char getValType(ConstantPointerNull *) {
1217 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1218 return NullPtrConstants->getOrCreate(Ty, 0);
1221 // destroyConstant - Remove the constant from the constant table...
1223 void ConstantPointerNull::destroyConstant() {
1224 NullPtrConstants->remove(this);
1225 destroyConstantImpl();
1229 //---- UndefValue::get() implementation...
1233 // UndefValue does not take extra "value" argument...
1234 template<class ValType>
1235 struct ConstantCreator<UndefValue, Type, ValType> {
1236 static UndefValue *create(const Type *Ty, const ValType &V) {
1237 return new UndefValue(Ty);
1242 struct ConvertConstantType<UndefValue, Type> {
1243 static void convert(UndefValue *OldC, const Type *NewTy) {
1244 // Make everyone now use a constant of the new type.
1245 Constant *New = UndefValue::get(NewTy);
1246 assert(New != OldC && "Didn't replace constant??");
1247 OldC->uncheckedReplaceAllUsesWith(New);
1248 OldC->destroyConstant(); // This constant is now dead, destroy it.
1253 static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
1255 static char getValType(UndefValue *) {
1260 UndefValue *UndefValue::get(const Type *Ty) {
1261 return UndefValueConstants->getOrCreate(Ty, 0);
1264 // destroyConstant - Remove the constant from the constant table.
1266 void UndefValue::destroyConstant() {
1267 UndefValueConstants->remove(this);
1268 destroyConstantImpl();
1272 //---- ConstantExpr::get() implementations...
1275 struct ExprMapKeyType {
1276 explicit ExprMapKeyType(unsigned opc, std::vector<Constant*> ops,
1277 unsigned short pred = 0) : opcode(opc), predicate(pred), operands(ops) { }
1280 std::vector<Constant*> operands;
1281 bool operator==(const ExprMapKeyType& that) const {
1282 return this->opcode == that.opcode &&
1283 this->predicate == that.predicate &&
1284 this->operands == that.operands;
1286 bool operator<(const ExprMapKeyType & that) const {
1287 return this->opcode < that.opcode ||
1288 (this->opcode == that.opcode && this->predicate < that.predicate) ||
1289 (this->opcode == that.opcode && this->predicate == that.predicate &&
1290 this->operands < that.operands);
1293 bool operator!=(const ExprMapKeyType& that) const {
1294 return !(*this == that);
1300 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1301 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1302 unsigned short pred = 0) {
1303 if (Instruction::isCast(V.opcode))
1304 return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1305 if ((V.opcode >= Instruction::BinaryOpsBegin &&
1306 V.opcode < Instruction::BinaryOpsEnd) ||
1307 V.opcode == Instruction::Shl ||
1308 V.opcode == Instruction::LShr ||
1309 V.opcode == Instruction::AShr)
1310 return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1311 if (V.opcode == Instruction::Select)
1312 return new SelectConstantExpr(V.operands[0], V.operands[1],
1314 if (V.opcode == Instruction::ExtractElement)
1315 return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1316 if (V.opcode == Instruction::InsertElement)
1317 return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1319 if (V.opcode == Instruction::ShuffleVector)
1320 return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1322 if (V.opcode == Instruction::GetElementPtr) {
1323 std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
1324 return new GetElementPtrConstantExpr(V.operands[0], IdxList, Ty);
1327 // The compare instructions are weird. We have to encode the predicate
1328 // value and it is combined with the instruction opcode by multiplying
1329 // the opcode by one hundred. We must decode this to get the predicate.
1330 if (V.opcode == Instruction::ICmp)
1331 return new CompareConstantExpr(Instruction::ICmp, V.predicate,
1332 V.operands[0], V.operands[1]);
1333 if (V.opcode == Instruction::FCmp)
1334 return new CompareConstantExpr(Instruction::FCmp, V.predicate,
1335 V.operands[0], V.operands[1]);
1336 assert(0 && "Invalid ConstantExpr!");
1342 struct ConvertConstantType<ConstantExpr, Type> {
1343 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1345 switch (OldC->getOpcode()) {
1346 case Instruction::Trunc:
1347 case Instruction::ZExt:
1348 case Instruction::SExt:
1349 case Instruction::FPTrunc:
1350 case Instruction::FPExt:
1351 case Instruction::UIToFP:
1352 case Instruction::SIToFP:
1353 case Instruction::FPToUI:
1354 case Instruction::FPToSI:
1355 case Instruction::PtrToInt:
1356 case Instruction::IntToPtr:
1357 case Instruction::BitCast:
1358 New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0),
1361 case Instruction::Select:
1362 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1363 OldC->getOperand(1),
1364 OldC->getOperand(2));
1366 case Instruction::Shl:
1367 case Instruction::LShr:
1368 case Instruction::AShr:
1369 New = ConstantExpr::getShiftTy(NewTy, OldC->getOpcode(),
1370 OldC->getOperand(0), OldC->getOperand(1));
1373 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1374 OldC->getOpcode() < Instruction::BinaryOpsEnd);
1375 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1376 OldC->getOperand(1));
1378 case Instruction::GetElementPtr:
1379 // Make everyone now use a constant of the new type...
1380 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1381 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0), Idx);
1385 assert(New != OldC && "Didn't replace constant??");
1386 OldC->uncheckedReplaceAllUsesWith(New);
1387 OldC->destroyConstant(); // This constant is now dead, destroy it.
1390 } // end namespace llvm
1393 static ExprMapKeyType getValType(ConstantExpr *CE) {
1394 std::vector<Constant*> Operands;
1395 Operands.reserve(CE->getNumOperands());
1396 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1397 Operands.push_back(cast<Constant>(CE->getOperand(i)));
1398 return ExprMapKeyType(CE->getOpcode(), Operands,
1399 CE->isCompare() ? CE->getPredicate() : 0);
1402 static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1403 ConstantExpr> > ExprConstants;
1405 /// This is a utility function to handle folding of casts and lookup of the
1406 /// cast in the ExprConstants map. It is usedby the various get* methods below.
1407 static inline Constant *getFoldedCast(
1408 Instruction::CastOps opc, Constant *C, const Type *Ty) {
1409 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1410 // Fold a few common cases
1411 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1414 // Look up the constant in the table first to ensure uniqueness
1415 std::vector<Constant*> argVec(1, C);
1416 ExprMapKeyType Key(opc, argVec);
1417 return ExprConstants->getOrCreate(Ty, Key);
1420 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1421 Instruction::CastOps opc = Instruction::CastOps(oc);
1422 assert(Instruction::isCast(opc) && "opcode out of range");
1423 assert(C && Ty && "Null arguments to getCast");
1424 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1428 assert(0 && "Invalid cast opcode");
1430 case Instruction::Trunc: return getTrunc(C, Ty);
1431 case Instruction::ZExt: return getZExt(C, Ty);
1432 case Instruction::SExt: return getSExt(C, Ty);
1433 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1434 case Instruction::FPExt: return getFPExtend(C, Ty);
1435 case Instruction::UIToFP: return getUIToFP(C, Ty);
1436 case Instruction::SIToFP: return getSIToFP(C, Ty);
1437 case Instruction::FPToUI: return getFPToUI(C, Ty);
1438 case Instruction::FPToSI: return getFPToSI(C, Ty);
1439 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1440 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1441 case Instruction::BitCast: return getBitCast(C, Ty);
1446 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1447 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1448 return getCast(Instruction::BitCast, C, Ty);
1449 return getCast(Instruction::ZExt, C, Ty);
1452 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1453 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1454 return getCast(Instruction::BitCast, C, Ty);
1455 return getCast(Instruction::SExt, C, Ty);
1458 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1459 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1460 return getCast(Instruction::BitCast, C, Ty);
1461 return getCast(Instruction::Trunc, C, Ty);
1464 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1465 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1466 assert((Ty->isIntegral() || isa<PointerType>(Ty)) && "Invalid cast");
1468 if (Ty->isIntegral())
1469 return getCast(Instruction::PtrToInt, S, Ty);
1470 return getCast(Instruction::BitCast, S, Ty);
1473 Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
1475 assert(C->getType()->isIntegral() && Ty->isIntegral() && "Invalid cast");
1476 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1477 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1478 Instruction::CastOps opcode =
1479 (SrcBits == DstBits ? Instruction::BitCast :
1480 (SrcBits > DstBits ? Instruction::Trunc :
1481 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1482 return getCast(opcode, C, Ty);
1485 Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1486 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1488 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1489 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1490 if (SrcBits == DstBits)
1491 return C; // Avoid a useless cast
1492 Instruction::CastOps opcode =
1493 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1494 return getCast(opcode, C, Ty);
1497 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
1498 assert(C->getType()->isIntegral() && "Trunc operand must be integer");
1499 assert(Ty->isIntegral() && "Trunc produces only integral");
1500 assert(C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1501 "SrcTy must be larger than DestTy for Trunc!");
1503 return getFoldedCast(Instruction::Trunc, C, Ty);
1506 Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
1507 assert(C->getType()->isIntegral() && "SEXt operand must be integral");
1508 assert(Ty->isIntegral() && "SExt produces only integer");
1509 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1510 "SrcTy must be smaller than DestTy for SExt!");
1512 return getFoldedCast(Instruction::SExt, C, Ty);
1515 Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
1516 assert(C->getType()->isIntegral() && "ZEXt operand must be integral");
1517 assert(Ty->isIntegral() && "ZExt produces only integer");
1518 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1519 "SrcTy must be smaller than DestTy for ZExt!");
1521 return getFoldedCast(Instruction::ZExt, C, Ty);
1524 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1525 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1526 C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1527 "This is an illegal floating point truncation!");
1528 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1531 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1532 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1533 C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1534 "This is an illegal floating point extension!");
1535 return getFoldedCast(Instruction::FPExt, C, Ty);
1538 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
1539 assert(C->getType()->isIntegral() && Ty->isFloatingPoint() &&
1540 "This is an illegal uint to floating point cast!");
1541 return getFoldedCast(Instruction::UIToFP, C, Ty);
1544 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
1545 assert(C->getType()->isIntegral() && Ty->isFloatingPoint() &&
1546 "This is an illegal sint to floating point cast!");
1547 return getFoldedCast(Instruction::SIToFP, C, Ty);
1550 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
1551 assert(C->getType()->isFloatingPoint() && Ty->isIntegral() &&
1552 "This is an illegal floating point to uint cast!");
1553 return getFoldedCast(Instruction::FPToUI, C, Ty);
1556 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
1557 assert(C->getType()->isFloatingPoint() && Ty->isIntegral() &&
1558 "This is an illegal floating point to sint cast!");
1559 return getFoldedCast(Instruction::FPToSI, C, Ty);
1562 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1563 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
1564 assert(DstTy->isIntegral() && "PtrToInt destination must be integral");
1565 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1568 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
1569 assert(C->getType()->isIntegral() && "IntToPtr source must be integral");
1570 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
1571 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1574 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1575 // BitCast implies a no-op cast of type only. No bits change. However, you
1576 // can't cast pointers to anything but pointers.
1577 const Type *SrcTy = C->getType();
1578 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
1579 "BitCast cannot cast pointer to non-pointer and vice versa");
1581 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
1582 // or nonptr->ptr). For all the other types, the cast is okay if source and
1583 // destination bit widths are identical.
1584 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1585 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
1586 assert(SrcBitSize == DstBitSize && "BitCast requies types of same width");
1587 return getFoldedCast(Instruction::BitCast, C, DstTy);
1590 Constant *ConstantExpr::getSizeOf(const Type *Ty) {
1591 // sizeof is implemented as: (ulong) gep (Ty*)null, 1
1592 return getCast(Instruction::PtrToInt, getGetElementPtr(getNullValue(
1593 PointerType::get(Ty)), std::vector<Constant*>(1,
1594 ConstantInt::get(Type::Int32Ty, 1))), Type::Int64Ty);
1597 Constant *ConstantExpr::getPtrPtrFromArrayPtr(Constant *C) {
1598 // pointer from array is implemented as: getelementptr arr ptr, 0, 0
1599 static std::vector<Constant*> Indices(2, ConstantInt::get(Type::Int32Ty, 0));
1601 return ConstantExpr::getGetElementPtr(C, Indices);
1604 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1605 Constant *C1, Constant *C2) {
1606 if (Opcode == Instruction::Shl || Opcode == Instruction::LShr ||
1607 Opcode == Instruction::AShr)
1608 return getShiftTy(ReqTy, Opcode, C1, C2);
1610 // Check the operands for consistency first
1611 assert(Opcode >= Instruction::BinaryOpsBegin &&
1612 Opcode < Instruction::BinaryOpsEnd &&
1613 "Invalid opcode in binary constant expression");
1614 assert(C1->getType() == C2->getType() &&
1615 "Operand types in binary constant expression should match");
1617 if (ReqTy == C1->getType() || ReqTy == Type::Int1Ty)
1618 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1619 return FC; // Fold a few common cases...
1621 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1622 ExprMapKeyType Key(Opcode, argVec);
1623 return ExprConstants->getOrCreate(ReqTy, Key);
1626 Constant *ConstantExpr::getCompareTy(unsigned short predicate,
1627 Constant *C1, Constant *C2) {
1628 switch (predicate) {
1629 default: assert(0 && "Invalid CmpInst predicate");
1630 case FCmpInst::FCMP_FALSE: case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_OGT:
1631 case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OLE:
1632 case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_ORD: case FCmpInst::FCMP_UNO:
1633 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UGT: case FCmpInst::FCMP_UGE:
1634 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_ULE: case FCmpInst::FCMP_UNE:
1635 case FCmpInst::FCMP_TRUE:
1636 return getFCmp(predicate, C1, C2);
1637 case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGT:
1638 case ICmpInst::ICMP_UGE: case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE:
1639 case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_SGE: case ICmpInst::ICMP_SLT:
1640 case ICmpInst::ICMP_SLE:
1641 return getICmp(predicate, C1, C2);
1645 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
1648 case Instruction::Add:
1649 case Instruction::Sub:
1650 case Instruction::Mul:
1651 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1652 assert((C1->getType()->isIntegral() || C1->getType()->isFloatingPoint() ||
1653 isa<PackedType>(C1->getType())) &&
1654 "Tried to create an arithmetic operation on a non-arithmetic type!");
1656 case Instruction::UDiv:
1657 case Instruction::SDiv:
1658 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1659 assert((C1->getType()->isIntegral() || (isa<PackedType>(C1->getType()) &&
1660 cast<PackedType>(C1->getType())->getElementType()->isIntegral())) &&
1661 "Tried to create an arithmetic operation on a non-arithmetic type!");
1663 case Instruction::FDiv:
1664 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1665 assert((C1->getType()->isFloatingPoint() || (isa<PackedType>(C1->getType())
1666 && cast<PackedType>(C1->getType())->getElementType()->isFloatingPoint()))
1667 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1669 case Instruction::URem:
1670 case Instruction::SRem:
1671 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1672 assert((C1->getType()->isIntegral() || (isa<PackedType>(C1->getType()) &&
1673 cast<PackedType>(C1->getType())->getElementType()->isIntegral())) &&
1674 "Tried to create an arithmetic operation on a non-arithmetic type!");
1676 case Instruction::FRem:
1677 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1678 assert((C1->getType()->isFloatingPoint() || (isa<PackedType>(C1->getType())
1679 && cast<PackedType>(C1->getType())->getElementType()->isFloatingPoint()))
1680 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1682 case Instruction::And:
1683 case Instruction::Or:
1684 case Instruction::Xor:
1685 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1686 assert((C1->getType()->isIntegral() || isa<PackedType>(C1->getType())) &&
1687 "Tried to create a logical operation on a non-integral type!");
1689 case Instruction::Shl:
1690 case Instruction::LShr:
1691 case Instruction::AShr:
1692 assert(C2->getType() == Type::Int8Ty && "Shift should be by ubyte!");
1693 assert(C1->getType()->isIntegral() &&
1694 "Tried to create a shift operation on a non-integer type!");
1701 return getTy(C1->getType(), Opcode, C1, C2);
1704 Constant *ConstantExpr::getCompare(unsigned short pred,
1705 Constant *C1, Constant *C2) {
1706 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1707 return getCompareTy(pred, C1, C2);
1710 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1711 Constant *V1, Constant *V2) {
1712 assert(C->getType() == Type::Int1Ty && "Select condition must be bool!");
1713 assert(V1->getType() == V2->getType() && "Select value types must match!");
1714 assert(V1->getType()->isFirstClassType() && "Cannot select aggregate type!");
1716 if (ReqTy == V1->getType())
1717 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1718 return SC; // Fold common cases
1720 std::vector<Constant*> argVec(3, C);
1723 ExprMapKeyType Key(Instruction::Select, argVec);
1724 return ExprConstants->getOrCreate(ReqTy, Key);
1727 /// getShiftTy - Return a shift left or shift right constant expr
1728 Constant *ConstantExpr::getShiftTy(const Type *ReqTy, unsigned Opcode,
1729 Constant *C1, Constant *C2) {
1730 // Check the operands for consistency first
1731 assert((Opcode == Instruction::Shl ||
1732 Opcode == Instruction::LShr ||
1733 Opcode == Instruction::AShr) &&
1734 "Invalid opcode in binary constant expression");
1735 assert(C1->getType()->isIntegral() && C2->getType() == Type::Int8Ty &&
1736 "Invalid operand types for Shift constant expr!");
1738 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1739 return FC; // Fold a few common cases...
1741 // Look up the constant in the table first to ensure uniqueness
1742 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1743 ExprMapKeyType Key(Opcode, argVec);
1744 return ExprConstants->getOrCreate(ReqTy, Key);
1747 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1748 const std::vector<Value*> &IdxList) {
1749 assert(GetElementPtrInst::getIndexedType(C->getType(), IdxList, true) &&
1750 "GEP indices invalid!");
1752 if (Constant *FC = ConstantFoldGetElementPtr(C, IdxList))
1753 return FC; // Fold a few common cases...
1755 assert(isa<PointerType>(C->getType()) &&
1756 "Non-pointer type for constant GetElementPtr expression");
1757 // Look up the constant in the table first to ensure uniqueness
1758 std::vector<Constant*> ArgVec;
1759 ArgVec.reserve(IdxList.size()+1);
1760 ArgVec.push_back(C);
1761 for (unsigned i = 0, e = IdxList.size(); i != e; ++i)
1762 ArgVec.push_back(cast<Constant>(IdxList[i]));
1763 const ExprMapKeyType Key(Instruction::GetElementPtr,ArgVec);
1764 return ExprConstants->getOrCreate(ReqTy, Key);
1767 Constant *ConstantExpr::getGetElementPtr(Constant *C,
1768 const std::vector<Constant*> &IdxList){
1769 // Get the result type of the getelementptr!
1770 std::vector<Value*> VIdxList(IdxList.begin(), IdxList.end());
1772 const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), VIdxList,
1774 assert(Ty && "GEP indices invalid!");
1775 return getGetElementPtrTy(PointerType::get(Ty), C, VIdxList);
1778 Constant *ConstantExpr::getGetElementPtr(Constant *C,
1779 const std::vector<Value*> &IdxList) {
1780 // Get the result type of the getelementptr!
1781 const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), IdxList,
1783 assert(Ty && "GEP indices invalid!");
1784 return getGetElementPtrTy(PointerType::get(Ty), C, IdxList);
1788 ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1789 assert(LHS->getType() == RHS->getType());
1790 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
1791 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1793 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1794 return FC; // Fold a few common cases...
1796 // Look up the constant in the table first to ensure uniqueness
1797 std::vector<Constant*> ArgVec;
1798 ArgVec.push_back(LHS);
1799 ArgVec.push_back(RHS);
1800 // Get the key type with both the opcode and predicate
1801 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
1802 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
1806 ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1807 assert(LHS->getType() == RHS->getType());
1808 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1810 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1811 return FC; // Fold a few common cases...
1813 // Look up the constant in the table first to ensure uniqueness
1814 std::vector<Constant*> ArgVec;
1815 ArgVec.push_back(LHS);
1816 ArgVec.push_back(RHS);
1817 // Get the key type with both the opcode and predicate
1818 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
1819 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
1822 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
1824 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
1825 return FC; // Fold a few common cases...
1826 // Look up the constant in the table first to ensure uniqueness
1827 std::vector<Constant*> ArgVec(1, Val);
1828 ArgVec.push_back(Idx);
1829 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
1830 return ExprConstants->getOrCreate(ReqTy, Key);
1833 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
1834 assert(isa<PackedType>(Val->getType()) &&
1835 "Tried to create extractelement operation on non-packed type!");
1836 assert(Idx->getType() == Type::Int32Ty &&
1837 "Extractelement index must be uint type!");
1838 return getExtractElementTy(cast<PackedType>(Val->getType())->getElementType(),
1842 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
1843 Constant *Elt, Constant *Idx) {
1844 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
1845 return FC; // Fold a few common cases...
1846 // Look up the constant in the table first to ensure uniqueness
1847 std::vector<Constant*> ArgVec(1, Val);
1848 ArgVec.push_back(Elt);
1849 ArgVec.push_back(Idx);
1850 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
1851 return ExprConstants->getOrCreate(ReqTy, Key);
1854 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1856 assert(isa<PackedType>(Val->getType()) &&
1857 "Tried to create insertelement operation on non-packed type!");
1858 assert(Elt->getType() == cast<PackedType>(Val->getType())->getElementType()
1859 && "Insertelement types must match!");
1860 assert(Idx->getType() == Type::Int32Ty &&
1861 "Insertelement index must be uint type!");
1862 return getInsertElementTy(cast<PackedType>(Val->getType())->getElementType(),
1866 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
1867 Constant *V2, Constant *Mask) {
1868 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
1869 return FC; // Fold a few common cases...
1870 // Look up the constant in the table first to ensure uniqueness
1871 std::vector<Constant*> ArgVec(1, V1);
1872 ArgVec.push_back(V2);
1873 ArgVec.push_back(Mask);
1874 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
1875 return ExprConstants->getOrCreate(ReqTy, Key);
1878 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
1880 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1881 "Invalid shuffle vector constant expr operands!");
1882 return getShuffleVectorTy(V1->getType(), V1, V2, Mask);
1885 // destroyConstant - Remove the constant from the constant table...
1887 void ConstantExpr::destroyConstant() {
1888 ExprConstants->remove(this);
1889 destroyConstantImpl();
1892 const char *ConstantExpr::getOpcodeName() const {
1893 return Instruction::getOpcodeName(getOpcode());
1896 //===----------------------------------------------------------------------===//
1897 // replaceUsesOfWithOnConstant implementations
1899 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
1901 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1902 Constant *ToC = cast<Constant>(To);
1904 unsigned OperandToUpdate = U-OperandList;
1905 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
1907 std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
1908 Lookup.first.first = getType();
1909 Lookup.second = this;
1911 std::vector<Constant*> &Values = Lookup.first.second;
1912 Values.reserve(getNumOperands()); // Build replacement array.
1914 // Fill values with the modified operands of the constant array. Also,
1915 // compute whether this turns into an all-zeros array.
1916 bool isAllZeros = false;
1917 if (!ToC->isNullValue()) {
1918 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
1919 Values.push_back(cast<Constant>(O->get()));
1922 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1923 Constant *Val = cast<Constant>(O->get());
1924 Values.push_back(Val);
1925 if (isAllZeros) isAllZeros = Val->isNullValue();
1928 Values[OperandToUpdate] = ToC;
1930 Constant *Replacement = 0;
1932 Replacement = ConstantAggregateZero::get(getType());
1934 // Check to see if we have this array type already.
1936 ArrayConstantsTy::MapTy::iterator I =
1937 ArrayConstants->InsertOrGetItem(Lookup, Exists);
1940 Replacement = I->second;
1942 // Okay, the new shape doesn't exist in the system yet. Instead of
1943 // creating a new constant array, inserting it, replaceallusesof'ing the
1944 // old with the new, then deleting the old... just update the current one
1946 ArrayConstants->MoveConstantToNewSlot(this, I);
1948 // Update to the new value.
1949 setOperand(OperandToUpdate, ToC);
1954 // Otherwise, I do need to replace this with an existing value.
1955 assert(Replacement != this && "I didn't contain From!");
1957 // Everyone using this now uses the replacement.
1958 uncheckedReplaceAllUsesWith(Replacement);
1960 // Delete the old constant!
1964 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
1966 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1967 Constant *ToC = cast<Constant>(To);
1969 unsigned OperandToUpdate = U-OperandList;
1970 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
1972 std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
1973 Lookup.first.first = getType();
1974 Lookup.second = this;
1975 std::vector<Constant*> &Values = Lookup.first.second;
1976 Values.reserve(getNumOperands()); // Build replacement struct.
1979 // Fill values with the modified operands of the constant struct. Also,
1980 // compute whether this turns into an all-zeros struct.
1981 bool isAllZeros = false;
1982 if (!ToC->isNullValue()) {
1983 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
1984 Values.push_back(cast<Constant>(O->get()));
1987 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1988 Constant *Val = cast<Constant>(O->get());
1989 Values.push_back(Val);
1990 if (isAllZeros) isAllZeros = Val->isNullValue();
1993 Values[OperandToUpdate] = ToC;
1995 Constant *Replacement = 0;
1997 Replacement = ConstantAggregateZero::get(getType());
1999 // Check to see if we have this array type already.
2001 StructConstantsTy::MapTy::iterator I =
2002 StructConstants->InsertOrGetItem(Lookup, Exists);
2005 Replacement = I->second;
2007 // Okay, the new shape doesn't exist in the system yet. Instead of
2008 // creating a new constant struct, inserting it, replaceallusesof'ing the
2009 // old with the new, then deleting the old... just update the current one
2011 StructConstants->MoveConstantToNewSlot(this, I);
2013 // Update to the new value.
2014 setOperand(OperandToUpdate, ToC);
2019 assert(Replacement != this && "I didn't contain From!");
2021 // Everyone using this now uses the replacement.
2022 uncheckedReplaceAllUsesWith(Replacement);
2024 // Delete the old constant!
2028 void ConstantPacked::replaceUsesOfWithOnConstant(Value *From, Value *To,
2030 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2032 std::vector<Constant*> Values;
2033 Values.reserve(getNumOperands()); // Build replacement array...
2034 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2035 Constant *Val = getOperand(i);
2036 if (Val == From) Val = cast<Constant>(To);
2037 Values.push_back(Val);
2040 Constant *Replacement = ConstantPacked::get(getType(), Values);
2041 assert(Replacement != this && "I didn't contain From!");
2043 // Everyone using this now uses the replacement.
2044 uncheckedReplaceAllUsesWith(Replacement);
2046 // Delete the old constant!
2050 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2052 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2053 Constant *To = cast<Constant>(ToV);
2055 Constant *Replacement = 0;
2056 if (getOpcode() == Instruction::GetElementPtr) {
2057 std::vector<Constant*> Indices;
2058 Constant *Pointer = getOperand(0);
2059 Indices.reserve(getNumOperands()-1);
2060 if (Pointer == From) Pointer = To;
2062 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2063 Constant *Val = getOperand(i);
2064 if (Val == From) Val = To;
2065 Indices.push_back(Val);
2067 Replacement = ConstantExpr::getGetElementPtr(Pointer, Indices);
2068 } else if (isCast()) {
2069 assert(getOperand(0) == From && "Cast only has one use!");
2070 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
2071 } else if (getOpcode() == Instruction::Select) {
2072 Constant *C1 = getOperand(0);
2073 Constant *C2 = getOperand(1);
2074 Constant *C3 = getOperand(2);
2075 if (C1 == From) C1 = To;
2076 if (C2 == From) C2 = To;
2077 if (C3 == From) C3 = To;
2078 Replacement = ConstantExpr::getSelect(C1, C2, C3);
2079 } else if (getOpcode() == Instruction::ExtractElement) {
2080 Constant *C1 = getOperand(0);
2081 Constant *C2 = getOperand(1);
2082 if (C1 == From) C1 = To;
2083 if (C2 == From) C2 = To;
2084 Replacement = ConstantExpr::getExtractElement(C1, C2);
2085 } else if (getOpcode() == Instruction::InsertElement) {
2086 Constant *C1 = getOperand(0);
2087 Constant *C2 = getOperand(1);
2088 Constant *C3 = getOperand(1);
2089 if (C1 == From) C1 = To;
2090 if (C2 == From) C2 = To;
2091 if (C3 == From) C3 = To;
2092 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2093 } else if (getOpcode() == Instruction::ShuffleVector) {
2094 Constant *C1 = getOperand(0);
2095 Constant *C2 = getOperand(1);
2096 Constant *C3 = getOperand(2);
2097 if (C1 == From) C1 = To;
2098 if (C2 == From) C2 = To;
2099 if (C3 == From) C3 = To;
2100 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2101 } else if (isCompare()) {
2102 Constant *C1 = getOperand(0);
2103 Constant *C2 = getOperand(1);
2104 if (C1 == From) C1 = To;
2105 if (C2 == From) C2 = To;
2106 if (getOpcode() == Instruction::ICmp)
2107 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2109 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2110 } else if (getNumOperands() == 2) {
2111 Constant *C1 = getOperand(0);
2112 Constant *C2 = getOperand(1);
2113 if (C1 == From) C1 = To;
2114 if (C2 == From) C2 = To;
2115 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2117 assert(0 && "Unknown ConstantExpr type!");
2121 assert(Replacement != this && "I didn't contain From!");
2123 // Everyone using this now uses the replacement.
2124 uncheckedReplaceAllUsesWith(Replacement);
2126 // Delete the old constant!
2131 /// getStringValue - Turn an LLVM constant pointer that eventually points to a
2132 /// global into a string value. Return an empty string if we can't do it.
2133 /// Parameter Chop determines if the result is chopped at the first null
2136 std::string Constant::getStringValue(bool Chop, unsigned Offset) {
2137 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(this)) {
2138 if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
2139 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
2140 if (Init->isString()) {
2141 std::string Result = Init->getAsString();
2142 if (Offset < Result.size()) {
2143 // If we are pointing INTO The string, erase the beginning...
2144 Result.erase(Result.begin(), Result.begin()+Offset);
2146 // Take off the null terminator, and any string fragments after it.
2148 std::string::size_type NullPos = Result.find_first_of((char)0);
2149 if (NullPos != std::string::npos)
2150 Result.erase(Result.begin()+NullPos, Result.end());
2156 } else if (Constant *C = dyn_cast<Constant>(this)) {
2157 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
2158 return GV->getStringValue(Chop, Offset);
2159 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2160 if (CE->getOpcode() == Instruction::GetElementPtr) {
2161 // Turn a gep into the specified offset.
2162 if (CE->getNumOperands() == 3 &&
2163 cast<Constant>(CE->getOperand(1))->isNullValue() &&
2164 isa<ConstantInt>(CE->getOperand(2))) {
2165 Offset += cast<ConstantInt>(CE->getOperand(2))->getZExtValue();
2166 return CE->getOperand(0)->getStringValue(Chop, Offset);