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