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