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