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