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 "LLVMContextImpl.h"
15 #include "llvm/Constants.h"
16 #include "ConstantFold.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/GlobalValue.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/MDNode.h"
21 #include "llvm/Module.h"
22 #include "llvm/Operator.h"
23 #include "llvm/ADT/FoldingSet.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/StringMap.h"
26 #include "llvm/Support/Compiler.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/ManagedStatic.h"
30 #include "llvm/Support/MathExtras.h"
31 #include "llvm/System/Mutex.h"
32 #include "llvm/System/RWMutex.h"
33 #include "llvm/System/Threading.h"
34 #include "llvm/ADT/DenseMap.h"
35 #include "llvm/ADT/SmallVector.h"
40 //===----------------------------------------------------------------------===//
42 //===----------------------------------------------------------------------===//
44 // Becomes a no-op when multithreading is disabled.
45 ManagedStatic<sys::SmartRWMutex<true> > ConstantsLock;
47 void Constant::destroyConstantImpl() {
48 // When a Constant is destroyed, there may be lingering
49 // references to the constant by other constants in the constant pool. These
50 // constants are implicitly dependent on the module that is being deleted,
51 // but they don't know that. Because we only find out when the CPV is
52 // deleted, we must now notify all of our users (that should only be
53 // Constants) that they are, in fact, invalid now and should be deleted.
55 while (!use_empty()) {
56 Value *V = use_back();
57 #ifndef NDEBUG // Only in -g mode...
58 if (!isa<Constant>(V))
59 DOUT << "While deleting: " << *this
60 << "\n\nUse still stuck around after Def is destroyed: "
63 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
64 Constant *CV = cast<Constant>(V);
65 CV->destroyConstant();
67 // The constant should remove itself from our use list...
68 assert((use_empty() || use_back() != V) && "Constant not removed!");
71 // Value has no outstanding references it is safe to delete it now...
75 /// canTrap - Return true if evaluation of this constant could trap. This is
76 /// true for things like constant expressions that could divide by zero.
77 bool Constant::canTrap() const {
78 assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
79 // The only thing that could possibly trap are constant exprs.
80 const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
81 if (!CE) return false;
83 // ConstantExpr traps if any operands can trap.
84 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
85 if (getOperand(i)->canTrap())
88 // Otherwise, only specific operations can trap.
89 switch (CE->getOpcode()) {
92 case Instruction::UDiv:
93 case Instruction::SDiv:
94 case Instruction::FDiv:
95 case Instruction::URem:
96 case Instruction::SRem:
97 case Instruction::FRem:
98 // Div and rem can trap if the RHS is not known to be non-zero.
99 if (!isa<ConstantInt>(getOperand(1)) || getOperand(1)->isNullValue())
106 /// getRelocationInfo - This method classifies the entry according to
107 /// whether or not it may generate a relocation entry. This must be
108 /// conservative, so if it might codegen to a relocatable entry, it should say
109 /// so. The return values are:
111 /// NoRelocation: This constant pool entry is guaranteed to never have a
112 /// relocation applied to it (because it holds a simple constant like
114 /// LocalRelocation: This entry has relocations, but the entries are
115 /// guaranteed to be resolvable by the static linker, so the dynamic
116 /// linker will never see them.
117 /// GlobalRelocations: This entry may have arbitrary relocations.
119 /// FIXME: This really should not be in VMCore.
120 Constant::PossibleRelocationsTy Constant::getRelocationInfo() const {
121 if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
122 if (GV->hasLocalLinkage() || GV->hasHiddenVisibility())
123 return LocalRelocation; // Local to this file/library.
124 return GlobalRelocations; // Global reference.
127 PossibleRelocationsTy Result = NoRelocation;
128 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
129 Result = std::max(Result, getOperand(i)->getRelocationInfo());
135 /// getVectorElements - This method, which is only valid on constant of vector
136 /// type, returns the elements of the vector in the specified smallvector.
137 /// This handles breaking down a vector undef into undef elements, etc. For
138 /// constant exprs and other cases we can't handle, we return an empty vector.
139 void Constant::getVectorElements(LLVMContext &Context,
140 SmallVectorImpl<Constant*> &Elts) const {
141 assert(isa<VectorType>(getType()) && "Not a vector constant!");
143 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this)) {
144 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i)
145 Elts.push_back(CV->getOperand(i));
149 const VectorType *VT = cast<VectorType>(getType());
150 if (isa<ConstantAggregateZero>(this)) {
151 Elts.assign(VT->getNumElements(),
152 Context.getNullValue(VT->getElementType()));
156 if (isa<UndefValue>(this)) {
157 Elts.assign(VT->getNumElements(), Context.getUndef(VT->getElementType()));
161 // Unknown type, must be constant expr etc.
166 //===----------------------------------------------------------------------===//
168 //===----------------------------------------------------------------------===//
170 ConstantInt::ConstantInt(const IntegerType *Ty, const APInt& V)
171 : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
172 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
175 // Get a ConstantInt from an APInt. Note that the value stored in the DenseMap
176 // as the key, is a DenseMapAPIntKeyInfo::KeyTy which has provided the
177 // operator== and operator!= to ensure that the DenseMap doesn't attempt to
178 // compare APInt's of different widths, which would violate an APInt class
179 // invariant which generates an assertion.
180 ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt& V) {
181 // Get the corresponding integer type for the bit width of the value.
182 const IntegerType *ITy = Context.getIntegerType(V.getBitWidth());
183 // get an existing value or the insertion position
184 DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
186 Context.pImpl->ConstantsLock.reader_acquire();
187 ConstantInt *&Slot = Context.pImpl->IntConstants[Key];
188 Context.pImpl->ConstantsLock.reader_release();
191 sys::SmartScopedWriter<true> Writer(Context.pImpl->ConstantsLock);
192 ConstantInt *&NewSlot = Context.pImpl->IntConstants[Key];
194 NewSlot = new ConstantInt(ITy, V);
203 Constant* ConstantInt::get(const Type* Ty, uint64_t V, bool isSigned) {
204 Constant *C = get(cast<IntegerType>(Ty->getScalarType()),
207 // For vectors, broadcast the value.
208 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
209 return Ty->getContext().getConstantVector(
210 std::vector<Constant *>(VTy->getNumElements(), C));
215 ConstantInt* ConstantInt::get(const IntegerType* Ty, uint64_t V,
217 return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned));
220 ConstantInt* ConstantInt::getSigned(const IntegerType* Ty, int64_t V) {
221 return get(Ty, V, true);
224 Constant *ConstantInt::getSigned(const Type *Ty, int64_t V) {
225 return get(Ty, V, true);
228 Constant* ConstantInt::get(const Type* Ty, const APInt& V) {
229 ConstantInt *C = get(Ty->getContext(), V);
230 assert(C->getType() == Ty->getScalarType() &&
231 "ConstantInt type doesn't match the type implied by its value!");
233 // For vectors, broadcast the value.
234 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
235 return Ty->getContext().getConstantVector(
236 std::vector<Constant *>(VTy->getNumElements(), C));
241 //===----------------------------------------------------------------------===//
243 //===----------------------------------------------------------------------===//
246 static const fltSemantics *TypeToFloatSemantics(const Type *Ty) {
247 if (Ty == Type::FloatTy)
248 return &APFloat::IEEEsingle;
249 if (Ty == Type::DoubleTy)
250 return &APFloat::IEEEdouble;
251 if (Ty == Type::X86_FP80Ty)
252 return &APFloat::x87DoubleExtended;
253 else if (Ty == Type::FP128Ty)
254 return &APFloat::IEEEquad;
256 assert(Ty == Type::PPC_FP128Ty && "Unknown FP format");
257 return &APFloat::PPCDoubleDouble;
261 ConstantFP::ConstantFP(const Type *Ty, const APFloat& V)
262 : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
263 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
267 bool ConstantFP::isNullValue() const {
268 return Val.isZero() && !Val.isNegative();
271 bool ConstantFP::isExactlyValue(const APFloat& V) const {
272 return Val.bitwiseIsEqual(V);
275 //===----------------------------------------------------------------------===//
276 // ConstantXXX Classes
277 //===----------------------------------------------------------------------===//
280 ConstantArray::ConstantArray(const ArrayType *T,
281 const std::vector<Constant*> &V)
282 : Constant(T, ConstantArrayVal,
283 OperandTraits<ConstantArray>::op_end(this) - V.size(),
285 assert(V.size() == T->getNumElements() &&
286 "Invalid initializer vector for constant array");
287 Use *OL = OperandList;
288 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
291 assert((C->getType() == T->getElementType() ||
293 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
294 "Initializer for array element doesn't match array element type!");
300 ConstantStruct::ConstantStruct(const StructType *T,
301 const std::vector<Constant*> &V)
302 : Constant(T, ConstantStructVal,
303 OperandTraits<ConstantStruct>::op_end(this) - V.size(),
305 assert(V.size() == T->getNumElements() &&
306 "Invalid initializer vector for constant structure");
307 Use *OL = OperandList;
308 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
311 assert((C->getType() == T->getElementType(I-V.begin()) ||
312 ((T->getElementType(I-V.begin())->isAbstract() ||
313 C->getType()->isAbstract()) &&
314 T->getElementType(I-V.begin())->getTypeID() ==
315 C->getType()->getTypeID())) &&
316 "Initializer for struct element doesn't match struct element type!");
322 ConstantVector::ConstantVector(const VectorType *T,
323 const std::vector<Constant*> &V)
324 : Constant(T, ConstantVectorVal,
325 OperandTraits<ConstantVector>::op_end(this) - V.size(),
327 Use *OL = OperandList;
328 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
331 assert((C->getType() == T->getElementType() ||
333 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
334 "Initializer for vector element doesn't match vector element type!");
341 // We declare several classes private to this file, so use an anonymous
345 /// UnaryConstantExpr - This class is private to Constants.cpp, and is used
346 /// behind the scenes to implement unary constant exprs.
347 class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
348 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
350 // allocate space for exactly one operand
351 void *operator new(size_t s) {
352 return User::operator new(s, 1);
354 UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
355 : ConstantExpr(Ty, Opcode, &Op<0>(), 1) {
358 /// Transparently provide more efficient getOperand methods.
359 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
362 /// BinaryConstantExpr - This class is private to Constants.cpp, and is used
363 /// behind the scenes to implement binary constant exprs.
364 class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
365 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
367 // allocate space for exactly two operands
368 void *operator new(size_t s) {
369 return User::operator new(s, 2);
371 BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
372 : ConstantExpr(C1->getType(), Opcode, &Op<0>(), 2) {
376 /// Transparently provide more efficient getOperand methods.
377 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
380 /// SelectConstantExpr - This class is private to Constants.cpp, and is used
381 /// behind the scenes to implement select constant exprs.
382 class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
383 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
385 // allocate space for exactly three operands
386 void *operator new(size_t s) {
387 return User::operator new(s, 3);
389 SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
390 : ConstantExpr(C2->getType(), Instruction::Select, &Op<0>(), 3) {
395 /// Transparently provide more efficient getOperand methods.
396 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
399 /// ExtractElementConstantExpr - This class is private to
400 /// Constants.cpp, and is used behind the scenes to implement
401 /// extractelement constant exprs.
402 class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
403 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
405 // allocate space for exactly two operands
406 void *operator new(size_t s) {
407 return User::operator new(s, 2);
409 ExtractElementConstantExpr(Constant *C1, Constant *C2)
410 : ConstantExpr(cast<VectorType>(C1->getType())->getElementType(),
411 Instruction::ExtractElement, &Op<0>(), 2) {
415 /// Transparently provide more efficient getOperand methods.
416 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
419 /// InsertElementConstantExpr - This class is private to
420 /// Constants.cpp, and is used behind the scenes to implement
421 /// insertelement constant exprs.
422 class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
423 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
425 // allocate space for exactly three operands
426 void *operator new(size_t s) {
427 return User::operator new(s, 3);
429 InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
430 : ConstantExpr(C1->getType(), Instruction::InsertElement,
436 /// Transparently provide more efficient getOperand methods.
437 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
440 /// ShuffleVectorConstantExpr - This class is private to
441 /// Constants.cpp, and is used behind the scenes to implement
442 /// shufflevector constant exprs.
443 class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
444 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
446 // allocate space for exactly three operands
447 void *operator new(size_t s) {
448 return User::operator new(s, 3);
450 ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
451 : ConstantExpr(VectorType::get(
452 cast<VectorType>(C1->getType())->getElementType(),
453 cast<VectorType>(C3->getType())->getNumElements()),
454 Instruction::ShuffleVector,
460 /// Transparently provide more efficient getOperand methods.
461 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
464 /// ExtractValueConstantExpr - This class is private to
465 /// Constants.cpp, and is used behind the scenes to implement
466 /// extractvalue constant exprs.
467 class VISIBILITY_HIDDEN ExtractValueConstantExpr : public ConstantExpr {
468 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
470 // allocate space for exactly one operand
471 void *operator new(size_t s) {
472 return User::operator new(s, 1);
474 ExtractValueConstantExpr(Constant *Agg,
475 const SmallVector<unsigned, 4> &IdxList,
477 : ConstantExpr(DestTy, Instruction::ExtractValue, &Op<0>(), 1),
482 /// Indices - These identify which value to extract.
483 const SmallVector<unsigned, 4> Indices;
485 /// Transparently provide more efficient getOperand methods.
486 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
489 /// InsertValueConstantExpr - This class is private to
490 /// Constants.cpp, and is used behind the scenes to implement
491 /// insertvalue constant exprs.
492 class VISIBILITY_HIDDEN InsertValueConstantExpr : public ConstantExpr {
493 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
495 // allocate space for exactly one operand
496 void *operator new(size_t s) {
497 return User::operator new(s, 2);
499 InsertValueConstantExpr(Constant *Agg, Constant *Val,
500 const SmallVector<unsigned, 4> &IdxList,
502 : ConstantExpr(DestTy, Instruction::InsertValue, &Op<0>(), 2),
508 /// Indices - These identify the position for the insertion.
509 const SmallVector<unsigned, 4> Indices;
511 /// Transparently provide more efficient getOperand methods.
512 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
516 /// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
517 /// used behind the scenes to implement getelementpr constant exprs.
518 class VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
519 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
522 static GetElementPtrConstantExpr *Create(Constant *C,
523 const std::vector<Constant*>&IdxList,
524 const Type *DestTy) {
526 new(IdxList.size() + 1) GetElementPtrConstantExpr(C, IdxList, DestTy);
528 /// Transparently provide more efficient getOperand methods.
529 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
532 // CompareConstantExpr - This class is private to Constants.cpp, and is used
533 // behind the scenes to implement ICmp and FCmp constant expressions. This is
534 // needed in order to store the predicate value for these instructions.
535 struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
536 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
537 // allocate space for exactly two operands
538 void *operator new(size_t s) {
539 return User::operator new(s, 2);
541 unsigned short predicate;
542 CompareConstantExpr(const Type *ty, Instruction::OtherOps opc,
543 unsigned short pred, Constant* LHS, Constant* RHS)
544 : ConstantExpr(ty, opc, &Op<0>(), 2), predicate(pred) {
548 /// Transparently provide more efficient getOperand methods.
549 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
552 } // end anonymous namespace
555 struct OperandTraits<UnaryConstantExpr> : FixedNumOperandTraits<1> {
557 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(UnaryConstantExpr, Value)
560 struct OperandTraits<BinaryConstantExpr> : FixedNumOperandTraits<2> {
562 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BinaryConstantExpr, Value)
565 struct OperandTraits<SelectConstantExpr> : FixedNumOperandTraits<3> {
567 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectConstantExpr, Value)
570 struct OperandTraits<ExtractElementConstantExpr> : FixedNumOperandTraits<2> {
572 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementConstantExpr, Value)
575 struct OperandTraits<InsertElementConstantExpr> : FixedNumOperandTraits<3> {
577 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementConstantExpr, Value)
580 struct OperandTraits<ShuffleVectorConstantExpr> : FixedNumOperandTraits<3> {
582 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorConstantExpr, Value)
585 struct OperandTraits<ExtractValueConstantExpr> : FixedNumOperandTraits<1> {
587 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractValueConstantExpr, Value)
590 struct OperandTraits<InsertValueConstantExpr> : FixedNumOperandTraits<2> {
592 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueConstantExpr, Value)
595 struct OperandTraits<GetElementPtrConstantExpr> : VariadicOperandTraits<1> {
598 GetElementPtrConstantExpr::GetElementPtrConstantExpr
600 const std::vector<Constant*> &IdxList,
602 : ConstantExpr(DestTy, Instruction::GetElementPtr,
603 OperandTraits<GetElementPtrConstantExpr>::op_end(this)
604 - (IdxList.size()+1),
607 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
608 OperandList[i+1] = IdxList[i];
611 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrConstantExpr, Value)
615 struct OperandTraits<CompareConstantExpr> : FixedNumOperandTraits<2> {
617 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CompareConstantExpr, Value)
620 } // End llvm namespace
623 // Utility function for determining if a ConstantExpr is a CastOp or not. This
624 // can't be inline because we don't want to #include Instruction.h into
626 bool ConstantExpr::isCast() const {
627 return Instruction::isCast(getOpcode());
630 bool ConstantExpr::isCompare() const {
631 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
634 bool ConstantExpr::hasIndices() const {
635 return getOpcode() == Instruction::ExtractValue ||
636 getOpcode() == Instruction::InsertValue;
639 const SmallVector<unsigned, 4> &ConstantExpr::getIndices() const {
640 if (const ExtractValueConstantExpr *EVCE =
641 dyn_cast<ExtractValueConstantExpr>(this))
642 return EVCE->Indices;
644 return cast<InsertValueConstantExpr>(this)->Indices;
647 unsigned ConstantExpr::getPredicate() const {
648 assert(getOpcode() == Instruction::FCmp ||
649 getOpcode() == Instruction::ICmp);
650 return ((const CompareConstantExpr*)this)->predicate;
653 /// getWithOperandReplaced - Return a constant expression identical to this
654 /// one, but with the specified operand set to the specified value.
656 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
657 assert(OpNo < getNumOperands() && "Operand num is out of range!");
658 assert(Op->getType() == getOperand(OpNo)->getType() &&
659 "Replacing operand with value of different type!");
660 if (getOperand(OpNo) == Op)
661 return const_cast<ConstantExpr*>(this);
663 Constant *Op0, *Op1, *Op2;
664 switch (getOpcode()) {
665 case Instruction::Trunc:
666 case Instruction::ZExt:
667 case Instruction::SExt:
668 case Instruction::FPTrunc:
669 case Instruction::FPExt:
670 case Instruction::UIToFP:
671 case Instruction::SIToFP:
672 case Instruction::FPToUI:
673 case Instruction::FPToSI:
674 case Instruction::PtrToInt:
675 case Instruction::IntToPtr:
676 case Instruction::BitCast:
677 return ConstantExpr::getCast(getOpcode(), Op, getType());
678 case Instruction::Select:
679 Op0 = (OpNo == 0) ? Op : getOperand(0);
680 Op1 = (OpNo == 1) ? Op : getOperand(1);
681 Op2 = (OpNo == 2) ? Op : getOperand(2);
682 return ConstantExpr::getSelect(Op0, Op1, Op2);
683 case Instruction::InsertElement:
684 Op0 = (OpNo == 0) ? Op : getOperand(0);
685 Op1 = (OpNo == 1) ? Op : getOperand(1);
686 Op2 = (OpNo == 2) ? Op : getOperand(2);
687 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
688 case Instruction::ExtractElement:
689 Op0 = (OpNo == 0) ? Op : getOperand(0);
690 Op1 = (OpNo == 1) ? Op : getOperand(1);
691 return ConstantExpr::getExtractElement(Op0, Op1);
692 case Instruction::ShuffleVector:
693 Op0 = (OpNo == 0) ? Op : getOperand(0);
694 Op1 = (OpNo == 1) ? Op : getOperand(1);
695 Op2 = (OpNo == 2) ? Op : getOperand(2);
696 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
697 case Instruction::GetElementPtr: {
698 SmallVector<Constant*, 8> Ops;
699 Ops.resize(getNumOperands()-1);
700 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
701 Ops[i-1] = getOperand(i);
703 return ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
705 return ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
708 assert(getNumOperands() == 2 && "Must be binary operator?");
709 Op0 = (OpNo == 0) ? Op : getOperand(0);
710 Op1 = (OpNo == 1) ? Op : getOperand(1);
711 return ConstantExpr::get(getOpcode(), Op0, Op1);
715 /// getWithOperands - This returns the current constant expression with the
716 /// operands replaced with the specified values. The specified operands must
717 /// match count and type with the existing ones.
718 Constant *ConstantExpr::
719 getWithOperands(Constant* const *Ops, unsigned NumOps) const {
720 assert(NumOps == getNumOperands() && "Operand count mismatch!");
721 bool AnyChange = false;
722 for (unsigned i = 0; i != NumOps; ++i) {
723 assert(Ops[i]->getType() == getOperand(i)->getType() &&
724 "Operand type mismatch!");
725 AnyChange |= Ops[i] != getOperand(i);
727 if (!AnyChange) // No operands changed, return self.
728 return const_cast<ConstantExpr*>(this);
730 switch (getOpcode()) {
731 case Instruction::Trunc:
732 case Instruction::ZExt:
733 case Instruction::SExt:
734 case Instruction::FPTrunc:
735 case Instruction::FPExt:
736 case Instruction::UIToFP:
737 case Instruction::SIToFP:
738 case Instruction::FPToUI:
739 case Instruction::FPToSI:
740 case Instruction::PtrToInt:
741 case Instruction::IntToPtr:
742 case Instruction::BitCast:
743 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
744 case Instruction::Select:
745 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
746 case Instruction::InsertElement:
747 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
748 case Instruction::ExtractElement:
749 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
750 case Instruction::ShuffleVector:
751 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
752 case Instruction::GetElementPtr:
753 return ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], NumOps-1);
754 case Instruction::ICmp:
755 case Instruction::FCmp:
756 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
758 assert(getNumOperands() == 2 && "Must be binary operator?");
759 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
764 //===----------------------------------------------------------------------===//
765 // isValueValidForType implementations
767 bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
768 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
769 if (Ty == Type::Int1Ty)
770 return Val == 0 || Val == 1;
772 return true; // always true, has to fit in largest type
773 uint64_t Max = (1ll << NumBits) - 1;
777 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
778 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
779 if (Ty == Type::Int1Ty)
780 return Val == 0 || Val == 1 || Val == -1;
782 return true; // always true, has to fit in largest type
783 int64_t Min = -(1ll << (NumBits-1));
784 int64_t Max = (1ll << (NumBits-1)) - 1;
785 return (Val >= Min && Val <= Max);
788 bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
789 // convert modifies in place, so make a copy.
790 APFloat Val2 = APFloat(Val);
792 switch (Ty->getTypeID()) {
794 return false; // These can't be represented as floating point!
796 // FIXME rounding mode needs to be more flexible
797 case Type::FloatTyID: {
798 if (&Val2.getSemantics() == &APFloat::IEEEsingle)
800 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
803 case Type::DoubleTyID: {
804 if (&Val2.getSemantics() == &APFloat::IEEEsingle ||
805 &Val2.getSemantics() == &APFloat::IEEEdouble)
807 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
810 case Type::X86_FP80TyID:
811 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
812 &Val2.getSemantics() == &APFloat::IEEEdouble ||
813 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
814 case Type::FP128TyID:
815 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
816 &Val2.getSemantics() == &APFloat::IEEEdouble ||
817 &Val2.getSemantics() == &APFloat::IEEEquad;
818 case Type::PPC_FP128TyID:
819 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
820 &Val2.getSemantics() == &APFloat::IEEEdouble ||
821 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
825 //===----------------------------------------------------------------------===//
826 // Factory Function Implementation
828 /// destroyConstant - Remove the constant from the constant table...
830 void ConstantAggregateZero::destroyConstant() {
831 // Implicitly locked.
832 getType()->getContext().erase(this);
833 destroyConstantImpl();
836 /// destroyConstant - Remove the constant from the constant table...
838 void ConstantArray::destroyConstant() {
839 // Implicitly locked.
840 getType()->getContext().erase(this);
841 destroyConstantImpl();
844 /// isString - This method returns true if the array is an array of i8, and
845 /// if the elements of the array are all ConstantInt's.
846 bool ConstantArray::isString() const {
847 // Check the element type for i8...
848 if (getType()->getElementType() != Type::Int8Ty)
850 // Check the elements to make sure they are all integers, not constant
852 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
853 if (!isa<ConstantInt>(getOperand(i)))
858 /// isCString - This method returns true if the array is a string (see
859 /// isString) and it ends in a null byte \\0 and does not contains any other
860 /// null bytes except its terminator.
861 bool ConstantArray::isCString() const {
862 // Check the element type for i8...
863 if (getType()->getElementType() != Type::Int8Ty)
866 // Last element must be a null.
867 if (!getOperand(getNumOperands()-1)->isNullValue())
869 // Other elements must be non-null integers.
870 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
871 if (!isa<ConstantInt>(getOperand(i)))
873 if (getOperand(i)->isNullValue())
880 /// getAsString - If the sub-element type of this array is i8
881 /// then this method converts the array to an std::string and returns it.
882 /// Otherwise, it asserts out.
884 std::string ConstantArray::getAsString() const {
885 assert(isString() && "Not a string!");
887 Result.reserve(getNumOperands());
888 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
889 Result.push_back((char)cast<ConstantInt>(getOperand(i))->getZExtValue());
894 //---- ConstantStruct::get() implementation...
901 // destroyConstant - Remove the constant from the constant table...
903 void ConstantStruct::destroyConstant() {
904 // Implicitly locked.
905 getType()->getContext().erase(this);
906 destroyConstantImpl();
909 // destroyConstant - Remove the constant from the constant table...
911 void ConstantVector::destroyConstant() {
912 // Implicitly locked.
913 getType()->getContext().erase(this);
914 destroyConstantImpl();
917 /// This function will return true iff every element in this vector constant
918 /// is set to all ones.
919 /// @returns true iff this constant's emements are all set to all ones.
920 /// @brief Determine if the value is all ones.
921 bool ConstantVector::isAllOnesValue() const {
922 // Check out first element.
923 const Constant *Elt = getOperand(0);
924 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
925 if (!CI || !CI->isAllOnesValue()) return false;
926 // Then make sure all remaining elements point to the same value.
927 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
928 if (getOperand(I) != Elt) return false;
933 /// getSplatValue - If this is a splat constant, where all of the
934 /// elements have the same value, return that value. Otherwise return null.
935 Constant *ConstantVector::getSplatValue() {
936 // Check out first element.
937 Constant *Elt = getOperand(0);
938 // Then make sure all remaining elements point to the same value.
939 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
940 if (getOperand(I) != Elt) return 0;
944 //---- ConstantPointerNull::get() implementation...
948 // ConstantPointerNull does not take extra "value" argument...
949 template<class ValType>
950 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
951 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
952 return new ConstantPointerNull(Ty);
957 struct ConvertConstantType<ConstantPointerNull, PointerType> {
958 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
959 // Make everyone now use a constant of the new type...
960 Constant *New = ConstantPointerNull::get(NewTy);
961 assert(New != OldC && "Didn't replace constant??");
962 OldC->uncheckedReplaceAllUsesWith(New);
963 OldC->destroyConstant(); // This constant is now dead, destroy it.
968 static ManagedStatic<ValueMap<char, PointerType,
969 ConstantPointerNull> > NullPtrConstants;
971 static char getValType(ConstantPointerNull *) {
976 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
977 // Implicitly locked.
978 return NullPtrConstants->getOrCreate(Ty, 0);
981 // destroyConstant - Remove the constant from the constant table...
983 void ConstantPointerNull::destroyConstant() {
984 // Implicitly locked.
985 NullPtrConstants->remove(this);
986 destroyConstantImpl();
990 //---- UndefValue::get() implementation...
994 // UndefValue does not take extra "value" argument...
995 template<class ValType>
996 struct ConstantCreator<UndefValue, Type, ValType> {
997 static UndefValue *create(const Type *Ty, const ValType &V) {
998 return new UndefValue(Ty);
1003 struct ConvertConstantType<UndefValue, Type> {
1004 static void convert(UndefValue *OldC, const Type *NewTy) {
1005 // Make everyone now use a constant of the new type.
1006 Constant *New = UndefValue::get(NewTy);
1007 assert(New != OldC && "Didn't replace constant??");
1008 OldC->uncheckedReplaceAllUsesWith(New);
1009 OldC->destroyConstant(); // This constant is now dead, destroy it.
1014 static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
1016 static char getValType(UndefValue *) {
1021 UndefValue *UndefValue::get(const Type *Ty) {
1022 // Implicitly locked.
1023 return UndefValueConstants->getOrCreate(Ty, 0);
1026 // destroyConstant - Remove the constant from the constant table.
1028 void UndefValue::destroyConstant() {
1029 // Implicitly locked.
1030 UndefValueConstants->remove(this);
1031 destroyConstantImpl();
1034 //---- MDNode::get() implementation
1037 MDNode::MDNode(Value*const* Vals, unsigned NumVals)
1038 : MetadataBase(Type::MetadataTy, Value::MDNodeVal) {
1039 for (unsigned i = 0; i != NumVals; ++i)
1040 Node.push_back(WeakVH(Vals[i]));
1043 void MDNode::Profile(FoldingSetNodeID &ID) const {
1044 for (const_elem_iterator I = elem_begin(), E = elem_end(); I != E; ++I)
1048 //---- ConstantExpr::get() implementations...
1053 struct ExprMapKeyType {
1054 typedef SmallVector<unsigned, 4> IndexList;
1056 ExprMapKeyType(unsigned opc,
1057 const std::vector<Constant*> &ops,
1058 unsigned short pred = 0,
1059 const IndexList &inds = IndexList())
1060 : opcode(opc), predicate(pred), operands(ops), indices(inds) {}
1063 std::vector<Constant*> operands;
1065 bool operator==(const ExprMapKeyType& that) const {
1066 return this->opcode == that.opcode &&
1067 this->predicate == that.predicate &&
1068 this->operands == that.operands &&
1069 this->indices == that.indices;
1071 bool operator<(const ExprMapKeyType & that) const {
1072 return this->opcode < that.opcode ||
1073 (this->opcode == that.opcode && this->predicate < that.predicate) ||
1074 (this->opcode == that.opcode && this->predicate == that.predicate &&
1075 this->operands < that.operands) ||
1076 (this->opcode == that.opcode && this->predicate == that.predicate &&
1077 this->operands == that.operands && this->indices < that.indices);
1080 bool operator!=(const ExprMapKeyType& that) const {
1081 return !(*this == that);
1089 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1090 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1091 unsigned short pred = 0) {
1092 if (Instruction::isCast(V.opcode))
1093 return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1094 if ((V.opcode >= Instruction::BinaryOpsBegin &&
1095 V.opcode < Instruction::BinaryOpsEnd))
1096 return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1097 if (V.opcode == Instruction::Select)
1098 return new SelectConstantExpr(V.operands[0], V.operands[1],
1100 if (V.opcode == Instruction::ExtractElement)
1101 return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1102 if (V.opcode == Instruction::InsertElement)
1103 return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1105 if (V.opcode == Instruction::ShuffleVector)
1106 return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1108 if (V.opcode == Instruction::InsertValue)
1109 return new InsertValueConstantExpr(V.operands[0], V.operands[1],
1111 if (V.opcode == Instruction::ExtractValue)
1112 return new ExtractValueConstantExpr(V.operands[0], V.indices, Ty);
1113 if (V.opcode == Instruction::GetElementPtr) {
1114 std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
1115 return GetElementPtrConstantExpr::Create(V.operands[0], IdxList, Ty);
1118 // The compare instructions are weird. We have to encode the predicate
1119 // value and it is combined with the instruction opcode by multiplying
1120 // the opcode by one hundred. We must decode this to get the predicate.
1121 if (V.opcode == Instruction::ICmp)
1122 return new CompareConstantExpr(Ty, Instruction::ICmp, V.predicate,
1123 V.operands[0], V.operands[1]);
1124 if (V.opcode == Instruction::FCmp)
1125 return new CompareConstantExpr(Ty, Instruction::FCmp, V.predicate,
1126 V.operands[0], V.operands[1]);
1127 llvm_unreachable("Invalid ConstantExpr!");
1133 struct ConvertConstantType<ConstantExpr, Type> {
1134 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1136 switch (OldC->getOpcode()) {
1137 case Instruction::Trunc:
1138 case Instruction::ZExt:
1139 case Instruction::SExt:
1140 case Instruction::FPTrunc:
1141 case Instruction::FPExt:
1142 case Instruction::UIToFP:
1143 case Instruction::SIToFP:
1144 case Instruction::FPToUI:
1145 case Instruction::FPToSI:
1146 case Instruction::PtrToInt:
1147 case Instruction::IntToPtr:
1148 case Instruction::BitCast:
1149 New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0),
1152 case Instruction::Select:
1153 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1154 OldC->getOperand(1),
1155 OldC->getOperand(2));
1158 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1159 OldC->getOpcode() < Instruction::BinaryOpsEnd);
1160 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1161 OldC->getOperand(1));
1163 case Instruction::GetElementPtr:
1164 // Make everyone now use a constant of the new type...
1165 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1166 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0),
1167 &Idx[0], Idx.size());
1171 assert(New != OldC && "Didn't replace constant??");
1172 OldC->uncheckedReplaceAllUsesWith(New);
1173 OldC->destroyConstant(); // This constant is now dead, destroy it.
1176 } // end namespace llvm
1179 static ExprMapKeyType getValType(ConstantExpr *CE) {
1180 std::vector<Constant*> Operands;
1181 Operands.reserve(CE->getNumOperands());
1182 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1183 Operands.push_back(cast<Constant>(CE->getOperand(i)));
1184 return ExprMapKeyType(CE->getOpcode(), Operands,
1185 CE->isCompare() ? CE->getPredicate() : 0,
1187 CE->getIndices() : SmallVector<unsigned, 4>());
1190 static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1191 ConstantExpr> > ExprConstants;
1193 /// This is a utility function to handle folding of casts and lookup of the
1194 /// cast in the ExprConstants map. It is used by the various get* methods below.
1195 static inline Constant *getFoldedCast(
1196 Instruction::CastOps opc, Constant *C, const Type *Ty) {
1197 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1198 // Fold a few common cases
1200 ConstantFoldCastInstruction(getGlobalContext(), opc, C, Ty))
1203 // Look up the constant in the table first to ensure uniqueness
1204 std::vector<Constant*> argVec(1, C);
1205 ExprMapKeyType Key(opc, argVec);
1207 // Implicitly locked.
1208 return ExprConstants->getOrCreate(Ty, Key);
1211 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1212 Instruction::CastOps opc = Instruction::CastOps(oc);
1213 assert(Instruction::isCast(opc) && "opcode out of range");
1214 assert(C && Ty && "Null arguments to getCast");
1215 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1219 llvm_unreachable("Invalid cast opcode");
1221 case Instruction::Trunc: return getTrunc(C, Ty);
1222 case Instruction::ZExt: return getZExt(C, Ty);
1223 case Instruction::SExt: return getSExt(C, Ty);
1224 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1225 case Instruction::FPExt: return getFPExtend(C, Ty);
1226 case Instruction::UIToFP: return getUIToFP(C, Ty);
1227 case Instruction::SIToFP: return getSIToFP(C, Ty);
1228 case Instruction::FPToUI: return getFPToUI(C, Ty);
1229 case Instruction::FPToSI: return getFPToSI(C, Ty);
1230 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1231 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1232 case Instruction::BitCast: return getBitCast(C, Ty);
1237 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1238 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1239 return getCast(Instruction::BitCast, C, Ty);
1240 return getCast(Instruction::ZExt, C, Ty);
1243 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1244 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1245 return getCast(Instruction::BitCast, C, Ty);
1246 return getCast(Instruction::SExt, C, Ty);
1249 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1250 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1251 return getCast(Instruction::BitCast, C, Ty);
1252 return getCast(Instruction::Trunc, C, Ty);
1255 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1256 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1257 assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
1259 if (Ty->isInteger())
1260 return getCast(Instruction::PtrToInt, S, Ty);
1261 return getCast(Instruction::BitCast, S, Ty);
1264 Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
1266 assert(C->getType()->isIntOrIntVector() &&
1267 Ty->isIntOrIntVector() && "Invalid cast");
1268 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1269 unsigned DstBits = Ty->getScalarSizeInBits();
1270 Instruction::CastOps opcode =
1271 (SrcBits == DstBits ? Instruction::BitCast :
1272 (SrcBits > DstBits ? Instruction::Trunc :
1273 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1274 return getCast(opcode, C, Ty);
1277 Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1278 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1280 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1281 unsigned DstBits = Ty->getScalarSizeInBits();
1282 if (SrcBits == DstBits)
1283 return C; // Avoid a useless cast
1284 Instruction::CastOps opcode =
1285 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1286 return getCast(opcode, C, Ty);
1289 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
1291 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1292 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1294 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1295 assert(C->getType()->isIntOrIntVector() && "Trunc operand must be integer");
1296 assert(Ty->isIntOrIntVector() && "Trunc produces only integral");
1297 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1298 "SrcTy must be larger than DestTy for Trunc!");
1300 return getFoldedCast(Instruction::Trunc, C, Ty);
1303 Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
1305 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1306 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1308 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1309 assert(C->getType()->isIntOrIntVector() && "SExt operand must be integral");
1310 assert(Ty->isIntOrIntVector() && "SExt produces only integer");
1311 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1312 "SrcTy must be smaller than DestTy for SExt!");
1314 return getFoldedCast(Instruction::SExt, C, Ty);
1317 Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
1319 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1320 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1322 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1323 assert(C->getType()->isIntOrIntVector() && "ZEXt operand must be integral");
1324 assert(Ty->isIntOrIntVector() && "ZExt produces only integer");
1325 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1326 "SrcTy must be smaller than DestTy for ZExt!");
1328 return getFoldedCast(Instruction::ZExt, C, Ty);
1331 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1333 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1334 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1336 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1337 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1338 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1339 "This is an illegal floating point truncation!");
1340 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1343 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1345 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1346 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1348 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1349 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1350 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1351 "This is an illegal floating point extension!");
1352 return getFoldedCast(Instruction::FPExt, C, Ty);
1355 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
1357 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1358 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1360 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1361 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1362 "This is an illegal uint to floating point cast!");
1363 return getFoldedCast(Instruction::UIToFP, C, Ty);
1366 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
1368 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1369 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1371 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1372 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1373 "This is an illegal sint to floating point cast!");
1374 return getFoldedCast(Instruction::SIToFP, C, Ty);
1377 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
1379 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1380 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1382 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1383 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1384 "This is an illegal floating point to uint cast!");
1385 return getFoldedCast(Instruction::FPToUI, C, Ty);
1388 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
1390 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1391 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1393 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1394 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1395 "This is an illegal floating point to sint cast!");
1396 return getFoldedCast(Instruction::FPToSI, C, Ty);
1399 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1400 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
1401 assert(DstTy->isInteger() && "PtrToInt destination must be integral");
1402 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1405 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
1406 assert(C->getType()->isInteger() && "IntToPtr source must be integral");
1407 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
1408 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1411 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1412 // BitCast implies a no-op cast of type only. No bits change. However, you
1413 // can't cast pointers to anything but pointers.
1415 const Type *SrcTy = C->getType();
1416 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
1417 "BitCast cannot cast pointer to non-pointer and vice versa");
1419 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
1420 // or nonptr->ptr). For all the other types, the cast is okay if source and
1421 // destination bit widths are identical.
1422 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1423 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
1425 assert(SrcBitSize == DstBitSize && "BitCast requires types of same width");
1427 // It is common to ask for a bitcast of a value to its own type, handle this
1429 if (C->getType() == DstTy) return C;
1431 return getFoldedCast(Instruction::BitCast, C, DstTy);
1434 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1435 Constant *C1, Constant *C2) {
1436 // Check the operands for consistency first
1437 assert(Opcode >= Instruction::BinaryOpsBegin &&
1438 Opcode < Instruction::BinaryOpsEnd &&
1439 "Invalid opcode in binary constant expression");
1440 assert(C1->getType() == C2->getType() &&
1441 "Operand types in binary constant expression should match");
1443 if (ReqTy == C1->getType() || ReqTy == Type::Int1Ty)
1444 if (Constant *FC = ConstantFoldBinaryInstruction(
1445 getGlobalContext(), Opcode, C1, C2))
1446 return FC; // Fold a few common cases...
1448 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1449 ExprMapKeyType Key(Opcode, argVec);
1451 // Implicitly locked.
1452 return ExprConstants->getOrCreate(ReqTy, Key);
1455 Constant *ConstantExpr::getCompareTy(unsigned short predicate,
1456 Constant *C1, Constant *C2) {
1457 switch (predicate) {
1458 default: llvm_unreachable("Invalid CmpInst predicate");
1459 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
1460 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
1461 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
1462 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
1463 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
1464 case CmpInst::FCMP_TRUE:
1465 return getFCmp(predicate, C1, C2);
1467 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
1468 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
1469 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
1470 case CmpInst::ICMP_SLE:
1471 return getICmp(predicate, C1, C2);
1475 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
1476 // API compatibility: Adjust integer opcodes to floating-point opcodes.
1477 if (C1->getType()->isFPOrFPVector()) {
1478 if (Opcode == Instruction::Add) Opcode = Instruction::FAdd;
1479 else if (Opcode == Instruction::Sub) Opcode = Instruction::FSub;
1480 else if (Opcode == Instruction::Mul) Opcode = Instruction::FMul;
1484 case Instruction::Add:
1485 case Instruction::Sub:
1486 case Instruction::Mul:
1487 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1488 assert(C1->getType()->isIntOrIntVector() &&
1489 "Tried to create an integer operation on a non-integer type!");
1491 case Instruction::FAdd:
1492 case Instruction::FSub:
1493 case Instruction::FMul:
1494 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1495 assert(C1->getType()->isFPOrFPVector() &&
1496 "Tried to create a floating-point operation on a "
1497 "non-floating-point type!");
1499 case Instruction::UDiv:
1500 case Instruction::SDiv:
1501 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1502 assert(C1->getType()->isIntOrIntVector() &&
1503 "Tried to create an arithmetic operation on a non-arithmetic type!");
1505 case Instruction::FDiv:
1506 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1507 assert(C1->getType()->isFPOrFPVector() &&
1508 "Tried to create an arithmetic operation on a non-arithmetic type!");
1510 case Instruction::URem:
1511 case Instruction::SRem:
1512 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1513 assert(C1->getType()->isIntOrIntVector() &&
1514 "Tried to create an arithmetic operation on a non-arithmetic type!");
1516 case Instruction::FRem:
1517 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1518 assert(C1->getType()->isFPOrFPVector() &&
1519 "Tried to create an arithmetic operation on a non-arithmetic type!");
1521 case Instruction::And:
1522 case Instruction::Or:
1523 case Instruction::Xor:
1524 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1525 assert(C1->getType()->isIntOrIntVector() &&
1526 "Tried to create a logical operation on a non-integral type!");
1528 case Instruction::Shl:
1529 case Instruction::LShr:
1530 case Instruction::AShr:
1531 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1532 assert(C1->getType()->isIntOrIntVector() &&
1533 "Tried to create a shift operation on a non-integer type!");
1540 return getTy(C1->getType(), Opcode, C1, C2);
1543 Constant *ConstantExpr::getCompare(unsigned short pred,
1544 Constant *C1, Constant *C2) {
1545 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1546 return getCompareTy(pred, C1, C2);
1549 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1550 Constant *V1, Constant *V2) {
1551 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
1553 if (ReqTy == V1->getType())
1554 if (Constant *SC = ConstantFoldSelectInstruction(
1555 getGlobalContext(), C, V1, V2))
1556 return SC; // Fold common cases
1558 std::vector<Constant*> argVec(3, C);
1561 ExprMapKeyType Key(Instruction::Select, argVec);
1563 // Implicitly locked.
1564 return ExprConstants->getOrCreate(ReqTy, Key);
1567 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1570 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs,
1572 cast<PointerType>(ReqTy)->getElementType() &&
1573 "GEP indices invalid!");
1575 if (Constant *FC = ConstantFoldGetElementPtr(
1576 getGlobalContext(), C, (Constant**)Idxs, NumIdx))
1577 return FC; // Fold a few common cases...
1579 assert(isa<PointerType>(C->getType()) &&
1580 "Non-pointer type for constant GetElementPtr expression");
1581 // Look up the constant in the table first to ensure uniqueness
1582 std::vector<Constant*> ArgVec;
1583 ArgVec.reserve(NumIdx+1);
1584 ArgVec.push_back(C);
1585 for (unsigned i = 0; i != NumIdx; ++i)
1586 ArgVec.push_back(cast<Constant>(Idxs[i]));
1587 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
1589 // Implicitly locked.
1590 return ExprConstants->getOrCreate(ReqTy, Key);
1593 Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
1595 // Get the result type of the getelementptr!
1597 GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx);
1598 assert(Ty && "GEP indices invalid!");
1599 unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
1600 return getGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx);
1603 Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
1605 return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
1610 ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1611 assert(LHS->getType() == RHS->getType());
1612 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
1613 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1615 if (Constant *FC = ConstantFoldCompareInstruction(
1616 getGlobalContext(),pred, LHS, RHS))
1617 return FC; // Fold a few common cases...
1619 // Look up the constant in the table first to ensure uniqueness
1620 std::vector<Constant*> ArgVec;
1621 ArgVec.push_back(LHS);
1622 ArgVec.push_back(RHS);
1623 // Get the key type with both the opcode and predicate
1624 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
1626 // Implicitly locked.
1627 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
1631 ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1632 assert(LHS->getType() == RHS->getType());
1633 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1635 if (Constant *FC = ConstantFoldCompareInstruction(
1636 getGlobalContext(), pred, LHS, RHS))
1637 return FC; // Fold a few common cases...
1639 // Look up the constant in the table first to ensure uniqueness
1640 std::vector<Constant*> ArgVec;
1641 ArgVec.push_back(LHS);
1642 ArgVec.push_back(RHS);
1643 // Get the key type with both the opcode and predicate
1644 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
1646 // Implicitly locked.
1647 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
1650 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
1652 if (Constant *FC = ConstantFoldExtractElementInstruction(
1653 getGlobalContext(), Val, Idx))
1654 return FC; // Fold a few common cases...
1655 // Look up the constant in the table first to ensure uniqueness
1656 std::vector<Constant*> ArgVec(1, Val);
1657 ArgVec.push_back(Idx);
1658 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
1660 // Implicitly locked.
1661 return ExprConstants->getOrCreate(ReqTy, Key);
1664 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
1665 assert(isa<VectorType>(Val->getType()) &&
1666 "Tried to create extractelement operation on non-vector type!");
1667 assert(Idx->getType() == Type::Int32Ty &&
1668 "Extractelement index must be i32 type!");
1669 return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
1673 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
1674 Constant *Elt, Constant *Idx) {
1675 if (Constant *FC = ConstantFoldInsertElementInstruction(
1676 getGlobalContext(), Val, Elt, Idx))
1677 return FC; // Fold a few common cases...
1678 // Look up the constant in the table first to ensure uniqueness
1679 std::vector<Constant*> ArgVec(1, Val);
1680 ArgVec.push_back(Elt);
1681 ArgVec.push_back(Idx);
1682 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
1684 // Implicitly locked.
1685 return ExprConstants->getOrCreate(ReqTy, Key);
1688 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1690 assert(isa<VectorType>(Val->getType()) &&
1691 "Tried to create insertelement operation on non-vector type!");
1692 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
1693 && "Insertelement types must match!");
1694 assert(Idx->getType() == Type::Int32Ty &&
1695 "Insertelement index must be i32 type!");
1696 return getInsertElementTy(Val->getType(), Val, Elt, Idx);
1699 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
1700 Constant *V2, Constant *Mask) {
1701 if (Constant *FC = ConstantFoldShuffleVectorInstruction(
1702 getGlobalContext(), V1, V2, Mask))
1703 return FC; // Fold a few common cases...
1704 // Look up the constant in the table first to ensure uniqueness
1705 std::vector<Constant*> ArgVec(1, V1);
1706 ArgVec.push_back(V2);
1707 ArgVec.push_back(Mask);
1708 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
1710 // Implicitly locked.
1711 return ExprConstants->getOrCreate(ReqTy, Key);
1714 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
1716 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1717 "Invalid shuffle vector constant expr operands!");
1719 unsigned NElts = cast<VectorType>(Mask->getType())->getNumElements();
1720 const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
1721 const Type *ShufTy = VectorType::get(EltTy, NElts);
1722 return getShuffleVectorTy(ShufTy, V1, V2, Mask);
1725 Constant *ConstantExpr::getInsertValueTy(const Type *ReqTy, Constant *Agg,
1727 const unsigned *Idxs, unsigned NumIdx) {
1728 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
1729 Idxs+NumIdx) == Val->getType() &&
1730 "insertvalue indices invalid!");
1731 assert(Agg->getType() == ReqTy &&
1732 "insertvalue type invalid!");
1733 assert(Agg->getType()->isFirstClassType() &&
1734 "Non-first-class type for constant InsertValue expression");
1735 Constant *FC = ConstantFoldInsertValueInstruction(
1736 getGlobalContext(), Agg, Val, Idxs, NumIdx);
1737 assert(FC && "InsertValue constant expr couldn't be folded!");
1741 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
1742 const unsigned *IdxList, unsigned NumIdx) {
1743 assert(Agg->getType()->isFirstClassType() &&
1744 "Tried to create insertelement operation on non-first-class type!");
1746 const Type *ReqTy = Agg->getType();
1749 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
1751 assert(ValTy == Val->getType() && "insertvalue indices invalid!");
1752 return getInsertValueTy(ReqTy, Agg, Val, IdxList, NumIdx);
1755 Constant *ConstantExpr::getExtractValueTy(const Type *ReqTy, Constant *Agg,
1756 const unsigned *Idxs, unsigned NumIdx) {
1757 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
1758 Idxs+NumIdx) == ReqTy &&
1759 "extractvalue indices invalid!");
1760 assert(Agg->getType()->isFirstClassType() &&
1761 "Non-first-class type for constant extractvalue expression");
1762 Constant *FC = ConstantFoldExtractValueInstruction(
1763 getGlobalContext(), Agg, Idxs, NumIdx);
1764 assert(FC && "ExtractValue constant expr couldn't be folded!");
1768 Constant *ConstantExpr::getExtractValue(Constant *Agg,
1769 const unsigned *IdxList, unsigned NumIdx) {
1770 assert(Agg->getType()->isFirstClassType() &&
1771 "Tried to create extractelement operation on non-first-class type!");
1774 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
1775 assert(ReqTy && "extractvalue indices invalid!");
1776 return getExtractValueTy(ReqTy, Agg, IdxList, NumIdx);
1779 // destroyConstant - Remove the constant from the constant table...
1781 void ConstantExpr::destroyConstant() {
1782 // Implicitly locked.
1783 ExprConstants->remove(this);
1784 destroyConstantImpl();
1787 const char *ConstantExpr::getOpcodeName() const {
1788 return Instruction::getOpcodeName(getOpcode());
1791 //===----------------------------------------------------------------------===//
1792 // replaceUsesOfWithOnConstant implementations
1794 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
1795 /// 'From' to be uses of 'To'. This must update the uniquing data structures
1798 /// Note that we intentionally replace all uses of From with To here. Consider
1799 /// a large array that uses 'From' 1000 times. By handling this case all here,
1800 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
1801 /// single invocation handles all 1000 uses. Handling them one at a time would
1802 /// work, but would be really slow because it would have to unique each updated
1804 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
1806 Constant *Replacement =
1807 getType()->getContext().replaceUsesOfWithOnConstant(this, From, To, U);
1809 if (!Replacement) return;
1811 // Otherwise, I do need to replace this with an existing value.
1812 assert(Replacement != this && "I didn't contain From!");
1814 // Everyone using this now uses the replacement.
1815 uncheckedReplaceAllUsesWith(Replacement);
1817 // Delete the old constant!
1821 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
1823 Constant* Replacement =
1824 getType()->getContext().replaceUsesOfWithOnConstant(this, From, To, U);
1825 if (!Replacement) return;
1827 // Everyone using this now uses the replacement.
1828 uncheckedReplaceAllUsesWith(Replacement);
1830 // Delete the old constant!
1834 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
1836 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1838 std::vector<Constant*> Values;
1839 Values.reserve(getNumOperands()); // Build replacement array...
1840 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1841 Constant *Val = getOperand(i);
1842 if (Val == From) Val = cast<Constant>(To);
1843 Values.push_back(Val);
1846 Constant *Replacement =
1847 getType()->getContext().getConstantVector(getType(), Values);
1848 assert(Replacement != this && "I didn't contain From!");
1850 // Everyone using this now uses the replacement.
1851 uncheckedReplaceAllUsesWith(Replacement);
1853 // Delete the old constant!
1857 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
1859 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
1860 Constant *To = cast<Constant>(ToV);
1862 Constant *Replacement = 0;
1863 if (getOpcode() == Instruction::GetElementPtr) {
1864 SmallVector<Constant*, 8> Indices;
1865 Constant *Pointer = getOperand(0);
1866 Indices.reserve(getNumOperands()-1);
1867 if (Pointer == From) Pointer = To;
1869 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1870 Constant *Val = getOperand(i);
1871 if (Val == From) Val = To;
1872 Indices.push_back(Val);
1874 Replacement = ConstantExpr::getGetElementPtr(Pointer,
1875 &Indices[0], Indices.size());
1876 } else if (getOpcode() == Instruction::ExtractValue) {
1877 Constant *Agg = getOperand(0);
1878 if (Agg == From) Agg = To;
1880 const SmallVector<unsigned, 4> &Indices = getIndices();
1881 Replacement = ConstantExpr::getExtractValue(Agg,
1882 &Indices[0], Indices.size());
1883 } else if (getOpcode() == Instruction::InsertValue) {
1884 Constant *Agg = getOperand(0);
1885 Constant *Val = getOperand(1);
1886 if (Agg == From) Agg = To;
1887 if (Val == From) Val = To;
1889 const SmallVector<unsigned, 4> &Indices = getIndices();
1890 Replacement = ConstantExpr::getInsertValue(Agg, Val,
1891 &Indices[0], Indices.size());
1892 } else if (isCast()) {
1893 assert(getOperand(0) == From && "Cast only has one use!");
1894 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
1895 } else if (getOpcode() == Instruction::Select) {
1896 Constant *C1 = getOperand(0);
1897 Constant *C2 = getOperand(1);
1898 Constant *C3 = getOperand(2);
1899 if (C1 == From) C1 = To;
1900 if (C2 == From) C2 = To;
1901 if (C3 == From) C3 = To;
1902 Replacement = ConstantExpr::getSelect(C1, C2, C3);
1903 } else if (getOpcode() == Instruction::ExtractElement) {
1904 Constant *C1 = getOperand(0);
1905 Constant *C2 = getOperand(1);
1906 if (C1 == From) C1 = To;
1907 if (C2 == From) C2 = To;
1908 Replacement = ConstantExpr::getExtractElement(C1, C2);
1909 } else if (getOpcode() == Instruction::InsertElement) {
1910 Constant *C1 = getOperand(0);
1911 Constant *C2 = getOperand(1);
1912 Constant *C3 = getOperand(1);
1913 if (C1 == From) C1 = To;
1914 if (C2 == From) C2 = To;
1915 if (C3 == From) C3 = To;
1916 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
1917 } else if (getOpcode() == Instruction::ShuffleVector) {
1918 Constant *C1 = getOperand(0);
1919 Constant *C2 = getOperand(1);
1920 Constant *C3 = getOperand(2);
1921 if (C1 == From) C1 = To;
1922 if (C2 == From) C2 = To;
1923 if (C3 == From) C3 = To;
1924 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
1925 } else if (isCompare()) {
1926 Constant *C1 = getOperand(0);
1927 Constant *C2 = getOperand(1);
1928 if (C1 == From) C1 = To;
1929 if (C2 == From) C2 = To;
1930 if (getOpcode() == Instruction::ICmp)
1931 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
1933 assert(getOpcode() == Instruction::FCmp);
1934 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
1936 } else if (getNumOperands() == 2) {
1937 Constant *C1 = getOperand(0);
1938 Constant *C2 = getOperand(1);
1939 if (C1 == From) C1 = To;
1940 if (C2 == From) C2 = To;
1941 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
1943 llvm_unreachable("Unknown ConstantExpr type!");
1947 assert(Replacement != this && "I didn't contain From!");
1949 // Everyone using this now uses the replacement.
1950 uncheckedReplaceAllUsesWith(Replacement);
1952 // Delete the old constant!
1956 void MDNode::replaceElement(Value *From, Value *To) {
1957 SmallVector<Value*, 4> Values;
1958 Values.reserve(getNumElements()); // Build replacement array...
1959 for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
1960 Value *Val = getElement(i);
1961 if (Val == From) Val = To;
1962 Values.push_back(Val);
1965 MDNode *Replacement =
1966 getType()->getContext().getMDNode(&Values[0], Values.size());
1967 assert(Replacement != this && "I didn't contain From!");
1969 uncheckedReplaceAllUsesWith(Replacement);