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...
1100 struct ConvertConstantType<ConstantStruct, StructType> {
1101 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1102 // Make everyone now use a constant of the new type...
1103 std::vector<Constant*> C;
1104 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1105 C.push_back(cast<Constant>(OldC->getOperand(i)));
1106 Constant *New = ConstantStruct::get(NewTy, C);
1107 assert(New != OldC && "Didn't replace constant??");
1109 OldC->uncheckedReplaceAllUsesWith(New);
1110 OldC->destroyConstant(); // This constant is now dead, destroy it.
1115 typedef ValueMap<std::vector<Constant*>, StructType,
1116 ConstantStruct, true /*largekey*/> StructConstantsTy;
1117 static ManagedStatic<StructConstantsTy> StructConstants;
1119 static std::vector<Constant*> getValType(ConstantStruct *CS) {
1120 std::vector<Constant*> Elements;
1121 Elements.reserve(CS->getNumOperands());
1122 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1123 Elements.push_back(cast<Constant>(CS->getOperand(i)));
1127 Constant *ConstantStruct::get(const StructType *Ty,
1128 const std::vector<Constant*> &V) {
1129 // Create a ConstantAggregateZero value if all elements are zeros...
1130 for (unsigned i = 0, e = V.size(); i != e; ++i)
1131 if (!V[i]->isNullValue())
1132 // Implicitly locked.
1133 return StructConstants->getOrCreate(Ty, V);
1135 return Ty->getContext().getConstantAggregateZero(Ty);
1138 // destroyConstant - Remove the constant from the constant table...
1140 void ConstantStruct::destroyConstant() {
1141 // Implicitly locked.
1142 StructConstants->remove(this);
1143 destroyConstantImpl();
1146 //---- ConstantVector::get() implementation...
1150 struct ConvertConstantType<ConstantVector, VectorType> {
1151 static void convert(ConstantVector *OldC, const VectorType *NewTy) {
1152 // Make everyone now use a constant of the new type...
1153 std::vector<Constant*> C;
1154 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1155 C.push_back(cast<Constant>(OldC->getOperand(i)));
1156 Constant *New = ConstantVector::get(NewTy, C);
1157 assert(New != OldC && "Didn't replace constant??");
1158 OldC->uncheckedReplaceAllUsesWith(New);
1159 OldC->destroyConstant(); // This constant is now dead, destroy it.
1164 static std::vector<Constant*> getValType(ConstantVector *CP) {
1165 std::vector<Constant*> Elements;
1166 Elements.reserve(CP->getNumOperands());
1167 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1168 Elements.push_back(CP->getOperand(i));
1172 static ManagedStatic<ValueMap<std::vector<Constant*>, VectorType,
1173 ConstantVector> > VectorConstants;
1175 Constant *ConstantVector::get(const VectorType *Ty,
1176 const std::vector<Constant*> &V) {
1177 assert(!V.empty() && "Vectors can't be empty");
1178 // If this is an all-undef or alll-zero vector, return a
1179 // ConstantAggregateZero or UndefValue.
1181 bool isZero = C->isNullValue();
1182 bool isUndef = isa<UndefValue>(C);
1184 if (isZero || isUndef) {
1185 for (unsigned i = 1, e = V.size(); i != e; ++i)
1187 isZero = isUndef = false;
1193 return Ty->getContext().getConstantAggregateZero(Ty);
1195 return UndefValue::get(Ty);
1197 // Implicitly locked.
1198 return VectorConstants->getOrCreate(Ty, V);
1201 // destroyConstant - Remove the constant from the constant table...
1203 void ConstantVector::destroyConstant() {
1204 // Implicitly locked.
1205 VectorConstants->remove(this);
1206 destroyConstantImpl();
1209 /// This function will return true iff every element in this vector constant
1210 /// is set to all ones.
1211 /// @returns true iff this constant's emements are all set to all ones.
1212 /// @brief Determine if the value is all ones.
1213 bool ConstantVector::isAllOnesValue() const {
1214 // Check out first element.
1215 const Constant *Elt = getOperand(0);
1216 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1217 if (!CI || !CI->isAllOnesValue()) return false;
1218 // Then make sure all remaining elements point to the same value.
1219 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1220 if (getOperand(I) != Elt) return false;
1225 /// getSplatValue - If this is a splat constant, where all of the
1226 /// elements have the same value, return that value. Otherwise return null.
1227 Constant *ConstantVector::getSplatValue() {
1228 // Check out first element.
1229 Constant *Elt = getOperand(0);
1230 // Then make sure all remaining elements point to the same value.
1231 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1232 if (getOperand(I) != Elt) return 0;
1236 //---- ConstantPointerNull::get() implementation...
1240 // ConstantPointerNull does not take extra "value" argument...
1241 template<class ValType>
1242 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1243 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1244 return new ConstantPointerNull(Ty);
1249 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1250 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1251 // Make everyone now use a constant of the new type...
1252 Constant *New = ConstantPointerNull::get(NewTy);
1253 assert(New != OldC && "Didn't replace constant??");
1254 OldC->uncheckedReplaceAllUsesWith(New);
1255 OldC->destroyConstant(); // This constant is now dead, destroy it.
1260 static ManagedStatic<ValueMap<char, PointerType,
1261 ConstantPointerNull> > NullPtrConstants;
1263 static char getValType(ConstantPointerNull *) {
1268 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1269 // Implicitly locked.
1270 return NullPtrConstants->getOrCreate(Ty, 0);
1273 // destroyConstant - Remove the constant from the constant table...
1275 void ConstantPointerNull::destroyConstant() {
1276 // Implicitly locked.
1277 NullPtrConstants->remove(this);
1278 destroyConstantImpl();
1282 //---- UndefValue::get() implementation...
1286 // UndefValue does not take extra "value" argument...
1287 template<class ValType>
1288 struct ConstantCreator<UndefValue, Type, ValType> {
1289 static UndefValue *create(const Type *Ty, const ValType &V) {
1290 return new UndefValue(Ty);
1295 struct ConvertConstantType<UndefValue, Type> {
1296 static void convert(UndefValue *OldC, const Type *NewTy) {
1297 // Make everyone now use a constant of the new type.
1298 Constant *New = UndefValue::get(NewTy);
1299 assert(New != OldC && "Didn't replace constant??");
1300 OldC->uncheckedReplaceAllUsesWith(New);
1301 OldC->destroyConstant(); // This constant is now dead, destroy it.
1306 static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
1308 static char getValType(UndefValue *) {
1313 UndefValue *UndefValue::get(const Type *Ty) {
1314 // Implicitly locked.
1315 return UndefValueConstants->getOrCreate(Ty, 0);
1318 // destroyConstant - Remove the constant from the constant table.
1320 void UndefValue::destroyConstant() {
1321 // Implicitly locked.
1322 UndefValueConstants->remove(this);
1323 destroyConstantImpl();
1326 //---- MDString::get() implementation
1329 MDString::MDString(const char *begin, const char *end)
1330 : Constant(Type::MetadataTy, MDStringVal, 0, 0),
1331 StrBegin(begin), StrEnd(end) {}
1333 void MDString::destroyConstant() {
1334 getType()->getContext().erase(this);
1335 destroyConstantImpl();
1338 //---- MDNode::get() implementation
1341 MDNode::MDNode(Value*const* Vals, unsigned NumVals)
1342 : Constant(Type::MetadataTy, MDNodeVal, 0, 0) {
1343 for (unsigned i = 0; i != NumVals; ++i)
1344 Node.push_back(ElementVH(Vals[i], this));
1347 void MDNode::Profile(FoldingSetNodeID &ID) const {
1348 for (const_elem_iterator I = elem_begin(), E = elem_end(); I != E; ++I)
1352 void MDNode::destroyConstant() {
1353 getType()->getContext().erase(this);
1354 destroyConstantImpl();
1357 //---- ConstantExpr::get() implementations...
1362 struct ExprMapKeyType {
1363 typedef SmallVector<unsigned, 4> IndexList;
1365 ExprMapKeyType(unsigned opc,
1366 const std::vector<Constant*> &ops,
1367 unsigned short pred = 0,
1368 const IndexList &inds = IndexList())
1369 : opcode(opc), predicate(pred), operands(ops), indices(inds) {}
1372 std::vector<Constant*> operands;
1374 bool operator==(const ExprMapKeyType& that) const {
1375 return this->opcode == that.opcode &&
1376 this->predicate == that.predicate &&
1377 this->operands == that.operands &&
1378 this->indices == that.indices;
1380 bool operator<(const ExprMapKeyType & that) const {
1381 return this->opcode < that.opcode ||
1382 (this->opcode == that.opcode && this->predicate < that.predicate) ||
1383 (this->opcode == that.opcode && this->predicate == that.predicate &&
1384 this->operands < that.operands) ||
1385 (this->opcode == that.opcode && this->predicate == that.predicate &&
1386 this->operands == that.operands && this->indices < that.indices);
1389 bool operator!=(const ExprMapKeyType& that) const {
1390 return !(*this == that);
1398 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1399 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1400 unsigned short pred = 0) {
1401 if (Instruction::isCast(V.opcode))
1402 return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1403 if ((V.opcode >= Instruction::BinaryOpsBegin &&
1404 V.opcode < Instruction::BinaryOpsEnd))
1405 return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1406 if (V.opcode == Instruction::Select)
1407 return new SelectConstantExpr(V.operands[0], V.operands[1],
1409 if (V.opcode == Instruction::ExtractElement)
1410 return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1411 if (V.opcode == Instruction::InsertElement)
1412 return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1414 if (V.opcode == Instruction::ShuffleVector)
1415 return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1417 if (V.opcode == Instruction::InsertValue)
1418 return new InsertValueConstantExpr(V.operands[0], V.operands[1],
1420 if (V.opcode == Instruction::ExtractValue)
1421 return new ExtractValueConstantExpr(V.operands[0], V.indices, Ty);
1422 if (V.opcode == Instruction::GetElementPtr) {
1423 std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
1424 return GetElementPtrConstantExpr::Create(V.operands[0], IdxList, Ty);
1427 // The compare instructions are weird. We have to encode the predicate
1428 // value and it is combined with the instruction opcode by multiplying
1429 // the opcode by one hundred. We must decode this to get the predicate.
1430 if (V.opcode == Instruction::ICmp)
1431 return new CompareConstantExpr(Ty, Instruction::ICmp, V.predicate,
1432 V.operands[0], V.operands[1]);
1433 if (V.opcode == Instruction::FCmp)
1434 return new CompareConstantExpr(Ty, Instruction::FCmp, V.predicate,
1435 V.operands[0], V.operands[1]);
1436 llvm_unreachable("Invalid ConstantExpr!");
1442 struct ConvertConstantType<ConstantExpr, Type> {
1443 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1445 switch (OldC->getOpcode()) {
1446 case Instruction::Trunc:
1447 case Instruction::ZExt:
1448 case Instruction::SExt:
1449 case Instruction::FPTrunc:
1450 case Instruction::FPExt:
1451 case Instruction::UIToFP:
1452 case Instruction::SIToFP:
1453 case Instruction::FPToUI:
1454 case Instruction::FPToSI:
1455 case Instruction::PtrToInt:
1456 case Instruction::IntToPtr:
1457 case Instruction::BitCast:
1458 New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0),
1461 case Instruction::Select:
1462 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1463 OldC->getOperand(1),
1464 OldC->getOperand(2));
1467 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1468 OldC->getOpcode() < Instruction::BinaryOpsEnd);
1469 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1470 OldC->getOperand(1));
1472 case Instruction::GetElementPtr:
1473 // Make everyone now use a constant of the new type...
1474 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1475 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0),
1476 &Idx[0], Idx.size());
1480 assert(New != OldC && "Didn't replace constant??");
1481 OldC->uncheckedReplaceAllUsesWith(New);
1482 OldC->destroyConstant(); // This constant is now dead, destroy it.
1485 } // end namespace llvm
1488 static ExprMapKeyType getValType(ConstantExpr *CE) {
1489 std::vector<Constant*> Operands;
1490 Operands.reserve(CE->getNumOperands());
1491 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1492 Operands.push_back(cast<Constant>(CE->getOperand(i)));
1493 return ExprMapKeyType(CE->getOpcode(), Operands,
1494 CE->isCompare() ? CE->getPredicate() : 0,
1496 CE->getIndices() : SmallVector<unsigned, 4>());
1499 static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1500 ConstantExpr> > ExprConstants;
1502 /// This is a utility function to handle folding of casts and lookup of the
1503 /// cast in the ExprConstants map. It is used by the various get* methods below.
1504 static inline Constant *getFoldedCast(
1505 Instruction::CastOps opc, Constant *C, const Type *Ty) {
1506 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1507 // Fold a few common cases
1509 ConstantFoldCastInstruction(getGlobalContext(), opc, C, Ty))
1512 // Look up the constant in the table first to ensure uniqueness
1513 std::vector<Constant*> argVec(1, C);
1514 ExprMapKeyType Key(opc, argVec);
1516 // Implicitly locked.
1517 return ExprConstants->getOrCreate(Ty, Key);
1520 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1521 Instruction::CastOps opc = Instruction::CastOps(oc);
1522 assert(Instruction::isCast(opc) && "opcode out of range");
1523 assert(C && Ty && "Null arguments to getCast");
1524 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1528 llvm_unreachable("Invalid cast opcode");
1530 case Instruction::Trunc: return getTrunc(C, Ty);
1531 case Instruction::ZExt: return getZExt(C, Ty);
1532 case Instruction::SExt: return getSExt(C, Ty);
1533 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1534 case Instruction::FPExt: return getFPExtend(C, Ty);
1535 case Instruction::UIToFP: return getUIToFP(C, Ty);
1536 case Instruction::SIToFP: return getSIToFP(C, Ty);
1537 case Instruction::FPToUI: return getFPToUI(C, Ty);
1538 case Instruction::FPToSI: return getFPToSI(C, Ty);
1539 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1540 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1541 case Instruction::BitCast: return getBitCast(C, Ty);
1546 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1547 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1548 return getCast(Instruction::BitCast, C, Ty);
1549 return getCast(Instruction::ZExt, C, Ty);
1552 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1553 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1554 return getCast(Instruction::BitCast, C, Ty);
1555 return getCast(Instruction::SExt, C, Ty);
1558 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1559 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1560 return getCast(Instruction::BitCast, C, Ty);
1561 return getCast(Instruction::Trunc, C, Ty);
1564 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1565 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1566 assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
1568 if (Ty->isInteger())
1569 return getCast(Instruction::PtrToInt, S, Ty);
1570 return getCast(Instruction::BitCast, S, Ty);
1573 Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
1575 assert(C->getType()->isIntOrIntVector() &&
1576 Ty->isIntOrIntVector() && "Invalid cast");
1577 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1578 unsigned DstBits = Ty->getScalarSizeInBits();
1579 Instruction::CastOps opcode =
1580 (SrcBits == DstBits ? Instruction::BitCast :
1581 (SrcBits > DstBits ? Instruction::Trunc :
1582 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1583 return getCast(opcode, C, Ty);
1586 Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1587 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1589 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1590 unsigned DstBits = Ty->getScalarSizeInBits();
1591 if (SrcBits == DstBits)
1592 return C; // Avoid a useless cast
1593 Instruction::CastOps opcode =
1594 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1595 return getCast(opcode, C, Ty);
1598 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
1600 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1601 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1603 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1604 assert(C->getType()->isIntOrIntVector() && "Trunc operand must be integer");
1605 assert(Ty->isIntOrIntVector() && "Trunc produces only integral");
1606 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1607 "SrcTy must be larger than DestTy for Trunc!");
1609 return getFoldedCast(Instruction::Trunc, C, Ty);
1612 Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
1614 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1615 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1617 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1618 assert(C->getType()->isIntOrIntVector() && "SExt operand must be integral");
1619 assert(Ty->isIntOrIntVector() && "SExt produces only integer");
1620 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1621 "SrcTy must be smaller than DestTy for SExt!");
1623 return getFoldedCast(Instruction::SExt, C, Ty);
1626 Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
1628 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1629 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1631 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1632 assert(C->getType()->isIntOrIntVector() && "ZEXt operand must be integral");
1633 assert(Ty->isIntOrIntVector() && "ZExt produces only integer");
1634 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1635 "SrcTy must be smaller than DestTy for ZExt!");
1637 return getFoldedCast(Instruction::ZExt, C, Ty);
1640 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1642 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1643 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1645 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1646 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1647 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1648 "This is an illegal floating point truncation!");
1649 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1652 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1654 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1655 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1657 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1658 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1659 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1660 "This is an illegal floating point extension!");
1661 return getFoldedCast(Instruction::FPExt, C, Ty);
1664 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
1666 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1667 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1669 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1670 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1671 "This is an illegal uint to floating point cast!");
1672 return getFoldedCast(Instruction::UIToFP, C, Ty);
1675 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
1677 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1678 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1680 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1681 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1682 "This is an illegal sint to floating point cast!");
1683 return getFoldedCast(Instruction::SIToFP, C, Ty);
1686 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
1688 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1689 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1691 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1692 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1693 "This is an illegal floating point to uint cast!");
1694 return getFoldedCast(Instruction::FPToUI, C, Ty);
1697 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
1699 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1700 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1702 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1703 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1704 "This is an illegal floating point to sint cast!");
1705 return getFoldedCast(Instruction::FPToSI, C, Ty);
1708 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1709 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
1710 assert(DstTy->isInteger() && "PtrToInt destination must be integral");
1711 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1714 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
1715 assert(C->getType()->isInteger() && "IntToPtr source must be integral");
1716 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
1717 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1720 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1721 // BitCast implies a no-op cast of type only. No bits change. However, you
1722 // can't cast pointers to anything but pointers.
1724 const Type *SrcTy = C->getType();
1725 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
1726 "BitCast cannot cast pointer to non-pointer and vice versa");
1728 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
1729 // or nonptr->ptr). For all the other types, the cast is okay if source and
1730 // destination bit widths are identical.
1731 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1732 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
1734 assert(SrcBitSize == DstBitSize && "BitCast requires types of same width");
1736 // It is common to ask for a bitcast of a value to its own type, handle this
1738 if (C->getType() == DstTy) return C;
1740 return getFoldedCast(Instruction::BitCast, C, DstTy);
1743 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1744 Constant *C1, Constant *C2) {
1745 // Check the operands for consistency first
1746 assert(Opcode >= Instruction::BinaryOpsBegin &&
1747 Opcode < Instruction::BinaryOpsEnd &&
1748 "Invalid opcode in binary constant expression");
1749 assert(C1->getType() == C2->getType() &&
1750 "Operand types in binary constant expression should match");
1752 if (ReqTy == C1->getType() || ReqTy == Type::Int1Ty)
1753 if (Constant *FC = ConstantFoldBinaryInstruction(
1754 getGlobalContext(), Opcode, C1, C2))
1755 return FC; // Fold a few common cases...
1757 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1758 ExprMapKeyType Key(Opcode, argVec);
1760 // Implicitly locked.
1761 return ExprConstants->getOrCreate(ReqTy, Key);
1764 Constant *ConstantExpr::getCompareTy(unsigned short predicate,
1765 Constant *C1, Constant *C2) {
1766 switch (predicate) {
1767 default: llvm_unreachable("Invalid CmpInst predicate");
1768 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
1769 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
1770 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
1771 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
1772 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
1773 case CmpInst::FCMP_TRUE:
1774 return getFCmp(predicate, C1, C2);
1776 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
1777 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
1778 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
1779 case CmpInst::ICMP_SLE:
1780 return getICmp(predicate, C1, C2);
1784 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
1785 // API compatibility: Adjust integer opcodes to floating-point opcodes.
1786 if (C1->getType()->isFPOrFPVector()) {
1787 if (Opcode == Instruction::Add) Opcode = Instruction::FAdd;
1788 else if (Opcode == Instruction::Sub) Opcode = Instruction::FSub;
1789 else if (Opcode == Instruction::Mul) Opcode = Instruction::FMul;
1793 case Instruction::Add:
1794 case Instruction::Sub:
1795 case Instruction::Mul:
1796 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1797 assert(C1->getType()->isIntOrIntVector() &&
1798 "Tried to create an integer operation on a non-integer type!");
1800 case Instruction::FAdd:
1801 case Instruction::FSub:
1802 case Instruction::FMul:
1803 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1804 assert(C1->getType()->isFPOrFPVector() &&
1805 "Tried to create a floating-point operation on a "
1806 "non-floating-point type!");
1808 case Instruction::UDiv:
1809 case Instruction::SDiv:
1810 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1811 assert(C1->getType()->isIntOrIntVector() &&
1812 "Tried to create an arithmetic operation on a non-arithmetic type!");
1814 case Instruction::FDiv:
1815 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1816 assert(C1->getType()->isFPOrFPVector() &&
1817 "Tried to create an arithmetic operation on a non-arithmetic type!");
1819 case Instruction::URem:
1820 case Instruction::SRem:
1821 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1822 assert(C1->getType()->isIntOrIntVector() &&
1823 "Tried to create an arithmetic operation on a non-arithmetic type!");
1825 case Instruction::FRem:
1826 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1827 assert(C1->getType()->isFPOrFPVector() &&
1828 "Tried to create an arithmetic operation on a non-arithmetic type!");
1830 case Instruction::And:
1831 case Instruction::Or:
1832 case Instruction::Xor:
1833 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1834 assert(C1->getType()->isIntOrIntVector() &&
1835 "Tried to create a logical operation on a non-integral type!");
1837 case Instruction::Shl:
1838 case Instruction::LShr:
1839 case Instruction::AShr:
1840 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1841 assert(C1->getType()->isIntOrIntVector() &&
1842 "Tried to create a shift operation on a non-integer type!");
1849 return getTy(C1->getType(), Opcode, C1, C2);
1852 Constant *ConstantExpr::getCompare(unsigned short pred,
1853 Constant *C1, Constant *C2) {
1854 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1855 return getCompareTy(pred, C1, C2);
1858 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1859 Constant *V1, Constant *V2) {
1860 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
1862 if (ReqTy == V1->getType())
1863 if (Constant *SC = ConstantFoldSelectInstruction(
1864 getGlobalContext(), C, V1, V2))
1865 return SC; // Fold common cases
1867 std::vector<Constant*> argVec(3, C);
1870 ExprMapKeyType Key(Instruction::Select, argVec);
1872 // Implicitly locked.
1873 return ExprConstants->getOrCreate(ReqTy, Key);
1876 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1879 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs,
1881 cast<PointerType>(ReqTy)->getElementType() &&
1882 "GEP indices invalid!");
1884 if (Constant *FC = ConstantFoldGetElementPtr(
1885 getGlobalContext(), C, (Constant**)Idxs, NumIdx))
1886 return FC; // Fold a few common cases...
1888 assert(isa<PointerType>(C->getType()) &&
1889 "Non-pointer type for constant GetElementPtr expression");
1890 // Look up the constant in the table first to ensure uniqueness
1891 std::vector<Constant*> ArgVec;
1892 ArgVec.reserve(NumIdx+1);
1893 ArgVec.push_back(C);
1894 for (unsigned i = 0; i != NumIdx; ++i)
1895 ArgVec.push_back(cast<Constant>(Idxs[i]));
1896 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
1898 // Implicitly locked.
1899 return ExprConstants->getOrCreate(ReqTy, Key);
1902 Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
1904 // Get the result type of the getelementptr!
1906 GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx);
1907 assert(Ty && "GEP indices invalid!");
1908 unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
1909 return getGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx);
1912 Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
1914 return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
1919 ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1920 assert(LHS->getType() == RHS->getType());
1921 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
1922 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1924 if (Constant *FC = ConstantFoldCompareInstruction(
1925 getGlobalContext(),pred, LHS, RHS))
1926 return FC; // Fold a few common cases...
1928 // Look up the constant in the table first to ensure uniqueness
1929 std::vector<Constant*> ArgVec;
1930 ArgVec.push_back(LHS);
1931 ArgVec.push_back(RHS);
1932 // Get the key type with both the opcode and predicate
1933 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
1935 // Implicitly locked.
1936 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
1940 ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1941 assert(LHS->getType() == RHS->getType());
1942 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1944 if (Constant *FC = ConstantFoldCompareInstruction(
1945 getGlobalContext(), pred, LHS, RHS))
1946 return FC; // Fold a few common cases...
1948 // Look up the constant in the table first to ensure uniqueness
1949 std::vector<Constant*> ArgVec;
1950 ArgVec.push_back(LHS);
1951 ArgVec.push_back(RHS);
1952 // Get the key type with both the opcode and predicate
1953 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
1955 // Implicitly locked.
1956 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
1959 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
1961 if (Constant *FC = ConstantFoldExtractElementInstruction(
1962 getGlobalContext(), Val, Idx))
1963 return FC; // Fold a few common cases...
1964 // Look up the constant in the table first to ensure uniqueness
1965 std::vector<Constant*> ArgVec(1, Val);
1966 ArgVec.push_back(Idx);
1967 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
1969 // Implicitly locked.
1970 return ExprConstants->getOrCreate(ReqTy, Key);
1973 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
1974 assert(isa<VectorType>(Val->getType()) &&
1975 "Tried to create extractelement operation on non-vector type!");
1976 assert(Idx->getType() == Type::Int32Ty &&
1977 "Extractelement index must be i32 type!");
1978 return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
1982 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
1983 Constant *Elt, Constant *Idx) {
1984 if (Constant *FC = ConstantFoldInsertElementInstruction(
1985 getGlobalContext(), Val, Elt, Idx))
1986 return FC; // Fold a few common cases...
1987 // Look up the constant in the table first to ensure uniqueness
1988 std::vector<Constant*> ArgVec(1, Val);
1989 ArgVec.push_back(Elt);
1990 ArgVec.push_back(Idx);
1991 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
1993 // Implicitly locked.
1994 return ExprConstants->getOrCreate(ReqTy, Key);
1997 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1999 assert(isa<VectorType>(Val->getType()) &&
2000 "Tried to create insertelement operation on non-vector type!");
2001 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
2002 && "Insertelement types must match!");
2003 assert(Idx->getType() == Type::Int32Ty &&
2004 "Insertelement index must be i32 type!");
2005 return getInsertElementTy(Val->getType(), Val, Elt, Idx);
2008 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
2009 Constant *V2, Constant *Mask) {
2010 if (Constant *FC = ConstantFoldShuffleVectorInstruction(
2011 getGlobalContext(), V1, V2, Mask))
2012 return FC; // Fold a few common cases...
2013 // Look up the constant in the table first to ensure uniqueness
2014 std::vector<Constant*> ArgVec(1, V1);
2015 ArgVec.push_back(V2);
2016 ArgVec.push_back(Mask);
2017 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
2019 // Implicitly locked.
2020 return ExprConstants->getOrCreate(ReqTy, Key);
2023 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
2025 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
2026 "Invalid shuffle vector constant expr operands!");
2028 unsigned NElts = cast<VectorType>(Mask->getType())->getNumElements();
2029 const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
2030 const Type *ShufTy = VectorType::get(EltTy, NElts);
2031 return getShuffleVectorTy(ShufTy, V1, V2, Mask);
2034 Constant *ConstantExpr::getInsertValueTy(const Type *ReqTy, Constant *Agg,
2036 const unsigned *Idxs, unsigned NumIdx) {
2037 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
2038 Idxs+NumIdx) == Val->getType() &&
2039 "insertvalue indices invalid!");
2040 assert(Agg->getType() == ReqTy &&
2041 "insertvalue type invalid!");
2042 assert(Agg->getType()->isFirstClassType() &&
2043 "Non-first-class type for constant InsertValue expression");
2044 Constant *FC = ConstantFoldInsertValueInstruction(
2045 getGlobalContext(), Agg, Val, Idxs, NumIdx);
2046 assert(FC && "InsertValue constant expr couldn't be folded!");
2050 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
2051 const unsigned *IdxList, unsigned NumIdx) {
2052 assert(Agg->getType()->isFirstClassType() &&
2053 "Tried to create insertelement operation on non-first-class type!");
2055 const Type *ReqTy = Agg->getType();
2058 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
2060 assert(ValTy == Val->getType() && "insertvalue indices invalid!");
2061 return getInsertValueTy(ReqTy, Agg, Val, IdxList, NumIdx);
2064 Constant *ConstantExpr::getExtractValueTy(const Type *ReqTy, Constant *Agg,
2065 const unsigned *Idxs, unsigned NumIdx) {
2066 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
2067 Idxs+NumIdx) == ReqTy &&
2068 "extractvalue indices invalid!");
2069 assert(Agg->getType()->isFirstClassType() &&
2070 "Non-first-class type for constant extractvalue expression");
2071 Constant *FC = ConstantFoldExtractValueInstruction(
2072 getGlobalContext(), Agg, Idxs, NumIdx);
2073 assert(FC && "ExtractValue constant expr couldn't be folded!");
2077 Constant *ConstantExpr::getExtractValue(Constant *Agg,
2078 const unsigned *IdxList, unsigned NumIdx) {
2079 assert(Agg->getType()->isFirstClassType() &&
2080 "Tried to create extractelement operation on non-first-class type!");
2083 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
2084 assert(ReqTy && "extractvalue indices invalid!");
2085 return getExtractValueTy(ReqTy, Agg, IdxList, NumIdx);
2088 // destroyConstant - Remove the constant from the constant table...
2090 void ConstantExpr::destroyConstant() {
2091 // Implicitly locked.
2092 ExprConstants->remove(this);
2093 destroyConstantImpl();
2096 const char *ConstantExpr::getOpcodeName() const {
2097 return Instruction::getOpcodeName(getOpcode());
2100 //===----------------------------------------------------------------------===//
2101 // replaceUsesOfWithOnConstant implementations
2103 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
2104 /// 'From' to be uses of 'To'. This must update the uniquing data structures
2107 /// Note that we intentionally replace all uses of From with To here. Consider
2108 /// a large array that uses 'From' 1000 times. By handling this case all here,
2109 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
2110 /// single invocation handles all 1000 uses. Handling them one at a time would
2111 /// work, but would be really slow because it would have to unique each updated
2113 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
2115 Constant *Replacement =
2116 getType()->getContext().replaceUsesOfWithOnConstant(this, From, To, U);
2118 if (!Replacement) return;
2120 // Otherwise, I do need to replace this with an existing value.
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!
2130 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
2132 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2133 Constant *ToC = cast<Constant>(To);
2135 unsigned OperandToUpdate = U-OperandList;
2136 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2138 std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
2139 Lookup.first.first = getType();
2140 Lookup.second = this;
2141 std::vector<Constant*> &Values = Lookup.first.second;
2142 Values.reserve(getNumOperands()); // Build replacement struct.
2145 // Fill values with the modified operands of the constant struct. Also,
2146 // compute whether this turns into an all-zeros struct.
2147 bool isAllZeros = false;
2148 if (!ToC->isNullValue()) {
2149 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
2150 Values.push_back(cast<Constant>(O->get()));
2153 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2154 Constant *Val = cast<Constant>(O->get());
2155 Values.push_back(Val);
2156 if (isAllZeros) isAllZeros = Val->isNullValue();
2159 Values[OperandToUpdate] = ToC;
2161 Constant *Replacement = 0;
2163 Replacement = getType()->getContext().getConstantAggregateZero(getType());
2165 // Check to see if we have this array type already.
2166 sys::SmartScopedWriter<true> Writer(*ConstantsLock);
2168 StructConstantsTy::MapTy::iterator I =
2169 StructConstants->InsertOrGetItem(Lookup, Exists);
2172 Replacement = I->second;
2174 // Okay, the new shape doesn't exist in the system yet. Instead of
2175 // creating a new constant struct, inserting it, replaceallusesof'ing the
2176 // old with the new, then deleting the old... just update the current one
2178 StructConstants->MoveConstantToNewSlot(this, I);
2180 // Update to the new value.
2181 setOperand(OperandToUpdate, ToC);
2186 assert(Replacement != this && "I didn't contain From!");
2188 // Everyone using this now uses the replacement.
2189 uncheckedReplaceAllUsesWith(Replacement);
2191 // Delete the old constant!
2195 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
2197 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2199 std::vector<Constant*> Values;
2200 Values.reserve(getNumOperands()); // Build replacement array...
2201 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2202 Constant *Val = getOperand(i);
2203 if (Val == From) Val = cast<Constant>(To);
2204 Values.push_back(Val);
2207 Constant *Replacement = ConstantVector::get(getType(), Values);
2208 assert(Replacement != this && "I didn't contain From!");
2210 // Everyone using this now uses the replacement.
2211 uncheckedReplaceAllUsesWith(Replacement);
2213 // Delete the old constant!
2217 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2219 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2220 Constant *To = cast<Constant>(ToV);
2222 Constant *Replacement = 0;
2223 if (getOpcode() == Instruction::GetElementPtr) {
2224 SmallVector<Constant*, 8> Indices;
2225 Constant *Pointer = getOperand(0);
2226 Indices.reserve(getNumOperands()-1);
2227 if (Pointer == From) Pointer = To;
2229 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2230 Constant *Val = getOperand(i);
2231 if (Val == From) Val = To;
2232 Indices.push_back(Val);
2234 Replacement = ConstantExpr::getGetElementPtr(Pointer,
2235 &Indices[0], Indices.size());
2236 } else if (getOpcode() == Instruction::ExtractValue) {
2237 Constant *Agg = getOperand(0);
2238 if (Agg == From) Agg = To;
2240 const SmallVector<unsigned, 4> &Indices = getIndices();
2241 Replacement = ConstantExpr::getExtractValue(Agg,
2242 &Indices[0], Indices.size());
2243 } else if (getOpcode() == Instruction::InsertValue) {
2244 Constant *Agg = getOperand(0);
2245 Constant *Val = getOperand(1);
2246 if (Agg == From) Agg = To;
2247 if (Val == From) Val = To;
2249 const SmallVector<unsigned, 4> &Indices = getIndices();
2250 Replacement = ConstantExpr::getInsertValue(Agg, Val,
2251 &Indices[0], Indices.size());
2252 } else if (isCast()) {
2253 assert(getOperand(0) == From && "Cast only has one use!");
2254 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
2255 } else if (getOpcode() == Instruction::Select) {
2256 Constant *C1 = getOperand(0);
2257 Constant *C2 = getOperand(1);
2258 Constant *C3 = getOperand(2);
2259 if (C1 == From) C1 = To;
2260 if (C2 == From) C2 = To;
2261 if (C3 == From) C3 = To;
2262 Replacement = ConstantExpr::getSelect(C1, C2, C3);
2263 } else if (getOpcode() == Instruction::ExtractElement) {
2264 Constant *C1 = getOperand(0);
2265 Constant *C2 = getOperand(1);
2266 if (C1 == From) C1 = To;
2267 if (C2 == From) C2 = To;
2268 Replacement = ConstantExpr::getExtractElement(C1, C2);
2269 } else if (getOpcode() == Instruction::InsertElement) {
2270 Constant *C1 = getOperand(0);
2271 Constant *C2 = getOperand(1);
2272 Constant *C3 = getOperand(1);
2273 if (C1 == From) C1 = To;
2274 if (C2 == From) C2 = To;
2275 if (C3 == From) C3 = To;
2276 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2277 } else if (getOpcode() == Instruction::ShuffleVector) {
2278 Constant *C1 = getOperand(0);
2279 Constant *C2 = getOperand(1);
2280 Constant *C3 = getOperand(2);
2281 if (C1 == From) C1 = To;
2282 if (C2 == From) C2 = To;
2283 if (C3 == From) C3 = To;
2284 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2285 } else if (isCompare()) {
2286 Constant *C1 = getOperand(0);
2287 Constant *C2 = getOperand(1);
2288 if (C1 == From) C1 = To;
2289 if (C2 == From) C2 = To;
2290 if (getOpcode() == Instruction::ICmp)
2291 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2293 assert(getOpcode() == Instruction::FCmp);
2294 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2296 } else if (getNumOperands() == 2) {
2297 Constant *C1 = getOperand(0);
2298 Constant *C2 = getOperand(1);
2299 if (C1 == From) C1 = To;
2300 if (C2 == From) C2 = To;
2301 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2303 llvm_unreachable("Unknown ConstantExpr type!");
2307 assert(Replacement != this && "I didn't contain From!");
2309 // Everyone using this now uses the replacement.
2310 uncheckedReplaceAllUsesWith(Replacement);
2312 // Delete the old constant!
2316 void MDNode::replaceElement(Value *From, Value *To) {
2317 SmallVector<Value*, 4> Values;
2318 Values.reserve(getNumElements()); // Build replacement array...
2319 for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
2320 Value *Val = getElement(i);
2321 if (Val == From) Val = To;
2322 Values.push_back(Val);
2325 MDNode *Replacement =
2326 getType()->getContext().getMDNode(&Values[0], Values.size());
2327 assert(Replacement != this && "I didn't contain From!");
2329 uncheckedReplaceAllUsesWith(Replacement);