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