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