1 //===-- Constants.cpp - Implement Constant nodes --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Constant* classes...
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Constants.h"
15 #include "ConstantFold.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/GlobalValue.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/MDNode.h"
20 #include "llvm/Module.h"
21 #include "llvm/Operator.h"
22 #include "llvm/ADT/FoldingSet.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/StringMap.h"
25 #include "llvm/Support/Compiler.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/ManagedStatic.h"
29 #include "llvm/Support/MathExtras.h"
30 #include "llvm/System/Mutex.h"
31 #include "llvm/System/RWMutex.h"
32 #include "llvm/System/Threading.h"
33 #include "llvm/ADT/DenseMap.h"
34 #include "llvm/ADT/SmallVector.h"
39 //===----------------------------------------------------------------------===//
41 //===----------------------------------------------------------------------===//
43 // Becomes a no-op when multithreading is disabled.
44 ManagedStatic<sys::SmartRWMutex<true> > ConstantsLock;
46 void Constant::destroyConstantImpl() {
47 // When a Constant is destroyed, there may be lingering
48 // references to the constant by other constants in the constant pool. These
49 // constants are implicitly dependent on the module that is being deleted,
50 // but they don't know that. Because we only find out when the CPV is
51 // deleted, we must now notify all of our users (that should only be
52 // Constants) that they are, in fact, invalid now and should be deleted.
54 while (!use_empty()) {
55 Value *V = use_back();
56 #ifndef NDEBUG // Only in -g mode...
57 if (!isa<Constant>(V))
58 DOUT << "While deleting: " << *this
59 << "\n\nUse still stuck around after Def is destroyed: "
62 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
63 Constant *CV = cast<Constant>(V);
64 CV->destroyConstant();
66 // The constant should remove itself from our use list...
67 assert((use_empty() || use_back() != V) && "Constant not removed!");
70 // Value has no outstanding references it is safe to delete it now...
74 /// canTrap - Return true if evaluation of this constant could trap. This is
75 /// true for things like constant expressions that could divide by zero.
76 bool Constant::canTrap() const {
77 assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
78 // The only thing that could possibly trap are constant exprs.
79 const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
80 if (!CE) return false;
82 // ConstantExpr traps if any operands can trap.
83 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
84 if (getOperand(i)->canTrap())
87 // Otherwise, only specific operations can trap.
88 switch (CE->getOpcode()) {
91 case Instruction::UDiv:
92 case Instruction::SDiv:
93 case Instruction::FDiv:
94 case Instruction::URem:
95 case Instruction::SRem:
96 case Instruction::FRem:
97 // Div and rem can trap if the RHS is not known to be non-zero.
98 if (!isa<ConstantInt>(getOperand(1)) || getOperand(1)->isNullValue())
105 /// getRelocationInfo - This method classifies the entry according to
106 /// whether or not it may generate a relocation entry. This must be
107 /// conservative, so if it might codegen to a relocatable entry, it should say
108 /// so. The return values are:
110 /// 0: This constant pool entry is guaranteed to never have a relocation
111 /// applied to it (because it holds a simple constant like '4').
112 /// 1: This entry has relocations, but the entries are guaranteed to be
113 /// resolvable by the static linker, so the dynamic linker will never see
115 /// 2: This entry may have arbitrary relocations.
117 /// FIXME: This really should not be in VMCore.
118 unsigned Constant::getRelocationInfo() const {
119 if (const GlobalValue* GV = dyn_cast<GlobalValue>(this)) {
120 if (GV->hasLocalLinkage() || GV->hasHiddenVisibility())
121 return 1; // Local to this file/library.
122 return 2; // Global reference.
126 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
127 Result = std::max(Result, getOperand(i)->getRelocationInfo());
133 /// getVectorElements - This method, which is only valid on constant of vector
134 /// type, returns the elements of the vector in the specified smallvector.
135 /// This handles breaking down a vector undef into undef elements, etc. For
136 /// constant exprs and other cases we can't handle, we return an empty vector.
137 void Constant::getVectorElements(LLVMContext &Context,
138 SmallVectorImpl<Constant*> &Elts) const {
139 assert(isa<VectorType>(getType()) && "Not a vector constant!");
141 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this)) {
142 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i)
143 Elts.push_back(CV->getOperand(i));
147 const VectorType *VT = cast<VectorType>(getType());
148 if (isa<ConstantAggregateZero>(this)) {
149 Elts.assign(VT->getNumElements(),
150 Context.getNullValue(VT->getElementType()));
154 if (isa<UndefValue>(this)) {
155 Elts.assign(VT->getNumElements(), Context.getUndef(VT->getElementType()));
159 // Unknown type, must be constant expr etc.
164 //===----------------------------------------------------------------------===//
166 //===----------------------------------------------------------------------===//
168 ConstantInt::ConstantInt(const IntegerType *Ty, const APInt& V)
169 : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
170 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
173 //===----------------------------------------------------------------------===//
175 //===----------------------------------------------------------------------===//
178 static const fltSemantics *TypeToFloatSemantics(const Type *Ty) {
179 if (Ty == Type::FloatTy)
180 return &APFloat::IEEEsingle;
181 if (Ty == Type::DoubleTy)
182 return &APFloat::IEEEdouble;
183 if (Ty == Type::X86_FP80Ty)
184 return &APFloat::x87DoubleExtended;
185 else if (Ty == Type::FP128Ty)
186 return &APFloat::IEEEquad;
188 assert(Ty == Type::PPC_FP128Ty && "Unknown FP format");
189 return &APFloat::PPCDoubleDouble;
193 ConstantFP::ConstantFP(const Type *Ty, const APFloat& V)
194 : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
195 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
199 bool ConstantFP::isNullValue() const {
200 return Val.isZero() && !Val.isNegative();
203 bool ConstantFP::isExactlyValue(const APFloat& V) const {
204 return Val.bitwiseIsEqual(V);
207 //===----------------------------------------------------------------------===//
208 // ConstantXXX Classes
209 //===----------------------------------------------------------------------===//
212 ConstantArray::ConstantArray(const ArrayType *T,
213 const std::vector<Constant*> &V)
214 : Constant(T, ConstantArrayVal,
215 OperandTraits<ConstantArray>::op_end(this) - V.size(),
217 assert(V.size() == T->getNumElements() &&
218 "Invalid initializer vector for constant array");
219 Use *OL = OperandList;
220 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
223 assert((C->getType() == T->getElementType() ||
225 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
226 "Initializer for array element doesn't match array element type!");
232 ConstantStruct::ConstantStruct(const StructType *T,
233 const std::vector<Constant*> &V)
234 : Constant(T, ConstantStructVal,
235 OperandTraits<ConstantStruct>::op_end(this) - V.size(),
237 assert(V.size() == T->getNumElements() &&
238 "Invalid initializer vector for constant structure");
239 Use *OL = OperandList;
240 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
243 assert((C->getType() == T->getElementType(I-V.begin()) ||
244 ((T->getElementType(I-V.begin())->isAbstract() ||
245 C->getType()->isAbstract()) &&
246 T->getElementType(I-V.begin())->getTypeID() ==
247 C->getType()->getTypeID())) &&
248 "Initializer for struct element doesn't match struct element type!");
254 ConstantVector::ConstantVector(const VectorType *T,
255 const std::vector<Constant*> &V)
256 : Constant(T, ConstantVectorVal,
257 OperandTraits<ConstantVector>::op_end(this) - V.size(),
259 Use *OL = OperandList;
260 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
263 assert((C->getType() == T->getElementType() ||
265 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
266 "Initializer for vector element doesn't match vector element type!");
273 // We declare several classes private to this file, so use an anonymous
277 /// UnaryConstantExpr - This class is private to Constants.cpp, and is used
278 /// behind the scenes to implement unary constant exprs.
279 class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
280 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
282 // allocate space for exactly one operand
283 void *operator new(size_t s) {
284 return User::operator new(s, 1);
286 UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
287 : ConstantExpr(Ty, Opcode, &Op<0>(), 1) {
290 /// Transparently provide more efficient getOperand methods.
291 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
294 /// BinaryConstantExpr - This class is private to Constants.cpp, and is used
295 /// behind the scenes to implement binary constant exprs.
296 class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
297 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
299 // allocate space for exactly two operands
300 void *operator new(size_t s) {
301 return User::operator new(s, 2);
303 BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
304 : ConstantExpr(C1->getType(), Opcode, &Op<0>(), 2) {
308 /// Transparently provide more efficient getOperand methods.
309 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
312 /// SelectConstantExpr - This class is private to Constants.cpp, and is used
313 /// behind the scenes to implement select constant exprs.
314 class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
315 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
317 // allocate space for exactly three operands
318 void *operator new(size_t s) {
319 return User::operator new(s, 3);
321 SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
322 : ConstantExpr(C2->getType(), Instruction::Select, &Op<0>(), 3) {
327 /// Transparently provide more efficient getOperand methods.
328 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
331 /// ExtractElementConstantExpr - This class is private to
332 /// Constants.cpp, and is used behind the scenes to implement
333 /// extractelement constant exprs.
334 class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
335 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
337 // allocate space for exactly two operands
338 void *operator new(size_t s) {
339 return User::operator new(s, 2);
341 ExtractElementConstantExpr(Constant *C1, Constant *C2)
342 : ConstantExpr(cast<VectorType>(C1->getType())->getElementType(),
343 Instruction::ExtractElement, &Op<0>(), 2) {
347 /// Transparently provide more efficient getOperand methods.
348 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
351 /// InsertElementConstantExpr - This class is private to
352 /// Constants.cpp, and is used behind the scenes to implement
353 /// insertelement constant exprs.
354 class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
355 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
357 // allocate space for exactly three operands
358 void *operator new(size_t s) {
359 return User::operator new(s, 3);
361 InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
362 : ConstantExpr(C1->getType(), Instruction::InsertElement,
368 /// Transparently provide more efficient getOperand methods.
369 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
372 /// ShuffleVectorConstantExpr - This class is private to
373 /// Constants.cpp, and is used behind the scenes to implement
374 /// shufflevector constant exprs.
375 class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
376 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
378 // allocate space for exactly three operands
379 void *operator new(size_t s) {
380 return User::operator new(s, 3);
382 ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
383 : ConstantExpr(VectorType::get(
384 cast<VectorType>(C1->getType())->getElementType(),
385 cast<VectorType>(C3->getType())->getNumElements()),
386 Instruction::ShuffleVector,
392 /// Transparently provide more efficient getOperand methods.
393 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
396 /// ExtractValueConstantExpr - This class is private to
397 /// Constants.cpp, and is used behind the scenes to implement
398 /// extractvalue constant exprs.
399 class VISIBILITY_HIDDEN ExtractValueConstantExpr : public ConstantExpr {
400 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
402 // allocate space for exactly one operand
403 void *operator new(size_t s) {
404 return User::operator new(s, 1);
406 ExtractValueConstantExpr(Constant *Agg,
407 const SmallVector<unsigned, 4> &IdxList,
409 : ConstantExpr(DestTy, Instruction::ExtractValue, &Op<0>(), 1),
414 /// Indices - These identify which value to extract.
415 const SmallVector<unsigned, 4> Indices;
417 /// Transparently provide more efficient getOperand methods.
418 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
421 /// InsertValueConstantExpr - This class is private to
422 /// Constants.cpp, and is used behind the scenes to implement
423 /// insertvalue constant exprs.
424 class VISIBILITY_HIDDEN InsertValueConstantExpr : public ConstantExpr {
425 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
427 // allocate space for exactly one operand
428 void *operator new(size_t s) {
429 return User::operator new(s, 2);
431 InsertValueConstantExpr(Constant *Agg, Constant *Val,
432 const SmallVector<unsigned, 4> &IdxList,
434 : ConstantExpr(DestTy, Instruction::InsertValue, &Op<0>(), 2),
440 /// Indices - These identify the position for the insertion.
441 const SmallVector<unsigned, 4> Indices;
443 /// Transparently provide more efficient getOperand methods.
444 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
448 /// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
449 /// used behind the scenes to implement getelementpr constant exprs.
450 class VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
451 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
454 static GetElementPtrConstantExpr *Create(Constant *C,
455 const std::vector<Constant*>&IdxList,
456 const Type *DestTy) {
458 new(IdxList.size() + 1) GetElementPtrConstantExpr(C, IdxList, DestTy);
460 /// Transparently provide more efficient getOperand methods.
461 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
464 // CompareConstantExpr - This class is private to Constants.cpp, and is used
465 // behind the scenes to implement ICmp and FCmp constant expressions. This is
466 // needed in order to store the predicate value for these instructions.
467 struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
468 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
469 // allocate space for exactly two operands
470 void *operator new(size_t s) {
471 return User::operator new(s, 2);
473 unsigned short predicate;
474 CompareConstantExpr(const Type *ty, Instruction::OtherOps opc,
475 unsigned short pred, Constant* LHS, Constant* RHS)
476 : ConstantExpr(ty, opc, &Op<0>(), 2), predicate(pred) {
480 /// Transparently provide more efficient getOperand methods.
481 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
484 } // end anonymous namespace
487 struct OperandTraits<UnaryConstantExpr> : FixedNumOperandTraits<1> {
489 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(UnaryConstantExpr, Value)
492 struct OperandTraits<BinaryConstantExpr> : FixedNumOperandTraits<2> {
494 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BinaryConstantExpr, Value)
497 struct OperandTraits<SelectConstantExpr> : FixedNumOperandTraits<3> {
499 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectConstantExpr, Value)
502 struct OperandTraits<ExtractElementConstantExpr> : FixedNumOperandTraits<2> {
504 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementConstantExpr, Value)
507 struct OperandTraits<InsertElementConstantExpr> : FixedNumOperandTraits<3> {
509 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementConstantExpr, Value)
512 struct OperandTraits<ShuffleVectorConstantExpr> : FixedNumOperandTraits<3> {
514 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorConstantExpr, Value)
517 struct OperandTraits<ExtractValueConstantExpr> : FixedNumOperandTraits<1> {
519 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractValueConstantExpr, Value)
522 struct OperandTraits<InsertValueConstantExpr> : FixedNumOperandTraits<2> {
524 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueConstantExpr, Value)
527 struct OperandTraits<GetElementPtrConstantExpr> : VariadicOperandTraits<1> {
530 GetElementPtrConstantExpr::GetElementPtrConstantExpr
532 const std::vector<Constant*> &IdxList,
534 : ConstantExpr(DestTy, Instruction::GetElementPtr,
535 OperandTraits<GetElementPtrConstantExpr>::op_end(this)
536 - (IdxList.size()+1),
539 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
540 OperandList[i+1] = IdxList[i];
543 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrConstantExpr, Value)
547 struct OperandTraits<CompareConstantExpr> : FixedNumOperandTraits<2> {
549 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CompareConstantExpr, Value)
552 } // End llvm namespace
555 // Utility function for determining if a ConstantExpr is a CastOp or not. This
556 // can't be inline because we don't want to #include Instruction.h into
558 bool ConstantExpr::isCast() const {
559 return Instruction::isCast(getOpcode());
562 bool ConstantExpr::isCompare() const {
563 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
566 bool ConstantExpr::hasIndices() const {
567 return getOpcode() == Instruction::ExtractValue ||
568 getOpcode() == Instruction::InsertValue;
571 const SmallVector<unsigned, 4> &ConstantExpr::getIndices() const {
572 if (const ExtractValueConstantExpr *EVCE =
573 dyn_cast<ExtractValueConstantExpr>(this))
574 return EVCE->Indices;
576 return cast<InsertValueConstantExpr>(this)->Indices;
579 unsigned ConstantExpr::getPredicate() const {
580 assert(getOpcode() == Instruction::FCmp ||
581 getOpcode() == Instruction::ICmp);
582 return ((const CompareConstantExpr*)this)->predicate;
585 /// getWithOperandReplaced - Return a constant expression identical to this
586 /// one, but with the specified operand set to the specified value.
588 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
589 assert(OpNo < getNumOperands() && "Operand num is out of range!");
590 assert(Op->getType() == getOperand(OpNo)->getType() &&
591 "Replacing operand with value of different type!");
592 if (getOperand(OpNo) == Op)
593 return const_cast<ConstantExpr*>(this);
595 Constant *Op0, *Op1, *Op2;
596 switch (getOpcode()) {
597 case Instruction::Trunc:
598 case Instruction::ZExt:
599 case Instruction::SExt:
600 case Instruction::FPTrunc:
601 case Instruction::FPExt:
602 case Instruction::UIToFP:
603 case Instruction::SIToFP:
604 case Instruction::FPToUI:
605 case Instruction::FPToSI:
606 case Instruction::PtrToInt:
607 case Instruction::IntToPtr:
608 case Instruction::BitCast:
609 return ConstantExpr::getCast(getOpcode(), Op, getType());
610 case Instruction::Select:
611 Op0 = (OpNo == 0) ? Op : getOperand(0);
612 Op1 = (OpNo == 1) ? Op : getOperand(1);
613 Op2 = (OpNo == 2) ? Op : getOperand(2);
614 return ConstantExpr::getSelect(Op0, Op1, Op2);
615 case Instruction::InsertElement:
616 Op0 = (OpNo == 0) ? Op : getOperand(0);
617 Op1 = (OpNo == 1) ? Op : getOperand(1);
618 Op2 = (OpNo == 2) ? Op : getOperand(2);
619 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
620 case Instruction::ExtractElement:
621 Op0 = (OpNo == 0) ? Op : getOperand(0);
622 Op1 = (OpNo == 1) ? Op : getOperand(1);
623 return ConstantExpr::getExtractElement(Op0, Op1);
624 case Instruction::ShuffleVector:
625 Op0 = (OpNo == 0) ? Op : getOperand(0);
626 Op1 = (OpNo == 1) ? Op : getOperand(1);
627 Op2 = (OpNo == 2) ? Op : getOperand(2);
628 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
629 case Instruction::GetElementPtr: {
630 SmallVector<Constant*, 8> Ops;
631 Ops.resize(getNumOperands()-1);
632 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
633 Ops[i-1] = getOperand(i);
635 return ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
637 return ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
640 assert(getNumOperands() == 2 && "Must be binary operator?");
641 Op0 = (OpNo == 0) ? Op : getOperand(0);
642 Op1 = (OpNo == 1) ? Op : getOperand(1);
643 return ConstantExpr::get(getOpcode(), Op0, Op1);
647 /// getWithOperands - This returns the current constant expression with the
648 /// operands replaced with the specified values. The specified operands must
649 /// match count and type with the existing ones.
650 Constant *ConstantExpr::
651 getWithOperands(Constant* const *Ops, unsigned NumOps) const {
652 assert(NumOps == getNumOperands() && "Operand count mismatch!");
653 bool AnyChange = false;
654 for (unsigned i = 0; i != NumOps; ++i) {
655 assert(Ops[i]->getType() == getOperand(i)->getType() &&
656 "Operand type mismatch!");
657 AnyChange |= Ops[i] != getOperand(i);
659 if (!AnyChange) // No operands changed, return self.
660 return const_cast<ConstantExpr*>(this);
662 switch (getOpcode()) {
663 case Instruction::Trunc:
664 case Instruction::ZExt:
665 case Instruction::SExt:
666 case Instruction::FPTrunc:
667 case Instruction::FPExt:
668 case Instruction::UIToFP:
669 case Instruction::SIToFP:
670 case Instruction::FPToUI:
671 case Instruction::FPToSI:
672 case Instruction::PtrToInt:
673 case Instruction::IntToPtr:
674 case Instruction::BitCast:
675 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
676 case Instruction::Select:
677 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
678 case Instruction::InsertElement:
679 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
680 case Instruction::ExtractElement:
681 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
682 case Instruction::ShuffleVector:
683 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
684 case Instruction::GetElementPtr:
685 return ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], NumOps-1);
686 case Instruction::ICmp:
687 case Instruction::FCmp:
688 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
690 assert(getNumOperands() == 2 && "Must be binary operator?");
691 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
696 //===----------------------------------------------------------------------===//
697 // isValueValidForType implementations
699 bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
700 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
701 if (Ty == Type::Int1Ty)
702 return Val == 0 || Val == 1;
704 return true; // always true, has to fit in largest type
705 uint64_t Max = (1ll << NumBits) - 1;
709 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
710 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
711 if (Ty == Type::Int1Ty)
712 return Val == 0 || Val == 1 || Val == -1;
714 return true; // always true, has to fit in largest type
715 int64_t Min = -(1ll << (NumBits-1));
716 int64_t Max = (1ll << (NumBits-1)) - 1;
717 return (Val >= Min && Val <= Max);
720 bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
721 // convert modifies in place, so make a copy.
722 APFloat Val2 = APFloat(Val);
724 switch (Ty->getTypeID()) {
726 return false; // These can't be represented as floating point!
728 // FIXME rounding mode needs to be more flexible
729 case Type::FloatTyID: {
730 if (&Val2.getSemantics() == &APFloat::IEEEsingle)
732 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
735 case Type::DoubleTyID: {
736 if (&Val2.getSemantics() == &APFloat::IEEEsingle ||
737 &Val2.getSemantics() == &APFloat::IEEEdouble)
739 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
742 case Type::X86_FP80TyID:
743 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
744 &Val2.getSemantics() == &APFloat::IEEEdouble ||
745 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
746 case Type::FP128TyID:
747 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
748 &Val2.getSemantics() == &APFloat::IEEEdouble ||
749 &Val2.getSemantics() == &APFloat::IEEEquad;
750 case Type::PPC_FP128TyID:
751 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
752 &Val2.getSemantics() == &APFloat::IEEEdouble ||
753 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
757 //===----------------------------------------------------------------------===//
758 // Factory Function Implementation
761 // The number of operands for each ConstantCreator::create method is
762 // determined by the ConstantTraits template.
763 // ConstantCreator - A class that is used to create constants by
764 // ValueMap*. This class should be partially specialized if there is
765 // something strange that needs to be done to interface to the ctor for the
769 template<class ValType>
770 struct ConstantTraits;
772 template<typename T, typename Alloc>
773 struct VISIBILITY_HIDDEN ConstantTraits< std::vector<T, Alloc> > {
774 static unsigned uses(const std::vector<T, Alloc>& v) {
779 template<class ConstantClass, class TypeClass, class ValType>
780 struct VISIBILITY_HIDDEN ConstantCreator {
781 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
782 return new(ConstantTraits<ValType>::uses(V)) ConstantClass(Ty, V);
786 template<class ConstantClass, class TypeClass>
787 struct VISIBILITY_HIDDEN ConvertConstantType {
788 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
789 llvm_unreachable("This type cannot be converted!");
793 template<class ValType, class TypeClass, class ConstantClass,
794 bool HasLargeKey = false /*true for arrays and structs*/ >
795 class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
797 typedef std::pair<const Type*, ValType> MapKey;
798 typedef std::map<MapKey, Constant *> MapTy;
799 typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
800 typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
802 /// Map - This is the main map from the element descriptor to the Constants.
803 /// This is the primary way we avoid creating two of the same shape
807 /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
808 /// from the constants to their element in Map. This is important for
809 /// removal of constants from the array, which would otherwise have to scan
810 /// through the map with very large keys.
811 InverseMapTy InverseMap;
813 /// AbstractTypeMap - Map for abstract type constants.
815 AbstractTypeMapTy AbstractTypeMap;
817 /// ValueMapLock - Mutex for this map.
818 sys::SmartMutex<true> ValueMapLock;
821 // NOTE: This function is not locked. It is the caller's responsibility
822 // to enforce proper synchronization.
823 typename MapTy::iterator map_end() { return Map.end(); }
825 /// InsertOrGetItem - Return an iterator for the specified element.
826 /// If the element exists in the map, the returned iterator points to the
827 /// entry and Exists=true. If not, the iterator points to the newly
828 /// inserted entry and returns Exists=false. Newly inserted entries have
829 /// I->second == 0, and should be filled in.
830 /// NOTE: This function is not locked. It is the caller's responsibility
831 // to enforce proper synchronization.
832 typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
835 std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
841 typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
843 typename InverseMapTy::iterator IMI = InverseMap.find(CP);
844 assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
845 IMI->second->second == CP &&
846 "InverseMap corrupt!");
850 typename MapTy::iterator I =
851 Map.find(MapKey(static_cast<const TypeClass*>(CP->getRawType()),
853 if (I == Map.end() || I->second != CP) {
854 // FIXME: This should not use a linear scan. If this gets to be a
855 // performance problem, someone should look at this.
856 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
862 ConstantClass* Create(const TypeClass *Ty, const ValType &V,
863 typename MapTy::iterator I) {
864 ConstantClass* Result =
865 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
867 assert(Result->getType() == Ty && "Type specified is not correct!");
868 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
870 if (HasLargeKey) // Remember the reverse mapping if needed.
871 InverseMap.insert(std::make_pair(Result, I));
873 // If the type of the constant is abstract, make sure that an entry
874 // exists for it in the AbstractTypeMap.
875 if (Ty->isAbstract()) {
876 typename AbstractTypeMapTy::iterator TI =
877 AbstractTypeMap.find(Ty);
879 if (TI == AbstractTypeMap.end()) {
880 // Add ourselves to the ATU list of the type.
881 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
883 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
891 /// getOrCreate - Return the specified constant from the map, creating it if
893 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
894 sys::SmartScopedLock<true> Lock(ValueMapLock);
895 MapKey Lookup(Ty, V);
896 ConstantClass* Result = 0;
898 typename MapTy::iterator I = Map.find(Lookup);
901 Result = static_cast<ConstantClass *>(I->second);
904 // If no preexisting value, create one now...
905 Result = Create(Ty, V, I);
911 void remove(ConstantClass *CP) {
912 sys::SmartScopedLock<true> Lock(ValueMapLock);
913 typename MapTy::iterator I = FindExistingElement(CP);
914 assert(I != Map.end() && "Constant not found in constant table!");
915 assert(I->second == CP && "Didn't find correct element?");
917 if (HasLargeKey) // Remember the reverse mapping if needed.
918 InverseMap.erase(CP);
920 // Now that we found the entry, make sure this isn't the entry that
921 // the AbstractTypeMap points to.
922 const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
923 if (Ty->isAbstract()) {
924 assert(AbstractTypeMap.count(Ty) &&
925 "Abstract type not in AbstractTypeMap?");
926 typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
927 if (ATMEntryIt == I) {
928 // Yes, we are removing the representative entry for this type.
929 // See if there are any other entries of the same type.
930 typename MapTy::iterator TmpIt = ATMEntryIt;
932 // First check the entry before this one...
933 if (TmpIt != Map.begin()) {
935 if (TmpIt->first.first != Ty) // Not the same type, move back...
939 // If we didn't find the same type, try to move forward...
940 if (TmpIt == ATMEntryIt) {
942 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
943 --TmpIt; // No entry afterwards with the same type
946 // If there is another entry in the map of the same abstract type,
947 // update the AbstractTypeMap entry now.
948 if (TmpIt != ATMEntryIt) {
951 // Otherwise, we are removing the last instance of this type
952 // from the table. Remove from the ATM, and from user list.
953 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
954 AbstractTypeMap.erase(Ty);
963 /// MoveConstantToNewSlot - If we are about to change C to be the element
964 /// specified by I, update our internal data structures to reflect this
966 /// NOTE: This function is not locked. It is the responsibility of the
967 /// caller to enforce proper synchronization if using this method.
968 void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
969 // First, remove the old location of the specified constant in the map.
970 typename MapTy::iterator OldI = FindExistingElement(C);
971 assert(OldI != Map.end() && "Constant not found in constant table!");
972 assert(OldI->second == C && "Didn't find correct element?");
974 // If this constant is the representative element for its abstract type,
975 // update the AbstractTypeMap so that the representative element is I.
976 if (C->getType()->isAbstract()) {
977 typename AbstractTypeMapTy::iterator ATI =
978 AbstractTypeMap.find(C->getType());
979 assert(ATI != AbstractTypeMap.end() &&
980 "Abstract type not in AbstractTypeMap?");
981 if (ATI->second == OldI)
985 // Remove the old entry from the map.
988 // Update the inverse map so that we know that this constant is now
989 // located at descriptor I.
991 assert(I->second == C && "Bad inversemap entry!");
996 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
997 sys::SmartScopedLock<true> Lock(ValueMapLock);
998 typename AbstractTypeMapTy::iterator I =
999 AbstractTypeMap.find(cast<Type>(OldTy));
1001 assert(I != AbstractTypeMap.end() &&
1002 "Abstract type not in AbstractTypeMap?");
1004 // Convert a constant at a time until the last one is gone. The last one
1005 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
1006 // eliminated eventually.
1008 ConvertConstantType<ConstantClass,
1009 TypeClass>::convert(
1010 static_cast<ConstantClass *>(I->second->second),
1011 cast<TypeClass>(NewTy));
1013 I = AbstractTypeMap.find(cast<Type>(OldTy));
1014 } while (I != AbstractTypeMap.end());
1017 // If the type became concrete without being refined to any other existing
1018 // type, we just remove ourselves from the ATU list.
1019 void typeBecameConcrete(const DerivedType *AbsTy) {
1020 AbsTy->removeAbstractTypeUser(this);
1024 DOUT << "Constant.cpp: ValueMap\n";
1029 /// destroyConstant - Remove the constant from the constant table...
1031 void ConstantAggregateZero::destroyConstant() {
1032 // Implicitly locked.
1033 getType()->getContext().erase(this);
1034 destroyConstantImpl();
1037 /// destroyConstant - Remove the constant from the constant table...
1039 void ConstantArray::destroyConstant() {
1040 // Implicitly locked.
1041 getType()->getContext().erase(this);
1042 destroyConstantImpl();
1045 /// isString - This method returns true if the array is an array of i8, and
1046 /// if the elements of the array are all ConstantInt's.
1047 bool ConstantArray::isString() const {
1048 // Check the element type for i8...
1049 if (getType()->getElementType() != Type::Int8Ty)
1051 // Check the elements to make sure they are all integers, not constant
1053 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1054 if (!isa<ConstantInt>(getOperand(i)))
1059 /// isCString - This method returns true if the array is a string (see
1060 /// isString) and it ends in a null byte \\0 and does not contains any other
1061 /// null bytes except its terminator.
1062 bool ConstantArray::isCString() const {
1063 // Check the element type for i8...
1064 if (getType()->getElementType() != Type::Int8Ty)
1067 // Last element must be a null.
1068 if (!getOperand(getNumOperands()-1)->isNullValue())
1070 // Other elements must be non-null integers.
1071 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1072 if (!isa<ConstantInt>(getOperand(i)))
1074 if (getOperand(i)->isNullValue())
1081 /// getAsString - If the sub-element type of this array is i8
1082 /// then this method converts the array to an std::string and returns it.
1083 /// Otherwise, it asserts out.
1085 std::string ConstantArray::getAsString() const {
1086 assert(isString() && "Not a string!");
1088 Result.reserve(getNumOperands());
1089 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1090 Result.push_back((char)cast<ConstantInt>(getOperand(i))->getZExtValue());
1095 //---- ConstantStruct::get() implementation...
1102 // destroyConstant - Remove the constant from the constant table...
1104 void ConstantStruct::destroyConstant() {
1105 // Implicitly locked.
1106 getType()->getContext().erase(this);
1107 destroyConstantImpl();
1110 // destroyConstant - Remove the constant from the constant table...
1112 void ConstantVector::destroyConstant() {
1113 // Implicitly locked.
1114 getType()->getContext().erase(this);
1115 destroyConstantImpl();
1118 /// This function will return true iff every element in this vector constant
1119 /// is set to all ones.
1120 /// @returns true iff this constant's emements are all set to all ones.
1121 /// @brief Determine if the value is all ones.
1122 bool ConstantVector::isAllOnesValue() const {
1123 // Check out first element.
1124 const Constant *Elt = getOperand(0);
1125 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1126 if (!CI || !CI->isAllOnesValue()) return false;
1127 // Then make sure all remaining elements point to the same value.
1128 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1129 if (getOperand(I) != Elt) return false;
1134 /// getSplatValue - If this is a splat constant, where all of the
1135 /// elements have the same value, return that value. Otherwise return null.
1136 Constant *ConstantVector::getSplatValue() {
1137 // Check out first element.
1138 Constant *Elt = getOperand(0);
1139 // Then make sure all remaining elements point to the same value.
1140 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1141 if (getOperand(I) != Elt) return 0;
1145 //---- ConstantPointerNull::get() implementation...
1149 // ConstantPointerNull does not take extra "value" argument...
1150 template<class ValType>
1151 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1152 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1153 return new ConstantPointerNull(Ty);
1158 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1159 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1160 // Make everyone now use a constant of the new type...
1161 Constant *New = ConstantPointerNull::get(NewTy);
1162 assert(New != OldC && "Didn't replace constant??");
1163 OldC->uncheckedReplaceAllUsesWith(New);
1164 OldC->destroyConstant(); // This constant is now dead, destroy it.
1169 static ManagedStatic<ValueMap<char, PointerType,
1170 ConstantPointerNull> > NullPtrConstants;
1172 static char getValType(ConstantPointerNull *) {
1177 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1178 // Implicitly locked.
1179 return NullPtrConstants->getOrCreate(Ty, 0);
1182 // destroyConstant - Remove the constant from the constant table...
1184 void ConstantPointerNull::destroyConstant() {
1185 // Implicitly locked.
1186 NullPtrConstants->remove(this);
1187 destroyConstantImpl();
1191 //---- UndefValue::get() implementation...
1195 // UndefValue does not take extra "value" argument...
1196 template<class ValType>
1197 struct ConstantCreator<UndefValue, Type, ValType> {
1198 static UndefValue *create(const Type *Ty, const ValType &V) {
1199 return new UndefValue(Ty);
1204 struct ConvertConstantType<UndefValue, Type> {
1205 static void convert(UndefValue *OldC, const Type *NewTy) {
1206 // Make everyone now use a constant of the new type.
1207 Constant *New = UndefValue::get(NewTy);
1208 assert(New != OldC && "Didn't replace constant??");
1209 OldC->uncheckedReplaceAllUsesWith(New);
1210 OldC->destroyConstant(); // This constant is now dead, destroy it.
1215 static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
1217 static char getValType(UndefValue *) {
1222 UndefValue *UndefValue::get(const Type *Ty) {
1223 // Implicitly locked.
1224 return UndefValueConstants->getOrCreate(Ty, 0);
1227 // destroyConstant - Remove the constant from the constant table.
1229 void UndefValue::destroyConstant() {
1230 // Implicitly locked.
1231 UndefValueConstants->remove(this);
1232 destroyConstantImpl();
1235 //---- MDNode::get() implementation
1238 MDNode::MDNode(Value*const* Vals, unsigned NumVals)
1239 : MetadataBase(Type::MetadataTy, Value::MDNodeVal) {
1240 for (unsigned i = 0; i != NumVals; ++i)
1241 Node.push_back(WeakVH(Vals[i]));
1244 void MDNode::Profile(FoldingSetNodeID &ID) const {
1245 for (const_elem_iterator I = elem_begin(), E = elem_end(); I != E; ++I)
1249 //---- ConstantExpr::get() implementations...
1254 struct ExprMapKeyType {
1255 typedef SmallVector<unsigned, 4> IndexList;
1257 ExprMapKeyType(unsigned opc,
1258 const std::vector<Constant*> &ops,
1259 unsigned short pred = 0,
1260 const IndexList &inds = IndexList())
1261 : opcode(opc), predicate(pred), operands(ops), indices(inds) {}
1264 std::vector<Constant*> operands;
1266 bool operator==(const ExprMapKeyType& that) const {
1267 return this->opcode == that.opcode &&
1268 this->predicate == that.predicate &&
1269 this->operands == that.operands &&
1270 this->indices == that.indices;
1272 bool operator<(const ExprMapKeyType & that) const {
1273 return this->opcode < that.opcode ||
1274 (this->opcode == that.opcode && this->predicate < that.predicate) ||
1275 (this->opcode == that.opcode && this->predicate == that.predicate &&
1276 this->operands < that.operands) ||
1277 (this->opcode == that.opcode && this->predicate == that.predicate &&
1278 this->operands == that.operands && this->indices < that.indices);
1281 bool operator!=(const ExprMapKeyType& that) const {
1282 return !(*this == that);
1290 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1291 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1292 unsigned short pred = 0) {
1293 if (Instruction::isCast(V.opcode))
1294 return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1295 if ((V.opcode >= Instruction::BinaryOpsBegin &&
1296 V.opcode < Instruction::BinaryOpsEnd))
1297 return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1298 if (V.opcode == Instruction::Select)
1299 return new SelectConstantExpr(V.operands[0], V.operands[1],
1301 if (V.opcode == Instruction::ExtractElement)
1302 return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1303 if (V.opcode == Instruction::InsertElement)
1304 return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1306 if (V.opcode == Instruction::ShuffleVector)
1307 return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1309 if (V.opcode == Instruction::InsertValue)
1310 return new InsertValueConstantExpr(V.operands[0], V.operands[1],
1312 if (V.opcode == Instruction::ExtractValue)
1313 return new ExtractValueConstantExpr(V.operands[0], V.indices, Ty);
1314 if (V.opcode == Instruction::GetElementPtr) {
1315 std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
1316 return GetElementPtrConstantExpr::Create(V.operands[0], IdxList, Ty);
1319 // The compare instructions are weird. We have to encode the predicate
1320 // value and it is combined with the instruction opcode by multiplying
1321 // the opcode by one hundred. We must decode this to get the predicate.
1322 if (V.opcode == Instruction::ICmp)
1323 return new CompareConstantExpr(Ty, Instruction::ICmp, V.predicate,
1324 V.operands[0], V.operands[1]);
1325 if (V.opcode == Instruction::FCmp)
1326 return new CompareConstantExpr(Ty, Instruction::FCmp, V.predicate,
1327 V.operands[0], V.operands[1]);
1328 llvm_unreachable("Invalid ConstantExpr!");
1334 struct ConvertConstantType<ConstantExpr, Type> {
1335 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1337 switch (OldC->getOpcode()) {
1338 case Instruction::Trunc:
1339 case Instruction::ZExt:
1340 case Instruction::SExt:
1341 case Instruction::FPTrunc:
1342 case Instruction::FPExt:
1343 case Instruction::UIToFP:
1344 case Instruction::SIToFP:
1345 case Instruction::FPToUI:
1346 case Instruction::FPToSI:
1347 case Instruction::PtrToInt:
1348 case Instruction::IntToPtr:
1349 case Instruction::BitCast:
1350 New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0),
1353 case Instruction::Select:
1354 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1355 OldC->getOperand(1),
1356 OldC->getOperand(2));
1359 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1360 OldC->getOpcode() < Instruction::BinaryOpsEnd);
1361 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1362 OldC->getOperand(1));
1364 case Instruction::GetElementPtr:
1365 // Make everyone now use a constant of the new type...
1366 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1367 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0),
1368 &Idx[0], Idx.size());
1372 assert(New != OldC && "Didn't replace constant??");
1373 OldC->uncheckedReplaceAllUsesWith(New);
1374 OldC->destroyConstant(); // This constant is now dead, destroy it.
1377 } // end namespace llvm
1380 static ExprMapKeyType getValType(ConstantExpr *CE) {
1381 std::vector<Constant*> Operands;
1382 Operands.reserve(CE->getNumOperands());
1383 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1384 Operands.push_back(cast<Constant>(CE->getOperand(i)));
1385 return ExprMapKeyType(CE->getOpcode(), Operands,
1386 CE->isCompare() ? CE->getPredicate() : 0,
1388 CE->getIndices() : SmallVector<unsigned, 4>());
1391 static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1392 ConstantExpr> > ExprConstants;
1394 /// This is a utility function to handle folding of casts and lookup of the
1395 /// cast in the ExprConstants map. It is used by the various get* methods below.
1396 static inline Constant *getFoldedCast(
1397 Instruction::CastOps opc, Constant *C, const Type *Ty) {
1398 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1399 // Fold a few common cases
1401 ConstantFoldCastInstruction(getGlobalContext(), opc, C, Ty))
1404 // Look up the constant in the table first to ensure uniqueness
1405 std::vector<Constant*> argVec(1, C);
1406 ExprMapKeyType Key(opc, argVec);
1408 // Implicitly locked.
1409 return ExprConstants->getOrCreate(Ty, Key);
1412 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1413 Instruction::CastOps opc = Instruction::CastOps(oc);
1414 assert(Instruction::isCast(opc) && "opcode out of range");
1415 assert(C && Ty && "Null arguments to getCast");
1416 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1420 llvm_unreachable("Invalid cast opcode");
1422 case Instruction::Trunc: return getTrunc(C, Ty);
1423 case Instruction::ZExt: return getZExt(C, Ty);
1424 case Instruction::SExt: return getSExt(C, Ty);
1425 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1426 case Instruction::FPExt: return getFPExtend(C, Ty);
1427 case Instruction::UIToFP: return getUIToFP(C, Ty);
1428 case Instruction::SIToFP: return getSIToFP(C, Ty);
1429 case Instruction::FPToUI: return getFPToUI(C, Ty);
1430 case Instruction::FPToSI: return getFPToSI(C, Ty);
1431 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1432 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1433 case Instruction::BitCast: return getBitCast(C, Ty);
1438 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1439 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1440 return getCast(Instruction::BitCast, C, Ty);
1441 return getCast(Instruction::ZExt, C, Ty);
1444 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1445 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1446 return getCast(Instruction::BitCast, C, Ty);
1447 return getCast(Instruction::SExt, C, Ty);
1450 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1451 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1452 return getCast(Instruction::BitCast, C, Ty);
1453 return getCast(Instruction::Trunc, C, Ty);
1456 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1457 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1458 assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
1460 if (Ty->isInteger())
1461 return getCast(Instruction::PtrToInt, S, Ty);
1462 return getCast(Instruction::BitCast, S, Ty);
1465 Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
1467 assert(C->getType()->isIntOrIntVector() &&
1468 Ty->isIntOrIntVector() && "Invalid cast");
1469 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1470 unsigned DstBits = Ty->getScalarSizeInBits();
1471 Instruction::CastOps opcode =
1472 (SrcBits == DstBits ? Instruction::BitCast :
1473 (SrcBits > DstBits ? Instruction::Trunc :
1474 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1475 return getCast(opcode, C, Ty);
1478 Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1479 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1481 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1482 unsigned DstBits = Ty->getScalarSizeInBits();
1483 if (SrcBits == DstBits)
1484 return C; // Avoid a useless cast
1485 Instruction::CastOps opcode =
1486 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1487 return getCast(opcode, C, Ty);
1490 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
1492 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1493 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1495 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1496 assert(C->getType()->isIntOrIntVector() && "Trunc operand must be integer");
1497 assert(Ty->isIntOrIntVector() && "Trunc produces only integral");
1498 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1499 "SrcTy must be larger than DestTy for Trunc!");
1501 return getFoldedCast(Instruction::Trunc, C, Ty);
1504 Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
1506 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1507 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1509 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1510 assert(C->getType()->isIntOrIntVector() && "SExt operand must be integral");
1511 assert(Ty->isIntOrIntVector() && "SExt produces only integer");
1512 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1513 "SrcTy must be smaller than DestTy for SExt!");
1515 return getFoldedCast(Instruction::SExt, C, Ty);
1518 Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
1520 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1521 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1523 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1524 assert(C->getType()->isIntOrIntVector() && "ZEXt operand must be integral");
1525 assert(Ty->isIntOrIntVector() && "ZExt produces only integer");
1526 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1527 "SrcTy must be smaller than DestTy for ZExt!");
1529 return getFoldedCast(Instruction::ZExt, C, Ty);
1532 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1534 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1535 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1537 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1538 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1539 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1540 "This is an illegal floating point truncation!");
1541 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1544 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1546 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1547 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1549 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1550 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1551 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1552 "This is an illegal floating point extension!");
1553 return getFoldedCast(Instruction::FPExt, C, Ty);
1556 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
1558 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1559 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1561 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1562 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1563 "This is an illegal uint to floating point cast!");
1564 return getFoldedCast(Instruction::UIToFP, C, Ty);
1567 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
1569 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1570 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1572 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1573 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1574 "This is an illegal sint to floating point cast!");
1575 return getFoldedCast(Instruction::SIToFP, C, Ty);
1578 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
1580 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1581 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1583 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1584 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1585 "This is an illegal floating point to uint cast!");
1586 return getFoldedCast(Instruction::FPToUI, C, Ty);
1589 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
1591 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1592 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1594 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1595 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1596 "This is an illegal floating point to sint cast!");
1597 return getFoldedCast(Instruction::FPToSI, C, Ty);
1600 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1601 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
1602 assert(DstTy->isInteger() && "PtrToInt destination must be integral");
1603 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1606 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
1607 assert(C->getType()->isInteger() && "IntToPtr source must be integral");
1608 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
1609 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1612 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1613 // BitCast implies a no-op cast of type only. No bits change. However, you
1614 // can't cast pointers to anything but pointers.
1616 const Type *SrcTy = C->getType();
1617 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
1618 "BitCast cannot cast pointer to non-pointer and vice versa");
1620 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
1621 // or nonptr->ptr). For all the other types, the cast is okay if source and
1622 // destination bit widths are identical.
1623 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1624 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
1626 assert(SrcBitSize == DstBitSize && "BitCast requires types of same width");
1628 // It is common to ask for a bitcast of a value to its own type, handle this
1630 if (C->getType() == DstTy) return C;
1632 return getFoldedCast(Instruction::BitCast, C, DstTy);
1635 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1636 Constant *C1, Constant *C2) {
1637 // Check the operands for consistency first
1638 assert(Opcode >= Instruction::BinaryOpsBegin &&
1639 Opcode < Instruction::BinaryOpsEnd &&
1640 "Invalid opcode in binary constant expression");
1641 assert(C1->getType() == C2->getType() &&
1642 "Operand types in binary constant expression should match");
1644 if (ReqTy == C1->getType() || ReqTy == Type::Int1Ty)
1645 if (Constant *FC = ConstantFoldBinaryInstruction(
1646 getGlobalContext(), Opcode, C1, C2))
1647 return FC; // Fold a few common cases...
1649 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1650 ExprMapKeyType Key(Opcode, argVec);
1652 // Implicitly locked.
1653 return ExprConstants->getOrCreate(ReqTy, Key);
1656 Constant *ConstantExpr::getCompareTy(unsigned short predicate,
1657 Constant *C1, Constant *C2) {
1658 switch (predicate) {
1659 default: llvm_unreachable("Invalid CmpInst predicate");
1660 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
1661 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
1662 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
1663 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
1664 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
1665 case CmpInst::FCMP_TRUE:
1666 return getFCmp(predicate, C1, C2);
1668 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
1669 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
1670 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
1671 case CmpInst::ICMP_SLE:
1672 return getICmp(predicate, C1, C2);
1676 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
1677 // API compatibility: Adjust integer opcodes to floating-point opcodes.
1678 if (C1->getType()->isFPOrFPVector()) {
1679 if (Opcode == Instruction::Add) Opcode = Instruction::FAdd;
1680 else if (Opcode == Instruction::Sub) Opcode = Instruction::FSub;
1681 else if (Opcode == Instruction::Mul) Opcode = Instruction::FMul;
1685 case Instruction::Add:
1686 case Instruction::Sub:
1687 case Instruction::Mul:
1688 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1689 assert(C1->getType()->isIntOrIntVector() &&
1690 "Tried to create an integer operation on a non-integer type!");
1692 case Instruction::FAdd:
1693 case Instruction::FSub:
1694 case Instruction::FMul:
1695 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1696 assert(C1->getType()->isFPOrFPVector() &&
1697 "Tried to create a floating-point operation on a "
1698 "non-floating-point type!");
1700 case Instruction::UDiv:
1701 case Instruction::SDiv:
1702 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1703 assert(C1->getType()->isIntOrIntVector() &&
1704 "Tried to create an arithmetic operation on a non-arithmetic type!");
1706 case Instruction::FDiv:
1707 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1708 assert(C1->getType()->isFPOrFPVector() &&
1709 "Tried to create an arithmetic operation on a non-arithmetic type!");
1711 case Instruction::URem:
1712 case Instruction::SRem:
1713 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1714 assert(C1->getType()->isIntOrIntVector() &&
1715 "Tried to create an arithmetic operation on a non-arithmetic type!");
1717 case Instruction::FRem:
1718 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1719 assert(C1->getType()->isFPOrFPVector() &&
1720 "Tried to create an arithmetic operation on a non-arithmetic type!");
1722 case Instruction::And:
1723 case Instruction::Or:
1724 case Instruction::Xor:
1725 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1726 assert(C1->getType()->isIntOrIntVector() &&
1727 "Tried to create a logical operation on a non-integral type!");
1729 case Instruction::Shl:
1730 case Instruction::LShr:
1731 case Instruction::AShr:
1732 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1733 assert(C1->getType()->isIntOrIntVector() &&
1734 "Tried to create a shift operation on a non-integer type!");
1741 return getTy(C1->getType(), Opcode, C1, C2);
1744 Constant *ConstantExpr::getCompare(unsigned short pred,
1745 Constant *C1, Constant *C2) {
1746 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1747 return getCompareTy(pred, C1, C2);
1750 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1751 Constant *V1, Constant *V2) {
1752 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
1754 if (ReqTy == V1->getType())
1755 if (Constant *SC = ConstantFoldSelectInstruction(
1756 getGlobalContext(), C, V1, V2))
1757 return SC; // Fold common cases
1759 std::vector<Constant*> argVec(3, C);
1762 ExprMapKeyType Key(Instruction::Select, argVec);
1764 // Implicitly locked.
1765 return ExprConstants->getOrCreate(ReqTy, Key);
1768 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1771 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs,
1773 cast<PointerType>(ReqTy)->getElementType() &&
1774 "GEP indices invalid!");
1776 if (Constant *FC = ConstantFoldGetElementPtr(
1777 getGlobalContext(), C, (Constant**)Idxs, NumIdx))
1778 return FC; // Fold a few common cases...
1780 assert(isa<PointerType>(C->getType()) &&
1781 "Non-pointer type for constant GetElementPtr expression");
1782 // Look up the constant in the table first to ensure uniqueness
1783 std::vector<Constant*> ArgVec;
1784 ArgVec.reserve(NumIdx+1);
1785 ArgVec.push_back(C);
1786 for (unsigned i = 0; i != NumIdx; ++i)
1787 ArgVec.push_back(cast<Constant>(Idxs[i]));
1788 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
1790 // Implicitly locked.
1791 return ExprConstants->getOrCreate(ReqTy, Key);
1794 Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
1796 // Get the result type of the getelementptr!
1798 GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx);
1799 assert(Ty && "GEP indices invalid!");
1800 unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
1801 return getGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx);
1804 Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
1806 return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
1811 ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1812 assert(LHS->getType() == RHS->getType());
1813 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
1814 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1816 if (Constant *FC = ConstantFoldCompareInstruction(
1817 getGlobalContext(),pred, LHS, RHS))
1818 return FC; // Fold a few common cases...
1820 // Look up the constant in the table first to ensure uniqueness
1821 std::vector<Constant*> ArgVec;
1822 ArgVec.push_back(LHS);
1823 ArgVec.push_back(RHS);
1824 // Get the key type with both the opcode and predicate
1825 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
1827 // Implicitly locked.
1828 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
1832 ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1833 assert(LHS->getType() == RHS->getType());
1834 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1836 if (Constant *FC = ConstantFoldCompareInstruction(
1837 getGlobalContext(), pred, LHS, RHS))
1838 return FC; // Fold a few common cases...
1840 // Look up the constant in the table first to ensure uniqueness
1841 std::vector<Constant*> ArgVec;
1842 ArgVec.push_back(LHS);
1843 ArgVec.push_back(RHS);
1844 // Get the key type with both the opcode and predicate
1845 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
1847 // Implicitly locked.
1848 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
1851 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
1853 if (Constant *FC = ConstantFoldExtractElementInstruction(
1854 getGlobalContext(), Val, Idx))
1855 return FC; // Fold a few common cases...
1856 // Look up the constant in the table first to ensure uniqueness
1857 std::vector<Constant*> ArgVec(1, Val);
1858 ArgVec.push_back(Idx);
1859 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
1861 // Implicitly locked.
1862 return ExprConstants->getOrCreate(ReqTy, Key);
1865 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
1866 assert(isa<VectorType>(Val->getType()) &&
1867 "Tried to create extractelement operation on non-vector type!");
1868 assert(Idx->getType() == Type::Int32Ty &&
1869 "Extractelement index must be i32 type!");
1870 return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
1874 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
1875 Constant *Elt, Constant *Idx) {
1876 if (Constant *FC = ConstantFoldInsertElementInstruction(
1877 getGlobalContext(), Val, Elt, Idx))
1878 return FC; // Fold a few common cases...
1879 // Look up the constant in the table first to ensure uniqueness
1880 std::vector<Constant*> ArgVec(1, Val);
1881 ArgVec.push_back(Elt);
1882 ArgVec.push_back(Idx);
1883 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
1885 // Implicitly locked.
1886 return ExprConstants->getOrCreate(ReqTy, Key);
1889 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1891 assert(isa<VectorType>(Val->getType()) &&
1892 "Tried to create insertelement operation on non-vector type!");
1893 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
1894 && "Insertelement types must match!");
1895 assert(Idx->getType() == Type::Int32Ty &&
1896 "Insertelement index must be i32 type!");
1897 return getInsertElementTy(Val->getType(), Val, Elt, Idx);
1900 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
1901 Constant *V2, Constant *Mask) {
1902 if (Constant *FC = ConstantFoldShuffleVectorInstruction(
1903 getGlobalContext(), V1, V2, Mask))
1904 return FC; // Fold a few common cases...
1905 // Look up the constant in the table first to ensure uniqueness
1906 std::vector<Constant*> ArgVec(1, V1);
1907 ArgVec.push_back(V2);
1908 ArgVec.push_back(Mask);
1909 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
1911 // Implicitly locked.
1912 return ExprConstants->getOrCreate(ReqTy, Key);
1915 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
1917 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1918 "Invalid shuffle vector constant expr operands!");
1920 unsigned NElts = cast<VectorType>(Mask->getType())->getNumElements();
1921 const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
1922 const Type *ShufTy = VectorType::get(EltTy, NElts);
1923 return getShuffleVectorTy(ShufTy, V1, V2, Mask);
1926 Constant *ConstantExpr::getInsertValueTy(const Type *ReqTy, Constant *Agg,
1928 const unsigned *Idxs, unsigned NumIdx) {
1929 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
1930 Idxs+NumIdx) == Val->getType() &&
1931 "insertvalue indices invalid!");
1932 assert(Agg->getType() == ReqTy &&
1933 "insertvalue type invalid!");
1934 assert(Agg->getType()->isFirstClassType() &&
1935 "Non-first-class type for constant InsertValue expression");
1936 Constant *FC = ConstantFoldInsertValueInstruction(
1937 getGlobalContext(), Agg, Val, Idxs, NumIdx);
1938 assert(FC && "InsertValue constant expr couldn't be folded!");
1942 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
1943 const unsigned *IdxList, unsigned NumIdx) {
1944 assert(Agg->getType()->isFirstClassType() &&
1945 "Tried to create insertelement operation on non-first-class type!");
1947 const Type *ReqTy = Agg->getType();
1950 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
1952 assert(ValTy == Val->getType() && "insertvalue indices invalid!");
1953 return getInsertValueTy(ReqTy, Agg, Val, IdxList, NumIdx);
1956 Constant *ConstantExpr::getExtractValueTy(const Type *ReqTy, Constant *Agg,
1957 const unsigned *Idxs, unsigned NumIdx) {
1958 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
1959 Idxs+NumIdx) == ReqTy &&
1960 "extractvalue indices invalid!");
1961 assert(Agg->getType()->isFirstClassType() &&
1962 "Non-first-class type for constant extractvalue expression");
1963 Constant *FC = ConstantFoldExtractValueInstruction(
1964 getGlobalContext(), Agg, Idxs, NumIdx);
1965 assert(FC && "ExtractValue constant expr couldn't be folded!");
1969 Constant *ConstantExpr::getExtractValue(Constant *Agg,
1970 const unsigned *IdxList, unsigned NumIdx) {
1971 assert(Agg->getType()->isFirstClassType() &&
1972 "Tried to create extractelement operation on non-first-class type!");
1975 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
1976 assert(ReqTy && "extractvalue indices invalid!");
1977 return getExtractValueTy(ReqTy, Agg, IdxList, NumIdx);
1980 // destroyConstant - Remove the constant from the constant table...
1982 void ConstantExpr::destroyConstant() {
1983 // Implicitly locked.
1984 ExprConstants->remove(this);
1985 destroyConstantImpl();
1988 const char *ConstantExpr::getOpcodeName() const {
1989 return Instruction::getOpcodeName(getOpcode());
1992 //===----------------------------------------------------------------------===//
1993 // replaceUsesOfWithOnConstant implementations
1995 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
1996 /// 'From' to be uses of 'To'. This must update the uniquing data structures
1999 /// Note that we intentionally replace all uses of From with To here. Consider
2000 /// a large array that uses 'From' 1000 times. By handling this case all here,
2001 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
2002 /// single invocation handles all 1000 uses. Handling them one at a time would
2003 /// work, but would be really slow because it would have to unique each updated
2005 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
2007 Constant *Replacement =
2008 getType()->getContext().replaceUsesOfWithOnConstant(this, From, To, U);
2010 if (!Replacement) return;
2012 // Otherwise, I do need to replace this with an existing value.
2013 assert(Replacement != this && "I didn't contain From!");
2015 // Everyone using this now uses the replacement.
2016 uncheckedReplaceAllUsesWith(Replacement);
2018 // Delete the old constant!
2022 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
2024 Constant* Replacement =
2025 getType()->getContext().replaceUsesOfWithOnConstant(this, From, To, U);
2026 if (!Replacement) return;
2028 // Everyone using this now uses the replacement.
2029 uncheckedReplaceAllUsesWith(Replacement);
2031 // Delete the old constant!
2035 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
2037 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2039 std::vector<Constant*> Values;
2040 Values.reserve(getNumOperands()); // Build replacement array...
2041 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2042 Constant *Val = getOperand(i);
2043 if (Val == From) Val = cast<Constant>(To);
2044 Values.push_back(Val);
2047 Constant *Replacement =
2048 getType()->getContext().getConstantVector(getType(), Values);
2049 assert(Replacement != this && "I didn't contain From!");
2051 // Everyone using this now uses the replacement.
2052 uncheckedReplaceAllUsesWith(Replacement);
2054 // Delete the old constant!
2058 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2060 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2061 Constant *To = cast<Constant>(ToV);
2063 Constant *Replacement = 0;
2064 if (getOpcode() == Instruction::GetElementPtr) {
2065 SmallVector<Constant*, 8> Indices;
2066 Constant *Pointer = getOperand(0);
2067 Indices.reserve(getNumOperands()-1);
2068 if (Pointer == From) Pointer = To;
2070 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2071 Constant *Val = getOperand(i);
2072 if (Val == From) Val = To;
2073 Indices.push_back(Val);
2075 Replacement = ConstantExpr::getGetElementPtr(Pointer,
2076 &Indices[0], Indices.size());
2077 } else if (getOpcode() == Instruction::ExtractValue) {
2078 Constant *Agg = getOperand(0);
2079 if (Agg == From) Agg = To;
2081 const SmallVector<unsigned, 4> &Indices = getIndices();
2082 Replacement = ConstantExpr::getExtractValue(Agg,
2083 &Indices[0], Indices.size());
2084 } else if (getOpcode() == Instruction::InsertValue) {
2085 Constant *Agg = getOperand(0);
2086 Constant *Val = getOperand(1);
2087 if (Agg == From) Agg = To;
2088 if (Val == From) Val = To;
2090 const SmallVector<unsigned, 4> &Indices = getIndices();
2091 Replacement = ConstantExpr::getInsertValue(Agg, Val,
2092 &Indices[0], Indices.size());
2093 } else if (isCast()) {
2094 assert(getOperand(0) == From && "Cast only has one use!");
2095 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
2096 } else if (getOpcode() == Instruction::Select) {
2097 Constant *C1 = getOperand(0);
2098 Constant *C2 = getOperand(1);
2099 Constant *C3 = getOperand(2);
2100 if (C1 == From) C1 = To;
2101 if (C2 == From) C2 = To;
2102 if (C3 == From) C3 = To;
2103 Replacement = ConstantExpr::getSelect(C1, C2, C3);
2104 } else if (getOpcode() == Instruction::ExtractElement) {
2105 Constant *C1 = getOperand(0);
2106 Constant *C2 = getOperand(1);
2107 if (C1 == From) C1 = To;
2108 if (C2 == From) C2 = To;
2109 Replacement = ConstantExpr::getExtractElement(C1, C2);
2110 } else if (getOpcode() == Instruction::InsertElement) {
2111 Constant *C1 = getOperand(0);
2112 Constant *C2 = getOperand(1);
2113 Constant *C3 = getOperand(1);
2114 if (C1 == From) C1 = To;
2115 if (C2 == From) C2 = To;
2116 if (C3 == From) C3 = To;
2117 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2118 } else if (getOpcode() == Instruction::ShuffleVector) {
2119 Constant *C1 = getOperand(0);
2120 Constant *C2 = getOperand(1);
2121 Constant *C3 = getOperand(2);
2122 if (C1 == From) C1 = To;
2123 if (C2 == From) C2 = To;
2124 if (C3 == From) C3 = To;
2125 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2126 } else if (isCompare()) {
2127 Constant *C1 = getOperand(0);
2128 Constant *C2 = getOperand(1);
2129 if (C1 == From) C1 = To;
2130 if (C2 == From) C2 = To;
2131 if (getOpcode() == Instruction::ICmp)
2132 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2134 assert(getOpcode() == Instruction::FCmp);
2135 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2137 } else if (getNumOperands() == 2) {
2138 Constant *C1 = getOperand(0);
2139 Constant *C2 = getOperand(1);
2140 if (C1 == From) C1 = To;
2141 if (C2 == From) C2 = To;
2142 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2144 llvm_unreachable("Unknown ConstantExpr type!");
2148 assert(Replacement != this && "I didn't contain From!");
2150 // Everyone using this now uses the replacement.
2151 uncheckedReplaceAllUsesWith(Replacement);
2153 // Delete the old constant!
2157 void MDNode::replaceElement(Value *From, Value *To) {
2158 SmallVector<Value*, 4> Values;
2159 Values.reserve(getNumElements()); // Build replacement array...
2160 for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
2161 Value *Val = getElement(i);
2162 if (Val == From) Val = To;
2163 Values.push_back(Val);
2166 MDNode *Replacement =
2167 getType()->getContext().getMDNode(&Values[0], Values.size());
2168 assert(Replacement != this && "I didn't contain From!");
2170 uncheckedReplaceAllUsesWith(Replacement);