1 //===-- Constants.cpp - Implement Constant nodes --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Constant* classes...
12 //===----------------------------------------------------------------------===//
14 #include "LLVMContextImpl.h"
15 #include "llvm/Constants.h"
16 #include "ConstantFold.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/GlobalValue.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Module.h"
21 #include "llvm/Operator.h"
22 #include "llvm/ADT/FoldingSet.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/StringMap.h"
25 #include "llvm/Support/Compiler.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/ManagedStatic.h"
29 #include "llvm/Support/MathExtras.h"
30 #include "llvm/System/Mutex.h"
31 #include "llvm/System/RWMutex.h"
32 #include "llvm/System/Threading.h"
33 #include "llvm/ADT/DenseMap.h"
34 #include "llvm/ADT/SmallVector.h"
39 //===----------------------------------------------------------------------===//
41 //===----------------------------------------------------------------------===//
43 // Constructor to create a '0' constant of arbitrary type...
44 static const uint64_t zero
[2] = {0, 0};
45 Constant
* Constant::getNullValue(const Type
* Ty
) {
46 switch (Ty
->getTypeID()) {
47 case Type::IntegerTyID
:
48 return ConstantInt::get(Ty
, 0);
50 return ConstantFP::get(Ty
->getContext(), APFloat(APInt(32, 0)));
51 case Type::DoubleTyID
:
52 return ConstantFP::get(Ty
->getContext(), APFloat(APInt(64, 0)));
53 case Type::X86_FP80TyID
:
54 return ConstantFP::get(Ty
->getContext(), APFloat(APInt(80, 2, zero
)));
56 return ConstantFP::get(Ty
->getContext(),
57 APFloat(APInt(128, 2, zero
), true));
58 case Type::PPC_FP128TyID
:
59 return ConstantFP::get(Ty
->getContext(), APFloat(APInt(128, 2, zero
)));
60 case Type::PointerTyID
:
61 return ConstantPointerNull::get(cast
<PointerType
>(Ty
));
62 case Type::StructTyID
:
64 case Type::VectorTyID
:
65 return ConstantAggregateZero::get(Ty
);
67 // Function, Label, or Opaque type?
68 assert(!"Cannot create a null constant of that type!");
73 Constant
* Constant::getIntegerValue(const Type
* Ty
, const APInt
&V
) {
74 const Type
*ScalarTy
= Ty
->getScalarType();
76 // Create the base integer constant.
77 Constant
*C
= ConstantInt::get(Ty
->getContext(), V
);
79 // Convert an integer to a pointer, if necessary.
80 if (const PointerType
*PTy
= dyn_cast
<PointerType
>(ScalarTy
))
81 C
= ConstantExpr::getIntToPtr(C
, PTy
);
83 // Broadcast a scalar to a vector, if necessary.
84 if (const VectorType
*VTy
= dyn_cast
<VectorType
>(Ty
))
85 C
= ConstantVector::get(std::vector
<Constant
*>(VTy
->getNumElements(), C
));
90 Constant
* Constant::getAllOnesValue(const Type
* Ty
) {
91 if (const IntegerType
* ITy
= dyn_cast
<IntegerType
>(Ty
))
92 return ConstantInt::get(Ty
->getContext(),
93 APInt::getAllOnesValue(ITy
->getBitWidth()));
95 std::vector
<Constant
*> Elts
;
96 const VectorType
* VTy
= cast
<VectorType
>(Ty
);
97 Elts
.resize(VTy
->getNumElements(), getAllOnesValue(VTy
->getElementType()));
98 assert(Elts
[0] && "Not a vector integer type!");
99 return cast
<ConstantVector
>(ConstantVector::get(Elts
));
102 void Constant::destroyConstantImpl() {
103 // When a Constant is destroyed, there may be lingering
104 // references to the constant by other constants in the constant pool. These
105 // constants are implicitly dependent on the module that is being deleted,
106 // but they don't know that. Because we only find out when the CPV is
107 // deleted, we must now notify all of our users (that should only be
108 // Constants) that they are, in fact, invalid now and should be deleted.
110 while (!use_empty()) {
111 Value
*V
= use_back();
112 #ifndef NDEBUG // Only in -g mode...
113 if (!isa
<Constant
>(V
))
114 DOUT
<< "While deleting: " << *this
115 << "\n\nUse still stuck around after Def is destroyed: "
118 assert(isa
<Constant
>(V
) && "References remain to Constant being destroyed");
119 Constant
*CV
= cast
<Constant
>(V
);
120 CV
->destroyConstant();
122 // The constant should remove itself from our use list...
123 assert((use_empty() || use_back() != V
) && "Constant not removed!");
126 // Value has no outstanding references it is safe to delete it now...
130 /// canTrap - Return true if evaluation of this constant could trap. This is
131 /// true for things like constant expressions that could divide by zero.
132 bool Constant::canTrap() const {
133 assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
134 // The only thing that could possibly trap are constant exprs.
135 const ConstantExpr
*CE
= dyn_cast
<ConstantExpr
>(this);
136 if (!CE
) return false;
138 // ConstantExpr traps if any operands can trap.
139 for (unsigned i
= 0, e
= getNumOperands(); i
!= e
; ++i
)
140 if (getOperand(i
)->canTrap())
143 // Otherwise, only specific operations can trap.
144 switch (CE
->getOpcode()) {
147 case Instruction::UDiv
:
148 case Instruction::SDiv
:
149 case Instruction::FDiv
:
150 case Instruction::URem
:
151 case Instruction::SRem
:
152 case Instruction::FRem
:
153 // Div and rem can trap if the RHS is not known to be non-zero.
154 if (!isa
<ConstantInt
>(getOperand(1)) || getOperand(1)->isNullValue())
161 /// getRelocationInfo - This method classifies the entry according to
162 /// whether or not it may generate a relocation entry. This must be
163 /// conservative, so if it might codegen to a relocatable entry, it should say
164 /// so. The return values are:
166 /// NoRelocation: This constant pool entry is guaranteed to never have a
167 /// relocation applied to it (because it holds a simple constant like
169 /// LocalRelocation: This entry has relocations, but the entries are
170 /// guaranteed to be resolvable by the static linker, so the dynamic
171 /// linker will never see them.
172 /// GlobalRelocations: This entry may have arbitrary relocations.
174 /// FIXME: This really should not be in VMCore.
175 Constant::PossibleRelocationsTy
Constant::getRelocationInfo() const {
176 if (const GlobalValue
*GV
= dyn_cast
<GlobalValue
>(this)) {
177 if (GV
->hasLocalLinkage() || GV
->hasHiddenVisibility())
178 return LocalRelocation
; // Local to this file/library.
179 return GlobalRelocations
; // Global reference.
182 PossibleRelocationsTy Result
= NoRelocation
;
183 for (unsigned i
= 0, e
= getNumOperands(); i
!= e
; ++i
)
184 Result
= std::max(Result
, getOperand(i
)->getRelocationInfo());
190 /// getVectorElements - This method, which is only valid on constant of vector
191 /// type, returns the elements of the vector in the specified smallvector.
192 /// This handles breaking down a vector undef into undef elements, etc. For
193 /// constant exprs and other cases we can't handle, we return an empty vector.
194 void Constant::getVectorElements(LLVMContext
&Context
,
195 SmallVectorImpl
<Constant
*> &Elts
) const {
196 assert(isa
<VectorType
>(getType()) && "Not a vector constant!");
198 if (const ConstantVector
*CV
= dyn_cast
<ConstantVector
>(this)) {
199 for (unsigned i
= 0, e
= CV
->getNumOperands(); i
!= e
; ++i
)
200 Elts
.push_back(CV
->getOperand(i
));
204 const VectorType
*VT
= cast
<VectorType
>(getType());
205 if (isa
<ConstantAggregateZero
>(this)) {
206 Elts
.assign(VT
->getNumElements(),
207 Constant::getNullValue(VT
->getElementType()));
211 if (isa
<UndefValue
>(this)) {
212 Elts
.assign(VT
->getNumElements(), UndefValue::get(VT
->getElementType()));
216 // Unknown type, must be constant expr etc.
221 //===----------------------------------------------------------------------===//
223 //===----------------------------------------------------------------------===//
225 ConstantInt::ConstantInt(const IntegerType
*Ty
, const APInt
& V
)
226 : Constant(Ty
, ConstantIntVal
, 0, 0), Val(V
) {
227 assert(V
.getBitWidth() == Ty
->getBitWidth() && "Invalid constant for type");
230 ConstantInt
* ConstantInt::getTrue(LLVMContext
&Context
) {
231 LLVMContextImpl
*pImpl
= Context
.pImpl
;
232 sys::SmartScopedWriter
<true>(pImpl
->ConstantsLock
);
233 if (pImpl
->TheTrueVal
)
234 return pImpl
->TheTrueVal
;
236 return (pImpl
->TheTrueVal
= ConstantInt::get(IntegerType::get(1), 1));
239 ConstantInt
* ConstantInt::getFalse(LLVMContext
&Context
) {
240 LLVMContextImpl
*pImpl
= Context
.pImpl
;
241 sys::SmartScopedWriter
<true>(pImpl
->ConstantsLock
);
242 if (pImpl
->TheFalseVal
)
243 return pImpl
->TheFalseVal
;
245 return (pImpl
->TheFalseVal
= ConstantInt::get(IntegerType::get(1), 0));
249 // Get a ConstantInt from an APInt. Note that the value stored in the DenseMap
250 // as the key, is a DenseMapAPIntKeyInfo::KeyTy which has provided the
251 // operator== and operator!= to ensure that the DenseMap doesn't attempt to
252 // compare APInt's of different widths, which would violate an APInt class
253 // invariant which generates an assertion.
254 ConstantInt
*ConstantInt::get(LLVMContext
&Context
, const APInt
& V
) {
255 // Get the corresponding integer type for the bit width of the value.
256 const IntegerType
*ITy
= IntegerType::get(V
.getBitWidth());
257 // get an existing value or the insertion position
258 DenseMapAPIntKeyInfo::KeyTy
Key(V
, ITy
);
260 Context
.pImpl
->ConstantsLock
.reader_acquire();
261 ConstantInt
*&Slot
= Context
.pImpl
->IntConstants
[Key
];
262 Context
.pImpl
->ConstantsLock
.reader_release();
265 sys::SmartScopedWriter
<true> Writer(Context
.pImpl
->ConstantsLock
);
266 ConstantInt
*&NewSlot
= Context
.pImpl
->IntConstants
[Key
];
268 NewSlot
= new ConstantInt(ITy
, V
);
277 Constant
* ConstantInt::get(const Type
* Ty
, uint64_t V
, bool isSigned
) {
278 Constant
*C
= get(cast
<IntegerType
>(Ty
->getScalarType()),
281 // For vectors, broadcast the value.
282 if (const VectorType
*VTy
= dyn_cast
<VectorType
>(Ty
))
283 return ConstantVector::get(
284 std::vector
<Constant
*>(VTy
->getNumElements(), C
));
289 ConstantInt
* ConstantInt::get(const IntegerType
* Ty
, uint64_t V
,
291 return get(Ty
->getContext(), APInt(Ty
->getBitWidth(), V
, isSigned
));
294 ConstantInt
* ConstantInt::getSigned(const IntegerType
* Ty
, int64_t V
) {
295 return get(Ty
, V
, true);
298 Constant
*ConstantInt::getSigned(const Type
*Ty
, int64_t V
) {
299 return get(Ty
, V
, true);
302 Constant
* ConstantInt::get(const Type
* Ty
, const APInt
& V
) {
303 ConstantInt
*C
= get(Ty
->getContext(), V
);
304 assert(C
->getType() == Ty
->getScalarType() &&
305 "ConstantInt type doesn't match the type implied by its value!");
307 // For vectors, broadcast the value.
308 if (const VectorType
*VTy
= dyn_cast
<VectorType
>(Ty
))
309 return ConstantVector::get(
310 std::vector
<Constant
*>(VTy
->getNumElements(), C
));
315 //===----------------------------------------------------------------------===//
317 //===----------------------------------------------------------------------===//
319 static const fltSemantics
*TypeToFloatSemantics(const Type
*Ty
) {
320 if (Ty
== Type::FloatTy
)
321 return &APFloat::IEEEsingle
;
322 if (Ty
== Type::DoubleTy
)
323 return &APFloat::IEEEdouble
;
324 if (Ty
== Type::X86_FP80Ty
)
325 return &APFloat::x87DoubleExtended
;
326 else if (Ty
== Type::FP128Ty
)
327 return &APFloat::IEEEquad
;
329 assert(Ty
== Type::PPC_FP128Ty
&& "Unknown FP format");
330 return &APFloat::PPCDoubleDouble
;
333 /// get() - This returns a constant fp for the specified value in the
334 /// specified type. This should only be used for simple constant values like
335 /// 2.0/1.0 etc, that are known-valid both as double and as the target format.
336 Constant
* ConstantFP::get(const Type
* Ty
, double V
) {
337 LLVMContext
&Context
= Ty
->getContext();
341 FV
.convert(*TypeToFloatSemantics(Ty
->getScalarType()),
342 APFloat::rmNearestTiesToEven
, &ignored
);
343 Constant
*C
= get(Context
, FV
);
345 // For vectors, broadcast the value.
346 if (const VectorType
*VTy
= dyn_cast
<VectorType
>(Ty
))
347 return ConstantVector::get(
348 std::vector
<Constant
*>(VTy
->getNumElements(), C
));
353 ConstantFP
* ConstantFP::getNegativeZero(const Type
* Ty
) {
354 LLVMContext
&Context
= Ty
->getContext();
355 APFloat apf
= cast
<ConstantFP
>(Constant::getNullValue(Ty
))->getValueAPF();
357 return get(Context
, apf
);
361 Constant
* ConstantFP::getZeroValueForNegation(const Type
* Ty
) {
362 if (const VectorType
*PTy
= dyn_cast
<VectorType
>(Ty
))
363 if (PTy
->getElementType()->isFloatingPoint()) {
364 std::vector
<Constant
*> zeros(PTy
->getNumElements(),
365 getNegativeZero(PTy
->getElementType()));
366 return ConstantVector::get(PTy
, zeros
);
369 if (Ty
->isFloatingPoint())
370 return getNegativeZero(Ty
);
372 return Constant::getNullValue(Ty
);
376 // ConstantFP accessors.
377 ConstantFP
* ConstantFP::get(LLVMContext
&Context
, const APFloat
& V
) {
378 DenseMapAPFloatKeyInfo::KeyTy
Key(V
);
380 LLVMContextImpl
* pImpl
= Context
.pImpl
;
382 pImpl
->ConstantsLock
.reader_acquire();
383 ConstantFP
*&Slot
= pImpl
->FPConstants
[Key
];
384 pImpl
->ConstantsLock
.reader_release();
387 sys::SmartScopedWriter
<true> Writer(pImpl
->ConstantsLock
);
388 ConstantFP
*&NewSlot
= pImpl
->FPConstants
[Key
];
391 if (&V
.getSemantics() == &APFloat::IEEEsingle
)
393 else if (&V
.getSemantics() == &APFloat::IEEEdouble
)
395 else if (&V
.getSemantics() == &APFloat::x87DoubleExtended
)
396 Ty
= Type::X86_FP80Ty
;
397 else if (&V
.getSemantics() == &APFloat::IEEEquad
)
400 assert(&V
.getSemantics() == &APFloat::PPCDoubleDouble
&&
401 "Unknown FP format");
402 Ty
= Type::PPC_FP128Ty
;
404 NewSlot
= new ConstantFP(Ty
, V
);
413 ConstantFP::ConstantFP(const Type
*Ty
, const APFloat
& V
)
414 : Constant(Ty
, ConstantFPVal
, 0, 0), Val(V
) {
415 assert(&V
.getSemantics() == TypeToFloatSemantics(Ty
) &&
419 bool ConstantFP::isNullValue() const {
420 return Val
.isZero() && !Val
.isNegative();
423 bool ConstantFP::isExactlyValue(const APFloat
& V
) const {
424 return Val
.bitwiseIsEqual(V
);
427 //===----------------------------------------------------------------------===//
428 // ConstantXXX Classes
429 //===----------------------------------------------------------------------===//
432 ConstantArray::ConstantArray(const ArrayType
*T
,
433 const std::vector
<Constant
*> &V
)
434 : Constant(T
, ConstantArrayVal
,
435 OperandTraits
<ConstantArray
>::op_end(this) - V
.size(),
437 assert(V
.size() == T
->getNumElements() &&
438 "Invalid initializer vector for constant array");
439 Use
*OL
= OperandList
;
440 for (std::vector
<Constant
*>::const_iterator I
= V
.begin(), E
= V
.end();
443 assert((C
->getType() == T
->getElementType() ||
445 C
->getType()->getTypeID() == T
->getElementType()->getTypeID())) &&
446 "Initializer for array element doesn't match array element type!");
451 Constant
*ConstantArray::get(const ArrayType
*Ty
,
452 const std::vector
<Constant
*> &V
) {
453 LLVMContextImpl
*pImpl
= Ty
->getContext().pImpl
;
454 // If this is an all-zero array, return a ConstantAggregateZero object
457 if (!C
->isNullValue()) {
458 // Implicitly locked.
459 return pImpl
->ArrayConstants
.getOrCreate(Ty
, V
);
461 for (unsigned i
= 1, e
= V
.size(); i
!= e
; ++i
)
463 // Implicitly locked.
464 return pImpl
->ArrayConstants
.getOrCreate(Ty
, V
);
468 return ConstantAggregateZero::get(Ty
);
472 Constant
* ConstantArray::get(const ArrayType
* T
, Constant
* const* Vals
,
474 // FIXME: make this the primary ctor method.
475 return get(T
, std::vector
<Constant
*>(Vals
, Vals
+NumVals
));
478 /// ConstantArray::get(const string&) - Return an array that is initialized to
479 /// contain the specified string. If length is zero then a null terminator is
480 /// added to the specified string so that it may be used in a natural way.
481 /// Otherwise, the length parameter specifies how much of the string to use
482 /// and it won't be null terminated.
484 Constant
* ConstantArray::get(const StringRef
&Str
, bool AddNull
) {
485 std::vector
<Constant
*> ElementVals
;
486 for (unsigned i
= 0; i
< Str
.size(); ++i
)
487 ElementVals
.push_back(ConstantInt::get(Type::Int8Ty
, Str
[i
]));
489 // Add a null terminator to the string...
491 ElementVals
.push_back(ConstantInt::get(Type::Int8Ty
, 0));
494 ArrayType
*ATy
= ArrayType::get(Type::Int8Ty
, ElementVals
.size());
495 return get(ATy
, ElementVals
);
500 ConstantStruct::ConstantStruct(const StructType
*T
,
501 const std::vector
<Constant
*> &V
)
502 : Constant(T
, ConstantStructVal
,
503 OperandTraits
<ConstantStruct
>::op_end(this) - V
.size(),
505 assert(V
.size() == T
->getNumElements() &&
506 "Invalid initializer vector for constant structure");
507 Use
*OL
= OperandList
;
508 for (std::vector
<Constant
*>::const_iterator I
= V
.begin(), E
= V
.end();
511 assert((C
->getType() == T
->getElementType(I
-V
.begin()) ||
512 ((T
->getElementType(I
-V
.begin())->isAbstract() ||
513 C
->getType()->isAbstract()) &&
514 T
->getElementType(I
-V
.begin())->getTypeID() ==
515 C
->getType()->getTypeID())) &&
516 "Initializer for struct element doesn't match struct element type!");
521 // ConstantStruct accessors.
522 Constant
* ConstantStruct::get(const StructType
* T
,
523 const std::vector
<Constant
*>& V
) {
524 LLVMContextImpl
* pImpl
= T
->getContext().pImpl
;
526 // Create a ConstantAggregateZero value if all elements are zeros...
527 for (unsigned i
= 0, e
= V
.size(); i
!= e
; ++i
)
528 if (!V
[i
]->isNullValue())
529 // Implicitly locked.
530 return pImpl
->StructConstants
.getOrCreate(T
, V
);
532 return ConstantAggregateZero::get(T
);
535 Constant
* ConstantStruct::get(LLVMContext
&Context
,
536 const std::vector
<Constant
*>& V
, bool packed
) {
537 std::vector
<const Type
*> StructEls
;
538 StructEls
.reserve(V
.size());
539 for (unsigned i
= 0, e
= V
.size(); i
!= e
; ++i
)
540 StructEls
.push_back(V
[i
]->getType());
541 return get(StructType::get(Context
, StructEls
, packed
), V
);
544 Constant
* ConstantStruct::get(LLVMContext
&Context
,
545 Constant
* const *Vals
, unsigned NumVals
,
547 // FIXME: make this the primary ctor method.
548 return get(Context
, std::vector
<Constant
*>(Vals
, Vals
+NumVals
), Packed
);
551 ConstantVector::ConstantVector(const VectorType
*T
,
552 const std::vector
<Constant
*> &V
)
553 : Constant(T
, ConstantVectorVal
,
554 OperandTraits
<ConstantVector
>::op_end(this) - V
.size(),
556 Use
*OL
= OperandList
;
557 for (std::vector
<Constant
*>::const_iterator I
= V
.begin(), E
= V
.end();
560 assert((C
->getType() == T
->getElementType() ||
562 C
->getType()->getTypeID() == T
->getElementType()->getTypeID())) &&
563 "Initializer for vector element doesn't match vector element type!");
568 // ConstantVector accessors.
569 Constant
* ConstantVector::get(const VectorType
* T
,
570 const std::vector
<Constant
*>& V
) {
571 assert(!V
.empty() && "Vectors can't be empty");
572 LLVMContext
&Context
= T
->getContext();
573 LLVMContextImpl
*pImpl
= Context
.pImpl
;
575 // If this is an all-undef or alll-zero vector, return a
576 // ConstantAggregateZero or UndefValue.
578 bool isZero
= C
->isNullValue();
579 bool isUndef
= isa
<UndefValue
>(C
);
581 if (isZero
|| isUndef
) {
582 for (unsigned i
= 1, e
= V
.size(); i
!= e
; ++i
)
584 isZero
= isUndef
= false;
590 return ConstantAggregateZero::get(T
);
592 return UndefValue::get(T
);
594 // Implicitly locked.
595 return pImpl
->VectorConstants
.getOrCreate(T
, V
);
598 Constant
* ConstantVector::get(const std::vector
<Constant
*>& V
) {
599 assert(!V
.empty() && "Cannot infer type if V is empty");
600 return get(VectorType::get(V
.front()->getType(),V
.size()), V
);
603 Constant
* ConstantVector::get(Constant
* const* Vals
, unsigned NumVals
) {
604 // FIXME: make this the primary ctor method.
605 return get(std::vector
<Constant
*>(Vals
, Vals
+NumVals
));
608 // Utility function for determining if a ConstantExpr is a CastOp or not. This
609 // can't be inline because we don't want to #include Instruction.h into
611 bool ConstantExpr::isCast() const {
612 return Instruction::isCast(getOpcode());
615 bool ConstantExpr::isCompare() const {
616 return getOpcode() == Instruction::ICmp
|| getOpcode() == Instruction::FCmp
;
619 bool ConstantExpr::hasIndices() const {
620 return getOpcode() == Instruction::ExtractValue
||
621 getOpcode() == Instruction::InsertValue
;
624 const SmallVector
<unsigned, 4> &ConstantExpr::getIndices() const {
625 if (const ExtractValueConstantExpr
*EVCE
=
626 dyn_cast
<ExtractValueConstantExpr
>(this))
627 return EVCE
->Indices
;
629 return cast
<InsertValueConstantExpr
>(this)->Indices
;
632 unsigned ConstantExpr::getPredicate() const {
633 assert(getOpcode() == Instruction::FCmp
||
634 getOpcode() == Instruction::ICmp
);
635 return ((const CompareConstantExpr
*)this)->predicate
;
638 /// getWithOperandReplaced - Return a constant expression identical to this
639 /// one, but with the specified operand set to the specified value.
641 ConstantExpr::getWithOperandReplaced(unsigned OpNo
, Constant
*Op
) const {
642 assert(OpNo
< getNumOperands() && "Operand num is out of range!");
643 assert(Op
->getType() == getOperand(OpNo
)->getType() &&
644 "Replacing operand with value of different type!");
645 if (getOperand(OpNo
) == Op
)
646 return const_cast<ConstantExpr
*>(this);
648 Constant
*Op0
, *Op1
, *Op2
;
649 switch (getOpcode()) {
650 case Instruction::Trunc
:
651 case Instruction::ZExt
:
652 case Instruction::SExt
:
653 case Instruction::FPTrunc
:
654 case Instruction::FPExt
:
655 case Instruction::UIToFP
:
656 case Instruction::SIToFP
:
657 case Instruction::FPToUI
:
658 case Instruction::FPToSI
:
659 case Instruction::PtrToInt
:
660 case Instruction::IntToPtr
:
661 case Instruction::BitCast
:
662 return ConstantExpr::getCast(getOpcode(), Op
, getType());
663 case Instruction::Select
:
664 Op0
= (OpNo
== 0) ? Op
: getOperand(0);
665 Op1
= (OpNo
== 1) ? Op
: getOperand(1);
666 Op2
= (OpNo
== 2) ? Op
: getOperand(2);
667 return ConstantExpr::getSelect(Op0
, Op1
, Op2
);
668 case Instruction::InsertElement
:
669 Op0
= (OpNo
== 0) ? Op
: getOperand(0);
670 Op1
= (OpNo
== 1) ? Op
: getOperand(1);
671 Op2
= (OpNo
== 2) ? Op
: getOperand(2);
672 return ConstantExpr::getInsertElement(Op0
, Op1
, Op2
);
673 case Instruction::ExtractElement
:
674 Op0
= (OpNo
== 0) ? Op
: getOperand(0);
675 Op1
= (OpNo
== 1) ? Op
: getOperand(1);
676 return ConstantExpr::getExtractElement(Op0
, Op1
);
677 case Instruction::ShuffleVector
:
678 Op0
= (OpNo
== 0) ? Op
: getOperand(0);
679 Op1
= (OpNo
== 1) ? Op
: getOperand(1);
680 Op2
= (OpNo
== 2) ? Op
: getOperand(2);
681 return ConstantExpr::getShuffleVector(Op0
, Op1
, Op2
);
682 case Instruction::GetElementPtr
: {
683 SmallVector
<Constant
*, 8> Ops
;
684 Ops
.resize(getNumOperands()-1);
685 for (unsigned i
= 1, e
= getNumOperands(); i
!= e
; ++i
)
686 Ops
[i
-1] = getOperand(i
);
688 return ConstantExpr::getGetElementPtr(Op
, &Ops
[0], Ops
.size());
690 return ConstantExpr::getGetElementPtr(getOperand(0), &Ops
[0], Ops
.size());
693 assert(getNumOperands() == 2 && "Must be binary operator?");
694 Op0
= (OpNo
== 0) ? Op
: getOperand(0);
695 Op1
= (OpNo
== 1) ? Op
: getOperand(1);
696 return ConstantExpr::get(getOpcode(), Op0
, Op1
);
700 /// getWithOperands - This returns the current constant expression with the
701 /// operands replaced with the specified values. The specified operands must
702 /// match count and type with the existing ones.
703 Constant
*ConstantExpr::
704 getWithOperands(Constant
* const *Ops
, unsigned NumOps
) const {
705 assert(NumOps
== getNumOperands() && "Operand count mismatch!");
706 bool AnyChange
= false;
707 for (unsigned i
= 0; i
!= NumOps
; ++i
) {
708 assert(Ops
[i
]->getType() == getOperand(i
)->getType() &&
709 "Operand type mismatch!");
710 AnyChange
|= Ops
[i
] != getOperand(i
);
712 if (!AnyChange
) // No operands changed, return self.
713 return const_cast<ConstantExpr
*>(this);
715 switch (getOpcode()) {
716 case Instruction::Trunc
:
717 case Instruction::ZExt
:
718 case Instruction::SExt
:
719 case Instruction::FPTrunc
:
720 case Instruction::FPExt
:
721 case Instruction::UIToFP
:
722 case Instruction::SIToFP
:
723 case Instruction::FPToUI
:
724 case Instruction::FPToSI
:
725 case Instruction::PtrToInt
:
726 case Instruction::IntToPtr
:
727 case Instruction::BitCast
:
728 return ConstantExpr::getCast(getOpcode(), Ops
[0], getType());
729 case Instruction::Select
:
730 return ConstantExpr::getSelect(Ops
[0], Ops
[1], Ops
[2]);
731 case Instruction::InsertElement
:
732 return ConstantExpr::getInsertElement(Ops
[0], Ops
[1], Ops
[2]);
733 case Instruction::ExtractElement
:
734 return ConstantExpr::getExtractElement(Ops
[0], Ops
[1]);
735 case Instruction::ShuffleVector
:
736 return ConstantExpr::getShuffleVector(Ops
[0], Ops
[1], Ops
[2]);
737 case Instruction::GetElementPtr
:
738 return ConstantExpr::getGetElementPtr(Ops
[0], &Ops
[1], NumOps
-1);
739 case Instruction::ICmp
:
740 case Instruction::FCmp
:
741 return ConstantExpr::getCompare(getPredicate(), Ops
[0], Ops
[1]);
743 assert(getNumOperands() == 2 && "Must be binary operator?");
744 return ConstantExpr::get(getOpcode(), Ops
[0], Ops
[1]);
749 //===----------------------------------------------------------------------===//
750 // isValueValidForType implementations
752 bool ConstantInt::isValueValidForType(const Type
*Ty
, uint64_t Val
) {
753 unsigned NumBits
= cast
<IntegerType
>(Ty
)->getBitWidth(); // assert okay
754 if (Ty
== Type::Int1Ty
)
755 return Val
== 0 || Val
== 1;
757 return true; // always true, has to fit in largest type
758 uint64_t Max
= (1ll << NumBits
) - 1;
762 bool ConstantInt::isValueValidForType(const Type
*Ty
, int64_t Val
) {
763 unsigned NumBits
= cast
<IntegerType
>(Ty
)->getBitWidth(); // assert okay
764 if (Ty
== Type::Int1Ty
)
765 return Val
== 0 || Val
== 1 || Val
== -1;
767 return true; // always true, has to fit in largest type
768 int64_t Min
= -(1ll << (NumBits
-1));
769 int64_t Max
= (1ll << (NumBits
-1)) - 1;
770 return (Val
>= Min
&& Val
<= Max
);
773 bool ConstantFP::isValueValidForType(const Type
*Ty
, const APFloat
& Val
) {
774 // convert modifies in place, so make a copy.
775 APFloat Val2
= APFloat(Val
);
777 switch (Ty
->getTypeID()) {
779 return false; // These can't be represented as floating point!
781 // FIXME rounding mode needs to be more flexible
782 case Type::FloatTyID
: {
783 if (&Val2
.getSemantics() == &APFloat::IEEEsingle
)
785 Val2
.convert(APFloat::IEEEsingle
, APFloat::rmNearestTiesToEven
, &losesInfo
);
788 case Type::DoubleTyID
: {
789 if (&Val2
.getSemantics() == &APFloat::IEEEsingle
||
790 &Val2
.getSemantics() == &APFloat::IEEEdouble
)
792 Val2
.convert(APFloat::IEEEdouble
, APFloat::rmNearestTiesToEven
, &losesInfo
);
795 case Type::X86_FP80TyID
:
796 return &Val2
.getSemantics() == &APFloat::IEEEsingle
||
797 &Val2
.getSemantics() == &APFloat::IEEEdouble
||
798 &Val2
.getSemantics() == &APFloat::x87DoubleExtended
;
799 case Type::FP128TyID
:
800 return &Val2
.getSemantics() == &APFloat::IEEEsingle
||
801 &Val2
.getSemantics() == &APFloat::IEEEdouble
||
802 &Val2
.getSemantics() == &APFloat::IEEEquad
;
803 case Type::PPC_FP128TyID
:
804 return &Val2
.getSemantics() == &APFloat::IEEEsingle
||
805 &Val2
.getSemantics() == &APFloat::IEEEdouble
||
806 &Val2
.getSemantics() == &APFloat::PPCDoubleDouble
;
810 //===----------------------------------------------------------------------===//
811 // Factory Function Implementation
813 static char getValType(ConstantAggregateZero
*CPZ
) { return 0; }
815 ConstantAggregateZero
* ConstantAggregateZero::get(const Type
* Ty
) {
816 assert((isa
<StructType
>(Ty
) || isa
<ArrayType
>(Ty
) || isa
<VectorType
>(Ty
)) &&
817 "Cannot create an aggregate zero of non-aggregate type!");
819 LLVMContextImpl
*pImpl
= Ty
->getContext().pImpl
;
820 // Implicitly locked.
821 return pImpl
->AggZeroConstants
.getOrCreate(Ty
, 0);
824 /// destroyConstant - Remove the constant from the constant table...
826 void ConstantAggregateZero::destroyConstant() {
827 // Implicitly locked.
828 getType()->getContext().pImpl
->AggZeroConstants
.remove(this);
829 destroyConstantImpl();
832 /// destroyConstant - Remove the constant from the constant table...
834 void ConstantArray::destroyConstant() {
835 // Implicitly locked.
836 getType()->getContext().pImpl
->ArrayConstants
.remove(this);
837 destroyConstantImpl();
840 /// isString - This method returns true if the array is an array of i8, and
841 /// if the elements of the array are all ConstantInt's.
842 bool ConstantArray::isString() const {
843 // Check the element type for i8...
844 if (getType()->getElementType() != Type::Int8Ty
)
846 // Check the elements to make sure they are all integers, not constant
848 for (unsigned i
= 0, e
= getNumOperands(); i
!= e
; ++i
)
849 if (!isa
<ConstantInt
>(getOperand(i
)))
854 /// isCString - This method returns true if the array is a string (see
855 /// isString) and it ends in a null byte \\0 and does not contains any other
856 /// null bytes except its terminator.
857 bool ConstantArray::isCString() const {
858 // Check the element type for i8...
859 if (getType()->getElementType() != Type::Int8Ty
)
862 // Last element must be a null.
863 if (!getOperand(getNumOperands()-1)->isNullValue())
865 // Other elements must be non-null integers.
866 for (unsigned i
= 0, e
= getNumOperands()-1; i
!= e
; ++i
) {
867 if (!isa
<ConstantInt
>(getOperand(i
)))
869 if (getOperand(i
)->isNullValue())
876 /// getAsString - If the sub-element type of this array is i8
877 /// then this method converts the array to an std::string and returns it.
878 /// Otherwise, it asserts out.
880 std::string
ConstantArray::getAsString() const {
881 assert(isString() && "Not a string!");
883 Result
.reserve(getNumOperands());
884 for (unsigned i
= 0, e
= getNumOperands(); i
!= e
; ++i
)
885 Result
.push_back((char)cast
<ConstantInt
>(getOperand(i
))->getZExtValue());
890 //---- ConstantStruct::get() implementation...
897 // destroyConstant - Remove the constant from the constant table...
899 void ConstantStruct::destroyConstant() {
900 // Implicitly locked.
901 getType()->getContext().pImpl
->StructConstants
.remove(this);
902 destroyConstantImpl();
905 // destroyConstant - Remove the constant from the constant table...
907 void ConstantVector::destroyConstant() {
908 // Implicitly locked.
909 getType()->getContext().pImpl
->VectorConstants
.remove(this);
910 destroyConstantImpl();
913 /// This function will return true iff every element in this vector constant
914 /// is set to all ones.
915 /// @returns true iff this constant's emements are all set to all ones.
916 /// @brief Determine if the value is all ones.
917 bool ConstantVector::isAllOnesValue() const {
918 // Check out first element.
919 const Constant
*Elt
= getOperand(0);
920 const ConstantInt
*CI
= dyn_cast
<ConstantInt
>(Elt
);
921 if (!CI
|| !CI
->isAllOnesValue()) return false;
922 // Then make sure all remaining elements point to the same value.
923 for (unsigned I
= 1, E
= getNumOperands(); I
< E
; ++I
) {
924 if (getOperand(I
) != Elt
) return false;
929 /// getSplatValue - If this is a splat constant, where all of the
930 /// elements have the same value, return that value. Otherwise return null.
931 Constant
*ConstantVector::getSplatValue() {
932 // Check out first element.
933 Constant
*Elt
= getOperand(0);
934 // Then make sure all remaining elements point to the same value.
935 for (unsigned I
= 1, E
= getNumOperands(); I
< E
; ++I
)
936 if (getOperand(I
) != Elt
) return 0;
940 //---- ConstantPointerNull::get() implementation...
943 static char getValType(ConstantPointerNull
*) {
948 ConstantPointerNull
*ConstantPointerNull::get(const PointerType
*Ty
) {
949 // Implicitly locked.
950 return Ty
->getContext().pImpl
->NullPtrConstants
.getOrCreate(Ty
, 0);
953 // destroyConstant - Remove the constant from the constant table...
955 void ConstantPointerNull::destroyConstant() {
956 // Implicitly locked.
957 getType()->getContext().pImpl
->NullPtrConstants
.remove(this);
958 destroyConstantImpl();
962 //---- UndefValue::get() implementation...
965 static char getValType(UndefValue
*) {
969 UndefValue
*UndefValue::get(const Type
*Ty
) {
970 // Implicitly locked.
971 return Ty
->getContext().pImpl
->UndefValueConstants
.getOrCreate(Ty
, 0);
974 // destroyConstant - Remove the constant from the constant table.
976 void UndefValue::destroyConstant() {
977 // Implicitly locked.
978 getType()->getContext().pImpl
->UndefValueConstants
.remove(this);
979 destroyConstantImpl();
982 //---- ConstantExpr::get() implementations...
985 static ExprMapKeyType
getValType(ConstantExpr
*CE
) {
986 std::vector
<Constant
*> Operands
;
987 Operands
.reserve(CE
->getNumOperands());
988 for (unsigned i
= 0, e
= CE
->getNumOperands(); i
!= e
; ++i
)
989 Operands
.push_back(cast
<Constant
>(CE
->getOperand(i
)));
990 return ExprMapKeyType(CE
->getOpcode(), Operands
,
991 CE
->isCompare() ? CE
->getPredicate() : 0,
993 CE
->getIndices() : SmallVector
<unsigned, 4>());
996 /// This is a utility function to handle folding of casts and lookup of the
997 /// cast in the ExprConstants map. It is used by the various get* methods below.
998 static inline Constant
*getFoldedCast(
999 Instruction::CastOps opc
, Constant
*C
, const Type
*Ty
) {
1000 assert(Ty
->isFirstClassType() && "Cannot cast to an aggregate type!");
1001 // Fold a few common cases
1002 if (Constant
*FC
= ConstantFoldCastInstruction(Ty
->getContext(), opc
, C
, Ty
))
1005 LLVMContextImpl
*pImpl
= Ty
->getContext().pImpl
;
1007 // Look up the constant in the table first to ensure uniqueness
1008 std::vector
<Constant
*> argVec(1, C
);
1009 ExprMapKeyType
Key(opc
, argVec
);
1011 // Implicitly locked.
1012 return pImpl
->ExprConstants
.getOrCreate(Ty
, Key
);
1015 Constant
*ConstantExpr::getCast(unsigned oc
, Constant
*C
, const Type
*Ty
) {
1016 Instruction::CastOps opc
= Instruction::CastOps(oc
);
1017 assert(Instruction::isCast(opc
) && "opcode out of range");
1018 assert(C
&& Ty
&& "Null arguments to getCast");
1019 assert(Ty
->isFirstClassType() && "Cannot cast to an aggregate type!");
1023 llvm_unreachable("Invalid cast opcode");
1025 case Instruction::Trunc
: return getTrunc(C
, Ty
);
1026 case Instruction::ZExt
: return getZExt(C
, Ty
);
1027 case Instruction::SExt
: return getSExt(C
, Ty
);
1028 case Instruction::FPTrunc
: return getFPTrunc(C
, Ty
);
1029 case Instruction::FPExt
: return getFPExtend(C
, Ty
);
1030 case Instruction::UIToFP
: return getUIToFP(C
, Ty
);
1031 case Instruction::SIToFP
: return getSIToFP(C
, Ty
);
1032 case Instruction::FPToUI
: return getFPToUI(C
, Ty
);
1033 case Instruction::FPToSI
: return getFPToSI(C
, Ty
);
1034 case Instruction::PtrToInt
: return getPtrToInt(C
, Ty
);
1035 case Instruction::IntToPtr
: return getIntToPtr(C
, Ty
);
1036 case Instruction::BitCast
: return getBitCast(C
, Ty
);
1041 Constant
*ConstantExpr::getZExtOrBitCast(Constant
*C
, const Type
*Ty
) {
1042 if (C
->getType()->getScalarSizeInBits() == Ty
->getScalarSizeInBits())
1043 return getCast(Instruction::BitCast
, C
, Ty
);
1044 return getCast(Instruction::ZExt
, C
, Ty
);
1047 Constant
*ConstantExpr::getSExtOrBitCast(Constant
*C
, const Type
*Ty
) {
1048 if (C
->getType()->getScalarSizeInBits() == Ty
->getScalarSizeInBits())
1049 return getCast(Instruction::BitCast
, C
, Ty
);
1050 return getCast(Instruction::SExt
, C
, Ty
);
1053 Constant
*ConstantExpr::getTruncOrBitCast(Constant
*C
, const Type
*Ty
) {
1054 if (C
->getType()->getScalarSizeInBits() == Ty
->getScalarSizeInBits())
1055 return getCast(Instruction::BitCast
, C
, Ty
);
1056 return getCast(Instruction::Trunc
, C
, Ty
);
1059 Constant
*ConstantExpr::getPointerCast(Constant
*S
, const Type
*Ty
) {
1060 assert(isa
<PointerType
>(S
->getType()) && "Invalid cast");
1061 assert((Ty
->isInteger() || isa
<PointerType
>(Ty
)) && "Invalid cast");
1063 if (Ty
->isInteger())
1064 return getCast(Instruction::PtrToInt
, S
, Ty
);
1065 return getCast(Instruction::BitCast
, S
, Ty
);
1068 Constant
*ConstantExpr::getIntegerCast(Constant
*C
, const Type
*Ty
,
1070 assert(C
->getType()->isIntOrIntVector() &&
1071 Ty
->isIntOrIntVector() && "Invalid cast");
1072 unsigned SrcBits
= C
->getType()->getScalarSizeInBits();
1073 unsigned DstBits
= Ty
->getScalarSizeInBits();
1074 Instruction::CastOps opcode
=
1075 (SrcBits
== DstBits
? Instruction::BitCast
:
1076 (SrcBits
> DstBits
? Instruction::Trunc
:
1077 (isSigned
? Instruction::SExt
: Instruction::ZExt
)));
1078 return getCast(opcode
, C
, Ty
);
1081 Constant
*ConstantExpr::getFPCast(Constant
*C
, const Type
*Ty
) {
1082 assert(C
->getType()->isFPOrFPVector() && Ty
->isFPOrFPVector() &&
1084 unsigned SrcBits
= C
->getType()->getScalarSizeInBits();
1085 unsigned DstBits
= Ty
->getScalarSizeInBits();
1086 if (SrcBits
== DstBits
)
1087 return C
; // Avoid a useless cast
1088 Instruction::CastOps opcode
=
1089 (SrcBits
> DstBits
? Instruction::FPTrunc
: Instruction::FPExt
);
1090 return getCast(opcode
, C
, Ty
);
1093 Constant
*ConstantExpr::getTrunc(Constant
*C
, const Type
*Ty
) {
1095 bool fromVec
= C
->getType()->getTypeID() == Type::VectorTyID
;
1096 bool toVec
= Ty
->getTypeID() == Type::VectorTyID
;
1098 assert((fromVec
== toVec
) && "Cannot convert from scalar to/from vector");
1099 assert(C
->getType()->isIntOrIntVector() && "Trunc operand must be integer");
1100 assert(Ty
->isIntOrIntVector() && "Trunc produces only integral");
1101 assert(C
->getType()->getScalarSizeInBits() > Ty
->getScalarSizeInBits()&&
1102 "SrcTy must be larger than DestTy for Trunc!");
1104 return getFoldedCast(Instruction::Trunc
, C
, Ty
);
1107 Constant
*ConstantExpr::getSExt(Constant
*C
, const Type
*Ty
) {
1109 bool fromVec
= C
->getType()->getTypeID() == Type::VectorTyID
;
1110 bool toVec
= Ty
->getTypeID() == Type::VectorTyID
;
1112 assert((fromVec
== toVec
) && "Cannot convert from scalar to/from vector");
1113 assert(C
->getType()->isIntOrIntVector() && "SExt operand must be integral");
1114 assert(Ty
->isIntOrIntVector() && "SExt produces only integer");
1115 assert(C
->getType()->getScalarSizeInBits() < Ty
->getScalarSizeInBits()&&
1116 "SrcTy must be smaller than DestTy for SExt!");
1118 return getFoldedCast(Instruction::SExt
, C
, Ty
);
1121 Constant
*ConstantExpr::getZExt(Constant
*C
, const Type
*Ty
) {
1123 bool fromVec
= C
->getType()->getTypeID() == Type::VectorTyID
;
1124 bool toVec
= Ty
->getTypeID() == Type::VectorTyID
;
1126 assert((fromVec
== toVec
) && "Cannot convert from scalar to/from vector");
1127 assert(C
->getType()->isIntOrIntVector() && "ZEXt operand must be integral");
1128 assert(Ty
->isIntOrIntVector() && "ZExt produces only integer");
1129 assert(C
->getType()->getScalarSizeInBits() < Ty
->getScalarSizeInBits()&&
1130 "SrcTy must be smaller than DestTy for ZExt!");
1132 return getFoldedCast(Instruction::ZExt
, C
, Ty
);
1135 Constant
*ConstantExpr::getFPTrunc(Constant
*C
, const Type
*Ty
) {
1137 bool fromVec
= C
->getType()->getTypeID() == Type::VectorTyID
;
1138 bool toVec
= Ty
->getTypeID() == Type::VectorTyID
;
1140 assert((fromVec
== toVec
) && "Cannot convert from scalar to/from vector");
1141 assert(C
->getType()->isFPOrFPVector() && Ty
->isFPOrFPVector() &&
1142 C
->getType()->getScalarSizeInBits() > Ty
->getScalarSizeInBits()&&
1143 "This is an illegal floating point truncation!");
1144 return getFoldedCast(Instruction::FPTrunc
, C
, Ty
);
1147 Constant
*ConstantExpr::getFPExtend(Constant
*C
, const Type
*Ty
) {
1149 bool fromVec
= C
->getType()->getTypeID() == Type::VectorTyID
;
1150 bool toVec
= Ty
->getTypeID() == Type::VectorTyID
;
1152 assert((fromVec
== toVec
) && "Cannot convert from scalar to/from vector");
1153 assert(C
->getType()->isFPOrFPVector() && Ty
->isFPOrFPVector() &&
1154 C
->getType()->getScalarSizeInBits() < Ty
->getScalarSizeInBits()&&
1155 "This is an illegal floating point extension!");
1156 return getFoldedCast(Instruction::FPExt
, C
, Ty
);
1159 Constant
*ConstantExpr::getUIToFP(Constant
*C
, const Type
*Ty
) {
1161 bool fromVec
= C
->getType()->getTypeID() == Type::VectorTyID
;
1162 bool toVec
= Ty
->getTypeID() == Type::VectorTyID
;
1164 assert((fromVec
== toVec
) && "Cannot convert from scalar to/from vector");
1165 assert(C
->getType()->isIntOrIntVector() && Ty
->isFPOrFPVector() &&
1166 "This is an illegal uint to floating point cast!");
1167 return getFoldedCast(Instruction::UIToFP
, C
, Ty
);
1170 Constant
*ConstantExpr::getSIToFP(Constant
*C
, const Type
*Ty
) {
1172 bool fromVec
= C
->getType()->getTypeID() == Type::VectorTyID
;
1173 bool toVec
= Ty
->getTypeID() == Type::VectorTyID
;
1175 assert((fromVec
== toVec
) && "Cannot convert from scalar to/from vector");
1176 assert(C
->getType()->isIntOrIntVector() && Ty
->isFPOrFPVector() &&
1177 "This is an illegal sint to floating point cast!");
1178 return getFoldedCast(Instruction::SIToFP
, C
, Ty
);
1181 Constant
*ConstantExpr::getFPToUI(Constant
*C
, const Type
*Ty
) {
1183 bool fromVec
= C
->getType()->getTypeID() == Type::VectorTyID
;
1184 bool toVec
= Ty
->getTypeID() == Type::VectorTyID
;
1186 assert((fromVec
== toVec
) && "Cannot convert from scalar to/from vector");
1187 assert(C
->getType()->isFPOrFPVector() && Ty
->isIntOrIntVector() &&
1188 "This is an illegal floating point to uint cast!");
1189 return getFoldedCast(Instruction::FPToUI
, C
, Ty
);
1192 Constant
*ConstantExpr::getFPToSI(Constant
*C
, const Type
*Ty
) {
1194 bool fromVec
= C
->getType()->getTypeID() == Type::VectorTyID
;
1195 bool toVec
= Ty
->getTypeID() == Type::VectorTyID
;
1197 assert((fromVec
== toVec
) && "Cannot convert from scalar to/from vector");
1198 assert(C
->getType()->isFPOrFPVector() && Ty
->isIntOrIntVector() &&
1199 "This is an illegal floating point to sint cast!");
1200 return getFoldedCast(Instruction::FPToSI
, C
, Ty
);
1203 Constant
*ConstantExpr::getPtrToInt(Constant
*C
, const Type
*DstTy
) {
1204 assert(isa
<PointerType
>(C
->getType()) && "PtrToInt source must be pointer");
1205 assert(DstTy
->isInteger() && "PtrToInt destination must be integral");
1206 return getFoldedCast(Instruction::PtrToInt
, C
, DstTy
);
1209 Constant
*ConstantExpr::getIntToPtr(Constant
*C
, const Type
*DstTy
) {
1210 assert(C
->getType()->isInteger() && "IntToPtr source must be integral");
1211 assert(isa
<PointerType
>(DstTy
) && "IntToPtr destination must be a pointer");
1212 return getFoldedCast(Instruction::IntToPtr
, C
, DstTy
);
1215 Constant
*ConstantExpr::getBitCast(Constant
*C
, const Type
*DstTy
) {
1216 // BitCast implies a no-op cast of type only. No bits change. However, you
1217 // can't cast pointers to anything but pointers.
1219 const Type
*SrcTy
= C
->getType();
1220 assert((isa
<PointerType
>(SrcTy
) == isa
<PointerType
>(DstTy
)) &&
1221 "BitCast cannot cast pointer to non-pointer and vice versa");
1223 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
1224 // or nonptr->ptr). For all the other types, the cast is okay if source and
1225 // destination bit widths are identical.
1226 unsigned SrcBitSize
= SrcTy
->getPrimitiveSizeInBits();
1227 unsigned DstBitSize
= DstTy
->getPrimitiveSizeInBits();
1229 assert(SrcBitSize
== DstBitSize
&& "BitCast requires types of same width");
1231 // It is common to ask for a bitcast of a value to its own type, handle this
1233 if (C
->getType() == DstTy
) return C
;
1235 return getFoldedCast(Instruction::BitCast
, C
, DstTy
);
1238 Constant
*ConstantExpr::getTy(const Type
*ReqTy
, unsigned Opcode
,
1239 Constant
*C1
, Constant
*C2
) {
1240 // Check the operands for consistency first
1241 assert(Opcode
>= Instruction::BinaryOpsBegin
&&
1242 Opcode
< Instruction::BinaryOpsEnd
&&
1243 "Invalid opcode in binary constant expression");
1244 assert(C1
->getType() == C2
->getType() &&
1245 "Operand types in binary constant expression should match");
1247 if (ReqTy
== C1
->getType() || ReqTy
== Type::Int1Ty
)
1248 if (Constant
*FC
= ConstantFoldBinaryInstruction(ReqTy
->getContext(),
1250 return FC
; // Fold a few common cases...
1252 std::vector
<Constant
*> argVec(1, C1
); argVec
.push_back(C2
);
1253 ExprMapKeyType
Key(Opcode
, argVec
);
1255 LLVMContextImpl
*pImpl
= ReqTy
->getContext().pImpl
;
1257 // Implicitly locked.
1258 return pImpl
->ExprConstants
.getOrCreate(ReqTy
, Key
);
1261 Constant
*ConstantExpr::getCompareTy(unsigned short predicate
,
1262 Constant
*C1
, Constant
*C2
) {
1263 switch (predicate
) {
1264 default: llvm_unreachable("Invalid CmpInst predicate");
1265 case CmpInst::FCMP_FALSE
: case CmpInst::FCMP_OEQ
: case CmpInst::FCMP_OGT
:
1266 case CmpInst::FCMP_OGE
: case CmpInst::FCMP_OLT
: case CmpInst::FCMP_OLE
:
1267 case CmpInst::FCMP_ONE
: case CmpInst::FCMP_ORD
: case CmpInst::FCMP_UNO
:
1268 case CmpInst::FCMP_UEQ
: case CmpInst::FCMP_UGT
: case CmpInst::FCMP_UGE
:
1269 case CmpInst::FCMP_ULT
: case CmpInst::FCMP_ULE
: case CmpInst::FCMP_UNE
:
1270 case CmpInst::FCMP_TRUE
:
1271 return getFCmp(predicate
, C1
, C2
);
1273 case CmpInst::ICMP_EQ
: case CmpInst::ICMP_NE
: case CmpInst::ICMP_UGT
:
1274 case CmpInst::ICMP_UGE
: case CmpInst::ICMP_ULT
: case CmpInst::ICMP_ULE
:
1275 case CmpInst::ICMP_SGT
: case CmpInst::ICMP_SGE
: case CmpInst::ICMP_SLT
:
1276 case CmpInst::ICMP_SLE
:
1277 return getICmp(predicate
, C1
, C2
);
1281 Constant
*ConstantExpr::get(unsigned Opcode
, Constant
*C1
, Constant
*C2
) {
1282 // API compatibility: Adjust integer opcodes to floating-point opcodes.
1283 if (C1
->getType()->isFPOrFPVector()) {
1284 if (Opcode
== Instruction::Add
) Opcode
= Instruction::FAdd
;
1285 else if (Opcode
== Instruction::Sub
) Opcode
= Instruction::FSub
;
1286 else if (Opcode
== Instruction::Mul
) Opcode
= Instruction::FMul
;
1290 case Instruction::Add
:
1291 case Instruction::Sub
:
1292 case Instruction::Mul
:
1293 assert(C1
->getType() == C2
->getType() && "Op types should be identical!");
1294 assert(C1
->getType()->isIntOrIntVector() &&
1295 "Tried to create an integer operation on a non-integer type!");
1297 case Instruction::FAdd
:
1298 case Instruction::FSub
:
1299 case Instruction::FMul
:
1300 assert(C1
->getType() == C2
->getType() && "Op types should be identical!");
1301 assert(C1
->getType()->isFPOrFPVector() &&
1302 "Tried to create a floating-point operation on a "
1303 "non-floating-point type!");
1305 case Instruction::UDiv
:
1306 case Instruction::SDiv
:
1307 assert(C1
->getType() == C2
->getType() && "Op types should be identical!");
1308 assert(C1
->getType()->isIntOrIntVector() &&
1309 "Tried to create an arithmetic operation on a non-arithmetic type!");
1311 case Instruction::FDiv
:
1312 assert(C1
->getType() == C2
->getType() && "Op types should be identical!");
1313 assert(C1
->getType()->isFPOrFPVector() &&
1314 "Tried to create an arithmetic operation on a non-arithmetic type!");
1316 case Instruction::URem
:
1317 case Instruction::SRem
:
1318 assert(C1
->getType() == C2
->getType() && "Op types should be identical!");
1319 assert(C1
->getType()->isIntOrIntVector() &&
1320 "Tried to create an arithmetic operation on a non-arithmetic type!");
1322 case Instruction::FRem
:
1323 assert(C1
->getType() == C2
->getType() && "Op types should be identical!");
1324 assert(C1
->getType()->isFPOrFPVector() &&
1325 "Tried to create an arithmetic operation on a non-arithmetic type!");
1327 case Instruction::And
:
1328 case Instruction::Or
:
1329 case Instruction::Xor
:
1330 assert(C1
->getType() == C2
->getType() && "Op types should be identical!");
1331 assert(C1
->getType()->isIntOrIntVector() &&
1332 "Tried to create a logical operation on a non-integral type!");
1334 case Instruction::Shl
:
1335 case Instruction::LShr
:
1336 case Instruction::AShr
:
1337 assert(C1
->getType() == C2
->getType() && "Op types should be identical!");
1338 assert(C1
->getType()->isIntOrIntVector() &&
1339 "Tried to create a shift operation on a non-integer type!");
1346 return getTy(C1
->getType(), Opcode
, C1
, C2
);
1349 Constant
* ConstantExpr::getSizeOf(const Type
* Ty
) {
1350 // sizeof is implemented as: (i64) gep (Ty*)null, 1
1351 // Note that a non-inbounds gep is used, as null isn't within any object.
1352 Constant
*GEPIdx
= ConstantInt::get(Type::Int32Ty
, 1);
1353 Constant
*GEP
= getGetElementPtr(
1354 Constant::getNullValue(PointerType::getUnqual(Ty
)), &GEPIdx
, 1);
1355 return getCast(Instruction::PtrToInt
, GEP
, Type::Int64Ty
);
1358 Constant
* ConstantExpr::getAlignOf(const Type
* Ty
) {
1359 // alignof is implemented as: (i64) gep ({i8,Ty}*)null, 0, 1
1360 const Type
*AligningTy
= StructType::get(Ty
->getContext(),
1361 Type::Int8Ty
, Ty
, NULL
);
1362 Constant
*NullPtr
= Constant::getNullValue(AligningTy
->getPointerTo());
1363 Constant
*Zero
= ConstantInt::get(Type::Int32Ty
, 0);
1364 Constant
*One
= ConstantInt::get(Type::Int32Ty
, 1);
1365 Constant
*Indices
[2] = { Zero
, One
};
1366 Constant
*GEP
= getGetElementPtr(NullPtr
, Indices
, 2);
1367 return getCast(Instruction::PtrToInt
, GEP
, Type::Int32Ty
);
1371 Constant
*ConstantExpr::getCompare(unsigned short pred
,
1372 Constant
*C1
, Constant
*C2
) {
1373 assert(C1
->getType() == C2
->getType() && "Op types should be identical!");
1374 return getCompareTy(pred
, C1
, C2
);
1377 Constant
*ConstantExpr::getSelectTy(const Type
*ReqTy
, Constant
*C
,
1378 Constant
*V1
, Constant
*V2
) {
1379 assert(!SelectInst::areInvalidOperands(C
, V1
, V2
)&&"Invalid select operands");
1381 if (ReqTy
== V1
->getType())
1382 if (Constant
*SC
= ConstantFoldSelectInstruction(
1383 ReqTy
->getContext(), C
, V1
, V2
))
1384 return SC
; // Fold common cases
1386 std::vector
<Constant
*> argVec(3, C
);
1389 ExprMapKeyType
Key(Instruction::Select
, argVec
);
1391 LLVMContextImpl
*pImpl
= ReqTy
->getContext().pImpl
;
1393 // Implicitly locked.
1394 return pImpl
->ExprConstants
.getOrCreate(ReqTy
, Key
);
1397 Constant
*ConstantExpr::getGetElementPtrTy(const Type
*ReqTy
, Constant
*C
,
1400 assert(GetElementPtrInst::getIndexedType(C
->getType(), Idxs
,
1402 cast
<PointerType
>(ReqTy
)->getElementType() &&
1403 "GEP indices invalid!");
1405 if (Constant
*FC
= ConstantFoldGetElementPtr(
1406 ReqTy
->getContext(), C
, (Constant
**)Idxs
, NumIdx
))
1407 return FC
; // Fold a few common cases...
1409 assert(isa
<PointerType
>(C
->getType()) &&
1410 "Non-pointer type for constant GetElementPtr expression");
1411 // Look up the constant in the table first to ensure uniqueness
1412 std::vector
<Constant
*> ArgVec
;
1413 ArgVec
.reserve(NumIdx
+1);
1414 ArgVec
.push_back(C
);
1415 for (unsigned i
= 0; i
!= NumIdx
; ++i
)
1416 ArgVec
.push_back(cast
<Constant
>(Idxs
[i
]));
1417 const ExprMapKeyType
Key(Instruction::GetElementPtr
, ArgVec
);
1419 LLVMContextImpl
*pImpl
= ReqTy
->getContext().pImpl
;
1421 // Implicitly locked.
1422 return pImpl
->ExprConstants
.getOrCreate(ReqTy
, Key
);
1425 Constant
*ConstantExpr::getGetElementPtr(Constant
*C
, Value
* const *Idxs
,
1427 // Get the result type of the getelementptr!
1429 GetElementPtrInst::getIndexedType(C
->getType(), Idxs
, Idxs
+NumIdx
);
1430 assert(Ty
&& "GEP indices invalid!");
1431 unsigned As
= cast
<PointerType
>(C
->getType())->getAddressSpace();
1432 return getGetElementPtrTy(PointerType::get(Ty
, As
), C
, Idxs
, NumIdx
);
1435 Constant
*ConstantExpr::getGetElementPtr(Constant
*C
, Constant
* const *Idxs
,
1437 return getGetElementPtr(C
, (Value
* const *)Idxs
, NumIdx
);
1442 ConstantExpr::getICmp(unsigned short pred
, Constant
* LHS
, Constant
* RHS
) {
1443 assert(LHS
->getType() == RHS
->getType());
1444 assert(pred
>= ICmpInst::FIRST_ICMP_PREDICATE
&&
1445 pred
<= ICmpInst::LAST_ICMP_PREDICATE
&& "Invalid ICmp Predicate");
1447 if (Constant
*FC
= ConstantFoldCompareInstruction(
1448 LHS
->getContext(), pred
, LHS
, RHS
))
1449 return FC
; // Fold a few common cases...
1451 // Look up the constant in the table first to ensure uniqueness
1452 std::vector
<Constant
*> ArgVec
;
1453 ArgVec
.push_back(LHS
);
1454 ArgVec
.push_back(RHS
);
1455 // Get the key type with both the opcode and predicate
1456 const ExprMapKeyType
Key(Instruction::ICmp
, ArgVec
, pred
);
1458 LLVMContextImpl
*pImpl
= LHS
->getType()->getContext().pImpl
;
1460 // Implicitly locked.
1461 return pImpl
->ExprConstants
.getOrCreate(Type::Int1Ty
, Key
);
1465 ConstantExpr::getFCmp(unsigned short pred
, Constant
* LHS
, Constant
* RHS
) {
1466 assert(LHS
->getType() == RHS
->getType());
1467 assert(pred
<= FCmpInst::LAST_FCMP_PREDICATE
&& "Invalid FCmp Predicate");
1469 if (Constant
*FC
= ConstantFoldCompareInstruction(
1470 LHS
->getContext(), pred
, LHS
, RHS
))
1471 return FC
; // Fold a few common cases...
1473 // Look up the constant in the table first to ensure uniqueness
1474 std::vector
<Constant
*> ArgVec
;
1475 ArgVec
.push_back(LHS
);
1476 ArgVec
.push_back(RHS
);
1477 // Get the key type with both the opcode and predicate
1478 const ExprMapKeyType
Key(Instruction::FCmp
, ArgVec
, pred
);
1480 LLVMContextImpl
*pImpl
= LHS
->getType()->getContext().pImpl
;
1482 // Implicitly locked.
1483 return pImpl
->ExprConstants
.getOrCreate(Type::Int1Ty
, Key
);
1486 Constant
*ConstantExpr::getExtractElementTy(const Type
*ReqTy
, Constant
*Val
,
1488 if (Constant
*FC
= ConstantFoldExtractElementInstruction(
1489 ReqTy
->getContext(), Val
, Idx
))
1490 return FC
; // Fold a few common cases...
1491 // Look up the constant in the table first to ensure uniqueness
1492 std::vector
<Constant
*> ArgVec(1, Val
);
1493 ArgVec
.push_back(Idx
);
1494 const ExprMapKeyType
Key(Instruction::ExtractElement
,ArgVec
);
1496 LLVMContextImpl
*pImpl
= ReqTy
->getContext().pImpl
;
1498 // Implicitly locked.
1499 return pImpl
->ExprConstants
.getOrCreate(ReqTy
, Key
);
1502 Constant
*ConstantExpr::getExtractElement(Constant
*Val
, Constant
*Idx
) {
1503 assert(isa
<VectorType
>(Val
->getType()) &&
1504 "Tried to create extractelement operation on non-vector type!");
1505 assert(Idx
->getType() == Type::Int32Ty
&&
1506 "Extractelement index must be i32 type!");
1507 return getExtractElementTy(cast
<VectorType
>(Val
->getType())->getElementType(),
1511 Constant
*ConstantExpr::getInsertElementTy(const Type
*ReqTy
, Constant
*Val
,
1512 Constant
*Elt
, Constant
*Idx
) {
1513 if (Constant
*FC
= ConstantFoldInsertElementInstruction(
1514 ReqTy
->getContext(), Val
, Elt
, Idx
))
1515 return FC
; // Fold a few common cases...
1516 // Look up the constant in the table first to ensure uniqueness
1517 std::vector
<Constant
*> ArgVec(1, Val
);
1518 ArgVec
.push_back(Elt
);
1519 ArgVec
.push_back(Idx
);
1520 const ExprMapKeyType
Key(Instruction::InsertElement
,ArgVec
);
1522 LLVMContextImpl
*pImpl
= ReqTy
->getContext().pImpl
;
1524 // Implicitly locked.
1525 return pImpl
->ExprConstants
.getOrCreate(ReqTy
, Key
);
1528 Constant
*ConstantExpr::getInsertElement(Constant
*Val
, Constant
*Elt
,
1530 assert(isa
<VectorType
>(Val
->getType()) &&
1531 "Tried to create insertelement operation on non-vector type!");
1532 assert(Elt
->getType() == cast
<VectorType
>(Val
->getType())->getElementType()
1533 && "Insertelement types must match!");
1534 assert(Idx
->getType() == Type::Int32Ty
&&
1535 "Insertelement index must be i32 type!");
1536 return getInsertElementTy(Val
->getType(), Val
, Elt
, Idx
);
1539 Constant
*ConstantExpr::getShuffleVectorTy(const Type
*ReqTy
, Constant
*V1
,
1540 Constant
*V2
, Constant
*Mask
) {
1541 if (Constant
*FC
= ConstantFoldShuffleVectorInstruction(
1542 ReqTy
->getContext(), V1
, V2
, Mask
))
1543 return FC
; // Fold a few common cases...
1544 // Look up the constant in the table first to ensure uniqueness
1545 std::vector
<Constant
*> ArgVec(1, V1
);
1546 ArgVec
.push_back(V2
);
1547 ArgVec
.push_back(Mask
);
1548 const ExprMapKeyType
Key(Instruction::ShuffleVector
,ArgVec
);
1550 LLVMContextImpl
*pImpl
= ReqTy
->getContext().pImpl
;
1552 // Implicitly locked.
1553 return pImpl
->ExprConstants
.getOrCreate(ReqTy
, Key
);
1556 Constant
*ConstantExpr::getShuffleVector(Constant
*V1
, Constant
*V2
,
1558 assert(ShuffleVectorInst::isValidOperands(V1
, V2
, Mask
) &&
1559 "Invalid shuffle vector constant expr operands!");
1561 unsigned NElts
= cast
<VectorType
>(Mask
->getType())->getNumElements();
1562 const Type
*EltTy
= cast
<VectorType
>(V1
->getType())->getElementType();
1563 const Type
*ShufTy
= VectorType::get(EltTy
, NElts
);
1564 return getShuffleVectorTy(ShufTy
, V1
, V2
, Mask
);
1567 Constant
*ConstantExpr::getInsertValueTy(const Type
*ReqTy
, Constant
*Agg
,
1569 const unsigned *Idxs
, unsigned NumIdx
) {
1570 assert(ExtractValueInst::getIndexedType(Agg
->getType(), Idxs
,
1571 Idxs
+NumIdx
) == Val
->getType() &&
1572 "insertvalue indices invalid!");
1573 assert(Agg
->getType() == ReqTy
&&
1574 "insertvalue type invalid!");
1575 assert(Agg
->getType()->isFirstClassType() &&
1576 "Non-first-class type for constant InsertValue expression");
1577 Constant
*FC
= ConstantFoldInsertValueInstruction(
1578 ReqTy
->getContext(), Agg
, Val
, Idxs
, NumIdx
);
1579 assert(FC
&& "InsertValue constant expr couldn't be folded!");
1583 Constant
*ConstantExpr::getInsertValue(Constant
*Agg
, Constant
*Val
,
1584 const unsigned *IdxList
, unsigned NumIdx
) {
1585 assert(Agg
->getType()->isFirstClassType() &&
1586 "Tried to create insertelement operation on non-first-class type!");
1588 const Type
*ReqTy
= Agg
->getType();
1591 ExtractValueInst::getIndexedType(Agg
->getType(), IdxList
, IdxList
+NumIdx
);
1593 assert(ValTy
== Val
->getType() && "insertvalue indices invalid!");
1594 return getInsertValueTy(ReqTy
, Agg
, Val
, IdxList
, NumIdx
);
1597 Constant
*ConstantExpr::getExtractValueTy(const Type
*ReqTy
, Constant
*Agg
,
1598 const unsigned *Idxs
, unsigned NumIdx
) {
1599 assert(ExtractValueInst::getIndexedType(Agg
->getType(), Idxs
,
1600 Idxs
+NumIdx
) == ReqTy
&&
1601 "extractvalue indices invalid!");
1602 assert(Agg
->getType()->isFirstClassType() &&
1603 "Non-first-class type for constant extractvalue expression");
1604 Constant
*FC
= ConstantFoldExtractValueInstruction(
1605 ReqTy
->getContext(), Agg
, Idxs
, NumIdx
);
1606 assert(FC
&& "ExtractValue constant expr couldn't be folded!");
1610 Constant
*ConstantExpr::getExtractValue(Constant
*Agg
,
1611 const unsigned *IdxList
, unsigned NumIdx
) {
1612 assert(Agg
->getType()->isFirstClassType() &&
1613 "Tried to create extractelement operation on non-first-class type!");
1616 ExtractValueInst::getIndexedType(Agg
->getType(), IdxList
, IdxList
+NumIdx
);
1617 assert(ReqTy
&& "extractvalue indices invalid!");
1618 return getExtractValueTy(ReqTy
, Agg
, IdxList
, NumIdx
);
1621 Constant
* ConstantExpr::getNeg(Constant
* C
) {
1622 // API compatibility: Adjust integer opcodes to floating-point opcodes.
1623 if (C
->getType()->isFPOrFPVector())
1625 assert(C
->getType()->isIntOrIntVector() &&
1626 "Cannot NEG a nonintegral value!");
1627 return get(Instruction::Sub
,
1628 ConstantFP::getZeroValueForNegation(C
->getType()),
1632 Constant
* ConstantExpr::getFNeg(Constant
* C
) {
1633 assert(C
->getType()->isFPOrFPVector() &&
1634 "Cannot FNEG a non-floating-point value!");
1635 return get(Instruction::FSub
,
1636 ConstantFP::getZeroValueForNegation(C
->getType()),
1640 Constant
* ConstantExpr::getNot(Constant
* C
) {
1641 assert(C
->getType()->isIntOrIntVector() &&
1642 "Cannot NOT a nonintegral value!");
1643 return get(Instruction::Xor
, C
, Constant::getAllOnesValue(C
->getType()));
1646 Constant
* ConstantExpr::getAdd(Constant
* C1
, Constant
* C2
) {
1647 return get(Instruction::Add
, C1
, C2
);
1650 Constant
* ConstantExpr::getFAdd(Constant
* C1
, Constant
* C2
) {
1651 return get(Instruction::FAdd
, C1
, C2
);
1654 Constant
* ConstantExpr::getSub(Constant
* C1
, Constant
* C2
) {
1655 return get(Instruction::Sub
, C1
, C2
);
1658 Constant
* ConstantExpr::getFSub(Constant
* C1
, Constant
* C2
) {
1659 return get(Instruction::FSub
, C1
, C2
);
1662 Constant
* ConstantExpr::getMul(Constant
* C1
, Constant
* C2
) {
1663 return get(Instruction::Mul
, C1
, C2
);
1666 Constant
* ConstantExpr::getFMul(Constant
* C1
, Constant
* C2
) {
1667 return get(Instruction::FMul
, C1
, C2
);
1670 Constant
* ConstantExpr::getUDiv(Constant
* C1
, Constant
* C2
) {
1671 return get(Instruction::UDiv
, C1
, C2
);
1674 Constant
* ConstantExpr::getSDiv(Constant
* C1
, Constant
* C2
) {
1675 return get(Instruction::SDiv
, C1
, C2
);
1678 Constant
* ConstantExpr::getFDiv(Constant
* C1
, Constant
* C2
) {
1679 return get(Instruction::FDiv
, C1
, C2
);
1682 Constant
* ConstantExpr::getURem(Constant
* C1
, Constant
* C2
) {
1683 return get(Instruction::URem
, C1
, C2
);
1686 Constant
* ConstantExpr::getSRem(Constant
* C1
, Constant
* C2
) {
1687 return get(Instruction::SRem
, C1
, C2
);
1690 Constant
* ConstantExpr::getFRem(Constant
* C1
, Constant
* C2
) {
1691 return get(Instruction::FRem
, C1
, C2
);
1694 Constant
* ConstantExpr::getAnd(Constant
* C1
, Constant
* C2
) {
1695 return get(Instruction::And
, C1
, C2
);
1698 Constant
* ConstantExpr::getOr(Constant
* C1
, Constant
* C2
) {
1699 return get(Instruction::Or
, C1
, C2
);
1702 Constant
* ConstantExpr::getXor(Constant
* C1
, Constant
* C2
) {
1703 return get(Instruction::Xor
, C1
, C2
);
1706 Constant
* ConstantExpr::getShl(Constant
* C1
, Constant
* C2
) {
1707 return get(Instruction::Shl
, C1
, C2
);
1710 Constant
* ConstantExpr::getLShr(Constant
* C1
, Constant
* C2
) {
1711 return get(Instruction::LShr
, C1
, C2
);
1714 Constant
* ConstantExpr::getAShr(Constant
* C1
, Constant
* C2
) {
1715 return get(Instruction::AShr
, C1
, C2
);
1718 // destroyConstant - Remove the constant from the constant table...
1720 void ConstantExpr::destroyConstant() {
1721 // Implicitly locked.
1722 LLVMContextImpl
*pImpl
= getType()->getContext().pImpl
;
1723 pImpl
->ExprConstants
.remove(this);
1724 destroyConstantImpl();
1727 const char *ConstantExpr::getOpcodeName() const {
1728 return Instruction::getOpcodeName(getOpcode());
1731 //===----------------------------------------------------------------------===//
1732 // replaceUsesOfWithOnConstant implementations
1734 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
1735 /// 'From' to be uses of 'To'. This must update the uniquing data structures
1738 /// Note that we intentionally replace all uses of From with To here. Consider
1739 /// a large array that uses 'From' 1000 times. By handling this case all here,
1740 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
1741 /// single invocation handles all 1000 uses. Handling them one at a time would
1742 /// work, but would be really slow because it would have to unique each updated
1745 static std::vector
<Constant
*> getValType(ConstantArray
*CA
) {
1746 std::vector
<Constant
*> Elements
;
1747 Elements
.reserve(CA
->getNumOperands());
1748 for (unsigned i
= 0, e
= CA
->getNumOperands(); i
!= e
; ++i
)
1749 Elements
.push_back(cast
<Constant
>(CA
->getOperand(i
)));
1754 void ConstantArray::replaceUsesOfWithOnConstant(Value
*From
, Value
*To
,
1756 assert(isa
<Constant
>(To
) && "Cannot make Constant refer to non-constant!");
1757 Constant
*ToC
= cast
<Constant
>(To
);
1759 LLVMContext
&Context
= getType()->getContext();
1760 LLVMContextImpl
*pImpl
= Context
.pImpl
;
1762 std::pair
<LLVMContextImpl::ArrayConstantsTy::MapKey
, Constant
*> Lookup
;
1763 Lookup
.first
.first
= getType();
1764 Lookup
.second
= this;
1766 std::vector
<Constant
*> &Values
= Lookup
.first
.second
;
1767 Values
.reserve(getNumOperands()); // Build replacement array.
1769 // Fill values with the modified operands of the constant array. Also,
1770 // compute whether this turns into an all-zeros array.
1771 bool isAllZeros
= false;
1772 unsigned NumUpdated
= 0;
1773 if (!ToC
->isNullValue()) {
1774 for (Use
*O
= OperandList
, *E
= OperandList
+getNumOperands(); O
!= E
; ++O
) {
1775 Constant
*Val
= cast
<Constant
>(O
->get());
1780 Values
.push_back(Val
);
1784 for (Use
*O
= OperandList
, *E
= OperandList
+getNumOperands();O
!= E
; ++O
) {
1785 Constant
*Val
= cast
<Constant
>(O
->get());
1790 Values
.push_back(Val
);
1791 if (isAllZeros
) isAllZeros
= Val
->isNullValue();
1795 Constant
*Replacement
= 0;
1797 Replacement
= ConstantAggregateZero::get(getType());
1799 // Check to see if we have this array type already.
1800 sys::SmartScopedWriter
<true> Writer(pImpl
->ConstantsLock
);
1802 LLVMContextImpl::ArrayConstantsTy::MapTy::iterator I
=
1803 pImpl
->ArrayConstants
.InsertOrGetItem(Lookup
, Exists
);
1806 Replacement
= I
->second
;
1808 // Okay, the new shape doesn't exist in the system yet. Instead of
1809 // creating a new constant array, inserting it, replaceallusesof'ing the
1810 // old with the new, then deleting the old... just update the current one
1812 pImpl
->ArrayConstants
.MoveConstantToNewSlot(this, I
);
1814 // Update to the new value. Optimize for the case when we have a single
1815 // operand that we're changing, but handle bulk updates efficiently.
1816 if (NumUpdated
== 1) {
1817 unsigned OperandToUpdate
= U
- OperandList
;
1818 assert(getOperand(OperandToUpdate
) == From
&&
1819 "ReplaceAllUsesWith broken!");
1820 setOperand(OperandToUpdate
, ToC
);
1822 for (unsigned i
= 0, e
= getNumOperands(); i
!= e
; ++i
)
1823 if (getOperand(i
) == From
)
1830 // Otherwise, I do need to replace this with an existing value.
1831 assert(Replacement
!= this && "I didn't contain From!");
1833 // Everyone using this now uses the replacement.
1834 uncheckedReplaceAllUsesWith(Replacement
);
1836 // Delete the old constant!
1840 static std::vector
<Constant
*> getValType(ConstantStruct
*CS
) {
1841 std::vector
<Constant
*> Elements
;
1842 Elements
.reserve(CS
->getNumOperands());
1843 for (unsigned i
= 0, e
= CS
->getNumOperands(); i
!= e
; ++i
)
1844 Elements
.push_back(cast
<Constant
>(CS
->getOperand(i
)));
1848 void ConstantStruct::replaceUsesOfWithOnConstant(Value
*From
, Value
*To
,
1850 assert(isa
<Constant
>(To
) && "Cannot make Constant refer to non-constant!");
1851 Constant
*ToC
= cast
<Constant
>(To
);
1853 unsigned OperandToUpdate
= U
-OperandList
;
1854 assert(getOperand(OperandToUpdate
) == From
&& "ReplaceAllUsesWith broken!");
1856 std::pair
<LLVMContextImpl::StructConstantsTy::MapKey
, Constant
*> Lookup
;
1857 Lookup
.first
.first
= getType();
1858 Lookup
.second
= this;
1859 std::vector
<Constant
*> &Values
= Lookup
.first
.second
;
1860 Values
.reserve(getNumOperands()); // Build replacement struct.
1863 // Fill values with the modified operands of the constant struct. Also,
1864 // compute whether this turns into an all-zeros struct.
1865 bool isAllZeros
= false;
1866 if (!ToC
->isNullValue()) {
1867 for (Use
*O
= OperandList
, *E
= OperandList
+ getNumOperands(); O
!= E
; ++O
)
1868 Values
.push_back(cast
<Constant
>(O
->get()));
1871 for (Use
*O
= OperandList
, *E
= OperandList
+getNumOperands(); O
!= E
; ++O
) {
1872 Constant
*Val
= cast
<Constant
>(O
->get());
1873 Values
.push_back(Val
);
1874 if (isAllZeros
) isAllZeros
= Val
->isNullValue();
1877 Values
[OperandToUpdate
] = ToC
;
1879 LLVMContext
&Context
= getType()->getContext();
1880 LLVMContextImpl
*pImpl
= Context
.pImpl
;
1882 Constant
*Replacement
= 0;
1884 Replacement
= ConstantAggregateZero::get(getType());
1886 // Check to see if we have this array type already.
1887 sys::SmartScopedWriter
<true> Writer(pImpl
->ConstantsLock
);
1889 LLVMContextImpl::StructConstantsTy::MapTy::iterator I
=
1890 pImpl
->StructConstants
.InsertOrGetItem(Lookup
, Exists
);
1893 Replacement
= I
->second
;
1895 // Okay, the new shape doesn't exist in the system yet. Instead of
1896 // creating a new constant struct, inserting it, replaceallusesof'ing the
1897 // old with the new, then deleting the old... just update the current one
1899 pImpl
->StructConstants
.MoveConstantToNewSlot(this, I
);
1901 // Update to the new value.
1902 setOperand(OperandToUpdate
, ToC
);
1907 assert(Replacement
!= this && "I didn't contain From!");
1909 // Everyone using this now uses the replacement.
1910 uncheckedReplaceAllUsesWith(Replacement
);
1912 // Delete the old constant!
1916 static std::vector
<Constant
*> getValType(ConstantVector
*CP
) {
1917 std::vector
<Constant
*> Elements
;
1918 Elements
.reserve(CP
->getNumOperands());
1919 for (unsigned i
= 0, e
= CP
->getNumOperands(); i
!= e
; ++i
)
1920 Elements
.push_back(CP
->getOperand(i
));
1924 void ConstantVector::replaceUsesOfWithOnConstant(Value
*From
, Value
*To
,
1926 assert(isa
<Constant
>(To
) && "Cannot make Constant refer to non-constant!");
1928 std::vector
<Constant
*> Values
;
1929 Values
.reserve(getNumOperands()); // Build replacement array...
1930 for (unsigned i
= 0, e
= getNumOperands(); i
!= e
; ++i
) {
1931 Constant
*Val
= getOperand(i
);
1932 if (Val
== From
) Val
= cast
<Constant
>(To
);
1933 Values
.push_back(Val
);
1936 Constant
*Replacement
= get(getType(), Values
);
1937 assert(Replacement
!= this && "I didn't contain From!");
1939 // Everyone using this now uses the replacement.
1940 uncheckedReplaceAllUsesWith(Replacement
);
1942 // Delete the old constant!
1946 void ConstantExpr::replaceUsesOfWithOnConstant(Value
*From
, Value
*ToV
,
1948 assert(isa
<Constant
>(ToV
) && "Cannot make Constant refer to non-constant!");
1949 Constant
*To
= cast
<Constant
>(ToV
);
1951 Constant
*Replacement
= 0;
1952 if (getOpcode() == Instruction::GetElementPtr
) {
1953 SmallVector
<Constant
*, 8> Indices
;
1954 Constant
*Pointer
= getOperand(0);
1955 Indices
.reserve(getNumOperands()-1);
1956 if (Pointer
== From
) Pointer
= To
;
1958 for (unsigned i
= 1, e
= getNumOperands(); i
!= e
; ++i
) {
1959 Constant
*Val
= getOperand(i
);
1960 if (Val
== From
) Val
= To
;
1961 Indices
.push_back(Val
);
1963 Replacement
= ConstantExpr::getGetElementPtr(Pointer
,
1964 &Indices
[0], Indices
.size());
1965 } else if (getOpcode() == Instruction::ExtractValue
) {
1966 Constant
*Agg
= getOperand(0);
1967 if (Agg
== From
) Agg
= To
;
1969 const SmallVector
<unsigned, 4> &Indices
= getIndices();
1970 Replacement
= ConstantExpr::getExtractValue(Agg
,
1971 &Indices
[0], Indices
.size());
1972 } else if (getOpcode() == Instruction::InsertValue
) {
1973 Constant
*Agg
= getOperand(0);
1974 Constant
*Val
= getOperand(1);
1975 if (Agg
== From
) Agg
= To
;
1976 if (Val
== From
) Val
= To
;
1978 const SmallVector
<unsigned, 4> &Indices
= getIndices();
1979 Replacement
= ConstantExpr::getInsertValue(Agg
, Val
,
1980 &Indices
[0], Indices
.size());
1981 } else if (isCast()) {
1982 assert(getOperand(0) == From
&& "Cast only has one use!");
1983 Replacement
= ConstantExpr::getCast(getOpcode(), To
, getType());
1984 } else if (getOpcode() == Instruction::Select
) {
1985 Constant
*C1
= getOperand(0);
1986 Constant
*C2
= getOperand(1);
1987 Constant
*C3
= getOperand(2);
1988 if (C1
== From
) C1
= To
;
1989 if (C2
== From
) C2
= To
;
1990 if (C3
== From
) C3
= To
;
1991 Replacement
= ConstantExpr::getSelect(C1
, C2
, C3
);
1992 } else if (getOpcode() == Instruction::ExtractElement
) {
1993 Constant
*C1
= getOperand(0);
1994 Constant
*C2
= getOperand(1);
1995 if (C1
== From
) C1
= To
;
1996 if (C2
== From
) C2
= To
;
1997 Replacement
= ConstantExpr::getExtractElement(C1
, C2
);
1998 } else if (getOpcode() == Instruction::InsertElement
) {
1999 Constant
*C1
= getOperand(0);
2000 Constant
*C2
= getOperand(1);
2001 Constant
*C3
= getOperand(1);
2002 if (C1
== From
) C1
= To
;
2003 if (C2
== From
) C2
= To
;
2004 if (C3
== From
) C3
= To
;
2005 Replacement
= ConstantExpr::getInsertElement(C1
, C2
, C3
);
2006 } else if (getOpcode() == Instruction::ShuffleVector
) {
2007 Constant
*C1
= getOperand(0);
2008 Constant
*C2
= getOperand(1);
2009 Constant
*C3
= getOperand(2);
2010 if (C1
== From
) C1
= To
;
2011 if (C2
== From
) C2
= To
;
2012 if (C3
== From
) C3
= To
;
2013 Replacement
= ConstantExpr::getShuffleVector(C1
, C2
, C3
);
2014 } else if (isCompare()) {
2015 Constant
*C1
= getOperand(0);
2016 Constant
*C2
= getOperand(1);
2017 if (C1
== From
) C1
= To
;
2018 if (C2
== From
) C2
= To
;
2019 if (getOpcode() == Instruction::ICmp
)
2020 Replacement
= ConstantExpr::getICmp(getPredicate(), C1
, C2
);
2022 assert(getOpcode() == Instruction::FCmp
);
2023 Replacement
= ConstantExpr::getFCmp(getPredicate(), C1
, C2
);
2025 } else if (getNumOperands() == 2) {
2026 Constant
*C1
= getOperand(0);
2027 Constant
*C2
= getOperand(1);
2028 if (C1
== From
) C1
= To
;
2029 if (C2
== From
) C2
= To
;
2030 Replacement
= ConstantExpr::get(getOpcode(), C1
, C2
);
2032 llvm_unreachable("Unknown ConstantExpr type!");
2036 assert(Replacement
!= this && "I didn't contain From!");
2038 // Everyone using this now uses the replacement.
2039 uncheckedReplaceAllUsesWith(Replacement
);
2041 // Delete the old constant!