1 //===-- Constants.cpp - Implement Constant nodes --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Constant* classes.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Constants.h"
15 #include "LLVMContextImpl.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/Support/raw_ostream.h"
31 #include "llvm/Support/GetElementPtrTypeIterator.h"
32 #include "llvm/ADT/DenseMap.h"
33 #include "llvm/ADT/SmallVector.h"
38 //===----------------------------------------------------------------------===//
40 //===----------------------------------------------------------------------===//
42 // Constructor to create a '0' constant of arbitrary type...
43 static const uint64_t zero[2] = {0, 0};
44 Constant *Constant::getNullValue(const Type *Ty) {
45 switch (Ty->getTypeID()) {
46 case Type::IntegerTyID:
47 return ConstantInt::get(Ty, 0);
49 return ConstantFP::get(Ty->getContext(), APFloat(APInt(32, 0)));
50 case Type::DoubleTyID:
51 return ConstantFP::get(Ty->getContext(), APFloat(APInt(64, 0)));
52 case Type::X86_FP80TyID:
53 return ConstantFP::get(Ty->getContext(), APFloat(APInt(80, 2, zero)));
55 return ConstantFP::get(Ty->getContext(),
56 APFloat(APInt(128, 2, zero), true));
57 case Type::PPC_FP128TyID:
58 return ConstantFP::get(Ty->getContext(), APFloat(APInt(128, 2, zero)));
59 case Type::PointerTyID:
60 return ConstantPointerNull::get(cast<PointerType>(Ty));
61 case Type::StructTyID:
63 case Type::VectorTyID:
64 return ConstantAggregateZero::get(Ty);
66 // Function, Label, or Opaque type?
67 assert(!"Cannot create a null constant of that type!");
72 Constant* Constant::getIntegerValue(const Type *Ty, const APInt &V) {
73 const Type *ScalarTy = Ty->getScalarType();
75 // Create the base integer constant.
76 Constant *C = ConstantInt::get(Ty->getContext(), V);
78 // Convert an integer to a pointer, if necessary.
79 if (const PointerType *PTy = dyn_cast<PointerType>(ScalarTy))
80 C = ConstantExpr::getIntToPtr(C, PTy);
82 // Broadcast a scalar to a vector, if necessary.
83 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
84 C = ConstantVector::get(std::vector<Constant *>(VTy->getNumElements(), C));
89 Constant* Constant::getAllOnesValue(const Type *Ty) {
90 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty))
91 return ConstantInt::get(Ty->getContext(),
92 APInt::getAllOnesValue(ITy->getBitWidth()));
94 std::vector<Constant*> Elts;
95 const VectorType *VTy = cast<VectorType>(Ty);
96 Elts.resize(VTy->getNumElements(), getAllOnesValue(VTy->getElementType()));
97 assert(Elts[0] && "Not a vector integer type!");
98 return cast<ConstantVector>(ConstantVector::get(Elts));
101 void Constant::destroyConstantImpl() {
102 // When a Constant is destroyed, there may be lingering
103 // references to the constant by other constants in the constant pool. These
104 // constants are implicitly dependent on the module that is being deleted,
105 // but they don't know that. Because we only find out when the CPV is
106 // deleted, we must now notify all of our users (that should only be
107 // Constants) that they are, in fact, invalid now and should be deleted.
109 while (!use_empty()) {
110 Value *V = use_back();
111 #ifndef NDEBUG // Only in -g mode...
112 if (!isa<Constant>(V)) {
113 dbgs() << "While deleting: " << *this
114 << "\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 (CE->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>(CE->getOperand(1)) ||CE->getOperand(1)->isNullValue())
160 /// isConstantUsed - Return true if the constant has users other than constant
161 /// exprs and other dangling things.
162 bool Constant::isConstantUsed() const {
163 for (const_use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
164 const Constant *UC = dyn_cast<Constant>(*UI);
165 if (UC == 0 || isa<GlobalValue>(UC))
168 if (UC->isConstantUsed())
176 /// getRelocationInfo - This method classifies the entry according to
177 /// whether or not it may generate a relocation entry. This must be
178 /// conservative, so if it might codegen to a relocatable entry, it should say
179 /// so. The return values are:
181 /// NoRelocation: This constant pool entry is guaranteed to never have a
182 /// relocation applied to it (because it holds a simple constant like
184 /// LocalRelocation: This entry has relocations, but the entries are
185 /// guaranteed to be resolvable by the static linker, so the dynamic
186 /// linker will never see them.
187 /// GlobalRelocations: This entry may have arbitrary relocations.
189 /// FIXME: This really should not be in VMCore.
190 Constant::PossibleRelocationsTy Constant::getRelocationInfo() const {
191 if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
192 if (GV->hasLocalLinkage() || GV->hasHiddenVisibility())
193 return LocalRelocation; // Local to this file/library.
194 return GlobalRelocations; // Global reference.
197 if (const BlockAddress *BA = dyn_cast<BlockAddress>(this))
198 return BA->getFunction()->getRelocationInfo();
200 // While raw uses of blockaddress need to be relocated, differences between
201 // two of them don't when they are for labels in the same function. This is a
202 // common idiom when creating a table for the indirect goto extension, so we
203 // handle it efficiently here.
204 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(this))
205 if (CE->getOpcode() == Instruction::Sub) {
206 ConstantExpr *LHS = dyn_cast<ConstantExpr>(CE->getOperand(0));
207 ConstantExpr *RHS = dyn_cast<ConstantExpr>(CE->getOperand(1));
209 LHS->getOpcode() == Instruction::PtrToInt &&
210 RHS->getOpcode() == Instruction::PtrToInt &&
211 isa<BlockAddress>(LHS->getOperand(0)) &&
212 isa<BlockAddress>(RHS->getOperand(0)) &&
213 cast<BlockAddress>(LHS->getOperand(0))->getFunction() ==
214 cast<BlockAddress>(RHS->getOperand(0))->getFunction())
218 PossibleRelocationsTy Result = NoRelocation;
219 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
220 Result = std::max(Result,
221 cast<Constant>(getOperand(i))->getRelocationInfo());
227 /// getVectorElements - This method, which is only valid on constant of vector
228 /// type, returns the elements of the vector in the specified smallvector.
229 /// This handles breaking down a vector undef into undef elements, etc. For
230 /// constant exprs and other cases we can't handle, we return an empty vector.
231 void Constant::getVectorElements(SmallVectorImpl<Constant*> &Elts) const {
232 assert(getType()->isVectorTy() && "Not a vector constant!");
234 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this)) {
235 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i)
236 Elts.push_back(CV->getOperand(i));
240 const VectorType *VT = cast<VectorType>(getType());
241 if (isa<ConstantAggregateZero>(this)) {
242 Elts.assign(VT->getNumElements(),
243 Constant::getNullValue(VT->getElementType()));
247 if (isa<UndefValue>(this)) {
248 Elts.assign(VT->getNumElements(), UndefValue::get(VT->getElementType()));
252 // Unknown type, must be constant expr etc.
257 //===----------------------------------------------------------------------===//
259 //===----------------------------------------------------------------------===//
261 ConstantInt::ConstantInt(const IntegerType *Ty, const APInt& V)
262 : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
263 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
266 ConstantInt* ConstantInt::getTrue(LLVMContext &Context) {
267 LLVMContextImpl *pImpl = Context.pImpl;
268 if (pImpl->TheTrueVal)
269 return pImpl->TheTrueVal;
271 return (pImpl->TheTrueVal =
272 ConstantInt::get(IntegerType::get(Context, 1), 1));
275 ConstantInt* ConstantInt::getFalse(LLVMContext &Context) {
276 LLVMContextImpl *pImpl = Context.pImpl;
277 if (pImpl->TheFalseVal)
278 return pImpl->TheFalseVal;
280 return (pImpl->TheFalseVal =
281 ConstantInt::get(IntegerType::get(Context, 1), 0));
285 // Get a ConstantInt from an APInt. Note that the value stored in the DenseMap
286 // as the key, is a DenseMapAPIntKeyInfo::KeyTy which has provided the
287 // operator== and operator!= to ensure that the DenseMap doesn't attempt to
288 // compare APInt's of different widths, which would violate an APInt class
289 // invariant which generates an assertion.
290 ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt& V) {
291 // Get the corresponding integer type for the bit width of the value.
292 const IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
293 // get an existing value or the insertion position
294 DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
295 ConstantInt *&Slot = Context.pImpl->IntConstants[Key];
296 if (!Slot) Slot = new ConstantInt(ITy, V);
300 Constant* ConstantInt::get(const Type* Ty, uint64_t V, bool isSigned) {
301 Constant *C = get(cast<IntegerType>(Ty->getScalarType()),
304 // For vectors, broadcast the value.
305 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
306 return ConstantVector::get(
307 std::vector<Constant *>(VTy->getNumElements(), C));
312 ConstantInt* ConstantInt::get(const IntegerType* Ty, uint64_t V,
314 return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned));
317 ConstantInt* ConstantInt::getSigned(const IntegerType* Ty, int64_t V) {
318 return get(Ty, V, true);
321 Constant *ConstantInt::getSigned(const Type *Ty, int64_t V) {
322 return get(Ty, V, true);
325 Constant* ConstantInt::get(const Type* Ty, const APInt& V) {
326 ConstantInt *C = get(Ty->getContext(), V);
327 assert(C->getType() == Ty->getScalarType() &&
328 "ConstantInt type doesn't match the type implied by its value!");
330 // For vectors, broadcast the value.
331 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
332 return ConstantVector::get(
333 std::vector<Constant *>(VTy->getNumElements(), C));
338 ConstantInt* ConstantInt::get(const IntegerType* Ty, StringRef Str,
340 return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
343 //===----------------------------------------------------------------------===//
345 //===----------------------------------------------------------------------===//
347 static const fltSemantics *TypeToFloatSemantics(const Type *Ty) {
349 return &APFloat::IEEEsingle;
350 if (Ty->isDoubleTy())
351 return &APFloat::IEEEdouble;
352 if (Ty->isX86_FP80Ty())
353 return &APFloat::x87DoubleExtended;
354 else if (Ty->isFP128Ty())
355 return &APFloat::IEEEquad;
357 assert(Ty->isPPC_FP128Ty() && "Unknown FP format");
358 return &APFloat::PPCDoubleDouble;
361 /// get() - This returns a constant fp for the specified value in the
362 /// specified type. This should only be used for simple constant values like
363 /// 2.0/1.0 etc, that are known-valid both as double and as the target format.
364 Constant* ConstantFP::get(const Type* Ty, double V) {
365 LLVMContext &Context = Ty->getContext();
369 FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
370 APFloat::rmNearestTiesToEven, &ignored);
371 Constant *C = get(Context, FV);
373 // For vectors, broadcast the value.
374 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
375 return ConstantVector::get(
376 std::vector<Constant *>(VTy->getNumElements(), C));
382 Constant* ConstantFP::get(const Type* Ty, StringRef Str) {
383 LLVMContext &Context = Ty->getContext();
385 APFloat FV(*TypeToFloatSemantics(Ty->getScalarType()), Str);
386 Constant *C = get(Context, FV);
388 // For vectors, broadcast the value.
389 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
390 return ConstantVector::get(
391 std::vector<Constant *>(VTy->getNumElements(), C));
397 ConstantFP* ConstantFP::getNegativeZero(const Type* Ty) {
398 LLVMContext &Context = Ty->getContext();
399 APFloat apf = cast <ConstantFP>(Constant::getNullValue(Ty))->getValueAPF();
401 return get(Context, apf);
405 Constant* ConstantFP::getZeroValueForNegation(const Type* Ty) {
406 if (const VectorType *PTy = dyn_cast<VectorType>(Ty))
407 if (PTy->getElementType()->isFloatingPointTy()) {
408 std::vector<Constant*> zeros(PTy->getNumElements(),
409 getNegativeZero(PTy->getElementType()));
410 return ConstantVector::get(PTy, zeros);
413 if (Ty->isFloatingPointTy())
414 return getNegativeZero(Ty);
416 return Constant::getNullValue(Ty);
420 // ConstantFP accessors.
421 ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
422 DenseMapAPFloatKeyInfo::KeyTy Key(V);
424 LLVMContextImpl* pImpl = Context.pImpl;
426 ConstantFP *&Slot = pImpl->FPConstants[Key];
430 if (&V.getSemantics() == &APFloat::IEEEsingle)
431 Ty = Type::getFloatTy(Context);
432 else if (&V.getSemantics() == &APFloat::IEEEdouble)
433 Ty = Type::getDoubleTy(Context);
434 else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
435 Ty = Type::getX86_FP80Ty(Context);
436 else if (&V.getSemantics() == &APFloat::IEEEquad)
437 Ty = Type::getFP128Ty(Context);
439 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble &&
440 "Unknown FP format");
441 Ty = Type::getPPC_FP128Ty(Context);
443 Slot = new ConstantFP(Ty, V);
449 ConstantFP *ConstantFP::getInfinity(const Type *Ty, bool Negative) {
450 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty);
451 return ConstantFP::get(Ty->getContext(),
452 APFloat::getInf(Semantics, Negative));
455 ConstantFP::ConstantFP(const Type *Ty, const APFloat& V)
456 : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
457 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
461 bool ConstantFP::isNullValue() const {
462 return Val.isZero() && !Val.isNegative();
465 bool ConstantFP::isExactlyValue(const APFloat& V) const {
466 return Val.bitwiseIsEqual(V);
469 //===----------------------------------------------------------------------===//
470 // ConstantXXX Classes
471 //===----------------------------------------------------------------------===//
474 ConstantArray::ConstantArray(const ArrayType *T,
475 const std::vector<Constant*> &V)
476 : Constant(T, ConstantArrayVal,
477 OperandTraits<ConstantArray>::op_end(this) - V.size(),
479 assert(V.size() == T->getNumElements() &&
480 "Invalid initializer vector for constant array");
481 Use *OL = OperandList;
482 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
485 assert(C->getType() == T->getElementType() &&
486 "Initializer for array element doesn't match array element type!");
491 Constant *ConstantArray::get(const ArrayType *Ty,
492 const std::vector<Constant*> &V) {
493 for (unsigned i = 0, e = V.size(); i != e; ++i) {
494 assert(V[i]->getType() == Ty->getElementType() &&
495 "Wrong type in array element initializer");
497 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
498 // If this is an all-zero array, return a ConstantAggregateZero object
501 if (!C->isNullValue())
502 return pImpl->ArrayConstants.getOrCreate(Ty, V);
504 for (unsigned i = 1, e = V.size(); i != e; ++i)
506 return pImpl->ArrayConstants.getOrCreate(Ty, V);
509 return ConstantAggregateZero::get(Ty);
513 Constant* ConstantArray::get(const ArrayType* T, Constant* const* Vals,
515 // FIXME: make this the primary ctor method.
516 return get(T, std::vector<Constant*>(Vals, Vals+NumVals));
519 /// ConstantArray::get(const string&) - Return an array that is initialized to
520 /// contain the specified string. If length is zero then a null terminator is
521 /// added to the specified string so that it may be used in a natural way.
522 /// Otherwise, the length parameter specifies how much of the string to use
523 /// and it won't be null terminated.
525 Constant* ConstantArray::get(LLVMContext &Context, StringRef Str,
527 std::vector<Constant*> ElementVals;
528 for (unsigned i = 0; i < Str.size(); ++i)
529 ElementVals.push_back(ConstantInt::get(Type::getInt8Ty(Context), Str[i]));
531 // Add a null terminator to the string...
533 ElementVals.push_back(ConstantInt::get(Type::getInt8Ty(Context), 0));
536 ArrayType *ATy = ArrayType::get(Type::getInt8Ty(Context), ElementVals.size());
537 return get(ATy, ElementVals);
542 ConstantStruct::ConstantStruct(const StructType *T,
543 const std::vector<Constant*> &V)
544 : Constant(T, ConstantStructVal,
545 OperandTraits<ConstantStruct>::op_end(this) - V.size(),
547 assert(V.size() == T->getNumElements() &&
548 "Invalid initializer vector for constant structure");
549 Use *OL = OperandList;
550 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
553 assert(C->getType() == T->getElementType(I-V.begin()) &&
554 "Initializer for struct element doesn't match struct element type!");
559 // ConstantStruct accessors.
560 Constant* ConstantStruct::get(const StructType* T,
561 const std::vector<Constant*>& V) {
562 LLVMContextImpl* pImpl = T->getContext().pImpl;
564 // Create a ConstantAggregateZero value if all elements are zeros...
565 for (unsigned i = 0, e = V.size(); i != e; ++i)
566 if (!V[i]->isNullValue())
567 return pImpl->StructConstants.getOrCreate(T, V);
569 return ConstantAggregateZero::get(T);
572 Constant* ConstantStruct::get(LLVMContext &Context,
573 const std::vector<Constant*>& V, bool packed) {
574 std::vector<const Type*> StructEls;
575 StructEls.reserve(V.size());
576 for (unsigned i = 0, e = V.size(); i != e; ++i)
577 StructEls.push_back(V[i]->getType());
578 return get(StructType::get(Context, StructEls, packed), V);
581 Constant* ConstantStruct::get(LLVMContext &Context,
582 Constant* const *Vals, unsigned NumVals,
584 // FIXME: make this the primary ctor method.
585 return get(Context, std::vector<Constant*>(Vals, Vals+NumVals), Packed);
588 ConstantUnion::ConstantUnion(const UnionType *T, Constant* V)
589 : Constant(T, ConstantUnionVal,
590 OperandTraits<ConstantUnion>::op_end(this) - 1, 1) {
591 Use *OL = OperandList;
592 assert(T->getElementTypeIndex(V->getType()) >= 0 &&
593 "Initializer for union element isn't a member of union type!");
597 // ConstantUnion accessors.
598 Constant* ConstantUnion::get(const UnionType* T, Constant* V) {
599 LLVMContextImpl* pImpl = T->getContext().pImpl;
601 // Create a ConstantAggregateZero value if all elements are zeros...
602 if (!V->isNullValue())
603 return pImpl->UnionConstants.getOrCreate(T, V);
605 return ConstantAggregateZero::get(T);
609 ConstantVector::ConstantVector(const VectorType *T,
610 const std::vector<Constant*> &V)
611 : Constant(T, ConstantVectorVal,
612 OperandTraits<ConstantVector>::op_end(this) - V.size(),
614 Use *OL = OperandList;
615 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
618 assert(C->getType() == T->getElementType() &&
619 "Initializer for vector element doesn't match vector element type!");
624 // ConstantVector accessors.
625 Constant* ConstantVector::get(const VectorType* T,
626 const std::vector<Constant*>& V) {
627 assert(!V.empty() && "Vectors can't be empty");
628 LLVMContext &Context = T->getContext();
629 LLVMContextImpl *pImpl = Context.pImpl;
631 // If this is an all-undef or alll-zero vector, return a
632 // ConstantAggregateZero or UndefValue.
634 bool isZero = C->isNullValue();
635 bool isUndef = isa<UndefValue>(C);
637 if (isZero || isUndef) {
638 for (unsigned i = 1, e = V.size(); i != e; ++i)
640 isZero = isUndef = false;
646 return ConstantAggregateZero::get(T);
648 return UndefValue::get(T);
650 return pImpl->VectorConstants.getOrCreate(T, V);
653 Constant* ConstantVector::get(const std::vector<Constant*>& V) {
654 assert(!V.empty() && "Cannot infer type if V is empty");
655 return get(VectorType::get(V.front()->getType(),V.size()), V);
658 Constant* ConstantVector::get(Constant* const* Vals, unsigned NumVals) {
659 // FIXME: make this the primary ctor method.
660 return get(std::vector<Constant*>(Vals, Vals+NumVals));
663 Constant* ConstantExpr::getNSWNeg(Constant* C) {
664 assert(C->getType()->isIntOrIntVectorTy() &&
665 "Cannot NEG a nonintegral value!");
666 return getNSWSub(ConstantFP::getZeroValueForNegation(C->getType()), C);
669 Constant* ConstantExpr::getNUWNeg(Constant* C) {
670 assert(C->getType()->isIntOrIntVectorTy() &&
671 "Cannot NEG a nonintegral value!");
672 return getNUWSub(ConstantFP::getZeroValueForNegation(C->getType()), C);
675 Constant* ConstantExpr::getNSWAdd(Constant* C1, Constant* C2) {
676 return getTy(C1->getType(), Instruction::Add, C1, C2,
677 OverflowingBinaryOperator::NoSignedWrap);
680 Constant* ConstantExpr::getNUWAdd(Constant* C1, Constant* C2) {
681 return getTy(C1->getType(), Instruction::Add, C1, C2,
682 OverflowingBinaryOperator::NoUnsignedWrap);
685 Constant* ConstantExpr::getNSWSub(Constant* C1, Constant* C2) {
686 return getTy(C1->getType(), Instruction::Sub, C1, C2,
687 OverflowingBinaryOperator::NoSignedWrap);
690 Constant* ConstantExpr::getNUWSub(Constant* C1, Constant* C2) {
691 return getTy(C1->getType(), Instruction::Sub, C1, C2,
692 OverflowingBinaryOperator::NoUnsignedWrap);
695 Constant* ConstantExpr::getNSWMul(Constant* C1, Constant* C2) {
696 return getTy(C1->getType(), Instruction::Mul, C1, C2,
697 OverflowingBinaryOperator::NoSignedWrap);
700 Constant* ConstantExpr::getNUWMul(Constant* C1, Constant* C2) {
701 return getTy(C1->getType(), Instruction::Mul, C1, C2,
702 OverflowingBinaryOperator::NoUnsignedWrap);
705 Constant* ConstantExpr::getExactSDiv(Constant* C1, Constant* C2) {
706 return getTy(C1->getType(), Instruction::SDiv, C1, C2,
707 SDivOperator::IsExact);
710 // Utility function for determining if a ConstantExpr is a CastOp or not. This
711 // can't be inline because we don't want to #include Instruction.h into
713 bool ConstantExpr::isCast() const {
714 return Instruction::isCast(getOpcode());
717 bool ConstantExpr::isCompare() const {
718 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
721 bool ConstantExpr::isGEPWithNoNotionalOverIndexing() const {
722 if (getOpcode() != Instruction::GetElementPtr) return false;
724 gep_type_iterator GEPI = gep_type_begin(this), E = gep_type_end(this);
725 User::const_op_iterator OI = next(this->op_begin());
727 // Skip the first index, as it has no static limit.
731 // The remaining indices must be compile-time known integers within the
732 // bounds of the corresponding notional static array types.
733 for (; GEPI != E; ++GEPI, ++OI) {
734 ConstantInt *CI = dyn_cast<ConstantInt>(*OI);
735 if (!CI) return false;
736 if (const ArrayType *ATy = dyn_cast<ArrayType>(*GEPI))
737 if (CI->getValue().getActiveBits() > 64 ||
738 CI->getZExtValue() >= ATy->getNumElements())
742 // All the indices checked out.
746 bool ConstantExpr::hasIndices() const {
747 return getOpcode() == Instruction::ExtractValue ||
748 getOpcode() == Instruction::InsertValue;
751 const SmallVector<unsigned, 4> &ConstantExpr::getIndices() const {
752 if (const ExtractValueConstantExpr *EVCE =
753 dyn_cast<ExtractValueConstantExpr>(this))
754 return EVCE->Indices;
756 return cast<InsertValueConstantExpr>(this)->Indices;
759 unsigned ConstantExpr::getPredicate() const {
760 assert(getOpcode() == Instruction::FCmp ||
761 getOpcode() == Instruction::ICmp);
762 return ((const CompareConstantExpr*)this)->predicate;
765 /// getWithOperandReplaced - Return a constant expression identical to this
766 /// one, but with the specified operand set to the specified value.
768 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
769 assert(OpNo < getNumOperands() && "Operand num is out of range!");
770 assert(Op->getType() == getOperand(OpNo)->getType() &&
771 "Replacing operand with value of different type!");
772 if (getOperand(OpNo) == Op)
773 return const_cast<ConstantExpr*>(this);
775 Constant *Op0, *Op1, *Op2;
776 switch (getOpcode()) {
777 case Instruction::Trunc:
778 case Instruction::ZExt:
779 case Instruction::SExt:
780 case Instruction::FPTrunc:
781 case Instruction::FPExt:
782 case Instruction::UIToFP:
783 case Instruction::SIToFP:
784 case Instruction::FPToUI:
785 case Instruction::FPToSI:
786 case Instruction::PtrToInt:
787 case Instruction::IntToPtr:
788 case Instruction::BitCast:
789 return ConstantExpr::getCast(getOpcode(), Op, getType());
790 case Instruction::Select:
791 Op0 = (OpNo == 0) ? Op : getOperand(0);
792 Op1 = (OpNo == 1) ? Op : getOperand(1);
793 Op2 = (OpNo == 2) ? Op : getOperand(2);
794 return ConstantExpr::getSelect(Op0, Op1, Op2);
795 case Instruction::InsertElement:
796 Op0 = (OpNo == 0) ? Op : getOperand(0);
797 Op1 = (OpNo == 1) ? Op : getOperand(1);
798 Op2 = (OpNo == 2) ? Op : getOperand(2);
799 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
800 case Instruction::ExtractElement:
801 Op0 = (OpNo == 0) ? Op : getOperand(0);
802 Op1 = (OpNo == 1) ? Op : getOperand(1);
803 return ConstantExpr::getExtractElement(Op0, Op1);
804 case Instruction::ShuffleVector:
805 Op0 = (OpNo == 0) ? Op : getOperand(0);
806 Op1 = (OpNo == 1) ? Op : getOperand(1);
807 Op2 = (OpNo == 2) ? Op : getOperand(2);
808 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
809 case Instruction::GetElementPtr: {
810 SmallVector<Constant*, 8> Ops;
811 Ops.resize(getNumOperands()-1);
812 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
813 Ops[i-1] = getOperand(i);
815 return cast<GEPOperator>(this)->isInBounds() ?
816 ConstantExpr::getInBoundsGetElementPtr(Op, &Ops[0], Ops.size()) :
817 ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
819 return cast<GEPOperator>(this)->isInBounds() ?
820 ConstantExpr::getInBoundsGetElementPtr(getOperand(0), &Ops[0],Ops.size()):
821 ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
824 assert(getNumOperands() == 2 && "Must be binary operator?");
825 Op0 = (OpNo == 0) ? Op : getOperand(0);
826 Op1 = (OpNo == 1) ? Op : getOperand(1);
827 return ConstantExpr::get(getOpcode(), Op0, Op1, SubclassOptionalData);
831 /// getWithOperands - This returns the current constant expression with the
832 /// operands replaced with the specified values. The specified operands must
833 /// match count and type with the existing ones.
834 Constant *ConstantExpr::
835 getWithOperands(Constant* const *Ops, unsigned NumOps) const {
836 assert(NumOps == getNumOperands() && "Operand count mismatch!");
837 bool AnyChange = false;
838 for (unsigned i = 0; i != NumOps; ++i) {
839 assert(Ops[i]->getType() == getOperand(i)->getType() &&
840 "Operand type mismatch!");
841 AnyChange |= Ops[i] != getOperand(i);
843 if (!AnyChange) // No operands changed, return self.
844 return const_cast<ConstantExpr*>(this);
846 switch (getOpcode()) {
847 case Instruction::Trunc:
848 case Instruction::ZExt:
849 case Instruction::SExt:
850 case Instruction::FPTrunc:
851 case Instruction::FPExt:
852 case Instruction::UIToFP:
853 case Instruction::SIToFP:
854 case Instruction::FPToUI:
855 case Instruction::FPToSI:
856 case Instruction::PtrToInt:
857 case Instruction::IntToPtr:
858 case Instruction::BitCast:
859 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
860 case Instruction::Select:
861 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
862 case Instruction::InsertElement:
863 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
864 case Instruction::ExtractElement:
865 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
866 case Instruction::ShuffleVector:
867 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
868 case Instruction::GetElementPtr:
869 return cast<GEPOperator>(this)->isInBounds() ?
870 ConstantExpr::getInBoundsGetElementPtr(Ops[0], &Ops[1], NumOps-1) :
871 ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], NumOps-1);
872 case Instruction::ICmp:
873 case Instruction::FCmp:
874 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
876 assert(getNumOperands() == 2 && "Must be binary operator?");
877 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1], SubclassOptionalData);
882 //===----------------------------------------------------------------------===//
883 // isValueValidForType implementations
885 bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
886 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
887 if (Ty == Type::getInt1Ty(Ty->getContext()))
888 return Val == 0 || Val == 1;
890 return true; // always true, has to fit in largest type
891 uint64_t Max = (1ll << NumBits) - 1;
895 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
896 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
897 if (Ty == Type::getInt1Ty(Ty->getContext()))
898 return Val == 0 || Val == 1 || Val == -1;
900 return true; // always true, has to fit in largest type
901 int64_t Min = -(1ll << (NumBits-1));
902 int64_t Max = (1ll << (NumBits-1)) - 1;
903 return (Val >= Min && Val <= Max);
906 bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
907 // convert modifies in place, so make a copy.
908 APFloat Val2 = APFloat(Val);
910 switch (Ty->getTypeID()) {
912 return false; // These can't be represented as floating point!
914 // FIXME rounding mode needs to be more flexible
915 case Type::FloatTyID: {
916 if (&Val2.getSemantics() == &APFloat::IEEEsingle)
918 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
921 case Type::DoubleTyID: {
922 if (&Val2.getSemantics() == &APFloat::IEEEsingle ||
923 &Val2.getSemantics() == &APFloat::IEEEdouble)
925 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
928 case Type::X86_FP80TyID:
929 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
930 &Val2.getSemantics() == &APFloat::IEEEdouble ||
931 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
932 case Type::FP128TyID:
933 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
934 &Val2.getSemantics() == &APFloat::IEEEdouble ||
935 &Val2.getSemantics() == &APFloat::IEEEquad;
936 case Type::PPC_FP128TyID:
937 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
938 &Val2.getSemantics() == &APFloat::IEEEdouble ||
939 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
943 //===----------------------------------------------------------------------===//
944 // Factory Function Implementation
946 ConstantAggregateZero* ConstantAggregateZero::get(const Type* Ty) {
947 assert((Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()) &&
948 "Cannot create an aggregate zero of non-aggregate type!");
950 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
951 return pImpl->AggZeroConstants.getOrCreate(Ty, 0);
954 /// destroyConstant - Remove the constant from the constant table...
956 void ConstantAggregateZero::destroyConstant() {
957 getType()->getContext().pImpl->AggZeroConstants.remove(this);
958 destroyConstantImpl();
961 /// destroyConstant - Remove the constant from the constant table...
963 void ConstantArray::destroyConstant() {
964 getType()->getContext().pImpl->ArrayConstants.remove(this);
965 destroyConstantImpl();
968 /// isString - This method returns true if the array is an array of i8, and
969 /// if the elements of the array are all ConstantInt's.
970 bool ConstantArray::isString() const {
971 // Check the element type for i8...
972 if (!getType()->getElementType()->isIntegerTy(8))
974 // Check the elements to make sure they are all integers, not constant
976 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
977 if (!isa<ConstantInt>(getOperand(i)))
982 /// isCString - This method returns true if the array is a string (see
983 /// isString) and it ends in a null byte \\0 and does not contains any other
984 /// null bytes except its terminator.
985 bool ConstantArray::isCString() const {
986 // Check the element type for i8...
987 if (!getType()->getElementType()->isIntegerTy(8))
990 // Last element must be a null.
991 if (!getOperand(getNumOperands()-1)->isNullValue())
993 // Other elements must be non-null integers.
994 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
995 if (!isa<ConstantInt>(getOperand(i)))
997 if (getOperand(i)->isNullValue())
1004 /// getAsString - If the sub-element type of this array is i8
1005 /// then this method converts the array to an std::string and returns it.
1006 /// Otherwise, it asserts out.
1008 std::string ConstantArray::getAsString() const {
1009 assert(isString() && "Not a string!");
1011 Result.reserve(getNumOperands());
1012 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1013 Result.push_back((char)cast<ConstantInt>(getOperand(i))->getZExtValue());
1018 //---- ConstantStruct::get() implementation...
1025 // destroyConstant - Remove the constant from the constant table...
1027 void ConstantStruct::destroyConstant() {
1028 getType()->getContext().pImpl->StructConstants.remove(this);
1029 destroyConstantImpl();
1032 // destroyConstant - Remove the constant from the constant table...
1034 void ConstantUnion::destroyConstant() {
1035 getType()->getContext().pImpl->UnionConstants.remove(this);
1036 destroyConstantImpl();
1039 // destroyConstant - Remove the constant from the constant table...
1041 void ConstantVector::destroyConstant() {
1042 getType()->getContext().pImpl->VectorConstants.remove(this);
1043 destroyConstantImpl();
1046 /// This function will return true iff every element in this vector constant
1047 /// is set to all ones.
1048 /// @returns true iff this constant's emements are all set to all ones.
1049 /// @brief Determine if the value is all ones.
1050 bool ConstantVector::isAllOnesValue() const {
1051 // Check out first element.
1052 const Constant *Elt = getOperand(0);
1053 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1054 if (!CI || !CI->isAllOnesValue()) return false;
1055 // Then make sure all remaining elements point to the same value.
1056 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1057 if (getOperand(I) != Elt) return false;
1062 /// getSplatValue - If this is a splat constant, where all of the
1063 /// elements have the same value, return that value. Otherwise return null.
1064 Constant *ConstantVector::getSplatValue() {
1065 // Check out first element.
1066 Constant *Elt = getOperand(0);
1067 // Then make sure all remaining elements point to the same value.
1068 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1069 if (getOperand(I) != Elt) return 0;
1073 //---- ConstantPointerNull::get() implementation.
1076 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1077 return Ty->getContext().pImpl->NullPtrConstants.getOrCreate(Ty, 0);
1080 // destroyConstant - Remove the constant from the constant table...
1082 void ConstantPointerNull::destroyConstant() {
1083 getType()->getContext().pImpl->NullPtrConstants.remove(this);
1084 destroyConstantImpl();
1088 //---- UndefValue::get() implementation.
1091 UndefValue *UndefValue::get(const Type *Ty) {
1092 return Ty->getContext().pImpl->UndefValueConstants.getOrCreate(Ty, 0);
1095 // destroyConstant - Remove the constant from the constant table.
1097 void UndefValue::destroyConstant() {
1098 getType()->getContext().pImpl->UndefValueConstants.remove(this);
1099 destroyConstantImpl();
1102 //---- BlockAddress::get() implementation.
1105 BlockAddress *BlockAddress::get(BasicBlock *BB) {
1106 assert(BB->getParent() != 0 && "Block must have a parent");
1107 return get(BB->getParent(), BB);
1110 BlockAddress *BlockAddress::get(Function *F, BasicBlock *BB) {
1112 F->getContext().pImpl->BlockAddresses[std::make_pair(F, BB)];
1114 BA = new BlockAddress(F, BB);
1116 assert(BA->getFunction() == F && "Basic block moved between functions");
1120 BlockAddress::BlockAddress(Function *F, BasicBlock *BB)
1121 : Constant(Type::getInt8PtrTy(F->getContext()), Value::BlockAddressVal,
1125 BB->AdjustBlockAddressRefCount(1);
1129 // destroyConstant - Remove the constant from the constant table.
1131 void BlockAddress::destroyConstant() {
1132 getFunction()->getType()->getContext().pImpl
1133 ->BlockAddresses.erase(std::make_pair(getFunction(), getBasicBlock()));
1134 getBasicBlock()->AdjustBlockAddressRefCount(-1);
1135 destroyConstantImpl();
1138 void BlockAddress::replaceUsesOfWithOnConstant(Value *From, Value *To, Use *U) {
1139 // This could be replacing either the Basic Block or the Function. In either
1140 // case, we have to remove the map entry.
1141 Function *NewF = getFunction();
1142 BasicBlock *NewBB = getBasicBlock();
1145 NewF = cast<Function>(To);
1147 NewBB = cast<BasicBlock>(To);
1149 // See if the 'new' entry already exists, if not, just update this in place
1150 // and return early.
1151 BlockAddress *&NewBA =
1152 getContext().pImpl->BlockAddresses[std::make_pair(NewF, NewBB)];
1154 getBasicBlock()->AdjustBlockAddressRefCount(-1);
1156 // Remove the old entry, this can't cause the map to rehash (just a
1157 // tombstone will get added).
1158 getContext().pImpl->BlockAddresses.erase(std::make_pair(getFunction(),
1161 setOperand(0, NewF);
1162 setOperand(1, NewBB);
1163 getBasicBlock()->AdjustBlockAddressRefCount(1);
1167 // Otherwise, I do need to replace this with an existing value.
1168 assert(NewBA != this && "I didn't contain From!");
1170 // Everyone using this now uses the replacement.
1171 uncheckedReplaceAllUsesWith(NewBA);
1176 //---- ConstantExpr::get() implementations.
1179 /// This is a utility function to handle folding of casts and lookup of the
1180 /// cast in the ExprConstants map. It is used by the various get* methods below.
1181 static inline Constant *getFoldedCast(
1182 Instruction::CastOps opc, Constant *C, const Type *Ty) {
1183 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1184 // Fold a few common cases
1185 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1188 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
1190 // Look up the constant in the table first to ensure uniqueness
1191 std::vector<Constant*> argVec(1, C);
1192 ExprMapKeyType Key(opc, argVec);
1194 return pImpl->ExprConstants.getOrCreate(Ty, Key);
1197 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1198 Instruction::CastOps opc = Instruction::CastOps(oc);
1199 assert(Instruction::isCast(opc) && "opcode out of range");
1200 assert(C && Ty && "Null arguments to getCast");
1201 assert(CastInst::castIsValid(opc, C, Ty) && "Invalid constantexpr cast!");
1205 llvm_unreachable("Invalid cast opcode");
1207 case Instruction::Trunc: return getTrunc(C, Ty);
1208 case Instruction::ZExt: return getZExt(C, Ty);
1209 case Instruction::SExt: return getSExt(C, Ty);
1210 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1211 case Instruction::FPExt: return getFPExtend(C, Ty);
1212 case Instruction::UIToFP: return getUIToFP(C, Ty);
1213 case Instruction::SIToFP: return getSIToFP(C, Ty);
1214 case Instruction::FPToUI: return getFPToUI(C, Ty);
1215 case Instruction::FPToSI: return getFPToSI(C, Ty);
1216 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1217 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1218 case Instruction::BitCast: return getBitCast(C, Ty);
1223 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1224 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1225 return getCast(Instruction::BitCast, C, Ty);
1226 return getCast(Instruction::ZExt, C, Ty);
1229 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1230 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1231 return getCast(Instruction::BitCast, C, Ty);
1232 return getCast(Instruction::SExt, C, Ty);
1235 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1236 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1237 return getCast(Instruction::BitCast, C, Ty);
1238 return getCast(Instruction::Trunc, C, Ty);
1241 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1242 assert(S->getType()->isPointerTy() && "Invalid cast");
1243 assert((Ty->isIntegerTy() || Ty->isPointerTy()) && "Invalid cast");
1245 if (Ty->isIntegerTy())
1246 return getCast(Instruction::PtrToInt, S, Ty);
1247 return getCast(Instruction::BitCast, S, Ty);
1250 Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
1252 assert(C->getType()->isIntOrIntVectorTy() &&
1253 Ty->isIntOrIntVectorTy() && "Invalid cast");
1254 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1255 unsigned DstBits = Ty->getScalarSizeInBits();
1256 Instruction::CastOps opcode =
1257 (SrcBits == DstBits ? Instruction::BitCast :
1258 (SrcBits > DstBits ? Instruction::Trunc :
1259 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1260 return getCast(opcode, C, Ty);
1263 Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1264 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1266 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1267 unsigned DstBits = Ty->getScalarSizeInBits();
1268 if (SrcBits == DstBits)
1269 return C; // Avoid a useless cast
1270 Instruction::CastOps opcode =
1271 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1272 return getCast(opcode, C, Ty);
1275 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
1277 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1278 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1280 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1281 assert(C->getType()->isIntOrIntVectorTy() && "Trunc operand must be integer");
1282 assert(Ty->isIntOrIntVectorTy() && "Trunc produces only integral");
1283 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1284 "SrcTy must be larger than DestTy for Trunc!");
1286 return getFoldedCast(Instruction::Trunc, C, Ty);
1289 Constant *ConstantExpr::getSExt(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()->isIntOrIntVectorTy() && "SExt operand must be integral");
1296 assert(Ty->isIntOrIntVectorTy() && "SExt produces only integer");
1297 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1298 "SrcTy must be smaller than DestTy for SExt!");
1300 return getFoldedCast(Instruction::SExt, C, Ty);
1303 Constant *ConstantExpr::getZExt(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()->isIntOrIntVectorTy() && "ZEXt operand must be integral");
1310 assert(Ty->isIntOrIntVectorTy() && "ZExt produces only integer");
1311 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1312 "SrcTy must be smaller than DestTy for ZExt!");
1314 return getFoldedCast(Instruction::ZExt, C, Ty);
1317 Constant *ConstantExpr::getFPTrunc(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()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1324 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1325 "This is an illegal floating point truncation!");
1326 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1329 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1331 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1332 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1334 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1335 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1336 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1337 "This is an illegal floating point extension!");
1338 return getFoldedCast(Instruction::FPExt, C, Ty);
1341 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
1343 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1344 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1346 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1347 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
1348 "This is an illegal uint to floating point cast!");
1349 return getFoldedCast(Instruction::UIToFP, C, Ty);
1352 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
1354 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1355 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1357 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1358 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
1359 "This is an illegal sint to floating point cast!");
1360 return getFoldedCast(Instruction::SIToFP, C, Ty);
1363 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
1365 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1366 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1368 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1369 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
1370 "This is an illegal floating point to uint cast!");
1371 return getFoldedCast(Instruction::FPToUI, C, Ty);
1374 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
1376 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1377 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1379 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1380 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
1381 "This is an illegal floating point to sint cast!");
1382 return getFoldedCast(Instruction::FPToSI, C, Ty);
1385 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1386 assert(C->getType()->isPointerTy() && "PtrToInt source must be pointer");
1387 assert(DstTy->isIntegerTy() && "PtrToInt destination must be integral");
1388 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1391 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
1392 assert(C->getType()->isIntegerTy() && "IntToPtr source must be integral");
1393 assert(DstTy->isPointerTy() && "IntToPtr destination must be a pointer");
1394 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1397 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1398 assert(CastInst::castIsValid(Instruction::BitCast, C, DstTy) &&
1399 "Invalid constantexpr bitcast!");
1401 // It is common to ask for a bitcast of a value to its own type, handle this
1403 if (C->getType() == DstTy) return C;
1405 return getFoldedCast(Instruction::BitCast, C, DstTy);
1408 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1409 Constant *C1, Constant *C2,
1411 // Check the operands for consistency first
1412 assert(Opcode >= Instruction::BinaryOpsBegin &&
1413 Opcode < Instruction::BinaryOpsEnd &&
1414 "Invalid opcode in binary constant expression");
1415 assert(C1->getType() == C2->getType() &&
1416 "Operand types in binary constant expression should match");
1418 if (ReqTy == C1->getType() || ReqTy == Type::getInt1Ty(ReqTy->getContext()))
1419 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1420 return FC; // Fold a few common cases...
1422 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1423 ExprMapKeyType Key(Opcode, argVec, 0, Flags);
1425 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1426 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1429 Constant *ConstantExpr::getCompareTy(unsigned short predicate,
1430 Constant *C1, Constant *C2) {
1431 switch (predicate) {
1432 default: llvm_unreachable("Invalid CmpInst predicate");
1433 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
1434 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
1435 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
1436 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
1437 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
1438 case CmpInst::FCMP_TRUE:
1439 return getFCmp(predicate, C1, C2);
1441 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
1442 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
1443 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
1444 case CmpInst::ICMP_SLE:
1445 return getICmp(predicate, C1, C2);
1449 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2,
1451 // API compatibility: Adjust integer opcodes to floating-point opcodes.
1452 if (C1->getType()->isFPOrFPVectorTy()) {
1453 if (Opcode == Instruction::Add) Opcode = Instruction::FAdd;
1454 else if (Opcode == Instruction::Sub) Opcode = Instruction::FSub;
1455 else if (Opcode == Instruction::Mul) Opcode = Instruction::FMul;
1459 case Instruction::Add:
1460 case Instruction::Sub:
1461 case Instruction::Mul:
1462 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1463 assert(C1->getType()->isIntOrIntVectorTy() &&
1464 "Tried to create an integer operation on a non-integer type!");
1466 case Instruction::FAdd:
1467 case Instruction::FSub:
1468 case Instruction::FMul:
1469 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1470 assert(C1->getType()->isFPOrFPVectorTy() &&
1471 "Tried to create a floating-point operation on a "
1472 "non-floating-point type!");
1474 case Instruction::UDiv:
1475 case Instruction::SDiv:
1476 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1477 assert(C1->getType()->isIntOrIntVectorTy() &&
1478 "Tried to create an arithmetic operation on a non-arithmetic type!");
1480 case Instruction::FDiv:
1481 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1482 assert(C1->getType()->isFPOrFPVectorTy() &&
1483 "Tried to create an arithmetic operation on a non-arithmetic type!");
1485 case Instruction::URem:
1486 case Instruction::SRem:
1487 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1488 assert(C1->getType()->isIntOrIntVectorTy() &&
1489 "Tried to create an arithmetic operation on a non-arithmetic type!");
1491 case Instruction::FRem:
1492 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1493 assert(C1->getType()->isFPOrFPVectorTy() &&
1494 "Tried to create an arithmetic operation on a non-arithmetic type!");
1496 case Instruction::And:
1497 case Instruction::Or:
1498 case Instruction::Xor:
1499 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1500 assert(C1->getType()->isIntOrIntVectorTy() &&
1501 "Tried to create a logical operation on a non-integral type!");
1503 case Instruction::Shl:
1504 case Instruction::LShr:
1505 case Instruction::AShr:
1506 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1507 assert(C1->getType()->isIntOrIntVectorTy() &&
1508 "Tried to create a shift operation on a non-integer type!");
1515 return getTy(C1->getType(), Opcode, C1, C2, Flags);
1518 Constant* ConstantExpr::getSizeOf(const Type* Ty) {
1519 // sizeof is implemented as: (i64) gep (Ty*)null, 1
1520 // Note that a non-inbounds gep is used, as null isn't within any object.
1521 Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
1522 Constant *GEP = getGetElementPtr(
1523 Constant::getNullValue(PointerType::getUnqual(Ty)), &GEPIdx, 1);
1524 return getCast(Instruction::PtrToInt, GEP,
1525 Type::getInt64Ty(Ty->getContext()));
1528 Constant* ConstantExpr::getAlignOf(const Type* Ty) {
1529 // alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1
1530 // Note that a non-inbounds gep is used, as null isn't within any object.
1531 const Type *AligningTy = StructType::get(Ty->getContext(),
1532 Type::getInt1Ty(Ty->getContext()), Ty, NULL);
1533 Constant *NullPtr = Constant::getNullValue(AligningTy->getPointerTo());
1534 Constant *Zero = ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0);
1535 Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
1536 Constant *Indices[2] = { Zero, One };
1537 Constant *GEP = getGetElementPtr(NullPtr, Indices, 2);
1538 return getCast(Instruction::PtrToInt, GEP,
1539 Type::getInt64Ty(Ty->getContext()));
1542 Constant* ConstantExpr::getOffsetOf(const StructType* STy, unsigned FieldNo) {
1543 return getOffsetOf(STy, ConstantInt::get(Type::getInt32Ty(STy->getContext()),
1547 Constant* ConstantExpr::getOffsetOf(const Type* Ty, Constant *FieldNo) {
1548 // offsetof is implemented as: (i64) gep (Ty*)null, 0, FieldNo
1549 // Note that a non-inbounds gep is used, as null isn't within any object.
1550 Constant *GEPIdx[] = {
1551 ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0),
1554 Constant *GEP = getGetElementPtr(
1555 Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx, 2);
1556 return getCast(Instruction::PtrToInt, GEP,
1557 Type::getInt64Ty(Ty->getContext()));
1560 Constant *ConstantExpr::getCompare(unsigned short pred,
1561 Constant *C1, Constant *C2) {
1562 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1563 return getCompareTy(pred, C1, C2);
1566 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1567 Constant *V1, Constant *V2) {
1568 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
1570 if (ReqTy == V1->getType())
1571 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1572 return SC; // Fold common cases
1574 std::vector<Constant*> argVec(3, C);
1577 ExprMapKeyType Key(Instruction::Select, argVec);
1579 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1580 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1583 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1586 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs,
1588 cast<PointerType>(ReqTy)->getElementType() &&
1589 "GEP indices invalid!");
1591 if (Constant *FC = ConstantFoldGetElementPtr(C, /*inBounds=*/false,
1592 (Constant**)Idxs, NumIdx))
1593 return FC; // Fold a few common cases...
1595 assert(C->getType()->isPointerTy() &&
1596 "Non-pointer type for constant GetElementPtr expression");
1597 // Look up the constant in the table first to ensure uniqueness
1598 std::vector<Constant*> ArgVec;
1599 ArgVec.reserve(NumIdx+1);
1600 ArgVec.push_back(C);
1601 for (unsigned i = 0; i != NumIdx; ++i)
1602 ArgVec.push_back(cast<Constant>(Idxs[i]));
1603 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
1605 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1606 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1609 Constant *ConstantExpr::getInBoundsGetElementPtrTy(const Type *ReqTy,
1613 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs,
1615 cast<PointerType>(ReqTy)->getElementType() &&
1616 "GEP indices invalid!");
1618 if (Constant *FC = ConstantFoldGetElementPtr(C, /*inBounds=*/true,
1619 (Constant**)Idxs, NumIdx))
1620 return FC; // Fold a few common cases...
1622 assert(C->getType()->isPointerTy() &&
1623 "Non-pointer type for constant GetElementPtr expression");
1624 // Look up the constant in the table first to ensure uniqueness
1625 std::vector<Constant*> ArgVec;
1626 ArgVec.reserve(NumIdx+1);
1627 ArgVec.push_back(C);
1628 for (unsigned i = 0; i != NumIdx; ++i)
1629 ArgVec.push_back(cast<Constant>(Idxs[i]));
1630 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec, 0,
1631 GEPOperator::IsInBounds);
1633 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1634 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1637 Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
1639 // Get the result type of the getelementptr!
1641 GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx);
1642 assert(Ty && "GEP indices invalid!");
1643 unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
1644 return getGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx);
1647 Constant *ConstantExpr::getInBoundsGetElementPtr(Constant *C,
1650 // Get the result type of the getelementptr!
1652 GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx);
1653 assert(Ty && "GEP indices invalid!");
1654 unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
1655 return getInBoundsGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx);
1658 Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
1660 return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
1663 Constant *ConstantExpr::getInBoundsGetElementPtr(Constant *C,
1664 Constant* const *Idxs,
1666 return getInBoundsGetElementPtr(C, (Value* const *)Idxs, NumIdx);
1670 ConstantExpr::getICmp(unsigned short pred, Constant *LHS, Constant *RHS) {
1671 assert(LHS->getType() == RHS->getType());
1672 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
1673 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1675 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1676 return FC; // Fold a few common cases...
1678 // Look up the constant in the table first to ensure uniqueness
1679 std::vector<Constant*> ArgVec;
1680 ArgVec.push_back(LHS);
1681 ArgVec.push_back(RHS);
1682 // Get the key type with both the opcode and predicate
1683 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
1685 const Type *ResultTy = Type::getInt1Ty(LHS->getContext());
1686 if (const VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
1687 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
1689 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
1690 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
1694 ConstantExpr::getFCmp(unsigned short pred, Constant *LHS, Constant *RHS) {
1695 assert(LHS->getType() == RHS->getType());
1696 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1698 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1699 return FC; // Fold a few common cases...
1701 // Look up the constant in the table first to ensure uniqueness
1702 std::vector<Constant*> ArgVec;
1703 ArgVec.push_back(LHS);
1704 ArgVec.push_back(RHS);
1705 // Get the key type with both the opcode and predicate
1706 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
1708 const Type *ResultTy = Type::getInt1Ty(LHS->getContext());
1709 if (const VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
1710 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
1712 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
1713 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
1716 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
1718 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
1719 return FC; // Fold a few common cases.
1720 // Look up the constant in the table first to ensure uniqueness
1721 std::vector<Constant*> ArgVec(1, Val);
1722 ArgVec.push_back(Idx);
1723 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
1725 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1726 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1729 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
1730 assert(Val->getType()->isVectorTy() &&
1731 "Tried to create extractelement operation on non-vector type!");
1732 assert(Idx->getType()->isIntegerTy(32) &&
1733 "Extractelement index must be i32 type!");
1734 return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
1738 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
1739 Constant *Elt, Constant *Idx) {
1740 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
1741 return FC; // Fold a few common cases.
1742 // Look up the constant in the table first to ensure uniqueness
1743 std::vector<Constant*> ArgVec(1, Val);
1744 ArgVec.push_back(Elt);
1745 ArgVec.push_back(Idx);
1746 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
1748 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1749 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1752 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1754 assert(Val->getType()->isVectorTy() &&
1755 "Tried to create insertelement operation on non-vector type!");
1756 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
1757 && "Insertelement types must match!");
1758 assert(Idx->getType()->isIntegerTy(32) &&
1759 "Insertelement index must be i32 type!");
1760 return getInsertElementTy(Val->getType(), Val, Elt, Idx);
1763 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
1764 Constant *V2, Constant *Mask) {
1765 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
1766 return FC; // Fold a few common cases...
1767 // Look up the constant in the table first to ensure uniqueness
1768 std::vector<Constant*> ArgVec(1, V1);
1769 ArgVec.push_back(V2);
1770 ArgVec.push_back(Mask);
1771 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
1773 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1774 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1777 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
1779 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1780 "Invalid shuffle vector constant expr operands!");
1782 unsigned NElts = cast<VectorType>(Mask->getType())->getNumElements();
1783 const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
1784 const Type *ShufTy = VectorType::get(EltTy, NElts);
1785 return getShuffleVectorTy(ShufTy, V1, V2, Mask);
1788 Constant *ConstantExpr::getInsertValueTy(const Type *ReqTy, Constant *Agg,
1790 const unsigned *Idxs, unsigned NumIdx) {
1791 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
1792 Idxs+NumIdx) == Val->getType() &&
1793 "insertvalue indices invalid!");
1794 assert(Agg->getType() == ReqTy &&
1795 "insertvalue type invalid!");
1796 assert(Agg->getType()->isFirstClassType() &&
1797 "Non-first-class type for constant InsertValue expression");
1798 Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs, NumIdx);
1799 assert(FC && "InsertValue constant expr couldn't be folded!");
1803 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
1804 const unsigned *IdxList, unsigned NumIdx) {
1805 assert(Agg->getType()->isFirstClassType() &&
1806 "Tried to create insertelement operation on non-first-class type!");
1808 const Type *ReqTy = Agg->getType();
1811 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
1813 assert(ValTy == Val->getType() && "insertvalue indices invalid!");
1814 return getInsertValueTy(ReqTy, Agg, Val, IdxList, NumIdx);
1817 Constant *ConstantExpr::getExtractValueTy(const Type *ReqTy, Constant *Agg,
1818 const unsigned *Idxs, unsigned NumIdx) {
1819 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
1820 Idxs+NumIdx) == ReqTy &&
1821 "extractvalue indices invalid!");
1822 assert(Agg->getType()->isFirstClassType() &&
1823 "Non-first-class type for constant extractvalue expression");
1824 Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs, NumIdx);
1825 assert(FC && "ExtractValue constant expr couldn't be folded!");
1829 Constant *ConstantExpr::getExtractValue(Constant *Agg,
1830 const unsigned *IdxList, unsigned NumIdx) {
1831 assert(Agg->getType()->isFirstClassType() &&
1832 "Tried to create extractelement operation on non-first-class type!");
1835 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
1836 assert(ReqTy && "extractvalue indices invalid!");
1837 return getExtractValueTy(ReqTy, Agg, IdxList, NumIdx);
1840 Constant* ConstantExpr::getNeg(Constant* C) {
1841 // API compatibility: Adjust integer opcodes to floating-point opcodes.
1842 if (C->getType()->isFPOrFPVectorTy())
1844 assert(C->getType()->isIntOrIntVectorTy() &&
1845 "Cannot NEG a nonintegral value!");
1846 return get(Instruction::Sub,
1847 ConstantFP::getZeroValueForNegation(C->getType()),
1851 Constant* ConstantExpr::getFNeg(Constant* C) {
1852 assert(C->getType()->isFPOrFPVectorTy() &&
1853 "Cannot FNEG a non-floating-point value!");
1854 return get(Instruction::FSub,
1855 ConstantFP::getZeroValueForNegation(C->getType()),
1859 Constant* ConstantExpr::getNot(Constant* C) {
1860 assert(C->getType()->isIntOrIntVectorTy() &&
1861 "Cannot NOT a nonintegral value!");
1862 return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
1865 Constant* ConstantExpr::getAdd(Constant* C1, Constant* C2) {
1866 return get(Instruction::Add, C1, C2);
1869 Constant* ConstantExpr::getFAdd(Constant* C1, Constant* C2) {
1870 return get(Instruction::FAdd, C1, C2);
1873 Constant* ConstantExpr::getSub(Constant* C1, Constant* C2) {
1874 return get(Instruction::Sub, C1, C2);
1877 Constant* ConstantExpr::getFSub(Constant* C1, Constant* C2) {
1878 return get(Instruction::FSub, C1, C2);
1881 Constant* ConstantExpr::getMul(Constant* C1, Constant* C2) {
1882 return get(Instruction::Mul, C1, C2);
1885 Constant* ConstantExpr::getFMul(Constant* C1, Constant* C2) {
1886 return get(Instruction::FMul, C1, C2);
1889 Constant* ConstantExpr::getUDiv(Constant* C1, Constant* C2) {
1890 return get(Instruction::UDiv, C1, C2);
1893 Constant* ConstantExpr::getSDiv(Constant* C1, Constant* C2) {
1894 return get(Instruction::SDiv, C1, C2);
1897 Constant* ConstantExpr::getFDiv(Constant* C1, Constant* C2) {
1898 return get(Instruction::FDiv, C1, C2);
1901 Constant* ConstantExpr::getURem(Constant* C1, Constant* C2) {
1902 return get(Instruction::URem, C1, C2);
1905 Constant* ConstantExpr::getSRem(Constant* C1, Constant* C2) {
1906 return get(Instruction::SRem, C1, C2);
1909 Constant* ConstantExpr::getFRem(Constant* C1, Constant* C2) {
1910 return get(Instruction::FRem, C1, C2);
1913 Constant* ConstantExpr::getAnd(Constant* C1, Constant* C2) {
1914 return get(Instruction::And, C1, C2);
1917 Constant* ConstantExpr::getOr(Constant* C1, Constant* C2) {
1918 return get(Instruction::Or, C1, C2);
1921 Constant* ConstantExpr::getXor(Constant* C1, Constant* C2) {
1922 return get(Instruction::Xor, C1, C2);
1925 Constant* ConstantExpr::getShl(Constant* C1, Constant* C2) {
1926 return get(Instruction::Shl, C1, C2);
1929 Constant* ConstantExpr::getLShr(Constant* C1, Constant* C2) {
1930 return get(Instruction::LShr, C1, C2);
1933 Constant* ConstantExpr::getAShr(Constant* C1, Constant* C2) {
1934 return get(Instruction::AShr, C1, C2);
1937 // destroyConstant - Remove the constant from the constant table...
1939 void ConstantExpr::destroyConstant() {
1940 getType()->getContext().pImpl->ExprConstants.remove(this);
1941 destroyConstantImpl();
1944 const char *ConstantExpr::getOpcodeName() const {
1945 return Instruction::getOpcodeName(getOpcode());
1948 //===----------------------------------------------------------------------===//
1949 // replaceUsesOfWithOnConstant implementations
1951 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
1952 /// 'From' to be uses of 'To'. This must update the uniquing data structures
1955 /// Note that we intentionally replace all uses of From with To here. Consider
1956 /// a large array that uses 'From' 1000 times. By handling this case all here,
1957 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
1958 /// single invocation handles all 1000 uses. Handling them one at a time would
1959 /// work, but would be really slow because it would have to unique each updated
1962 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
1964 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1965 Constant *ToC = cast<Constant>(To);
1967 LLVMContext &Context = getType()->getContext();
1968 LLVMContextImpl *pImpl = Context.pImpl;
1970 std::pair<LLVMContextImpl::ArrayConstantsTy::MapKey, ConstantArray*> Lookup;
1971 Lookup.first.first = getType();
1972 Lookup.second = this;
1974 std::vector<Constant*> &Values = Lookup.first.second;
1975 Values.reserve(getNumOperands()); // Build replacement array.
1977 // Fill values with the modified operands of the constant array. Also,
1978 // compute whether this turns into an all-zeros array.
1979 bool isAllZeros = false;
1980 unsigned NumUpdated = 0;
1981 if (!ToC->isNullValue()) {
1982 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1983 Constant *Val = cast<Constant>(O->get());
1988 Values.push_back(Val);
1992 for (Use *O = OperandList, *E = OperandList+getNumOperands();O != E; ++O) {
1993 Constant *Val = cast<Constant>(O->get());
1998 Values.push_back(Val);
1999 if (isAllZeros) isAllZeros = Val->isNullValue();
2003 Constant *Replacement = 0;
2005 Replacement = ConstantAggregateZero::get(getType());
2007 // Check to see if we have this array type already.
2009 LLVMContextImpl::ArrayConstantsTy::MapTy::iterator I =
2010 pImpl->ArrayConstants.InsertOrGetItem(Lookup, Exists);
2013 Replacement = I->second;
2015 // Okay, the new shape doesn't exist in the system yet. Instead of
2016 // creating a new constant array, inserting it, replaceallusesof'ing the
2017 // old with the new, then deleting the old... just update the current one
2019 pImpl->ArrayConstants.MoveConstantToNewSlot(this, I);
2021 // Update to the new value. Optimize for the case when we have a single
2022 // operand that we're changing, but handle bulk updates efficiently.
2023 if (NumUpdated == 1) {
2024 unsigned OperandToUpdate = U - OperandList;
2025 assert(getOperand(OperandToUpdate) == From &&
2026 "ReplaceAllUsesWith broken!");
2027 setOperand(OperandToUpdate, ToC);
2029 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2030 if (getOperand(i) == From)
2037 // Otherwise, I do need to replace this with an existing value.
2038 assert(Replacement != this && "I didn't contain From!");
2040 // Everyone using this now uses the replacement.
2041 uncheckedReplaceAllUsesWith(Replacement);
2043 // Delete the old constant!
2047 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
2049 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2050 Constant *ToC = cast<Constant>(To);
2052 unsigned OperandToUpdate = U-OperandList;
2053 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2055 std::pair<LLVMContextImpl::StructConstantsTy::MapKey, ConstantStruct*> Lookup;
2056 Lookup.first.first = getType();
2057 Lookup.second = this;
2058 std::vector<Constant*> &Values = Lookup.first.second;
2059 Values.reserve(getNumOperands()); // Build replacement struct.
2062 // Fill values with the modified operands of the constant struct. Also,
2063 // compute whether this turns into an all-zeros struct.
2064 bool isAllZeros = false;
2065 if (!ToC->isNullValue()) {
2066 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O)
2067 Values.push_back(cast<Constant>(O->get()));
2070 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2071 Constant *Val = cast<Constant>(O->get());
2072 Values.push_back(Val);
2073 if (isAllZeros) isAllZeros = Val->isNullValue();
2076 Values[OperandToUpdate] = ToC;
2078 LLVMContext &Context = getType()->getContext();
2079 LLVMContextImpl *pImpl = Context.pImpl;
2081 Constant *Replacement = 0;
2083 Replacement = ConstantAggregateZero::get(getType());
2085 // Check to see if we have this array type already.
2087 LLVMContextImpl::StructConstantsTy::MapTy::iterator I =
2088 pImpl->StructConstants.InsertOrGetItem(Lookup, Exists);
2091 Replacement = I->second;
2093 // Okay, the new shape doesn't exist in the system yet. Instead of
2094 // creating a new constant struct, inserting it, replaceallusesof'ing the
2095 // old with the new, then deleting the old... just update the current one
2097 pImpl->StructConstants.MoveConstantToNewSlot(this, I);
2099 // Update to the new value.
2100 setOperand(OperandToUpdate, ToC);
2105 assert(Replacement != this && "I didn't contain From!");
2107 // Everyone using this now uses the replacement.
2108 uncheckedReplaceAllUsesWith(Replacement);
2110 // Delete the old constant!
2114 void ConstantUnion::replaceUsesOfWithOnConstant(Value *From, Value *To,
2116 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2117 Constant *ToC = cast<Constant>(To);
2119 assert(U == OperandList && "Union constants can only have one use!");
2120 assert(getNumOperands() == 1 && "Union constants can only have one use!");
2121 assert(getOperand(0) == From && "ReplaceAllUsesWith broken!");
2123 std::pair<LLVMContextImpl::UnionConstantsTy::MapKey, ConstantUnion*> Lookup;
2124 Lookup.first.first = getType();
2125 Lookup.second = this;
2126 Lookup.first.second = ToC;
2128 LLVMContext &Context = getType()->getContext();
2129 LLVMContextImpl *pImpl = Context.pImpl;
2131 Constant *Replacement = 0;
2132 if (ToC->isNullValue()) {
2133 Replacement = ConstantAggregateZero::get(getType());
2135 // Check to see if we have this union type already.
2137 LLVMContextImpl::UnionConstantsTy::MapTy::iterator I =
2138 pImpl->UnionConstants.InsertOrGetItem(Lookup, Exists);
2141 Replacement = I->second;
2143 // Okay, the new shape doesn't exist in the system yet. Instead of
2144 // creating a new constant union, inserting it, replaceallusesof'ing the
2145 // old with the new, then deleting the old... just update the current one
2147 pImpl->UnionConstants.MoveConstantToNewSlot(this, I);
2149 // Update to the new value.
2155 assert(Replacement != this && "I didn't contain From!");
2157 // Everyone using this now uses the replacement.
2158 uncheckedReplaceAllUsesWith(Replacement);
2160 // Delete the old constant!
2164 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
2166 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2168 std::vector<Constant*> Values;
2169 Values.reserve(getNumOperands()); // Build replacement array...
2170 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2171 Constant *Val = getOperand(i);
2172 if (Val == From) Val = cast<Constant>(To);
2173 Values.push_back(Val);
2176 Constant *Replacement = get(getType(), Values);
2177 assert(Replacement != this && "I didn't contain From!");
2179 // Everyone using this now uses the replacement.
2180 uncheckedReplaceAllUsesWith(Replacement);
2182 // Delete the old constant!
2186 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2188 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2189 Constant *To = cast<Constant>(ToV);
2191 Constant *Replacement = 0;
2192 if (getOpcode() == Instruction::GetElementPtr) {
2193 SmallVector<Constant*, 8> Indices;
2194 Constant *Pointer = getOperand(0);
2195 Indices.reserve(getNumOperands()-1);
2196 if (Pointer == From) Pointer = To;
2198 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2199 Constant *Val = getOperand(i);
2200 if (Val == From) Val = To;
2201 Indices.push_back(Val);
2203 Replacement = ConstantExpr::getGetElementPtr(Pointer,
2204 &Indices[0], Indices.size());
2205 } else if (getOpcode() == Instruction::ExtractValue) {
2206 Constant *Agg = getOperand(0);
2207 if (Agg == From) Agg = To;
2209 const SmallVector<unsigned, 4> &Indices = getIndices();
2210 Replacement = ConstantExpr::getExtractValue(Agg,
2211 &Indices[0], Indices.size());
2212 } else if (getOpcode() == Instruction::InsertValue) {
2213 Constant *Agg = getOperand(0);
2214 Constant *Val = getOperand(1);
2215 if (Agg == From) Agg = To;
2216 if (Val == From) Val = To;
2218 const SmallVector<unsigned, 4> &Indices = getIndices();
2219 Replacement = ConstantExpr::getInsertValue(Agg, Val,
2220 &Indices[0], Indices.size());
2221 } else if (isCast()) {
2222 assert(getOperand(0) == From && "Cast only has one use!");
2223 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
2224 } else if (getOpcode() == Instruction::Select) {
2225 Constant *C1 = getOperand(0);
2226 Constant *C2 = getOperand(1);
2227 Constant *C3 = getOperand(2);
2228 if (C1 == From) C1 = To;
2229 if (C2 == From) C2 = To;
2230 if (C3 == From) C3 = To;
2231 Replacement = ConstantExpr::getSelect(C1, C2, C3);
2232 } else if (getOpcode() == Instruction::ExtractElement) {
2233 Constant *C1 = getOperand(0);
2234 Constant *C2 = getOperand(1);
2235 if (C1 == From) C1 = To;
2236 if (C2 == From) C2 = To;
2237 Replacement = ConstantExpr::getExtractElement(C1, C2);
2238 } else if (getOpcode() == Instruction::InsertElement) {
2239 Constant *C1 = getOperand(0);
2240 Constant *C2 = getOperand(1);
2241 Constant *C3 = getOperand(1);
2242 if (C1 == From) C1 = To;
2243 if (C2 == From) C2 = To;
2244 if (C3 == From) C3 = To;
2245 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2246 } else if (getOpcode() == Instruction::ShuffleVector) {
2247 Constant *C1 = getOperand(0);
2248 Constant *C2 = getOperand(1);
2249 Constant *C3 = getOperand(2);
2250 if (C1 == From) C1 = To;
2251 if (C2 == From) C2 = To;
2252 if (C3 == From) C3 = To;
2253 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2254 } else if (isCompare()) {
2255 Constant *C1 = getOperand(0);
2256 Constant *C2 = getOperand(1);
2257 if (C1 == From) C1 = To;
2258 if (C2 == From) C2 = To;
2259 if (getOpcode() == Instruction::ICmp)
2260 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2262 assert(getOpcode() == Instruction::FCmp);
2263 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2265 } else if (getNumOperands() == 2) {
2266 Constant *C1 = getOperand(0);
2267 Constant *C2 = getOperand(1);
2268 if (C1 == From) C1 = To;
2269 if (C2 == From) C2 = To;
2270 Replacement = ConstantExpr::get(getOpcode(), C1, C2, SubclassOptionalData);
2272 llvm_unreachable("Unknown ConstantExpr type!");
2276 assert(Replacement != this && "I didn't contain From!");
2278 // Everyone using this now uses the replacement.
2279 uncheckedReplaceAllUsesWith(Replacement);
2281 // Delete the old constant!