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