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.
10 //
11 //===----------------------------------------------------------------------===//
12 
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/BasicBlock.h"
20 #include "llvm/IR/DerivedTypes.h"
21 #include "llvm/IR/Function.h"
22 #include "llvm/IR/GetElementPtrTypeIterator.h"
23 #include "llvm/IR/GlobalAlias.h"
24 #include "llvm/IR/GlobalIFunc.h"
25 #include "llvm/IR/GlobalValue.h"
26 #include "llvm/IR/GlobalVariable.h"
27 #include "llvm/IR/Instructions.h"
28 #include "llvm/IR/Operator.h"
29 #include "llvm/IR/PatternMatch.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/MathExtras.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include <algorithm>
34 
35 using namespace llvm;
36 using namespace PatternMatch;
37 
38 //===----------------------------------------------------------------------===//
39 //                              Constant Class
40 //===----------------------------------------------------------------------===//
41 
42 bool Constant::isNegativeZeroValue() const {
43   // Floating point values have an explicit -0.0 value.
44   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
45     return CFP->isZero() && CFP->isNegative();
46 
47   // Equivalent for a vector of -0.0's.
48   if (getType()->isVectorTy())
49     if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))
50       return SplatCFP->isNegativeZeroValue();
51 
52   // We've already handled true FP case; any other FP vectors can't represent -0.0.
53   if (getType()->isFPOrFPVectorTy())
54     return false;
55 
56   // Otherwise, just use +0.0.
57   return isNullValue();
58 }
59 
60 // Return true iff this constant is positive zero (floating point), negative
61 // zero (floating point), or a null value.
62 bool Constant::isZeroValue() const {
63   // Floating point values have an explicit -0.0 value.
64   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
65     return CFP->isZero();
66 
67   // Check for constant splat vectors of 1 values.
68   if (getType()->isVectorTy())
69     if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))
70       return SplatCFP->isZero();
71 
72   // Otherwise, just use +0.0.
73   return isNullValue();
74 }
75 
76 bool Constant::isNullValue() const {
77   // 0 is null.
78   if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
79     return CI->isZero();
80 
81   // +0.0 is null.
82   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
83     // ppc_fp128 determine isZero using high order double only
84     // Should check the bitwise value to make sure all bits are zero.
85     return CFP->isExactlyValue(+0.0);
86 
87   // constant zero is zero for aggregates, cpnull is null for pointers, none for
88   // tokens.
89   return isa<ConstantAggregateZero>(this) || isa<ConstantPointerNull>(this) ||
90          isa<ConstantTokenNone>(this);
91 }
92 
93 bool Constant::isAllOnesValue() const {
94   // Check for -1 integers
95   if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
96     return CI->isMinusOne();
97 
98   // Check for FP which are bitcasted from -1 integers
99   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
100     return CFP->getValueAPF().bitcastToAPInt().isAllOnes();
101 
102   // Check for constant splat vectors of 1 values.
103   if (getType()->isVectorTy())
104     if (const auto *SplatVal = getSplatValue())
105       return SplatVal->isAllOnesValue();
106 
107   return false;
108 }
109 
110 bool Constant::isOneValue() const {
111   // Check for 1 integers
112   if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
113     return CI->isOne();
114 
115   // Check for FP which are bitcasted from 1 integers
116   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
117     return CFP->getValueAPF().bitcastToAPInt().isOne();
118 
119   // Check for constant splat vectors of 1 values.
120   if (getType()->isVectorTy())
121     if (const auto *SplatVal = getSplatValue())
122       return SplatVal->isOneValue();
123 
124   return false;
125 }
126 
127 bool Constant::isNotOneValue() const {
128   // Check for 1 integers
129   if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
130     return !CI->isOneValue();
131 
132   // Check for FP which are bitcasted from 1 integers
133   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
134     return !CFP->getValueAPF().bitcastToAPInt().isOne();
135 
136   // Check that vectors don't contain 1
137   if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
138     for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
139       Constant *Elt = getAggregateElement(I);
140       if (!Elt || !Elt->isNotOneValue())
141         return false;
142     }
143     return true;
144   }
145 
146   // Check for splats that don't contain 1
147   if (getType()->isVectorTy())
148     if (const auto *SplatVal = getSplatValue())
149       return SplatVal->isNotOneValue();
150 
151   // It *may* contain 1, we can't tell.
152   return false;
153 }
154 
155 bool Constant::isMinSignedValue() const {
156   // Check for INT_MIN integers
157   if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
158     return CI->isMinValue(/*isSigned=*/true);
159 
160   // Check for FP which are bitcasted from INT_MIN integers
161   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
162     return CFP->getValueAPF().bitcastToAPInt().isMinSignedValue();
163 
164   // Check for splats of INT_MIN values.
165   if (getType()->isVectorTy())
166     if (const auto *SplatVal = getSplatValue())
167       return SplatVal->isMinSignedValue();
168 
169   return false;
170 }
171 
172 bool Constant::isNotMinSignedValue() const {
173   // Check for INT_MIN integers
174   if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
175     return !CI->isMinValue(/*isSigned=*/true);
176 
177   // Check for FP which are bitcasted from INT_MIN integers
178   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
179     return !CFP->getValueAPF().bitcastToAPInt().isMinSignedValue();
180 
181   // Check that vectors don't contain INT_MIN
182   if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
183     for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
184       Constant *Elt = getAggregateElement(I);
185       if (!Elt || !Elt->isNotMinSignedValue())
186         return false;
187     }
188     return true;
189   }
190 
191   // Check for splats that aren't INT_MIN
192   if (getType()->isVectorTy())
193     if (const auto *SplatVal = getSplatValue())
194       return SplatVal->isNotMinSignedValue();
195 
196   // It *may* contain INT_MIN, we can't tell.
197   return false;
198 }
199 
200 bool Constant::isFiniteNonZeroFP() const {
201   if (auto *CFP = dyn_cast<ConstantFP>(this))
202     return CFP->getValueAPF().isFiniteNonZero();
203 
204   if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
205     for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
206       auto *CFP = dyn_cast_or_null<ConstantFP>(getAggregateElement(I));
207       if (!CFP || !CFP->getValueAPF().isFiniteNonZero())
208         return false;
209     }
210     return true;
211   }
212 
213   if (getType()->isVectorTy())
214     if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))
215       return SplatCFP->isFiniteNonZeroFP();
216 
217   // It *may* contain finite non-zero, we can't tell.
218   return false;
219 }
220 
221 bool Constant::isNormalFP() const {
222   if (auto *CFP = dyn_cast<ConstantFP>(this))
223     return CFP->getValueAPF().isNormal();
224 
225   if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
226     for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
227       auto *CFP = dyn_cast_or_null<ConstantFP>(getAggregateElement(I));
228       if (!CFP || !CFP->getValueAPF().isNormal())
229         return false;
230     }
231     return true;
232   }
233 
234   if (getType()->isVectorTy())
235     if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))
236       return SplatCFP->isNormalFP();
237 
238   // It *may* contain a normal fp value, we can't tell.
239   return false;
240 }
241 
242 bool Constant::hasExactInverseFP() const {
243   if (auto *CFP = dyn_cast<ConstantFP>(this))
244     return CFP->getValueAPF().getExactInverse(nullptr);
245 
246   if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
247     for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
248       auto *CFP = dyn_cast_or_null<ConstantFP>(getAggregateElement(I));
249       if (!CFP || !CFP->getValueAPF().getExactInverse(nullptr))
250         return false;
251     }
252     return true;
253   }
254 
255   if (getType()->isVectorTy())
256     if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))
257       return SplatCFP->hasExactInverseFP();
258 
259   // It *may* have an exact inverse fp value, we can't tell.
260   return false;
261 }
262 
263 bool Constant::isNaN() const {
264   if (auto *CFP = dyn_cast<ConstantFP>(this))
265     return CFP->isNaN();
266 
267   if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
268     for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
269       auto *CFP = dyn_cast_or_null<ConstantFP>(getAggregateElement(I));
270       if (!CFP || !CFP->isNaN())
271         return false;
272     }
273     return true;
274   }
275 
276   if (getType()->isVectorTy())
277     if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))
278       return SplatCFP->isNaN();
279 
280   // It *may* be NaN, we can't tell.
281   return false;
282 }
283 
284 bool Constant::isElementWiseEqual(Value *Y) const {
285   // Are they fully identical?
286   if (this == Y)
287     return true;
288 
289   // The input value must be a vector constant with the same type.
290   auto *VTy = dyn_cast<VectorType>(getType());
291   if (!isa<Constant>(Y) || !VTy || VTy != Y->getType())
292     return false;
293 
294   // TODO: Compare pointer constants?
295   if (!(VTy->getElementType()->isIntegerTy() ||
296         VTy->getElementType()->isFloatingPointTy()))
297     return false;
298 
299   // They may still be identical element-wise (if they have `undef`s).
300   // Bitcast to integer to allow exact bitwise comparison for all types.
301   Type *IntTy = VectorType::getInteger(VTy);
302   Constant *C0 = ConstantExpr::getBitCast(const_cast<Constant *>(this), IntTy);
303   Constant *C1 = ConstantExpr::getBitCast(cast<Constant>(Y), IntTy);
304   Constant *CmpEq = ConstantExpr::getICmp(ICmpInst::ICMP_EQ, C0, C1);
305   return isa<UndefValue>(CmpEq) || match(CmpEq, m_One());
306 }
307 
308 static bool
309 containsUndefinedElement(const Constant *C,
310                          function_ref<bool(const Constant *)> HasFn) {
311   if (auto *VTy = dyn_cast<VectorType>(C->getType())) {
312     if (HasFn(C))
313       return true;
314     if (isa<ConstantAggregateZero>(C))
315       return false;
316     if (isa<ScalableVectorType>(C->getType()))
317       return false;
318 
319     for (unsigned i = 0, e = cast<FixedVectorType>(VTy)->getNumElements();
320          i != e; ++i) {
321       if (Constant *Elem = C->getAggregateElement(i))
322         if (HasFn(Elem))
323           return true;
324     }
325   }
326 
327   return false;
328 }
329 
330 bool Constant::containsUndefOrPoisonElement() const {
331   return containsUndefinedElement(
332       this, [&](const auto *C) { return isa<UndefValue>(C); });
333 }
334 
335 bool Constant::containsPoisonElement() const {
336   return containsUndefinedElement(
337       this, [&](const auto *C) { return isa<PoisonValue>(C); });
338 }
339 
340 bool Constant::containsConstantExpression() const {
341   if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
342     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i)
343       if (isa<ConstantExpr>(getAggregateElement(i)))
344         return true;
345   }
346   return false;
347 }
348 
349 /// Constructor to create a '0' constant of arbitrary type.
350 Constant *Constant::getNullValue(Type *Ty) {
351   switch (Ty->getTypeID()) {
352   case Type::IntegerTyID:
353     return ConstantInt::get(Ty, 0);
354   case Type::HalfTyID:
355   case Type::BFloatTyID:
356   case Type::FloatTyID:
357   case Type::DoubleTyID:
358   case Type::X86_FP80TyID:
359   case Type::FP128TyID:
360   case Type::PPC_FP128TyID:
361     return ConstantFP::get(Ty->getContext(),
362                            APFloat::getZero(Ty->getFltSemantics()));
363   case Type::PointerTyID:
364     return ConstantPointerNull::get(cast<PointerType>(Ty));
365   case Type::StructTyID:
366   case Type::ArrayTyID:
367   case Type::FixedVectorTyID:
368   case Type::ScalableVectorTyID:
369     return ConstantAggregateZero::get(Ty);
370   case Type::TokenTyID:
371     return ConstantTokenNone::get(Ty->getContext());
372   default:
373     // Function, Label, or Opaque type?
374     llvm_unreachable("Cannot create a null constant of that type!");
375   }
376 }
377 
378 Constant *Constant::getIntegerValue(Type *Ty, const APInt &V) {
379   Type *ScalarTy = Ty->getScalarType();
380 
381   // Create the base integer constant.
382   Constant *C = ConstantInt::get(Ty->getContext(), V);
383 
384   // Convert an integer to a pointer, if necessary.
385   if (PointerType *PTy = dyn_cast<PointerType>(ScalarTy))
386     C = ConstantExpr::getIntToPtr(C, PTy);
387 
388   // Broadcast a scalar to a vector, if necessary.
389   if (VectorType *VTy = dyn_cast<VectorType>(Ty))
390     C = ConstantVector::getSplat(VTy->getElementCount(), C);
391 
392   return C;
393 }
394 
395 Constant *Constant::getAllOnesValue(Type *Ty) {
396   if (IntegerType *ITy = dyn_cast<IntegerType>(Ty))
397     return ConstantInt::get(Ty->getContext(),
398                             APInt::getAllOnes(ITy->getBitWidth()));
399 
400   if (Ty->isFloatingPointTy()) {
401     APFloat FL = APFloat::getAllOnesValue(Ty->getFltSemantics());
402     return ConstantFP::get(Ty->getContext(), FL);
403   }
404 
405   VectorType *VTy = cast<VectorType>(Ty);
406   return ConstantVector::getSplat(VTy->getElementCount(),
407                                   getAllOnesValue(VTy->getElementType()));
408 }
409 
410 Constant *Constant::getAggregateElement(unsigned Elt) const {
411   assert((getType()->isAggregateType() || getType()->isVectorTy()) &&
412          "Must be an aggregate/vector constant");
413 
414   if (const auto *CC = dyn_cast<ConstantAggregate>(this))
415     return Elt < CC->getNumOperands() ? CC->getOperand(Elt) : nullptr;
416 
417   if (const auto *CAZ = dyn_cast<ConstantAggregateZero>(this))
418     return Elt < CAZ->getElementCount().getKnownMinValue()
419                ? CAZ->getElementValue(Elt)
420                : nullptr;
421 
422   // FIXME: getNumElements() will fail for non-fixed vector types.
423   if (isa<ScalableVectorType>(getType()))
424     return nullptr;
425 
426   if (const auto *PV = dyn_cast<PoisonValue>(this))
427     return Elt < PV->getNumElements() ? PV->getElementValue(Elt) : nullptr;
428 
429   if (const auto *UV = dyn_cast<UndefValue>(this))
430     return Elt < UV->getNumElements() ? UV->getElementValue(Elt) : nullptr;
431 
432   if (const auto *CDS = dyn_cast<ConstantDataSequential>(this))
433     return Elt < CDS->getNumElements() ? CDS->getElementAsConstant(Elt)
434                                        : nullptr;
435 
436   return nullptr;
437 }
438 
439 Constant *Constant::getAggregateElement(Constant *Elt) const {
440   assert(isa<IntegerType>(Elt->getType()) && "Index must be an integer");
441   if (ConstantInt *CI = dyn_cast<ConstantInt>(Elt)) {
442     // Check if the constant fits into an uint64_t.
443     if (CI->getValue().getActiveBits() > 64)
444       return nullptr;
445     return getAggregateElement(CI->getZExtValue());
446   }
447   return nullptr;
448 }
449 
450 void Constant::destroyConstant() {
451   /// First call destroyConstantImpl on the subclass.  This gives the subclass
452   /// a chance to remove the constant from any maps/pools it's contained in.
453   switch (getValueID()) {
454   default:
455     llvm_unreachable("Not a constant!");
456 #define HANDLE_CONSTANT(Name)                                                  \
457   case Value::Name##Val:                                                       \
458     cast<Name>(this)->destroyConstantImpl();                                   \
459     break;
460 #include "llvm/IR/Value.def"
461   }
462 
463   // When a Constant is destroyed, there may be lingering
464   // references to the constant by other constants in the constant pool.  These
465   // constants are implicitly dependent on the module that is being deleted,
466   // but they don't know that.  Because we only find out when the CPV is
467   // deleted, we must now notify all of our users (that should only be
468   // Constants) that they are, in fact, invalid now and should be deleted.
469   //
470   while (!use_empty()) {
471     Value *V = user_back();
472 #ifndef NDEBUG // Only in -g mode...
473     if (!isa<Constant>(V)) {
474       dbgs() << "While deleting: " << *this
475              << "\n\nUse still stuck around after Def is destroyed: " << *V
476              << "\n\n";
477     }
478 #endif
479     assert(isa<Constant>(V) && "References remain to Constant being destroyed");
480     cast<Constant>(V)->destroyConstant();
481 
482     // The constant should remove itself from our use list...
483     assert((use_empty() || user_back() != V) && "Constant not removed!");
484   }
485 
486   // Value has no outstanding references it is safe to delete it now...
487   deleteConstant(this);
488 }
489 
490 void llvm::deleteConstant(Constant *C) {
491   switch (C->getValueID()) {
492   case Constant::ConstantIntVal:
493     delete static_cast<ConstantInt *>(C);
494     break;
495   case Constant::ConstantFPVal:
496     delete static_cast<ConstantFP *>(C);
497     break;
498   case Constant::ConstantAggregateZeroVal:
499     delete static_cast<ConstantAggregateZero *>(C);
500     break;
501   case Constant::ConstantArrayVal:
502     delete static_cast<ConstantArray *>(C);
503     break;
504   case Constant::ConstantStructVal:
505     delete static_cast<ConstantStruct *>(C);
506     break;
507   case Constant::ConstantVectorVal:
508     delete static_cast<ConstantVector *>(C);
509     break;
510   case Constant::ConstantPointerNullVal:
511     delete static_cast<ConstantPointerNull *>(C);
512     break;
513   case Constant::ConstantDataArrayVal:
514     delete static_cast<ConstantDataArray *>(C);
515     break;
516   case Constant::ConstantDataVectorVal:
517     delete static_cast<ConstantDataVector *>(C);
518     break;
519   case Constant::ConstantTokenNoneVal:
520     delete static_cast<ConstantTokenNone *>(C);
521     break;
522   case Constant::BlockAddressVal:
523     delete static_cast<BlockAddress *>(C);
524     break;
525   case Constant::DSOLocalEquivalentVal:
526     delete static_cast<DSOLocalEquivalent *>(C);
527     break;
528   case Constant::NoCFIValueVal:
529     delete static_cast<NoCFIValue *>(C);
530     break;
531   case Constant::UndefValueVal:
532     delete static_cast<UndefValue *>(C);
533     break;
534   case Constant::PoisonValueVal:
535     delete static_cast<PoisonValue *>(C);
536     break;
537   case Constant::ConstantExprVal:
538     if (isa<UnaryConstantExpr>(C))
539       delete static_cast<UnaryConstantExpr *>(C);
540     else if (isa<BinaryConstantExpr>(C))
541       delete static_cast<BinaryConstantExpr *>(C);
542     else if (isa<SelectConstantExpr>(C))
543       delete static_cast<SelectConstantExpr *>(C);
544     else if (isa<ExtractElementConstantExpr>(C))
545       delete static_cast<ExtractElementConstantExpr *>(C);
546     else if (isa<InsertElementConstantExpr>(C))
547       delete static_cast<InsertElementConstantExpr *>(C);
548     else if (isa<ShuffleVectorConstantExpr>(C))
549       delete static_cast<ShuffleVectorConstantExpr *>(C);
550     else if (isa<ExtractValueConstantExpr>(C))
551       delete static_cast<ExtractValueConstantExpr *>(C);
552     else if (isa<InsertValueConstantExpr>(C))
553       delete static_cast<InsertValueConstantExpr *>(C);
554     else if (isa<GetElementPtrConstantExpr>(C))
555       delete static_cast<GetElementPtrConstantExpr *>(C);
556     else if (isa<CompareConstantExpr>(C))
557       delete static_cast<CompareConstantExpr *>(C);
558     else
559       llvm_unreachable("Unexpected constant expr");
560     break;
561   default:
562     llvm_unreachable("Unexpected constant");
563   }
564 }
565 
566 static bool canTrapImpl(const Constant *C,
567                         SmallPtrSetImpl<const ConstantExpr *> &NonTrappingOps) {
568   assert(C->getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
569   // The only thing that could possibly trap are constant exprs.
570   const ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
571   if (!CE)
572     return false;
573 
574   // ConstantExpr traps if any operands can trap.
575   for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
576     if (ConstantExpr *Op = dyn_cast<ConstantExpr>(CE->getOperand(i))) {
577       if (NonTrappingOps.insert(Op).second && canTrapImpl(Op, NonTrappingOps))
578         return true;
579     }
580   }
581 
582   // Otherwise, only specific operations can trap.
583   switch (CE->getOpcode()) {
584   default:
585     return false;
586   case Instruction::UDiv:
587   case Instruction::SDiv:
588   case Instruction::URem:
589   case Instruction::SRem:
590     // Div and rem can trap if the RHS is not known to be non-zero.
591     if (!isa<ConstantInt>(CE->getOperand(1)) ||CE->getOperand(1)->isNullValue())
592       return true;
593     return false;
594   }
595 }
596 
597 bool Constant::canTrap() const {
598   SmallPtrSet<const ConstantExpr *, 4> NonTrappingOps;
599   return canTrapImpl(this, NonTrappingOps);
600 }
601 
602 /// Check if C contains a GlobalValue for which Predicate is true.
603 static bool
604 ConstHasGlobalValuePredicate(const Constant *C,
605                              bool (*Predicate)(const GlobalValue *)) {
606   SmallPtrSet<const Constant *, 8> Visited;
607   SmallVector<const Constant *, 8> WorkList;
608   WorkList.push_back(C);
609   Visited.insert(C);
610 
611   while (!WorkList.empty()) {
612     const Constant *WorkItem = WorkList.pop_back_val();
613     if (const auto *GV = dyn_cast<GlobalValue>(WorkItem))
614       if (Predicate(GV))
615         return true;
616     for (const Value *Op : WorkItem->operands()) {
617       const Constant *ConstOp = dyn_cast<Constant>(Op);
618       if (!ConstOp)
619         continue;
620       if (Visited.insert(ConstOp).second)
621         WorkList.push_back(ConstOp);
622     }
623   }
624   return false;
625 }
626 
627 bool Constant::isThreadDependent() const {
628   auto DLLImportPredicate = [](const GlobalValue *GV) {
629     return GV->isThreadLocal();
630   };
631   return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
632 }
633 
634 bool Constant::isDLLImportDependent() const {
635   auto DLLImportPredicate = [](const GlobalValue *GV) {
636     return GV->hasDLLImportStorageClass();
637   };
638   return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
639 }
640 
641 bool Constant::isConstantUsed() const {
642   for (const User *U : users()) {
643     const Constant *UC = dyn_cast<Constant>(U);
644     if (!UC || isa<GlobalValue>(UC))
645       return true;
646 
647     if (UC->isConstantUsed())
648       return true;
649   }
650   return false;
651 }
652 
653 bool Constant::needsDynamicRelocation() const {
654   return getRelocationInfo() == GlobalRelocation;
655 }
656 
657 bool Constant::needsRelocation() const {
658   return getRelocationInfo() != NoRelocation;
659 }
660 
661 Constant::PossibleRelocationsTy Constant::getRelocationInfo() const {
662   if (isa<GlobalValue>(this))
663     return GlobalRelocation; // Global reference.
664 
665   if (const BlockAddress *BA = dyn_cast<BlockAddress>(this))
666     return BA->getFunction()->getRelocationInfo();
667 
668   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(this)) {
669     if (CE->getOpcode() == Instruction::Sub) {
670       ConstantExpr *LHS = dyn_cast<ConstantExpr>(CE->getOperand(0));
671       ConstantExpr *RHS = dyn_cast<ConstantExpr>(CE->getOperand(1));
672       if (LHS && RHS && LHS->getOpcode() == Instruction::PtrToInt &&
673           RHS->getOpcode() == Instruction::PtrToInt) {
674         Constant *LHSOp0 = LHS->getOperand(0);
675         Constant *RHSOp0 = RHS->getOperand(0);
676 
677         // While raw uses of blockaddress need to be relocated, differences
678         // between two of them don't when they are for labels in the same
679         // function.  This is a common idiom when creating a table for the
680         // indirect goto extension, so we handle it efficiently here.
681         if (isa<BlockAddress>(LHSOp0) && isa<BlockAddress>(RHSOp0) &&
682             cast<BlockAddress>(LHSOp0)->getFunction() ==
683                 cast<BlockAddress>(RHSOp0)->getFunction())
684           return NoRelocation;
685 
686         // Relative pointers do not need to be dynamically relocated.
687         if (auto *RHSGV =
688                 dyn_cast<GlobalValue>(RHSOp0->stripInBoundsConstantOffsets())) {
689           auto *LHS = LHSOp0->stripInBoundsConstantOffsets();
690           if (auto *LHSGV = dyn_cast<GlobalValue>(LHS)) {
691             if (LHSGV->isDSOLocal() && RHSGV->isDSOLocal())
692               return LocalRelocation;
693           } else if (isa<DSOLocalEquivalent>(LHS)) {
694             if (RHSGV->isDSOLocal())
695               return LocalRelocation;
696           }
697         }
698       }
699     }
700   }
701 
702   PossibleRelocationsTy Result = NoRelocation;
703   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
704     Result =
705         std::max(cast<Constant>(getOperand(i))->getRelocationInfo(), Result);
706 
707   return Result;
708 }
709 
710 /// Return true if the specified constantexpr is dead. This involves
711 /// recursively traversing users of the constantexpr.
712 /// If RemoveDeadUsers is true, also remove dead users at the same time.
713 static bool constantIsDead(const Constant *C, bool RemoveDeadUsers) {
714   if (isa<GlobalValue>(C)) return false; // Cannot remove this
715 
716   Value::const_user_iterator I = C->user_begin(), E = C->user_end();
717   while (I != E) {
718     const Constant *User = dyn_cast<Constant>(*I);
719     if (!User) return false; // Non-constant usage;
720     if (!constantIsDead(User, RemoveDeadUsers))
721       return false; // Constant wasn't dead
722 
723     // Just removed User, so the iterator was invalidated.
724     // Since we return immediately upon finding a live user, we can always
725     // restart from user_begin().
726     if (RemoveDeadUsers)
727       I = C->user_begin();
728     else
729       ++I;
730   }
731 
732   if (RemoveDeadUsers) {
733     // If C is only used by metadata, it should not be preserved but should
734     // have its uses replaced.
735     ReplaceableMetadataImpl::SalvageDebugInfo(*C);
736     const_cast<Constant *>(C)->destroyConstant();
737   }
738 
739   return true;
740 }
741 
742 void Constant::removeDeadConstantUsers() const {
743   Value::const_user_iterator I = user_begin(), E = user_end();
744   Value::const_user_iterator LastNonDeadUser = E;
745   while (I != E) {
746     const Constant *User = dyn_cast<Constant>(*I);
747     if (!User) {
748       LastNonDeadUser = I;
749       ++I;
750       continue;
751     }
752 
753     if (!constantIsDead(User, /* RemoveDeadUsers= */ true)) {
754       // If the constant wasn't dead, remember that this was the last live use
755       // and move on to the next constant.
756       LastNonDeadUser = I;
757       ++I;
758       continue;
759     }
760 
761     // If the constant was dead, then the iterator is invalidated.
762     if (LastNonDeadUser == E)
763       I = user_begin();
764     else
765       I = std::next(LastNonDeadUser);
766   }
767 }
768 
769 bool Constant::hasOneLiveUse() const { return hasNLiveUses(1); }
770 
771 bool Constant::hasZeroLiveUses() const { return hasNLiveUses(0); }
772 
773 bool Constant::hasNLiveUses(unsigned N) const {
774   unsigned NumUses = 0;
775   for (const Use &U : uses()) {
776     const Constant *User = dyn_cast<Constant>(U.getUser());
777     if (!User || !constantIsDead(User, /* RemoveDeadUsers= */ false)) {
778       ++NumUses;
779 
780       if (NumUses > N)
781         return false;
782     }
783   }
784   return NumUses == N;
785 }
786 
787 Constant *Constant::replaceUndefsWith(Constant *C, Constant *Replacement) {
788   assert(C && Replacement && "Expected non-nullptr constant arguments");
789   Type *Ty = C->getType();
790   if (match(C, m_Undef())) {
791     assert(Ty == Replacement->getType() && "Expected matching types");
792     return Replacement;
793   }
794 
795   // Don't know how to deal with this constant.
796   auto *VTy = dyn_cast<FixedVectorType>(Ty);
797   if (!VTy)
798     return C;
799 
800   unsigned NumElts = VTy->getNumElements();
801   SmallVector<Constant *, 32> NewC(NumElts);
802   for (unsigned i = 0; i != NumElts; ++i) {
803     Constant *EltC = C->getAggregateElement(i);
804     assert((!EltC || EltC->getType() == Replacement->getType()) &&
805            "Expected matching types");
806     NewC[i] = EltC && match(EltC, m_Undef()) ? Replacement : EltC;
807   }
808   return ConstantVector::get(NewC);
809 }
810 
811 Constant *Constant::mergeUndefsWith(Constant *C, Constant *Other) {
812   assert(C && Other && "Expected non-nullptr constant arguments");
813   if (match(C, m_Undef()))
814     return C;
815 
816   Type *Ty = C->getType();
817   if (match(Other, m_Undef()))
818     return UndefValue::get(Ty);
819 
820   auto *VTy = dyn_cast<FixedVectorType>(Ty);
821   if (!VTy)
822     return C;
823 
824   Type *EltTy = VTy->getElementType();
825   unsigned NumElts = VTy->getNumElements();
826   assert(isa<FixedVectorType>(Other->getType()) &&
827          cast<FixedVectorType>(Other->getType())->getNumElements() == NumElts &&
828          "Type mismatch");
829 
830   bool FoundExtraUndef = false;
831   SmallVector<Constant *, 32> NewC(NumElts);
832   for (unsigned I = 0; I != NumElts; ++I) {
833     NewC[I] = C->getAggregateElement(I);
834     Constant *OtherEltC = Other->getAggregateElement(I);
835     assert(NewC[I] && OtherEltC && "Unknown vector element");
836     if (!match(NewC[I], m_Undef()) && match(OtherEltC, m_Undef())) {
837       NewC[I] = UndefValue::get(EltTy);
838       FoundExtraUndef = true;
839     }
840   }
841   if (FoundExtraUndef)
842     return ConstantVector::get(NewC);
843   return C;
844 }
845 
846 bool Constant::isManifestConstant() const {
847   if (isa<ConstantData>(this))
848     return true;
849   if (isa<ConstantAggregate>(this) || isa<ConstantExpr>(this)) {
850     for (const Value *Op : operand_values())
851       if (!cast<Constant>(Op)->isManifestConstant())
852         return false;
853     return true;
854   }
855   return false;
856 }
857 
858 //===----------------------------------------------------------------------===//
859 //                                ConstantInt
860 //===----------------------------------------------------------------------===//
861 
862 ConstantInt::ConstantInt(IntegerType *Ty, const APInt &V)
863     : ConstantData(Ty, ConstantIntVal), Val(V) {
864   assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
865 }
866 
867 ConstantInt *ConstantInt::getTrue(LLVMContext &Context) {
868   LLVMContextImpl *pImpl = Context.pImpl;
869   if (!pImpl->TheTrueVal)
870     pImpl->TheTrueVal = ConstantInt::get(Type::getInt1Ty(Context), 1);
871   return pImpl->TheTrueVal;
872 }
873 
874 ConstantInt *ConstantInt::getFalse(LLVMContext &Context) {
875   LLVMContextImpl *pImpl = Context.pImpl;
876   if (!pImpl->TheFalseVal)
877     pImpl->TheFalseVal = ConstantInt::get(Type::getInt1Ty(Context), 0);
878   return pImpl->TheFalseVal;
879 }
880 
881 ConstantInt *ConstantInt::getBool(LLVMContext &Context, bool V) {
882   return V ? getTrue(Context) : getFalse(Context);
883 }
884 
885 Constant *ConstantInt::getTrue(Type *Ty) {
886   assert(Ty->isIntOrIntVectorTy(1) && "Type not i1 or vector of i1.");
887   ConstantInt *TrueC = ConstantInt::getTrue(Ty->getContext());
888   if (auto *VTy = dyn_cast<VectorType>(Ty))
889     return ConstantVector::getSplat(VTy->getElementCount(), TrueC);
890   return TrueC;
891 }
892 
893 Constant *ConstantInt::getFalse(Type *Ty) {
894   assert(Ty->isIntOrIntVectorTy(1) && "Type not i1 or vector of i1.");
895   ConstantInt *FalseC = ConstantInt::getFalse(Ty->getContext());
896   if (auto *VTy = dyn_cast<VectorType>(Ty))
897     return ConstantVector::getSplat(VTy->getElementCount(), FalseC);
898   return FalseC;
899 }
900 
901 Constant *ConstantInt::getBool(Type *Ty, bool V) {
902   return V ? getTrue(Ty) : getFalse(Ty);
903 }
904 
905 // Get a ConstantInt from an APInt.
906 ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt &V) {
907   // get an existing value or the insertion position
908   LLVMContextImpl *pImpl = Context.pImpl;
909   std::unique_ptr<ConstantInt> &Slot = pImpl->IntConstants[V];
910   if (!Slot) {
911     // Get the corresponding integer type for the bit width of the value.
912     IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
913     Slot.reset(new ConstantInt(ITy, V));
914   }
915   assert(Slot->getType() == IntegerType::get(Context, V.getBitWidth()));
916   return Slot.get();
917 }
918 
919 Constant *ConstantInt::get(Type *Ty, uint64_t V, bool isSigned) {
920   Constant *C = get(cast<IntegerType>(Ty->getScalarType()), V, isSigned);
921 
922   // For vectors, broadcast the value.
923   if (VectorType *VTy = dyn_cast<VectorType>(Ty))
924     return ConstantVector::getSplat(VTy->getElementCount(), C);
925 
926   return C;
927 }
928 
929 ConstantInt *ConstantInt::get(IntegerType *Ty, uint64_t V, bool isSigned) {
930   return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned));
931 }
932 
933 ConstantInt *ConstantInt::getSigned(IntegerType *Ty, int64_t V) {
934   return get(Ty, V, true);
935 }
936 
937 Constant *ConstantInt::getSigned(Type *Ty, int64_t V) {
938   return get(Ty, V, true);
939 }
940 
941 Constant *ConstantInt::get(Type *Ty, const APInt& V) {
942   ConstantInt *C = get(Ty->getContext(), V);
943   assert(C->getType() == Ty->getScalarType() &&
944          "ConstantInt type doesn't match the type implied by its value!");
945 
946   // For vectors, broadcast the value.
947   if (VectorType *VTy = dyn_cast<VectorType>(Ty))
948     return ConstantVector::getSplat(VTy->getElementCount(), C);
949 
950   return C;
951 }
952 
953 ConstantInt *ConstantInt::get(IntegerType* Ty, StringRef Str, uint8_t radix) {
954   return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
955 }
956 
957 /// Remove the constant from the constant table.
958 void ConstantInt::destroyConstantImpl() {
959   llvm_unreachable("You can't ConstantInt->destroyConstantImpl()!");
960 }
961 
962 //===----------------------------------------------------------------------===//
963 //                                ConstantFP
964 //===----------------------------------------------------------------------===//
965 
966 Constant *ConstantFP::get(Type *Ty, double V) {
967   LLVMContext &Context = Ty->getContext();
968 
969   APFloat FV(V);
970   bool ignored;
971   FV.convert(Ty->getScalarType()->getFltSemantics(),
972              APFloat::rmNearestTiesToEven, &ignored);
973   Constant *C = get(Context, FV);
974 
975   // For vectors, broadcast the value.
976   if (VectorType *VTy = dyn_cast<VectorType>(Ty))
977     return ConstantVector::getSplat(VTy->getElementCount(), C);
978 
979   return C;
980 }
981 
982 Constant *ConstantFP::get(Type *Ty, const APFloat &V) {
983   ConstantFP *C = get(Ty->getContext(), V);
984   assert(C->getType() == Ty->getScalarType() &&
985          "ConstantFP type doesn't match the type implied by its value!");
986 
987   // For vectors, broadcast the value.
988   if (auto *VTy = dyn_cast<VectorType>(Ty))
989     return ConstantVector::getSplat(VTy->getElementCount(), C);
990 
991   return C;
992 }
993 
994 Constant *ConstantFP::get(Type *Ty, StringRef Str) {
995   LLVMContext &Context = Ty->getContext();
996 
997   APFloat FV(Ty->getScalarType()->getFltSemantics(), Str);
998   Constant *C = get(Context, FV);
999 
1000   // For vectors, broadcast the value.
1001   if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1002     return ConstantVector::getSplat(VTy->getElementCount(), C);
1003 
1004   return C;
1005 }
1006 
1007 Constant *ConstantFP::getNaN(Type *Ty, bool Negative, uint64_t Payload) {
1008   const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
1009   APFloat NaN = APFloat::getNaN(Semantics, Negative, Payload);
1010   Constant *C = get(Ty->getContext(), NaN);
1011 
1012   if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1013     return ConstantVector::getSplat(VTy->getElementCount(), C);
1014 
1015   return C;
1016 }
1017 
1018 Constant *ConstantFP::getQNaN(Type *Ty, bool Negative, APInt *Payload) {
1019   const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
1020   APFloat NaN = APFloat::getQNaN(Semantics, Negative, Payload);
1021   Constant *C = get(Ty->getContext(), NaN);
1022 
1023   if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1024     return ConstantVector::getSplat(VTy->getElementCount(), C);
1025 
1026   return C;
1027 }
1028 
1029 Constant *ConstantFP::getSNaN(Type *Ty, bool Negative, APInt *Payload) {
1030   const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
1031   APFloat NaN = APFloat::getSNaN(Semantics, Negative, Payload);
1032   Constant *C = get(Ty->getContext(), NaN);
1033 
1034   if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1035     return ConstantVector::getSplat(VTy->getElementCount(), C);
1036 
1037   return C;
1038 }
1039 
1040 Constant *ConstantFP::getNegativeZero(Type *Ty) {
1041   const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
1042   APFloat NegZero = APFloat::getZero(Semantics, /*Negative=*/true);
1043   Constant *C = get(Ty->getContext(), NegZero);
1044 
1045   if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1046     return ConstantVector::getSplat(VTy->getElementCount(), C);
1047 
1048   return C;
1049 }
1050 
1051 
1052 Constant *ConstantFP::getZeroValueForNegation(Type *Ty) {
1053   if (Ty->isFPOrFPVectorTy())
1054     return getNegativeZero(Ty);
1055 
1056   return Constant::getNullValue(Ty);
1057 }
1058 
1059 
1060 // ConstantFP accessors.
1061 ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
1062   LLVMContextImpl* pImpl = Context.pImpl;
1063 
1064   std::unique_ptr<ConstantFP> &Slot = pImpl->FPConstants[V];
1065 
1066   if (!Slot) {
1067     Type *Ty = Type::getFloatingPointTy(Context, V.getSemantics());
1068     Slot.reset(new ConstantFP(Ty, V));
1069   }
1070 
1071   return Slot.get();
1072 }
1073 
1074 Constant *ConstantFP::getInfinity(Type *Ty, bool Negative) {
1075   const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
1076   Constant *C = get(Ty->getContext(), APFloat::getInf(Semantics, Negative));
1077 
1078   if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1079     return ConstantVector::getSplat(VTy->getElementCount(), C);
1080 
1081   return C;
1082 }
1083 
1084 ConstantFP::ConstantFP(Type *Ty, const APFloat &V)
1085     : ConstantData(Ty, ConstantFPVal), Val(V) {
1086   assert(&V.getSemantics() == &Ty->getFltSemantics() &&
1087          "FP type Mismatch");
1088 }
1089 
1090 bool ConstantFP::isExactlyValue(const APFloat &V) const {
1091   return Val.bitwiseIsEqual(V);
1092 }
1093 
1094 /// Remove the constant from the constant table.
1095 void ConstantFP::destroyConstantImpl() {
1096   llvm_unreachable("You can't ConstantFP->destroyConstantImpl()!");
1097 }
1098 
1099 //===----------------------------------------------------------------------===//
1100 //                   ConstantAggregateZero Implementation
1101 //===----------------------------------------------------------------------===//
1102 
1103 Constant *ConstantAggregateZero::getSequentialElement() const {
1104   if (auto *AT = dyn_cast<ArrayType>(getType()))
1105     return Constant::getNullValue(AT->getElementType());
1106   return Constant::getNullValue(cast<VectorType>(getType())->getElementType());
1107 }
1108 
1109 Constant *ConstantAggregateZero::getStructElement(unsigned Elt) const {
1110   return Constant::getNullValue(getType()->getStructElementType(Elt));
1111 }
1112 
1113 Constant *ConstantAggregateZero::getElementValue(Constant *C) const {
1114   if (isa<ArrayType>(getType()) || isa<VectorType>(getType()))
1115     return getSequentialElement();
1116   return getStructElement(cast<ConstantInt>(C)->getZExtValue());
1117 }
1118 
1119 Constant *ConstantAggregateZero::getElementValue(unsigned Idx) const {
1120   if (isa<ArrayType>(getType()) || isa<VectorType>(getType()))
1121     return getSequentialElement();
1122   return getStructElement(Idx);
1123 }
1124 
1125 ElementCount ConstantAggregateZero::getElementCount() const {
1126   Type *Ty = getType();
1127   if (auto *AT = dyn_cast<ArrayType>(Ty))
1128     return ElementCount::getFixed(AT->getNumElements());
1129   if (auto *VT = dyn_cast<VectorType>(Ty))
1130     return VT->getElementCount();
1131   return ElementCount::getFixed(Ty->getStructNumElements());
1132 }
1133 
1134 //===----------------------------------------------------------------------===//
1135 //                         UndefValue Implementation
1136 //===----------------------------------------------------------------------===//
1137 
1138 UndefValue *UndefValue::getSequentialElement() const {
1139   if (ArrayType *ATy = dyn_cast<ArrayType>(getType()))
1140     return UndefValue::get(ATy->getElementType());
1141   return UndefValue::get(cast<VectorType>(getType())->getElementType());
1142 }
1143 
1144 UndefValue *UndefValue::getStructElement(unsigned Elt) const {
1145   return UndefValue::get(getType()->getStructElementType(Elt));
1146 }
1147 
1148 UndefValue *UndefValue::getElementValue(Constant *C) const {
1149   if (isa<ArrayType>(getType()) || isa<VectorType>(getType()))
1150     return getSequentialElement();
1151   return getStructElement(cast<ConstantInt>(C)->getZExtValue());
1152 }
1153 
1154 UndefValue *UndefValue::getElementValue(unsigned Idx) const {
1155   if (isa<ArrayType>(getType()) || isa<VectorType>(getType()))
1156     return getSequentialElement();
1157   return getStructElement(Idx);
1158 }
1159 
1160 unsigned UndefValue::getNumElements() const {
1161   Type *Ty = getType();
1162   if (auto *AT = dyn_cast<ArrayType>(Ty))
1163     return AT->getNumElements();
1164   if (auto *VT = dyn_cast<VectorType>(Ty))
1165     return cast<FixedVectorType>(VT)->getNumElements();
1166   return Ty->getStructNumElements();
1167 }
1168 
1169 //===----------------------------------------------------------------------===//
1170 //                         PoisonValue Implementation
1171 //===----------------------------------------------------------------------===//
1172 
1173 PoisonValue *PoisonValue::getSequentialElement() const {
1174   if (ArrayType *ATy = dyn_cast<ArrayType>(getType()))
1175     return PoisonValue::get(ATy->getElementType());
1176   return PoisonValue::get(cast<VectorType>(getType())->getElementType());
1177 }
1178 
1179 PoisonValue *PoisonValue::getStructElement(unsigned Elt) const {
1180   return PoisonValue::get(getType()->getStructElementType(Elt));
1181 }
1182 
1183 PoisonValue *PoisonValue::getElementValue(Constant *C) const {
1184   if (isa<ArrayType>(getType()) || isa<VectorType>(getType()))
1185     return getSequentialElement();
1186   return getStructElement(cast<ConstantInt>(C)->getZExtValue());
1187 }
1188 
1189 PoisonValue *PoisonValue::getElementValue(unsigned Idx) const {
1190   if (isa<ArrayType>(getType()) || isa<VectorType>(getType()))
1191     return getSequentialElement();
1192   return getStructElement(Idx);
1193 }
1194 
1195 //===----------------------------------------------------------------------===//
1196 //                            ConstantXXX Classes
1197 //===----------------------------------------------------------------------===//
1198 
1199 template <typename ItTy, typename EltTy>
1200 static bool rangeOnlyContains(ItTy Start, ItTy End, EltTy Elt) {
1201   for (; Start != End; ++Start)
1202     if (*Start != Elt)
1203       return false;
1204   return true;
1205 }
1206 
1207 template <typename SequentialTy, typename ElementTy>
1208 static Constant *getIntSequenceIfElementsMatch(ArrayRef<Constant *> V) {
1209   assert(!V.empty() && "Cannot get empty int sequence.");
1210 
1211   SmallVector<ElementTy, 16> Elts;
1212   for (Constant *C : V)
1213     if (auto *CI = dyn_cast<ConstantInt>(C))
1214       Elts.push_back(CI->getZExtValue());
1215     else
1216       return nullptr;
1217   return SequentialTy::get(V[0]->getContext(), Elts);
1218 }
1219 
1220 template <typename SequentialTy, typename ElementTy>
1221 static Constant *getFPSequenceIfElementsMatch(ArrayRef<Constant *> V) {
1222   assert(!V.empty() && "Cannot get empty FP sequence.");
1223 
1224   SmallVector<ElementTy, 16> Elts;
1225   for (Constant *C : V)
1226     if (auto *CFP = dyn_cast<ConstantFP>(C))
1227       Elts.push_back(CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
1228     else
1229       return nullptr;
1230   return SequentialTy::getFP(V[0]->getType(), Elts);
1231 }
1232 
1233 template <typename SequenceTy>
1234 static Constant *getSequenceIfElementsMatch(Constant *C,
1235                                             ArrayRef<Constant *> V) {
1236   // We speculatively build the elements here even if it turns out that there is
1237   // a constantexpr or something else weird, since it is so uncommon for that to
1238   // happen.
1239   if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
1240     if (CI->getType()->isIntegerTy(8))
1241       return getIntSequenceIfElementsMatch<SequenceTy, uint8_t>(V);
1242     else if (CI->getType()->isIntegerTy(16))
1243       return getIntSequenceIfElementsMatch<SequenceTy, uint16_t>(V);
1244     else if (CI->getType()->isIntegerTy(32))
1245       return getIntSequenceIfElementsMatch<SequenceTy, uint32_t>(V);
1246     else if (CI->getType()->isIntegerTy(64))
1247       return getIntSequenceIfElementsMatch<SequenceTy, uint64_t>(V);
1248   } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
1249     if (CFP->getType()->isHalfTy() || CFP->getType()->isBFloatTy())
1250       return getFPSequenceIfElementsMatch<SequenceTy, uint16_t>(V);
1251     else if (CFP->getType()->isFloatTy())
1252       return getFPSequenceIfElementsMatch<SequenceTy, uint32_t>(V);
1253     else if (CFP->getType()->isDoubleTy())
1254       return getFPSequenceIfElementsMatch<SequenceTy, uint64_t>(V);
1255   }
1256 
1257   return nullptr;
1258 }
1259 
1260 ConstantAggregate::ConstantAggregate(Type *T, ValueTy VT,
1261                                      ArrayRef<Constant *> V)
1262     : Constant(T, VT, OperandTraits<ConstantAggregate>::op_end(this) - V.size(),
1263                V.size()) {
1264   llvm::copy(V, op_begin());
1265 
1266   // Check that types match, unless this is an opaque struct.
1267   if (auto *ST = dyn_cast<StructType>(T)) {
1268     if (ST->isOpaque())
1269       return;
1270     for (unsigned I = 0, E = V.size(); I != E; ++I)
1271       assert(V[I]->getType() == ST->getTypeAtIndex(I) &&
1272              "Initializer for struct element doesn't match!");
1273   }
1274 }
1275 
1276 ConstantArray::ConstantArray(ArrayType *T, ArrayRef<Constant *> V)
1277     : ConstantAggregate(T, ConstantArrayVal, V) {
1278   assert(V.size() == T->getNumElements() &&
1279          "Invalid initializer for constant array");
1280 }
1281 
1282 Constant *ConstantArray::get(ArrayType *Ty, ArrayRef<Constant*> V) {
1283   if (Constant *C = getImpl(Ty, V))
1284     return C;
1285   return Ty->getContext().pImpl->ArrayConstants.getOrCreate(Ty, V);
1286 }
1287 
1288 Constant *ConstantArray::getImpl(ArrayType *Ty, ArrayRef<Constant*> V) {
1289   // Empty arrays are canonicalized to ConstantAggregateZero.
1290   if (V.empty())
1291     return ConstantAggregateZero::get(Ty);
1292 
1293   for (Constant *C : V) {
1294     assert(C->getType() == Ty->getElementType() &&
1295            "Wrong type in array element initializer");
1296     (void)C;
1297   }
1298 
1299   // If this is an all-zero array, return a ConstantAggregateZero object.  If
1300   // all undef, return an UndefValue, if "all simple", then return a
1301   // ConstantDataArray.
1302   Constant *C = V[0];
1303   if (isa<PoisonValue>(C) && rangeOnlyContains(V.begin(), V.end(), C))
1304     return PoisonValue::get(Ty);
1305 
1306   if (isa<UndefValue>(C) && rangeOnlyContains(V.begin(), V.end(), C))
1307     return UndefValue::get(Ty);
1308 
1309   if (C->isNullValue() && rangeOnlyContains(V.begin(), V.end(), C))
1310     return ConstantAggregateZero::get(Ty);
1311 
1312   // Check to see if all of the elements are ConstantFP or ConstantInt and if
1313   // the element type is compatible with ConstantDataVector.  If so, use it.
1314   if (ConstantDataSequential::isElementTypeCompatible(C->getType()))
1315     return getSequenceIfElementsMatch<ConstantDataArray>(C, V);
1316 
1317   // Otherwise, we really do want to create a ConstantArray.
1318   return nullptr;
1319 }
1320 
1321 StructType *ConstantStruct::getTypeForElements(LLVMContext &Context,
1322                                                ArrayRef<Constant*> V,
1323                                                bool Packed) {
1324   unsigned VecSize = V.size();
1325   SmallVector<Type*, 16> EltTypes(VecSize);
1326   for (unsigned i = 0; i != VecSize; ++i)
1327     EltTypes[i] = V[i]->getType();
1328 
1329   return StructType::get(Context, EltTypes, Packed);
1330 }
1331 
1332 
1333 StructType *ConstantStruct::getTypeForElements(ArrayRef<Constant*> V,
1334                                                bool Packed) {
1335   assert(!V.empty() &&
1336          "ConstantStruct::getTypeForElements cannot be called on empty list");
1337   return getTypeForElements(V[0]->getContext(), V, Packed);
1338 }
1339 
1340 ConstantStruct::ConstantStruct(StructType *T, ArrayRef<Constant *> V)
1341     : ConstantAggregate(T, ConstantStructVal, V) {
1342   assert((T->isOpaque() || V.size() == T->getNumElements()) &&
1343          "Invalid initializer for constant struct");
1344 }
1345 
1346 // ConstantStruct accessors.
1347 Constant *ConstantStruct::get(StructType *ST, ArrayRef<Constant*> V) {
1348   assert((ST->isOpaque() || ST->getNumElements() == V.size()) &&
1349          "Incorrect # elements specified to ConstantStruct::get");
1350 
1351   // Create a ConstantAggregateZero value if all elements are zeros.
1352   bool isZero = true;
1353   bool isUndef = false;
1354   bool isPoison = false;
1355 
1356   if (!V.empty()) {
1357     isUndef = isa<UndefValue>(V[0]);
1358     isPoison = isa<PoisonValue>(V[0]);
1359     isZero = V[0]->isNullValue();
1360     // PoisonValue inherits UndefValue, so its check is not necessary.
1361     if (isUndef || isZero) {
1362       for (Constant *C : V) {
1363         if (!C->isNullValue())
1364           isZero = false;
1365         if (!isa<PoisonValue>(C))
1366           isPoison = false;
1367         if (isa<PoisonValue>(C) || !isa<UndefValue>(C))
1368           isUndef = false;
1369       }
1370     }
1371   }
1372   if (isZero)
1373     return ConstantAggregateZero::get(ST);
1374   if (isPoison)
1375     return PoisonValue::get(ST);
1376   if (isUndef)
1377     return UndefValue::get(ST);
1378 
1379   return ST->getContext().pImpl->StructConstants.getOrCreate(ST, V);
1380 }
1381 
1382 ConstantVector::ConstantVector(VectorType *T, ArrayRef<Constant *> V)
1383     : ConstantAggregate(T, ConstantVectorVal, V) {
1384   assert(V.size() == cast<FixedVectorType>(T)->getNumElements() &&
1385          "Invalid initializer for constant vector");
1386 }
1387 
1388 // ConstantVector accessors.
1389 Constant *ConstantVector::get(ArrayRef<Constant*> V) {
1390   if (Constant *C = getImpl(V))
1391     return C;
1392   auto *Ty = FixedVectorType::get(V.front()->getType(), V.size());
1393   return Ty->getContext().pImpl->VectorConstants.getOrCreate(Ty, V);
1394 }
1395 
1396 Constant *ConstantVector::getImpl(ArrayRef<Constant*> V) {
1397   assert(!V.empty() && "Vectors can't be empty");
1398   auto *T = FixedVectorType::get(V.front()->getType(), V.size());
1399 
1400   // If this is an all-undef or all-zero vector, return a
1401   // ConstantAggregateZero or UndefValue.
1402   Constant *C = V[0];
1403   bool isZero = C->isNullValue();
1404   bool isUndef = isa<UndefValue>(C);
1405   bool isPoison = isa<PoisonValue>(C);
1406 
1407   if (isZero || isUndef) {
1408     for (unsigned i = 1, e = V.size(); i != e; ++i)
1409       if (V[i] != C) {
1410         isZero = isUndef = isPoison = false;
1411         break;
1412       }
1413   }
1414 
1415   if (isZero)
1416     return ConstantAggregateZero::get(T);
1417   if (isPoison)
1418     return PoisonValue::get(T);
1419   if (isUndef)
1420     return UndefValue::get(T);
1421 
1422   // Check to see if all of the elements are ConstantFP or ConstantInt and if
1423   // the element type is compatible with ConstantDataVector.  If so, use it.
1424   if (ConstantDataSequential::isElementTypeCompatible(C->getType()))
1425     return getSequenceIfElementsMatch<ConstantDataVector>(C, V);
1426 
1427   // Otherwise, the element type isn't compatible with ConstantDataVector, or
1428   // the operand list contains a ConstantExpr or something else strange.
1429   return nullptr;
1430 }
1431 
1432 Constant *ConstantVector::getSplat(ElementCount EC, Constant *V) {
1433   if (!EC.isScalable()) {
1434     // If this splat is compatible with ConstantDataVector, use it instead of
1435     // ConstantVector.
1436     if ((isa<ConstantFP>(V) || isa<ConstantInt>(V)) &&
1437         ConstantDataSequential::isElementTypeCompatible(V->getType()))
1438       return ConstantDataVector::getSplat(EC.getKnownMinValue(), V);
1439 
1440     SmallVector<Constant *, 32> Elts(EC.getKnownMinValue(), V);
1441     return get(Elts);
1442   }
1443 
1444   Type *VTy = VectorType::get(V->getType(), EC);
1445 
1446   if (V->isNullValue())
1447     return ConstantAggregateZero::get(VTy);
1448   else if (isa<UndefValue>(V))
1449     return UndefValue::get(VTy);
1450 
1451   Type *I32Ty = Type::getInt32Ty(VTy->getContext());
1452 
1453   // Move scalar into vector.
1454   Constant *PoisonV = PoisonValue::get(VTy);
1455   V = ConstantExpr::getInsertElement(PoisonV, V, ConstantInt::get(I32Ty, 0));
1456   // Build shuffle mask to perform the splat.
1457   SmallVector<int, 8> Zeros(EC.getKnownMinValue(), 0);
1458   // Splat.
1459   return ConstantExpr::getShuffleVector(V, PoisonV, Zeros);
1460 }
1461 
1462 ConstantTokenNone *ConstantTokenNone::get(LLVMContext &Context) {
1463   LLVMContextImpl *pImpl = Context.pImpl;
1464   if (!pImpl->TheNoneToken)
1465     pImpl->TheNoneToken.reset(new ConstantTokenNone(Context));
1466   return pImpl->TheNoneToken.get();
1467 }
1468 
1469 /// Remove the constant from the constant table.
1470 void ConstantTokenNone::destroyConstantImpl() {
1471   llvm_unreachable("You can't ConstantTokenNone->destroyConstantImpl()!");
1472 }
1473 
1474 // Utility function for determining if a ConstantExpr is a CastOp or not. This
1475 // can't be inline because we don't want to #include Instruction.h into
1476 // Constant.h
1477 bool ConstantExpr::isCast() const {
1478   return Instruction::isCast(getOpcode());
1479 }
1480 
1481 bool ConstantExpr::isCompare() const {
1482   return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
1483 }
1484 
1485 bool ConstantExpr::hasIndices() const {
1486   return getOpcode() == Instruction::ExtractValue ||
1487          getOpcode() == Instruction::InsertValue;
1488 }
1489 
1490 ArrayRef<unsigned> ConstantExpr::getIndices() const {
1491   if (const ExtractValueConstantExpr *EVCE =
1492         dyn_cast<ExtractValueConstantExpr>(this))
1493     return EVCE->Indices;
1494 
1495   return cast<InsertValueConstantExpr>(this)->Indices;
1496 }
1497 
1498 unsigned ConstantExpr::getPredicate() const {
1499   return cast<CompareConstantExpr>(this)->predicate;
1500 }
1501 
1502 ArrayRef<int> ConstantExpr::getShuffleMask() const {
1503   return cast<ShuffleVectorConstantExpr>(this)->ShuffleMask;
1504 }
1505 
1506 Constant *ConstantExpr::getShuffleMaskForBitcode() const {
1507   return cast<ShuffleVectorConstantExpr>(this)->ShuffleMaskForBitcode;
1508 }
1509 
1510 Constant *ConstantExpr::getWithOperands(ArrayRef<Constant *> Ops, Type *Ty,
1511                                         bool OnlyIfReduced, Type *SrcTy) const {
1512   assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
1513 
1514   // If no operands changed return self.
1515   if (Ty == getType() && std::equal(Ops.begin(), Ops.end(), op_begin()))
1516     return const_cast<ConstantExpr*>(this);
1517 
1518   Type *OnlyIfReducedTy = OnlyIfReduced ? Ty : nullptr;
1519   switch (getOpcode()) {
1520   case Instruction::Trunc:
1521   case Instruction::ZExt:
1522   case Instruction::SExt:
1523   case Instruction::FPTrunc:
1524   case Instruction::FPExt:
1525   case Instruction::UIToFP:
1526   case Instruction::SIToFP:
1527   case Instruction::FPToUI:
1528   case Instruction::FPToSI:
1529   case Instruction::PtrToInt:
1530   case Instruction::IntToPtr:
1531   case Instruction::BitCast:
1532   case Instruction::AddrSpaceCast:
1533     return ConstantExpr::getCast(getOpcode(), Ops[0], Ty, OnlyIfReduced);
1534   case Instruction::Select:
1535     return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2], OnlyIfReducedTy);
1536   case Instruction::InsertElement:
1537     return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2],
1538                                           OnlyIfReducedTy);
1539   case Instruction::ExtractElement:
1540     return ConstantExpr::getExtractElement(Ops[0], Ops[1], OnlyIfReducedTy);
1541   case Instruction::InsertValue:
1542     return ConstantExpr::getInsertValue(Ops[0], Ops[1], getIndices(),
1543                                         OnlyIfReducedTy);
1544   case Instruction::ExtractValue:
1545     return ConstantExpr::getExtractValue(Ops[0], getIndices(), OnlyIfReducedTy);
1546   case Instruction::FNeg:
1547     return ConstantExpr::getFNeg(Ops[0]);
1548   case Instruction::ShuffleVector:
1549     return ConstantExpr::getShuffleVector(Ops[0], Ops[1], getShuffleMask(),
1550                                           OnlyIfReducedTy);
1551   case Instruction::GetElementPtr: {
1552     auto *GEPO = cast<GEPOperator>(this);
1553     assert(SrcTy || (Ops[0]->getType() == getOperand(0)->getType()));
1554     return ConstantExpr::getGetElementPtr(
1555         SrcTy ? SrcTy : GEPO->getSourceElementType(), Ops[0], Ops.slice(1),
1556         GEPO->isInBounds(), GEPO->getInRangeIndex(), OnlyIfReducedTy);
1557   }
1558   case Instruction::ICmp:
1559   case Instruction::FCmp:
1560     return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1],
1561                                     OnlyIfReducedTy);
1562   default:
1563     assert(getNumOperands() == 2 && "Must be binary operator?");
1564     return ConstantExpr::get(getOpcode(), Ops[0], Ops[1], SubclassOptionalData,
1565                              OnlyIfReducedTy);
1566   }
1567 }
1568 
1569 
1570 //===----------------------------------------------------------------------===//
1571 //                      isValueValidForType implementations
1572 
1573 bool ConstantInt::isValueValidForType(Type *Ty, uint64_t Val) {
1574   unsigned NumBits = Ty->getIntegerBitWidth(); // assert okay
1575   if (Ty->isIntegerTy(1))
1576     return Val == 0 || Val == 1;
1577   return isUIntN(NumBits, Val);
1578 }
1579 
1580 bool ConstantInt::isValueValidForType(Type *Ty, int64_t Val) {
1581   unsigned NumBits = Ty->getIntegerBitWidth();
1582   if (Ty->isIntegerTy(1))
1583     return Val == 0 || Val == 1 || Val == -1;
1584   return isIntN(NumBits, Val);
1585 }
1586 
1587 bool ConstantFP::isValueValidForType(Type *Ty, const APFloat& Val) {
1588   // convert modifies in place, so make a copy.
1589   APFloat Val2 = APFloat(Val);
1590   bool losesInfo;
1591   switch (Ty->getTypeID()) {
1592   default:
1593     return false;         // These can't be represented as floating point!
1594 
1595   // FIXME rounding mode needs to be more flexible
1596   case Type::HalfTyID: {
1597     if (&Val2.getSemantics() == &APFloat::IEEEhalf())
1598       return true;
1599     Val2.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven, &losesInfo);
1600     return !losesInfo;
1601   }
1602   case Type::BFloatTyID: {
1603     if (&Val2.getSemantics() == &APFloat::BFloat())
1604       return true;
1605     Val2.convert(APFloat::BFloat(), APFloat::rmNearestTiesToEven, &losesInfo);
1606     return !losesInfo;
1607   }
1608   case Type::FloatTyID: {
1609     if (&Val2.getSemantics() == &APFloat::IEEEsingle())
1610       return true;
1611     Val2.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, &losesInfo);
1612     return !losesInfo;
1613   }
1614   case Type::DoubleTyID: {
1615     if (&Val2.getSemantics() == &APFloat::IEEEhalf() ||
1616         &Val2.getSemantics() == &APFloat::BFloat() ||
1617         &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1618         &Val2.getSemantics() == &APFloat::IEEEdouble())
1619       return true;
1620     Val2.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, &losesInfo);
1621     return !losesInfo;
1622   }
1623   case Type::X86_FP80TyID:
1624     return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
1625            &Val2.getSemantics() == &APFloat::BFloat() ||
1626            &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1627            &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1628            &Val2.getSemantics() == &APFloat::x87DoubleExtended();
1629   case Type::FP128TyID:
1630     return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
1631            &Val2.getSemantics() == &APFloat::BFloat() ||
1632            &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1633            &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1634            &Val2.getSemantics() == &APFloat::IEEEquad();
1635   case Type::PPC_FP128TyID:
1636     return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
1637            &Val2.getSemantics() == &APFloat::BFloat() ||
1638            &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1639            &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1640            &Val2.getSemantics() == &APFloat::PPCDoubleDouble();
1641   }
1642 }
1643 
1644 
1645 //===----------------------------------------------------------------------===//
1646 //                      Factory Function Implementation
1647 
1648 ConstantAggregateZero *ConstantAggregateZero::get(Type *Ty) {
1649   assert((Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()) &&
1650          "Cannot create an aggregate zero of non-aggregate type!");
1651 
1652   std::unique_ptr<ConstantAggregateZero> &Entry =
1653       Ty->getContext().pImpl->CAZConstants[Ty];
1654   if (!Entry)
1655     Entry.reset(new ConstantAggregateZero(Ty));
1656 
1657   return Entry.get();
1658 }
1659 
1660 /// Remove the constant from the constant table.
1661 void ConstantAggregateZero::destroyConstantImpl() {
1662   getContext().pImpl->CAZConstants.erase(getType());
1663 }
1664 
1665 /// Remove the constant from the constant table.
1666 void ConstantArray::destroyConstantImpl() {
1667   getType()->getContext().pImpl->ArrayConstants.remove(this);
1668 }
1669 
1670 
1671 //---- ConstantStruct::get() implementation...
1672 //
1673 
1674 /// Remove the constant from the constant table.
1675 void ConstantStruct::destroyConstantImpl() {
1676   getType()->getContext().pImpl->StructConstants.remove(this);
1677 }
1678 
1679 /// Remove the constant from the constant table.
1680 void ConstantVector::destroyConstantImpl() {
1681   getType()->getContext().pImpl->VectorConstants.remove(this);
1682 }
1683 
1684 Constant *Constant::getSplatValue(bool AllowUndefs) const {
1685   assert(this->getType()->isVectorTy() && "Only valid for vectors!");
1686   if (isa<ConstantAggregateZero>(this))
1687     return getNullValue(cast<VectorType>(getType())->getElementType());
1688   if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
1689     return CV->getSplatValue();
1690   if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
1691     return CV->getSplatValue(AllowUndefs);
1692 
1693   // Check if this is a constant expression splat of the form returned by
1694   // ConstantVector::getSplat()
1695   const auto *Shuf = dyn_cast<ConstantExpr>(this);
1696   if (Shuf && Shuf->getOpcode() == Instruction::ShuffleVector &&
1697       isa<UndefValue>(Shuf->getOperand(1))) {
1698 
1699     const auto *IElt = dyn_cast<ConstantExpr>(Shuf->getOperand(0));
1700     if (IElt && IElt->getOpcode() == Instruction::InsertElement &&
1701         isa<UndefValue>(IElt->getOperand(0))) {
1702 
1703       ArrayRef<int> Mask = Shuf->getShuffleMask();
1704       Constant *SplatVal = IElt->getOperand(1);
1705       ConstantInt *Index = dyn_cast<ConstantInt>(IElt->getOperand(2));
1706 
1707       if (Index && Index->getValue() == 0 &&
1708           llvm::all_of(Mask, [](int I) { return I == 0; }))
1709         return SplatVal;
1710     }
1711   }
1712 
1713   return nullptr;
1714 }
1715 
1716 Constant *ConstantVector::getSplatValue(bool AllowUndefs) const {
1717   // Check out first element.
1718   Constant *Elt = getOperand(0);
1719   // Then make sure all remaining elements point to the same value.
1720   for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1721     Constant *OpC = getOperand(I);
1722     if (OpC == Elt)
1723       continue;
1724 
1725     // Strict mode: any mismatch is not a splat.
1726     if (!AllowUndefs)
1727       return nullptr;
1728 
1729     // Allow undefs mode: ignore undefined elements.
1730     if (isa<UndefValue>(OpC))
1731       continue;
1732 
1733     // If we do not have a defined element yet, use the current operand.
1734     if (isa<UndefValue>(Elt))
1735       Elt = OpC;
1736 
1737     if (OpC != Elt)
1738       return nullptr;
1739   }
1740   return Elt;
1741 }
1742 
1743 const APInt &Constant::getUniqueInteger() const {
1744   if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
1745     return CI->getValue();
1746   assert(this->getSplatValue() && "Doesn't contain a unique integer!");
1747   const Constant *C = this->getAggregateElement(0U);
1748   assert(C && isa<ConstantInt>(C) && "Not a vector of numbers!");
1749   return cast<ConstantInt>(C)->getValue();
1750 }
1751 
1752 //---- ConstantPointerNull::get() implementation.
1753 //
1754 
1755 ConstantPointerNull *ConstantPointerNull::get(PointerType *Ty) {
1756   std::unique_ptr<ConstantPointerNull> &Entry =
1757       Ty->getContext().pImpl->CPNConstants[Ty];
1758   if (!Entry)
1759     Entry.reset(new ConstantPointerNull(Ty));
1760 
1761   return Entry.get();
1762 }
1763 
1764 /// Remove the constant from the constant table.
1765 void ConstantPointerNull::destroyConstantImpl() {
1766   getContext().pImpl->CPNConstants.erase(getType());
1767 }
1768 
1769 UndefValue *UndefValue::get(Type *Ty) {
1770   std::unique_ptr<UndefValue> &Entry = Ty->getContext().pImpl->UVConstants[Ty];
1771   if (!Entry)
1772     Entry.reset(new UndefValue(Ty));
1773 
1774   return Entry.get();
1775 }
1776 
1777 /// Remove the constant from the constant table.
1778 void UndefValue::destroyConstantImpl() {
1779   // Free the constant and any dangling references to it.
1780   if (getValueID() == UndefValueVal) {
1781     getContext().pImpl->UVConstants.erase(getType());
1782   } else if (getValueID() == PoisonValueVal) {
1783     getContext().pImpl->PVConstants.erase(getType());
1784   }
1785   llvm_unreachable("Not a undef or a poison!");
1786 }
1787 
1788 PoisonValue *PoisonValue::get(Type *Ty) {
1789   std::unique_ptr<PoisonValue> &Entry = Ty->getContext().pImpl->PVConstants[Ty];
1790   if (!Entry)
1791     Entry.reset(new PoisonValue(Ty));
1792 
1793   return Entry.get();
1794 }
1795 
1796 /// Remove the constant from the constant table.
1797 void PoisonValue::destroyConstantImpl() {
1798   // Free the constant and any dangling references to it.
1799   getContext().pImpl->PVConstants.erase(getType());
1800 }
1801 
1802 BlockAddress *BlockAddress::get(BasicBlock *BB) {
1803   assert(BB->getParent() && "Block must have a parent");
1804   return get(BB->getParent(), BB);
1805 }
1806 
1807 BlockAddress *BlockAddress::get(Function *F, BasicBlock *BB) {
1808   BlockAddress *&BA =
1809     F->getContext().pImpl->BlockAddresses[std::make_pair(F, BB)];
1810   if (!BA)
1811     BA = new BlockAddress(F, BB);
1812 
1813   assert(BA->getFunction() == F && "Basic block moved between functions");
1814   return BA;
1815 }
1816 
1817 BlockAddress::BlockAddress(Function *F, BasicBlock *BB)
1818     : Constant(Type::getInt8PtrTy(F->getContext(), F->getAddressSpace()),
1819                Value::BlockAddressVal, &Op<0>(), 2) {
1820   setOperand(0, F);
1821   setOperand(1, BB);
1822   BB->AdjustBlockAddressRefCount(1);
1823 }
1824 
1825 BlockAddress *BlockAddress::lookup(const BasicBlock *BB) {
1826   if (!BB->hasAddressTaken())
1827     return nullptr;
1828 
1829   const Function *F = BB->getParent();
1830   assert(F && "Block must have a parent");
1831   BlockAddress *BA =
1832       F->getContext().pImpl->BlockAddresses.lookup(std::make_pair(F, BB));
1833   assert(BA && "Refcount and block address map disagree!");
1834   return BA;
1835 }
1836 
1837 /// Remove the constant from the constant table.
1838 void BlockAddress::destroyConstantImpl() {
1839   getFunction()->getType()->getContext().pImpl
1840     ->BlockAddresses.erase(std::make_pair(getFunction(), getBasicBlock()));
1841   getBasicBlock()->AdjustBlockAddressRefCount(-1);
1842 }
1843 
1844 Value *BlockAddress::handleOperandChangeImpl(Value *From, Value *To) {
1845   // This could be replacing either the Basic Block or the Function.  In either
1846   // case, we have to remove the map entry.
1847   Function *NewF = getFunction();
1848   BasicBlock *NewBB = getBasicBlock();
1849 
1850   if (From == NewF)
1851     NewF = cast<Function>(To->stripPointerCasts());
1852   else {
1853     assert(From == NewBB && "From does not match any operand");
1854     NewBB = cast<BasicBlock>(To);
1855   }
1856 
1857   // See if the 'new' entry already exists, if not, just update this in place
1858   // and return early.
1859   BlockAddress *&NewBA =
1860     getContext().pImpl->BlockAddresses[std::make_pair(NewF, NewBB)];
1861   if (NewBA)
1862     return NewBA;
1863 
1864   getBasicBlock()->AdjustBlockAddressRefCount(-1);
1865 
1866   // Remove the old entry, this can't cause the map to rehash (just a
1867   // tombstone will get added).
1868   getContext().pImpl->BlockAddresses.erase(std::make_pair(getFunction(),
1869                                                           getBasicBlock()));
1870   NewBA = this;
1871   setOperand(0, NewF);
1872   setOperand(1, NewBB);
1873   getBasicBlock()->AdjustBlockAddressRefCount(1);
1874 
1875   // If we just want to keep the existing value, then return null.
1876   // Callers know that this means we shouldn't delete this value.
1877   return nullptr;
1878 }
1879 
1880 DSOLocalEquivalent *DSOLocalEquivalent::get(GlobalValue *GV) {
1881   DSOLocalEquivalent *&Equiv = GV->getContext().pImpl->DSOLocalEquivalents[GV];
1882   if (!Equiv)
1883     Equiv = new DSOLocalEquivalent(GV);
1884 
1885   assert(Equiv->getGlobalValue() == GV &&
1886          "DSOLocalFunction does not match the expected global value");
1887   return Equiv;
1888 }
1889 
1890 DSOLocalEquivalent::DSOLocalEquivalent(GlobalValue *GV)
1891     : Constant(GV->getType(), Value::DSOLocalEquivalentVal, &Op<0>(), 1) {
1892   setOperand(0, GV);
1893 }
1894 
1895 /// Remove the constant from the constant table.
1896 void DSOLocalEquivalent::destroyConstantImpl() {
1897   const GlobalValue *GV = getGlobalValue();
1898   GV->getContext().pImpl->DSOLocalEquivalents.erase(GV);
1899 }
1900 
1901 Value *DSOLocalEquivalent::handleOperandChangeImpl(Value *From, Value *To) {
1902   assert(From == getGlobalValue() && "Changing value does not match operand.");
1903   assert(isa<Constant>(To) && "Can only replace the operands with a constant");
1904 
1905   // The replacement is with another global value.
1906   if (const auto *ToObj = dyn_cast<GlobalValue>(To)) {
1907     DSOLocalEquivalent *&NewEquiv =
1908         getContext().pImpl->DSOLocalEquivalents[ToObj];
1909     if (NewEquiv)
1910       return llvm::ConstantExpr::getBitCast(NewEquiv, getType());
1911   }
1912 
1913   // If the argument is replaced with a null value, just replace this constant
1914   // with a null value.
1915   if (cast<Constant>(To)->isNullValue())
1916     return To;
1917 
1918   // The replacement could be a bitcast or an alias to another function. We can
1919   // replace it with a bitcast to the dso_local_equivalent of that function.
1920   auto *Func = cast<Function>(To->stripPointerCastsAndAliases());
1921   DSOLocalEquivalent *&NewEquiv = getContext().pImpl->DSOLocalEquivalents[Func];
1922   if (NewEquiv)
1923     return llvm::ConstantExpr::getBitCast(NewEquiv, getType());
1924 
1925   // Replace this with the new one.
1926   getContext().pImpl->DSOLocalEquivalents.erase(getGlobalValue());
1927   NewEquiv = this;
1928   setOperand(0, Func);
1929 
1930   if (Func->getType() != getType()) {
1931     // It is ok to mutate the type here because this constant should always
1932     // reflect the type of the function it's holding.
1933     mutateType(Func->getType());
1934   }
1935   return nullptr;
1936 }
1937 
1938 NoCFIValue *NoCFIValue::get(GlobalValue *GV) {
1939   NoCFIValue *&NC = GV->getContext().pImpl->NoCFIValues[GV];
1940   if (!NC)
1941     NC = new NoCFIValue(GV);
1942 
1943   assert(NC->getGlobalValue() == GV &&
1944          "NoCFIValue does not match the expected global value");
1945   return NC;
1946 }
1947 
1948 NoCFIValue::NoCFIValue(GlobalValue *GV)
1949     : Constant(GV->getType(), Value::NoCFIValueVal, &Op<0>(), 1) {
1950   setOperand(0, GV);
1951 }
1952 
1953 /// Remove the constant from the constant table.
1954 void NoCFIValue::destroyConstantImpl() {
1955   const GlobalValue *GV = getGlobalValue();
1956   GV->getContext().pImpl->NoCFIValues.erase(GV);
1957 }
1958 
1959 Value *NoCFIValue::handleOperandChangeImpl(Value *From, Value *To) {
1960   assert(From == getGlobalValue() && "Changing value does not match operand.");
1961 
1962   GlobalValue *GV = dyn_cast<GlobalValue>(To->stripPointerCasts());
1963   assert(GV && "Can only replace the operands with a global value");
1964 
1965   NoCFIValue *&NewNC = getContext().pImpl->NoCFIValues[GV];
1966   if (NewNC)
1967     return llvm::ConstantExpr::getBitCast(NewNC, getType());
1968 
1969   getContext().pImpl->NoCFIValues.erase(getGlobalValue());
1970   NewNC = this;
1971   setOperand(0, GV);
1972 
1973   if (GV->getType() != getType())
1974     mutateType(GV->getType());
1975 
1976   return nullptr;
1977 }
1978 
1979 //---- ConstantExpr::get() implementations.
1980 //
1981 
1982 /// This is a utility function to handle folding of casts and lookup of the
1983 /// cast in the ExprConstants map. It is used by the various get* methods below.
1984 static Constant *getFoldedCast(Instruction::CastOps opc, Constant *C, Type *Ty,
1985                                bool OnlyIfReduced = false) {
1986   assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1987   // Fold a few common cases
1988   if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1989     return FC;
1990 
1991   if (OnlyIfReduced)
1992     return nullptr;
1993 
1994   LLVMContextImpl *pImpl = Ty->getContext().pImpl;
1995 
1996   // Look up the constant in the table first to ensure uniqueness.
1997   ConstantExprKeyType Key(opc, C);
1998 
1999   return pImpl->ExprConstants.getOrCreate(Ty, Key);
2000 }
2001 
2002 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, Type *Ty,
2003                                 bool OnlyIfReduced) {
2004   Instruction::CastOps opc = Instruction::CastOps(oc);
2005   assert(Instruction::isCast(opc) && "opcode out of range");
2006   assert(C && Ty && "Null arguments to getCast");
2007   assert(CastInst::castIsValid(opc, C, Ty) && "Invalid constantexpr cast!");
2008 
2009   switch (opc) {
2010   default:
2011     llvm_unreachable("Invalid cast opcode");
2012   case Instruction::Trunc:
2013     return getTrunc(C, Ty, OnlyIfReduced);
2014   case Instruction::ZExt:
2015     return getZExt(C, Ty, OnlyIfReduced);
2016   case Instruction::SExt:
2017     return getSExt(C, Ty, OnlyIfReduced);
2018   case Instruction::FPTrunc:
2019     return getFPTrunc(C, Ty, OnlyIfReduced);
2020   case Instruction::FPExt:
2021     return getFPExtend(C, Ty, OnlyIfReduced);
2022   case Instruction::UIToFP:
2023     return getUIToFP(C, Ty, OnlyIfReduced);
2024   case Instruction::SIToFP:
2025     return getSIToFP(C, Ty, OnlyIfReduced);
2026   case Instruction::FPToUI:
2027     return getFPToUI(C, Ty, OnlyIfReduced);
2028   case Instruction::FPToSI:
2029     return getFPToSI(C, Ty, OnlyIfReduced);
2030   case Instruction::PtrToInt:
2031     return getPtrToInt(C, Ty, OnlyIfReduced);
2032   case Instruction::IntToPtr:
2033     return getIntToPtr(C, Ty, OnlyIfReduced);
2034   case Instruction::BitCast:
2035     return getBitCast(C, Ty, OnlyIfReduced);
2036   case Instruction::AddrSpaceCast:
2037     return getAddrSpaceCast(C, Ty, OnlyIfReduced);
2038   }
2039 }
2040 
2041 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, Type *Ty) {
2042   if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2043     return getBitCast(C, Ty);
2044   return getZExt(C, Ty);
2045 }
2046 
2047 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, Type *Ty) {
2048   if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2049     return getBitCast(C, Ty);
2050   return getSExt(C, Ty);
2051 }
2052 
2053 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, Type *Ty) {
2054   if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2055     return getBitCast(C, Ty);
2056   return getTrunc(C, Ty);
2057 }
2058 
2059 Constant *ConstantExpr::getSExtOrTrunc(Constant *C, Type *Ty) {
2060   assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
2061          "Can only sign extend/truncate integers!");
2062   Type *CTy = C->getType();
2063   if (CTy->getScalarSizeInBits() < Ty->getScalarSizeInBits())
2064     return getSExt(C, Ty);
2065   if (CTy->getScalarSizeInBits() > Ty->getScalarSizeInBits())
2066     return getTrunc(C, Ty);
2067   return C;
2068 }
2069 
2070 Constant *ConstantExpr::getPointerCast(Constant *S, Type *Ty) {
2071   assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2072   assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
2073           "Invalid cast");
2074 
2075   if (Ty->isIntOrIntVectorTy())
2076     return getPtrToInt(S, Ty);
2077 
2078   unsigned SrcAS = S->getType()->getPointerAddressSpace();
2079   if (Ty->isPtrOrPtrVectorTy() && SrcAS != Ty->getPointerAddressSpace())
2080     return getAddrSpaceCast(S, Ty);
2081 
2082   return getBitCast(S, Ty);
2083 }
2084 
2085 Constant *ConstantExpr::getPointerBitCastOrAddrSpaceCast(Constant *S,
2086                                                          Type *Ty) {
2087   assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2088   assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
2089 
2090   if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
2091     return getAddrSpaceCast(S, Ty);
2092 
2093   return getBitCast(S, Ty);
2094 }
2095 
2096 Constant *ConstantExpr::getIntegerCast(Constant *C, Type *Ty, bool isSigned) {
2097   assert(C->getType()->isIntOrIntVectorTy() &&
2098          Ty->isIntOrIntVectorTy() && "Invalid cast");
2099   unsigned SrcBits = C->getType()->getScalarSizeInBits();
2100   unsigned DstBits = Ty->getScalarSizeInBits();
2101   Instruction::CastOps opcode =
2102     (SrcBits == DstBits ? Instruction::BitCast :
2103      (SrcBits > DstBits ? Instruction::Trunc :
2104       (isSigned ? Instruction::SExt : Instruction::ZExt)));
2105   return getCast(opcode, C, Ty);
2106 }
2107 
2108 Constant *ConstantExpr::getFPCast(Constant *C, Type *Ty) {
2109   assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
2110          "Invalid cast");
2111   unsigned SrcBits = C->getType()->getScalarSizeInBits();
2112   unsigned DstBits = Ty->getScalarSizeInBits();
2113   if (SrcBits == DstBits)
2114     return C; // Avoid a useless cast
2115   Instruction::CastOps opcode =
2116     (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
2117   return getCast(opcode, C, Ty);
2118 }
2119 
2120 Constant *ConstantExpr::getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) {
2121 #ifndef NDEBUG
2122   bool fromVec = isa<VectorType>(C->getType());
2123   bool toVec = isa<VectorType>(Ty);
2124 #endif
2125   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2126   assert(C->getType()->isIntOrIntVectorTy() && "Trunc operand must be integer");
2127   assert(Ty->isIntOrIntVectorTy() && "Trunc produces only integral");
2128   assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
2129          "SrcTy must be larger than DestTy for Trunc!");
2130 
2131   return getFoldedCast(Instruction::Trunc, C, Ty, OnlyIfReduced);
2132 }
2133 
2134 Constant *ConstantExpr::getSExt(Constant *C, Type *Ty, bool OnlyIfReduced) {
2135 #ifndef NDEBUG
2136   bool fromVec = isa<VectorType>(C->getType());
2137   bool toVec = isa<VectorType>(Ty);
2138 #endif
2139   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2140   assert(C->getType()->isIntOrIntVectorTy() && "SExt operand must be integral");
2141   assert(Ty->isIntOrIntVectorTy() && "SExt produces only integer");
2142   assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
2143          "SrcTy must be smaller than DestTy for SExt!");
2144 
2145   return getFoldedCast(Instruction::SExt, C, Ty, OnlyIfReduced);
2146 }
2147 
2148 Constant *ConstantExpr::getZExt(Constant *C, Type *Ty, bool OnlyIfReduced) {
2149 #ifndef NDEBUG
2150   bool fromVec = isa<VectorType>(C->getType());
2151   bool toVec = isa<VectorType>(Ty);
2152 #endif
2153   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2154   assert(C->getType()->isIntOrIntVectorTy() && "ZEXt operand must be integral");
2155   assert(Ty->isIntOrIntVectorTy() && "ZExt produces only integer");
2156   assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
2157          "SrcTy must be smaller than DestTy for ZExt!");
2158 
2159   return getFoldedCast(Instruction::ZExt, C, Ty, OnlyIfReduced);
2160 }
2161 
2162 Constant *ConstantExpr::getFPTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) {
2163 #ifndef NDEBUG
2164   bool fromVec = isa<VectorType>(C->getType());
2165   bool toVec = isa<VectorType>(Ty);
2166 #endif
2167   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2168   assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
2169          C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
2170          "This is an illegal floating point truncation!");
2171   return getFoldedCast(Instruction::FPTrunc, C, Ty, OnlyIfReduced);
2172 }
2173 
2174 Constant *ConstantExpr::getFPExtend(Constant *C, Type *Ty, bool OnlyIfReduced) {
2175 #ifndef NDEBUG
2176   bool fromVec = isa<VectorType>(C->getType());
2177   bool toVec = isa<VectorType>(Ty);
2178 #endif
2179   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2180   assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
2181          C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
2182          "This is an illegal floating point extension!");
2183   return getFoldedCast(Instruction::FPExt, C, Ty, OnlyIfReduced);
2184 }
2185 
2186 Constant *ConstantExpr::getUIToFP(Constant *C, Type *Ty, bool OnlyIfReduced) {
2187 #ifndef NDEBUG
2188   bool fromVec = isa<VectorType>(C->getType());
2189   bool toVec = isa<VectorType>(Ty);
2190 #endif
2191   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2192   assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
2193          "This is an illegal uint to floating point cast!");
2194   return getFoldedCast(Instruction::UIToFP, C, Ty, OnlyIfReduced);
2195 }
2196 
2197 Constant *ConstantExpr::getSIToFP(Constant *C, Type *Ty, bool OnlyIfReduced) {
2198 #ifndef NDEBUG
2199   bool fromVec = isa<VectorType>(C->getType());
2200   bool toVec = isa<VectorType>(Ty);
2201 #endif
2202   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2203   assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
2204          "This is an illegal sint to floating point cast!");
2205   return getFoldedCast(Instruction::SIToFP, C, Ty, OnlyIfReduced);
2206 }
2207 
2208 Constant *ConstantExpr::getFPToUI(Constant *C, Type *Ty, bool OnlyIfReduced) {
2209 #ifndef NDEBUG
2210   bool fromVec = isa<VectorType>(C->getType());
2211   bool toVec = isa<VectorType>(Ty);
2212 #endif
2213   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2214   assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
2215          "This is an illegal floating point to uint cast!");
2216   return getFoldedCast(Instruction::FPToUI, C, Ty, OnlyIfReduced);
2217 }
2218 
2219 Constant *ConstantExpr::getFPToSI(Constant *C, Type *Ty, bool OnlyIfReduced) {
2220 #ifndef NDEBUG
2221   bool fromVec = isa<VectorType>(C->getType());
2222   bool toVec = isa<VectorType>(Ty);
2223 #endif
2224   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2225   assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
2226          "This is an illegal floating point to sint cast!");
2227   return getFoldedCast(Instruction::FPToSI, C, Ty, OnlyIfReduced);
2228 }
2229 
2230 Constant *ConstantExpr::getPtrToInt(Constant *C, Type *DstTy,
2231                                     bool OnlyIfReduced) {
2232   assert(C->getType()->isPtrOrPtrVectorTy() &&
2233          "PtrToInt source must be pointer or pointer vector");
2234   assert(DstTy->isIntOrIntVectorTy() &&
2235          "PtrToInt destination must be integer or integer vector");
2236   assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
2237   if (isa<VectorType>(C->getType()))
2238     assert(cast<FixedVectorType>(C->getType())->getNumElements() ==
2239                cast<FixedVectorType>(DstTy)->getNumElements() &&
2240            "Invalid cast between a different number of vector elements");
2241   return getFoldedCast(Instruction::PtrToInt, C, DstTy, OnlyIfReduced);
2242 }
2243 
2244 Constant *ConstantExpr::getIntToPtr(Constant *C, Type *DstTy,
2245                                     bool OnlyIfReduced) {
2246   assert(C->getType()->isIntOrIntVectorTy() &&
2247          "IntToPtr source must be integer or integer vector");
2248   assert(DstTy->isPtrOrPtrVectorTy() &&
2249          "IntToPtr destination must be a pointer or pointer vector");
2250   assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
2251   if (isa<VectorType>(C->getType()))
2252     assert(cast<VectorType>(C->getType())->getElementCount() ==
2253                cast<VectorType>(DstTy)->getElementCount() &&
2254            "Invalid cast between a different number of vector elements");
2255   return getFoldedCast(Instruction::IntToPtr, C, DstTy, OnlyIfReduced);
2256 }
2257 
2258 Constant *ConstantExpr::getBitCast(Constant *C, Type *DstTy,
2259                                    bool OnlyIfReduced) {
2260   assert(CastInst::castIsValid(Instruction::BitCast, C, DstTy) &&
2261          "Invalid constantexpr bitcast!");
2262 
2263   // It is common to ask for a bitcast of a value to its own type, handle this
2264   // speedily.
2265   if (C->getType() == DstTy) return C;
2266 
2267   return getFoldedCast(Instruction::BitCast, C, DstTy, OnlyIfReduced);
2268 }
2269 
2270 Constant *ConstantExpr::getAddrSpaceCast(Constant *C, Type *DstTy,
2271                                          bool OnlyIfReduced) {
2272   assert(CastInst::castIsValid(Instruction::AddrSpaceCast, C, DstTy) &&
2273          "Invalid constantexpr addrspacecast!");
2274 
2275   // Canonicalize addrspacecasts between different pointer types by first
2276   // bitcasting the pointer type and then converting the address space.
2277   PointerType *SrcScalarTy = cast<PointerType>(C->getType()->getScalarType());
2278   PointerType *DstScalarTy = cast<PointerType>(DstTy->getScalarType());
2279   if (!SrcScalarTy->hasSameElementTypeAs(DstScalarTy)) {
2280     Type *MidTy = PointerType::getWithSamePointeeType(
2281         DstScalarTy, SrcScalarTy->getAddressSpace());
2282     if (VectorType *VT = dyn_cast<VectorType>(DstTy)) {
2283       // Handle vectors of pointers.
2284       MidTy = FixedVectorType::get(MidTy,
2285                                    cast<FixedVectorType>(VT)->getNumElements());
2286     }
2287     C = getBitCast(C, MidTy);
2288   }
2289   return getFoldedCast(Instruction::AddrSpaceCast, C, DstTy, OnlyIfReduced);
2290 }
2291 
2292 Constant *ConstantExpr::get(unsigned Opcode, Constant *C, unsigned Flags,
2293                             Type *OnlyIfReducedTy) {
2294   // Check the operands for consistency first.
2295   assert(Instruction::isUnaryOp(Opcode) &&
2296          "Invalid opcode in unary constant expression");
2297 
2298 #ifndef NDEBUG
2299   switch (Opcode) {
2300   case Instruction::FNeg:
2301     assert(C->getType()->isFPOrFPVectorTy() &&
2302            "Tried to create a floating-point operation on a "
2303            "non-floating-point type!");
2304     break;
2305   default:
2306     break;
2307   }
2308 #endif
2309 
2310   if (Constant *FC = ConstantFoldUnaryInstruction(Opcode, C))
2311     return FC;
2312 
2313   if (OnlyIfReducedTy == C->getType())
2314     return nullptr;
2315 
2316   Constant *ArgVec[] = { C };
2317   ConstantExprKeyType Key(Opcode, ArgVec, 0, Flags);
2318 
2319   LLVMContextImpl *pImpl = C->getContext().pImpl;
2320   return pImpl->ExprConstants.getOrCreate(C->getType(), Key);
2321 }
2322 
2323 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2,
2324                             unsigned Flags, Type *OnlyIfReducedTy) {
2325   // Check the operands for consistency first.
2326   assert(Instruction::isBinaryOp(Opcode) &&
2327          "Invalid opcode in binary constant expression");
2328   assert(C1->getType() == C2->getType() &&
2329          "Operand types in binary constant expression should match");
2330 
2331 #ifndef NDEBUG
2332   switch (Opcode) {
2333   case Instruction::Add:
2334   case Instruction::Sub:
2335   case Instruction::Mul:
2336   case Instruction::UDiv:
2337   case Instruction::SDiv:
2338   case Instruction::URem:
2339   case Instruction::SRem:
2340     assert(C1->getType()->isIntOrIntVectorTy() &&
2341            "Tried to create an integer operation on a non-integer type!");
2342     break;
2343   case Instruction::FAdd:
2344   case Instruction::FSub:
2345   case Instruction::FMul:
2346   case Instruction::FDiv:
2347   case Instruction::FRem:
2348     assert(C1->getType()->isFPOrFPVectorTy() &&
2349            "Tried to create a floating-point operation on a "
2350            "non-floating-point type!");
2351     break;
2352   case Instruction::And:
2353   case Instruction::Or:
2354   case Instruction::Xor:
2355     assert(C1->getType()->isIntOrIntVectorTy() &&
2356            "Tried to create a logical operation on a non-integral type!");
2357     break;
2358   case Instruction::Shl:
2359   case Instruction::LShr:
2360   case Instruction::AShr:
2361     assert(C1->getType()->isIntOrIntVectorTy() &&
2362            "Tried to create a shift operation on a non-integer type!");
2363     break;
2364   default:
2365     break;
2366   }
2367 #endif
2368 
2369   if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
2370     return FC;
2371 
2372   if (OnlyIfReducedTy == C1->getType())
2373     return nullptr;
2374 
2375   Constant *ArgVec[] = { C1, C2 };
2376   ConstantExprKeyType Key(Opcode, ArgVec, 0, Flags);
2377 
2378   LLVMContextImpl *pImpl = C1->getContext().pImpl;
2379   return pImpl->ExprConstants.getOrCreate(C1->getType(), Key);
2380 }
2381 
2382 Constant *ConstantExpr::getSizeOf(Type* Ty) {
2383   // sizeof is implemented as: (i64) gep (Ty*)null, 1
2384   // Note that a non-inbounds gep is used, as null isn't within any object.
2385   Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
2386   Constant *GEP = getGetElementPtr(
2387       Ty, Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
2388   return getPtrToInt(GEP,
2389                      Type::getInt64Ty(Ty->getContext()));
2390 }
2391 
2392 Constant *ConstantExpr::getAlignOf(Type* Ty) {
2393   // alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1
2394   // Note that a non-inbounds gep is used, as null isn't within any object.
2395   Type *AligningTy = StructType::get(Type::getInt1Ty(Ty->getContext()), Ty);
2396   Constant *NullPtr = Constant::getNullValue(AligningTy->getPointerTo(0));
2397   Constant *Zero = ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0);
2398   Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
2399   Constant *Indices[2] = { Zero, One };
2400   Constant *GEP = getGetElementPtr(AligningTy, NullPtr, Indices);
2401   return getPtrToInt(GEP,
2402                      Type::getInt64Ty(Ty->getContext()));
2403 }
2404 
2405 Constant *ConstantExpr::getOffsetOf(StructType* STy, unsigned FieldNo) {
2406   return getOffsetOf(STy, ConstantInt::get(Type::getInt32Ty(STy->getContext()),
2407                                            FieldNo));
2408 }
2409 
2410 Constant *ConstantExpr::getOffsetOf(Type* Ty, Constant *FieldNo) {
2411   // offsetof is implemented as: (i64) gep (Ty*)null, 0, FieldNo
2412   // Note that a non-inbounds gep is used, as null isn't within any object.
2413   Constant *GEPIdx[] = {
2414     ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0),
2415     FieldNo
2416   };
2417   Constant *GEP = getGetElementPtr(
2418       Ty, Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
2419   return getPtrToInt(GEP,
2420                      Type::getInt64Ty(Ty->getContext()));
2421 }
2422 
2423 Constant *ConstantExpr::getCompare(unsigned short Predicate, Constant *C1,
2424                                    Constant *C2, bool OnlyIfReduced) {
2425   assert(C1->getType() == C2->getType() && "Op types should be identical!");
2426 
2427   switch (Predicate) {
2428   default: llvm_unreachable("Invalid CmpInst predicate");
2429   case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
2430   case CmpInst::FCMP_OGE:   case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
2431   case CmpInst::FCMP_ONE:   case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
2432   case CmpInst::FCMP_UEQ:   case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
2433   case CmpInst::FCMP_ULT:   case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
2434   case CmpInst::FCMP_TRUE:
2435     return getFCmp(Predicate, C1, C2, OnlyIfReduced);
2436 
2437   case CmpInst::ICMP_EQ:  case CmpInst::ICMP_NE:  case CmpInst::ICMP_UGT:
2438   case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
2439   case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
2440   case CmpInst::ICMP_SLE:
2441     return getICmp(Predicate, C1, C2, OnlyIfReduced);
2442   }
2443 }
2444 
2445 Constant *ConstantExpr::getSelect(Constant *C, Constant *V1, Constant *V2,
2446                                   Type *OnlyIfReducedTy) {
2447   assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
2448 
2449   if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
2450     return SC;        // Fold common cases
2451 
2452   if (OnlyIfReducedTy == V1->getType())
2453     return nullptr;
2454 
2455   Constant *ArgVec[] = { C, V1, V2 };
2456   ConstantExprKeyType Key(Instruction::Select, ArgVec);
2457 
2458   LLVMContextImpl *pImpl = C->getContext().pImpl;
2459   return pImpl->ExprConstants.getOrCreate(V1->getType(), Key);
2460 }
2461 
2462 Constant *ConstantExpr::getGetElementPtr(Type *Ty, Constant *C,
2463                                          ArrayRef<Value *> Idxs, bool InBounds,
2464                                          Optional<unsigned> InRangeIndex,
2465                                          Type *OnlyIfReducedTy) {
2466   PointerType *OrigPtrTy = cast<PointerType>(C->getType()->getScalarType());
2467   assert(Ty && "Must specify element type");
2468   assert(OrigPtrTy->isOpaqueOrPointeeTypeMatches(Ty));
2469 
2470   if (Constant *FC =
2471           ConstantFoldGetElementPtr(Ty, C, InBounds, InRangeIndex, Idxs))
2472     return FC;          // Fold a few common cases.
2473 
2474   // Get the result type of the getelementptr!
2475   Type *DestTy = GetElementPtrInst::getIndexedType(Ty, Idxs);
2476   assert(DestTy && "GEP indices invalid!");
2477   unsigned AS = OrigPtrTy->getAddressSpace();
2478   Type *ReqTy = OrigPtrTy->isOpaque()
2479       ? PointerType::get(OrigPtrTy->getContext(), AS)
2480       : DestTy->getPointerTo(AS);
2481 
2482   auto EltCount = ElementCount::getFixed(0);
2483   if (VectorType *VecTy = dyn_cast<VectorType>(C->getType()))
2484     EltCount = VecTy->getElementCount();
2485   else
2486     for (auto Idx : Idxs)
2487       if (VectorType *VecTy = dyn_cast<VectorType>(Idx->getType()))
2488         EltCount = VecTy->getElementCount();
2489 
2490   if (EltCount.isNonZero())
2491     ReqTy = VectorType::get(ReqTy, EltCount);
2492 
2493   if (OnlyIfReducedTy == ReqTy)
2494     return nullptr;
2495 
2496   // Look up the constant in the table first to ensure uniqueness
2497   std::vector<Constant*> ArgVec;
2498   ArgVec.reserve(1 + Idxs.size());
2499   ArgVec.push_back(C);
2500   auto GTI = gep_type_begin(Ty, Idxs), GTE = gep_type_end(Ty, Idxs);
2501   for (; GTI != GTE; ++GTI) {
2502     auto *Idx = cast<Constant>(GTI.getOperand());
2503     assert(
2504         (!isa<VectorType>(Idx->getType()) ||
2505          cast<VectorType>(Idx->getType())->getElementCount() == EltCount) &&
2506         "getelementptr index type missmatch");
2507 
2508     if (GTI.isStruct() && Idx->getType()->isVectorTy()) {
2509       Idx = Idx->getSplatValue();
2510     } else if (GTI.isSequential() && EltCount.isNonZero() &&
2511                !Idx->getType()->isVectorTy()) {
2512       Idx = ConstantVector::getSplat(EltCount, Idx);
2513     }
2514     ArgVec.push_back(Idx);
2515   }
2516 
2517   unsigned SubClassOptionalData = InBounds ? GEPOperator::IsInBounds : 0;
2518   if (InRangeIndex && *InRangeIndex < 63)
2519     SubClassOptionalData |= (*InRangeIndex + 1) << 1;
2520   const ConstantExprKeyType Key(Instruction::GetElementPtr, ArgVec, 0,
2521                                 SubClassOptionalData, None, None, Ty);
2522 
2523   LLVMContextImpl *pImpl = C->getContext().pImpl;
2524   return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2525 }
2526 
2527 Constant *ConstantExpr::getICmp(unsigned short pred, Constant *LHS,
2528                                 Constant *RHS, bool OnlyIfReduced) {
2529   auto Predicate = static_cast<CmpInst::Predicate>(pred);
2530   assert(LHS->getType() == RHS->getType());
2531   assert(CmpInst::isIntPredicate(Predicate) && "Invalid ICmp Predicate");
2532 
2533   if (Constant *FC = ConstantFoldCompareInstruction(Predicate, LHS, RHS))
2534     return FC;          // Fold a few common cases...
2535 
2536   if (OnlyIfReduced)
2537     return nullptr;
2538 
2539   // Look up the constant in the table first to ensure uniqueness
2540   Constant *ArgVec[] = { LHS, RHS };
2541   // Get the key type with both the opcode and predicate
2542   const ConstantExprKeyType Key(Instruction::ICmp, ArgVec, Predicate);
2543 
2544   Type *ResultTy = Type::getInt1Ty(LHS->getContext());
2545   if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
2546     ResultTy = VectorType::get(ResultTy, VT->getElementCount());
2547 
2548   LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
2549   return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
2550 }
2551 
2552 Constant *ConstantExpr::getFCmp(unsigned short pred, Constant *LHS,
2553                                 Constant *RHS, bool OnlyIfReduced) {
2554   auto Predicate = static_cast<CmpInst::Predicate>(pred);
2555   assert(LHS->getType() == RHS->getType());
2556   assert(CmpInst::isFPPredicate(Predicate) && "Invalid FCmp Predicate");
2557 
2558   if (Constant *FC = ConstantFoldCompareInstruction(Predicate, LHS, RHS))
2559     return FC;          // Fold a few common cases...
2560 
2561   if (OnlyIfReduced)
2562     return nullptr;
2563 
2564   // Look up the constant in the table first to ensure uniqueness
2565   Constant *ArgVec[] = { LHS, RHS };
2566   // Get the key type with both the opcode and predicate
2567   const ConstantExprKeyType Key(Instruction::FCmp, ArgVec, Predicate);
2568 
2569   Type *ResultTy = Type::getInt1Ty(LHS->getContext());
2570   if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
2571     ResultTy = VectorType::get(ResultTy, VT->getElementCount());
2572 
2573   LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
2574   return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
2575 }
2576 
2577 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx,
2578                                           Type *OnlyIfReducedTy) {
2579   assert(Val->getType()->isVectorTy() &&
2580          "Tried to create extractelement operation on non-vector type!");
2581   assert(Idx->getType()->isIntegerTy() &&
2582          "Extractelement index must be an integer type!");
2583 
2584   if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
2585     return FC;          // Fold a few common cases.
2586 
2587   Type *ReqTy = cast<VectorType>(Val->getType())->getElementType();
2588   if (OnlyIfReducedTy == ReqTy)
2589     return nullptr;
2590 
2591   // Look up the constant in the table first to ensure uniqueness
2592   Constant *ArgVec[] = { Val, Idx };
2593   const ConstantExprKeyType Key(Instruction::ExtractElement, ArgVec);
2594 
2595   LLVMContextImpl *pImpl = Val->getContext().pImpl;
2596   return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2597 }
2598 
2599 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
2600                                          Constant *Idx, Type *OnlyIfReducedTy) {
2601   assert(Val->getType()->isVectorTy() &&
2602          "Tried to create insertelement operation on non-vector type!");
2603   assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType() &&
2604          "Insertelement types must match!");
2605   assert(Idx->getType()->isIntegerTy() &&
2606          "Insertelement index must be i32 type!");
2607 
2608   if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
2609     return FC;          // Fold a few common cases.
2610 
2611   if (OnlyIfReducedTy == Val->getType())
2612     return nullptr;
2613 
2614   // Look up the constant in the table first to ensure uniqueness
2615   Constant *ArgVec[] = { Val, Elt, Idx };
2616   const ConstantExprKeyType Key(Instruction::InsertElement, ArgVec);
2617 
2618   LLVMContextImpl *pImpl = Val->getContext().pImpl;
2619   return pImpl->ExprConstants.getOrCreate(Val->getType(), Key);
2620 }
2621 
2622 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
2623                                          ArrayRef<int> Mask,
2624                                          Type *OnlyIfReducedTy) {
2625   assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
2626          "Invalid shuffle vector constant expr operands!");
2627 
2628   if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
2629     return FC;          // Fold a few common cases.
2630 
2631   unsigned NElts = Mask.size();
2632   auto V1VTy = cast<VectorType>(V1->getType());
2633   Type *EltTy = V1VTy->getElementType();
2634   bool TypeIsScalable = isa<ScalableVectorType>(V1VTy);
2635   Type *ShufTy = VectorType::get(EltTy, NElts, TypeIsScalable);
2636 
2637   if (OnlyIfReducedTy == ShufTy)
2638     return nullptr;
2639 
2640   // Look up the constant in the table first to ensure uniqueness
2641   Constant *ArgVec[] = {V1, V2};
2642   ConstantExprKeyType Key(Instruction::ShuffleVector, ArgVec, 0, 0, None, Mask);
2643 
2644   LLVMContextImpl *pImpl = ShufTy->getContext().pImpl;
2645   return pImpl->ExprConstants.getOrCreate(ShufTy, Key);
2646 }
2647 
2648 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
2649                                        ArrayRef<unsigned> Idxs,
2650                                        Type *OnlyIfReducedTy) {
2651   assert(Agg->getType()->isFirstClassType() &&
2652          "Non-first-class type for constant insertvalue expression");
2653 
2654   assert(ExtractValueInst::getIndexedType(Agg->getType(),
2655                                           Idxs) == Val->getType() &&
2656          "insertvalue indices invalid!");
2657   Type *ReqTy = Val->getType();
2658 
2659   if (Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs))
2660     return FC;
2661 
2662   if (OnlyIfReducedTy == ReqTy)
2663     return nullptr;
2664 
2665   Constant *ArgVec[] = { Agg, Val };
2666   const ConstantExprKeyType Key(Instruction::InsertValue, ArgVec, 0, 0, Idxs);
2667 
2668   LLVMContextImpl *pImpl = Agg->getContext().pImpl;
2669   return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2670 }
2671 
2672 Constant *ConstantExpr::getExtractValue(Constant *Agg, ArrayRef<unsigned> Idxs,
2673                                         Type *OnlyIfReducedTy) {
2674   assert(Agg->getType()->isFirstClassType() &&
2675          "Tried to create extractelement operation on non-first-class type!");
2676 
2677   Type *ReqTy = ExtractValueInst::getIndexedType(Agg->getType(), Idxs);
2678   (void)ReqTy;
2679   assert(ReqTy && "extractvalue indices invalid!");
2680 
2681   assert(Agg->getType()->isFirstClassType() &&
2682          "Non-first-class type for constant extractvalue expression");
2683   if (Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs))
2684     return FC;
2685 
2686   if (OnlyIfReducedTy == ReqTy)
2687     return nullptr;
2688 
2689   Constant *ArgVec[] = { Agg };
2690   const ConstantExprKeyType Key(Instruction::ExtractValue, ArgVec, 0, 0, Idxs);
2691 
2692   LLVMContextImpl *pImpl = Agg->getContext().pImpl;
2693   return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2694 }
2695 
2696 Constant *ConstantExpr::getNeg(Constant *C, bool HasNUW, bool HasNSW) {
2697   assert(C->getType()->isIntOrIntVectorTy() &&
2698          "Cannot NEG a nonintegral value!");
2699   return getSub(ConstantFP::getZeroValueForNegation(C->getType()),
2700                 C, HasNUW, HasNSW);
2701 }
2702 
2703 Constant *ConstantExpr::getFNeg(Constant *C) {
2704   assert(C->getType()->isFPOrFPVectorTy() &&
2705          "Cannot FNEG a non-floating-point value!");
2706   return get(Instruction::FNeg, C);
2707 }
2708 
2709 Constant *ConstantExpr::getNot(Constant *C) {
2710   assert(C->getType()->isIntOrIntVectorTy() &&
2711          "Cannot NOT a nonintegral value!");
2712   return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
2713 }
2714 
2715 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2,
2716                                bool HasNUW, bool HasNSW) {
2717   unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2718                    (HasNSW ? OverflowingBinaryOperator::NoSignedWrap   : 0);
2719   return get(Instruction::Add, C1, C2, Flags);
2720 }
2721 
2722 Constant *ConstantExpr::getFAdd(Constant *C1, Constant *C2) {
2723   return get(Instruction::FAdd, C1, C2);
2724 }
2725 
2726 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2,
2727                                bool HasNUW, bool HasNSW) {
2728   unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2729                    (HasNSW ? OverflowingBinaryOperator::NoSignedWrap   : 0);
2730   return get(Instruction::Sub, C1, C2, Flags);
2731 }
2732 
2733 Constant *ConstantExpr::getFSub(Constant *C1, Constant *C2) {
2734   return get(Instruction::FSub, C1, C2);
2735 }
2736 
2737 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2,
2738                                bool HasNUW, bool HasNSW) {
2739   unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2740                    (HasNSW ? OverflowingBinaryOperator::NoSignedWrap   : 0);
2741   return get(Instruction::Mul, C1, C2, Flags);
2742 }
2743 
2744 Constant *ConstantExpr::getFMul(Constant *C1, Constant *C2) {
2745   return get(Instruction::FMul, C1, C2);
2746 }
2747 
2748 Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2, bool isExact) {
2749   return get(Instruction::UDiv, C1, C2,
2750              isExact ? PossiblyExactOperator::IsExact : 0);
2751 }
2752 
2753 Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2, bool isExact) {
2754   return get(Instruction::SDiv, C1, C2,
2755              isExact ? PossiblyExactOperator::IsExact : 0);
2756 }
2757 
2758 Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
2759   return get(Instruction::FDiv, C1, C2);
2760 }
2761 
2762 Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
2763   return get(Instruction::URem, C1, C2);
2764 }
2765 
2766 Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
2767   return get(Instruction::SRem, C1, C2);
2768 }
2769 
2770 Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
2771   return get(Instruction::FRem, C1, C2);
2772 }
2773 
2774 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
2775   return get(Instruction::And, C1, C2);
2776 }
2777 
2778 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
2779   return get(Instruction::Or, C1, C2);
2780 }
2781 
2782 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
2783   return get(Instruction::Xor, C1, C2);
2784 }
2785 
2786 Constant *ConstantExpr::getUMin(Constant *C1, Constant *C2) {
2787   Constant *Cmp = ConstantExpr::getICmp(CmpInst::ICMP_ULT, C1, C2);
2788   return getSelect(Cmp, C1, C2);
2789 }
2790 
2791 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2,
2792                                bool HasNUW, bool HasNSW) {
2793   unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2794                    (HasNSW ? OverflowingBinaryOperator::NoSignedWrap   : 0);
2795   return get(Instruction::Shl, C1, C2, Flags);
2796 }
2797 
2798 Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2, bool isExact) {
2799   return get(Instruction::LShr, C1, C2,
2800              isExact ? PossiblyExactOperator::IsExact : 0);
2801 }
2802 
2803 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2, bool isExact) {
2804   return get(Instruction::AShr, C1, C2,
2805              isExact ? PossiblyExactOperator::IsExact : 0);
2806 }
2807 
2808 Constant *ConstantExpr::getExactLogBase2(Constant *C) {
2809   Type *Ty = C->getType();
2810   const APInt *IVal;
2811   if (match(C, m_APInt(IVal)) && IVal->isPowerOf2())
2812     return ConstantInt::get(Ty, IVal->logBase2());
2813 
2814   // FIXME: We can extract pow of 2 of splat constant for scalable vectors.
2815   auto *VecTy = dyn_cast<FixedVectorType>(Ty);
2816   if (!VecTy)
2817     return nullptr;
2818 
2819   SmallVector<Constant *, 4> Elts;
2820   for (unsigned I = 0, E = VecTy->getNumElements(); I != E; ++I) {
2821     Constant *Elt = C->getAggregateElement(I);
2822     if (!Elt)
2823       return nullptr;
2824     // Note that log2(iN undef) is *NOT* iN undef, because log2(iN undef) u< N.
2825     if (isa<UndefValue>(Elt)) {
2826       Elts.push_back(Constant::getNullValue(Ty->getScalarType()));
2827       continue;
2828     }
2829     if (!match(Elt, m_APInt(IVal)) || !IVal->isPowerOf2())
2830       return nullptr;
2831     Elts.push_back(ConstantInt::get(Ty->getScalarType(), IVal->logBase2()));
2832   }
2833 
2834   return ConstantVector::get(Elts);
2835 }
2836 
2837 Constant *ConstantExpr::getBinOpIdentity(unsigned Opcode, Type *Ty,
2838                                          bool AllowRHSConstant) {
2839   assert(Instruction::isBinaryOp(Opcode) && "Only binops allowed");
2840 
2841   // Commutative opcodes: it does not matter if AllowRHSConstant is set.
2842   if (Instruction::isCommutative(Opcode)) {
2843     switch (Opcode) {
2844       case Instruction::Add: // X + 0 = X
2845       case Instruction::Or:  // X | 0 = X
2846       case Instruction::Xor: // X ^ 0 = X
2847         return Constant::getNullValue(Ty);
2848       case Instruction::Mul: // X * 1 = X
2849         return ConstantInt::get(Ty, 1);
2850       case Instruction::And: // X & -1 = X
2851         return Constant::getAllOnesValue(Ty);
2852       case Instruction::FAdd: // X + -0.0 = X
2853         // TODO: If the fadd has 'nsz', should we return +0.0?
2854         return ConstantFP::getNegativeZero(Ty);
2855       case Instruction::FMul: // X * 1.0 = X
2856         return ConstantFP::get(Ty, 1.0);
2857       default:
2858         llvm_unreachable("Every commutative binop has an identity constant");
2859     }
2860   }
2861 
2862   // Non-commutative opcodes: AllowRHSConstant must be set.
2863   if (!AllowRHSConstant)
2864     return nullptr;
2865 
2866   switch (Opcode) {
2867     case Instruction::Sub:  // X - 0 = X
2868     case Instruction::Shl:  // X << 0 = X
2869     case Instruction::LShr: // X >>u 0 = X
2870     case Instruction::AShr: // X >> 0 = X
2871     case Instruction::FSub: // X - 0.0 = X
2872       return Constant::getNullValue(Ty);
2873     case Instruction::SDiv: // X / 1 = X
2874     case Instruction::UDiv: // X /u 1 = X
2875       return ConstantInt::get(Ty, 1);
2876     case Instruction::FDiv: // X / 1.0 = X
2877       return ConstantFP::get(Ty, 1.0);
2878     default:
2879       return nullptr;
2880   }
2881 }
2882 
2883 Constant *ConstantExpr::getBinOpAbsorber(unsigned Opcode, Type *Ty) {
2884   switch (Opcode) {
2885   default:
2886     // Doesn't have an absorber.
2887     return nullptr;
2888 
2889   case Instruction::Or:
2890     return Constant::getAllOnesValue(Ty);
2891 
2892   case Instruction::And:
2893   case Instruction::Mul:
2894     return Constant::getNullValue(Ty);
2895   }
2896 }
2897 
2898 /// Remove the constant from the constant table.
2899 void ConstantExpr::destroyConstantImpl() {
2900   getType()->getContext().pImpl->ExprConstants.remove(this);
2901 }
2902 
2903 const char *ConstantExpr::getOpcodeName() const {
2904   return Instruction::getOpcodeName(getOpcode());
2905 }
2906 
2907 GetElementPtrConstantExpr::GetElementPtrConstantExpr(
2908     Type *SrcElementTy, Constant *C, ArrayRef<Constant *> IdxList, Type *DestTy)
2909     : ConstantExpr(DestTy, Instruction::GetElementPtr,
2910                    OperandTraits<GetElementPtrConstantExpr>::op_end(this) -
2911                        (IdxList.size() + 1),
2912                    IdxList.size() + 1),
2913       SrcElementTy(SrcElementTy),
2914       ResElementTy(GetElementPtrInst::getIndexedType(SrcElementTy, IdxList)) {
2915   Op<0>() = C;
2916   Use *OperandList = getOperandList();
2917   for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
2918     OperandList[i+1] = IdxList[i];
2919 }
2920 
2921 Type *GetElementPtrConstantExpr::getSourceElementType() const {
2922   return SrcElementTy;
2923 }
2924 
2925 Type *GetElementPtrConstantExpr::getResultElementType() const {
2926   return ResElementTy;
2927 }
2928 
2929 //===----------------------------------------------------------------------===//
2930 //                       ConstantData* implementations
2931 
2932 Type *ConstantDataSequential::getElementType() const {
2933   if (ArrayType *ATy = dyn_cast<ArrayType>(getType()))
2934     return ATy->getElementType();
2935   return cast<VectorType>(getType())->getElementType();
2936 }
2937 
2938 StringRef ConstantDataSequential::getRawDataValues() const {
2939   return StringRef(DataElements, getNumElements()*getElementByteSize());
2940 }
2941 
2942 bool ConstantDataSequential::isElementTypeCompatible(Type *Ty) {
2943   if (Ty->isHalfTy() || Ty->isBFloatTy() || Ty->isFloatTy() || Ty->isDoubleTy())
2944     return true;
2945   if (auto *IT = dyn_cast<IntegerType>(Ty)) {
2946     switch (IT->getBitWidth()) {
2947     case 8:
2948     case 16:
2949     case 32:
2950     case 64:
2951       return true;
2952     default: break;
2953     }
2954   }
2955   return false;
2956 }
2957 
2958 unsigned ConstantDataSequential::getNumElements() const {
2959   if (ArrayType *AT = dyn_cast<ArrayType>(getType()))
2960     return AT->getNumElements();
2961   return cast<FixedVectorType>(getType())->getNumElements();
2962 }
2963 
2964 
2965 uint64_t ConstantDataSequential::getElementByteSize() const {
2966   return getElementType()->getPrimitiveSizeInBits()/8;
2967 }
2968 
2969 /// Return the start of the specified element.
2970 const char *ConstantDataSequential::getElementPointer(unsigned Elt) const {
2971   assert(Elt < getNumElements() && "Invalid Elt");
2972   return DataElements+Elt*getElementByteSize();
2973 }
2974 
2975 
2976 /// Return true if the array is empty or all zeros.
2977 static bool isAllZeros(StringRef Arr) {
2978   for (char I : Arr)
2979     if (I != 0)
2980       return false;
2981   return true;
2982 }
2983 
2984 /// This is the underlying implementation of all of the
2985 /// ConstantDataSequential::get methods.  They all thunk down to here, providing
2986 /// the correct element type.  We take the bytes in as a StringRef because
2987 /// we *want* an underlying "char*" to avoid TBAA type punning violations.
2988 Constant *ConstantDataSequential::getImpl(StringRef Elements, Type *Ty) {
2989 #ifndef NDEBUG
2990   if (ArrayType *ATy = dyn_cast<ArrayType>(Ty))
2991     assert(isElementTypeCompatible(ATy->getElementType()));
2992   else
2993     assert(isElementTypeCompatible(cast<VectorType>(Ty)->getElementType()));
2994 #endif
2995   // If the elements are all zero or there are no elements, return a CAZ, which
2996   // is more dense and canonical.
2997   if (isAllZeros(Elements))
2998     return ConstantAggregateZero::get(Ty);
2999 
3000   // Do a lookup to see if we have already formed one of these.
3001   auto &Slot =
3002       *Ty->getContext()
3003            .pImpl->CDSConstants.insert(std::make_pair(Elements, nullptr))
3004            .first;
3005 
3006   // The bucket can point to a linked list of different CDS's that have the same
3007   // body but different types.  For example, 0,0,0,1 could be a 4 element array
3008   // of i8, or a 1-element array of i32.  They'll both end up in the same
3009   /// StringMap bucket, linked up by their Next pointers.  Walk the list.
3010   std::unique_ptr<ConstantDataSequential> *Entry = &Slot.second;
3011   for (; *Entry; Entry = &(*Entry)->Next)
3012     if ((*Entry)->getType() == Ty)
3013       return Entry->get();
3014 
3015   // Okay, we didn't get a hit.  Create a node of the right class, link it in,
3016   // and return it.
3017   if (isa<ArrayType>(Ty)) {
3018     // Use reset because std::make_unique can't access the constructor.
3019     Entry->reset(new ConstantDataArray(Ty, Slot.first().data()));
3020     return Entry->get();
3021   }
3022 
3023   assert(isa<VectorType>(Ty));
3024   // Use reset because std::make_unique can't access the constructor.
3025   Entry->reset(new ConstantDataVector(Ty, Slot.first().data()));
3026   return Entry->get();
3027 }
3028 
3029 void ConstantDataSequential::destroyConstantImpl() {
3030   // Remove the constant from the StringMap.
3031   StringMap<std::unique_ptr<ConstantDataSequential>> &CDSConstants =
3032       getType()->getContext().pImpl->CDSConstants;
3033 
3034   auto Slot = CDSConstants.find(getRawDataValues());
3035 
3036   assert(Slot != CDSConstants.end() && "CDS not found in uniquing table");
3037 
3038   std::unique_ptr<ConstantDataSequential> *Entry = &Slot->getValue();
3039 
3040   // Remove the entry from the hash table.
3041   if (!(*Entry)->Next) {
3042     // If there is only one value in the bucket (common case) it must be this
3043     // entry, and removing the entry should remove the bucket completely.
3044     assert(Entry->get() == this && "Hash mismatch in ConstantDataSequential");
3045     getContext().pImpl->CDSConstants.erase(Slot);
3046     return;
3047   }
3048 
3049   // Otherwise, there are multiple entries linked off the bucket, unlink the
3050   // node we care about but keep the bucket around.
3051   while (true) {
3052     std::unique_ptr<ConstantDataSequential> &Node = *Entry;
3053     assert(Node && "Didn't find entry in its uniquing hash table!");
3054     // If we found our entry, unlink it from the list and we're done.
3055     if (Node.get() == this) {
3056       Node = std::move(Node->Next);
3057       return;
3058     }
3059 
3060     Entry = &Node->Next;
3061   }
3062 }
3063 
3064 /// getFP() constructors - Return a constant of array type with a float
3065 /// element type taken from argument `ElementType', and count taken from
3066 /// argument `Elts'.  The amount of bits of the contained type must match the
3067 /// number of bits of the type contained in the passed in ArrayRef.
3068 /// (i.e. half or bfloat for 16bits, float for 32bits, double for 64bits) Note
3069 /// that this can return a ConstantAggregateZero object.
3070 Constant *ConstantDataArray::getFP(Type *ElementType, ArrayRef<uint16_t> Elts) {
3071   assert((ElementType->isHalfTy() || ElementType->isBFloatTy()) &&
3072          "Element type is not a 16-bit float type");
3073   Type *Ty = ArrayType::get(ElementType, Elts.size());
3074   const char *Data = reinterpret_cast<const char *>(Elts.data());
3075   return getImpl(StringRef(Data, Elts.size() * 2), Ty);
3076 }
3077 Constant *ConstantDataArray::getFP(Type *ElementType, ArrayRef<uint32_t> Elts) {
3078   assert(ElementType->isFloatTy() && "Element type is not a 32-bit float type");
3079   Type *Ty = ArrayType::get(ElementType, Elts.size());
3080   const char *Data = reinterpret_cast<const char *>(Elts.data());
3081   return getImpl(StringRef(Data, Elts.size() * 4), Ty);
3082 }
3083 Constant *ConstantDataArray::getFP(Type *ElementType, ArrayRef<uint64_t> Elts) {
3084   assert(ElementType->isDoubleTy() &&
3085          "Element type is not a 64-bit float type");
3086   Type *Ty = ArrayType::get(ElementType, Elts.size());
3087   const char *Data = reinterpret_cast<const char *>(Elts.data());
3088   return getImpl(StringRef(Data, Elts.size() * 8), Ty);
3089 }
3090 
3091 Constant *ConstantDataArray::getString(LLVMContext &Context,
3092                                        StringRef Str, bool AddNull) {
3093   if (!AddNull) {
3094     const uint8_t *Data = Str.bytes_begin();
3095     return get(Context, makeArrayRef(Data, Str.size()));
3096   }
3097 
3098   SmallVector<uint8_t, 64> ElementVals;
3099   ElementVals.append(Str.begin(), Str.end());
3100   ElementVals.push_back(0);
3101   return get(Context, ElementVals);
3102 }
3103 
3104 /// get() constructors - Return a constant with vector type with an element
3105 /// count and element type matching the ArrayRef passed in.  Note that this
3106 /// can return a ConstantAggregateZero object.
3107 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint8_t> Elts){
3108   auto *Ty = FixedVectorType::get(Type::getInt8Ty(Context), Elts.size());
3109   const char *Data = reinterpret_cast<const char *>(Elts.data());
3110   return getImpl(StringRef(Data, Elts.size() * 1), Ty);
3111 }
3112 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint16_t> Elts){
3113   auto *Ty = FixedVectorType::get(Type::getInt16Ty(Context), Elts.size());
3114   const char *Data = reinterpret_cast<const char *>(Elts.data());
3115   return getImpl(StringRef(Data, Elts.size() * 2), Ty);
3116 }
3117 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint32_t> Elts){
3118   auto *Ty = FixedVectorType::get(Type::getInt32Ty(Context), Elts.size());
3119   const char *Data = reinterpret_cast<const char *>(Elts.data());
3120   return getImpl(StringRef(Data, Elts.size() * 4), Ty);
3121 }
3122 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint64_t> Elts){
3123   auto *Ty = FixedVectorType::get(Type::getInt64Ty(Context), Elts.size());
3124   const char *Data = reinterpret_cast<const char *>(Elts.data());
3125   return getImpl(StringRef(Data, Elts.size() * 8), Ty);
3126 }
3127 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<float> Elts) {
3128   auto *Ty = FixedVectorType::get(Type::getFloatTy(Context), Elts.size());
3129   const char *Data = reinterpret_cast<const char *>(Elts.data());
3130   return getImpl(StringRef(Data, Elts.size() * 4), Ty);
3131 }
3132 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<double> Elts) {
3133   auto *Ty = FixedVectorType::get(Type::getDoubleTy(Context), Elts.size());
3134   const char *Data = reinterpret_cast<const char *>(Elts.data());
3135   return getImpl(StringRef(Data, Elts.size() * 8), Ty);
3136 }
3137 
3138 /// getFP() constructors - Return a constant of vector type with a float
3139 /// element type taken from argument `ElementType', and count taken from
3140 /// argument `Elts'.  The amount of bits of the contained type must match the
3141 /// number of bits of the type contained in the passed in ArrayRef.
3142 /// (i.e. half or bfloat for 16bits, float for 32bits, double for 64bits) Note
3143 /// that this can return a ConstantAggregateZero object.
3144 Constant *ConstantDataVector::getFP(Type *ElementType,
3145                                     ArrayRef<uint16_t> Elts) {
3146   assert((ElementType->isHalfTy() || ElementType->isBFloatTy()) &&
3147          "Element type is not a 16-bit float type");
3148   auto *Ty = FixedVectorType::get(ElementType, Elts.size());
3149   const char *Data = reinterpret_cast<const char *>(Elts.data());
3150   return getImpl(StringRef(Data, Elts.size() * 2), Ty);
3151 }
3152 Constant *ConstantDataVector::getFP(Type *ElementType,
3153                                     ArrayRef<uint32_t> Elts) {
3154   assert(ElementType->isFloatTy() && "Element type is not a 32-bit float type");
3155   auto *Ty = FixedVectorType::get(ElementType, Elts.size());
3156   const char *Data = reinterpret_cast<const char *>(Elts.data());
3157   return getImpl(StringRef(Data, Elts.size() * 4), Ty);
3158 }
3159 Constant *ConstantDataVector::getFP(Type *ElementType,
3160                                     ArrayRef<uint64_t> Elts) {
3161   assert(ElementType->isDoubleTy() &&
3162          "Element type is not a 64-bit float type");
3163   auto *Ty = FixedVectorType::get(ElementType, Elts.size());
3164   const char *Data = reinterpret_cast<const char *>(Elts.data());
3165   return getImpl(StringRef(Data, Elts.size() * 8), Ty);
3166 }
3167 
3168 Constant *ConstantDataVector::getSplat(unsigned NumElts, Constant *V) {
3169   assert(isElementTypeCompatible(V->getType()) &&
3170          "Element type not compatible with ConstantData");
3171   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
3172     if (CI->getType()->isIntegerTy(8)) {
3173       SmallVector<uint8_t, 16> Elts(NumElts, CI->getZExtValue());
3174       return get(V->getContext(), Elts);
3175     }
3176     if (CI->getType()->isIntegerTy(16)) {
3177       SmallVector<uint16_t, 16> Elts(NumElts, CI->getZExtValue());
3178       return get(V->getContext(), Elts);
3179     }
3180     if (CI->getType()->isIntegerTy(32)) {
3181       SmallVector<uint32_t, 16> Elts(NumElts, CI->getZExtValue());
3182       return get(V->getContext(), Elts);
3183     }
3184     assert(CI->getType()->isIntegerTy(64) && "Unsupported ConstantData type");
3185     SmallVector<uint64_t, 16> Elts(NumElts, CI->getZExtValue());
3186     return get(V->getContext(), Elts);
3187   }
3188 
3189   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
3190     if (CFP->getType()->isHalfTy()) {
3191       SmallVector<uint16_t, 16> Elts(
3192           NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
3193       return getFP(V->getType(), Elts);
3194     }
3195     if (CFP->getType()->isBFloatTy()) {
3196       SmallVector<uint16_t, 16> Elts(
3197           NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
3198       return getFP(V->getType(), Elts);
3199     }
3200     if (CFP->getType()->isFloatTy()) {
3201       SmallVector<uint32_t, 16> Elts(
3202           NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
3203       return getFP(V->getType(), Elts);
3204     }
3205     if (CFP->getType()->isDoubleTy()) {
3206       SmallVector<uint64_t, 16> Elts(
3207           NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
3208       return getFP(V->getType(), Elts);
3209     }
3210   }
3211   return ConstantVector::getSplat(ElementCount::getFixed(NumElts), V);
3212 }
3213 
3214 
3215 uint64_t ConstantDataSequential::getElementAsInteger(unsigned Elt) const {
3216   assert(isa<IntegerType>(getElementType()) &&
3217          "Accessor can only be used when element is an integer");
3218   const char *EltPtr = getElementPointer(Elt);
3219 
3220   // The data is stored in host byte order, make sure to cast back to the right
3221   // type to load with the right endianness.
3222   switch (getElementType()->getIntegerBitWidth()) {
3223   default: llvm_unreachable("Invalid bitwidth for CDS");
3224   case 8:
3225     return *reinterpret_cast<const uint8_t *>(EltPtr);
3226   case 16:
3227     return *reinterpret_cast<const uint16_t *>(EltPtr);
3228   case 32:
3229     return *reinterpret_cast<const uint32_t *>(EltPtr);
3230   case 64:
3231     return *reinterpret_cast<const uint64_t *>(EltPtr);
3232   }
3233 }
3234 
3235 APInt ConstantDataSequential::getElementAsAPInt(unsigned Elt) const {
3236   assert(isa<IntegerType>(getElementType()) &&
3237          "Accessor can only be used when element is an integer");
3238   const char *EltPtr = getElementPointer(Elt);
3239 
3240   // The data is stored in host byte order, make sure to cast back to the right
3241   // type to load with the right endianness.
3242   switch (getElementType()->getIntegerBitWidth()) {
3243   default: llvm_unreachable("Invalid bitwidth for CDS");
3244   case 8: {
3245     auto EltVal = *reinterpret_cast<const uint8_t *>(EltPtr);
3246     return APInt(8, EltVal);
3247   }
3248   case 16: {
3249     auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
3250     return APInt(16, EltVal);
3251   }
3252   case 32: {
3253     auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr);
3254     return APInt(32, EltVal);
3255   }
3256   case 64: {
3257     auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr);
3258     return APInt(64, EltVal);
3259   }
3260   }
3261 }
3262 
3263 APFloat ConstantDataSequential::getElementAsAPFloat(unsigned Elt) const {
3264   const char *EltPtr = getElementPointer(Elt);
3265 
3266   switch (getElementType()->getTypeID()) {
3267   default:
3268     llvm_unreachable("Accessor can only be used when element is float/double!");
3269   case Type::HalfTyID: {
3270     auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
3271     return APFloat(APFloat::IEEEhalf(), APInt(16, EltVal));
3272   }
3273   case Type::BFloatTyID: {
3274     auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
3275     return APFloat(APFloat::BFloat(), APInt(16, EltVal));
3276   }
3277   case Type::FloatTyID: {
3278     auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr);
3279     return APFloat(APFloat::IEEEsingle(), APInt(32, EltVal));
3280   }
3281   case Type::DoubleTyID: {
3282     auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr);
3283     return APFloat(APFloat::IEEEdouble(), APInt(64, EltVal));
3284   }
3285   }
3286 }
3287 
3288 float ConstantDataSequential::getElementAsFloat(unsigned Elt) const {
3289   assert(getElementType()->isFloatTy() &&
3290          "Accessor can only be used when element is a 'float'");
3291   return *reinterpret_cast<const float *>(getElementPointer(Elt));
3292 }
3293 
3294 double ConstantDataSequential::getElementAsDouble(unsigned Elt) const {
3295   assert(getElementType()->isDoubleTy() &&
3296          "Accessor can only be used when element is a 'float'");
3297   return *reinterpret_cast<const double *>(getElementPointer(Elt));
3298 }
3299 
3300 Constant *ConstantDataSequential::getElementAsConstant(unsigned Elt) const {
3301   if (getElementType()->isHalfTy() || getElementType()->isBFloatTy() ||
3302       getElementType()->isFloatTy() || getElementType()->isDoubleTy())
3303     return ConstantFP::get(getContext(), getElementAsAPFloat(Elt));
3304 
3305   return ConstantInt::get(getElementType(), getElementAsInteger(Elt));
3306 }
3307 
3308 bool ConstantDataSequential::isString(unsigned CharSize) const {
3309   return isa<ArrayType>(getType()) && getElementType()->isIntegerTy(CharSize);
3310 }
3311 
3312 bool ConstantDataSequential::isCString() const {
3313   if (!isString())
3314     return false;
3315 
3316   StringRef Str = getAsString();
3317 
3318   // The last value must be nul.
3319   if (Str.back() != 0) return false;
3320 
3321   // Other elements must be non-nul.
3322   return !Str.drop_back().contains(0);
3323 }
3324 
3325 bool ConstantDataVector::isSplatData() const {
3326   const char *Base = getRawDataValues().data();
3327 
3328   // Compare elements 1+ to the 0'th element.
3329   unsigned EltSize = getElementByteSize();
3330   for (unsigned i = 1, e = getNumElements(); i != e; ++i)
3331     if (memcmp(Base, Base+i*EltSize, EltSize))
3332       return false;
3333 
3334   return true;
3335 }
3336 
3337 bool ConstantDataVector::isSplat() const {
3338   if (!IsSplatSet) {
3339     IsSplatSet = true;
3340     IsSplat = isSplatData();
3341   }
3342   return IsSplat;
3343 }
3344 
3345 Constant *ConstantDataVector::getSplatValue() const {
3346   // If they're all the same, return the 0th one as a representative.
3347   return isSplat() ? getElementAsConstant(0) : nullptr;
3348 }
3349 
3350 //===----------------------------------------------------------------------===//
3351 //                handleOperandChange implementations
3352 
3353 /// Update this constant array to change uses of
3354 /// 'From' to be uses of 'To'.  This must update the uniquing data structures
3355 /// etc.
3356 ///
3357 /// Note that we intentionally replace all uses of From with To here.  Consider
3358 /// a large array that uses 'From' 1000 times.  By handling this case all here,
3359 /// ConstantArray::handleOperandChange is only invoked once, and that
3360 /// single invocation handles all 1000 uses.  Handling them one at a time would
3361 /// work, but would be really slow because it would have to unique each updated
3362 /// array instance.
3363 ///
3364 void Constant::handleOperandChange(Value *From, Value *To) {
3365   Value *Replacement = nullptr;
3366   switch (getValueID()) {
3367   default:
3368     llvm_unreachable("Not a constant!");
3369 #define HANDLE_CONSTANT(Name)                                                  \
3370   case Value::Name##Val:                                                       \
3371     Replacement = cast<Name>(this)->handleOperandChangeImpl(From, To);         \
3372     break;
3373 #include "llvm/IR/Value.def"
3374   }
3375 
3376   // If handleOperandChangeImpl returned nullptr, then it handled
3377   // replacing itself and we don't want to delete or replace anything else here.
3378   if (!Replacement)
3379     return;
3380 
3381   // I do need to replace this with an existing value.
3382   assert(Replacement != this && "I didn't contain From!");
3383 
3384   // Everyone using this now uses the replacement.
3385   replaceAllUsesWith(Replacement);
3386 
3387   // Delete the old constant!
3388   destroyConstant();
3389 }
3390 
3391 Value *ConstantArray::handleOperandChangeImpl(Value *From, Value *To) {
3392   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
3393   Constant *ToC = cast<Constant>(To);
3394 
3395   SmallVector<Constant*, 8> Values;
3396   Values.reserve(getNumOperands());  // Build replacement array.
3397 
3398   // Fill values with the modified operands of the constant array.  Also,
3399   // compute whether this turns into an all-zeros array.
3400   unsigned NumUpdated = 0;
3401 
3402   // Keep track of whether all the values in the array are "ToC".
3403   bool AllSame = true;
3404   Use *OperandList = getOperandList();
3405   unsigned OperandNo = 0;
3406   for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
3407     Constant *Val = cast<Constant>(O->get());
3408     if (Val == From) {
3409       OperandNo = (O - OperandList);
3410       Val = ToC;
3411       ++NumUpdated;
3412     }
3413     Values.push_back(Val);
3414     AllSame &= Val == ToC;
3415   }
3416 
3417   if (AllSame && ToC->isNullValue())
3418     return ConstantAggregateZero::get(getType());
3419 
3420   if (AllSame && isa<UndefValue>(ToC))
3421     return UndefValue::get(getType());
3422 
3423   // Check for any other type of constant-folding.
3424   if (Constant *C = getImpl(getType(), Values))
3425     return C;
3426 
3427   // Update to the new value.
3428   return getContext().pImpl->ArrayConstants.replaceOperandsInPlace(
3429       Values, this, From, ToC, NumUpdated, OperandNo);
3430 }
3431 
3432 Value *ConstantStruct::handleOperandChangeImpl(Value *From, Value *To) {
3433   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
3434   Constant *ToC = cast<Constant>(To);
3435 
3436   Use *OperandList = getOperandList();
3437 
3438   SmallVector<Constant*, 8> Values;
3439   Values.reserve(getNumOperands());  // Build replacement struct.
3440 
3441   // Fill values with the modified operands of the constant struct.  Also,
3442   // compute whether this turns into an all-zeros struct.
3443   unsigned NumUpdated = 0;
3444   bool AllSame = true;
3445   unsigned OperandNo = 0;
3446   for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O) {
3447     Constant *Val = cast<Constant>(O->get());
3448     if (Val == From) {
3449       OperandNo = (O - OperandList);
3450       Val = ToC;
3451       ++NumUpdated;
3452     }
3453     Values.push_back(Val);
3454     AllSame &= Val == ToC;
3455   }
3456 
3457   if (AllSame && ToC->isNullValue())
3458     return ConstantAggregateZero::get(getType());
3459 
3460   if (AllSame && isa<UndefValue>(ToC))
3461     return UndefValue::get(getType());
3462 
3463   // Update to the new value.
3464   return getContext().pImpl->StructConstants.replaceOperandsInPlace(
3465       Values, this, From, ToC, NumUpdated, OperandNo);
3466 }
3467 
3468 Value *ConstantVector::handleOperandChangeImpl(Value *From, Value *To) {
3469   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
3470   Constant *ToC = cast<Constant>(To);
3471 
3472   SmallVector<Constant*, 8> Values;
3473   Values.reserve(getNumOperands());  // Build replacement array...
3474   unsigned NumUpdated = 0;
3475   unsigned OperandNo = 0;
3476   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
3477     Constant *Val = getOperand(i);
3478     if (Val == From) {
3479       OperandNo = i;
3480       ++NumUpdated;
3481       Val = ToC;
3482     }
3483     Values.push_back(Val);
3484   }
3485 
3486   if (Constant *C = getImpl(Values))
3487     return C;
3488 
3489   // Update to the new value.
3490   return getContext().pImpl->VectorConstants.replaceOperandsInPlace(
3491       Values, this, From, ToC, NumUpdated, OperandNo);
3492 }
3493 
3494 Value *ConstantExpr::handleOperandChangeImpl(Value *From, Value *ToV) {
3495   assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
3496   Constant *To = cast<Constant>(ToV);
3497 
3498   SmallVector<Constant*, 8> NewOps;
3499   unsigned NumUpdated = 0;
3500   unsigned OperandNo = 0;
3501   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
3502     Constant *Op = getOperand(i);
3503     if (Op == From) {
3504       OperandNo = i;
3505       ++NumUpdated;
3506       Op = To;
3507     }
3508     NewOps.push_back(Op);
3509   }
3510   assert(NumUpdated && "I didn't contain From!");
3511 
3512   if (Constant *C = getWithOperands(NewOps, getType(), true))
3513     return C;
3514 
3515   // Update to the new value.
3516   return getContext().pImpl->ExprConstants.replaceOperandsInPlace(
3517       NewOps, this, From, To, NumUpdated, OperandNo);
3518 }
3519 
3520 Instruction *ConstantExpr::getAsInstruction(Instruction *InsertBefore) const {
3521   SmallVector<Value *, 4> ValueOperands(operands());
3522   ArrayRef<Value*> Ops(ValueOperands);
3523 
3524   switch (getOpcode()) {
3525   case Instruction::Trunc:
3526   case Instruction::ZExt:
3527   case Instruction::SExt:
3528   case Instruction::FPTrunc:
3529   case Instruction::FPExt:
3530   case Instruction::UIToFP:
3531   case Instruction::SIToFP:
3532   case Instruction::FPToUI:
3533   case Instruction::FPToSI:
3534   case Instruction::PtrToInt:
3535   case Instruction::IntToPtr:
3536   case Instruction::BitCast:
3537   case Instruction::AddrSpaceCast:
3538     return CastInst::Create((Instruction::CastOps)getOpcode(), Ops[0],
3539                             getType(), "", InsertBefore);
3540   case Instruction::Select:
3541     return SelectInst::Create(Ops[0], Ops[1], Ops[2], "", InsertBefore);
3542   case Instruction::InsertElement:
3543     return InsertElementInst::Create(Ops[0], Ops[1], Ops[2], "", InsertBefore);
3544   case Instruction::ExtractElement:
3545     return ExtractElementInst::Create(Ops[0], Ops[1], "", InsertBefore);
3546   case Instruction::InsertValue:
3547     return InsertValueInst::Create(Ops[0], Ops[1], getIndices(), "",
3548                                    InsertBefore);
3549   case Instruction::ExtractValue:
3550     return ExtractValueInst::Create(Ops[0], getIndices(), "", InsertBefore);
3551   case Instruction::ShuffleVector:
3552     return new ShuffleVectorInst(Ops[0], Ops[1], getShuffleMask(), "",
3553                                  InsertBefore);
3554 
3555   case Instruction::GetElementPtr: {
3556     const auto *GO = cast<GEPOperator>(this);
3557     if (GO->isInBounds())
3558       return GetElementPtrInst::CreateInBounds(
3559           GO->getSourceElementType(), Ops[0], Ops.slice(1), "", InsertBefore);
3560     return GetElementPtrInst::Create(GO->getSourceElementType(), Ops[0],
3561                                      Ops.slice(1), "", InsertBefore);
3562   }
3563   case Instruction::ICmp:
3564   case Instruction::FCmp:
3565     return CmpInst::Create((Instruction::OtherOps)getOpcode(),
3566                            (CmpInst::Predicate)getPredicate(), Ops[0], Ops[1],
3567                            "", InsertBefore);
3568   case Instruction::FNeg:
3569     return UnaryOperator::Create((Instruction::UnaryOps)getOpcode(), Ops[0], "",
3570                                  InsertBefore);
3571   default:
3572     assert(getNumOperands() == 2 && "Must be binary operator?");
3573     BinaryOperator *BO = BinaryOperator::Create(
3574         (Instruction::BinaryOps)getOpcode(), Ops[0], Ops[1], "", InsertBefore);
3575     if (isa<OverflowingBinaryOperator>(BO)) {
3576       BO->setHasNoUnsignedWrap(SubclassOptionalData &
3577                                OverflowingBinaryOperator::NoUnsignedWrap);
3578       BO->setHasNoSignedWrap(SubclassOptionalData &
3579                              OverflowingBinaryOperator::NoSignedWrap);
3580     }
3581     if (isa<PossiblyExactOperator>(BO))
3582       BO->setIsExact(SubclassOptionalData & PossiblyExactOperator::IsExact);
3583     return BO;
3584   }
3585 }
3586