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