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