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