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