[LLVM][Alignment] Introduce Alignment In Attributes
[llvm-core.git] / lib / IR / Constants.cpp
blobcc1eaed1c4bb4138621c4e9ff2c8a0fb55c2661d
1 //===-- Constants.cpp - Implement Constant nodes --------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the Constant* classes.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/IR/Constants.h"
14 #include "ConstantFold.h"
15 #include "LLVMContextImpl.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/StringMap.h"
19 #include "llvm/IR/DerivedTypes.h"
20 #include "llvm/IR/GetElementPtrTypeIterator.h"
21 #include "llvm/IR/GlobalValue.h"
22 #include "llvm/IR/Instructions.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/IR/Operator.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/ManagedStatic.h"
28 #include "llvm/Support/MathExtras.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include <algorithm>
32 using namespace llvm;
34 //===----------------------------------------------------------------------===//
35 // Constant Class
36 //===----------------------------------------------------------------------===//
38 bool Constant::isNegativeZeroValue() const {
39 // Floating point values have an explicit -0.0 value.
40 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
41 return CFP->isZero() && CFP->isNegative();
43 // Equivalent for a vector of -0.0's.
44 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
45 if (CV->getElementType()->isFloatingPointTy() && CV->isSplat())
46 if (CV->getElementAsAPFloat(0).isNegZero())
47 return true;
49 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
50 if (ConstantFP *SplatCFP = dyn_cast_or_null<ConstantFP>(CV->getSplatValue()))
51 if (SplatCFP && SplatCFP->isZero() && SplatCFP->isNegative())
52 return true;
54 // We've already handled true FP case; any other FP vectors can't represent -0.0.
55 if (getType()->isFPOrFPVectorTy())
56 return false;
58 // Otherwise, just use +0.0.
59 return isNullValue();
62 // Return true iff this constant is positive zero (floating point), negative
63 // zero (floating point), or a null value.
64 bool Constant::isZeroValue() const {
65 // Floating point values have an explicit -0.0 value.
66 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
67 return CFP->isZero();
69 // Equivalent for a vector of -0.0's.
70 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
71 if (CV->getElementType()->isFloatingPointTy() && CV->isSplat())
72 if (CV->getElementAsAPFloat(0).isZero())
73 return true;
75 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
76 if (ConstantFP *SplatCFP = dyn_cast_or_null<ConstantFP>(CV->getSplatValue()))
77 if (SplatCFP && SplatCFP->isZero())
78 return true;
80 // Otherwise, just use +0.0.
81 return isNullValue();
84 bool Constant::isNullValue() const {
85 // 0 is null.
86 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
87 return CI->isZero();
89 // +0.0 is null.
90 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
91 return CFP->isZero() && !CFP->isNegative();
93 // constant zero is zero for aggregates, cpnull is null for pointers, none for
94 // tokens.
95 return isa<ConstantAggregateZero>(this) || isa<ConstantPointerNull>(this) ||
96 isa<ConstantTokenNone>(this);
99 bool Constant::isAllOnesValue() const {
100 // Check for -1 integers
101 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
102 return CI->isMinusOne();
104 // Check for FP which are bitcasted from -1 integers
105 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
106 return CFP->getValueAPF().bitcastToAPInt().isAllOnesValue();
108 // Check for constant vectors which are splats of -1 values.
109 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
110 if (Constant *Splat = CV->getSplatValue())
111 return Splat->isAllOnesValue();
113 // Check for constant vectors which are splats of -1 values.
114 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this)) {
115 if (CV->isSplat()) {
116 if (CV->getElementType()->isFloatingPointTy())
117 return CV->getElementAsAPFloat(0).bitcastToAPInt().isAllOnesValue();
118 return CV->getElementAsAPInt(0).isAllOnesValue();
122 return false;
125 bool Constant::isOneValue() const {
126 // Check for 1 integers
127 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
128 return CI->isOne();
130 // Check for FP which are bitcasted from 1 integers
131 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
132 return CFP->getValueAPF().bitcastToAPInt().isOneValue();
134 // Check for constant vectors which are splats of 1 values.
135 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
136 if (Constant *Splat = CV->getSplatValue())
137 return Splat->isOneValue();
139 // Check for constant vectors which are splats of 1 values.
140 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this)) {
141 if (CV->isSplat()) {
142 if (CV->getElementType()->isFloatingPointTy())
143 return CV->getElementAsAPFloat(0).bitcastToAPInt().isOneValue();
144 return CV->getElementAsAPInt(0).isOneValue();
148 return false;
151 bool Constant::isMinSignedValue() const {
152 // Check for INT_MIN integers
153 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
154 return CI->isMinValue(/*isSigned=*/true);
156 // Check for FP which are bitcasted from INT_MIN integers
157 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
158 return CFP->getValueAPF().bitcastToAPInt().isMinSignedValue();
160 // Check for constant vectors which are splats of INT_MIN values.
161 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
162 if (Constant *Splat = CV->getSplatValue())
163 return Splat->isMinSignedValue();
165 // Check for constant vectors which are splats of INT_MIN values.
166 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this)) {
167 if (CV->isSplat()) {
168 if (CV->getElementType()->isFloatingPointTy())
169 return CV->getElementAsAPFloat(0).bitcastToAPInt().isMinSignedValue();
170 return CV->getElementAsAPInt(0).isMinSignedValue();
174 return false;
177 bool Constant::isNotMinSignedValue() const {
178 // Check for INT_MIN integers
179 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
180 return !CI->isMinValue(/*isSigned=*/true);
182 // Check for FP which are bitcasted from INT_MIN integers
183 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
184 return !CFP->getValueAPF().bitcastToAPInt().isMinSignedValue();
186 // Check that vectors don't contain INT_MIN
187 if (this->getType()->isVectorTy()) {
188 unsigned NumElts = this->getType()->getVectorNumElements();
189 for (unsigned i = 0; i != NumElts; ++i) {
190 Constant *Elt = this->getAggregateElement(i);
191 if (!Elt || !Elt->isNotMinSignedValue())
192 return false;
194 return true;
197 // It *may* contain INT_MIN, we can't tell.
198 return false;
201 bool Constant::isFiniteNonZeroFP() const {
202 if (auto *CFP = dyn_cast<ConstantFP>(this))
203 return CFP->getValueAPF().isFiniteNonZero();
204 if (!getType()->isVectorTy())
205 return false;
206 for (unsigned i = 0, e = getType()->getVectorNumElements(); i != e; ++i) {
207 auto *CFP = dyn_cast_or_null<ConstantFP>(this->getAggregateElement(i));
208 if (!CFP || !CFP->getValueAPF().isFiniteNonZero())
209 return false;
211 return true;
214 bool Constant::isNormalFP() const {
215 if (auto *CFP = dyn_cast<ConstantFP>(this))
216 return CFP->getValueAPF().isNormal();
217 if (!getType()->isVectorTy())
218 return false;
219 for (unsigned i = 0, e = getType()->getVectorNumElements(); i != e; ++i) {
220 auto *CFP = dyn_cast_or_null<ConstantFP>(this->getAggregateElement(i));
221 if (!CFP || !CFP->getValueAPF().isNormal())
222 return false;
224 return true;
227 bool Constant::hasExactInverseFP() const {
228 if (auto *CFP = dyn_cast<ConstantFP>(this))
229 return CFP->getValueAPF().getExactInverse(nullptr);
230 if (!getType()->isVectorTy())
231 return false;
232 for (unsigned i = 0, e = getType()->getVectorNumElements(); i != e; ++i) {
233 auto *CFP = dyn_cast_or_null<ConstantFP>(this->getAggregateElement(i));
234 if (!CFP || !CFP->getValueAPF().getExactInverse(nullptr))
235 return false;
237 return true;
240 bool Constant::isNaN() const {
241 if (auto *CFP = dyn_cast<ConstantFP>(this))
242 return CFP->isNaN();
243 if (!getType()->isVectorTy())
244 return false;
245 for (unsigned i = 0, e = getType()->getVectorNumElements(); i != e; ++i) {
246 auto *CFP = dyn_cast_or_null<ConstantFP>(this->getAggregateElement(i));
247 if (!CFP || !CFP->isNaN())
248 return false;
250 return true;
253 bool Constant::containsUndefElement() const {
254 if (!getType()->isVectorTy())
255 return false;
256 for (unsigned i = 0, e = getType()->getVectorNumElements(); i != e; ++i)
257 if (isa<UndefValue>(getAggregateElement(i)))
258 return true;
260 return false;
263 bool Constant::containsConstantExpression() const {
264 if (!getType()->isVectorTy())
265 return false;
266 for (unsigned i = 0, e = getType()->getVectorNumElements(); i != e; ++i)
267 if (isa<ConstantExpr>(getAggregateElement(i)))
268 return true;
270 return false;
273 /// Constructor to create a '0' constant of arbitrary type.
274 Constant *Constant::getNullValue(Type *Ty) {
275 switch (Ty->getTypeID()) {
276 case Type::IntegerTyID:
277 return ConstantInt::get(Ty, 0);
278 case Type::HalfTyID:
279 return ConstantFP::get(Ty->getContext(),
280 APFloat::getZero(APFloat::IEEEhalf()));
281 case Type::FloatTyID:
282 return ConstantFP::get(Ty->getContext(),
283 APFloat::getZero(APFloat::IEEEsingle()));
284 case Type::DoubleTyID:
285 return ConstantFP::get(Ty->getContext(),
286 APFloat::getZero(APFloat::IEEEdouble()));
287 case Type::X86_FP80TyID:
288 return ConstantFP::get(Ty->getContext(),
289 APFloat::getZero(APFloat::x87DoubleExtended()));
290 case Type::FP128TyID:
291 return ConstantFP::get(Ty->getContext(),
292 APFloat::getZero(APFloat::IEEEquad()));
293 case Type::PPC_FP128TyID:
294 return ConstantFP::get(Ty->getContext(),
295 APFloat(APFloat::PPCDoubleDouble(),
296 APInt::getNullValue(128)));
297 case Type::PointerTyID:
298 return ConstantPointerNull::get(cast<PointerType>(Ty));
299 case Type::StructTyID:
300 case Type::ArrayTyID:
301 case Type::VectorTyID:
302 return ConstantAggregateZero::get(Ty);
303 case Type::TokenTyID:
304 return ConstantTokenNone::get(Ty->getContext());
305 default:
306 // Function, Label, or Opaque type?
307 llvm_unreachable("Cannot create a null constant of that type!");
311 Constant *Constant::getIntegerValue(Type *Ty, const APInt &V) {
312 Type *ScalarTy = Ty->getScalarType();
314 // Create the base integer constant.
315 Constant *C = ConstantInt::get(Ty->getContext(), V);
317 // Convert an integer to a pointer, if necessary.
318 if (PointerType *PTy = dyn_cast<PointerType>(ScalarTy))
319 C = ConstantExpr::getIntToPtr(C, PTy);
321 // Broadcast a scalar to a vector, if necessary.
322 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
323 C = ConstantVector::getSplat(VTy->getNumElements(), C);
325 return C;
328 Constant *Constant::getAllOnesValue(Type *Ty) {
329 if (IntegerType *ITy = dyn_cast<IntegerType>(Ty))
330 return ConstantInt::get(Ty->getContext(),
331 APInt::getAllOnesValue(ITy->getBitWidth()));
333 if (Ty->isFloatingPointTy()) {
334 APFloat FL = APFloat::getAllOnesValue(Ty->getPrimitiveSizeInBits(),
335 !Ty->isPPC_FP128Ty());
336 return ConstantFP::get(Ty->getContext(), FL);
339 VectorType *VTy = cast<VectorType>(Ty);
340 return ConstantVector::getSplat(VTy->getNumElements(),
341 getAllOnesValue(VTy->getElementType()));
344 Constant *Constant::getAggregateElement(unsigned Elt) const {
345 if (const ConstantAggregate *CC = dyn_cast<ConstantAggregate>(this))
346 return Elt < CC->getNumOperands() ? CC->getOperand(Elt) : nullptr;
348 if (const ConstantAggregateZero *CAZ = dyn_cast<ConstantAggregateZero>(this))
349 return Elt < CAZ->getNumElements() ? CAZ->getElementValue(Elt) : nullptr;
351 if (const UndefValue *UV = dyn_cast<UndefValue>(this))
352 return Elt < UV->getNumElements() ? UV->getElementValue(Elt) : nullptr;
354 if (const ConstantDataSequential *CDS =dyn_cast<ConstantDataSequential>(this))
355 return Elt < CDS->getNumElements() ? CDS->getElementAsConstant(Elt)
356 : nullptr;
357 return nullptr;
360 Constant *Constant::getAggregateElement(Constant *Elt) const {
361 assert(isa<IntegerType>(Elt->getType()) && "Index must be an integer");
362 if (ConstantInt *CI = dyn_cast<ConstantInt>(Elt)) {
363 // Check if the constant fits into an uint64_t.
364 if (CI->getValue().getActiveBits() > 64)
365 return nullptr;
366 return getAggregateElement(CI->getZExtValue());
368 return nullptr;
371 void Constant::destroyConstant() {
372 /// First call destroyConstantImpl on the subclass. This gives the subclass
373 /// a chance to remove the constant from any maps/pools it's contained in.
374 switch (getValueID()) {
375 default:
376 llvm_unreachable("Not a constant!");
377 #define HANDLE_CONSTANT(Name) \
378 case Value::Name##Val: \
379 cast<Name>(this)->destroyConstantImpl(); \
380 break;
381 #include "llvm/IR/Value.def"
384 // When a Constant is destroyed, there may be lingering
385 // references to the constant by other constants in the constant pool. These
386 // constants are implicitly dependent on the module that is being deleted,
387 // but they don't know that. Because we only find out when the CPV is
388 // deleted, we must now notify all of our users (that should only be
389 // Constants) that they are, in fact, invalid now and should be deleted.
391 while (!use_empty()) {
392 Value *V = user_back();
393 #ifndef NDEBUG // Only in -g mode...
394 if (!isa<Constant>(V)) {
395 dbgs() << "While deleting: " << *this
396 << "\n\nUse still stuck around after Def is destroyed: " << *V
397 << "\n\n";
399 #endif
400 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
401 cast<Constant>(V)->destroyConstant();
403 // The constant should remove itself from our use list...
404 assert((use_empty() || user_back() != V) && "Constant not removed!");
407 // Value has no outstanding references it is safe to delete it now...
408 delete this;
411 static bool canTrapImpl(const Constant *C,
412 SmallPtrSetImpl<const ConstantExpr *> &NonTrappingOps) {
413 assert(C->getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
414 // The only thing that could possibly trap are constant exprs.
415 const ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
416 if (!CE)
417 return false;
419 // ConstantExpr traps if any operands can trap.
420 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
421 if (ConstantExpr *Op = dyn_cast<ConstantExpr>(CE->getOperand(i))) {
422 if (NonTrappingOps.insert(Op).second && canTrapImpl(Op, NonTrappingOps))
423 return true;
427 // Otherwise, only specific operations can trap.
428 switch (CE->getOpcode()) {
429 default:
430 return false;
431 case Instruction::UDiv:
432 case Instruction::SDiv:
433 case Instruction::URem:
434 case Instruction::SRem:
435 // Div and rem can trap if the RHS is not known to be non-zero.
436 if (!isa<ConstantInt>(CE->getOperand(1)) ||CE->getOperand(1)->isNullValue())
437 return true;
438 return false;
442 bool Constant::canTrap() const {
443 SmallPtrSet<const ConstantExpr *, 4> NonTrappingOps;
444 return canTrapImpl(this, NonTrappingOps);
447 /// Check if C contains a GlobalValue for which Predicate is true.
448 static bool
449 ConstHasGlobalValuePredicate(const Constant *C,
450 bool (*Predicate)(const GlobalValue *)) {
451 SmallPtrSet<const Constant *, 8> Visited;
452 SmallVector<const Constant *, 8> WorkList;
453 WorkList.push_back(C);
454 Visited.insert(C);
456 while (!WorkList.empty()) {
457 const Constant *WorkItem = WorkList.pop_back_val();
458 if (const auto *GV = dyn_cast<GlobalValue>(WorkItem))
459 if (Predicate(GV))
460 return true;
461 for (const Value *Op : WorkItem->operands()) {
462 const Constant *ConstOp = dyn_cast<Constant>(Op);
463 if (!ConstOp)
464 continue;
465 if (Visited.insert(ConstOp).second)
466 WorkList.push_back(ConstOp);
469 return false;
472 bool Constant::isThreadDependent() const {
473 auto DLLImportPredicate = [](const GlobalValue *GV) {
474 return GV->isThreadLocal();
476 return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
479 bool Constant::isDLLImportDependent() const {
480 auto DLLImportPredicate = [](const GlobalValue *GV) {
481 return GV->hasDLLImportStorageClass();
483 return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
486 bool Constant::isConstantUsed() const {
487 for (const User *U : users()) {
488 const Constant *UC = dyn_cast<Constant>(U);
489 if (!UC || isa<GlobalValue>(UC))
490 return true;
492 if (UC->isConstantUsed())
493 return true;
495 return false;
498 bool Constant::needsRelocation() const {
499 if (isa<GlobalValue>(this))
500 return true; // Global reference.
502 if (const BlockAddress *BA = dyn_cast<BlockAddress>(this))
503 return BA->getFunction()->needsRelocation();
505 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(this)) {
506 if (CE->getOpcode() == Instruction::Sub) {
507 ConstantExpr *LHS = dyn_cast<ConstantExpr>(CE->getOperand(0));
508 ConstantExpr *RHS = dyn_cast<ConstantExpr>(CE->getOperand(1));
509 if (LHS && RHS && LHS->getOpcode() == Instruction::PtrToInt &&
510 RHS->getOpcode() == Instruction::PtrToInt) {
511 Constant *LHSOp0 = LHS->getOperand(0);
512 Constant *RHSOp0 = RHS->getOperand(0);
514 // While raw uses of blockaddress need to be relocated, differences
515 // between two of them don't when they are for labels in the same
516 // function. This is a common idiom when creating a table for the
517 // indirect goto extension, so we handle it efficiently here.
518 if (isa<BlockAddress>(LHSOp0) && isa<BlockAddress>(RHSOp0) &&
519 cast<BlockAddress>(LHSOp0)->getFunction() ==
520 cast<BlockAddress>(RHSOp0)->getFunction())
521 return false;
523 // Relative pointers do not need to be dynamically relocated.
524 if (auto *LHSGV = dyn_cast<GlobalValue>(
525 LHSOp0->stripPointerCastsNoFollowAliases()))
526 if (auto *RHSGV = dyn_cast<GlobalValue>(
527 RHSOp0->stripPointerCastsNoFollowAliases()))
528 if (LHSGV->isDSOLocal() && RHSGV->isDSOLocal())
529 return false;
534 bool Result = false;
535 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
536 Result |= cast<Constant>(getOperand(i))->needsRelocation();
538 return Result;
541 /// If the specified constantexpr is dead, remove it. This involves recursively
542 /// eliminating any dead users of the constantexpr.
543 static bool removeDeadUsersOfConstant(const Constant *C) {
544 if (isa<GlobalValue>(C)) return false; // Cannot remove this
546 while (!C->use_empty()) {
547 const Constant *User = dyn_cast<Constant>(C->user_back());
548 if (!User) return false; // Non-constant usage;
549 if (!removeDeadUsersOfConstant(User))
550 return false; // Constant wasn't dead
553 const_cast<Constant*>(C)->destroyConstant();
554 return true;
558 void Constant::removeDeadConstantUsers() const {
559 Value::const_user_iterator I = user_begin(), E = user_end();
560 Value::const_user_iterator LastNonDeadUser = E;
561 while (I != E) {
562 const Constant *User = dyn_cast<Constant>(*I);
563 if (!User) {
564 LastNonDeadUser = I;
565 ++I;
566 continue;
569 if (!removeDeadUsersOfConstant(User)) {
570 // If the constant wasn't dead, remember that this was the last live use
571 // and move on to the next constant.
572 LastNonDeadUser = I;
573 ++I;
574 continue;
577 // If the constant was dead, then the iterator is invalidated.
578 if (LastNonDeadUser == E) {
579 I = user_begin();
580 if (I == E) break;
581 } else {
582 I = LastNonDeadUser;
583 ++I;
590 //===----------------------------------------------------------------------===//
591 // ConstantInt
592 //===----------------------------------------------------------------------===//
594 ConstantInt::ConstantInt(IntegerType *Ty, const APInt &V)
595 : ConstantData(Ty, ConstantIntVal), Val(V) {
596 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
599 ConstantInt *ConstantInt::getTrue(LLVMContext &Context) {
600 LLVMContextImpl *pImpl = Context.pImpl;
601 if (!pImpl->TheTrueVal)
602 pImpl->TheTrueVal = ConstantInt::get(Type::getInt1Ty(Context), 1);
603 return pImpl->TheTrueVal;
606 ConstantInt *ConstantInt::getFalse(LLVMContext &Context) {
607 LLVMContextImpl *pImpl = Context.pImpl;
608 if (!pImpl->TheFalseVal)
609 pImpl->TheFalseVal = ConstantInt::get(Type::getInt1Ty(Context), 0);
610 return pImpl->TheFalseVal;
613 Constant *ConstantInt::getTrue(Type *Ty) {
614 assert(Ty->isIntOrIntVectorTy(1) && "Type not i1 or vector of i1.");
615 ConstantInt *TrueC = ConstantInt::getTrue(Ty->getContext());
616 if (auto *VTy = dyn_cast<VectorType>(Ty))
617 return ConstantVector::getSplat(VTy->getNumElements(), TrueC);
618 return TrueC;
621 Constant *ConstantInt::getFalse(Type *Ty) {
622 assert(Ty->isIntOrIntVectorTy(1) && "Type not i1 or vector of i1.");
623 ConstantInt *FalseC = ConstantInt::getFalse(Ty->getContext());
624 if (auto *VTy = dyn_cast<VectorType>(Ty))
625 return ConstantVector::getSplat(VTy->getNumElements(), FalseC);
626 return FalseC;
629 // Get a ConstantInt from an APInt.
630 ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt &V) {
631 // get an existing value or the insertion position
632 LLVMContextImpl *pImpl = Context.pImpl;
633 std::unique_ptr<ConstantInt> &Slot = pImpl->IntConstants[V];
634 if (!Slot) {
635 // Get the corresponding integer type for the bit width of the value.
636 IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
637 Slot.reset(new ConstantInt(ITy, V));
639 assert(Slot->getType() == IntegerType::get(Context, V.getBitWidth()));
640 return Slot.get();
643 Constant *ConstantInt::get(Type *Ty, uint64_t V, bool isSigned) {
644 Constant *C = get(cast<IntegerType>(Ty->getScalarType()), V, isSigned);
646 // For vectors, broadcast the value.
647 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
648 return ConstantVector::getSplat(VTy->getNumElements(), C);
650 return C;
653 ConstantInt *ConstantInt::get(IntegerType *Ty, uint64_t V, bool isSigned) {
654 return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned));
657 ConstantInt *ConstantInt::getSigned(IntegerType *Ty, int64_t V) {
658 return get(Ty, V, true);
661 Constant *ConstantInt::getSigned(Type *Ty, int64_t V) {
662 return get(Ty, V, true);
665 Constant *ConstantInt::get(Type *Ty, const APInt& V) {
666 ConstantInt *C = get(Ty->getContext(), V);
667 assert(C->getType() == Ty->getScalarType() &&
668 "ConstantInt type doesn't match the type implied by its value!");
670 // For vectors, broadcast the value.
671 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
672 return ConstantVector::getSplat(VTy->getNumElements(), C);
674 return C;
677 ConstantInt *ConstantInt::get(IntegerType* Ty, StringRef Str, uint8_t radix) {
678 return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
681 /// Remove the constant from the constant table.
682 void ConstantInt::destroyConstantImpl() {
683 llvm_unreachable("You can't ConstantInt->destroyConstantImpl()!");
686 //===----------------------------------------------------------------------===//
687 // ConstantFP
688 //===----------------------------------------------------------------------===//
690 static const fltSemantics *TypeToFloatSemantics(Type *Ty) {
691 if (Ty->isHalfTy())
692 return &APFloat::IEEEhalf();
693 if (Ty->isFloatTy())
694 return &APFloat::IEEEsingle();
695 if (Ty->isDoubleTy())
696 return &APFloat::IEEEdouble();
697 if (Ty->isX86_FP80Ty())
698 return &APFloat::x87DoubleExtended();
699 else if (Ty->isFP128Ty())
700 return &APFloat::IEEEquad();
702 assert(Ty->isPPC_FP128Ty() && "Unknown FP format");
703 return &APFloat::PPCDoubleDouble();
706 Constant *ConstantFP::get(Type *Ty, double V) {
707 LLVMContext &Context = Ty->getContext();
709 APFloat FV(V);
710 bool ignored;
711 FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
712 APFloat::rmNearestTiesToEven, &ignored);
713 Constant *C = get(Context, FV);
715 // For vectors, broadcast the value.
716 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
717 return ConstantVector::getSplat(VTy->getNumElements(), C);
719 return C;
722 Constant *ConstantFP::get(Type *Ty, const APFloat &V) {
723 ConstantFP *C = get(Ty->getContext(), V);
724 assert(C->getType() == Ty->getScalarType() &&
725 "ConstantFP type doesn't match the type implied by its value!");
727 // For vectors, broadcast the value.
728 if (auto *VTy = dyn_cast<VectorType>(Ty))
729 return ConstantVector::getSplat(VTy->getNumElements(), C);
731 return C;
734 Constant *ConstantFP::get(Type *Ty, StringRef Str) {
735 LLVMContext &Context = Ty->getContext();
737 APFloat FV(*TypeToFloatSemantics(Ty->getScalarType()), Str);
738 Constant *C = get(Context, FV);
740 // For vectors, broadcast the value.
741 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
742 return ConstantVector::getSplat(VTy->getNumElements(), C);
744 return C;
747 Constant *ConstantFP::getNaN(Type *Ty, bool Negative, uint64_t Payload) {
748 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
749 APFloat NaN = APFloat::getNaN(Semantics, Negative, Payload);
750 Constant *C = get(Ty->getContext(), NaN);
752 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
753 return ConstantVector::getSplat(VTy->getNumElements(), C);
755 return C;
758 Constant *ConstantFP::getQNaN(Type *Ty, bool Negative, APInt *Payload) {
759 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
760 APFloat NaN = APFloat::getQNaN(Semantics, Negative, Payload);
761 Constant *C = get(Ty->getContext(), NaN);
763 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
764 return ConstantVector::getSplat(VTy->getNumElements(), C);
766 return C;
769 Constant *ConstantFP::getSNaN(Type *Ty, bool Negative, APInt *Payload) {
770 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
771 APFloat NaN = APFloat::getSNaN(Semantics, Negative, Payload);
772 Constant *C = get(Ty->getContext(), NaN);
774 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
775 return ConstantVector::getSplat(VTy->getNumElements(), C);
777 return C;
780 Constant *ConstantFP::getNegativeZero(Type *Ty) {
781 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
782 APFloat NegZero = APFloat::getZero(Semantics, /*Negative=*/true);
783 Constant *C = get(Ty->getContext(), NegZero);
785 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
786 return ConstantVector::getSplat(VTy->getNumElements(), C);
788 return C;
792 Constant *ConstantFP::getZeroValueForNegation(Type *Ty) {
793 if (Ty->isFPOrFPVectorTy())
794 return getNegativeZero(Ty);
796 return Constant::getNullValue(Ty);
800 // ConstantFP accessors.
801 ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
802 LLVMContextImpl* pImpl = Context.pImpl;
804 std::unique_ptr<ConstantFP> &Slot = pImpl->FPConstants[V];
806 if (!Slot) {
807 Type *Ty;
808 if (&V.getSemantics() == &APFloat::IEEEhalf())
809 Ty = Type::getHalfTy(Context);
810 else if (&V.getSemantics() == &APFloat::IEEEsingle())
811 Ty = Type::getFloatTy(Context);
812 else if (&V.getSemantics() == &APFloat::IEEEdouble())
813 Ty = Type::getDoubleTy(Context);
814 else if (&V.getSemantics() == &APFloat::x87DoubleExtended())
815 Ty = Type::getX86_FP80Ty(Context);
816 else if (&V.getSemantics() == &APFloat::IEEEquad())
817 Ty = Type::getFP128Ty(Context);
818 else {
819 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble() &&
820 "Unknown FP format");
821 Ty = Type::getPPC_FP128Ty(Context);
823 Slot.reset(new ConstantFP(Ty, V));
826 return Slot.get();
829 Constant *ConstantFP::getInfinity(Type *Ty, bool Negative) {
830 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
831 Constant *C = get(Ty->getContext(), APFloat::getInf(Semantics, Negative));
833 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
834 return ConstantVector::getSplat(VTy->getNumElements(), C);
836 return C;
839 ConstantFP::ConstantFP(Type *Ty, const APFloat &V)
840 : ConstantData(Ty, ConstantFPVal), Val(V) {
841 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
842 "FP type Mismatch");
845 bool ConstantFP::isExactlyValue(const APFloat &V) const {
846 return Val.bitwiseIsEqual(V);
849 /// Remove the constant from the constant table.
850 void ConstantFP::destroyConstantImpl() {
851 llvm_unreachable("You can't ConstantFP->destroyConstantImpl()!");
854 //===----------------------------------------------------------------------===//
855 // ConstantAggregateZero Implementation
856 //===----------------------------------------------------------------------===//
858 Constant *ConstantAggregateZero::getSequentialElement() const {
859 return Constant::getNullValue(getType()->getSequentialElementType());
862 Constant *ConstantAggregateZero::getStructElement(unsigned Elt) const {
863 return Constant::getNullValue(getType()->getStructElementType(Elt));
866 Constant *ConstantAggregateZero::getElementValue(Constant *C) const {
867 if (isa<SequentialType>(getType()))
868 return getSequentialElement();
869 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
872 Constant *ConstantAggregateZero::getElementValue(unsigned Idx) const {
873 if (isa<SequentialType>(getType()))
874 return getSequentialElement();
875 return getStructElement(Idx);
878 unsigned ConstantAggregateZero::getNumElements() const {
879 Type *Ty = getType();
880 if (auto *AT = dyn_cast<ArrayType>(Ty))
881 return AT->getNumElements();
882 if (auto *VT = dyn_cast<VectorType>(Ty))
883 return VT->getNumElements();
884 return Ty->getStructNumElements();
887 //===----------------------------------------------------------------------===//
888 // UndefValue Implementation
889 //===----------------------------------------------------------------------===//
891 UndefValue *UndefValue::getSequentialElement() const {
892 return UndefValue::get(getType()->getSequentialElementType());
895 UndefValue *UndefValue::getStructElement(unsigned Elt) const {
896 return UndefValue::get(getType()->getStructElementType(Elt));
899 UndefValue *UndefValue::getElementValue(Constant *C) const {
900 if (isa<SequentialType>(getType()))
901 return getSequentialElement();
902 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
905 UndefValue *UndefValue::getElementValue(unsigned Idx) const {
906 if (isa<SequentialType>(getType()))
907 return getSequentialElement();
908 return getStructElement(Idx);
911 unsigned UndefValue::getNumElements() const {
912 Type *Ty = getType();
913 if (auto *ST = dyn_cast<SequentialType>(Ty))
914 return ST->getNumElements();
915 return Ty->getStructNumElements();
918 //===----------------------------------------------------------------------===//
919 // ConstantXXX Classes
920 //===----------------------------------------------------------------------===//
922 template <typename ItTy, typename EltTy>
923 static bool rangeOnlyContains(ItTy Start, ItTy End, EltTy Elt) {
924 for (; Start != End; ++Start)
925 if (*Start != Elt)
926 return false;
927 return true;
930 template <typename SequentialTy, typename ElementTy>
931 static Constant *getIntSequenceIfElementsMatch(ArrayRef<Constant *> V) {
932 assert(!V.empty() && "Cannot get empty int sequence.");
934 SmallVector<ElementTy, 16> Elts;
935 for (Constant *C : V)
936 if (auto *CI = dyn_cast<ConstantInt>(C))
937 Elts.push_back(CI->getZExtValue());
938 else
939 return nullptr;
940 return SequentialTy::get(V[0]->getContext(), Elts);
943 template <typename SequentialTy, typename ElementTy>
944 static Constant *getFPSequenceIfElementsMatch(ArrayRef<Constant *> V) {
945 assert(!V.empty() && "Cannot get empty FP sequence.");
947 SmallVector<ElementTy, 16> Elts;
948 for (Constant *C : V)
949 if (auto *CFP = dyn_cast<ConstantFP>(C))
950 Elts.push_back(CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
951 else
952 return nullptr;
953 return SequentialTy::getFP(V[0]->getContext(), Elts);
956 template <typename SequenceTy>
957 static Constant *getSequenceIfElementsMatch(Constant *C,
958 ArrayRef<Constant *> V) {
959 // We speculatively build the elements here even if it turns out that there is
960 // a constantexpr or something else weird, since it is so uncommon for that to
961 // happen.
962 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
963 if (CI->getType()->isIntegerTy(8))
964 return getIntSequenceIfElementsMatch<SequenceTy, uint8_t>(V);
965 else if (CI->getType()->isIntegerTy(16))
966 return getIntSequenceIfElementsMatch<SequenceTy, uint16_t>(V);
967 else if (CI->getType()->isIntegerTy(32))
968 return getIntSequenceIfElementsMatch<SequenceTy, uint32_t>(V);
969 else if (CI->getType()->isIntegerTy(64))
970 return getIntSequenceIfElementsMatch<SequenceTy, uint64_t>(V);
971 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
972 if (CFP->getType()->isHalfTy())
973 return getFPSequenceIfElementsMatch<SequenceTy, uint16_t>(V);
974 else if (CFP->getType()->isFloatTy())
975 return getFPSequenceIfElementsMatch<SequenceTy, uint32_t>(V);
976 else if (CFP->getType()->isDoubleTy())
977 return getFPSequenceIfElementsMatch<SequenceTy, uint64_t>(V);
980 return nullptr;
983 ConstantAggregate::ConstantAggregate(CompositeType *T, ValueTy VT,
984 ArrayRef<Constant *> V)
985 : Constant(T, VT, OperandTraits<ConstantAggregate>::op_end(this) - V.size(),
986 V.size()) {
987 llvm::copy(V, op_begin());
989 // Check that types match, unless this is an opaque struct.
990 if (auto *ST = dyn_cast<StructType>(T))
991 if (ST->isOpaque())
992 return;
993 for (unsigned I = 0, E = V.size(); I != E; ++I)
994 assert(V[I]->getType() == T->getTypeAtIndex(I) &&
995 "Initializer for composite element doesn't match!");
998 ConstantArray::ConstantArray(ArrayType *T, ArrayRef<Constant *> V)
999 : ConstantAggregate(T, ConstantArrayVal, V) {
1000 assert(V.size() == T->getNumElements() &&
1001 "Invalid initializer for constant array");
1004 Constant *ConstantArray::get(ArrayType *Ty, ArrayRef<Constant*> V) {
1005 if (Constant *C = getImpl(Ty, V))
1006 return C;
1007 return Ty->getContext().pImpl->ArrayConstants.getOrCreate(Ty, V);
1010 Constant *ConstantArray::getImpl(ArrayType *Ty, ArrayRef<Constant*> V) {
1011 // Empty arrays are canonicalized to ConstantAggregateZero.
1012 if (V.empty())
1013 return ConstantAggregateZero::get(Ty);
1015 for (unsigned i = 0, e = V.size(); i != e; ++i) {
1016 assert(V[i]->getType() == Ty->getElementType() &&
1017 "Wrong type in array element initializer");
1020 // If this is an all-zero array, return a ConstantAggregateZero object. If
1021 // all undef, return an UndefValue, if "all simple", then return a
1022 // ConstantDataArray.
1023 Constant *C = V[0];
1024 if (isa<UndefValue>(C) && rangeOnlyContains(V.begin(), V.end(), C))
1025 return UndefValue::get(Ty);
1027 if (C->isNullValue() && rangeOnlyContains(V.begin(), V.end(), C))
1028 return ConstantAggregateZero::get(Ty);
1030 // Check to see if all of the elements are ConstantFP or ConstantInt and if
1031 // the element type is compatible with ConstantDataVector. If so, use it.
1032 if (ConstantDataSequential::isElementTypeCompatible(C->getType()))
1033 return getSequenceIfElementsMatch<ConstantDataArray>(C, V);
1035 // Otherwise, we really do want to create a ConstantArray.
1036 return nullptr;
1039 StructType *ConstantStruct::getTypeForElements(LLVMContext &Context,
1040 ArrayRef<Constant*> V,
1041 bool Packed) {
1042 unsigned VecSize = V.size();
1043 SmallVector<Type*, 16> EltTypes(VecSize);
1044 for (unsigned i = 0; i != VecSize; ++i)
1045 EltTypes[i] = V[i]->getType();
1047 return StructType::get(Context, EltTypes, Packed);
1051 StructType *ConstantStruct::getTypeForElements(ArrayRef<Constant*> V,
1052 bool Packed) {
1053 assert(!V.empty() &&
1054 "ConstantStruct::getTypeForElements cannot be called on empty list");
1055 return getTypeForElements(V[0]->getContext(), V, Packed);
1058 ConstantStruct::ConstantStruct(StructType *T, ArrayRef<Constant *> V)
1059 : ConstantAggregate(T, ConstantStructVal, V) {
1060 assert((T->isOpaque() || V.size() == T->getNumElements()) &&
1061 "Invalid initializer for constant struct");
1064 // ConstantStruct accessors.
1065 Constant *ConstantStruct::get(StructType *ST, ArrayRef<Constant*> V) {
1066 assert((ST->isOpaque() || ST->getNumElements() == V.size()) &&
1067 "Incorrect # elements specified to ConstantStruct::get");
1069 // Create a ConstantAggregateZero value if all elements are zeros.
1070 bool isZero = true;
1071 bool isUndef = false;
1073 if (!V.empty()) {
1074 isUndef = isa<UndefValue>(V[0]);
1075 isZero = V[0]->isNullValue();
1076 if (isUndef || isZero) {
1077 for (unsigned i = 0, e = V.size(); i != e; ++i) {
1078 if (!V[i]->isNullValue())
1079 isZero = false;
1080 if (!isa<UndefValue>(V[i]))
1081 isUndef = false;
1085 if (isZero)
1086 return ConstantAggregateZero::get(ST);
1087 if (isUndef)
1088 return UndefValue::get(ST);
1090 return ST->getContext().pImpl->StructConstants.getOrCreate(ST, V);
1093 ConstantVector::ConstantVector(VectorType *T, ArrayRef<Constant *> V)
1094 : ConstantAggregate(T, ConstantVectorVal, V) {
1095 assert(V.size() == T->getNumElements() &&
1096 "Invalid initializer for constant vector");
1099 // ConstantVector accessors.
1100 Constant *ConstantVector::get(ArrayRef<Constant*> V) {
1101 if (Constant *C = getImpl(V))
1102 return C;
1103 VectorType *Ty = VectorType::get(V.front()->getType(), V.size());
1104 return Ty->getContext().pImpl->VectorConstants.getOrCreate(Ty, V);
1107 Constant *ConstantVector::getImpl(ArrayRef<Constant*> V) {
1108 assert(!V.empty() && "Vectors can't be empty");
1109 VectorType *T = VectorType::get(V.front()->getType(), V.size());
1111 // If this is an all-undef or all-zero vector, return a
1112 // ConstantAggregateZero or UndefValue.
1113 Constant *C = V[0];
1114 bool isZero = C->isNullValue();
1115 bool isUndef = isa<UndefValue>(C);
1117 if (isZero || isUndef) {
1118 for (unsigned i = 1, e = V.size(); i != e; ++i)
1119 if (V[i] != C) {
1120 isZero = isUndef = false;
1121 break;
1125 if (isZero)
1126 return ConstantAggregateZero::get(T);
1127 if (isUndef)
1128 return UndefValue::get(T);
1130 // Check to see if all of the elements are ConstantFP or ConstantInt and if
1131 // the element type is compatible with ConstantDataVector. If so, use it.
1132 if (ConstantDataSequential::isElementTypeCompatible(C->getType()))
1133 return getSequenceIfElementsMatch<ConstantDataVector>(C, V);
1135 // Otherwise, the element type isn't compatible with ConstantDataVector, or
1136 // the operand list contains a ConstantExpr or something else strange.
1137 return nullptr;
1140 Constant *ConstantVector::getSplat(unsigned NumElts, Constant *V) {
1141 // If this splat is compatible with ConstantDataVector, use it instead of
1142 // ConstantVector.
1143 if ((isa<ConstantFP>(V) || isa<ConstantInt>(V)) &&
1144 ConstantDataSequential::isElementTypeCompatible(V->getType()))
1145 return ConstantDataVector::getSplat(NumElts, V);
1147 SmallVector<Constant*, 32> Elts(NumElts, V);
1148 return get(Elts);
1151 ConstantTokenNone *ConstantTokenNone::get(LLVMContext &Context) {
1152 LLVMContextImpl *pImpl = Context.pImpl;
1153 if (!pImpl->TheNoneToken)
1154 pImpl->TheNoneToken.reset(new ConstantTokenNone(Context));
1155 return pImpl->TheNoneToken.get();
1158 /// Remove the constant from the constant table.
1159 void ConstantTokenNone::destroyConstantImpl() {
1160 llvm_unreachable("You can't ConstantTokenNone->destroyConstantImpl()!");
1163 // Utility function for determining if a ConstantExpr is a CastOp or not. This
1164 // can't be inline because we don't want to #include Instruction.h into
1165 // Constant.h
1166 bool ConstantExpr::isCast() const {
1167 return Instruction::isCast(getOpcode());
1170 bool ConstantExpr::isCompare() const {
1171 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
1174 bool ConstantExpr::isGEPWithNoNotionalOverIndexing() const {
1175 if (getOpcode() != Instruction::GetElementPtr) return false;
1177 gep_type_iterator GEPI = gep_type_begin(this), E = gep_type_end(this);
1178 User::const_op_iterator OI = std::next(this->op_begin());
1180 // The remaining indices may be compile-time known integers within the bounds
1181 // of the corresponding notional static array types.
1182 for (; GEPI != E; ++GEPI, ++OI) {
1183 if (isa<UndefValue>(*OI))
1184 continue;
1185 auto *CI = dyn_cast<ConstantInt>(*OI);
1186 if (!CI || (GEPI.isBoundedSequential() &&
1187 (CI->getValue().getActiveBits() > 64 ||
1188 CI->getZExtValue() >= GEPI.getSequentialNumElements())))
1189 return false;
1192 // All the indices checked out.
1193 return true;
1196 bool ConstantExpr::hasIndices() const {
1197 return getOpcode() == Instruction::ExtractValue ||
1198 getOpcode() == Instruction::InsertValue;
1201 ArrayRef<unsigned> ConstantExpr::getIndices() const {
1202 if (const ExtractValueConstantExpr *EVCE =
1203 dyn_cast<ExtractValueConstantExpr>(this))
1204 return EVCE->Indices;
1206 return cast<InsertValueConstantExpr>(this)->Indices;
1209 unsigned ConstantExpr::getPredicate() const {
1210 return cast<CompareConstantExpr>(this)->predicate;
1213 Constant *
1214 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
1215 assert(Op->getType() == getOperand(OpNo)->getType() &&
1216 "Replacing operand with value of different type!");
1217 if (getOperand(OpNo) == Op)
1218 return const_cast<ConstantExpr*>(this);
1220 SmallVector<Constant*, 8> NewOps;
1221 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1222 NewOps.push_back(i == OpNo ? Op : getOperand(i));
1224 return getWithOperands(NewOps);
1227 Constant *ConstantExpr::getWithOperands(ArrayRef<Constant *> Ops, Type *Ty,
1228 bool OnlyIfReduced, Type *SrcTy) const {
1229 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
1231 // If no operands changed return self.
1232 if (Ty == getType() && std::equal(Ops.begin(), Ops.end(), op_begin()))
1233 return const_cast<ConstantExpr*>(this);
1235 Type *OnlyIfReducedTy = OnlyIfReduced ? Ty : nullptr;
1236 switch (getOpcode()) {
1237 case Instruction::Trunc:
1238 case Instruction::ZExt:
1239 case Instruction::SExt:
1240 case Instruction::FPTrunc:
1241 case Instruction::FPExt:
1242 case Instruction::UIToFP:
1243 case Instruction::SIToFP:
1244 case Instruction::FPToUI:
1245 case Instruction::FPToSI:
1246 case Instruction::PtrToInt:
1247 case Instruction::IntToPtr:
1248 case Instruction::BitCast:
1249 case Instruction::AddrSpaceCast:
1250 return ConstantExpr::getCast(getOpcode(), Ops[0], Ty, OnlyIfReduced);
1251 case Instruction::Select:
1252 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2], OnlyIfReducedTy);
1253 case Instruction::InsertElement:
1254 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2],
1255 OnlyIfReducedTy);
1256 case Instruction::ExtractElement:
1257 return ConstantExpr::getExtractElement(Ops[0], Ops[1], OnlyIfReducedTy);
1258 case Instruction::InsertValue:
1259 return ConstantExpr::getInsertValue(Ops[0], Ops[1], getIndices(),
1260 OnlyIfReducedTy);
1261 case Instruction::ExtractValue:
1262 return ConstantExpr::getExtractValue(Ops[0], getIndices(), OnlyIfReducedTy);
1263 case Instruction::ShuffleVector:
1264 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2],
1265 OnlyIfReducedTy);
1266 case Instruction::GetElementPtr: {
1267 auto *GEPO = cast<GEPOperator>(this);
1268 assert(SrcTy || (Ops[0]->getType() == getOperand(0)->getType()));
1269 return ConstantExpr::getGetElementPtr(
1270 SrcTy ? SrcTy : GEPO->getSourceElementType(), Ops[0], Ops.slice(1),
1271 GEPO->isInBounds(), GEPO->getInRangeIndex(), OnlyIfReducedTy);
1273 case Instruction::ICmp:
1274 case Instruction::FCmp:
1275 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1],
1276 OnlyIfReducedTy);
1277 default:
1278 assert(getNumOperands() == 2 && "Must be binary operator?");
1279 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1], SubclassOptionalData,
1280 OnlyIfReducedTy);
1285 //===----------------------------------------------------------------------===//
1286 // isValueValidForType implementations
1288 bool ConstantInt::isValueValidForType(Type *Ty, uint64_t Val) {
1289 unsigned NumBits = Ty->getIntegerBitWidth(); // assert okay
1290 if (Ty->isIntegerTy(1))
1291 return Val == 0 || Val == 1;
1292 return isUIntN(NumBits, Val);
1295 bool ConstantInt::isValueValidForType(Type *Ty, int64_t Val) {
1296 unsigned NumBits = Ty->getIntegerBitWidth();
1297 if (Ty->isIntegerTy(1))
1298 return Val == 0 || Val == 1 || Val == -1;
1299 return isIntN(NumBits, Val);
1302 bool ConstantFP::isValueValidForType(Type *Ty, const APFloat& Val) {
1303 // convert modifies in place, so make a copy.
1304 APFloat Val2 = APFloat(Val);
1305 bool losesInfo;
1306 switch (Ty->getTypeID()) {
1307 default:
1308 return false; // These can't be represented as floating point!
1310 // FIXME rounding mode needs to be more flexible
1311 case Type::HalfTyID: {
1312 if (&Val2.getSemantics() == &APFloat::IEEEhalf())
1313 return true;
1314 Val2.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven, &losesInfo);
1315 return !losesInfo;
1317 case Type::FloatTyID: {
1318 if (&Val2.getSemantics() == &APFloat::IEEEsingle())
1319 return true;
1320 Val2.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, &losesInfo);
1321 return !losesInfo;
1323 case Type::DoubleTyID: {
1324 if (&Val2.getSemantics() == &APFloat::IEEEhalf() ||
1325 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1326 &Val2.getSemantics() == &APFloat::IEEEdouble())
1327 return true;
1328 Val2.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, &losesInfo);
1329 return !losesInfo;
1331 case Type::X86_FP80TyID:
1332 return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
1333 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1334 &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1335 &Val2.getSemantics() == &APFloat::x87DoubleExtended();
1336 case Type::FP128TyID:
1337 return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
1338 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1339 &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1340 &Val2.getSemantics() == &APFloat::IEEEquad();
1341 case Type::PPC_FP128TyID:
1342 return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
1343 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1344 &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1345 &Val2.getSemantics() == &APFloat::PPCDoubleDouble();
1350 //===----------------------------------------------------------------------===//
1351 // Factory Function Implementation
1353 ConstantAggregateZero *ConstantAggregateZero::get(Type *Ty) {
1354 assert((Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()) &&
1355 "Cannot create an aggregate zero of non-aggregate type!");
1357 std::unique_ptr<ConstantAggregateZero> &Entry =
1358 Ty->getContext().pImpl->CAZConstants[Ty];
1359 if (!Entry)
1360 Entry.reset(new ConstantAggregateZero(Ty));
1362 return Entry.get();
1365 /// Remove the constant from the constant table.
1366 void ConstantAggregateZero::destroyConstantImpl() {
1367 getContext().pImpl->CAZConstants.erase(getType());
1370 /// Remove the constant from the constant table.
1371 void ConstantArray::destroyConstantImpl() {
1372 getType()->getContext().pImpl->ArrayConstants.remove(this);
1376 //---- ConstantStruct::get() implementation...
1379 /// Remove the constant from the constant table.
1380 void ConstantStruct::destroyConstantImpl() {
1381 getType()->getContext().pImpl->StructConstants.remove(this);
1384 /// Remove the constant from the constant table.
1385 void ConstantVector::destroyConstantImpl() {
1386 getType()->getContext().pImpl->VectorConstants.remove(this);
1389 Constant *Constant::getSplatValue() const {
1390 assert(this->getType()->isVectorTy() && "Only valid for vectors!");
1391 if (isa<ConstantAggregateZero>(this))
1392 return getNullValue(this->getType()->getVectorElementType());
1393 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
1394 return CV->getSplatValue();
1395 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
1396 return CV->getSplatValue();
1397 return nullptr;
1400 Constant *ConstantVector::getSplatValue() const {
1401 // Check out first element.
1402 Constant *Elt = getOperand(0);
1403 // Then make sure all remaining elements point to the same value.
1404 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1405 if (getOperand(I) != Elt)
1406 return nullptr;
1407 return Elt;
1410 const APInt &Constant::getUniqueInteger() const {
1411 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
1412 return CI->getValue();
1413 assert(this->getSplatValue() && "Doesn't contain a unique integer!");
1414 const Constant *C = this->getAggregateElement(0U);
1415 assert(C && isa<ConstantInt>(C) && "Not a vector of numbers!");
1416 return cast<ConstantInt>(C)->getValue();
1419 //---- ConstantPointerNull::get() implementation.
1422 ConstantPointerNull *ConstantPointerNull::get(PointerType *Ty) {
1423 std::unique_ptr<ConstantPointerNull> &Entry =
1424 Ty->getContext().pImpl->CPNConstants[Ty];
1425 if (!Entry)
1426 Entry.reset(new ConstantPointerNull(Ty));
1428 return Entry.get();
1431 /// Remove the constant from the constant table.
1432 void ConstantPointerNull::destroyConstantImpl() {
1433 getContext().pImpl->CPNConstants.erase(getType());
1436 UndefValue *UndefValue::get(Type *Ty) {
1437 std::unique_ptr<UndefValue> &Entry = Ty->getContext().pImpl->UVConstants[Ty];
1438 if (!Entry)
1439 Entry.reset(new UndefValue(Ty));
1441 return Entry.get();
1444 /// Remove the constant from the constant table.
1445 void UndefValue::destroyConstantImpl() {
1446 // Free the constant and any dangling references to it.
1447 getContext().pImpl->UVConstants.erase(getType());
1450 BlockAddress *BlockAddress::get(BasicBlock *BB) {
1451 assert(BB->getParent() && "Block must have a parent");
1452 return get(BB->getParent(), BB);
1455 BlockAddress *BlockAddress::get(Function *F, BasicBlock *BB) {
1456 BlockAddress *&BA =
1457 F->getContext().pImpl->BlockAddresses[std::make_pair(F, BB)];
1458 if (!BA)
1459 BA = new BlockAddress(F, BB);
1461 assert(BA->getFunction() == F && "Basic block moved between functions");
1462 return BA;
1465 BlockAddress::BlockAddress(Function *F, BasicBlock *BB)
1466 : Constant(Type::getInt8PtrTy(F->getContext()), Value::BlockAddressVal,
1467 &Op<0>(), 2) {
1468 setOperand(0, F);
1469 setOperand(1, BB);
1470 BB->AdjustBlockAddressRefCount(1);
1473 BlockAddress *BlockAddress::lookup(const BasicBlock *BB) {
1474 if (!BB->hasAddressTaken())
1475 return nullptr;
1477 const Function *F = BB->getParent();
1478 assert(F && "Block must have a parent");
1479 BlockAddress *BA =
1480 F->getContext().pImpl->BlockAddresses.lookup(std::make_pair(F, BB));
1481 assert(BA && "Refcount and block address map disagree!");
1482 return BA;
1485 /// Remove the constant from the constant table.
1486 void BlockAddress::destroyConstantImpl() {
1487 getFunction()->getType()->getContext().pImpl
1488 ->BlockAddresses.erase(std::make_pair(getFunction(), getBasicBlock()));
1489 getBasicBlock()->AdjustBlockAddressRefCount(-1);
1492 Value *BlockAddress::handleOperandChangeImpl(Value *From, Value *To) {
1493 // This could be replacing either the Basic Block or the Function. In either
1494 // case, we have to remove the map entry.
1495 Function *NewF = getFunction();
1496 BasicBlock *NewBB = getBasicBlock();
1498 if (From == NewF)
1499 NewF = cast<Function>(To->stripPointerCasts());
1500 else {
1501 assert(From == NewBB && "From does not match any operand");
1502 NewBB = cast<BasicBlock>(To);
1505 // See if the 'new' entry already exists, if not, just update this in place
1506 // and return early.
1507 BlockAddress *&NewBA =
1508 getContext().pImpl->BlockAddresses[std::make_pair(NewF, NewBB)];
1509 if (NewBA)
1510 return NewBA;
1512 getBasicBlock()->AdjustBlockAddressRefCount(-1);
1514 // Remove the old entry, this can't cause the map to rehash (just a
1515 // tombstone will get added).
1516 getContext().pImpl->BlockAddresses.erase(std::make_pair(getFunction(),
1517 getBasicBlock()));
1518 NewBA = this;
1519 setOperand(0, NewF);
1520 setOperand(1, NewBB);
1521 getBasicBlock()->AdjustBlockAddressRefCount(1);
1523 // If we just want to keep the existing value, then return null.
1524 // Callers know that this means we shouldn't delete this value.
1525 return nullptr;
1528 //---- ConstantExpr::get() implementations.
1531 /// This is a utility function to handle folding of casts and lookup of the
1532 /// cast in the ExprConstants map. It is used by the various get* methods below.
1533 static Constant *getFoldedCast(Instruction::CastOps opc, Constant *C, Type *Ty,
1534 bool OnlyIfReduced = false) {
1535 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1536 // Fold a few common cases
1537 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1538 return FC;
1540 if (OnlyIfReduced)
1541 return nullptr;
1543 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
1545 // Look up the constant in the table first to ensure uniqueness.
1546 ConstantExprKeyType Key(opc, C);
1548 return pImpl->ExprConstants.getOrCreate(Ty, Key);
1551 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, Type *Ty,
1552 bool OnlyIfReduced) {
1553 Instruction::CastOps opc = Instruction::CastOps(oc);
1554 assert(Instruction::isCast(opc) && "opcode out of range");
1555 assert(C && Ty && "Null arguments to getCast");
1556 assert(CastInst::castIsValid(opc, C, Ty) && "Invalid constantexpr cast!");
1558 switch (opc) {
1559 default:
1560 llvm_unreachable("Invalid cast opcode");
1561 case Instruction::Trunc:
1562 return getTrunc(C, Ty, OnlyIfReduced);
1563 case Instruction::ZExt:
1564 return getZExt(C, Ty, OnlyIfReduced);
1565 case Instruction::SExt:
1566 return getSExt(C, Ty, OnlyIfReduced);
1567 case Instruction::FPTrunc:
1568 return getFPTrunc(C, Ty, OnlyIfReduced);
1569 case Instruction::FPExt:
1570 return getFPExtend(C, Ty, OnlyIfReduced);
1571 case Instruction::UIToFP:
1572 return getUIToFP(C, Ty, OnlyIfReduced);
1573 case Instruction::SIToFP:
1574 return getSIToFP(C, Ty, OnlyIfReduced);
1575 case Instruction::FPToUI:
1576 return getFPToUI(C, Ty, OnlyIfReduced);
1577 case Instruction::FPToSI:
1578 return getFPToSI(C, Ty, OnlyIfReduced);
1579 case Instruction::PtrToInt:
1580 return getPtrToInt(C, Ty, OnlyIfReduced);
1581 case Instruction::IntToPtr:
1582 return getIntToPtr(C, Ty, OnlyIfReduced);
1583 case Instruction::BitCast:
1584 return getBitCast(C, Ty, OnlyIfReduced);
1585 case Instruction::AddrSpaceCast:
1586 return getAddrSpaceCast(C, Ty, OnlyIfReduced);
1590 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, Type *Ty) {
1591 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1592 return getBitCast(C, Ty);
1593 return getZExt(C, Ty);
1596 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, Type *Ty) {
1597 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1598 return getBitCast(C, Ty);
1599 return getSExt(C, Ty);
1602 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, Type *Ty) {
1603 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1604 return getBitCast(C, Ty);
1605 return getTrunc(C, Ty);
1608 Constant *ConstantExpr::getPointerCast(Constant *S, Type *Ty) {
1609 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
1610 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
1611 "Invalid cast");
1613 if (Ty->isIntOrIntVectorTy())
1614 return getPtrToInt(S, Ty);
1616 unsigned SrcAS = S->getType()->getPointerAddressSpace();
1617 if (Ty->isPtrOrPtrVectorTy() && SrcAS != Ty->getPointerAddressSpace())
1618 return getAddrSpaceCast(S, Ty);
1620 return getBitCast(S, Ty);
1623 Constant *ConstantExpr::getPointerBitCastOrAddrSpaceCast(Constant *S,
1624 Type *Ty) {
1625 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
1626 assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
1628 if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
1629 return getAddrSpaceCast(S, Ty);
1631 return getBitCast(S, Ty);
1634 Constant *ConstantExpr::getIntegerCast(Constant *C, Type *Ty, bool isSigned) {
1635 assert(C->getType()->isIntOrIntVectorTy() &&
1636 Ty->isIntOrIntVectorTy() && "Invalid cast");
1637 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1638 unsigned DstBits = Ty->getScalarSizeInBits();
1639 Instruction::CastOps opcode =
1640 (SrcBits == DstBits ? Instruction::BitCast :
1641 (SrcBits > DstBits ? Instruction::Trunc :
1642 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1643 return getCast(opcode, C, Ty);
1646 Constant *ConstantExpr::getFPCast(Constant *C, Type *Ty) {
1647 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1648 "Invalid cast");
1649 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1650 unsigned DstBits = Ty->getScalarSizeInBits();
1651 if (SrcBits == DstBits)
1652 return C; // Avoid a useless cast
1653 Instruction::CastOps opcode =
1654 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1655 return getCast(opcode, C, Ty);
1658 Constant *ConstantExpr::getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) {
1659 #ifndef NDEBUG
1660 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1661 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1662 #endif
1663 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1664 assert(C->getType()->isIntOrIntVectorTy() && "Trunc operand must be integer");
1665 assert(Ty->isIntOrIntVectorTy() && "Trunc produces only integral");
1666 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1667 "SrcTy must be larger than DestTy for Trunc!");
1669 return getFoldedCast(Instruction::Trunc, C, Ty, OnlyIfReduced);
1672 Constant *ConstantExpr::getSExt(Constant *C, Type *Ty, bool OnlyIfReduced) {
1673 #ifndef NDEBUG
1674 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1675 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1676 #endif
1677 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1678 assert(C->getType()->isIntOrIntVectorTy() && "SExt operand must be integral");
1679 assert(Ty->isIntOrIntVectorTy() && "SExt produces only integer");
1680 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1681 "SrcTy must be smaller than DestTy for SExt!");
1683 return getFoldedCast(Instruction::SExt, C, Ty, OnlyIfReduced);
1686 Constant *ConstantExpr::getZExt(Constant *C, Type *Ty, bool OnlyIfReduced) {
1687 #ifndef NDEBUG
1688 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1689 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1690 #endif
1691 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1692 assert(C->getType()->isIntOrIntVectorTy() && "ZEXt operand must be integral");
1693 assert(Ty->isIntOrIntVectorTy() && "ZExt produces only integer");
1694 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1695 "SrcTy must be smaller than DestTy for ZExt!");
1697 return getFoldedCast(Instruction::ZExt, C, Ty, OnlyIfReduced);
1700 Constant *ConstantExpr::getFPTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) {
1701 #ifndef NDEBUG
1702 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1703 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1704 #endif
1705 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1706 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1707 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1708 "This is an illegal floating point truncation!");
1709 return getFoldedCast(Instruction::FPTrunc, C, Ty, OnlyIfReduced);
1712 Constant *ConstantExpr::getFPExtend(Constant *C, Type *Ty, bool OnlyIfReduced) {
1713 #ifndef NDEBUG
1714 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1715 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1716 #endif
1717 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1718 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1719 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1720 "This is an illegal floating point extension!");
1721 return getFoldedCast(Instruction::FPExt, C, Ty, OnlyIfReduced);
1724 Constant *ConstantExpr::getUIToFP(Constant *C, Type *Ty, bool OnlyIfReduced) {
1725 #ifndef NDEBUG
1726 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1727 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1728 #endif
1729 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1730 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
1731 "This is an illegal uint to floating point cast!");
1732 return getFoldedCast(Instruction::UIToFP, C, Ty, OnlyIfReduced);
1735 Constant *ConstantExpr::getSIToFP(Constant *C, Type *Ty, bool OnlyIfReduced) {
1736 #ifndef NDEBUG
1737 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1738 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1739 #endif
1740 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1741 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
1742 "This is an illegal sint to floating point cast!");
1743 return getFoldedCast(Instruction::SIToFP, C, Ty, OnlyIfReduced);
1746 Constant *ConstantExpr::getFPToUI(Constant *C, Type *Ty, bool OnlyIfReduced) {
1747 #ifndef NDEBUG
1748 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1749 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1750 #endif
1751 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1752 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
1753 "This is an illegal floating point to uint cast!");
1754 return getFoldedCast(Instruction::FPToUI, C, Ty, OnlyIfReduced);
1757 Constant *ConstantExpr::getFPToSI(Constant *C, Type *Ty, bool OnlyIfReduced) {
1758 #ifndef NDEBUG
1759 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1760 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1761 #endif
1762 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1763 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
1764 "This is an illegal floating point to sint cast!");
1765 return getFoldedCast(Instruction::FPToSI, C, Ty, OnlyIfReduced);
1768 Constant *ConstantExpr::getPtrToInt(Constant *C, Type *DstTy,
1769 bool OnlyIfReduced) {
1770 assert(C->getType()->isPtrOrPtrVectorTy() &&
1771 "PtrToInt source must be pointer or pointer vector");
1772 assert(DstTy->isIntOrIntVectorTy() &&
1773 "PtrToInt destination must be integer or integer vector");
1774 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
1775 if (isa<VectorType>(C->getType()))
1776 assert(C->getType()->getVectorNumElements()==DstTy->getVectorNumElements()&&
1777 "Invalid cast between a different number of vector elements");
1778 return getFoldedCast(Instruction::PtrToInt, C, DstTy, OnlyIfReduced);
1781 Constant *ConstantExpr::getIntToPtr(Constant *C, Type *DstTy,
1782 bool OnlyIfReduced) {
1783 assert(C->getType()->isIntOrIntVectorTy() &&
1784 "IntToPtr source must be integer or integer vector");
1785 assert(DstTy->isPtrOrPtrVectorTy() &&
1786 "IntToPtr destination must be a pointer or pointer vector");
1787 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
1788 if (isa<VectorType>(C->getType()))
1789 assert(C->getType()->getVectorNumElements()==DstTy->getVectorNumElements()&&
1790 "Invalid cast between a different number of vector elements");
1791 return getFoldedCast(Instruction::IntToPtr, C, DstTy, OnlyIfReduced);
1794 Constant *ConstantExpr::getBitCast(Constant *C, Type *DstTy,
1795 bool OnlyIfReduced) {
1796 assert(CastInst::castIsValid(Instruction::BitCast, C, DstTy) &&
1797 "Invalid constantexpr bitcast!");
1799 // It is common to ask for a bitcast of a value to its own type, handle this
1800 // speedily.
1801 if (C->getType() == DstTy) return C;
1803 return getFoldedCast(Instruction::BitCast, C, DstTy, OnlyIfReduced);
1806 Constant *ConstantExpr::getAddrSpaceCast(Constant *C, Type *DstTy,
1807 bool OnlyIfReduced) {
1808 assert(CastInst::castIsValid(Instruction::AddrSpaceCast, C, DstTy) &&
1809 "Invalid constantexpr addrspacecast!");
1811 // Canonicalize addrspacecasts between different pointer types by first
1812 // bitcasting the pointer type and then converting the address space.
1813 PointerType *SrcScalarTy = cast<PointerType>(C->getType()->getScalarType());
1814 PointerType *DstScalarTy = cast<PointerType>(DstTy->getScalarType());
1815 Type *DstElemTy = DstScalarTy->getElementType();
1816 if (SrcScalarTy->getElementType() != DstElemTy) {
1817 Type *MidTy = PointerType::get(DstElemTy, SrcScalarTy->getAddressSpace());
1818 if (VectorType *VT = dyn_cast<VectorType>(DstTy)) {
1819 // Handle vectors of pointers.
1820 MidTy = VectorType::get(MidTy, VT->getNumElements());
1822 C = getBitCast(C, MidTy);
1824 return getFoldedCast(Instruction::AddrSpaceCast, C, DstTy, OnlyIfReduced);
1827 Constant *ConstantExpr::get(unsigned Opcode, Constant *C, unsigned Flags,
1828 Type *OnlyIfReducedTy) {
1829 // Check the operands for consistency first.
1830 assert(Instruction::isUnaryOp(Opcode) &&
1831 "Invalid opcode in unary constant expression");
1833 #ifndef NDEBUG
1834 switch (Opcode) {
1835 case Instruction::FNeg:
1836 assert(C->getType()->isFPOrFPVectorTy() &&
1837 "Tried to create a floating-point operation on a "
1838 "non-floating-point type!");
1839 break;
1840 default:
1841 break;
1843 #endif
1845 if (Constant *FC = ConstantFoldUnaryInstruction(Opcode, C))
1846 return FC;
1848 if (OnlyIfReducedTy == C->getType())
1849 return nullptr;
1851 Constant *ArgVec[] = { C };
1852 ConstantExprKeyType Key(Opcode, ArgVec, 0, Flags);
1854 LLVMContextImpl *pImpl = C->getContext().pImpl;
1855 return pImpl->ExprConstants.getOrCreate(C->getType(), Key);
1858 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2,
1859 unsigned Flags, Type *OnlyIfReducedTy) {
1860 // Check the operands for consistency first.
1861 assert(Instruction::isBinaryOp(Opcode) &&
1862 "Invalid opcode in binary constant expression");
1863 assert(C1->getType() == C2->getType() &&
1864 "Operand types in binary constant expression should match");
1866 #ifndef NDEBUG
1867 switch (Opcode) {
1868 case Instruction::Add:
1869 case Instruction::Sub:
1870 case Instruction::Mul:
1871 case Instruction::UDiv:
1872 case Instruction::SDiv:
1873 case Instruction::URem:
1874 case Instruction::SRem:
1875 assert(C1->getType()->isIntOrIntVectorTy() &&
1876 "Tried to create an integer operation on a non-integer type!");
1877 break;
1878 case Instruction::FAdd:
1879 case Instruction::FSub:
1880 case Instruction::FMul:
1881 case Instruction::FDiv:
1882 case Instruction::FRem:
1883 assert(C1->getType()->isFPOrFPVectorTy() &&
1884 "Tried to create a floating-point operation on a "
1885 "non-floating-point type!");
1886 break;
1887 case Instruction::And:
1888 case Instruction::Or:
1889 case Instruction::Xor:
1890 assert(C1->getType()->isIntOrIntVectorTy() &&
1891 "Tried to create a logical operation on a non-integral type!");
1892 break;
1893 case Instruction::Shl:
1894 case Instruction::LShr:
1895 case Instruction::AShr:
1896 assert(C1->getType()->isIntOrIntVectorTy() &&
1897 "Tried to create a shift operation on a non-integer type!");
1898 break;
1899 default:
1900 break;
1902 #endif
1904 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1905 return FC;
1907 if (OnlyIfReducedTy == C1->getType())
1908 return nullptr;
1910 Constant *ArgVec[] = { C1, C2 };
1911 ConstantExprKeyType Key(Opcode, ArgVec, 0, Flags);
1913 LLVMContextImpl *pImpl = C1->getContext().pImpl;
1914 return pImpl->ExprConstants.getOrCreate(C1->getType(), Key);
1917 Constant *ConstantExpr::getSizeOf(Type* Ty) {
1918 // sizeof is implemented as: (i64) gep (Ty*)null, 1
1919 // Note that a non-inbounds gep is used, as null isn't within any object.
1920 Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
1921 Constant *GEP = getGetElementPtr(
1922 Ty, Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
1923 return getPtrToInt(GEP,
1924 Type::getInt64Ty(Ty->getContext()));
1927 Constant *ConstantExpr::getAlignOf(Type* Ty) {
1928 // alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1
1929 // Note that a non-inbounds gep is used, as null isn't within any object.
1930 Type *AligningTy = StructType::get(Type::getInt1Ty(Ty->getContext()), Ty);
1931 Constant *NullPtr = Constant::getNullValue(AligningTy->getPointerTo(0));
1932 Constant *Zero = ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0);
1933 Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
1934 Constant *Indices[2] = { Zero, One };
1935 Constant *GEP = getGetElementPtr(AligningTy, NullPtr, Indices);
1936 return getPtrToInt(GEP,
1937 Type::getInt64Ty(Ty->getContext()));
1940 Constant *ConstantExpr::getOffsetOf(StructType* STy, unsigned FieldNo) {
1941 return getOffsetOf(STy, ConstantInt::get(Type::getInt32Ty(STy->getContext()),
1942 FieldNo));
1945 Constant *ConstantExpr::getOffsetOf(Type* Ty, Constant *FieldNo) {
1946 // offsetof is implemented as: (i64) gep (Ty*)null, 0, FieldNo
1947 // Note that a non-inbounds gep is used, as null isn't within any object.
1948 Constant *GEPIdx[] = {
1949 ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0),
1950 FieldNo
1952 Constant *GEP = getGetElementPtr(
1953 Ty, Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
1954 return getPtrToInt(GEP,
1955 Type::getInt64Ty(Ty->getContext()));
1958 Constant *ConstantExpr::getCompare(unsigned short Predicate, Constant *C1,
1959 Constant *C2, bool OnlyIfReduced) {
1960 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1962 switch (Predicate) {
1963 default: llvm_unreachable("Invalid CmpInst predicate");
1964 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
1965 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
1966 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
1967 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
1968 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
1969 case CmpInst::FCMP_TRUE:
1970 return getFCmp(Predicate, C1, C2, OnlyIfReduced);
1972 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
1973 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
1974 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
1975 case CmpInst::ICMP_SLE:
1976 return getICmp(Predicate, C1, C2, OnlyIfReduced);
1980 Constant *ConstantExpr::getSelect(Constant *C, Constant *V1, Constant *V2,
1981 Type *OnlyIfReducedTy) {
1982 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
1984 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1985 return SC; // Fold common cases
1987 if (OnlyIfReducedTy == V1->getType())
1988 return nullptr;
1990 Constant *ArgVec[] = { C, V1, V2 };
1991 ConstantExprKeyType Key(Instruction::Select, ArgVec);
1993 LLVMContextImpl *pImpl = C->getContext().pImpl;
1994 return pImpl->ExprConstants.getOrCreate(V1->getType(), Key);
1997 Constant *ConstantExpr::getGetElementPtr(Type *Ty, Constant *C,
1998 ArrayRef<Value *> Idxs, bool InBounds,
1999 Optional<unsigned> InRangeIndex,
2000 Type *OnlyIfReducedTy) {
2001 if (!Ty)
2002 Ty = cast<PointerType>(C->getType()->getScalarType())->getElementType();
2003 else
2004 assert(Ty ==
2005 cast<PointerType>(C->getType()->getScalarType())->getElementType());
2007 if (Constant *FC =
2008 ConstantFoldGetElementPtr(Ty, C, InBounds, InRangeIndex, Idxs))
2009 return FC; // Fold a few common cases.
2011 // Get the result type of the getelementptr!
2012 Type *DestTy = GetElementPtrInst::getIndexedType(Ty, Idxs);
2013 assert(DestTy && "GEP indices invalid!");
2014 unsigned AS = C->getType()->getPointerAddressSpace();
2015 Type *ReqTy = DestTy->getPointerTo(AS);
2017 unsigned NumVecElts = 0;
2018 if (C->getType()->isVectorTy())
2019 NumVecElts = C->getType()->getVectorNumElements();
2020 else for (auto Idx : Idxs)
2021 if (Idx->getType()->isVectorTy())
2022 NumVecElts = Idx->getType()->getVectorNumElements();
2024 if (NumVecElts)
2025 ReqTy = VectorType::get(ReqTy, NumVecElts);
2027 if (OnlyIfReducedTy == ReqTy)
2028 return nullptr;
2030 // Look up the constant in the table first to ensure uniqueness
2031 std::vector<Constant*> ArgVec;
2032 ArgVec.reserve(1 + Idxs.size());
2033 ArgVec.push_back(C);
2034 for (unsigned i = 0, e = Idxs.size(); i != e; ++i) {
2035 assert((!Idxs[i]->getType()->isVectorTy() ||
2036 Idxs[i]->getType()->getVectorNumElements() == NumVecElts) &&
2037 "getelementptr index type missmatch");
2039 Constant *Idx = cast<Constant>(Idxs[i]);
2040 if (NumVecElts && !Idxs[i]->getType()->isVectorTy())
2041 Idx = ConstantVector::getSplat(NumVecElts, Idx);
2042 ArgVec.push_back(Idx);
2045 unsigned SubClassOptionalData = InBounds ? GEPOperator::IsInBounds : 0;
2046 if (InRangeIndex && *InRangeIndex < 63)
2047 SubClassOptionalData |= (*InRangeIndex + 1) << 1;
2048 const ConstantExprKeyType Key(Instruction::GetElementPtr, ArgVec, 0,
2049 SubClassOptionalData, None, Ty);
2051 LLVMContextImpl *pImpl = C->getContext().pImpl;
2052 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2055 Constant *ConstantExpr::getICmp(unsigned short pred, Constant *LHS,
2056 Constant *RHS, bool OnlyIfReduced) {
2057 assert(LHS->getType() == RHS->getType());
2058 assert(CmpInst::isIntPredicate((CmpInst::Predicate)pred) &&
2059 "Invalid ICmp Predicate");
2061 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
2062 return FC; // Fold a few common cases...
2064 if (OnlyIfReduced)
2065 return nullptr;
2067 // Look up the constant in the table first to ensure uniqueness
2068 Constant *ArgVec[] = { LHS, RHS };
2069 // Get the key type with both the opcode and predicate
2070 const ConstantExprKeyType Key(Instruction::ICmp, ArgVec, pred);
2072 Type *ResultTy = Type::getInt1Ty(LHS->getContext());
2073 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
2074 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
2076 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
2077 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
2080 Constant *ConstantExpr::getFCmp(unsigned short pred, Constant *LHS,
2081 Constant *RHS, bool OnlyIfReduced) {
2082 assert(LHS->getType() == RHS->getType());
2083 assert(CmpInst::isFPPredicate((CmpInst::Predicate)pred) &&
2084 "Invalid FCmp Predicate");
2086 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
2087 return FC; // Fold a few common cases...
2089 if (OnlyIfReduced)
2090 return nullptr;
2092 // Look up the constant in the table first to ensure uniqueness
2093 Constant *ArgVec[] = { LHS, RHS };
2094 // Get the key type with both the opcode and predicate
2095 const ConstantExprKeyType Key(Instruction::FCmp, ArgVec, pred);
2097 Type *ResultTy = Type::getInt1Ty(LHS->getContext());
2098 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
2099 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
2101 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
2102 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
2105 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx,
2106 Type *OnlyIfReducedTy) {
2107 assert(Val->getType()->isVectorTy() &&
2108 "Tried to create extractelement operation on non-vector type!");
2109 assert(Idx->getType()->isIntegerTy() &&
2110 "Extractelement index must be an integer type!");
2112 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
2113 return FC; // Fold a few common cases.
2115 Type *ReqTy = Val->getType()->getVectorElementType();
2116 if (OnlyIfReducedTy == ReqTy)
2117 return nullptr;
2119 // Look up the constant in the table first to ensure uniqueness
2120 Constant *ArgVec[] = { Val, Idx };
2121 const ConstantExprKeyType Key(Instruction::ExtractElement, ArgVec);
2123 LLVMContextImpl *pImpl = Val->getContext().pImpl;
2124 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2127 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
2128 Constant *Idx, Type *OnlyIfReducedTy) {
2129 assert(Val->getType()->isVectorTy() &&
2130 "Tried to create insertelement operation on non-vector type!");
2131 assert(Elt->getType() == Val->getType()->getVectorElementType() &&
2132 "Insertelement types must match!");
2133 assert(Idx->getType()->isIntegerTy() &&
2134 "Insertelement index must be i32 type!");
2136 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
2137 return FC; // Fold a few common cases.
2139 if (OnlyIfReducedTy == Val->getType())
2140 return nullptr;
2142 // Look up the constant in the table first to ensure uniqueness
2143 Constant *ArgVec[] = { Val, Elt, Idx };
2144 const ConstantExprKeyType Key(Instruction::InsertElement, ArgVec);
2146 LLVMContextImpl *pImpl = Val->getContext().pImpl;
2147 return pImpl->ExprConstants.getOrCreate(Val->getType(), Key);
2150 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
2151 Constant *Mask, Type *OnlyIfReducedTy) {
2152 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
2153 "Invalid shuffle vector constant expr operands!");
2155 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
2156 return FC; // Fold a few common cases.
2158 unsigned NElts = Mask->getType()->getVectorNumElements();
2159 Type *EltTy = V1->getType()->getVectorElementType();
2160 Type *ShufTy = VectorType::get(EltTy, NElts);
2162 if (OnlyIfReducedTy == ShufTy)
2163 return nullptr;
2165 // Look up the constant in the table first to ensure uniqueness
2166 Constant *ArgVec[] = { V1, V2, Mask };
2167 const ConstantExprKeyType Key(Instruction::ShuffleVector, ArgVec);
2169 LLVMContextImpl *pImpl = ShufTy->getContext().pImpl;
2170 return pImpl->ExprConstants.getOrCreate(ShufTy, Key);
2173 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
2174 ArrayRef<unsigned> Idxs,
2175 Type *OnlyIfReducedTy) {
2176 assert(Agg->getType()->isFirstClassType() &&
2177 "Non-first-class type for constant insertvalue expression");
2179 assert(ExtractValueInst::getIndexedType(Agg->getType(),
2180 Idxs) == Val->getType() &&
2181 "insertvalue indices invalid!");
2182 Type *ReqTy = Val->getType();
2184 if (Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs))
2185 return FC;
2187 if (OnlyIfReducedTy == ReqTy)
2188 return nullptr;
2190 Constant *ArgVec[] = { Agg, Val };
2191 const ConstantExprKeyType Key(Instruction::InsertValue, ArgVec, 0, 0, Idxs);
2193 LLVMContextImpl *pImpl = Agg->getContext().pImpl;
2194 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2197 Constant *ConstantExpr::getExtractValue(Constant *Agg, ArrayRef<unsigned> Idxs,
2198 Type *OnlyIfReducedTy) {
2199 assert(Agg->getType()->isFirstClassType() &&
2200 "Tried to create extractelement operation on non-first-class type!");
2202 Type *ReqTy = ExtractValueInst::getIndexedType(Agg->getType(), Idxs);
2203 (void)ReqTy;
2204 assert(ReqTy && "extractvalue indices invalid!");
2206 assert(Agg->getType()->isFirstClassType() &&
2207 "Non-first-class type for constant extractvalue expression");
2208 if (Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs))
2209 return FC;
2211 if (OnlyIfReducedTy == ReqTy)
2212 return nullptr;
2214 Constant *ArgVec[] = { Agg };
2215 const ConstantExprKeyType Key(Instruction::ExtractValue, ArgVec, 0, 0, Idxs);
2217 LLVMContextImpl *pImpl = Agg->getContext().pImpl;
2218 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2221 Constant *ConstantExpr::getNeg(Constant *C, bool HasNUW, bool HasNSW) {
2222 assert(C->getType()->isIntOrIntVectorTy() &&
2223 "Cannot NEG a nonintegral value!");
2224 return getSub(ConstantFP::getZeroValueForNegation(C->getType()),
2225 C, HasNUW, HasNSW);
2228 Constant *ConstantExpr::getFNeg(Constant *C) {
2229 assert(C->getType()->isFPOrFPVectorTy() &&
2230 "Cannot FNEG a non-floating-point value!");
2231 return get(Instruction::FNeg, C);
2234 Constant *ConstantExpr::getNot(Constant *C) {
2235 assert(C->getType()->isIntOrIntVectorTy() &&
2236 "Cannot NOT a nonintegral value!");
2237 return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
2240 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2,
2241 bool HasNUW, bool HasNSW) {
2242 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2243 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2244 return get(Instruction::Add, C1, C2, Flags);
2247 Constant *ConstantExpr::getFAdd(Constant *C1, Constant *C2) {
2248 return get(Instruction::FAdd, C1, C2);
2251 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2,
2252 bool HasNUW, bool HasNSW) {
2253 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2254 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2255 return get(Instruction::Sub, C1, C2, Flags);
2258 Constant *ConstantExpr::getFSub(Constant *C1, Constant *C2) {
2259 return get(Instruction::FSub, C1, C2);
2262 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2,
2263 bool HasNUW, bool HasNSW) {
2264 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2265 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2266 return get(Instruction::Mul, C1, C2, Flags);
2269 Constant *ConstantExpr::getFMul(Constant *C1, Constant *C2) {
2270 return get(Instruction::FMul, C1, C2);
2273 Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2, bool isExact) {
2274 return get(Instruction::UDiv, C1, C2,
2275 isExact ? PossiblyExactOperator::IsExact : 0);
2278 Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2, bool isExact) {
2279 return get(Instruction::SDiv, C1, C2,
2280 isExact ? PossiblyExactOperator::IsExact : 0);
2283 Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
2284 return get(Instruction::FDiv, C1, C2);
2287 Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
2288 return get(Instruction::URem, C1, C2);
2291 Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
2292 return get(Instruction::SRem, C1, C2);
2295 Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
2296 return get(Instruction::FRem, C1, C2);
2299 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
2300 return get(Instruction::And, C1, C2);
2303 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
2304 return get(Instruction::Or, C1, C2);
2307 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
2308 return get(Instruction::Xor, C1, C2);
2311 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2,
2312 bool HasNUW, bool HasNSW) {
2313 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2314 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2315 return get(Instruction::Shl, C1, C2, Flags);
2318 Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2, bool isExact) {
2319 return get(Instruction::LShr, C1, C2,
2320 isExact ? PossiblyExactOperator::IsExact : 0);
2323 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2, bool isExact) {
2324 return get(Instruction::AShr, C1, C2,
2325 isExact ? PossiblyExactOperator::IsExact : 0);
2328 Constant *ConstantExpr::getBinOpIdentity(unsigned Opcode, Type *Ty,
2329 bool AllowRHSConstant) {
2330 assert(Instruction::isBinaryOp(Opcode) && "Only binops allowed");
2332 // Commutative opcodes: it does not matter if AllowRHSConstant is set.
2333 if (Instruction::isCommutative(Opcode)) {
2334 switch (Opcode) {
2335 case Instruction::Add: // X + 0 = X
2336 case Instruction::Or: // X | 0 = X
2337 case Instruction::Xor: // X ^ 0 = X
2338 return Constant::getNullValue(Ty);
2339 case Instruction::Mul: // X * 1 = X
2340 return ConstantInt::get(Ty, 1);
2341 case Instruction::And: // X & -1 = X
2342 return Constant::getAllOnesValue(Ty);
2343 case Instruction::FAdd: // X + -0.0 = X
2344 // TODO: If the fadd has 'nsz', should we return +0.0?
2345 return ConstantFP::getNegativeZero(Ty);
2346 case Instruction::FMul: // X * 1.0 = X
2347 return ConstantFP::get(Ty, 1.0);
2348 default:
2349 llvm_unreachable("Every commutative binop has an identity constant");
2353 // Non-commutative opcodes: AllowRHSConstant must be set.
2354 if (!AllowRHSConstant)
2355 return nullptr;
2357 switch (Opcode) {
2358 case Instruction::Sub: // X - 0 = X
2359 case Instruction::Shl: // X << 0 = X
2360 case Instruction::LShr: // X >>u 0 = X
2361 case Instruction::AShr: // X >> 0 = X
2362 case Instruction::FSub: // X - 0.0 = X
2363 return Constant::getNullValue(Ty);
2364 case Instruction::SDiv: // X / 1 = X
2365 case Instruction::UDiv: // X /u 1 = X
2366 return ConstantInt::get(Ty, 1);
2367 case Instruction::FDiv: // X / 1.0 = X
2368 return ConstantFP::get(Ty, 1.0);
2369 default:
2370 return nullptr;
2374 Constant *ConstantExpr::getBinOpAbsorber(unsigned Opcode, Type *Ty) {
2375 switch (Opcode) {
2376 default:
2377 // Doesn't have an absorber.
2378 return nullptr;
2380 case Instruction::Or:
2381 return Constant::getAllOnesValue(Ty);
2383 case Instruction::And:
2384 case Instruction::Mul:
2385 return Constant::getNullValue(Ty);
2389 /// Remove the constant from the constant table.
2390 void ConstantExpr::destroyConstantImpl() {
2391 getType()->getContext().pImpl->ExprConstants.remove(this);
2394 const char *ConstantExpr::getOpcodeName() const {
2395 return Instruction::getOpcodeName(getOpcode());
2398 GetElementPtrConstantExpr::GetElementPtrConstantExpr(
2399 Type *SrcElementTy, Constant *C, ArrayRef<Constant *> IdxList, Type *DestTy)
2400 : ConstantExpr(DestTy, Instruction::GetElementPtr,
2401 OperandTraits<GetElementPtrConstantExpr>::op_end(this) -
2402 (IdxList.size() + 1),
2403 IdxList.size() + 1),
2404 SrcElementTy(SrcElementTy),
2405 ResElementTy(GetElementPtrInst::getIndexedType(SrcElementTy, IdxList)) {
2406 Op<0>() = C;
2407 Use *OperandList = getOperandList();
2408 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
2409 OperandList[i+1] = IdxList[i];
2412 Type *GetElementPtrConstantExpr::getSourceElementType() const {
2413 return SrcElementTy;
2416 Type *GetElementPtrConstantExpr::getResultElementType() const {
2417 return ResElementTy;
2420 //===----------------------------------------------------------------------===//
2421 // ConstantData* implementations
2423 Type *ConstantDataSequential::getElementType() const {
2424 return getType()->getElementType();
2427 StringRef ConstantDataSequential::getRawDataValues() const {
2428 return StringRef(DataElements, getNumElements()*getElementByteSize());
2431 bool ConstantDataSequential::isElementTypeCompatible(Type *Ty) {
2432 if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) return true;
2433 if (auto *IT = dyn_cast<IntegerType>(Ty)) {
2434 switch (IT->getBitWidth()) {
2435 case 8:
2436 case 16:
2437 case 32:
2438 case 64:
2439 return true;
2440 default: break;
2443 return false;
2446 unsigned ConstantDataSequential::getNumElements() const {
2447 if (ArrayType *AT = dyn_cast<ArrayType>(getType()))
2448 return AT->getNumElements();
2449 return getType()->getVectorNumElements();
2453 uint64_t ConstantDataSequential::getElementByteSize() const {
2454 return getElementType()->getPrimitiveSizeInBits()/8;
2457 /// Return the start of the specified element.
2458 const char *ConstantDataSequential::getElementPointer(unsigned Elt) const {
2459 assert(Elt < getNumElements() && "Invalid Elt");
2460 return DataElements+Elt*getElementByteSize();
2464 /// Return true if the array is empty or all zeros.
2465 static bool isAllZeros(StringRef Arr) {
2466 for (char I : Arr)
2467 if (I != 0)
2468 return false;
2469 return true;
2472 /// This is the underlying implementation of all of the
2473 /// ConstantDataSequential::get methods. They all thunk down to here, providing
2474 /// the correct element type. We take the bytes in as a StringRef because
2475 /// we *want* an underlying "char*" to avoid TBAA type punning violations.
2476 Constant *ConstantDataSequential::getImpl(StringRef Elements, Type *Ty) {
2477 assert(isElementTypeCompatible(Ty->getSequentialElementType()));
2478 // If the elements are all zero or there are no elements, return a CAZ, which
2479 // is more dense and canonical.
2480 if (isAllZeros(Elements))
2481 return ConstantAggregateZero::get(Ty);
2483 // Do a lookup to see if we have already formed one of these.
2484 auto &Slot =
2485 *Ty->getContext()
2486 .pImpl->CDSConstants.insert(std::make_pair(Elements, nullptr))
2487 .first;
2489 // The bucket can point to a linked list of different CDS's that have the same
2490 // body but different types. For example, 0,0,0,1 could be a 4 element array
2491 // of i8, or a 1-element array of i32. They'll both end up in the same
2492 /// StringMap bucket, linked up by their Next pointers. Walk the list.
2493 ConstantDataSequential **Entry = &Slot.second;
2494 for (ConstantDataSequential *Node = *Entry; Node;
2495 Entry = &Node->Next, Node = *Entry)
2496 if (Node->getType() == Ty)
2497 return Node;
2499 // Okay, we didn't get a hit. Create a node of the right class, link it in,
2500 // and return it.
2501 if (isa<ArrayType>(Ty))
2502 return *Entry = new ConstantDataArray(Ty, Slot.first().data());
2504 assert(isa<VectorType>(Ty));
2505 return *Entry = new ConstantDataVector(Ty, Slot.first().data());
2508 void ConstantDataSequential::destroyConstantImpl() {
2509 // Remove the constant from the StringMap.
2510 StringMap<ConstantDataSequential*> &CDSConstants =
2511 getType()->getContext().pImpl->CDSConstants;
2513 StringMap<ConstantDataSequential*>::iterator Slot =
2514 CDSConstants.find(getRawDataValues());
2516 assert(Slot != CDSConstants.end() && "CDS not found in uniquing table");
2518 ConstantDataSequential **Entry = &Slot->getValue();
2520 // Remove the entry from the hash table.
2521 if (!(*Entry)->Next) {
2522 // If there is only one value in the bucket (common case) it must be this
2523 // entry, and removing the entry should remove the bucket completely.
2524 assert((*Entry) == this && "Hash mismatch in ConstantDataSequential");
2525 getContext().pImpl->CDSConstants.erase(Slot);
2526 } else {
2527 // Otherwise, there are multiple entries linked off the bucket, unlink the
2528 // node we care about but keep the bucket around.
2529 for (ConstantDataSequential *Node = *Entry; ;
2530 Entry = &Node->Next, Node = *Entry) {
2531 assert(Node && "Didn't find entry in its uniquing hash table!");
2532 // If we found our entry, unlink it from the list and we're done.
2533 if (Node == this) {
2534 *Entry = Node->Next;
2535 break;
2540 // If we were part of a list, make sure that we don't delete the list that is
2541 // still owned by the uniquing map.
2542 Next = nullptr;
2545 /// getFP() constructors - Return a constant with array type with an element
2546 /// count and element type of float with precision matching the number of
2547 /// bits in the ArrayRef passed in. (i.e. half for 16bits, float for 32bits,
2548 /// double for 64bits) Note that this can return a ConstantAggregateZero
2549 /// object.
2550 Constant *ConstantDataArray::getFP(LLVMContext &Context,
2551 ArrayRef<uint16_t> Elts) {
2552 Type *Ty = ArrayType::get(Type::getHalfTy(Context), Elts.size());
2553 const char *Data = reinterpret_cast<const char *>(Elts.data());
2554 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
2556 Constant *ConstantDataArray::getFP(LLVMContext &Context,
2557 ArrayRef<uint32_t> Elts) {
2558 Type *Ty = ArrayType::get(Type::getFloatTy(Context), Elts.size());
2559 const char *Data = reinterpret_cast<const char *>(Elts.data());
2560 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
2562 Constant *ConstantDataArray::getFP(LLVMContext &Context,
2563 ArrayRef<uint64_t> Elts) {
2564 Type *Ty = ArrayType::get(Type::getDoubleTy(Context), Elts.size());
2565 const char *Data = reinterpret_cast<const char *>(Elts.data());
2566 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
2569 Constant *ConstantDataArray::getString(LLVMContext &Context,
2570 StringRef Str, bool AddNull) {
2571 if (!AddNull) {
2572 const uint8_t *Data = Str.bytes_begin();
2573 return get(Context, makeArrayRef(Data, Str.size()));
2576 SmallVector<uint8_t, 64> ElementVals;
2577 ElementVals.append(Str.begin(), Str.end());
2578 ElementVals.push_back(0);
2579 return get(Context, ElementVals);
2582 /// get() constructors - Return a constant with vector type with an element
2583 /// count and element type matching the ArrayRef passed in. Note that this
2584 /// can return a ConstantAggregateZero object.
2585 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint8_t> Elts){
2586 Type *Ty = VectorType::get(Type::getInt8Ty(Context), Elts.size());
2587 const char *Data = reinterpret_cast<const char *>(Elts.data());
2588 return getImpl(StringRef(Data, Elts.size() * 1), Ty);
2590 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint16_t> Elts){
2591 Type *Ty = VectorType::get(Type::getInt16Ty(Context), Elts.size());
2592 const char *Data = reinterpret_cast<const char *>(Elts.data());
2593 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
2595 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint32_t> Elts){
2596 Type *Ty = VectorType::get(Type::getInt32Ty(Context), Elts.size());
2597 const char *Data = reinterpret_cast<const char *>(Elts.data());
2598 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
2600 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint64_t> Elts){
2601 Type *Ty = VectorType::get(Type::getInt64Ty(Context), Elts.size());
2602 const char *Data = reinterpret_cast<const char *>(Elts.data());
2603 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
2605 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<float> Elts) {
2606 Type *Ty = VectorType::get(Type::getFloatTy(Context), Elts.size());
2607 const char *Data = reinterpret_cast<const char *>(Elts.data());
2608 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
2610 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<double> Elts) {
2611 Type *Ty = VectorType::get(Type::getDoubleTy(Context), Elts.size());
2612 const char *Data = reinterpret_cast<const char *>(Elts.data());
2613 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
2616 /// getFP() constructors - Return a constant with vector type with an element
2617 /// count and element type of float with the precision matching the number of
2618 /// bits in the ArrayRef passed in. (i.e. half for 16bits, float for 32bits,
2619 /// double for 64bits) Note that this can return a ConstantAggregateZero
2620 /// object.
2621 Constant *ConstantDataVector::getFP(LLVMContext &Context,
2622 ArrayRef<uint16_t> Elts) {
2623 Type *Ty = VectorType::get(Type::getHalfTy(Context), Elts.size());
2624 const char *Data = reinterpret_cast<const char *>(Elts.data());
2625 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
2627 Constant *ConstantDataVector::getFP(LLVMContext &Context,
2628 ArrayRef<uint32_t> Elts) {
2629 Type *Ty = VectorType::get(Type::getFloatTy(Context), Elts.size());
2630 const char *Data = reinterpret_cast<const char *>(Elts.data());
2631 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
2633 Constant *ConstantDataVector::getFP(LLVMContext &Context,
2634 ArrayRef<uint64_t> Elts) {
2635 Type *Ty = VectorType::get(Type::getDoubleTy(Context), Elts.size());
2636 const char *Data = reinterpret_cast<const char *>(Elts.data());
2637 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
2640 Constant *ConstantDataVector::getSplat(unsigned NumElts, Constant *V) {
2641 assert(isElementTypeCompatible(V->getType()) &&
2642 "Element type not compatible with ConstantData");
2643 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
2644 if (CI->getType()->isIntegerTy(8)) {
2645 SmallVector<uint8_t, 16> Elts(NumElts, CI->getZExtValue());
2646 return get(V->getContext(), Elts);
2648 if (CI->getType()->isIntegerTy(16)) {
2649 SmallVector<uint16_t, 16> Elts(NumElts, CI->getZExtValue());
2650 return get(V->getContext(), Elts);
2652 if (CI->getType()->isIntegerTy(32)) {
2653 SmallVector<uint32_t, 16> Elts(NumElts, CI->getZExtValue());
2654 return get(V->getContext(), Elts);
2656 assert(CI->getType()->isIntegerTy(64) && "Unsupported ConstantData type");
2657 SmallVector<uint64_t, 16> Elts(NumElts, CI->getZExtValue());
2658 return get(V->getContext(), Elts);
2661 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
2662 if (CFP->getType()->isHalfTy()) {
2663 SmallVector<uint16_t, 16> Elts(
2664 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
2665 return getFP(V->getContext(), Elts);
2667 if (CFP->getType()->isFloatTy()) {
2668 SmallVector<uint32_t, 16> Elts(
2669 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
2670 return getFP(V->getContext(), Elts);
2672 if (CFP->getType()->isDoubleTy()) {
2673 SmallVector<uint64_t, 16> Elts(
2674 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
2675 return getFP(V->getContext(), Elts);
2678 return ConstantVector::getSplat(NumElts, V);
2682 uint64_t ConstantDataSequential::getElementAsInteger(unsigned Elt) const {
2683 assert(isa<IntegerType>(getElementType()) &&
2684 "Accessor can only be used when element is an integer");
2685 const char *EltPtr = getElementPointer(Elt);
2687 // The data is stored in host byte order, make sure to cast back to the right
2688 // type to load with the right endianness.
2689 switch (getElementType()->getIntegerBitWidth()) {
2690 default: llvm_unreachable("Invalid bitwidth for CDS");
2691 case 8:
2692 return *reinterpret_cast<const uint8_t *>(EltPtr);
2693 case 16:
2694 return *reinterpret_cast<const uint16_t *>(EltPtr);
2695 case 32:
2696 return *reinterpret_cast<const uint32_t *>(EltPtr);
2697 case 64:
2698 return *reinterpret_cast<const uint64_t *>(EltPtr);
2702 APInt ConstantDataSequential::getElementAsAPInt(unsigned Elt) const {
2703 assert(isa<IntegerType>(getElementType()) &&
2704 "Accessor can only be used when element is an integer");
2705 const char *EltPtr = getElementPointer(Elt);
2707 // The data is stored in host byte order, make sure to cast back to the right
2708 // type to load with the right endianness.
2709 switch (getElementType()->getIntegerBitWidth()) {
2710 default: llvm_unreachable("Invalid bitwidth for CDS");
2711 case 8: {
2712 auto EltVal = *reinterpret_cast<const uint8_t *>(EltPtr);
2713 return APInt(8, EltVal);
2715 case 16: {
2716 auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
2717 return APInt(16, EltVal);
2719 case 32: {
2720 auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr);
2721 return APInt(32, EltVal);
2723 case 64: {
2724 auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr);
2725 return APInt(64, EltVal);
2730 APFloat ConstantDataSequential::getElementAsAPFloat(unsigned Elt) const {
2731 const char *EltPtr = getElementPointer(Elt);
2733 switch (getElementType()->getTypeID()) {
2734 default:
2735 llvm_unreachable("Accessor can only be used when element is float/double!");
2736 case Type::HalfTyID: {
2737 auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
2738 return APFloat(APFloat::IEEEhalf(), APInt(16, EltVal));
2740 case Type::FloatTyID: {
2741 auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr);
2742 return APFloat(APFloat::IEEEsingle(), APInt(32, EltVal));
2744 case Type::DoubleTyID: {
2745 auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr);
2746 return APFloat(APFloat::IEEEdouble(), APInt(64, EltVal));
2751 float ConstantDataSequential::getElementAsFloat(unsigned Elt) const {
2752 assert(getElementType()->isFloatTy() &&
2753 "Accessor can only be used when element is a 'float'");
2754 return *reinterpret_cast<const float *>(getElementPointer(Elt));
2757 double ConstantDataSequential::getElementAsDouble(unsigned Elt) const {
2758 assert(getElementType()->isDoubleTy() &&
2759 "Accessor can only be used when element is a 'float'");
2760 return *reinterpret_cast<const double *>(getElementPointer(Elt));
2763 Constant *ConstantDataSequential::getElementAsConstant(unsigned Elt) const {
2764 if (getElementType()->isHalfTy() || getElementType()->isFloatTy() ||
2765 getElementType()->isDoubleTy())
2766 return ConstantFP::get(getContext(), getElementAsAPFloat(Elt));
2768 return ConstantInt::get(getElementType(), getElementAsInteger(Elt));
2771 bool ConstantDataSequential::isString(unsigned CharSize) const {
2772 return isa<ArrayType>(getType()) && getElementType()->isIntegerTy(CharSize);
2775 bool ConstantDataSequential::isCString() const {
2776 if (!isString())
2777 return false;
2779 StringRef Str = getAsString();
2781 // The last value must be nul.
2782 if (Str.back() != 0) return false;
2784 // Other elements must be non-nul.
2785 return Str.drop_back().find(0) == StringRef::npos;
2788 bool ConstantDataVector::isSplat() const {
2789 const char *Base = getRawDataValues().data();
2791 // Compare elements 1+ to the 0'th element.
2792 unsigned EltSize = getElementByteSize();
2793 for (unsigned i = 1, e = getNumElements(); i != e; ++i)
2794 if (memcmp(Base, Base+i*EltSize, EltSize))
2795 return false;
2797 return true;
2800 Constant *ConstantDataVector::getSplatValue() const {
2801 // If they're all the same, return the 0th one as a representative.
2802 return isSplat() ? getElementAsConstant(0) : nullptr;
2805 //===----------------------------------------------------------------------===//
2806 // handleOperandChange implementations
2808 /// Update this constant array to change uses of
2809 /// 'From' to be uses of 'To'. This must update the uniquing data structures
2810 /// etc.
2812 /// Note that we intentionally replace all uses of From with To here. Consider
2813 /// a large array that uses 'From' 1000 times. By handling this case all here,
2814 /// ConstantArray::handleOperandChange is only invoked once, and that
2815 /// single invocation handles all 1000 uses. Handling them one at a time would
2816 /// work, but would be really slow because it would have to unique each updated
2817 /// array instance.
2819 void Constant::handleOperandChange(Value *From, Value *To) {
2820 Value *Replacement = nullptr;
2821 switch (getValueID()) {
2822 default:
2823 llvm_unreachable("Not a constant!");
2824 #define HANDLE_CONSTANT(Name) \
2825 case Value::Name##Val: \
2826 Replacement = cast<Name>(this)->handleOperandChangeImpl(From, To); \
2827 break;
2828 #include "llvm/IR/Value.def"
2831 // If handleOperandChangeImpl returned nullptr, then it handled
2832 // replacing itself and we don't want to delete or replace anything else here.
2833 if (!Replacement)
2834 return;
2836 // I do need to replace this with an existing value.
2837 assert(Replacement != this && "I didn't contain From!");
2839 // Everyone using this now uses the replacement.
2840 replaceAllUsesWith(Replacement);
2842 // Delete the old constant!
2843 destroyConstant();
2846 Value *ConstantArray::handleOperandChangeImpl(Value *From, Value *To) {
2847 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2848 Constant *ToC = cast<Constant>(To);
2850 SmallVector<Constant*, 8> Values;
2851 Values.reserve(getNumOperands()); // Build replacement array.
2853 // Fill values with the modified operands of the constant array. Also,
2854 // compute whether this turns into an all-zeros array.
2855 unsigned NumUpdated = 0;
2857 // Keep track of whether all the values in the array are "ToC".
2858 bool AllSame = true;
2859 Use *OperandList = getOperandList();
2860 unsigned OperandNo = 0;
2861 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2862 Constant *Val = cast<Constant>(O->get());
2863 if (Val == From) {
2864 OperandNo = (O - OperandList);
2865 Val = ToC;
2866 ++NumUpdated;
2868 Values.push_back(Val);
2869 AllSame &= Val == ToC;
2872 if (AllSame && ToC->isNullValue())
2873 return ConstantAggregateZero::get(getType());
2875 if (AllSame && isa<UndefValue>(ToC))
2876 return UndefValue::get(getType());
2878 // Check for any other type of constant-folding.
2879 if (Constant *C = getImpl(getType(), Values))
2880 return C;
2882 // Update to the new value.
2883 return getContext().pImpl->ArrayConstants.replaceOperandsInPlace(
2884 Values, this, From, ToC, NumUpdated, OperandNo);
2887 Value *ConstantStruct::handleOperandChangeImpl(Value *From, Value *To) {
2888 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2889 Constant *ToC = cast<Constant>(To);
2891 Use *OperandList = getOperandList();
2893 SmallVector<Constant*, 8> Values;
2894 Values.reserve(getNumOperands()); // Build replacement struct.
2896 // Fill values with the modified operands of the constant struct. Also,
2897 // compute whether this turns into an all-zeros struct.
2898 unsigned NumUpdated = 0;
2899 bool AllSame = true;
2900 unsigned OperandNo = 0;
2901 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O) {
2902 Constant *Val = cast<Constant>(O->get());
2903 if (Val == From) {
2904 OperandNo = (O - OperandList);
2905 Val = ToC;
2906 ++NumUpdated;
2908 Values.push_back(Val);
2909 AllSame &= Val == ToC;
2912 if (AllSame && ToC->isNullValue())
2913 return ConstantAggregateZero::get(getType());
2915 if (AllSame && isa<UndefValue>(ToC))
2916 return UndefValue::get(getType());
2918 // Update to the new value.
2919 return getContext().pImpl->StructConstants.replaceOperandsInPlace(
2920 Values, this, From, ToC, NumUpdated, OperandNo);
2923 Value *ConstantVector::handleOperandChangeImpl(Value *From, Value *To) {
2924 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2925 Constant *ToC = cast<Constant>(To);
2927 SmallVector<Constant*, 8> Values;
2928 Values.reserve(getNumOperands()); // Build replacement array...
2929 unsigned NumUpdated = 0;
2930 unsigned OperandNo = 0;
2931 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2932 Constant *Val = getOperand(i);
2933 if (Val == From) {
2934 OperandNo = i;
2935 ++NumUpdated;
2936 Val = ToC;
2938 Values.push_back(Val);
2941 if (Constant *C = getImpl(Values))
2942 return C;
2944 // Update to the new value.
2945 return getContext().pImpl->VectorConstants.replaceOperandsInPlace(
2946 Values, this, From, ToC, NumUpdated, OperandNo);
2949 Value *ConstantExpr::handleOperandChangeImpl(Value *From, Value *ToV) {
2950 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2951 Constant *To = cast<Constant>(ToV);
2953 SmallVector<Constant*, 8> NewOps;
2954 unsigned NumUpdated = 0;
2955 unsigned OperandNo = 0;
2956 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2957 Constant *Op = getOperand(i);
2958 if (Op == From) {
2959 OperandNo = i;
2960 ++NumUpdated;
2961 Op = To;
2963 NewOps.push_back(Op);
2965 assert(NumUpdated && "I didn't contain From!");
2967 if (Constant *C = getWithOperands(NewOps, getType(), true))
2968 return C;
2970 // Update to the new value.
2971 return getContext().pImpl->ExprConstants.replaceOperandsInPlace(
2972 NewOps, this, From, To, NumUpdated, OperandNo);
2975 Instruction *ConstantExpr::getAsInstruction() {
2976 SmallVector<Value *, 4> ValueOperands(op_begin(), op_end());
2977 ArrayRef<Value*> Ops(ValueOperands);
2979 switch (getOpcode()) {
2980 case Instruction::Trunc:
2981 case Instruction::ZExt:
2982 case Instruction::SExt:
2983 case Instruction::FPTrunc:
2984 case Instruction::FPExt:
2985 case Instruction::UIToFP:
2986 case Instruction::SIToFP:
2987 case Instruction::FPToUI:
2988 case Instruction::FPToSI:
2989 case Instruction::PtrToInt:
2990 case Instruction::IntToPtr:
2991 case Instruction::BitCast:
2992 case Instruction::AddrSpaceCast:
2993 return CastInst::Create((Instruction::CastOps)getOpcode(),
2994 Ops[0], getType());
2995 case Instruction::Select:
2996 return SelectInst::Create(Ops[0], Ops[1], Ops[2]);
2997 case Instruction::InsertElement:
2998 return InsertElementInst::Create(Ops[0], Ops[1], Ops[2]);
2999 case Instruction::ExtractElement:
3000 return ExtractElementInst::Create(Ops[0], Ops[1]);
3001 case Instruction::InsertValue:
3002 return InsertValueInst::Create(Ops[0], Ops[1], getIndices());
3003 case Instruction::ExtractValue:
3004 return ExtractValueInst::Create(Ops[0], getIndices());
3005 case Instruction::ShuffleVector:
3006 return new ShuffleVectorInst(Ops[0], Ops[1], Ops[2]);
3008 case Instruction::GetElementPtr: {
3009 const auto *GO = cast<GEPOperator>(this);
3010 if (GO->isInBounds())
3011 return GetElementPtrInst::CreateInBounds(GO->getSourceElementType(),
3012 Ops[0], Ops.slice(1));
3013 return GetElementPtrInst::Create(GO->getSourceElementType(), Ops[0],
3014 Ops.slice(1));
3016 case Instruction::ICmp:
3017 case Instruction::FCmp:
3018 return CmpInst::Create((Instruction::OtherOps)getOpcode(),
3019 (CmpInst::Predicate)getPredicate(), Ops[0], Ops[1]);
3020 case Instruction::FNeg:
3021 return UnaryOperator::Create((Instruction::UnaryOps)getOpcode(), Ops[0]);
3022 default:
3023 assert(getNumOperands() == 2 && "Must be binary operator?");
3024 BinaryOperator *BO =
3025 BinaryOperator::Create((Instruction::BinaryOps)getOpcode(),
3026 Ops[0], Ops[1]);
3027 if (isa<OverflowingBinaryOperator>(BO)) {
3028 BO->setHasNoUnsignedWrap(SubclassOptionalData &
3029 OverflowingBinaryOperator::NoUnsignedWrap);
3030 BO->setHasNoSignedWrap(SubclassOptionalData &
3031 OverflowingBinaryOperator::NoSignedWrap);
3033 if (isa<PossiblyExactOperator>(BO))
3034 BO->setIsExact(SubclassOptionalData & PossiblyExactOperator::IsExact);
3035 return BO;