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