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())
104 /// ContainsRelocations - Return true if the constant value contains relocations
105 /// which cannot be resolved at compile time. Kind argument is used to filter
106 /// only 'interesting' sorts of relocations.
107 bool Constant::ContainsRelocations(unsigned Kind) const {
108 if (const GlobalValue* GV = dyn_cast<GlobalValue>(this)) {
109 bool isLocal = GV->hasLocalLinkage();
110 if ((Kind & Reloc::Local) && isLocal) {
111 // Global has local linkage and 'local' kind of relocations are
116 if ((Kind & Reloc::Global) && !isLocal) {
117 // Global has non-local linkage and 'global' kind of relocations are
125 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
126 if (getOperand(i)->ContainsRelocations(Kind))
132 /// getVectorElements - This method, which is only valid on constant of vector
133 /// type, returns the elements of the vector in the specified smallvector.
134 /// This handles breaking down a vector undef into undef elements, etc. For
135 /// constant exprs and other cases we can't handle, we return an empty vector.
136 void Constant::getVectorElements(LLVMContext &Context,
137 SmallVectorImpl<Constant*> &Elts) const {
138 assert(isa<VectorType>(getType()) && "Not a vector constant!");
140 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this)) {
141 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i)
142 Elts.push_back(CV->getOperand(i));
146 const VectorType *VT = cast<VectorType>(getType());
147 if (isa<ConstantAggregateZero>(this)) {
148 Elts.assign(VT->getNumElements(),
149 Context.getNullValue(VT->getElementType()));
153 if (isa<UndefValue>(this)) {
154 Elts.assign(VT->getNumElements(), Context.getUndef(VT->getElementType()));
158 // Unknown type, must be constant expr etc.
163 //===----------------------------------------------------------------------===//
165 //===----------------------------------------------------------------------===//
167 ConstantInt::ConstantInt(const IntegerType *Ty, const APInt& V)
168 : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
169 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
172 //===----------------------------------------------------------------------===//
174 //===----------------------------------------------------------------------===//
177 static const fltSemantics *TypeToFloatSemantics(const Type *Ty) {
178 if (Ty == Type::FloatTy)
179 return &APFloat::IEEEsingle;
180 if (Ty == Type::DoubleTy)
181 return &APFloat::IEEEdouble;
182 if (Ty == Type::X86_FP80Ty)
183 return &APFloat::x87DoubleExtended;
184 else if (Ty == Type::FP128Ty)
185 return &APFloat::IEEEquad;
187 assert(Ty == Type::PPC_FP128Ty && "Unknown FP format");
188 return &APFloat::PPCDoubleDouble;
192 ConstantFP::ConstantFP(const Type *Ty, const APFloat& V)
193 : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
194 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
198 bool ConstantFP::isNullValue() const {
199 return Val.isZero() && !Val.isNegative();
202 bool ConstantFP::isExactlyValue(const APFloat& V) const {
203 return Val.bitwiseIsEqual(V);
206 //===----------------------------------------------------------------------===//
207 // ConstantXXX Classes
208 //===----------------------------------------------------------------------===//
211 ConstantArray::ConstantArray(const ArrayType *T,
212 const std::vector<Constant*> &V)
213 : Constant(T, ConstantArrayVal,
214 OperandTraits<ConstantArray>::op_end(this) - V.size(),
216 assert(V.size() == T->getNumElements() &&
217 "Invalid initializer vector for constant array");
218 Use *OL = OperandList;
219 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
222 assert((C->getType() == T->getElementType() ||
224 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
225 "Initializer for array element doesn't match array element type!");
231 ConstantStruct::ConstantStruct(const StructType *T,
232 const std::vector<Constant*> &V)
233 : Constant(T, ConstantStructVal,
234 OperandTraits<ConstantStruct>::op_end(this) - V.size(),
236 assert(V.size() == T->getNumElements() &&
237 "Invalid initializer vector for constant structure");
238 Use *OL = OperandList;
239 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
242 assert((C->getType() == T->getElementType(I-V.begin()) ||
243 ((T->getElementType(I-V.begin())->isAbstract() ||
244 C->getType()->isAbstract()) &&
245 T->getElementType(I-V.begin())->getTypeID() ==
246 C->getType()->getTypeID())) &&
247 "Initializer for struct element doesn't match struct element type!");
253 ConstantVector::ConstantVector(const VectorType *T,
254 const std::vector<Constant*> &V)
255 : Constant(T, ConstantVectorVal,
256 OperandTraits<ConstantVector>::op_end(this) - V.size(),
258 Use *OL = OperandList;
259 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
262 assert((C->getType() == T->getElementType() ||
264 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
265 "Initializer for vector element doesn't match vector element type!");
272 // We declare several classes private to this file, so use an anonymous
276 /// UnaryConstantExpr - This class is private to Constants.cpp, and is used
277 /// behind the scenes to implement unary constant exprs.
278 class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
279 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
281 // allocate space for exactly one operand
282 void *operator new(size_t s) {
283 return User::operator new(s, 1);
285 UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
286 : ConstantExpr(Ty, Opcode, &Op<0>(), 1) {
289 /// Transparently provide more efficient getOperand methods.
290 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
293 /// BinaryConstantExpr - This class is private to Constants.cpp, and is used
294 /// behind the scenes to implement binary constant exprs.
295 class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
296 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
298 // allocate space for exactly two operands
299 void *operator new(size_t s) {
300 return User::operator new(s, 2);
302 BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
303 : ConstantExpr(C1->getType(), Opcode, &Op<0>(), 2) {
307 /// Transparently provide more efficient getOperand methods.
308 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
311 /// SelectConstantExpr - This class is private to Constants.cpp, and is used
312 /// behind the scenes to implement select constant exprs.
313 class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
314 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
316 // allocate space for exactly three operands
317 void *operator new(size_t s) {
318 return User::operator new(s, 3);
320 SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
321 : ConstantExpr(C2->getType(), Instruction::Select, &Op<0>(), 3) {
326 /// Transparently provide more efficient getOperand methods.
327 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
330 /// ExtractElementConstantExpr - This class is private to
331 /// Constants.cpp, and is used behind the scenes to implement
332 /// extractelement constant exprs.
333 class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
334 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
336 // allocate space for exactly two operands
337 void *operator new(size_t s) {
338 return User::operator new(s, 2);
340 ExtractElementConstantExpr(Constant *C1, Constant *C2)
341 : ConstantExpr(cast<VectorType>(C1->getType())->getElementType(),
342 Instruction::ExtractElement, &Op<0>(), 2) {
346 /// Transparently provide more efficient getOperand methods.
347 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
350 /// InsertElementConstantExpr - This class is private to
351 /// Constants.cpp, and is used behind the scenes to implement
352 /// insertelement constant exprs.
353 class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
354 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
356 // allocate space for exactly three operands
357 void *operator new(size_t s) {
358 return User::operator new(s, 3);
360 InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
361 : ConstantExpr(C1->getType(), Instruction::InsertElement,
367 /// Transparently provide more efficient getOperand methods.
368 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
371 /// ShuffleVectorConstantExpr - This class is private to
372 /// Constants.cpp, and is used behind the scenes to implement
373 /// shufflevector constant exprs.
374 class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
375 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
377 // allocate space for exactly three operands
378 void *operator new(size_t s) {
379 return User::operator new(s, 3);
381 ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
382 : ConstantExpr(VectorType::get(
383 cast<VectorType>(C1->getType())->getElementType(),
384 cast<VectorType>(C3->getType())->getNumElements()),
385 Instruction::ShuffleVector,
391 /// Transparently provide more efficient getOperand methods.
392 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
395 /// ExtractValueConstantExpr - This class is private to
396 /// Constants.cpp, and is used behind the scenes to implement
397 /// extractvalue constant exprs.
398 class VISIBILITY_HIDDEN ExtractValueConstantExpr : public ConstantExpr {
399 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
401 // allocate space for exactly one operand
402 void *operator new(size_t s) {
403 return User::operator new(s, 1);
405 ExtractValueConstantExpr(Constant *Agg,
406 const SmallVector<unsigned, 4> &IdxList,
408 : ConstantExpr(DestTy, Instruction::ExtractValue, &Op<0>(), 1),
413 /// Indices - These identify which value to extract.
414 const SmallVector<unsigned, 4> Indices;
416 /// Transparently provide more efficient getOperand methods.
417 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
420 /// InsertValueConstantExpr - This class is private to
421 /// Constants.cpp, and is used behind the scenes to implement
422 /// insertvalue constant exprs.
423 class VISIBILITY_HIDDEN InsertValueConstantExpr : public ConstantExpr {
424 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
426 // allocate space for exactly one operand
427 void *operator new(size_t s) {
428 return User::operator new(s, 2);
430 InsertValueConstantExpr(Constant *Agg, Constant *Val,
431 const SmallVector<unsigned, 4> &IdxList,
433 : ConstantExpr(DestTy, Instruction::InsertValue, &Op<0>(), 2),
439 /// Indices - These identify the position for the insertion.
440 const SmallVector<unsigned, 4> Indices;
442 /// Transparently provide more efficient getOperand methods.
443 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
447 /// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
448 /// used behind the scenes to implement getelementpr constant exprs.
449 class VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
450 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
453 static GetElementPtrConstantExpr *Create(Constant *C,
454 const std::vector<Constant*>&IdxList,
455 const Type *DestTy) {
457 new(IdxList.size() + 1) GetElementPtrConstantExpr(C, IdxList, DestTy);
459 /// Transparently provide more efficient getOperand methods.
460 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
463 // CompareConstantExpr - This class is private to Constants.cpp, and is used
464 // behind the scenes to implement ICmp and FCmp constant expressions. This is
465 // needed in order to store the predicate value for these instructions.
466 struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
467 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
468 // allocate space for exactly two operands
469 void *operator new(size_t s) {
470 return User::operator new(s, 2);
472 unsigned short predicate;
473 CompareConstantExpr(const Type *ty, Instruction::OtherOps opc,
474 unsigned short pred, Constant* LHS, Constant* RHS)
475 : ConstantExpr(ty, opc, &Op<0>(), 2), predicate(pred) {
479 /// Transparently provide more efficient getOperand methods.
480 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
483 } // end anonymous namespace
486 struct OperandTraits<UnaryConstantExpr> : FixedNumOperandTraits<1> {
488 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(UnaryConstantExpr, Value)
491 struct OperandTraits<BinaryConstantExpr> : FixedNumOperandTraits<2> {
493 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BinaryConstantExpr, Value)
496 struct OperandTraits<SelectConstantExpr> : FixedNumOperandTraits<3> {
498 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectConstantExpr, Value)
501 struct OperandTraits<ExtractElementConstantExpr> : FixedNumOperandTraits<2> {
503 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementConstantExpr, Value)
506 struct OperandTraits<InsertElementConstantExpr> : FixedNumOperandTraits<3> {
508 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementConstantExpr, Value)
511 struct OperandTraits<ShuffleVectorConstantExpr> : FixedNumOperandTraits<3> {
513 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorConstantExpr, Value)
516 struct OperandTraits<ExtractValueConstantExpr> : FixedNumOperandTraits<1> {
518 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractValueConstantExpr, Value)
521 struct OperandTraits<InsertValueConstantExpr> : FixedNumOperandTraits<2> {
523 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueConstantExpr, Value)
526 struct OperandTraits<GetElementPtrConstantExpr> : VariadicOperandTraits<1> {
529 GetElementPtrConstantExpr::GetElementPtrConstantExpr
531 const std::vector<Constant*> &IdxList,
533 : ConstantExpr(DestTy, Instruction::GetElementPtr,
534 OperandTraits<GetElementPtrConstantExpr>::op_end(this)
535 - (IdxList.size()+1),
538 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
539 OperandList[i+1] = IdxList[i];
542 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrConstantExpr, Value)
546 struct OperandTraits<CompareConstantExpr> : FixedNumOperandTraits<2> {
548 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CompareConstantExpr, Value)
551 } // End llvm namespace
554 // Utility function for determining if a ConstantExpr is a CastOp or not. This
555 // can't be inline because we don't want to #include Instruction.h into
557 bool ConstantExpr::isCast() const {
558 return Instruction::isCast(getOpcode());
561 bool ConstantExpr::isCompare() const {
562 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
565 bool ConstantExpr::hasIndices() const {
566 return getOpcode() == Instruction::ExtractValue ||
567 getOpcode() == Instruction::InsertValue;
570 const SmallVector<unsigned, 4> &ConstantExpr::getIndices() const {
571 if (const ExtractValueConstantExpr *EVCE =
572 dyn_cast<ExtractValueConstantExpr>(this))
573 return EVCE->Indices;
575 return cast<InsertValueConstantExpr>(this)->Indices;
578 unsigned ConstantExpr::getPredicate() const {
579 assert(getOpcode() == Instruction::FCmp ||
580 getOpcode() == Instruction::ICmp);
581 return ((const CompareConstantExpr*)this)->predicate;
584 /// getWithOperandReplaced - Return a constant expression identical to this
585 /// one, but with the specified operand set to the specified value.
587 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
588 assert(OpNo < getNumOperands() && "Operand num is out of range!");
589 assert(Op->getType() == getOperand(OpNo)->getType() &&
590 "Replacing operand with value of different type!");
591 if (getOperand(OpNo) == Op)
592 return const_cast<ConstantExpr*>(this);
594 Constant *Op0, *Op1, *Op2;
595 switch (getOpcode()) {
596 case Instruction::Trunc:
597 case Instruction::ZExt:
598 case Instruction::SExt:
599 case Instruction::FPTrunc:
600 case Instruction::FPExt:
601 case Instruction::UIToFP:
602 case Instruction::SIToFP:
603 case Instruction::FPToUI:
604 case Instruction::FPToSI:
605 case Instruction::PtrToInt:
606 case Instruction::IntToPtr:
607 case Instruction::BitCast:
608 return ConstantExpr::getCast(getOpcode(), Op, getType());
609 case Instruction::Select:
610 Op0 = (OpNo == 0) ? Op : getOperand(0);
611 Op1 = (OpNo == 1) ? Op : getOperand(1);
612 Op2 = (OpNo == 2) ? Op : getOperand(2);
613 return ConstantExpr::getSelect(Op0, Op1, Op2);
614 case Instruction::InsertElement:
615 Op0 = (OpNo == 0) ? Op : getOperand(0);
616 Op1 = (OpNo == 1) ? Op : getOperand(1);
617 Op2 = (OpNo == 2) ? Op : getOperand(2);
618 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
619 case Instruction::ExtractElement:
620 Op0 = (OpNo == 0) ? Op : getOperand(0);
621 Op1 = (OpNo == 1) ? Op : getOperand(1);
622 return ConstantExpr::getExtractElement(Op0, Op1);
623 case Instruction::ShuffleVector:
624 Op0 = (OpNo == 0) ? Op : getOperand(0);
625 Op1 = (OpNo == 1) ? Op : getOperand(1);
626 Op2 = (OpNo == 2) ? Op : getOperand(2);
627 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
628 case Instruction::GetElementPtr: {
629 SmallVector<Constant*, 8> Ops;
630 Ops.resize(getNumOperands()-1);
631 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
632 Ops[i-1] = getOperand(i);
634 return ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
636 return ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
639 assert(getNumOperands() == 2 && "Must be binary operator?");
640 Op0 = (OpNo == 0) ? Op : getOperand(0);
641 Op1 = (OpNo == 1) ? Op : getOperand(1);
642 return ConstantExpr::get(getOpcode(), Op0, Op1);
646 /// getWithOperands - This returns the current constant expression with the
647 /// operands replaced with the specified values. The specified operands must
648 /// match count and type with the existing ones.
649 Constant *ConstantExpr::
650 getWithOperands(Constant* const *Ops, unsigned NumOps) const {
651 assert(NumOps == getNumOperands() && "Operand count mismatch!");
652 bool AnyChange = false;
653 for (unsigned i = 0; i != NumOps; ++i) {
654 assert(Ops[i]->getType() == getOperand(i)->getType() &&
655 "Operand type mismatch!");
656 AnyChange |= Ops[i] != getOperand(i);
658 if (!AnyChange) // No operands changed, return self.
659 return const_cast<ConstantExpr*>(this);
661 switch (getOpcode()) {
662 case Instruction::Trunc:
663 case Instruction::ZExt:
664 case Instruction::SExt:
665 case Instruction::FPTrunc:
666 case Instruction::FPExt:
667 case Instruction::UIToFP:
668 case Instruction::SIToFP:
669 case Instruction::FPToUI:
670 case Instruction::FPToSI:
671 case Instruction::PtrToInt:
672 case Instruction::IntToPtr:
673 case Instruction::BitCast:
674 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
675 case Instruction::Select:
676 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
677 case Instruction::InsertElement:
678 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
679 case Instruction::ExtractElement:
680 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
681 case Instruction::ShuffleVector:
682 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
683 case Instruction::GetElementPtr:
684 return ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], NumOps-1);
685 case Instruction::ICmp:
686 case Instruction::FCmp:
687 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
689 assert(getNumOperands() == 2 && "Must be binary operator?");
690 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
695 //===----------------------------------------------------------------------===//
696 // isValueValidForType implementations
698 bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
699 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
700 if (Ty == Type::Int1Ty)
701 return Val == 0 || Val == 1;
703 return true; // always true, has to fit in largest type
704 uint64_t Max = (1ll << NumBits) - 1;
708 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
709 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
710 if (Ty == Type::Int1Ty)
711 return Val == 0 || Val == 1 || Val == -1;
713 return true; // always true, has to fit in largest type
714 int64_t Min = -(1ll << (NumBits-1));
715 int64_t Max = (1ll << (NumBits-1)) - 1;
716 return (Val >= Min && Val <= Max);
719 bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
720 // convert modifies in place, so make a copy.
721 APFloat Val2 = APFloat(Val);
723 switch (Ty->getTypeID()) {
725 return false; // These can't be represented as floating point!
727 // FIXME rounding mode needs to be more flexible
728 case Type::FloatTyID: {
729 if (&Val2.getSemantics() == &APFloat::IEEEsingle)
731 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
734 case Type::DoubleTyID: {
735 if (&Val2.getSemantics() == &APFloat::IEEEsingle ||
736 &Val2.getSemantics() == &APFloat::IEEEdouble)
738 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
741 case Type::X86_FP80TyID:
742 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
743 &Val2.getSemantics() == &APFloat::IEEEdouble ||
744 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
745 case Type::FP128TyID:
746 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
747 &Val2.getSemantics() == &APFloat::IEEEdouble ||
748 &Val2.getSemantics() == &APFloat::IEEEquad;
749 case Type::PPC_FP128TyID:
750 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
751 &Val2.getSemantics() == &APFloat::IEEEdouble ||
752 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
756 //===----------------------------------------------------------------------===//
757 // Factory Function Implementation
760 // The number of operands for each ConstantCreator::create method is
761 // determined by the ConstantTraits template.
762 // ConstantCreator - A class that is used to create constants by
763 // ValueMap*. This class should be partially specialized if there is
764 // something strange that needs to be done to interface to the ctor for the
768 template<class ValType>
769 struct ConstantTraits;
771 template<typename T, typename Alloc>
772 struct VISIBILITY_HIDDEN ConstantTraits< std::vector<T, Alloc> > {
773 static unsigned uses(const std::vector<T, Alloc>& v) {
778 template<class ConstantClass, class TypeClass, class ValType>
779 struct VISIBILITY_HIDDEN ConstantCreator {
780 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
781 return new(ConstantTraits<ValType>::uses(V)) ConstantClass(Ty, V);
785 template<class ConstantClass, class TypeClass>
786 struct VISIBILITY_HIDDEN ConvertConstantType {
787 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
788 llvm_unreachable("This type cannot be converted!");
792 template<class ValType, class TypeClass, class ConstantClass,
793 bool HasLargeKey = false /*true for arrays and structs*/ >
794 class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
796 typedef std::pair<const Type*, ValType> MapKey;
797 typedef std::map<MapKey, Constant *> MapTy;
798 typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
799 typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
801 /// Map - This is the main map from the element descriptor to the Constants.
802 /// This is the primary way we avoid creating two of the same shape
806 /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
807 /// from the constants to their element in Map. This is important for
808 /// removal of constants from the array, which would otherwise have to scan
809 /// through the map with very large keys.
810 InverseMapTy InverseMap;
812 /// AbstractTypeMap - Map for abstract type constants.
814 AbstractTypeMapTy AbstractTypeMap;
816 /// ValueMapLock - Mutex for this map.
817 sys::SmartMutex<true> ValueMapLock;
820 // NOTE: This function is not locked. It is the caller's responsibility
821 // to enforce proper synchronization.
822 typename MapTy::iterator map_end() { return Map.end(); }
824 /// InsertOrGetItem - Return an iterator for the specified element.
825 /// If the element exists in the map, the returned iterator points to the
826 /// entry and Exists=true. If not, the iterator points to the newly
827 /// inserted entry and returns Exists=false. Newly inserted entries have
828 /// I->second == 0, and should be filled in.
829 /// NOTE: This function is not locked. It is the caller's responsibility
830 // to enforce proper synchronization.
831 typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
834 std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
840 typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
842 typename InverseMapTy::iterator IMI = InverseMap.find(CP);
843 assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
844 IMI->second->second == CP &&
845 "InverseMap corrupt!");
849 typename MapTy::iterator I =
850 Map.find(MapKey(static_cast<const TypeClass*>(CP->getRawType()),
852 if (I == Map.end() || I->second != CP) {
853 // FIXME: This should not use a linear scan. If this gets to be a
854 // performance problem, someone should look at this.
855 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
861 ConstantClass* Create(const TypeClass *Ty, const ValType &V,
862 typename MapTy::iterator I) {
863 ConstantClass* Result =
864 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
866 assert(Result->getType() == Ty && "Type specified is not correct!");
867 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
869 if (HasLargeKey) // Remember the reverse mapping if needed.
870 InverseMap.insert(std::make_pair(Result, I));
872 // If the type of the constant is abstract, make sure that an entry
873 // exists for it in the AbstractTypeMap.
874 if (Ty->isAbstract()) {
875 typename AbstractTypeMapTy::iterator TI =
876 AbstractTypeMap.find(Ty);
878 if (TI == AbstractTypeMap.end()) {
879 // Add ourselves to the ATU list of the type.
880 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
882 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
890 /// getOrCreate - Return the specified constant from the map, creating it if
892 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
893 sys::SmartScopedLock<true> Lock(ValueMapLock);
894 MapKey Lookup(Ty, V);
895 ConstantClass* Result = 0;
897 typename MapTy::iterator I = Map.find(Lookup);
900 Result = static_cast<ConstantClass *>(I->second);
903 // If no preexisting value, create one now...
904 Result = Create(Ty, V, I);
910 void remove(ConstantClass *CP) {
911 sys::SmartScopedLock<true> Lock(ValueMapLock);
912 typename MapTy::iterator I = FindExistingElement(CP);
913 assert(I != Map.end() && "Constant not found in constant table!");
914 assert(I->second == CP && "Didn't find correct element?");
916 if (HasLargeKey) // Remember the reverse mapping if needed.
917 InverseMap.erase(CP);
919 // Now that we found the entry, make sure this isn't the entry that
920 // the AbstractTypeMap points to.
921 const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
922 if (Ty->isAbstract()) {
923 assert(AbstractTypeMap.count(Ty) &&
924 "Abstract type not in AbstractTypeMap?");
925 typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
926 if (ATMEntryIt == I) {
927 // Yes, we are removing the representative entry for this type.
928 // See if there are any other entries of the same type.
929 typename MapTy::iterator TmpIt = ATMEntryIt;
931 // First check the entry before this one...
932 if (TmpIt != Map.begin()) {
934 if (TmpIt->first.first != Ty) // Not the same type, move back...
938 // If we didn't find the same type, try to move forward...
939 if (TmpIt == ATMEntryIt) {
941 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
942 --TmpIt; // No entry afterwards with the same type
945 // If there is another entry in the map of the same abstract type,
946 // update the AbstractTypeMap entry now.
947 if (TmpIt != ATMEntryIt) {
950 // Otherwise, we are removing the last instance of this type
951 // from the table. Remove from the ATM, and from user list.
952 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
953 AbstractTypeMap.erase(Ty);
962 /// MoveConstantToNewSlot - If we are about to change C to be the element
963 /// specified by I, update our internal data structures to reflect this
965 /// NOTE: This function is not locked. It is the responsibility of the
966 /// caller to enforce proper synchronization if using this method.
967 void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
968 // First, remove the old location of the specified constant in the map.
969 typename MapTy::iterator OldI = FindExistingElement(C);
970 assert(OldI != Map.end() && "Constant not found in constant table!");
971 assert(OldI->second == C && "Didn't find correct element?");
973 // If this constant is the representative element for its abstract type,
974 // update the AbstractTypeMap so that the representative element is I.
975 if (C->getType()->isAbstract()) {
976 typename AbstractTypeMapTy::iterator ATI =
977 AbstractTypeMap.find(C->getType());
978 assert(ATI != AbstractTypeMap.end() &&
979 "Abstract type not in AbstractTypeMap?");
980 if (ATI->second == OldI)
984 // Remove the old entry from the map.
987 // Update the inverse map so that we know that this constant is now
988 // located at descriptor I.
990 assert(I->second == C && "Bad inversemap entry!");
995 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
996 sys::SmartScopedLock<true> Lock(ValueMapLock);
997 typename AbstractTypeMapTy::iterator I =
998 AbstractTypeMap.find(cast<Type>(OldTy));
1000 assert(I != AbstractTypeMap.end() &&
1001 "Abstract type not in AbstractTypeMap?");
1003 // Convert a constant at a time until the last one is gone. The last one
1004 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
1005 // eliminated eventually.
1007 ConvertConstantType<ConstantClass,
1008 TypeClass>::convert(
1009 static_cast<ConstantClass *>(I->second->second),
1010 cast<TypeClass>(NewTy));
1012 I = AbstractTypeMap.find(cast<Type>(OldTy));
1013 } while (I != AbstractTypeMap.end());
1016 // If the type became concrete without being refined to any other existing
1017 // type, we just remove ourselves from the ATU list.
1018 void typeBecameConcrete(const DerivedType *AbsTy) {
1019 AbsTy->removeAbstractTypeUser(this);
1023 DOUT << "Constant.cpp: ValueMap\n";
1030 //---- ConstantAggregateZero::get() implementation...
1033 // ConstantAggregateZero does not take extra "value" argument...
1034 template<class ValType>
1035 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
1036 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
1037 return new ConstantAggregateZero(Ty);
1042 struct ConvertConstantType<ConstantAggregateZero, Type> {
1043 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
1044 // Make everyone now use a constant of the new type...
1045 Constant *New = ConstantAggregateZero::get(NewTy);
1046 assert(New != OldC && "Didn't replace constant??");
1047 OldC->uncheckedReplaceAllUsesWith(New);
1048 OldC->destroyConstant(); // This constant is now dead, destroy it.
1053 static ManagedStatic<ValueMap<char, Type,
1054 ConstantAggregateZero> > AggZeroConstants;
1056 static char getValType(ConstantAggregateZero *CPZ) { return 0; }
1058 ConstantAggregateZero *ConstantAggregateZero::get(const Type *Ty) {
1059 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) &&
1060 "Cannot create an aggregate zero of non-aggregate type!");
1062 // Implicitly locked.
1063 return AggZeroConstants->getOrCreate(Ty, 0);
1066 /// destroyConstant - Remove the constant from the constant table...
1068 void ConstantAggregateZero::destroyConstant() {
1069 // Implicitly locked.
1070 AggZeroConstants->remove(this);
1071 destroyConstantImpl();
1074 //---- ConstantArray::get() implementation...
1078 struct ConvertConstantType<ConstantArray, ArrayType> {
1079 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
1080 // Make everyone now use a constant of the new type...
1081 std::vector<Constant*> C;
1082 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1083 C.push_back(cast<Constant>(OldC->getOperand(i)));
1084 Constant *New = ConstantArray::get(NewTy, C);
1085 assert(New != OldC && "Didn't replace constant??");
1086 OldC->uncheckedReplaceAllUsesWith(New);
1087 OldC->destroyConstant(); // This constant is now dead, destroy it.
1092 static std::vector<Constant*> getValType(ConstantArray *CA) {
1093 std::vector<Constant*> Elements;
1094 Elements.reserve(CA->getNumOperands());
1095 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1096 Elements.push_back(cast<Constant>(CA->getOperand(i)));
1100 typedef ValueMap<std::vector<Constant*>, ArrayType,
1101 ConstantArray, true /*largekey*/> ArrayConstantsTy;
1102 static ManagedStatic<ArrayConstantsTy> ArrayConstants;
1104 Constant *ConstantArray::get(const ArrayType *Ty,
1105 const std::vector<Constant*> &V) {
1106 // If this is an all-zero array, return a ConstantAggregateZero object
1109 if (!C->isNullValue()) {
1110 // Implicitly locked.
1111 return ArrayConstants->getOrCreate(Ty, V);
1113 for (unsigned i = 1, e = V.size(); i != e; ++i)
1115 // Implicitly locked.
1116 return ArrayConstants->getOrCreate(Ty, V);
1120 return ConstantAggregateZero::get(Ty);
1123 /// destroyConstant - Remove the constant from the constant table...
1125 void ConstantArray::destroyConstant() {
1126 // Implicitly locked.
1127 ArrayConstants->remove(this);
1128 destroyConstantImpl();
1131 /// isString - This method returns true if the array is an array of i8, and
1132 /// if the elements of the array are all ConstantInt's.
1133 bool ConstantArray::isString() const {
1134 // Check the element type for i8...
1135 if (getType()->getElementType() != Type::Int8Ty)
1137 // Check the elements to make sure they are all integers, not constant
1139 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1140 if (!isa<ConstantInt>(getOperand(i)))
1145 /// isCString - This method returns true if the array is a string (see
1146 /// isString) and it ends in a null byte \\0 and does not contains any other
1147 /// null bytes except its terminator.
1148 bool ConstantArray::isCString() const {
1149 // Check the element type for i8...
1150 if (getType()->getElementType() != Type::Int8Ty)
1153 // Last element must be a null.
1154 if (!getOperand(getNumOperands()-1)->isNullValue())
1156 // Other elements must be non-null integers.
1157 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1158 if (!isa<ConstantInt>(getOperand(i)))
1160 if (getOperand(i)->isNullValue())
1167 /// getAsString - If the sub-element type of this array is i8
1168 /// then this method converts the array to an std::string and returns it.
1169 /// Otherwise, it asserts out.
1171 std::string ConstantArray::getAsString() const {
1172 assert(isString() && "Not a string!");
1174 Result.reserve(getNumOperands());
1175 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1176 Result.push_back((char)cast<ConstantInt>(getOperand(i))->getZExtValue());
1181 //---- ConstantStruct::get() implementation...
1186 struct ConvertConstantType<ConstantStruct, StructType> {
1187 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1188 // Make everyone now use a constant of the new type...
1189 std::vector<Constant*> C;
1190 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1191 C.push_back(cast<Constant>(OldC->getOperand(i)));
1192 Constant *New = ConstantStruct::get(NewTy, C);
1193 assert(New != OldC && "Didn't replace constant??");
1195 OldC->uncheckedReplaceAllUsesWith(New);
1196 OldC->destroyConstant(); // This constant is now dead, destroy it.
1201 typedef ValueMap<std::vector<Constant*>, StructType,
1202 ConstantStruct, true /*largekey*/> StructConstantsTy;
1203 static ManagedStatic<StructConstantsTy> StructConstants;
1205 static std::vector<Constant*> getValType(ConstantStruct *CS) {
1206 std::vector<Constant*> Elements;
1207 Elements.reserve(CS->getNumOperands());
1208 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1209 Elements.push_back(cast<Constant>(CS->getOperand(i)));
1213 Constant *ConstantStruct::get(const StructType *Ty,
1214 const std::vector<Constant*> &V) {
1215 // Create a ConstantAggregateZero value if all elements are zeros...
1216 for (unsigned i = 0, e = V.size(); i != e; ++i)
1217 if (!V[i]->isNullValue())
1218 // Implicitly locked.
1219 return StructConstants->getOrCreate(Ty, V);
1221 return ConstantAggregateZero::get(Ty);
1224 // destroyConstant - Remove the constant from the constant table...
1226 void ConstantStruct::destroyConstant() {
1227 // Implicitly locked.
1228 StructConstants->remove(this);
1229 destroyConstantImpl();
1232 //---- ConstantVector::get() implementation...
1236 struct ConvertConstantType<ConstantVector, VectorType> {
1237 static void convert(ConstantVector *OldC, const VectorType *NewTy) {
1238 // Make everyone now use a constant of the new type...
1239 std::vector<Constant*> C;
1240 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1241 C.push_back(cast<Constant>(OldC->getOperand(i)));
1242 Constant *New = ConstantVector::get(NewTy, C);
1243 assert(New != OldC && "Didn't replace constant??");
1244 OldC->uncheckedReplaceAllUsesWith(New);
1245 OldC->destroyConstant(); // This constant is now dead, destroy it.
1250 static std::vector<Constant*> getValType(ConstantVector *CP) {
1251 std::vector<Constant*> Elements;
1252 Elements.reserve(CP->getNumOperands());
1253 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1254 Elements.push_back(CP->getOperand(i));
1258 static ManagedStatic<ValueMap<std::vector<Constant*>, VectorType,
1259 ConstantVector> > VectorConstants;
1261 Constant *ConstantVector::get(const VectorType *Ty,
1262 const std::vector<Constant*> &V) {
1263 assert(!V.empty() && "Vectors can't be empty");
1264 // If this is an all-undef or alll-zero vector, return a
1265 // ConstantAggregateZero or UndefValue.
1267 bool isZero = C->isNullValue();
1268 bool isUndef = isa<UndefValue>(C);
1270 if (isZero || isUndef) {
1271 for (unsigned i = 1, e = V.size(); i != e; ++i)
1273 isZero = isUndef = false;
1279 return ConstantAggregateZero::get(Ty);
1281 return UndefValue::get(Ty);
1283 // Implicitly locked.
1284 return VectorConstants->getOrCreate(Ty, V);
1287 // destroyConstant - Remove the constant from the constant table...
1289 void ConstantVector::destroyConstant() {
1290 // Implicitly locked.
1291 VectorConstants->remove(this);
1292 destroyConstantImpl();
1295 /// This function will return true iff every element in this vector constant
1296 /// is set to all ones.
1297 /// @returns true iff this constant's emements are all set to all ones.
1298 /// @brief Determine if the value is all ones.
1299 bool ConstantVector::isAllOnesValue() const {
1300 // Check out first element.
1301 const Constant *Elt = getOperand(0);
1302 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1303 if (!CI || !CI->isAllOnesValue()) return false;
1304 // Then make sure all remaining elements point to the same value.
1305 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1306 if (getOperand(I) != Elt) return false;
1311 /// getSplatValue - If this is a splat constant, where all of the
1312 /// elements have the same value, return that value. Otherwise return null.
1313 Constant *ConstantVector::getSplatValue() {
1314 // Check out first element.
1315 Constant *Elt = getOperand(0);
1316 // Then make sure all remaining elements point to the same value.
1317 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1318 if (getOperand(I) != Elt) return 0;
1322 //---- ConstantPointerNull::get() implementation...
1326 // ConstantPointerNull does not take extra "value" argument...
1327 template<class ValType>
1328 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1329 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1330 return new ConstantPointerNull(Ty);
1335 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1336 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1337 // Make everyone now use a constant of the new type...
1338 Constant *New = ConstantPointerNull::get(NewTy);
1339 assert(New != OldC && "Didn't replace constant??");
1340 OldC->uncheckedReplaceAllUsesWith(New);
1341 OldC->destroyConstant(); // This constant is now dead, destroy it.
1346 static ManagedStatic<ValueMap<char, PointerType,
1347 ConstantPointerNull> > NullPtrConstants;
1349 static char getValType(ConstantPointerNull *) {
1354 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1355 // Implicitly locked.
1356 return NullPtrConstants->getOrCreate(Ty, 0);
1359 // destroyConstant - Remove the constant from the constant table...
1361 void ConstantPointerNull::destroyConstant() {
1362 // Implicitly locked.
1363 NullPtrConstants->remove(this);
1364 destroyConstantImpl();
1368 //---- UndefValue::get() implementation...
1372 // UndefValue does not take extra "value" argument...
1373 template<class ValType>
1374 struct ConstantCreator<UndefValue, Type, ValType> {
1375 static UndefValue *create(const Type *Ty, const ValType &V) {
1376 return new UndefValue(Ty);
1381 struct ConvertConstantType<UndefValue, Type> {
1382 static void convert(UndefValue *OldC, const Type *NewTy) {
1383 // Make everyone now use a constant of the new type.
1384 Constant *New = UndefValue::get(NewTy);
1385 assert(New != OldC && "Didn't replace constant??");
1386 OldC->uncheckedReplaceAllUsesWith(New);
1387 OldC->destroyConstant(); // This constant is now dead, destroy it.
1392 static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
1394 static char getValType(UndefValue *) {
1399 UndefValue *UndefValue::get(const Type *Ty) {
1400 // Implicitly locked.
1401 return UndefValueConstants->getOrCreate(Ty, 0);
1404 // destroyConstant - Remove the constant from the constant table.
1406 void UndefValue::destroyConstant() {
1407 // Implicitly locked.
1408 UndefValueConstants->remove(this);
1409 destroyConstantImpl();
1412 //---- MDString::get() implementation
1415 MDString::MDString(const char *begin, const char *end)
1416 : Constant(Type::MetadataTy, MDStringVal, 0, 0),
1417 StrBegin(begin), StrEnd(end) {}
1419 void MDString::destroyConstant() {
1420 getType()->getContext().erase(this);
1421 destroyConstantImpl();
1424 //---- MDNode::get() implementation
1427 MDNode::MDNode(Value*const* Vals, unsigned NumVals)
1428 : Constant(Type::MetadataTy, MDNodeVal, 0, 0) {
1429 for (unsigned i = 0; i != NumVals; ++i)
1430 Node.push_back(ElementVH(Vals[i], this));
1433 void MDNode::Profile(FoldingSetNodeID &ID) const {
1434 for (const_elem_iterator I = elem_begin(), E = elem_end(); I != E; ++I)
1438 void MDNode::destroyConstant() {
1439 getType()->getContext().erase(this);
1440 destroyConstantImpl();
1443 //---- ConstantExpr::get() implementations...
1448 struct ExprMapKeyType {
1449 typedef SmallVector<unsigned, 4> IndexList;
1451 ExprMapKeyType(unsigned opc,
1452 const std::vector<Constant*> &ops,
1453 unsigned short pred = 0,
1454 const IndexList &inds = IndexList())
1455 : opcode(opc), predicate(pred), operands(ops), indices(inds) {}
1458 std::vector<Constant*> operands;
1460 bool operator==(const ExprMapKeyType& that) const {
1461 return this->opcode == that.opcode &&
1462 this->predicate == that.predicate &&
1463 this->operands == that.operands &&
1464 this->indices == that.indices;
1466 bool operator<(const ExprMapKeyType & that) const {
1467 return this->opcode < that.opcode ||
1468 (this->opcode == that.opcode && this->predicate < that.predicate) ||
1469 (this->opcode == that.opcode && this->predicate == that.predicate &&
1470 this->operands < that.operands) ||
1471 (this->opcode == that.opcode && this->predicate == that.predicate &&
1472 this->operands == that.operands && this->indices < that.indices);
1475 bool operator!=(const ExprMapKeyType& that) const {
1476 return !(*this == that);
1484 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1485 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1486 unsigned short pred = 0) {
1487 if (Instruction::isCast(V.opcode))
1488 return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1489 if ((V.opcode >= Instruction::BinaryOpsBegin &&
1490 V.opcode < Instruction::BinaryOpsEnd))
1491 return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1492 if (V.opcode == Instruction::Select)
1493 return new SelectConstantExpr(V.operands[0], V.operands[1],
1495 if (V.opcode == Instruction::ExtractElement)
1496 return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1497 if (V.opcode == Instruction::InsertElement)
1498 return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1500 if (V.opcode == Instruction::ShuffleVector)
1501 return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1503 if (V.opcode == Instruction::InsertValue)
1504 return new InsertValueConstantExpr(V.operands[0], V.operands[1],
1506 if (V.opcode == Instruction::ExtractValue)
1507 return new ExtractValueConstantExpr(V.operands[0], V.indices, Ty);
1508 if (V.opcode == Instruction::GetElementPtr) {
1509 std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
1510 return GetElementPtrConstantExpr::Create(V.operands[0], IdxList, Ty);
1513 // The compare instructions are weird. We have to encode the predicate
1514 // value and it is combined with the instruction opcode by multiplying
1515 // the opcode by one hundred. We must decode this to get the predicate.
1516 if (V.opcode == Instruction::ICmp)
1517 return new CompareConstantExpr(Ty, Instruction::ICmp, V.predicate,
1518 V.operands[0], V.operands[1]);
1519 if (V.opcode == Instruction::FCmp)
1520 return new CompareConstantExpr(Ty, Instruction::FCmp, V.predicate,
1521 V.operands[0], V.operands[1]);
1522 llvm_unreachable("Invalid ConstantExpr!");
1528 struct ConvertConstantType<ConstantExpr, Type> {
1529 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1531 switch (OldC->getOpcode()) {
1532 case Instruction::Trunc:
1533 case Instruction::ZExt:
1534 case Instruction::SExt:
1535 case Instruction::FPTrunc:
1536 case Instruction::FPExt:
1537 case Instruction::UIToFP:
1538 case Instruction::SIToFP:
1539 case Instruction::FPToUI:
1540 case Instruction::FPToSI:
1541 case Instruction::PtrToInt:
1542 case Instruction::IntToPtr:
1543 case Instruction::BitCast:
1544 New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0),
1547 case Instruction::Select:
1548 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1549 OldC->getOperand(1),
1550 OldC->getOperand(2));
1553 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1554 OldC->getOpcode() < Instruction::BinaryOpsEnd);
1555 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1556 OldC->getOperand(1));
1558 case Instruction::GetElementPtr:
1559 // Make everyone now use a constant of the new type...
1560 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1561 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0),
1562 &Idx[0], Idx.size());
1566 assert(New != OldC && "Didn't replace constant??");
1567 OldC->uncheckedReplaceAllUsesWith(New);
1568 OldC->destroyConstant(); // This constant is now dead, destroy it.
1571 } // end namespace llvm
1574 static ExprMapKeyType getValType(ConstantExpr *CE) {
1575 std::vector<Constant*> Operands;
1576 Operands.reserve(CE->getNumOperands());
1577 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1578 Operands.push_back(cast<Constant>(CE->getOperand(i)));
1579 return ExprMapKeyType(CE->getOpcode(), Operands,
1580 CE->isCompare() ? CE->getPredicate() : 0,
1582 CE->getIndices() : SmallVector<unsigned, 4>());
1585 static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1586 ConstantExpr> > ExprConstants;
1588 /// This is a utility function to handle folding of casts and lookup of the
1589 /// cast in the ExprConstants map. It is used by the various get* methods below.
1590 static inline Constant *getFoldedCast(
1591 Instruction::CastOps opc, Constant *C, const Type *Ty) {
1592 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1593 // Fold a few common cases
1595 ConstantFoldCastInstruction(getGlobalContext(), opc, C, Ty))
1598 // Look up the constant in the table first to ensure uniqueness
1599 std::vector<Constant*> argVec(1, C);
1600 ExprMapKeyType Key(opc, argVec);
1602 // Implicitly locked.
1603 return ExprConstants->getOrCreate(Ty, Key);
1606 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1607 Instruction::CastOps opc = Instruction::CastOps(oc);
1608 assert(Instruction::isCast(opc) && "opcode out of range");
1609 assert(C && Ty && "Null arguments to getCast");
1610 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1614 llvm_unreachable("Invalid cast opcode");
1616 case Instruction::Trunc: return getTrunc(C, Ty);
1617 case Instruction::ZExt: return getZExt(C, Ty);
1618 case Instruction::SExt: return getSExt(C, Ty);
1619 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1620 case Instruction::FPExt: return getFPExtend(C, Ty);
1621 case Instruction::UIToFP: return getUIToFP(C, Ty);
1622 case Instruction::SIToFP: return getSIToFP(C, Ty);
1623 case Instruction::FPToUI: return getFPToUI(C, Ty);
1624 case Instruction::FPToSI: return getFPToSI(C, Ty);
1625 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1626 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1627 case Instruction::BitCast: return getBitCast(C, Ty);
1632 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1633 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1634 return getCast(Instruction::BitCast, C, Ty);
1635 return getCast(Instruction::ZExt, C, Ty);
1638 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1639 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1640 return getCast(Instruction::BitCast, C, Ty);
1641 return getCast(Instruction::SExt, C, Ty);
1644 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1645 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1646 return getCast(Instruction::BitCast, C, Ty);
1647 return getCast(Instruction::Trunc, C, Ty);
1650 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1651 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1652 assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
1654 if (Ty->isInteger())
1655 return getCast(Instruction::PtrToInt, S, Ty);
1656 return getCast(Instruction::BitCast, S, Ty);
1659 Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
1661 assert(C->getType()->isIntOrIntVector() &&
1662 Ty->isIntOrIntVector() && "Invalid cast");
1663 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1664 unsigned DstBits = Ty->getScalarSizeInBits();
1665 Instruction::CastOps opcode =
1666 (SrcBits == DstBits ? Instruction::BitCast :
1667 (SrcBits > DstBits ? Instruction::Trunc :
1668 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1669 return getCast(opcode, C, Ty);
1672 Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1673 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1675 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1676 unsigned DstBits = Ty->getScalarSizeInBits();
1677 if (SrcBits == DstBits)
1678 return C; // Avoid a useless cast
1679 Instruction::CastOps opcode =
1680 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1681 return getCast(opcode, C, Ty);
1684 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
1686 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1687 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1689 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1690 assert(C->getType()->isIntOrIntVector() && "Trunc operand must be integer");
1691 assert(Ty->isIntOrIntVector() && "Trunc produces only integral");
1692 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1693 "SrcTy must be larger than DestTy for Trunc!");
1695 return getFoldedCast(Instruction::Trunc, C, Ty);
1698 Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
1700 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1701 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1703 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1704 assert(C->getType()->isIntOrIntVector() && "SExt operand must be integral");
1705 assert(Ty->isIntOrIntVector() && "SExt produces only integer");
1706 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1707 "SrcTy must be smaller than DestTy for SExt!");
1709 return getFoldedCast(Instruction::SExt, C, Ty);
1712 Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
1714 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1715 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1717 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1718 assert(C->getType()->isIntOrIntVector() && "ZEXt operand must be integral");
1719 assert(Ty->isIntOrIntVector() && "ZExt produces only integer");
1720 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1721 "SrcTy must be smaller than DestTy for ZExt!");
1723 return getFoldedCast(Instruction::ZExt, C, Ty);
1726 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1728 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1729 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1731 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1732 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1733 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1734 "This is an illegal floating point truncation!");
1735 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1738 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1740 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1741 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1743 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1744 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1745 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1746 "This is an illegal floating point extension!");
1747 return getFoldedCast(Instruction::FPExt, C, Ty);
1750 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
1752 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1753 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1755 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1756 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1757 "This is an illegal uint to floating point cast!");
1758 return getFoldedCast(Instruction::UIToFP, C, Ty);
1761 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
1763 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1764 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1766 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1767 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1768 "This is an illegal sint to floating point cast!");
1769 return getFoldedCast(Instruction::SIToFP, C, Ty);
1772 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
1774 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1775 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1777 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1778 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1779 "This is an illegal floating point to uint cast!");
1780 return getFoldedCast(Instruction::FPToUI, C, Ty);
1783 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
1785 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1786 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1788 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1789 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1790 "This is an illegal floating point to sint cast!");
1791 return getFoldedCast(Instruction::FPToSI, C, Ty);
1794 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1795 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
1796 assert(DstTy->isInteger() && "PtrToInt destination must be integral");
1797 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1800 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
1801 assert(C->getType()->isInteger() && "IntToPtr source must be integral");
1802 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
1803 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1806 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1807 // BitCast implies a no-op cast of type only. No bits change. However, you
1808 // can't cast pointers to anything but pointers.
1810 const Type *SrcTy = C->getType();
1811 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
1812 "BitCast cannot cast pointer to non-pointer and vice versa");
1814 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
1815 // or nonptr->ptr). For all the other types, the cast is okay if source and
1816 // destination bit widths are identical.
1817 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1818 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
1820 assert(SrcBitSize == DstBitSize && "BitCast requires types of same width");
1822 // It is common to ask for a bitcast of a value to its own type, handle this
1824 if (C->getType() == DstTy) return C;
1826 return getFoldedCast(Instruction::BitCast, C, DstTy);
1829 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1830 Constant *C1, Constant *C2) {
1831 // Check the operands for consistency first
1832 assert(Opcode >= Instruction::BinaryOpsBegin &&
1833 Opcode < Instruction::BinaryOpsEnd &&
1834 "Invalid opcode in binary constant expression");
1835 assert(C1->getType() == C2->getType() &&
1836 "Operand types in binary constant expression should match");
1838 if (ReqTy == C1->getType() || ReqTy == Type::Int1Ty)
1839 if (Constant *FC = ConstantFoldBinaryInstruction(
1840 getGlobalContext(), Opcode, C1, C2))
1841 return FC; // Fold a few common cases...
1843 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1844 ExprMapKeyType Key(Opcode, argVec);
1846 // Implicitly locked.
1847 return ExprConstants->getOrCreate(ReqTy, Key);
1850 Constant *ConstantExpr::getCompareTy(unsigned short predicate,
1851 Constant *C1, Constant *C2) {
1852 switch (predicate) {
1853 default: llvm_unreachable("Invalid CmpInst predicate");
1854 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
1855 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
1856 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
1857 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
1858 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
1859 case CmpInst::FCMP_TRUE:
1860 return getFCmp(predicate, C1, C2);
1862 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
1863 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
1864 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
1865 case CmpInst::ICMP_SLE:
1866 return getICmp(predicate, C1, C2);
1870 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
1871 // API compatibility: Adjust integer opcodes to floating-point opcodes.
1872 if (C1->getType()->isFPOrFPVector()) {
1873 if (Opcode == Instruction::Add) Opcode = Instruction::FAdd;
1874 else if (Opcode == Instruction::Sub) Opcode = Instruction::FSub;
1875 else if (Opcode == Instruction::Mul) Opcode = Instruction::FMul;
1879 case Instruction::Add:
1880 case Instruction::Sub:
1881 case Instruction::Mul:
1882 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1883 assert(C1->getType()->isIntOrIntVector() &&
1884 "Tried to create an integer operation on a non-integer type!");
1886 case Instruction::FAdd:
1887 case Instruction::FSub:
1888 case Instruction::FMul:
1889 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1890 assert(C1->getType()->isFPOrFPVector() &&
1891 "Tried to create a floating-point operation on a "
1892 "non-floating-point type!");
1894 case Instruction::UDiv:
1895 case Instruction::SDiv:
1896 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1897 assert(C1->getType()->isIntOrIntVector() &&
1898 "Tried to create an arithmetic operation on a non-arithmetic type!");
1900 case Instruction::FDiv:
1901 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1902 assert(C1->getType()->isFPOrFPVector() &&
1903 "Tried to create an arithmetic operation on a non-arithmetic type!");
1905 case Instruction::URem:
1906 case Instruction::SRem:
1907 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1908 assert(C1->getType()->isIntOrIntVector() &&
1909 "Tried to create an arithmetic operation on a non-arithmetic type!");
1911 case Instruction::FRem:
1912 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1913 assert(C1->getType()->isFPOrFPVector() &&
1914 "Tried to create an arithmetic operation on a non-arithmetic type!");
1916 case Instruction::And:
1917 case Instruction::Or:
1918 case Instruction::Xor:
1919 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1920 assert(C1->getType()->isIntOrIntVector() &&
1921 "Tried to create a logical operation on a non-integral type!");
1923 case Instruction::Shl:
1924 case Instruction::LShr:
1925 case Instruction::AShr:
1926 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1927 assert(C1->getType()->isIntOrIntVector() &&
1928 "Tried to create a shift operation on a non-integer type!");
1935 return getTy(C1->getType(), Opcode, C1, C2);
1938 Constant *ConstantExpr::getCompare(unsigned short pred,
1939 Constant *C1, Constant *C2) {
1940 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1941 return getCompareTy(pred, C1, C2);
1944 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1945 Constant *V1, Constant *V2) {
1946 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
1948 if (ReqTy == V1->getType())
1949 if (Constant *SC = ConstantFoldSelectInstruction(
1950 getGlobalContext(), C, V1, V2))
1951 return SC; // Fold common cases
1953 std::vector<Constant*> argVec(3, C);
1956 ExprMapKeyType Key(Instruction::Select, argVec);
1958 // Implicitly locked.
1959 return ExprConstants->getOrCreate(ReqTy, Key);
1962 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1965 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs,
1967 cast<PointerType>(ReqTy)->getElementType() &&
1968 "GEP indices invalid!");
1970 if (Constant *FC = ConstantFoldGetElementPtr(
1971 getGlobalContext(), C, (Constant**)Idxs, NumIdx))
1972 return FC; // Fold a few common cases...
1974 assert(isa<PointerType>(C->getType()) &&
1975 "Non-pointer type for constant GetElementPtr expression");
1976 // Look up the constant in the table first to ensure uniqueness
1977 std::vector<Constant*> ArgVec;
1978 ArgVec.reserve(NumIdx+1);
1979 ArgVec.push_back(C);
1980 for (unsigned i = 0; i != NumIdx; ++i)
1981 ArgVec.push_back(cast<Constant>(Idxs[i]));
1982 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
1984 // Implicitly locked.
1985 return ExprConstants->getOrCreate(ReqTy, Key);
1988 Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
1990 // Get the result type of the getelementptr!
1992 GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx);
1993 assert(Ty && "GEP indices invalid!");
1994 unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
1995 return getGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx);
1998 Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
2000 return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
2005 ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2006 assert(LHS->getType() == RHS->getType());
2007 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
2008 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
2010 if (Constant *FC = ConstantFoldCompareInstruction(
2011 getGlobalContext(),pred, LHS, RHS))
2012 return FC; // Fold a few common cases...
2014 // Look up the constant in the table first to ensure uniqueness
2015 std::vector<Constant*> ArgVec;
2016 ArgVec.push_back(LHS);
2017 ArgVec.push_back(RHS);
2018 // Get the key type with both the opcode and predicate
2019 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
2021 // Implicitly locked.
2022 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
2026 ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2027 assert(LHS->getType() == RHS->getType());
2028 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
2030 if (Constant *FC = ConstantFoldCompareInstruction(
2031 getGlobalContext(), pred, LHS, RHS))
2032 return FC; // Fold a few common cases...
2034 // Look up the constant in the table first to ensure uniqueness
2035 std::vector<Constant*> ArgVec;
2036 ArgVec.push_back(LHS);
2037 ArgVec.push_back(RHS);
2038 // Get the key type with both the opcode and predicate
2039 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
2041 // Implicitly locked.
2042 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
2045 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
2047 if (Constant *FC = ConstantFoldExtractElementInstruction(
2048 getGlobalContext(), Val, Idx))
2049 return FC; // Fold a few common cases...
2050 // Look up the constant in the table first to ensure uniqueness
2051 std::vector<Constant*> ArgVec(1, Val);
2052 ArgVec.push_back(Idx);
2053 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
2055 // Implicitly locked.
2056 return ExprConstants->getOrCreate(ReqTy, Key);
2059 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
2060 assert(isa<VectorType>(Val->getType()) &&
2061 "Tried to create extractelement operation on non-vector type!");
2062 assert(Idx->getType() == Type::Int32Ty &&
2063 "Extractelement index must be i32 type!");
2064 return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
2068 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
2069 Constant *Elt, Constant *Idx) {
2070 if (Constant *FC = ConstantFoldInsertElementInstruction(
2071 getGlobalContext(), Val, Elt, Idx))
2072 return FC; // Fold a few common cases...
2073 // Look up the constant in the table first to ensure uniqueness
2074 std::vector<Constant*> ArgVec(1, Val);
2075 ArgVec.push_back(Elt);
2076 ArgVec.push_back(Idx);
2077 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
2079 // Implicitly locked.
2080 return ExprConstants->getOrCreate(ReqTy, Key);
2083 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
2085 assert(isa<VectorType>(Val->getType()) &&
2086 "Tried to create insertelement operation on non-vector type!");
2087 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
2088 && "Insertelement types must match!");
2089 assert(Idx->getType() == Type::Int32Ty &&
2090 "Insertelement index must be i32 type!");
2091 return getInsertElementTy(Val->getType(), Val, Elt, Idx);
2094 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
2095 Constant *V2, Constant *Mask) {
2096 if (Constant *FC = ConstantFoldShuffleVectorInstruction(
2097 getGlobalContext(), V1, V2, Mask))
2098 return FC; // Fold a few common cases...
2099 // Look up the constant in the table first to ensure uniqueness
2100 std::vector<Constant*> ArgVec(1, V1);
2101 ArgVec.push_back(V2);
2102 ArgVec.push_back(Mask);
2103 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
2105 // Implicitly locked.
2106 return ExprConstants->getOrCreate(ReqTy, Key);
2109 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
2111 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
2112 "Invalid shuffle vector constant expr operands!");
2114 unsigned NElts = cast<VectorType>(Mask->getType())->getNumElements();
2115 const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
2116 const Type *ShufTy = VectorType::get(EltTy, NElts);
2117 return getShuffleVectorTy(ShufTy, V1, V2, Mask);
2120 Constant *ConstantExpr::getInsertValueTy(const Type *ReqTy, Constant *Agg,
2122 const unsigned *Idxs, unsigned NumIdx) {
2123 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
2124 Idxs+NumIdx) == Val->getType() &&
2125 "insertvalue indices invalid!");
2126 assert(Agg->getType() == ReqTy &&
2127 "insertvalue type invalid!");
2128 assert(Agg->getType()->isFirstClassType() &&
2129 "Non-first-class type for constant InsertValue expression");
2130 Constant *FC = ConstantFoldInsertValueInstruction(
2131 getGlobalContext(), Agg, Val, Idxs, NumIdx);
2132 assert(FC && "InsertValue constant expr couldn't be folded!");
2136 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
2137 const unsigned *IdxList, unsigned NumIdx) {
2138 assert(Agg->getType()->isFirstClassType() &&
2139 "Tried to create insertelement operation on non-first-class type!");
2141 const Type *ReqTy = Agg->getType();
2144 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
2146 assert(ValTy == Val->getType() && "insertvalue indices invalid!");
2147 return getInsertValueTy(ReqTy, Agg, Val, IdxList, NumIdx);
2150 Constant *ConstantExpr::getExtractValueTy(const Type *ReqTy, Constant *Agg,
2151 const unsigned *Idxs, unsigned NumIdx) {
2152 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
2153 Idxs+NumIdx) == ReqTy &&
2154 "extractvalue indices invalid!");
2155 assert(Agg->getType()->isFirstClassType() &&
2156 "Non-first-class type for constant extractvalue expression");
2157 Constant *FC = ConstantFoldExtractValueInstruction(
2158 getGlobalContext(), Agg, Idxs, NumIdx);
2159 assert(FC && "ExtractValue constant expr couldn't be folded!");
2163 Constant *ConstantExpr::getExtractValue(Constant *Agg,
2164 const unsigned *IdxList, unsigned NumIdx) {
2165 assert(Agg->getType()->isFirstClassType() &&
2166 "Tried to create extractelement operation on non-first-class type!");
2169 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
2170 assert(ReqTy && "extractvalue indices invalid!");
2171 return getExtractValueTy(ReqTy, Agg, IdxList, NumIdx);
2174 // destroyConstant - Remove the constant from the constant table...
2176 void ConstantExpr::destroyConstant() {
2177 // Implicitly locked.
2178 ExprConstants->remove(this);
2179 destroyConstantImpl();
2182 const char *ConstantExpr::getOpcodeName() const {
2183 return Instruction::getOpcodeName(getOpcode());
2186 //===----------------------------------------------------------------------===//
2187 // replaceUsesOfWithOnConstant implementations
2189 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
2190 /// 'From' to be uses of 'To'. This must update the uniquing data structures
2193 /// Note that we intentionally replace all uses of From with To here. Consider
2194 /// a large array that uses 'From' 1000 times. By handling this case all here,
2195 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
2196 /// single invocation handles all 1000 uses. Handling them one at a time would
2197 /// work, but would be really slow because it would have to unique each updated
2199 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
2201 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2202 Constant *ToC = cast<Constant>(To);
2204 std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
2205 Lookup.first.first = getType();
2206 Lookup.second = this;
2208 std::vector<Constant*> &Values = Lookup.first.second;
2209 Values.reserve(getNumOperands()); // Build replacement array.
2211 // Fill values with the modified operands of the constant array. Also,
2212 // compute whether this turns into an all-zeros array.
2213 bool isAllZeros = false;
2214 unsigned NumUpdated = 0;
2215 if (!ToC->isNullValue()) {
2216 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2217 Constant *Val = cast<Constant>(O->get());
2222 Values.push_back(Val);
2226 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2227 Constant *Val = cast<Constant>(O->get());
2232 Values.push_back(Val);
2233 if (isAllZeros) isAllZeros = Val->isNullValue();
2237 Constant *Replacement = 0;
2239 Replacement = ConstantAggregateZero::get(getType());
2241 // Check to see if we have this array type already.
2242 sys::SmartScopedWriter<true> Writer(*ConstantsLock);
2244 ArrayConstantsTy::MapTy::iterator I =
2245 ArrayConstants->InsertOrGetItem(Lookup, Exists);
2248 Replacement = I->second;
2250 // Okay, the new shape doesn't exist in the system yet. Instead of
2251 // creating a new constant array, inserting it, replaceallusesof'ing the
2252 // old with the new, then deleting the old... just update the current one
2254 ArrayConstants->MoveConstantToNewSlot(this, I);
2256 // Update to the new value. Optimize for the case when we have a single
2257 // operand that we're changing, but handle bulk updates efficiently.
2258 if (NumUpdated == 1) {
2259 unsigned OperandToUpdate = U-OperandList;
2260 assert(getOperand(OperandToUpdate) == From &&
2261 "ReplaceAllUsesWith broken!");
2262 setOperand(OperandToUpdate, ToC);
2264 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2265 if (getOperand(i) == From)
2272 // Otherwise, I do need to replace this with an existing value.
2273 assert(Replacement != this && "I didn't contain From!");
2275 // Everyone using this now uses the replacement.
2276 uncheckedReplaceAllUsesWith(Replacement);
2278 // Delete the old constant!
2282 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
2284 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2285 Constant *ToC = cast<Constant>(To);
2287 unsigned OperandToUpdate = U-OperandList;
2288 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2290 std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
2291 Lookup.first.first = getType();
2292 Lookup.second = this;
2293 std::vector<Constant*> &Values = Lookup.first.second;
2294 Values.reserve(getNumOperands()); // Build replacement struct.
2297 // Fill values with the modified operands of the constant struct. Also,
2298 // compute whether this turns into an all-zeros struct.
2299 bool isAllZeros = false;
2300 if (!ToC->isNullValue()) {
2301 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
2302 Values.push_back(cast<Constant>(O->get()));
2305 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2306 Constant *Val = cast<Constant>(O->get());
2307 Values.push_back(Val);
2308 if (isAllZeros) isAllZeros = Val->isNullValue();
2311 Values[OperandToUpdate] = ToC;
2313 Constant *Replacement = 0;
2315 Replacement = ConstantAggregateZero::get(getType());
2317 // Check to see if we have this array type already.
2318 sys::SmartScopedWriter<true> Writer(*ConstantsLock);
2320 StructConstantsTy::MapTy::iterator I =
2321 StructConstants->InsertOrGetItem(Lookup, Exists);
2324 Replacement = I->second;
2326 // Okay, the new shape doesn't exist in the system yet. Instead of
2327 // creating a new constant struct, inserting it, replaceallusesof'ing the
2328 // old with the new, then deleting the old... just update the current one
2330 StructConstants->MoveConstantToNewSlot(this, I);
2332 // Update to the new value.
2333 setOperand(OperandToUpdate, ToC);
2338 assert(Replacement != this && "I didn't contain From!");
2340 // Everyone using this now uses the replacement.
2341 uncheckedReplaceAllUsesWith(Replacement);
2343 // Delete the old constant!
2347 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
2349 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2351 std::vector<Constant*> Values;
2352 Values.reserve(getNumOperands()); // Build replacement array...
2353 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2354 Constant *Val = getOperand(i);
2355 if (Val == From) Val = cast<Constant>(To);
2356 Values.push_back(Val);
2359 Constant *Replacement = ConstantVector::get(getType(), Values);
2360 assert(Replacement != this && "I didn't contain From!");
2362 // Everyone using this now uses the replacement.
2363 uncheckedReplaceAllUsesWith(Replacement);
2365 // Delete the old constant!
2369 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2371 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2372 Constant *To = cast<Constant>(ToV);
2374 Constant *Replacement = 0;
2375 if (getOpcode() == Instruction::GetElementPtr) {
2376 SmallVector<Constant*, 8> Indices;
2377 Constant *Pointer = getOperand(0);
2378 Indices.reserve(getNumOperands()-1);
2379 if (Pointer == From) Pointer = To;
2381 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2382 Constant *Val = getOperand(i);
2383 if (Val == From) Val = To;
2384 Indices.push_back(Val);
2386 Replacement = ConstantExpr::getGetElementPtr(Pointer,
2387 &Indices[0], Indices.size());
2388 } else if (getOpcode() == Instruction::ExtractValue) {
2389 Constant *Agg = getOperand(0);
2390 if (Agg == From) Agg = To;
2392 const SmallVector<unsigned, 4> &Indices = getIndices();
2393 Replacement = ConstantExpr::getExtractValue(Agg,
2394 &Indices[0], Indices.size());
2395 } else if (getOpcode() == Instruction::InsertValue) {
2396 Constant *Agg = getOperand(0);
2397 Constant *Val = getOperand(1);
2398 if (Agg == From) Agg = To;
2399 if (Val == From) Val = To;
2401 const SmallVector<unsigned, 4> &Indices = getIndices();
2402 Replacement = ConstantExpr::getInsertValue(Agg, Val,
2403 &Indices[0], Indices.size());
2404 } else if (isCast()) {
2405 assert(getOperand(0) == From && "Cast only has one use!");
2406 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
2407 } else if (getOpcode() == Instruction::Select) {
2408 Constant *C1 = getOperand(0);
2409 Constant *C2 = getOperand(1);
2410 Constant *C3 = getOperand(2);
2411 if (C1 == From) C1 = To;
2412 if (C2 == From) C2 = To;
2413 if (C3 == From) C3 = To;
2414 Replacement = ConstantExpr::getSelect(C1, C2, C3);
2415 } else if (getOpcode() == Instruction::ExtractElement) {
2416 Constant *C1 = getOperand(0);
2417 Constant *C2 = getOperand(1);
2418 if (C1 == From) C1 = To;
2419 if (C2 == From) C2 = To;
2420 Replacement = ConstantExpr::getExtractElement(C1, C2);
2421 } else if (getOpcode() == Instruction::InsertElement) {
2422 Constant *C1 = getOperand(0);
2423 Constant *C2 = getOperand(1);
2424 Constant *C3 = getOperand(1);
2425 if (C1 == From) C1 = To;
2426 if (C2 == From) C2 = To;
2427 if (C3 == From) C3 = To;
2428 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2429 } else if (getOpcode() == Instruction::ShuffleVector) {
2430 Constant *C1 = getOperand(0);
2431 Constant *C2 = getOperand(1);
2432 Constant *C3 = getOperand(2);
2433 if (C1 == From) C1 = To;
2434 if (C2 == From) C2 = To;
2435 if (C3 == From) C3 = To;
2436 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2437 } else if (isCompare()) {
2438 Constant *C1 = getOperand(0);
2439 Constant *C2 = getOperand(1);
2440 if (C1 == From) C1 = To;
2441 if (C2 == From) C2 = To;
2442 if (getOpcode() == Instruction::ICmp)
2443 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2445 assert(getOpcode() == Instruction::FCmp);
2446 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2448 } else if (getNumOperands() == 2) {
2449 Constant *C1 = getOperand(0);
2450 Constant *C2 = getOperand(1);
2451 if (C1 == From) C1 = To;
2452 if (C2 == From) C2 = To;
2453 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2455 llvm_unreachable("Unknown ConstantExpr type!");
2459 assert(Replacement != this && "I didn't contain From!");
2461 // Everyone using this now uses the replacement.
2462 uncheckedReplaceAllUsesWith(Replacement);
2464 // Delete the old constant!
2468 void MDNode::replaceElement(Value *From, Value *To) {
2469 SmallVector<Value*, 4> Values;
2470 Values.reserve(getNumElements()); // Build replacement array...
2471 for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
2472 Value *Val = getElement(i);
2473 if (Val == From) Val = To;
2474 Values.push_back(Val);
2477 MDNode *Replacement =
2478 getType()->getContext().getMDNode(&Values[0], Values.size());
2479 assert(Replacement != this && "I didn't contain From!");
2481 uncheckedReplaceAllUsesWith(Replacement);