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