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