1 //===-- Constants.cpp - Implement Constant nodes --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Constant* classes...
12 //===----------------------------------------------------------------------===//
14 #include "LLVMContextImpl.h"
15 #include "llvm/Constants.h"
16 #include "ConstantFold.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/GlobalValue.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Module.h"
21 #include "llvm/Operator.h"
22 #include "llvm/ADT/FoldingSet.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/StringMap.h"
25 #include "llvm/Support/Compiler.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/ManagedStatic.h"
29 #include "llvm/Support/MathExtras.h"
30 #include "llvm/System/Mutex.h"
31 #include "llvm/System/RWMutex.h"
32 #include "llvm/System/Threading.h"
33 #include "llvm/ADT/DenseMap.h"
34 #include "llvm/ADT/SmallVector.h"
39 //===----------------------------------------------------------------------===//
41 //===----------------------------------------------------------------------===//
43 // Becomes a no-op when multithreading is disabled.
44 ManagedStatic<sys::SmartRWMutex<true> > ConstantsLock;
46 void Constant::destroyConstantImpl() {
47 // When a Constant is destroyed, there may be lingering
48 // references to the constant by other constants in the constant pool. These
49 // constants are implicitly dependent on the module that is being deleted,
50 // but they don't know that. Because we only find out when the CPV is
51 // deleted, we must now notify all of our users (that should only be
52 // Constants) that they are, in fact, invalid now and should be deleted.
54 while (!use_empty()) {
55 Value *V = use_back();
56 #ifndef NDEBUG // Only in -g mode...
57 if (!isa<Constant>(V))
58 DOUT << "While deleting: " << *this
59 << "\n\nUse still stuck around after Def is destroyed: "
62 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
63 Constant *CV = cast<Constant>(V);
64 CV->destroyConstant();
66 // The constant should remove itself from our use list...
67 assert((use_empty() || use_back() != V) && "Constant not removed!");
70 // Value has no outstanding references it is safe to delete it now...
74 /// canTrap - Return true if evaluation of this constant could trap. This is
75 /// true for things like constant expressions that could divide by zero.
76 bool Constant::canTrap() const {
77 assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
78 // The only thing that could possibly trap are constant exprs.
79 const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
80 if (!CE) return false;
82 // ConstantExpr traps if any operands can trap.
83 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
84 if (getOperand(i)->canTrap())
87 // Otherwise, only specific operations can trap.
88 switch (CE->getOpcode()) {
91 case Instruction::UDiv:
92 case Instruction::SDiv:
93 case Instruction::FDiv:
94 case Instruction::URem:
95 case Instruction::SRem:
96 case Instruction::FRem:
97 // Div and rem can trap if the RHS is not known to be non-zero.
98 if (!isa<ConstantInt>(getOperand(1)) || getOperand(1)->isNullValue())
105 /// getRelocationInfo - This method classifies the entry according to
106 /// whether or not it may generate a relocation entry. This must be
107 /// conservative, so if it might codegen to a relocatable entry, it should say
108 /// so. The return values are:
110 /// NoRelocation: This constant pool entry is guaranteed to never have a
111 /// relocation applied to it (because it holds a simple constant like
113 /// LocalRelocation: This entry has relocations, but the entries are
114 /// guaranteed to be resolvable by the static linker, so the dynamic
115 /// linker will never see them.
116 /// GlobalRelocations: This entry may have arbitrary relocations.
118 /// FIXME: This really should not be in VMCore.
119 Constant::PossibleRelocationsTy Constant::getRelocationInfo() const {
120 if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
121 if (GV->hasLocalLinkage() || GV->hasHiddenVisibility())
122 return LocalRelocation; // Local to this file/library.
123 return GlobalRelocations; // Global reference.
126 PossibleRelocationsTy Result = NoRelocation;
127 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
128 Result = std::max(Result, getOperand(i)->getRelocationInfo());
134 /// getVectorElements - This method, which is only valid on constant of vector
135 /// type, returns the elements of the vector in the specified smallvector.
136 /// This handles breaking down a vector undef into undef elements, etc. For
137 /// constant exprs and other cases we can't handle, we return an empty vector.
138 void Constant::getVectorElements(LLVMContext &Context,
139 SmallVectorImpl<Constant*> &Elts) const {
140 assert(isa<VectorType>(getType()) && "Not a vector constant!");
142 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this)) {
143 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i)
144 Elts.push_back(CV->getOperand(i));
148 const VectorType *VT = cast<VectorType>(getType());
149 if (isa<ConstantAggregateZero>(this)) {
150 Elts.assign(VT->getNumElements(),
151 Context.getNullValue(VT->getElementType()));
155 if (isa<UndefValue>(this)) {
156 Elts.assign(VT->getNumElements(), UndefValue::get(VT->getElementType()));
160 // Unknown type, must be constant expr etc.
165 //===----------------------------------------------------------------------===//
167 //===----------------------------------------------------------------------===//
169 ConstantInt::ConstantInt(const IntegerType *Ty, const APInt& V)
170 : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
171 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
174 // Get a ConstantInt from an APInt. Note that the value stored in the DenseMap
175 // as the key, is a DenseMapAPIntKeyInfo::KeyTy which has provided the
176 // operator== and operator!= to ensure that the DenseMap doesn't attempt to
177 // compare APInt's of different widths, which would violate an APInt class
178 // invariant which generates an assertion.
179 ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt& V) {
180 // Get the corresponding integer type for the bit width of the value.
181 const IntegerType *ITy = IntegerType::get(V.getBitWidth());
182 // get an existing value or the insertion position
183 DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
185 Context.pImpl->ConstantsLock.reader_acquire();
186 ConstantInt *&Slot = Context.pImpl->IntConstants[Key];
187 Context.pImpl->ConstantsLock.reader_release();
190 sys::SmartScopedWriter<true> Writer(Context.pImpl->ConstantsLock);
191 ConstantInt *&NewSlot = Context.pImpl->IntConstants[Key];
193 NewSlot = new ConstantInt(ITy, V);
202 Constant* ConstantInt::get(const Type* Ty, uint64_t V, bool isSigned) {
203 Constant *C = get(cast<IntegerType>(Ty->getScalarType()),
206 // For vectors, broadcast the value.
207 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
208 return ConstantVector::get(
209 std::vector<Constant *>(VTy->getNumElements(), C));
214 ConstantInt* ConstantInt::get(const IntegerType* Ty, uint64_t V,
216 return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned));
219 ConstantInt* ConstantInt::getSigned(const IntegerType* Ty, int64_t V) {
220 return get(Ty, V, true);
223 Constant *ConstantInt::getSigned(const Type *Ty, int64_t V) {
224 return get(Ty, V, true);
227 Constant* ConstantInt::get(const Type* Ty, const APInt& V) {
228 ConstantInt *C = get(Ty->getContext(), V);
229 assert(C->getType() == Ty->getScalarType() &&
230 "ConstantInt type doesn't match the type implied by its value!");
232 // For vectors, broadcast the value.
233 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
234 return ConstantVector::get(
235 std::vector<Constant *>(VTy->getNumElements(), C));
240 //===----------------------------------------------------------------------===//
242 //===----------------------------------------------------------------------===//
244 static const fltSemantics *TypeToFloatSemantics(const Type *Ty) {
245 if (Ty == Type::FloatTy)
246 return &APFloat::IEEEsingle;
247 if (Ty == Type::DoubleTy)
248 return &APFloat::IEEEdouble;
249 if (Ty == Type::X86_FP80Ty)
250 return &APFloat::x87DoubleExtended;
251 else if (Ty == Type::FP128Ty)
252 return &APFloat::IEEEquad;
254 assert(Ty == Type::PPC_FP128Ty && "Unknown FP format");
255 return &APFloat::PPCDoubleDouble;
258 /// get() - This returns a constant fp for the specified value in the
259 /// specified type. This should only be used for simple constant values like
260 /// 2.0/1.0 etc, that are known-valid both as double and as the target format.
261 Constant* ConstantFP::get(const Type* Ty, double V) {
262 LLVMContext &Context = Ty->getContext();
266 FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
267 APFloat::rmNearestTiesToEven, &ignored);
268 Constant *C = get(Context, FV);
270 // For vectors, broadcast the value.
271 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
272 return ConstantVector::get(
273 std::vector<Constant *>(VTy->getNumElements(), C));
278 ConstantFP* ConstantFP::getNegativeZero(const Type* Ty) {
279 LLVMContext &Context = Ty->getContext();
280 APFloat apf = cast <ConstantFP>(Context.getNullValue(Ty))->getValueAPF();
282 return get(Context, apf);
286 Constant* ConstantFP::getZeroValueForNegation(const Type* Ty) {
287 LLVMContext &Context = Ty->getContext();
288 if (const VectorType *PTy = dyn_cast<VectorType>(Ty))
289 if (PTy->getElementType()->isFloatingPoint()) {
290 std::vector<Constant*> zeros(PTy->getNumElements(),
291 getNegativeZero(PTy->getElementType()));
292 return ConstantVector::get(PTy, zeros);
295 if (Ty->isFloatingPoint())
296 return getNegativeZero(Ty);
298 return Context.getNullValue(Ty);
302 // ConstantFP accessors.
303 ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
304 DenseMapAPFloatKeyInfo::KeyTy Key(V);
306 LLVMContextImpl* pImpl = Context.pImpl;
308 pImpl->ConstantsLock.reader_acquire();
309 ConstantFP *&Slot = pImpl->FPConstants[Key];
310 pImpl->ConstantsLock.reader_release();
313 sys::SmartScopedWriter<true> Writer(pImpl->ConstantsLock);
314 ConstantFP *&NewSlot = pImpl->FPConstants[Key];
317 if (&V.getSemantics() == &APFloat::IEEEsingle)
319 else if (&V.getSemantics() == &APFloat::IEEEdouble)
321 else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
322 Ty = Type::X86_FP80Ty;
323 else if (&V.getSemantics() == &APFloat::IEEEquad)
326 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble &&
327 "Unknown FP format");
328 Ty = Type::PPC_FP128Ty;
330 NewSlot = new ConstantFP(Ty, V);
339 ConstantFP::ConstantFP(const Type *Ty, const APFloat& V)
340 : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
341 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
345 bool ConstantFP::isNullValue() const {
346 return Val.isZero() && !Val.isNegative();
349 bool ConstantFP::isExactlyValue(const APFloat& V) const {
350 return Val.bitwiseIsEqual(V);
353 //===----------------------------------------------------------------------===//
354 // ConstantXXX Classes
355 //===----------------------------------------------------------------------===//
358 ConstantArray::ConstantArray(const ArrayType *T,
359 const std::vector<Constant*> &V)
360 : Constant(T, ConstantArrayVal,
361 OperandTraits<ConstantArray>::op_end(this) - V.size(),
363 assert(V.size() == T->getNumElements() &&
364 "Invalid initializer vector for constant array");
365 Use *OL = OperandList;
366 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
369 assert((C->getType() == T->getElementType() ||
371 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
372 "Initializer for array element doesn't match array element type!");
377 Constant *ConstantArray::get(const ArrayType *Ty,
378 const std::vector<Constant*> &V) {
379 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
380 // If this is an all-zero array, return a ConstantAggregateZero object
383 if (!C->isNullValue()) {
384 // Implicitly locked.
385 return pImpl->ArrayConstants.getOrCreate(Ty, V);
387 for (unsigned i = 1, e = V.size(); i != e; ++i)
389 // Implicitly locked.
390 return pImpl->ArrayConstants.getOrCreate(Ty, V);
394 return ConstantAggregateZero::get(Ty);
398 Constant* ConstantArray::get(const ArrayType* T, Constant* const* Vals,
400 // FIXME: make this the primary ctor method.
401 return get(T, std::vector<Constant*>(Vals, Vals+NumVals));
404 /// ConstantArray::get(const string&) - Return an array that is initialized to
405 /// contain the specified string. If length is zero then a null terminator is
406 /// added to the specified string so that it may be used in a natural way.
407 /// Otherwise, the length parameter specifies how much of the string to use
408 /// and it won't be null terminated.
410 Constant* ConstantArray::get(const StringRef &Str, bool AddNull) {
411 std::vector<Constant*> ElementVals;
412 for (unsigned i = 0; i < Str.size(); ++i)
413 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, Str[i]));
415 // Add a null terminator to the string...
417 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, 0));
420 ArrayType *ATy = ArrayType::get(Type::Int8Ty, ElementVals.size());
421 return get(ATy, ElementVals);
426 ConstantStruct::ConstantStruct(const StructType *T,
427 const std::vector<Constant*> &V)
428 : Constant(T, ConstantStructVal,
429 OperandTraits<ConstantStruct>::op_end(this) - V.size(),
431 assert(V.size() == T->getNumElements() &&
432 "Invalid initializer vector for constant structure");
433 Use *OL = OperandList;
434 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
437 assert((C->getType() == T->getElementType(I-V.begin()) ||
438 ((T->getElementType(I-V.begin())->isAbstract() ||
439 C->getType()->isAbstract()) &&
440 T->getElementType(I-V.begin())->getTypeID() ==
441 C->getType()->getTypeID())) &&
442 "Initializer for struct element doesn't match struct element type!");
447 // ConstantStruct accessors.
448 Constant* ConstantStruct::get(const StructType* T,
449 const std::vector<Constant*>& V) {
450 LLVMContextImpl* pImpl = T->getContext().pImpl;
452 // Create a ConstantAggregateZero value if all elements are zeros...
453 for (unsigned i = 0, e = V.size(); i != e; ++i)
454 if (!V[i]->isNullValue())
455 // Implicitly locked.
456 return pImpl->StructConstants.getOrCreate(T, V);
458 return ConstantAggregateZero::get(T);
461 Constant* ConstantStruct::get(const std::vector<Constant*>& V, bool packed) {
462 std::vector<const Type*> StructEls;
463 StructEls.reserve(V.size());
464 for (unsigned i = 0, e = V.size(); i != e; ++i)
465 StructEls.push_back(V[i]->getType());
466 return get(StructType::get(StructEls, packed), V);
469 Constant* ConstantStruct::get(Constant* const *Vals, unsigned NumVals,
471 // FIXME: make this the primary ctor method.
472 return get(std::vector<Constant*>(Vals, Vals+NumVals), Packed);
475 ConstantVector::ConstantVector(const VectorType *T,
476 const std::vector<Constant*> &V)
477 : Constant(T, ConstantVectorVal,
478 OperandTraits<ConstantVector>::op_end(this) - V.size(),
480 Use *OL = OperandList;
481 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
484 assert((C->getType() == T->getElementType() ||
486 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
487 "Initializer for vector element doesn't match vector element type!");
492 // ConstantVector accessors.
493 Constant* ConstantVector::get(const VectorType* T,
494 const std::vector<Constant*>& V) {
495 assert(!V.empty() && "Vectors can't be empty");
496 LLVMContext &Context = T->getContext();
497 LLVMContextImpl *pImpl = Context.pImpl;
499 // If this is an all-undef or alll-zero vector, return a
500 // ConstantAggregateZero or UndefValue.
502 bool isZero = C->isNullValue();
503 bool isUndef = isa<UndefValue>(C);
505 if (isZero || isUndef) {
506 for (unsigned i = 1, e = V.size(); i != e; ++i)
508 isZero = isUndef = false;
514 return ConstantAggregateZero::get(T);
516 return UndefValue::get(T);
518 // Implicitly locked.
519 return pImpl->VectorConstants.getOrCreate(T, V);
522 Constant* ConstantVector::get(const std::vector<Constant*>& V) {
523 assert(!V.empty() && "Cannot infer type if V is empty");
524 return get(VectorType::get(V.front()->getType(),V.size()), V);
527 Constant* ConstantVector::get(Constant* const* Vals, unsigned NumVals) {
528 // FIXME: make this the primary ctor method.
529 return get(std::vector<Constant*>(Vals, Vals+NumVals));
534 // We declare several classes private to this file, so use an anonymous
538 /// UnaryConstantExpr - This class is private to Constants.cpp, and is used
539 /// behind the scenes to implement unary constant exprs.
540 class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
541 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
543 // allocate space for exactly one operand
544 void *operator new(size_t s) {
545 return User::operator new(s, 1);
547 UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
548 : ConstantExpr(Ty, Opcode, &Op<0>(), 1) {
551 /// Transparently provide more efficient getOperand methods.
552 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
555 /// BinaryConstantExpr - This class is private to Constants.cpp, and is used
556 /// behind the scenes to implement binary constant exprs.
557 class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
558 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
560 // allocate space for exactly two operands
561 void *operator new(size_t s) {
562 return User::operator new(s, 2);
564 BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
565 : ConstantExpr(C1->getType(), Opcode, &Op<0>(), 2) {
569 /// Transparently provide more efficient getOperand methods.
570 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
573 /// SelectConstantExpr - This class is private to Constants.cpp, and is used
574 /// behind the scenes to implement select constant exprs.
575 class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
576 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
578 // allocate space for exactly three operands
579 void *operator new(size_t s) {
580 return User::operator new(s, 3);
582 SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
583 : ConstantExpr(C2->getType(), Instruction::Select, &Op<0>(), 3) {
588 /// Transparently provide more efficient getOperand methods.
589 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
592 /// ExtractElementConstantExpr - This class is private to
593 /// Constants.cpp, and is used behind the scenes to implement
594 /// extractelement constant exprs.
595 class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
596 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
598 // allocate space for exactly two operands
599 void *operator new(size_t s) {
600 return User::operator new(s, 2);
602 ExtractElementConstantExpr(Constant *C1, Constant *C2)
603 : ConstantExpr(cast<VectorType>(C1->getType())->getElementType(),
604 Instruction::ExtractElement, &Op<0>(), 2) {
608 /// Transparently provide more efficient getOperand methods.
609 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
612 /// InsertElementConstantExpr - This class is private to
613 /// Constants.cpp, and is used behind the scenes to implement
614 /// insertelement constant exprs.
615 class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
616 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
618 // allocate space for exactly three operands
619 void *operator new(size_t s) {
620 return User::operator new(s, 3);
622 InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
623 : ConstantExpr(C1->getType(), Instruction::InsertElement,
629 /// Transparently provide more efficient getOperand methods.
630 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
633 /// ShuffleVectorConstantExpr - This class is private to
634 /// Constants.cpp, and is used behind the scenes to implement
635 /// shufflevector constant exprs.
636 class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
637 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
639 // allocate space for exactly three operands
640 void *operator new(size_t s) {
641 return User::operator new(s, 3);
643 ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
644 : ConstantExpr(VectorType::get(
645 cast<VectorType>(C1->getType())->getElementType(),
646 cast<VectorType>(C3->getType())->getNumElements()),
647 Instruction::ShuffleVector,
653 /// Transparently provide more efficient getOperand methods.
654 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
657 /// ExtractValueConstantExpr - This class is private to
658 /// Constants.cpp, and is used behind the scenes to implement
659 /// extractvalue constant exprs.
660 class VISIBILITY_HIDDEN ExtractValueConstantExpr : public ConstantExpr {
661 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
663 // allocate space for exactly one operand
664 void *operator new(size_t s) {
665 return User::operator new(s, 1);
667 ExtractValueConstantExpr(Constant *Agg,
668 const SmallVector<unsigned, 4> &IdxList,
670 : ConstantExpr(DestTy, Instruction::ExtractValue, &Op<0>(), 1),
675 /// Indices - These identify which value to extract.
676 const SmallVector<unsigned, 4> Indices;
678 /// Transparently provide more efficient getOperand methods.
679 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
682 /// InsertValueConstantExpr - This class is private to
683 /// Constants.cpp, and is used behind the scenes to implement
684 /// insertvalue constant exprs.
685 class VISIBILITY_HIDDEN InsertValueConstantExpr : public ConstantExpr {
686 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
688 // allocate space for exactly one operand
689 void *operator new(size_t s) {
690 return User::operator new(s, 2);
692 InsertValueConstantExpr(Constant *Agg, Constant *Val,
693 const SmallVector<unsigned, 4> &IdxList,
695 : ConstantExpr(DestTy, Instruction::InsertValue, &Op<0>(), 2),
701 /// Indices - These identify the position for the insertion.
702 const SmallVector<unsigned, 4> Indices;
704 /// Transparently provide more efficient getOperand methods.
705 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
709 /// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
710 /// used behind the scenes to implement getelementpr constant exprs.
711 class VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
712 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
715 static GetElementPtrConstantExpr *Create(Constant *C,
716 const std::vector<Constant*>&IdxList,
717 const Type *DestTy) {
719 new(IdxList.size() + 1) GetElementPtrConstantExpr(C, IdxList, DestTy);
721 /// Transparently provide more efficient getOperand methods.
722 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
725 // CompareConstantExpr - This class is private to Constants.cpp, and is used
726 // behind the scenes to implement ICmp and FCmp constant expressions. This is
727 // needed in order to store the predicate value for these instructions.
728 struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
729 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
730 // allocate space for exactly two operands
731 void *operator new(size_t s) {
732 return User::operator new(s, 2);
734 unsigned short predicate;
735 CompareConstantExpr(const Type *ty, Instruction::OtherOps opc,
736 unsigned short pred, Constant* LHS, Constant* RHS)
737 : ConstantExpr(ty, opc, &Op<0>(), 2), predicate(pred) {
741 /// Transparently provide more efficient getOperand methods.
742 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
745 } // end anonymous namespace
748 struct OperandTraits<UnaryConstantExpr> : FixedNumOperandTraits<1> {
750 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(UnaryConstantExpr, Value)
753 struct OperandTraits<BinaryConstantExpr> : FixedNumOperandTraits<2> {
755 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BinaryConstantExpr, Value)
758 struct OperandTraits<SelectConstantExpr> : FixedNumOperandTraits<3> {
760 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectConstantExpr, Value)
763 struct OperandTraits<ExtractElementConstantExpr> : FixedNumOperandTraits<2> {
765 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementConstantExpr, Value)
768 struct OperandTraits<InsertElementConstantExpr> : FixedNumOperandTraits<3> {
770 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementConstantExpr, Value)
773 struct OperandTraits<ShuffleVectorConstantExpr> : FixedNumOperandTraits<3> {
775 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorConstantExpr, Value)
778 struct OperandTraits<ExtractValueConstantExpr> : FixedNumOperandTraits<1> {
780 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractValueConstantExpr, Value)
783 struct OperandTraits<InsertValueConstantExpr> : FixedNumOperandTraits<2> {
785 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueConstantExpr, Value)
788 struct OperandTraits<GetElementPtrConstantExpr> : VariadicOperandTraits<1> {
791 GetElementPtrConstantExpr::GetElementPtrConstantExpr
793 const std::vector<Constant*> &IdxList,
795 : ConstantExpr(DestTy, Instruction::GetElementPtr,
796 OperandTraits<GetElementPtrConstantExpr>::op_end(this)
797 - (IdxList.size()+1),
800 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
801 OperandList[i+1] = IdxList[i];
804 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrConstantExpr, Value)
808 struct OperandTraits<CompareConstantExpr> : FixedNumOperandTraits<2> {
810 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CompareConstantExpr, Value)
813 } // End llvm namespace
816 // Utility function for determining if a ConstantExpr is a CastOp or not. This
817 // can't be inline because we don't want to #include Instruction.h into
819 bool ConstantExpr::isCast() const {
820 return Instruction::isCast(getOpcode());
823 bool ConstantExpr::isCompare() const {
824 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
827 bool ConstantExpr::hasIndices() const {
828 return getOpcode() == Instruction::ExtractValue ||
829 getOpcode() == Instruction::InsertValue;
832 const SmallVector<unsigned, 4> &ConstantExpr::getIndices() const {
833 if (const ExtractValueConstantExpr *EVCE =
834 dyn_cast<ExtractValueConstantExpr>(this))
835 return EVCE->Indices;
837 return cast<InsertValueConstantExpr>(this)->Indices;
840 unsigned ConstantExpr::getPredicate() const {
841 assert(getOpcode() == Instruction::FCmp ||
842 getOpcode() == Instruction::ICmp);
843 return ((const CompareConstantExpr*)this)->predicate;
846 /// getWithOperandReplaced - Return a constant expression identical to this
847 /// one, but with the specified operand set to the specified value.
849 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
850 assert(OpNo < getNumOperands() && "Operand num is out of range!");
851 assert(Op->getType() == getOperand(OpNo)->getType() &&
852 "Replacing operand with value of different type!");
853 if (getOperand(OpNo) == Op)
854 return const_cast<ConstantExpr*>(this);
856 Constant *Op0, *Op1, *Op2;
857 switch (getOpcode()) {
858 case Instruction::Trunc:
859 case Instruction::ZExt:
860 case Instruction::SExt:
861 case Instruction::FPTrunc:
862 case Instruction::FPExt:
863 case Instruction::UIToFP:
864 case Instruction::SIToFP:
865 case Instruction::FPToUI:
866 case Instruction::FPToSI:
867 case Instruction::PtrToInt:
868 case Instruction::IntToPtr:
869 case Instruction::BitCast:
870 return ConstantExpr::getCast(getOpcode(), Op, getType());
871 case Instruction::Select:
872 Op0 = (OpNo == 0) ? Op : getOperand(0);
873 Op1 = (OpNo == 1) ? Op : getOperand(1);
874 Op2 = (OpNo == 2) ? Op : getOperand(2);
875 return ConstantExpr::getSelect(Op0, Op1, Op2);
876 case Instruction::InsertElement:
877 Op0 = (OpNo == 0) ? Op : getOperand(0);
878 Op1 = (OpNo == 1) ? Op : getOperand(1);
879 Op2 = (OpNo == 2) ? Op : getOperand(2);
880 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
881 case Instruction::ExtractElement:
882 Op0 = (OpNo == 0) ? Op : getOperand(0);
883 Op1 = (OpNo == 1) ? Op : getOperand(1);
884 return ConstantExpr::getExtractElement(Op0, Op1);
885 case Instruction::ShuffleVector:
886 Op0 = (OpNo == 0) ? Op : getOperand(0);
887 Op1 = (OpNo == 1) ? Op : getOperand(1);
888 Op2 = (OpNo == 2) ? Op : getOperand(2);
889 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
890 case Instruction::GetElementPtr: {
891 SmallVector<Constant*, 8> Ops;
892 Ops.resize(getNumOperands()-1);
893 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
894 Ops[i-1] = getOperand(i);
896 return ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
898 return ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
901 assert(getNumOperands() == 2 && "Must be binary operator?");
902 Op0 = (OpNo == 0) ? Op : getOperand(0);
903 Op1 = (OpNo == 1) ? Op : getOperand(1);
904 return ConstantExpr::get(getOpcode(), Op0, Op1);
908 /// getWithOperands - This returns the current constant expression with the
909 /// operands replaced with the specified values. The specified operands must
910 /// match count and type with the existing ones.
911 Constant *ConstantExpr::
912 getWithOperands(Constant* const *Ops, unsigned NumOps) const {
913 assert(NumOps == getNumOperands() && "Operand count mismatch!");
914 bool AnyChange = false;
915 for (unsigned i = 0; i != NumOps; ++i) {
916 assert(Ops[i]->getType() == getOperand(i)->getType() &&
917 "Operand type mismatch!");
918 AnyChange |= Ops[i] != getOperand(i);
920 if (!AnyChange) // No operands changed, return self.
921 return const_cast<ConstantExpr*>(this);
923 switch (getOpcode()) {
924 case Instruction::Trunc:
925 case Instruction::ZExt:
926 case Instruction::SExt:
927 case Instruction::FPTrunc:
928 case Instruction::FPExt:
929 case Instruction::UIToFP:
930 case Instruction::SIToFP:
931 case Instruction::FPToUI:
932 case Instruction::FPToSI:
933 case Instruction::PtrToInt:
934 case Instruction::IntToPtr:
935 case Instruction::BitCast:
936 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
937 case Instruction::Select:
938 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
939 case Instruction::InsertElement:
940 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
941 case Instruction::ExtractElement:
942 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
943 case Instruction::ShuffleVector:
944 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
945 case Instruction::GetElementPtr:
946 return ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], NumOps-1);
947 case Instruction::ICmp:
948 case Instruction::FCmp:
949 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
951 assert(getNumOperands() == 2 && "Must be binary operator?");
952 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
957 //===----------------------------------------------------------------------===//
958 // isValueValidForType implementations
960 bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
961 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
962 if (Ty == Type::Int1Ty)
963 return Val == 0 || Val == 1;
965 return true; // always true, has to fit in largest type
966 uint64_t Max = (1ll << NumBits) - 1;
970 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
971 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
972 if (Ty == Type::Int1Ty)
973 return Val == 0 || Val == 1 || Val == -1;
975 return true; // always true, has to fit in largest type
976 int64_t Min = -(1ll << (NumBits-1));
977 int64_t Max = (1ll << (NumBits-1)) - 1;
978 return (Val >= Min && Val <= Max);
981 bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
982 // convert modifies in place, so make a copy.
983 APFloat Val2 = APFloat(Val);
985 switch (Ty->getTypeID()) {
987 return false; // These can't be represented as floating point!
989 // FIXME rounding mode needs to be more flexible
990 case Type::FloatTyID: {
991 if (&Val2.getSemantics() == &APFloat::IEEEsingle)
993 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
996 case Type::DoubleTyID: {
997 if (&Val2.getSemantics() == &APFloat::IEEEsingle ||
998 &Val2.getSemantics() == &APFloat::IEEEdouble)
1000 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
1003 case Type::X86_FP80TyID:
1004 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
1005 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1006 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
1007 case Type::FP128TyID:
1008 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
1009 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1010 &Val2.getSemantics() == &APFloat::IEEEquad;
1011 case Type::PPC_FP128TyID:
1012 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
1013 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1014 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
1018 //===----------------------------------------------------------------------===//
1019 // Factory Function Implementation
1021 static char getValType(ConstantAggregateZero *CPZ) { return 0; }
1023 ConstantAggregateZero* ConstantAggregateZero::get(const Type* Ty) {
1024 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) &&
1025 "Cannot create an aggregate zero of non-aggregate type!");
1027 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
1028 // Implicitly locked.
1029 return pImpl->AggZeroConstants.getOrCreate(Ty, 0);
1032 /// destroyConstant - Remove the constant from the constant table...
1034 void ConstantAggregateZero::destroyConstant() {
1035 // Implicitly locked.
1036 getType()->getContext().pImpl->AggZeroConstants.remove(this);
1037 destroyConstantImpl();
1040 /// destroyConstant - Remove the constant from the constant table...
1042 void ConstantArray::destroyConstant() {
1043 // Implicitly locked.
1044 getType()->getContext().pImpl->ArrayConstants.remove(this);
1045 destroyConstantImpl();
1048 /// isString - This method returns true if the array is an array of i8, and
1049 /// if the elements of the array are all ConstantInt's.
1050 bool ConstantArray::isString() const {
1051 // Check the element type for i8...
1052 if (getType()->getElementType() != Type::Int8Ty)
1054 // Check the elements to make sure they are all integers, not constant
1056 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1057 if (!isa<ConstantInt>(getOperand(i)))
1062 /// isCString - This method returns true if the array is a string (see
1063 /// isString) and it ends in a null byte \\0 and does not contains any other
1064 /// null bytes except its terminator.
1065 bool ConstantArray::isCString() const {
1066 // Check the element type for i8...
1067 if (getType()->getElementType() != Type::Int8Ty)
1070 // Last element must be a null.
1071 if (!getOperand(getNumOperands()-1)->isNullValue())
1073 // Other elements must be non-null integers.
1074 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1075 if (!isa<ConstantInt>(getOperand(i)))
1077 if (getOperand(i)->isNullValue())
1084 /// getAsString - If the sub-element type of this array is i8
1085 /// then this method converts the array to an std::string and returns it.
1086 /// Otherwise, it asserts out.
1088 std::string ConstantArray::getAsString() const {
1089 assert(isString() && "Not a string!");
1091 Result.reserve(getNumOperands());
1092 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1093 Result.push_back((char)cast<ConstantInt>(getOperand(i))->getZExtValue());
1098 //---- ConstantStruct::get() implementation...
1105 // destroyConstant - Remove the constant from the constant table...
1107 void ConstantStruct::destroyConstant() {
1108 // Implicitly locked.
1109 getType()->getContext().pImpl->StructConstants.remove(this);
1110 destroyConstantImpl();
1113 // destroyConstant - Remove the constant from the constant table...
1115 void ConstantVector::destroyConstant() {
1116 // Implicitly locked.
1117 getType()->getContext().pImpl->VectorConstants.remove(this);
1118 destroyConstantImpl();
1121 /// This function will return true iff every element in this vector constant
1122 /// is set to all ones.
1123 /// @returns true iff this constant's emements are all set to all ones.
1124 /// @brief Determine if the value is all ones.
1125 bool ConstantVector::isAllOnesValue() const {
1126 // Check out first element.
1127 const Constant *Elt = getOperand(0);
1128 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1129 if (!CI || !CI->isAllOnesValue()) return false;
1130 // Then make sure all remaining elements point to the same value.
1131 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1132 if (getOperand(I) != Elt) return false;
1137 /// getSplatValue - If this is a splat constant, where all of the
1138 /// elements have the same value, return that value. Otherwise return null.
1139 Constant *ConstantVector::getSplatValue() {
1140 // Check out first element.
1141 Constant *Elt = getOperand(0);
1142 // Then make sure all remaining elements point to the same value.
1143 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1144 if (getOperand(I) != Elt) return 0;
1148 //---- ConstantPointerNull::get() implementation...
1152 // ConstantPointerNull does not take extra "value" argument...
1153 template<class ValType>
1154 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1155 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1156 return new ConstantPointerNull(Ty);
1161 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1162 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1163 // Make everyone now use a constant of the new type...
1164 Constant *New = ConstantPointerNull::get(NewTy);
1165 assert(New != OldC && "Didn't replace constant??");
1166 OldC->uncheckedReplaceAllUsesWith(New);
1167 OldC->destroyConstant(); // This constant is now dead, destroy it.
1172 static ManagedStatic<ValueMap<char, PointerType,
1173 ConstantPointerNull> > NullPtrConstants;
1175 static char getValType(ConstantPointerNull *) {
1180 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1181 // Implicitly locked.
1182 return NullPtrConstants->getOrCreate(Ty, 0);
1185 // destroyConstant - Remove the constant from the constant table...
1187 void ConstantPointerNull::destroyConstant() {
1188 // Implicitly locked.
1189 NullPtrConstants->remove(this);
1190 destroyConstantImpl();
1194 //---- UndefValue::get() implementation...
1198 // UndefValue does not take extra "value" argument...
1199 template<class ValType>
1200 struct ConstantCreator<UndefValue, Type, ValType> {
1201 static UndefValue *create(const Type *Ty, const ValType &V) {
1202 return new UndefValue(Ty);
1207 struct ConvertConstantType<UndefValue, Type> {
1208 static void convert(UndefValue *OldC, const Type *NewTy) {
1209 // Make everyone now use a constant of the new type.
1210 Constant *New = UndefValue::get(NewTy);
1211 assert(New != OldC && "Didn't replace constant??");
1212 OldC->uncheckedReplaceAllUsesWith(New);
1213 OldC->destroyConstant(); // This constant is now dead, destroy it.
1218 static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
1220 static char getValType(UndefValue *) {
1225 UndefValue *UndefValue::get(const Type *Ty) {
1226 // Implicitly locked.
1227 return UndefValueConstants->getOrCreate(Ty, 0);
1230 // destroyConstant - Remove the constant from the constant table.
1232 void UndefValue::destroyConstant() {
1233 // Implicitly locked.
1234 UndefValueConstants->remove(this);
1235 destroyConstantImpl();
1238 //---- ConstantExpr::get() implementations...
1243 struct ExprMapKeyType {
1244 typedef SmallVector<unsigned, 4> IndexList;
1246 ExprMapKeyType(unsigned opc,
1247 const std::vector<Constant*> &ops,
1248 unsigned short pred = 0,
1249 const IndexList &inds = IndexList())
1250 : opcode(opc), predicate(pred), operands(ops), indices(inds) {}
1253 std::vector<Constant*> operands;
1255 bool operator==(const ExprMapKeyType& that) const {
1256 return this->opcode == that.opcode &&
1257 this->predicate == that.predicate &&
1258 this->operands == that.operands &&
1259 this->indices == that.indices;
1261 bool operator<(const ExprMapKeyType & that) const {
1262 return this->opcode < that.opcode ||
1263 (this->opcode == that.opcode && this->predicate < that.predicate) ||
1264 (this->opcode == that.opcode && this->predicate == that.predicate &&
1265 this->operands < that.operands) ||
1266 (this->opcode == that.opcode && this->predicate == that.predicate &&
1267 this->operands == that.operands && this->indices < that.indices);
1270 bool operator!=(const ExprMapKeyType& that) const {
1271 return !(*this == that);
1279 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1280 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1281 unsigned short pred = 0) {
1282 if (Instruction::isCast(V.opcode))
1283 return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1284 if ((V.opcode >= Instruction::BinaryOpsBegin &&
1285 V.opcode < Instruction::BinaryOpsEnd))
1286 return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1287 if (V.opcode == Instruction::Select)
1288 return new SelectConstantExpr(V.operands[0], V.operands[1],
1290 if (V.opcode == Instruction::ExtractElement)
1291 return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1292 if (V.opcode == Instruction::InsertElement)
1293 return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1295 if (V.opcode == Instruction::ShuffleVector)
1296 return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1298 if (V.opcode == Instruction::InsertValue)
1299 return new InsertValueConstantExpr(V.operands[0], V.operands[1],
1301 if (V.opcode == Instruction::ExtractValue)
1302 return new ExtractValueConstantExpr(V.operands[0], V.indices, Ty);
1303 if (V.opcode == Instruction::GetElementPtr) {
1304 std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
1305 return GetElementPtrConstantExpr::Create(V.operands[0], IdxList, Ty);
1308 // The compare instructions are weird. We have to encode the predicate
1309 // value and it is combined with the instruction opcode by multiplying
1310 // the opcode by one hundred. We must decode this to get the predicate.
1311 if (V.opcode == Instruction::ICmp)
1312 return new CompareConstantExpr(Ty, Instruction::ICmp, V.predicate,
1313 V.operands[0], V.operands[1]);
1314 if (V.opcode == Instruction::FCmp)
1315 return new CompareConstantExpr(Ty, Instruction::FCmp, V.predicate,
1316 V.operands[0], V.operands[1]);
1317 llvm_unreachable("Invalid ConstantExpr!");
1323 struct ConvertConstantType<ConstantExpr, Type> {
1324 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1326 switch (OldC->getOpcode()) {
1327 case Instruction::Trunc:
1328 case Instruction::ZExt:
1329 case Instruction::SExt:
1330 case Instruction::FPTrunc:
1331 case Instruction::FPExt:
1332 case Instruction::UIToFP:
1333 case Instruction::SIToFP:
1334 case Instruction::FPToUI:
1335 case Instruction::FPToSI:
1336 case Instruction::PtrToInt:
1337 case Instruction::IntToPtr:
1338 case Instruction::BitCast:
1339 New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0),
1342 case Instruction::Select:
1343 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1344 OldC->getOperand(1),
1345 OldC->getOperand(2));
1348 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1349 OldC->getOpcode() < Instruction::BinaryOpsEnd);
1350 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1351 OldC->getOperand(1));
1353 case Instruction::GetElementPtr:
1354 // Make everyone now use a constant of the new type...
1355 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1356 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0),
1357 &Idx[0], Idx.size());
1361 assert(New != OldC && "Didn't replace constant??");
1362 OldC->uncheckedReplaceAllUsesWith(New);
1363 OldC->destroyConstant(); // This constant is now dead, destroy it.
1366 } // end namespace llvm
1369 static ExprMapKeyType getValType(ConstantExpr *CE) {
1370 std::vector<Constant*> Operands;
1371 Operands.reserve(CE->getNumOperands());
1372 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1373 Operands.push_back(cast<Constant>(CE->getOperand(i)));
1374 return ExprMapKeyType(CE->getOpcode(), Operands,
1375 CE->isCompare() ? CE->getPredicate() : 0,
1377 CE->getIndices() : SmallVector<unsigned, 4>());
1380 static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1381 ConstantExpr> > ExprConstants;
1383 /// This is a utility function to handle folding of casts and lookup of the
1384 /// cast in the ExprConstants map. It is used by the various get* methods below.
1385 static inline Constant *getFoldedCast(
1386 Instruction::CastOps opc, Constant *C, const Type *Ty) {
1387 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1388 // Fold a few common cases
1390 ConstantFoldCastInstruction(getGlobalContext(), opc, C, Ty))
1393 // Look up the constant in the table first to ensure uniqueness
1394 std::vector<Constant*> argVec(1, C);
1395 ExprMapKeyType Key(opc, argVec);
1397 // Implicitly locked.
1398 return ExprConstants->getOrCreate(Ty, Key);
1401 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1402 Instruction::CastOps opc = Instruction::CastOps(oc);
1403 assert(Instruction::isCast(opc) && "opcode out of range");
1404 assert(C && Ty && "Null arguments to getCast");
1405 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1409 llvm_unreachable("Invalid cast opcode");
1411 case Instruction::Trunc: return getTrunc(C, Ty);
1412 case Instruction::ZExt: return getZExt(C, Ty);
1413 case Instruction::SExt: return getSExt(C, Ty);
1414 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1415 case Instruction::FPExt: return getFPExtend(C, Ty);
1416 case Instruction::UIToFP: return getUIToFP(C, Ty);
1417 case Instruction::SIToFP: return getSIToFP(C, Ty);
1418 case Instruction::FPToUI: return getFPToUI(C, Ty);
1419 case Instruction::FPToSI: return getFPToSI(C, Ty);
1420 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1421 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1422 case Instruction::BitCast: return getBitCast(C, Ty);
1427 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1428 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1429 return getCast(Instruction::BitCast, C, Ty);
1430 return getCast(Instruction::ZExt, C, Ty);
1433 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1434 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1435 return getCast(Instruction::BitCast, C, Ty);
1436 return getCast(Instruction::SExt, C, Ty);
1439 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1440 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1441 return getCast(Instruction::BitCast, C, Ty);
1442 return getCast(Instruction::Trunc, C, Ty);
1445 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1446 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1447 assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
1449 if (Ty->isInteger())
1450 return getCast(Instruction::PtrToInt, S, Ty);
1451 return getCast(Instruction::BitCast, S, Ty);
1454 Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
1456 assert(C->getType()->isIntOrIntVector() &&
1457 Ty->isIntOrIntVector() && "Invalid cast");
1458 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1459 unsigned DstBits = Ty->getScalarSizeInBits();
1460 Instruction::CastOps opcode =
1461 (SrcBits == DstBits ? Instruction::BitCast :
1462 (SrcBits > DstBits ? Instruction::Trunc :
1463 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1464 return getCast(opcode, C, Ty);
1467 Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1468 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1470 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1471 unsigned DstBits = Ty->getScalarSizeInBits();
1472 if (SrcBits == DstBits)
1473 return C; // Avoid a useless cast
1474 Instruction::CastOps opcode =
1475 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1476 return getCast(opcode, C, Ty);
1479 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
1481 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1482 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1484 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1485 assert(C->getType()->isIntOrIntVector() && "Trunc operand must be integer");
1486 assert(Ty->isIntOrIntVector() && "Trunc produces only integral");
1487 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1488 "SrcTy must be larger than DestTy for Trunc!");
1490 return getFoldedCast(Instruction::Trunc, C, Ty);
1493 Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
1495 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1496 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1498 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1499 assert(C->getType()->isIntOrIntVector() && "SExt operand must be integral");
1500 assert(Ty->isIntOrIntVector() && "SExt produces only integer");
1501 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1502 "SrcTy must be smaller than DestTy for SExt!");
1504 return getFoldedCast(Instruction::SExt, C, Ty);
1507 Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
1509 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1510 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1512 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1513 assert(C->getType()->isIntOrIntVector() && "ZEXt operand must be integral");
1514 assert(Ty->isIntOrIntVector() && "ZExt produces only integer");
1515 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1516 "SrcTy must be smaller than DestTy for ZExt!");
1518 return getFoldedCast(Instruction::ZExt, C, Ty);
1521 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1523 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1524 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1526 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1527 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1528 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1529 "This is an illegal floating point truncation!");
1530 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1533 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1535 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1536 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1538 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1539 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1540 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1541 "This is an illegal floating point extension!");
1542 return getFoldedCast(Instruction::FPExt, C, Ty);
1545 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
1547 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1548 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1550 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1551 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1552 "This is an illegal uint to floating point cast!");
1553 return getFoldedCast(Instruction::UIToFP, C, Ty);
1556 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
1558 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1559 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1561 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1562 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1563 "This is an illegal sint to floating point cast!");
1564 return getFoldedCast(Instruction::SIToFP, C, Ty);
1567 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
1569 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1570 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1572 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1573 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1574 "This is an illegal floating point to uint cast!");
1575 return getFoldedCast(Instruction::FPToUI, C, Ty);
1578 Constant *ConstantExpr::getFPToSI(Constant *C, const 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()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1585 "This is an illegal floating point to sint cast!");
1586 return getFoldedCast(Instruction::FPToSI, C, Ty);
1589 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1590 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
1591 assert(DstTy->isInteger() && "PtrToInt destination must be integral");
1592 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1595 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
1596 assert(C->getType()->isInteger() && "IntToPtr source must be integral");
1597 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
1598 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1601 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1602 // BitCast implies a no-op cast of type only. No bits change. However, you
1603 // can't cast pointers to anything but pointers.
1605 const Type *SrcTy = C->getType();
1606 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
1607 "BitCast cannot cast pointer to non-pointer and vice versa");
1609 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
1610 // or nonptr->ptr). For all the other types, the cast is okay if source and
1611 // destination bit widths are identical.
1612 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1613 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
1615 assert(SrcBitSize == DstBitSize && "BitCast requires types of same width");
1617 // It is common to ask for a bitcast of a value to its own type, handle this
1619 if (C->getType() == DstTy) return C;
1621 return getFoldedCast(Instruction::BitCast, C, DstTy);
1624 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1625 Constant *C1, Constant *C2) {
1626 // Check the operands for consistency first
1627 assert(Opcode >= Instruction::BinaryOpsBegin &&
1628 Opcode < Instruction::BinaryOpsEnd &&
1629 "Invalid opcode in binary constant expression");
1630 assert(C1->getType() == C2->getType() &&
1631 "Operand types in binary constant expression should match");
1633 if (ReqTy == C1->getType() || ReqTy == Type::Int1Ty)
1634 if (Constant *FC = ConstantFoldBinaryInstruction(
1635 getGlobalContext(), Opcode, C1, C2))
1636 return FC; // Fold a few common cases...
1638 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1639 ExprMapKeyType Key(Opcode, argVec);
1641 // Implicitly locked.
1642 return ExprConstants->getOrCreate(ReqTy, Key);
1645 Constant *ConstantExpr::getCompareTy(unsigned short predicate,
1646 Constant *C1, Constant *C2) {
1647 switch (predicate) {
1648 default: llvm_unreachable("Invalid CmpInst predicate");
1649 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
1650 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
1651 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
1652 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
1653 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
1654 case CmpInst::FCMP_TRUE:
1655 return getFCmp(predicate, C1, C2);
1657 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
1658 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
1659 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
1660 case CmpInst::ICMP_SLE:
1661 return getICmp(predicate, C1, C2);
1665 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
1666 // API compatibility: Adjust integer opcodes to floating-point opcodes.
1667 if (C1->getType()->isFPOrFPVector()) {
1668 if (Opcode == Instruction::Add) Opcode = Instruction::FAdd;
1669 else if (Opcode == Instruction::Sub) Opcode = Instruction::FSub;
1670 else if (Opcode == Instruction::Mul) Opcode = Instruction::FMul;
1674 case Instruction::Add:
1675 case Instruction::Sub:
1676 case Instruction::Mul:
1677 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1678 assert(C1->getType()->isIntOrIntVector() &&
1679 "Tried to create an integer operation on a non-integer type!");
1681 case Instruction::FAdd:
1682 case Instruction::FSub:
1683 case Instruction::FMul:
1684 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1685 assert(C1->getType()->isFPOrFPVector() &&
1686 "Tried to create a floating-point operation on a "
1687 "non-floating-point type!");
1689 case Instruction::UDiv:
1690 case Instruction::SDiv:
1691 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1692 assert(C1->getType()->isIntOrIntVector() &&
1693 "Tried to create an arithmetic operation on a non-arithmetic type!");
1695 case Instruction::FDiv:
1696 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1697 assert(C1->getType()->isFPOrFPVector() &&
1698 "Tried to create an arithmetic operation on a non-arithmetic type!");
1700 case Instruction::URem:
1701 case Instruction::SRem:
1702 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1703 assert(C1->getType()->isIntOrIntVector() &&
1704 "Tried to create an arithmetic operation on a non-arithmetic type!");
1706 case Instruction::FRem:
1707 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1708 assert(C1->getType()->isFPOrFPVector() &&
1709 "Tried to create an arithmetic operation on a non-arithmetic type!");
1711 case Instruction::And:
1712 case Instruction::Or:
1713 case Instruction::Xor:
1714 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1715 assert(C1->getType()->isIntOrIntVector() &&
1716 "Tried to create a logical operation on a non-integral type!");
1718 case Instruction::Shl:
1719 case Instruction::LShr:
1720 case Instruction::AShr:
1721 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1722 assert(C1->getType()->isIntOrIntVector() &&
1723 "Tried to create a shift operation on a non-integer type!");
1730 return getTy(C1->getType(), Opcode, C1, C2);
1733 Constant* ConstantExpr::getSizeOf(const Type* Ty) {
1734 // sizeof is implemented as: (i64) gep (Ty*)null, 1
1735 // Note that a non-inbounds gep is used, as null isn't within any object.
1736 LLVMContext &Context = Ty->getContext();
1737 Constant *GEPIdx = ConstantInt::get(Type::Int32Ty, 1);
1738 Constant *GEP = getGetElementPtr(
1739 Context.getNullValue(PointerType::getUnqual(Ty)), &GEPIdx, 1);
1740 return getCast(Instruction::PtrToInt, GEP, Type::Int64Ty);
1743 Constant* ConstantExpr::getAlignOf(const Type* Ty) {
1744 LLVMContext &Context = Ty->getContext();
1745 // alignof is implemented as: (i64) gep ({i8,Ty}*)null, 0, 1
1746 const Type *AligningTy = StructType::get(Type::Int8Ty, Ty, NULL);
1747 Constant *NullPtr = Context.getNullValue(AligningTy->getPointerTo());
1748 Constant *Zero = ConstantInt::get(Type::Int32Ty, 0);
1749 Constant *One = ConstantInt::get(Type::Int32Ty, 1);
1750 Constant *Indices[2] = { Zero, One };
1751 Constant *GEP = getGetElementPtr(NullPtr, Indices, 2);
1752 return getCast(Instruction::PtrToInt, GEP, Type::Int32Ty);
1756 Constant *ConstantExpr::getCompare(unsigned short pred,
1757 Constant *C1, Constant *C2) {
1758 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1759 return getCompareTy(pred, C1, C2);
1762 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1763 Constant *V1, Constant *V2) {
1764 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
1766 if (ReqTy == V1->getType())
1767 if (Constant *SC = ConstantFoldSelectInstruction(
1768 getGlobalContext(), C, V1, V2))
1769 return SC; // Fold common cases
1771 std::vector<Constant*> argVec(3, C);
1774 ExprMapKeyType Key(Instruction::Select, argVec);
1776 // Implicitly locked.
1777 return ExprConstants->getOrCreate(ReqTy, Key);
1780 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1783 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs,
1785 cast<PointerType>(ReqTy)->getElementType() &&
1786 "GEP indices invalid!");
1788 if (Constant *FC = ConstantFoldGetElementPtr(
1789 getGlobalContext(), C, (Constant**)Idxs, NumIdx))
1790 return FC; // Fold a few common cases...
1792 assert(isa<PointerType>(C->getType()) &&
1793 "Non-pointer type for constant GetElementPtr expression");
1794 // Look up the constant in the table first to ensure uniqueness
1795 std::vector<Constant*> ArgVec;
1796 ArgVec.reserve(NumIdx+1);
1797 ArgVec.push_back(C);
1798 for (unsigned i = 0; i != NumIdx; ++i)
1799 ArgVec.push_back(cast<Constant>(Idxs[i]));
1800 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
1802 // Implicitly locked.
1803 return ExprConstants->getOrCreate(ReqTy, Key);
1806 Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
1808 // Get the result type of the getelementptr!
1810 GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx);
1811 assert(Ty && "GEP indices invalid!");
1812 unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
1813 return getGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx);
1816 Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
1818 return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
1823 ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1824 assert(LHS->getType() == RHS->getType());
1825 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
1826 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1828 if (Constant *FC = ConstantFoldCompareInstruction(
1829 getGlobalContext(),pred, LHS, RHS))
1830 return FC; // Fold a few common cases...
1832 // Look up the constant in the table first to ensure uniqueness
1833 std::vector<Constant*> ArgVec;
1834 ArgVec.push_back(LHS);
1835 ArgVec.push_back(RHS);
1836 // Get the key type with both the opcode and predicate
1837 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
1839 // Implicitly locked.
1840 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
1844 ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1845 assert(LHS->getType() == RHS->getType());
1846 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1848 if (Constant *FC = ConstantFoldCompareInstruction(
1849 getGlobalContext(), pred, LHS, RHS))
1850 return FC; // Fold a few common cases...
1852 // Look up the constant in the table first to ensure uniqueness
1853 std::vector<Constant*> ArgVec;
1854 ArgVec.push_back(LHS);
1855 ArgVec.push_back(RHS);
1856 // Get the key type with both the opcode and predicate
1857 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
1859 // Implicitly locked.
1860 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
1863 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
1865 if (Constant *FC = ConstantFoldExtractElementInstruction(
1866 getGlobalContext(), Val, Idx))
1867 return FC; // Fold a few common cases...
1868 // Look up the constant in the table first to ensure uniqueness
1869 std::vector<Constant*> ArgVec(1, Val);
1870 ArgVec.push_back(Idx);
1871 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
1873 // Implicitly locked.
1874 return ExprConstants->getOrCreate(ReqTy, Key);
1877 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
1878 assert(isa<VectorType>(Val->getType()) &&
1879 "Tried to create extractelement operation on non-vector type!");
1880 assert(Idx->getType() == Type::Int32Ty &&
1881 "Extractelement index must be i32 type!");
1882 return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
1886 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
1887 Constant *Elt, Constant *Idx) {
1888 if (Constant *FC = ConstantFoldInsertElementInstruction(
1889 getGlobalContext(), Val, Elt, Idx))
1890 return FC; // Fold a few common cases...
1891 // Look up the constant in the table first to ensure uniqueness
1892 std::vector<Constant*> ArgVec(1, Val);
1893 ArgVec.push_back(Elt);
1894 ArgVec.push_back(Idx);
1895 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
1897 // Implicitly locked.
1898 return ExprConstants->getOrCreate(ReqTy, Key);
1901 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1903 assert(isa<VectorType>(Val->getType()) &&
1904 "Tried to create insertelement operation on non-vector type!");
1905 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
1906 && "Insertelement types must match!");
1907 assert(Idx->getType() == Type::Int32Ty &&
1908 "Insertelement index must be i32 type!");
1909 return getInsertElementTy(Val->getType(), Val, Elt, Idx);
1912 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
1913 Constant *V2, Constant *Mask) {
1914 if (Constant *FC = ConstantFoldShuffleVectorInstruction(
1915 getGlobalContext(), V1, V2, Mask))
1916 return FC; // Fold a few common cases...
1917 // Look up the constant in the table first to ensure uniqueness
1918 std::vector<Constant*> ArgVec(1, V1);
1919 ArgVec.push_back(V2);
1920 ArgVec.push_back(Mask);
1921 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
1923 // Implicitly locked.
1924 return ExprConstants->getOrCreate(ReqTy, Key);
1927 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
1929 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1930 "Invalid shuffle vector constant expr operands!");
1932 unsigned NElts = cast<VectorType>(Mask->getType())->getNumElements();
1933 const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
1934 const Type *ShufTy = VectorType::get(EltTy, NElts);
1935 return getShuffleVectorTy(ShufTy, V1, V2, Mask);
1938 Constant *ConstantExpr::getInsertValueTy(const Type *ReqTy, Constant *Agg,
1940 const unsigned *Idxs, unsigned NumIdx) {
1941 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
1942 Idxs+NumIdx) == Val->getType() &&
1943 "insertvalue indices invalid!");
1944 assert(Agg->getType() == ReqTy &&
1945 "insertvalue type invalid!");
1946 assert(Agg->getType()->isFirstClassType() &&
1947 "Non-first-class type for constant InsertValue expression");
1948 Constant *FC = ConstantFoldInsertValueInstruction(
1949 getGlobalContext(), Agg, Val, Idxs, NumIdx);
1950 assert(FC && "InsertValue constant expr couldn't be folded!");
1954 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
1955 const unsigned *IdxList, unsigned NumIdx) {
1956 assert(Agg->getType()->isFirstClassType() &&
1957 "Tried to create insertelement operation on non-first-class type!");
1959 const Type *ReqTy = Agg->getType();
1962 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
1964 assert(ValTy == Val->getType() && "insertvalue indices invalid!");
1965 return getInsertValueTy(ReqTy, Agg, Val, IdxList, NumIdx);
1968 Constant *ConstantExpr::getExtractValueTy(const Type *ReqTy, Constant *Agg,
1969 const unsigned *Idxs, unsigned NumIdx) {
1970 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
1971 Idxs+NumIdx) == ReqTy &&
1972 "extractvalue indices invalid!");
1973 assert(Agg->getType()->isFirstClassType() &&
1974 "Non-first-class type for constant extractvalue expression");
1975 Constant *FC = ConstantFoldExtractValueInstruction(
1976 getGlobalContext(), Agg, Idxs, NumIdx);
1977 assert(FC && "ExtractValue constant expr couldn't be folded!");
1981 Constant *ConstantExpr::getExtractValue(Constant *Agg,
1982 const unsigned *IdxList, unsigned NumIdx) {
1983 assert(Agg->getType()->isFirstClassType() &&
1984 "Tried to create extractelement operation on non-first-class type!");
1987 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
1988 assert(ReqTy && "extractvalue indices invalid!");
1989 return getExtractValueTy(ReqTy, Agg, IdxList, NumIdx);
1992 Constant* ConstantExpr::getNeg(Constant* C) {
1993 // API compatibility: Adjust integer opcodes to floating-point opcodes.
1994 if (C->getType()->isFPOrFPVector())
1996 assert(C->getType()->isIntOrIntVector() &&
1997 "Cannot NEG a nonintegral value!");
1998 return get(Instruction::Sub,
1999 ConstantFP::getZeroValueForNegation(C->getType()),
2003 Constant* ConstantExpr::getFNeg(Constant* C) {
2004 assert(C->getType()->isFPOrFPVector() &&
2005 "Cannot FNEG a non-floating-point value!");
2006 return get(Instruction::FSub,
2007 ConstantFP::getZeroValueForNegation(C->getType()),
2011 Constant* ConstantExpr::getNot(Constant* C) {
2012 assert(C->getType()->isIntOrIntVector() &&
2013 "Cannot NOT a nonintegral value!");
2014 LLVMContext &Context = C->getType()->getContext();
2015 return get(Instruction::Xor, C, Context.getAllOnesValue(C->getType()));
2018 Constant* ConstantExpr::getAdd(Constant* C1, Constant* C2) {
2019 return get(Instruction::Add, C1, C2);
2022 Constant* ConstantExpr::getFAdd(Constant* C1, Constant* C2) {
2023 return get(Instruction::FAdd, C1, C2);
2026 Constant* ConstantExpr::getSub(Constant* C1, Constant* C2) {
2027 return get(Instruction::Sub, C1, C2);
2030 Constant* ConstantExpr::getFSub(Constant* C1, Constant* C2) {
2031 return get(Instruction::FSub, C1, C2);
2034 Constant* ConstantExpr::getMul(Constant* C1, Constant* C2) {
2035 return get(Instruction::Mul, C1, C2);
2038 Constant* ConstantExpr::getFMul(Constant* C1, Constant* C2) {
2039 return get(Instruction::FMul, C1, C2);
2042 Constant* ConstantExpr::getUDiv(Constant* C1, Constant* C2) {
2043 return get(Instruction::UDiv, C1, C2);
2046 Constant* ConstantExpr::getSDiv(Constant* C1, Constant* C2) {
2047 return get(Instruction::SDiv, C1, C2);
2050 Constant* ConstantExpr::getFDiv(Constant* C1, Constant* C2) {
2051 return get(Instruction::FDiv, C1, C2);
2054 Constant* ConstantExpr::getURem(Constant* C1, Constant* C2) {
2055 return get(Instruction::URem, C1, C2);
2058 Constant* ConstantExpr::getSRem(Constant* C1, Constant* C2) {
2059 return get(Instruction::SRem, C1, C2);
2062 Constant* ConstantExpr::getFRem(Constant* C1, Constant* C2) {
2063 return get(Instruction::FRem, C1, C2);
2066 Constant* ConstantExpr::getAnd(Constant* C1, Constant* C2) {
2067 return get(Instruction::And, C1, C2);
2070 Constant* ConstantExpr::getOr(Constant* C1, Constant* C2) {
2071 return get(Instruction::Or, C1, C2);
2074 Constant* ConstantExpr::getXor(Constant* C1, Constant* C2) {
2075 return get(Instruction::Xor, C1, C2);
2078 Constant* ConstantExpr::getShl(Constant* C1, Constant* C2) {
2079 return get(Instruction::Shl, C1, C2);
2082 Constant* ConstantExpr::getLShr(Constant* C1, Constant* C2) {
2083 return get(Instruction::LShr, C1, C2);
2086 Constant* ConstantExpr::getAShr(Constant* C1, Constant* C2) {
2087 return get(Instruction::AShr, C1, C2);
2090 // destroyConstant - Remove the constant from the constant table...
2092 void ConstantExpr::destroyConstant() {
2093 // Implicitly locked.
2094 ExprConstants->remove(this);
2095 destroyConstantImpl();
2098 const char *ConstantExpr::getOpcodeName() const {
2099 return Instruction::getOpcodeName(getOpcode());
2102 //===----------------------------------------------------------------------===//
2103 // replaceUsesOfWithOnConstant implementations
2105 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
2106 /// 'From' to be uses of 'To'. This must update the uniquing data structures
2109 /// Note that we intentionally replace all uses of From with To here. Consider
2110 /// a large array that uses 'From' 1000 times. By handling this case all here,
2111 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
2112 /// single invocation handles all 1000 uses. Handling them one at a time would
2113 /// work, but would be really slow because it would have to unique each updated
2116 static std::vector<Constant*> getValType(ConstantArray *CA) {
2117 std::vector<Constant*> Elements;
2118 Elements.reserve(CA->getNumOperands());
2119 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
2120 Elements.push_back(cast<Constant>(CA->getOperand(i)));
2125 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
2127 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2128 Constant *ToC = cast<Constant>(To);
2130 LLVMContext &Context = getType()->getContext();
2131 LLVMContextImpl *pImpl = Context.pImpl;
2133 std::pair<LLVMContextImpl::ArrayConstantsTy::MapKey, Constant*> Lookup;
2134 Lookup.first.first = getType();
2135 Lookup.second = this;
2137 std::vector<Constant*> &Values = Lookup.first.second;
2138 Values.reserve(getNumOperands()); // Build replacement array.
2140 // Fill values with the modified operands of the constant array. Also,
2141 // compute whether this turns into an all-zeros array.
2142 bool isAllZeros = false;
2143 unsigned NumUpdated = 0;
2144 if (!ToC->isNullValue()) {
2145 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2146 Constant *Val = cast<Constant>(O->get());
2151 Values.push_back(Val);
2155 for (Use *O = OperandList, *E = OperandList+getNumOperands();O != E; ++O) {
2156 Constant *Val = cast<Constant>(O->get());
2161 Values.push_back(Val);
2162 if (isAllZeros) isAllZeros = Val->isNullValue();
2166 Constant *Replacement = 0;
2168 Replacement = ConstantAggregateZero::get(getType());
2170 // Check to see if we have this array type already.
2171 sys::SmartScopedWriter<true> Writer(pImpl->ConstantsLock);
2173 LLVMContextImpl::ArrayConstantsTy::MapTy::iterator I =
2174 pImpl->ArrayConstants.InsertOrGetItem(Lookup, Exists);
2177 Replacement = I->second;
2179 // Okay, the new shape doesn't exist in the system yet. Instead of
2180 // creating a new constant array, inserting it, replaceallusesof'ing the
2181 // old with the new, then deleting the old... just update the current one
2183 pImpl->ArrayConstants.MoveConstantToNewSlot(this, I);
2185 // Update to the new value. Optimize for the case when we have a single
2186 // operand that we're changing, but handle bulk updates efficiently.
2187 if (NumUpdated == 1) {
2188 unsigned OperandToUpdate = U - OperandList;
2189 assert(getOperand(OperandToUpdate) == From &&
2190 "ReplaceAllUsesWith broken!");
2191 setOperand(OperandToUpdate, ToC);
2193 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2194 if (getOperand(i) == From)
2201 // Otherwise, I do need to replace this with an existing value.
2202 assert(Replacement != this && "I didn't contain From!");
2204 // Everyone using this now uses the replacement.
2205 uncheckedReplaceAllUsesWith(Replacement);
2207 // Delete the old constant!
2211 static std::vector<Constant*> getValType(ConstantStruct *CS) {
2212 std::vector<Constant*> Elements;
2213 Elements.reserve(CS->getNumOperands());
2214 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
2215 Elements.push_back(cast<Constant>(CS->getOperand(i)));
2219 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
2221 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2222 Constant *ToC = cast<Constant>(To);
2224 unsigned OperandToUpdate = U-OperandList;
2225 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2227 std::pair<LLVMContextImpl::StructConstantsTy::MapKey, Constant*> Lookup;
2228 Lookup.first.first = getType();
2229 Lookup.second = this;
2230 std::vector<Constant*> &Values = Lookup.first.second;
2231 Values.reserve(getNumOperands()); // Build replacement struct.
2234 // Fill values with the modified operands of the constant struct. Also,
2235 // compute whether this turns into an all-zeros struct.
2236 bool isAllZeros = false;
2237 if (!ToC->isNullValue()) {
2238 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O)
2239 Values.push_back(cast<Constant>(O->get()));
2242 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2243 Constant *Val = cast<Constant>(O->get());
2244 Values.push_back(Val);
2245 if (isAllZeros) isAllZeros = Val->isNullValue();
2248 Values[OperandToUpdate] = ToC;
2250 LLVMContext &Context = getType()->getContext();
2251 LLVMContextImpl *pImpl = Context.pImpl;
2253 Constant *Replacement = 0;
2255 Replacement = ConstantAggregateZero::get(getType());
2257 // Check to see if we have this array type already.
2258 sys::SmartScopedWriter<true> Writer(pImpl->ConstantsLock);
2260 LLVMContextImpl::StructConstantsTy::MapTy::iterator I =
2261 pImpl->StructConstants.InsertOrGetItem(Lookup, Exists);
2264 Replacement = I->second;
2266 // Okay, the new shape doesn't exist in the system yet. Instead of
2267 // creating a new constant struct, inserting it, replaceallusesof'ing the
2268 // old with the new, then deleting the old... just update the current one
2270 pImpl->StructConstants.MoveConstantToNewSlot(this, I);
2272 // Update to the new value.
2273 setOperand(OperandToUpdate, ToC);
2278 assert(Replacement != this && "I didn't contain From!");
2280 // Everyone using this now uses the replacement.
2281 uncheckedReplaceAllUsesWith(Replacement);
2283 // Delete the old constant!
2287 static std::vector<Constant*> getValType(ConstantVector *CP) {
2288 std::vector<Constant*> Elements;
2289 Elements.reserve(CP->getNumOperands());
2290 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
2291 Elements.push_back(CP->getOperand(i));
2295 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
2297 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2299 std::vector<Constant*> Values;
2300 Values.reserve(getNumOperands()); // Build replacement array...
2301 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2302 Constant *Val = getOperand(i);
2303 if (Val == From) Val = cast<Constant>(To);
2304 Values.push_back(Val);
2307 Constant *Replacement = get(getType(), Values);
2308 assert(Replacement != this && "I didn't contain From!");
2310 // Everyone using this now uses the replacement.
2311 uncheckedReplaceAllUsesWith(Replacement);
2313 // Delete the old constant!
2317 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2319 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2320 Constant *To = cast<Constant>(ToV);
2322 Constant *Replacement = 0;
2323 if (getOpcode() == Instruction::GetElementPtr) {
2324 SmallVector<Constant*, 8> Indices;
2325 Constant *Pointer = getOperand(0);
2326 Indices.reserve(getNumOperands()-1);
2327 if (Pointer == From) Pointer = To;
2329 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2330 Constant *Val = getOperand(i);
2331 if (Val == From) Val = To;
2332 Indices.push_back(Val);
2334 Replacement = ConstantExpr::getGetElementPtr(Pointer,
2335 &Indices[0], Indices.size());
2336 } else if (getOpcode() == Instruction::ExtractValue) {
2337 Constant *Agg = getOperand(0);
2338 if (Agg == From) Agg = To;
2340 const SmallVector<unsigned, 4> &Indices = getIndices();
2341 Replacement = ConstantExpr::getExtractValue(Agg,
2342 &Indices[0], Indices.size());
2343 } else if (getOpcode() == Instruction::InsertValue) {
2344 Constant *Agg = getOperand(0);
2345 Constant *Val = getOperand(1);
2346 if (Agg == From) Agg = To;
2347 if (Val == From) Val = To;
2349 const SmallVector<unsigned, 4> &Indices = getIndices();
2350 Replacement = ConstantExpr::getInsertValue(Agg, Val,
2351 &Indices[0], Indices.size());
2352 } else if (isCast()) {
2353 assert(getOperand(0) == From && "Cast only has one use!");
2354 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
2355 } else if (getOpcode() == Instruction::Select) {
2356 Constant *C1 = getOperand(0);
2357 Constant *C2 = getOperand(1);
2358 Constant *C3 = getOperand(2);
2359 if (C1 == From) C1 = To;
2360 if (C2 == From) C2 = To;
2361 if (C3 == From) C3 = To;
2362 Replacement = ConstantExpr::getSelect(C1, C2, C3);
2363 } else if (getOpcode() == Instruction::ExtractElement) {
2364 Constant *C1 = getOperand(0);
2365 Constant *C2 = getOperand(1);
2366 if (C1 == From) C1 = To;
2367 if (C2 == From) C2 = To;
2368 Replacement = ConstantExpr::getExtractElement(C1, C2);
2369 } else if (getOpcode() == Instruction::InsertElement) {
2370 Constant *C1 = getOperand(0);
2371 Constant *C2 = getOperand(1);
2372 Constant *C3 = getOperand(1);
2373 if (C1 == From) C1 = To;
2374 if (C2 == From) C2 = To;
2375 if (C3 == From) C3 = To;
2376 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2377 } else if (getOpcode() == Instruction::ShuffleVector) {
2378 Constant *C1 = getOperand(0);
2379 Constant *C2 = getOperand(1);
2380 Constant *C3 = getOperand(2);
2381 if (C1 == From) C1 = To;
2382 if (C2 == From) C2 = To;
2383 if (C3 == From) C3 = To;
2384 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2385 } else if (isCompare()) {
2386 Constant *C1 = getOperand(0);
2387 Constant *C2 = getOperand(1);
2388 if (C1 == From) C1 = To;
2389 if (C2 == From) C2 = To;
2390 if (getOpcode() == Instruction::ICmp)
2391 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2393 assert(getOpcode() == Instruction::FCmp);
2394 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2396 } else if (getNumOperands() == 2) {
2397 Constant *C1 = getOperand(0);
2398 Constant *C2 = getOperand(1);
2399 if (C1 == From) C1 = To;
2400 if (C2 == From) C2 = To;
2401 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2403 llvm_unreachable("Unknown ConstantExpr type!");
2407 assert(Replacement != this && "I didn't contain From!");
2409 // Everyone using this now uses the replacement.
2410 uncheckedReplaceAllUsesWith(Replacement);
2412 // Delete the old constant!