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