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