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/IR/Constants.h"
15 #include "ConstantFold.h"
16 #include "LLVMContextImpl.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/FoldingSet.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/ADT/StringMap.h"
23 #include "llvm/IR/DerivedTypes.h"
24 #include "llvm/IR/GlobalValue.h"
25 #include "llvm/IR/Instructions.h"
26 #include "llvm/IR/Module.h"
27 #include "llvm/IR/Operator.h"
28 #include "llvm/Support/Compiler.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/GetElementPtrTypeIterator.h"
32 #include "llvm/Support/ManagedStatic.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/raw_ostream.h"
39 //===----------------------------------------------------------------------===//
41 //===----------------------------------------------------------------------===//
43 void Constant::anchor() { }
45 bool Constant::isNegativeZeroValue() const {
46 // Floating point values have an explicit -0.0 value.
47 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
48 return CFP->isZero() && CFP->isNegative();
50 // Equivalent for a vector of -0.0's.
51 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
52 if (ConstantFP *SplatCFP = dyn_cast_or_null<ConstantFP>(CV->getSplatValue()))
53 if (SplatCFP && SplatCFP->isZero() && SplatCFP->isNegative())
56 // We've already handled true FP case; any other FP vectors can't represent -0.0.
57 if (getType()->isFPOrFPVectorTy())
60 // Otherwise, just use +0.0.
64 // Return true iff this constant is positive zero (floating point), negative
65 // zero (floating point), or a null value.
66 bool Constant::isZeroValue() const {
67 // Floating point values have an explicit -0.0 value.
68 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
71 // Otherwise, just use +0.0.
75 bool Constant::isNullValue() const {
77 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
81 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
82 return CFP->isZero() && !CFP->isNegative();
84 // constant zero is zero for aggregates and cpnull is null for pointers.
85 return isa<ConstantAggregateZero>(this) || isa<ConstantPointerNull>(this);
88 bool Constant::isAllOnesValue() const {
89 // Check for -1 integers
90 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
91 return CI->isMinusOne();
93 // Check for FP which are bitcasted from -1 integers
94 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
95 return CFP->getValueAPF().bitcastToAPInt().isAllOnesValue();
97 // Check for constant vectors which are splats of -1 values.
98 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
99 if (Constant *Splat = CV->getSplatValue())
100 return Splat->isAllOnesValue();
102 // Check for constant vectors which are splats of -1 values.
103 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
104 if (Constant *Splat = CV->getSplatValue())
105 return Splat->isAllOnesValue();
110 // Constructor to create a '0' constant of arbitrary type...
111 Constant *Constant::getNullValue(Type *Ty) {
112 switch (Ty->getTypeID()) {
113 case Type::IntegerTyID:
114 return ConstantInt::get(Ty, 0);
116 return ConstantFP::get(Ty->getContext(),
117 APFloat::getZero(APFloat::IEEEhalf));
118 case Type::FloatTyID:
119 return ConstantFP::get(Ty->getContext(),
120 APFloat::getZero(APFloat::IEEEsingle));
121 case Type::DoubleTyID:
122 return ConstantFP::get(Ty->getContext(),
123 APFloat::getZero(APFloat::IEEEdouble));
124 case Type::X86_FP80TyID:
125 return ConstantFP::get(Ty->getContext(),
126 APFloat::getZero(APFloat::x87DoubleExtended));
127 case Type::FP128TyID:
128 return ConstantFP::get(Ty->getContext(),
129 APFloat::getZero(APFloat::IEEEquad));
130 case Type::PPC_FP128TyID:
131 return ConstantFP::get(Ty->getContext(),
132 APFloat(APFloat::PPCDoubleDouble,
133 APInt::getNullValue(128)));
134 case Type::PointerTyID:
135 return ConstantPointerNull::get(cast<PointerType>(Ty));
136 case Type::StructTyID:
137 case Type::ArrayTyID:
138 case Type::VectorTyID:
139 return ConstantAggregateZero::get(Ty);
141 // Function, Label, or Opaque type?
142 llvm_unreachable("Cannot create a null constant of that type!");
146 Constant *Constant::getIntegerValue(Type *Ty, const APInt &V) {
147 Type *ScalarTy = Ty->getScalarType();
149 // Create the base integer constant.
150 Constant *C = ConstantInt::get(Ty->getContext(), V);
152 // Convert an integer to a pointer, if necessary.
153 if (PointerType *PTy = dyn_cast<PointerType>(ScalarTy))
154 C = ConstantExpr::getIntToPtr(C, PTy);
156 // Broadcast a scalar to a vector, if necessary.
157 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
158 C = ConstantVector::getSplat(VTy->getNumElements(), C);
163 Constant *Constant::getAllOnesValue(Type *Ty) {
164 if (IntegerType *ITy = dyn_cast<IntegerType>(Ty))
165 return ConstantInt::get(Ty->getContext(),
166 APInt::getAllOnesValue(ITy->getBitWidth()));
168 if (Ty->isFloatingPointTy()) {
169 APFloat FL = APFloat::getAllOnesValue(Ty->getPrimitiveSizeInBits(),
170 !Ty->isPPC_FP128Ty());
171 return ConstantFP::get(Ty->getContext(), FL);
174 VectorType *VTy = cast<VectorType>(Ty);
175 return ConstantVector::getSplat(VTy->getNumElements(),
176 getAllOnesValue(VTy->getElementType()));
179 /// getAggregateElement - For aggregates (struct/array/vector) return the
180 /// constant that corresponds to the specified element if possible, or null if
181 /// not. This can return null if the element index is a ConstantExpr, or if
182 /// 'this' is a constant expr.
183 Constant *Constant::getAggregateElement(unsigned Elt) const {
184 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(this))
185 return Elt < CS->getNumOperands() ? CS->getOperand(Elt) : 0;
187 if (const ConstantArray *CA = dyn_cast<ConstantArray>(this))
188 return Elt < CA->getNumOperands() ? CA->getOperand(Elt) : 0;
190 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
191 return Elt < CV->getNumOperands() ? CV->getOperand(Elt) : 0;
193 if (const ConstantAggregateZero *CAZ =dyn_cast<ConstantAggregateZero>(this))
194 return CAZ->getElementValue(Elt);
196 if (const UndefValue *UV = dyn_cast<UndefValue>(this))
197 return UV->getElementValue(Elt);
199 if (const ConstantDataSequential *CDS =dyn_cast<ConstantDataSequential>(this))
200 return Elt < CDS->getNumElements() ? CDS->getElementAsConstant(Elt) : 0;
204 Constant *Constant::getAggregateElement(Constant *Elt) const {
205 assert(isa<IntegerType>(Elt->getType()) && "Index must be an integer");
206 if (ConstantInt *CI = dyn_cast<ConstantInt>(Elt))
207 return getAggregateElement(CI->getZExtValue());
212 void Constant::destroyConstantImpl() {
213 // When a Constant is destroyed, there may be lingering
214 // references to the constant by other constants in the constant pool. These
215 // constants are implicitly dependent on the module that is being deleted,
216 // but they don't know that. Because we only find out when the CPV is
217 // deleted, we must now notify all of our users (that should only be
218 // Constants) that they are, in fact, invalid now and should be deleted.
220 while (!use_empty()) {
221 Value *V = use_back();
222 #ifndef NDEBUG // Only in -g mode...
223 if (!isa<Constant>(V)) {
224 dbgs() << "While deleting: " << *this
225 << "\n\nUse still stuck around after Def is destroyed: "
229 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
230 cast<Constant>(V)->destroyConstant();
232 // The constant should remove itself from our use list...
233 assert((use_empty() || use_back() != V) && "Constant not removed!");
236 // Value has no outstanding references it is safe to delete it now...
240 /// canTrap - Return true if evaluation of this constant could trap. This is
241 /// true for things like constant expressions that could divide by zero.
242 bool Constant::canTrap() const {
243 assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
244 // The only thing that could possibly trap are constant exprs.
245 const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
246 if (!CE) return false;
248 // ConstantExpr traps if any operands can trap.
249 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
250 if (CE->getOperand(i)->canTrap())
253 // Otherwise, only specific operations can trap.
254 switch (CE->getOpcode()) {
257 case Instruction::UDiv:
258 case Instruction::SDiv:
259 case Instruction::FDiv:
260 case Instruction::URem:
261 case Instruction::SRem:
262 case Instruction::FRem:
263 // Div and rem can trap if the RHS is not known to be non-zero.
264 if (!isa<ConstantInt>(CE->getOperand(1)) ||CE->getOperand(1)->isNullValue())
270 /// isThreadDependent - Return true if the value can vary between threads.
271 bool Constant::isThreadDependent() const {
272 SmallPtrSet<const Constant*, 64> Visited;
273 SmallVector<const Constant*, 64> WorkList;
274 WorkList.push_back(this);
275 Visited.insert(this);
277 while (!WorkList.empty()) {
278 const Constant *C = WorkList.pop_back_val();
280 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
281 if (GV->isThreadLocal())
285 for (unsigned I = 0, E = C->getNumOperands(); I != E; ++I) {
286 const Constant *D = dyn_cast<Constant>(C->getOperand(I));
289 if (Visited.insert(D))
290 WorkList.push_back(D);
297 /// isConstantUsed - Return true if the constant has users other than constant
298 /// exprs and other dangling things.
299 bool Constant::isConstantUsed() const {
300 for (const_use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
301 const Constant *UC = dyn_cast<Constant>(*UI);
302 if (UC == 0 || isa<GlobalValue>(UC))
305 if (UC->isConstantUsed())
313 /// getRelocationInfo - This method classifies the entry according to
314 /// whether or not it may generate a relocation entry. This must be
315 /// conservative, so if it might codegen to a relocatable entry, it should say
316 /// so. The return values are:
318 /// NoRelocation: This constant pool entry is guaranteed to never have a
319 /// relocation applied to it (because it holds a simple constant like
321 /// LocalRelocation: This entry has relocations, but the entries are
322 /// guaranteed to be resolvable by the static linker, so the dynamic
323 /// linker will never see them.
324 /// GlobalRelocations: This entry may have arbitrary relocations.
326 /// FIXME: This really should not be in IR.
327 Constant::PossibleRelocationsTy Constant::getRelocationInfo() const {
328 if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
329 if (GV->hasLocalLinkage() || GV->hasHiddenVisibility())
330 return LocalRelocation; // Local to this file/library.
331 return GlobalRelocations; // Global reference.
334 if (const BlockAddress *BA = dyn_cast<BlockAddress>(this))
335 return BA->getFunction()->getRelocationInfo();
337 // While raw uses of blockaddress need to be relocated, differences between
338 // two of them don't when they are for labels in the same function. This is a
339 // common idiom when creating a table for the indirect goto extension, so we
340 // handle it efficiently here.
341 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(this))
342 if (CE->getOpcode() == Instruction::Sub) {
343 ConstantExpr *LHS = dyn_cast<ConstantExpr>(CE->getOperand(0));
344 ConstantExpr *RHS = dyn_cast<ConstantExpr>(CE->getOperand(1));
346 LHS->getOpcode() == Instruction::PtrToInt &&
347 RHS->getOpcode() == Instruction::PtrToInt &&
348 isa<BlockAddress>(LHS->getOperand(0)) &&
349 isa<BlockAddress>(RHS->getOperand(0)) &&
350 cast<BlockAddress>(LHS->getOperand(0))->getFunction() ==
351 cast<BlockAddress>(RHS->getOperand(0))->getFunction())
355 PossibleRelocationsTy Result = NoRelocation;
356 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
357 Result = std::max(Result,
358 cast<Constant>(getOperand(i))->getRelocationInfo());
363 /// removeDeadUsersOfConstant - If the specified constantexpr is dead, remove
364 /// it. This involves recursively eliminating any dead users of the
366 static bool removeDeadUsersOfConstant(const Constant *C) {
367 if (isa<GlobalValue>(C)) return false; // Cannot remove this
369 while (!C->use_empty()) {
370 const Constant *User = dyn_cast<Constant>(C->use_back());
371 if (!User) return false; // Non-constant usage;
372 if (!removeDeadUsersOfConstant(User))
373 return false; // Constant wasn't dead
376 const_cast<Constant*>(C)->destroyConstant();
381 /// removeDeadConstantUsers - If there are any dead constant users dangling
382 /// off of this constant, remove them. This method is useful for clients
383 /// that want to check to see if a global is unused, but don't want to deal
384 /// with potentially dead constants hanging off of the globals.
385 void Constant::removeDeadConstantUsers() const {
386 Value::const_use_iterator I = use_begin(), E = use_end();
387 Value::const_use_iterator LastNonDeadUser = E;
389 const Constant *User = dyn_cast<Constant>(*I);
396 if (!removeDeadUsersOfConstant(User)) {
397 // If the constant wasn't dead, remember that this was the last live use
398 // and move on to the next constant.
404 // If the constant was dead, then the iterator is invalidated.
405 if (LastNonDeadUser == E) {
417 //===----------------------------------------------------------------------===//
419 //===----------------------------------------------------------------------===//
421 void ConstantInt::anchor() { }
423 ConstantInt::ConstantInt(IntegerType *Ty, const APInt& V)
424 : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
425 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
428 ConstantInt *ConstantInt::getTrue(LLVMContext &Context) {
429 LLVMContextImpl *pImpl = Context.pImpl;
430 if (!pImpl->TheTrueVal)
431 pImpl->TheTrueVal = ConstantInt::get(Type::getInt1Ty(Context), 1);
432 return pImpl->TheTrueVal;
435 ConstantInt *ConstantInt::getFalse(LLVMContext &Context) {
436 LLVMContextImpl *pImpl = Context.pImpl;
437 if (!pImpl->TheFalseVal)
438 pImpl->TheFalseVal = ConstantInt::get(Type::getInt1Ty(Context), 0);
439 return pImpl->TheFalseVal;
442 Constant *ConstantInt::getTrue(Type *Ty) {
443 VectorType *VTy = dyn_cast<VectorType>(Ty);
445 assert(Ty->isIntegerTy(1) && "True must be i1 or vector of i1.");
446 return ConstantInt::getTrue(Ty->getContext());
448 assert(VTy->getElementType()->isIntegerTy(1) &&
449 "True must be vector of i1 or i1.");
450 return ConstantVector::getSplat(VTy->getNumElements(),
451 ConstantInt::getTrue(Ty->getContext()));
454 Constant *ConstantInt::getFalse(Type *Ty) {
455 VectorType *VTy = dyn_cast<VectorType>(Ty);
457 assert(Ty->isIntegerTy(1) && "False must be i1 or vector of i1.");
458 return ConstantInt::getFalse(Ty->getContext());
460 assert(VTy->getElementType()->isIntegerTy(1) &&
461 "False must be vector of i1 or i1.");
462 return ConstantVector::getSplat(VTy->getNumElements(),
463 ConstantInt::getFalse(Ty->getContext()));
467 // Get a ConstantInt from an APInt. Note that the value stored in the DenseMap
468 // as the key, is a DenseMapAPIntKeyInfo::KeyTy which has provided the
469 // operator== and operator!= to ensure that the DenseMap doesn't attempt to
470 // compare APInt's of different widths, which would violate an APInt class
471 // invariant which generates an assertion.
472 ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt &V) {
473 // Get the corresponding integer type for the bit width of the value.
474 IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
475 // get an existing value or the insertion position
476 DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
477 ConstantInt *&Slot = Context.pImpl->IntConstants[Key];
478 if (!Slot) Slot = new ConstantInt(ITy, V);
482 Constant *ConstantInt::get(Type *Ty, uint64_t V, bool isSigned) {
483 Constant *C = get(cast<IntegerType>(Ty->getScalarType()), V, isSigned);
485 // For vectors, broadcast the value.
486 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
487 return ConstantVector::getSplat(VTy->getNumElements(), C);
492 ConstantInt *ConstantInt::get(IntegerType *Ty, uint64_t V,
494 return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned));
497 ConstantInt *ConstantInt::getSigned(IntegerType *Ty, int64_t V) {
498 return get(Ty, V, true);
501 Constant *ConstantInt::getSigned(Type *Ty, int64_t V) {
502 return get(Ty, V, true);
505 Constant *ConstantInt::get(Type *Ty, const APInt& V) {
506 ConstantInt *C = get(Ty->getContext(), V);
507 assert(C->getType() == Ty->getScalarType() &&
508 "ConstantInt type doesn't match the type implied by its value!");
510 // For vectors, broadcast the value.
511 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
512 return ConstantVector::getSplat(VTy->getNumElements(), C);
517 ConstantInt *ConstantInt::get(IntegerType* Ty, StringRef Str,
519 return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
522 //===----------------------------------------------------------------------===//
524 //===----------------------------------------------------------------------===//
526 static const fltSemantics *TypeToFloatSemantics(Type *Ty) {
528 return &APFloat::IEEEhalf;
530 return &APFloat::IEEEsingle;
531 if (Ty->isDoubleTy())
532 return &APFloat::IEEEdouble;
533 if (Ty->isX86_FP80Ty())
534 return &APFloat::x87DoubleExtended;
535 else if (Ty->isFP128Ty())
536 return &APFloat::IEEEquad;
538 assert(Ty->isPPC_FP128Ty() && "Unknown FP format");
539 return &APFloat::PPCDoubleDouble;
542 void ConstantFP::anchor() { }
544 /// get() - This returns a constant fp for the specified value in the
545 /// specified type. This should only be used for simple constant values like
546 /// 2.0/1.0 etc, that are known-valid both as double and as the target format.
547 Constant *ConstantFP::get(Type *Ty, double V) {
548 LLVMContext &Context = Ty->getContext();
552 FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
553 APFloat::rmNearestTiesToEven, &ignored);
554 Constant *C = get(Context, FV);
556 // For vectors, broadcast the value.
557 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
558 return ConstantVector::getSplat(VTy->getNumElements(), C);
564 Constant *ConstantFP::get(Type *Ty, StringRef Str) {
565 LLVMContext &Context = Ty->getContext();
567 APFloat FV(*TypeToFloatSemantics(Ty->getScalarType()), Str);
568 Constant *C = get(Context, FV);
570 // For vectors, broadcast the value.
571 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
572 return ConstantVector::getSplat(VTy->getNumElements(), C);
578 ConstantFP *ConstantFP::getNegativeZero(Type *Ty) {
579 LLVMContext &Context = Ty->getContext();
580 APFloat apf = cast<ConstantFP>(Constant::getNullValue(Ty))->getValueAPF();
582 return get(Context, apf);
586 Constant *ConstantFP::getZeroValueForNegation(Type *Ty) {
587 Type *ScalarTy = Ty->getScalarType();
588 if (ScalarTy->isFloatingPointTy()) {
589 Constant *C = getNegativeZero(ScalarTy);
590 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
591 return ConstantVector::getSplat(VTy->getNumElements(), C);
595 return Constant::getNullValue(Ty);
599 // ConstantFP accessors.
600 ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
601 DenseMapAPFloatKeyInfo::KeyTy Key(V);
603 LLVMContextImpl* pImpl = Context.pImpl;
605 ConstantFP *&Slot = pImpl->FPConstants[Key];
609 if (&V.getSemantics() == &APFloat::IEEEhalf)
610 Ty = Type::getHalfTy(Context);
611 else if (&V.getSemantics() == &APFloat::IEEEsingle)
612 Ty = Type::getFloatTy(Context);
613 else if (&V.getSemantics() == &APFloat::IEEEdouble)
614 Ty = Type::getDoubleTy(Context);
615 else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
616 Ty = Type::getX86_FP80Ty(Context);
617 else if (&V.getSemantics() == &APFloat::IEEEquad)
618 Ty = Type::getFP128Ty(Context);
620 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble &&
621 "Unknown FP format");
622 Ty = Type::getPPC_FP128Ty(Context);
624 Slot = new ConstantFP(Ty, V);
630 ConstantFP *ConstantFP::getInfinity(Type *Ty, bool Negative) {
631 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty);
632 return ConstantFP::get(Ty->getContext(),
633 APFloat::getInf(Semantics, Negative));
636 ConstantFP::ConstantFP(Type *Ty, const APFloat& V)
637 : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
638 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
642 bool ConstantFP::isExactlyValue(const APFloat &V) const {
643 return Val.bitwiseIsEqual(V);
646 //===----------------------------------------------------------------------===//
647 // ConstantAggregateZero Implementation
648 //===----------------------------------------------------------------------===//
650 /// getSequentialElement - If this CAZ has array or vector type, return a zero
651 /// with the right element type.
652 Constant *ConstantAggregateZero::getSequentialElement() const {
653 return Constant::getNullValue(getType()->getSequentialElementType());
656 /// getStructElement - If this CAZ has struct type, return a zero with the
657 /// right element type for the specified element.
658 Constant *ConstantAggregateZero::getStructElement(unsigned Elt) const {
659 return Constant::getNullValue(getType()->getStructElementType(Elt));
662 /// getElementValue - Return a zero of the right value for the specified GEP
663 /// index if we can, otherwise return null (e.g. if C is a ConstantExpr).
664 Constant *ConstantAggregateZero::getElementValue(Constant *C) const {
665 if (isa<SequentialType>(getType()))
666 return getSequentialElement();
667 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
670 /// getElementValue - Return a zero of the right value for the specified GEP
672 Constant *ConstantAggregateZero::getElementValue(unsigned Idx) const {
673 if (isa<SequentialType>(getType()))
674 return getSequentialElement();
675 return getStructElement(Idx);
679 //===----------------------------------------------------------------------===//
680 // UndefValue Implementation
681 //===----------------------------------------------------------------------===//
683 /// getSequentialElement - If this undef has array or vector type, return an
684 /// undef with the right element type.
685 UndefValue *UndefValue::getSequentialElement() const {
686 return UndefValue::get(getType()->getSequentialElementType());
689 /// getStructElement - If this undef has struct type, return a zero with the
690 /// right element type for the specified element.
691 UndefValue *UndefValue::getStructElement(unsigned Elt) const {
692 return UndefValue::get(getType()->getStructElementType(Elt));
695 /// getElementValue - Return an undef of the right value for the specified GEP
696 /// index if we can, otherwise return null (e.g. if C is a ConstantExpr).
697 UndefValue *UndefValue::getElementValue(Constant *C) const {
698 if (isa<SequentialType>(getType()))
699 return getSequentialElement();
700 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
703 /// getElementValue - Return an undef of the right value for the specified GEP
705 UndefValue *UndefValue::getElementValue(unsigned Idx) const {
706 if (isa<SequentialType>(getType()))
707 return getSequentialElement();
708 return getStructElement(Idx);
713 //===----------------------------------------------------------------------===//
714 // ConstantXXX Classes
715 //===----------------------------------------------------------------------===//
717 template <typename ItTy, typename EltTy>
718 static bool rangeOnlyContains(ItTy Start, ItTy End, EltTy Elt) {
719 for (; Start != End; ++Start)
725 ConstantArray::ConstantArray(ArrayType *T, ArrayRef<Constant *> V)
726 : Constant(T, ConstantArrayVal,
727 OperandTraits<ConstantArray>::op_end(this) - V.size(),
729 assert(V.size() == T->getNumElements() &&
730 "Invalid initializer vector for constant array");
731 for (unsigned i = 0, e = V.size(); i != e; ++i)
732 assert(V[i]->getType() == T->getElementType() &&
733 "Initializer for array element doesn't match array element type!");
734 std::copy(V.begin(), V.end(), op_begin());
737 Constant *ConstantArray::get(ArrayType *Ty, ArrayRef<Constant*> V) {
738 // Empty arrays are canonicalized to ConstantAggregateZero.
740 return ConstantAggregateZero::get(Ty);
742 for (unsigned i = 0, e = V.size(); i != e; ++i) {
743 assert(V[i]->getType() == Ty->getElementType() &&
744 "Wrong type in array element initializer");
746 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
748 // If this is an all-zero array, return a ConstantAggregateZero object. If
749 // all undef, return an UndefValue, if "all simple", then return a
750 // ConstantDataArray.
752 if (isa<UndefValue>(C) && rangeOnlyContains(V.begin(), V.end(), C))
753 return UndefValue::get(Ty);
755 if (C->isNullValue() && rangeOnlyContains(V.begin(), V.end(), C))
756 return ConstantAggregateZero::get(Ty);
758 // Check to see if all of the elements are ConstantFP or ConstantInt and if
759 // the element type is compatible with ConstantDataVector. If so, use it.
760 if (ConstantDataSequential::isElementTypeCompatible(C->getType())) {
761 // We speculatively build the elements here even if it turns out that there
762 // is a constantexpr or something else weird in the array, since it is so
763 // uncommon for that to happen.
764 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
765 if (CI->getType()->isIntegerTy(8)) {
766 SmallVector<uint8_t, 16> Elts;
767 for (unsigned i = 0, e = V.size(); i != e; ++i)
768 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
769 Elts.push_back(CI->getZExtValue());
772 if (Elts.size() == V.size())
773 return ConstantDataArray::get(C->getContext(), Elts);
774 } else if (CI->getType()->isIntegerTy(16)) {
775 SmallVector<uint16_t, 16> Elts;
776 for (unsigned i = 0, e = V.size(); i != e; ++i)
777 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
778 Elts.push_back(CI->getZExtValue());
781 if (Elts.size() == V.size())
782 return ConstantDataArray::get(C->getContext(), Elts);
783 } else if (CI->getType()->isIntegerTy(32)) {
784 SmallVector<uint32_t, 16> Elts;
785 for (unsigned i = 0, e = V.size(); i != e; ++i)
786 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
787 Elts.push_back(CI->getZExtValue());
790 if (Elts.size() == V.size())
791 return ConstantDataArray::get(C->getContext(), Elts);
792 } else if (CI->getType()->isIntegerTy(64)) {
793 SmallVector<uint64_t, 16> Elts;
794 for (unsigned i = 0, e = V.size(); i != e; ++i)
795 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
796 Elts.push_back(CI->getZExtValue());
799 if (Elts.size() == V.size())
800 return ConstantDataArray::get(C->getContext(), Elts);
804 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
805 if (CFP->getType()->isFloatTy()) {
806 SmallVector<float, 16> Elts;
807 for (unsigned i = 0, e = V.size(); i != e; ++i)
808 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V[i]))
809 Elts.push_back(CFP->getValueAPF().convertToFloat());
812 if (Elts.size() == V.size())
813 return ConstantDataArray::get(C->getContext(), Elts);
814 } else if (CFP->getType()->isDoubleTy()) {
815 SmallVector<double, 16> Elts;
816 for (unsigned i = 0, e = V.size(); i != e; ++i)
817 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V[i]))
818 Elts.push_back(CFP->getValueAPF().convertToDouble());
821 if (Elts.size() == V.size())
822 return ConstantDataArray::get(C->getContext(), Elts);
827 // Otherwise, we really do want to create a ConstantArray.
828 return pImpl->ArrayConstants.getOrCreate(Ty, V);
831 /// getTypeForElements - Return an anonymous struct type to use for a constant
832 /// with the specified set of elements. The list must not be empty.
833 StructType *ConstantStruct::getTypeForElements(LLVMContext &Context,
834 ArrayRef<Constant*> V,
836 unsigned VecSize = V.size();
837 SmallVector<Type*, 16> EltTypes(VecSize);
838 for (unsigned i = 0; i != VecSize; ++i)
839 EltTypes[i] = V[i]->getType();
841 return StructType::get(Context, EltTypes, Packed);
845 StructType *ConstantStruct::getTypeForElements(ArrayRef<Constant*> V,
848 "ConstantStruct::getTypeForElements cannot be called on empty list");
849 return getTypeForElements(V[0]->getContext(), V, Packed);
853 ConstantStruct::ConstantStruct(StructType *T, ArrayRef<Constant *> V)
854 : Constant(T, ConstantStructVal,
855 OperandTraits<ConstantStruct>::op_end(this) - V.size(),
857 assert(V.size() == T->getNumElements() &&
858 "Invalid initializer vector for constant structure");
859 for (unsigned i = 0, e = V.size(); i != e; ++i)
860 assert((T->isOpaque() || V[i]->getType() == T->getElementType(i)) &&
861 "Initializer for struct element doesn't match struct element type!");
862 std::copy(V.begin(), V.end(), op_begin());
865 // ConstantStruct accessors.
866 Constant *ConstantStruct::get(StructType *ST, ArrayRef<Constant*> V) {
867 assert((ST->isOpaque() || ST->getNumElements() == V.size()) &&
868 "Incorrect # elements specified to ConstantStruct::get");
870 // Create a ConstantAggregateZero value if all elements are zeros.
872 bool isUndef = false;
875 isUndef = isa<UndefValue>(V[0]);
876 isZero = V[0]->isNullValue();
877 if (isUndef || isZero) {
878 for (unsigned i = 0, e = V.size(); i != e; ++i) {
879 if (!V[i]->isNullValue())
881 if (!isa<UndefValue>(V[i]))
887 return ConstantAggregateZero::get(ST);
889 return UndefValue::get(ST);
891 return ST->getContext().pImpl->StructConstants.getOrCreate(ST, V);
894 Constant *ConstantStruct::get(StructType *T, ...) {
896 SmallVector<Constant*, 8> Values;
898 while (Constant *Val = va_arg(ap, llvm::Constant*))
899 Values.push_back(Val);
901 return get(T, Values);
904 ConstantVector::ConstantVector(VectorType *T, ArrayRef<Constant *> V)
905 : Constant(T, ConstantVectorVal,
906 OperandTraits<ConstantVector>::op_end(this) - V.size(),
908 for (size_t i = 0, e = V.size(); i != e; i++)
909 assert(V[i]->getType() == T->getElementType() &&
910 "Initializer for vector element doesn't match vector element type!");
911 std::copy(V.begin(), V.end(), op_begin());
914 // ConstantVector accessors.
915 Constant *ConstantVector::get(ArrayRef<Constant*> V) {
916 assert(!V.empty() && "Vectors can't be empty");
917 VectorType *T = VectorType::get(V.front()->getType(), V.size());
918 LLVMContextImpl *pImpl = T->getContext().pImpl;
920 // If this is an all-undef or all-zero vector, return a
921 // ConstantAggregateZero or UndefValue.
923 bool isZero = C->isNullValue();
924 bool isUndef = isa<UndefValue>(C);
926 if (isZero || isUndef) {
927 for (unsigned i = 1, e = V.size(); i != e; ++i)
929 isZero = isUndef = false;
935 return ConstantAggregateZero::get(T);
937 return UndefValue::get(T);
939 // Check to see if all of the elements are ConstantFP or ConstantInt and if
940 // the element type is compatible with ConstantDataVector. If so, use it.
941 if (ConstantDataSequential::isElementTypeCompatible(C->getType())) {
942 // We speculatively build the elements here even if it turns out that there
943 // is a constantexpr or something else weird in the array, since it is so
944 // uncommon for that to happen.
945 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
946 if (CI->getType()->isIntegerTy(8)) {
947 SmallVector<uint8_t, 16> Elts;
948 for (unsigned i = 0, e = V.size(); i != e; ++i)
949 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
950 Elts.push_back(CI->getZExtValue());
953 if (Elts.size() == V.size())
954 return ConstantDataVector::get(C->getContext(), Elts);
955 } else if (CI->getType()->isIntegerTy(16)) {
956 SmallVector<uint16_t, 16> Elts;
957 for (unsigned i = 0, e = V.size(); i != e; ++i)
958 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
959 Elts.push_back(CI->getZExtValue());
962 if (Elts.size() == V.size())
963 return ConstantDataVector::get(C->getContext(), Elts);
964 } else if (CI->getType()->isIntegerTy(32)) {
965 SmallVector<uint32_t, 16> Elts;
966 for (unsigned i = 0, e = V.size(); i != e; ++i)
967 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
968 Elts.push_back(CI->getZExtValue());
971 if (Elts.size() == V.size())
972 return ConstantDataVector::get(C->getContext(), Elts);
973 } else if (CI->getType()->isIntegerTy(64)) {
974 SmallVector<uint64_t, 16> Elts;
975 for (unsigned i = 0, e = V.size(); i != e; ++i)
976 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
977 Elts.push_back(CI->getZExtValue());
980 if (Elts.size() == V.size())
981 return ConstantDataVector::get(C->getContext(), Elts);
985 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
986 if (CFP->getType()->isFloatTy()) {
987 SmallVector<float, 16> Elts;
988 for (unsigned i = 0, e = V.size(); i != e; ++i)
989 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V[i]))
990 Elts.push_back(CFP->getValueAPF().convertToFloat());
993 if (Elts.size() == V.size())
994 return ConstantDataVector::get(C->getContext(), Elts);
995 } else if (CFP->getType()->isDoubleTy()) {
996 SmallVector<double, 16> Elts;
997 for (unsigned i = 0, e = V.size(); i != e; ++i)
998 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V[i]))
999 Elts.push_back(CFP->getValueAPF().convertToDouble());
1002 if (Elts.size() == V.size())
1003 return ConstantDataVector::get(C->getContext(), Elts);
1008 // Otherwise, the element type isn't compatible with ConstantDataVector, or
1009 // the operand list constants a ConstantExpr or something else strange.
1010 return pImpl->VectorConstants.getOrCreate(T, V);
1013 Constant *ConstantVector::getSplat(unsigned NumElts, Constant *V) {
1014 // If this splat is compatible with ConstantDataVector, use it instead of
1016 if ((isa<ConstantFP>(V) || isa<ConstantInt>(V)) &&
1017 ConstantDataSequential::isElementTypeCompatible(V->getType()))
1018 return ConstantDataVector::getSplat(NumElts, V);
1020 SmallVector<Constant*, 32> Elts(NumElts, V);
1025 // Utility function for determining if a ConstantExpr is a CastOp or not. This
1026 // can't be inline because we don't want to #include Instruction.h into
1028 bool ConstantExpr::isCast() const {
1029 return Instruction::isCast(getOpcode());
1032 bool ConstantExpr::isCompare() const {
1033 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
1036 bool ConstantExpr::isGEPWithNoNotionalOverIndexing() const {
1037 if (getOpcode() != Instruction::GetElementPtr) return false;
1039 gep_type_iterator GEPI = gep_type_begin(this), E = gep_type_end(this);
1040 User::const_op_iterator OI = llvm::next(this->op_begin());
1042 // Skip the first index, as it has no static limit.
1046 // The remaining indices must be compile-time known integers within the
1047 // bounds of the corresponding notional static array types.
1048 for (; GEPI != E; ++GEPI, ++OI) {
1049 ConstantInt *CI = dyn_cast<ConstantInt>(*OI);
1050 if (!CI) return false;
1051 if (ArrayType *ATy = dyn_cast<ArrayType>(*GEPI))
1052 if (CI->getValue().getActiveBits() > 64 ||
1053 CI->getZExtValue() >= ATy->getNumElements())
1057 // All the indices checked out.
1061 bool ConstantExpr::hasIndices() const {
1062 return getOpcode() == Instruction::ExtractValue ||
1063 getOpcode() == Instruction::InsertValue;
1066 ArrayRef<unsigned> ConstantExpr::getIndices() const {
1067 if (const ExtractValueConstantExpr *EVCE =
1068 dyn_cast<ExtractValueConstantExpr>(this))
1069 return EVCE->Indices;
1071 return cast<InsertValueConstantExpr>(this)->Indices;
1074 unsigned ConstantExpr::getPredicate() const {
1075 assert(isCompare());
1076 return ((const CompareConstantExpr*)this)->predicate;
1079 /// getWithOperandReplaced - Return a constant expression identical to this
1080 /// one, but with the specified operand set to the specified value.
1082 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
1083 assert(Op->getType() == getOperand(OpNo)->getType() &&
1084 "Replacing operand with value of different type!");
1085 if (getOperand(OpNo) == Op)
1086 return const_cast<ConstantExpr*>(this);
1088 SmallVector<Constant*, 8> NewOps;
1089 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1090 NewOps.push_back(i == OpNo ? Op : getOperand(i));
1092 return getWithOperands(NewOps);
1095 /// getWithOperands - This returns the current constant expression with the
1096 /// operands replaced with the specified values. The specified array must
1097 /// have the same number of operands as our current one.
1098 Constant *ConstantExpr::
1099 getWithOperands(ArrayRef<Constant*> Ops, Type *Ty) const {
1100 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
1101 bool AnyChange = Ty != getType();
1102 for (unsigned i = 0; i != Ops.size(); ++i)
1103 AnyChange |= Ops[i] != getOperand(i);
1105 if (!AnyChange) // No operands changed, return self.
1106 return const_cast<ConstantExpr*>(this);
1108 switch (getOpcode()) {
1109 case Instruction::Trunc:
1110 case Instruction::ZExt:
1111 case Instruction::SExt:
1112 case Instruction::FPTrunc:
1113 case Instruction::FPExt:
1114 case Instruction::UIToFP:
1115 case Instruction::SIToFP:
1116 case Instruction::FPToUI:
1117 case Instruction::FPToSI:
1118 case Instruction::PtrToInt:
1119 case Instruction::IntToPtr:
1120 case Instruction::BitCast:
1121 return ConstantExpr::getCast(getOpcode(), Ops[0], Ty);
1122 case Instruction::Select:
1123 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
1124 case Instruction::InsertElement:
1125 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
1126 case Instruction::ExtractElement:
1127 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
1128 case Instruction::InsertValue:
1129 return ConstantExpr::getInsertValue(Ops[0], Ops[1], getIndices());
1130 case Instruction::ExtractValue:
1131 return ConstantExpr::getExtractValue(Ops[0], getIndices());
1132 case Instruction::ShuffleVector:
1133 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
1134 case Instruction::GetElementPtr:
1135 return ConstantExpr::getGetElementPtr(Ops[0], Ops.slice(1),
1136 cast<GEPOperator>(this)->isInBounds());
1137 case Instruction::ICmp:
1138 case Instruction::FCmp:
1139 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
1141 assert(getNumOperands() == 2 && "Must be binary operator?");
1142 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1], SubclassOptionalData);
1147 //===----------------------------------------------------------------------===//
1148 // isValueValidForType implementations
1150 bool ConstantInt::isValueValidForType(Type *Ty, uint64_t Val) {
1151 unsigned NumBits = Ty->getIntegerBitWidth(); // assert okay
1152 if (Ty->isIntegerTy(1))
1153 return Val == 0 || Val == 1;
1155 return true; // always true, has to fit in largest type
1156 uint64_t Max = (1ll << NumBits) - 1;
1160 bool ConstantInt::isValueValidForType(Type *Ty, int64_t Val) {
1161 unsigned NumBits = Ty->getIntegerBitWidth();
1162 if (Ty->isIntegerTy(1))
1163 return Val == 0 || Val == 1 || Val == -1;
1165 return true; // always true, has to fit in largest type
1166 int64_t Min = -(1ll << (NumBits-1));
1167 int64_t Max = (1ll << (NumBits-1)) - 1;
1168 return (Val >= Min && Val <= Max);
1171 bool ConstantFP::isValueValidForType(Type *Ty, const APFloat& Val) {
1172 // convert modifies in place, so make a copy.
1173 APFloat Val2 = APFloat(Val);
1175 switch (Ty->getTypeID()) {
1177 return false; // These can't be represented as floating point!
1179 // FIXME rounding mode needs to be more flexible
1180 case Type::HalfTyID: {
1181 if (&Val2.getSemantics() == &APFloat::IEEEhalf)
1183 Val2.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, &losesInfo);
1186 case Type::FloatTyID: {
1187 if (&Val2.getSemantics() == &APFloat::IEEEsingle)
1189 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
1192 case Type::DoubleTyID: {
1193 if (&Val2.getSemantics() == &APFloat::IEEEhalf ||
1194 &Val2.getSemantics() == &APFloat::IEEEsingle ||
1195 &Val2.getSemantics() == &APFloat::IEEEdouble)
1197 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
1200 case Type::X86_FP80TyID:
1201 return &Val2.getSemantics() == &APFloat::IEEEhalf ||
1202 &Val2.getSemantics() == &APFloat::IEEEsingle ||
1203 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1204 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
1205 case Type::FP128TyID:
1206 return &Val2.getSemantics() == &APFloat::IEEEhalf ||
1207 &Val2.getSemantics() == &APFloat::IEEEsingle ||
1208 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1209 &Val2.getSemantics() == &APFloat::IEEEquad;
1210 case Type::PPC_FP128TyID:
1211 return &Val2.getSemantics() == &APFloat::IEEEhalf ||
1212 &Val2.getSemantics() == &APFloat::IEEEsingle ||
1213 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1214 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
1219 //===----------------------------------------------------------------------===//
1220 // Factory Function Implementation
1222 ConstantAggregateZero *ConstantAggregateZero::get(Type *Ty) {
1223 assert((Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()) &&
1224 "Cannot create an aggregate zero of non-aggregate type!");
1226 ConstantAggregateZero *&Entry = Ty->getContext().pImpl->CAZConstants[Ty];
1228 Entry = new ConstantAggregateZero(Ty);
1233 /// destroyConstant - Remove the constant from the constant table.
1235 void ConstantAggregateZero::destroyConstant() {
1236 getContext().pImpl->CAZConstants.erase(getType());
1237 destroyConstantImpl();
1240 /// destroyConstant - Remove the constant from the constant table...
1242 void ConstantArray::destroyConstant() {
1243 getType()->getContext().pImpl->ArrayConstants.remove(this);
1244 destroyConstantImpl();
1248 //---- ConstantStruct::get() implementation...
1251 // destroyConstant - Remove the constant from the constant table...
1253 void ConstantStruct::destroyConstant() {
1254 getType()->getContext().pImpl->StructConstants.remove(this);
1255 destroyConstantImpl();
1258 // destroyConstant - Remove the constant from the constant table...
1260 void ConstantVector::destroyConstant() {
1261 getType()->getContext().pImpl->VectorConstants.remove(this);
1262 destroyConstantImpl();
1265 /// getSplatValue - If this is a splat vector constant, meaning that all of
1266 /// the elements have the same value, return that value. Otherwise return 0.
1267 Constant *Constant::getSplatValue() const {
1268 assert(this->getType()->isVectorTy() && "Only valid for vectors!");
1269 if (isa<ConstantAggregateZero>(this))
1270 return getNullValue(this->getType()->getVectorElementType());
1271 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
1272 return CV->getSplatValue();
1273 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
1274 return CV->getSplatValue();
1278 /// getSplatValue - If this is a splat constant, where all of the
1279 /// elements have the same value, return that value. Otherwise return null.
1280 Constant *ConstantVector::getSplatValue() const {
1281 // Check out first element.
1282 Constant *Elt = getOperand(0);
1283 // Then make sure all remaining elements point to the same value.
1284 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1285 if (getOperand(I) != Elt)
1290 /// If C is a constant integer then return its value, otherwise C must be a
1291 /// vector of constant integers, all equal, and the common value is returned.
1292 const APInt &Constant::getUniqueInteger() const {
1293 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
1294 return CI->getValue();
1295 assert(this->getSplatValue() && "Doesn't contain a unique integer!");
1296 const Constant *C = this->getAggregateElement(0U);
1297 assert(C && isa<ConstantInt>(C) && "Not a vector of numbers!");
1298 return cast<ConstantInt>(C)->getValue();
1302 //---- ConstantPointerNull::get() implementation.
1305 ConstantPointerNull *ConstantPointerNull::get(PointerType *Ty) {
1306 ConstantPointerNull *&Entry = Ty->getContext().pImpl->CPNConstants[Ty];
1308 Entry = new ConstantPointerNull(Ty);
1313 // destroyConstant - Remove the constant from the constant table...
1315 void ConstantPointerNull::destroyConstant() {
1316 getContext().pImpl->CPNConstants.erase(getType());
1317 // Free the constant and any dangling references to it.
1318 destroyConstantImpl();
1322 //---- UndefValue::get() implementation.
1325 UndefValue *UndefValue::get(Type *Ty) {
1326 UndefValue *&Entry = Ty->getContext().pImpl->UVConstants[Ty];
1328 Entry = new UndefValue(Ty);
1333 // destroyConstant - Remove the constant from the constant table.
1335 void UndefValue::destroyConstant() {
1336 // Free the constant and any dangling references to it.
1337 getContext().pImpl->UVConstants.erase(getType());
1338 destroyConstantImpl();
1341 //---- BlockAddress::get() implementation.
1344 BlockAddress *BlockAddress::get(BasicBlock *BB) {
1345 assert(BB->getParent() != 0 && "Block must have a parent");
1346 return get(BB->getParent(), BB);
1349 BlockAddress *BlockAddress::get(Function *F, BasicBlock *BB) {
1351 F->getContext().pImpl->BlockAddresses[std::make_pair(F, BB)];
1353 BA = new BlockAddress(F, BB);
1355 assert(BA->getFunction() == F && "Basic block moved between functions");
1359 BlockAddress::BlockAddress(Function *F, BasicBlock *BB)
1360 : Constant(Type::getInt8PtrTy(F->getContext()), Value::BlockAddressVal,
1364 BB->AdjustBlockAddressRefCount(1);
1368 // destroyConstant - Remove the constant from the constant table.
1370 void BlockAddress::destroyConstant() {
1371 getFunction()->getType()->getContext().pImpl
1372 ->BlockAddresses.erase(std::make_pair(getFunction(), getBasicBlock()));
1373 getBasicBlock()->AdjustBlockAddressRefCount(-1);
1374 destroyConstantImpl();
1377 void BlockAddress::replaceUsesOfWithOnConstant(Value *From, Value *To, Use *U) {
1378 // This could be replacing either the Basic Block or the Function. In either
1379 // case, we have to remove the map entry.
1380 Function *NewF = getFunction();
1381 BasicBlock *NewBB = getBasicBlock();
1384 NewF = cast<Function>(To);
1386 NewBB = cast<BasicBlock>(To);
1388 // See if the 'new' entry already exists, if not, just update this in place
1389 // and return early.
1390 BlockAddress *&NewBA =
1391 getContext().pImpl->BlockAddresses[std::make_pair(NewF, NewBB)];
1393 getBasicBlock()->AdjustBlockAddressRefCount(-1);
1395 // Remove the old entry, this can't cause the map to rehash (just a
1396 // tombstone will get added).
1397 getContext().pImpl->BlockAddresses.erase(std::make_pair(getFunction(),
1400 setOperand(0, NewF);
1401 setOperand(1, NewBB);
1402 getBasicBlock()->AdjustBlockAddressRefCount(1);
1406 // Otherwise, I do need to replace this with an existing value.
1407 assert(NewBA != this && "I didn't contain From!");
1409 // Everyone using this now uses the replacement.
1410 replaceAllUsesWith(NewBA);
1415 //---- ConstantExpr::get() implementations.
1418 /// This is a utility function to handle folding of casts and lookup of the
1419 /// cast in the ExprConstants map. It is used by the various get* methods below.
1420 static inline Constant *getFoldedCast(
1421 Instruction::CastOps opc, Constant *C, Type *Ty) {
1422 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1423 // Fold a few common cases
1424 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1427 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
1429 // Look up the constant in the table first to ensure uniqueness.
1430 ExprMapKeyType Key(opc, C);
1432 return pImpl->ExprConstants.getOrCreate(Ty, Key);
1435 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, Type *Ty) {
1436 Instruction::CastOps opc = Instruction::CastOps(oc);
1437 assert(Instruction::isCast(opc) && "opcode out of range");
1438 assert(C && Ty && "Null arguments to getCast");
1439 assert(CastInst::castIsValid(opc, C, Ty) && "Invalid constantexpr cast!");
1443 llvm_unreachable("Invalid cast opcode");
1444 case Instruction::Trunc: return getTrunc(C, Ty);
1445 case Instruction::ZExt: return getZExt(C, Ty);
1446 case Instruction::SExt: return getSExt(C, Ty);
1447 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1448 case Instruction::FPExt: return getFPExtend(C, Ty);
1449 case Instruction::UIToFP: return getUIToFP(C, Ty);
1450 case Instruction::SIToFP: return getSIToFP(C, Ty);
1451 case Instruction::FPToUI: return getFPToUI(C, Ty);
1452 case Instruction::FPToSI: return getFPToSI(C, Ty);
1453 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1454 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1455 case Instruction::BitCast: return getBitCast(C, Ty);
1459 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, Type *Ty) {
1460 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1461 return getBitCast(C, Ty);
1462 return getZExt(C, Ty);
1465 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, Type *Ty) {
1466 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1467 return getBitCast(C, Ty);
1468 return getSExt(C, Ty);
1471 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, Type *Ty) {
1472 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1473 return getBitCast(C, Ty);
1474 return getTrunc(C, Ty);
1477 Constant *ConstantExpr::getPointerCast(Constant *S, Type *Ty) {
1478 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
1479 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
1482 if (Ty->isIntOrIntVectorTy())
1483 return getPtrToInt(S, Ty);
1484 return getBitCast(S, Ty);
1487 Constant *ConstantExpr::getIntegerCast(Constant *C, Type *Ty,
1489 assert(C->getType()->isIntOrIntVectorTy() &&
1490 Ty->isIntOrIntVectorTy() && "Invalid cast");
1491 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1492 unsigned DstBits = Ty->getScalarSizeInBits();
1493 Instruction::CastOps opcode =
1494 (SrcBits == DstBits ? Instruction::BitCast :
1495 (SrcBits > DstBits ? Instruction::Trunc :
1496 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1497 return getCast(opcode, C, Ty);
1500 Constant *ConstantExpr::getFPCast(Constant *C, Type *Ty) {
1501 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1503 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1504 unsigned DstBits = Ty->getScalarSizeInBits();
1505 if (SrcBits == DstBits)
1506 return C; // Avoid a useless cast
1507 Instruction::CastOps opcode =
1508 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1509 return getCast(opcode, C, Ty);
1512 Constant *ConstantExpr::getTrunc(Constant *C, Type *Ty) {
1514 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1515 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1517 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1518 assert(C->getType()->isIntOrIntVectorTy() && "Trunc operand must be integer");
1519 assert(Ty->isIntOrIntVectorTy() && "Trunc produces only integral");
1520 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1521 "SrcTy must be larger than DestTy for Trunc!");
1523 return getFoldedCast(Instruction::Trunc, C, Ty);
1526 Constant *ConstantExpr::getSExt(Constant *C, Type *Ty) {
1528 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1529 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1531 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1532 assert(C->getType()->isIntOrIntVectorTy() && "SExt operand must be integral");
1533 assert(Ty->isIntOrIntVectorTy() && "SExt produces only integer");
1534 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1535 "SrcTy must be smaller than DestTy for SExt!");
1537 return getFoldedCast(Instruction::SExt, C, Ty);
1540 Constant *ConstantExpr::getZExt(Constant *C, Type *Ty) {
1542 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1543 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1545 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1546 assert(C->getType()->isIntOrIntVectorTy() && "ZEXt operand must be integral");
1547 assert(Ty->isIntOrIntVectorTy() && "ZExt produces only integer");
1548 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1549 "SrcTy must be smaller than DestTy for ZExt!");
1551 return getFoldedCast(Instruction::ZExt, C, Ty);
1554 Constant *ConstantExpr::getFPTrunc(Constant *C, Type *Ty) {
1556 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1557 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1559 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1560 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1561 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1562 "This is an illegal floating point truncation!");
1563 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1566 Constant *ConstantExpr::getFPExtend(Constant *C, Type *Ty) {
1568 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1569 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1571 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1572 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1573 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1574 "This is an illegal floating point extension!");
1575 return getFoldedCast(Instruction::FPExt, C, Ty);
1578 Constant *ConstantExpr::getUIToFP(Constant *C, Type *Ty) {
1580 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1581 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1583 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1584 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
1585 "This is an illegal uint to floating point cast!");
1586 return getFoldedCast(Instruction::UIToFP, C, Ty);
1589 Constant *ConstantExpr::getSIToFP(Constant *C, Type *Ty) {
1591 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1592 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1594 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1595 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
1596 "This is an illegal sint to floating point cast!");
1597 return getFoldedCast(Instruction::SIToFP, C, Ty);
1600 Constant *ConstantExpr::getFPToUI(Constant *C, Type *Ty) {
1602 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1603 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1605 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1606 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
1607 "This is an illegal floating point to uint cast!");
1608 return getFoldedCast(Instruction::FPToUI, C, Ty);
1611 Constant *ConstantExpr::getFPToSI(Constant *C, Type *Ty) {
1613 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1614 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1616 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1617 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
1618 "This is an illegal floating point to sint cast!");
1619 return getFoldedCast(Instruction::FPToSI, C, Ty);
1622 Constant *ConstantExpr::getPtrToInt(Constant *C, Type *DstTy) {
1623 assert(C->getType()->getScalarType()->isPointerTy() &&
1624 "PtrToInt source must be pointer or pointer vector");
1625 assert(DstTy->getScalarType()->isIntegerTy() &&
1626 "PtrToInt destination must be integer or integer vector");
1627 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
1628 if (isa<VectorType>(C->getType()))
1629 assert(C->getType()->getVectorNumElements()==DstTy->getVectorNumElements()&&
1630 "Invalid cast between a different number of vector elements");
1631 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1634 Constant *ConstantExpr::getIntToPtr(Constant *C, Type *DstTy) {
1635 assert(C->getType()->getScalarType()->isIntegerTy() &&
1636 "IntToPtr source must be integer or integer vector");
1637 assert(DstTy->getScalarType()->isPointerTy() &&
1638 "IntToPtr destination must be a pointer or pointer vector");
1639 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
1640 if (isa<VectorType>(C->getType()))
1641 assert(C->getType()->getVectorNumElements()==DstTy->getVectorNumElements()&&
1642 "Invalid cast between a different number of vector elements");
1643 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1646 Constant *ConstantExpr::getBitCast(Constant *C, Type *DstTy) {
1647 assert(CastInst::castIsValid(Instruction::BitCast, C, DstTy) &&
1648 "Invalid constantexpr bitcast!");
1650 // It is common to ask for a bitcast of a value to its own type, handle this
1652 if (C->getType() == DstTy) return C;
1654 return getFoldedCast(Instruction::BitCast, C, DstTy);
1657 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2,
1659 // Check the operands for consistency first.
1660 assert(Opcode >= Instruction::BinaryOpsBegin &&
1661 Opcode < Instruction::BinaryOpsEnd &&
1662 "Invalid opcode in binary constant expression");
1663 assert(C1->getType() == C2->getType() &&
1664 "Operand types in binary constant expression should match");
1668 case Instruction::Add:
1669 case Instruction::Sub:
1670 case Instruction::Mul:
1671 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1672 assert(C1->getType()->isIntOrIntVectorTy() &&
1673 "Tried to create an integer operation on a non-integer type!");
1675 case Instruction::FAdd:
1676 case Instruction::FSub:
1677 case Instruction::FMul:
1678 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1679 assert(C1->getType()->isFPOrFPVectorTy() &&
1680 "Tried to create a floating-point operation on a "
1681 "non-floating-point type!");
1683 case Instruction::UDiv:
1684 case Instruction::SDiv:
1685 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1686 assert(C1->getType()->isIntOrIntVectorTy() &&
1687 "Tried to create an arithmetic operation on a non-arithmetic type!");
1689 case Instruction::FDiv:
1690 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1691 assert(C1->getType()->isFPOrFPVectorTy() &&
1692 "Tried to create an arithmetic operation on a non-arithmetic type!");
1694 case Instruction::URem:
1695 case Instruction::SRem:
1696 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1697 assert(C1->getType()->isIntOrIntVectorTy() &&
1698 "Tried to create an arithmetic operation on a non-arithmetic type!");
1700 case Instruction::FRem:
1701 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1702 assert(C1->getType()->isFPOrFPVectorTy() &&
1703 "Tried to create an arithmetic operation on a non-arithmetic type!");
1705 case Instruction::And:
1706 case Instruction::Or:
1707 case Instruction::Xor:
1708 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1709 assert(C1->getType()->isIntOrIntVectorTy() &&
1710 "Tried to create a logical operation on a non-integral type!");
1712 case Instruction::Shl:
1713 case Instruction::LShr:
1714 case Instruction::AShr:
1715 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1716 assert(C1->getType()->isIntOrIntVectorTy() &&
1717 "Tried to create a shift operation on a non-integer type!");
1724 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1725 return FC; // Fold a few common cases.
1727 Constant *ArgVec[] = { C1, C2 };
1728 ExprMapKeyType Key(Opcode, ArgVec, 0, Flags);
1730 LLVMContextImpl *pImpl = C1->getContext().pImpl;
1731 return pImpl->ExprConstants.getOrCreate(C1->getType(), Key);
1734 Constant *ConstantExpr::getSizeOf(Type* Ty) {
1735 // sizeof is implemented as: (i64) gep (Ty*)null, 1
1736 // Note that a non-inbounds gep is used, as null isn't within any object.
1737 Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
1738 Constant *GEP = getGetElementPtr(
1739 Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
1740 return getPtrToInt(GEP,
1741 Type::getInt64Ty(Ty->getContext()));
1744 Constant *ConstantExpr::getAlignOf(Type* Ty) {
1745 // alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1
1746 // Note that a non-inbounds gep is used, as null isn't within any object.
1748 StructType::get(Type::getInt1Ty(Ty->getContext()), Ty, NULL);
1749 Constant *NullPtr = Constant::getNullValue(AligningTy->getPointerTo());
1750 Constant *Zero = ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0);
1751 Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
1752 Constant *Indices[2] = { Zero, One };
1753 Constant *GEP = getGetElementPtr(NullPtr, Indices);
1754 return getPtrToInt(GEP,
1755 Type::getInt64Ty(Ty->getContext()));
1758 Constant *ConstantExpr::getOffsetOf(StructType* STy, unsigned FieldNo) {
1759 return getOffsetOf(STy, ConstantInt::get(Type::getInt32Ty(STy->getContext()),
1763 Constant *ConstantExpr::getOffsetOf(Type* Ty, Constant *FieldNo) {
1764 // offsetof is implemented as: (i64) gep (Ty*)null, 0, FieldNo
1765 // Note that a non-inbounds gep is used, as null isn't within any object.
1766 Constant *GEPIdx[] = {
1767 ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0),
1770 Constant *GEP = getGetElementPtr(
1771 Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
1772 return getPtrToInt(GEP,
1773 Type::getInt64Ty(Ty->getContext()));
1776 Constant *ConstantExpr::getCompare(unsigned short Predicate,
1777 Constant *C1, Constant *C2) {
1778 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1780 switch (Predicate) {
1781 default: llvm_unreachable("Invalid CmpInst predicate");
1782 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
1783 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
1784 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
1785 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
1786 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
1787 case CmpInst::FCMP_TRUE:
1788 return getFCmp(Predicate, C1, C2);
1790 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
1791 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
1792 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
1793 case CmpInst::ICMP_SLE:
1794 return getICmp(Predicate, C1, C2);
1798 Constant *ConstantExpr::getSelect(Constant *C, Constant *V1, Constant *V2) {
1799 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
1801 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1802 return SC; // Fold common cases
1804 Constant *ArgVec[] = { C, V1, V2 };
1805 ExprMapKeyType Key(Instruction::Select, ArgVec);
1807 LLVMContextImpl *pImpl = C->getContext().pImpl;
1808 return pImpl->ExprConstants.getOrCreate(V1->getType(), Key);
1811 Constant *ConstantExpr::getGetElementPtr(Constant *C, ArrayRef<Value *> Idxs,
1813 assert(C->getType()->isPtrOrPtrVectorTy() &&
1814 "Non-pointer type for constant GetElementPtr expression");
1816 if (Constant *FC = ConstantFoldGetElementPtr(C, InBounds, Idxs))
1817 return FC; // Fold a few common cases.
1819 // Get the result type of the getelementptr!
1820 Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), Idxs);
1821 assert(Ty && "GEP indices invalid!");
1822 unsigned AS = C->getType()->getPointerAddressSpace();
1823 Type *ReqTy = Ty->getPointerTo(AS);
1824 if (VectorType *VecTy = dyn_cast<VectorType>(C->getType()))
1825 ReqTy = VectorType::get(ReqTy, VecTy->getNumElements());
1827 // Look up the constant in the table first to ensure uniqueness
1828 std::vector<Constant*> ArgVec;
1829 ArgVec.reserve(1 + Idxs.size());
1830 ArgVec.push_back(C);
1831 for (unsigned i = 0, e = Idxs.size(); i != e; ++i) {
1832 assert(Idxs[i]->getType()->isVectorTy() == ReqTy->isVectorTy() &&
1833 "getelementptr index type missmatch");
1834 assert((!Idxs[i]->getType()->isVectorTy() ||
1835 ReqTy->getVectorNumElements() ==
1836 Idxs[i]->getType()->getVectorNumElements()) &&
1837 "getelementptr index type missmatch");
1838 ArgVec.push_back(cast<Constant>(Idxs[i]));
1840 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec, 0,
1841 InBounds ? GEPOperator::IsInBounds : 0);
1843 LLVMContextImpl *pImpl = C->getContext().pImpl;
1844 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1848 ConstantExpr::getICmp(unsigned short pred, Constant *LHS, Constant *RHS) {
1849 assert(LHS->getType() == RHS->getType());
1850 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
1851 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1853 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1854 return FC; // Fold a few common cases...
1856 // Look up the constant in the table first to ensure uniqueness
1857 Constant *ArgVec[] = { LHS, RHS };
1858 // Get the key type with both the opcode and predicate
1859 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
1861 Type *ResultTy = Type::getInt1Ty(LHS->getContext());
1862 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
1863 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
1865 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
1866 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
1870 ConstantExpr::getFCmp(unsigned short pred, Constant *LHS, Constant *RHS) {
1871 assert(LHS->getType() == RHS->getType());
1872 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1874 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1875 return FC; // Fold a few common cases...
1877 // Look up the constant in the table first to ensure uniqueness
1878 Constant *ArgVec[] = { LHS, RHS };
1879 // Get the key type with both the opcode and predicate
1880 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
1882 Type *ResultTy = Type::getInt1Ty(LHS->getContext());
1883 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
1884 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
1886 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
1887 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
1890 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
1891 assert(Val->getType()->isVectorTy() &&
1892 "Tried to create extractelement operation on non-vector type!");
1893 assert(Idx->getType()->isIntegerTy(32) &&
1894 "Extractelement index must be i32 type!");
1896 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
1897 return FC; // Fold a few common cases.
1899 // Look up the constant in the table first to ensure uniqueness
1900 Constant *ArgVec[] = { Val, Idx };
1901 const ExprMapKeyType Key(Instruction::ExtractElement, ArgVec);
1903 LLVMContextImpl *pImpl = Val->getContext().pImpl;
1904 Type *ReqTy = Val->getType()->getVectorElementType();
1905 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1908 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1910 assert(Val->getType()->isVectorTy() &&
1911 "Tried to create insertelement operation on non-vector type!");
1912 assert(Elt->getType() == Val->getType()->getVectorElementType() &&
1913 "Insertelement types must match!");
1914 assert(Idx->getType()->isIntegerTy(32) &&
1915 "Insertelement index must be i32 type!");
1917 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
1918 return FC; // Fold a few common cases.
1919 // Look up the constant in the table first to ensure uniqueness
1920 Constant *ArgVec[] = { Val, Elt, Idx };
1921 const ExprMapKeyType Key(Instruction::InsertElement, ArgVec);
1923 LLVMContextImpl *pImpl = Val->getContext().pImpl;
1924 return pImpl->ExprConstants.getOrCreate(Val->getType(), Key);
1927 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
1929 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1930 "Invalid shuffle vector constant expr operands!");
1932 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
1933 return FC; // Fold a few common cases.
1935 unsigned NElts = Mask->getType()->getVectorNumElements();
1936 Type *EltTy = V1->getType()->getVectorElementType();
1937 Type *ShufTy = VectorType::get(EltTy, NElts);
1939 // Look up the constant in the table first to ensure uniqueness
1940 Constant *ArgVec[] = { V1, V2, Mask };
1941 const ExprMapKeyType Key(Instruction::ShuffleVector, ArgVec);
1943 LLVMContextImpl *pImpl = ShufTy->getContext().pImpl;
1944 return pImpl->ExprConstants.getOrCreate(ShufTy, Key);
1947 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
1948 ArrayRef<unsigned> Idxs) {
1949 assert(ExtractValueInst::getIndexedType(Agg->getType(),
1950 Idxs) == Val->getType() &&
1951 "insertvalue indices invalid!");
1952 assert(Agg->getType()->isFirstClassType() &&
1953 "Non-first-class type for constant insertvalue expression");
1954 Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs);
1955 assert(FC && "insertvalue constant expr couldn't be folded!");
1959 Constant *ConstantExpr::getExtractValue(Constant *Agg,
1960 ArrayRef<unsigned> Idxs) {
1961 assert(Agg->getType()->isFirstClassType() &&
1962 "Tried to create extractelement operation on non-first-class type!");
1964 Type *ReqTy = ExtractValueInst::getIndexedType(Agg->getType(), Idxs);
1966 assert(ReqTy && "extractvalue indices invalid!");
1968 assert(Agg->getType()->isFirstClassType() &&
1969 "Non-first-class type for constant extractvalue expression");
1970 Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs);
1971 assert(FC && "ExtractValue constant expr couldn't be folded!");
1975 Constant *ConstantExpr::getNeg(Constant *C, bool HasNUW, bool HasNSW) {
1976 assert(C->getType()->isIntOrIntVectorTy() &&
1977 "Cannot NEG a nonintegral value!");
1978 return getSub(ConstantFP::getZeroValueForNegation(C->getType()),
1982 Constant *ConstantExpr::getFNeg(Constant *C) {
1983 assert(C->getType()->isFPOrFPVectorTy() &&
1984 "Cannot FNEG a non-floating-point value!");
1985 return getFSub(ConstantFP::getZeroValueForNegation(C->getType()), C);
1988 Constant *ConstantExpr::getNot(Constant *C) {
1989 assert(C->getType()->isIntOrIntVectorTy() &&
1990 "Cannot NOT a nonintegral value!");
1991 return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
1994 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2,
1995 bool HasNUW, bool HasNSW) {
1996 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
1997 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
1998 return get(Instruction::Add, C1, C2, Flags);
2001 Constant *ConstantExpr::getFAdd(Constant *C1, Constant *C2) {
2002 return get(Instruction::FAdd, C1, C2);
2005 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2,
2006 bool HasNUW, bool HasNSW) {
2007 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2008 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2009 return get(Instruction::Sub, C1, C2, Flags);
2012 Constant *ConstantExpr::getFSub(Constant *C1, Constant *C2) {
2013 return get(Instruction::FSub, C1, C2);
2016 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2,
2017 bool HasNUW, bool HasNSW) {
2018 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2019 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2020 return get(Instruction::Mul, C1, C2, Flags);
2023 Constant *ConstantExpr::getFMul(Constant *C1, Constant *C2) {
2024 return get(Instruction::FMul, C1, C2);
2027 Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2, bool isExact) {
2028 return get(Instruction::UDiv, C1, C2,
2029 isExact ? PossiblyExactOperator::IsExact : 0);
2032 Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2, bool isExact) {
2033 return get(Instruction::SDiv, C1, C2,
2034 isExact ? PossiblyExactOperator::IsExact : 0);
2037 Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
2038 return get(Instruction::FDiv, C1, C2);
2041 Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
2042 return get(Instruction::URem, C1, C2);
2045 Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
2046 return get(Instruction::SRem, C1, C2);
2049 Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
2050 return get(Instruction::FRem, C1, C2);
2053 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
2054 return get(Instruction::And, C1, C2);
2057 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
2058 return get(Instruction::Or, C1, C2);
2061 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
2062 return get(Instruction::Xor, C1, C2);
2065 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2,
2066 bool HasNUW, bool HasNSW) {
2067 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2068 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2069 return get(Instruction::Shl, C1, C2, Flags);
2072 Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2, bool isExact) {
2073 return get(Instruction::LShr, C1, C2,
2074 isExact ? PossiblyExactOperator::IsExact : 0);
2077 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2, bool isExact) {
2078 return get(Instruction::AShr, C1, C2,
2079 isExact ? PossiblyExactOperator::IsExact : 0);
2082 /// getBinOpIdentity - Return the identity for the given binary operation,
2083 /// i.e. a constant C such that X op C = X and C op X = X for every X. It
2084 /// returns null if the operator doesn't have an identity.
2085 Constant *ConstantExpr::getBinOpIdentity(unsigned Opcode, Type *Ty) {
2088 // Doesn't have an identity.
2091 case Instruction::Add:
2092 case Instruction::Or:
2093 case Instruction::Xor:
2094 return Constant::getNullValue(Ty);
2096 case Instruction::Mul:
2097 return ConstantInt::get(Ty, 1);
2099 case Instruction::And:
2100 return Constant::getAllOnesValue(Ty);
2104 /// getBinOpAbsorber - Return the absorbing element for the given binary
2105 /// operation, i.e. a constant C such that X op C = C and C op X = C for
2106 /// every X. For example, this returns zero for integer multiplication.
2107 /// It returns null if the operator doesn't have an absorbing element.
2108 Constant *ConstantExpr::getBinOpAbsorber(unsigned Opcode, Type *Ty) {
2111 // Doesn't have an absorber.
2114 case Instruction::Or:
2115 return Constant::getAllOnesValue(Ty);
2117 case Instruction::And:
2118 case Instruction::Mul:
2119 return Constant::getNullValue(Ty);
2123 // destroyConstant - Remove the constant from the constant table...
2125 void ConstantExpr::destroyConstant() {
2126 getType()->getContext().pImpl->ExprConstants.remove(this);
2127 destroyConstantImpl();
2130 const char *ConstantExpr::getOpcodeName() const {
2131 return Instruction::getOpcodeName(getOpcode());
2136 GetElementPtrConstantExpr::
2137 GetElementPtrConstantExpr(Constant *C, ArrayRef<Constant*> IdxList,
2139 : ConstantExpr(DestTy, Instruction::GetElementPtr,
2140 OperandTraits<GetElementPtrConstantExpr>::op_end(this)
2141 - (IdxList.size()+1), IdxList.size()+1) {
2143 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
2144 OperandList[i+1] = IdxList[i];
2147 //===----------------------------------------------------------------------===//
2148 // ConstantData* implementations
2150 void ConstantDataArray::anchor() {}
2151 void ConstantDataVector::anchor() {}
2153 /// getElementType - Return the element type of the array/vector.
2154 Type *ConstantDataSequential::getElementType() const {
2155 return getType()->getElementType();
2158 StringRef ConstantDataSequential::getRawDataValues() const {
2159 return StringRef(DataElements, getNumElements()*getElementByteSize());
2162 /// isElementTypeCompatible - Return true if a ConstantDataSequential can be
2163 /// formed with a vector or array of the specified element type.
2164 /// ConstantDataArray only works with normal float and int types that are
2165 /// stored densely in memory, not with things like i42 or x86_f80.
2166 bool ConstantDataSequential::isElementTypeCompatible(const Type *Ty) {
2167 if (Ty->isFloatTy() || Ty->isDoubleTy()) return true;
2168 if (const IntegerType *IT = dyn_cast<IntegerType>(Ty)) {
2169 switch (IT->getBitWidth()) {
2181 /// getNumElements - Return the number of elements in the array or vector.
2182 unsigned ConstantDataSequential::getNumElements() const {
2183 if (ArrayType *AT = dyn_cast<ArrayType>(getType()))
2184 return AT->getNumElements();
2185 return getType()->getVectorNumElements();
2189 /// getElementByteSize - Return the size in bytes of the elements in the data.
2190 uint64_t ConstantDataSequential::getElementByteSize() const {
2191 return getElementType()->getPrimitiveSizeInBits()/8;
2194 /// getElementPointer - Return the start of the specified element.
2195 const char *ConstantDataSequential::getElementPointer(unsigned Elt) const {
2196 assert(Elt < getNumElements() && "Invalid Elt");
2197 return DataElements+Elt*getElementByteSize();
2201 /// isAllZeros - return true if the array is empty or all zeros.
2202 static bool isAllZeros(StringRef Arr) {
2203 for (StringRef::iterator I = Arr.begin(), E = Arr.end(); I != E; ++I)
2209 /// getImpl - This is the underlying implementation of all of the
2210 /// ConstantDataSequential::get methods. They all thunk down to here, providing
2211 /// the correct element type. We take the bytes in as a StringRef because
2212 /// we *want* an underlying "char*" to avoid TBAA type punning violations.
2213 Constant *ConstantDataSequential::getImpl(StringRef Elements, Type *Ty) {
2214 assert(isElementTypeCompatible(Ty->getSequentialElementType()));
2215 // If the elements are all zero or there are no elements, return a CAZ, which
2216 // is more dense and canonical.
2217 if (isAllZeros(Elements))
2218 return ConstantAggregateZero::get(Ty);
2220 // Do a lookup to see if we have already formed one of these.
2221 StringMap<ConstantDataSequential*>::MapEntryTy &Slot =
2222 Ty->getContext().pImpl->CDSConstants.GetOrCreateValue(Elements);
2224 // The bucket can point to a linked list of different CDS's that have the same
2225 // body but different types. For example, 0,0,0,1 could be a 4 element array
2226 // of i8, or a 1-element array of i32. They'll both end up in the same
2227 /// StringMap bucket, linked up by their Next pointers. Walk the list.
2228 ConstantDataSequential **Entry = &Slot.getValue();
2229 for (ConstantDataSequential *Node = *Entry; Node != 0;
2230 Entry = &Node->Next, Node = *Entry)
2231 if (Node->getType() == Ty)
2234 // Okay, we didn't get a hit. Create a node of the right class, link it in,
2236 if (isa<ArrayType>(Ty))
2237 return *Entry = new ConstantDataArray(Ty, Slot.getKeyData());
2239 assert(isa<VectorType>(Ty));
2240 return *Entry = new ConstantDataVector(Ty, Slot.getKeyData());
2243 void ConstantDataSequential::destroyConstant() {
2244 // Remove the constant from the StringMap.
2245 StringMap<ConstantDataSequential*> &CDSConstants =
2246 getType()->getContext().pImpl->CDSConstants;
2248 StringMap<ConstantDataSequential*>::iterator Slot =
2249 CDSConstants.find(getRawDataValues());
2251 assert(Slot != CDSConstants.end() && "CDS not found in uniquing table");
2253 ConstantDataSequential **Entry = &Slot->getValue();
2255 // Remove the entry from the hash table.
2256 if ((*Entry)->Next == 0) {
2257 // If there is only one value in the bucket (common case) it must be this
2258 // entry, and removing the entry should remove the bucket completely.
2259 assert((*Entry) == this && "Hash mismatch in ConstantDataSequential");
2260 getContext().pImpl->CDSConstants.erase(Slot);
2262 // Otherwise, there are multiple entries linked off the bucket, unlink the
2263 // node we care about but keep the bucket around.
2264 for (ConstantDataSequential *Node = *Entry; ;
2265 Entry = &Node->Next, Node = *Entry) {
2266 assert(Node && "Didn't find entry in its uniquing hash table!");
2267 // If we found our entry, unlink it from the list and we're done.
2269 *Entry = Node->Next;
2275 // If we were part of a list, make sure that we don't delete the list that is
2276 // still owned by the uniquing map.
2279 // Finally, actually delete it.
2280 destroyConstantImpl();
2283 /// get() constructors - Return a constant with array type with an element
2284 /// count and element type matching the ArrayRef passed in. Note that this
2285 /// can return a ConstantAggregateZero object.
2286 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint8_t> Elts) {
2287 Type *Ty = ArrayType::get(Type::getInt8Ty(Context), Elts.size());
2288 const char *Data = reinterpret_cast<const char *>(Elts.data());
2289 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*1), Ty);
2291 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint16_t> Elts){
2292 Type *Ty = ArrayType::get(Type::getInt16Ty(Context), Elts.size());
2293 const char *Data = reinterpret_cast<const char *>(Elts.data());
2294 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*2), Ty);
2296 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint32_t> Elts){
2297 Type *Ty = ArrayType::get(Type::getInt32Ty(Context), Elts.size());
2298 const char *Data = reinterpret_cast<const char *>(Elts.data());
2299 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
2301 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint64_t> Elts){
2302 Type *Ty = ArrayType::get(Type::getInt64Ty(Context), Elts.size());
2303 const char *Data = reinterpret_cast<const char *>(Elts.data());
2304 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*8), Ty);
2306 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<float> Elts) {
2307 Type *Ty = ArrayType::get(Type::getFloatTy(Context), Elts.size());
2308 const char *Data = reinterpret_cast<const char *>(Elts.data());
2309 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
2311 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<double> Elts) {
2312 Type *Ty = ArrayType::get(Type::getDoubleTy(Context), Elts.size());
2313 const char *Data = reinterpret_cast<const char *>(Elts.data());
2314 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*8), Ty);
2317 /// getString - This method constructs a CDS and initializes it with a text
2318 /// string. The default behavior (AddNull==true) causes a null terminator to
2319 /// be placed at the end of the array (increasing the length of the string by
2320 /// one more than the StringRef would normally indicate. Pass AddNull=false
2321 /// to disable this behavior.
2322 Constant *ConstantDataArray::getString(LLVMContext &Context,
2323 StringRef Str, bool AddNull) {
2325 const uint8_t *Data = reinterpret_cast<const uint8_t *>(Str.data());
2326 return get(Context, ArrayRef<uint8_t>(const_cast<uint8_t *>(Data),
2330 SmallVector<uint8_t, 64> ElementVals;
2331 ElementVals.append(Str.begin(), Str.end());
2332 ElementVals.push_back(0);
2333 return get(Context, ElementVals);
2336 /// get() constructors - Return a constant with vector type with an element
2337 /// count and element type matching the ArrayRef passed in. Note that this
2338 /// can return a ConstantAggregateZero object.
2339 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint8_t> Elts){
2340 Type *Ty = VectorType::get(Type::getInt8Ty(Context), Elts.size());
2341 const char *Data = reinterpret_cast<const char *>(Elts.data());
2342 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*1), Ty);
2344 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint16_t> Elts){
2345 Type *Ty = VectorType::get(Type::getInt16Ty(Context), Elts.size());
2346 const char *Data = reinterpret_cast<const char *>(Elts.data());
2347 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*2), Ty);
2349 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint32_t> Elts){
2350 Type *Ty = VectorType::get(Type::getInt32Ty(Context), Elts.size());
2351 const char *Data = reinterpret_cast<const char *>(Elts.data());
2352 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
2354 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint64_t> Elts){
2355 Type *Ty = VectorType::get(Type::getInt64Ty(Context), Elts.size());
2356 const char *Data = reinterpret_cast<const char *>(Elts.data());
2357 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*8), Ty);
2359 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<float> Elts) {
2360 Type *Ty = VectorType::get(Type::getFloatTy(Context), Elts.size());
2361 const char *Data = reinterpret_cast<const char *>(Elts.data());
2362 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
2364 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<double> Elts) {
2365 Type *Ty = VectorType::get(Type::getDoubleTy(Context), Elts.size());
2366 const char *Data = reinterpret_cast<const char *>(Elts.data());
2367 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*8), Ty);
2370 Constant *ConstantDataVector::getSplat(unsigned NumElts, Constant *V) {
2371 assert(isElementTypeCompatible(V->getType()) &&
2372 "Element type not compatible with ConstantData");
2373 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
2374 if (CI->getType()->isIntegerTy(8)) {
2375 SmallVector<uint8_t, 16> Elts(NumElts, CI->getZExtValue());
2376 return get(V->getContext(), Elts);
2378 if (CI->getType()->isIntegerTy(16)) {
2379 SmallVector<uint16_t, 16> Elts(NumElts, CI->getZExtValue());
2380 return get(V->getContext(), Elts);
2382 if (CI->getType()->isIntegerTy(32)) {
2383 SmallVector<uint32_t, 16> Elts(NumElts, CI->getZExtValue());
2384 return get(V->getContext(), Elts);
2386 assert(CI->getType()->isIntegerTy(64) && "Unsupported ConstantData type");
2387 SmallVector<uint64_t, 16> Elts(NumElts, CI->getZExtValue());
2388 return get(V->getContext(), Elts);
2391 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
2392 if (CFP->getType()->isFloatTy()) {
2393 SmallVector<float, 16> Elts(NumElts, CFP->getValueAPF().convertToFloat());
2394 return get(V->getContext(), Elts);
2396 if (CFP->getType()->isDoubleTy()) {
2397 SmallVector<double, 16> Elts(NumElts,
2398 CFP->getValueAPF().convertToDouble());
2399 return get(V->getContext(), Elts);
2402 return ConstantVector::getSplat(NumElts, V);
2406 /// getElementAsInteger - If this is a sequential container of integers (of
2407 /// any size), return the specified element in the low bits of a uint64_t.
2408 uint64_t ConstantDataSequential::getElementAsInteger(unsigned Elt) const {
2409 assert(isa<IntegerType>(getElementType()) &&
2410 "Accessor can only be used when element is an integer");
2411 const char *EltPtr = getElementPointer(Elt);
2413 // The data is stored in host byte order, make sure to cast back to the right
2414 // type to load with the right endianness.
2415 switch (getElementType()->getIntegerBitWidth()) {
2416 default: llvm_unreachable("Invalid bitwidth for CDS");
2418 return *const_cast<uint8_t *>(reinterpret_cast<const uint8_t *>(EltPtr));
2420 return *const_cast<uint16_t *>(reinterpret_cast<const uint16_t *>(EltPtr));
2422 return *const_cast<uint32_t *>(reinterpret_cast<const uint32_t *>(EltPtr));
2424 return *const_cast<uint64_t *>(reinterpret_cast<const uint64_t *>(EltPtr));
2428 /// getElementAsAPFloat - If this is a sequential container of floating point
2429 /// type, return the specified element as an APFloat.
2430 APFloat ConstantDataSequential::getElementAsAPFloat(unsigned Elt) const {
2431 const char *EltPtr = getElementPointer(Elt);
2433 switch (getElementType()->getTypeID()) {
2435 llvm_unreachable("Accessor can only be used when element is float/double!");
2436 case Type::FloatTyID: {
2437 const float *FloatPrt = reinterpret_cast<const float *>(EltPtr);
2438 return APFloat(*const_cast<float *>(FloatPrt));
2440 case Type::DoubleTyID: {
2441 const double *DoublePtr = reinterpret_cast<const double *>(EltPtr);
2442 return APFloat(*const_cast<double *>(DoublePtr));
2447 /// getElementAsFloat - If this is an sequential container of floats, return
2448 /// the specified element as a float.
2449 float ConstantDataSequential::getElementAsFloat(unsigned Elt) const {
2450 assert(getElementType()->isFloatTy() &&
2451 "Accessor can only be used when element is a 'float'");
2452 const float *EltPtr = reinterpret_cast<const float *>(getElementPointer(Elt));
2453 return *const_cast<float *>(EltPtr);
2456 /// getElementAsDouble - If this is an sequential container of doubles, return
2457 /// the specified element as a float.
2458 double ConstantDataSequential::getElementAsDouble(unsigned Elt) const {
2459 assert(getElementType()->isDoubleTy() &&
2460 "Accessor can only be used when element is a 'float'");
2461 const double *EltPtr =
2462 reinterpret_cast<const double *>(getElementPointer(Elt));
2463 return *const_cast<double *>(EltPtr);
2466 /// getElementAsConstant - Return a Constant for a specified index's element.
2467 /// Note that this has to compute a new constant to return, so it isn't as
2468 /// efficient as getElementAsInteger/Float/Double.
2469 Constant *ConstantDataSequential::getElementAsConstant(unsigned Elt) const {
2470 if (getElementType()->isFloatTy() || getElementType()->isDoubleTy())
2471 return ConstantFP::get(getContext(), getElementAsAPFloat(Elt));
2473 return ConstantInt::get(getElementType(), getElementAsInteger(Elt));
2476 /// isString - This method returns true if this is an array of i8.
2477 bool ConstantDataSequential::isString() const {
2478 return isa<ArrayType>(getType()) && getElementType()->isIntegerTy(8);
2481 /// isCString - This method returns true if the array "isString", ends with a
2482 /// nul byte, and does not contains any other nul bytes.
2483 bool ConstantDataSequential::isCString() const {
2487 StringRef Str = getAsString();
2489 // The last value must be nul.
2490 if (Str.back() != 0) return false;
2492 // Other elements must be non-nul.
2493 return Str.drop_back().find(0) == StringRef::npos;
2496 /// getSplatValue - If this is a splat constant, meaning that all of the
2497 /// elements have the same value, return that value. Otherwise return NULL.
2498 Constant *ConstantDataVector::getSplatValue() const {
2499 const char *Base = getRawDataValues().data();
2501 // Compare elements 1+ to the 0'th element.
2502 unsigned EltSize = getElementByteSize();
2503 for (unsigned i = 1, e = getNumElements(); i != e; ++i)
2504 if (memcmp(Base, Base+i*EltSize, EltSize))
2507 // If they're all the same, return the 0th one as a representative.
2508 return getElementAsConstant(0);
2511 //===----------------------------------------------------------------------===//
2512 // replaceUsesOfWithOnConstant implementations
2514 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
2515 /// 'From' to be uses of 'To'. This must update the uniquing data structures
2518 /// Note that we intentionally replace all uses of From with To here. Consider
2519 /// a large array that uses 'From' 1000 times. By handling this case all here,
2520 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
2521 /// single invocation handles all 1000 uses. Handling them one at a time would
2522 /// work, but would be really slow because it would have to unique each updated
2525 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
2527 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2528 Constant *ToC = cast<Constant>(To);
2530 LLVMContextImpl *pImpl = getType()->getContext().pImpl;
2532 SmallVector<Constant*, 8> Values;
2533 LLVMContextImpl::ArrayConstantsTy::LookupKey Lookup;
2534 Lookup.first = cast<ArrayType>(getType());
2535 Values.reserve(getNumOperands()); // Build replacement array.
2537 // Fill values with the modified operands of the constant array. Also,
2538 // compute whether this turns into an all-zeros array.
2539 unsigned NumUpdated = 0;
2541 // Keep track of whether all the values in the array are "ToC".
2542 bool AllSame = true;
2543 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2544 Constant *Val = cast<Constant>(O->get());
2549 Values.push_back(Val);
2550 AllSame &= Val == ToC;
2553 Constant *Replacement = 0;
2554 if (AllSame && ToC->isNullValue()) {
2555 Replacement = ConstantAggregateZero::get(getType());
2556 } else if (AllSame && isa<UndefValue>(ToC)) {
2557 Replacement = UndefValue::get(getType());
2559 // Check to see if we have this array type already.
2560 Lookup.second = makeArrayRef(Values);
2561 LLVMContextImpl::ArrayConstantsTy::MapTy::iterator I =
2562 pImpl->ArrayConstants.find(Lookup);
2564 if (I != pImpl->ArrayConstants.map_end()) {
2565 Replacement = I->first;
2567 // Okay, the new shape doesn't exist in the system yet. Instead of
2568 // creating a new constant array, inserting it, replaceallusesof'ing the
2569 // old with the new, then deleting the old... just update the current one
2571 pImpl->ArrayConstants.remove(this);
2573 // Update to the new value. Optimize for the case when we have a single
2574 // operand that we're changing, but handle bulk updates efficiently.
2575 if (NumUpdated == 1) {
2576 unsigned OperandToUpdate = U - OperandList;
2577 assert(getOperand(OperandToUpdate) == From &&
2578 "ReplaceAllUsesWith broken!");
2579 setOperand(OperandToUpdate, ToC);
2581 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2582 if (getOperand(i) == From)
2585 pImpl->ArrayConstants.insert(this);
2590 // Otherwise, I do need to replace this with an existing value.
2591 assert(Replacement != this && "I didn't contain From!");
2593 // Everyone using this now uses the replacement.
2594 replaceAllUsesWith(Replacement);
2596 // Delete the old constant!
2600 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
2602 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2603 Constant *ToC = cast<Constant>(To);
2605 unsigned OperandToUpdate = U-OperandList;
2606 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2608 SmallVector<Constant*, 8> Values;
2609 LLVMContextImpl::StructConstantsTy::LookupKey Lookup;
2610 Lookup.first = cast<StructType>(getType());
2611 Values.reserve(getNumOperands()); // Build replacement struct.
2613 // Fill values with the modified operands of the constant struct. Also,
2614 // compute whether this turns into an all-zeros struct.
2615 bool isAllZeros = false;
2616 bool isAllUndef = false;
2617 if (ToC->isNullValue()) {
2619 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2620 Constant *Val = cast<Constant>(O->get());
2621 Values.push_back(Val);
2622 if (isAllZeros) isAllZeros = Val->isNullValue();
2624 } else if (isa<UndefValue>(ToC)) {
2626 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2627 Constant *Val = cast<Constant>(O->get());
2628 Values.push_back(Val);
2629 if (isAllUndef) isAllUndef = isa<UndefValue>(Val);
2632 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O)
2633 Values.push_back(cast<Constant>(O->get()));
2635 Values[OperandToUpdate] = ToC;
2637 LLVMContextImpl *pImpl = getContext().pImpl;
2639 Constant *Replacement = 0;
2641 Replacement = ConstantAggregateZero::get(getType());
2642 } else if (isAllUndef) {
2643 Replacement = UndefValue::get(getType());
2645 // Check to see if we have this struct type already.
2646 Lookup.second = makeArrayRef(Values);
2647 LLVMContextImpl::StructConstantsTy::MapTy::iterator I =
2648 pImpl->StructConstants.find(Lookup);
2650 if (I != pImpl->StructConstants.map_end()) {
2651 Replacement = I->first;
2653 // Okay, the new shape doesn't exist in the system yet. Instead of
2654 // creating a new constant struct, inserting it, replaceallusesof'ing the
2655 // old with the new, then deleting the old... just update the current one
2657 pImpl->StructConstants.remove(this);
2659 // Update to the new value.
2660 setOperand(OperandToUpdate, ToC);
2661 pImpl->StructConstants.insert(this);
2666 assert(Replacement != this && "I didn't contain From!");
2668 // Everyone using this now uses the replacement.
2669 replaceAllUsesWith(Replacement);
2671 // Delete the old constant!
2675 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
2677 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2679 SmallVector<Constant*, 8> Values;
2680 Values.reserve(getNumOperands()); // Build replacement array...
2681 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2682 Constant *Val = getOperand(i);
2683 if (Val == From) Val = cast<Constant>(To);
2684 Values.push_back(Val);
2687 Constant *Replacement = get(Values);
2688 assert(Replacement != this && "I didn't contain From!");
2690 // Everyone using this now uses the replacement.
2691 replaceAllUsesWith(Replacement);
2693 // Delete the old constant!
2697 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2699 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2700 Constant *To = cast<Constant>(ToV);
2702 SmallVector<Constant*, 8> NewOps;
2703 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2704 Constant *Op = getOperand(i);
2705 NewOps.push_back(Op == From ? To : Op);
2708 Constant *Replacement = getWithOperands(NewOps);
2709 assert(Replacement != this && "I didn't contain From!");
2711 // Everyone using this now uses the replacement.
2712 replaceAllUsesWith(Replacement);
2714 // Delete the old constant!
2718 Instruction *ConstantExpr::getAsInstruction() {
2719 SmallVector<Value*,4> ValueOperands;
2720 for (op_iterator I = op_begin(), E = op_end(); I != E; ++I)
2721 ValueOperands.push_back(cast<Value>(I));
2723 ArrayRef<Value*> Ops(ValueOperands);
2725 switch (getOpcode()) {
2726 case Instruction::Trunc:
2727 case Instruction::ZExt:
2728 case Instruction::SExt:
2729 case Instruction::FPTrunc:
2730 case Instruction::FPExt:
2731 case Instruction::UIToFP:
2732 case Instruction::SIToFP:
2733 case Instruction::FPToUI:
2734 case Instruction::FPToSI:
2735 case Instruction::PtrToInt:
2736 case Instruction::IntToPtr:
2737 case Instruction::BitCast:
2738 return CastInst::Create((Instruction::CastOps)getOpcode(),
2740 case Instruction::Select:
2741 return SelectInst::Create(Ops[0], Ops[1], Ops[2]);
2742 case Instruction::InsertElement:
2743 return InsertElementInst::Create(Ops[0], Ops[1], Ops[2]);
2744 case Instruction::ExtractElement:
2745 return ExtractElementInst::Create(Ops[0], Ops[1]);
2746 case Instruction::InsertValue:
2747 return InsertValueInst::Create(Ops[0], Ops[1], getIndices());
2748 case Instruction::ExtractValue:
2749 return ExtractValueInst::Create(Ops[0], getIndices());
2750 case Instruction::ShuffleVector:
2751 return new ShuffleVectorInst(Ops[0], Ops[1], Ops[2]);
2753 case Instruction::GetElementPtr:
2754 if (cast<GEPOperator>(this)->isInBounds())
2755 return GetElementPtrInst::CreateInBounds(Ops[0], Ops.slice(1));
2757 return GetElementPtrInst::Create(Ops[0], Ops.slice(1));
2759 case Instruction::ICmp:
2760 case Instruction::FCmp:
2761 return CmpInst::Create((Instruction::OtherOps)getOpcode(),
2762 getPredicate(), Ops[0], Ops[1]);
2765 assert(getNumOperands() == 2 && "Must be binary operator?");
2766 BinaryOperator *BO =
2767 BinaryOperator::Create((Instruction::BinaryOps)getOpcode(),
2769 if (isa<OverflowingBinaryOperator>(BO)) {
2770 BO->setHasNoUnsignedWrap(SubclassOptionalData &
2771 OverflowingBinaryOperator::NoUnsignedWrap);
2772 BO->setHasNoSignedWrap(SubclassOptionalData &
2773 OverflowingBinaryOperator::NoSignedWrap);
2775 if (isa<PossiblyExactOperator>(BO))
2776 BO->setIsExact(SubclassOptionalData & PossiblyExactOperator::IsExact);