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::getZero(Type *Ty, bool Negative) {
1041   const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
1042   APFloat NegZero = APFloat::getZero(Semantics, Negative);
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 Constant *ConstantFP::getZeroValueForNegation(Type *Ty) {
1052   if (Ty->isFPOrFPVectorTy())
1053     return getNegativeZero(Ty);
1054 
1055   return Constant::getNullValue(Ty);
1056 }
1057 
1058 
1059 // ConstantFP accessors.
1060 ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
1061   LLVMContextImpl* pImpl = Context.pImpl;
1062 
1063   std::unique_ptr<ConstantFP> &Slot = pImpl->FPConstants[V];
1064 
1065   if (!Slot) {
1066     Type *Ty = Type::getFloatingPointTy(Context, V.getSemantics());
1067     Slot.reset(new ConstantFP(Ty, V));
1068   }
1069 
1070   return Slot.get();
1071 }
1072 
1073 Constant *ConstantFP::getInfinity(Type *Ty, bool Negative) {
1074   const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
1075   Constant *C = get(Ty->getContext(), APFloat::getInf(Semantics, Negative));
1076 
1077   if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1078     return ConstantVector::getSplat(VTy->getElementCount(), C);
1079 
1080   return C;
1081 }
1082 
1083 ConstantFP::ConstantFP(Type *Ty, const APFloat &V)
1084     : ConstantData(Ty, ConstantFPVal), Val(V) {
1085   assert(&V.getSemantics() == &Ty->getFltSemantics() &&
1086          "FP type Mismatch");
1087 }
1088 
1089 bool ConstantFP::isExactlyValue(const APFloat &V) const {
1090   return Val.bitwiseIsEqual(V);
1091 }
1092 
1093 /// Remove the constant from the constant table.
1094 void ConstantFP::destroyConstantImpl() {
1095   llvm_unreachable("You can't ConstantFP->destroyConstantImpl()!");
1096 }
1097 
1098 //===----------------------------------------------------------------------===//
1099 //                   ConstantAggregateZero Implementation
1100 //===----------------------------------------------------------------------===//
1101 
1102 Constant *ConstantAggregateZero::getSequentialElement() const {
1103   if (auto *AT = dyn_cast<ArrayType>(getType()))
1104     return Constant::getNullValue(AT->getElementType());
1105   return Constant::getNullValue(cast<VectorType>(getType())->getElementType());
1106 }
1107 
1108 Constant *ConstantAggregateZero::getStructElement(unsigned Elt) const {
1109   return Constant::getNullValue(getType()->getStructElementType(Elt));
1110 }
1111 
1112 Constant *ConstantAggregateZero::getElementValue(Constant *C) const {
1113   if (isa<ArrayType>(getType()) || isa<VectorType>(getType()))
1114     return getSequentialElement();
1115   return getStructElement(cast<ConstantInt>(C)->getZExtValue());
1116 }
1117 
1118 Constant *ConstantAggregateZero::getElementValue(unsigned Idx) const {
1119   if (isa<ArrayType>(getType()) || isa<VectorType>(getType()))
1120     return getSequentialElement();
1121   return getStructElement(Idx);
1122 }
1123 
1124 ElementCount ConstantAggregateZero::getElementCount() const {
1125   Type *Ty = getType();
1126   if (auto *AT = dyn_cast<ArrayType>(Ty))
1127     return ElementCount::getFixed(AT->getNumElements());
1128   if (auto *VT = dyn_cast<VectorType>(Ty))
1129     return VT->getElementCount();
1130   return ElementCount::getFixed(Ty->getStructNumElements());
1131 }
1132 
1133 //===----------------------------------------------------------------------===//
1134 //                         UndefValue Implementation
1135 //===----------------------------------------------------------------------===//
1136 
1137 UndefValue *UndefValue::getSequentialElement() const {
1138   if (ArrayType *ATy = dyn_cast<ArrayType>(getType()))
1139     return UndefValue::get(ATy->getElementType());
1140   return UndefValue::get(cast<VectorType>(getType())->getElementType());
1141 }
1142 
1143 UndefValue *UndefValue::getStructElement(unsigned Elt) const {
1144   return UndefValue::get(getType()->getStructElementType(Elt));
1145 }
1146 
1147 UndefValue *UndefValue::getElementValue(Constant *C) const {
1148   if (isa<ArrayType>(getType()) || isa<VectorType>(getType()))
1149     return getSequentialElement();
1150   return getStructElement(cast<ConstantInt>(C)->getZExtValue());
1151 }
1152 
1153 UndefValue *UndefValue::getElementValue(unsigned Idx) const {
1154   if (isa<ArrayType>(getType()) || isa<VectorType>(getType()))
1155     return getSequentialElement();
1156   return getStructElement(Idx);
1157 }
1158 
1159 unsigned UndefValue::getNumElements() const {
1160   Type *Ty = getType();
1161   if (auto *AT = dyn_cast<ArrayType>(Ty))
1162     return AT->getNumElements();
1163   if (auto *VT = dyn_cast<VectorType>(Ty))
1164     return cast<FixedVectorType>(VT)->getNumElements();
1165   return Ty->getStructNumElements();
1166 }
1167 
1168 //===----------------------------------------------------------------------===//
1169 //                         PoisonValue Implementation
1170 //===----------------------------------------------------------------------===//
1171 
1172 PoisonValue *PoisonValue::getSequentialElement() const {
1173   if (ArrayType *ATy = dyn_cast<ArrayType>(getType()))
1174     return PoisonValue::get(ATy->getElementType());
1175   return PoisonValue::get(cast<VectorType>(getType())->getElementType());
1176 }
1177 
1178 PoisonValue *PoisonValue::getStructElement(unsigned Elt) const {
1179   return PoisonValue::get(getType()->getStructElementType(Elt));
1180 }
1181 
1182 PoisonValue *PoisonValue::getElementValue(Constant *C) const {
1183   if (isa<ArrayType>(getType()) || isa<VectorType>(getType()))
1184     return getSequentialElement();
1185   return getStructElement(cast<ConstantInt>(C)->getZExtValue());
1186 }
1187 
1188 PoisonValue *PoisonValue::getElementValue(unsigned Idx) const {
1189   if (isa<ArrayType>(getType()) || isa<VectorType>(getType()))
1190     return getSequentialElement();
1191   return getStructElement(Idx);
1192 }
1193 
1194 //===----------------------------------------------------------------------===//
1195 //                            ConstantXXX Classes
1196 //===----------------------------------------------------------------------===//
1197 
1198 template <typename ItTy, typename EltTy>
1199 static bool rangeOnlyContains(ItTy Start, ItTy End, EltTy Elt) {
1200   for (; Start != End; ++Start)
1201     if (*Start != Elt)
1202       return false;
1203   return true;
1204 }
1205 
1206 template <typename SequentialTy, typename ElementTy>
1207 static Constant *getIntSequenceIfElementsMatch(ArrayRef<Constant *> V) {
1208   assert(!V.empty() && "Cannot get empty int sequence.");
1209 
1210   SmallVector<ElementTy, 16> Elts;
1211   for (Constant *C : V)
1212     if (auto *CI = dyn_cast<ConstantInt>(C))
1213       Elts.push_back(CI->getZExtValue());
1214     else
1215       return nullptr;
1216   return SequentialTy::get(V[0]->getContext(), Elts);
1217 }
1218 
1219 template <typename SequentialTy, typename ElementTy>
1220 static Constant *getFPSequenceIfElementsMatch(ArrayRef<Constant *> V) {
1221   assert(!V.empty() && "Cannot get empty FP sequence.");
1222 
1223   SmallVector<ElementTy, 16> Elts;
1224   for (Constant *C : V)
1225     if (auto *CFP = dyn_cast<ConstantFP>(C))
1226       Elts.push_back(CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
1227     else
1228       return nullptr;
1229   return SequentialTy::getFP(V[0]->getType(), Elts);
1230 }
1231 
1232 template <typename SequenceTy>
1233 static Constant *getSequenceIfElementsMatch(Constant *C,
1234                                             ArrayRef<Constant *> V) {
1235   // We speculatively build the elements here even if it turns out that there is
1236   // a constantexpr or something else weird, since it is so uncommon for that to
1237   // happen.
1238   if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
1239     if (CI->getType()->isIntegerTy(8))
1240       return getIntSequenceIfElementsMatch<SequenceTy, uint8_t>(V);
1241     else if (CI->getType()->isIntegerTy(16))
1242       return getIntSequenceIfElementsMatch<SequenceTy, uint16_t>(V);
1243     else if (CI->getType()->isIntegerTy(32))
1244       return getIntSequenceIfElementsMatch<SequenceTy, uint32_t>(V);
1245     else if (CI->getType()->isIntegerTy(64))
1246       return getIntSequenceIfElementsMatch<SequenceTy, uint64_t>(V);
1247   } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
1248     if (CFP->getType()->isHalfTy() || CFP->getType()->isBFloatTy())
1249       return getFPSequenceIfElementsMatch<SequenceTy, uint16_t>(V);
1250     else if (CFP->getType()->isFloatTy())
1251       return getFPSequenceIfElementsMatch<SequenceTy, uint32_t>(V);
1252     else if (CFP->getType()->isDoubleTy())
1253       return getFPSequenceIfElementsMatch<SequenceTy, uint64_t>(V);
1254   }
1255 
1256   return nullptr;
1257 }
1258 
1259 ConstantAggregate::ConstantAggregate(Type *T, ValueTy VT,
1260                                      ArrayRef<Constant *> V)
1261     : Constant(T, VT, OperandTraits<ConstantAggregate>::op_end(this) - V.size(),
1262                V.size()) {
1263   llvm::copy(V, op_begin());
1264 
1265   // Check that types match, unless this is an opaque struct.
1266   if (auto *ST = dyn_cast<StructType>(T)) {
1267     if (ST->isOpaque())
1268       return;
1269     for (unsigned I = 0, E = V.size(); I != E; ++I)
1270       assert(V[I]->getType() == ST->getTypeAtIndex(I) &&
1271              "Initializer for struct element doesn't match!");
1272   }
1273 }
1274 
1275 ConstantArray::ConstantArray(ArrayType *T, ArrayRef<Constant *> V)
1276     : ConstantAggregate(T, ConstantArrayVal, V) {
1277   assert(V.size() == T->getNumElements() &&
1278          "Invalid initializer for constant array");
1279 }
1280 
1281 Constant *ConstantArray::get(ArrayType *Ty, ArrayRef<Constant*> V) {
1282   if (Constant *C = getImpl(Ty, V))
1283     return C;
1284   return Ty->getContext().pImpl->ArrayConstants.getOrCreate(Ty, V);
1285 }
1286 
1287 Constant *ConstantArray::getImpl(ArrayType *Ty, ArrayRef<Constant*> V) {
1288   // Empty arrays are canonicalized to ConstantAggregateZero.
1289   if (V.empty())
1290     return ConstantAggregateZero::get(Ty);
1291 
1292   for (Constant *C : V) {
1293     assert(C->getType() == Ty->getElementType() &&
1294            "Wrong type in array element initializer");
1295     (void)C;
1296   }
1297 
1298   // If this is an all-zero array, return a ConstantAggregateZero object.  If
1299   // all undef, return an UndefValue, if "all simple", then return a
1300   // ConstantDataArray.
1301   Constant *C = V[0];
1302   if (isa<PoisonValue>(C) && rangeOnlyContains(V.begin(), V.end(), C))
1303     return PoisonValue::get(Ty);
1304 
1305   if (isa<UndefValue>(C) && rangeOnlyContains(V.begin(), V.end(), C))
1306     return UndefValue::get(Ty);
1307 
1308   if (C->isNullValue() && rangeOnlyContains(V.begin(), V.end(), C))
1309     return ConstantAggregateZero::get(Ty);
1310 
1311   // Check to see if all of the elements are ConstantFP or ConstantInt and if
1312   // the element type is compatible with ConstantDataVector.  If so, use it.
1313   if (ConstantDataSequential::isElementTypeCompatible(C->getType()))
1314     return getSequenceIfElementsMatch<ConstantDataArray>(C, V);
1315 
1316   // Otherwise, we really do want to create a ConstantArray.
1317   return nullptr;
1318 }
1319 
1320 StructType *ConstantStruct::getTypeForElements(LLVMContext &Context,
1321                                                ArrayRef<Constant*> V,
1322                                                bool Packed) {
1323   unsigned VecSize = V.size();
1324   SmallVector<Type*, 16> EltTypes(VecSize);
1325   for (unsigned i = 0; i != VecSize; ++i)
1326     EltTypes[i] = V[i]->getType();
1327 
1328   return StructType::get(Context, EltTypes, Packed);
1329 }
1330 
1331 
1332 StructType *ConstantStruct::getTypeForElements(ArrayRef<Constant*> V,
1333                                                bool Packed) {
1334   assert(!V.empty() &&
1335          "ConstantStruct::getTypeForElements cannot be called on empty list");
1336   return getTypeForElements(V[0]->getContext(), V, Packed);
1337 }
1338 
1339 ConstantStruct::ConstantStruct(StructType *T, ArrayRef<Constant *> V)
1340     : ConstantAggregate(T, ConstantStructVal, V) {
1341   assert((T->isOpaque() || V.size() == T->getNumElements()) &&
1342          "Invalid initializer for constant struct");
1343 }
1344 
1345 // ConstantStruct accessors.
1346 Constant *ConstantStruct::get(StructType *ST, ArrayRef<Constant*> V) {
1347   assert((ST->isOpaque() || ST->getNumElements() == V.size()) &&
1348          "Incorrect # elements specified to ConstantStruct::get");
1349 
1350   // Create a ConstantAggregateZero value if all elements are zeros.
1351   bool isZero = true;
1352   bool isUndef = false;
1353   bool isPoison = false;
1354 
1355   if (!V.empty()) {
1356     isUndef = isa<UndefValue>(V[0]);
1357     isPoison = isa<PoisonValue>(V[0]);
1358     isZero = V[0]->isNullValue();
1359     // PoisonValue inherits UndefValue, so its check is not necessary.
1360     if (isUndef || isZero) {
1361       for (Constant *C : V) {
1362         if (!C->isNullValue())
1363           isZero = false;
1364         if (!isa<PoisonValue>(C))
1365           isPoison = false;
1366         if (isa<PoisonValue>(C) || !isa<UndefValue>(C))
1367           isUndef = false;
1368       }
1369     }
1370   }
1371   if (isZero)
1372     return ConstantAggregateZero::get(ST);
1373   if (isPoison)
1374     return PoisonValue::get(ST);
1375   if (isUndef)
1376     return UndefValue::get(ST);
1377 
1378   return ST->getContext().pImpl->StructConstants.getOrCreate(ST, V);
1379 }
1380 
1381 ConstantVector::ConstantVector(VectorType *T, ArrayRef<Constant *> V)
1382     : ConstantAggregate(T, ConstantVectorVal, V) {
1383   assert(V.size() == cast<FixedVectorType>(T)->getNumElements() &&
1384          "Invalid initializer for constant vector");
1385 }
1386 
1387 // ConstantVector accessors.
1388 Constant *ConstantVector::get(ArrayRef<Constant*> V) {
1389   if (Constant *C = getImpl(V))
1390     return C;
1391   auto *Ty = FixedVectorType::get(V.front()->getType(), V.size());
1392   return Ty->getContext().pImpl->VectorConstants.getOrCreate(Ty, V);
1393 }
1394 
1395 Constant *ConstantVector::getImpl(ArrayRef<Constant*> V) {
1396   assert(!V.empty() && "Vectors can't be empty");
1397   auto *T = FixedVectorType::get(V.front()->getType(), V.size());
1398 
1399   // If this is an all-undef or all-zero vector, return a
1400   // ConstantAggregateZero or UndefValue.
1401   Constant *C = V[0];
1402   bool isZero = C->isNullValue();
1403   bool isUndef = isa<UndefValue>(C);
1404   bool isPoison = isa<PoisonValue>(C);
1405 
1406   if (isZero || isUndef) {
1407     for (unsigned i = 1, e = V.size(); i != e; ++i)
1408       if (V[i] != C) {
1409         isZero = isUndef = isPoison = false;
1410         break;
1411       }
1412   }
1413 
1414   if (isZero)
1415     return ConstantAggregateZero::get(T);
1416   if (isPoison)
1417     return PoisonValue::get(T);
1418   if (isUndef)
1419     return UndefValue::get(T);
1420 
1421   // Check to see if all of the elements are ConstantFP or ConstantInt and if
1422   // the element type is compatible with ConstantDataVector.  If so, use it.
1423   if (ConstantDataSequential::isElementTypeCompatible(C->getType()))
1424     return getSequenceIfElementsMatch<ConstantDataVector>(C, V);
1425 
1426   // Otherwise, the element type isn't compatible with ConstantDataVector, or
1427   // the operand list contains a ConstantExpr or something else strange.
1428   return nullptr;
1429 }
1430 
1431 Constant *ConstantVector::getSplat(ElementCount EC, Constant *V) {
1432   if (!EC.isScalable()) {
1433     // If this splat is compatible with ConstantDataVector, use it instead of
1434     // ConstantVector.
1435     if ((isa<ConstantFP>(V) || isa<ConstantInt>(V)) &&
1436         ConstantDataSequential::isElementTypeCompatible(V->getType()))
1437       return ConstantDataVector::getSplat(EC.getKnownMinValue(), V);
1438 
1439     SmallVector<Constant *, 32> Elts(EC.getKnownMinValue(), V);
1440     return get(Elts);
1441   }
1442 
1443   Type *VTy = VectorType::get(V->getType(), EC);
1444 
1445   if (V->isNullValue())
1446     return ConstantAggregateZero::get(VTy);
1447   else if (isa<UndefValue>(V))
1448     return UndefValue::get(VTy);
1449 
1450   Type *I32Ty = Type::getInt32Ty(VTy->getContext());
1451 
1452   // Move scalar into vector.
1453   Constant *PoisonV = PoisonValue::get(VTy);
1454   V = ConstantExpr::getInsertElement(PoisonV, V, ConstantInt::get(I32Ty, 0));
1455   // Build shuffle mask to perform the splat.
1456   SmallVector<int, 8> Zeros(EC.getKnownMinValue(), 0);
1457   // Splat.
1458   return ConstantExpr::getShuffleVector(V, PoisonV, Zeros);
1459 }
1460 
1461 ConstantTokenNone *ConstantTokenNone::get(LLVMContext &Context) {
1462   LLVMContextImpl *pImpl = Context.pImpl;
1463   if (!pImpl->TheNoneToken)
1464     pImpl->TheNoneToken.reset(new ConstantTokenNone(Context));
1465   return pImpl->TheNoneToken.get();
1466 }
1467 
1468 /// Remove the constant from the constant table.
1469 void ConstantTokenNone::destroyConstantImpl() {
1470   llvm_unreachable("You can't ConstantTokenNone->destroyConstantImpl()!");
1471 }
1472 
1473 // Utility function for determining if a ConstantExpr is a CastOp or not. This
1474 // can't be inline because we don't want to #include Instruction.h into
1475 // Constant.h
1476 bool ConstantExpr::isCast() const {
1477   return Instruction::isCast(getOpcode());
1478 }
1479 
1480 bool ConstantExpr::isCompare() const {
1481   return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
1482 }
1483 
1484 bool ConstantExpr::hasIndices() const {
1485   return getOpcode() == Instruction::ExtractValue ||
1486          getOpcode() == Instruction::InsertValue;
1487 }
1488 
1489 ArrayRef<unsigned> ConstantExpr::getIndices() const {
1490   if (const ExtractValueConstantExpr *EVCE =
1491         dyn_cast<ExtractValueConstantExpr>(this))
1492     return EVCE->Indices;
1493 
1494   return cast<InsertValueConstantExpr>(this)->Indices;
1495 }
1496 
1497 unsigned ConstantExpr::getPredicate() const {
1498   return cast<CompareConstantExpr>(this)->predicate;
1499 }
1500 
1501 ArrayRef<int> ConstantExpr::getShuffleMask() const {
1502   return cast<ShuffleVectorConstantExpr>(this)->ShuffleMask;
1503 }
1504 
1505 Constant *ConstantExpr::getShuffleMaskForBitcode() const {
1506   return cast<ShuffleVectorConstantExpr>(this)->ShuffleMaskForBitcode;
1507 }
1508 
1509 Constant *ConstantExpr::getWithOperands(ArrayRef<Constant *> Ops, Type *Ty,
1510                                         bool OnlyIfReduced, Type *SrcTy) const {
1511   assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
1512 
1513   // If no operands changed return self.
1514   if (Ty == getType() && std::equal(Ops.begin(), Ops.end(), op_begin()))
1515     return const_cast<ConstantExpr*>(this);
1516 
1517   Type *OnlyIfReducedTy = OnlyIfReduced ? Ty : nullptr;
1518   switch (getOpcode()) {
1519   case Instruction::Trunc:
1520   case Instruction::ZExt:
1521   case Instruction::SExt:
1522   case Instruction::FPTrunc:
1523   case Instruction::FPExt:
1524   case Instruction::UIToFP:
1525   case Instruction::SIToFP:
1526   case Instruction::FPToUI:
1527   case Instruction::FPToSI:
1528   case Instruction::PtrToInt:
1529   case Instruction::IntToPtr:
1530   case Instruction::BitCast:
1531   case Instruction::AddrSpaceCast:
1532     return ConstantExpr::getCast(getOpcode(), Ops[0], Ty, OnlyIfReduced);
1533   case Instruction::Select:
1534     return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2], OnlyIfReducedTy);
1535   case Instruction::InsertElement:
1536     return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2],
1537                                           OnlyIfReducedTy);
1538   case Instruction::ExtractElement:
1539     return ConstantExpr::getExtractElement(Ops[0], Ops[1], OnlyIfReducedTy);
1540   case Instruction::InsertValue:
1541     return ConstantExpr::getInsertValue(Ops[0], Ops[1], getIndices(),
1542                                         OnlyIfReducedTy);
1543   case Instruction::ExtractValue:
1544     return ConstantExpr::getExtractValue(Ops[0], getIndices(), OnlyIfReducedTy);
1545   case Instruction::FNeg:
1546     return ConstantExpr::getFNeg(Ops[0]);
1547   case Instruction::ShuffleVector:
1548     return ConstantExpr::getShuffleVector(Ops[0], Ops[1], getShuffleMask(),
1549                                           OnlyIfReducedTy);
1550   case Instruction::GetElementPtr: {
1551     auto *GEPO = cast<GEPOperator>(this);
1552     assert(SrcTy || (Ops[0]->getType() == getOperand(0)->getType()));
1553     return ConstantExpr::getGetElementPtr(
1554         SrcTy ? SrcTy : GEPO->getSourceElementType(), Ops[0], Ops.slice(1),
1555         GEPO->isInBounds(), GEPO->getInRangeIndex(), OnlyIfReducedTy);
1556   }
1557   case Instruction::ICmp:
1558   case Instruction::FCmp:
1559     return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1],
1560                                     OnlyIfReducedTy);
1561   default:
1562     assert(getNumOperands() == 2 && "Must be binary operator?");
1563     return ConstantExpr::get(getOpcode(), Ops[0], Ops[1], SubclassOptionalData,
1564                              OnlyIfReducedTy);
1565   }
1566 }
1567 
1568 
1569 //===----------------------------------------------------------------------===//
1570 //                      isValueValidForType implementations
1571 
1572 bool ConstantInt::isValueValidForType(Type *Ty, uint64_t Val) {
1573   unsigned NumBits = Ty->getIntegerBitWidth(); // assert okay
1574   if (Ty->isIntegerTy(1))
1575     return Val == 0 || Val == 1;
1576   return isUIntN(NumBits, Val);
1577 }
1578 
1579 bool ConstantInt::isValueValidForType(Type *Ty, int64_t Val) {
1580   unsigned NumBits = Ty->getIntegerBitWidth();
1581   if (Ty->isIntegerTy(1))
1582     return Val == 0 || Val == 1 || Val == -1;
1583   return isIntN(NumBits, Val);
1584 }
1585 
1586 bool ConstantFP::isValueValidForType(Type *Ty, const APFloat& Val) {
1587   // convert modifies in place, so make a copy.
1588   APFloat Val2 = APFloat(Val);
1589   bool losesInfo;
1590   switch (Ty->getTypeID()) {
1591   default:
1592     return false;         // These can't be represented as floating point!
1593 
1594   // FIXME rounding mode needs to be more flexible
1595   case Type::HalfTyID: {
1596     if (&Val2.getSemantics() == &APFloat::IEEEhalf())
1597       return true;
1598     Val2.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven, &losesInfo);
1599     return !losesInfo;
1600   }
1601   case Type::BFloatTyID: {
1602     if (&Val2.getSemantics() == &APFloat::BFloat())
1603       return true;
1604     Val2.convert(APFloat::BFloat(), APFloat::rmNearestTiesToEven, &losesInfo);
1605     return !losesInfo;
1606   }
1607   case Type::FloatTyID: {
1608     if (&Val2.getSemantics() == &APFloat::IEEEsingle())
1609       return true;
1610     Val2.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, &losesInfo);
1611     return !losesInfo;
1612   }
1613   case Type::DoubleTyID: {
1614     if (&Val2.getSemantics() == &APFloat::IEEEhalf() ||
1615         &Val2.getSemantics() == &APFloat::BFloat() ||
1616         &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1617         &Val2.getSemantics() == &APFloat::IEEEdouble())
1618       return true;
1619     Val2.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, &losesInfo);
1620     return !losesInfo;
1621   }
1622   case Type::X86_FP80TyID:
1623     return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
1624            &Val2.getSemantics() == &APFloat::BFloat() ||
1625            &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1626            &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1627            &Val2.getSemantics() == &APFloat::x87DoubleExtended();
1628   case Type::FP128TyID:
1629     return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
1630            &Val2.getSemantics() == &APFloat::BFloat() ||
1631            &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1632            &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1633            &Val2.getSemantics() == &APFloat::IEEEquad();
1634   case Type::PPC_FP128TyID:
1635     return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
1636            &Val2.getSemantics() == &APFloat::BFloat() ||
1637            &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1638            &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1639            &Val2.getSemantics() == &APFloat::PPCDoubleDouble();
1640   }
1641 }
1642 
1643 
1644 //===----------------------------------------------------------------------===//
1645 //                      Factory Function Implementation
1646 
1647 ConstantAggregateZero *ConstantAggregateZero::get(Type *Ty) {
1648   assert((Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()) &&
1649          "Cannot create an aggregate zero of non-aggregate type!");
1650 
1651   std::unique_ptr<ConstantAggregateZero> &Entry =
1652       Ty->getContext().pImpl->CAZConstants[Ty];
1653   if (!Entry)
1654     Entry.reset(new ConstantAggregateZero(Ty));
1655 
1656   return Entry.get();
1657 }
1658 
1659 /// Remove the constant from the constant table.
1660 void ConstantAggregateZero::destroyConstantImpl() {
1661   getContext().pImpl->CAZConstants.erase(getType());
1662 }
1663 
1664 /// Remove the constant from the constant table.
1665 void ConstantArray::destroyConstantImpl() {
1666   getType()->getContext().pImpl->ArrayConstants.remove(this);
1667 }
1668 
1669 
1670 //---- ConstantStruct::get() implementation...
1671 //
1672 
1673 /// Remove the constant from the constant table.
1674 void ConstantStruct::destroyConstantImpl() {
1675   getType()->getContext().pImpl->StructConstants.remove(this);
1676 }
1677 
1678 /// Remove the constant from the constant table.
1679 void ConstantVector::destroyConstantImpl() {
1680   getType()->getContext().pImpl->VectorConstants.remove(this);
1681 }
1682 
1683 Constant *Constant::getSplatValue(bool AllowUndefs) const {
1684   assert(this->getType()->isVectorTy() && "Only valid for vectors!");
1685   if (isa<ConstantAggregateZero>(this))
1686     return getNullValue(cast<VectorType>(getType())->getElementType());
1687   if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
1688     return CV->getSplatValue();
1689   if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
1690     return CV->getSplatValue(AllowUndefs);
1691 
1692   // Check if this is a constant expression splat of the form returned by
1693   // ConstantVector::getSplat()
1694   const auto *Shuf = dyn_cast<ConstantExpr>(this);
1695   if (Shuf && Shuf->getOpcode() == Instruction::ShuffleVector &&
1696       isa<UndefValue>(Shuf->getOperand(1))) {
1697 
1698     const auto *IElt = dyn_cast<ConstantExpr>(Shuf->getOperand(0));
1699     if (IElt && IElt->getOpcode() == Instruction::InsertElement &&
1700         isa<UndefValue>(IElt->getOperand(0))) {
1701 
1702       ArrayRef<int> Mask = Shuf->getShuffleMask();
1703       Constant *SplatVal = IElt->getOperand(1);
1704       ConstantInt *Index = dyn_cast<ConstantInt>(IElt->getOperand(2));
1705 
1706       if (Index && Index->getValue() == 0 &&
1707           llvm::all_of(Mask, [](int I) { return I == 0; }))
1708         return SplatVal;
1709     }
1710   }
1711 
1712   return nullptr;
1713 }
1714 
1715 Constant *ConstantVector::getSplatValue(bool AllowUndefs) const {
1716   // Check out first element.
1717   Constant *Elt = getOperand(0);
1718   // Then make sure all remaining elements point to the same value.
1719   for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1720     Constant *OpC = getOperand(I);
1721     if (OpC == Elt)
1722       continue;
1723 
1724     // Strict mode: any mismatch is not a splat.
1725     if (!AllowUndefs)
1726       return nullptr;
1727 
1728     // Allow undefs mode: ignore undefined elements.
1729     if (isa<UndefValue>(OpC))
1730       continue;
1731 
1732     // If we do not have a defined element yet, use the current operand.
1733     if (isa<UndefValue>(Elt))
1734       Elt = OpC;
1735 
1736     if (OpC != Elt)
1737       return nullptr;
1738   }
1739   return Elt;
1740 }
1741 
1742 const APInt &Constant::getUniqueInteger() const {
1743   if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
1744     return CI->getValue();
1745   assert(this->getSplatValue() && "Doesn't contain a unique integer!");
1746   const Constant *C = this->getAggregateElement(0U);
1747   assert(C && isa<ConstantInt>(C) && "Not a vector of numbers!");
1748   return cast<ConstantInt>(C)->getValue();
1749 }
1750 
1751 //---- ConstantPointerNull::get() implementation.
1752 //
1753 
1754 ConstantPointerNull *ConstantPointerNull::get(PointerType *Ty) {
1755   std::unique_ptr<ConstantPointerNull> &Entry =
1756       Ty->getContext().pImpl->CPNConstants[Ty];
1757   if (!Entry)
1758     Entry.reset(new ConstantPointerNull(Ty));
1759 
1760   return Entry.get();
1761 }
1762 
1763 /// Remove the constant from the constant table.
1764 void ConstantPointerNull::destroyConstantImpl() {
1765   getContext().pImpl->CPNConstants.erase(getType());
1766 }
1767 
1768 UndefValue *UndefValue::get(Type *Ty) {
1769   std::unique_ptr<UndefValue> &Entry = Ty->getContext().pImpl->UVConstants[Ty];
1770   if (!Entry)
1771     Entry.reset(new UndefValue(Ty));
1772 
1773   return Entry.get();
1774 }
1775 
1776 /// Remove the constant from the constant table.
1777 void UndefValue::destroyConstantImpl() {
1778   // Free the constant and any dangling references to it.
1779   if (getValueID() == UndefValueVal) {
1780     getContext().pImpl->UVConstants.erase(getType());
1781   } else if (getValueID() == PoisonValueVal) {
1782     getContext().pImpl->PVConstants.erase(getType());
1783   }
1784   llvm_unreachable("Not a undef or a poison!");
1785 }
1786 
1787 PoisonValue *PoisonValue::get(Type *Ty) {
1788   std::unique_ptr<PoisonValue> &Entry = Ty->getContext().pImpl->PVConstants[Ty];
1789   if (!Entry)
1790     Entry.reset(new PoisonValue(Ty));
1791 
1792   return Entry.get();
1793 }
1794 
1795 /// Remove the constant from the constant table.
1796 void PoisonValue::destroyConstantImpl() {
1797   // Free the constant and any dangling references to it.
1798   getContext().pImpl->PVConstants.erase(getType());
1799 }
1800 
1801 BlockAddress *BlockAddress::get(BasicBlock *BB) {
1802   assert(BB->getParent() && "Block must have a parent");
1803   return get(BB->getParent(), BB);
1804 }
1805 
1806 BlockAddress *BlockAddress::get(Function *F, BasicBlock *BB) {
1807   BlockAddress *&BA =
1808     F->getContext().pImpl->BlockAddresses[std::make_pair(F, BB)];
1809   if (!BA)
1810     BA = new BlockAddress(F, BB);
1811 
1812   assert(BA->getFunction() == F && "Basic block moved between functions");
1813   return BA;
1814 }
1815 
1816 BlockAddress::BlockAddress(Function *F, BasicBlock *BB)
1817     : Constant(Type::getInt8PtrTy(F->getContext(), F->getAddressSpace()),
1818                Value::BlockAddressVal, &Op<0>(), 2) {
1819   setOperand(0, F);
1820   setOperand(1, BB);
1821   BB->AdjustBlockAddressRefCount(1);
1822 }
1823 
1824 BlockAddress *BlockAddress::lookup(const BasicBlock *BB) {
1825   if (!BB->hasAddressTaken())
1826     return nullptr;
1827 
1828   const Function *F = BB->getParent();
1829   assert(F && "Block must have a parent");
1830   BlockAddress *BA =
1831       F->getContext().pImpl->BlockAddresses.lookup(std::make_pair(F, BB));
1832   assert(BA && "Refcount and block address map disagree!");
1833   return BA;
1834 }
1835 
1836 /// Remove the constant from the constant table.
1837 void BlockAddress::destroyConstantImpl() {
1838   getFunction()->getType()->getContext().pImpl
1839     ->BlockAddresses.erase(std::make_pair(getFunction(), getBasicBlock()));
1840   getBasicBlock()->AdjustBlockAddressRefCount(-1);
1841 }
1842 
1843 Value *BlockAddress::handleOperandChangeImpl(Value *From, Value *To) {
1844   // This could be replacing either the Basic Block or the Function.  In either
1845   // case, we have to remove the map entry.
1846   Function *NewF = getFunction();
1847   BasicBlock *NewBB = getBasicBlock();
1848 
1849   if (From == NewF)
1850     NewF = cast<Function>(To->stripPointerCasts());
1851   else {
1852     assert(From == NewBB && "From does not match any operand");
1853     NewBB = cast<BasicBlock>(To);
1854   }
1855 
1856   // See if the 'new' entry already exists, if not, just update this in place
1857   // and return early.
1858   BlockAddress *&NewBA =
1859     getContext().pImpl->BlockAddresses[std::make_pair(NewF, NewBB)];
1860   if (NewBA)
1861     return NewBA;
1862 
1863   getBasicBlock()->AdjustBlockAddressRefCount(-1);
1864 
1865   // Remove the old entry, this can't cause the map to rehash (just a
1866   // tombstone will get added).
1867   getContext().pImpl->BlockAddresses.erase(std::make_pair(getFunction(),
1868                                                           getBasicBlock()));
1869   NewBA = this;
1870   setOperand(0, NewF);
1871   setOperand(1, NewBB);
1872   getBasicBlock()->AdjustBlockAddressRefCount(1);
1873 
1874   // If we just want to keep the existing value, then return null.
1875   // Callers know that this means we shouldn't delete this value.
1876   return nullptr;
1877 }
1878 
1879 DSOLocalEquivalent *DSOLocalEquivalent::get(GlobalValue *GV) {
1880   DSOLocalEquivalent *&Equiv = GV->getContext().pImpl->DSOLocalEquivalents[GV];
1881   if (!Equiv)
1882     Equiv = new DSOLocalEquivalent(GV);
1883 
1884   assert(Equiv->getGlobalValue() == GV &&
1885          "DSOLocalFunction does not match the expected global value");
1886   return Equiv;
1887 }
1888 
1889 DSOLocalEquivalent::DSOLocalEquivalent(GlobalValue *GV)
1890     : Constant(GV->getType(), Value::DSOLocalEquivalentVal, &Op<0>(), 1) {
1891   setOperand(0, GV);
1892 }
1893 
1894 /// Remove the constant from the constant table.
1895 void DSOLocalEquivalent::destroyConstantImpl() {
1896   const GlobalValue *GV = getGlobalValue();
1897   GV->getContext().pImpl->DSOLocalEquivalents.erase(GV);
1898 }
1899 
1900 Value *DSOLocalEquivalent::handleOperandChangeImpl(Value *From, Value *To) {
1901   assert(From == getGlobalValue() && "Changing value does not match operand.");
1902   assert(isa<Constant>(To) && "Can only replace the operands with a constant");
1903 
1904   // The replacement is with another global value.
1905   if (const auto *ToObj = dyn_cast<GlobalValue>(To)) {
1906     DSOLocalEquivalent *&NewEquiv =
1907         getContext().pImpl->DSOLocalEquivalents[ToObj];
1908     if (NewEquiv)
1909       return llvm::ConstantExpr::getBitCast(NewEquiv, getType());
1910   }
1911 
1912   // If the argument is replaced with a null value, just replace this constant
1913   // with a null value.
1914   if (cast<Constant>(To)->isNullValue())
1915     return To;
1916 
1917   // The replacement could be a bitcast or an alias to another function. We can
1918   // replace it with a bitcast to the dso_local_equivalent of that function.
1919   auto *Func = cast<Function>(To->stripPointerCastsAndAliases());
1920   DSOLocalEquivalent *&NewEquiv = getContext().pImpl->DSOLocalEquivalents[Func];
1921   if (NewEquiv)
1922     return llvm::ConstantExpr::getBitCast(NewEquiv, getType());
1923 
1924   // Replace this with the new one.
1925   getContext().pImpl->DSOLocalEquivalents.erase(getGlobalValue());
1926   NewEquiv = this;
1927   setOperand(0, Func);
1928 
1929   if (Func->getType() != getType()) {
1930     // It is ok to mutate the type here because this constant should always
1931     // reflect the type of the function it's holding.
1932     mutateType(Func->getType());
1933   }
1934   return nullptr;
1935 }
1936 
1937 NoCFIValue *NoCFIValue::get(GlobalValue *GV) {
1938   NoCFIValue *&NC = GV->getContext().pImpl->NoCFIValues[GV];
1939   if (!NC)
1940     NC = new NoCFIValue(GV);
1941 
1942   assert(NC->getGlobalValue() == GV &&
1943          "NoCFIValue does not match the expected global value");
1944   return NC;
1945 }
1946 
1947 NoCFIValue::NoCFIValue(GlobalValue *GV)
1948     : Constant(GV->getType(), Value::NoCFIValueVal, &Op<0>(), 1) {
1949   setOperand(0, GV);
1950 }
1951 
1952 /// Remove the constant from the constant table.
1953 void NoCFIValue::destroyConstantImpl() {
1954   const GlobalValue *GV = getGlobalValue();
1955   GV->getContext().pImpl->NoCFIValues.erase(GV);
1956 }
1957 
1958 Value *NoCFIValue::handleOperandChangeImpl(Value *From, Value *To) {
1959   assert(From == getGlobalValue() && "Changing value does not match operand.");
1960 
1961   GlobalValue *GV = dyn_cast<GlobalValue>(To->stripPointerCasts());
1962   assert(GV && "Can only replace the operands with a global value");
1963 
1964   NoCFIValue *&NewNC = getContext().pImpl->NoCFIValues[GV];
1965   if (NewNC)
1966     return llvm::ConstantExpr::getBitCast(NewNC, getType());
1967 
1968   getContext().pImpl->NoCFIValues.erase(getGlobalValue());
1969   NewNC = this;
1970   setOperand(0, GV);
1971 
1972   if (GV->getType() != getType())
1973     mutateType(GV->getType());
1974 
1975   return nullptr;
1976 }
1977 
1978 //---- ConstantExpr::get() implementations.
1979 //
1980 
1981 /// This is a utility function to handle folding of casts and lookup of the
1982 /// cast in the ExprConstants map. It is used by the various get* methods below.
1983 static Constant *getFoldedCast(Instruction::CastOps opc, Constant *C, Type *Ty,
1984                                bool OnlyIfReduced = false) {
1985   assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1986   // Fold a few common cases
1987   if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1988     return FC;
1989 
1990   if (OnlyIfReduced)
1991     return nullptr;
1992 
1993   LLVMContextImpl *pImpl = Ty->getContext().pImpl;
1994 
1995   // Look up the constant in the table first to ensure uniqueness.
1996   ConstantExprKeyType Key(opc, C);
1997 
1998   return pImpl->ExprConstants.getOrCreate(Ty, Key);
1999 }
2000 
2001 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, Type *Ty,
2002                                 bool OnlyIfReduced) {
2003   Instruction::CastOps opc = Instruction::CastOps(oc);
2004   assert(Instruction::isCast(opc) && "opcode out of range");
2005   assert(C && Ty && "Null arguments to getCast");
2006   assert(CastInst::castIsValid(opc, C, Ty) && "Invalid constantexpr cast!");
2007 
2008   switch (opc) {
2009   default:
2010     llvm_unreachable("Invalid cast opcode");
2011   case Instruction::Trunc:
2012     return getTrunc(C, Ty, OnlyIfReduced);
2013   case Instruction::ZExt:
2014     return getZExt(C, Ty, OnlyIfReduced);
2015   case Instruction::SExt:
2016     return getSExt(C, Ty, OnlyIfReduced);
2017   case Instruction::FPTrunc:
2018     return getFPTrunc(C, Ty, OnlyIfReduced);
2019   case Instruction::FPExt:
2020     return getFPExtend(C, Ty, OnlyIfReduced);
2021   case Instruction::UIToFP:
2022     return getUIToFP(C, Ty, OnlyIfReduced);
2023   case Instruction::SIToFP:
2024     return getSIToFP(C, Ty, OnlyIfReduced);
2025   case Instruction::FPToUI:
2026     return getFPToUI(C, Ty, OnlyIfReduced);
2027   case Instruction::FPToSI:
2028     return getFPToSI(C, Ty, OnlyIfReduced);
2029   case Instruction::PtrToInt:
2030     return getPtrToInt(C, Ty, OnlyIfReduced);
2031   case Instruction::IntToPtr:
2032     return getIntToPtr(C, Ty, OnlyIfReduced);
2033   case Instruction::BitCast:
2034     return getBitCast(C, Ty, OnlyIfReduced);
2035   case Instruction::AddrSpaceCast:
2036     return getAddrSpaceCast(C, Ty, OnlyIfReduced);
2037   }
2038 }
2039 
2040 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, Type *Ty) {
2041   if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2042     return getBitCast(C, Ty);
2043   return getZExt(C, Ty);
2044 }
2045 
2046 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, Type *Ty) {
2047   if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2048     return getBitCast(C, Ty);
2049   return getSExt(C, Ty);
2050 }
2051 
2052 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, Type *Ty) {
2053   if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2054     return getBitCast(C, Ty);
2055   return getTrunc(C, Ty);
2056 }
2057 
2058 Constant *ConstantExpr::getSExtOrTrunc(Constant *C, Type *Ty) {
2059   assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
2060          "Can only sign extend/truncate integers!");
2061   Type *CTy = C->getType();
2062   if (CTy->getScalarSizeInBits() < Ty->getScalarSizeInBits())
2063     return getSExt(C, Ty);
2064   if (CTy->getScalarSizeInBits() > Ty->getScalarSizeInBits())
2065     return getTrunc(C, Ty);
2066   return C;
2067 }
2068 
2069 Constant *ConstantExpr::getPointerCast(Constant *S, Type *Ty) {
2070   assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2071   assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
2072           "Invalid cast");
2073 
2074   if (Ty->isIntOrIntVectorTy())
2075     return getPtrToInt(S, Ty);
2076 
2077   unsigned SrcAS = S->getType()->getPointerAddressSpace();
2078   if (Ty->isPtrOrPtrVectorTy() && SrcAS != Ty->getPointerAddressSpace())
2079     return getAddrSpaceCast(S, Ty);
2080 
2081   return getBitCast(S, Ty);
2082 }
2083 
2084 Constant *ConstantExpr::getPointerBitCastOrAddrSpaceCast(Constant *S,
2085                                                          Type *Ty) {
2086   assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2087   assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
2088 
2089   if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
2090     return getAddrSpaceCast(S, Ty);
2091 
2092   return getBitCast(S, Ty);
2093 }
2094 
2095 Constant *ConstantExpr::getIntegerCast(Constant *C, Type *Ty, bool isSigned) {
2096   assert(C->getType()->isIntOrIntVectorTy() &&
2097          Ty->isIntOrIntVectorTy() && "Invalid cast");
2098   unsigned SrcBits = C->getType()->getScalarSizeInBits();
2099   unsigned DstBits = Ty->getScalarSizeInBits();
2100   Instruction::CastOps opcode =
2101     (SrcBits == DstBits ? Instruction::BitCast :
2102      (SrcBits > DstBits ? Instruction::Trunc :
2103       (isSigned ? Instruction::SExt : Instruction::ZExt)));
2104   return getCast(opcode, C, Ty);
2105 }
2106 
2107 Constant *ConstantExpr::getFPCast(Constant *C, Type *Ty) {
2108   assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
2109          "Invalid cast");
2110   unsigned SrcBits = C->getType()->getScalarSizeInBits();
2111   unsigned DstBits = Ty->getScalarSizeInBits();
2112   if (SrcBits == DstBits)
2113     return C; // Avoid a useless cast
2114   Instruction::CastOps opcode =
2115     (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
2116   return getCast(opcode, C, Ty);
2117 }
2118 
2119 Constant *ConstantExpr::getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) {
2120 #ifndef NDEBUG
2121   bool fromVec = isa<VectorType>(C->getType());
2122   bool toVec = isa<VectorType>(Ty);
2123 #endif
2124   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2125   assert(C->getType()->isIntOrIntVectorTy() && "Trunc operand must be integer");
2126   assert(Ty->isIntOrIntVectorTy() && "Trunc produces only integral");
2127   assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
2128          "SrcTy must be larger than DestTy for Trunc!");
2129 
2130   return getFoldedCast(Instruction::Trunc, C, Ty, OnlyIfReduced);
2131 }
2132 
2133 Constant *ConstantExpr::getSExt(Constant *C, Type *Ty, bool OnlyIfReduced) {
2134 #ifndef NDEBUG
2135   bool fromVec = isa<VectorType>(C->getType());
2136   bool toVec = isa<VectorType>(Ty);
2137 #endif
2138   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2139   assert(C->getType()->isIntOrIntVectorTy() && "SExt operand must be integral");
2140   assert(Ty->isIntOrIntVectorTy() && "SExt produces only integer");
2141   assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
2142          "SrcTy must be smaller than DestTy for SExt!");
2143 
2144   return getFoldedCast(Instruction::SExt, C, Ty, OnlyIfReduced);
2145 }
2146 
2147 Constant *ConstantExpr::getZExt(Constant *C, Type *Ty, bool OnlyIfReduced) {
2148 #ifndef NDEBUG
2149   bool fromVec = isa<VectorType>(C->getType());
2150   bool toVec = isa<VectorType>(Ty);
2151 #endif
2152   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2153   assert(C->getType()->isIntOrIntVectorTy() && "ZEXt operand must be integral");
2154   assert(Ty->isIntOrIntVectorTy() && "ZExt produces only integer");
2155   assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
2156          "SrcTy must be smaller than DestTy for ZExt!");
2157 
2158   return getFoldedCast(Instruction::ZExt, C, Ty, OnlyIfReduced);
2159 }
2160 
2161 Constant *ConstantExpr::getFPTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) {
2162 #ifndef NDEBUG
2163   bool fromVec = isa<VectorType>(C->getType());
2164   bool toVec = isa<VectorType>(Ty);
2165 #endif
2166   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2167   assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
2168          C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
2169          "This is an illegal floating point truncation!");
2170   return getFoldedCast(Instruction::FPTrunc, C, Ty, OnlyIfReduced);
2171 }
2172 
2173 Constant *ConstantExpr::getFPExtend(Constant *C, Type *Ty, bool OnlyIfReduced) {
2174 #ifndef NDEBUG
2175   bool fromVec = isa<VectorType>(C->getType());
2176   bool toVec = isa<VectorType>(Ty);
2177 #endif
2178   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2179   assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
2180          C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
2181          "This is an illegal floating point extension!");
2182   return getFoldedCast(Instruction::FPExt, C, Ty, OnlyIfReduced);
2183 }
2184 
2185 Constant *ConstantExpr::getUIToFP(Constant *C, Type *Ty, bool OnlyIfReduced) {
2186 #ifndef NDEBUG
2187   bool fromVec = isa<VectorType>(C->getType());
2188   bool toVec = isa<VectorType>(Ty);
2189 #endif
2190   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2191   assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
2192          "This is an illegal uint to floating point cast!");
2193   return getFoldedCast(Instruction::UIToFP, C, Ty, OnlyIfReduced);
2194 }
2195 
2196 Constant *ConstantExpr::getSIToFP(Constant *C, Type *Ty, bool OnlyIfReduced) {
2197 #ifndef NDEBUG
2198   bool fromVec = isa<VectorType>(C->getType());
2199   bool toVec = isa<VectorType>(Ty);
2200 #endif
2201   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2202   assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
2203          "This is an illegal sint to floating point cast!");
2204   return getFoldedCast(Instruction::SIToFP, C, Ty, OnlyIfReduced);
2205 }
2206 
2207 Constant *ConstantExpr::getFPToUI(Constant *C, Type *Ty, bool OnlyIfReduced) {
2208 #ifndef NDEBUG
2209   bool fromVec = isa<VectorType>(C->getType());
2210   bool toVec = isa<VectorType>(Ty);
2211 #endif
2212   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2213   assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
2214          "This is an illegal floating point to uint cast!");
2215   return getFoldedCast(Instruction::FPToUI, C, Ty, OnlyIfReduced);
2216 }
2217 
2218 Constant *ConstantExpr::getFPToSI(Constant *C, Type *Ty, bool OnlyIfReduced) {
2219 #ifndef NDEBUG
2220   bool fromVec = isa<VectorType>(C->getType());
2221   bool toVec = isa<VectorType>(Ty);
2222 #endif
2223   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2224   assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
2225          "This is an illegal floating point to sint cast!");
2226   return getFoldedCast(Instruction::FPToSI, C, Ty, OnlyIfReduced);
2227 }
2228 
2229 Constant *ConstantExpr::getPtrToInt(Constant *C, Type *DstTy,
2230                                     bool OnlyIfReduced) {
2231   assert(C->getType()->isPtrOrPtrVectorTy() &&
2232          "PtrToInt source must be pointer or pointer vector");
2233   assert(DstTy->isIntOrIntVectorTy() &&
2234          "PtrToInt destination must be integer or integer vector");
2235   assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
2236   if (isa<VectorType>(C->getType()))
2237     assert(cast<VectorType>(C->getType())->getElementCount() ==
2238                cast<VectorType>(DstTy)->getElementCount() &&
2239            "Invalid cast between a different number of vector elements");
2240   return getFoldedCast(Instruction::PtrToInt, C, DstTy, OnlyIfReduced);
2241 }
2242 
2243 Constant *ConstantExpr::getIntToPtr(Constant *C, Type *DstTy,
2244                                     bool OnlyIfReduced) {
2245   assert(C->getType()->isIntOrIntVectorTy() &&
2246          "IntToPtr source must be integer or integer vector");
2247   assert(DstTy->isPtrOrPtrVectorTy() &&
2248          "IntToPtr destination must be a pointer or pointer vector");
2249   assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
2250   if (isa<VectorType>(C->getType()))
2251     assert(cast<VectorType>(C->getType())->getElementCount() ==
2252                cast<VectorType>(DstTy)->getElementCount() &&
2253            "Invalid cast between a different number of vector elements");
2254   return getFoldedCast(Instruction::IntToPtr, C, DstTy, OnlyIfReduced);
2255 }
2256 
2257 Constant *ConstantExpr::getBitCast(Constant *C, Type *DstTy,
2258                                    bool OnlyIfReduced) {
2259   assert(CastInst::castIsValid(Instruction::BitCast, C, DstTy) &&
2260          "Invalid constantexpr bitcast!");
2261 
2262   // It is common to ask for a bitcast of a value to its own type, handle this
2263   // speedily.
2264   if (C->getType() == DstTy) return C;
2265 
2266   return getFoldedCast(Instruction::BitCast, C, DstTy, OnlyIfReduced);
2267 }
2268 
2269 Constant *ConstantExpr::getAddrSpaceCast(Constant *C, Type *DstTy,
2270                                          bool OnlyIfReduced) {
2271   assert(CastInst::castIsValid(Instruction::AddrSpaceCast, C, DstTy) &&
2272          "Invalid constantexpr addrspacecast!");
2273 
2274   // Canonicalize addrspacecasts between different pointer types by first
2275   // bitcasting the pointer type and then converting the address space.
2276   PointerType *SrcScalarTy = cast<PointerType>(C->getType()->getScalarType());
2277   PointerType *DstScalarTy = cast<PointerType>(DstTy->getScalarType());
2278   if (!SrcScalarTy->hasSameElementTypeAs(DstScalarTy)) {
2279     Type *MidTy = PointerType::getWithSamePointeeType(
2280         DstScalarTy, SrcScalarTy->getAddressSpace());
2281     if (VectorType *VT = dyn_cast<VectorType>(DstTy)) {
2282       // Handle vectors of pointers.
2283       MidTy = FixedVectorType::get(MidTy,
2284                                    cast<FixedVectorType>(VT)->getNumElements());
2285     }
2286     C = getBitCast(C, MidTy);
2287   }
2288   return getFoldedCast(Instruction::AddrSpaceCast, C, DstTy, OnlyIfReduced);
2289 }
2290 
2291 Constant *ConstantExpr::get(unsigned Opcode, Constant *C, unsigned Flags,
2292                             Type *OnlyIfReducedTy) {
2293   // Check the operands for consistency first.
2294   assert(Instruction::isUnaryOp(Opcode) &&
2295          "Invalid opcode in unary constant expression");
2296 
2297 #ifndef NDEBUG
2298   switch (Opcode) {
2299   case Instruction::FNeg:
2300     assert(C->getType()->isFPOrFPVectorTy() &&
2301            "Tried to create a floating-point operation on a "
2302            "non-floating-point type!");
2303     break;
2304   default:
2305     break;
2306   }
2307 #endif
2308 
2309   if (Constant *FC = ConstantFoldUnaryInstruction(Opcode, C))
2310     return FC;
2311 
2312   if (OnlyIfReducedTy == C->getType())
2313     return nullptr;
2314 
2315   Constant *ArgVec[] = { C };
2316   ConstantExprKeyType Key(Opcode, ArgVec, 0, Flags);
2317 
2318   LLVMContextImpl *pImpl = C->getContext().pImpl;
2319   return pImpl->ExprConstants.getOrCreate(C->getType(), Key);
2320 }
2321 
2322 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2,
2323                             unsigned Flags, Type *OnlyIfReducedTy) {
2324   // Check the operands for consistency first.
2325   assert(Instruction::isBinaryOp(Opcode) &&
2326          "Invalid opcode in binary constant expression");
2327   assert(C1->getType() == C2->getType() &&
2328          "Operand types in binary constant expression should match");
2329 
2330 #ifndef NDEBUG
2331   switch (Opcode) {
2332   case Instruction::Add:
2333   case Instruction::Sub:
2334   case Instruction::Mul:
2335   case Instruction::UDiv:
2336   case Instruction::SDiv:
2337   case Instruction::URem:
2338   case Instruction::SRem:
2339     assert(C1->getType()->isIntOrIntVectorTy() &&
2340            "Tried to create an integer operation on a non-integer type!");
2341     break;
2342   case Instruction::FAdd:
2343   case Instruction::FSub:
2344   case Instruction::FMul:
2345   case Instruction::FDiv:
2346   case Instruction::FRem:
2347     assert(C1->getType()->isFPOrFPVectorTy() &&
2348            "Tried to create a floating-point operation on a "
2349            "non-floating-point type!");
2350     break;
2351   case Instruction::And:
2352   case Instruction::Or:
2353   case Instruction::Xor:
2354     assert(C1->getType()->isIntOrIntVectorTy() &&
2355            "Tried to create a logical operation on a non-integral type!");
2356     break;
2357   case Instruction::Shl:
2358   case Instruction::LShr:
2359   case Instruction::AShr:
2360     assert(C1->getType()->isIntOrIntVectorTy() &&
2361            "Tried to create a shift operation on a non-integer type!");
2362     break;
2363   default:
2364     break;
2365   }
2366 #endif
2367 
2368   if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
2369     return FC;
2370 
2371   if (OnlyIfReducedTy == C1->getType())
2372     return nullptr;
2373 
2374   Constant *ArgVec[] = { C1, C2 };
2375   ConstantExprKeyType Key(Opcode, ArgVec, 0, Flags);
2376 
2377   LLVMContextImpl *pImpl = C1->getContext().pImpl;
2378   return pImpl->ExprConstants.getOrCreate(C1->getType(), Key);
2379 }
2380 
2381 Constant *ConstantExpr::getSizeOf(Type* Ty) {
2382   // sizeof is implemented as: (i64) gep (Ty*)null, 1
2383   // Note that a non-inbounds gep is used, as null isn't within any object.
2384   Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
2385   Constant *GEP = getGetElementPtr(
2386       Ty, Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
2387   return getPtrToInt(GEP,
2388                      Type::getInt64Ty(Ty->getContext()));
2389 }
2390 
2391 Constant *ConstantExpr::getAlignOf(Type* Ty) {
2392   // alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1
2393   // Note that a non-inbounds gep is used, as null isn't within any object.
2394   Type *AligningTy = StructType::get(Type::getInt1Ty(Ty->getContext()), Ty);
2395   Constant *NullPtr = Constant::getNullValue(AligningTy->getPointerTo(0));
2396   Constant *Zero = ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0);
2397   Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
2398   Constant *Indices[2] = { Zero, One };
2399   Constant *GEP = getGetElementPtr(AligningTy, NullPtr, Indices);
2400   return getPtrToInt(GEP,
2401                      Type::getInt64Ty(Ty->getContext()));
2402 }
2403 
2404 Constant *ConstantExpr::getOffsetOf(StructType* STy, unsigned FieldNo) {
2405   return getOffsetOf(STy, ConstantInt::get(Type::getInt32Ty(STy->getContext()),
2406                                            FieldNo));
2407 }
2408 
2409 Constant *ConstantExpr::getOffsetOf(Type* Ty, Constant *FieldNo) {
2410   // offsetof is implemented as: (i64) gep (Ty*)null, 0, FieldNo
2411   // Note that a non-inbounds gep is used, as null isn't within any object.
2412   Constant *GEPIdx[] = {
2413     ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0),
2414     FieldNo
2415   };
2416   Constant *GEP = getGetElementPtr(
2417       Ty, Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
2418   return getPtrToInt(GEP,
2419                      Type::getInt64Ty(Ty->getContext()));
2420 }
2421 
2422 Constant *ConstantExpr::getCompare(unsigned short Predicate, Constant *C1,
2423                                    Constant *C2, bool OnlyIfReduced) {
2424   assert(C1->getType() == C2->getType() && "Op types should be identical!");
2425 
2426   switch (Predicate) {
2427   default: llvm_unreachable("Invalid CmpInst predicate");
2428   case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
2429   case CmpInst::FCMP_OGE:   case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
2430   case CmpInst::FCMP_ONE:   case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
2431   case CmpInst::FCMP_UEQ:   case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
2432   case CmpInst::FCMP_ULT:   case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
2433   case CmpInst::FCMP_TRUE:
2434     return getFCmp(Predicate, C1, C2, OnlyIfReduced);
2435 
2436   case CmpInst::ICMP_EQ:  case CmpInst::ICMP_NE:  case CmpInst::ICMP_UGT:
2437   case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
2438   case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
2439   case CmpInst::ICMP_SLE:
2440     return getICmp(Predicate, C1, C2, OnlyIfReduced);
2441   }
2442 }
2443 
2444 Constant *ConstantExpr::getSelect(Constant *C, Constant *V1, Constant *V2,
2445                                   Type *OnlyIfReducedTy) {
2446   assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
2447 
2448   if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
2449     return SC;        // Fold common cases
2450 
2451   if (OnlyIfReducedTy == V1->getType())
2452     return nullptr;
2453 
2454   Constant *ArgVec[] = { C, V1, V2 };
2455   ConstantExprKeyType Key(Instruction::Select, ArgVec);
2456 
2457   LLVMContextImpl *pImpl = C->getContext().pImpl;
2458   return pImpl->ExprConstants.getOrCreate(V1->getType(), Key);
2459 }
2460 
2461 Constant *ConstantExpr::getGetElementPtr(Type *Ty, Constant *C,
2462                                          ArrayRef<Value *> Idxs, bool InBounds,
2463                                          Optional<unsigned> InRangeIndex,
2464                                          Type *OnlyIfReducedTy) {
2465   PointerType *OrigPtrTy = cast<PointerType>(C->getType()->getScalarType());
2466   assert(Ty && "Must specify element type");
2467   assert(OrigPtrTy->isOpaqueOrPointeeTypeMatches(Ty));
2468 
2469   if (Constant *FC =
2470           ConstantFoldGetElementPtr(Ty, C, InBounds, InRangeIndex, Idxs))
2471     return FC;          // Fold a few common cases.
2472 
2473   // Get the result type of the getelementptr!
2474   Type *DestTy = GetElementPtrInst::getIndexedType(Ty, Idxs);
2475   assert(DestTy && "GEP indices invalid!");
2476   unsigned AS = OrigPtrTy->getAddressSpace();
2477   Type *ReqTy = OrigPtrTy->isOpaque()
2478       ? PointerType::get(OrigPtrTy->getContext(), AS)
2479       : DestTy->getPointerTo(AS);
2480 
2481   auto EltCount = ElementCount::getFixed(0);
2482   if (VectorType *VecTy = dyn_cast<VectorType>(C->getType()))
2483     EltCount = VecTy->getElementCount();
2484   else
2485     for (auto Idx : Idxs)
2486       if (VectorType *VecTy = dyn_cast<VectorType>(Idx->getType()))
2487         EltCount = VecTy->getElementCount();
2488 
2489   if (EltCount.isNonZero())
2490     ReqTy = VectorType::get(ReqTy, EltCount);
2491 
2492   if (OnlyIfReducedTy == ReqTy)
2493     return nullptr;
2494 
2495   // Look up the constant in the table first to ensure uniqueness
2496   std::vector<Constant*> ArgVec;
2497   ArgVec.reserve(1 + Idxs.size());
2498   ArgVec.push_back(C);
2499   auto GTI = gep_type_begin(Ty, Idxs), GTE = gep_type_end(Ty, Idxs);
2500   for (; GTI != GTE; ++GTI) {
2501     auto *Idx = cast<Constant>(GTI.getOperand());
2502     assert(
2503         (!isa<VectorType>(Idx->getType()) ||
2504          cast<VectorType>(Idx->getType())->getElementCount() == EltCount) &&
2505         "getelementptr index type missmatch");
2506 
2507     if (GTI.isStruct() && Idx->getType()->isVectorTy()) {
2508       Idx = Idx->getSplatValue();
2509     } else if (GTI.isSequential() && EltCount.isNonZero() &&
2510                !Idx->getType()->isVectorTy()) {
2511       Idx = ConstantVector::getSplat(EltCount, Idx);
2512     }
2513     ArgVec.push_back(Idx);
2514   }
2515 
2516   unsigned SubClassOptionalData = InBounds ? GEPOperator::IsInBounds : 0;
2517   if (InRangeIndex && *InRangeIndex < 63)
2518     SubClassOptionalData |= (*InRangeIndex + 1) << 1;
2519   const ConstantExprKeyType Key(Instruction::GetElementPtr, ArgVec, 0,
2520                                 SubClassOptionalData, None, None, Ty);
2521 
2522   LLVMContextImpl *pImpl = C->getContext().pImpl;
2523   return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2524 }
2525 
2526 Constant *ConstantExpr::getICmp(unsigned short pred, Constant *LHS,
2527                                 Constant *RHS, bool OnlyIfReduced) {
2528   auto Predicate = static_cast<CmpInst::Predicate>(pred);
2529   assert(LHS->getType() == RHS->getType());
2530   assert(CmpInst::isIntPredicate(Predicate) && "Invalid ICmp Predicate");
2531 
2532   if (Constant *FC = ConstantFoldCompareInstruction(Predicate, LHS, RHS))
2533     return FC;          // Fold a few common cases...
2534 
2535   if (OnlyIfReduced)
2536     return nullptr;
2537 
2538   // Look up the constant in the table first to ensure uniqueness
2539   Constant *ArgVec[] = { LHS, RHS };
2540   // Get the key type with both the opcode and predicate
2541   const ConstantExprKeyType Key(Instruction::ICmp, ArgVec, Predicate);
2542 
2543   Type *ResultTy = Type::getInt1Ty(LHS->getContext());
2544   if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
2545     ResultTy = VectorType::get(ResultTy, VT->getElementCount());
2546 
2547   LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
2548   return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
2549 }
2550 
2551 Constant *ConstantExpr::getFCmp(unsigned short pred, Constant *LHS,
2552                                 Constant *RHS, bool OnlyIfReduced) {
2553   auto Predicate = static_cast<CmpInst::Predicate>(pred);
2554   assert(LHS->getType() == RHS->getType());
2555   assert(CmpInst::isFPPredicate(Predicate) && "Invalid FCmp Predicate");
2556 
2557   if (Constant *FC = ConstantFoldCompareInstruction(Predicate, LHS, RHS))
2558     return FC;          // Fold a few common cases...
2559 
2560   if (OnlyIfReduced)
2561     return nullptr;
2562 
2563   // Look up the constant in the table first to ensure uniqueness
2564   Constant *ArgVec[] = { LHS, RHS };
2565   // Get the key type with both the opcode and predicate
2566   const ConstantExprKeyType Key(Instruction::FCmp, ArgVec, Predicate);
2567 
2568   Type *ResultTy = Type::getInt1Ty(LHS->getContext());
2569   if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
2570     ResultTy = VectorType::get(ResultTy, VT->getElementCount());
2571 
2572   LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
2573   return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
2574 }
2575 
2576 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx,
2577                                           Type *OnlyIfReducedTy) {
2578   assert(Val->getType()->isVectorTy() &&
2579          "Tried to create extractelement operation on non-vector type!");
2580   assert(Idx->getType()->isIntegerTy() &&
2581          "Extractelement index must be an integer type!");
2582 
2583   if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
2584     return FC;          // Fold a few common cases.
2585 
2586   Type *ReqTy = cast<VectorType>(Val->getType())->getElementType();
2587   if (OnlyIfReducedTy == ReqTy)
2588     return nullptr;
2589 
2590   // Look up the constant in the table first to ensure uniqueness
2591   Constant *ArgVec[] = { Val, Idx };
2592   const ConstantExprKeyType Key(Instruction::ExtractElement, ArgVec);
2593 
2594   LLVMContextImpl *pImpl = Val->getContext().pImpl;
2595   return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2596 }
2597 
2598 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
2599                                          Constant *Idx, Type *OnlyIfReducedTy) {
2600   assert(Val->getType()->isVectorTy() &&
2601          "Tried to create insertelement operation on non-vector type!");
2602   assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType() &&
2603          "Insertelement types must match!");
2604   assert(Idx->getType()->isIntegerTy() &&
2605          "Insertelement index must be i32 type!");
2606 
2607   if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
2608     return FC;          // Fold a few common cases.
2609 
2610   if (OnlyIfReducedTy == Val->getType())
2611     return nullptr;
2612 
2613   // Look up the constant in the table first to ensure uniqueness
2614   Constant *ArgVec[] = { Val, Elt, Idx };
2615   const ConstantExprKeyType Key(Instruction::InsertElement, ArgVec);
2616 
2617   LLVMContextImpl *pImpl = Val->getContext().pImpl;
2618   return pImpl->ExprConstants.getOrCreate(Val->getType(), Key);
2619 }
2620 
2621 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
2622                                          ArrayRef<int> Mask,
2623                                          Type *OnlyIfReducedTy) {
2624   assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
2625          "Invalid shuffle vector constant expr operands!");
2626 
2627   if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
2628     return FC;          // Fold a few common cases.
2629 
2630   unsigned NElts = Mask.size();
2631   auto V1VTy = cast<VectorType>(V1->getType());
2632   Type *EltTy = V1VTy->getElementType();
2633   bool TypeIsScalable = isa<ScalableVectorType>(V1VTy);
2634   Type *ShufTy = VectorType::get(EltTy, NElts, TypeIsScalable);
2635 
2636   if (OnlyIfReducedTy == ShufTy)
2637     return nullptr;
2638 
2639   // Look up the constant in the table first to ensure uniqueness
2640   Constant *ArgVec[] = {V1, V2};
2641   ConstantExprKeyType Key(Instruction::ShuffleVector, ArgVec, 0, 0, None, Mask);
2642 
2643   LLVMContextImpl *pImpl = ShufTy->getContext().pImpl;
2644   return pImpl->ExprConstants.getOrCreate(ShufTy, Key);
2645 }
2646 
2647 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
2648                                        ArrayRef<unsigned> Idxs,
2649                                        Type *OnlyIfReducedTy) {
2650   assert(Agg->getType()->isFirstClassType() &&
2651          "Non-first-class type for constant insertvalue expression");
2652 
2653   assert(ExtractValueInst::getIndexedType(Agg->getType(),
2654                                           Idxs) == Val->getType() &&
2655          "insertvalue indices invalid!");
2656   Type *ReqTy = Val->getType();
2657 
2658   if (Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs))
2659     return FC;
2660 
2661   if (OnlyIfReducedTy == ReqTy)
2662     return nullptr;
2663 
2664   Constant *ArgVec[] = { Agg, Val };
2665   const ConstantExprKeyType Key(Instruction::InsertValue, ArgVec, 0, 0, Idxs);
2666 
2667   LLVMContextImpl *pImpl = Agg->getContext().pImpl;
2668   return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2669 }
2670 
2671 Constant *ConstantExpr::getExtractValue(Constant *Agg, ArrayRef<unsigned> Idxs,
2672                                         Type *OnlyIfReducedTy) {
2673   assert(Agg->getType()->isFirstClassType() &&
2674          "Tried to create extractelement operation on non-first-class type!");
2675 
2676   Type *ReqTy = ExtractValueInst::getIndexedType(Agg->getType(), Idxs);
2677   (void)ReqTy;
2678   assert(ReqTy && "extractvalue indices invalid!");
2679 
2680   assert(Agg->getType()->isFirstClassType() &&
2681          "Non-first-class type for constant extractvalue expression");
2682   if (Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs))
2683     return FC;
2684 
2685   if (OnlyIfReducedTy == ReqTy)
2686     return nullptr;
2687 
2688   Constant *ArgVec[] = { Agg };
2689   const ConstantExprKeyType Key(Instruction::ExtractValue, ArgVec, 0, 0, Idxs);
2690 
2691   LLVMContextImpl *pImpl = Agg->getContext().pImpl;
2692   return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2693 }
2694 
2695 Constant *ConstantExpr::getNeg(Constant *C, bool HasNUW, bool HasNSW) {
2696   assert(C->getType()->isIntOrIntVectorTy() &&
2697          "Cannot NEG a nonintegral value!");
2698   return getSub(ConstantFP::getZeroValueForNegation(C->getType()),
2699                 C, HasNUW, HasNSW);
2700 }
2701 
2702 Constant *ConstantExpr::getFNeg(Constant *C) {
2703   assert(C->getType()->isFPOrFPVectorTy() &&
2704          "Cannot FNEG a non-floating-point value!");
2705   return get(Instruction::FNeg, C);
2706 }
2707 
2708 Constant *ConstantExpr::getNot(Constant *C) {
2709   assert(C->getType()->isIntOrIntVectorTy() &&
2710          "Cannot NOT a nonintegral value!");
2711   return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
2712 }
2713 
2714 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2,
2715                                bool HasNUW, bool HasNSW) {
2716   unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2717                    (HasNSW ? OverflowingBinaryOperator::NoSignedWrap   : 0);
2718   return get(Instruction::Add, C1, C2, Flags);
2719 }
2720 
2721 Constant *ConstantExpr::getFAdd(Constant *C1, Constant *C2) {
2722   return get(Instruction::FAdd, C1, C2);
2723 }
2724 
2725 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2,
2726                                bool HasNUW, bool HasNSW) {
2727   unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2728                    (HasNSW ? OverflowingBinaryOperator::NoSignedWrap   : 0);
2729   return get(Instruction::Sub, C1, C2, Flags);
2730 }
2731 
2732 Constant *ConstantExpr::getFSub(Constant *C1, Constant *C2) {
2733   return get(Instruction::FSub, C1, C2);
2734 }
2735 
2736 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2,
2737                                bool HasNUW, bool HasNSW) {
2738   unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2739                    (HasNSW ? OverflowingBinaryOperator::NoSignedWrap   : 0);
2740   return get(Instruction::Mul, C1, C2, Flags);
2741 }
2742 
2743 Constant *ConstantExpr::getFMul(Constant *C1, Constant *C2) {
2744   return get(Instruction::FMul, C1, C2);
2745 }
2746 
2747 Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2, bool isExact) {
2748   return get(Instruction::UDiv, C1, C2,
2749              isExact ? PossiblyExactOperator::IsExact : 0);
2750 }
2751 
2752 Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2, bool isExact) {
2753   return get(Instruction::SDiv, C1, C2,
2754              isExact ? PossiblyExactOperator::IsExact : 0);
2755 }
2756 
2757 Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
2758   return get(Instruction::FDiv, C1, C2);
2759 }
2760 
2761 Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
2762   return get(Instruction::URem, C1, C2);
2763 }
2764 
2765 Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
2766   return get(Instruction::SRem, C1, C2);
2767 }
2768 
2769 Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
2770   return get(Instruction::FRem, C1, C2);
2771 }
2772 
2773 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
2774   return get(Instruction::And, C1, C2);
2775 }
2776 
2777 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
2778   return get(Instruction::Or, C1, C2);
2779 }
2780 
2781 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
2782   return get(Instruction::Xor, C1, C2);
2783 }
2784 
2785 Constant *ConstantExpr::getUMin(Constant *C1, Constant *C2) {
2786   Constant *Cmp = ConstantExpr::getICmp(CmpInst::ICMP_ULT, C1, C2);
2787   return getSelect(Cmp, C1, C2);
2788 }
2789 
2790 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2,
2791                                bool HasNUW, bool HasNSW) {
2792   unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2793                    (HasNSW ? OverflowingBinaryOperator::NoSignedWrap   : 0);
2794   return get(Instruction::Shl, C1, C2, Flags);
2795 }
2796 
2797 Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2, bool isExact) {
2798   return get(Instruction::LShr, C1, C2,
2799              isExact ? PossiblyExactOperator::IsExact : 0);
2800 }
2801 
2802 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2, bool isExact) {
2803   return get(Instruction::AShr, C1, C2,
2804              isExact ? PossiblyExactOperator::IsExact : 0);
2805 }
2806 
2807 Constant *ConstantExpr::getExactLogBase2(Constant *C) {
2808   Type *Ty = C->getType();
2809   const APInt *IVal;
2810   if (match(C, m_APInt(IVal)) && IVal->isPowerOf2())
2811     return ConstantInt::get(Ty, IVal->logBase2());
2812 
2813   // FIXME: We can extract pow of 2 of splat constant for scalable vectors.
2814   auto *VecTy = dyn_cast<FixedVectorType>(Ty);
2815   if (!VecTy)
2816     return nullptr;
2817 
2818   SmallVector<Constant *, 4> Elts;
2819   for (unsigned I = 0, E = VecTy->getNumElements(); I != E; ++I) {
2820     Constant *Elt = C->getAggregateElement(I);
2821     if (!Elt)
2822       return nullptr;
2823     // Note that log2(iN undef) is *NOT* iN undef, because log2(iN undef) u< N.
2824     if (isa<UndefValue>(Elt)) {
2825       Elts.push_back(Constant::getNullValue(Ty->getScalarType()));
2826       continue;
2827     }
2828     if (!match(Elt, m_APInt(IVal)) || !IVal->isPowerOf2())
2829       return nullptr;
2830     Elts.push_back(ConstantInt::get(Ty->getScalarType(), IVal->logBase2()));
2831   }
2832 
2833   return ConstantVector::get(Elts);
2834 }
2835 
2836 Constant *ConstantExpr::getBinOpIdentity(unsigned Opcode, Type *Ty,
2837                                          bool AllowRHSConstant, bool NSZ) {
2838   assert(Instruction::isBinaryOp(Opcode) && "Only binops allowed");
2839 
2840   // Commutative opcodes: it does not matter if AllowRHSConstant is set.
2841   if (Instruction::isCommutative(Opcode)) {
2842     switch (Opcode) {
2843       case Instruction::Add: // X + 0 = X
2844       case Instruction::Or:  // X | 0 = X
2845       case Instruction::Xor: // X ^ 0 = X
2846         return Constant::getNullValue(Ty);
2847       case Instruction::Mul: // X * 1 = X
2848         return ConstantInt::get(Ty, 1);
2849       case Instruction::And: // X & -1 = X
2850         return Constant::getAllOnesValue(Ty);
2851       case Instruction::FAdd: // X + -0.0 = X
2852         return ConstantFP::getZero(Ty, !NSZ);
2853       case Instruction::FMul: // X * 1.0 = X
2854         return ConstantFP::get(Ty, 1.0);
2855       default:
2856         llvm_unreachable("Every commutative binop has an identity constant");
2857     }
2858   }
2859 
2860   // Non-commutative opcodes: AllowRHSConstant must be set.
2861   if (!AllowRHSConstant)
2862     return nullptr;
2863 
2864   switch (Opcode) {
2865     case Instruction::Sub:  // X - 0 = X
2866     case Instruction::Shl:  // X << 0 = X
2867     case Instruction::LShr: // X >>u 0 = X
2868     case Instruction::AShr: // X >> 0 = X
2869     case Instruction::FSub: // X - 0.0 = X
2870       return Constant::getNullValue(Ty);
2871     case Instruction::SDiv: // X / 1 = X
2872     case Instruction::UDiv: // X /u 1 = X
2873       return ConstantInt::get(Ty, 1);
2874     case Instruction::FDiv: // X / 1.0 = X
2875       return ConstantFP::get(Ty, 1.0);
2876     default:
2877       return nullptr;
2878   }
2879 }
2880 
2881 Constant *ConstantExpr::getBinOpAbsorber(unsigned Opcode, Type *Ty) {
2882   switch (Opcode) {
2883   default:
2884     // Doesn't have an absorber.
2885     return nullptr;
2886 
2887   case Instruction::Or:
2888     return Constant::getAllOnesValue(Ty);
2889 
2890   case Instruction::And:
2891   case Instruction::Mul:
2892     return Constant::getNullValue(Ty);
2893   }
2894 }
2895 
2896 /// Remove the constant from the constant table.
2897 void ConstantExpr::destroyConstantImpl() {
2898   getType()->getContext().pImpl->ExprConstants.remove(this);
2899 }
2900 
2901 const char *ConstantExpr::getOpcodeName() const {
2902   return Instruction::getOpcodeName(getOpcode());
2903 }
2904 
2905 GetElementPtrConstantExpr::GetElementPtrConstantExpr(
2906     Type *SrcElementTy, Constant *C, ArrayRef<Constant *> IdxList, Type *DestTy)
2907     : ConstantExpr(DestTy, Instruction::GetElementPtr,
2908                    OperandTraits<GetElementPtrConstantExpr>::op_end(this) -
2909                        (IdxList.size() + 1),
2910                    IdxList.size() + 1),
2911       SrcElementTy(SrcElementTy),
2912       ResElementTy(GetElementPtrInst::getIndexedType(SrcElementTy, IdxList)) {
2913   Op<0>() = C;
2914   Use *OperandList = getOperandList();
2915   for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
2916     OperandList[i+1] = IdxList[i];
2917 }
2918 
2919 Type *GetElementPtrConstantExpr::getSourceElementType() const {
2920   return SrcElementTy;
2921 }
2922 
2923 Type *GetElementPtrConstantExpr::getResultElementType() const {
2924   return ResElementTy;
2925 }
2926 
2927 //===----------------------------------------------------------------------===//
2928 //                       ConstantData* implementations
2929 
2930 Type *ConstantDataSequential::getElementType() const {
2931   if (ArrayType *ATy = dyn_cast<ArrayType>(getType()))
2932     return ATy->getElementType();
2933   return cast<VectorType>(getType())->getElementType();
2934 }
2935 
2936 StringRef ConstantDataSequential::getRawDataValues() const {
2937   return StringRef(DataElements, getNumElements()*getElementByteSize());
2938 }
2939 
2940 bool ConstantDataSequential::isElementTypeCompatible(Type *Ty) {
2941   if (Ty->isHalfTy() || Ty->isBFloatTy() || Ty->isFloatTy() || Ty->isDoubleTy())
2942     return true;
2943   if (auto *IT = dyn_cast<IntegerType>(Ty)) {
2944     switch (IT->getBitWidth()) {
2945     case 8:
2946     case 16:
2947     case 32:
2948     case 64:
2949       return true;
2950     default: break;
2951     }
2952   }
2953   return false;
2954 }
2955 
2956 unsigned ConstantDataSequential::getNumElements() const {
2957   if (ArrayType *AT = dyn_cast<ArrayType>(getType()))
2958     return AT->getNumElements();
2959   return cast<FixedVectorType>(getType())->getNumElements();
2960 }
2961 
2962 
2963 uint64_t ConstantDataSequential::getElementByteSize() const {
2964   return getElementType()->getPrimitiveSizeInBits()/8;
2965 }
2966 
2967 /// Return the start of the specified element.
2968 const char *ConstantDataSequential::getElementPointer(unsigned Elt) const {
2969   assert(Elt < getNumElements() && "Invalid Elt");
2970   return DataElements+Elt*getElementByteSize();
2971 }
2972 
2973 
2974 /// Return true if the array is empty or all zeros.
2975 static bool isAllZeros(StringRef Arr) {
2976   for (char I : Arr)
2977     if (I != 0)
2978       return false;
2979   return true;
2980 }
2981 
2982 /// This is the underlying implementation of all of the
2983 /// ConstantDataSequential::get methods.  They all thunk down to here, providing
2984 /// the correct element type.  We take the bytes in as a StringRef because
2985 /// we *want* an underlying "char*" to avoid TBAA type punning violations.
2986 Constant *ConstantDataSequential::getImpl(StringRef Elements, Type *Ty) {
2987 #ifndef NDEBUG
2988   if (ArrayType *ATy = dyn_cast<ArrayType>(Ty))
2989     assert(isElementTypeCompatible(ATy->getElementType()));
2990   else
2991     assert(isElementTypeCompatible(cast<VectorType>(Ty)->getElementType()));
2992 #endif
2993   // If the elements are all zero or there are no elements, return a CAZ, which
2994   // is more dense and canonical.
2995   if (isAllZeros(Elements))
2996     return ConstantAggregateZero::get(Ty);
2997 
2998   // Do a lookup to see if we have already formed one of these.
2999   auto &Slot =
3000       *Ty->getContext()
3001            .pImpl->CDSConstants.insert(std::make_pair(Elements, nullptr))
3002            .first;
3003 
3004   // The bucket can point to a linked list of different CDS's that have the same
3005   // body but different types.  For example, 0,0,0,1 could be a 4 element array
3006   // of i8, or a 1-element array of i32.  They'll both end up in the same
3007   /// StringMap bucket, linked up by their Next pointers.  Walk the list.
3008   std::unique_ptr<ConstantDataSequential> *Entry = &Slot.second;
3009   for (; *Entry; Entry = &(*Entry)->Next)
3010     if ((*Entry)->getType() == Ty)
3011       return Entry->get();
3012 
3013   // Okay, we didn't get a hit.  Create a node of the right class, link it in,
3014   // and return it.
3015   if (isa<ArrayType>(Ty)) {
3016     // Use reset because std::make_unique can't access the constructor.
3017     Entry->reset(new ConstantDataArray(Ty, Slot.first().data()));
3018     return Entry->get();
3019   }
3020 
3021   assert(isa<VectorType>(Ty));
3022   // Use reset because std::make_unique can't access the constructor.
3023   Entry->reset(new ConstantDataVector(Ty, Slot.first().data()));
3024   return Entry->get();
3025 }
3026 
3027 void ConstantDataSequential::destroyConstantImpl() {
3028   // Remove the constant from the StringMap.
3029   StringMap<std::unique_ptr<ConstantDataSequential>> &CDSConstants =
3030       getType()->getContext().pImpl->CDSConstants;
3031 
3032   auto Slot = CDSConstants.find(getRawDataValues());
3033 
3034   assert(Slot != CDSConstants.end() && "CDS not found in uniquing table");
3035 
3036   std::unique_ptr<ConstantDataSequential> *Entry = &Slot->getValue();
3037 
3038   // Remove the entry from the hash table.
3039   if (!(*Entry)->Next) {
3040     // If there is only one value in the bucket (common case) it must be this
3041     // entry, and removing the entry should remove the bucket completely.
3042     assert(Entry->get() == this && "Hash mismatch in ConstantDataSequential");
3043     getContext().pImpl->CDSConstants.erase(Slot);
3044     return;
3045   }
3046 
3047   // Otherwise, there are multiple entries linked off the bucket, unlink the
3048   // node we care about but keep the bucket around.
3049   while (true) {
3050     std::unique_ptr<ConstantDataSequential> &Node = *Entry;
3051     assert(Node && "Didn't find entry in its uniquing hash table!");
3052     // If we found our entry, unlink it from the list and we're done.
3053     if (Node.get() == this) {
3054       Node = std::move(Node->Next);
3055       return;
3056     }
3057 
3058     Entry = &Node->Next;
3059   }
3060 }
3061 
3062 /// getFP() constructors - Return a constant of array type with a float
3063 /// element type taken from argument `ElementType', and count taken from
3064 /// argument `Elts'.  The amount of bits of the contained type must match the
3065 /// number of bits of the type contained in the passed in ArrayRef.
3066 /// (i.e. half or bfloat for 16bits, float for 32bits, double for 64bits) Note
3067 /// that this can return a ConstantAggregateZero object.
3068 Constant *ConstantDataArray::getFP(Type *ElementType, ArrayRef<uint16_t> Elts) {
3069   assert((ElementType->isHalfTy() || ElementType->isBFloatTy()) &&
3070          "Element type is not a 16-bit float type");
3071   Type *Ty = ArrayType::get(ElementType, Elts.size());
3072   const char *Data = reinterpret_cast<const char *>(Elts.data());
3073   return getImpl(StringRef(Data, Elts.size() * 2), Ty);
3074 }
3075 Constant *ConstantDataArray::getFP(Type *ElementType, ArrayRef<uint32_t> Elts) {
3076   assert(ElementType->isFloatTy() && "Element type is not a 32-bit float type");
3077   Type *Ty = ArrayType::get(ElementType, Elts.size());
3078   const char *Data = reinterpret_cast<const char *>(Elts.data());
3079   return getImpl(StringRef(Data, Elts.size() * 4), Ty);
3080 }
3081 Constant *ConstantDataArray::getFP(Type *ElementType, ArrayRef<uint64_t> Elts) {
3082   assert(ElementType->isDoubleTy() &&
3083          "Element type is not a 64-bit float type");
3084   Type *Ty = ArrayType::get(ElementType, Elts.size());
3085   const char *Data = reinterpret_cast<const char *>(Elts.data());
3086   return getImpl(StringRef(Data, Elts.size() * 8), Ty);
3087 }
3088 
3089 Constant *ConstantDataArray::getString(LLVMContext &Context,
3090                                        StringRef Str, bool AddNull) {
3091   if (!AddNull) {
3092     const uint8_t *Data = Str.bytes_begin();
3093     return get(Context, makeArrayRef(Data, Str.size()));
3094   }
3095 
3096   SmallVector<uint8_t, 64> ElementVals;
3097   ElementVals.append(Str.begin(), Str.end());
3098   ElementVals.push_back(0);
3099   return get(Context, ElementVals);
3100 }
3101 
3102 /// get() constructors - Return a constant with vector type with an element
3103 /// count and element type matching the ArrayRef passed in.  Note that this
3104 /// can return a ConstantAggregateZero object.
3105 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint8_t> Elts){
3106   auto *Ty = FixedVectorType::get(Type::getInt8Ty(Context), Elts.size());
3107   const char *Data = reinterpret_cast<const char *>(Elts.data());
3108   return getImpl(StringRef(Data, Elts.size() * 1), Ty);
3109 }
3110 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint16_t> Elts){
3111   auto *Ty = FixedVectorType::get(Type::getInt16Ty(Context), Elts.size());
3112   const char *Data = reinterpret_cast<const char *>(Elts.data());
3113   return getImpl(StringRef(Data, Elts.size() * 2), Ty);
3114 }
3115 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint32_t> Elts){
3116   auto *Ty = FixedVectorType::get(Type::getInt32Ty(Context), Elts.size());
3117   const char *Data = reinterpret_cast<const char *>(Elts.data());
3118   return getImpl(StringRef(Data, Elts.size() * 4), Ty);
3119 }
3120 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint64_t> Elts){
3121   auto *Ty = FixedVectorType::get(Type::getInt64Ty(Context), Elts.size());
3122   const char *Data = reinterpret_cast<const char *>(Elts.data());
3123   return getImpl(StringRef(Data, Elts.size() * 8), Ty);
3124 }
3125 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<float> Elts) {
3126   auto *Ty = FixedVectorType::get(Type::getFloatTy(Context), Elts.size());
3127   const char *Data = reinterpret_cast<const char *>(Elts.data());
3128   return getImpl(StringRef(Data, Elts.size() * 4), Ty);
3129 }
3130 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<double> Elts) {
3131   auto *Ty = FixedVectorType::get(Type::getDoubleTy(Context), Elts.size());
3132   const char *Data = reinterpret_cast<const char *>(Elts.data());
3133   return getImpl(StringRef(Data, Elts.size() * 8), Ty);
3134 }
3135 
3136 /// getFP() constructors - Return a constant of vector type with a float
3137 /// element type taken from argument `ElementType', and count taken from
3138 /// argument `Elts'.  The amount of bits of the contained type must match the
3139 /// number of bits of the type contained in the passed in ArrayRef.
3140 /// (i.e. half or bfloat for 16bits, float for 32bits, double for 64bits) Note
3141 /// that this can return a ConstantAggregateZero object.
3142 Constant *ConstantDataVector::getFP(Type *ElementType,
3143                                     ArrayRef<uint16_t> Elts) {
3144   assert((ElementType->isHalfTy() || ElementType->isBFloatTy()) &&
3145          "Element type is not a 16-bit float type");
3146   auto *Ty = FixedVectorType::get(ElementType, Elts.size());
3147   const char *Data = reinterpret_cast<const char *>(Elts.data());
3148   return getImpl(StringRef(Data, Elts.size() * 2), Ty);
3149 }
3150 Constant *ConstantDataVector::getFP(Type *ElementType,
3151                                     ArrayRef<uint32_t> Elts) {
3152   assert(ElementType->isFloatTy() && "Element type is not a 32-bit float type");
3153   auto *Ty = FixedVectorType::get(ElementType, Elts.size());
3154   const char *Data = reinterpret_cast<const char *>(Elts.data());
3155   return getImpl(StringRef(Data, Elts.size() * 4), Ty);
3156 }
3157 Constant *ConstantDataVector::getFP(Type *ElementType,
3158                                     ArrayRef<uint64_t> Elts) {
3159   assert(ElementType->isDoubleTy() &&
3160          "Element type is not a 64-bit float type");
3161   auto *Ty = FixedVectorType::get(ElementType, Elts.size());
3162   const char *Data = reinterpret_cast<const char *>(Elts.data());
3163   return getImpl(StringRef(Data, Elts.size() * 8), Ty);
3164 }
3165 
3166 Constant *ConstantDataVector::getSplat(unsigned NumElts, Constant *V) {
3167   assert(isElementTypeCompatible(V->getType()) &&
3168          "Element type not compatible with ConstantData");
3169   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
3170     if (CI->getType()->isIntegerTy(8)) {
3171       SmallVector<uint8_t, 16> Elts(NumElts, CI->getZExtValue());
3172       return get(V->getContext(), Elts);
3173     }
3174     if (CI->getType()->isIntegerTy(16)) {
3175       SmallVector<uint16_t, 16> Elts(NumElts, CI->getZExtValue());
3176       return get(V->getContext(), Elts);
3177     }
3178     if (CI->getType()->isIntegerTy(32)) {
3179       SmallVector<uint32_t, 16> Elts(NumElts, CI->getZExtValue());
3180       return get(V->getContext(), Elts);
3181     }
3182     assert(CI->getType()->isIntegerTy(64) && "Unsupported ConstantData type");
3183     SmallVector<uint64_t, 16> Elts(NumElts, CI->getZExtValue());
3184     return get(V->getContext(), Elts);
3185   }
3186 
3187   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
3188     if (CFP->getType()->isHalfTy()) {
3189       SmallVector<uint16_t, 16> Elts(
3190           NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
3191       return getFP(V->getType(), Elts);
3192     }
3193     if (CFP->getType()->isBFloatTy()) {
3194       SmallVector<uint16_t, 16> Elts(
3195           NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
3196       return getFP(V->getType(), Elts);
3197     }
3198     if (CFP->getType()->isFloatTy()) {
3199       SmallVector<uint32_t, 16> Elts(
3200           NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
3201       return getFP(V->getType(), Elts);
3202     }
3203     if (CFP->getType()->isDoubleTy()) {
3204       SmallVector<uint64_t, 16> Elts(
3205           NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
3206       return getFP(V->getType(), Elts);
3207     }
3208   }
3209   return ConstantVector::getSplat(ElementCount::getFixed(NumElts), V);
3210 }
3211 
3212 
3213 uint64_t ConstantDataSequential::getElementAsInteger(unsigned Elt) const {
3214   assert(isa<IntegerType>(getElementType()) &&
3215          "Accessor can only be used when element is an integer");
3216   const char *EltPtr = getElementPointer(Elt);
3217 
3218   // The data is stored in host byte order, make sure to cast back to the right
3219   // type to load with the right endianness.
3220   switch (getElementType()->getIntegerBitWidth()) {
3221   default: llvm_unreachable("Invalid bitwidth for CDS");
3222   case 8:
3223     return *reinterpret_cast<const uint8_t *>(EltPtr);
3224   case 16:
3225     return *reinterpret_cast<const uint16_t *>(EltPtr);
3226   case 32:
3227     return *reinterpret_cast<const uint32_t *>(EltPtr);
3228   case 64:
3229     return *reinterpret_cast<const uint64_t *>(EltPtr);
3230   }
3231 }
3232 
3233 APInt ConstantDataSequential::getElementAsAPInt(unsigned Elt) const {
3234   assert(isa<IntegerType>(getElementType()) &&
3235          "Accessor can only be used when element is an integer");
3236   const char *EltPtr = getElementPointer(Elt);
3237 
3238   // The data is stored in host byte order, make sure to cast back to the right
3239   // type to load with the right endianness.
3240   switch (getElementType()->getIntegerBitWidth()) {
3241   default: llvm_unreachable("Invalid bitwidth for CDS");
3242   case 8: {
3243     auto EltVal = *reinterpret_cast<const uint8_t *>(EltPtr);
3244     return APInt(8, EltVal);
3245   }
3246   case 16: {
3247     auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
3248     return APInt(16, EltVal);
3249   }
3250   case 32: {
3251     auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr);
3252     return APInt(32, EltVal);
3253   }
3254   case 64: {
3255     auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr);
3256     return APInt(64, EltVal);
3257   }
3258   }
3259 }
3260 
3261 APFloat ConstantDataSequential::getElementAsAPFloat(unsigned Elt) const {
3262   const char *EltPtr = getElementPointer(Elt);
3263 
3264   switch (getElementType()->getTypeID()) {
3265   default:
3266     llvm_unreachable("Accessor can only be used when element is float/double!");
3267   case Type::HalfTyID: {
3268     auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
3269     return APFloat(APFloat::IEEEhalf(), APInt(16, EltVal));
3270   }
3271   case Type::BFloatTyID: {
3272     auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
3273     return APFloat(APFloat::BFloat(), APInt(16, EltVal));
3274   }
3275   case Type::FloatTyID: {
3276     auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr);
3277     return APFloat(APFloat::IEEEsingle(), APInt(32, EltVal));
3278   }
3279   case Type::DoubleTyID: {
3280     auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr);
3281     return APFloat(APFloat::IEEEdouble(), APInt(64, EltVal));
3282   }
3283   }
3284 }
3285 
3286 float ConstantDataSequential::getElementAsFloat(unsigned Elt) const {
3287   assert(getElementType()->isFloatTy() &&
3288          "Accessor can only be used when element is a 'float'");
3289   return *reinterpret_cast<const float *>(getElementPointer(Elt));
3290 }
3291 
3292 double ConstantDataSequential::getElementAsDouble(unsigned Elt) const {
3293   assert(getElementType()->isDoubleTy() &&
3294          "Accessor can only be used when element is a 'float'");
3295   return *reinterpret_cast<const double *>(getElementPointer(Elt));
3296 }
3297 
3298 Constant *ConstantDataSequential::getElementAsConstant(unsigned Elt) const {
3299   if (getElementType()->isHalfTy() || getElementType()->isBFloatTy() ||
3300       getElementType()->isFloatTy() || getElementType()->isDoubleTy())
3301     return ConstantFP::get(getContext(), getElementAsAPFloat(Elt));
3302 
3303   return ConstantInt::get(getElementType(), getElementAsInteger(Elt));
3304 }
3305 
3306 bool ConstantDataSequential::isString(unsigned CharSize) const {
3307   return isa<ArrayType>(getType()) && getElementType()->isIntegerTy(CharSize);
3308 }
3309 
3310 bool ConstantDataSequential::isCString() const {
3311   if (!isString())
3312     return false;
3313 
3314   StringRef Str = getAsString();
3315 
3316   // The last value must be nul.
3317   if (Str.back() != 0) return false;
3318 
3319   // Other elements must be non-nul.
3320   return !Str.drop_back().contains(0);
3321 }
3322 
3323 bool ConstantDataVector::isSplatData() const {
3324   const char *Base = getRawDataValues().data();
3325 
3326   // Compare elements 1+ to the 0'th element.
3327   unsigned EltSize = getElementByteSize();
3328   for (unsigned i = 1, e = getNumElements(); i != e; ++i)
3329     if (memcmp(Base, Base+i*EltSize, EltSize))
3330       return false;
3331 
3332   return true;
3333 }
3334 
3335 bool ConstantDataVector::isSplat() const {
3336   if (!IsSplatSet) {
3337     IsSplatSet = true;
3338     IsSplat = isSplatData();
3339   }
3340   return IsSplat;
3341 }
3342 
3343 Constant *ConstantDataVector::getSplatValue() const {
3344   // If they're all the same, return the 0th one as a representative.
3345   return isSplat() ? getElementAsConstant(0) : nullptr;
3346 }
3347 
3348 //===----------------------------------------------------------------------===//
3349 //                handleOperandChange implementations
3350 
3351 /// Update this constant array to change uses of
3352 /// 'From' to be uses of 'To'.  This must update the uniquing data structures
3353 /// etc.
3354 ///
3355 /// Note that we intentionally replace all uses of From with To here.  Consider
3356 /// a large array that uses 'From' 1000 times.  By handling this case all here,
3357 /// ConstantArray::handleOperandChange is only invoked once, and that
3358 /// single invocation handles all 1000 uses.  Handling them one at a time would
3359 /// work, but would be really slow because it would have to unique each updated
3360 /// array instance.
3361 ///
3362 void Constant::handleOperandChange(Value *From, Value *To) {
3363   Value *Replacement = nullptr;
3364   switch (getValueID()) {
3365   default:
3366     llvm_unreachable("Not a constant!");
3367 #define HANDLE_CONSTANT(Name)                                                  \
3368   case Value::Name##Val:                                                       \
3369     Replacement = cast<Name>(this)->handleOperandChangeImpl(From, To);         \
3370     break;
3371 #include "llvm/IR/Value.def"
3372   }
3373 
3374   // If handleOperandChangeImpl returned nullptr, then it handled
3375   // replacing itself and we don't want to delete or replace anything else here.
3376   if (!Replacement)
3377     return;
3378 
3379   // I do need to replace this with an existing value.
3380   assert(Replacement != this && "I didn't contain From!");
3381 
3382   // Everyone using this now uses the replacement.
3383   replaceAllUsesWith(Replacement);
3384 
3385   // Delete the old constant!
3386   destroyConstant();
3387 }
3388 
3389 Value *ConstantArray::handleOperandChangeImpl(Value *From, Value *To) {
3390   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
3391   Constant *ToC = cast<Constant>(To);
3392 
3393   SmallVector<Constant*, 8> Values;
3394   Values.reserve(getNumOperands());  // Build replacement array.
3395 
3396   // Fill values with the modified operands of the constant array.  Also,
3397   // compute whether this turns into an all-zeros array.
3398   unsigned NumUpdated = 0;
3399 
3400   // Keep track of whether all the values in the array are "ToC".
3401   bool AllSame = true;
3402   Use *OperandList = getOperandList();
3403   unsigned OperandNo = 0;
3404   for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
3405     Constant *Val = cast<Constant>(O->get());
3406     if (Val == From) {
3407       OperandNo = (O - OperandList);
3408       Val = ToC;
3409       ++NumUpdated;
3410     }
3411     Values.push_back(Val);
3412     AllSame &= Val == ToC;
3413   }
3414 
3415   if (AllSame && ToC->isNullValue())
3416     return ConstantAggregateZero::get(getType());
3417 
3418   if (AllSame && isa<UndefValue>(ToC))
3419     return UndefValue::get(getType());
3420 
3421   // Check for any other type of constant-folding.
3422   if (Constant *C = getImpl(getType(), Values))
3423     return C;
3424 
3425   // Update to the new value.
3426   return getContext().pImpl->ArrayConstants.replaceOperandsInPlace(
3427       Values, this, From, ToC, NumUpdated, OperandNo);
3428 }
3429 
3430 Value *ConstantStruct::handleOperandChangeImpl(Value *From, Value *To) {
3431   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
3432   Constant *ToC = cast<Constant>(To);
3433 
3434   Use *OperandList = getOperandList();
3435 
3436   SmallVector<Constant*, 8> Values;
3437   Values.reserve(getNumOperands());  // Build replacement struct.
3438 
3439   // Fill values with the modified operands of the constant struct.  Also,
3440   // compute whether this turns into an all-zeros struct.
3441   unsigned NumUpdated = 0;
3442   bool AllSame = true;
3443   unsigned OperandNo = 0;
3444   for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O) {
3445     Constant *Val = cast<Constant>(O->get());
3446     if (Val == From) {
3447       OperandNo = (O - OperandList);
3448       Val = ToC;
3449       ++NumUpdated;
3450     }
3451     Values.push_back(Val);
3452     AllSame &= Val == ToC;
3453   }
3454 
3455   if (AllSame && ToC->isNullValue())
3456     return ConstantAggregateZero::get(getType());
3457 
3458   if (AllSame && isa<UndefValue>(ToC))
3459     return UndefValue::get(getType());
3460 
3461   // Update to the new value.
3462   return getContext().pImpl->StructConstants.replaceOperandsInPlace(
3463       Values, this, From, ToC, NumUpdated, OperandNo);
3464 }
3465 
3466 Value *ConstantVector::handleOperandChangeImpl(Value *From, Value *To) {
3467   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
3468   Constant *ToC = cast<Constant>(To);
3469 
3470   SmallVector<Constant*, 8> Values;
3471   Values.reserve(getNumOperands());  // Build replacement array...
3472   unsigned NumUpdated = 0;
3473   unsigned OperandNo = 0;
3474   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
3475     Constant *Val = getOperand(i);
3476     if (Val == From) {
3477       OperandNo = i;
3478       ++NumUpdated;
3479       Val = ToC;
3480     }
3481     Values.push_back(Val);
3482   }
3483 
3484   if (Constant *C = getImpl(Values))
3485     return C;
3486 
3487   // Update to the new value.
3488   return getContext().pImpl->VectorConstants.replaceOperandsInPlace(
3489       Values, this, From, ToC, NumUpdated, OperandNo);
3490 }
3491 
3492 Value *ConstantExpr::handleOperandChangeImpl(Value *From, Value *ToV) {
3493   assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
3494   Constant *To = cast<Constant>(ToV);
3495 
3496   SmallVector<Constant*, 8> NewOps;
3497   unsigned NumUpdated = 0;
3498   unsigned OperandNo = 0;
3499   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
3500     Constant *Op = getOperand(i);
3501     if (Op == From) {
3502       OperandNo = i;
3503       ++NumUpdated;
3504       Op = To;
3505     }
3506     NewOps.push_back(Op);
3507   }
3508   assert(NumUpdated && "I didn't contain From!");
3509 
3510   if (Constant *C = getWithOperands(NewOps, getType(), true))
3511     return C;
3512 
3513   // Update to the new value.
3514   return getContext().pImpl->ExprConstants.replaceOperandsInPlace(
3515       NewOps, this, From, To, NumUpdated, OperandNo);
3516 }
3517 
3518 Instruction *ConstantExpr::getAsInstruction(Instruction *InsertBefore) const {
3519   SmallVector<Value *, 4> ValueOperands(operands());
3520   ArrayRef<Value*> Ops(ValueOperands);
3521 
3522   switch (getOpcode()) {
3523   case Instruction::Trunc:
3524   case Instruction::ZExt:
3525   case Instruction::SExt:
3526   case Instruction::FPTrunc:
3527   case Instruction::FPExt:
3528   case Instruction::UIToFP:
3529   case Instruction::SIToFP:
3530   case Instruction::FPToUI:
3531   case Instruction::FPToSI:
3532   case Instruction::PtrToInt:
3533   case Instruction::IntToPtr:
3534   case Instruction::BitCast:
3535   case Instruction::AddrSpaceCast:
3536     return CastInst::Create((Instruction::CastOps)getOpcode(), Ops[0],
3537                             getType(), "", InsertBefore);
3538   case Instruction::Select:
3539     return SelectInst::Create(Ops[0], Ops[1], Ops[2], "", InsertBefore);
3540   case Instruction::InsertElement:
3541     return InsertElementInst::Create(Ops[0], Ops[1], Ops[2], "", InsertBefore);
3542   case Instruction::ExtractElement:
3543     return ExtractElementInst::Create(Ops[0], Ops[1], "", InsertBefore);
3544   case Instruction::InsertValue:
3545     return InsertValueInst::Create(Ops[0], Ops[1], getIndices(), "",
3546                                    InsertBefore);
3547   case Instruction::ExtractValue:
3548     return ExtractValueInst::Create(Ops[0], getIndices(), "", InsertBefore);
3549   case Instruction::ShuffleVector:
3550     return new ShuffleVectorInst(Ops[0], Ops[1], getShuffleMask(), "",
3551                                  InsertBefore);
3552 
3553   case Instruction::GetElementPtr: {
3554     const auto *GO = cast<GEPOperator>(this);
3555     if (GO->isInBounds())
3556       return GetElementPtrInst::CreateInBounds(
3557           GO->getSourceElementType(), Ops[0], Ops.slice(1), "", InsertBefore);
3558     return GetElementPtrInst::Create(GO->getSourceElementType(), Ops[0],
3559                                      Ops.slice(1), "", InsertBefore);
3560   }
3561   case Instruction::ICmp:
3562   case Instruction::FCmp:
3563     return CmpInst::Create((Instruction::OtherOps)getOpcode(),
3564                            (CmpInst::Predicate)getPredicate(), Ops[0], Ops[1],
3565                            "", InsertBefore);
3566   case Instruction::FNeg:
3567     return UnaryOperator::Create((Instruction::UnaryOps)getOpcode(), Ops[0], "",
3568                                  InsertBefore);
3569   default:
3570     assert(getNumOperands() == 2 && "Must be binary operator?");
3571     BinaryOperator *BO = BinaryOperator::Create(
3572         (Instruction::BinaryOps)getOpcode(), Ops[0], Ops[1], "", InsertBefore);
3573     if (isa<OverflowingBinaryOperator>(BO)) {
3574       BO->setHasNoUnsignedWrap(SubclassOptionalData &
3575                                OverflowingBinaryOperator::NoUnsignedWrap);
3576       BO->setHasNoSignedWrap(SubclassOptionalData &
3577                              OverflowingBinaryOperator::NoSignedWrap);
3578     }
3579     if (isa<PossiblyExactOperator>(BO))
3580       BO->setIsExact(SubclassOptionalData & PossiblyExactOperator::IsExact);
3581     return BO;
3582   }
3583 }
3584