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