LLVM  13.0.0git
ConstantFold.cpp
Go to the documentation of this file.
1 //===- ConstantFold.cpp - LLVM constant folder ----------------------------===//
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 folding of constants for LLVM. This implements the
10 // (internal) ConstantFold.h interface, which is used by the
11 // ConstantExpr::get* methods to automatically fold constants when possible.
12 //
13 // The current constant folding implementation is implemented in two pieces: the
14 // pieces that don't need DataLayout, and the pieces that do. This is to avoid
15 // a dependence in IR on Target.
16 //
17 //===----------------------------------------------------------------------===//
18 
19 #include "ConstantFold.h"
20 #include "llvm/ADT/APSInt.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/IR/Constants.h"
23 #include "llvm/IR/DerivedTypes.h"
24 #include "llvm/IR/Function.h"
26 #include "llvm/IR/GlobalAlias.h"
27 #include "llvm/IR/GlobalVariable.h"
28 #include "llvm/IR/Instructions.h"
29 #include "llvm/IR/Module.h"
30 #include "llvm/IR/Operator.h"
31 #include "llvm/IR/PatternMatch.h"
35 using namespace llvm;
36 using namespace llvm::PatternMatch;
37 
38 //===----------------------------------------------------------------------===//
39 // ConstantFold*Instruction Implementations
40 //===----------------------------------------------------------------------===//
41 
42 /// Convert the specified vector Constant node to the specified vector type.
43 /// At this point, we know that the elements of the input vector constant are
44 /// all simple integer or FP values.
46 
47  if (CV->isAllOnesValue()) return Constant::getAllOnesValue(DstTy);
48  if (CV->isNullValue()) return Constant::getNullValue(DstTy);
49 
50  // Do not iterate on scalable vector. The num of elements is unknown at
51  // compile-time.
52  if (isa<ScalableVectorType>(DstTy))
53  return nullptr;
54 
55  // If this cast changes element count then we can't handle it here:
56  // doing so requires endianness information. This should be handled by
57  // Analysis/ConstantFolding.cpp
58  unsigned NumElts = cast<FixedVectorType>(DstTy)->getNumElements();
59  if (NumElts != cast<FixedVectorType>(CV->getType())->getNumElements())
60  return nullptr;
61 
62  Type *DstEltTy = DstTy->getElementType();
63  // Fast path for splatted constants.
64  if (Constant *Splat = CV->getSplatValue()) {
66  ConstantExpr::getBitCast(Splat, DstEltTy));
67  }
68 
70  Type *Ty = IntegerType::get(CV->getContext(), 32);
71  for (unsigned i = 0; i != NumElts; ++i) {
72  Constant *C =
74  C = ConstantExpr::getBitCast(C, DstEltTy);
75  Result.push_back(C);
76  }
77 
78  return ConstantVector::get(Result);
79 }
80 
81 /// This function determines which opcode to use to fold two constant cast
82 /// expressions together. It uses CastInst::isEliminableCastPair to determine
83 /// the opcode. Consequently its just a wrapper around that function.
84 /// Determine if it is valid to fold a cast of a cast
85 static unsigned
87  unsigned opc, ///< opcode of the second cast constant expression
88  ConstantExpr *Op, ///< the first cast constant expression
89  Type *DstTy ///< destination type of the first cast
90 ) {
91  assert(Op && Op->isCast() && "Can't fold cast of cast without a cast!");
92  assert(DstTy && DstTy->isFirstClassType() && "Invalid cast destination type");
93  assert(CastInst::isCast(opc) && "Invalid cast opcode");
94 
95  // The types and opcodes for the two Cast constant expressions
96  Type *SrcTy = Op->getOperand(0)->getType();
97  Type *MidTy = Op->getType();
98  Instruction::CastOps firstOp = Instruction::CastOps(Op->getOpcode());
100 
101  // Assume that pointers are never more than 64 bits wide, and only use this
102  // for the middle type. Otherwise we could end up folding away illegal
103  // bitcasts between address spaces with different sizes.
104  IntegerType *FakeIntPtrTy = Type::getInt64Ty(DstTy->getContext());
105 
106  // Let CastInst::isEliminableCastPair do the heavy lifting.
107  return CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy, DstTy,
108  nullptr, FakeIntPtrTy, nullptr);
109 }
110 
111 static Constant *FoldBitCast(Constant *V, Type *DestTy) {
112  Type *SrcTy = V->getType();
113  if (SrcTy == DestTy)
114  return V; // no-op cast
115 
116  // Check to see if we are casting a pointer to an aggregate to a pointer to
117  // the first element. If so, return the appropriate GEP instruction.
118  if (PointerType *PTy = dyn_cast<PointerType>(V->getType()))
119  if (PointerType *DPTy = dyn_cast<PointerType>(DestTy))
120  if (PTy->getAddressSpace() == DPTy->getAddressSpace()
121  && PTy->getElementType()->isSized()) {
122  SmallVector<Value*, 8> IdxList;
123  Value *Zero =
124  Constant::getNullValue(Type::getInt32Ty(DPTy->getContext()));
125  IdxList.push_back(Zero);
126  Type *ElTy = PTy->getElementType();
127  while (ElTy && ElTy != DPTy->getElementType()) {
128  ElTy = GetElementPtrInst::getTypeAtIndex(ElTy, (uint64_t)0);
129  IdxList.push_back(Zero);
130  }
131 
132  if (ElTy == DPTy->getElementType())
133  // This GEP is inbounds because all indices are zero.
134  return ConstantExpr::getInBoundsGetElementPtr(PTy->getElementType(),
135  V, IdxList);
136  }
137 
138  // Handle casts from one vector constant to another. We know that the src
139  // and dest type have the same size (otherwise its an illegal cast).
140  if (VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
141  if (VectorType *SrcTy = dyn_cast<VectorType>(V->getType())) {
142  assert(DestPTy->getPrimitiveSizeInBits() ==
143  SrcTy->getPrimitiveSizeInBits() &&
144  "Not cast between same sized vectors!");
145  SrcTy = nullptr;
146  // First, check for null. Undef is already handled.
147  if (isa<ConstantAggregateZero>(V))
148  return Constant::getNullValue(DestTy);
149 
150  // Handle ConstantVector and ConstantAggregateVector.
151  return BitCastConstantVector(V, DestPTy);
152  }
153 
154  // Canonicalize scalar-to-vector bitcasts into vector-to-vector bitcasts
155  // This allows for other simplifications (although some of them
156  // can only be handled by Analysis/ConstantFolding.cpp).
157  if (isa<ConstantInt>(V) || isa<ConstantFP>(V))
158  return ConstantExpr::getBitCast(ConstantVector::get(V), DestPTy);
159  }
160 
161  // Finally, implement bitcast folding now. The code below doesn't handle
162  // bitcast right.
163  if (isa<ConstantPointerNull>(V)) // ptr->ptr cast.
164  return ConstantPointerNull::get(cast<PointerType>(DestTy));
165 
166  // Handle integral constant input.
167  if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
168  if (DestTy->isIntegerTy())
169  // Integral -> Integral. This is a no-op because the bit widths must
170  // be the same. Consequently, we just fold to V.
171  return V;
172 
173  // See note below regarding the PPC_FP128 restriction.
174  if (DestTy->isFloatingPointTy() && !DestTy->isPPC_FP128Ty())
175  return ConstantFP::get(DestTy->getContext(),
176  APFloat(DestTy->getFltSemantics(),
177  CI->getValue()));
178 
179  // Otherwise, can't fold this (vector?)
180  return nullptr;
181  }
182 
183  // Handle ConstantFP input: FP -> Integral.
184  if (ConstantFP *FP = dyn_cast<ConstantFP>(V)) {
185  // PPC_FP128 is really the sum of two consecutive doubles, where the first
186  // double is always stored first in memory, regardless of the target
187  // endianness. The memory layout of i128, however, depends on the target
188  // endianness, and so we can't fold this without target endianness
189  // information. This should instead be handled by
190  // Analysis/ConstantFolding.cpp
191  if (FP->getType()->isPPC_FP128Ty())
192  return nullptr;
193 
194  // Make sure dest type is compatible with the folded integer constant.
195  if (!DestTy->isIntegerTy())
196  return nullptr;
197 
198  return ConstantInt::get(FP->getContext(),
199  FP->getValueAPF().bitcastToAPInt());
200  }
201 
202  return nullptr;
203 }
204 
205 
206 /// V is an integer constant which only has a subset of its bytes used.
207 /// The bytes used are indicated by ByteStart (which is the first byte used,
208 /// counting from the least significant byte) and ByteSize, which is the number
209 /// of bytes used.
210 ///
211 /// This function analyzes the specified constant to see if the specified byte
212 /// range can be returned as a simplified constant. If so, the constant is
213 /// returned, otherwise null is returned.
214 static Constant *ExtractConstantBytes(Constant *C, unsigned ByteStart,
215  unsigned ByteSize) {
216  assert(C->getType()->isIntegerTy() &&
217  (cast<IntegerType>(C->getType())->getBitWidth() & 7) == 0 &&
218  "Non-byte sized integer input");
219  unsigned CSize = cast<IntegerType>(C->getType())->getBitWidth()/8;
220  assert(ByteSize && "Must be accessing some piece");
221  assert(ByteStart+ByteSize <= CSize && "Extracting invalid piece from input");
222  assert(ByteSize != CSize && "Should not extract everything");
223 
224  // Constant Integers are simple.
225  if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
226  APInt V = CI->getValue();
227  if (ByteStart)
228  V.lshrInPlace(ByteStart*8);
229  V = V.trunc(ByteSize*8);
230  return ConstantInt::get(CI->getContext(), V);
231  }
232 
233  // In the input is a constant expr, we might be able to recursively simplify.
234  // If not, we definitely can't do anything.
235  ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
236  if (!CE) return nullptr;
237 
238  switch (CE->getOpcode()) {
239  default: return nullptr;
240  case Instruction::Or: {
241  Constant *RHS = ExtractConstantBytes(CE->getOperand(1), ByteStart,ByteSize);
242  if (!RHS)
243  return nullptr;
244 
245  // X | -1 -> -1.
246  if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS))
247  if (RHSC->isMinusOne())
248  return RHSC;
249 
250  Constant *LHS = ExtractConstantBytes(CE->getOperand(0), ByteStart,ByteSize);
251  if (!LHS)
252  return nullptr;
253  return ConstantExpr::getOr(LHS, RHS);
254  }
255  case Instruction::And: {
256  Constant *RHS = ExtractConstantBytes(CE->getOperand(1), ByteStart,ByteSize);
257  if (!RHS)
258  return nullptr;
259 
260  // X & 0 -> 0.
261  if (RHS->isNullValue())
262  return RHS;
263 
264  Constant *LHS = ExtractConstantBytes(CE->getOperand(0), ByteStart,ByteSize);
265  if (!LHS)
266  return nullptr;
267  return ConstantExpr::getAnd(LHS, RHS);
268  }
269  case Instruction::LShr: {
270  ConstantInt *Amt = dyn_cast<ConstantInt>(CE->getOperand(1));
271  if (!Amt)
272  return nullptr;
273  APInt ShAmt = Amt->getValue();
274  // Cannot analyze non-byte shifts.
275  if ((ShAmt & 7) != 0)
276  return nullptr;
277  ShAmt.lshrInPlace(3);
278 
279  // If the extract is known to be all zeros, return zero.
280  if (ShAmt.uge(CSize - ByteStart))
281  return Constant::getNullValue(
282  IntegerType::get(CE->getContext(), ByteSize * 8));
283  // If the extract is known to be fully in the input, extract it.
284  if (ShAmt.ule(CSize - (ByteStart + ByteSize)))
285  return ExtractConstantBytes(CE->getOperand(0),
286  ByteStart + ShAmt.getZExtValue(), ByteSize);
287 
288  // TODO: Handle the 'partially zero' case.
289  return nullptr;
290  }
291 
292  case Instruction::Shl: {
293  ConstantInt *Amt = dyn_cast<ConstantInt>(CE->getOperand(1));
294  if (!Amt)
295  return nullptr;
296  APInt ShAmt = Amt->getValue();
297  // Cannot analyze non-byte shifts.
298  if ((ShAmt & 7) != 0)
299  return nullptr;
300  ShAmt.lshrInPlace(3);
301 
302  // If the extract is known to be all zeros, return zero.
303  if (ShAmt.uge(ByteStart + ByteSize))
304  return Constant::getNullValue(
305  IntegerType::get(CE->getContext(), ByteSize * 8));
306  // If the extract is known to be fully in the input, extract it.
307  if (ShAmt.ule(ByteStart))
308  return ExtractConstantBytes(CE->getOperand(0),
309  ByteStart - ShAmt.getZExtValue(), ByteSize);
310 
311  // TODO: Handle the 'partially zero' case.
312  return nullptr;
313  }
314 
315  case Instruction::ZExt: {
316  unsigned SrcBitSize =
317  cast<IntegerType>(CE->getOperand(0)->getType())->getBitWidth();
318 
319  // If extracting something that is completely zero, return 0.
320  if (ByteStart*8 >= SrcBitSize)
321  return Constant::getNullValue(IntegerType::get(CE->getContext(),
322  ByteSize*8));
323 
324  // If exactly extracting the input, return it.
325  if (ByteStart == 0 && ByteSize*8 == SrcBitSize)
326  return CE->getOperand(0);
327 
328  // If extracting something completely in the input, if the input is a
329  // multiple of 8 bits, recurse.
330  if ((SrcBitSize&7) == 0 && (ByteStart+ByteSize)*8 <= SrcBitSize)
331  return ExtractConstantBytes(CE->getOperand(0), ByteStart, ByteSize);
332 
333  // Otherwise, if extracting a subset of the input, which is not multiple of
334  // 8 bits, do a shift and trunc to get the bits.
335  if ((ByteStart+ByteSize)*8 < SrcBitSize) {
336  assert((SrcBitSize&7) && "Shouldn't get byte sized case here");
337  Constant *Res = CE->getOperand(0);
338  if (ByteStart)
339  Res = ConstantExpr::getLShr(Res,
340  ConstantInt::get(Res->getType(), ByteStart*8));
341  return ConstantExpr::getTrunc(Res, IntegerType::get(C->getContext(),
342  ByteSize*8));
343  }
344 
345  // TODO: Handle the 'partially zero' case.
346  return nullptr;
347  }
348  }
349 }
350 
351 /// Wrapper around getFoldedSizeOfImpl() that adds caching.
352 static Constant *getFoldedSizeOf(Type *Ty, Type *DestTy, bool Folded,
354 
355 /// Return a ConstantExpr with type DestTy for sizeof on Ty, with any known
356 /// factors factored out. If Folded is false, return null if no factoring was
357 /// possible, to avoid endlessly bouncing an unfoldable expression back into the
358 /// top-level folder.
359 static Constant *getFoldedSizeOfImpl(Type *Ty, Type *DestTy, bool Folded,
361  // This is the actual implementation of getFoldedSizeOf(). To get the caching
362  // behavior, we need to call getFoldedSizeOf() when we recurse.
363 
364  if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
365  Constant *N = ConstantInt::get(DestTy, ATy->getNumElements());
366  Constant *E = getFoldedSizeOf(ATy->getElementType(), DestTy, true, Cache);
367  return ConstantExpr::getNUWMul(E, N);
368  }
369 
370  if (StructType *STy = dyn_cast<StructType>(Ty))
371  if (!STy->isPacked()) {
372  unsigned NumElems = STy->getNumElements();
373  // An empty struct has size zero.
374  if (NumElems == 0)
375  return ConstantExpr::getNullValue(DestTy);
376  // Check for a struct with all members having the same size.
377  Constant *MemberSize =
378  getFoldedSizeOf(STy->getElementType(0), DestTy, true, Cache);
379  bool AllSame = true;
380  for (unsigned i = 1; i != NumElems; ++i)
381  if (MemberSize !=
382  getFoldedSizeOf(STy->getElementType(i), DestTy, true, Cache)) {
383  AllSame = false;
384  break;
385  }
386  if (AllSame) {
387  Constant *N = ConstantInt::get(DestTy, NumElems);
388  return ConstantExpr::getNUWMul(MemberSize, N);
389  }
390  }
391 
392  // Pointer size doesn't depend on the pointee type, so canonicalize them
393  // to an arbitrary pointee.
394  if (PointerType *PTy = dyn_cast<PointerType>(Ty))
395  if (!PTy->getElementType()->isIntegerTy(1))
396  return getFoldedSizeOf(
397  PointerType::get(IntegerType::get(PTy->getContext(), 1),
398  PTy->getAddressSpace()),
399  DestTy, true, Cache);
400 
401  // If there's no interesting folding happening, bail so that we don't create
402  // a constant that looks like it needs folding but really doesn't.
403  if (!Folded)
404  return nullptr;
405 
406  // Base case: Get a regular sizeof expression.
409  DestTy, false),
410  C, DestTy);
411  return C;
412 }
413 
414 static Constant *getFoldedSizeOf(Type *Ty, Type *DestTy, bool Folded,
416  // Check for previously generated folded size constant.
417  auto It = Cache.find(Ty);
418  if (It != Cache.end())
419  return It->second;
420  return Cache[Ty] = getFoldedSizeOfImpl(Ty, DestTy, Folded, Cache);
421 }
422 
423 static Constant *getFoldedSizeOf(Type *Ty, Type *DestTy, bool Folded) {
425  return getFoldedSizeOf(Ty, DestTy, Folded, Cache);
426 }
427 
428 /// Return a ConstantExpr with type DestTy for alignof on Ty, with any known
429 /// factors factored out. If Folded is false, return null if no factoring was
430 /// possible, to avoid endlessly bouncing an unfoldable expression back into the
431 /// top-level folder.
432 static Constant *getFoldedAlignOf(Type *Ty, Type *DestTy, bool Folded) {
433  // The alignment of an array is equal to the alignment of the
434  // array element. Note that this is not always true for vectors.
435  if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
436  Constant *C = ConstantExpr::getAlignOf(ATy->getElementType());
438  DestTy,
439  false),
440  C, DestTy);
441  return C;
442  }
443 
444  if (StructType *STy = dyn_cast<StructType>(Ty)) {
445  // Packed structs always have an alignment of 1.
446  if (STy->isPacked())
447  return ConstantInt::get(DestTy, 1);
448 
449  // Otherwise, struct alignment is the maximum alignment of any member.
450  // Without target data, we can't compare much, but we can check to see
451  // if all the members have the same alignment.
452  unsigned NumElems = STy->getNumElements();
453  // An empty struct has minimal alignment.
454  if (NumElems == 0)
455  return ConstantInt::get(DestTy, 1);
456  // Check for a struct with all members having the same alignment.
457  Constant *MemberAlign =
458  getFoldedAlignOf(STy->getElementType(0), DestTy, true);
459  bool AllSame = true;
460  for (unsigned i = 1; i != NumElems; ++i)
461  if (MemberAlign != getFoldedAlignOf(STy->getElementType(i), DestTy, true)) {
462  AllSame = false;
463  break;
464  }
465  if (AllSame)
466  return MemberAlign;
467  }
468 
469  // Pointer alignment doesn't depend on the pointee type, so canonicalize them
470  // to an arbitrary pointee.
471  if (PointerType *PTy = dyn_cast<PointerType>(Ty))
472  if (!PTy->getElementType()->isIntegerTy(1))
473  return
475  1),
476  PTy->getAddressSpace()),
477  DestTy, true);
478 
479  // If there's no interesting folding happening, bail so that we don't create
480  // a constant that looks like it needs folding but really doesn't.
481  if (!Folded)
482  return nullptr;
483 
484  // Base case: Get a regular alignof expression.
487  DestTy, false),
488  C, DestTy);
489  return C;
490 }
491 
492 /// Return a ConstantExpr with type DestTy for offsetof on Ty and FieldNo, with
493 /// any known factors factored out. If Folded is false, return null if no
494 /// factoring was possible, to avoid endlessly bouncing an unfoldable expression
495 /// back into the top-level folder.
496 static Constant *getFoldedOffsetOf(Type *Ty, Constant *FieldNo, Type *DestTy,
497  bool Folded) {
498  if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
500  DestTy, false),
501  FieldNo, DestTy);
502  Constant *E = getFoldedSizeOf(ATy->getElementType(), DestTy, true);
503  return ConstantExpr::getNUWMul(E, N);
504  }
505 
506  if (StructType *STy = dyn_cast<StructType>(Ty))
507  if (!STy->isPacked()) {
508  unsigned NumElems = STy->getNumElements();
509  // An empty struct has no members.
510  if (NumElems == 0)
511  return nullptr;
512  // Check for a struct with all members having the same size.
513  Constant *MemberSize =
514  getFoldedSizeOf(STy->getElementType(0), DestTy, true);
515  bool AllSame = true;
516  for (unsigned i = 1; i != NumElems; ++i)
517  if (MemberSize !=
518  getFoldedSizeOf(STy->getElementType(i), DestTy, true)) {
519  AllSame = false;
520  break;
521  }
522  if (AllSame) {
524  false,
525  DestTy,
526  false),
527  FieldNo, DestTy);
528  return ConstantExpr::getNUWMul(MemberSize, N);
529  }
530  }
531 
532  // If there's no interesting folding happening, bail so that we don't create
533  // a constant that looks like it needs folding but really doesn't.
534  if (!Folded)
535  return nullptr;
536 
537  // Base case: Get a regular offsetof expression.
538  Constant *C = ConstantExpr::getOffsetOf(Ty, FieldNo);
540  DestTy, false),
541  C, DestTy);
542  return C;
543 }
544 
546  Type *DestTy) {
547  if (isa<PoisonValue>(V))
548  return PoisonValue::get(DestTy);
549 
550  if (isa<UndefValue>(V)) {
551  // zext(undef) = 0, because the top bits will be zero.
552  // sext(undef) = 0, because the top bits will all be the same.
553  // [us]itofp(undef) = 0, because the result value is bounded.
554  if (opc == Instruction::ZExt || opc == Instruction::SExt ||
555  opc == Instruction::UIToFP || opc == Instruction::SIToFP)
556  return Constant::getNullValue(DestTy);
557  return UndefValue::get(DestTy);
558  }
559 
560  if (V->isNullValue() && !DestTy->isX86_MMXTy() && !DestTy->isX86_AMXTy() &&
561  opc != Instruction::AddrSpaceCast)
562  return Constant::getNullValue(DestTy);
563 
564  // If the cast operand is a constant expression, there's a few things we can
565  // do to try to simplify it.
566  if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
567  if (CE->isCast()) {
568  // Try hard to fold cast of cast because they are often eliminable.
569  if (unsigned newOpc = foldConstantCastPair(opc, CE, DestTy))
570  return ConstantExpr::getCast(newOpc, CE->getOperand(0), DestTy);
571  } else if (CE->getOpcode() == Instruction::GetElementPtr &&
572  // Do not fold addrspacecast (gep 0, .., 0). It might make the
573  // addrspacecast uncanonicalized.
574  opc != Instruction::AddrSpaceCast &&
575  // Do not fold bitcast (gep) with inrange index, as this loses
576  // information.
577  !cast<GEPOperator>(CE)->getInRangeIndex().hasValue() &&
578  // Do not fold if the gep type is a vector, as bitcasting
579  // operand 0 of a vector gep will result in a bitcast between
580  // different sizes.
581  !CE->getType()->isVectorTy()) {
582  // If all of the indexes in the GEP are null values, there is no pointer
583  // adjustment going on. We might as well cast the source pointer.
584  bool isAllNull = true;
585  for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
586  if (!CE->getOperand(i)->isNullValue()) {
587  isAllNull = false;
588  break;
589  }
590  if (isAllNull)
591  // This is casting one pointer type to another, always BitCast
592  return ConstantExpr::getPointerCast(CE->getOperand(0), DestTy);
593  }
594  }
595 
596  // If the cast operand is a constant vector, perform the cast by
597  // operating on each element. In the cast of bitcasts, the element
598  // count may be mismatched; don't attempt to handle that here.
599  if ((isa<ConstantVector>(V) || isa<ConstantDataVector>(V)) &&
600  DestTy->isVectorTy() &&
601  cast<FixedVectorType>(DestTy)->getNumElements() ==
602  cast<FixedVectorType>(V->getType())->getNumElements()) {
603  VectorType *DestVecTy = cast<VectorType>(DestTy);
604  Type *DstEltTy = DestVecTy->getElementType();
605  // Fast path for splatted constants.
606  if (Constant *Splat = V->getSplatValue()) {
608  cast<VectorType>(DestTy)->getElementCount(),
609  ConstantExpr::getCast(opc, Splat, DstEltTy));
610  }
612  Type *Ty = IntegerType::get(V->getContext(), 32);
613  for (unsigned i = 0,
614  e = cast<FixedVectorType>(V->getType())->getNumElements();
615  i != e; ++i) {
616  Constant *C =
618  res.push_back(ConstantExpr::getCast(opc, C, DstEltTy));
619  }
620  return ConstantVector::get(res);
621  }
622 
623  // We actually have to do a cast now. Perform the cast according to the
624  // opcode specified.
625  switch (opc) {
626  default:
627  llvm_unreachable("Failed to cast constant expression");
628  case Instruction::FPTrunc:
629  case Instruction::FPExt:
630  if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
631  bool ignored;
632  APFloat Val = FPC->getValueAPF();
633  Val.convert(DestTy->isHalfTy() ? APFloat::IEEEhalf() :
634  DestTy->isFloatTy() ? APFloat::IEEEsingle() :
635  DestTy->isDoubleTy() ? APFloat::IEEEdouble() :
637  DestTy->isFP128Ty() ? APFloat::IEEEquad() :
639  APFloat::Bogus(),
640  APFloat::rmNearestTiesToEven, &ignored);
641  return ConstantFP::get(V->getContext(), Val);
642  }
643  return nullptr; // Can't fold.
644  case Instruction::FPToUI:
645  case Instruction::FPToSI:
646  if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
647  const APFloat &V = FPC->getValueAPF();
648  bool ignored;
649  uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
650  APSInt IntVal(DestBitWidth, opc == Instruction::FPToUI);
651  if (APFloat::opInvalidOp ==
653  // Undefined behavior invoked - the destination type can't represent
654  // the input constant.
655  return UndefValue::get(DestTy);
656  }
657  return ConstantInt::get(FPC->getContext(), IntVal);
658  }
659  return nullptr; // Can't fold.
660  case Instruction::IntToPtr: //always treated as unsigned
661  if (V->isNullValue()) // Is it an integral null value?
662  return ConstantPointerNull::get(cast<PointerType>(DestTy));
663  return nullptr; // Other pointer types cannot be casted
664  case Instruction::PtrToInt: // always treated as unsigned
665  // Is it a null pointer value?
666  if (V->isNullValue())
667  return ConstantInt::get(DestTy, 0);
668  // If this is a sizeof-like expression, pull out multiplications by
669  // known factors to expose them to subsequent folding. If it's an
670  // alignof-like expression, factor out known factors.
671  if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
672  if (CE->getOpcode() == Instruction::GetElementPtr &&
673  CE->getOperand(0)->isNullValue()) {
674  // FIXME: Looks like getFoldedSizeOf(), getFoldedOffsetOf() and
675  // getFoldedAlignOf() don't handle the case when DestTy is a vector of
676  // pointers yet. We end up in asserts in CastInst::getCastOpcode (see
677  // test/Analysis/ConstantFolding/cast-vector.ll). I've only seen this
678  // happen in one "real" C-code test case, so it does not seem to be an
679  // important optimization to handle vectors here. For now, simply bail
680  // out.
681  if (DestTy->isVectorTy())
682  return nullptr;
683  GEPOperator *GEPO = cast<GEPOperator>(CE);
684  Type *Ty = GEPO->getSourceElementType();
685  if (CE->getNumOperands() == 2) {
686  // Handle a sizeof-like expression.
687  Constant *Idx = CE->getOperand(1);
688  bool isOne = isa<ConstantInt>(Idx) && cast<ConstantInt>(Idx)->isOne();
689  if (Constant *C = getFoldedSizeOf(Ty, DestTy, !isOne)) {
691  DestTy, false),
692  Idx, DestTy);
693  return ConstantExpr::getMul(C, Idx);
694  }
695  } else if (CE->getNumOperands() == 3 &&
696  CE->getOperand(1)->isNullValue()) {
697  // Handle an alignof-like expression.
698  if (StructType *STy = dyn_cast<StructType>(Ty))
699  if (!STy->isPacked()) {
700  ConstantInt *CI = cast<ConstantInt>(CE->getOperand(2));
701  if (CI->isOne() &&
702  STy->getNumElements() == 2 &&
703  STy->getElementType(0)->isIntegerTy(1)) {
704  return getFoldedAlignOf(STy->getElementType(1), DestTy, false);
705  }
706  }
707  // Handle an offsetof-like expression.
708  if (Ty->isStructTy() || Ty->isArrayTy()) {
709  if (Constant *C = getFoldedOffsetOf(Ty, CE->getOperand(2),
710  DestTy, false))
711  return C;
712  }
713  }
714  }
715  // Other pointer types cannot be casted
716  return nullptr;
717  case Instruction::UIToFP:
718  case Instruction::SIToFP:
719  if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
720  const APInt &api = CI->getValue();
721  APFloat apf(DestTy->getFltSemantics(),
723  apf.convertFromAPInt(api, opc==Instruction::SIToFP,
725  return ConstantFP::get(V->getContext(), apf);
726  }
727  return nullptr;
728  case Instruction::ZExt:
729  if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
730  uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
731  return ConstantInt::get(V->getContext(),
732  CI->getValue().zext(BitWidth));
733  }
734  return nullptr;
735  case Instruction::SExt:
736  if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
737  uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
738  return ConstantInt::get(V->getContext(),
739  CI->getValue().sext(BitWidth));
740  }
741  return nullptr;
742  case Instruction::Trunc: {
743  if (V->getType()->isVectorTy())
744  return nullptr;
745 
746  uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
747  if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
748  return ConstantInt::get(V->getContext(),
749  CI->getValue().trunc(DestBitWidth));
750  }
751 
752  // The input must be a constantexpr. See if we can simplify this based on
753  // the bytes we are demanding. Only do this if the source and dest are an
754  // even multiple of a byte.
755  if ((DestBitWidth & 7) == 0 &&
756  (cast<IntegerType>(V->getType())->getBitWidth() & 7) == 0)
757  if (Constant *Res = ExtractConstantBytes(V, 0, DestBitWidth / 8))
758  return Res;
759 
760  return nullptr;
761  }
762  case Instruction::BitCast:
763  return FoldBitCast(V, DestTy);
764  case Instruction::AddrSpaceCast:
765  return nullptr;
766  }
767 }
768 
770  Constant *V1, Constant *V2) {
771  // Check for i1 and vector true/false conditions.
772  if (Cond->isNullValue()) return V2;
773  if (Cond->isAllOnesValue()) return V1;
774 
775  // If the condition is a vector constant, fold the result elementwise.
776  if (ConstantVector *CondV = dyn_cast<ConstantVector>(Cond)) {
777  auto *V1VTy = CondV->getType();
779  Type *Ty = IntegerType::get(CondV->getContext(), 32);
780  for (unsigned i = 0, e = V1VTy->getNumElements(); i != e; ++i) {
781  Constant *V;
783  ConstantInt::get(Ty, i));
785  ConstantInt::get(Ty, i));
786  auto *Cond = cast<Constant>(CondV->getOperand(i));
787  if (isa<PoisonValue>(Cond)) {
788  V = PoisonValue::get(V1Element->getType());
789  } else if (V1Element == V2Element) {
790  V = V1Element;
791  } else if (isa<UndefValue>(Cond)) {
792  V = isa<UndefValue>(V1Element) ? V1Element : V2Element;
793  } else {
794  if (!isa<ConstantInt>(Cond)) break;
795  V = Cond->isNullValue() ? V2Element : V1Element;
796  }
797  Result.push_back(V);
798  }
799 
800  // If we were able to build the vector, return it.
801  if (Result.size() == V1VTy->getNumElements())
802  return ConstantVector::get(Result);
803  }
804 
805  if (isa<PoisonValue>(Cond))
806  return PoisonValue::get(V1->getType());
807 
808  if (isa<UndefValue>(Cond)) {
809  if (isa<UndefValue>(V1)) return V1;
810  return V2;
811  }
812 
813  if (V1 == V2) return V1;
814 
815  if (isa<PoisonValue>(V1))
816  return V2;
817  if (isa<PoisonValue>(V2))
818  return V1;
819 
820  // If the true or false value is undef, we can fold to the other value as
821  // long as the other value isn't poison.
822  auto NotPoison = [](Constant *C) {
823  if (isa<PoisonValue>(C))
824  return false;
825 
826  // TODO: We can analyze ConstExpr by opcode to determine if there is any
827  // possibility of poison.
828  if (isa<ConstantExpr>(C))
829  return false;
830 
831  if (isa<ConstantInt>(C) || isa<GlobalVariable>(C) || isa<ConstantFP>(C) ||
832  isa<ConstantPointerNull>(C) || isa<Function>(C))
833  return true;
834 
835  if (C->getType()->isVectorTy())
836  return !C->containsPoisonElement() && !C->containsConstantExpression();
837 
838  // TODO: Recursively analyze aggregates or other constants.
839  return false;
840  };
841  if (isa<UndefValue>(V1) && NotPoison(V2)) return V2;
842  if (isa<UndefValue>(V2) && NotPoison(V1)) return V1;
843 
844  if (ConstantExpr *TrueVal = dyn_cast<ConstantExpr>(V1)) {
845  if (TrueVal->getOpcode() == Instruction::Select)
846  if (TrueVal->getOperand(0) == Cond)
847  return ConstantExpr::getSelect(Cond, TrueVal->getOperand(1), V2);
848  }
849  if (ConstantExpr *FalseVal = dyn_cast<ConstantExpr>(V2)) {
850  if (FalseVal->getOpcode() == Instruction::Select)
851  if (FalseVal->getOperand(0) == Cond)
852  return ConstantExpr::getSelect(Cond, V1, FalseVal->getOperand(2));
853  }
854 
855  return nullptr;
856 }
857 
859  Constant *Idx) {
860  auto *ValVTy = cast<VectorType>(Val->getType());
861 
862  // extractelt poison, C -> poison
863  // extractelt C, undef -> poison
864  if (isa<PoisonValue>(Val) || isa<UndefValue>(Idx))
865  return PoisonValue::get(ValVTy->getElementType());
866 
867  // extractelt undef, C -> undef
868  if (isa<UndefValue>(Val))
869  return UndefValue::get(ValVTy->getElementType());
870 
871  auto *CIdx = dyn_cast<ConstantInt>(Idx);
872  if (!CIdx)
873  return nullptr;
874 
875  if (auto *ValFVTy = dyn_cast<FixedVectorType>(Val->getType())) {
876  // ee({w,x,y,z}, wrong_value) -> poison
877  if (CIdx->uge(ValFVTy->getNumElements()))
878  return PoisonValue::get(ValFVTy->getElementType());
879  }
880 
881  // ee (gep (ptr, idx0, ...), idx) -> gep (ee (ptr, idx), ee (idx0, idx), ...)
882  if (auto *CE = dyn_cast<ConstantExpr>(Val)) {
883  if (CE->getOpcode() == Instruction::GetElementPtr) {
885  Ops.reserve(CE->getNumOperands());
886  for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
887  Constant *Op = CE->getOperand(i);
888  if (Op->getType()->isVectorTy()) {
889  Constant *ScalarOp = ConstantExpr::getExtractElement(Op, Idx);
890  if (!ScalarOp)
891  return nullptr;
892  Ops.push_back(ScalarOp);
893  } else
894  Ops.push_back(Op);
895  }
896  return CE->getWithOperands(Ops, ValVTy->getElementType(), false,
897  Ops[0]->getType()->getPointerElementType());
898  } else if (CE->getOpcode() == Instruction::InsertElement) {
899  if (const auto *IEIdx = dyn_cast<ConstantInt>(CE->getOperand(2))) {
900  if (APSInt::isSameValue(APSInt(IEIdx->getValue()),
901  APSInt(CIdx->getValue()))) {
902  return CE->getOperand(1);
903  } else {
904  return ConstantExpr::getExtractElement(CE->getOperand(0), CIdx);
905  }
906  }
907  }
908  }
909 
910  // CAZ of type ScalableVectorType and n < CAZ->getMinNumElements() =>
911  // extractelt CAZ, n -> 0
912  if (auto *ValSVTy = dyn_cast<ScalableVectorType>(Val->getType())) {
913  if (!CIdx->uge(ValSVTy->getMinNumElements())) {
914  if (auto *CAZ = dyn_cast<ConstantAggregateZero>(Val))
915  return CAZ->getElementValue(CIdx->getZExtValue());
916  }
917  return nullptr;
918  }
919 
920  return Val->getAggregateElement(CIdx);
921 }
922 
924  Constant *Elt,
925  Constant *Idx) {
926  if (isa<UndefValue>(Idx))
927  return PoisonValue::get(Val->getType());
928 
929  ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx);
930  if (!CIdx) return nullptr;
931 
932  // Do not iterate on scalable vector. The num of elements is unknown at
933  // compile-time.
934  if (isa<ScalableVectorType>(Val->getType()))
935  return nullptr;
936 
937  auto *ValTy = cast<FixedVectorType>(Val->getType());
938 
939  unsigned NumElts = ValTy->getNumElements();
940  if (CIdx->uge(NumElts))
941  return UndefValue::get(Val->getType());
942 
944  Result.reserve(NumElts);
945  auto *Ty = Type::getInt32Ty(Val->getContext());
946  uint64_t IdxVal = CIdx->getZExtValue();
947  for (unsigned i = 0; i != NumElts; ++i) {
948  if (i == IdxVal) {
949  Result.push_back(Elt);
950  continue;
951  }
952 
954  Result.push_back(C);
955  }
956 
957  return ConstantVector::get(Result);
958 }
959 
962  auto *V1VTy = cast<VectorType>(V1->getType());
963  unsigned MaskNumElts = Mask.size();
964  auto MaskEltCount =
965  ElementCount::get(MaskNumElts, isa<ScalableVectorType>(V1VTy));
966  Type *EltTy = V1VTy->getElementType();
967 
968  // Undefined shuffle mask -> undefined value.
969  if (all_of(Mask, [](int Elt) { return Elt == UndefMaskElem; })) {
970  return UndefValue::get(FixedVectorType::get(EltTy, MaskNumElts));
971  }
972 
973  // If the mask is all zeros this is a splat, no need to go through all
974  // elements.
975  if (all_of(Mask, [](int Elt) { return Elt == 0; }) &&
976  !MaskEltCount.isScalable()) {
977  Type *Ty = IntegerType::get(V1->getContext(), 32);
978  Constant *Elt =
980  return ConstantVector::getSplat(MaskEltCount, Elt);
981  }
982  // Do not iterate on scalable vector. The num of elements is unknown at
983  // compile-time.
984  if (isa<ScalableVectorType>(V1VTy))
985  return nullptr;
986 
987  unsigned SrcNumElts = V1VTy->getElementCount().getKnownMinValue();
988 
989  // Loop over the shuffle mask, evaluating each element.
991  for (unsigned i = 0; i != MaskNumElts; ++i) {
992  int Elt = Mask[i];
993  if (Elt == -1) {
994  Result.push_back(UndefValue::get(EltTy));
995  continue;
996  }
997  Constant *InElt;
998  if (unsigned(Elt) >= SrcNumElts*2)
999  InElt = UndefValue::get(EltTy);
1000  else if (unsigned(Elt) >= SrcNumElts) {
1001  Type *Ty = IntegerType::get(V2->getContext(), 32);
1002  InElt =
1004  ConstantInt::get(Ty, Elt - SrcNumElts));
1005  } else {
1006  Type *Ty = IntegerType::get(V1->getContext(), 32);
1007  InElt = ConstantExpr::getExtractElement(V1, ConstantInt::get(Ty, Elt));
1008  }
1009  Result.push_back(InElt);
1010  }
1011 
1012  return ConstantVector::get(Result);
1013 }
1014 
1016  ArrayRef<unsigned> Idxs) {
1017  // Base case: no indices, so return the entire value.
1018  if (Idxs.empty())
1019  return Agg;
1020 
1021  if (Constant *C = Agg->getAggregateElement(Idxs[0]))
1022  return ConstantFoldExtractValueInstruction(C, Idxs.slice(1));
1023 
1024  return nullptr;
1025 }
1026 
1028  Constant *Val,
1029  ArrayRef<unsigned> Idxs) {
1030  // Base case: no indices, so replace the entire value.
1031  if (Idxs.empty())
1032  return Val;
1033 
1034  unsigned NumElts;
1035  if (StructType *ST = dyn_cast<StructType>(Agg->getType()))
1036  NumElts = ST->getNumElements();
1037  else
1038  NumElts = cast<ArrayType>(Agg->getType())->getNumElements();
1039 
1041  for (unsigned i = 0; i != NumElts; ++i) {
1042  Constant *C = Agg->getAggregateElement(i);
1043  if (!C) return nullptr;
1044 
1045  if (Idxs[0] == i)
1046  C = ConstantFoldInsertValueInstruction(C, Val, Idxs.slice(1));
1047 
1048  Result.push_back(C);
1049  }
1050 
1051  if (StructType *ST = dyn_cast<StructType>(Agg->getType()))
1052  return ConstantStruct::get(ST, Result);
1053  return ConstantArray::get(cast<ArrayType>(Agg->getType()), Result);
1054 }
1055 
1057  assert(Instruction::isUnaryOp(Opcode) && "Non-unary instruction detected");
1058 
1059  // Handle scalar UndefValue and scalable vector UndefValue. Fixed-length
1060  // vectors are always evaluated per element.
1061  bool IsScalableVector = isa<ScalableVectorType>(C->getType());
1062  bool HasScalarUndefOrScalableVectorUndef =
1063  (!C->getType()->isVectorTy() || IsScalableVector) && isa<UndefValue>(C);
1064 
1065  if (HasScalarUndefOrScalableVectorUndef) {
1066  switch (static_cast<Instruction::UnaryOps>(Opcode)) {
1067  case Instruction::FNeg:
1068  return C; // -undef -> undef
1069  case Instruction::UnaryOpsEnd:
1070  llvm_unreachable("Invalid UnaryOp");
1071  }
1072  }
1073 
1074  // Constant should not be UndefValue, unless these are vector constants.
1075  assert(!HasScalarUndefOrScalableVectorUndef && "Unexpected UndefValue");
1076  // We only have FP UnaryOps right now.
1077  assert(!isa<ConstantInt>(C) && "Unexpected Integer UnaryOp");
1078 
1079  if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
1080  const APFloat &CV = CFP->getValueAPF();
1081  switch (Opcode) {
1082  default:
1083  break;
1084  case Instruction::FNeg:
1085  return ConstantFP::get(C->getContext(), neg(CV));
1086  }
1087  } else if (auto *VTy = dyn_cast<FixedVectorType>(C->getType())) {
1088 
1089  Type *Ty = IntegerType::get(VTy->getContext(), 32);
1090  // Fast path for splatted constants.
1091  if (Constant *Splat = C->getSplatValue()) {
1092  Constant *Elt = ConstantExpr::get(Opcode, Splat);
1093  return ConstantVector::getSplat(VTy->getElementCount(), Elt);
1094  }
1095 
1096  // Fold each element and create a vector constant from those constants.
1098  for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1099  Constant *ExtractIdx = ConstantInt::get(Ty, i);
1100  Constant *Elt = ConstantExpr::getExtractElement(C, ExtractIdx);
1101 
1102  Result.push_back(ConstantExpr::get(Opcode, Elt));
1103  }
1104 
1105  return ConstantVector::get(Result);
1106  }
1107 
1108  // We don't know how to fold this.
1109  return nullptr;
1110 }
1111 
1113  Constant *C2) {
1114  assert(Instruction::isBinaryOp(Opcode) && "Non-binary instruction detected");
1115 
1116  // Simplify BinOps with their identity values first. They are no-ops and we
1117  // can always return the other value, including undef or poison values.
1118  // FIXME: remove unnecessary duplicated identity patterns below.
1119  // FIXME: Use AllowRHSConstant with getBinOpIdentity to handle additional ops,
1120  // like X << 0 = X.
1121  Constant *Identity = ConstantExpr::getBinOpIdentity(Opcode, C1->getType());
1122  if (Identity) {
1123  if (C1 == Identity)
1124  return C2;
1125  if (C2 == Identity)
1126  return C1;
1127  }
1128 
1129  // Binary operations propagate poison.
1130  // FIXME: Currently, or/and i1 poison aren't folded into poison because
1131  // it causes miscompilation when combined with another optimization in
1132  // InstCombine (select i1 -> and/or). The select fold is wrong, but
1133  // fixing it requires an effort, so temporarily disable this until it is
1134  // fixed.
1135  bool PoisonFold = !C1->getType()->isIntegerTy(1) ||
1136  (Opcode != Instruction::Or && Opcode != Instruction::And);
1137  if (PoisonFold && (isa<PoisonValue>(C1) || isa<PoisonValue>(C2)))
1138  return PoisonValue::get(C1->getType());
1139 
1140  // Handle scalar UndefValue and scalable vector UndefValue. Fixed-length
1141  // vectors are always evaluated per element.
1142  bool IsScalableVector = isa<ScalableVectorType>(C1->getType());
1143  bool HasScalarUndefOrScalableVectorUndef =
1144  (!C1->getType()->isVectorTy() || IsScalableVector) &&
1145  (isa<UndefValue>(C1) || isa<UndefValue>(C2));
1146  if (HasScalarUndefOrScalableVectorUndef) {
1147  switch (static_cast<Instruction::BinaryOps>(Opcode)) {
1148  case Instruction::Xor:
1149  if (isa<UndefValue>(C1) && isa<UndefValue>(C2))
1150  // Handle undef ^ undef -> 0 special case. This is a common
1151  // idiom (misuse).
1152  return Constant::getNullValue(C1->getType());
1154  case Instruction::Add:
1155  case Instruction::Sub:
1156  return UndefValue::get(C1->getType());
1157  case Instruction::And:
1158  if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) // undef & undef -> undef
1159  return C1;
1160  return Constant::getNullValue(C1->getType()); // undef & X -> 0
1161  case Instruction::Mul: {
1162  // undef * undef -> undef
1163  if (isa<UndefValue>(C1) && isa<UndefValue>(C2))
1164  return C1;
1165  const APInt *CV;
1166  // X * undef -> undef if X is odd
1167  if (match(C1, m_APInt(CV)) || match(C2, m_APInt(CV)))
1168  if ((*CV)[0])
1169  return UndefValue::get(C1->getType());
1170 
1171  // X * undef -> 0 otherwise
1172  return Constant::getNullValue(C1->getType());
1173  }
1174  case Instruction::SDiv:
1175  case Instruction::UDiv:
1176  // X / undef -> undef
1177  if (isa<UndefValue>(C2))
1178  return C2;
1179  // undef / 0 -> undef
1180  // undef / 1 -> undef
1181  if (match(C2, m_Zero()) || match(C2, m_One()))
1182  return C1;
1183  // undef / X -> 0 otherwise
1184  return Constant::getNullValue(C1->getType());
1185  case Instruction::URem:
1186  case Instruction::SRem:
1187  // X % undef -> undef
1188  if (match(C2, m_Undef()))
1189  return C2;
1190  // undef % 0 -> undef
1191  if (match(C2, m_Zero()))
1192  return C1;
1193  // undef % X -> 0 otherwise
1194  return Constant::getNullValue(C1->getType());
1195  case Instruction::Or: // X | undef -> -1
1196  if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) // undef | undef -> undef
1197  return C1;
1198  return Constant::getAllOnesValue(C1->getType()); // undef | X -> ~0
1199  case Instruction::LShr:
1200  // X >>l undef -> undef
1201  if (isa<UndefValue>(C2))
1202  return C2;
1203  // undef >>l 0 -> undef
1204  if (match(C2, m_Zero()))
1205  return C1;
1206  // undef >>l X -> 0
1207  return Constant::getNullValue(C1->getType());
1208  case Instruction::AShr:
1209  // X >>a undef -> undef
1210  if (isa<UndefValue>(C2))
1211  return C2;
1212  // undef >>a 0 -> undef
1213  if (match(C2, m_Zero()))
1214  return C1;
1215  // TODO: undef >>a X -> undef if the shift is exact
1216  // undef >>a X -> 0
1217  return Constant::getNullValue(C1->getType());
1218  case Instruction::Shl:
1219  // X << undef -> undef
1220  if (isa<UndefValue>(C2))
1221  return C2;
1222  // undef << 0 -> undef
1223  if (match(C2, m_Zero()))
1224  return C1;
1225  // undef << X -> 0
1226  return Constant::getNullValue(C1->getType());
1227  case Instruction::FSub:
1228  // -0.0 - undef --> undef (consistent with "fneg undef")
1229  if (match(C1, m_NegZeroFP()) && isa<UndefValue>(C2))
1230  return C2;
1232  case Instruction::FAdd:
1233  case Instruction::FMul:
1234  case Instruction::FDiv:
1235  case Instruction::FRem:
1236  // [any flop] undef, undef -> undef
1237  if (isa<UndefValue>(C1) && isa<UndefValue>(C2))
1238  return C1;
1239  // [any flop] C, undef -> NaN
1240  // [any flop] undef, C -> NaN
1241  // We could potentially specialize NaN/Inf constants vs. 'normal'
1242  // constants (possibly differently depending on opcode and operand). This
1243  // would allow returning undef sometimes. But it is always safe to fold to
1244  // NaN because we can choose the undef operand as NaN, and any FP opcode
1245  // with a NaN operand will propagate NaN.
1246  return ConstantFP::getNaN(C1->getType());
1247  case Instruction::BinaryOpsEnd:
1248  llvm_unreachable("Invalid BinaryOp");
1249  }
1250  }
1251 
1252  // Neither constant should be UndefValue, unless these are vector constants.
1253  assert((!HasScalarUndefOrScalableVectorUndef) && "Unexpected UndefValue");
1254 
1255  // Handle simplifications when the RHS is a constant int.
1256  if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
1257  switch (Opcode) {
1258  case Instruction::Add:
1259  if (CI2->isZero()) return C1; // X + 0 == X
1260  break;
1261  case Instruction::Sub:
1262  if (CI2->isZero()) return C1; // X - 0 == X
1263  break;
1264  case Instruction::Mul:
1265  if (CI2->isZero()) return C2; // X * 0 == 0
1266  if (CI2->isOne())
1267  return C1; // X * 1 == X
1268  break;
1269  case Instruction::UDiv:
1270  case Instruction::SDiv:
1271  if (CI2->isOne())
1272  return C1; // X / 1 == X
1273  if (CI2->isZero())
1274  return UndefValue::get(CI2->getType()); // X / 0 == undef
1275  break;
1276  case Instruction::URem:
1277  case Instruction::SRem:
1278  if (CI2->isOne())
1279  return Constant::getNullValue(CI2->getType()); // X % 1 == 0
1280  if (CI2->isZero())
1281  return UndefValue::get(CI2->getType()); // X % 0 == undef
1282  break;
1283  case Instruction::And:
1284  if (CI2->isZero()) return C2; // X & 0 == 0
1285  if (CI2->isMinusOne())
1286  return C1; // X & -1 == X
1287 
1288  if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
1289  // (zext i32 to i64) & 4294967295 -> (zext i32 to i64)
1290  if (CE1->getOpcode() == Instruction::ZExt) {
1291  unsigned DstWidth = CI2->getType()->getBitWidth();
1292  unsigned SrcWidth =
1293  CE1->getOperand(0)->getType()->getPrimitiveSizeInBits();
1294  APInt PossiblySetBits(APInt::getLowBitsSet(DstWidth, SrcWidth));
1295  if ((PossiblySetBits & CI2->getValue()) == PossiblySetBits)
1296  return C1;
1297  }
1298 
1299  // If and'ing the address of a global with a constant, fold it.
1300  if (CE1->getOpcode() == Instruction::PtrToInt &&
1301  isa<GlobalValue>(CE1->getOperand(0))) {
1302  GlobalValue *GV = cast<GlobalValue>(CE1->getOperand(0));
1303 
1304  MaybeAlign GVAlign;
1305 
1306  if (Module *TheModule = GV->getParent()) {
1307  const DataLayout &DL = TheModule->getDataLayout();
1308  GVAlign = GV->getPointerAlignment(DL);
1309 
1310  // If the function alignment is not specified then assume that it
1311  // is 4.
1312  // This is dangerous; on x86, the alignment of the pointer
1313  // corresponds to the alignment of the function, but might be less
1314  // than 4 if it isn't explicitly specified.
1315  // However, a fix for this behaviour was reverted because it
1316  // increased code size (see https://reviews.llvm.org/D55115)
1317  // FIXME: This code should be deleted once existing targets have
1318  // appropriate defaults
1319  if (isa<Function>(GV) && !DL.getFunctionPtrAlign())
1320  GVAlign = Align(4);
1321  } else if (isa<Function>(GV)) {
1322  // Without a datalayout we have to assume the worst case: that the
1323  // function pointer isn't aligned at all.
1324  GVAlign = llvm::None;
1325  } else if (isa<GlobalVariable>(GV)) {
1326  GVAlign = cast<GlobalVariable>(GV)->getAlign();
1327  }
1328 
1329  if (GVAlign && *GVAlign > 1) {
1330  unsigned DstWidth = CI2->getType()->getBitWidth();
1331  unsigned SrcWidth = std::min(DstWidth, Log2(*GVAlign));
1332  APInt BitsNotSet(APInt::getLowBitsSet(DstWidth, SrcWidth));
1333 
1334  // If checking bits we know are clear, return zero.
1335  if ((CI2->getValue() & BitsNotSet) == CI2->getValue())
1336  return Constant::getNullValue(CI2->getType());
1337  }
1338  }
1339  }
1340  break;
1341  case Instruction::Or:
1342  if (CI2->isZero()) return C1; // X | 0 == X
1343  if (CI2->isMinusOne())
1344  return C2; // X | -1 == -1
1345  break;
1346  case Instruction::Xor:
1347  if (CI2->isZero()) return C1; // X ^ 0 == X
1348 
1349  if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
1350  switch (CE1->getOpcode()) {
1351  default: break;
1352  case Instruction::ICmp:
1353  case Instruction::FCmp:
1354  // cmp pred ^ true -> cmp !pred
1355  assert(CI2->isOne());
1356  CmpInst::Predicate pred = (CmpInst::Predicate)CE1->getPredicate();
1358  return ConstantExpr::getCompare(pred, CE1->getOperand(0),
1359  CE1->getOperand(1));
1360  }
1361  }
1362  break;
1363  case Instruction::AShr:
1364  // ashr (zext C to Ty), C2 -> lshr (zext C, CSA), C2
1365  if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1))
1366  if (CE1->getOpcode() == Instruction::ZExt) // Top bits known zero.
1367  return ConstantExpr::getLShr(C1, C2);
1368  break;
1369  }
1370  } else if (isa<ConstantInt>(C1)) {
1371  // If C1 is a ConstantInt and C2 is not, swap the operands.
1372  if (Instruction::isCommutative(Opcode))
1373  return ConstantExpr::get(Opcode, C2, C1);
1374  }
1375 
1376  if (ConstantInt *CI1 = dyn_cast<ConstantInt>(C1)) {
1377  if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
1378  const APInt &C1V = CI1->getValue();
1379  const APInt &C2V = CI2->getValue();
1380  switch (Opcode) {
1381  default:
1382  break;
1383  case Instruction::Add:
1384  return ConstantInt::get(CI1->getContext(), C1V + C2V);
1385  case Instruction::Sub:
1386  return ConstantInt::get(CI1->getContext(), C1V - C2V);
1387  case Instruction::Mul:
1388  return ConstantInt::get(CI1->getContext(), C1V * C2V);
1389  case Instruction::UDiv:
1390  assert(!CI2->isZero() && "Div by zero handled above");
1391  return ConstantInt::get(CI1->getContext(), C1V.udiv(C2V));
1392  case Instruction::SDiv:
1393  assert(!CI2->isZero() && "Div by zero handled above");
1394  if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
1395  return UndefValue::get(CI1->getType()); // MIN_INT / -1 -> undef
1396  return ConstantInt::get(CI1->getContext(), C1V.sdiv(C2V));
1397  case Instruction::URem:
1398  assert(!CI2->isZero() && "Div by zero handled above");
1399  return ConstantInt::get(CI1->getContext(), C1V.urem(C2V));
1400  case Instruction::SRem:
1401  assert(!CI2->isZero() && "Div by zero handled above");
1402  if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
1403  return UndefValue::get(CI1->getType()); // MIN_INT % -1 -> undef
1404  return ConstantInt::get(CI1->getContext(), C1V.srem(C2V));
1405  case Instruction::And:
1406  return ConstantInt::get(CI1->getContext(), C1V & C2V);
1407  case Instruction::Or:
1408  return ConstantInt::get(CI1->getContext(), C1V | C2V);
1409  case Instruction::Xor:
1410  return ConstantInt::get(CI1->getContext(), C1V ^ C2V);
1411  case Instruction::Shl:
1412  if (C2V.ult(C1V.getBitWidth()))
1413  return ConstantInt::get(CI1->getContext(), C1V.shl(C2V));
1414  return UndefValue::get(C1->getType()); // too big shift is undef
1415  case Instruction::LShr:
1416  if (C2V.ult(C1V.getBitWidth()))
1417  return ConstantInt::get(CI1->getContext(), C1V.lshr(C2V));
1418  return UndefValue::get(C1->getType()); // too big shift is undef
1419  case Instruction::AShr:
1420  if (C2V.ult(C1V.getBitWidth()))
1421  return ConstantInt::get(CI1->getContext(), C1V.ashr(C2V));
1422  return UndefValue::get(C1->getType()); // too big shift is undef
1423  }
1424  }
1425 
1426  switch (Opcode) {
1427  case Instruction::SDiv:
1428  case Instruction::UDiv:
1429  case Instruction::URem:
1430  case Instruction::SRem:
1431  case Instruction::LShr:
1432  case Instruction::AShr:
1433  case Instruction::Shl:
1434  if (CI1->isZero()) return C1;
1435  break;
1436  default:
1437  break;
1438  }
1439  } else if (ConstantFP *CFP1 = dyn_cast<ConstantFP>(C1)) {
1440  if (ConstantFP *CFP2 = dyn_cast<ConstantFP>(C2)) {
1441  const APFloat &C1V = CFP1->getValueAPF();
1442  const APFloat &C2V = CFP2->getValueAPF();
1443  APFloat C3V = C1V; // copy for modification
1444  switch (Opcode) {
1445  default:
1446  break;
1447  case Instruction::FAdd:
1448  (void)C3V.add(C2V, APFloat::rmNearestTiesToEven);
1449  return ConstantFP::get(C1->getContext(), C3V);
1450  case Instruction::FSub:
1451  (void)C3V.subtract(C2V, APFloat::rmNearestTiesToEven);
1452  return ConstantFP::get(C1->getContext(), C3V);
1453  case Instruction::FMul:
1454  (void)C3V.multiply(C2V, APFloat::rmNearestTiesToEven);
1455  return ConstantFP::get(C1->getContext(), C3V);
1456  case Instruction::FDiv:
1457  (void)C3V.divide(C2V, APFloat::rmNearestTiesToEven);
1458  return ConstantFP::get(C1->getContext(), C3V);
1459  case Instruction::FRem:
1460  (void)C3V.mod(C2V);
1461  return ConstantFP::get(C1->getContext(), C3V);
1462  }
1463  }
1464  } else if (auto *VTy = dyn_cast<VectorType>(C1->getType())) {
1465  // Fast path for splatted constants.
1466  if (Constant *C2Splat = C2->getSplatValue()) {
1467  if (Instruction::isIntDivRem(Opcode) && C2Splat->isNullValue())
1468  return UndefValue::get(VTy);
1469  if (Constant *C1Splat = C1->getSplatValue()) {
1470  return ConstantVector::getSplat(
1471  VTy->getElementCount(),
1472  ConstantExpr::get(Opcode, C1Splat, C2Splat));
1473  }
1474  }
1475 
1476  if (auto *FVTy = dyn_cast<FixedVectorType>(VTy)) {
1477  // Fold each element and create a vector constant from those constants.
1479  Type *Ty = IntegerType::get(FVTy->getContext(), 32);
1480  for (unsigned i = 0, e = FVTy->getNumElements(); i != e; ++i) {
1481  Constant *ExtractIdx = ConstantInt::get(Ty, i);
1482  Constant *LHS = ConstantExpr::getExtractElement(C1, ExtractIdx);
1483  Constant *RHS = ConstantExpr::getExtractElement(C2, ExtractIdx);
1484 
1485  // If any element of a divisor vector is zero, the whole op is undef.
1486  if (Instruction::isIntDivRem(Opcode) && RHS->isNullValue())
1487  return UndefValue::get(VTy);
1488 
1489  Result.push_back(ConstantExpr::get(Opcode, LHS, RHS));
1490  }
1491 
1492  return ConstantVector::get(Result);
1493  }
1494  }
1495 
1496  if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
1497  // There are many possible foldings we could do here. We should probably
1498  // at least fold add of a pointer with an integer into the appropriate
1499  // getelementptr. This will improve alias analysis a bit.
1500 
1501  // Given ((a + b) + c), if (b + c) folds to something interesting, return
1502  // (a + (b + c)).
1503  if (Instruction::isAssociative(Opcode) && CE1->getOpcode() == Opcode) {
1504  Constant *T = ConstantExpr::get(Opcode, CE1->getOperand(1), C2);
1505  if (!isa<ConstantExpr>(T) || cast<ConstantExpr>(T)->getOpcode() != Opcode)
1506  return ConstantExpr::get(Opcode, CE1->getOperand(0), T);
1507  }
1508  } else if (isa<ConstantExpr>(C2)) {
1509  // If C2 is a constant expr and C1 isn't, flop them around and fold the
1510  // other way if possible.
1511  if (Instruction::isCommutative(Opcode))
1512  return ConstantFoldBinaryInstruction(Opcode, C2, C1);
1513  }
1514 
1515  // i1 can be simplified in many cases.
1516  if (C1->getType()->isIntegerTy(1)) {
1517  switch (Opcode) {
1518  case Instruction::Add:
1519  case Instruction::Sub:
1520  return ConstantExpr::getXor(C1, C2);
1521  case Instruction::Mul:
1522  return ConstantExpr::getAnd(C1, C2);
1523  case Instruction::Shl:
1524  case Instruction::LShr:
1525  case Instruction::AShr:
1526  // We can assume that C2 == 0. If it were one the result would be
1527  // undefined because the shift value is as large as the bitwidth.
1528  return C1;
1529  case Instruction::SDiv:
1530  case Instruction::UDiv:
1531  // We can assume that C2 == 1. If it were zero the result would be
1532  // undefined through division by zero.
1533  return C1;
1534  case Instruction::URem:
1535  case Instruction::SRem:
1536  // We can assume that C2 == 1. If it were zero the result would be
1537  // undefined through division by zero.
1538  return ConstantInt::getFalse(C1->getContext());
1539  default:
1540  break;
1541  }
1542  }
1543 
1544  // We don't know how to fold this.
1545  return nullptr;
1546 }
1547 
1548 /// This type is zero-sized if it's an array or structure of zero-sized types.
1549 /// The only leaf zero-sized type is an empty structure.
1550 static bool isMaybeZeroSizedType(Type *Ty) {
1551  if (StructType *STy = dyn_cast<StructType>(Ty)) {
1552  if (STy->isOpaque()) return true; // Can't say.
1553 
1554  // If all of elements have zero size, this does too.
1555  for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1556  if (!isMaybeZeroSizedType(STy->getElementType(i))) return false;
1557  return true;
1558 
1559  } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1560  return isMaybeZeroSizedType(ATy->getElementType());
1561  }
1562  return false;
1563 }
1564 
1565 /// Compare the two constants as though they were getelementptr indices.
1566 /// This allows coercion of the types to be the same thing.
1567 ///
1568 /// If the two constants are the "same" (after coercion), return 0. If the
1569 /// first is less than the second, return -1, if the second is less than the
1570 /// first, return 1. If the constants are not integral, return -2.
1571 ///
1572 static int IdxCompare(Constant *C1, Constant *C2, Type *ElTy) {
1573  if (C1 == C2) return 0;
1574 
1575  // Ok, we found a different index. If they are not ConstantInt, we can't do
1576  // anything with them.
1577  if (!isa<ConstantInt>(C1) || !isa<ConstantInt>(C2))
1578  return -2; // don't know!
1579 
1580  // We cannot compare the indices if they don't fit in an int64_t.
1581  if (cast<ConstantInt>(C1)->getValue().getActiveBits() > 64 ||
1582  cast<ConstantInt>(C2)->getValue().getActiveBits() > 64)
1583  return -2; // don't know!
1584 
1585  // Ok, we have two differing integer indices. Sign extend them to be the same
1586  // type.
1587  int64_t C1Val = cast<ConstantInt>(C1)->getSExtValue();
1588  int64_t C2Val = cast<ConstantInt>(C2)->getSExtValue();
1589 
1590  if (C1Val == C2Val) return 0; // They are equal
1591 
1592  // If the type being indexed over is really just a zero sized type, there is
1593  // no pointer difference being made here.
1594  if (isMaybeZeroSizedType(ElTy))
1595  return -2; // dunno.
1596 
1597  // If they are really different, now that they are the same type, then we
1598  // found a difference!
1599  if (C1Val < C2Val)
1600  return -1;
1601  else
1602  return 1;
1603 }
1604 
1605 /// This function determines if there is anything we can decide about the two
1606 /// constants provided. This doesn't need to handle simple things like
1607 /// ConstantFP comparisons, but should instead handle ConstantExprs.
1608 /// If we can determine that the two constants have a particular relation to
1609 /// each other, we should return the corresponding FCmpInst predicate,
1610 /// otherwise return FCmpInst::BAD_FCMP_PREDICATE. This is used below in
1611 /// ConstantFoldCompareInstruction.
1612 ///
1613 /// To simplify this code we canonicalize the relation so that the first
1614 /// operand is always the most "complex" of the two. We consider ConstantFP
1615 /// to be the simplest, and ConstantExprs to be the most complex.
1617  assert(V1->getType() == V2->getType() &&
1618  "Cannot compare values of different types!");
1619 
1620  // We do not know if a constant expression will evaluate to a number or NaN.
1621  // Therefore, we can only say that the relation is unordered or equal.
1622  if (V1 == V2) return FCmpInst::FCMP_UEQ;
1623 
1624  if (!isa<ConstantExpr>(V1)) {
1625  if (!isa<ConstantExpr>(V2)) {
1626  // Simple case, use the standard constant folder.
1627  ConstantInt *R = nullptr;
1628  R = dyn_cast<ConstantInt>(
1630  if (R && !R->isZero())
1631  return FCmpInst::FCMP_OEQ;
1632  R = dyn_cast<ConstantInt>(
1634  if (R && !R->isZero())
1635  return FCmpInst::FCMP_OLT;
1636  R = dyn_cast<ConstantInt>(
1638  if (R && !R->isZero())
1639  return FCmpInst::FCMP_OGT;
1640 
1641  // Nothing more we can do
1643  }
1644 
1645  // If the first operand is simple and second is ConstantExpr, swap operands.
1646  FCmpInst::Predicate SwappedRelation = evaluateFCmpRelation(V2, V1);
1647  if (SwappedRelation != FCmpInst::BAD_FCMP_PREDICATE)
1648  return FCmpInst::getSwappedPredicate(SwappedRelation);
1649  } else {
1650  // Ok, the LHS is known to be a constantexpr. The RHS can be any of a
1651  // constantexpr or a simple constant.
1652  ConstantExpr *CE1 = cast<ConstantExpr>(V1);
1653  switch (CE1->getOpcode()) {
1654  case Instruction::FPTrunc:
1655  case Instruction::FPExt:
1656  case Instruction::UIToFP:
1657  case Instruction::SIToFP:
1658  // We might be able to do something with these but we don't right now.
1659  break;
1660  default:
1661  break;
1662  }
1663  }
1664  // There are MANY other foldings that we could perform here. They will
1665  // probably be added on demand, as they seem needed.
1667 }
1668 
1670  const GlobalValue *GV2) {
1671  auto isGlobalUnsafeForEquality = [](const GlobalValue *GV) {
1672  if (GV->isInterposable() || GV->hasGlobalUnnamedAddr())
1673  return true;
1674  if (const auto *GVar = dyn_cast<GlobalVariable>(GV)) {
1675  Type *Ty = GVar->getValueType();
1676  // A global with opaque type might end up being zero sized.
1677  if (!Ty->isSized())
1678  return true;
1679  // A global with an empty type might lie at the address of any other
1680  // global.
1681  if (Ty->isEmptyTy())
1682  return true;
1683  }
1684  return false;
1685  };
1686  // Don't try to decide equality of aliases.
1687  if (!isa<GlobalAlias>(GV1) && !isa<GlobalAlias>(GV2))
1688  if (!isGlobalUnsafeForEquality(GV1) && !isGlobalUnsafeForEquality(GV2))
1689  return ICmpInst::ICMP_NE;
1691 }
1692 
1693 /// This function determines if there is anything we can decide about the two
1694 /// constants provided. This doesn't need to handle simple things like integer
1695 /// comparisons, but should instead handle ConstantExprs and GlobalValues.
1696 /// If we can determine that the two constants have a particular relation to
1697 /// each other, we should return the corresponding ICmp predicate, otherwise
1698 /// return ICmpInst::BAD_ICMP_PREDICATE.
1699 ///
1700 /// To simplify this code we canonicalize the relation so that the first
1701 /// operand is always the most "complex" of the two. We consider simple
1702 /// constants (like ConstantInt) to be the simplest, followed by
1703 /// GlobalValues, followed by ConstantExpr's (the most complex).
1704 ///
1706  bool isSigned) {
1707  assert(V1->getType() == V2->getType() &&
1708  "Cannot compare different types of values!");
1709  if (V1 == V2) return ICmpInst::ICMP_EQ;
1710 
1711  if (!isa<ConstantExpr>(V1) && !isa<GlobalValue>(V1) &&
1712  !isa<BlockAddress>(V1)) {
1713  if (!isa<GlobalValue>(V2) && !isa<ConstantExpr>(V2) &&
1714  !isa<BlockAddress>(V2)) {
1715  // We distilled this down to a simple case, use the standard constant
1716  // folder.
1717  ConstantInt *R = nullptr;
1719  R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
1720  if (R && !R->isZero())
1721  return pred;
1723  R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
1724  if (R && !R->isZero())
1725  return pred;
1727  R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
1728  if (R && !R->isZero())
1729  return pred;
1730 
1731  // If we couldn't figure it out, bail.
1733  }
1734 
1735  // If the first operand is simple, swap operands.
1736  ICmpInst::Predicate SwappedRelation =
1737  evaluateICmpRelation(V2, V1, isSigned);
1738  if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1739  return ICmpInst::getSwappedPredicate(SwappedRelation);
1740 
1741  } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V1)) {
1742  if (isa<ConstantExpr>(V2)) { // Swap as necessary.
1743  ICmpInst::Predicate SwappedRelation =
1744  evaluateICmpRelation(V2, V1, isSigned);
1745  if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1746  return ICmpInst::getSwappedPredicate(SwappedRelation);
1748  }
1749 
1750  // Now we know that the RHS is a GlobalValue, BlockAddress or simple
1751  // constant (which, since the types must match, means that it's a
1752  // ConstantPointerNull).
1753  if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) {
1754  return areGlobalsPotentiallyEqual(GV, GV2);
1755  } else if (isa<BlockAddress>(V2)) {
1756  return ICmpInst::ICMP_NE; // Globals never equal labels.
1757  } else {
1758  assert(isa<ConstantPointerNull>(V2) && "Canonicalization guarantee!");
1759  // GlobalVals can never be null unless they have external weak linkage.
1760  // We don't try to evaluate aliases here.
1761  // NOTE: We should not be doing this constant folding if null pointer
1762  // is considered valid for the function. But currently there is no way to
1763  // query it from the Constant type.
1764  if (!GV->hasExternalWeakLinkage() && !isa<GlobalAlias>(GV) &&
1765  !NullPointerIsDefined(nullptr /* F */,
1766  GV->getType()->getAddressSpace()))
1767  return ICmpInst::ICMP_UGT;
1768  }
1769  } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(V1)) {
1770  if (isa<ConstantExpr>(V2)) { // Swap as necessary.
1771  ICmpInst::Predicate SwappedRelation =
1772  evaluateICmpRelation(V2, V1, isSigned);
1773  if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1774  return ICmpInst::getSwappedPredicate(SwappedRelation);
1776  }
1777 
1778  // Now we know that the RHS is a GlobalValue, BlockAddress or simple
1779  // constant (which, since the types must match, means that it is a
1780  // ConstantPointerNull).
1781  if (const BlockAddress *BA2 = dyn_cast<BlockAddress>(V2)) {
1782  // Block address in another function can't equal this one, but block
1783  // addresses in the current function might be the same if blocks are
1784  // empty.
1785  if (BA2->getFunction() != BA->getFunction())
1786  return ICmpInst::ICMP_NE;
1787  } else {
1788  // Block addresses aren't null, don't equal the address of globals.
1789  assert((isa<ConstantPointerNull>(V2) || isa<GlobalValue>(V2)) &&
1790  "Canonicalization guarantee!");
1791  return ICmpInst::ICMP_NE;
1792  }
1793  } else {
1794  // Ok, the LHS is known to be a constantexpr. The RHS can be any of a
1795  // constantexpr, a global, block address, or a simple constant.
1796  ConstantExpr *CE1 = cast<ConstantExpr>(V1);
1797  Constant *CE1Op0 = CE1->getOperand(0);
1798 
1799  switch (CE1->getOpcode()) {
1800  case Instruction::Trunc:
1801  case Instruction::FPTrunc:
1802  case Instruction::FPExt:
1803  case Instruction::FPToUI:
1804  case Instruction::FPToSI:
1805  break; // We can't evaluate floating point casts or truncations.
1806 
1807  case Instruction::BitCast:
1808  // If this is a global value cast, check to see if the RHS is also a
1809  // GlobalValue.
1810  if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0))
1811  if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2))
1812  return areGlobalsPotentiallyEqual(GV, GV2);
1814  case Instruction::UIToFP:
1815  case Instruction::SIToFP:
1816  case Instruction::ZExt:
1817  case Instruction::SExt:
1818  // We can't evaluate floating point casts or truncations.
1819  if (CE1Op0->getType()->isFPOrFPVectorTy())
1820  break;
1821 
1822  // If the cast is not actually changing bits, and the second operand is a
1823  // null pointer, do the comparison with the pre-casted value.
1824  if (V2->isNullValue() && CE1->getType()->isIntOrPtrTy()) {
1825  if (CE1->getOpcode() == Instruction::ZExt) isSigned = false;
1826  if (CE1->getOpcode() == Instruction::SExt) isSigned = true;
1827  return evaluateICmpRelation(CE1Op0,
1828  Constant::getNullValue(CE1Op0->getType()),
1829  isSigned);
1830  }
1831  break;
1832 
1833  case Instruction::GetElementPtr: {
1834  GEPOperator *CE1GEP = cast<GEPOperator>(CE1);
1835  // Ok, since this is a getelementptr, we know that the constant has a
1836  // pointer type. Check the various cases.
1837  if (isa<ConstantPointerNull>(V2)) {
1838  // If we are comparing a GEP to a null pointer, check to see if the base
1839  // of the GEP equals the null pointer.
1840  if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
1841  // If its not weak linkage, the GVal must have a non-zero address
1842  // so the result is greater-than
1843  if (!GV->hasExternalWeakLinkage())
1844  return ICmpInst::ICMP_UGT;
1845  } else if (isa<ConstantPointerNull>(CE1Op0)) {
1846  // If we are indexing from a null pointer, check to see if we have any
1847  // non-zero indices.
1848  for (unsigned i = 1, e = CE1->getNumOperands(); i != e; ++i)
1849  if (!CE1->getOperand(i)->isNullValue())
1850  // Offsetting from null, must not be equal.
1851  return ICmpInst::ICMP_UGT;
1852  // Only zero indexes from null, must still be zero.
1853  return ICmpInst::ICMP_EQ;
1854  }
1855  // Otherwise, we can't really say if the first operand is null or not.
1856  } else if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) {
1857  if (isa<ConstantPointerNull>(CE1Op0)) {
1858  // If its not weak linkage, the GVal must have a non-zero address
1859  // so the result is less-than
1860  if (!GV2->hasExternalWeakLinkage())
1861  return ICmpInst::ICMP_ULT;
1862  } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
1863  if (GV == GV2) {
1864  // If this is a getelementptr of the same global, then it must be
1865  // different. Because the types must match, the getelementptr could
1866  // only have at most one index, and because we fold getelementptr's
1867  // with a single zero index, it must be nonzero.
1868  assert(CE1->getNumOperands() == 2 &&
1869  !CE1->getOperand(1)->isNullValue() &&
1870  "Surprising getelementptr!");
1871  return ICmpInst::ICMP_UGT;
1872  } else {
1873  if (CE1GEP->hasAllZeroIndices())
1874  return areGlobalsPotentiallyEqual(GV, GV2);
1876  }
1877  }
1878  } else {
1879  ConstantExpr *CE2 = cast<ConstantExpr>(V2);
1880  Constant *CE2Op0 = CE2->getOperand(0);
1881 
1882  // There are MANY other foldings that we could perform here. They will
1883  // probably be added on demand, as they seem needed.
1884  switch (CE2->getOpcode()) {
1885  default: break;
1886  case Instruction::GetElementPtr:
1887  // By far the most common case to handle is when the base pointers are
1888  // obviously to the same global.
1889  if (isa<GlobalValue>(CE1Op0) && isa<GlobalValue>(CE2Op0)) {
1890  // Don't know relative ordering, but check for inequality.
1891  if (CE1Op0 != CE2Op0) {
1892  GEPOperator *CE2GEP = cast<GEPOperator>(CE2);
1893  if (CE1GEP->hasAllZeroIndices() && CE2GEP->hasAllZeroIndices())
1894  return areGlobalsPotentiallyEqual(cast<GlobalValue>(CE1Op0),
1895  cast<GlobalValue>(CE2Op0));
1897  }
1898  // Ok, we know that both getelementptr instructions are based on the
1899  // same global. From this, we can precisely determine the relative
1900  // ordering of the resultant pointers.
1901  unsigned i = 1;
1902 
1903  // The logic below assumes that the result of the comparison
1904  // can be determined by finding the first index that differs.
1905  // This doesn't work if there is over-indexing in any
1906  // subsequent indices, so check for that case first.
1907  if (!CE1->isGEPWithNoNotionalOverIndexing() ||
1909  return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1910 
1911  // Compare all of the operands the GEP's have in common.
1912  gep_type_iterator GTI = gep_type_begin(CE1);
1913  for (;i != CE1->getNumOperands() && i != CE2->getNumOperands();
1914  ++i, ++GTI)
1915  switch (IdxCompare(CE1->getOperand(i),
1916  CE2->getOperand(i), GTI.getIndexedType())) {
1917  case -1: return isSigned ? ICmpInst::ICMP_SLT:ICmpInst::ICMP_ULT;
1918  case 1: return isSigned ? ICmpInst::ICMP_SGT:ICmpInst::ICMP_UGT;
1919  case -2: return ICmpInst::BAD_ICMP_PREDICATE;
1920  }
1921 
1922  // Ok, we ran out of things they have in common. If any leftovers
1923  // are non-zero then we have a difference, otherwise we are equal.
1924  for (; i < CE1->getNumOperands(); ++i)
1925  if (!CE1->getOperand(i)->isNullValue()) {
1926  if (isa<ConstantInt>(CE1->getOperand(i)))
1927  return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1928  else
1929  return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1930  }
1931 
1932  for (; i < CE2->getNumOperands(); ++i)
1933  if (!CE2->getOperand(i)->isNullValue()) {
1934  if (isa<ConstantInt>(CE2->getOperand(i)))
1935  return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1936  else
1937  return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1938  }
1939  return ICmpInst::ICMP_EQ;
1940  }
1941  }
1942  }
1943  break;
1944  }
1945  default:
1946  break;
1947  }
1948  }
1949 
1951 }
1952 
1954  Constant *C1, Constant *C2) {
1955  Type *ResultTy;
1956  if (VectorType *VT = dyn_cast<VectorType>(C1->getType()))
1957  ResultTy = VectorType::get(Type::getInt1Ty(C1->getContext()),
1958  VT->getElementCount());
1959  else
1960  ResultTy = Type::getInt1Ty(C1->getContext());
1961 
1962  // Fold FCMP_FALSE/FCMP_TRUE unconditionally.
1963  if (pred == FCmpInst::FCMP_FALSE)
1964  return Constant::getNullValue(ResultTy);
1965 
1966  if (pred == FCmpInst::FCMP_TRUE)
1967  return Constant::getAllOnesValue(ResultTy);
1968 
1969  // Handle some degenerate cases first
1970  if (isa<PoisonValue>(C1) || isa<PoisonValue>(C2))
1971  return PoisonValue::get(ResultTy);
1972 
1973  if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
1975  bool isIntegerPredicate = ICmpInst::isIntPredicate(Predicate);
1976  // For EQ and NE, we can always pick a value for the undef to make the
1977  // predicate pass or fail, so we can return undef.
1978  // Also, if both operands are undef, we can return undef for int comparison.
1979  if (ICmpInst::isEquality(Predicate) || (isIntegerPredicate && C1 == C2))
1980  return UndefValue::get(ResultTy);
1981 
1982  // Otherwise, for integer compare, pick the same value as the non-undef
1983  // operand, and fold it to true or false.
1984  if (isIntegerPredicate)
1986 
1987  // Choosing NaN for the undef will always make unordered comparison succeed
1988  // and ordered comparison fails.
1989  return ConstantInt::get(ResultTy, CmpInst::isUnordered(Predicate));
1990  }
1991 
1992  // icmp eq/ne(null,GV) -> false/true
1993  if (C1->isNullValue()) {
1994  if (const GlobalValue *GV = dyn_cast<GlobalValue>(C2))
1995  // Don't try to evaluate aliases. External weak GV can be null.
1996  if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage() &&
1997  !NullPointerIsDefined(nullptr /* F */,
1998  GV->getType()->getAddressSpace())) {
1999  if (pred == ICmpInst::ICMP_EQ)
2000  return ConstantInt::getFalse(C1->getContext());
2001  else if (pred == ICmpInst::ICMP_NE)
2002  return ConstantInt::getTrue(C1->getContext());
2003  }
2004  // icmp eq/ne(GV,null) -> false/true
2005  } else if (C2->isNullValue()) {
2006  if (const GlobalValue *GV = dyn_cast<GlobalValue>(C1)) {
2007  // Don't try to evaluate aliases. External weak GV can be null.
2008  if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage() &&
2009  !NullPointerIsDefined(nullptr /* F */,
2010  GV->getType()->getAddressSpace())) {
2011  if (pred == ICmpInst::ICMP_EQ)
2012  return ConstantInt::getFalse(C1->getContext());
2013  else if (pred == ICmpInst::ICMP_NE)
2014  return ConstantInt::getTrue(C1->getContext());
2015  }
2016  }
2017 
2018  // The caller is expected to commute the operands if the constant expression
2019  // is C2.
2020  // C1 >= 0 --> true
2021  if (pred == ICmpInst::ICMP_UGE)
2022  return Constant::getAllOnesValue(ResultTy);
2023  // C1 < 0 --> false
2024  if (pred == ICmpInst::ICMP_ULT)
2025  return Constant::getNullValue(ResultTy);
2026  }
2027 
2028  // If the comparison is a comparison between two i1's, simplify it.
2029  if (C1->getType()->isIntegerTy(1)) {
2030  switch(pred) {
2031  case ICmpInst::ICMP_EQ:
2032  if (isa<ConstantInt>(C2))
2035  case ICmpInst::ICMP_NE:
2036  return ConstantExpr::getXor(C1, C2);
2037  default:
2038  break;
2039  }
2040  }
2041 
2042  if (isa<ConstantInt>(C1) && isa<ConstantInt>(C2)) {
2043  const APInt &V1 = cast<ConstantInt>(C1)->getValue();
2044  const APInt &V2 = cast<ConstantInt>(C2)->getValue();
2045  switch (pred) {
2046  default: llvm_unreachable("Invalid ICmp Predicate");
2047  case ICmpInst::ICMP_EQ: return ConstantInt::get(ResultTy, V1 == V2);
2048  case ICmpInst::ICMP_NE: return ConstantInt::get(ResultTy, V1 != V2);
2049  case ICmpInst::ICMP_SLT: return ConstantInt::get(ResultTy, V1.slt(V2));
2050  case ICmpInst::ICMP_SGT: return ConstantInt::get(ResultTy, V1.sgt(V2));
2051  case ICmpInst::ICMP_SLE: return ConstantInt::get(ResultTy, V1.sle(V2));
2052  case ICmpInst::ICMP_SGE: return ConstantInt::get(ResultTy, V1.sge(V2));
2053  case ICmpInst::ICMP_ULT: return ConstantInt::get(ResultTy, V1.ult(V2));
2054  case ICmpInst::ICMP_UGT: return ConstantInt::get(ResultTy, V1.ugt(V2));
2055  case ICmpInst::ICMP_ULE: return ConstantInt::get(ResultTy, V1.ule(V2));
2056  case ICmpInst::ICMP_UGE: return ConstantInt::get(ResultTy, V1.uge(V2));
2057  }
2058  } else if (isa<ConstantFP>(C1) && isa<ConstantFP>(C2)) {
2059  const APFloat &C1V = cast<ConstantFP>(C1)->getValueAPF();
2060  const APFloat &C2V = cast<ConstantFP>(C2)->getValueAPF();
2061  APFloat::cmpResult R = C1V.compare(C2V);
2062  switch (pred) {
2063  default: llvm_unreachable("Invalid FCmp Predicate");
2064  case FCmpInst::FCMP_FALSE: return Constant::getNullValue(ResultTy);
2065  case FCmpInst::FCMP_TRUE: return Constant::getAllOnesValue(ResultTy);
2066  case FCmpInst::FCMP_UNO:
2067  return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered);
2068  case FCmpInst::FCMP_ORD:
2069  return ConstantInt::get(ResultTy, R!=APFloat::cmpUnordered);
2070  case FCmpInst::FCMP_UEQ:
2071  return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
2072  R==APFloat::cmpEqual);
2073  case FCmpInst::FCMP_OEQ:
2074  return ConstantInt::get(ResultTy, R==APFloat::cmpEqual);
2075  case FCmpInst::FCMP_UNE:
2076  return ConstantInt::get(ResultTy, R!=APFloat::cmpEqual);
2077  case FCmpInst::FCMP_ONE:
2078  return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan ||
2080  case FCmpInst::FCMP_ULT:
2081  return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
2083  case FCmpInst::FCMP_OLT:
2084  return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan);
2085  case FCmpInst::FCMP_UGT:
2086  return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
2088  case FCmpInst::FCMP_OGT:
2089  return ConstantInt::get(ResultTy, R==APFloat::cmpGreaterThan);
2090  case FCmpInst::FCMP_ULE:
2091  return ConstantInt::get(ResultTy, R!=APFloat::cmpGreaterThan);
2092  case FCmpInst::FCMP_OLE:
2093  return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan ||
2094  R==APFloat::cmpEqual);
2095  case FCmpInst::FCMP_UGE:
2096  return ConstantInt::get(ResultTy, R!=APFloat::cmpLessThan);
2097  case FCmpInst::FCMP_OGE:
2098  return ConstantInt::get(ResultTy, R==APFloat::cmpGreaterThan ||
2099  R==APFloat::cmpEqual);
2100  }
2101  } else if (auto *C1VTy = dyn_cast<VectorType>(C1->getType())) {
2102 
2103  // Fast path for splatted constants.
2104  if (Constant *C1Splat = C1->getSplatValue())
2105  if (Constant *C2Splat = C2->getSplatValue())
2106  return ConstantVector::getSplat(
2107  C1VTy->getElementCount(),
2108  ConstantExpr::getCompare(pred, C1Splat, C2Splat));
2109 
2110  // Do not iterate on scalable vector. The number of elements is unknown at
2111  // compile-time.
2112  if (isa<ScalableVectorType>(C1VTy))
2113  return nullptr;
2114 
2115  // If we can constant fold the comparison of each element, constant fold
2116  // the whole vector comparison.
2117  SmallVector<Constant*, 4> ResElts;
2118  Type *Ty = IntegerType::get(C1->getContext(), 32);
2119  // Compare the elements, producing an i1 result or constant expr.
2120  for (unsigned I = 0, E = C1VTy->getElementCount().getKnownMinValue();
2121  I != E; ++I) {
2122  Constant *C1E =
2124  Constant *C2E =
2126 
2127  ResElts.push_back(ConstantExpr::getCompare(pred, C1E, C2E));
2128  }
2129 
2130  return ConstantVector::get(ResElts);
2131  }
2132 
2133  if (C1->getType()->isFloatingPointTy() &&
2134  // Only call evaluateFCmpRelation if we have a constant expr to avoid
2135  // infinite recursive loop
2136  (isa<ConstantExpr>(C1) || isa<ConstantExpr>(C2))) {
2137  int Result = -1; // -1 = unknown, 0 = known false, 1 = known true.
2138  switch (evaluateFCmpRelation(C1, C2)) {
2139  default: llvm_unreachable("Unknown relation!");
2140  case FCmpInst::FCMP_UNO:
2141  case FCmpInst::FCMP_ORD:
2142  case FCmpInst::FCMP_UNE:
2143  case FCmpInst::FCMP_ULT:
2144  case FCmpInst::FCMP_UGT:
2145  case FCmpInst::FCMP_ULE:
2146  case FCmpInst::FCMP_UGE:
2147  case FCmpInst::FCMP_TRUE:
2148  case FCmpInst::FCMP_FALSE:
2150  break; // Couldn't determine anything about these constants.
2151  case FCmpInst::FCMP_OEQ: // We know that C1 == C2
2152  Result = (pred == FCmpInst::FCMP_UEQ || pred == FCmpInst::FCMP_OEQ ||
2155  break;
2156  case FCmpInst::FCMP_OLT: // We know that C1 < C2
2157  Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
2160  break;
2161  case FCmpInst::FCMP_OGT: // We know that C1 > C2
2162  Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
2165  break;
2166  case FCmpInst::FCMP_OLE: // We know that C1 <= C2
2167  // We can only partially decide this relation.
2169  Result = 0;
2170  else if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT)
2171  Result = 1;
2172  break;
2173  case FCmpInst::FCMP_OGE: // We known that C1 >= C2
2174  // We can only partially decide this relation.
2176  Result = 0;
2177  else if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT)
2178  Result = 1;
2179  break;
2180  case FCmpInst::FCMP_ONE: // We know that C1 != C2
2181  // We can only partially decide this relation.
2183  Result = 0;
2184  else if (pred == FCmpInst::FCMP_ONE || pred == FCmpInst::FCMP_UNE)
2185  Result = 1;
2186  break;
2187  case FCmpInst::FCMP_UEQ: // We know that C1 == C2 || isUnordered(C1, C2).
2188  // We can only partially decide this relation.
2189  if (pred == FCmpInst::FCMP_ONE)
2190  Result = 0;
2191  else if (pred == FCmpInst::FCMP_UEQ)
2192  Result = 1;
2193  break;
2194  }
2195 
2196  // If we evaluated the result, return it now.
2197  if (Result != -1)
2198  return ConstantInt::get(ResultTy, Result);
2199 
2200  } else {
2201  // Evaluate the relation between the two constants, per the predicate.
2202  int Result = -1; // -1 = unknown, 0 = known false, 1 = known true.
2203  switch (evaluateICmpRelation(C1, C2,
2205  default: llvm_unreachable("Unknown relational!");
2207  break; // Couldn't determine anything about these constants.
2208  case ICmpInst::ICMP_EQ: // We know the constants are equal!
2209  // If we know the constants are equal, we can decide the result of this
2210  // computation precisely.
2212  break;
2213  case ICmpInst::ICMP_ULT:
2214  switch (pred) {
2216  Result = 1; break;
2218  Result = 0; break;
2219  }
2220  break;
2221  case ICmpInst::ICMP_SLT:
2222  switch (pred) {
2224  Result = 1; break;
2226  Result = 0; break;
2227  }
2228  break;
2229  case ICmpInst::ICMP_UGT:
2230  switch (pred) {
2232  Result = 1; break;
2234  Result = 0; break;
2235  }
2236  break;
2237  case ICmpInst::ICMP_SGT:
2238  switch (pred) {
2240  Result = 1; break;
2242  Result = 0; break;
2243  }
2244  break;
2245  case ICmpInst::ICMP_ULE:
2246  if (pred == ICmpInst::ICMP_UGT) Result = 0;
2247  if (pred == ICmpInst::ICMP_ULT || pred == ICmpInst::ICMP_ULE) Result = 1;
2248  break;
2249  case ICmpInst::ICMP_SLE:
2250  if (pred == ICmpInst::ICMP_SGT) Result = 0;
2251  if (pred == ICmpInst::ICMP_SLT || pred == ICmpInst::ICMP_SLE) Result = 1;
2252  break;
2253  case ICmpInst::ICMP_UGE:
2254  if (pred == ICmpInst::ICMP_ULT) Result = 0;
2255  if (pred == ICmpInst::ICMP_UGT || pred == ICmpInst::ICMP_UGE) Result = 1;
2256  break;
2257  case ICmpInst::ICMP_SGE:
2258  if (pred == ICmpInst::ICMP_SLT) Result = 0;
2259  if (pred == ICmpInst::ICMP_SGT || pred == ICmpInst::ICMP_SGE) Result = 1;
2260  break;
2261  case ICmpInst::ICMP_NE:
2262  if (pred == ICmpInst::ICMP_EQ) Result = 0;
2263  if (pred == ICmpInst::ICMP_NE) Result = 1;
2264  break;
2265  }
2266 
2267  // If we evaluated the result, return it now.
2268  if (Result != -1)
2269  return ConstantInt::get(ResultTy, Result);
2270 
2271  // If the right hand side is a bitcast, try using its inverse to simplify
2272  // it by moving it to the left hand side. We can't do this if it would turn
2273  // a vector compare into a scalar compare or visa versa, or if it would turn
2274  // the operands into FP values.
2275  if (ConstantExpr *CE2 = dyn_cast<ConstantExpr>(C2)) {
2276  Constant *CE2Op0 = CE2->getOperand(0);
2277  if (CE2->getOpcode() == Instruction::BitCast &&
2278  CE2->getType()->isVectorTy() == CE2Op0->getType()->isVectorTy() &&
2279  !CE2Op0->getType()->isFPOrFPVectorTy()) {
2281  return ConstantExpr::getICmp(pred, Inverse, CE2Op0);
2282  }
2283  }
2284 
2285  // If the left hand side is an extension, try eliminating it.
2286  if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
2287  if ((CE1->getOpcode() == Instruction::SExt &&
2289  (CE1->getOpcode() == Instruction::ZExt &&
2291  Constant *CE1Op0 = CE1->getOperand(0);
2292  Constant *CE1Inverse = ConstantExpr::getTrunc(CE1, CE1Op0->getType());
2293  if (CE1Inverse == CE1Op0) {
2294  // Check whether we can safely truncate the right hand side.
2295  Constant *C2Inverse = ConstantExpr::getTrunc(C2, CE1Op0->getType());
2296  if (ConstantExpr::getCast(CE1->getOpcode(), C2Inverse,
2297  C2->getType()) == C2)
2298  return ConstantExpr::getICmp(pred, CE1Inverse, C2Inverse);
2299  }
2300  }
2301  }
2302 
2303  if ((!isa<ConstantExpr>(C1) && isa<ConstantExpr>(C2)) ||
2304  (C1->isNullValue() && !C2->isNullValue())) {
2305  // If C2 is a constant expr and C1 isn't, flip them around and fold the
2306  // other way if possible.
2307  // Also, if C1 is null and C2 isn't, flip them around.
2309  return ConstantExpr::getICmp(pred, C2, C1);
2310  }
2311  }
2312  return nullptr;
2313 }
2314 
2315 /// Test whether the given sequence of *normalized* indices is "inbounds".
2316 template<typename IndexTy>
2318  // No indices means nothing that could be out of bounds.
2319  if (Idxs.empty()) return true;
2320 
2321  // If the first index is zero, it's in bounds.
2322  if (cast<Constant>(Idxs[0])->isNullValue()) return true;
2323 
2324  // If the first index is one and all the rest are zero, it's in bounds,
2325  // by the one-past-the-end rule.
2326  if (auto *CI = dyn_cast<ConstantInt>(Idxs[0])) {
2327  if (!CI->isOne())
2328  return false;
2329  } else {
2330  auto *CV = cast<ConstantDataVector>(Idxs[0]);
2331  CI = dyn_cast_or_null<ConstantInt>(CV->getSplatValue());
2332  if (!CI || !CI->isOne())
2333  return false;
2334  }
2335 
2336  for (unsigned i = 1, e = Idxs.size(); i != e; ++i)
2337  if (!cast<Constant>(Idxs[i])->isNullValue())
2338  return false;
2339  return true;
2340 }
2341 
2342 /// Test whether a given ConstantInt is in-range for a SequentialType.
2343 static bool isIndexInRangeOfArrayType(uint64_t NumElements,
2344  const ConstantInt *CI) {
2345  // We cannot bounds check the index if it doesn't fit in an int64_t.
2346  if (CI->getValue().getMinSignedBits() > 64)
2347  return false;
2348 
2349  // A negative index or an index past the end of our sequential type is
2350  // considered out-of-range.
2351  int64_t IndexVal = CI->getSExtValue();
2352  if (IndexVal < 0 || (NumElements > 0 && (uint64_t)IndexVal >= NumElements))
2353  return false;
2354 
2355  // Otherwise, it is in-range.
2356  return true;
2357 }
2358 
2360  bool InBounds,
2361  Optional<unsigned> InRangeIndex,
2362  ArrayRef<Value *> Idxs) {
2363  if (Idxs.empty()) return C;
2364 
2366  PointeeTy, C, makeArrayRef((Value *const *)Idxs.data(), Idxs.size()));
2367 
2368  if (isa<PoisonValue>(C))
2369  return PoisonValue::get(GEPTy);
2370 
2371  if (isa<UndefValue>(C))
2372  return UndefValue::get(GEPTy);
2373 
2374  Constant *Idx0 = cast<Constant>(Idxs[0]);
2375  if (Idxs.size() == 1 && (Idx0->isNullValue() || isa<UndefValue>(Idx0)))
2376  return GEPTy->isVectorTy() && !C->getType()->isVectorTy()
2378  cast<VectorType>(GEPTy)->getElementCount(), C)
2379  : C;
2380 
2381  if (C->isNullValue()) {
2382  bool isNull = true;
2383  for (unsigned i = 0, e = Idxs.size(); i != e; ++i)
2384  if (!isa<UndefValue>(Idxs[i]) &&
2385  !cast<Constant>(Idxs[i])->isNullValue()) {
2386  isNull = false;
2387  break;
2388  }
2389  if (isNull) {
2390  PointerType *PtrTy = cast<PointerType>(C->getType()->getScalarType());
2391  Type *Ty = GetElementPtrInst::getIndexedType(PointeeTy, Idxs);
2392 
2393  assert(Ty && "Invalid indices for GEP!");
2394  Type *OrigGEPTy = PointerType::get(Ty, PtrTy->getAddressSpace());
2395  Type *GEPTy = PointerType::get(Ty, PtrTy->getAddressSpace());
2396  if (VectorType *VT = dyn_cast<VectorType>(C->getType()))
2397  GEPTy = VectorType::get(OrigGEPTy, VT->getElementCount());
2398 
2399  // The GEP returns a vector of pointers when one of more of
2400  // its arguments is a vector.
2401  for (unsigned i = 0, e = Idxs.size(); i != e; ++i) {
2402  if (auto *VT = dyn_cast<VectorType>(Idxs[i]->getType())) {
2403  assert((!isa<VectorType>(GEPTy) || isa<ScalableVectorType>(GEPTy) ==
2404  isa<ScalableVectorType>(VT)) &&
2405  "Mismatched GEPTy vector types");
2406  GEPTy = VectorType::get(OrigGEPTy, VT->getElementCount());
2407  break;
2408  }
2409  }
2410 
2411  return Constant::getNullValue(GEPTy);
2412  }
2413  }
2414 
2415  if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2416  // Combine Indices - If the source pointer to this getelementptr instruction
2417  // is a getelementptr instruction, combine the indices of the two
2418  // getelementptr instructions into a single instruction.
2419  //
2420  if (CE->getOpcode() == Instruction::GetElementPtr) {
2421  gep_type_iterator LastI = gep_type_end(CE);
2422  for (gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
2423  I != E; ++I)
2424  LastI = I;
2425 
2426  // We cannot combine indices if doing so would take us outside of an
2427  // array or vector. Doing otherwise could trick us if we evaluated such a
2428  // GEP as part of a load.
2429  //
2430  // e.g. Consider if the original GEP was:
2431  // i8* getelementptr ({ [2 x i8], i32, i8, [3 x i8] }* @main.c,
2432  // i32 0, i32 0, i64 0)
2433  //
2434  // If we then tried to offset it by '8' to get to the third element,
2435  // an i8, we should *not* get:
2436  // i8* getelementptr ({ [2 x i8], i32, i8, [3 x i8] }* @main.c,
2437  // i32 0, i32 0, i64 8)
2438  //
2439  // This GEP tries to index array element '8 which runs out-of-bounds.
2440  // Subsequent evaluation would get confused and produce erroneous results.
2441  //
2442  // The following prohibits such a GEP from being formed by checking to see
2443  // if the index is in-range with respect to an array.
2444  // TODO: This code may be extended to handle vectors as well.
2445  bool PerformFold = false;
2446  if (Idx0->isNullValue())
2447  PerformFold = true;
2448  else if (LastI.isSequential())
2449  if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx0))
2450  PerformFold = (!LastI.isBoundedSequential() ||
2452  LastI.getSequentialNumElements(), CI)) &&
2453  !CE->getOperand(CE->getNumOperands() - 1)
2454  ->getType()
2455  ->isVectorTy();
2456 
2457  if (PerformFold) {
2458  SmallVector<Value*, 16> NewIndices;
2459  NewIndices.reserve(Idxs.size() + CE->getNumOperands());
2460  NewIndices.append(CE->op_begin() + 1, CE->op_end() - 1);
2461 
2462  // Add the last index of the source with the first index of the new GEP.
2463  // Make sure to handle the case when they are actually different types.
2464  Constant *Combined = CE->getOperand(CE->getNumOperands()-1);
2465  // Otherwise it must be an array.
2466  if (!Idx0->isNullValue()) {
2467  Type *IdxTy = Combined->getType();
2468  if (IdxTy != Idx0->getType()) {
2469  unsigned CommonExtendedWidth =
2470  std::max(IdxTy->getIntegerBitWidth(),
2471  Idx0->getType()->getIntegerBitWidth());
2472  CommonExtendedWidth = std::max(CommonExtendedWidth, 64U);
2473 
2474  Type *CommonTy =
2475  Type::getIntNTy(IdxTy->getContext(), CommonExtendedWidth);
2476  Constant *C1 = ConstantExpr::getSExtOrBitCast(Idx0, CommonTy);
2477  Constant *C2 = ConstantExpr::getSExtOrBitCast(Combined, CommonTy);
2478  Combined = ConstantExpr::get(Instruction::Add, C1, C2);
2479  } else {
2480  Combined =
2481  ConstantExpr::get(Instruction::Add, Idx0, Combined);
2482  }
2483  }
2484 
2485  NewIndices.push_back(Combined);
2486  NewIndices.append(Idxs.begin() + 1, Idxs.end());
2487 
2488  // The combined GEP normally inherits its index inrange attribute from
2489  // the inner GEP, but if the inner GEP's last index was adjusted by the
2490  // outer GEP, any inbounds attribute on that index is invalidated.
2491  Optional<unsigned> IRIndex = cast<GEPOperator>(CE)->getInRangeIndex();
2492  if (IRIndex && *IRIndex == CE->getNumOperands() - 2 && !Idx0->isNullValue())
2493  IRIndex = None;
2494 
2496  cast<GEPOperator>(CE)->getSourceElementType(), CE->getOperand(0),
2497  NewIndices, InBounds && cast<GEPOperator>(CE)->isInBounds(),
2498  IRIndex);
2499  }
2500  }
2501 
2502  // Attempt to fold casts to the same type away. For example, folding:
2503  //
2504  // i32* getelementptr ([2 x i32]* bitcast ([3 x i32]* %X to [2 x i32]*),
2505  // i64 0, i64 0)
2506  // into:
2507  //
2508  // i32* getelementptr ([3 x i32]* %X, i64 0, i64 0)
2509  //
2510  // Don't fold if the cast is changing address spaces.
2511  if (CE->isCast() && Idxs.size() > 1 && Idx0->isNullValue()) {
2512  PointerType *SrcPtrTy =
2513  dyn_cast<PointerType>(CE->getOperand(0)->getType());
2514  PointerType *DstPtrTy = dyn_cast<PointerType>(CE->getType());
2515  if (SrcPtrTy && DstPtrTy) {
2516  ArrayType *SrcArrayTy =
2517  dyn_cast<ArrayType>(SrcPtrTy->getElementType());
2518  ArrayType *DstArrayTy =
2519  dyn_cast<ArrayType>(DstPtrTy->getElementType());
2520  if (SrcArrayTy && DstArrayTy
2521  && SrcArrayTy->getElementType() == DstArrayTy->getElementType()
2522  && SrcPtrTy->getAddressSpace() == DstPtrTy->getAddressSpace())
2523  return ConstantExpr::getGetElementPtr(SrcArrayTy,
2524  (Constant *)CE->getOperand(0),
2525  Idxs, InBounds, InRangeIndex);
2526  }
2527  }
2528  }
2529 
2530  // Check to see if any array indices are not within the corresponding
2531  // notional array or vector bounds. If so, try to determine if they can be
2532  // factored out into preceding dimensions.
2534  Type *Ty = PointeeTy;
2535  Type *Prev = C->getType();
2536  auto GEPIter = gep_type_begin(PointeeTy, Idxs);
2537  bool Unknown =
2538  !isa<ConstantInt>(Idxs[0]) && !isa<ConstantDataVector>(Idxs[0]);
2539  for (unsigned i = 1, e = Idxs.size(); i != e;
2540  Prev = Ty, Ty = (++GEPIter).getIndexedType(), ++i) {
2541  if (!isa<ConstantInt>(Idxs[i]) && !isa<ConstantDataVector>(Idxs[i])) {
2542  // We don't know if it's in range or not.
2543  Unknown = true;
2544  continue;
2545  }
2546  if (!isa<ConstantInt>(Idxs[i - 1]) && !isa<ConstantDataVector>(Idxs[i - 1]))
2547  // Skip if the type of the previous index is not supported.
2548  continue;
2549  if (InRangeIndex && i == *InRangeIndex + 1) {
2550  // If an index is marked inrange, we cannot apply this canonicalization to
2551  // the following index, as that will cause the inrange index to point to
2552  // the wrong element.
2553  continue;
2554  }
2555  if (isa<StructType>(Ty)) {
2556  // The verify makes sure that GEPs into a struct are in range.
2557  continue;
2558  }
2559  if (isa<VectorType>(Ty)) {
2560  // There can be awkward padding in after a non-power of two vector.
2561  Unknown = true;
2562  continue;
2563  }
2564  auto *STy = cast<ArrayType>(Ty);
2565  if (ConstantInt *CI = dyn_cast<ConstantInt>(Idxs[i])) {
2566  if (isIndexInRangeOfArrayType(STy->getNumElements(), CI))
2567  // It's in range, skip to the next index.
2568  continue;
2569  if (CI->getSExtValue() < 0) {
2570  // It's out of range and negative, don't try to factor it.
2571  Unknown = true;
2572  continue;
2573  }
2574  } else {
2575  auto *CV = cast<ConstantDataVector>(Idxs[i]);
2576  bool InRange = true;
2577  for (unsigned I = 0, E = CV->getNumElements(); I != E; ++I) {
2578  auto *CI = cast<ConstantInt>(CV->getElementAsConstant(I));
2579  InRange &= isIndexInRangeOfArrayType(STy->getNumElements(), CI);
2580  if (CI->getSExtValue() < 0) {
2581  Unknown = true;
2582  break;
2583  }
2584  }
2585  if (InRange || Unknown)
2586  // It's in range, skip to the next index.
2587  // It's out of range and negative, don't try to factor it.
2588  continue;
2589  }
2590  if (isa<StructType>(Prev)) {
2591  // It's out of range, but the prior dimension is a struct
2592  // so we can't do anything about it.
2593  Unknown = true;
2594  continue;
2595  }
2596  // It's out of range, but we can factor it into the prior
2597  // dimension.
2598  NewIdxs.resize(Idxs.size());
2599  // Determine the number of elements in our sequential type.
2600  uint64_t NumElements = STy->getArrayNumElements();
2601 
2602  // Expand the current index or the previous index to a vector from a scalar
2603  // if necessary.
2604  Constant *CurrIdx = cast<Constant>(Idxs[i]);
2605  auto *PrevIdx =
2606  NewIdxs[i - 1] ? NewIdxs[i - 1] : cast<Constant>(Idxs[i - 1]);
2607  bool IsCurrIdxVector = CurrIdx->getType()->isVectorTy();
2608  bool IsPrevIdxVector = PrevIdx->getType()->isVectorTy();
2609  bool UseVector = IsCurrIdxVector || IsPrevIdxVector;
2610 
2611  if (!IsCurrIdxVector && IsPrevIdxVector)
2612  CurrIdx = ConstantDataVector::getSplat(
2613  cast<FixedVectorType>(PrevIdx->getType())->getNumElements(), CurrIdx);
2614 
2615  if (!IsPrevIdxVector && IsCurrIdxVector)
2616  PrevIdx = ConstantDataVector::getSplat(
2617  cast<FixedVectorType>(CurrIdx->getType())->getNumElements(), PrevIdx);
2618 
2619  Constant *Factor =
2620  ConstantInt::get(CurrIdx->getType()->getScalarType(), NumElements);
2621  if (UseVector)
2623  IsPrevIdxVector
2624  ? cast<FixedVectorType>(PrevIdx->getType())->getNumElements()
2625  : cast<FixedVectorType>(CurrIdx->getType())->getNumElements(),
2626  Factor);
2627 
2628  NewIdxs[i] = ConstantExpr::getSRem(CurrIdx, Factor);
2629 
2630  Constant *Div = ConstantExpr::getSDiv(CurrIdx, Factor);
2631 
2632  unsigned CommonExtendedWidth =
2633  std::max(PrevIdx->getType()->getScalarSizeInBits(),
2634  Div->getType()->getScalarSizeInBits());
2635  CommonExtendedWidth = std::max(CommonExtendedWidth, 64U);
2636 
2637  // Before adding, extend both operands to i64 to avoid
2638  // overflow trouble.
2639  Type *ExtendedTy = Type::getIntNTy(Div->getContext(), CommonExtendedWidth);
2640  if (UseVector)
2641  ExtendedTy = FixedVectorType::get(
2642  ExtendedTy,
2643  IsPrevIdxVector
2644  ? cast<FixedVectorType>(PrevIdx->getType())->getNumElements()
2645  : cast<FixedVectorType>(CurrIdx->getType())->getNumElements());
2646 
2647  if (!PrevIdx->getType()->isIntOrIntVectorTy(CommonExtendedWidth))
2648  PrevIdx = ConstantExpr::getSExt(PrevIdx, ExtendedTy);
2649 
2650  if (!Div->getType()->isIntOrIntVectorTy(CommonExtendedWidth))
2651  Div = ConstantExpr::getSExt(Div, ExtendedTy);
2652 
2653  NewIdxs[i - 1] = ConstantExpr::getAdd(PrevIdx, Div);
2654  }
2655 
2656  // If we did any factoring, start over with the adjusted indices.
2657  if (!NewIdxs.empty()) {
2658  for (unsigned i = 0, e = Idxs.size(); i != e; ++i)
2659  if (!NewIdxs[i]) NewIdxs[i] = cast<Constant>(Idxs[i]);
2660  return ConstantExpr::getGetElementPtr(PointeeTy, C, NewIdxs, InBounds,
2661  InRangeIndex);
2662  }
2663 
2664  // If all indices are known integers and normalized, we can do a simple
2665  // check for the "inbounds" property.
2666  if (!Unknown && !InBounds)
2667  if (auto *GV = dyn_cast<GlobalVariable>(C))
2668  if (!GV->hasExternalWeakLinkage() && isInBoundsIndices(Idxs))
2669  return ConstantExpr::getGetElementPtr(PointeeTy, C, Idxs,
2670  /*InBounds=*/true, InRangeIndex);
2671 
2672  return nullptr;
2673 }
i
i
Definition: README.txt:29
llvm::CmpInst::FCMP_ULE
@ FCMP_ULE
1 1 0 1 True if unordered, less than, or equal
Definition: InstrTypes.h:737
llvm::APSInt::isSameValue
static bool isSameValue(const APSInt &I1, const APSInt &I2)
Determine if two APSInts have the same value, zero- or sign-extending as needed.
Definition: APSInt.h:301
llvm::Constant::isAllOnesValue
bool isAllOnesValue() const
Return true if this is the value that would be returned by getAllOnesValue.
Definition: Constants.cpp:101
llvm::Type::isSized
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition: Type.h:272
foldConstantCastPair
static unsigned foldConstantCastPair(unsigned opc, ConstantExpr *Op, Type *DstTy)
This function determines which opcode to use to fold two constant cast expressions together.
Definition: ConstantFold.cpp:86
llvm::Instruction::isAssociative
bool isAssociative() const LLVM_READONLY
Return true if the instruction is associative:
Definition: Instruction.cpp:714
llvm::CmpInst::getSwappedPredicate
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Definition: InstrTypes.h:839
MathExtras.h
llvm
Definition: AllocatorList.h:23
llvm::Type::getInt1Ty
static IntegerType * getInt1Ty(LLVMContext &C)
Definition: Type.cpp:201
llvm::APFloatBase::cmpGreaterThan
@ cmpGreaterThan
Definition: APFloat.h:183
llvm::ConstantExpr::getExtractElement
static Constant * getExtractElement(Constant *Vec, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
Definition: Constants.cpp:2526
llvm::CmpInst::ICMP_EQ
@ ICMP_EQ
equal
Definition: InstrTypes.h:743
llvm::Value::getPointerAlignment
Align getPointerAlignment(const DataLayout &DL) const
Returns an alignment of the pointer value.
Definition: Value.cpp:864
llvm::ConstantExpr::getNot
static Constant * getNot(Constant *C)
Definition: Constants.cpp:2658
llvm::DataLayout
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:112
llvm::Instruction::UnaryOps
UnaryOps
Definition: Instruction.h:761
llvm::generic_gep_type_iterator
Definition: GetElementPtrTypeIterator.h:31
llvm::CmpInst::Predicate
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition: InstrTypes.h:722
llvm::Type::isX86_MMXTy
bool isX86_MMXTy() const
Return true if this is X86 MMX.
Definition: Type.h:184
llvm::Constant::containsPoisonElement
bool containsPoisonElement() const
Return true if this is a vector constant that includes any poison elements.
Definition: Constants.cpp:332
llvm::APFloat::add
opStatus add(const APFloat &RHS, roundingMode RM)
Definition: APFloat.h:972
llvm::APFloatBase::IEEEsingle
static const fltSemantics & IEEEsingle() LLVM_READNONE
Definition: APFloat.cpp:163
llvm::PointerType::getElementType
Type * getElementType() const
Definition: DerivedTypes.h:653
llvm::Instruction::isCast
bool isCast() const
Definition: Instruction.h:168
llvm::APInt::ule
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition: APInt.h:1243
llvm::ConstantStruct::get
static Constant * get(StructType *T, ArrayRef< Constant * > V)
Definition: Constants.cpp:1312
IdxCompare
static int IdxCompare(Constant *C1, Constant *C2, Type *ElTy)
Compare the two constants as though they were getelementptr indices.
Definition: ConstantFold.cpp:1572
llvm::PointerType::get
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:693
C1
instcombine should handle this C2 when C1
Definition: README.txt:263
llvm::ConstantFoldSelectInstruction
Constant * ConstantFoldSelectInstruction(Constant *Cond, Constant *V1, Constant *V2)
Attempt to constant fold a select instruction with the specified operands.
Definition: ConstantFold.cpp:769
GetElementPtrTypeIterator.h
llvm::APInt::getMinSignedBits
unsigned getMinSignedBits() const
Get the minimum bit size for this signed APInt.
Definition: APInt.h:1624
llvm::Type::getScalarType
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition: Type.h:317
llvm::ConstantExpr::getOpcode
unsigned getOpcode() const
Return the opcode at the root of this constant expression.
Definition: Constants.h:1262
llvm::ConstantInt::getValue
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition: Constants.h:131
llvm::ConstantExpr::getSExt
static Constant * getSExt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:2083
llvm::SmallVector
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1168
llvm::ConstantExpr::getICmp
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:2476
llvm::generic_gep_type_iterator::getSequentialNumElements
uint64_t getSequentialNumElements() const
Definition: GetElementPtrTypeIterator.h:131
llvm::CmpInst::FCMP_ONE
@ FCMP_ONE
0 1 1 0 True if ordered and operands are unequal
Definition: InstrTypes.h:730
ErrorHandling.h
ManagedStatic.h
llvm::PointerType::getAddressSpace
unsigned getAddressSpace() const
Return the address space of the Pointer type.
Definition: DerivedTypes.h:662
llvm::CmpInst::ICMP_NE
@ ICMP_NE
not equal
Definition: InstrTypes.h:744
llvm::CmpInst::getInversePredicate
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Definition: InstrTypes.h:823
llvm::ConstantExpr::getBitCast
static Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:2207
llvm::CastInst::isEliminableCastPair
static unsigned isEliminableCastPair(Instruction::CastOps firstOpcode, Instruction::CastOps secondOpcode, Type *SrcTy, Type *MidTy, Type *DstTy, Type *SrcIntPtrTy, Type *MidIntPtrTy, Type *DstIntPtrTy)
Determine how a pair of casts can be eliminated, if they can be at all.
Definition: Instructions.cpp:2728
llvm::ConstantExpr::getSelect
static Constant * getSelect(Constant *C, Constant *V1, Constant *V2, Type *OnlyIfReducedTy=nullptr)
Select constant expr.
Definition: Constants.cpp:2394
llvm::lltok::APSInt
@ APSInt
Definition: LLToken.h:488
llvm::APFloatBase::x87DoubleExtended
static const fltSemantics & x87DoubleExtended() LLVM_READNONE
Definition: APFloat.cpp:172
llvm::Type::isFPOrFPVectorTy
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
Definition: Type.h:190
llvm::APFloat::divide
opStatus divide(const APFloat &RHS, roundingMode RM)
Definition: APFloat.h:999
llvm::PatternMatch::m_NegZeroFP
cstfp_pred_ty< is_neg_zero_fp > m_NegZeroFP()
Match a floating-point negative zero.
Definition: PatternMatch.h:670
llvm::ConstantExpr::getOffsetOf
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:2354
llvm::CmpInst::ICMP_SGT
@ ICMP_SGT
signed greater than
Definition: InstrTypes.h:749
llvm::Type
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:46
llvm::APInt::getBitWidth
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition: APInt.h:1581
llvm::ICmpInst::isEquality
bool isEquality() const
Return true if this predicate is either EQ or NE.
Definition: Instructions.h:1273
Module.h
llvm::ConstantExpr::getNUWMul
static Constant * getNUWMul(Constant *C1, Constant *C2)
Definition: Constants.h:1043
llvm::APInt::ugt
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Definition: APInt.h:1275
llvm::Optional< unsigned >
T
#define T
Definition: Mips16ISelLowering.cpp:341
llvm::CastInst::getCastOpcode
static Instruction::CastOps getCastOpcode(const Value *Val, bool SrcIsSigned, Type *Ty, bool DstIsSigned)
Returns the opcode necessary to cast Val into Ty using usual casting rules.
Definition: Instructions.cpp:3227
llvm::Type::isX86_FP80Ty
bool isX86_FP80Ty() const
Return true if this is x86 long double.
Definition: Type.h:154
llvm::tgtok::FalseVal
@ FalseVal
Definition: TGLexer.h:61
Operator.h
llvm::VectorType::getElementType
Type * getElementType() const
Definition: DerivedTypes.h:424
llvm::CmpInst::ICMP_SLE
@ ICMP_SLE
signed less or equal
Definition: InstrTypes.h:752
llvm::GetElementPtrInst::getGEPReturnType
static Type * getGEPReturnType(Type *ElTy, Value *Ptr, ArrayRef< Value * > IdxList)
Returns the pointer type returned by the GEP instruction, which may be a vector of pointers.
Definition: Instructions.h:1073
llvm::ConstantExpr::getInBoundsGetElementPtr
static Constant * getInBoundsGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant * > IdxList)
Create an "inbounds" getelementptr.
Definition: Constants.h:1232
evaluateICmpRelation
static ICmpInst::Predicate evaluateICmpRelation(Constant *V1, Constant *V2, bool isSigned)
This function determines if there is anything we can decide about the two constants provided.
Definition: ConstantFold.cpp:1705
BitCastConstantVector
static Constant * BitCastConstantVector(Constant *CV, VectorType *DstTy)
Convert the specified vector Constant node to the specified vector type.
Definition: ConstantFold.cpp:45
llvm::APInt::lshr
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition: APInt.h:987
llvm::ArrayType
Class to represent array types.
Definition: DerivedTypes.h:359
llvm::gep_type_begin
gep_type_iterator gep_type_begin(const User *GEP)
Definition: GetElementPtrTypeIterator.h:139
getFoldedAlignOf
static Constant * getFoldedAlignOf(Type *Ty, Type *DestTy, bool Folded)
Return a ConstantExpr with type DestTy for alignof on Ty, with any known factors factored out.
Definition: ConstantFold.cpp:432
llvm::Type::isFloatingPointTy
bool isFloatingPointTy() const
Return true if this is one of the six floating-point types.
Definition: Type.h:163
evaluateFCmpRelation
static FCmpInst::Predicate evaluateFCmpRelation(Constant *V1, Constant *V2)
This function determines if there is anything we can decide about the two constants provided.
Definition: ConstantFold.cpp:1616
llvm::APFloat::mod
opStatus mod(const APFloat &RHS)
Definition: APFloat.h:1017
llvm::CmpInst::FCMP_OGT
@ FCMP_OGT
0 0 1 0 True if ordered and greater than
Definition: InstrTypes.h:726
llvm::BitmaskEnumDetail::Mask
std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
Definition: BitmaskEnum.h:80
llvm::Type::getInt32Ty
static IntegerType * getInt32Ty(LLVMContext &C)
Definition: Type.cpp:204
llvm::ArrayRef::empty
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:158
llvm::ArrayRef::data
const T * data() const
Definition: ArrayRef.h:160
llvm::ConstantFoldExtractValueInstruction
Constant * ConstantFoldExtractValueInstruction(Constant *Agg, ArrayRef< unsigned > Idxs)
Attempt to constant fold an extractvalue instruction with the specified operands and indices.
Definition: ConstantFold.cpp:1015
llvm::ConstantExpr::getPointerCast
static Constant * getPointerCast(Constant *C, Type *Ty)
Create a BitCast, AddrSpaceCast, or a PtrToInt cast constant expression.
Definition: Constants.cpp:2019
llvm::APFloatBase::IEEEquad
static const fltSemantics & IEEEquad() LLVM_READNONE
Definition: APFloat.cpp:169
llvm::gep_type_end
gep_type_iterator gep_type_end(const User *GEP)
Definition: GetElementPtrTypeIterator.h:146
llvm::UndefMaskElem
constexpr int UndefMaskElem
Definition: Instructions.h:1974
llvm::CmpInst::FCMP_ULT
@ FCMP_ULT
1 1 0 0 True if unordered or less than
Definition: InstrTypes.h:736
llvm::PatternMatch::m_APInt
apint_match m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
Definition: PatternMatch.h:226
llvm::APInt::uge
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition: APInt.h:1313
llvm::ConstantInt
This is the shared class of boolean and integer constants.
Definition: Constants.h:77
llvm::Type::isArrayTy
bool isArrayTy() const
True if this is an instance of ArrayType.
Definition: Type.h:226
llvm::Intrinsic::getType
FunctionType * getType(LLVMContext &Context, ID id, ArrayRef< Type * > Tys=None)
Return the function type for an intrinsic.
Definition: Function.cpp:1247
llvm::all_of
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1505
llvm::LinearPolySize< ElementCount >::get
static ElementCount get(ScalarTy MinVal, bool Scalable)
Definition: TypeSize.h:290
llvm::APFloat::convertToInteger
opStatus convertToInteger(MutableArrayRef< integerPart > Input, unsigned int Width, bool IsSigned, roundingMode RM, bool *IsExact) const
Definition: APFloat.h:1107
getFoldedSizeOfImpl
static Constant * getFoldedSizeOfImpl(Type *Ty, Type *DestTy, bool Folded, DenseMap< Type *, Constant * > &Cache)
Return a ConstantExpr with type DestTy for sizeof on Ty, with any known factors factored out.
Definition: ConstantFold.cpp:359
llvm::APInt::lshrInPlace
void lshrInPlace(unsigned ShiftAmt)
Logical right-shift this APInt by ShiftAmt in place.
Definition: APInt.h:994
Constants.h
llvm::PatternMatch::match
bool match(Val *V, const Pattern &P)
Definition: PatternMatch.h:49
llvm::Constant::isNullValue
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition: Constants.cpp:86
FoldBitCast
static Constant * FoldBitCast(Constant *V, Type *DestTy)
Definition: ConstantFold.cpp:111
E
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
llvm::SmallVectorImpl::append
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
Definition: SmallVector.h:648
llvm::APFloatBase::IEEEhalf
static const fltSemantics & IEEEhalf() LLVM_READNONE
Definition: APFloat.cpp:157
C
(vector float) vec_cmpeq(*A, *B) C
Definition: README_ALTIVEC.txt:86
llvm::CmpInst::ICMP_ULE
@ ICMP_ULE
unsigned less or equal
Definition: InstrTypes.h:748
llvm::Log2
unsigned Log2(Align A)
Returns the log2 of the alignment.
Definition: Alignment.h:217
llvm::CmpInst::FCMP_UGE
@ FCMP_UGE
1 0 1 1 True if unordered, greater than, or equal
Definition: InstrTypes.h:735
getOpcode
static Optional< unsigned > getOpcode(ArrayRef< VPValue * > Values)
Returns the opcode of Values or ~0 if they do not all agree.
Definition: VPlanSLP.cpp:199
llvm::APFloatBase::Bogus
static const fltSemantics & Bogus() LLVM_READNONE
A Pseudo fltsemantic used to construct APFloats that cannot conflict with anything real.
Definition: APFloat.cpp:175
llvm::Type::isVectorTy
bool isVectorTy() const
True if this is an instance of VectorType.
Definition: Type.h:235
llvm::VectorType::getElementCount
ElementCount getElementCount() const
Return an ElementCount instance to represent the (possibly scalable) number of elements in the vector...
Definition: DerivedTypes.h:629
llvm::MaybeAlign
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition: Alignment.h:119
llvm::Type::getFltSemantics
const fltSemantics & getFltSemantics() const
Definition: Type.h:170
llvm::IntegerType
Class to represent integer types.
Definition: DerivedTypes.h:40
llvm::Instruction::CastOps
CastOps
Definition: Instruction.h:782
llvm::Constant::getAllOnesValue
static Constant * getAllOnesValue(Type *Ty)
Definition: Constants.cpp:405
llvm::generic_gep_type_iterator::isBoundedSequential
bool isBoundedSequential() const
Definition: GetElementPtrTypeIterator.h:127
getFoldedOffsetOf
static Constant * getFoldedOffsetOf(Type *Ty, Constant *FieldNo, Type *DestTy, bool Folded)
Return a ConstantExpr with type DestTy for offsetof on Ty and FieldNo, with any known factors factore...
Definition: ConstantFold.cpp:496
llvm::CmpInst::FCMP_UNO
@ FCMP_UNO
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
Definition: InstrTypes.h:732
llvm::Type::getScalarSizeInBits
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition: Type.cpp:154
llvm::ConstantFoldGetElementPtr
Constant * ConstantFoldGetElementPtr(Type *Ty, Constant *C, bool InBounds, Optional< unsigned > InRangeIndex, ArrayRef< Value * > Idxs)
Definition: ConstantFold.cpp:2359
llvm::APSInt
An arbitrary precision integer that knows its signedness.
Definition: APSInt.h:22
llvm::APInt::getZExtValue
uint64_t getZExtValue() const
Get zero extended value.
Definition: APInt.h:1631
llvm::ConstantFP
ConstantFP - Floating Point Values [float, double].
Definition: Constants.h:255
llvm::ConstantVector::getSplat
static Constant * getSplat(ElementCount EC, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
Definition: Constants.cpp:1397
llvm::SmallVectorImpl::resize
void resize(size_type N)
Definition: SmallVector.h:606
llvm::UndefValue::get
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
Definition: Constants.cpp:1770
llvm::ConstantExpr::getXor
static Constant * getXor(Constant *C1, Constant *C2)
Definition: Constants.cpp:2731
llvm::ConstantInt::get
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:885
llvm::CmpInst::FCMP_OEQ
@ FCMP_OEQ
0 0 0 1 True if ordered and equal
Definition: InstrTypes.h:725
llvm::CmpInst::FCMP_OLT
@ FCMP_OLT
0 1 0 0 True if ordered and less than
Definition: InstrTypes.h:728
llvm::APInt::sle
bool sle(const APInt &RHS) const
Signed less or equal comparison.
Definition: APInt.h:1259
Align
uint64_t Align
Definition: ELFObjHandler.cpp:83
PatternMatch.h
llvm::FixedVectorType::get
static FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition: Type.cpp:650
llvm::ConstantFoldCompareInstruction
Constant * ConstantFoldCompareInstruction(unsigned short predicate, Constant *C1, Constant *C2)
Definition: ConstantFold.cpp:1953
llvm::Instruction::isIntDivRem
bool isIntDivRem() const
Definition: Instruction.h:166
llvm::ArrayRef::slice
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:193
llvm::None
const NoneType None
Definition: None.h:23
llvm::Type::getIntegerBitWidth
unsigned getIntegerBitWidth() const
Definition: DerivedTypes.h:96
llvm::APFloat::subtract
opStatus subtract(const APFloat &RHS, roundingMode RM)
Definition: APFloat.h:981
llvm::APInt::srem
APInt srem(const APInt &RHS) const
Function for signed remainder operation.
Definition: APInt.cpp:1763
llvm::ConstantFoldBinaryInstruction
Constant * ConstantFoldBinaryInstruction(unsigned Opcode, Constant *V1, Constant *V2)
Definition: ConstantFold.cpp:1112
llvm::ConstantFoldExtractElementInstruction
Constant * ConstantFoldExtractElementInstruction(Constant *Val, Constant *Idx)
Attempt to constant fold an extractelement instruction with the specified operands and indices.
Definition: ConstantFold.cpp:858
llvm::PatternMatch::m_One
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
Definition: PatternMatch.h:469
llvm::Instruction::isCommutative
bool isCommutative() const LLVM_READONLY
Return true if the instruction is commutative:
Definition: Instruction.cpp:729
llvm::CmpInst::FCMP_FALSE
@ FCMP_FALSE
0 0 0 0 Always false (always folded)
Definition: InstrTypes.h:724
llvm::APFloat::multiply
opStatus multiply(const APFloat &RHS, roundingMode RM)
Definition: APFloat.h:990
llvm::APInt::ashr
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
Definition: APInt.h:963
llvm::ConstantFoldCastInstruction
Constant * ConstantFoldCastInstruction(unsigned opcode, Constant *V, Type *DestTy)
Definition: ConstantFold.cpp:545
llvm::Type::isIntegerTy
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition: Type.h:202
llvm::VectorType
Base class of all SIMD vector types.
Definition: DerivedTypes.h:391
llvm::ConstantExpr::getTrunc
static Constant * getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:2069
llvm::GEPOperator::hasAllZeroIndices
bool hasAllZeroIndices() const
Return true if all of the indices of this GEP are zeros.
Definition: Operator.h:524
llvm::APFloat
Definition: APFloat.h:701
llvm::APInt::slt
bool slt(const APInt &RHS) const
Signed less than comparison.
Definition: APInt.h:1224
llvm::ConstantExpr::getCompare
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:2372
llvm::PatternMatch::m_Zero
is_zero m_Zero()
Match any null constant or a vector with all elements equal to 0.
Definition: PatternMatch.h:491
llvm::GlobalValue
Definition: GlobalValue.h:44
llvm::Constant
This is an important base class in LLVM.
Definition: Constant.h:41
llvm::ConstantExpr::getBinOpIdentity
static Constant * getBinOpIdentity(unsigned Opcode, Type *Ty, bool AllowRHSConstant=false)
Return the identity constant for a binary opcode.
Definition: Constants.cpp:2786
llvm::APInt::sdiv
APInt sdiv(const APInt &RHS) const
Signed division function for APInt.
Definition: APInt.cpp:1671
llvm::APFloatBase::cmpResult
cmpResult
IEEE-754R 5.11: Floating Point Comparison Relations.
Definition: APFloat.h:180
llvm::ConstantFoldInsertValueInstruction
Constant * ConstantFoldInsertValueInstruction(Constant *Agg, Constant *Val, ArrayRef< unsigned > Idxs)
ConstantFoldInsertValueInstruction - Attempt to constant fold an insertvalue instruction with the spe...
Definition: ConstantFold.cpp:1027
llvm::GlobalValue::getParent
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:572
llvm::ARM_MB::ST
@ ST
Definition: ARMBaseInfo.h:73
llvm::Type::isIntOrPtrTy
bool isIntOrPtrTy() const
Return true if this is an integer type or a pointer type.
Definition: Type.h:217
llvm::APFloatBase::cmpUnordered
@ cmpUnordered
Definition: APFloat.h:184
llvm::ConstantPointerNull::get
static ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
Definition: Constants.cpp:1756
llvm::neg
APFloat neg(APFloat X)
Returns the negated value of the argument.
Definition: APFloat.h:1278
llvm::numbers::e
constexpr double e
Definition: MathExtras.h:58
llvm::DenseMap
Definition: DenseMap.h:714
llvm::ConstantExpr::get
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:2241
llvm::ConstantExpr::getAlignOf
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:2341
I
#define I(x, y, z)
Definition: MD5.cpp:59
llvm::ConstantExpr::getOr
static Constant * getOr(Constant *C1, Constant *C2)
Definition: Constants.cpp:2727
llvm::PointerType
Class to represent pointers.
Definition: DerivedTypes.h:634
ExtractConstantBytes
static Constant * ExtractConstantBytes(Constant *C, unsigned ByteStart, unsigned ByteSize)
V is an integer constant which only has a subset of its bytes used.
Definition: ConstantFold.cpp:214
llvm::Type::isHalfTy
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
Definition: Type.h:142
llvm::DenseMapBase< DenseMap< KeyT, ValueT, DenseMapInfo< KeyT >, llvm::detail::DenseMapPair< KeyT, ValueT > >, KeyT, ValueT, DenseMapInfo< KeyT >, llvm::detail::DenseMapPair< KeyT, ValueT > >::find
iterator find(const_arg_type_t< KeyT > Val)
Definition: DenseMap.h:150
llvm::ConstantVector
Constant Vector Declarations.
Definition: Constants.h:492
llvm::APFloatBase::PPCDoubleDouble
static const fltSemantics & PPCDoubleDouble() LLVM_READNONE
Definition: APFloat.cpp:178
llvm::ConstantFoldInsertElementInstruction
Constant * ConstantFoldInsertElementInstruction(Constant *Val, Constant *Elt, Constant *Idx)
Attempt to constant fold an insertelement instruction with the specified operands and indices.
Definition: ConstantFold.cpp:923
assert
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
llvm::APInt::sge
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
Definition: APInt.h:1329
llvm::CmpInst::FCMP_OGE
@ FCMP_OGE
0 0 1 1 True if ordered and greater than or equal
Definition: InstrTypes.h:727
llvm::ConstantExpr::getCast
static Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
Definition: Constants.cpp:1962
llvm::generic_gep_type_iterator::getIndexedType
Type * getIndexedType() const
Definition: GetElementPtrTypeIterator.h:72
llvm::CmpInst::ICMP_UGE
@ ICMP_UGE
unsigned greater or equal
Definition: InstrTypes.h:746
llvm::CmpInst::BAD_ICMP_PREDICATE
@ BAD_ICMP_PREDICATE
Definition: InstrTypes.h:755
APSInt.h
llvm::Instruction::isBinaryOp
bool isBinaryOp() const
Definition: Instruction.h:165
llvm::Module
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:67
llvm::ConstantFP::getNaN
static Constant * getNaN(Type *Ty, bool Negative=false, uint64_t Payload=0)
Definition: Constants.cpp:973
llvm::GEPOperator
Definition: Operator.h:457
llvm::APInt::urem
APInt urem(const APInt &RHS) const
Unsigned remainder operation.
Definition: APInt.cpp:1693
llvm::ConstantExpr::getSizeOf
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:2331
llvm::APInt
Class for arbitrary precision integers.
Definition: APInt.h:70
llvm::CmpInst::ICMP_SLT
@ ICMP_SLT
signed less than
Definition: InstrTypes.h:751
llvm::CmpInst::isIntPredicate
bool isIntPredicate() const
Definition: InstrTypes.h:817
llvm::BlockAddress
The address of a basic block.
Definition: Constants.h:847
llvm::ArrayRef< int >
llvm::min
Expected< ExpressionValue > min(const ExpressionValue &Lhs, const ExpressionValue &Rhs)
Definition: FileCheck.cpp:357
llvm::StructType
Class to represent struct types.
Definition: DerivedTypes.h:212
Cond
SmallVector< MachineOperand, 4 > Cond
Definition: BasicBlockSections.cpp:167
llvm::APFloatBase::IEEEdouble
static const fltSemantics & IEEEdouble() LLVM_READNONE
Definition: APFloat.cpp:166
llvm::ConstantExpr::getSExtOrBitCast
static Constant * getSExtOrBitCast(Constant *C, Type *Ty)
Definition: Constants.cpp:2007
llvm::CmpInst::ICMP_ULT
@ ICMP_ULT
unsigned less than
Definition: InstrTypes.h:747
llvm::APFloatBase::opInvalidOp
@ opInvalidOp
Definition: APFloat.h:208
llvm_unreachable
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Definition: ErrorHandling.h:136
llvm::Constant::getAggregateElement
Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
Definition: Constants.cpp:421
llvm::Value::getType
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:256
uint32_t
llvm::Value::getContext
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:937
llvm::generic_gep_type_iterator::isSequential
bool isSequential() const
Definition: GetElementPtrTypeIterator.h:119
DL
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Definition: AArch64SLSHardening.cpp:76
areGlobalsPotentiallyEqual
static ICmpInst::Predicate areGlobalsPotentiallyEqual(const GlobalValue *GV1, const GlobalValue *GV2)
Definition: ConstantFold.cpp:1669
llvm::ConstantVector::get
static Constant * get(ArrayRef< Constant * > V)
Definition: Constants.cpp:1354
llvm::ConstantInt::getSExtValue
int64_t getSExtValue() const
Return the constant as a 64-bit integer value after it has been sign extended as appropriate for the ...
Definition: Constants.h:146
llvm::APInt::ult
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition: APInt.h:1205
LLVM_FALLTHROUGH
#define LLVM_FALLTHROUGH
LLVM_FALLTHROUGH - Mark fallthrough cases in switch statements.
Definition: Compiler.h:281
llvm::Type::getContext
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition: Type.h:128
llvm::APInt::udiv
APInt udiv(const APInt &RHS) const
Unsigned division operation.
Definition: APInt.cpp:1600
llvm::ConstantInt::getFalse
static ConstantInt * getFalse(LLVMContext &Context)
Definition: Constants.cpp:840
llvm::ConstantExpr::getFCmp
static Constant * getFCmp(unsigned short pred, Constant *LHS, Constant *RHS, bool OnlyIfReduced=false)
Definition: Constants.cpp:2501
ConstantFold.h
llvm::ConstantInt::getZExtValue
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition: Constants.h:140
llvm::APInt::getNullValue
static APInt getNullValue(unsigned numBits)
Get the '0' value.
Definition: APInt.h:574
llvm::MCID::Select
@ Select
Definition: MCInstrDesc.h:163
llvm::tgtok::IntVal
@ IntVal
Definition: TGLexer.h:64
llvm::CmpInst::FCMP_UGT
@ FCMP_UGT
1 0 1 0 True if unordered or greater than
Definition: InstrTypes.h:734
llvm::NVPTX::PTXLdStInstCode::V2
@ V2
Definition: NVPTX.h:123
llvm::APFloatBase::rmTowardZero
static constexpr roundingMode rmTowardZero
Definition: APFloat.h:194
isIndexInRangeOfArrayType
static bool isIndexInRangeOfArrayType(uint64_t NumElements, const ConstantInt *CI)
Test whether a given ConstantInt is in-range for a SequentialType.
Definition: ConstantFold.cpp:2343
llvm::Type::getInt64Ty
static IntegerType * getInt64Ty(LLVMContext &C)
Definition: Type.cpp:205
llvm::ConstantExpr
A constant value that is initialized with an expression using other constant values.
Definition: Constants.h:931
llvm::ConstantExpr::getSDiv
static Constant * getSDiv(Constant *C1, Constant *C2, bool isExact=false)
Definition: Constants.cpp:2702
llvm::ConstantInt::getTrue
static ConstantInt * getTrue(LLVMContext &Context)
Definition: Constants.cpp:833
llvm::APInt::trunc
APInt trunc(unsigned width) const
Truncate to new width.
Definition: APInt.cpp:858
llvm::Constant::getNullValue
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
Definition: Constants.cpp:347
llvm::Type::getIntNTy
static IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition: Type.cpp:208
llvm::Type::isFloatTy
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
Definition: Type.h:148
llvm::APInt::isMinSignedValue
bool isMinSignedValue() const
Determine if this is the smallest signed value.
Definition: APInt.h:448
llvm::DenseMapBase< DenseMap< KeyT, ValueT, DenseMapInfo< KeyT >, llvm::detail::DenseMapPair< KeyT, ValueT > >, KeyT, ValueT, DenseMapInfo< KeyT >, llvm::detail::DenseMapPair< KeyT, ValueT > >::end
iterator end()
Definition: DenseMap.h:83
llvm::AMDGPU::SendMsg::Op
Op
Definition: SIDefines.h:314
llvm::ArrayRef::begin
iterator begin() const
Definition: ArrayRef.h:151
llvm::Type::isEmptyTy
bool isEmptyTy() const
Return true if this type is empty, that is, it has no elements or all of its elements are empty.
Definition: Type.cpp:112
llvm::ConstantExpr::getAdd
static Constant * getAdd(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
Definition: Constants.cpp:2664
llvm::Type::isIntOrIntVectorTy
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition: Type.h:208
GlobalVariable.h
llvm::ConstantFP::get
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:932
llvm::ConstantInt::uge
bool uge(uint64_t Num) const
This function will return true iff this constant represents a value with active bits bigger than 64 b...
Definition: Constants.h:235
llvm::GetElementPtrInst::getTypeAtIndex
static Type * getTypeAtIndex(Type *Ty, Value *Idx)
Return the type of the element at the given index of an indexable type.
Definition: Instructions.cpp:1717
Function.h
InRange
static bool InRange(int64_t Value, unsigned short Shift, int LBound, int HBound)
Definition: MicroMipsSizeReduction.cpp:327
llvm::BitWidth
constexpr unsigned BitWidth
Definition: BitmaskEnum.h:147
llvm::ConstantExpr::getAnd
static Constant * getAnd(Constant *C1, Constant *C2)
Definition: Constants.cpp:2723
llvm::ConstantFoldShuffleVectorInstruction
Constant * ConstantFoldShuffleVectorInstruction(Constant *V1, Constant *V2, ArrayRef< int > Mask)
Attempt to constant fold a shufflevector instruction with the specified operands and mask.
Definition: ConstantFold.cpp:960
llvm::CmpInst::isSigned
bool isSigned() const
Definition: InstrTypes.h:937
llvm::Type::isDoubleTy
bool isDoubleTy() const
Return true if this is 'double', a 64-bit IEEE fp type.
Definition: Type.h:151
llvm::Type::isPPC_FP128Ty
bool isPPC_FP128Ty() const
Return true if this is powerpc long double.
Definition: Type.h:160
llvm::ConstantArray::get
static Constant * get(ArrayType *T, ArrayRef< Constant * > V)
Definition: Constants.cpp:1248
isMaybeZeroSizedType
static bool isMaybeZeroSizedType(Type *Ty)
This type is zero-sized if it's an array or structure of zero-sized types.
Definition: ConstantFold.cpp:1550
llvm::ConstantExpr::getGetElementPtr
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:1205
llvm::GetElementPtrInst::getIndexedType
static Type * getIndexedType(Type *Ty, ArrayRef< Value * > IdxList)
Returns the result type of a getelementptr with the given source element type and indexes.
Definition: Instructions.cpp:1757
llvm::ConstantExpr::getLShr
static Constant * getLShr(Constant *C1, Constant *C2, bool isExact=false)
Definition: Constants.cpp:2747
llvm::CmpInst::ICMP_SGE
@ ICMP_SGE
signed greater or equal
Definition: InstrTypes.h:750
llvm::MCID::Add
@ Add
Definition: MCInstrDesc.h:184
llvm::Inverse
Definition: GraphTraits.h:95
GlobalAlias.h
llvm::CmpInst::isTrueWhenEqual
bool isTrueWhenEqual() const
This is just a convenience.
Definition: InstrTypes.h:986
llvm::makeArrayRef
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
Definition: ArrayRef.h:474
Predicate
llvm::Instruction::BinaryOps
BinaryOps
Definition: Instruction.h:768
llvm::APFloatBase::rmNearestTiesToEven
static constexpr roundingMode rmNearestTiesToEven
Definition: APFloat.h:190
Instructions.h
llvm::APFloat::convert
opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
Definition: APFloat.cpp:4818
llvm::GEPOperator::getSourceElementType
Type * getSourceElementType() const
Definition: Operator.cpp:22
llvm::User::getNumOperands
unsigned getNumOperands() const
Definition: User.h:191
llvm::Type::isStructTy
bool isStructTy() const
True if this is an instance of StructType.
Definition: Type.h:223
llvm::ConstantExpr::getSRem
static Constant * getSRem(Constant *C1, Constant *C2)
Definition: Constants.cpp:2715
SmallVector.h
isInBoundsIndices
static bool isInBoundsIndices(ArrayRef< IndexTy > Idxs)
Test whether the given sequence of normalized indices is "inbounds".
Definition: ConstantFold.cpp:2317
llvm::CmpInst::ICMP_UGT
@ ICMP_UGT
unsigned greater than
Definition: InstrTypes.h:745
llvm::CmpInst::FCMP_UNE
@ FCMP_UNE
1 1 1 0 True if unordered or not equal
Definition: InstrTypes.h:738
llvm::ConstantDataVector::getSplat
static Constant * getSplat(unsigned NumElts, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
Definition: Constants.cpp:3117
N
#define N
llvm::ArrayRef::size
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:163
llvm::ConstantExpr::getMul
static Constant * getMul(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
Definition: Constants.cpp:2686
llvm::max
Align max(MaybeAlign Lhs, Align Rhs)
Definition: Alignment.h:350
llvm::Instruction::isUnaryOp
bool isUnaryOp() const
Definition: Instruction.h:164
llvm::PatternMatch
Definition: PatternMatch.h:47
llvm::Constant::getSplatValue
Constant * getSplatValue(bool AllowUndefs=false) const
If all elements of the vector constant have the same value, return that value.
Definition: Constants.cpp:1685
llvm::CmpInst::FCMP_OLE
@ FCMP_OLE
0 1 0 1 True if ordered and less than or equal
Definition: InstrTypes.h:729
llvm::APInt::sgt
bool sgt(const APInt &RHS) const
Signed greater than comparison.
Definition: APInt.h:1294
DerivedTypes.h
pred
hexagon gen pred
Definition: HexagonGenPredicate.cpp:134
llvm::CmpInst::isUnordered
static bool isUnordered(Predicate predicate)
Determine if the predicate is an unordered operation.
Definition: Instructions.cpp:3948
llvm::APInt::getLowBitsSet
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Get a value with low bits set.
Definition: APInt.h:667
llvm::IntegerType::get
static IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition: Type.cpp:276
llvm::ConstantInt::isOne
bool isOne() const
This is just a convenience method to make client code smaller for a common case.
Definition: Constants.h:198
llvm::APFloat::compare
cmpResult compare(const APFloat &RHS) const
Definition: APFloat.h:1160
llvm::APFloat::convertFromAPInt
opStatus convertFromAPInt(const APInt &Input, bool IsSigned, roundingMode RM)
Definition: APFloat.h:1115
llvm::APInt::shl
APInt shl(unsigned shiftAmt) const
Left-shift function.
Definition: APInt.h:1009
llvm::User::getOperand
Value * getOperand(unsigned i) const
Definition: User.h:169
llvm::NullPointerIsDefined
bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
Definition: Function.cpp:1847
getFoldedSizeOf
static Constant * getFoldedSizeOf(Type *Ty, Type *DestTy, bool Folded, DenseMap< Type *, Constant * > &Cache)
Wrapper around getFoldedSizeOfImpl() that adds caching.
Definition: ConstantFold.cpp:414
llvm::ConstantFoldUnaryInstruction
Constant * ConstantFoldUnaryInstruction(unsigned Opcode, Constant *V)
Definition: ConstantFold.cpp:1056
llvm::SmallVectorImpl::reserve
void reserve(size_type N)
Definition: SmallVector.h:624
llvm::APFloatBase::cmpEqual
@ cmpEqual
Definition: APFloat.h:182
llvm::CmpInst::FCMP_TRUE
@ FCMP_TRUE
1 1 1 1 Always true (always folded)
Definition: InstrTypes.h:739
llvm::tgtok::TrueVal
@ TrueVal
Definition: TGLexer.h:61
llvm::PatternMatch::m_Undef
class_match< UndefValue > m_Undef()
Match an arbitrary undef constant.
Definition: PatternMatch.h:92
llvm::APFloatBase::cmpLessThan
@ cmpLessThan
Definition: APFloat.h:181
llvm::Value
LLVM Value Representation.
Definition: Value.h:75
llvm::Type::isFP128Ty
bool isFP128Ty() const
Return true if this is 'fp128'.
Definition: Type.h:157
llvm::VectorType::get
static VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
Definition: Type.cpp:634
llvm::CmpInst::BAD_FCMP_PREDICATE
@ BAD_FCMP_PREDICATE
Definition: InstrTypes.h:742
llvm::ArrayRef::end
iterator end() const
Definition: ArrayRef.h:152
llvm::ArrayType::getElementType
Type * getElementType() const
Definition: DerivedTypes.h:372
llvm::Type::isX86_AMXTy
bool isX86_AMXTy() const
Return true if this is X86 AMX.
Definition: Type.h:187
llvm::CmpInst::FCMP_ORD
@ FCMP_ORD
0 1 1 1 True if ordered (no nans)
Definition: InstrTypes.h:731
llvm::Type::isFirstClassType
bool isFirstClassType() const
Return true if the type is "first class", meaning it is a valid type for a Value.
Definition: Type.h:251
llvm::CmpInst::FCMP_UEQ
@ FCMP_UEQ
1 0 0 1 True if unordered or equal
Definition: InstrTypes.h:733
llvm::ConstantExpr::isGEPWithNoNotionalOverIndexing
bool isGEPWithNoNotionalOverIndexing() const
Return true if this is a getelementptr expression and all the index operands are compile-time known i...
Definition: Constants.cpp:1450
llvm::Type::getPrimitiveSizeInBits
TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition: Type.cpp:129
llvm::PoisonValue::get
static PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Definition: Constants.cpp:1789