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