1249259Sdim//===-- Constants.cpp - Implement Constant nodes --------------------------===//
2249259Sdim//
3249259Sdim//                     The LLVM Compiler Infrastructure
4249259Sdim//
5249259Sdim// This file is distributed under the University of Illinois Open Source
6249259Sdim// License. See LICENSE.TXT for details.
7249259Sdim//
8249259Sdim//===----------------------------------------------------------------------===//
9249259Sdim//
10249259Sdim// This file implements the Constant* classes.
11249259Sdim//
12249259Sdim//===----------------------------------------------------------------------===//
13249259Sdim
14249259Sdim#include "llvm/IR/Constants.h"
15249259Sdim#include "ConstantFold.h"
16249259Sdim#include "LLVMContextImpl.h"
17249259Sdim#include "llvm/ADT/DenseMap.h"
18249259Sdim#include "llvm/ADT/FoldingSet.h"
19249259Sdim#include "llvm/ADT/STLExtras.h"
20249259Sdim#include "llvm/ADT/SmallVector.h"
21249259Sdim#include "llvm/ADT/StringExtras.h"
22249259Sdim#include "llvm/ADT/StringMap.h"
23249259Sdim#include "llvm/IR/DerivedTypes.h"
24276479Sdim#include "llvm/IR/GetElementPtrTypeIterator.h"
25249259Sdim#include "llvm/IR/GlobalValue.h"
26249259Sdim#include "llvm/IR/Instructions.h"
27249259Sdim#include "llvm/IR/Module.h"
28249259Sdim#include "llvm/IR/Operator.h"
29249259Sdim#include "llvm/Support/Compiler.h"
30249259Sdim#include "llvm/Support/Debug.h"
31249259Sdim#include "llvm/Support/ErrorHandling.h"
32249259Sdim#include "llvm/Support/ManagedStatic.h"
33249259Sdim#include "llvm/Support/MathExtras.h"
34249259Sdim#include "llvm/Support/raw_ostream.h"
35249259Sdim#include <algorithm>
36249259Sdim#include <cstdarg>
37249259Sdimusing namespace llvm;
38249259Sdim
39249259Sdim//===----------------------------------------------------------------------===//
40249259Sdim//                              Constant Class
41249259Sdim//===----------------------------------------------------------------------===//
42249259Sdim
43249259Sdimvoid Constant::anchor() { }
44249259Sdim
45249259Sdimbool Constant::isNegativeZeroValue() const {
46249259Sdim  // Floating point values have an explicit -0.0 value.
47249259Sdim  if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
48249259Sdim    return CFP->isZero() && CFP->isNegative();
49249259Sdim
50249259Sdim  // Equivalent for a vector of -0.0's.
51249259Sdim  if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
52249259Sdim    if (ConstantFP *SplatCFP = dyn_cast_or_null<ConstantFP>(CV->getSplatValue()))
53249259Sdim      if (SplatCFP && SplatCFP->isZero() && SplatCFP->isNegative())
54249259Sdim        return true;
55249259Sdim
56296417Sdim  if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
57296417Sdim    if (ConstantFP *SplatCFP = dyn_cast_or_null<ConstantFP>(CV->getSplatValue()))
58296417Sdim      if (SplatCFP && SplatCFP->isZero() && SplatCFP->isNegative())
59296417Sdim        return true;
60296417Sdim
61249259Sdim  // We've already handled true FP case; any other FP vectors can't represent -0.0.
62249259Sdim  if (getType()->isFPOrFPVectorTy())
63249259Sdim    return false;
64249259Sdim
65249259Sdim  // Otherwise, just use +0.0.
66249259Sdim  return isNullValue();
67249259Sdim}
68249259Sdim
69249259Sdim// Return true iff this constant is positive zero (floating point), negative
70249259Sdim// zero (floating point), or a null value.
71249259Sdimbool Constant::isZeroValue() const {
72249259Sdim  // Floating point values have an explicit -0.0 value.
73249259Sdim  if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
74249259Sdim    return CFP->isZero();
75249259Sdim
76296417Sdim  // Equivalent for a vector of -0.0's.
77296417Sdim  if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
78296417Sdim    if (ConstantFP *SplatCFP = dyn_cast_or_null<ConstantFP>(CV->getSplatValue()))
79296417Sdim      if (SplatCFP && SplatCFP->isZero())
80296417Sdim        return true;
81296417Sdim
82296417Sdim  if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
83296417Sdim    if (ConstantFP *SplatCFP = dyn_cast_or_null<ConstantFP>(CV->getSplatValue()))
84296417Sdim      if (SplatCFP && SplatCFP->isZero())
85296417Sdim        return true;
86296417Sdim
87249259Sdim  // Otherwise, just use +0.0.
88249259Sdim  return isNullValue();
89249259Sdim}
90249259Sdim
91249259Sdimbool Constant::isNullValue() const {
92249259Sdim  // 0 is null.
93249259Sdim  if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
94249259Sdim    return CI->isZero();
95249259Sdim
96249259Sdim  // +0.0 is null.
97249259Sdim  if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
98249259Sdim    return CFP->isZero() && !CFP->isNegative();
99249259Sdim
100296417Sdim  // constant zero is zero for aggregates, cpnull is null for pointers, none for
101296417Sdim  // tokens.
102296417Sdim  return isa<ConstantAggregateZero>(this) || isa<ConstantPointerNull>(this) ||
103296417Sdim         isa<ConstantTokenNone>(this);
104249259Sdim}
105249259Sdim
106249259Sdimbool Constant::isAllOnesValue() const {
107249259Sdim  // Check for -1 integers
108249259Sdim  if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
109249259Sdim    return CI->isMinusOne();
110249259Sdim
111249259Sdim  // Check for FP which are bitcasted from -1 integers
112249259Sdim  if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
113249259Sdim    return CFP->getValueAPF().bitcastToAPInt().isAllOnesValue();
114249259Sdim
115249259Sdim  // Check for constant vectors which are splats of -1 values.
116249259Sdim  if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
117249259Sdim    if (Constant *Splat = CV->getSplatValue())
118249259Sdim      return Splat->isAllOnesValue();
119249259Sdim
120249259Sdim  // Check for constant vectors which are splats of -1 values.
121249259Sdim  if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
122249259Sdim    if (Constant *Splat = CV->getSplatValue())
123249259Sdim      return Splat->isAllOnesValue();
124249259Sdim
125249259Sdim  return false;
126249259Sdim}
127249259Sdim
128280031Sdimbool Constant::isOneValue() const {
129280031Sdim  // Check for 1 integers
130280031Sdim  if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
131280031Sdim    return CI->isOne();
132280031Sdim
133280031Sdim  // Check for FP which are bitcasted from 1 integers
134280031Sdim  if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
135280031Sdim    return CFP->getValueAPF().bitcastToAPInt() == 1;
136280031Sdim
137280031Sdim  // Check for constant vectors which are splats of 1 values.
138280031Sdim  if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
139280031Sdim    if (Constant *Splat = CV->getSplatValue())
140280031Sdim      return Splat->isOneValue();
141280031Sdim
142280031Sdim  // Check for constant vectors which are splats of 1 values.
143280031Sdim  if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
144280031Sdim    if (Constant *Splat = CV->getSplatValue())
145280031Sdim      return Splat->isOneValue();
146280031Sdim
147280031Sdim  return false;
148280031Sdim}
149280031Sdim
150276479Sdimbool Constant::isMinSignedValue() const {
151276479Sdim  // Check for INT_MIN integers
152276479Sdim  if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
153276479Sdim    return CI->isMinValue(/*isSigned=*/true);
154276479Sdim
155276479Sdim  // Check for FP which are bitcasted from INT_MIN integers
156276479Sdim  if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
157276479Sdim    return CFP->getValueAPF().bitcastToAPInt().isMinSignedValue();
158276479Sdim
159276479Sdim  // Check for constant vectors which are splats of INT_MIN values.
160276479Sdim  if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
161276479Sdim    if (Constant *Splat = CV->getSplatValue())
162276479Sdim      return Splat->isMinSignedValue();
163276479Sdim
164276479Sdim  // Check for constant vectors which are splats of INT_MIN values.
165276479Sdim  if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
166276479Sdim    if (Constant *Splat = CV->getSplatValue())
167276479Sdim      return Splat->isMinSignedValue();
168276479Sdim
169276479Sdim  return false;
170276479Sdim}
171276479Sdim
172280031Sdimbool Constant::isNotMinSignedValue() const {
173280031Sdim  // Check for INT_MIN integers
174280031Sdim  if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
175280031Sdim    return !CI->isMinValue(/*isSigned=*/true);
176280031Sdim
177280031Sdim  // Check for FP which are bitcasted from INT_MIN integers
178280031Sdim  if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
179280031Sdim    return !CFP->getValueAPF().bitcastToAPInt().isMinSignedValue();
180280031Sdim
181280031Sdim  // Check for constant vectors which are splats of INT_MIN values.
182280031Sdim  if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
183280031Sdim    if (Constant *Splat = CV->getSplatValue())
184280031Sdim      return Splat->isNotMinSignedValue();
185280031Sdim
186280031Sdim  // Check for constant vectors which are splats of INT_MIN values.
187280031Sdim  if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
188280031Sdim    if (Constant *Splat = CV->getSplatValue())
189280031Sdim      return Splat->isNotMinSignedValue();
190280031Sdim
191280031Sdim  // It *may* contain INT_MIN, we can't tell.
192280031Sdim  return false;
193280031Sdim}
194280031Sdim
195249259Sdim// Constructor to create a '0' constant of arbitrary type...
196249259SdimConstant *Constant::getNullValue(Type *Ty) {
197249259Sdim  switch (Ty->getTypeID()) {
198249259Sdim  case Type::IntegerTyID:
199249259Sdim    return ConstantInt::get(Ty, 0);
200249259Sdim  case Type::HalfTyID:
201249259Sdim    return ConstantFP::get(Ty->getContext(),
202249259Sdim                           APFloat::getZero(APFloat::IEEEhalf));
203249259Sdim  case Type::FloatTyID:
204249259Sdim    return ConstantFP::get(Ty->getContext(),
205249259Sdim                           APFloat::getZero(APFloat::IEEEsingle));
206249259Sdim  case Type::DoubleTyID:
207249259Sdim    return ConstantFP::get(Ty->getContext(),
208249259Sdim                           APFloat::getZero(APFloat::IEEEdouble));
209249259Sdim  case Type::X86_FP80TyID:
210249259Sdim    return ConstantFP::get(Ty->getContext(),
211249259Sdim                           APFloat::getZero(APFloat::x87DoubleExtended));
212249259Sdim  case Type::FP128TyID:
213249259Sdim    return ConstantFP::get(Ty->getContext(),
214249259Sdim                           APFloat::getZero(APFloat::IEEEquad));
215249259Sdim  case Type::PPC_FP128TyID:
216249259Sdim    return ConstantFP::get(Ty->getContext(),
217249259Sdim                           APFloat(APFloat::PPCDoubleDouble,
218249259Sdim                                   APInt::getNullValue(128)));
219249259Sdim  case Type::PointerTyID:
220249259Sdim    return ConstantPointerNull::get(cast<PointerType>(Ty));
221249259Sdim  case Type::StructTyID:
222249259Sdim  case Type::ArrayTyID:
223249259Sdim  case Type::VectorTyID:
224249259Sdim    return ConstantAggregateZero::get(Ty);
225296417Sdim  case Type::TokenTyID:
226296417Sdim    return ConstantTokenNone::get(Ty->getContext());
227249259Sdim  default:
228249259Sdim    // Function, Label, or Opaque type?
229249259Sdim    llvm_unreachable("Cannot create a null constant of that type!");
230249259Sdim  }
231249259Sdim}
232249259Sdim
233249259SdimConstant *Constant::getIntegerValue(Type *Ty, const APInt &V) {
234249259Sdim  Type *ScalarTy = Ty->getScalarType();
235249259Sdim
236249259Sdim  // Create the base integer constant.
237249259Sdim  Constant *C = ConstantInt::get(Ty->getContext(), V);
238249259Sdim
239249259Sdim  // Convert an integer to a pointer, if necessary.
240249259Sdim  if (PointerType *PTy = dyn_cast<PointerType>(ScalarTy))
241249259Sdim    C = ConstantExpr::getIntToPtr(C, PTy);
242249259Sdim
243249259Sdim  // Broadcast a scalar to a vector, if necessary.
244249259Sdim  if (VectorType *VTy = dyn_cast<VectorType>(Ty))
245249259Sdim    C = ConstantVector::getSplat(VTy->getNumElements(), C);
246249259Sdim
247249259Sdim  return C;
248249259Sdim}
249249259Sdim
250249259SdimConstant *Constant::getAllOnesValue(Type *Ty) {
251249259Sdim  if (IntegerType *ITy = dyn_cast<IntegerType>(Ty))
252249259Sdim    return ConstantInt::get(Ty->getContext(),
253249259Sdim                            APInt::getAllOnesValue(ITy->getBitWidth()));
254249259Sdim
255249259Sdim  if (Ty->isFloatingPointTy()) {
256249259Sdim    APFloat FL = APFloat::getAllOnesValue(Ty->getPrimitiveSizeInBits(),
257249259Sdim                                          !Ty->isPPC_FP128Ty());
258249259Sdim    return ConstantFP::get(Ty->getContext(), FL);
259249259Sdim  }
260249259Sdim
261249259Sdim  VectorType *VTy = cast<VectorType>(Ty);
262249259Sdim  return ConstantVector::getSplat(VTy->getNumElements(),
263249259Sdim                                  getAllOnesValue(VTy->getElementType()));
264249259Sdim}
265249259Sdim
266249259Sdim/// getAggregateElement - For aggregates (struct/array/vector) return the
267249259Sdim/// constant that corresponds to the specified element if possible, or null if
268249259Sdim/// not.  This can return null if the element index is a ConstantExpr, or if
269249259Sdim/// 'this' is a constant expr.
270249259SdimConstant *Constant::getAggregateElement(unsigned Elt) const {
271249259Sdim  if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(this))
272276479Sdim    return Elt < CS->getNumOperands() ? CS->getOperand(Elt) : nullptr;
273249259Sdim
274249259Sdim  if (const ConstantArray *CA = dyn_cast<ConstantArray>(this))
275276479Sdim    return Elt < CA->getNumOperands() ? CA->getOperand(Elt) : nullptr;
276249259Sdim
277249259Sdim  if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
278276479Sdim    return Elt < CV->getNumOperands() ? CV->getOperand(Elt) : nullptr;
279249259Sdim
280280031Sdim  if (const ConstantAggregateZero *CAZ = dyn_cast<ConstantAggregateZero>(this))
281280031Sdim    return Elt < CAZ->getNumElements() ? CAZ->getElementValue(Elt) : nullptr;
282249259Sdim
283249259Sdim  if (const UndefValue *UV = dyn_cast<UndefValue>(this))
284280031Sdim    return Elt < UV->getNumElements() ? UV->getElementValue(Elt) : nullptr;
285249259Sdim
286249259Sdim  if (const ConstantDataSequential *CDS =dyn_cast<ConstantDataSequential>(this))
287276479Sdim    return Elt < CDS->getNumElements() ? CDS->getElementAsConstant(Elt)
288276479Sdim                                       : nullptr;
289276479Sdim  return nullptr;
290249259Sdim}
291249259Sdim
292249259SdimConstant *Constant::getAggregateElement(Constant *Elt) const {
293249259Sdim  assert(isa<IntegerType>(Elt->getType()) && "Index must be an integer");
294249259Sdim  if (ConstantInt *CI = dyn_cast<ConstantInt>(Elt))
295249259Sdim    return getAggregateElement(CI->getZExtValue());
296276479Sdim  return nullptr;
297249259Sdim}
298249259Sdim
299288943Sdimvoid Constant::destroyConstant() {
300288943Sdim  /// First call destroyConstantImpl on the subclass.  This gives the subclass
301288943Sdim  /// a chance to remove the constant from any maps/pools it's contained in.
302288943Sdim  switch (getValueID()) {
303288943Sdim  default:
304288943Sdim    llvm_unreachable("Not a constant!");
305288943Sdim#define HANDLE_CONSTANT(Name)                                                  \
306288943Sdim  case Value::Name##Val:                                                       \
307288943Sdim    cast<Name>(this)->destroyConstantImpl();                                   \
308288943Sdim    break;
309288943Sdim#include "llvm/IR/Value.def"
310288943Sdim  }
311249259Sdim
312249259Sdim  // When a Constant is destroyed, there may be lingering
313249259Sdim  // references to the constant by other constants in the constant pool.  These
314249259Sdim  // constants are implicitly dependent on the module that is being deleted,
315249259Sdim  // but they don't know that.  Because we only find out when the CPV is
316249259Sdim  // deleted, we must now notify all of our users (that should only be
317249259Sdim  // Constants) that they are, in fact, invalid now and should be deleted.
318249259Sdim  //
319249259Sdim  while (!use_empty()) {
320276479Sdim    Value *V = user_back();
321288943Sdim#ifndef NDEBUG // Only in -g mode...
322249259Sdim    if (!isa<Constant>(V)) {
323249259Sdim      dbgs() << "While deleting: " << *this
324288943Sdim             << "\n\nUse still stuck around after Def is destroyed: " << *V
325288943Sdim             << "\n\n";
326249259Sdim    }
327249259Sdim#endif
328249259Sdim    assert(isa<Constant>(V) && "References remain to Constant being destroyed");
329249259Sdim    cast<Constant>(V)->destroyConstant();
330249259Sdim
331249259Sdim    // The constant should remove itself from our use list...
332276479Sdim    assert((use_empty() || user_back() != V) && "Constant not removed!");
333249259Sdim  }
334249259Sdim
335249259Sdim  // Value has no outstanding references it is safe to delete it now...
336249259Sdim  delete this;
337249259Sdim}
338249259Sdim
339251662Sdimstatic bool canTrapImpl(const Constant *C,
340280031Sdim                        SmallPtrSetImpl<const ConstantExpr *> &NonTrappingOps) {
341251662Sdim  assert(C->getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
342249259Sdim  // The only thing that could possibly trap are constant exprs.
343251662Sdim  const ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
344251662Sdim  if (!CE)
345251662Sdim    return false;
346249259Sdim
347249259Sdim  // ConstantExpr traps if any operands can trap.
348251662Sdim  for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
349251662Sdim    if (ConstantExpr *Op = dyn_cast<ConstantExpr>(CE->getOperand(i))) {
350280031Sdim      if (NonTrappingOps.insert(Op).second && canTrapImpl(Op, NonTrappingOps))
351251662Sdim        return true;
352251662Sdim    }
353251662Sdim  }
354249259Sdim
355249259Sdim  // Otherwise, only specific operations can trap.
356249259Sdim  switch (CE->getOpcode()) {
357249259Sdim  default:
358249259Sdim    return false;
359249259Sdim  case Instruction::UDiv:
360249259Sdim  case Instruction::SDiv:
361249259Sdim  case Instruction::FDiv:
362249259Sdim  case Instruction::URem:
363249259Sdim  case Instruction::SRem:
364249259Sdim  case Instruction::FRem:
365249259Sdim    // Div and rem can trap if the RHS is not known to be non-zero.
366249259Sdim    if (!isa<ConstantInt>(CE->getOperand(1)) ||CE->getOperand(1)->isNullValue())
367249259Sdim      return true;
368249259Sdim    return false;
369249259Sdim  }
370249259Sdim}
371249259Sdim
372251662Sdim/// canTrap - Return true if evaluation of this constant could trap.  This is
373251662Sdim/// true for things like constant expressions that could divide by zero.
374251662Sdimbool Constant::canTrap() const {
375251662Sdim  SmallPtrSet<const ConstantExpr *, 4> NonTrappingOps;
376251662Sdim  return canTrapImpl(this, NonTrappingOps);
377251662Sdim}
378251662Sdim
379276479Sdim/// Check if C contains a GlobalValue for which Predicate is true.
380276479Sdimstatic bool
381276479SdimConstHasGlobalValuePredicate(const Constant *C,
382276479Sdim                             bool (*Predicate)(const GlobalValue *)) {
383276479Sdim  SmallPtrSet<const Constant *, 8> Visited;
384276479Sdim  SmallVector<const Constant *, 8> WorkList;
385276479Sdim  WorkList.push_back(C);
386276479Sdim  Visited.insert(C);
387249259Sdim
388249259Sdim  while (!WorkList.empty()) {
389276479Sdim    const Constant *WorkItem = WorkList.pop_back_val();
390276479Sdim    if (const auto *GV = dyn_cast<GlobalValue>(WorkItem))
391276479Sdim      if (Predicate(GV))
392249259Sdim        return true;
393276479Sdim    for (const Value *Op : WorkItem->operands()) {
394276479Sdim      const Constant *ConstOp = dyn_cast<Constant>(Op);
395276479Sdim      if (!ConstOp)
396249259Sdim        continue;
397280031Sdim      if (Visited.insert(ConstOp).second)
398276479Sdim        WorkList.push_back(ConstOp);
399249259Sdim    }
400249259Sdim  }
401249259Sdim  return false;
402249259Sdim}
403249259Sdim
404276479Sdim/// Return true if the value can vary between threads.
405276479Sdimbool Constant::isThreadDependent() const {
406276479Sdim  auto DLLImportPredicate = [](const GlobalValue *GV) {
407276479Sdim    return GV->isThreadLocal();
408276479Sdim  };
409276479Sdim  return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
410276479Sdim}
411276479Sdim
412276479Sdimbool Constant::isDLLImportDependent() const {
413276479Sdim  auto DLLImportPredicate = [](const GlobalValue *GV) {
414276479Sdim    return GV->hasDLLImportStorageClass();
415276479Sdim  };
416276479Sdim  return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
417276479Sdim}
418276479Sdim
419276479Sdim/// Return true if the constant has users other than constant exprs and other
420276479Sdim/// dangling things.
421249259Sdimbool Constant::isConstantUsed() const {
422276479Sdim  for (const User *U : users()) {
423276479Sdim    const Constant *UC = dyn_cast<Constant>(U);
424276479Sdim    if (!UC || isa<GlobalValue>(UC))
425249259Sdim      return true;
426249259Sdim
427249259Sdim    if (UC->isConstantUsed())
428249259Sdim      return true;
429249259Sdim  }
430249259Sdim  return false;
431249259Sdim}
432249259Sdim
433296417Sdimbool Constant::needsRelocation() const {
434296417Sdim  if (isa<GlobalValue>(this))
435296417Sdim    return true; // Global reference.
436249259Sdim
437296417Sdim  if (const BlockAddress *BA = dyn_cast<BlockAddress>(this))
438296417Sdim    return BA->getFunction()->needsRelocation();
439249259Sdim
440249259Sdim  // While raw uses of blockaddress need to be relocated, differences between
441249259Sdim  // two of them don't when they are for labels in the same function.  This is a
442249259Sdim  // common idiom when creating a table for the indirect goto extension, so we
443249259Sdim  // handle it efficiently here.
444249259Sdim  if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(this))
445249259Sdim    if (CE->getOpcode() == Instruction::Sub) {
446249259Sdim      ConstantExpr *LHS = dyn_cast<ConstantExpr>(CE->getOperand(0));
447249259Sdim      ConstantExpr *RHS = dyn_cast<ConstantExpr>(CE->getOperand(1));
448296417Sdim      if (LHS && RHS && LHS->getOpcode() == Instruction::PtrToInt &&
449249259Sdim          RHS->getOpcode() == Instruction::PtrToInt &&
450249259Sdim          isa<BlockAddress>(LHS->getOperand(0)) &&
451249259Sdim          isa<BlockAddress>(RHS->getOperand(0)) &&
452249259Sdim          cast<BlockAddress>(LHS->getOperand(0))->getFunction() ==
453296417Sdim              cast<BlockAddress>(RHS->getOperand(0))->getFunction())
454296417Sdim        return false;
455249259Sdim    }
456249259Sdim
457296417Sdim  bool Result = false;
458249259Sdim  for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
459296417Sdim    Result |= cast<Constant>(getOperand(i))->needsRelocation();
460249259Sdim
461249259Sdim  return Result;
462249259Sdim}
463249259Sdim
464249259Sdim/// removeDeadUsersOfConstant - If the specified constantexpr is dead, remove
465249259Sdim/// it.  This involves recursively eliminating any dead users of the
466249259Sdim/// constantexpr.
467249259Sdimstatic bool removeDeadUsersOfConstant(const Constant *C) {
468249259Sdim  if (isa<GlobalValue>(C)) return false; // Cannot remove this
469249259Sdim
470249259Sdim  while (!C->use_empty()) {
471276479Sdim    const Constant *User = dyn_cast<Constant>(C->user_back());
472249259Sdim    if (!User) return false; // Non-constant usage;
473249259Sdim    if (!removeDeadUsersOfConstant(User))
474249259Sdim      return false; // Constant wasn't dead
475249259Sdim  }
476249259Sdim
477249259Sdim  const_cast<Constant*>(C)->destroyConstant();
478249259Sdim  return true;
479249259Sdim}
480249259Sdim
481249259Sdim
482249259Sdim/// removeDeadConstantUsers - If there are any dead constant users dangling
483249259Sdim/// off of this constant, remove them.  This method is useful for clients
484249259Sdim/// that want to check to see if a global is unused, but don't want to deal
485249259Sdim/// with potentially dead constants hanging off of the globals.
486249259Sdimvoid Constant::removeDeadConstantUsers() const {
487276479Sdim  Value::const_user_iterator I = user_begin(), E = user_end();
488276479Sdim  Value::const_user_iterator LastNonDeadUser = E;
489249259Sdim  while (I != E) {
490249259Sdim    const Constant *User = dyn_cast<Constant>(*I);
491276479Sdim    if (!User) {
492249259Sdim      LastNonDeadUser = I;
493249259Sdim      ++I;
494249259Sdim      continue;
495249259Sdim    }
496249259Sdim
497249259Sdim    if (!removeDeadUsersOfConstant(User)) {
498249259Sdim      // If the constant wasn't dead, remember that this was the last live use
499249259Sdim      // and move on to the next constant.
500249259Sdim      LastNonDeadUser = I;
501249259Sdim      ++I;
502249259Sdim      continue;
503249259Sdim    }
504249259Sdim
505249259Sdim    // If the constant was dead, then the iterator is invalidated.
506249259Sdim    if (LastNonDeadUser == E) {
507276479Sdim      I = user_begin();
508249259Sdim      if (I == E) break;
509249259Sdim    } else {
510249259Sdim      I = LastNonDeadUser;
511249259Sdim      ++I;
512249259Sdim    }
513249259Sdim  }
514249259Sdim}
515249259Sdim
516249259Sdim
517249259Sdim
518249259Sdim//===----------------------------------------------------------------------===//
519249259Sdim//                                ConstantInt
520249259Sdim//===----------------------------------------------------------------------===//
521249259Sdim
522249259Sdimvoid ConstantInt::anchor() { }
523249259Sdim
524249259SdimConstantInt::ConstantInt(IntegerType *Ty, const APInt& V)
525276479Sdim  : Constant(Ty, ConstantIntVal, nullptr, 0), Val(V) {
526249259Sdim  assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
527249259Sdim}
528249259Sdim
529249259SdimConstantInt *ConstantInt::getTrue(LLVMContext &Context) {
530249259Sdim  LLVMContextImpl *pImpl = Context.pImpl;
531249259Sdim  if (!pImpl->TheTrueVal)
532249259Sdim    pImpl->TheTrueVal = ConstantInt::get(Type::getInt1Ty(Context), 1);
533249259Sdim  return pImpl->TheTrueVal;
534249259Sdim}
535249259Sdim
536249259SdimConstantInt *ConstantInt::getFalse(LLVMContext &Context) {
537249259Sdim  LLVMContextImpl *pImpl = Context.pImpl;
538249259Sdim  if (!pImpl->TheFalseVal)
539249259Sdim    pImpl->TheFalseVal = ConstantInt::get(Type::getInt1Ty(Context), 0);
540249259Sdim  return pImpl->TheFalseVal;
541249259Sdim}
542249259Sdim
543249259SdimConstant *ConstantInt::getTrue(Type *Ty) {
544249259Sdim  VectorType *VTy = dyn_cast<VectorType>(Ty);
545249259Sdim  if (!VTy) {
546249259Sdim    assert(Ty->isIntegerTy(1) && "True must be i1 or vector of i1.");
547249259Sdim    return ConstantInt::getTrue(Ty->getContext());
548249259Sdim  }
549249259Sdim  assert(VTy->getElementType()->isIntegerTy(1) &&
550249259Sdim         "True must be vector of i1 or i1.");
551249259Sdim  return ConstantVector::getSplat(VTy->getNumElements(),
552249259Sdim                                  ConstantInt::getTrue(Ty->getContext()));
553249259Sdim}
554249259Sdim
555249259SdimConstant *ConstantInt::getFalse(Type *Ty) {
556249259Sdim  VectorType *VTy = dyn_cast<VectorType>(Ty);
557249259Sdim  if (!VTy) {
558249259Sdim    assert(Ty->isIntegerTy(1) && "False must be i1 or vector of i1.");
559249259Sdim    return ConstantInt::getFalse(Ty->getContext());
560249259Sdim  }
561249259Sdim  assert(VTy->getElementType()->isIntegerTy(1) &&
562249259Sdim         "False must be vector of i1 or i1.");
563249259Sdim  return ConstantVector::getSplat(VTy->getNumElements(),
564249259Sdim                                  ConstantInt::getFalse(Ty->getContext()));
565249259Sdim}
566249259Sdim
567280031Sdim// Get a ConstantInt from an APInt.
568249259SdimConstantInt *ConstantInt::get(LLVMContext &Context, const APInt &V) {
569249259Sdim  // get an existing value or the insertion position
570261991Sdim  LLVMContextImpl *pImpl = Context.pImpl;
571280031Sdim  ConstantInt *&Slot = pImpl->IntConstants[V];
572280031Sdim  if (!Slot) {
573280031Sdim    // Get the corresponding integer type for the bit width of the value.
574280031Sdim    IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
575280031Sdim    Slot = new ConstantInt(ITy, V);
576280031Sdim  }
577280031Sdim  assert(Slot->getType() == IntegerType::get(Context, V.getBitWidth()));
578249259Sdim  return Slot;
579249259Sdim}
580249259Sdim
581249259SdimConstant *ConstantInt::get(Type *Ty, uint64_t V, bool isSigned) {
582249259Sdim  Constant *C = get(cast<IntegerType>(Ty->getScalarType()), V, isSigned);
583249259Sdim
584249259Sdim  // For vectors, broadcast the value.
585249259Sdim  if (VectorType *VTy = dyn_cast<VectorType>(Ty))
586249259Sdim    return ConstantVector::getSplat(VTy->getNumElements(), C);
587249259Sdim
588249259Sdim  return C;
589249259Sdim}
590249259Sdim
591249259SdimConstantInt *ConstantInt::get(IntegerType *Ty, uint64_t V,
592249259Sdim                              bool isSigned) {
593249259Sdim  return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned));
594249259Sdim}
595249259Sdim
596249259SdimConstantInt *ConstantInt::getSigned(IntegerType *Ty, int64_t V) {
597249259Sdim  return get(Ty, V, true);
598249259Sdim}
599249259Sdim
600249259SdimConstant *ConstantInt::getSigned(Type *Ty, int64_t V) {
601249259Sdim  return get(Ty, V, true);
602249259Sdim}
603249259Sdim
604249259SdimConstant *ConstantInt::get(Type *Ty, const APInt& V) {
605249259Sdim  ConstantInt *C = get(Ty->getContext(), V);
606249259Sdim  assert(C->getType() == Ty->getScalarType() &&
607249259Sdim         "ConstantInt type doesn't match the type implied by its value!");
608249259Sdim
609249259Sdim  // For vectors, broadcast the value.
610249259Sdim  if (VectorType *VTy = dyn_cast<VectorType>(Ty))
611249259Sdim    return ConstantVector::getSplat(VTy->getNumElements(), C);
612249259Sdim
613249259Sdim  return C;
614249259Sdim}
615249259Sdim
616249259SdimConstantInt *ConstantInt::get(IntegerType* Ty, StringRef Str,
617249259Sdim                              uint8_t radix) {
618249259Sdim  return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
619249259Sdim}
620249259Sdim
621288943Sdim/// Remove the constant from the constant table.
622288943Sdimvoid ConstantInt::destroyConstantImpl() {
623288943Sdim  llvm_unreachable("You can't ConstantInt->destroyConstantImpl()!");
624288943Sdim}
625288943Sdim
626249259Sdim//===----------------------------------------------------------------------===//
627249259Sdim//                                ConstantFP
628249259Sdim//===----------------------------------------------------------------------===//
629249259Sdim
630249259Sdimstatic const fltSemantics *TypeToFloatSemantics(Type *Ty) {
631249259Sdim  if (Ty->isHalfTy())
632249259Sdim    return &APFloat::IEEEhalf;
633249259Sdim  if (Ty->isFloatTy())
634249259Sdim    return &APFloat::IEEEsingle;
635249259Sdim  if (Ty->isDoubleTy())
636249259Sdim    return &APFloat::IEEEdouble;
637249259Sdim  if (Ty->isX86_FP80Ty())
638249259Sdim    return &APFloat::x87DoubleExtended;
639249259Sdim  else if (Ty->isFP128Ty())
640249259Sdim    return &APFloat::IEEEquad;
641249259Sdim
642249259Sdim  assert(Ty->isPPC_FP128Ty() && "Unknown FP format");
643249259Sdim  return &APFloat::PPCDoubleDouble;
644249259Sdim}
645249259Sdim
646249259Sdimvoid ConstantFP::anchor() { }
647249259Sdim
648249259Sdim/// get() - This returns a constant fp for the specified value in the
649249259Sdim/// specified type.  This should only be used for simple constant values like
650249259Sdim/// 2.0/1.0 etc, that are known-valid both as double and as the target format.
651249259SdimConstant *ConstantFP::get(Type *Ty, double V) {
652249259Sdim  LLVMContext &Context = Ty->getContext();
653249259Sdim
654249259Sdim  APFloat FV(V);
655249259Sdim  bool ignored;
656249259Sdim  FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
657249259Sdim             APFloat::rmNearestTiesToEven, &ignored);
658249259Sdim  Constant *C = get(Context, FV);
659249259Sdim
660249259Sdim  // For vectors, broadcast the value.
661249259Sdim  if (VectorType *VTy = dyn_cast<VectorType>(Ty))
662249259Sdim    return ConstantVector::getSplat(VTy->getNumElements(), C);
663249259Sdim
664249259Sdim  return C;
665249259Sdim}
666249259Sdim
667249259Sdim
668249259SdimConstant *ConstantFP::get(Type *Ty, StringRef Str) {
669249259Sdim  LLVMContext &Context = Ty->getContext();
670249259Sdim
671249259Sdim  APFloat FV(*TypeToFloatSemantics(Ty->getScalarType()), Str);
672249259Sdim  Constant *C = get(Context, FV);
673249259Sdim
674249259Sdim  // For vectors, broadcast the value.
675249259Sdim  if (VectorType *VTy = dyn_cast<VectorType>(Ty))
676249259Sdim    return ConstantVector::getSplat(VTy->getNumElements(), C);
677249259Sdim
678249259Sdim  return C;
679249259Sdim}
680249259Sdim
681288943SdimConstant *ConstantFP::getNaN(Type *Ty, bool Negative, unsigned Type) {
682288943Sdim  const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
683288943Sdim  APFloat NaN = APFloat::getNaN(Semantics, Negative, Type);
684288943Sdim  Constant *C = get(Ty->getContext(), NaN);
685288943Sdim
686288943Sdim  if (VectorType *VTy = dyn_cast<VectorType>(Ty))
687288943Sdim    return ConstantVector::getSplat(VTy->getNumElements(), C);
688288943Sdim
689288943Sdim  return C;
690288943Sdim}
691288943Sdim
692276479SdimConstant *ConstantFP::getNegativeZero(Type *Ty) {
693276479Sdim  const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
694276479Sdim  APFloat NegZero = APFloat::getZero(Semantics, /*Negative=*/true);
695276479Sdim  Constant *C = get(Ty->getContext(), NegZero);
696249259Sdim
697276479Sdim  if (VectorType *VTy = dyn_cast<VectorType>(Ty))
698276479Sdim    return ConstantVector::getSplat(VTy->getNumElements(), C);
699276479Sdim
700276479Sdim  return C;
701249259Sdim}
702249259Sdim
703249259Sdim
704249259SdimConstant *ConstantFP::getZeroValueForNegation(Type *Ty) {
705276479Sdim  if (Ty->isFPOrFPVectorTy())
706276479Sdim    return getNegativeZero(Ty);
707249259Sdim
708249259Sdim  return Constant::getNullValue(Ty);
709249259Sdim}
710249259Sdim
711249259Sdim
712249259Sdim// ConstantFP accessors.
713249259SdimConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
714249259Sdim  LLVMContextImpl* pImpl = Context.pImpl;
715249259Sdim
716280031Sdim  ConstantFP *&Slot = pImpl->FPConstants[V];
717249259Sdim
718249259Sdim  if (!Slot) {
719249259Sdim    Type *Ty;
720249259Sdim    if (&V.getSemantics() == &APFloat::IEEEhalf)
721249259Sdim      Ty = Type::getHalfTy(Context);
722249259Sdim    else if (&V.getSemantics() == &APFloat::IEEEsingle)
723249259Sdim      Ty = Type::getFloatTy(Context);
724249259Sdim    else if (&V.getSemantics() == &APFloat::IEEEdouble)
725249259Sdim      Ty = Type::getDoubleTy(Context);
726249259Sdim    else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
727249259Sdim      Ty = Type::getX86_FP80Ty(Context);
728249259Sdim    else if (&V.getSemantics() == &APFloat::IEEEquad)
729249259Sdim      Ty = Type::getFP128Ty(Context);
730249259Sdim    else {
731249259Sdim      assert(&V.getSemantics() == &APFloat::PPCDoubleDouble &&
732249259Sdim             "Unknown FP format");
733249259Sdim      Ty = Type::getPPC_FP128Ty(Context);
734249259Sdim    }
735249259Sdim    Slot = new ConstantFP(Ty, V);
736249259Sdim  }
737249259Sdim
738249259Sdim  return Slot;
739249259Sdim}
740249259Sdim
741276479SdimConstant *ConstantFP::getInfinity(Type *Ty, bool Negative) {
742276479Sdim  const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
743276479Sdim  Constant *C = get(Ty->getContext(), APFloat::getInf(Semantics, Negative));
744276479Sdim
745276479Sdim  if (VectorType *VTy = dyn_cast<VectorType>(Ty))
746276479Sdim    return ConstantVector::getSplat(VTy->getNumElements(), C);
747276479Sdim
748276479Sdim  return C;
749249259Sdim}
750249259Sdim
751249259SdimConstantFP::ConstantFP(Type *Ty, const APFloat& V)
752276479Sdim  : Constant(Ty, ConstantFPVal, nullptr, 0), Val(V) {
753249259Sdim  assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
754249259Sdim         "FP type Mismatch");
755249259Sdim}
756249259Sdim
757249259Sdimbool ConstantFP::isExactlyValue(const APFloat &V) const {
758249259Sdim  return Val.bitwiseIsEqual(V);
759249259Sdim}
760249259Sdim
761288943Sdim/// Remove the constant from the constant table.
762288943Sdimvoid ConstantFP::destroyConstantImpl() {
763288943Sdim  llvm_unreachable("You can't ConstantInt->destroyConstantImpl()!");
764288943Sdim}
765288943Sdim
766249259Sdim//===----------------------------------------------------------------------===//
767249259Sdim//                   ConstantAggregateZero Implementation
768249259Sdim//===----------------------------------------------------------------------===//
769249259Sdim
770249259Sdim/// getSequentialElement - If this CAZ has array or vector type, return a zero
771249259Sdim/// with the right element type.
772249259SdimConstant *ConstantAggregateZero::getSequentialElement() const {
773249259Sdim  return Constant::getNullValue(getType()->getSequentialElementType());
774249259Sdim}
775249259Sdim
776249259Sdim/// getStructElement - If this CAZ has struct type, return a zero with the
777249259Sdim/// right element type for the specified element.
778249259SdimConstant *ConstantAggregateZero::getStructElement(unsigned Elt) const {
779249259Sdim  return Constant::getNullValue(getType()->getStructElementType(Elt));
780249259Sdim}
781249259Sdim
782249259Sdim/// getElementValue - Return a zero of the right value for the specified GEP
783249259Sdim/// index if we can, otherwise return null (e.g. if C is a ConstantExpr).
784249259SdimConstant *ConstantAggregateZero::getElementValue(Constant *C) const {
785249259Sdim  if (isa<SequentialType>(getType()))
786249259Sdim    return getSequentialElement();
787249259Sdim  return getStructElement(cast<ConstantInt>(C)->getZExtValue());
788249259Sdim}
789249259Sdim
790249259Sdim/// getElementValue - Return a zero of the right value for the specified GEP
791249259Sdim/// index.
792249259SdimConstant *ConstantAggregateZero::getElementValue(unsigned Idx) const {
793249259Sdim  if (isa<SequentialType>(getType()))
794249259Sdim    return getSequentialElement();
795249259Sdim  return getStructElement(Idx);
796249259Sdim}
797249259Sdim
798280031Sdimunsigned ConstantAggregateZero::getNumElements() const {
799296417Sdim  Type *Ty = getType();
800296417Sdim  if (auto *AT = dyn_cast<ArrayType>(Ty))
801280031Sdim    return AT->getNumElements();
802296417Sdim  if (auto *VT = dyn_cast<VectorType>(Ty))
803280031Sdim    return VT->getNumElements();
804280031Sdim  return Ty->getStructNumElements();
805280031Sdim}
806249259Sdim
807249259Sdim//===----------------------------------------------------------------------===//
808249259Sdim//                         UndefValue Implementation
809249259Sdim//===----------------------------------------------------------------------===//
810249259Sdim
811249259Sdim/// getSequentialElement - If this undef has array or vector type, return an
812249259Sdim/// undef with the right element type.
813249259SdimUndefValue *UndefValue::getSequentialElement() const {
814249259Sdim  return UndefValue::get(getType()->getSequentialElementType());
815249259Sdim}
816249259Sdim
817249259Sdim/// getStructElement - If this undef has struct type, return a zero with the
818249259Sdim/// right element type for the specified element.
819249259SdimUndefValue *UndefValue::getStructElement(unsigned Elt) const {
820249259Sdim  return UndefValue::get(getType()->getStructElementType(Elt));
821249259Sdim}
822249259Sdim
823249259Sdim/// getElementValue - Return an undef of the right value for the specified GEP
824249259Sdim/// index if we can, otherwise return null (e.g. if C is a ConstantExpr).
825249259SdimUndefValue *UndefValue::getElementValue(Constant *C) const {
826249259Sdim  if (isa<SequentialType>(getType()))
827249259Sdim    return getSequentialElement();
828249259Sdim  return getStructElement(cast<ConstantInt>(C)->getZExtValue());
829249259Sdim}
830249259Sdim
831249259Sdim/// getElementValue - Return an undef of the right value for the specified GEP
832249259Sdim/// index.
833249259SdimUndefValue *UndefValue::getElementValue(unsigned Idx) const {
834249259Sdim  if (isa<SequentialType>(getType()))
835249259Sdim    return getSequentialElement();
836249259Sdim  return getStructElement(Idx);
837249259Sdim}
838249259Sdim
839280031Sdimunsigned UndefValue::getNumElements() const {
840296417Sdim  Type *Ty = getType();
841296417Sdim  if (auto *AT = dyn_cast<ArrayType>(Ty))
842280031Sdim    return AT->getNumElements();
843296417Sdim  if (auto *VT = dyn_cast<VectorType>(Ty))
844280031Sdim    return VT->getNumElements();
845280031Sdim  return Ty->getStructNumElements();
846280031Sdim}
847249259Sdim
848249259Sdim//===----------------------------------------------------------------------===//
849249259Sdim//                            ConstantXXX Classes
850249259Sdim//===----------------------------------------------------------------------===//
851249259Sdim
852249259Sdimtemplate <typename ItTy, typename EltTy>
853249259Sdimstatic bool rangeOnlyContains(ItTy Start, ItTy End, EltTy Elt) {
854249259Sdim  for (; Start != End; ++Start)
855249259Sdim    if (*Start != Elt)
856249259Sdim      return false;
857249259Sdim  return true;
858249259Sdim}
859249259Sdim
860296417Sdimtemplate <typename SequentialTy, typename ElementTy>
861296417Sdimstatic Constant *getIntSequenceIfElementsMatch(ArrayRef<Constant *> V) {
862296417Sdim  assert(!V.empty() && "Cannot get empty int sequence.");
863296417Sdim
864296417Sdim  SmallVector<ElementTy, 16> Elts;
865296417Sdim  for (Constant *C : V)
866296417Sdim    if (auto *CI = dyn_cast<ConstantInt>(C))
867296417Sdim      Elts.push_back(CI->getZExtValue());
868296417Sdim    else
869296417Sdim      return nullptr;
870296417Sdim  return SequentialTy::get(V[0]->getContext(), Elts);
871296417Sdim}
872296417Sdim
873296417Sdimtemplate <typename SequentialTy, typename ElementTy>
874296417Sdimstatic Constant *getFPSequenceIfElementsMatch(ArrayRef<Constant *> V) {
875296417Sdim  assert(!V.empty() && "Cannot get empty FP sequence.");
876296417Sdim
877296417Sdim  SmallVector<ElementTy, 16> Elts;
878296417Sdim  for (Constant *C : V)
879296417Sdim    if (auto *CFP = dyn_cast<ConstantFP>(C))
880296417Sdim      Elts.push_back(CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
881296417Sdim    else
882296417Sdim      return nullptr;
883296417Sdim  return SequentialTy::getFP(V[0]->getContext(), Elts);
884296417Sdim}
885296417Sdim
886296417Sdimtemplate <typename SequenceTy>
887296417Sdimstatic Constant *getSequenceIfElementsMatch(Constant *C,
888296417Sdim                                            ArrayRef<Constant *> V) {
889296417Sdim  // We speculatively build the elements here even if it turns out that there is
890296417Sdim  // a constantexpr or something else weird, since it is so uncommon for that to
891296417Sdim  // happen.
892296417Sdim  if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
893296417Sdim    if (CI->getType()->isIntegerTy(8))
894296417Sdim      return getIntSequenceIfElementsMatch<SequenceTy, uint8_t>(V);
895296417Sdim    else if (CI->getType()->isIntegerTy(16))
896296417Sdim      return getIntSequenceIfElementsMatch<SequenceTy, uint16_t>(V);
897296417Sdim    else if (CI->getType()->isIntegerTy(32))
898296417Sdim      return getIntSequenceIfElementsMatch<SequenceTy, uint32_t>(V);
899296417Sdim    else if (CI->getType()->isIntegerTy(64))
900296417Sdim      return getIntSequenceIfElementsMatch<SequenceTy, uint64_t>(V);
901296417Sdim  } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
902296417Sdim    if (CFP->getType()->isHalfTy())
903296417Sdim      return getFPSequenceIfElementsMatch<SequenceTy, uint16_t>(V);
904296417Sdim    else if (CFP->getType()->isFloatTy())
905296417Sdim      return getFPSequenceIfElementsMatch<SequenceTy, uint32_t>(V);
906296417Sdim    else if (CFP->getType()->isDoubleTy())
907296417Sdim      return getFPSequenceIfElementsMatch<SequenceTy, uint64_t>(V);
908296417Sdim  }
909296417Sdim
910296417Sdim  return nullptr;
911296417Sdim}
912296417Sdim
913249259SdimConstantArray::ConstantArray(ArrayType *T, ArrayRef<Constant *> V)
914249259Sdim  : Constant(T, ConstantArrayVal,
915249259Sdim             OperandTraits<ConstantArray>::op_end(this) - V.size(),
916249259Sdim             V.size()) {
917249259Sdim  assert(V.size() == T->getNumElements() &&
918249259Sdim         "Invalid initializer vector for constant array");
919249259Sdim  for (unsigned i = 0, e = V.size(); i != e; ++i)
920249259Sdim    assert(V[i]->getType() == T->getElementType() &&
921249259Sdim           "Initializer for array element doesn't match array element type!");
922249259Sdim  std::copy(V.begin(), V.end(), op_begin());
923249259Sdim}
924249259Sdim
925249259SdimConstant *ConstantArray::get(ArrayType *Ty, ArrayRef<Constant*> V) {
926280031Sdim  if (Constant *C = getImpl(Ty, V))
927280031Sdim    return C;
928280031Sdim  return Ty->getContext().pImpl->ArrayConstants.getOrCreate(Ty, V);
929280031Sdim}
930296417Sdim
931280031SdimConstant *ConstantArray::getImpl(ArrayType *Ty, ArrayRef<Constant*> V) {
932249259Sdim  // Empty arrays are canonicalized to ConstantAggregateZero.
933249259Sdim  if (V.empty())
934249259Sdim    return ConstantAggregateZero::get(Ty);
935249259Sdim
936249259Sdim  for (unsigned i = 0, e = V.size(); i != e; ++i) {
937249259Sdim    assert(V[i]->getType() == Ty->getElementType() &&
938249259Sdim           "Wrong type in array element initializer");
939249259Sdim  }
940249259Sdim
941249259Sdim  // If this is an all-zero array, return a ConstantAggregateZero object.  If
942249259Sdim  // all undef, return an UndefValue, if "all simple", then return a
943249259Sdim  // ConstantDataArray.
944249259Sdim  Constant *C = V[0];
945249259Sdim  if (isa<UndefValue>(C) && rangeOnlyContains(V.begin(), V.end(), C))
946249259Sdim    return UndefValue::get(Ty);
947249259Sdim
948249259Sdim  if (C->isNullValue() && rangeOnlyContains(V.begin(), V.end(), C))
949249259Sdim    return ConstantAggregateZero::get(Ty);
950249259Sdim
951249259Sdim  // Check to see if all of the elements are ConstantFP or ConstantInt and if
952249259Sdim  // the element type is compatible with ConstantDataVector.  If so, use it.
953296417Sdim  if (ConstantDataSequential::isElementTypeCompatible(C->getType()))
954296417Sdim    return getSequenceIfElementsMatch<ConstantDataArray>(C, V);
955249259Sdim
956249259Sdim  // Otherwise, we really do want to create a ConstantArray.
957280031Sdim  return nullptr;
958249259Sdim}
959249259Sdim
960249259Sdim/// getTypeForElements - Return an anonymous struct type to use for a constant
961249259Sdim/// with the specified set of elements.  The list must not be empty.
962249259SdimStructType *ConstantStruct::getTypeForElements(LLVMContext &Context,
963249259Sdim                                               ArrayRef<Constant*> V,
964249259Sdim                                               bool Packed) {
965249259Sdim  unsigned VecSize = V.size();
966249259Sdim  SmallVector<Type*, 16> EltTypes(VecSize);
967249259Sdim  for (unsigned i = 0; i != VecSize; ++i)
968249259Sdim    EltTypes[i] = V[i]->getType();
969249259Sdim
970249259Sdim  return StructType::get(Context, EltTypes, Packed);
971249259Sdim}
972249259Sdim
973249259Sdim
974249259SdimStructType *ConstantStruct::getTypeForElements(ArrayRef<Constant*> V,
975249259Sdim                                               bool Packed) {
976249259Sdim  assert(!V.empty() &&
977249259Sdim         "ConstantStruct::getTypeForElements cannot be called on empty list");
978249259Sdim  return getTypeForElements(V[0]->getContext(), V, Packed);
979249259Sdim}
980249259Sdim
981249259Sdim
982249259SdimConstantStruct::ConstantStruct(StructType *T, ArrayRef<Constant *> V)
983249259Sdim  : Constant(T, ConstantStructVal,
984249259Sdim             OperandTraits<ConstantStruct>::op_end(this) - V.size(),
985249259Sdim             V.size()) {
986249259Sdim  assert(V.size() == T->getNumElements() &&
987249259Sdim         "Invalid initializer vector for constant structure");
988249259Sdim  for (unsigned i = 0, e = V.size(); i != e; ++i)
989249259Sdim    assert((T->isOpaque() || V[i]->getType() == T->getElementType(i)) &&
990249259Sdim           "Initializer for struct element doesn't match struct element type!");
991249259Sdim  std::copy(V.begin(), V.end(), op_begin());
992249259Sdim}
993249259Sdim
994249259Sdim// ConstantStruct accessors.
995249259SdimConstant *ConstantStruct::get(StructType *ST, ArrayRef<Constant*> V) {
996249259Sdim  assert((ST->isOpaque() || ST->getNumElements() == V.size()) &&
997249259Sdim         "Incorrect # elements specified to ConstantStruct::get");
998249259Sdim
999249259Sdim  // Create a ConstantAggregateZero value if all elements are zeros.
1000249259Sdim  bool isZero = true;
1001249259Sdim  bool isUndef = false;
1002249259Sdim
1003249259Sdim  if (!V.empty()) {
1004249259Sdim    isUndef = isa<UndefValue>(V[0]);
1005249259Sdim    isZero = V[0]->isNullValue();
1006249259Sdim    if (isUndef || isZero) {
1007249259Sdim      for (unsigned i = 0, e = V.size(); i != e; ++i) {
1008249259Sdim        if (!V[i]->isNullValue())
1009249259Sdim          isZero = false;
1010249259Sdim        if (!isa<UndefValue>(V[i]))
1011249259Sdim          isUndef = false;
1012249259Sdim      }
1013249259Sdim    }
1014249259Sdim  }
1015249259Sdim  if (isZero)
1016249259Sdim    return ConstantAggregateZero::get(ST);
1017249259Sdim  if (isUndef)
1018249259Sdim    return UndefValue::get(ST);
1019249259Sdim
1020249259Sdim  return ST->getContext().pImpl->StructConstants.getOrCreate(ST, V);
1021249259Sdim}
1022249259Sdim
1023249259SdimConstant *ConstantStruct::get(StructType *T, ...) {
1024249259Sdim  va_list ap;
1025249259Sdim  SmallVector<Constant*, 8> Values;
1026249259Sdim  va_start(ap, T);
1027249259Sdim  while (Constant *Val = va_arg(ap, llvm::Constant*))
1028249259Sdim    Values.push_back(Val);
1029249259Sdim  va_end(ap);
1030249259Sdim  return get(T, Values);
1031249259Sdim}
1032249259Sdim
1033249259SdimConstantVector::ConstantVector(VectorType *T, ArrayRef<Constant *> V)
1034249259Sdim  : Constant(T, ConstantVectorVal,
1035249259Sdim             OperandTraits<ConstantVector>::op_end(this) - V.size(),
1036249259Sdim             V.size()) {
1037249259Sdim  for (size_t i = 0, e = V.size(); i != e; i++)
1038249259Sdim    assert(V[i]->getType() == T->getElementType() &&
1039249259Sdim           "Initializer for vector element doesn't match vector element type!");
1040249259Sdim  std::copy(V.begin(), V.end(), op_begin());
1041249259Sdim}
1042249259Sdim
1043249259Sdim// ConstantVector accessors.
1044249259SdimConstant *ConstantVector::get(ArrayRef<Constant*> V) {
1045280031Sdim  if (Constant *C = getImpl(V))
1046280031Sdim    return C;
1047280031Sdim  VectorType *Ty = VectorType::get(V.front()->getType(), V.size());
1048280031Sdim  return Ty->getContext().pImpl->VectorConstants.getOrCreate(Ty, V);
1049280031Sdim}
1050296417Sdim
1051280031SdimConstant *ConstantVector::getImpl(ArrayRef<Constant*> V) {
1052249259Sdim  assert(!V.empty() && "Vectors can't be empty");
1053249259Sdim  VectorType *T = VectorType::get(V.front()->getType(), V.size());
1054249259Sdim
1055249259Sdim  // If this is an all-undef or all-zero vector, return a
1056249259Sdim  // ConstantAggregateZero or UndefValue.
1057249259Sdim  Constant *C = V[0];
1058249259Sdim  bool isZero = C->isNullValue();
1059249259Sdim  bool isUndef = isa<UndefValue>(C);
1060249259Sdim
1061249259Sdim  if (isZero || isUndef) {
1062249259Sdim    for (unsigned i = 1, e = V.size(); i != e; ++i)
1063249259Sdim      if (V[i] != C) {
1064249259Sdim        isZero = isUndef = false;
1065249259Sdim        break;
1066249259Sdim      }
1067249259Sdim  }
1068249259Sdim
1069249259Sdim  if (isZero)
1070249259Sdim    return ConstantAggregateZero::get(T);
1071249259Sdim  if (isUndef)
1072249259Sdim    return UndefValue::get(T);
1073249259Sdim
1074249259Sdim  // Check to see if all of the elements are ConstantFP or ConstantInt and if
1075249259Sdim  // the element type is compatible with ConstantDataVector.  If so, use it.
1076296417Sdim  if (ConstantDataSequential::isElementTypeCompatible(C->getType()))
1077296417Sdim    return getSequenceIfElementsMatch<ConstantDataVector>(C, V);
1078249259Sdim
1079249259Sdim  // Otherwise, the element type isn't compatible with ConstantDataVector, or
1080249259Sdim  // the operand list constants a ConstantExpr or something else strange.
1081280031Sdim  return nullptr;
1082249259Sdim}
1083249259Sdim
1084249259SdimConstant *ConstantVector::getSplat(unsigned NumElts, Constant *V) {
1085249259Sdim  // If this splat is compatible with ConstantDataVector, use it instead of
1086249259Sdim  // ConstantVector.
1087249259Sdim  if ((isa<ConstantFP>(V) || isa<ConstantInt>(V)) &&
1088249259Sdim      ConstantDataSequential::isElementTypeCompatible(V->getType()))
1089249259Sdim    return ConstantDataVector::getSplat(NumElts, V);
1090249259Sdim
1091249259Sdim  SmallVector<Constant*, 32> Elts(NumElts, V);
1092249259Sdim  return get(Elts);
1093249259Sdim}
1094249259Sdim
1095296417SdimConstantTokenNone *ConstantTokenNone::get(LLVMContext &Context) {
1096296417Sdim  LLVMContextImpl *pImpl = Context.pImpl;
1097296417Sdim  if (!pImpl->TheNoneToken)
1098296417Sdim    pImpl->TheNoneToken.reset(new ConstantTokenNone(Context));
1099296417Sdim  return pImpl->TheNoneToken.get();
1100296417Sdim}
1101249259Sdim
1102296417Sdim/// Remove the constant from the constant table.
1103296417Sdimvoid ConstantTokenNone::destroyConstantImpl() {
1104296417Sdim  llvm_unreachable("You can't ConstantTokenNone->destroyConstantImpl()!");
1105296417Sdim}
1106296417Sdim
1107249259Sdim// Utility function for determining if a ConstantExpr is a CastOp or not. This
1108249259Sdim// can't be inline because we don't want to #include Instruction.h into
1109249259Sdim// Constant.h
1110249259Sdimbool ConstantExpr::isCast() const {
1111249259Sdim  return Instruction::isCast(getOpcode());
1112249259Sdim}
1113249259Sdim
1114249259Sdimbool ConstantExpr::isCompare() const {
1115249259Sdim  return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
1116249259Sdim}
1117249259Sdim
1118249259Sdimbool ConstantExpr::isGEPWithNoNotionalOverIndexing() const {
1119249259Sdim  if (getOpcode() != Instruction::GetElementPtr) return false;
1120249259Sdim
1121249259Sdim  gep_type_iterator GEPI = gep_type_begin(this), E = gep_type_end(this);
1122276479Sdim  User::const_op_iterator OI = std::next(this->op_begin());
1123249259Sdim
1124249259Sdim  // Skip the first index, as it has no static limit.
1125249259Sdim  ++GEPI;
1126249259Sdim  ++OI;
1127249259Sdim
1128249259Sdim  // The remaining indices must be compile-time known integers within the
1129249259Sdim  // bounds of the corresponding notional static array types.
1130249259Sdim  for (; GEPI != E; ++GEPI, ++OI) {
1131249259Sdim    ConstantInt *CI = dyn_cast<ConstantInt>(*OI);
1132249259Sdim    if (!CI) return false;
1133249259Sdim    if (ArrayType *ATy = dyn_cast<ArrayType>(*GEPI))
1134249259Sdim      if (CI->getValue().getActiveBits() > 64 ||
1135249259Sdim          CI->getZExtValue() >= ATy->getNumElements())
1136249259Sdim        return false;
1137249259Sdim  }
1138249259Sdim
1139249259Sdim  // All the indices checked out.
1140249259Sdim  return true;
1141249259Sdim}
1142249259Sdim
1143249259Sdimbool ConstantExpr::hasIndices() const {
1144249259Sdim  return getOpcode() == Instruction::ExtractValue ||
1145249259Sdim         getOpcode() == Instruction::InsertValue;
1146249259Sdim}
1147249259Sdim
1148249259SdimArrayRef<unsigned> ConstantExpr::getIndices() const {
1149249259Sdim  if (const ExtractValueConstantExpr *EVCE =
1150249259Sdim        dyn_cast<ExtractValueConstantExpr>(this))
1151249259Sdim    return EVCE->Indices;
1152249259Sdim
1153249259Sdim  return cast<InsertValueConstantExpr>(this)->Indices;
1154249259Sdim}
1155249259Sdim
1156249259Sdimunsigned ConstantExpr::getPredicate() const {
1157296417Sdim  return cast<CompareConstantExpr>(this)->predicate;
1158249259Sdim}
1159249259Sdim
1160249259Sdim/// getWithOperandReplaced - Return a constant expression identical to this
1161249259Sdim/// one, but with the specified operand set to the specified value.
1162249259SdimConstant *
1163249259SdimConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
1164249259Sdim  assert(Op->getType() == getOperand(OpNo)->getType() &&
1165249259Sdim         "Replacing operand with value of different type!");
1166249259Sdim  if (getOperand(OpNo) == Op)
1167249259Sdim    return const_cast<ConstantExpr*>(this);
1168249259Sdim
1169249259Sdim  SmallVector<Constant*, 8> NewOps;
1170249259Sdim  for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1171249259Sdim    NewOps.push_back(i == OpNo ? Op : getOperand(i));
1172249259Sdim
1173249259Sdim  return getWithOperands(NewOps);
1174249259Sdim}
1175249259Sdim
1176249259Sdim/// getWithOperands - This returns the current constant expression with the
1177249259Sdim/// operands replaced with the specified values.  The specified array must
1178249259Sdim/// have the same number of operands as our current one.
1179280031SdimConstant *ConstantExpr::getWithOperands(ArrayRef<Constant *> Ops, Type *Ty,
1180296417Sdim                                        bool OnlyIfReduced, Type *SrcTy) const {
1181249259Sdim  assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
1182249259Sdim
1183288943Sdim  // If no operands changed return self.
1184288943Sdim  if (Ty == getType() && std::equal(Ops.begin(), Ops.end(), op_begin()))
1185249259Sdim    return const_cast<ConstantExpr*>(this);
1186249259Sdim
1187280031Sdim  Type *OnlyIfReducedTy = OnlyIfReduced ? Ty : nullptr;
1188249259Sdim  switch (getOpcode()) {
1189249259Sdim  case Instruction::Trunc:
1190249259Sdim  case Instruction::ZExt:
1191249259Sdim  case Instruction::SExt:
1192249259Sdim  case Instruction::FPTrunc:
1193249259Sdim  case Instruction::FPExt:
1194249259Sdim  case Instruction::UIToFP:
1195249259Sdim  case Instruction::SIToFP:
1196249259Sdim  case Instruction::FPToUI:
1197249259Sdim  case Instruction::FPToSI:
1198249259Sdim  case Instruction::PtrToInt:
1199249259Sdim  case Instruction::IntToPtr:
1200249259Sdim  case Instruction::BitCast:
1201261991Sdim  case Instruction::AddrSpaceCast:
1202280031Sdim    return ConstantExpr::getCast(getOpcode(), Ops[0], Ty, OnlyIfReduced);
1203249259Sdim  case Instruction::Select:
1204280031Sdim    return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2], OnlyIfReducedTy);
1205249259Sdim  case Instruction::InsertElement:
1206280031Sdim    return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2],
1207280031Sdim                                          OnlyIfReducedTy);
1208249259Sdim  case Instruction::ExtractElement:
1209280031Sdim    return ConstantExpr::getExtractElement(Ops[0], Ops[1], OnlyIfReducedTy);
1210249259Sdim  case Instruction::InsertValue:
1211280031Sdim    return ConstantExpr::getInsertValue(Ops[0], Ops[1], getIndices(),
1212280031Sdim                                        OnlyIfReducedTy);
1213249259Sdim  case Instruction::ExtractValue:
1214280031Sdim    return ConstantExpr::getExtractValue(Ops[0], getIndices(), OnlyIfReducedTy);
1215249259Sdim  case Instruction::ShuffleVector:
1216280031Sdim    return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2],
1217280031Sdim                                          OnlyIfReducedTy);
1218296417Sdim  case Instruction::GetElementPtr: {
1219296417Sdim    auto *GEPO = cast<GEPOperator>(this);
1220296417Sdim    assert(SrcTy || (Ops[0]->getType() == getOperand(0)->getType()));
1221296417Sdim    return ConstantExpr::getGetElementPtr(
1222296417Sdim        SrcTy ? SrcTy : GEPO->getSourceElementType(), Ops[0], Ops.slice(1),
1223296417Sdim        GEPO->isInBounds(), OnlyIfReducedTy);
1224296417Sdim  }
1225249259Sdim  case Instruction::ICmp:
1226249259Sdim  case Instruction::FCmp:
1227280031Sdim    return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1],
1228280031Sdim                                    OnlyIfReducedTy);
1229249259Sdim  default:
1230249259Sdim    assert(getNumOperands() == 2 && "Must be binary operator?");
1231280031Sdim    return ConstantExpr::get(getOpcode(), Ops[0], Ops[1], SubclassOptionalData,
1232280031Sdim                             OnlyIfReducedTy);
1233249259Sdim  }
1234249259Sdim}
1235249259Sdim
1236249259Sdim
1237249259Sdim//===----------------------------------------------------------------------===//
1238249259Sdim//                      isValueValidForType implementations
1239249259Sdim
1240249259Sdimbool ConstantInt::isValueValidForType(Type *Ty, uint64_t Val) {
1241249259Sdim  unsigned NumBits = Ty->getIntegerBitWidth(); // assert okay
1242249259Sdim  if (Ty->isIntegerTy(1))
1243249259Sdim    return Val == 0 || Val == 1;
1244249259Sdim  if (NumBits >= 64)
1245249259Sdim    return true; // always true, has to fit in largest type
1246249259Sdim  uint64_t Max = (1ll << NumBits) - 1;
1247249259Sdim  return Val <= Max;
1248249259Sdim}
1249249259Sdim
1250249259Sdimbool ConstantInt::isValueValidForType(Type *Ty, int64_t Val) {
1251249259Sdim  unsigned NumBits = Ty->getIntegerBitWidth();
1252249259Sdim  if (Ty->isIntegerTy(1))
1253249259Sdim    return Val == 0 || Val == 1 || Val == -1;
1254249259Sdim  if (NumBits >= 64)
1255249259Sdim    return true; // always true, has to fit in largest type
1256249259Sdim  int64_t Min = -(1ll << (NumBits-1));
1257249259Sdim  int64_t Max = (1ll << (NumBits-1)) - 1;
1258249259Sdim  return (Val >= Min && Val <= Max);
1259249259Sdim}
1260249259Sdim
1261249259Sdimbool ConstantFP::isValueValidForType(Type *Ty, const APFloat& Val) {
1262249259Sdim  // convert modifies in place, so make a copy.
1263249259Sdim  APFloat Val2 = APFloat(Val);
1264249259Sdim  bool losesInfo;
1265249259Sdim  switch (Ty->getTypeID()) {
1266249259Sdim  default:
1267249259Sdim    return false;         // These can't be represented as floating point!
1268249259Sdim
1269249259Sdim  // FIXME rounding mode needs to be more flexible
1270249259Sdim  case Type::HalfTyID: {
1271249259Sdim    if (&Val2.getSemantics() == &APFloat::IEEEhalf)
1272249259Sdim      return true;
1273249259Sdim    Val2.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, &losesInfo);
1274249259Sdim    return !losesInfo;
1275249259Sdim  }
1276249259Sdim  case Type::FloatTyID: {
1277249259Sdim    if (&Val2.getSemantics() == &APFloat::IEEEsingle)
1278249259Sdim      return true;
1279249259Sdim    Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
1280249259Sdim    return !losesInfo;
1281249259Sdim  }
1282249259Sdim  case Type::DoubleTyID: {
1283249259Sdim    if (&Val2.getSemantics() == &APFloat::IEEEhalf ||
1284249259Sdim        &Val2.getSemantics() == &APFloat::IEEEsingle ||
1285249259Sdim        &Val2.getSemantics() == &APFloat::IEEEdouble)
1286249259Sdim      return true;
1287249259Sdim    Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
1288249259Sdim    return !losesInfo;
1289249259Sdim  }
1290249259Sdim  case Type::X86_FP80TyID:
1291249259Sdim    return &Val2.getSemantics() == &APFloat::IEEEhalf ||
1292249259Sdim           &Val2.getSemantics() == &APFloat::IEEEsingle ||
1293249259Sdim           &Val2.getSemantics() == &APFloat::IEEEdouble ||
1294249259Sdim           &Val2.getSemantics() == &APFloat::x87DoubleExtended;
1295249259Sdim  case Type::FP128TyID:
1296249259Sdim    return &Val2.getSemantics() == &APFloat::IEEEhalf ||
1297249259Sdim           &Val2.getSemantics() == &APFloat::IEEEsingle ||
1298249259Sdim           &Val2.getSemantics() == &APFloat::IEEEdouble ||
1299249259Sdim           &Val2.getSemantics() == &APFloat::IEEEquad;
1300249259Sdim  case Type::PPC_FP128TyID:
1301249259Sdim    return &Val2.getSemantics() == &APFloat::IEEEhalf ||
1302249259Sdim           &Val2.getSemantics() == &APFloat::IEEEsingle ||
1303249259Sdim           &Val2.getSemantics() == &APFloat::IEEEdouble ||
1304249259Sdim           &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
1305249259Sdim  }
1306249259Sdim}
1307249259Sdim
1308249259Sdim
1309249259Sdim//===----------------------------------------------------------------------===//
1310249259Sdim//                      Factory Function Implementation
1311249259Sdim
1312249259SdimConstantAggregateZero *ConstantAggregateZero::get(Type *Ty) {
1313249259Sdim  assert((Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()) &&
1314249259Sdim         "Cannot create an aggregate zero of non-aggregate type!");
1315249259Sdim
1316249259Sdim  ConstantAggregateZero *&Entry = Ty->getContext().pImpl->CAZConstants[Ty];
1317276479Sdim  if (!Entry)
1318249259Sdim    Entry = new ConstantAggregateZero(Ty);
1319249259Sdim
1320249259Sdim  return Entry;
1321249259Sdim}
1322249259Sdim
1323249259Sdim/// destroyConstant - Remove the constant from the constant table.
1324249259Sdim///
1325288943Sdimvoid ConstantAggregateZero::destroyConstantImpl() {
1326249259Sdim  getContext().pImpl->CAZConstants.erase(getType());
1327249259Sdim}
1328249259Sdim
1329249259Sdim/// destroyConstant - Remove the constant from the constant table...
1330249259Sdim///
1331288943Sdimvoid ConstantArray::destroyConstantImpl() {
1332249259Sdim  getType()->getContext().pImpl->ArrayConstants.remove(this);
1333249259Sdim}
1334249259Sdim
1335249259Sdim
1336249259Sdim//---- ConstantStruct::get() implementation...
1337249259Sdim//
1338249259Sdim
1339249259Sdim// destroyConstant - Remove the constant from the constant table...
1340249259Sdim//
1341288943Sdimvoid ConstantStruct::destroyConstantImpl() {
1342249259Sdim  getType()->getContext().pImpl->StructConstants.remove(this);
1343249259Sdim}
1344249259Sdim
1345249259Sdim// destroyConstant - Remove the constant from the constant table...
1346249259Sdim//
1347288943Sdimvoid ConstantVector::destroyConstantImpl() {
1348249259Sdim  getType()->getContext().pImpl->VectorConstants.remove(this);
1349249259Sdim}
1350249259Sdim
1351249259Sdim/// getSplatValue - If this is a splat vector constant, meaning that all of
1352249259Sdim/// the elements have the same value, return that value. Otherwise return 0.
1353249259SdimConstant *Constant::getSplatValue() const {
1354249259Sdim  assert(this->getType()->isVectorTy() && "Only valid for vectors!");
1355249259Sdim  if (isa<ConstantAggregateZero>(this))
1356249259Sdim    return getNullValue(this->getType()->getVectorElementType());
1357249259Sdim  if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
1358249259Sdim    return CV->getSplatValue();
1359249259Sdim  if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
1360249259Sdim    return CV->getSplatValue();
1361276479Sdim  return nullptr;
1362249259Sdim}
1363249259Sdim
1364249259Sdim/// getSplatValue - If this is a splat constant, where all of the
1365249259Sdim/// elements have the same value, return that value. Otherwise return null.
1366249259SdimConstant *ConstantVector::getSplatValue() const {
1367249259Sdim  // Check out first element.
1368249259Sdim  Constant *Elt = getOperand(0);
1369249259Sdim  // Then make sure all remaining elements point to the same value.
1370249259Sdim  for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1371249259Sdim    if (getOperand(I) != Elt)
1372276479Sdim      return nullptr;
1373249259Sdim  return Elt;
1374249259Sdim}
1375249259Sdim
1376249259Sdim/// If C is a constant integer then return its value, otherwise C must be a
1377249259Sdim/// vector of constant integers, all equal, and the common value is returned.
1378249259Sdimconst APInt &Constant::getUniqueInteger() const {
1379249259Sdim  if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
1380249259Sdim    return CI->getValue();
1381249259Sdim  assert(this->getSplatValue() && "Doesn't contain a unique integer!");
1382249259Sdim  const Constant *C = this->getAggregateElement(0U);
1383249259Sdim  assert(C && isa<ConstantInt>(C) && "Not a vector of numbers!");
1384249259Sdim  return cast<ConstantInt>(C)->getValue();
1385249259Sdim}
1386249259Sdim
1387249259Sdim//---- ConstantPointerNull::get() implementation.
1388249259Sdim//
1389249259Sdim
1390249259SdimConstantPointerNull *ConstantPointerNull::get(PointerType *Ty) {
1391249259Sdim  ConstantPointerNull *&Entry = Ty->getContext().pImpl->CPNConstants[Ty];
1392276479Sdim  if (!Entry)
1393249259Sdim    Entry = new ConstantPointerNull(Ty);
1394249259Sdim
1395249259Sdim  return Entry;
1396249259Sdim}
1397249259Sdim
1398249259Sdim// destroyConstant - Remove the constant from the constant table...
1399249259Sdim//
1400288943Sdimvoid ConstantPointerNull::destroyConstantImpl() {
1401249259Sdim  getContext().pImpl->CPNConstants.erase(getType());
1402249259Sdim}
1403249259Sdim
1404249259Sdim
1405249259Sdim//---- UndefValue::get() implementation.
1406249259Sdim//
1407249259Sdim
1408249259SdimUndefValue *UndefValue::get(Type *Ty) {
1409249259Sdim  UndefValue *&Entry = Ty->getContext().pImpl->UVConstants[Ty];
1410276479Sdim  if (!Entry)
1411249259Sdim    Entry = new UndefValue(Ty);
1412249259Sdim
1413249259Sdim  return Entry;
1414249259Sdim}
1415249259Sdim
1416249259Sdim// destroyConstant - Remove the constant from the constant table.
1417249259Sdim//
1418288943Sdimvoid UndefValue::destroyConstantImpl() {
1419249259Sdim  // Free the constant and any dangling references to it.
1420249259Sdim  getContext().pImpl->UVConstants.erase(getType());
1421249259Sdim}
1422249259Sdim
1423249259Sdim//---- BlockAddress::get() implementation.
1424249259Sdim//
1425249259Sdim
1426249259SdimBlockAddress *BlockAddress::get(BasicBlock *BB) {
1427276479Sdim  assert(BB->getParent() && "Block must have a parent");
1428249259Sdim  return get(BB->getParent(), BB);
1429249259Sdim}
1430249259Sdim
1431249259SdimBlockAddress *BlockAddress::get(Function *F, BasicBlock *BB) {
1432249259Sdim  BlockAddress *&BA =
1433249259Sdim    F->getContext().pImpl->BlockAddresses[std::make_pair(F, BB)];
1434276479Sdim  if (!BA)
1435249259Sdim    BA = new BlockAddress(F, BB);
1436249259Sdim
1437249259Sdim  assert(BA->getFunction() == F && "Basic block moved between functions");
1438249259Sdim  return BA;
1439249259Sdim}
1440249259Sdim
1441249259SdimBlockAddress::BlockAddress(Function *F, BasicBlock *BB)
1442249259Sdim: Constant(Type::getInt8PtrTy(F->getContext()), Value::BlockAddressVal,
1443249259Sdim           &Op<0>(), 2) {
1444249259Sdim  setOperand(0, F);
1445249259Sdim  setOperand(1, BB);
1446249259Sdim  BB->AdjustBlockAddressRefCount(1);
1447249259Sdim}
1448249259Sdim
1449276479SdimBlockAddress *BlockAddress::lookup(const BasicBlock *BB) {
1450276479Sdim  if (!BB->hasAddressTaken())
1451276479Sdim    return nullptr;
1452249259Sdim
1453276479Sdim  const Function *F = BB->getParent();
1454276479Sdim  assert(F && "Block must have a parent");
1455276479Sdim  BlockAddress *BA =
1456276479Sdim      F->getContext().pImpl->BlockAddresses.lookup(std::make_pair(F, BB));
1457276479Sdim  assert(BA && "Refcount and block address map disagree!");
1458276479Sdim  return BA;
1459276479Sdim}
1460276479Sdim
1461249259Sdim// destroyConstant - Remove the constant from the constant table.
1462249259Sdim//
1463288943Sdimvoid BlockAddress::destroyConstantImpl() {
1464249259Sdim  getFunction()->getType()->getContext().pImpl
1465249259Sdim    ->BlockAddresses.erase(std::make_pair(getFunction(), getBasicBlock()));
1466249259Sdim  getBasicBlock()->AdjustBlockAddressRefCount(-1);
1467249259Sdim}
1468249259Sdim
1469288943SdimValue *BlockAddress::handleOperandChangeImpl(Value *From, Value *To, Use *U) {
1470249259Sdim  // This could be replacing either the Basic Block or the Function.  In either
1471249259Sdim  // case, we have to remove the map entry.
1472249259Sdim  Function *NewF = getFunction();
1473249259Sdim  BasicBlock *NewBB = getBasicBlock();
1474249259Sdim
1475249259Sdim  if (U == &Op<0>())
1476261991Sdim    NewF = cast<Function>(To->stripPointerCasts());
1477249259Sdim  else
1478249259Sdim    NewBB = cast<BasicBlock>(To);
1479249259Sdim
1480249259Sdim  // See if the 'new' entry already exists, if not, just update this in place
1481249259Sdim  // and return early.
1482249259Sdim  BlockAddress *&NewBA =
1483249259Sdim    getContext().pImpl->BlockAddresses[std::make_pair(NewF, NewBB)];
1484288943Sdim  if (NewBA)
1485288943Sdim    return NewBA;
1486249259Sdim
1487280031Sdim  getBasicBlock()->AdjustBlockAddressRefCount(-1);
1488249259Sdim
1489280031Sdim  // Remove the old entry, this can't cause the map to rehash (just a
1490280031Sdim  // tombstone will get added).
1491280031Sdim  getContext().pImpl->BlockAddresses.erase(std::make_pair(getFunction(),
1492280031Sdim                                                          getBasicBlock()));
1493280031Sdim  NewBA = this;
1494280031Sdim  setOperand(0, NewF);
1495280031Sdim  setOperand(1, NewBB);
1496280031Sdim  getBasicBlock()->AdjustBlockAddressRefCount(1);
1497288943Sdim
1498288943Sdim  // If we just want to keep the existing value, then return null.
1499288943Sdim  // Callers know that this means we shouldn't delete this value.
1500288943Sdim  return nullptr;
1501249259Sdim}
1502249259Sdim
1503249259Sdim//---- ConstantExpr::get() implementations.
1504249259Sdim//
1505249259Sdim
1506249259Sdim/// This is a utility function to handle folding of casts and lookup of the
1507249259Sdim/// cast in the ExprConstants map. It is used by the various get* methods below.
1508280031Sdimstatic Constant *getFoldedCast(Instruction::CastOps opc, Constant *C, Type *Ty,
1509280031Sdim                               bool OnlyIfReduced = false) {
1510249259Sdim  assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1511249259Sdim  // Fold a few common cases
1512249259Sdim  if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1513249259Sdim    return FC;
1514249259Sdim
1515280031Sdim  if (OnlyIfReduced)
1516280031Sdim    return nullptr;
1517280031Sdim
1518249259Sdim  LLVMContextImpl *pImpl = Ty->getContext().pImpl;
1519249259Sdim
1520249259Sdim  // Look up the constant in the table first to ensure uniqueness.
1521280031Sdim  ConstantExprKeyType Key(opc, C);
1522249259Sdim
1523249259Sdim  return pImpl->ExprConstants.getOrCreate(Ty, Key);
1524249259Sdim}
1525249259Sdim
1526280031SdimConstant *ConstantExpr::getCast(unsigned oc, Constant *C, Type *Ty,
1527280031Sdim                                bool OnlyIfReduced) {
1528249259Sdim  Instruction::CastOps opc = Instruction::CastOps(oc);
1529249259Sdim  assert(Instruction::isCast(opc) && "opcode out of range");
1530249259Sdim  assert(C && Ty && "Null arguments to getCast");
1531249259Sdim  assert(CastInst::castIsValid(opc, C, Ty) && "Invalid constantexpr cast!");
1532249259Sdim
1533249259Sdim  switch (opc) {
1534249259Sdim  default:
1535249259Sdim    llvm_unreachable("Invalid cast opcode");
1536280031Sdim  case Instruction::Trunc:
1537280031Sdim    return getTrunc(C, Ty, OnlyIfReduced);
1538280031Sdim  case Instruction::ZExt:
1539280031Sdim    return getZExt(C, Ty, OnlyIfReduced);
1540280031Sdim  case Instruction::SExt:
1541280031Sdim    return getSExt(C, Ty, OnlyIfReduced);
1542280031Sdim  case Instruction::FPTrunc:
1543280031Sdim    return getFPTrunc(C, Ty, OnlyIfReduced);
1544280031Sdim  case Instruction::FPExt:
1545280031Sdim    return getFPExtend(C, Ty, OnlyIfReduced);
1546280031Sdim  case Instruction::UIToFP:
1547280031Sdim    return getUIToFP(C, Ty, OnlyIfReduced);
1548280031Sdim  case Instruction::SIToFP:
1549280031Sdim    return getSIToFP(C, Ty, OnlyIfReduced);
1550280031Sdim  case Instruction::FPToUI:
1551280031Sdim    return getFPToUI(C, Ty, OnlyIfReduced);
1552280031Sdim  case Instruction::FPToSI:
1553280031Sdim    return getFPToSI(C, Ty, OnlyIfReduced);
1554280031Sdim  case Instruction::PtrToInt:
1555280031Sdim    return getPtrToInt(C, Ty, OnlyIfReduced);
1556280031Sdim  case Instruction::IntToPtr:
1557280031Sdim    return getIntToPtr(C, Ty, OnlyIfReduced);
1558280031Sdim  case Instruction::BitCast:
1559280031Sdim    return getBitCast(C, Ty, OnlyIfReduced);
1560280031Sdim  case Instruction::AddrSpaceCast:
1561280031Sdim    return getAddrSpaceCast(C, Ty, OnlyIfReduced);
1562249259Sdim  }
1563249259Sdim}
1564249259Sdim
1565249259SdimConstant *ConstantExpr::getZExtOrBitCast(Constant *C, Type *Ty) {
1566249259Sdim  if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1567249259Sdim    return getBitCast(C, Ty);
1568249259Sdim  return getZExt(C, Ty);
1569249259Sdim}
1570249259Sdim
1571249259SdimConstant *ConstantExpr::getSExtOrBitCast(Constant *C, Type *Ty) {
1572249259Sdim  if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1573249259Sdim    return getBitCast(C, Ty);
1574249259Sdim  return getSExt(C, Ty);
1575249259Sdim}
1576249259Sdim
1577249259SdimConstant *ConstantExpr::getTruncOrBitCast(Constant *C, Type *Ty) {
1578249259Sdim  if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1579249259Sdim    return getBitCast(C, Ty);
1580249259Sdim  return getTrunc(C, Ty);
1581249259Sdim}
1582249259Sdim
1583249259SdimConstant *ConstantExpr::getPointerCast(Constant *S, Type *Ty) {
1584249259Sdim  assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
1585249259Sdim  assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
1586249259Sdim          "Invalid cast");
1587249259Sdim
1588249259Sdim  if (Ty->isIntOrIntVectorTy())
1589249259Sdim    return getPtrToInt(S, Ty);
1590261991Sdim
1591261991Sdim  unsigned SrcAS = S->getType()->getPointerAddressSpace();
1592261991Sdim  if (Ty->isPtrOrPtrVectorTy() && SrcAS != Ty->getPointerAddressSpace())
1593261991Sdim    return getAddrSpaceCast(S, Ty);
1594261991Sdim
1595249259Sdim  return getBitCast(S, Ty);
1596249259Sdim}
1597249259Sdim
1598261991SdimConstant *ConstantExpr::getPointerBitCastOrAddrSpaceCast(Constant *S,
1599261991Sdim                                                         Type *Ty) {
1600261991Sdim  assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
1601261991Sdim  assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
1602261991Sdim
1603261991Sdim  if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
1604261991Sdim    return getAddrSpaceCast(S, Ty);
1605261991Sdim
1606261991Sdim  return getBitCast(S, Ty);
1607261991Sdim}
1608261991Sdim
1609261991SdimConstant *ConstantExpr::getIntegerCast(Constant *C, Type *Ty,
1610249259Sdim                                       bool isSigned) {
1611249259Sdim  assert(C->getType()->isIntOrIntVectorTy() &&
1612249259Sdim         Ty->isIntOrIntVectorTy() && "Invalid cast");
1613249259Sdim  unsigned SrcBits = C->getType()->getScalarSizeInBits();
1614249259Sdim  unsigned DstBits = Ty->getScalarSizeInBits();
1615249259Sdim  Instruction::CastOps opcode =
1616249259Sdim    (SrcBits == DstBits ? Instruction::BitCast :
1617249259Sdim     (SrcBits > DstBits ? Instruction::Trunc :
1618249259Sdim      (isSigned ? Instruction::SExt : Instruction::ZExt)));
1619249259Sdim  return getCast(opcode, C, Ty);
1620249259Sdim}
1621249259Sdim
1622249259SdimConstant *ConstantExpr::getFPCast(Constant *C, Type *Ty) {
1623249259Sdim  assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1624249259Sdim         "Invalid cast");
1625249259Sdim  unsigned SrcBits = C->getType()->getScalarSizeInBits();
1626249259Sdim  unsigned DstBits = Ty->getScalarSizeInBits();
1627249259Sdim  if (SrcBits == DstBits)
1628249259Sdim    return C; // Avoid a useless cast
1629249259Sdim  Instruction::CastOps opcode =
1630249259Sdim    (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1631249259Sdim  return getCast(opcode, C, Ty);
1632249259Sdim}
1633249259Sdim
1634280031SdimConstant *ConstantExpr::getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) {
1635249259Sdim#ifndef NDEBUG
1636249259Sdim  bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1637249259Sdim  bool toVec = Ty->getTypeID() == Type::VectorTyID;
1638249259Sdim#endif
1639249259Sdim  assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1640249259Sdim  assert(C->getType()->isIntOrIntVectorTy() && "Trunc operand must be integer");
1641249259Sdim  assert(Ty->isIntOrIntVectorTy() && "Trunc produces only integral");
1642249259Sdim  assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1643249259Sdim         "SrcTy must be larger than DestTy for Trunc!");
1644249259Sdim
1645280031Sdim  return getFoldedCast(Instruction::Trunc, C, Ty, OnlyIfReduced);
1646249259Sdim}
1647249259Sdim
1648280031SdimConstant *ConstantExpr::getSExt(Constant *C, Type *Ty, bool OnlyIfReduced) {
1649249259Sdim#ifndef NDEBUG
1650249259Sdim  bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1651249259Sdim  bool toVec = Ty->getTypeID() == Type::VectorTyID;
1652249259Sdim#endif
1653249259Sdim  assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1654249259Sdim  assert(C->getType()->isIntOrIntVectorTy() && "SExt operand must be integral");
1655249259Sdim  assert(Ty->isIntOrIntVectorTy() && "SExt produces only integer");
1656249259Sdim  assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1657249259Sdim         "SrcTy must be smaller than DestTy for SExt!");
1658249259Sdim
1659280031Sdim  return getFoldedCast(Instruction::SExt, C, Ty, OnlyIfReduced);
1660249259Sdim}
1661249259Sdim
1662280031SdimConstant *ConstantExpr::getZExt(Constant *C, Type *Ty, bool OnlyIfReduced) {
1663249259Sdim#ifndef NDEBUG
1664249259Sdim  bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1665249259Sdim  bool toVec = Ty->getTypeID() == Type::VectorTyID;
1666249259Sdim#endif
1667249259Sdim  assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1668249259Sdim  assert(C->getType()->isIntOrIntVectorTy() && "ZEXt operand must be integral");
1669249259Sdim  assert(Ty->isIntOrIntVectorTy() && "ZExt produces only integer");
1670249259Sdim  assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1671249259Sdim         "SrcTy must be smaller than DestTy for ZExt!");
1672249259Sdim
1673280031Sdim  return getFoldedCast(Instruction::ZExt, C, Ty, OnlyIfReduced);
1674249259Sdim}
1675249259Sdim
1676280031SdimConstant *ConstantExpr::getFPTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) {
1677249259Sdim#ifndef NDEBUG
1678249259Sdim  bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1679249259Sdim  bool toVec = Ty->getTypeID() == Type::VectorTyID;
1680249259Sdim#endif
1681249259Sdim  assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1682249259Sdim  assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1683249259Sdim         C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1684249259Sdim         "This is an illegal floating point truncation!");
1685280031Sdim  return getFoldedCast(Instruction::FPTrunc, C, Ty, OnlyIfReduced);
1686249259Sdim}
1687249259Sdim
1688280031SdimConstant *ConstantExpr::getFPExtend(Constant *C, Type *Ty, bool OnlyIfReduced) {
1689249259Sdim#ifndef NDEBUG
1690249259Sdim  bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1691249259Sdim  bool toVec = Ty->getTypeID() == Type::VectorTyID;
1692249259Sdim#endif
1693249259Sdim  assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1694249259Sdim  assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1695249259Sdim         C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1696249259Sdim         "This is an illegal floating point extension!");
1697280031Sdim  return getFoldedCast(Instruction::FPExt, C, Ty, OnlyIfReduced);
1698249259Sdim}
1699249259Sdim
1700280031SdimConstant *ConstantExpr::getUIToFP(Constant *C, Type *Ty, bool OnlyIfReduced) {
1701249259Sdim#ifndef NDEBUG
1702249259Sdim  bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1703249259Sdim  bool toVec = Ty->getTypeID() == Type::VectorTyID;
1704249259Sdim#endif
1705249259Sdim  assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1706249259Sdim  assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
1707249259Sdim         "This is an illegal uint to floating point cast!");
1708280031Sdim  return getFoldedCast(Instruction::UIToFP, C, Ty, OnlyIfReduced);
1709249259Sdim}
1710249259Sdim
1711280031SdimConstant *ConstantExpr::getSIToFP(Constant *C, Type *Ty, bool OnlyIfReduced) {
1712249259Sdim#ifndef NDEBUG
1713249259Sdim  bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1714249259Sdim  bool toVec = Ty->getTypeID() == Type::VectorTyID;
1715249259Sdim#endif
1716249259Sdim  assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1717249259Sdim  assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
1718249259Sdim         "This is an illegal sint to floating point cast!");
1719280031Sdim  return getFoldedCast(Instruction::SIToFP, C, Ty, OnlyIfReduced);
1720249259Sdim}
1721249259Sdim
1722280031SdimConstant *ConstantExpr::getFPToUI(Constant *C, Type *Ty, bool OnlyIfReduced) {
1723249259Sdim#ifndef NDEBUG
1724249259Sdim  bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1725249259Sdim  bool toVec = Ty->getTypeID() == Type::VectorTyID;
1726249259Sdim#endif
1727249259Sdim  assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1728249259Sdim  assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
1729249259Sdim         "This is an illegal floating point to uint cast!");
1730280031Sdim  return getFoldedCast(Instruction::FPToUI, C, Ty, OnlyIfReduced);
1731249259Sdim}
1732249259Sdim
1733280031SdimConstant *ConstantExpr::getFPToSI(Constant *C, Type *Ty, bool OnlyIfReduced) {
1734249259Sdim#ifndef NDEBUG
1735249259Sdim  bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1736249259Sdim  bool toVec = Ty->getTypeID() == Type::VectorTyID;
1737249259Sdim#endif
1738249259Sdim  assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1739249259Sdim  assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
1740249259Sdim         "This is an illegal floating point to sint cast!");
1741280031Sdim  return getFoldedCast(Instruction::FPToSI, C, Ty, OnlyIfReduced);
1742249259Sdim}
1743249259Sdim
1744280031SdimConstant *ConstantExpr::getPtrToInt(Constant *C, Type *DstTy,
1745280031Sdim                                    bool OnlyIfReduced) {
1746249259Sdim  assert(C->getType()->getScalarType()->isPointerTy() &&
1747249259Sdim         "PtrToInt source must be pointer or pointer vector");
1748249259Sdim  assert(DstTy->getScalarType()->isIntegerTy() &&
1749249259Sdim         "PtrToInt destination must be integer or integer vector");
1750249259Sdim  assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
1751249259Sdim  if (isa<VectorType>(C->getType()))
1752249259Sdim    assert(C->getType()->getVectorNumElements()==DstTy->getVectorNumElements()&&
1753249259Sdim           "Invalid cast between a different number of vector elements");
1754280031Sdim  return getFoldedCast(Instruction::PtrToInt, C, DstTy, OnlyIfReduced);
1755249259Sdim}
1756249259Sdim
1757280031SdimConstant *ConstantExpr::getIntToPtr(Constant *C, Type *DstTy,
1758280031Sdim                                    bool OnlyIfReduced) {
1759249259Sdim  assert(C->getType()->getScalarType()->isIntegerTy() &&
1760249259Sdim         "IntToPtr source must be integer or integer vector");
1761249259Sdim  assert(DstTy->getScalarType()->isPointerTy() &&
1762249259Sdim         "IntToPtr destination must be a pointer or pointer vector");
1763249259Sdim  assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
1764249259Sdim  if (isa<VectorType>(C->getType()))
1765249259Sdim    assert(C->getType()->getVectorNumElements()==DstTy->getVectorNumElements()&&
1766249259Sdim           "Invalid cast between a different number of vector elements");
1767280031Sdim  return getFoldedCast(Instruction::IntToPtr, C, DstTy, OnlyIfReduced);
1768249259Sdim}
1769249259Sdim
1770280031SdimConstant *ConstantExpr::getBitCast(Constant *C, Type *DstTy,
1771280031Sdim                                   bool OnlyIfReduced) {
1772249259Sdim  assert(CastInst::castIsValid(Instruction::BitCast, C, DstTy) &&
1773249259Sdim         "Invalid constantexpr bitcast!");
1774249259Sdim
1775249259Sdim  // It is common to ask for a bitcast of a value to its own type, handle this
1776249259Sdim  // speedily.
1777249259Sdim  if (C->getType() == DstTy) return C;
1778249259Sdim
1779280031Sdim  return getFoldedCast(Instruction::BitCast, C, DstTy, OnlyIfReduced);
1780249259Sdim}
1781249259Sdim
1782280031SdimConstant *ConstantExpr::getAddrSpaceCast(Constant *C, Type *DstTy,
1783280031Sdim                                         bool OnlyIfReduced) {
1784261991Sdim  assert(CastInst::castIsValid(Instruction::AddrSpaceCast, C, DstTy) &&
1785261991Sdim         "Invalid constantexpr addrspacecast!");
1786261991Sdim
1787276479Sdim  // Canonicalize addrspacecasts between different pointer types by first
1788276479Sdim  // bitcasting the pointer type and then converting the address space.
1789276479Sdim  PointerType *SrcScalarTy = cast<PointerType>(C->getType()->getScalarType());
1790276479Sdim  PointerType *DstScalarTy = cast<PointerType>(DstTy->getScalarType());
1791276479Sdim  Type *DstElemTy = DstScalarTy->getElementType();
1792276479Sdim  if (SrcScalarTy->getElementType() != DstElemTy) {
1793276479Sdim    Type *MidTy = PointerType::get(DstElemTy, SrcScalarTy->getAddressSpace());
1794276479Sdim    if (VectorType *VT = dyn_cast<VectorType>(DstTy)) {
1795276479Sdim      // Handle vectors of pointers.
1796276479Sdim      MidTy = VectorType::get(MidTy, VT->getNumElements());
1797276479Sdim    }
1798276479Sdim    C = getBitCast(C, MidTy);
1799276479Sdim  }
1800280031Sdim  return getFoldedCast(Instruction::AddrSpaceCast, C, DstTy, OnlyIfReduced);
1801261991Sdim}
1802261991Sdim
1803249259SdimConstant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2,
1804280031Sdim                            unsigned Flags, Type *OnlyIfReducedTy) {
1805249259Sdim  // Check the operands for consistency first.
1806249259Sdim  assert(Opcode >= Instruction::BinaryOpsBegin &&
1807249259Sdim         Opcode <  Instruction::BinaryOpsEnd   &&
1808249259Sdim         "Invalid opcode in binary constant expression");
1809249259Sdim  assert(C1->getType() == C2->getType() &&
1810249259Sdim         "Operand types in binary constant expression should match");
1811249259Sdim
1812249259Sdim#ifndef NDEBUG
1813249259Sdim  switch (Opcode) {
1814249259Sdim  case Instruction::Add:
1815249259Sdim  case Instruction::Sub:
1816249259Sdim  case Instruction::Mul:
1817249259Sdim    assert(C1->getType() == C2->getType() && "Op types should be identical!");
1818249259Sdim    assert(C1->getType()->isIntOrIntVectorTy() &&
1819249259Sdim           "Tried to create an integer operation on a non-integer type!");
1820249259Sdim    break;
1821249259Sdim  case Instruction::FAdd:
1822249259Sdim  case Instruction::FSub:
1823249259Sdim  case Instruction::FMul:
1824249259Sdim    assert(C1->getType() == C2->getType() && "Op types should be identical!");
1825249259Sdim    assert(C1->getType()->isFPOrFPVectorTy() &&
1826249259Sdim           "Tried to create a floating-point operation on a "
1827249259Sdim           "non-floating-point type!");
1828249259Sdim    break;
1829249259Sdim  case Instruction::UDiv:
1830249259Sdim  case Instruction::SDiv:
1831249259Sdim    assert(C1->getType() == C2->getType() && "Op types should be identical!");
1832249259Sdim    assert(C1->getType()->isIntOrIntVectorTy() &&
1833249259Sdim           "Tried to create an arithmetic operation on a non-arithmetic type!");
1834249259Sdim    break;
1835249259Sdim  case Instruction::FDiv:
1836249259Sdim    assert(C1->getType() == C2->getType() && "Op types should be identical!");
1837249259Sdim    assert(C1->getType()->isFPOrFPVectorTy() &&
1838249259Sdim           "Tried to create an arithmetic operation on a non-arithmetic type!");
1839249259Sdim    break;
1840249259Sdim  case Instruction::URem:
1841249259Sdim  case Instruction::SRem:
1842249259Sdim    assert(C1->getType() == C2->getType() && "Op types should be identical!");
1843249259Sdim    assert(C1->getType()->isIntOrIntVectorTy() &&
1844249259Sdim           "Tried to create an arithmetic operation on a non-arithmetic type!");
1845249259Sdim    break;
1846249259Sdim  case Instruction::FRem:
1847249259Sdim    assert(C1->getType() == C2->getType() && "Op types should be identical!");
1848249259Sdim    assert(C1->getType()->isFPOrFPVectorTy() &&
1849249259Sdim           "Tried to create an arithmetic operation on a non-arithmetic type!");
1850249259Sdim    break;
1851249259Sdim  case Instruction::And:
1852249259Sdim  case Instruction::Or:
1853249259Sdim  case Instruction::Xor:
1854249259Sdim    assert(C1->getType() == C2->getType() && "Op types should be identical!");
1855249259Sdim    assert(C1->getType()->isIntOrIntVectorTy() &&
1856249259Sdim           "Tried to create a logical operation on a non-integral type!");
1857249259Sdim    break;
1858249259Sdim  case Instruction::Shl:
1859249259Sdim  case Instruction::LShr:
1860249259Sdim  case Instruction::AShr:
1861249259Sdim    assert(C1->getType() == C2->getType() && "Op types should be identical!");
1862249259Sdim    assert(C1->getType()->isIntOrIntVectorTy() &&
1863249259Sdim           "Tried to create a shift operation on a non-integer type!");
1864249259Sdim    break;
1865249259Sdim  default:
1866249259Sdim    break;
1867249259Sdim  }
1868249259Sdim#endif
1869249259Sdim
1870249259Sdim  if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1871249259Sdim    return FC;          // Fold a few common cases.
1872249259Sdim
1873280031Sdim  if (OnlyIfReducedTy == C1->getType())
1874280031Sdim    return nullptr;
1875280031Sdim
1876249259Sdim  Constant *ArgVec[] = { C1, C2 };
1877280031Sdim  ConstantExprKeyType Key(Opcode, ArgVec, 0, Flags);
1878249259Sdim
1879249259Sdim  LLVMContextImpl *pImpl = C1->getContext().pImpl;
1880249259Sdim  return pImpl->ExprConstants.getOrCreate(C1->getType(), Key);
1881249259Sdim}
1882249259Sdim
1883249259SdimConstant *ConstantExpr::getSizeOf(Type* Ty) {
1884249259Sdim  // sizeof is implemented as: (i64) gep (Ty*)null, 1
1885249259Sdim  // Note that a non-inbounds gep is used, as null isn't within any object.
1886249259Sdim  Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
1887249259Sdim  Constant *GEP = getGetElementPtr(
1888288943Sdim      Ty, Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
1889249259Sdim  return getPtrToInt(GEP,
1890249259Sdim                     Type::getInt64Ty(Ty->getContext()));
1891249259Sdim}
1892249259Sdim
1893249259SdimConstant *ConstantExpr::getAlignOf(Type* Ty) {
1894249259Sdim  // alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1
1895249259Sdim  // Note that a non-inbounds gep is used, as null isn't within any object.
1896249259Sdim  Type *AligningTy =
1897280031Sdim    StructType::get(Type::getInt1Ty(Ty->getContext()), Ty, nullptr);
1898276479Sdim  Constant *NullPtr = Constant::getNullValue(AligningTy->getPointerTo(0));
1899249259Sdim  Constant *Zero = ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0);
1900249259Sdim  Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
1901249259Sdim  Constant *Indices[2] = { Zero, One };
1902288943Sdim  Constant *GEP = getGetElementPtr(AligningTy, NullPtr, Indices);
1903249259Sdim  return getPtrToInt(GEP,
1904249259Sdim                     Type::getInt64Ty(Ty->getContext()));
1905249259Sdim}
1906249259Sdim
1907249259SdimConstant *ConstantExpr::getOffsetOf(StructType* STy, unsigned FieldNo) {
1908249259Sdim  return getOffsetOf(STy, ConstantInt::get(Type::getInt32Ty(STy->getContext()),
1909249259Sdim                                           FieldNo));
1910249259Sdim}
1911249259Sdim
1912249259SdimConstant *ConstantExpr::getOffsetOf(Type* Ty, Constant *FieldNo) {
1913249259Sdim  // offsetof is implemented as: (i64) gep (Ty*)null, 0, FieldNo
1914249259Sdim  // Note that a non-inbounds gep is used, as null isn't within any object.
1915249259Sdim  Constant *GEPIdx[] = {
1916249259Sdim    ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0),
1917249259Sdim    FieldNo
1918249259Sdim  };
1919249259Sdim  Constant *GEP = getGetElementPtr(
1920288943Sdim      Ty, Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
1921249259Sdim  return getPtrToInt(GEP,
1922249259Sdim                     Type::getInt64Ty(Ty->getContext()));
1923249259Sdim}
1924249259Sdim
1925280031SdimConstant *ConstantExpr::getCompare(unsigned short Predicate, Constant *C1,
1926280031Sdim                                   Constant *C2, bool OnlyIfReduced) {
1927249259Sdim  assert(C1->getType() == C2->getType() && "Op types should be identical!");
1928249259Sdim
1929249259Sdim  switch (Predicate) {
1930249259Sdim  default: llvm_unreachable("Invalid CmpInst predicate");
1931249259Sdim  case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
1932249259Sdim  case CmpInst::FCMP_OGE:   case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
1933249259Sdim  case CmpInst::FCMP_ONE:   case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
1934249259Sdim  case CmpInst::FCMP_UEQ:   case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
1935249259Sdim  case CmpInst::FCMP_ULT:   case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
1936249259Sdim  case CmpInst::FCMP_TRUE:
1937280031Sdim    return getFCmp(Predicate, C1, C2, OnlyIfReduced);
1938249259Sdim
1939249259Sdim  case CmpInst::ICMP_EQ:  case CmpInst::ICMP_NE:  case CmpInst::ICMP_UGT:
1940249259Sdim  case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
1941249259Sdim  case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
1942249259Sdim  case CmpInst::ICMP_SLE:
1943280031Sdim    return getICmp(Predicate, C1, C2, OnlyIfReduced);
1944249259Sdim  }
1945249259Sdim}
1946249259Sdim
1947280031SdimConstant *ConstantExpr::getSelect(Constant *C, Constant *V1, Constant *V2,
1948280031Sdim                                  Type *OnlyIfReducedTy) {
1949249259Sdim  assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
1950249259Sdim
1951249259Sdim  if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1952249259Sdim    return SC;        // Fold common cases
1953249259Sdim
1954280031Sdim  if (OnlyIfReducedTy == V1->getType())
1955280031Sdim    return nullptr;
1956280031Sdim
1957249259Sdim  Constant *ArgVec[] = { C, V1, V2 };
1958280031Sdim  ConstantExprKeyType Key(Instruction::Select, ArgVec);
1959249259Sdim
1960249259Sdim  LLVMContextImpl *pImpl = C->getContext().pImpl;
1961249259Sdim  return pImpl->ExprConstants.getOrCreate(V1->getType(), Key);
1962249259Sdim}
1963249259Sdim
1964288943SdimConstant *ConstantExpr::getGetElementPtr(Type *Ty, Constant *C,
1965288943Sdim                                         ArrayRef<Value *> Idxs, bool InBounds,
1966288943Sdim                                         Type *OnlyIfReducedTy) {
1967288943Sdim  if (!Ty)
1968288943Sdim    Ty = cast<PointerType>(C->getType()->getScalarType())->getElementType();
1969288943Sdim  else
1970288943Sdim    assert(
1971288943Sdim        Ty ==
1972288943Sdim        cast<PointerType>(C->getType()->getScalarType())->getContainedType(0u));
1973249259Sdim
1974288943Sdim  if (Constant *FC = ConstantFoldGetElementPtr(Ty, C, InBounds, Idxs))
1975249259Sdim    return FC;          // Fold a few common cases.
1976249259Sdim
1977249259Sdim  // Get the result type of the getelementptr!
1978288943Sdim  Type *DestTy = GetElementPtrInst::getIndexedType(Ty, Idxs);
1979288943Sdim  assert(DestTy && "GEP indices invalid!");
1980249259Sdim  unsigned AS = C->getType()->getPointerAddressSpace();
1981288943Sdim  Type *ReqTy = DestTy->getPointerTo(AS);
1982249259Sdim  if (VectorType *VecTy = dyn_cast<VectorType>(C->getType()))
1983249259Sdim    ReqTy = VectorType::get(ReqTy, VecTy->getNumElements());
1984249259Sdim
1985280031Sdim  if (OnlyIfReducedTy == ReqTy)
1986280031Sdim    return nullptr;
1987280031Sdim
1988249259Sdim  // Look up the constant in the table first to ensure uniqueness
1989249259Sdim  std::vector<Constant*> ArgVec;
1990249259Sdim  ArgVec.reserve(1 + Idxs.size());
1991249259Sdim  ArgVec.push_back(C);
1992249259Sdim  for (unsigned i = 0, e = Idxs.size(); i != e; ++i) {
1993249259Sdim    assert(Idxs[i]->getType()->isVectorTy() == ReqTy->isVectorTy() &&
1994249259Sdim           "getelementptr index type missmatch");
1995249259Sdim    assert((!Idxs[i]->getType()->isVectorTy() ||
1996249259Sdim            ReqTy->getVectorNumElements() ==
1997249259Sdim            Idxs[i]->getType()->getVectorNumElements()) &&
1998249259Sdim           "getelementptr index type missmatch");
1999249259Sdim    ArgVec.push_back(cast<Constant>(Idxs[i]));
2000249259Sdim  }
2001280031Sdim  const ConstantExprKeyType Key(Instruction::GetElementPtr, ArgVec, 0,
2002288943Sdim                                InBounds ? GEPOperator::IsInBounds : 0, None,
2003288943Sdim                                Ty);
2004249259Sdim
2005249259Sdim  LLVMContextImpl *pImpl = C->getContext().pImpl;
2006249259Sdim  return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2007249259Sdim}
2008249259Sdim
2009280031SdimConstant *ConstantExpr::getICmp(unsigned short pred, Constant *LHS,
2010280031Sdim                                Constant *RHS, bool OnlyIfReduced) {
2011249259Sdim  assert(LHS->getType() == RHS->getType());
2012249259Sdim  assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
2013249259Sdim         pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
2014249259Sdim
2015249259Sdim  if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
2016249259Sdim    return FC;          // Fold a few common cases...
2017249259Sdim
2018280031Sdim  if (OnlyIfReduced)
2019280031Sdim    return nullptr;
2020280031Sdim
2021249259Sdim  // Look up the constant in the table first to ensure uniqueness
2022249259Sdim  Constant *ArgVec[] = { LHS, RHS };
2023249259Sdim  // Get the key type with both the opcode and predicate
2024280031Sdim  const ConstantExprKeyType Key(Instruction::ICmp, ArgVec, pred);
2025249259Sdim
2026249259Sdim  Type *ResultTy = Type::getInt1Ty(LHS->getContext());
2027249259Sdim  if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
2028249259Sdim    ResultTy = VectorType::get(ResultTy, VT->getNumElements());
2029249259Sdim
2030249259Sdim  LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
2031249259Sdim  return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
2032249259Sdim}
2033249259Sdim
2034280031SdimConstant *ConstantExpr::getFCmp(unsigned short pred, Constant *LHS,
2035280031Sdim                                Constant *RHS, bool OnlyIfReduced) {
2036249259Sdim  assert(LHS->getType() == RHS->getType());
2037249259Sdim  assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
2038249259Sdim
2039249259Sdim  if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
2040249259Sdim    return FC;          // Fold a few common cases...
2041249259Sdim
2042280031Sdim  if (OnlyIfReduced)
2043280031Sdim    return nullptr;
2044280031Sdim
2045249259Sdim  // Look up the constant in the table first to ensure uniqueness
2046249259Sdim  Constant *ArgVec[] = { LHS, RHS };
2047249259Sdim  // Get the key type with both the opcode and predicate
2048280031Sdim  const ConstantExprKeyType Key(Instruction::FCmp, ArgVec, pred);
2049249259Sdim
2050249259Sdim  Type *ResultTy = Type::getInt1Ty(LHS->getContext());
2051249259Sdim  if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
2052249259Sdim    ResultTy = VectorType::get(ResultTy, VT->getNumElements());
2053249259Sdim
2054249259Sdim  LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
2055249259Sdim  return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
2056249259Sdim}
2057249259Sdim
2058280031SdimConstant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx,
2059280031Sdim                                          Type *OnlyIfReducedTy) {
2060249259Sdim  assert(Val->getType()->isVectorTy() &&
2061249259Sdim         "Tried to create extractelement operation on non-vector type!");
2062276479Sdim  assert(Idx->getType()->isIntegerTy() &&
2063276479Sdim         "Extractelement index must be an integer type!");
2064249259Sdim
2065249259Sdim  if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
2066249259Sdim    return FC;          // Fold a few common cases.
2067249259Sdim
2068280031Sdim  Type *ReqTy = Val->getType()->getVectorElementType();
2069280031Sdim  if (OnlyIfReducedTy == ReqTy)
2070280031Sdim    return nullptr;
2071280031Sdim
2072249259Sdim  // Look up the constant in the table first to ensure uniqueness
2073249259Sdim  Constant *ArgVec[] = { Val, Idx };
2074280031Sdim  const ConstantExprKeyType Key(Instruction::ExtractElement, ArgVec);
2075249259Sdim
2076249259Sdim  LLVMContextImpl *pImpl = Val->getContext().pImpl;
2077249259Sdim  return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2078249259Sdim}
2079249259Sdim
2080280031SdimConstant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
2081280031Sdim                                         Constant *Idx, Type *OnlyIfReducedTy) {
2082249259Sdim  assert(Val->getType()->isVectorTy() &&
2083249259Sdim         "Tried to create insertelement operation on non-vector type!");
2084249259Sdim  assert(Elt->getType() == Val->getType()->getVectorElementType() &&
2085249259Sdim         "Insertelement types must match!");
2086276479Sdim  assert(Idx->getType()->isIntegerTy() &&
2087249259Sdim         "Insertelement index must be i32 type!");
2088249259Sdim
2089249259Sdim  if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
2090249259Sdim    return FC;          // Fold a few common cases.
2091280031Sdim
2092280031Sdim  if (OnlyIfReducedTy == Val->getType())
2093280031Sdim    return nullptr;
2094280031Sdim
2095249259Sdim  // Look up the constant in the table first to ensure uniqueness
2096249259Sdim  Constant *ArgVec[] = { Val, Elt, Idx };
2097280031Sdim  const ConstantExprKeyType Key(Instruction::InsertElement, ArgVec);
2098249259Sdim
2099249259Sdim  LLVMContextImpl *pImpl = Val->getContext().pImpl;
2100249259Sdim  return pImpl->ExprConstants.getOrCreate(Val->getType(), Key);
2101249259Sdim}
2102249259Sdim
2103280031SdimConstant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
2104280031Sdim                                         Constant *Mask, Type *OnlyIfReducedTy) {
2105249259Sdim  assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
2106249259Sdim         "Invalid shuffle vector constant expr operands!");
2107249259Sdim
2108249259Sdim  if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
2109249259Sdim    return FC;          // Fold a few common cases.
2110249259Sdim
2111249259Sdim  unsigned NElts = Mask->getType()->getVectorNumElements();
2112249259Sdim  Type *EltTy = V1->getType()->getVectorElementType();
2113249259Sdim  Type *ShufTy = VectorType::get(EltTy, NElts);
2114249259Sdim
2115280031Sdim  if (OnlyIfReducedTy == ShufTy)
2116280031Sdim    return nullptr;
2117280031Sdim
2118249259Sdim  // Look up the constant in the table first to ensure uniqueness
2119249259Sdim  Constant *ArgVec[] = { V1, V2, Mask };
2120280031Sdim  const ConstantExprKeyType Key(Instruction::ShuffleVector, ArgVec);
2121249259Sdim
2122249259Sdim  LLVMContextImpl *pImpl = ShufTy->getContext().pImpl;
2123249259Sdim  return pImpl->ExprConstants.getOrCreate(ShufTy, Key);
2124249259Sdim}
2125249259Sdim
2126249259SdimConstant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
2127280031Sdim                                       ArrayRef<unsigned> Idxs,
2128280031Sdim                                       Type *OnlyIfReducedTy) {
2129261991Sdim  assert(Agg->getType()->isFirstClassType() &&
2130261991Sdim         "Non-first-class type for constant insertvalue expression");
2131261991Sdim
2132249259Sdim  assert(ExtractValueInst::getIndexedType(Agg->getType(),
2133249259Sdim                                          Idxs) == Val->getType() &&
2134249259Sdim         "insertvalue indices invalid!");
2135261991Sdim  Type *ReqTy = Val->getType();
2136261991Sdim
2137261991Sdim  if (Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs))
2138261991Sdim    return FC;
2139261991Sdim
2140280031Sdim  if (OnlyIfReducedTy == ReqTy)
2141280031Sdim    return nullptr;
2142280031Sdim
2143261991Sdim  Constant *ArgVec[] = { Agg, Val };
2144280031Sdim  const ConstantExprKeyType Key(Instruction::InsertValue, ArgVec, 0, 0, Idxs);
2145261991Sdim
2146261991Sdim  LLVMContextImpl *pImpl = Agg->getContext().pImpl;
2147261991Sdim  return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2148249259Sdim}
2149249259Sdim
2150280031SdimConstant *ConstantExpr::getExtractValue(Constant *Agg, ArrayRef<unsigned> Idxs,
2151280031Sdim                                        Type *OnlyIfReducedTy) {
2152249259Sdim  assert(Agg->getType()->isFirstClassType() &&
2153249259Sdim         "Tried to create extractelement operation on non-first-class type!");
2154249259Sdim
2155249259Sdim  Type *ReqTy = ExtractValueInst::getIndexedType(Agg->getType(), Idxs);
2156249259Sdim  (void)ReqTy;
2157249259Sdim  assert(ReqTy && "extractvalue indices invalid!");
2158249259Sdim
2159249259Sdim  assert(Agg->getType()->isFirstClassType() &&
2160249259Sdim         "Non-first-class type for constant extractvalue expression");
2161261991Sdim  if (Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs))
2162261991Sdim    return FC;
2163261991Sdim
2164280031Sdim  if (OnlyIfReducedTy == ReqTy)
2165280031Sdim    return nullptr;
2166280031Sdim
2167261991Sdim  Constant *ArgVec[] = { Agg };
2168280031Sdim  const ConstantExprKeyType Key(Instruction::ExtractValue, ArgVec, 0, 0, Idxs);
2169261991Sdim
2170261991Sdim  LLVMContextImpl *pImpl = Agg->getContext().pImpl;
2171261991Sdim  return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2172249259Sdim}
2173249259Sdim
2174249259SdimConstant *ConstantExpr::getNeg(Constant *C, bool HasNUW, bool HasNSW) {
2175249259Sdim  assert(C->getType()->isIntOrIntVectorTy() &&
2176249259Sdim         "Cannot NEG a nonintegral value!");
2177249259Sdim  return getSub(ConstantFP::getZeroValueForNegation(C->getType()),
2178249259Sdim                C, HasNUW, HasNSW);
2179249259Sdim}
2180249259Sdim
2181249259SdimConstant *ConstantExpr::getFNeg(Constant *C) {
2182249259Sdim  assert(C->getType()->isFPOrFPVectorTy() &&
2183249259Sdim         "Cannot FNEG a non-floating-point value!");
2184249259Sdim  return getFSub(ConstantFP::getZeroValueForNegation(C->getType()), C);
2185249259Sdim}
2186249259Sdim
2187249259SdimConstant *ConstantExpr::getNot(Constant *C) {
2188249259Sdim  assert(C->getType()->isIntOrIntVectorTy() &&
2189249259Sdim         "Cannot NOT a nonintegral value!");
2190249259Sdim  return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
2191249259Sdim}
2192249259Sdim
2193249259SdimConstant *ConstantExpr::getAdd(Constant *C1, Constant *C2,
2194249259Sdim                               bool HasNUW, bool HasNSW) {
2195249259Sdim  unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2196249259Sdim                   (HasNSW ? OverflowingBinaryOperator::NoSignedWrap   : 0);
2197249259Sdim  return get(Instruction::Add, C1, C2, Flags);
2198249259Sdim}
2199249259Sdim
2200249259SdimConstant *ConstantExpr::getFAdd(Constant *C1, Constant *C2) {
2201249259Sdim  return get(Instruction::FAdd, C1, C2);
2202249259Sdim}
2203249259Sdim
2204249259SdimConstant *ConstantExpr::getSub(Constant *C1, Constant *C2,
2205249259Sdim                               bool HasNUW, bool HasNSW) {
2206249259Sdim  unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2207249259Sdim                   (HasNSW ? OverflowingBinaryOperator::NoSignedWrap   : 0);
2208249259Sdim  return get(Instruction::Sub, C1, C2, Flags);
2209249259Sdim}
2210249259Sdim
2211249259SdimConstant *ConstantExpr::getFSub(Constant *C1, Constant *C2) {
2212249259Sdim  return get(Instruction::FSub, C1, C2);
2213249259Sdim}
2214249259Sdim
2215249259SdimConstant *ConstantExpr::getMul(Constant *C1, Constant *C2,
2216249259Sdim                               bool HasNUW, bool HasNSW) {
2217249259Sdim  unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2218249259Sdim                   (HasNSW ? OverflowingBinaryOperator::NoSignedWrap   : 0);
2219249259Sdim  return get(Instruction::Mul, C1, C2, Flags);
2220249259Sdim}
2221249259Sdim
2222249259SdimConstant *ConstantExpr::getFMul(Constant *C1, Constant *C2) {
2223249259Sdim  return get(Instruction::FMul, C1, C2);
2224249259Sdim}
2225249259Sdim
2226249259SdimConstant *ConstantExpr::getUDiv(Constant *C1, Constant *C2, bool isExact) {
2227249259Sdim  return get(Instruction::UDiv, C1, C2,
2228249259Sdim             isExact ? PossiblyExactOperator::IsExact : 0);
2229249259Sdim}
2230249259Sdim
2231249259SdimConstant *ConstantExpr::getSDiv(Constant *C1, Constant *C2, bool isExact) {
2232249259Sdim  return get(Instruction::SDiv, C1, C2,
2233249259Sdim             isExact ? PossiblyExactOperator::IsExact : 0);
2234249259Sdim}
2235249259Sdim
2236249259SdimConstant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
2237249259Sdim  return get(Instruction::FDiv, C1, C2);
2238249259Sdim}
2239249259Sdim
2240249259SdimConstant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
2241249259Sdim  return get(Instruction::URem, C1, C2);
2242249259Sdim}
2243249259Sdim
2244249259SdimConstant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
2245249259Sdim  return get(Instruction::SRem, C1, C2);
2246249259Sdim}
2247249259Sdim
2248249259SdimConstant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
2249249259Sdim  return get(Instruction::FRem, C1, C2);
2250249259Sdim}
2251249259Sdim
2252249259SdimConstant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
2253249259Sdim  return get(Instruction::And, C1, C2);
2254249259Sdim}
2255249259Sdim
2256249259SdimConstant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
2257249259Sdim  return get(Instruction::Or, C1, C2);
2258249259Sdim}
2259249259Sdim
2260249259SdimConstant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
2261249259Sdim  return get(Instruction::Xor, C1, C2);
2262249259Sdim}
2263249259Sdim
2264249259SdimConstant *ConstantExpr::getShl(Constant *C1, Constant *C2,
2265249259Sdim                               bool HasNUW, bool HasNSW) {
2266249259Sdim  unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2267249259Sdim                   (HasNSW ? OverflowingBinaryOperator::NoSignedWrap   : 0);
2268249259Sdim  return get(Instruction::Shl, C1, C2, Flags);
2269249259Sdim}
2270249259Sdim
2271249259SdimConstant *ConstantExpr::getLShr(Constant *C1, Constant *C2, bool isExact) {
2272249259Sdim  return get(Instruction::LShr, C1, C2,
2273249259Sdim             isExact ? PossiblyExactOperator::IsExact : 0);
2274249259Sdim}
2275249259Sdim
2276249259SdimConstant *ConstantExpr::getAShr(Constant *C1, Constant *C2, bool isExact) {
2277249259Sdim  return get(Instruction::AShr, C1, C2,
2278249259Sdim             isExact ? PossiblyExactOperator::IsExact : 0);
2279249259Sdim}
2280249259Sdim
2281249259Sdim/// getBinOpIdentity - Return the identity for the given binary operation,
2282249259Sdim/// i.e. a constant C such that X op C = X and C op X = X for every X.  It
2283249259Sdim/// returns null if the operator doesn't have an identity.
2284249259SdimConstant *ConstantExpr::getBinOpIdentity(unsigned Opcode, Type *Ty) {
2285249259Sdim  switch (Opcode) {
2286249259Sdim  default:
2287249259Sdim    // Doesn't have an identity.
2288276479Sdim    return nullptr;
2289249259Sdim
2290249259Sdim  case Instruction::Add:
2291249259Sdim  case Instruction::Or:
2292249259Sdim  case Instruction::Xor:
2293249259Sdim    return Constant::getNullValue(Ty);
2294249259Sdim
2295249259Sdim  case Instruction::Mul:
2296249259Sdim    return ConstantInt::get(Ty, 1);
2297249259Sdim
2298249259Sdim  case Instruction::And:
2299249259Sdim    return Constant::getAllOnesValue(Ty);
2300249259Sdim  }
2301249259Sdim}
2302249259Sdim
2303249259Sdim/// getBinOpAbsorber - Return the absorbing element for the given binary
2304249259Sdim/// operation, i.e. a constant C such that X op C = C and C op X = C for
2305249259Sdim/// every X.  For example, this returns zero for integer multiplication.
2306249259Sdim/// It returns null if the operator doesn't have an absorbing element.
2307249259SdimConstant *ConstantExpr::getBinOpAbsorber(unsigned Opcode, Type *Ty) {
2308249259Sdim  switch (Opcode) {
2309249259Sdim  default:
2310249259Sdim    // Doesn't have an absorber.
2311276479Sdim    return nullptr;
2312249259Sdim
2313249259Sdim  case Instruction::Or:
2314249259Sdim    return Constant::getAllOnesValue(Ty);
2315249259Sdim
2316249259Sdim  case Instruction::And:
2317249259Sdim  case Instruction::Mul:
2318249259Sdim    return Constant::getNullValue(Ty);
2319249259Sdim  }
2320249259Sdim}
2321249259Sdim
2322249259Sdim// destroyConstant - Remove the constant from the constant table...
2323249259Sdim//
2324288943Sdimvoid ConstantExpr::destroyConstantImpl() {
2325249259Sdim  getType()->getContext().pImpl->ExprConstants.remove(this);
2326249259Sdim}
2327249259Sdim
2328249259Sdimconst char *ConstantExpr::getOpcodeName() const {
2329249259Sdim  return Instruction::getOpcodeName(getOpcode());
2330249259Sdim}
2331249259Sdim
2332288943SdimGetElementPtrConstantExpr::GetElementPtrConstantExpr(
2333288943Sdim    Type *SrcElementTy, Constant *C, ArrayRef<Constant *> IdxList, Type *DestTy)
2334288943Sdim    : ConstantExpr(DestTy, Instruction::GetElementPtr,
2335288943Sdim                   OperandTraits<GetElementPtrConstantExpr>::op_end(this) -
2336288943Sdim                       (IdxList.size() + 1),
2337288943Sdim                   IdxList.size() + 1),
2338288943Sdim      SrcElementTy(SrcElementTy) {
2339288943Sdim  Op<0>() = C;
2340288943Sdim  Use *OperandList = getOperandList();
2341249259Sdim  for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
2342249259Sdim    OperandList[i+1] = IdxList[i];
2343249259Sdim}
2344249259Sdim
2345288943SdimType *GetElementPtrConstantExpr::getSourceElementType() const {
2346288943Sdim  return SrcElementTy;
2347288943Sdim}
2348288943Sdim
2349249259Sdim//===----------------------------------------------------------------------===//
2350249259Sdim//                       ConstantData* implementations
2351249259Sdim
2352249259Sdimvoid ConstantDataArray::anchor() {}
2353249259Sdimvoid ConstantDataVector::anchor() {}
2354249259Sdim
2355249259Sdim/// getElementType - Return the element type of the array/vector.
2356249259SdimType *ConstantDataSequential::getElementType() const {
2357249259Sdim  return getType()->getElementType();
2358249259Sdim}
2359249259Sdim
2360249259SdimStringRef ConstantDataSequential::getRawDataValues() const {
2361249259Sdim  return StringRef(DataElements, getNumElements()*getElementByteSize());
2362249259Sdim}
2363249259Sdim
2364249259Sdim/// isElementTypeCompatible - Return true if a ConstantDataSequential can be
2365249259Sdim/// formed with a vector or array of the specified element type.
2366249259Sdim/// ConstantDataArray only works with normal float and int types that are
2367249259Sdim/// stored densely in memory, not with things like i42 or x86_f80.
2368296417Sdimbool ConstantDataSequential::isElementTypeCompatible(Type *Ty) {
2369296417Sdim  if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) return true;
2370296417Sdim  if (auto *IT = dyn_cast<IntegerType>(Ty)) {
2371249259Sdim    switch (IT->getBitWidth()) {
2372249259Sdim    case 8:
2373249259Sdim    case 16:
2374249259Sdim    case 32:
2375249259Sdim    case 64:
2376249259Sdim      return true;
2377249259Sdim    default: break;
2378249259Sdim    }
2379249259Sdim  }
2380249259Sdim  return false;
2381249259Sdim}
2382249259Sdim
2383249259Sdim/// getNumElements - Return the number of elements in the array or vector.
2384249259Sdimunsigned ConstantDataSequential::getNumElements() const {
2385249259Sdim  if (ArrayType *AT = dyn_cast<ArrayType>(getType()))
2386249259Sdim    return AT->getNumElements();
2387249259Sdim  return getType()->getVectorNumElements();
2388249259Sdim}
2389249259Sdim
2390249259Sdim
2391249259Sdim/// getElementByteSize - Return the size in bytes of the elements in the data.
2392249259Sdimuint64_t ConstantDataSequential::getElementByteSize() const {
2393249259Sdim  return getElementType()->getPrimitiveSizeInBits()/8;
2394249259Sdim}
2395249259Sdim
2396249259Sdim/// getElementPointer - Return the start of the specified element.
2397249259Sdimconst char *ConstantDataSequential::getElementPointer(unsigned Elt) const {
2398249259Sdim  assert(Elt < getNumElements() && "Invalid Elt");
2399249259Sdim  return DataElements+Elt*getElementByteSize();
2400249259Sdim}
2401249259Sdim
2402249259Sdim
2403249259Sdim/// isAllZeros - return true if the array is empty or all zeros.
2404249259Sdimstatic bool isAllZeros(StringRef Arr) {
2405249259Sdim  for (StringRef::iterator I = Arr.begin(), E = Arr.end(); I != E; ++I)
2406249259Sdim    if (*I != 0)
2407249259Sdim      return false;
2408249259Sdim  return true;
2409249259Sdim}
2410249259Sdim
2411249259Sdim/// getImpl - This is the underlying implementation of all of the
2412249259Sdim/// ConstantDataSequential::get methods.  They all thunk down to here, providing
2413249259Sdim/// the correct element type.  We take the bytes in as a StringRef because
2414249259Sdim/// we *want* an underlying "char*" to avoid TBAA type punning violations.
2415249259SdimConstant *ConstantDataSequential::getImpl(StringRef Elements, Type *Ty) {
2416249259Sdim  assert(isElementTypeCompatible(Ty->getSequentialElementType()));
2417249259Sdim  // If the elements are all zero or there are no elements, return a CAZ, which
2418249259Sdim  // is more dense and canonical.
2419249259Sdim  if (isAllZeros(Elements))
2420249259Sdim    return ConstantAggregateZero::get(Ty);
2421249259Sdim
2422249259Sdim  // Do a lookup to see if we have already formed one of these.
2423280031Sdim  auto &Slot =
2424280031Sdim      *Ty->getContext()
2425280031Sdim           .pImpl->CDSConstants.insert(std::make_pair(Elements, nullptr))
2426280031Sdim           .first;
2427249259Sdim
2428249259Sdim  // The bucket can point to a linked list of different CDS's that have the same
2429249259Sdim  // body but different types.  For example, 0,0,0,1 could be a 4 element array
2430249259Sdim  // of i8, or a 1-element array of i32.  They'll both end up in the same
2431249259Sdim  /// StringMap bucket, linked up by their Next pointers.  Walk the list.
2432280031Sdim  ConstantDataSequential **Entry = &Slot.second;
2433276479Sdim  for (ConstantDataSequential *Node = *Entry; Node;
2434249259Sdim       Entry = &Node->Next, Node = *Entry)
2435249259Sdim    if (Node->getType() == Ty)
2436249259Sdim      return Node;
2437249259Sdim
2438249259Sdim  // Okay, we didn't get a hit.  Create a node of the right class, link it in,
2439249259Sdim  // and return it.
2440249259Sdim  if (isa<ArrayType>(Ty))
2441280031Sdim    return *Entry = new ConstantDataArray(Ty, Slot.first().data());
2442249259Sdim
2443249259Sdim  assert(isa<VectorType>(Ty));
2444280031Sdim  return *Entry = new ConstantDataVector(Ty, Slot.first().data());
2445249259Sdim}
2446249259Sdim
2447288943Sdimvoid ConstantDataSequential::destroyConstantImpl() {
2448249259Sdim  // Remove the constant from the StringMap.
2449249259Sdim  StringMap<ConstantDataSequential*> &CDSConstants =
2450249259Sdim    getType()->getContext().pImpl->CDSConstants;
2451249259Sdim
2452249259Sdim  StringMap<ConstantDataSequential*>::iterator Slot =
2453249259Sdim    CDSConstants.find(getRawDataValues());
2454249259Sdim
2455249259Sdim  assert(Slot != CDSConstants.end() && "CDS not found in uniquing table");
2456249259Sdim
2457249259Sdim  ConstantDataSequential **Entry = &Slot->getValue();
2458249259Sdim
2459249259Sdim  // Remove the entry from the hash table.
2460276479Sdim  if (!(*Entry)->Next) {
2461249259Sdim    // If there is only one value in the bucket (common case) it must be this
2462249259Sdim    // entry, and removing the entry should remove the bucket completely.
2463249259Sdim    assert((*Entry) == this && "Hash mismatch in ConstantDataSequential");
2464249259Sdim    getContext().pImpl->CDSConstants.erase(Slot);
2465249259Sdim  } else {
2466249259Sdim    // Otherwise, there are multiple entries linked off the bucket, unlink the
2467249259Sdim    // node we care about but keep the bucket around.
2468249259Sdim    for (ConstantDataSequential *Node = *Entry; ;
2469249259Sdim         Entry = &Node->Next, Node = *Entry) {
2470249259Sdim      assert(Node && "Didn't find entry in its uniquing hash table!");
2471249259Sdim      // If we found our entry, unlink it from the list and we're done.
2472249259Sdim      if (Node == this) {
2473249259Sdim        *Entry = Node->Next;
2474249259Sdim        break;
2475249259Sdim      }
2476249259Sdim    }
2477249259Sdim  }
2478249259Sdim
2479249259Sdim  // If we were part of a list, make sure that we don't delete the list that is
2480249259Sdim  // still owned by the uniquing map.
2481276479Sdim  Next = nullptr;
2482249259Sdim}
2483249259Sdim
2484249259Sdim/// get() constructors - Return a constant with array type with an element
2485249259Sdim/// count and element type matching the ArrayRef passed in.  Note that this
2486249259Sdim/// can return a ConstantAggregateZero object.
2487249259SdimConstant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint8_t> Elts) {
2488249259Sdim  Type *Ty = ArrayType::get(Type::getInt8Ty(Context), Elts.size());
2489249259Sdim  const char *Data = reinterpret_cast<const char *>(Elts.data());
2490249259Sdim  return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*1), Ty);
2491249259Sdim}
2492249259SdimConstant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint16_t> Elts){
2493249259Sdim  Type *Ty = ArrayType::get(Type::getInt16Ty(Context), Elts.size());
2494249259Sdim  const char *Data = reinterpret_cast<const char *>(Elts.data());
2495249259Sdim  return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*2), Ty);
2496249259Sdim}
2497249259SdimConstant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint32_t> Elts){
2498249259Sdim  Type *Ty = ArrayType::get(Type::getInt32Ty(Context), Elts.size());
2499249259Sdim  const char *Data = reinterpret_cast<const char *>(Elts.data());
2500249259Sdim  return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
2501249259Sdim}
2502249259SdimConstant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint64_t> Elts){
2503249259Sdim  Type *Ty = ArrayType::get(Type::getInt64Ty(Context), Elts.size());
2504249259Sdim  const char *Data = reinterpret_cast<const char *>(Elts.data());
2505249259Sdim  return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*8), Ty);
2506249259Sdim}
2507249259SdimConstant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<float> Elts) {
2508249259Sdim  Type *Ty = ArrayType::get(Type::getFloatTy(Context), Elts.size());
2509249259Sdim  const char *Data = reinterpret_cast<const char *>(Elts.data());
2510249259Sdim  return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
2511249259Sdim}
2512249259SdimConstant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<double> Elts) {
2513249259Sdim  Type *Ty = ArrayType::get(Type::getDoubleTy(Context), Elts.size());
2514249259Sdim  const char *Data = reinterpret_cast<const char *>(Elts.data());
2515288943Sdim  return getImpl(StringRef(const_cast<char *>(Data), Elts.size() * 8), Ty);
2516249259Sdim}
2517249259Sdim
2518288943Sdim/// getFP() constructors - Return a constant with array type with an element
2519288943Sdim/// count and element type of float with precision matching the number of
2520288943Sdim/// bits in the ArrayRef passed in. (i.e. half for 16bits, float for 32bits,
2521288943Sdim/// double for 64bits) Note that this can return a ConstantAggregateZero
2522288943Sdim/// object.
2523288943SdimConstant *ConstantDataArray::getFP(LLVMContext &Context,
2524288943Sdim                                   ArrayRef<uint16_t> Elts) {
2525296417Sdim  Type *Ty = ArrayType::get(Type::getHalfTy(Context), Elts.size());
2526288943Sdim  const char *Data = reinterpret_cast<const char *>(Elts.data());
2527288943Sdim  return getImpl(StringRef(const_cast<char *>(Data), Elts.size() * 2), Ty);
2528288943Sdim}
2529288943SdimConstant *ConstantDataArray::getFP(LLVMContext &Context,
2530288943Sdim                                   ArrayRef<uint32_t> Elts) {
2531288943Sdim  Type *Ty = ArrayType::get(Type::getFloatTy(Context), Elts.size());
2532288943Sdim  const char *Data = reinterpret_cast<const char *>(Elts.data());
2533288943Sdim  return getImpl(StringRef(const_cast<char *>(Data), Elts.size() * 4), Ty);
2534288943Sdim}
2535288943SdimConstant *ConstantDataArray::getFP(LLVMContext &Context,
2536288943Sdim                                   ArrayRef<uint64_t> Elts) {
2537288943Sdim  Type *Ty = ArrayType::get(Type::getDoubleTy(Context), Elts.size());
2538288943Sdim  const char *Data = reinterpret_cast<const char *>(Elts.data());
2539288943Sdim  return getImpl(StringRef(const_cast<char *>(Data), Elts.size() * 8), Ty);
2540288943Sdim}
2541288943Sdim
2542249259Sdim/// getString - This method constructs a CDS and initializes it with a text
2543249259Sdim/// string. The default behavior (AddNull==true) causes a null terminator to
2544249259Sdim/// be placed at the end of the array (increasing the length of the string by
2545249259Sdim/// one more than the StringRef would normally indicate.  Pass AddNull=false
2546249259Sdim/// to disable this behavior.
2547249259SdimConstant *ConstantDataArray::getString(LLVMContext &Context,
2548249259Sdim                                       StringRef Str, bool AddNull) {
2549249259Sdim  if (!AddNull) {
2550249259Sdim    const uint8_t *Data = reinterpret_cast<const uint8_t *>(Str.data());
2551280031Sdim    return get(Context, makeArrayRef(const_cast<uint8_t *>(Data),
2552249259Sdim               Str.size()));
2553249259Sdim  }
2554249259Sdim
2555249259Sdim  SmallVector<uint8_t, 64> ElementVals;
2556249259Sdim  ElementVals.append(Str.begin(), Str.end());
2557249259Sdim  ElementVals.push_back(0);
2558249259Sdim  return get(Context, ElementVals);
2559249259Sdim}
2560249259Sdim
2561249259Sdim/// get() constructors - Return a constant with vector type with an element
2562249259Sdim/// count and element type matching the ArrayRef passed in.  Note that this
2563249259Sdim/// can return a ConstantAggregateZero object.
2564249259SdimConstant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint8_t> Elts){
2565249259Sdim  Type *Ty = VectorType::get(Type::getInt8Ty(Context), Elts.size());
2566249259Sdim  const char *Data = reinterpret_cast<const char *>(Elts.data());
2567249259Sdim  return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*1), Ty);
2568249259Sdim}
2569249259SdimConstant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint16_t> Elts){
2570249259Sdim  Type *Ty = VectorType::get(Type::getInt16Ty(Context), Elts.size());
2571249259Sdim  const char *Data = reinterpret_cast<const char *>(Elts.data());
2572249259Sdim  return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*2), Ty);
2573249259Sdim}
2574249259SdimConstant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint32_t> Elts){
2575249259Sdim  Type *Ty = VectorType::get(Type::getInt32Ty(Context), Elts.size());
2576249259Sdim  const char *Data = reinterpret_cast<const char *>(Elts.data());
2577249259Sdim  return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
2578249259Sdim}
2579249259SdimConstant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint64_t> Elts){
2580249259Sdim  Type *Ty = VectorType::get(Type::getInt64Ty(Context), Elts.size());
2581249259Sdim  const char *Data = reinterpret_cast<const char *>(Elts.data());
2582249259Sdim  return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*8), Ty);
2583249259Sdim}
2584249259SdimConstant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<float> Elts) {
2585249259Sdim  Type *Ty = VectorType::get(Type::getFloatTy(Context), Elts.size());
2586249259Sdim  const char *Data = reinterpret_cast<const char *>(Elts.data());
2587249259Sdim  return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
2588249259Sdim}
2589249259SdimConstant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<double> Elts) {
2590249259Sdim  Type *Ty = VectorType::get(Type::getDoubleTy(Context), Elts.size());
2591249259Sdim  const char *Data = reinterpret_cast<const char *>(Elts.data());
2592288943Sdim  return getImpl(StringRef(const_cast<char *>(Data), Elts.size() * 8), Ty);
2593249259Sdim}
2594249259Sdim
2595288943Sdim/// getFP() constructors - Return a constant with vector type with an element
2596288943Sdim/// count and element type of float with the precision matching the number of
2597288943Sdim/// bits in the ArrayRef passed in.  (i.e. half for 16bits, float for 32bits,
2598288943Sdim/// double for 64bits) Note that this can return a ConstantAggregateZero
2599288943Sdim/// object.
2600288943SdimConstant *ConstantDataVector::getFP(LLVMContext &Context,
2601288943Sdim                                    ArrayRef<uint16_t> Elts) {
2602288943Sdim  Type *Ty = VectorType::get(Type::getHalfTy(Context), Elts.size());
2603288943Sdim  const char *Data = reinterpret_cast<const char *>(Elts.data());
2604288943Sdim  return getImpl(StringRef(const_cast<char *>(Data), Elts.size() * 2), Ty);
2605288943Sdim}
2606288943SdimConstant *ConstantDataVector::getFP(LLVMContext &Context,
2607288943Sdim                                    ArrayRef<uint32_t> Elts) {
2608288943Sdim  Type *Ty = VectorType::get(Type::getFloatTy(Context), Elts.size());
2609288943Sdim  const char *Data = reinterpret_cast<const char *>(Elts.data());
2610288943Sdim  return getImpl(StringRef(const_cast<char *>(Data), Elts.size() * 4), Ty);
2611288943Sdim}
2612288943SdimConstant *ConstantDataVector::getFP(LLVMContext &Context,
2613288943Sdim                                    ArrayRef<uint64_t> Elts) {
2614288943Sdim  Type *Ty = VectorType::get(Type::getDoubleTy(Context), Elts.size());
2615288943Sdim  const char *Data = reinterpret_cast<const char *>(Elts.data());
2616288943Sdim  return getImpl(StringRef(const_cast<char *>(Data), Elts.size() * 8), Ty);
2617288943Sdim}
2618288943Sdim
2619249259SdimConstant *ConstantDataVector::getSplat(unsigned NumElts, Constant *V) {
2620249259Sdim  assert(isElementTypeCompatible(V->getType()) &&
2621249259Sdim         "Element type not compatible with ConstantData");
2622249259Sdim  if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
2623249259Sdim    if (CI->getType()->isIntegerTy(8)) {
2624249259Sdim      SmallVector<uint8_t, 16> Elts(NumElts, CI->getZExtValue());
2625249259Sdim      return get(V->getContext(), Elts);
2626249259Sdim    }
2627249259Sdim    if (CI->getType()->isIntegerTy(16)) {
2628249259Sdim      SmallVector<uint16_t, 16> Elts(NumElts, CI->getZExtValue());
2629249259Sdim      return get(V->getContext(), Elts);
2630249259Sdim    }
2631249259Sdim    if (CI->getType()->isIntegerTy(32)) {
2632249259Sdim      SmallVector<uint32_t, 16> Elts(NumElts, CI->getZExtValue());
2633249259Sdim      return get(V->getContext(), Elts);
2634249259Sdim    }
2635249259Sdim    assert(CI->getType()->isIntegerTy(64) && "Unsupported ConstantData type");
2636249259Sdim    SmallVector<uint64_t, 16> Elts(NumElts, CI->getZExtValue());
2637249259Sdim    return get(V->getContext(), Elts);
2638249259Sdim  }
2639249259Sdim
2640249259Sdim  if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
2641296417Sdim    if (CFP->getType()->isHalfTy()) {
2642296417Sdim      SmallVector<uint16_t, 16> Elts(
2643296417Sdim          NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
2644296417Sdim      return getFP(V->getContext(), Elts);
2645296417Sdim    }
2646249259Sdim    if (CFP->getType()->isFloatTy()) {
2647288943Sdim      SmallVector<uint32_t, 16> Elts(
2648288943Sdim          NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
2649288943Sdim      return getFP(V->getContext(), Elts);
2650249259Sdim    }
2651249259Sdim    if (CFP->getType()->isDoubleTy()) {
2652288943Sdim      SmallVector<uint64_t, 16> Elts(
2653288943Sdim          NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
2654288943Sdim      return getFP(V->getContext(), Elts);
2655249259Sdim    }
2656249259Sdim  }
2657249259Sdim  return ConstantVector::getSplat(NumElts, V);
2658249259Sdim}
2659249259Sdim
2660249259Sdim
2661249259Sdim/// getElementAsInteger - If this is a sequential container of integers (of
2662249259Sdim/// any size), return the specified element in the low bits of a uint64_t.
2663249259Sdimuint64_t ConstantDataSequential::getElementAsInteger(unsigned Elt) const {
2664249259Sdim  assert(isa<IntegerType>(getElementType()) &&
2665249259Sdim         "Accessor can only be used when element is an integer");
2666249259Sdim  const char *EltPtr = getElementPointer(Elt);
2667249259Sdim
2668249259Sdim  // The data is stored in host byte order, make sure to cast back to the right
2669249259Sdim  // type to load with the right endianness.
2670249259Sdim  switch (getElementType()->getIntegerBitWidth()) {
2671249259Sdim  default: llvm_unreachable("Invalid bitwidth for CDS");
2672249259Sdim  case 8:
2673249259Sdim    return *const_cast<uint8_t *>(reinterpret_cast<const uint8_t *>(EltPtr));
2674249259Sdim  case 16:
2675249259Sdim    return *const_cast<uint16_t *>(reinterpret_cast<const uint16_t *>(EltPtr));
2676249259Sdim  case 32:
2677249259Sdim    return *const_cast<uint32_t *>(reinterpret_cast<const uint32_t *>(EltPtr));
2678249259Sdim  case 64:
2679249259Sdim    return *const_cast<uint64_t *>(reinterpret_cast<const uint64_t *>(EltPtr));
2680249259Sdim  }
2681249259Sdim}
2682249259Sdim
2683249259Sdim/// getElementAsAPFloat - If this is a sequential container of floating point
2684249259Sdim/// type, return the specified element as an APFloat.
2685249259SdimAPFloat ConstantDataSequential::getElementAsAPFloat(unsigned Elt) const {
2686249259Sdim  const char *EltPtr = getElementPointer(Elt);
2687249259Sdim
2688249259Sdim  switch (getElementType()->getTypeID()) {
2689249259Sdim  default:
2690249259Sdim    llvm_unreachable("Accessor can only be used when element is float/double!");
2691296417Sdim  case Type::HalfTyID: {
2692296417Sdim    auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
2693296417Sdim    return APFloat(APFloat::IEEEhalf, APInt(16, EltVal));
2694296417Sdim  }
2695249259Sdim  case Type::FloatTyID: {
2696288943Sdim    auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr);
2697288943Sdim    return APFloat(APFloat::IEEEsingle, APInt(32, EltVal));
2698288943Sdim  }
2699249259Sdim  case Type::DoubleTyID: {
2700288943Sdim    auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr);
2701288943Sdim    return APFloat(APFloat::IEEEdouble, APInt(64, EltVal));
2702249259Sdim  }
2703288943Sdim  }
2704249259Sdim}
2705249259Sdim
2706249259Sdim/// getElementAsFloat - If this is an sequential container of floats, return
2707249259Sdim/// the specified element as a float.
2708249259Sdimfloat ConstantDataSequential::getElementAsFloat(unsigned Elt) const {
2709249259Sdim  assert(getElementType()->isFloatTy() &&
2710249259Sdim         "Accessor can only be used when element is a 'float'");
2711249259Sdim  const float *EltPtr = reinterpret_cast<const float *>(getElementPointer(Elt));
2712249259Sdim  return *const_cast<float *>(EltPtr);
2713249259Sdim}
2714249259Sdim
2715249259Sdim/// getElementAsDouble - If this is an sequential container of doubles, return
2716249259Sdim/// the specified element as a float.
2717249259Sdimdouble ConstantDataSequential::getElementAsDouble(unsigned Elt) const {
2718249259Sdim  assert(getElementType()->isDoubleTy() &&
2719249259Sdim         "Accessor can only be used when element is a 'float'");
2720249259Sdim  const double *EltPtr =
2721249259Sdim      reinterpret_cast<const double *>(getElementPointer(Elt));
2722249259Sdim  return *const_cast<double *>(EltPtr);
2723249259Sdim}
2724249259Sdim
2725249259Sdim/// getElementAsConstant - Return a Constant for a specified index's element.
2726249259Sdim/// Note that this has to compute a new constant to return, so it isn't as
2727249259Sdim/// efficient as getElementAsInteger/Float/Double.
2728249259SdimConstant *ConstantDataSequential::getElementAsConstant(unsigned Elt) const {
2729296417Sdim  if (getElementType()->isHalfTy() || getElementType()->isFloatTy() ||
2730296417Sdim      getElementType()->isDoubleTy())
2731249259Sdim    return ConstantFP::get(getContext(), getElementAsAPFloat(Elt));
2732249259Sdim
2733249259Sdim  return ConstantInt::get(getElementType(), getElementAsInteger(Elt));
2734249259Sdim}
2735249259Sdim
2736249259Sdim/// isString - This method returns true if this is an array of i8.
2737249259Sdimbool ConstantDataSequential::isString() const {
2738249259Sdim  return isa<ArrayType>(getType()) && getElementType()->isIntegerTy(8);
2739249259Sdim}
2740249259Sdim
2741249259Sdim/// isCString - This method returns true if the array "isString", ends with a
2742249259Sdim/// nul byte, and does not contains any other nul bytes.
2743249259Sdimbool ConstantDataSequential::isCString() const {
2744249259Sdim  if (!isString())
2745249259Sdim    return false;
2746249259Sdim
2747249259Sdim  StringRef Str = getAsString();
2748249259Sdim
2749249259Sdim  // The last value must be nul.
2750249259Sdim  if (Str.back() != 0) return false;
2751249259Sdim
2752249259Sdim  // Other elements must be non-nul.
2753249259Sdim  return Str.drop_back().find(0) == StringRef::npos;
2754249259Sdim}
2755249259Sdim
2756249259Sdim/// getSplatValue - If this is a splat constant, meaning that all of the
2757280031Sdim/// elements have the same value, return that value. Otherwise return nullptr.
2758249259SdimConstant *ConstantDataVector::getSplatValue() const {
2759249259Sdim  const char *Base = getRawDataValues().data();
2760249259Sdim
2761249259Sdim  // Compare elements 1+ to the 0'th element.
2762249259Sdim  unsigned EltSize = getElementByteSize();
2763249259Sdim  for (unsigned i = 1, e = getNumElements(); i != e; ++i)
2764249259Sdim    if (memcmp(Base, Base+i*EltSize, EltSize))
2765276479Sdim      return nullptr;
2766249259Sdim
2767249259Sdim  // If they're all the same, return the 0th one as a representative.
2768249259Sdim  return getElementAsConstant(0);
2769249259Sdim}
2770249259Sdim
2771249259Sdim//===----------------------------------------------------------------------===//
2772288943Sdim//                handleOperandChange implementations
2773249259Sdim
2774288943Sdim/// Update this constant array to change uses of
2775249259Sdim/// 'From' to be uses of 'To'.  This must update the uniquing data structures
2776249259Sdim/// etc.
2777249259Sdim///
2778249259Sdim/// Note that we intentionally replace all uses of From with To here.  Consider
2779249259Sdim/// a large array that uses 'From' 1000 times.  By handling this case all here,
2780288943Sdim/// ConstantArray::handleOperandChange is only invoked once, and that
2781249259Sdim/// single invocation handles all 1000 uses.  Handling them one at a time would
2782249259Sdim/// work, but would be really slow because it would have to unique each updated
2783249259Sdim/// array instance.
2784249259Sdim///
2785288943Sdimvoid Constant::handleOperandChange(Value *From, Value *To, Use *U) {
2786288943Sdim  Value *Replacement = nullptr;
2787288943Sdim  switch (getValueID()) {
2788288943Sdim  default:
2789288943Sdim    llvm_unreachable("Not a constant!");
2790288943Sdim#define HANDLE_CONSTANT(Name)                                                  \
2791288943Sdim  case Value::Name##Val:                                                       \
2792288943Sdim    Replacement = cast<Name>(this)->handleOperandChangeImpl(From, To, U);      \
2793288943Sdim    break;
2794288943Sdim#include "llvm/IR/Value.def"
2795288943Sdim  }
2796288943Sdim
2797288943Sdim  // If handleOperandChangeImpl returned nullptr, then it handled
2798288943Sdim  // replacing itself and we don't want to delete or replace anything else here.
2799288943Sdim  if (!Replacement)
2800288943Sdim    return;
2801288943Sdim
2802280031Sdim  // I do need to replace this with an existing value.
2803280031Sdim  assert(Replacement != this && "I didn't contain From!");
2804280031Sdim
2805280031Sdim  // Everyone using this now uses the replacement.
2806280031Sdim  replaceAllUsesWith(Replacement);
2807280031Sdim
2808280031Sdim  // Delete the old constant!
2809280031Sdim  destroyConstant();
2810280031Sdim}
2811280031Sdim
2812288943SdimValue *ConstantInt::handleOperandChangeImpl(Value *From, Value *To, Use *U) {
2813288943Sdim  llvm_unreachable("Unsupported class for handleOperandChange()!");
2814288943Sdim}
2815288943Sdim
2816288943SdimValue *ConstantFP::handleOperandChangeImpl(Value *From, Value *To, Use *U) {
2817288943Sdim  llvm_unreachable("Unsupported class for handleOperandChange()!");
2818288943Sdim}
2819288943Sdim
2820296417SdimValue *ConstantTokenNone::handleOperandChangeImpl(Value *From, Value *To,
2821296417Sdim                                                  Use *U) {
2822296417Sdim  llvm_unreachable("Unsupported class for handleOperandChange()!");
2823296417Sdim}
2824296417Sdim
2825288943SdimValue *UndefValue::handleOperandChangeImpl(Value *From, Value *To, Use *U) {
2826288943Sdim  llvm_unreachable("Unsupported class for handleOperandChange()!");
2827288943Sdim}
2828288943Sdim
2829288943SdimValue *ConstantPointerNull::handleOperandChangeImpl(Value *From, Value *To,
2830288943Sdim                                                    Use *U) {
2831288943Sdim  llvm_unreachable("Unsupported class for handleOperandChange()!");
2832288943Sdim}
2833288943Sdim
2834288943SdimValue *ConstantAggregateZero::handleOperandChangeImpl(Value *From, Value *To,
2835288943Sdim                                                      Use *U) {
2836288943Sdim  llvm_unreachable("Unsupported class for handleOperandChange()!");
2837288943Sdim}
2838288943Sdim
2839288943SdimValue *ConstantDataSequential::handleOperandChangeImpl(Value *From, Value *To,
2840288943Sdim                                                       Use *U) {
2841288943Sdim  llvm_unreachable("Unsupported class for handleOperandChange()!");
2842288943Sdim}
2843288943Sdim
2844288943SdimValue *ConstantArray::handleOperandChangeImpl(Value *From, Value *To, Use *U) {
2845249259Sdim  assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2846249259Sdim  Constant *ToC = cast<Constant>(To);
2847249259Sdim
2848249259Sdim  SmallVector<Constant*, 8> Values;
2849249259Sdim  Values.reserve(getNumOperands());  // Build replacement array.
2850249259Sdim
2851249259Sdim  // Fill values with the modified operands of the constant array.  Also,
2852249259Sdim  // compute whether this turns into an all-zeros array.
2853249259Sdim  unsigned NumUpdated = 0;
2854249259Sdim
2855249259Sdim  // Keep track of whether all the values in the array are "ToC".
2856249259Sdim  bool AllSame = true;
2857288943Sdim  Use *OperandList = getOperandList();
2858249259Sdim  for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2859249259Sdim    Constant *Val = cast<Constant>(O->get());
2860249259Sdim    if (Val == From) {
2861249259Sdim      Val = ToC;
2862249259Sdim      ++NumUpdated;
2863249259Sdim    }
2864249259Sdim    Values.push_back(Val);
2865249259Sdim    AllSame &= Val == ToC;
2866249259Sdim  }
2867249259Sdim
2868288943Sdim  if (AllSame && ToC->isNullValue())
2869288943Sdim    return ConstantAggregateZero::get(getType());
2870249259Sdim
2871288943Sdim  if (AllSame && isa<UndefValue>(ToC))
2872288943Sdim    return UndefValue::get(getType());
2873288943Sdim
2874280031Sdim  // Check for any other type of constant-folding.
2875288943Sdim  if (Constant *C = getImpl(getType(), Values))
2876288943Sdim    return C;
2877249259Sdim
2878280031Sdim  // Update to the new value.
2879288943Sdim  return getContext().pImpl->ArrayConstants.replaceOperandsInPlace(
2880288943Sdim      Values, this, From, ToC, NumUpdated, U - OperandList);
2881249259Sdim}
2882249259Sdim
2883288943SdimValue *ConstantStruct::handleOperandChangeImpl(Value *From, Value *To, Use *U) {
2884249259Sdim  assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2885249259Sdim  Constant *ToC = cast<Constant>(To);
2886249259Sdim
2887288943Sdim  Use *OperandList = getOperandList();
2888249259Sdim  unsigned OperandToUpdate = U-OperandList;
2889249259Sdim  assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2890249259Sdim
2891249259Sdim  SmallVector<Constant*, 8> Values;
2892249259Sdim  Values.reserve(getNumOperands());  // Build replacement struct.
2893249259Sdim
2894249259Sdim  // Fill values with the modified operands of the constant struct.  Also,
2895249259Sdim  // compute whether this turns into an all-zeros struct.
2896249259Sdim  bool isAllZeros = false;
2897249259Sdim  bool isAllUndef = false;
2898249259Sdim  if (ToC->isNullValue()) {
2899249259Sdim    isAllZeros = true;
2900249259Sdim    for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2901249259Sdim      Constant *Val = cast<Constant>(O->get());
2902249259Sdim      Values.push_back(Val);
2903249259Sdim      if (isAllZeros) isAllZeros = Val->isNullValue();
2904249259Sdim    }
2905249259Sdim  } else if (isa<UndefValue>(ToC)) {
2906249259Sdim    isAllUndef = true;
2907249259Sdim    for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2908249259Sdim      Constant *Val = cast<Constant>(O->get());
2909249259Sdim      Values.push_back(Val);
2910249259Sdim      if (isAllUndef) isAllUndef = isa<UndefValue>(Val);
2911249259Sdim    }
2912249259Sdim  } else {
2913249259Sdim    for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O)
2914249259Sdim      Values.push_back(cast<Constant>(O->get()));
2915249259Sdim  }
2916249259Sdim  Values[OperandToUpdate] = ToC;
2917249259Sdim
2918288943Sdim  if (isAllZeros)
2919288943Sdim    return ConstantAggregateZero::get(getType());
2920249259Sdim
2921288943Sdim  if (isAllUndef)
2922288943Sdim    return UndefValue::get(getType());
2923288943Sdim
2924280031Sdim  // Update to the new value.
2925288943Sdim  return getContext().pImpl->StructConstants.replaceOperandsInPlace(
2926288943Sdim      Values, this, From, ToC);
2927249259Sdim}
2928249259Sdim
2929288943SdimValue *ConstantVector::handleOperandChangeImpl(Value *From, Value *To, Use *U) {
2930249259Sdim  assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2931280031Sdim  Constant *ToC = cast<Constant>(To);
2932249259Sdim
2933249259Sdim  SmallVector<Constant*, 8> Values;
2934249259Sdim  Values.reserve(getNumOperands());  // Build replacement array...
2935280031Sdim  unsigned NumUpdated = 0;
2936249259Sdim  for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2937249259Sdim    Constant *Val = getOperand(i);
2938280031Sdim    if (Val == From) {
2939280031Sdim      ++NumUpdated;
2940280031Sdim      Val = ToC;
2941280031Sdim    }
2942249259Sdim    Values.push_back(Val);
2943249259Sdim  }
2944249259Sdim
2945288943Sdim  if (Constant *C = getImpl(Values))
2946288943Sdim    return C;
2947249259Sdim
2948280031Sdim  // Update to the new value.
2949288943Sdim  Use *OperandList = getOperandList();
2950288943Sdim  return getContext().pImpl->VectorConstants.replaceOperandsInPlace(
2951288943Sdim      Values, this, From, ToC, NumUpdated, U - OperandList);
2952249259Sdim}
2953249259Sdim
2954288943SdimValue *ConstantExpr::handleOperandChangeImpl(Value *From, Value *ToV, Use *U) {
2955249259Sdim  assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2956249259Sdim  Constant *To = cast<Constant>(ToV);
2957249259Sdim
2958249259Sdim  SmallVector<Constant*, 8> NewOps;
2959280031Sdim  unsigned NumUpdated = 0;
2960249259Sdim  for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2961249259Sdim    Constant *Op = getOperand(i);
2962280031Sdim    if (Op == From) {
2963280031Sdim      ++NumUpdated;
2964280031Sdim      Op = To;
2965280031Sdim    }
2966280031Sdim    NewOps.push_back(Op);
2967249259Sdim  }
2968280031Sdim  assert(NumUpdated && "I didn't contain From!");
2969249259Sdim
2970288943Sdim  if (Constant *C = getWithOperands(NewOps, getType(), true))
2971288943Sdim    return C;
2972249259Sdim
2973280031Sdim  // Update to the new value.
2974288943Sdim  Use *OperandList = getOperandList();
2975288943Sdim  return getContext().pImpl->ExprConstants.replaceOperandsInPlace(
2976288943Sdim      NewOps, this, From, To, NumUpdated, U - OperandList);
2977249259Sdim}
2978249259Sdim
2979249259SdimInstruction *ConstantExpr::getAsInstruction() {
2980288943Sdim  SmallVector<Value *, 4> ValueOperands(op_begin(), op_end());
2981249259Sdim  ArrayRef<Value*> Ops(ValueOperands);
2982249259Sdim
2983249259Sdim  switch (getOpcode()) {
2984249259Sdim  case Instruction::Trunc:
2985249259Sdim  case Instruction::ZExt:
2986249259Sdim  case Instruction::SExt:
2987249259Sdim  case Instruction::FPTrunc:
2988249259Sdim  case Instruction::FPExt:
2989249259Sdim  case Instruction::UIToFP:
2990249259Sdim  case Instruction::SIToFP:
2991249259Sdim  case Instruction::FPToUI:
2992249259Sdim  case Instruction::FPToSI:
2993249259Sdim  case Instruction::PtrToInt:
2994249259Sdim  case Instruction::IntToPtr:
2995249259Sdim  case Instruction::BitCast:
2996276479Sdim  case Instruction::AddrSpaceCast:
2997249259Sdim    return CastInst::Create((Instruction::CastOps)getOpcode(),
2998249259Sdim                            Ops[0], getType());
2999249259Sdim  case Instruction::Select:
3000249259Sdim    return SelectInst::Create(Ops[0], Ops[1], Ops[2]);
3001249259Sdim  case Instruction::InsertElement:
3002249259Sdim    return InsertElementInst::Create(Ops[0], Ops[1], Ops[2]);
3003249259Sdim  case Instruction::ExtractElement:
3004249259Sdim    return ExtractElementInst::Create(Ops[0], Ops[1]);
3005249259Sdim  case Instruction::InsertValue:
3006249259Sdim    return InsertValueInst::Create(Ops[0], Ops[1], getIndices());
3007249259Sdim  case Instruction::ExtractValue:
3008249259Sdim    return ExtractValueInst::Create(Ops[0], getIndices());
3009249259Sdim  case Instruction::ShuffleVector:
3010249259Sdim    return new ShuffleVectorInst(Ops[0], Ops[1], Ops[2]);
3011249259Sdim
3012288943Sdim  case Instruction::GetElementPtr: {
3013288943Sdim    const auto *GO = cast<GEPOperator>(this);
3014288943Sdim    if (GO->isInBounds())
3015288943Sdim      return GetElementPtrInst::CreateInBounds(GO->getSourceElementType(),
3016288943Sdim                                               Ops[0], Ops.slice(1));
3017288943Sdim    return GetElementPtrInst::Create(GO->getSourceElementType(), Ops[0],
3018288943Sdim                                     Ops.slice(1));
3019288943Sdim  }
3020249259Sdim  case Instruction::ICmp:
3021249259Sdim  case Instruction::FCmp:
3022249259Sdim    return CmpInst::Create((Instruction::OtherOps)getOpcode(),
3023296417Sdim                           (CmpInst::Predicate)getPredicate(), Ops[0], Ops[1]);
3024249259Sdim
3025249259Sdim  default:
3026249259Sdim    assert(getNumOperands() == 2 && "Must be binary operator?");
3027249259Sdim    BinaryOperator *BO =
3028249259Sdim      BinaryOperator::Create((Instruction::BinaryOps)getOpcode(),
3029249259Sdim                             Ops[0], Ops[1]);
3030249259Sdim    if (isa<OverflowingBinaryOperator>(BO)) {
3031249259Sdim      BO->setHasNoUnsignedWrap(SubclassOptionalData &
3032249259Sdim                               OverflowingBinaryOperator::NoUnsignedWrap);
3033249259Sdim      BO->setHasNoSignedWrap(SubclassOptionalData &
3034249259Sdim                             OverflowingBinaryOperator::NoSignedWrap);
3035249259Sdim    }
3036249259Sdim    if (isa<PossiblyExactOperator>(BO))
3037249259Sdim      BO->setIsExact(SubclassOptionalData & PossiblyExactOperator::IsExact);
3038249259Sdim    return BO;
3039249259Sdim  }
3040249259Sdim}
3041