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