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/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 // Constructor to create a '0' constant of arbitrary type...
44 static const uint64_t zero[2] = {0, 0};
45 Constant* Constant::getNullValue(const Type* Ty) {
46 switch (Ty->getTypeID()) {
47 case Type::IntegerTyID:
48 return ConstantInt::get(Ty, 0);
50 return ConstantFP::get(Ty->getContext(), APFloat(APInt(32, 0)));
51 case Type::DoubleTyID:
52 return ConstantFP::get(Ty->getContext(), APFloat(APInt(64, 0)));
53 case Type::X86_FP80TyID:
54 return ConstantFP::get(Ty->getContext(), APFloat(APInt(80, 2, zero)));
56 return ConstantFP::get(Ty->getContext(),
57 APFloat(APInt(128, 2, zero), true));
58 case Type::PPC_FP128TyID:
59 return ConstantFP::get(Ty->getContext(), APFloat(APInt(128, 2, zero)));
60 case Type::PointerTyID:
61 return ConstantPointerNull::get(cast<PointerType>(Ty));
62 case Type::StructTyID:
64 case Type::VectorTyID:
65 return ConstantAggregateZero::get(Ty);
67 // Function, Label, or Opaque type?
68 assert(!"Cannot create a null constant of that type!");
73 Constant* Constant::getIntegerValue(const Type* Ty, const APInt &V) {
74 const Type *ScalarTy = Ty->getScalarType();
76 // Create the base integer constant.
77 Constant *C = ConstantInt::get(Ty->getContext(), V);
79 // Convert an integer to a pointer, if necessary.
80 if (const PointerType *PTy = dyn_cast<PointerType>(ScalarTy))
81 C = ConstantExpr::getIntToPtr(C, PTy);
83 // Broadcast a scalar to a vector, if necessary.
84 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
85 C = ConstantVector::get(std::vector<Constant *>(VTy->getNumElements(), C));
90 Constant* Constant::getAllOnesValue(const Type* Ty) {
91 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
92 return ConstantInt::get(Ty->getContext(),
93 APInt::getAllOnesValue(ITy->getBitWidth()));
95 std::vector<Constant*> Elts;
96 const VectorType* VTy = cast<VectorType>(Ty);
97 Elts.resize(VTy->getNumElements(), getAllOnesValue(VTy->getElementType()));
98 assert(Elts[0] && "Not a vector integer type!");
99 return cast<ConstantVector>(ConstantVector::get(Elts));
102 void Constant::destroyConstantImpl() {
103 // When a Constant is destroyed, there may be lingering
104 // references to the constant by other constants in the constant pool. These
105 // constants are implicitly dependent on the module that is being deleted,
106 // but they don't know that. Because we only find out when the CPV is
107 // deleted, we must now notify all of our users (that should only be
108 // Constants) that they are, in fact, invalid now and should be deleted.
110 while (!use_empty()) {
111 Value *V = use_back();
112 #ifndef NDEBUG // Only in -g mode...
113 if (!isa<Constant>(V))
114 DOUT << "While deleting: " << *this
115 << "\n\nUse still stuck around after Def is destroyed: "
118 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
119 Constant *CV = cast<Constant>(V);
120 CV->destroyConstant();
122 // The constant should remove itself from our use list...
123 assert((use_empty() || use_back() != V) && "Constant not removed!");
126 // Value has no outstanding references it is safe to delete it now...
130 /// canTrap - Return true if evaluation of this constant could trap. This is
131 /// true for things like constant expressions that could divide by zero.
132 bool Constant::canTrap() const {
133 assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
134 // The only thing that could possibly trap are constant exprs.
135 const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
136 if (!CE) return false;
138 // ConstantExpr traps if any operands can trap.
139 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
140 if (getOperand(i)->canTrap())
143 // Otherwise, only specific operations can trap.
144 switch (CE->getOpcode()) {
147 case Instruction::UDiv:
148 case Instruction::SDiv:
149 case Instruction::FDiv:
150 case Instruction::URem:
151 case Instruction::SRem:
152 case Instruction::FRem:
153 // Div and rem can trap if the RHS is not known to be non-zero.
154 if (!isa<ConstantInt>(getOperand(1)) || getOperand(1)->isNullValue())
161 /// getRelocationInfo - This method classifies the entry according to
162 /// whether or not it may generate a relocation entry. This must be
163 /// conservative, so if it might codegen to a relocatable entry, it should say
164 /// so. The return values are:
166 /// NoRelocation: This constant pool entry is guaranteed to never have a
167 /// relocation applied to it (because it holds a simple constant like
169 /// LocalRelocation: This entry has relocations, but the entries are
170 /// guaranteed to be resolvable by the static linker, so the dynamic
171 /// linker will never see them.
172 /// GlobalRelocations: This entry may have arbitrary relocations.
174 /// FIXME: This really should not be in VMCore.
175 Constant::PossibleRelocationsTy Constant::getRelocationInfo() const {
176 if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
177 if (GV->hasLocalLinkage() || GV->hasHiddenVisibility())
178 return LocalRelocation; // Local to this file/library.
179 return GlobalRelocations; // Global reference.
182 PossibleRelocationsTy Result = NoRelocation;
183 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
184 Result = std::max(Result, getOperand(i)->getRelocationInfo());
190 /// getVectorElements - This method, which is only valid on constant of vector
191 /// type, returns the elements of the vector in the specified smallvector.
192 /// This handles breaking down a vector undef into undef elements, etc. For
193 /// constant exprs and other cases we can't handle, we return an empty vector.
194 void Constant::getVectorElements(LLVMContext &Context,
195 SmallVectorImpl<Constant*> &Elts) const {
196 assert(isa<VectorType>(getType()) && "Not a vector constant!");
198 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this)) {
199 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i)
200 Elts.push_back(CV->getOperand(i));
204 const VectorType *VT = cast<VectorType>(getType());
205 if (isa<ConstantAggregateZero>(this)) {
206 Elts.assign(VT->getNumElements(),
207 Constant::getNullValue(VT->getElementType()));
211 if (isa<UndefValue>(this)) {
212 Elts.assign(VT->getNumElements(), UndefValue::get(VT->getElementType()));
216 // Unknown type, must be constant expr etc.
221 //===----------------------------------------------------------------------===//
223 //===----------------------------------------------------------------------===//
225 ConstantInt::ConstantInt(const IntegerType *Ty, const APInt& V)
226 : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
227 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
230 ConstantInt* ConstantInt::getTrue(LLVMContext &Context) {
231 LLVMContextImpl *pImpl = Context.pImpl;
232 sys::SmartScopedWriter<true>(pImpl->ConstantsLock);
233 if (pImpl->TheTrueVal)
234 return pImpl->TheTrueVal;
236 return (pImpl->TheTrueVal = ConstantInt::get(IntegerType::get(1), 1));
239 ConstantInt* ConstantInt::getFalse(LLVMContext &Context) {
240 LLVMContextImpl *pImpl = Context.pImpl;
241 sys::SmartScopedWriter<true>(pImpl->ConstantsLock);
242 if (pImpl->TheFalseVal)
243 return pImpl->TheFalseVal;
245 return (pImpl->TheFalseVal = ConstantInt::get(IntegerType::get(1), 0));
249 // Get a ConstantInt from an APInt. Note that the value stored in the DenseMap
250 // as the key, is a DenseMapAPIntKeyInfo::KeyTy which has provided the
251 // operator== and operator!= to ensure that the DenseMap doesn't attempt to
252 // compare APInt's of different widths, which would violate an APInt class
253 // invariant which generates an assertion.
254 ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt& V) {
255 // Get the corresponding integer type for the bit width of the value.
256 const IntegerType *ITy = IntegerType::get(V.getBitWidth());
257 // get an existing value or the insertion position
258 DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
260 Context.pImpl->ConstantsLock.reader_acquire();
261 ConstantInt *&Slot = Context.pImpl->IntConstants[Key];
262 Context.pImpl->ConstantsLock.reader_release();
265 sys::SmartScopedWriter<true> Writer(Context.pImpl->ConstantsLock);
266 ConstantInt *&NewSlot = Context.pImpl->IntConstants[Key];
268 NewSlot = new ConstantInt(ITy, V);
277 Constant* ConstantInt::get(const Type* Ty, uint64_t V, bool isSigned) {
278 Constant *C = get(cast<IntegerType>(Ty->getScalarType()),
281 // For vectors, broadcast the value.
282 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
283 return ConstantVector::get(
284 std::vector<Constant *>(VTy->getNumElements(), C));
289 ConstantInt* ConstantInt::get(const IntegerType* Ty, uint64_t V,
291 return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned));
294 ConstantInt* ConstantInt::getSigned(const IntegerType* Ty, int64_t V) {
295 return get(Ty, V, true);
298 Constant *ConstantInt::getSigned(const Type *Ty, int64_t V) {
299 return get(Ty, V, true);
302 Constant* ConstantInt::get(const Type* Ty, const APInt& V) {
303 ConstantInt *C = get(Ty->getContext(), V);
304 assert(C->getType() == Ty->getScalarType() &&
305 "ConstantInt type doesn't match the type implied by its value!");
307 // For vectors, broadcast the value.
308 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
309 return ConstantVector::get(
310 std::vector<Constant *>(VTy->getNumElements(), C));
315 //===----------------------------------------------------------------------===//
317 //===----------------------------------------------------------------------===//
319 static const fltSemantics *TypeToFloatSemantics(const Type *Ty) {
320 if (Ty == Type::FloatTy)
321 return &APFloat::IEEEsingle;
322 if (Ty == Type::DoubleTy)
323 return &APFloat::IEEEdouble;
324 if (Ty == Type::X86_FP80Ty)
325 return &APFloat::x87DoubleExtended;
326 else if (Ty == Type::FP128Ty)
327 return &APFloat::IEEEquad;
329 assert(Ty == Type::PPC_FP128Ty && "Unknown FP format");
330 return &APFloat::PPCDoubleDouble;
333 /// get() - This returns a constant fp for the specified value in the
334 /// specified type. This should only be used for simple constant values like
335 /// 2.0/1.0 etc, that are known-valid both as double and as the target format.
336 Constant* ConstantFP::get(const Type* Ty, double V) {
337 LLVMContext &Context = Ty->getContext();
341 FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
342 APFloat::rmNearestTiesToEven, &ignored);
343 Constant *C = get(Context, FV);
345 // For vectors, broadcast the value.
346 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
347 return ConstantVector::get(
348 std::vector<Constant *>(VTy->getNumElements(), C));
353 ConstantFP* ConstantFP::getNegativeZero(const Type* Ty) {
354 LLVMContext &Context = Ty->getContext();
355 APFloat apf = cast <ConstantFP>(Constant::getNullValue(Ty))->getValueAPF();
357 return get(Context, apf);
361 Constant* ConstantFP::getZeroValueForNegation(const Type* Ty) {
362 if (const VectorType *PTy = dyn_cast<VectorType>(Ty))
363 if (PTy->getElementType()->isFloatingPoint()) {
364 std::vector<Constant*> zeros(PTy->getNumElements(),
365 getNegativeZero(PTy->getElementType()));
366 return ConstantVector::get(PTy, zeros);
369 if (Ty->isFloatingPoint())
370 return getNegativeZero(Ty);
372 return Constant::getNullValue(Ty);
376 // ConstantFP accessors.
377 ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
378 DenseMapAPFloatKeyInfo::KeyTy Key(V);
380 LLVMContextImpl* pImpl = Context.pImpl;
382 pImpl->ConstantsLock.reader_acquire();
383 ConstantFP *&Slot = pImpl->FPConstants[Key];
384 pImpl->ConstantsLock.reader_release();
387 sys::SmartScopedWriter<true> Writer(pImpl->ConstantsLock);
388 ConstantFP *&NewSlot = pImpl->FPConstants[Key];
391 if (&V.getSemantics() == &APFloat::IEEEsingle)
393 else if (&V.getSemantics() == &APFloat::IEEEdouble)
395 else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
396 Ty = Type::X86_FP80Ty;
397 else if (&V.getSemantics() == &APFloat::IEEEquad)
400 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble &&
401 "Unknown FP format");
402 Ty = Type::PPC_FP128Ty;
404 NewSlot = new ConstantFP(Ty, V);
413 ConstantFP::ConstantFP(const Type *Ty, const APFloat& V)
414 : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
415 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
419 bool ConstantFP::isNullValue() const {
420 return Val.isZero() && !Val.isNegative();
423 bool ConstantFP::isExactlyValue(const APFloat& V) const {
424 return Val.bitwiseIsEqual(V);
427 //===----------------------------------------------------------------------===//
428 // ConstantXXX Classes
429 //===----------------------------------------------------------------------===//
432 ConstantArray::ConstantArray(const ArrayType *T,
433 const std::vector<Constant*> &V)
434 : Constant(T, ConstantArrayVal,
435 OperandTraits<ConstantArray>::op_end(this) - V.size(),
437 assert(V.size() == T->getNumElements() &&
438 "Invalid initializer vector for constant array");
439 Use *OL = OperandList;
440 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
443 assert((C->getType() == T->getElementType() ||
445 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
446 "Initializer for array element doesn't match array element type!");
451 Constant *ConstantArray::get(const ArrayType *Ty,
452 const std::vector<Constant*> &V) {
453 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
454 // If this is an all-zero array, return a ConstantAggregateZero object
457 if (!C->isNullValue()) {
458 // Implicitly locked.
459 return pImpl->ArrayConstants.getOrCreate(Ty, V);
461 for (unsigned i = 1, e = V.size(); i != e; ++i)
463 // Implicitly locked.
464 return pImpl->ArrayConstants.getOrCreate(Ty, V);
468 return ConstantAggregateZero::get(Ty);
472 Constant* ConstantArray::get(const ArrayType* T, Constant* const* Vals,
474 // FIXME: make this the primary ctor method.
475 return get(T, std::vector<Constant*>(Vals, Vals+NumVals));
478 /// ConstantArray::get(const string&) - Return an array that is initialized to
479 /// contain the specified string. If length is zero then a null terminator is
480 /// added to the specified string so that it may be used in a natural way.
481 /// Otherwise, the length parameter specifies how much of the string to use
482 /// and it won't be null terminated.
484 Constant* ConstantArray::get(const StringRef &Str, bool AddNull) {
485 std::vector<Constant*> ElementVals;
486 for (unsigned i = 0; i < Str.size(); ++i)
487 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, Str[i]));
489 // Add a null terminator to the string...
491 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, 0));
494 ArrayType *ATy = ArrayType::get(Type::Int8Ty, ElementVals.size());
495 return get(ATy, ElementVals);
500 ConstantStruct::ConstantStruct(const StructType *T,
501 const std::vector<Constant*> &V)
502 : Constant(T, ConstantStructVal,
503 OperandTraits<ConstantStruct>::op_end(this) - V.size(),
505 assert(V.size() == T->getNumElements() &&
506 "Invalid initializer vector for constant structure");
507 Use *OL = OperandList;
508 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
511 assert((C->getType() == T->getElementType(I-V.begin()) ||
512 ((T->getElementType(I-V.begin())->isAbstract() ||
513 C->getType()->isAbstract()) &&
514 T->getElementType(I-V.begin())->getTypeID() ==
515 C->getType()->getTypeID())) &&
516 "Initializer for struct element doesn't match struct element type!");
521 // ConstantStruct accessors.
522 Constant* ConstantStruct::get(const StructType* T,
523 const std::vector<Constant*>& V) {
524 LLVMContextImpl* pImpl = T->getContext().pImpl;
526 // Create a ConstantAggregateZero value if all elements are zeros...
527 for (unsigned i = 0, e = V.size(); i != e; ++i)
528 if (!V[i]->isNullValue())
529 // Implicitly locked.
530 return pImpl->StructConstants.getOrCreate(T, V);
532 return ConstantAggregateZero::get(T);
535 Constant* ConstantStruct::get(const std::vector<Constant*>& V, bool packed) {
536 std::vector<const Type*> StructEls;
537 StructEls.reserve(V.size());
538 for (unsigned i = 0, e = V.size(); i != e; ++i)
539 StructEls.push_back(V[i]->getType());
540 return get(StructType::get(StructEls, packed), V);
543 Constant* ConstantStruct::get(Constant* const *Vals, unsigned NumVals,
545 // FIXME: make this the primary ctor method.
546 return get(std::vector<Constant*>(Vals, Vals+NumVals), Packed);
549 ConstantVector::ConstantVector(const VectorType *T,
550 const std::vector<Constant*> &V)
551 : Constant(T, ConstantVectorVal,
552 OperandTraits<ConstantVector>::op_end(this) - V.size(),
554 Use *OL = OperandList;
555 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
558 assert((C->getType() == T->getElementType() ||
560 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
561 "Initializer for vector element doesn't match vector element type!");
566 // ConstantVector accessors.
567 Constant* ConstantVector::get(const VectorType* T,
568 const std::vector<Constant*>& V) {
569 assert(!V.empty() && "Vectors can't be empty");
570 LLVMContext &Context = T->getContext();
571 LLVMContextImpl *pImpl = Context.pImpl;
573 // If this is an all-undef or alll-zero vector, return a
574 // ConstantAggregateZero or UndefValue.
576 bool isZero = C->isNullValue();
577 bool isUndef = isa<UndefValue>(C);
579 if (isZero || isUndef) {
580 for (unsigned i = 1, e = V.size(); i != e; ++i)
582 isZero = isUndef = false;
588 return ConstantAggregateZero::get(T);
590 return UndefValue::get(T);
592 // Implicitly locked.
593 return pImpl->VectorConstants.getOrCreate(T, V);
596 Constant* ConstantVector::get(const std::vector<Constant*>& V) {
597 assert(!V.empty() && "Cannot infer type if V is empty");
598 return get(VectorType::get(V.front()->getType(),V.size()), V);
601 Constant* ConstantVector::get(Constant* const* Vals, unsigned NumVals) {
602 // FIXME: make this the primary ctor method.
603 return get(std::vector<Constant*>(Vals, Vals+NumVals));
606 // Utility function for determining if a ConstantExpr is a CastOp or not. This
607 // can't be inline because we don't want to #include Instruction.h into
609 bool ConstantExpr::isCast() const {
610 return Instruction::isCast(getOpcode());
613 bool ConstantExpr::isCompare() const {
614 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
617 bool ConstantExpr::hasIndices() const {
618 return getOpcode() == Instruction::ExtractValue ||
619 getOpcode() == Instruction::InsertValue;
622 const SmallVector<unsigned, 4> &ConstantExpr::getIndices() const {
623 if (const ExtractValueConstantExpr *EVCE =
624 dyn_cast<ExtractValueConstantExpr>(this))
625 return EVCE->Indices;
627 return cast<InsertValueConstantExpr>(this)->Indices;
630 unsigned ConstantExpr::getPredicate() const {
631 assert(getOpcode() == Instruction::FCmp ||
632 getOpcode() == Instruction::ICmp);
633 return ((const CompareConstantExpr*)this)->predicate;
636 /// getWithOperandReplaced - Return a constant expression identical to this
637 /// one, but with the specified operand set to the specified value.
639 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
640 assert(OpNo < getNumOperands() && "Operand num is out of range!");
641 assert(Op->getType() == getOperand(OpNo)->getType() &&
642 "Replacing operand with value of different type!");
643 if (getOperand(OpNo) == Op)
644 return const_cast<ConstantExpr*>(this);
646 Constant *Op0, *Op1, *Op2;
647 switch (getOpcode()) {
648 case Instruction::Trunc:
649 case Instruction::ZExt:
650 case Instruction::SExt:
651 case Instruction::FPTrunc:
652 case Instruction::FPExt:
653 case Instruction::UIToFP:
654 case Instruction::SIToFP:
655 case Instruction::FPToUI:
656 case Instruction::FPToSI:
657 case Instruction::PtrToInt:
658 case Instruction::IntToPtr:
659 case Instruction::BitCast:
660 return ConstantExpr::getCast(getOpcode(), Op, getType());
661 case Instruction::Select:
662 Op0 = (OpNo == 0) ? Op : getOperand(0);
663 Op1 = (OpNo == 1) ? Op : getOperand(1);
664 Op2 = (OpNo == 2) ? Op : getOperand(2);
665 return ConstantExpr::getSelect(Op0, Op1, Op2);
666 case Instruction::InsertElement:
667 Op0 = (OpNo == 0) ? Op : getOperand(0);
668 Op1 = (OpNo == 1) ? Op : getOperand(1);
669 Op2 = (OpNo == 2) ? Op : getOperand(2);
670 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
671 case Instruction::ExtractElement:
672 Op0 = (OpNo == 0) ? Op : getOperand(0);
673 Op1 = (OpNo == 1) ? Op : getOperand(1);
674 return ConstantExpr::getExtractElement(Op0, Op1);
675 case Instruction::ShuffleVector:
676 Op0 = (OpNo == 0) ? Op : getOperand(0);
677 Op1 = (OpNo == 1) ? Op : getOperand(1);
678 Op2 = (OpNo == 2) ? Op : getOperand(2);
679 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
680 case Instruction::GetElementPtr: {
681 SmallVector<Constant*, 8> Ops;
682 Ops.resize(getNumOperands()-1);
683 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
684 Ops[i-1] = getOperand(i);
686 return ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
688 return ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
691 assert(getNumOperands() == 2 && "Must be binary operator?");
692 Op0 = (OpNo == 0) ? Op : getOperand(0);
693 Op1 = (OpNo == 1) ? Op : getOperand(1);
694 return ConstantExpr::get(getOpcode(), Op0, Op1);
698 /// getWithOperands - This returns the current constant expression with the
699 /// operands replaced with the specified values. The specified operands must
700 /// match count and type with the existing ones.
701 Constant *ConstantExpr::
702 getWithOperands(Constant* const *Ops, unsigned NumOps) const {
703 assert(NumOps == getNumOperands() && "Operand count mismatch!");
704 bool AnyChange = false;
705 for (unsigned i = 0; i != NumOps; ++i) {
706 assert(Ops[i]->getType() == getOperand(i)->getType() &&
707 "Operand type mismatch!");
708 AnyChange |= Ops[i] != getOperand(i);
710 if (!AnyChange) // No operands changed, return self.
711 return const_cast<ConstantExpr*>(this);
713 switch (getOpcode()) {
714 case Instruction::Trunc:
715 case Instruction::ZExt:
716 case Instruction::SExt:
717 case Instruction::FPTrunc:
718 case Instruction::FPExt:
719 case Instruction::UIToFP:
720 case Instruction::SIToFP:
721 case Instruction::FPToUI:
722 case Instruction::FPToSI:
723 case Instruction::PtrToInt:
724 case Instruction::IntToPtr:
725 case Instruction::BitCast:
726 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
727 case Instruction::Select:
728 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
729 case Instruction::InsertElement:
730 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
731 case Instruction::ExtractElement:
732 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
733 case Instruction::ShuffleVector:
734 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
735 case Instruction::GetElementPtr:
736 return ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], NumOps-1);
737 case Instruction::ICmp:
738 case Instruction::FCmp:
739 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
741 assert(getNumOperands() == 2 && "Must be binary operator?");
742 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
747 //===----------------------------------------------------------------------===//
748 // isValueValidForType implementations
750 bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
751 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
752 if (Ty == Type::Int1Ty)
753 return Val == 0 || Val == 1;
755 return true; // always true, has to fit in largest type
756 uint64_t Max = (1ll << NumBits) - 1;
760 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
761 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
762 if (Ty == Type::Int1Ty)
763 return Val == 0 || Val == 1 || Val == -1;
765 return true; // always true, has to fit in largest type
766 int64_t Min = -(1ll << (NumBits-1));
767 int64_t Max = (1ll << (NumBits-1)) - 1;
768 return (Val >= Min && Val <= Max);
771 bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
772 // convert modifies in place, so make a copy.
773 APFloat Val2 = APFloat(Val);
775 switch (Ty->getTypeID()) {
777 return false; // These can't be represented as floating point!
779 // FIXME rounding mode needs to be more flexible
780 case Type::FloatTyID: {
781 if (&Val2.getSemantics() == &APFloat::IEEEsingle)
783 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
786 case Type::DoubleTyID: {
787 if (&Val2.getSemantics() == &APFloat::IEEEsingle ||
788 &Val2.getSemantics() == &APFloat::IEEEdouble)
790 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
793 case Type::X86_FP80TyID:
794 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
795 &Val2.getSemantics() == &APFloat::IEEEdouble ||
796 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
797 case Type::FP128TyID:
798 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
799 &Val2.getSemantics() == &APFloat::IEEEdouble ||
800 &Val2.getSemantics() == &APFloat::IEEEquad;
801 case Type::PPC_FP128TyID:
802 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
803 &Val2.getSemantics() == &APFloat::IEEEdouble ||
804 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
808 //===----------------------------------------------------------------------===//
809 // Factory Function Implementation
811 static char getValType(ConstantAggregateZero *CPZ) { return 0; }
813 ConstantAggregateZero* ConstantAggregateZero::get(const Type* Ty) {
814 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) &&
815 "Cannot create an aggregate zero of non-aggregate type!");
817 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
818 // Implicitly locked.
819 return pImpl->AggZeroConstants.getOrCreate(Ty, 0);
822 /// destroyConstant - Remove the constant from the constant table...
824 void ConstantAggregateZero::destroyConstant() {
825 // Implicitly locked.
826 getType()->getContext().pImpl->AggZeroConstants.remove(this);
827 destroyConstantImpl();
830 /// destroyConstant - Remove the constant from the constant table...
832 void ConstantArray::destroyConstant() {
833 // Implicitly locked.
834 getType()->getContext().pImpl->ArrayConstants.remove(this);
835 destroyConstantImpl();
838 /// isString - This method returns true if the array is an array of i8, and
839 /// if the elements of the array are all ConstantInt's.
840 bool ConstantArray::isString() const {
841 // Check the element type for i8...
842 if (getType()->getElementType() != Type::Int8Ty)
844 // Check the elements to make sure they are all integers, not constant
846 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
847 if (!isa<ConstantInt>(getOperand(i)))
852 /// isCString - This method returns true if the array is a string (see
853 /// isString) and it ends in a null byte \\0 and does not contains any other
854 /// null bytes except its terminator.
855 bool ConstantArray::isCString() const {
856 // Check the element type for i8...
857 if (getType()->getElementType() != Type::Int8Ty)
860 // Last element must be a null.
861 if (!getOperand(getNumOperands()-1)->isNullValue())
863 // Other elements must be non-null integers.
864 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
865 if (!isa<ConstantInt>(getOperand(i)))
867 if (getOperand(i)->isNullValue())
874 /// getAsString - If the sub-element type of this array is i8
875 /// then this method converts the array to an std::string and returns it.
876 /// Otherwise, it asserts out.
878 std::string ConstantArray::getAsString() const {
879 assert(isString() && "Not a string!");
881 Result.reserve(getNumOperands());
882 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
883 Result.push_back((char)cast<ConstantInt>(getOperand(i))->getZExtValue());
888 //---- ConstantStruct::get() implementation...
895 // destroyConstant - Remove the constant from the constant table...
897 void ConstantStruct::destroyConstant() {
898 // Implicitly locked.
899 getType()->getContext().pImpl->StructConstants.remove(this);
900 destroyConstantImpl();
903 // destroyConstant - Remove the constant from the constant table...
905 void ConstantVector::destroyConstant() {
906 // Implicitly locked.
907 getType()->getContext().pImpl->VectorConstants.remove(this);
908 destroyConstantImpl();
911 /// This function will return true iff every element in this vector constant
912 /// is set to all ones.
913 /// @returns true iff this constant's emements are all set to all ones.
914 /// @brief Determine if the value is all ones.
915 bool ConstantVector::isAllOnesValue() const {
916 // Check out first element.
917 const Constant *Elt = getOperand(0);
918 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
919 if (!CI || !CI->isAllOnesValue()) return false;
920 // Then make sure all remaining elements point to the same value.
921 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
922 if (getOperand(I) != Elt) return false;
927 /// getSplatValue - If this is a splat constant, where all of the
928 /// elements have the same value, return that value. Otherwise return null.
929 Constant *ConstantVector::getSplatValue() {
930 // Check out first element.
931 Constant *Elt = getOperand(0);
932 // Then make sure all remaining elements point to the same value.
933 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
934 if (getOperand(I) != Elt) return 0;
938 //---- ConstantPointerNull::get() implementation...
941 static char getValType(ConstantPointerNull *) {
946 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
947 // Implicitly locked.
948 return Ty->getContext().pImpl->NullPtrConstants.getOrCreate(Ty, 0);
951 // destroyConstant - Remove the constant from the constant table...
953 void ConstantPointerNull::destroyConstant() {
954 // Implicitly locked.
955 getType()->getContext().pImpl->NullPtrConstants.remove(this);
956 destroyConstantImpl();
960 //---- UndefValue::get() implementation...
963 static char getValType(UndefValue *) {
967 UndefValue *UndefValue::get(const Type *Ty) {
968 // Implicitly locked.
969 return Ty->getContext().pImpl->UndefValueConstants.getOrCreate(Ty, 0);
972 // destroyConstant - Remove the constant from the constant table.
974 void UndefValue::destroyConstant() {
975 // Implicitly locked.
976 getType()->getContext().pImpl->UndefValueConstants.remove(this);
977 destroyConstantImpl();
980 //---- ConstantExpr::get() implementations...
983 static ExprMapKeyType getValType(ConstantExpr *CE) {
984 std::vector<Constant*> Operands;
985 Operands.reserve(CE->getNumOperands());
986 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
987 Operands.push_back(cast<Constant>(CE->getOperand(i)));
988 return ExprMapKeyType(CE->getOpcode(), Operands,
989 CE->isCompare() ? CE->getPredicate() : 0,
991 CE->getIndices() : SmallVector<unsigned, 4>());
994 /// This is a utility function to handle folding of casts and lookup of the
995 /// cast in the ExprConstants map. It is used by the various get* methods below.
996 static inline Constant *getFoldedCast(
997 Instruction::CastOps opc, Constant *C, const Type *Ty) {
998 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
999 // Fold a few common cases
1000 if (Constant *FC = ConstantFoldCastInstruction(Ty->getContext(), opc, C, Ty))
1003 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
1005 // Look up the constant in the table first to ensure uniqueness
1006 std::vector<Constant*> argVec(1, C);
1007 ExprMapKeyType Key(opc, argVec);
1009 // Implicitly locked.
1010 return pImpl->ExprConstants.getOrCreate(Ty, Key);
1013 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1014 Instruction::CastOps opc = Instruction::CastOps(oc);
1015 assert(Instruction::isCast(opc) && "opcode out of range");
1016 assert(C && Ty && "Null arguments to getCast");
1017 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1021 llvm_unreachable("Invalid cast opcode");
1023 case Instruction::Trunc: return getTrunc(C, Ty);
1024 case Instruction::ZExt: return getZExt(C, Ty);
1025 case Instruction::SExt: return getSExt(C, Ty);
1026 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1027 case Instruction::FPExt: return getFPExtend(C, Ty);
1028 case Instruction::UIToFP: return getUIToFP(C, Ty);
1029 case Instruction::SIToFP: return getSIToFP(C, Ty);
1030 case Instruction::FPToUI: return getFPToUI(C, Ty);
1031 case Instruction::FPToSI: return getFPToSI(C, Ty);
1032 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1033 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1034 case Instruction::BitCast: return getBitCast(C, Ty);
1039 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1040 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1041 return getCast(Instruction::BitCast, C, Ty);
1042 return getCast(Instruction::ZExt, C, Ty);
1045 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1046 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1047 return getCast(Instruction::BitCast, C, Ty);
1048 return getCast(Instruction::SExt, C, Ty);
1051 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1052 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1053 return getCast(Instruction::BitCast, C, Ty);
1054 return getCast(Instruction::Trunc, C, Ty);
1057 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1058 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1059 assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
1061 if (Ty->isInteger())
1062 return getCast(Instruction::PtrToInt, S, Ty);
1063 return getCast(Instruction::BitCast, S, Ty);
1066 Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
1068 assert(C->getType()->isIntOrIntVector() &&
1069 Ty->isIntOrIntVector() && "Invalid cast");
1070 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1071 unsigned DstBits = Ty->getScalarSizeInBits();
1072 Instruction::CastOps opcode =
1073 (SrcBits == DstBits ? Instruction::BitCast :
1074 (SrcBits > DstBits ? Instruction::Trunc :
1075 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1076 return getCast(opcode, C, Ty);
1079 Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1080 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1082 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1083 unsigned DstBits = Ty->getScalarSizeInBits();
1084 if (SrcBits == DstBits)
1085 return C; // Avoid a useless cast
1086 Instruction::CastOps opcode =
1087 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1088 return getCast(opcode, C, Ty);
1091 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
1093 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1094 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1096 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1097 assert(C->getType()->isIntOrIntVector() && "Trunc operand must be integer");
1098 assert(Ty->isIntOrIntVector() && "Trunc produces only integral");
1099 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1100 "SrcTy must be larger than DestTy for Trunc!");
1102 return getFoldedCast(Instruction::Trunc, C, Ty);
1105 Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
1107 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1108 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1110 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1111 assert(C->getType()->isIntOrIntVector() && "SExt operand must be integral");
1112 assert(Ty->isIntOrIntVector() && "SExt produces only integer");
1113 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1114 "SrcTy must be smaller than DestTy for SExt!");
1116 return getFoldedCast(Instruction::SExt, C, Ty);
1119 Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
1121 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1122 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1124 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1125 assert(C->getType()->isIntOrIntVector() && "ZEXt operand must be integral");
1126 assert(Ty->isIntOrIntVector() && "ZExt produces only integer");
1127 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1128 "SrcTy must be smaller than DestTy for ZExt!");
1130 return getFoldedCast(Instruction::ZExt, C, Ty);
1133 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1135 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1136 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1138 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1139 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1140 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1141 "This is an illegal floating point truncation!");
1142 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1145 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1147 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1148 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1150 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1151 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1152 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1153 "This is an illegal floating point extension!");
1154 return getFoldedCast(Instruction::FPExt, C, Ty);
1157 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
1159 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1160 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1162 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1163 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1164 "This is an illegal uint to floating point cast!");
1165 return getFoldedCast(Instruction::UIToFP, C, Ty);
1168 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
1170 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1171 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1173 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1174 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1175 "This is an illegal sint to floating point cast!");
1176 return getFoldedCast(Instruction::SIToFP, C, Ty);
1179 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
1181 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1182 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1184 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1185 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1186 "This is an illegal floating point to uint cast!");
1187 return getFoldedCast(Instruction::FPToUI, C, Ty);
1190 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
1192 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1193 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1195 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1196 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1197 "This is an illegal floating point to sint cast!");
1198 return getFoldedCast(Instruction::FPToSI, C, Ty);
1201 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1202 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
1203 assert(DstTy->isInteger() && "PtrToInt destination must be integral");
1204 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1207 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
1208 assert(C->getType()->isInteger() && "IntToPtr source must be integral");
1209 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
1210 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1213 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1214 // BitCast implies a no-op cast of type only. No bits change. However, you
1215 // can't cast pointers to anything but pointers.
1217 const Type *SrcTy = C->getType();
1218 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
1219 "BitCast cannot cast pointer to non-pointer and vice versa");
1221 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
1222 // or nonptr->ptr). For all the other types, the cast is okay if source and
1223 // destination bit widths are identical.
1224 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1225 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
1227 assert(SrcBitSize == DstBitSize && "BitCast requires types of same width");
1229 // It is common to ask for a bitcast of a value to its own type, handle this
1231 if (C->getType() == DstTy) return C;
1233 return getFoldedCast(Instruction::BitCast, C, DstTy);
1236 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1237 Constant *C1, Constant *C2) {
1238 // Check the operands for consistency first
1239 assert(Opcode >= Instruction::BinaryOpsBegin &&
1240 Opcode < Instruction::BinaryOpsEnd &&
1241 "Invalid opcode in binary constant expression");
1242 assert(C1->getType() == C2->getType() &&
1243 "Operand types in binary constant expression should match");
1245 if (ReqTy == C1->getType() || ReqTy == Type::Int1Ty)
1246 if (Constant *FC = ConstantFoldBinaryInstruction(ReqTy->getContext(),
1248 return FC; // Fold a few common cases...
1250 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1251 ExprMapKeyType Key(Opcode, argVec);
1253 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1255 // Implicitly locked.
1256 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1259 Constant *ConstantExpr::getCompareTy(unsigned short predicate,
1260 Constant *C1, Constant *C2) {
1261 switch (predicate) {
1262 default: llvm_unreachable("Invalid CmpInst predicate");
1263 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
1264 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
1265 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
1266 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
1267 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
1268 case CmpInst::FCMP_TRUE:
1269 return getFCmp(predicate, C1, C2);
1271 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
1272 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
1273 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
1274 case CmpInst::ICMP_SLE:
1275 return getICmp(predicate, C1, C2);
1279 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
1280 // API compatibility: Adjust integer opcodes to floating-point opcodes.
1281 if (C1->getType()->isFPOrFPVector()) {
1282 if (Opcode == Instruction::Add) Opcode = Instruction::FAdd;
1283 else if (Opcode == Instruction::Sub) Opcode = Instruction::FSub;
1284 else if (Opcode == Instruction::Mul) Opcode = Instruction::FMul;
1288 case Instruction::Add:
1289 case Instruction::Sub:
1290 case Instruction::Mul:
1291 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1292 assert(C1->getType()->isIntOrIntVector() &&
1293 "Tried to create an integer operation on a non-integer type!");
1295 case Instruction::FAdd:
1296 case Instruction::FSub:
1297 case Instruction::FMul:
1298 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1299 assert(C1->getType()->isFPOrFPVector() &&
1300 "Tried to create a floating-point operation on a "
1301 "non-floating-point type!");
1303 case Instruction::UDiv:
1304 case Instruction::SDiv:
1305 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1306 assert(C1->getType()->isIntOrIntVector() &&
1307 "Tried to create an arithmetic operation on a non-arithmetic type!");
1309 case Instruction::FDiv:
1310 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1311 assert(C1->getType()->isFPOrFPVector() &&
1312 "Tried to create an arithmetic operation on a non-arithmetic type!");
1314 case Instruction::URem:
1315 case Instruction::SRem:
1316 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1317 assert(C1->getType()->isIntOrIntVector() &&
1318 "Tried to create an arithmetic operation on a non-arithmetic type!");
1320 case Instruction::FRem:
1321 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1322 assert(C1->getType()->isFPOrFPVector() &&
1323 "Tried to create an arithmetic operation on a non-arithmetic type!");
1325 case Instruction::And:
1326 case Instruction::Or:
1327 case Instruction::Xor:
1328 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1329 assert(C1->getType()->isIntOrIntVector() &&
1330 "Tried to create a logical operation on a non-integral type!");
1332 case Instruction::Shl:
1333 case Instruction::LShr:
1334 case Instruction::AShr:
1335 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1336 assert(C1->getType()->isIntOrIntVector() &&
1337 "Tried to create a shift operation on a non-integer type!");
1344 return getTy(C1->getType(), Opcode, C1, C2);
1347 Constant* ConstantExpr::getSizeOf(const Type* Ty) {
1348 // sizeof is implemented as: (i64) gep (Ty*)null, 1
1349 // Note that a non-inbounds gep is used, as null isn't within any object.
1350 Constant *GEPIdx = ConstantInt::get(Type::Int32Ty, 1);
1351 Constant *GEP = getGetElementPtr(
1352 Constant::getNullValue(PointerType::getUnqual(Ty)), &GEPIdx, 1);
1353 return getCast(Instruction::PtrToInt, GEP, Type::Int64Ty);
1356 Constant* ConstantExpr::getAlignOf(const Type* Ty) {
1357 // alignof is implemented as: (i64) gep ({i8,Ty}*)null, 0, 1
1358 const Type *AligningTy = StructType::get(Type::Int8Ty, Ty, NULL);
1359 Constant *NullPtr = Constant::getNullValue(AligningTy->getPointerTo());
1360 Constant *Zero = ConstantInt::get(Type::Int32Ty, 0);
1361 Constant *One = ConstantInt::get(Type::Int32Ty, 1);
1362 Constant *Indices[2] = { Zero, One };
1363 Constant *GEP = getGetElementPtr(NullPtr, Indices, 2);
1364 return getCast(Instruction::PtrToInt, GEP, Type::Int32Ty);
1368 Constant *ConstantExpr::getCompare(unsigned short pred,
1369 Constant *C1, Constant *C2) {
1370 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1371 return getCompareTy(pred, C1, C2);
1374 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1375 Constant *V1, Constant *V2) {
1376 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
1378 if (ReqTy == V1->getType())
1379 if (Constant *SC = ConstantFoldSelectInstruction(
1380 ReqTy->getContext(), C, V1, V2))
1381 return SC; // Fold common cases
1383 std::vector<Constant*> argVec(3, C);
1386 ExprMapKeyType Key(Instruction::Select, argVec);
1388 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1390 // Implicitly locked.
1391 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1394 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1397 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs,
1399 cast<PointerType>(ReqTy)->getElementType() &&
1400 "GEP indices invalid!");
1402 if (Constant *FC = ConstantFoldGetElementPtr(
1403 ReqTy->getContext(), C, (Constant**)Idxs, NumIdx))
1404 return FC; // Fold a few common cases...
1406 assert(isa<PointerType>(C->getType()) &&
1407 "Non-pointer type for constant GetElementPtr expression");
1408 // Look up the constant in the table first to ensure uniqueness
1409 std::vector<Constant*> ArgVec;
1410 ArgVec.reserve(NumIdx+1);
1411 ArgVec.push_back(C);
1412 for (unsigned i = 0; i != NumIdx; ++i)
1413 ArgVec.push_back(cast<Constant>(Idxs[i]));
1414 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
1416 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1418 // Implicitly locked.
1419 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1422 Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
1424 // Get the result type of the getelementptr!
1426 GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx);
1427 assert(Ty && "GEP indices invalid!");
1428 unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
1429 return getGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx);
1432 Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
1434 return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
1439 ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1440 assert(LHS->getType() == RHS->getType());
1441 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
1442 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1444 if (Constant *FC = ConstantFoldCompareInstruction(
1445 LHS->getContext(), pred, LHS, RHS))
1446 return FC; // Fold a few common cases...
1448 // Look up the constant in the table first to ensure uniqueness
1449 std::vector<Constant*> ArgVec;
1450 ArgVec.push_back(LHS);
1451 ArgVec.push_back(RHS);
1452 // Get the key type with both the opcode and predicate
1453 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
1455 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
1457 // Implicitly locked.
1458 return pImpl->ExprConstants.getOrCreate(Type::Int1Ty, Key);
1462 ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1463 assert(LHS->getType() == RHS->getType());
1464 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1466 if (Constant *FC = ConstantFoldCompareInstruction(
1467 LHS->getContext(), pred, LHS, RHS))
1468 return FC; // Fold a few common cases...
1470 // Look up the constant in the table first to ensure uniqueness
1471 std::vector<Constant*> ArgVec;
1472 ArgVec.push_back(LHS);
1473 ArgVec.push_back(RHS);
1474 // Get the key type with both the opcode and predicate
1475 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
1477 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
1479 // Implicitly locked.
1480 return pImpl->ExprConstants.getOrCreate(Type::Int1Ty, Key);
1483 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
1485 if (Constant *FC = ConstantFoldExtractElementInstruction(
1486 ReqTy->getContext(), Val, Idx))
1487 return FC; // Fold a few common cases...
1488 // Look up the constant in the table first to ensure uniqueness
1489 std::vector<Constant*> ArgVec(1, Val);
1490 ArgVec.push_back(Idx);
1491 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
1493 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1495 // Implicitly locked.
1496 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1499 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
1500 assert(isa<VectorType>(Val->getType()) &&
1501 "Tried to create extractelement operation on non-vector type!");
1502 assert(Idx->getType() == Type::Int32Ty &&
1503 "Extractelement index must be i32 type!");
1504 return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
1508 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
1509 Constant *Elt, Constant *Idx) {
1510 if (Constant *FC = ConstantFoldInsertElementInstruction(
1511 ReqTy->getContext(), Val, Elt, Idx))
1512 return FC; // Fold a few common cases...
1513 // Look up the constant in the table first to ensure uniqueness
1514 std::vector<Constant*> ArgVec(1, Val);
1515 ArgVec.push_back(Elt);
1516 ArgVec.push_back(Idx);
1517 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
1519 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1521 // Implicitly locked.
1522 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1525 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1527 assert(isa<VectorType>(Val->getType()) &&
1528 "Tried to create insertelement operation on non-vector type!");
1529 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
1530 && "Insertelement types must match!");
1531 assert(Idx->getType() == Type::Int32Ty &&
1532 "Insertelement index must be i32 type!");
1533 return getInsertElementTy(Val->getType(), Val, Elt, Idx);
1536 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
1537 Constant *V2, Constant *Mask) {
1538 if (Constant *FC = ConstantFoldShuffleVectorInstruction(
1539 ReqTy->getContext(), V1, V2, Mask))
1540 return FC; // Fold a few common cases...
1541 // Look up the constant in the table first to ensure uniqueness
1542 std::vector<Constant*> ArgVec(1, V1);
1543 ArgVec.push_back(V2);
1544 ArgVec.push_back(Mask);
1545 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
1547 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1549 // Implicitly locked.
1550 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1553 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
1555 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1556 "Invalid shuffle vector constant expr operands!");
1558 unsigned NElts = cast<VectorType>(Mask->getType())->getNumElements();
1559 const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
1560 const Type *ShufTy = VectorType::get(EltTy, NElts);
1561 return getShuffleVectorTy(ShufTy, V1, V2, Mask);
1564 Constant *ConstantExpr::getInsertValueTy(const Type *ReqTy, Constant *Agg,
1566 const unsigned *Idxs, unsigned NumIdx) {
1567 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
1568 Idxs+NumIdx) == Val->getType() &&
1569 "insertvalue indices invalid!");
1570 assert(Agg->getType() == ReqTy &&
1571 "insertvalue type invalid!");
1572 assert(Agg->getType()->isFirstClassType() &&
1573 "Non-first-class type for constant InsertValue expression");
1574 Constant *FC = ConstantFoldInsertValueInstruction(
1575 ReqTy->getContext(), Agg, Val, Idxs, NumIdx);
1576 assert(FC && "InsertValue constant expr couldn't be folded!");
1580 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
1581 const unsigned *IdxList, unsigned NumIdx) {
1582 assert(Agg->getType()->isFirstClassType() &&
1583 "Tried to create insertelement operation on non-first-class type!");
1585 const Type *ReqTy = Agg->getType();
1588 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
1590 assert(ValTy == Val->getType() && "insertvalue indices invalid!");
1591 return getInsertValueTy(ReqTy, Agg, Val, IdxList, NumIdx);
1594 Constant *ConstantExpr::getExtractValueTy(const Type *ReqTy, Constant *Agg,
1595 const unsigned *Idxs, unsigned NumIdx) {
1596 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
1597 Idxs+NumIdx) == ReqTy &&
1598 "extractvalue indices invalid!");
1599 assert(Agg->getType()->isFirstClassType() &&
1600 "Non-first-class type for constant extractvalue expression");
1601 Constant *FC = ConstantFoldExtractValueInstruction(
1602 ReqTy->getContext(), Agg, Idxs, NumIdx);
1603 assert(FC && "ExtractValue constant expr couldn't be folded!");
1607 Constant *ConstantExpr::getExtractValue(Constant *Agg,
1608 const unsigned *IdxList, unsigned NumIdx) {
1609 assert(Agg->getType()->isFirstClassType() &&
1610 "Tried to create extractelement operation on non-first-class type!");
1613 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
1614 assert(ReqTy && "extractvalue indices invalid!");
1615 return getExtractValueTy(ReqTy, Agg, IdxList, NumIdx);
1618 Constant* ConstantExpr::getNeg(Constant* C) {
1619 // API compatibility: Adjust integer opcodes to floating-point opcodes.
1620 if (C->getType()->isFPOrFPVector())
1622 assert(C->getType()->isIntOrIntVector() &&
1623 "Cannot NEG a nonintegral value!");
1624 return get(Instruction::Sub,
1625 ConstantFP::getZeroValueForNegation(C->getType()),
1629 Constant* ConstantExpr::getFNeg(Constant* C) {
1630 assert(C->getType()->isFPOrFPVector() &&
1631 "Cannot FNEG a non-floating-point value!");
1632 return get(Instruction::FSub,
1633 ConstantFP::getZeroValueForNegation(C->getType()),
1637 Constant* ConstantExpr::getNot(Constant* C) {
1638 assert(C->getType()->isIntOrIntVector() &&
1639 "Cannot NOT a nonintegral value!");
1640 return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
1643 Constant* ConstantExpr::getAdd(Constant* C1, Constant* C2) {
1644 return get(Instruction::Add, C1, C2);
1647 Constant* ConstantExpr::getFAdd(Constant* C1, Constant* C2) {
1648 return get(Instruction::FAdd, C1, C2);
1651 Constant* ConstantExpr::getSub(Constant* C1, Constant* C2) {
1652 return get(Instruction::Sub, C1, C2);
1655 Constant* ConstantExpr::getFSub(Constant* C1, Constant* C2) {
1656 return get(Instruction::FSub, C1, C2);
1659 Constant* ConstantExpr::getMul(Constant* C1, Constant* C2) {
1660 return get(Instruction::Mul, C1, C2);
1663 Constant* ConstantExpr::getFMul(Constant* C1, Constant* C2) {
1664 return get(Instruction::FMul, C1, C2);
1667 Constant* ConstantExpr::getUDiv(Constant* C1, Constant* C2) {
1668 return get(Instruction::UDiv, C1, C2);
1671 Constant* ConstantExpr::getSDiv(Constant* C1, Constant* C2) {
1672 return get(Instruction::SDiv, C1, C2);
1675 Constant* ConstantExpr::getFDiv(Constant* C1, Constant* C2) {
1676 return get(Instruction::FDiv, C1, C2);
1679 Constant* ConstantExpr::getURem(Constant* C1, Constant* C2) {
1680 return get(Instruction::URem, C1, C2);
1683 Constant* ConstantExpr::getSRem(Constant* C1, Constant* C2) {
1684 return get(Instruction::SRem, C1, C2);
1687 Constant* ConstantExpr::getFRem(Constant* C1, Constant* C2) {
1688 return get(Instruction::FRem, C1, C2);
1691 Constant* ConstantExpr::getAnd(Constant* C1, Constant* C2) {
1692 return get(Instruction::And, C1, C2);
1695 Constant* ConstantExpr::getOr(Constant* C1, Constant* C2) {
1696 return get(Instruction::Or, C1, C2);
1699 Constant* ConstantExpr::getXor(Constant* C1, Constant* C2) {
1700 return get(Instruction::Xor, C1, C2);
1703 Constant* ConstantExpr::getShl(Constant* C1, Constant* C2) {
1704 return get(Instruction::Shl, C1, C2);
1707 Constant* ConstantExpr::getLShr(Constant* C1, Constant* C2) {
1708 return get(Instruction::LShr, C1, C2);
1711 Constant* ConstantExpr::getAShr(Constant* C1, Constant* C2) {
1712 return get(Instruction::AShr, C1, C2);
1715 // destroyConstant - Remove the constant from the constant table...
1717 void ConstantExpr::destroyConstant() {
1718 // Implicitly locked.
1719 LLVMContextImpl *pImpl = getType()->getContext().pImpl;
1720 pImpl->ExprConstants.remove(this);
1721 destroyConstantImpl();
1724 const char *ConstantExpr::getOpcodeName() const {
1725 return Instruction::getOpcodeName(getOpcode());
1728 //===----------------------------------------------------------------------===//
1729 // replaceUsesOfWithOnConstant implementations
1731 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
1732 /// 'From' to be uses of 'To'. This must update the uniquing data structures
1735 /// Note that we intentionally replace all uses of From with To here. Consider
1736 /// a large array that uses 'From' 1000 times. By handling this case all here,
1737 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
1738 /// single invocation handles all 1000 uses. Handling them one at a time would
1739 /// work, but would be really slow because it would have to unique each updated
1742 static std::vector<Constant*> getValType(ConstantArray *CA) {
1743 std::vector<Constant*> Elements;
1744 Elements.reserve(CA->getNumOperands());
1745 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1746 Elements.push_back(cast<Constant>(CA->getOperand(i)));
1751 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
1753 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1754 Constant *ToC = cast<Constant>(To);
1756 LLVMContext &Context = getType()->getContext();
1757 LLVMContextImpl *pImpl = Context.pImpl;
1759 std::pair<LLVMContextImpl::ArrayConstantsTy::MapKey, Constant*> Lookup;
1760 Lookup.first.first = getType();
1761 Lookup.second = this;
1763 std::vector<Constant*> &Values = Lookup.first.second;
1764 Values.reserve(getNumOperands()); // Build replacement array.
1766 // Fill values with the modified operands of the constant array. Also,
1767 // compute whether this turns into an all-zeros array.
1768 bool isAllZeros = false;
1769 unsigned NumUpdated = 0;
1770 if (!ToC->isNullValue()) {
1771 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1772 Constant *Val = cast<Constant>(O->get());
1777 Values.push_back(Val);
1781 for (Use *O = OperandList, *E = OperandList+getNumOperands();O != E; ++O) {
1782 Constant *Val = cast<Constant>(O->get());
1787 Values.push_back(Val);
1788 if (isAllZeros) isAllZeros = Val->isNullValue();
1792 Constant *Replacement = 0;
1794 Replacement = ConstantAggregateZero::get(getType());
1796 // Check to see if we have this array type already.
1797 sys::SmartScopedWriter<true> Writer(pImpl->ConstantsLock);
1799 LLVMContextImpl::ArrayConstantsTy::MapTy::iterator I =
1800 pImpl->ArrayConstants.InsertOrGetItem(Lookup, Exists);
1803 Replacement = I->second;
1805 // Okay, the new shape doesn't exist in the system yet. Instead of
1806 // creating a new constant array, inserting it, replaceallusesof'ing the
1807 // old with the new, then deleting the old... just update the current one
1809 pImpl->ArrayConstants.MoveConstantToNewSlot(this, I);
1811 // Update to the new value. Optimize for the case when we have a single
1812 // operand that we're changing, but handle bulk updates efficiently.
1813 if (NumUpdated == 1) {
1814 unsigned OperandToUpdate = U - OperandList;
1815 assert(getOperand(OperandToUpdate) == From &&
1816 "ReplaceAllUsesWith broken!");
1817 setOperand(OperandToUpdate, ToC);
1819 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1820 if (getOperand(i) == From)
1827 // Otherwise, I do need to replace this with an existing value.
1828 assert(Replacement != this && "I didn't contain From!");
1830 // Everyone using this now uses the replacement.
1831 uncheckedReplaceAllUsesWith(Replacement);
1833 // Delete the old constant!
1837 static std::vector<Constant*> getValType(ConstantStruct *CS) {
1838 std::vector<Constant*> Elements;
1839 Elements.reserve(CS->getNumOperands());
1840 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1841 Elements.push_back(cast<Constant>(CS->getOperand(i)));
1845 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
1847 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1848 Constant *ToC = cast<Constant>(To);
1850 unsigned OperandToUpdate = U-OperandList;
1851 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
1853 std::pair<LLVMContextImpl::StructConstantsTy::MapKey, Constant*> Lookup;
1854 Lookup.first.first = getType();
1855 Lookup.second = this;
1856 std::vector<Constant*> &Values = Lookup.first.second;
1857 Values.reserve(getNumOperands()); // Build replacement struct.
1860 // Fill values with the modified operands of the constant struct. Also,
1861 // compute whether this turns into an all-zeros struct.
1862 bool isAllZeros = false;
1863 if (!ToC->isNullValue()) {
1864 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O)
1865 Values.push_back(cast<Constant>(O->get()));
1868 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1869 Constant *Val = cast<Constant>(O->get());
1870 Values.push_back(Val);
1871 if (isAllZeros) isAllZeros = Val->isNullValue();
1874 Values[OperandToUpdate] = ToC;
1876 LLVMContext &Context = getType()->getContext();
1877 LLVMContextImpl *pImpl = Context.pImpl;
1879 Constant *Replacement = 0;
1881 Replacement = ConstantAggregateZero::get(getType());
1883 // Check to see if we have this array type already.
1884 sys::SmartScopedWriter<true> Writer(pImpl->ConstantsLock);
1886 LLVMContextImpl::StructConstantsTy::MapTy::iterator I =
1887 pImpl->StructConstants.InsertOrGetItem(Lookup, Exists);
1890 Replacement = I->second;
1892 // Okay, the new shape doesn't exist in the system yet. Instead of
1893 // creating a new constant struct, inserting it, replaceallusesof'ing the
1894 // old with the new, then deleting the old... just update the current one
1896 pImpl->StructConstants.MoveConstantToNewSlot(this, I);
1898 // Update to the new value.
1899 setOperand(OperandToUpdate, ToC);
1904 assert(Replacement != this && "I didn't contain From!");
1906 // Everyone using this now uses the replacement.
1907 uncheckedReplaceAllUsesWith(Replacement);
1909 // Delete the old constant!
1913 static std::vector<Constant*> getValType(ConstantVector *CP) {
1914 std::vector<Constant*> Elements;
1915 Elements.reserve(CP->getNumOperands());
1916 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1917 Elements.push_back(CP->getOperand(i));
1921 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
1923 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1925 std::vector<Constant*> Values;
1926 Values.reserve(getNumOperands()); // Build replacement array...
1927 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1928 Constant *Val = getOperand(i);
1929 if (Val == From) Val = cast<Constant>(To);
1930 Values.push_back(Val);
1933 Constant *Replacement = get(getType(), Values);
1934 assert(Replacement != this && "I didn't contain From!");
1936 // Everyone using this now uses the replacement.
1937 uncheckedReplaceAllUsesWith(Replacement);
1939 // Delete the old constant!
1943 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
1945 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
1946 Constant *To = cast<Constant>(ToV);
1948 Constant *Replacement = 0;
1949 if (getOpcode() == Instruction::GetElementPtr) {
1950 SmallVector<Constant*, 8> Indices;
1951 Constant *Pointer = getOperand(0);
1952 Indices.reserve(getNumOperands()-1);
1953 if (Pointer == From) Pointer = To;
1955 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1956 Constant *Val = getOperand(i);
1957 if (Val == From) Val = To;
1958 Indices.push_back(Val);
1960 Replacement = ConstantExpr::getGetElementPtr(Pointer,
1961 &Indices[0], Indices.size());
1962 } else if (getOpcode() == Instruction::ExtractValue) {
1963 Constant *Agg = getOperand(0);
1964 if (Agg == From) Agg = To;
1966 const SmallVector<unsigned, 4> &Indices = getIndices();
1967 Replacement = ConstantExpr::getExtractValue(Agg,
1968 &Indices[0], Indices.size());
1969 } else if (getOpcode() == Instruction::InsertValue) {
1970 Constant *Agg = getOperand(0);
1971 Constant *Val = getOperand(1);
1972 if (Agg == From) Agg = To;
1973 if (Val == From) Val = To;
1975 const SmallVector<unsigned, 4> &Indices = getIndices();
1976 Replacement = ConstantExpr::getInsertValue(Agg, Val,
1977 &Indices[0], Indices.size());
1978 } else if (isCast()) {
1979 assert(getOperand(0) == From && "Cast only has one use!");
1980 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
1981 } else if (getOpcode() == Instruction::Select) {
1982 Constant *C1 = getOperand(0);
1983 Constant *C2 = getOperand(1);
1984 Constant *C3 = getOperand(2);
1985 if (C1 == From) C1 = To;
1986 if (C2 == From) C2 = To;
1987 if (C3 == From) C3 = To;
1988 Replacement = ConstantExpr::getSelect(C1, C2, C3);
1989 } else if (getOpcode() == Instruction::ExtractElement) {
1990 Constant *C1 = getOperand(0);
1991 Constant *C2 = getOperand(1);
1992 if (C1 == From) C1 = To;
1993 if (C2 == From) C2 = To;
1994 Replacement = ConstantExpr::getExtractElement(C1, C2);
1995 } else if (getOpcode() == Instruction::InsertElement) {
1996 Constant *C1 = getOperand(0);
1997 Constant *C2 = getOperand(1);
1998 Constant *C3 = getOperand(1);
1999 if (C1 == From) C1 = To;
2000 if (C2 == From) C2 = To;
2001 if (C3 == From) C3 = To;
2002 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2003 } else if (getOpcode() == Instruction::ShuffleVector) {
2004 Constant *C1 = getOperand(0);
2005 Constant *C2 = getOperand(1);
2006 Constant *C3 = getOperand(2);
2007 if (C1 == From) C1 = To;
2008 if (C2 == From) C2 = To;
2009 if (C3 == From) C3 = To;
2010 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2011 } else if (isCompare()) {
2012 Constant *C1 = getOperand(0);
2013 Constant *C2 = getOperand(1);
2014 if (C1 == From) C1 = To;
2015 if (C2 == From) C2 = To;
2016 if (getOpcode() == Instruction::ICmp)
2017 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2019 assert(getOpcode() == Instruction::FCmp);
2020 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2022 } else if (getNumOperands() == 2) {
2023 Constant *C1 = getOperand(0);
2024 Constant *C2 = getOperand(1);
2025 if (C1 == From) C1 = To;
2026 if (C2 == From) C2 = To;
2027 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2029 llvm_unreachable("Unknown ConstantExpr type!");
2033 assert(Replacement != this && "I didn't contain From!");
2035 // Everyone using this now uses the replacement.
2036 uncheckedReplaceAllUsesWith(Replacement);
2038 // Delete the old constant!