LLVM  8.0.1
ConstantFolding.cpp
Go to the documentation of this file.
1 //===-- ConstantFolding.cpp - Fold instructions into constants ------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines routines for folding instructions into constants.
11 //
12 // Also, to supplement the basic IR ConstantExpr simplifications,
13 // this file defines some additional folding routines that can make use of
14 // DataLayout information. These functions cannot go in IR due to library
15 // dependency issues.
16 //
17 //===----------------------------------------------------------------------===//
18 
20 #include "llvm/ADT/APFloat.h"
21 #include "llvm/ADT/APInt.h"
22 #include "llvm/ADT/ArrayRef.h"
23 #include "llvm/ADT/DenseMap.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/StringRef.h"
29 #include "llvm/Config/config.h"
30 #include "llvm/IR/Constant.h"
31 #include "llvm/IR/Constants.h"
32 #include "llvm/IR/DataLayout.h"
33 #include "llvm/IR/DerivedTypes.h"
34 #include "llvm/IR/Function.h"
35 #include "llvm/IR/GlobalValue.h"
36 #include "llvm/IR/GlobalVariable.h"
37 #include "llvm/IR/InstrTypes.h"
38 #include "llvm/IR/Instruction.h"
39 #include "llvm/IR/Instructions.h"
40 #include "llvm/IR/Operator.h"
41 #include "llvm/IR/Type.h"
42 #include "llvm/IR/Value.h"
43 #include "llvm/Support/Casting.h"
45 #include "llvm/Support/KnownBits.h"
47 #include <cassert>
48 #include <cerrno>
49 #include <cfenv>
50 #include <cmath>
51 #include <cstddef>
52 #include <cstdint>
53 
54 using namespace llvm;
55 
56 namespace {
57 
58 //===----------------------------------------------------------------------===//
59 // Constant Folding internal helper functions
60 //===----------------------------------------------------------------------===//
61 
62 static Constant *foldConstVectorToAPInt(APInt &Result, Type *DestTy,
63  Constant *C, Type *SrcEltTy,
64  unsigned NumSrcElts,
65  const DataLayout &DL) {
66  // Now that we know that the input value is a vector of integers, just shift
67  // and insert them into our result.
68  unsigned BitShift = DL.getTypeSizeInBits(SrcEltTy);
69  for (unsigned i = 0; i != NumSrcElts; ++i) {
70  Constant *Element;
71  if (DL.isLittleEndian())
72  Element = C->getAggregateElement(NumSrcElts - i - 1);
73  else
74  Element = C->getAggregateElement(i);
75 
76  if (Element && isa<UndefValue>(Element)) {
77  Result <<= BitShift;
78  continue;
79  }
80 
81  auto *ElementCI = dyn_cast_or_null<ConstantInt>(Element);
82  if (!ElementCI)
83  return ConstantExpr::getBitCast(C, DestTy);
84 
85  Result <<= BitShift;
86  Result |= ElementCI->getValue().zextOrSelf(Result.getBitWidth());
87  }
88 
89  return nullptr;
90 }
91 
92 /// Constant fold bitcast, symbolically evaluating it with DataLayout.
93 /// This always returns a non-null constant, but it may be a
94 /// ConstantExpr if unfoldable.
95 Constant *FoldBitCast(Constant *C, Type *DestTy, const DataLayout &DL) {
96  // Catch the obvious splat cases.
97  if (C->isNullValue() && !DestTy->isX86_MMXTy())
98  return Constant::getNullValue(DestTy);
99  if (C->isAllOnesValue() && !DestTy->isX86_MMXTy() &&
100  !DestTy->isPtrOrPtrVectorTy()) // Don't get ones for ptr types!
101  return Constant::getAllOnesValue(DestTy);
102 
103  if (auto *VTy = dyn_cast<VectorType>(C->getType())) {
104  // Handle a vector->scalar integer/fp cast.
105  if (isa<IntegerType>(DestTy) || DestTy->isFloatingPointTy()) {
106  unsigned NumSrcElts = VTy->getNumElements();
107  Type *SrcEltTy = VTy->getElementType();
108 
109  // If the vector is a vector of floating point, convert it to vector of int
110  // to simplify things.
111  if (SrcEltTy->isFloatingPointTy()) {
112  unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
113  Type *SrcIVTy =
114  VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumSrcElts);
115  // Ask IR to do the conversion now that #elts line up.
116  C = ConstantExpr::getBitCast(C, SrcIVTy);
117  }
118 
119  APInt Result(DL.getTypeSizeInBits(DestTy), 0);
120  if (Constant *CE = foldConstVectorToAPInt(Result, DestTy, C,
121  SrcEltTy, NumSrcElts, DL))
122  return CE;
123 
124  if (isa<IntegerType>(DestTy))
125  return ConstantInt::get(DestTy, Result);
126 
127  APFloat FP(DestTy->getFltSemantics(), Result);
128  return ConstantFP::get(DestTy->getContext(), FP);
129  }
130  }
131 
132  // The code below only handles casts to vectors currently.
133  auto *DestVTy = dyn_cast<VectorType>(DestTy);
134  if (!DestVTy)
135  return ConstantExpr::getBitCast(C, DestTy);
136 
137  // If this is a scalar -> vector cast, convert the input into a <1 x scalar>
138  // vector so the code below can handle it uniformly.
139  if (isa<ConstantFP>(C) || isa<ConstantInt>(C)) {
140  Constant *Ops = C; // don't take the address of C!
141  return FoldBitCast(ConstantVector::get(Ops), DestTy, DL);
142  }
143 
144  // If this is a bitcast from constant vector -> vector, fold it.
145  if (!isa<ConstantDataVector>(C) && !isa<ConstantVector>(C))
146  return ConstantExpr::getBitCast(C, DestTy);
147 
148  // If the element types match, IR can fold it.
149  unsigned NumDstElt = DestVTy->getNumElements();
150  unsigned NumSrcElt = C->getType()->getVectorNumElements();
151  if (NumDstElt == NumSrcElt)
152  return ConstantExpr::getBitCast(C, DestTy);
153 
154  Type *SrcEltTy = C->getType()->getVectorElementType();
155  Type *DstEltTy = DestVTy->getElementType();
156 
157  // Otherwise, we're changing the number of elements in a vector, which
158  // requires endianness information to do the right thing. For example,
159  // bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
160  // folds to (little endian):
161  // <4 x i32> <i32 0, i32 0, i32 1, i32 0>
162  // and to (big endian):
163  // <4 x i32> <i32 0, i32 0, i32 0, i32 1>
164 
165  // First thing is first. We only want to think about integer here, so if
166  // we have something in FP form, recast it as integer.
167  if (DstEltTy->isFloatingPointTy()) {
168  // Fold to an vector of integers with same size as our FP type.
169  unsigned FPWidth = DstEltTy->getPrimitiveSizeInBits();
170  Type *DestIVTy =
171  VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumDstElt);
172  // Recursively handle this integer conversion, if possible.
173  C = FoldBitCast(C, DestIVTy, DL);
174 
175  // Finally, IR can handle this now that #elts line up.
176  return ConstantExpr::getBitCast(C, DestTy);
177  }
178 
179  // Okay, we know the destination is integer, if the input is FP, convert
180  // it to integer first.
181  if (SrcEltTy->isFloatingPointTy()) {
182  unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
183  Type *SrcIVTy =
184  VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumSrcElt);
185  // Ask IR to do the conversion now that #elts line up.
186  C = ConstantExpr::getBitCast(C, SrcIVTy);
187  // If IR wasn't able to fold it, bail out.
188  if (!isa<ConstantVector>(C) && // FIXME: Remove ConstantVector.
189  !isa<ConstantDataVector>(C))
190  return C;
191  }
192 
193  // Now we know that the input and output vectors are both integer vectors
194  // of the same size, and that their #elements is not the same. Do the
195  // conversion here, which depends on whether the input or output has
196  // more elements.
197  bool isLittleEndian = DL.isLittleEndian();
198 
200  if (NumDstElt < NumSrcElt) {
201  // Handle: bitcast (<4 x i32> <i32 0, i32 1, i32 2, i32 3> to <2 x i64>)
202  Constant *Zero = Constant::getNullValue(DstEltTy);
203  unsigned Ratio = NumSrcElt/NumDstElt;
204  unsigned SrcBitSize = SrcEltTy->getPrimitiveSizeInBits();
205  unsigned SrcElt = 0;
206  for (unsigned i = 0; i != NumDstElt; ++i) {
207  // Build each element of the result.
208  Constant *Elt = Zero;
209  unsigned ShiftAmt = isLittleEndian ? 0 : SrcBitSize*(Ratio-1);
210  for (unsigned j = 0; j != Ratio; ++j) {
211  Constant *Src = C->getAggregateElement(SrcElt++);
212  if (Src && isa<UndefValue>(Src))
214  else
215  Src = dyn_cast_or_null<ConstantInt>(Src);
216  if (!Src) // Reject constantexpr elements.
217  return ConstantExpr::getBitCast(C, DestTy);
218 
219  // Zero extend the element to the right size.
220  Src = ConstantExpr::getZExt(Src, Elt->getType());
221 
222  // Shift it to the right place, depending on endianness.
223  Src = ConstantExpr::getShl(Src,
224  ConstantInt::get(Src->getType(), ShiftAmt));
225  ShiftAmt += isLittleEndian ? SrcBitSize : -SrcBitSize;
226 
227  // Mix it in.
228  Elt = ConstantExpr::getOr(Elt, Src);
229  }
230  Result.push_back(Elt);
231  }
232  return ConstantVector::get(Result);
233  }
234 
235  // Handle: bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
236  unsigned Ratio = NumDstElt/NumSrcElt;
237  unsigned DstBitSize = DL.getTypeSizeInBits(DstEltTy);
238 
239  // Loop over each source value, expanding into multiple results.
240  for (unsigned i = 0; i != NumSrcElt; ++i) {
241  auto *Element = C->getAggregateElement(i);
242 
243  if (!Element) // Reject constantexpr elements.
244  return ConstantExpr::getBitCast(C, DestTy);
245 
246  if (isa<UndefValue>(Element)) {
247  // Correctly Propagate undef values.
248  Result.append(Ratio, UndefValue::get(DstEltTy));
249  continue;
250  }
251 
252  auto *Src = dyn_cast<ConstantInt>(Element);
253  if (!Src)
254  return ConstantExpr::getBitCast(C, DestTy);
255 
256  unsigned ShiftAmt = isLittleEndian ? 0 : DstBitSize*(Ratio-1);
257  for (unsigned j = 0; j != Ratio; ++j) {
258  // Shift the piece of the value into the right place, depending on
259  // endianness.
260  Constant *Elt = ConstantExpr::getLShr(Src,
261  ConstantInt::get(Src->getType(), ShiftAmt));
262  ShiftAmt += isLittleEndian ? DstBitSize : -DstBitSize;
263 
264  // Truncate the element to an integer with the same pointer size and
265  // convert the element back to a pointer using a inttoptr.
266  if (DstEltTy->isPointerTy()) {
267  IntegerType *DstIntTy = Type::getIntNTy(C->getContext(), DstBitSize);
268  Constant *CE = ConstantExpr::getTrunc(Elt, DstIntTy);
269  Result.push_back(ConstantExpr::getIntToPtr(CE, DstEltTy));
270  continue;
271  }
272 
273  // Truncate and remember this piece.
274  Result.push_back(ConstantExpr::getTrunc(Elt, DstEltTy));
275  }
276  }
277 
278  return ConstantVector::get(Result);
279 }
280 
281 } // end anonymous namespace
282 
283 /// If this constant is a constant offset from a global, return the global and
284 /// the constant. Because of constantexprs, this function is recursive.
286  APInt &Offset, const DataLayout &DL) {
287  // Trivial case, constant is the global.
288  if ((GV = dyn_cast<GlobalValue>(C))) {
289  unsigned BitWidth = DL.getIndexTypeSizeInBits(GV->getType());
290  Offset = APInt(BitWidth, 0);
291  return true;
292  }
293 
294  // Otherwise, if this isn't a constant expr, bail out.
295  auto *CE = dyn_cast<ConstantExpr>(C);
296  if (!CE) return false;
297 
298  // Look through ptr->int and ptr->ptr casts.
299  if (CE->getOpcode() == Instruction::PtrToInt ||
300  CE->getOpcode() == Instruction::BitCast)
301  return IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, DL);
302 
303  // i32* getelementptr ([5 x i32]* @a, i32 0, i32 5)
304  auto *GEP = dyn_cast<GEPOperator>(CE);
305  if (!GEP)
306  return false;
307 
308  unsigned BitWidth = DL.getIndexTypeSizeInBits(GEP->getType());
309  APInt TmpOffset(BitWidth, 0);
310 
311  // If the base isn't a global+constant, we aren't either.
312  if (!IsConstantOffsetFromGlobal(CE->getOperand(0), GV, TmpOffset, DL))
313  return false;
314 
315  // Otherwise, add any offset that our operands provide.
316  if (!GEP->accumulateConstantOffset(DL, TmpOffset))
317  return false;
318 
319  Offset = TmpOffset;
320  return true;
321 }
322 
324  const DataLayout &DL) {
325  do {
326  Type *SrcTy = C->getType();
327 
328  // If the type sizes are the same and a cast is legal, just directly
329  // cast the constant.
330  if (DL.getTypeSizeInBits(DestTy) == DL.getTypeSizeInBits(SrcTy)) {
331  Instruction::CastOps Cast = Instruction::BitCast;
332  // If we are going from a pointer to int or vice versa, we spell the cast
333  // differently.
334  if (SrcTy->isIntegerTy() && DestTy->isPointerTy())
335  Cast = Instruction::IntToPtr;
336  else if (SrcTy->isPointerTy() && DestTy->isIntegerTy())
337  Cast = Instruction::PtrToInt;
338 
339  if (CastInst::castIsValid(Cast, C, DestTy))
340  return ConstantExpr::getCast(Cast, C, DestTy);
341  }
342 
343  // If this isn't an aggregate type, there is nothing we can do to drill down
344  // and find a bitcastable constant.
345  if (!SrcTy->isAggregateType())
346  return nullptr;
347 
348  // We're simulating a load through a pointer that was bitcast to point to
349  // a different type, so we can try to walk down through the initial
350  // elements of an aggregate to see if some part of the aggregate is
351  // castable to implement the "load" semantic model.
352  if (SrcTy->isStructTy()) {
353  // Struct types might have leading zero-length elements like [0 x i32],
354  // which are certainly not what we are looking for, so skip them.
355  unsigned Elem = 0;
356  Constant *ElemC;
357  do {
358  ElemC = C->getAggregateElement(Elem++);
359  } while (ElemC && DL.getTypeSizeInBits(ElemC->getType()) == 0);
360  C = ElemC;
361  } else {
362  C = C->getAggregateElement(0u);
363  }
364  } while (C);
365 
366  return nullptr;
367 }
368 
369 namespace {
370 
371 /// Recursive helper to read bits out of global. C is the constant being copied
372 /// out of. ByteOffset is an offset into C. CurPtr is the pointer to copy
373 /// results into and BytesLeft is the number of bytes left in
374 /// the CurPtr buffer. DL is the DataLayout.
375 bool ReadDataFromGlobal(Constant *C, uint64_t ByteOffset, unsigned char *CurPtr,
376  unsigned BytesLeft, const DataLayout &DL) {
377  assert(ByteOffset <= DL.getTypeAllocSize(C->getType()) &&
378  "Out of range access");
379 
380  // If this element is zero or undefined, we can just return since *CurPtr is
381  // zero initialized.
382  if (isa<ConstantAggregateZero>(C) || isa<UndefValue>(C))
383  return true;
384 
385  if (auto *CI = dyn_cast<ConstantInt>(C)) {
386  if (CI->getBitWidth() > 64 ||
387  (CI->getBitWidth() & 7) != 0)
388  return false;
389 
390  uint64_t Val = CI->getZExtValue();
391  unsigned IntBytes = unsigned(CI->getBitWidth()/8);
392 
393  for (unsigned i = 0; i != BytesLeft && ByteOffset != IntBytes; ++i) {
394  int n = ByteOffset;
395  if (!DL.isLittleEndian())
396  n = IntBytes - n - 1;
397  CurPtr[i] = (unsigned char)(Val >> (n * 8));
398  ++ByteOffset;
399  }
400  return true;
401  }
402 
403  if (auto *CFP = dyn_cast<ConstantFP>(C)) {
404  if (CFP->getType()->isDoubleTy()) {
405  C = FoldBitCast(C, Type::getInt64Ty(C->getContext()), DL);
406  return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL);
407  }
408  if (CFP->getType()->isFloatTy()){
409  C = FoldBitCast(C, Type::getInt32Ty(C->getContext()), DL);
410  return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL);
411  }
412  if (CFP->getType()->isHalfTy()){
413  C = FoldBitCast(C, Type::getInt16Ty(C->getContext()), DL);
414  return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL);
415  }
416  return false;
417  }
418 
419  if (auto *CS = dyn_cast<ConstantStruct>(C)) {
420  const StructLayout *SL = DL.getStructLayout(CS->getType());
421  unsigned Index = SL->getElementContainingOffset(ByteOffset);
422  uint64_t CurEltOffset = SL->getElementOffset(Index);
423  ByteOffset -= CurEltOffset;
424 
425  while (true) {
426  // If the element access is to the element itself and not to tail padding,
427  // read the bytes from the element.
428  uint64_t EltSize = DL.getTypeAllocSize(CS->getOperand(Index)->getType());
429 
430  if (ByteOffset < EltSize &&
431  !ReadDataFromGlobal(CS->getOperand(Index), ByteOffset, CurPtr,
432  BytesLeft, DL))
433  return false;
434 
435  ++Index;
436 
437  // Check to see if we read from the last struct element, if so we're done.
438  if (Index == CS->getType()->getNumElements())
439  return true;
440 
441  // If we read all of the bytes we needed from this element we're done.
442  uint64_t NextEltOffset = SL->getElementOffset(Index);
443 
444  if (BytesLeft <= NextEltOffset - CurEltOffset - ByteOffset)
445  return true;
446 
447  // Move to the next element of the struct.
448  CurPtr += NextEltOffset - CurEltOffset - ByteOffset;
449  BytesLeft -= NextEltOffset - CurEltOffset - ByteOffset;
450  ByteOffset = 0;
451  CurEltOffset = NextEltOffset;
452  }
453  // not reached.
454  }
455 
456  if (isa<ConstantArray>(C) || isa<ConstantVector>(C) ||
457  isa<ConstantDataSequential>(C)) {
458  Type *EltTy = C->getType()->getSequentialElementType();
459  uint64_t EltSize = DL.getTypeAllocSize(EltTy);
460  uint64_t Index = ByteOffset / EltSize;
461  uint64_t Offset = ByteOffset - Index * EltSize;
462  uint64_t NumElts;
463  if (auto *AT = dyn_cast<ArrayType>(C->getType()))
464  NumElts = AT->getNumElements();
465  else
466  NumElts = C->getType()->getVectorNumElements();
467 
468  for (; Index != NumElts; ++Index) {
469  if (!ReadDataFromGlobal(C->getAggregateElement(Index), Offset, CurPtr,
470  BytesLeft, DL))
471  return false;
472 
473  uint64_t BytesWritten = EltSize - Offset;
474  assert(BytesWritten <= EltSize && "Not indexing into this element?");
475  if (BytesWritten >= BytesLeft)
476  return true;
477 
478  Offset = 0;
479  BytesLeft -= BytesWritten;
480  CurPtr += BytesWritten;
481  }
482  return true;
483  }
484 
485  if (auto *CE = dyn_cast<ConstantExpr>(C)) {
486  if (CE->getOpcode() == Instruction::IntToPtr &&
487  CE->getOperand(0)->getType() == DL.getIntPtrType(CE->getType())) {
488  return ReadDataFromGlobal(CE->getOperand(0), ByteOffset, CurPtr,
489  BytesLeft, DL);
490  }
491  }
492 
493  // Otherwise, unknown initializer type.
494  return false;
495 }
496 
497 Constant *FoldReinterpretLoadFromConstPtr(Constant *C, Type *LoadTy,
498  const DataLayout &DL) {
499  auto *PTy = cast<PointerType>(C->getType());
500  auto *IntType = dyn_cast<IntegerType>(LoadTy);
501 
502  // If this isn't an integer load we can't fold it directly.
503  if (!IntType) {
504  unsigned AS = PTy->getAddressSpace();
505 
506  // If this is a float/double load, we can try folding it as an int32/64 load
507  // and then bitcast the result. This can be useful for union cases. Note
508  // that address spaces don't matter here since we're not going to result in
509  // an actual new load.
510  Type *MapTy;
511  if (LoadTy->isHalfTy())
512  MapTy = Type::getInt16Ty(C->getContext());
513  else if (LoadTy->isFloatTy())
514  MapTy = Type::getInt32Ty(C->getContext());
515  else if (LoadTy->isDoubleTy())
516  MapTy = Type::getInt64Ty(C->getContext());
517  else if (LoadTy->isVectorTy()) {
518  MapTy = PointerType::getIntNTy(C->getContext(),
519  DL.getTypeAllocSizeInBits(LoadTy));
520  } else
521  return nullptr;
522 
523  C = FoldBitCast(C, MapTy->getPointerTo(AS), DL);
524  if (Constant *Res = FoldReinterpretLoadFromConstPtr(C, MapTy, DL))
525  return FoldBitCast(Res, LoadTy, DL);
526  return nullptr;
527  }
528 
529  unsigned BytesLoaded = (IntType->getBitWidth() + 7) / 8;
530  if (BytesLoaded > 32 || BytesLoaded == 0)
531  return nullptr;
532 
533  GlobalValue *GVal;
534  APInt OffsetAI;
535  if (!IsConstantOffsetFromGlobal(C, GVal, OffsetAI, DL))
536  return nullptr;
537 
538  auto *GV = dyn_cast<GlobalVariable>(GVal);
539  if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
540  !GV->getInitializer()->getType()->isSized())
541  return nullptr;
542 
543  int64_t Offset = OffsetAI.getSExtValue();
544  int64_t InitializerSize = DL.getTypeAllocSize(GV->getInitializer()->getType());
545 
546  // If we're not accessing anything in this constant, the result is undefined.
547  if (Offset + BytesLoaded <= 0)
548  return UndefValue::get(IntType);
549 
550  // If we're not accessing anything in this constant, the result is undefined.
551  if (Offset >= InitializerSize)
552  return UndefValue::get(IntType);
553 
554  unsigned char RawBytes[32] = {0};
555  unsigned char *CurPtr = RawBytes;
556  unsigned BytesLeft = BytesLoaded;
557 
558  // If we're loading off the beginning of the global, some bytes may be valid.
559  if (Offset < 0) {
560  CurPtr += -Offset;
561  BytesLeft += Offset;
562  Offset = 0;
563  }
564 
565  if (!ReadDataFromGlobal(GV->getInitializer(), Offset, CurPtr, BytesLeft, DL))
566  return nullptr;
567 
568  APInt ResultVal = APInt(IntType->getBitWidth(), 0);
569  if (DL.isLittleEndian()) {
570  ResultVal = RawBytes[BytesLoaded - 1];
571  for (unsigned i = 1; i != BytesLoaded; ++i) {
572  ResultVal <<= 8;
573  ResultVal |= RawBytes[BytesLoaded - 1 - i];
574  }
575  } else {
576  ResultVal = RawBytes[0];
577  for (unsigned i = 1; i != BytesLoaded; ++i) {
578  ResultVal <<= 8;
579  ResultVal |= RawBytes[i];
580  }
581  }
582 
583  return ConstantInt::get(IntType->getContext(), ResultVal);
584 }
585 
586 Constant *ConstantFoldLoadThroughBitcastExpr(ConstantExpr *CE, Type *DestTy,
587  const DataLayout &DL) {
588  auto *SrcPtr = CE->getOperand(0);
589  auto *SrcPtrTy = dyn_cast<PointerType>(SrcPtr->getType());
590  if (!SrcPtrTy)
591  return nullptr;
592  Type *SrcTy = SrcPtrTy->getPointerElementType();
593 
594  Constant *C = ConstantFoldLoadFromConstPtr(SrcPtr, SrcTy, DL);
595  if (!C)
596  return nullptr;
597 
598  return llvm::ConstantFoldLoadThroughBitcast(C, DestTy, DL);
599 }
600 
601 } // end anonymous namespace
602 
604  const DataLayout &DL) {
605  // First, try the easy cases:
606  if (auto *GV = dyn_cast<GlobalVariable>(C))
607  if (GV->isConstant() && GV->hasDefinitiveInitializer())
608  return GV->getInitializer();
609 
610  if (auto *GA = dyn_cast<GlobalAlias>(C))
611  if (GA->getAliasee() && !GA->isInterposable())
612  return ConstantFoldLoadFromConstPtr(GA->getAliasee(), Ty, DL);
613 
614  // If the loaded value isn't a constant expr, we can't handle it.
615  auto *CE = dyn_cast<ConstantExpr>(C);
616  if (!CE)
617  return nullptr;
618 
619  if (CE->getOpcode() == Instruction::GetElementPtr) {
620  if (auto *GV = dyn_cast<GlobalVariable>(CE->getOperand(0))) {
621  if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
622  if (Constant *V =
623  ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
624  return V;
625  }
626  }
627  }
628 
629  if (CE->getOpcode() == Instruction::BitCast)
630  if (Constant *LoadedC = ConstantFoldLoadThroughBitcastExpr(CE, Ty, DL))
631  return LoadedC;
632 
633  // Instead of loading constant c string, use corresponding integer value
634  // directly if string length is small enough.
635  StringRef Str;
636  if (getConstantStringInfo(CE, Str) && !Str.empty()) {
637  size_t StrLen = Str.size();
638  unsigned NumBits = Ty->getPrimitiveSizeInBits();
639  // Replace load with immediate integer if the result is an integer or fp
640  // value.
641  if ((NumBits >> 3) == StrLen + 1 && (NumBits & 7) == 0 &&
642  (isa<IntegerType>(Ty) || Ty->isFloatingPointTy())) {
643  APInt StrVal(NumBits, 0);
644  APInt SingleChar(NumBits, 0);
645  if (DL.isLittleEndian()) {
646  for (unsigned char C : reverse(Str.bytes())) {
647  SingleChar = static_cast<uint64_t>(C);
648  StrVal = (StrVal << 8) | SingleChar;
649  }
650  } else {
651  for (unsigned char C : Str.bytes()) {
652  SingleChar = static_cast<uint64_t>(C);
653  StrVal = (StrVal << 8) | SingleChar;
654  }
655  // Append NULL at the end.
656  SingleChar = 0;
657  StrVal = (StrVal << 8) | SingleChar;
658  }
659 
660  Constant *Res = ConstantInt::get(CE->getContext(), StrVal);
661  if (Ty->isFloatingPointTy())
662  Res = ConstantExpr::getBitCast(Res, Ty);
663  return Res;
664  }
665  }
666 
667  // If this load comes from anywhere in a constant global, and if the global
668  // is all undef or zero, we know what it loads.
669  if (auto *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(CE, DL))) {
670  if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
671  if (GV->getInitializer()->isNullValue())
672  return Constant::getNullValue(Ty);
673  if (isa<UndefValue>(GV->getInitializer()))
674  return UndefValue::get(Ty);
675  }
676  }
677 
678  // Try hard to fold loads from bitcasted strange and non-type-safe things.
679  return FoldReinterpretLoadFromConstPtr(CE, Ty, DL);
680 }
681 
682 namespace {
683 
684 Constant *ConstantFoldLoadInst(const LoadInst *LI, const DataLayout &DL) {
685  if (LI->isVolatile()) return nullptr;
686 
687  if (auto *C = dyn_cast<Constant>(LI->getOperand(0)))
688  return ConstantFoldLoadFromConstPtr(C, LI->getType(), DL);
689 
690  return nullptr;
691 }
692 
693 /// One of Op0/Op1 is a constant expression.
694 /// Attempt to symbolically evaluate the result of a binary operator merging
695 /// these together. If target data info is available, it is provided as DL,
696 /// otherwise DL is null.
697 Constant *SymbolicallyEvaluateBinop(unsigned Opc, Constant *Op0, Constant *Op1,
698  const DataLayout &DL) {
699  // SROA
700 
701  // Fold (and 0xffffffff00000000, (shl x, 32)) -> shl.
702  // Fold (lshr (or X, Y), 32) -> (lshr [X/Y], 32) if one doesn't contribute
703  // bits.
704 
705  if (Opc == Instruction::And) {
706  KnownBits Known0 = computeKnownBits(Op0, DL);
707  KnownBits Known1 = computeKnownBits(Op1, DL);
708  if ((Known1.One | Known0.Zero).isAllOnesValue()) {
709  // All the bits of Op0 that the 'and' could be masking are already zero.
710  return Op0;
711  }
712  if ((Known0.One | Known1.Zero).isAllOnesValue()) {
713  // All the bits of Op1 that the 'and' could be masking are already zero.
714  return Op1;
715  }
716 
717  Known0.Zero |= Known1.Zero;
718  Known0.One &= Known1.One;
719  if (Known0.isConstant())
720  return ConstantInt::get(Op0->getType(), Known0.getConstant());
721  }
722 
723  // If the constant expr is something like &A[123] - &A[4].f, fold this into a
724  // constant. This happens frequently when iterating over a global array.
725  if (Opc == Instruction::Sub) {
726  GlobalValue *GV1, *GV2;
727  APInt Offs1, Offs2;
728 
729  if (IsConstantOffsetFromGlobal(Op0, GV1, Offs1, DL))
730  if (IsConstantOffsetFromGlobal(Op1, GV2, Offs2, DL) && GV1 == GV2) {
731  unsigned OpSize = DL.getTypeSizeInBits(Op0->getType());
732 
733  // (&GV+C1) - (&GV+C2) -> C1-C2, pointer arithmetic cannot overflow.
734  // PtrToInt may change the bitwidth so we have convert to the right size
735  // first.
736  return ConstantInt::get(Op0->getType(), Offs1.zextOrTrunc(OpSize) -
737  Offs2.zextOrTrunc(OpSize));
738  }
739  }
740 
741  return nullptr;
742 }
743 
744 /// If array indices are not pointer-sized integers, explicitly cast them so
745 /// that they aren't implicitly casted by the getelementptr.
746 Constant *CastGEPIndices(Type *SrcElemTy, ArrayRef<Constant *> Ops,
747  Type *ResultTy, Optional<unsigned> InRangeIndex,
748  const DataLayout &DL, const TargetLibraryInfo *TLI) {
749  Type *IntPtrTy = DL.getIntPtrType(ResultTy);
750  Type *IntPtrScalarTy = IntPtrTy->getScalarType();
751 
752  bool Any = false;
754  for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
755  if ((i == 1 ||
756  !isa<StructType>(GetElementPtrInst::getIndexedType(
757  SrcElemTy, Ops.slice(1, i - 1)))) &&
758  Ops[i]->getType()->getScalarType() != IntPtrScalarTy) {
759  Any = true;
760  Type *NewType = Ops[i]->getType()->isVectorTy()
761  ? IntPtrTy
762  : IntPtrTy->getScalarType();
764  true,
765  NewType,
766  true),
767  Ops[i], NewType));
768  } else
769  NewIdxs.push_back(Ops[i]);
770  }
771 
772  if (!Any)
773  return nullptr;
774 
776  SrcElemTy, Ops[0], NewIdxs, /*InBounds=*/false, InRangeIndex);
777  if (Constant *Folded = ConstantFoldConstant(C, DL, TLI))
778  C = Folded;
779 
780  return C;
781 }
782 
783 /// Strip the pointer casts, but preserve the address space information.
784 Constant* StripPtrCastKeepAS(Constant* Ptr, Type *&ElemTy) {
785  assert(Ptr->getType()->isPointerTy() && "Not a pointer type");
786  auto *OldPtrTy = cast<PointerType>(Ptr->getType());
787  Ptr = Ptr->stripPointerCasts();
788  auto *NewPtrTy = cast<PointerType>(Ptr->getType());
789 
790  ElemTy = NewPtrTy->getPointerElementType();
791 
792  // Preserve the address space number of the pointer.
793  if (NewPtrTy->getAddressSpace() != OldPtrTy->getAddressSpace()) {
794  NewPtrTy = ElemTy->getPointerTo(OldPtrTy->getAddressSpace());
795  Ptr = ConstantExpr::getPointerCast(Ptr, NewPtrTy);
796  }
797  return Ptr;
798 }
799 
800 /// If we can symbolically evaluate the GEP constant expression, do so.
801 Constant *SymbolicallyEvaluateGEP(const GEPOperator *GEP,
803  const DataLayout &DL,
804  const TargetLibraryInfo *TLI) {
805  const GEPOperator *InnermostGEP = GEP;
806  bool InBounds = GEP->isInBounds();
807 
808  Type *SrcElemTy = GEP->getSourceElementType();
809  Type *ResElemTy = GEP->getResultElementType();
810  Type *ResTy = GEP->getType();
811  if (!SrcElemTy->isSized())
812  return nullptr;
813 
814  if (Constant *C = CastGEPIndices(SrcElemTy, Ops, ResTy,
815  GEP->getInRangeIndex(), DL, TLI))
816  return C;
817 
818  Constant *Ptr = Ops[0];
819  if (!Ptr->getType()->isPointerTy())
820  return nullptr;
821 
822  Type *IntPtrTy = DL.getIntPtrType(Ptr->getType());
823 
824  // If this is a constant expr gep that is effectively computing an
825  // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
826  for (unsigned i = 1, e = Ops.size(); i != e; ++i)
827  if (!isa<ConstantInt>(Ops[i])) {
828 
829  // If this is "gep i8* Ptr, (sub 0, V)", fold this as:
830  // "inttoptr (sub (ptrtoint Ptr), V)"
831  if (Ops.size() == 2 && ResElemTy->isIntegerTy(8)) {
832  auto *CE = dyn_cast<ConstantExpr>(Ops[1]);
833  assert((!CE || CE->getType() == IntPtrTy) &&
834  "CastGEPIndices didn't canonicalize index types!");
835  if (CE && CE->getOpcode() == Instruction::Sub &&
836  CE->getOperand(0)->isNullValue()) {
837  Constant *Res = ConstantExpr::getPtrToInt(Ptr, CE->getType());
838  Res = ConstantExpr::getSub(Res, CE->getOperand(1));
839  Res = ConstantExpr::getIntToPtr(Res, ResTy);
840  if (auto *FoldedRes = ConstantFoldConstant(Res, DL, TLI))
841  Res = FoldedRes;
842  return Res;
843  }
844  }
845  return nullptr;
846  }
847 
848  unsigned BitWidth = DL.getTypeSizeInBits(IntPtrTy);
849  APInt Offset =
850  APInt(BitWidth,
852  SrcElemTy,
853  makeArrayRef((Value * const *)Ops.data() + 1, Ops.size() - 1)));
854  Ptr = StripPtrCastKeepAS(Ptr, SrcElemTy);
855 
856  // If this is a GEP of a GEP, fold it all into a single GEP.
857  while (auto *GEP = dyn_cast<GEPOperator>(Ptr)) {
858  InnermostGEP = GEP;
859  InBounds &= GEP->isInBounds();
860 
861  SmallVector<Value *, 4> NestedOps(GEP->op_begin() + 1, GEP->op_end());
862 
863  // Do not try the incorporate the sub-GEP if some index is not a number.
864  bool AllConstantInt = true;
865  for (Value *NestedOp : NestedOps)
866  if (!isa<ConstantInt>(NestedOp)) {
867  AllConstantInt = false;
868  break;
869  }
870  if (!AllConstantInt)
871  break;
872 
873  Ptr = cast<Constant>(GEP->getOperand(0));
874  SrcElemTy = GEP->getSourceElementType();
875  Offset += APInt(BitWidth, DL.getIndexedOffsetInType(SrcElemTy, NestedOps));
876  Ptr = StripPtrCastKeepAS(Ptr, SrcElemTy);
877  }
878 
879  // If the base value for this address is a literal integer value, fold the
880  // getelementptr to the resulting integer value casted to the pointer type.
881  APInt BasePtr(BitWidth, 0);
882  if (auto *CE = dyn_cast<ConstantExpr>(Ptr)) {
883  if (CE->getOpcode() == Instruction::IntToPtr) {
884  if (auto *Base = dyn_cast<ConstantInt>(CE->getOperand(0)))
885  BasePtr = Base->getValue().zextOrTrunc(BitWidth);
886  }
887  }
888 
889  auto *PTy = cast<PointerType>(Ptr->getType());
890  if ((Ptr->isNullValue() || BasePtr != 0) &&
891  !DL.isNonIntegralPointerType(PTy)) {
892  Constant *C = ConstantInt::get(Ptr->getContext(), Offset + BasePtr);
893  return ConstantExpr::getIntToPtr(C, ResTy);
894  }
895 
896  // Otherwise form a regular getelementptr. Recompute the indices so that
897  // we eliminate over-indexing of the notional static type array bounds.
898  // This makes it easy to determine if the getelementptr is "inbounds".
899  // Also, this helps GlobalOpt do SROA on GlobalVariables.
900  Type *Ty = PTy;
902 
903  do {
904  if (!Ty->isStructTy()) {
905  if (Ty->isPointerTy()) {
906  // The only pointer indexing we'll do is on the first index of the GEP.
907  if (!NewIdxs.empty())
908  break;
909 
910  Ty = SrcElemTy;
911 
912  // Only handle pointers to sized types, not pointers to functions.
913  if (!Ty->isSized())
914  return nullptr;
915  } else if (auto *ATy = dyn_cast<SequentialType>(Ty)) {
916  Ty = ATy->getElementType();
917  } else {
918  // We've reached some non-indexable type.
919  break;
920  }
921 
922  // Determine which element of the array the offset points into.
923  APInt ElemSize(BitWidth, DL.getTypeAllocSize(Ty));
924  if (ElemSize == 0) {
925  // The element size is 0. This may be [0 x Ty]*, so just use a zero
926  // index for this level and proceed to the next level to see if it can
927  // accommodate the offset.
928  NewIdxs.push_back(ConstantInt::get(IntPtrTy, 0));
929  } else {
930  // The element size is non-zero divide the offset by the element
931  // size (rounding down), to compute the index at this level.
932  bool Overflow;
933  APInt NewIdx = Offset.sdiv_ov(ElemSize, Overflow);
934  if (Overflow)
935  break;
936  Offset -= NewIdx * ElemSize;
937  NewIdxs.push_back(ConstantInt::get(IntPtrTy, NewIdx));
938  }
939  } else {
940  auto *STy = cast<StructType>(Ty);
941  // If we end up with an offset that isn't valid for this struct type, we
942  // can't re-form this GEP in a regular form, so bail out. The pointer
943  // operand likely went through casts that are necessary to make the GEP
944  // sensible.
945  const StructLayout &SL = *DL.getStructLayout(STy);
946  if (Offset.isNegative() || Offset.uge(SL.getSizeInBytes()))
947  break;
948 
949  // Determine which field of the struct the offset points into. The
950  // getZExtValue is fine as we've already ensured that the offset is
951  // within the range representable by the StructLayout API.
952  unsigned ElIdx = SL.getElementContainingOffset(Offset.getZExtValue());
954  ElIdx));
955  Offset -= APInt(BitWidth, SL.getElementOffset(ElIdx));
956  Ty = STy->getTypeAtIndex(ElIdx);
957  }
958  } while (Ty != ResElemTy);
959 
960  // If we haven't used up the entire offset by descending the static
961  // type, then the offset is pointing into the middle of an indivisible
962  // member, so we can't simplify it.
963  if (Offset != 0)
964  return nullptr;
965 
966  // Preserve the inrange index from the innermost GEP if possible. We must
967  // have calculated the same indices up to and including the inrange index.
968  Optional<unsigned> InRangeIndex;
969  if (Optional<unsigned> LastIRIndex = InnermostGEP->getInRangeIndex())
970  if (SrcElemTy == InnermostGEP->getSourceElementType() &&
971  NewIdxs.size() > *LastIRIndex) {
972  InRangeIndex = LastIRIndex;
973  for (unsigned I = 0; I <= *LastIRIndex; ++I)
974  if (NewIdxs[I] != InnermostGEP->getOperand(I + 1))
975  return nullptr;
976  }
977 
978  // Create a GEP.
979  Constant *C = ConstantExpr::getGetElementPtr(SrcElemTy, Ptr, NewIdxs,
980  InBounds, InRangeIndex);
981  assert(C->getType()->getPointerElementType() == Ty &&
982  "Computed GetElementPtr has unexpected type!");
983 
984  // If we ended up indexing a member with a type that doesn't match
985  // the type of what the original indices indexed, add a cast.
986  if (Ty != ResElemTy)
987  C = FoldBitCast(C, ResTy, DL);
988 
989  return C;
990 }
991 
992 /// Attempt to constant fold an instruction with the
993 /// specified opcode and operands. If successful, the constant result is
994 /// returned, if not, null is returned. Note that this function can fail when
995 /// attempting to fold instructions like loads and stores, which have no
996 /// constant expression form.
997 Constant *ConstantFoldInstOperandsImpl(const Value *InstOrCE, unsigned Opcode,
999  const DataLayout &DL,
1000  const TargetLibraryInfo *TLI) {
1001  Type *DestTy = InstOrCE->getType();
1002 
1003  // Handle easy binops first.
1004  if (Instruction::isBinaryOp(Opcode))
1005  return ConstantFoldBinaryOpOperands(Opcode, Ops[0], Ops[1], DL);
1006 
1007  if (Instruction::isCast(Opcode))
1008  return ConstantFoldCastOperand(Opcode, Ops[0], DestTy, DL);
1009 
1010  if (auto *GEP = dyn_cast<GEPOperator>(InstOrCE)) {
1011  if (Constant *C = SymbolicallyEvaluateGEP(GEP, Ops, DL, TLI))
1012  return C;
1013 
1015  Ops.slice(1), GEP->isInBounds(),
1016  GEP->getInRangeIndex());
1017  }
1018 
1019  if (auto *CE = dyn_cast<ConstantExpr>(InstOrCE))
1020  return CE->getWithOperands(Ops);
1021 
1022  switch (Opcode) {
1023  default: return nullptr;
1024  case Instruction::ICmp:
1025  case Instruction::FCmp: llvm_unreachable("Invalid for compares");
1026  case Instruction::Call:
1027  if (auto *F = dyn_cast<Function>(Ops.back())) {
1028  ImmutableCallSite CS(cast<CallInst>(InstOrCE));
1029  if (canConstantFoldCallTo(CS, F))
1030  return ConstantFoldCall(CS, F, Ops.slice(0, Ops.size() - 1), TLI);
1031  }
1032  return nullptr;
1033  case Instruction::Select:
1034  return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
1035  case Instruction::ExtractElement:
1036  return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
1037  case Instruction::InsertElement:
1038  return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
1039  case Instruction::ShuffleVector:
1040  return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
1041  }
1042 }
1043 
1044 } // end anonymous namespace
1045 
1046 //===----------------------------------------------------------------------===//
1047 // Constant Folding public APIs
1048 //===----------------------------------------------------------------------===//
1049 
1050 namespace {
1051 
1052 Constant *
1053 ConstantFoldConstantImpl(const Constant *C, const DataLayout &DL,
1054  const TargetLibraryInfo *TLI,
1056  if (!isa<ConstantVector>(C) && !isa<ConstantExpr>(C))
1057  return nullptr;
1058 
1060  for (const Use &NewU : C->operands()) {
1061  auto *NewC = cast<Constant>(&NewU);
1062  // Recursively fold the ConstantExpr's operands. If we have already folded
1063  // a ConstantExpr, we don't have to process it again.
1064  if (isa<ConstantVector>(NewC) || isa<ConstantExpr>(NewC)) {
1065  auto It = FoldedOps.find(NewC);
1066  if (It == FoldedOps.end()) {
1067  if (auto *FoldedC =
1068  ConstantFoldConstantImpl(NewC, DL, TLI, FoldedOps)) {
1069  FoldedOps.insert({NewC, FoldedC});
1070  NewC = FoldedC;
1071  } else {
1072  FoldedOps.insert({NewC, NewC});
1073  }
1074  } else {
1075  NewC = It->second;
1076  }
1077  }
1078  Ops.push_back(NewC);
1079  }
1080 
1081  if (auto *CE = dyn_cast<ConstantExpr>(C)) {
1082  if (CE->isCompare())
1083  return ConstantFoldCompareInstOperands(CE->getPredicate(), Ops[0], Ops[1],
1084  DL, TLI);
1085 
1086  return ConstantFoldInstOperandsImpl(CE, CE->getOpcode(), Ops, DL, TLI);
1087  }
1088 
1089  assert(isa<ConstantVector>(C));
1090  return ConstantVector::get(Ops);
1091 }
1092 
1093 } // end anonymous namespace
1094 
1096  const TargetLibraryInfo *TLI) {
1097  // Handle PHI nodes quickly here...
1098  if (auto *PN = dyn_cast<PHINode>(I)) {
1099  Constant *CommonValue = nullptr;
1100 
1102  for (Value *Incoming : PN->incoming_values()) {
1103  // If the incoming value is undef then skip it. Note that while we could
1104  // skip the value if it is equal to the phi node itself we choose not to
1105  // because that would break the rule that constant folding only applies if
1106  // all operands are constants.
1107  if (isa<UndefValue>(Incoming))
1108  continue;
1109  // If the incoming value is not a constant, then give up.
1110  auto *C = dyn_cast<Constant>(Incoming);
1111  if (!C)
1112  return nullptr;
1113  // Fold the PHI's operands.
1114  if (auto *FoldedC = ConstantFoldConstantImpl(C, DL, TLI, FoldedOps))
1115  C = FoldedC;
1116  // If the incoming value is a different constant to
1117  // the one we saw previously, then give up.
1118  if (CommonValue && C != CommonValue)
1119  return nullptr;
1120  CommonValue = C;
1121  }
1122 
1123  // If we reach here, all incoming values are the same constant or undef.
1124  return CommonValue ? CommonValue : UndefValue::get(PN->getType());
1125  }
1126 
1127  // Scan the operand list, checking to see if they are all constants, if so,
1128  // hand off to ConstantFoldInstOperandsImpl.
1129  if (!all_of(I->operands(), [](Use &U) { return isa<Constant>(U); }))
1130  return nullptr;
1131 
1134  for (const Use &OpU : I->operands()) {
1135  auto *Op = cast<Constant>(&OpU);
1136  // Fold the Instruction's operands.
1137  if (auto *FoldedOp = ConstantFoldConstantImpl(Op, DL, TLI, FoldedOps))
1138  Op = FoldedOp;
1139 
1140  Ops.push_back(Op);
1141  }
1142 
1143  if (const auto *CI = dyn_cast<CmpInst>(I))
1144  return ConstantFoldCompareInstOperands(CI->getPredicate(), Ops[0], Ops[1],
1145  DL, TLI);
1146 
1147  if (const auto *LI = dyn_cast<LoadInst>(I))
1148  return ConstantFoldLoadInst(LI, DL);
1149 
1150  if (auto *IVI = dyn_cast<InsertValueInst>(I)) {
1152  cast<Constant>(IVI->getAggregateOperand()),
1153  cast<Constant>(IVI->getInsertedValueOperand()),
1154  IVI->getIndices());
1155  }
1156 
1157  if (auto *EVI = dyn_cast<ExtractValueInst>(I)) {
1159  cast<Constant>(EVI->getAggregateOperand()),
1160  EVI->getIndices());
1161  }
1162 
1163  return ConstantFoldInstOperands(I, Ops, DL, TLI);
1164 }
1165 
1167  const TargetLibraryInfo *TLI) {
1169  return ConstantFoldConstantImpl(C, DL, TLI, FoldedOps);
1170 }
1171 
1174  const DataLayout &DL,
1175  const TargetLibraryInfo *TLI) {
1176  return ConstantFoldInstOperandsImpl(I, I->getOpcode(), Ops, DL, TLI);
1177 }
1178 
1180  Constant *Ops0, Constant *Ops1,
1181  const DataLayout &DL,
1182  const TargetLibraryInfo *TLI) {
1183  // fold: icmp (inttoptr x), null -> icmp x, 0
1184  // fold: icmp null, (inttoptr x) -> icmp 0, x
1185  // fold: icmp (ptrtoint x), 0 -> icmp x, null
1186  // fold: icmp 0, (ptrtoint x) -> icmp null, x
1187  // fold: icmp (inttoptr x), (inttoptr y) -> icmp trunc/zext x, trunc/zext y
1188  // fold: icmp (ptrtoint x), (ptrtoint y) -> icmp x, y
1189  //
1190  // FIXME: The following comment is out of data and the DataLayout is here now.
1191  // ConstantExpr::getCompare cannot do this, because it doesn't have DL
1192  // around to know if bit truncation is happening.
1193  if (auto *CE0 = dyn_cast<ConstantExpr>(Ops0)) {
1194  if (Ops1->isNullValue()) {
1195  if (CE0->getOpcode() == Instruction::IntToPtr) {
1196  Type *IntPtrTy = DL.getIntPtrType(CE0->getType());
1197  // Convert the integer value to the right size to ensure we get the
1198  // proper extension or truncation.
1199  Constant *C = ConstantExpr::getIntegerCast(CE0->getOperand(0),
1200  IntPtrTy, false);
1201  Constant *Null = Constant::getNullValue(C->getType());
1202  return ConstantFoldCompareInstOperands(Predicate, C, Null, DL, TLI);
1203  }
1204 
1205  // Only do this transformation if the int is intptrty in size, otherwise
1206  // there is a truncation or extension that we aren't modeling.
1207  if (CE0->getOpcode() == Instruction::PtrToInt) {
1208  Type *IntPtrTy = DL.getIntPtrType(CE0->getOperand(0)->getType());
1209  if (CE0->getType() == IntPtrTy) {
1210  Constant *C = CE0->getOperand(0);
1211  Constant *Null = Constant::getNullValue(C->getType());
1212  return ConstantFoldCompareInstOperands(Predicate, C, Null, DL, TLI);
1213  }
1214  }
1215  }
1216 
1217  if (auto *CE1 = dyn_cast<ConstantExpr>(Ops1)) {
1218  if (CE0->getOpcode() == CE1->getOpcode()) {
1219  if (CE0->getOpcode() == Instruction::IntToPtr) {
1220  Type *IntPtrTy = DL.getIntPtrType(CE0->getType());
1221 
1222  // Convert the integer value to the right size to ensure we get the
1223  // proper extension or truncation.
1224  Constant *C0 = ConstantExpr::getIntegerCast(CE0->getOperand(0),
1225  IntPtrTy, false);
1226  Constant *C1 = ConstantExpr::getIntegerCast(CE1->getOperand(0),
1227  IntPtrTy, false);
1228  return ConstantFoldCompareInstOperands(Predicate, C0, C1, DL, TLI);
1229  }
1230 
1231  // Only do this transformation if the int is intptrty in size, otherwise
1232  // there is a truncation or extension that we aren't modeling.
1233  if (CE0->getOpcode() == Instruction::PtrToInt) {
1234  Type *IntPtrTy = DL.getIntPtrType(CE0->getOperand(0)->getType());
1235  if (CE0->getType() == IntPtrTy &&
1236  CE0->getOperand(0)->getType() == CE1->getOperand(0)->getType()) {
1238  Predicate, CE0->getOperand(0), CE1->getOperand(0), DL, TLI);
1239  }
1240  }
1241  }
1242  }
1243 
1244  // icmp eq (or x, y), 0 -> (icmp eq x, 0) & (icmp eq y, 0)
1245  // icmp ne (or x, y), 0 -> (icmp ne x, 0) | (icmp ne y, 0)
1246  if ((Predicate == ICmpInst::ICMP_EQ || Predicate == ICmpInst::ICMP_NE) &&
1247  CE0->getOpcode() == Instruction::Or && Ops1->isNullValue()) {
1249  Predicate, CE0->getOperand(0), Ops1, DL, TLI);
1251  Predicate, CE0->getOperand(1), Ops1, DL, TLI);
1252  unsigned OpC =
1253  Predicate == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
1254  return ConstantFoldBinaryOpOperands(OpC, LHS, RHS, DL);
1255  }
1256  } else if (isa<ConstantExpr>(Ops1)) {
1257  // If RHS is a constant expression, but the left side isn't, swap the
1258  // operands and try again.
1259  Predicate = ICmpInst::getSwappedPredicate((ICmpInst::Predicate)Predicate);
1260  return ConstantFoldCompareInstOperands(Predicate, Ops1, Ops0, DL, TLI);
1261  }
1262 
1263  return ConstantExpr::getCompare(Predicate, Ops0, Ops1);
1264 }
1265 
1267  Constant *RHS,
1268  const DataLayout &DL) {
1270  if (isa<ConstantExpr>(LHS) || isa<ConstantExpr>(RHS))
1271  if (Constant *C = SymbolicallyEvaluateBinop(Opcode, LHS, RHS, DL))
1272  return C;
1273 
1274  return ConstantExpr::get(Opcode, LHS, RHS);
1275 }
1276 
1278  Type *DestTy, const DataLayout &DL) {
1279  assert(Instruction::isCast(Opcode));
1280  switch (Opcode) {
1281  default:
1282  llvm_unreachable("Missing case");
1283  case Instruction::PtrToInt:
1284  // If the input is a inttoptr, eliminate the pair. This requires knowing
1285  // the width of a pointer, so it can't be done in ConstantExpr::getCast.
1286  if (auto *CE = dyn_cast<ConstantExpr>(C)) {
1287  if (CE->getOpcode() == Instruction::IntToPtr) {
1288  Constant *Input = CE->getOperand(0);
1289  unsigned InWidth = Input->getType()->getScalarSizeInBits();
1290  unsigned PtrWidth = DL.getPointerTypeSizeInBits(CE->getType());
1291  if (PtrWidth < InWidth) {
1292  Constant *Mask =
1293  ConstantInt::get(CE->getContext(),
1294  APInt::getLowBitsSet(InWidth, PtrWidth));
1295  Input = ConstantExpr::getAnd(Input, Mask);
1296  }
1297  // Do a zext or trunc to get to the dest size.
1298  return ConstantExpr::getIntegerCast(Input, DestTy, false);
1299  }
1300  }
1301  return ConstantExpr::getCast(Opcode, C, DestTy);
1302  case Instruction::IntToPtr:
1303  // If the input is a ptrtoint, turn the pair into a ptr to ptr bitcast if
1304  // the int size is >= the ptr size and the address spaces are the same.
1305  // This requires knowing the width of a pointer, so it can't be done in
1306  // ConstantExpr::getCast.
1307  if (auto *CE = dyn_cast<ConstantExpr>(C)) {
1308  if (CE->getOpcode() == Instruction::PtrToInt) {
1309  Constant *SrcPtr = CE->getOperand(0);
1310  unsigned SrcPtrSize = DL.getPointerTypeSizeInBits(SrcPtr->getType());
1311  unsigned MidIntSize = CE->getType()->getScalarSizeInBits();
1312 
1313  if (MidIntSize >= SrcPtrSize) {
1314  unsigned SrcAS = SrcPtr->getType()->getPointerAddressSpace();
1315  if (SrcAS == DestTy->getPointerAddressSpace())
1316  return FoldBitCast(CE->getOperand(0), DestTy, DL);
1317  }
1318  }
1319  }
1320 
1321  return ConstantExpr::getCast(Opcode, C, DestTy);
1322  case Instruction::Trunc:
1323  case Instruction::ZExt:
1324  case Instruction::SExt:
1325  case Instruction::FPTrunc:
1326  case Instruction::FPExt:
1327  case Instruction::UIToFP:
1328  case Instruction::SIToFP:
1329  case Instruction::FPToUI:
1330  case Instruction::FPToSI:
1331  case Instruction::AddrSpaceCast:
1332  return ConstantExpr::getCast(Opcode, C, DestTy);
1333  case Instruction::BitCast:
1334  return FoldBitCast(C, DestTy, DL);
1335  }
1336 }
1337 
1339  ConstantExpr *CE) {
1340  if (!CE->getOperand(1)->isNullValue())
1341  return nullptr; // Do not allow stepping over the value!
1342 
1343  // Loop over all of the operands, tracking down which value we are
1344  // addressing.
1345  for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i) {
1346  C = C->getAggregateElement(CE->getOperand(i));
1347  if (!C)
1348  return nullptr;
1349  }
1350  return C;
1351 }
1352 
1353 Constant *
1355  ArrayRef<Constant *> Indices) {
1356  // Loop over all of the operands, tracking down which value we are
1357  // addressing.
1358  for (Constant *Index : Indices) {
1359  C = C->getAggregateElement(Index);
1360  if (!C)
1361  return nullptr;
1362  }
1363  return C;
1364 }
1365 
1366 //===----------------------------------------------------------------------===//
1367 // Constant Folding for Calls
1368 //
1369 
1371  if (CS.isNoBuiltin() || CS.isStrictFP())
1372  return false;
1373  switch (F->getIntrinsicID()) {
1374  case Intrinsic::fabs:
1375  case Intrinsic::minnum:
1376  case Intrinsic::maxnum:
1377  case Intrinsic::minimum:
1378  case Intrinsic::maximum:
1379  case Intrinsic::log:
1380  case Intrinsic::log2:
1381  case Intrinsic::log10:
1382  case Intrinsic::exp:
1383  case Intrinsic::exp2:
1384  case Intrinsic::floor:
1385  case Intrinsic::ceil:
1386  case Intrinsic::sqrt:
1387  case Intrinsic::sin:
1388  case Intrinsic::cos:
1389  case Intrinsic::trunc:
1390  case Intrinsic::rint:
1391  case Intrinsic::nearbyint:
1392  case Intrinsic::pow:
1393  case Intrinsic::powi:
1394  case Intrinsic::bswap:
1395  case Intrinsic::ctpop:
1396  case Intrinsic::ctlz:
1397  case Intrinsic::cttz:
1398  case Intrinsic::fshl:
1399  case Intrinsic::fshr:
1400  case Intrinsic::fma:
1401  case Intrinsic::fmuladd:
1402  case Intrinsic::copysign:
1405  case Intrinsic::round:
1413  case Intrinsic::sadd_sat:
1414  case Intrinsic::uadd_sat:
1415  case Intrinsic::ssub_sat:
1416  case Intrinsic::usub_sat:
1419  case Intrinsic::bitreverse:
1445  return true;
1446  default:
1447  return false;
1448  case Intrinsic::not_intrinsic: break;
1449  }
1450 
1451  if (!F->hasName())
1452  return false;
1453  StringRef Name = F->getName();
1454 
1455  // In these cases, the check of the length is required. We don't want to
1456  // return true for a name like "cos\0blah" which strcmp would return equal to
1457  // "cos", but has length 8.
1458  switch (Name[0]) {
1459  default:
1460  return false;
1461  case 'a':
1462  return Name == "acos" || Name == "asin" || Name == "atan" ||
1463  Name == "atan2" || Name == "acosf" || Name == "asinf" ||
1464  Name == "atanf" || Name == "atan2f";
1465  case 'c':
1466  return Name == "ceil" || Name == "cos" || Name == "cosh" ||
1467  Name == "ceilf" || Name == "cosf" || Name == "coshf";
1468  case 'e':
1469  return Name == "exp" || Name == "exp2" || Name == "expf" || Name == "exp2f";
1470  case 'f':
1471  return Name == "fabs" || Name == "floor" || Name == "fmod" ||
1472  Name == "fabsf" || Name == "floorf" || Name == "fmodf";
1473  case 'l':
1474  return Name == "log" || Name == "log10" || Name == "logf" ||
1475  Name == "log10f";
1476  case 'p':
1477  return Name == "pow" || Name == "powf";
1478  case 'r':
1479  return Name == "round" || Name == "roundf";
1480  case 's':
1481  return Name == "sin" || Name == "sinh" || Name == "sqrt" ||
1482  Name == "sinf" || Name == "sinhf" || Name == "sqrtf";
1483  case 't':
1484  return Name == "tan" || Name == "tanh" || Name == "tanf" || Name == "tanhf";
1485  case '_':
1486 
1487  // Check for various function names that get used for the math functions
1488  // when the header files are preprocessed with the macro
1489  // __FINITE_MATH_ONLY__ enabled.
1490  // The '12' here is the length of the shortest name that can match.
1491  // We need to check the size before looking at Name[1] and Name[2]
1492  // so we may as well check a limit that will eliminate mismatches.
1493  if (Name.size() < 12 || Name[1] != '_')
1494  return false;
1495  switch (Name[2]) {
1496  default:
1497  return false;
1498  case 'a':
1499  return Name == "__acos_finite" || Name == "__acosf_finite" ||
1500  Name == "__asin_finite" || Name == "__asinf_finite" ||
1501  Name == "__atan2_finite" || Name == "__atan2f_finite";
1502  case 'c':
1503  return Name == "__cosh_finite" || Name == "__coshf_finite";
1504  case 'e':
1505  return Name == "__exp_finite" || Name == "__expf_finite" ||
1506  Name == "__exp2_finite" || Name == "__exp2f_finite";
1507  case 'l':
1508  return Name == "__log_finite" || Name == "__logf_finite" ||
1509  Name == "__log10_finite" || Name == "__log10f_finite";
1510  case 'p':
1511  return Name == "__pow_finite" || Name == "__powf_finite";
1512  case 's':
1513  return Name == "__sinh_finite" || Name == "__sinhf_finite";
1514  }
1515  }
1516 }
1517 
1518 namespace {
1519 
1520 Constant *GetConstantFoldFPValue(double V, Type *Ty) {
1521  if (Ty->isHalfTy()) {
1522  APFloat APF(V);
1523  bool unused;
1525  return ConstantFP::get(Ty->getContext(), APF);
1526  }
1527  if (Ty->isFloatTy())
1528  return ConstantFP::get(Ty->getContext(), APFloat((float)V));
1529  if (Ty->isDoubleTy())
1530  return ConstantFP::get(Ty->getContext(), APFloat(V));
1531  llvm_unreachable("Can only constant fold half/float/double");
1532 }
1533 
1534 /// Clear the floating-point exception state.
1535 inline void llvm_fenv_clearexcept() {
1536 #if defined(HAVE_FENV_H) && HAVE_DECL_FE_ALL_EXCEPT
1537  feclearexcept(FE_ALL_EXCEPT);
1538 #endif
1539  errno = 0;
1540 }
1541 
1542 /// Test if a floating-point exception was raised.
1543 inline bool llvm_fenv_testexcept() {
1544  int errno_val = errno;
1545  if (errno_val == ERANGE || errno_val == EDOM)
1546  return true;
1547 #if defined(HAVE_FENV_H) && HAVE_DECL_FE_ALL_EXCEPT && HAVE_DECL_FE_INEXACT
1548  if (fetestexcept(FE_ALL_EXCEPT & ~FE_INEXACT))
1549  return true;
1550 #endif
1551  return false;
1552 }
1553 
1554 Constant *ConstantFoldFP(double (*NativeFP)(double), double V, Type *Ty) {
1555  llvm_fenv_clearexcept();
1556  V = NativeFP(V);
1557  if (llvm_fenv_testexcept()) {
1558  llvm_fenv_clearexcept();
1559  return nullptr;
1560  }
1561 
1562  return GetConstantFoldFPValue(V, Ty);
1563 }
1564 
1565 Constant *ConstantFoldBinaryFP(double (*NativeFP)(double, double), double V,
1566  double W, Type *Ty) {
1567  llvm_fenv_clearexcept();
1568  V = NativeFP(V, W);
1569  if (llvm_fenv_testexcept()) {
1570  llvm_fenv_clearexcept();
1571  return nullptr;
1572  }
1573 
1574  return GetConstantFoldFPValue(V, Ty);
1575 }
1576 
1577 /// Attempt to fold an SSE floating point to integer conversion of a constant
1578 /// floating point. If roundTowardZero is false, the default IEEE rounding is
1579 /// used (toward nearest, ties to even). This matches the behavior of the
1580 /// non-truncating SSE instructions in the default rounding mode. The desired
1581 /// integer type Ty is used to select how many bits are available for the
1582 /// result. Returns null if the conversion cannot be performed, otherwise
1583 /// returns the Constant value resulting from the conversion.
1584 Constant *ConstantFoldSSEConvertToInt(const APFloat &Val, bool roundTowardZero,
1585  Type *Ty, bool IsSigned) {
1586  // All of these conversion intrinsics form an integer of at most 64bits.
1587  unsigned ResultWidth = Ty->getIntegerBitWidth();
1588  assert(ResultWidth <= 64 &&
1589  "Can only constant fold conversions to 64 and 32 bit ints");
1590 
1591  uint64_t UIntVal;
1592  bool isExact = false;
1596  Val.convertToInteger(makeMutableArrayRef(UIntVal), ResultWidth,
1597  IsSigned, mode, &isExact);
1598  if (status != APFloat::opOK &&
1599  (!roundTowardZero || status != APFloat::opInexact))
1600  return nullptr;
1601  return ConstantInt::get(Ty, UIntVal, IsSigned);
1602 }
1603 
1604 double getValueAsDouble(ConstantFP *Op) {
1605  Type *Ty = Op->getType();
1606 
1607  if (Ty->isFloatTy())
1608  return Op->getValueAPF().convertToFloat();
1609 
1610  if (Ty->isDoubleTy())
1611  return Op->getValueAPF().convertToDouble();
1612 
1613  bool unused;
1614  APFloat APF = Op->getValueAPF();
1616  return APF.convertToDouble();
1617 }
1618 
1619 static bool isManifestConstant(const Constant *c) {
1620  if (isa<ConstantData>(c)) {
1621  return true;
1622  } else if (isa<ConstantAggregate>(c) || isa<ConstantExpr>(c)) {
1623  for (const Value *subc : c->operand_values()) {
1624  if (!isManifestConstant(cast<Constant>(subc)))
1625  return false;
1626  }
1627  return true;
1628  }
1629  return false;
1630 }
1631 
1632 static bool getConstIntOrUndef(Value *Op, const APInt *&C) {
1633  if (auto *CI = dyn_cast<ConstantInt>(Op)) {
1634  C = &CI->getValue();
1635  return true;
1636  }
1637  if (isa<UndefValue>(Op)) {
1638  C = nullptr;
1639  return true;
1640  }
1641  return false;
1642 }
1643 
1644 Constant *ConstantFoldScalarCall(StringRef Name, unsigned IntrinsicID, Type *Ty,
1645  ArrayRef<Constant *> Operands,
1646  const TargetLibraryInfo *TLI,
1647  ImmutableCallSite CS) {
1648  if (Operands.size() == 1) {
1649  if (IntrinsicID == Intrinsic::is_constant) {
1650  // We know we have a "Constant" argument. But we want to only
1651  // return true for manifest constants, not those that depend on
1652  // constants with unknowable values, e.g. GlobalValue or BlockAddress.
1653  if (isManifestConstant(Operands[0]))
1654  return ConstantInt::getTrue(Ty->getContext());
1655  return nullptr;
1656  }
1657  if (isa<UndefValue>(Operands[0])) {
1658  // cosine(arg) is between -1 and 1. cosine(invalid arg) is NaN.
1659  // ctpop() is between 0 and bitwidth, pick 0 for undef.
1660  if (IntrinsicID == Intrinsic::cos ||
1661  IntrinsicID == Intrinsic::ctpop)
1662  return Constant::getNullValue(Ty);
1663  if (IntrinsicID == Intrinsic::bswap ||
1664  IntrinsicID == Intrinsic::bitreverse ||
1665  IntrinsicID == Intrinsic::launder_invariant_group ||
1666  IntrinsicID == Intrinsic::strip_invariant_group)
1667  return Operands[0];
1668  }
1669 
1670  if (isa<ConstantPointerNull>(Operands[0])) {
1671  // launder(null) == null == strip(null) iff in addrspace 0
1672  if (IntrinsicID == Intrinsic::launder_invariant_group ||
1673  IntrinsicID == Intrinsic::strip_invariant_group) {
1674  // If instruction is not yet put in a basic block (e.g. when cloning
1675  // a function during inlining), CS caller may not be available.
1676  // So check CS's BB first before querying CS.getCaller.
1677  const Function *Caller = CS.getParent() ? CS.getCaller() : nullptr;
1678  if (Caller &&
1680  Caller, Operands[0]->getType()->getPointerAddressSpace())) {
1681  return Operands[0];
1682  }
1683  return nullptr;
1684  }
1685  }
1686 
1687  if (auto *Op = dyn_cast<ConstantFP>(Operands[0])) {
1688  if (IntrinsicID == Intrinsic::convert_to_fp16) {
1689  APFloat Val(Op->getValueAPF());
1690 
1691  bool lost = false;
1693 
1694  return ConstantInt::get(Ty->getContext(), Val.bitcastToAPInt());
1695  }
1696 
1697  if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
1698  return nullptr;
1699 
1700  if (IntrinsicID == Intrinsic::round) {
1701  APFloat V = Op->getValueAPF();
1703  return ConstantFP::get(Ty->getContext(), V);
1704  }
1705 
1706  if (IntrinsicID == Intrinsic::floor) {
1707  APFloat V = Op->getValueAPF();
1709  return ConstantFP::get(Ty->getContext(), V);
1710  }
1711 
1712  if (IntrinsicID == Intrinsic::ceil) {
1713  APFloat V = Op->getValueAPF();
1715  return ConstantFP::get(Ty->getContext(), V);
1716  }
1717 
1718  if (IntrinsicID == Intrinsic::trunc) {
1719  APFloat V = Op->getValueAPF();
1721  return ConstantFP::get(Ty->getContext(), V);
1722  }
1723 
1724  if (IntrinsicID == Intrinsic::rint) {
1725  APFloat V = Op->getValueAPF();
1727  return ConstantFP::get(Ty->getContext(), V);
1728  }
1729 
1730  if (IntrinsicID == Intrinsic::nearbyint) {
1731  APFloat V = Op->getValueAPF();
1733  return ConstantFP::get(Ty->getContext(), V);
1734  }
1735 
1736  /// We only fold functions with finite arguments. Folding NaN and inf is
1737  /// likely to be aborted with an exception anyway, and some host libms
1738  /// have known errors raising exceptions.
1739  if (Op->getValueAPF().isNaN() || Op->getValueAPF().isInfinity())
1740  return nullptr;
1741 
1742  /// Currently APFloat versions of these functions do not exist, so we use
1743  /// the host native double versions. Float versions are not called
1744  /// directly but for all these it is true (float)(f((double)arg)) ==
1745  /// f(arg). Long double not supported yet.
1746  double V = getValueAsDouble(Op);
1747 
1748  switch (IntrinsicID) {
1749  default: break;
1750  case Intrinsic::fabs:
1751  return ConstantFoldFP(fabs, V, Ty);
1752  case Intrinsic::log2:
1753  return ConstantFoldFP(Log2, V, Ty);
1754  case Intrinsic::log:
1755  return ConstantFoldFP(log, V, Ty);
1756  case Intrinsic::log10:
1757  return ConstantFoldFP(log10, V, Ty);
1758  case Intrinsic::exp:
1759  return ConstantFoldFP(exp, V, Ty);
1760  case Intrinsic::exp2:
1761  return ConstantFoldFP(exp2, V, Ty);
1762  case Intrinsic::sin:
1763  return ConstantFoldFP(sin, V, Ty);
1764  case Intrinsic::cos:
1765  return ConstantFoldFP(cos, V, Ty);
1766  case Intrinsic::sqrt:
1767  return ConstantFoldFP(sqrt, V, Ty);
1768  }
1769 
1770  if (!TLI)
1771  return nullptr;
1772 
1773  char NameKeyChar = Name[0];
1774  if (Name[0] == '_' && Name.size() > 2 && Name[1] == '_')
1775  NameKeyChar = Name[2];
1776 
1777  switch (NameKeyChar) {
1778  case 'a':
1779  if ((Name == "acos" && TLI->has(LibFunc_acos)) ||
1780  (Name == "acosf" && TLI->has(LibFunc_acosf)) ||
1781  (Name == "__acos_finite" && TLI->has(LibFunc_acos_finite)) ||
1782  (Name == "__acosf_finite" && TLI->has(LibFunc_acosf_finite)))
1783  return ConstantFoldFP(acos, V, Ty);
1784  else if ((Name == "asin" && TLI->has(LibFunc_asin)) ||
1785  (Name == "asinf" && TLI->has(LibFunc_asinf)) ||
1786  (Name == "__asin_finite" && TLI->has(LibFunc_asin_finite)) ||
1787  (Name == "__asinf_finite" && TLI->has(LibFunc_asinf_finite)))
1788  return ConstantFoldFP(asin, V, Ty);
1789  else if ((Name == "atan" && TLI->has(LibFunc_atan)) ||
1790  (Name == "atanf" && TLI->has(LibFunc_atanf)))
1791  return ConstantFoldFP(atan, V, Ty);
1792  break;
1793  case 'c':
1794  if ((Name == "ceil" && TLI->has(LibFunc_ceil)) ||
1795  (Name == "ceilf" && TLI->has(LibFunc_ceilf)))
1796  return ConstantFoldFP(ceil, V, Ty);
1797  else if ((Name == "cos" && TLI->has(LibFunc_cos)) ||
1798  (Name == "cosf" && TLI->has(LibFunc_cosf)))
1799  return ConstantFoldFP(cos, V, Ty);
1800  else if ((Name == "cosh" && TLI->has(LibFunc_cosh)) ||
1801  (Name == "coshf" && TLI->has(LibFunc_coshf)) ||
1802  (Name == "__cosh_finite" && TLI->has(LibFunc_cosh_finite)) ||
1803  (Name == "__coshf_finite" && TLI->has(LibFunc_coshf_finite)))
1804  return ConstantFoldFP(cosh, V, Ty);
1805  break;
1806  case 'e':
1807  if ((Name == "exp" && TLI->has(LibFunc_exp)) ||
1808  (Name == "expf" && TLI->has(LibFunc_expf)) ||
1809  (Name == "__exp_finite" && TLI->has(LibFunc_exp_finite)) ||
1810  (Name == "__expf_finite" && TLI->has(LibFunc_expf_finite)))
1811  return ConstantFoldFP(exp, V, Ty);
1812  if ((Name == "exp2" && TLI->has(LibFunc_exp2)) ||
1813  (Name == "exp2f" && TLI->has(LibFunc_exp2f)) ||
1814  (Name == "__exp2_finite" && TLI->has(LibFunc_exp2_finite)) ||
1815  (Name == "__exp2f_finite" && TLI->has(LibFunc_exp2f_finite)))
1816  // Constant fold exp2(x) as pow(2,x) in case the host doesn't have a
1817  // C99 library.
1818  return ConstantFoldBinaryFP(pow, 2.0, V, Ty);
1819  break;
1820  case 'f':
1821  if ((Name == "fabs" && TLI->has(LibFunc_fabs)) ||
1822  (Name == "fabsf" && TLI->has(LibFunc_fabsf)))
1823  return ConstantFoldFP(fabs, V, Ty);
1824  else if ((Name == "floor" && TLI->has(LibFunc_floor)) ||
1825  (Name == "floorf" && TLI->has(LibFunc_floorf)))
1826  return ConstantFoldFP(floor, V, Ty);
1827  break;
1828  case 'l':
1829  if ((Name == "log" && V > 0 && TLI->has(LibFunc_log)) ||
1830  (Name == "logf" && V > 0 && TLI->has(LibFunc_logf)) ||
1831  (Name == "__log_finite" && V > 0 &&
1832  TLI->has(LibFunc_log_finite)) ||
1833  (Name == "__logf_finite" && V > 0 &&
1834  TLI->has(LibFunc_logf_finite)))
1835  return ConstantFoldFP(log, V, Ty);
1836  else if ((Name == "log10" && V > 0 && TLI->has(LibFunc_log10)) ||
1837  (Name == "log10f" && V > 0 && TLI->has(LibFunc_log10f)) ||
1838  (Name == "__log10_finite" && V > 0 &&
1839  TLI->has(LibFunc_log10_finite)) ||
1840  (Name == "__log10f_finite" && V > 0 &&
1841  TLI->has(LibFunc_log10f_finite)))
1842  return ConstantFoldFP(log10, V, Ty);
1843  break;
1844  case 'r':
1845  if ((Name == "round" && TLI->has(LibFunc_round)) ||
1846  (Name == "roundf" && TLI->has(LibFunc_roundf)))
1847  return ConstantFoldFP(round, V, Ty);
1848  break;
1849  case 's':
1850  if ((Name == "sin" && TLI->has(LibFunc_sin)) ||
1851  (Name == "sinf" && TLI->has(LibFunc_sinf)))
1852  return ConstantFoldFP(sin, V, Ty);
1853  else if ((Name == "sinh" && TLI->has(LibFunc_sinh)) ||
1854  (Name == "sinhf" && TLI->has(LibFunc_sinhf)) ||
1855  (Name == "__sinh_finite" && TLI->has(LibFunc_sinh_finite)) ||
1856  (Name == "__sinhf_finite" && TLI->has(LibFunc_sinhf_finite)))
1857  return ConstantFoldFP(sinh, V, Ty);
1858  else if ((Name == "sqrt" && V >= 0 && TLI->has(LibFunc_sqrt)) ||
1859  (Name == "sqrtf" && V >= 0 && TLI->has(LibFunc_sqrtf)))
1860  return ConstantFoldFP(sqrt, V, Ty);
1861  break;
1862  case 't':
1863  if ((Name == "tan" && TLI->has(LibFunc_tan)) ||
1864  (Name == "tanf" && TLI->has(LibFunc_tanf)))
1865  return ConstantFoldFP(tan, V, Ty);
1866  else if ((Name == "tanh" && TLI->has(LibFunc_tanh)) ||
1867  (Name == "tanhf" && TLI->has(LibFunc_tanhf)))
1868  return ConstantFoldFP(tanh, V, Ty);
1869  break;
1870  default:
1871  break;
1872  }
1873  return nullptr;
1874  }
1875 
1876  if (auto *Op = dyn_cast<ConstantInt>(Operands[0])) {
1877  switch (IntrinsicID) {
1878  case Intrinsic::bswap:
1879  return ConstantInt::get(Ty->getContext(), Op->getValue().byteSwap());
1880  case Intrinsic::ctpop:
1881  return ConstantInt::get(Ty, Op->getValue().countPopulation());
1882  case Intrinsic::bitreverse:
1883  return ConstantInt::get(Ty->getContext(), Op->getValue().reverseBits());
1885  APFloat Val(APFloat::IEEEhalf(), Op->getValue());
1886 
1887  bool lost = false;
1890 
1891  // Conversion is always precise.
1892  (void)status;
1893  assert(status == APFloat::opOK && !lost &&
1894  "Precision lost during fp16 constfolding");
1895 
1896  return ConstantFP::get(Ty->getContext(), Val);
1897  }
1898  default:
1899  return nullptr;
1900  }
1901  }
1902 
1903  // Support ConstantVector in case we have an Undef in the top.
1904  if (isa<ConstantVector>(Operands[0]) ||
1905  isa<ConstantDataVector>(Operands[0])) {
1906  auto *Op = cast<Constant>(Operands[0]);
1907  switch (IntrinsicID) {
1908  default: break;
1913  if (ConstantFP *FPOp =
1914  dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
1915  return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
1916  /*roundTowardZero=*/false, Ty,
1917  /*IsSigned*/true);
1918  break;
1923  if (ConstantFP *FPOp =
1924  dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
1925  return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
1926  /*roundTowardZero=*/true, Ty,
1927  /*IsSigned*/true);
1928  break;
1929  }
1930  }
1931 
1932  return nullptr;
1933  }
1934 
1935  if (Operands.size() == 2) {
1936  if (auto *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
1937  if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
1938  return nullptr;
1939  double Op1V = getValueAsDouble(Op1);
1940 
1941  if (auto *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
1942  if (Op2->getType() != Op1->getType())
1943  return nullptr;
1944 
1945  double Op2V = getValueAsDouble(Op2);
1946  if (IntrinsicID == Intrinsic::pow) {
1947  return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
1948  }
1949  if (IntrinsicID == Intrinsic::copysign) {
1950  APFloat V1 = Op1->getValueAPF();
1951  const APFloat &V2 = Op2->getValueAPF();
1952  V1.copySign(V2);
1953  return ConstantFP::get(Ty->getContext(), V1);
1954  }
1955 
1956  if (IntrinsicID == Intrinsic::minnum) {
1957  const APFloat &C1 = Op1->getValueAPF();
1958  const APFloat &C2 = Op2->getValueAPF();
1959  return ConstantFP::get(Ty->getContext(), minnum(C1, C2));
1960  }
1961 
1962  if (IntrinsicID == Intrinsic::maxnum) {
1963  const APFloat &C1 = Op1->getValueAPF();
1964  const APFloat &C2 = Op2->getValueAPF();
1965  return ConstantFP::get(Ty->getContext(), maxnum(C1, C2));
1966  }
1967 
1968  if (IntrinsicID == Intrinsic::minimum) {
1969  const APFloat &C1 = Op1->getValueAPF();
1970  const APFloat &C2 = Op2->getValueAPF();
1971  return ConstantFP::get(Ty->getContext(), minimum(C1, C2));
1972  }
1973 
1974  if (IntrinsicID == Intrinsic::maximum) {
1975  const APFloat &C1 = Op1->getValueAPF();
1976  const APFloat &C2 = Op2->getValueAPF();
1977  return ConstantFP::get(Ty->getContext(), maximum(C1, C2));
1978  }
1979 
1980  if (!TLI)
1981  return nullptr;
1982  if ((Name == "pow" && TLI->has(LibFunc_pow)) ||
1983  (Name == "powf" && TLI->has(LibFunc_powf)) ||
1984  (Name == "__pow_finite" && TLI->has(LibFunc_pow_finite)) ||
1985  (Name == "__powf_finite" && TLI->has(LibFunc_powf_finite)))
1986  return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
1987  if ((Name == "fmod" && TLI->has(LibFunc_fmod)) ||
1988  (Name == "fmodf" && TLI->has(LibFunc_fmodf)))
1989  return ConstantFoldBinaryFP(fmod, Op1V, Op2V, Ty);
1990  if ((Name == "atan2" && TLI->has(LibFunc_atan2)) ||
1991  (Name == "atan2f" && TLI->has(LibFunc_atan2f)) ||
1992  (Name == "__atan2_finite" && TLI->has(LibFunc_atan2_finite)) ||
1993  (Name == "__atan2f_finite" && TLI->has(LibFunc_atan2f_finite)))
1994  return ConstantFoldBinaryFP(atan2, Op1V, Op2V, Ty);
1995  } else if (auto *Op2C = dyn_cast<ConstantInt>(Operands[1])) {
1996  if (IntrinsicID == Intrinsic::powi && Ty->isHalfTy())
1997  return ConstantFP::get(Ty->getContext(),
1998  APFloat((float)std::pow((float)Op1V,
1999  (int)Op2C->getZExtValue())));
2000  if (IntrinsicID == Intrinsic::powi && Ty->isFloatTy())
2001  return ConstantFP::get(Ty->getContext(),
2002  APFloat((float)std::pow((float)Op1V,
2003  (int)Op2C->getZExtValue())));
2004  if (IntrinsicID == Intrinsic::powi && Ty->isDoubleTy())
2005  return ConstantFP::get(Ty->getContext(),
2006  APFloat((double)std::pow((double)Op1V,
2007  (int)Op2C->getZExtValue())));
2008  }
2009  return nullptr;
2010  }
2011 
2012  if (Operands[0]->getType()->isIntegerTy() &&
2013  Operands[1]->getType()->isIntegerTy()) {
2014  const APInt *C0, *C1;
2015  if (!getConstIntOrUndef(Operands[0], C0) ||
2016  !getConstIntOrUndef(Operands[1], C1))
2017  return nullptr;
2018 
2019  switch (IntrinsicID) {
2020  default: break;
2023  // Even if both operands are undef, we cannot fold muls to undef
2024  // in the general case. For example, on i2 there are no inputs
2025  // that would produce { i2 -1, i1 true } as the result.
2026  if (!C0 || !C1)
2027  return Constant::getNullValue(Ty);
2033  if (!C0 || !C1)
2034  return UndefValue::get(Ty);
2035 
2036  APInt Res;
2037  bool Overflow;
2038  switch (IntrinsicID) {
2039  default: llvm_unreachable("Invalid case");
2041  Res = C0->sadd_ov(*C1, Overflow);
2042  break;
2044  Res = C0->uadd_ov(*C1, Overflow);
2045  break;
2047  Res = C0->ssub_ov(*C1, Overflow);
2048  break;
2050  Res = C0->usub_ov(*C1, Overflow);
2051  break;
2053  Res = C0->smul_ov(*C1, Overflow);
2054  break;
2056  Res = C0->umul_ov(*C1, Overflow);
2057  break;
2058  }
2059  Constant *Ops[] = {
2060  ConstantInt::get(Ty->getContext(), Res),
2061  ConstantInt::get(Type::getInt1Ty(Ty->getContext()), Overflow)
2062  };
2063  return ConstantStruct::get(cast<StructType>(Ty), Ops);
2064  }
2065  case Intrinsic::uadd_sat:
2066  case Intrinsic::sadd_sat:
2067  if (!C0 && !C1)
2068  return UndefValue::get(Ty);
2069  if (!C0 || !C1)
2070  return Constant::getAllOnesValue(Ty);
2071  if (IntrinsicID == Intrinsic::uadd_sat)
2072  return ConstantInt::get(Ty, C0->uadd_sat(*C1));
2073  else
2074  return ConstantInt::get(Ty, C0->sadd_sat(*C1));
2075  case Intrinsic::usub_sat:
2076  case Intrinsic::ssub_sat:
2077  if (!C0 && !C1)
2078  return UndefValue::get(Ty);
2079  if (!C0 || !C1)
2080  return Constant::getNullValue(Ty);
2081  if (IntrinsicID == Intrinsic::usub_sat)
2082  return ConstantInt::get(Ty, C0->usub_sat(*C1));
2083  else
2084  return ConstantInt::get(Ty, C0->ssub_sat(*C1));
2085  case Intrinsic::cttz:
2086  case Intrinsic::ctlz:
2087  assert(C1 && "Must be constant int");
2088 
2089  // cttz(0, 1) and ctlz(0, 1) are undef.
2090  if (C1->isOneValue() && (!C0 || C0->isNullValue()))
2091  return UndefValue::get(Ty);
2092  if (!C0)
2093  return Constant::getNullValue(Ty);
2094  if (IntrinsicID == Intrinsic::cttz)
2095  return ConstantInt::get(Ty, C0->countTrailingZeros());
2096  else
2097  return ConstantInt::get(Ty, C0->countLeadingZeros());
2098  }
2099 
2100  return nullptr;
2101  }
2102 
2103  // Support ConstantVector in case we have an Undef in the top.
2104  if ((isa<ConstantVector>(Operands[0]) ||
2105  isa<ConstantDataVector>(Operands[0])) &&
2106  // Check for default rounding mode.
2107  // FIXME: Support other rounding modes?
2108  isa<ConstantInt>(Operands[1]) &&
2109  cast<ConstantInt>(Operands[1])->getValue() == 4) {
2110  auto *Op = cast<Constant>(Operands[0]);
2111  switch (IntrinsicID) {
2112  default: break;
2117  if (ConstantFP *FPOp =
2118  dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
2119  return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
2120  /*roundTowardZero=*/false, Ty,
2121  /*IsSigned*/true);
2122  break;
2127  if (ConstantFP *FPOp =
2128  dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
2129  return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
2130  /*roundTowardZero=*/false, Ty,
2131  /*IsSigned*/false);
2132  break;
2137  if (ConstantFP *FPOp =
2138  dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
2139  return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
2140  /*roundTowardZero=*/true, Ty,
2141  /*IsSigned*/true);
2142  break;
2147  if (ConstantFP *FPOp =
2148  dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
2149  return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
2150  /*roundTowardZero=*/true, Ty,
2151  /*IsSigned*/false);
2152  break;
2153  }
2154  }
2155  return nullptr;
2156  }
2157 
2158  if (Operands.size() != 3)
2159  return nullptr;
2160 
2161  if (const auto *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
2162  if (const auto *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
2163  if (const auto *Op3 = dyn_cast<ConstantFP>(Operands[2])) {
2164  switch (IntrinsicID) {
2165  default: break;
2166  case Intrinsic::fma:
2167  case Intrinsic::fmuladd: {
2168  APFloat V = Op1->getValueAPF();
2169  APFloat::opStatus s = V.fusedMultiplyAdd(Op2->getValueAPF(),
2170  Op3->getValueAPF(),
2172  if (s != APFloat::opInvalidOp)
2173  return ConstantFP::get(Ty->getContext(), V);
2174 
2175  return nullptr;
2176  }
2177  }
2178  }
2179  }
2180  }
2181 
2182  if (IntrinsicID == Intrinsic::fshl || IntrinsicID == Intrinsic::fshr) {
2183  const APInt *C0, *C1, *C2;
2184  if (!getConstIntOrUndef(Operands[0], C0) ||
2185  !getConstIntOrUndef(Operands[1], C1) ||
2186  !getConstIntOrUndef(Operands[2], C2))
2187  return nullptr;
2188 
2189  bool IsRight = IntrinsicID == Intrinsic::fshr;
2190  if (!C2)
2191  return Operands[IsRight ? 1 : 0];
2192  if (!C0 && !C1)
2193  return UndefValue::get(Ty);
2194 
2195  // The shift amount is interpreted as modulo the bitwidth. If the shift
2196  // amount is effectively 0, avoid UB due to oversized inverse shift below.
2197  unsigned BitWidth = C2->getBitWidth();
2198  unsigned ShAmt = C2->urem(BitWidth);
2199  if (!ShAmt)
2200  return Operands[IsRight ? 1 : 0];
2201 
2202  // (C0 << ShlAmt) | (C1 >> LshrAmt)
2203  unsigned LshrAmt = IsRight ? ShAmt : BitWidth - ShAmt;
2204  unsigned ShlAmt = !IsRight ? ShAmt : BitWidth - ShAmt;
2205  if (!C0)
2206  return ConstantInt::get(Ty, C1->lshr(LshrAmt));
2207  if (!C1)
2208  return ConstantInt::get(Ty, C0->shl(ShlAmt));
2209  return ConstantInt::get(Ty, C0->shl(ShlAmt) | C1->lshr(LshrAmt));
2210  }
2211 
2212  return nullptr;
2213 }
2214 
2215 Constant *ConstantFoldVectorCall(StringRef Name, unsigned IntrinsicID,
2216  VectorType *VTy, ArrayRef<Constant *> Operands,
2217  const DataLayout &DL,
2218  const TargetLibraryInfo *TLI,
2219  ImmutableCallSite CS) {
2221  SmallVector<Constant *, 4> Lane(Operands.size());
2222  Type *Ty = VTy->getElementType();
2223 
2224  if (IntrinsicID == Intrinsic::masked_load) {
2225  auto *SrcPtr = Operands[0];
2226  auto *Mask = Operands[2];
2227  auto *Passthru = Operands[3];
2228 
2229  Constant *VecData = ConstantFoldLoadFromConstPtr(SrcPtr, VTy, DL);
2230 
2231  SmallVector<Constant *, 32> NewElements;
2232  for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
2233  auto *MaskElt = Mask->getAggregateElement(I);
2234  if (!MaskElt)
2235  break;
2236  auto *PassthruElt = Passthru->getAggregateElement(I);
2237  auto *VecElt = VecData ? VecData->getAggregateElement(I) : nullptr;
2238  if (isa<UndefValue>(MaskElt)) {
2239  if (PassthruElt)
2240  NewElements.push_back(PassthruElt);
2241  else if (VecElt)
2242  NewElements.push_back(VecElt);
2243  else
2244  return nullptr;
2245  }
2246  if (MaskElt->isNullValue()) {
2247  if (!PassthruElt)
2248  return nullptr;
2249  NewElements.push_back(PassthruElt);
2250  } else if (MaskElt->isOneValue()) {
2251  if (!VecElt)
2252  return nullptr;
2253  NewElements.push_back(VecElt);
2254  } else {
2255  return nullptr;
2256  }
2257  }
2258  if (NewElements.size() != VTy->getNumElements())
2259  return nullptr;
2260  return ConstantVector::get(NewElements);
2261  }
2262 
2263  for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
2264  // Gather a column of constants.
2265  for (unsigned J = 0, JE = Operands.size(); J != JE; ++J) {
2266  // These intrinsics use a scalar type for their second argument.
2267  if (J == 1 &&
2268  (IntrinsicID == Intrinsic::cttz || IntrinsicID == Intrinsic::ctlz ||
2269  IntrinsicID == Intrinsic::powi)) {
2270  Lane[J] = Operands[J];
2271  continue;
2272  }
2273 
2274  Constant *Agg = Operands[J]->getAggregateElement(I);
2275  if (!Agg)
2276  return nullptr;
2277 
2278  Lane[J] = Agg;
2279  }
2280 
2281  // Use the regular scalar folding to simplify this column.
2282  Constant *Folded = ConstantFoldScalarCall(Name, IntrinsicID, Ty, Lane, TLI, CS);
2283  if (!Folded)
2284  return nullptr;
2285  Result[I] = Folded;
2286  }
2287 
2288  return ConstantVector::get(Result);
2289 }
2290 
2291 } // end anonymous namespace
2292 
2293 Constant *
2295  ArrayRef<Constant *> Operands,
2296  const TargetLibraryInfo *TLI) {
2297  if (CS.isNoBuiltin() || CS.isStrictFP())
2298  return nullptr;
2299  if (!F->hasName())
2300  return nullptr;
2301  StringRef Name = F->getName();
2302 
2303  Type *Ty = F->getReturnType();
2304 
2305  if (auto *VTy = dyn_cast<VectorType>(Ty))
2306  return ConstantFoldVectorCall(Name, F->getIntrinsicID(), VTy, Operands,
2307  F->getParent()->getDataLayout(), TLI, CS);
2308 
2309  return ConstantFoldScalarCall(Name, F->getIntrinsicID(), Ty, Operands, TLI, CS);
2310 }
2311 
2313  // FIXME: Refactor this code; this duplicates logic in LibCallsShrinkWrap
2314  // (and to some extent ConstantFoldScalarCall).
2315  if (CS.isNoBuiltin() || CS.isStrictFP())
2316  return false;
2317  Function *F = CS.getCalledFunction();
2318  if (!F)
2319  return false;
2320 
2321  LibFunc Func;
2322  if (!TLI || !TLI->getLibFunc(*F, Func))
2323  return false;
2324 
2325  if (CS.getNumArgOperands() == 1) {
2326  if (ConstantFP *OpC = dyn_cast<ConstantFP>(CS.getArgOperand(0))) {
2327  const APFloat &Op = OpC->getValueAPF();
2328  switch (Func) {
2329  case LibFunc_logl:
2330  case LibFunc_log:
2331  case LibFunc_logf:
2332  case LibFunc_log2l:
2333  case LibFunc_log2:
2334  case LibFunc_log2f:
2335  case LibFunc_log10l:
2336  case LibFunc_log10:
2337  case LibFunc_log10f:
2338  return Op.isNaN() || (!Op.isZero() && !Op.isNegative());
2339 
2340  case LibFunc_expl:
2341  case LibFunc_exp:
2342  case LibFunc_expf:
2343  // FIXME: These boundaries are slightly conservative.
2344  if (OpC->getType()->isDoubleTy())
2345  return Op.compare(APFloat(-745.0)) != APFloat::cmpLessThan &&
2346  Op.compare(APFloat(709.0)) != APFloat::cmpGreaterThan;
2347  if (OpC->getType()->isFloatTy())
2348  return Op.compare(APFloat(-103.0f)) != APFloat::cmpLessThan &&
2349  Op.compare(APFloat(88.0f)) != APFloat::cmpGreaterThan;
2350  break;
2351 
2352  case LibFunc_exp2l:
2353  case LibFunc_exp2:
2354  case LibFunc_exp2f:
2355  // FIXME: These boundaries are slightly conservative.
2356  if (OpC->getType()->isDoubleTy())
2357  return Op.compare(APFloat(-1074.0)) != APFloat::cmpLessThan &&
2358  Op.compare(APFloat(1023.0)) != APFloat::cmpGreaterThan;
2359  if (OpC->getType()->isFloatTy())
2360  return Op.compare(APFloat(-149.0f)) != APFloat::cmpLessThan &&
2361  Op.compare(APFloat(127.0f)) != APFloat::cmpGreaterThan;
2362  break;
2363 
2364  case LibFunc_sinl:
2365  case LibFunc_sin:
2366  case LibFunc_sinf:
2367  case LibFunc_cosl:
2368  case LibFunc_cos:
2369  case LibFunc_cosf:
2370  return !Op.isInfinity();
2371 
2372  case LibFunc_tanl:
2373  case LibFunc_tan:
2374  case LibFunc_tanf: {
2375  // FIXME: Stop using the host math library.
2376  // FIXME: The computation isn't done in the right precision.
2377  Type *Ty = OpC->getType();
2378  if (Ty->isDoubleTy() || Ty->isFloatTy() || Ty->isHalfTy()) {
2379  double OpV = getValueAsDouble(OpC);
2380  return ConstantFoldFP(tan, OpV, Ty) != nullptr;
2381  }
2382  break;
2383  }
2384 
2385  case LibFunc_asinl:
2386  case LibFunc_asin:
2387  case LibFunc_asinf:
2388  case LibFunc_acosl:
2389  case LibFunc_acos:
2390  case LibFunc_acosf:
2391  return Op.compare(APFloat(Op.getSemantics(), "-1")) !=
2393  Op.compare(APFloat(Op.getSemantics(), "1")) !=
2395 
2396  case LibFunc_sinh:
2397  case LibFunc_cosh:
2398  case LibFunc_sinhf:
2399  case LibFunc_coshf:
2400  case LibFunc_sinhl:
2401  case LibFunc_coshl:
2402  // FIXME: These boundaries are slightly conservative.
2403  if (OpC->getType()->isDoubleTy())
2404  return Op.compare(APFloat(-710.0)) != APFloat::cmpLessThan &&
2405  Op.compare(APFloat(710.0)) != APFloat::cmpGreaterThan;
2406  if (OpC->getType()->isFloatTy())
2407  return Op.compare(APFloat(-89.0f)) != APFloat::cmpLessThan &&
2408  Op.compare(APFloat(89.0f)) != APFloat::cmpGreaterThan;
2409  break;
2410 
2411  case LibFunc_sqrtl:
2412  case LibFunc_sqrt:
2413  case LibFunc_sqrtf:
2414  return Op.isNaN() || Op.isZero() || !Op.isNegative();
2415 
2416  // FIXME: Add more functions: sqrt_finite, atanh, expm1, log1p,
2417  // maybe others?
2418  default:
2419  break;
2420  }
2421  }
2422  }
2423 
2424  if (CS.getNumArgOperands() == 2) {
2425  ConstantFP *Op0C = dyn_cast<ConstantFP>(CS.getArgOperand(0));
2426  ConstantFP *Op1C = dyn_cast<ConstantFP>(CS.getArgOperand(1));
2427  if (Op0C && Op1C) {
2428  const APFloat &Op0 = Op0C->getValueAPF();
2429  const APFloat &Op1 = Op1C->getValueAPF();
2430 
2431  switch (Func) {
2432  case LibFunc_powl:
2433  case LibFunc_pow:
2434  case LibFunc_powf: {
2435  // FIXME: Stop using the host math library.
2436  // FIXME: The computation isn't done in the right precision.
2437  Type *Ty = Op0C->getType();
2438  if (Ty->isDoubleTy() || Ty->isFloatTy() || Ty->isHalfTy()) {
2439  if (Ty == Op1C->getType()) {
2440  double Op0V = getValueAsDouble(Op0C);
2441  double Op1V = getValueAsDouble(Op1C);
2442  return ConstantFoldBinaryFP(pow, Op0V, Op1V, Ty) != nullptr;
2443  }
2444  }
2445  break;
2446  }
2447 
2448  case LibFunc_fmodl:
2449  case LibFunc_fmod:
2450  case LibFunc_fmodf:
2451  return Op0.isNaN() || Op1.isNaN() ||
2452  (!Op0.isInfinity() && !Op1.isZero());
2453 
2454  default:
2455  break;
2456  }
2457  }
2458  }
2459 
2460  return false;
2461 }
Constant * ConstantFoldCastOperand(unsigned Opcode, Constant *C, Type *DestTy, const DataLayout &DL)
Attempt to constant fold a cast with the specified operand.
opStatus roundToIntegral(roundingMode RM)
Definition: APFloat.h:1008
Type * getVectorElementType() const
Definition: Type.h:371
uint64_t CallInst * C
static Constant * FoldBitCast(Constant *V, Type *DestTy)
void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, OptimizationRemarkEmitter *ORE=nullptr, bool UseInstrInfo=true)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:111
Definition: Any.h:27
bool isZero() const
Definition: APFloat.h:1143
bool isAllOnesValue() const
Return true if this is the value that would be returned by getAllOnesValue.
Definition: Constants.cpp:100
static IntegerType * getInt1Ty(LLVMContext &C)
Definition: Type.cpp:173
uint64_t getZExtValue() const
Get zero extended value.
Definition: APInt.h:1563
const T & back() const
back - Get the last element.
Definition: ArrayRef.h:158
MutableArrayRef< T > makeMutableArrayRef(T &OneElt)
Construct a MutableArrayRef from a single element.
Definition: ArrayRef.h:503
This class represents lattice values for constants.
Definition: AllocatorList.h:24
Constant * ConstantFoldLoadThroughGEPConstantExpr(Constant *C, ConstantExpr *CE)
ConstantFoldLoadThroughGEPConstantExpr - Given a constant and a getelementptr constantexpr, return the constant value being addressed by the constant expression, or null if something is funny and we can&#39;t decide.
static Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant *> IdxList, bool InBounds=false, Optional< unsigned > InRangeIndex=None, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
Definition: Constants.h:1154
bool isSized(SmallPtrSetImpl< Type *> *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition: Type.h:265
#define LLVM_FALLTHROUGH
Definition: Compiler.h:86
const StructLayout * getStructLayout(StructType *Ty) const
Returns a StructLayout object, indicating the alignment of the struct, its size, and the offsets of i...
Definition: DataLayout.cpp:588
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE size_t size() const
size - Get the string size.
Definition: StringRef.h:138
APInt uadd_sat(const APInt &RHS) const
Definition: APInt.cpp:1960
Optional< unsigned > getInRangeIndex() const
Returns the offset of the index with an inrange attachment, or None if none.
Definition: Operator.h:457
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Get a value with low bits set.
Definition: APInt.h:648
static uint64_t round(uint64_t Acc, uint64_t Input)
Definition: xxhash.cpp:57
static Constant * getIntToPtr(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:1760
float convertToFloat() const
Definition: APFloat.h:1098
static Constant * getExtractElement(Constant *Vec, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
Definition: Constants.cpp:2103
bool IsConstantOffsetFromGlobal(Constant *C, GlobalValue *&GV, APInt &Offset, const DataLayout &DL)
If this constant is a constant offset from a global, return the global and the constant.
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:705
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:1186
F(f)
const fltSemantics & getSemantics() const
Definition: APFloat.h:1155
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
Definition: DerivedTypes.h:503
An instruction for reading from memory.
Definition: Instructions.h:168
static IntegerType * getInt64Ty(LLVMContext &C)
Definition: Type.cpp:177
APInt zextOrTrunc(unsigned width) const
Zero extend or truncate to width.
Definition: APInt.cpp:876
static Constant * getCompare(unsigned short pred, Constant *C1, Constant *C2, bool OnlyIfReduced=false)
Return an ICmp or FCmp comparison operator constant expression.
Definition: Constants.cpp:1956
Hexagon Common GEP
static Constant * getSub(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
Definition: Constants.cpp:2249
bool isVectorTy() const
True if this is an instance of VectorType.
Definition: Type.h:230
LLVM_READONLY APFloat maximum(const APFloat &A, const APFloat &B)
Implements IEEE 754-2018 maximum semantics.
Definition: APFloat.h:1262
static IntegerType * getInt16Ty(LLVMContext &C)
Definition: Type.cpp:175
op_iterator op_begin()
Definition: User.h:230
unsigned getElementContainingOffset(uint64_t Offset) const
Given a valid byte offset into the structure, returns the structure index that contains it...
Definition: DataLayout.cpp:84
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition: APInt.h:1509
static Constant * getInsertElement(Constant *Vec, Constant *Elt, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
Definition: Constants.cpp:2125
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition: Type.h:130
static Constant * getNullValue(Type *Ty)
Constructor to create a &#39;0&#39; constant of arbitrary type.
Definition: Constants.cpp:265
amode Optimize addressing mode
opStatus convertToInteger(MutableArrayRef< integerPart > Input, unsigned int Width, bool IsSigned, roundingMode RM, bool *IsExact) const
Definition: APFloat.h:1069
unsigned countTrailingZeros() const
Count the number of trailing zero bits.
Definition: APInt.h:1632
Used to lazily calculate structure layout information for a target machine, based on the DataLayout s...
Definition: DataLayout.h:529
bool isVolatile() const
Return true if this is a load from a volatile memory location.
Definition: Instructions.h:232
static Constant * getIntegerCast(Constant *C, Type *Ty, bool isSigned)
Create a ZExt, Bitcast or Trunc for integer -> integer casts.
Definition: Constants.cpp:1613
static bool castIsValid(Instruction::CastOps op, Value *S, Type *DstTy)
This method can be used to determine if a cast from S to DstTy using Opcode op is valid or not...
amdgpu Simplify well known AMD library false Value Value const Twine & Name
Type * getPointerElementType() const
Definition: Type.h:376
const DataLayout & getDataLayout() const
Get the data layout for the module&#39;s target platform.
Definition: Module.cpp:371
unsigned getPointerTypeSizeInBits(Type *) const
Layout pointer size, in bits, based on the type.
Definition: DataLayout.cpp:646
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
Definition: ArrayRef.h:451
bool isFloatingPointTy() const
Return true if this is one of the six floating-point types.
Definition: Type.h:162
APInt shl(unsigned shiftAmt) const
Left-shift function.
Definition: APInt.h:993
roundingMode
IEEE-754R 4.3: Rounding-direction attributes.
Definition: APFloat.h:174
APInt zextOrSelf(unsigned width) const
Zero extend or truncate to width.
Definition: APInt.cpp:892
A Use represents the edge between a Value definition and its users.
Definition: Use.h:56
static Constant * getLShr(Constant *C1, Constant *C2, bool isExact=false)
Definition: Constants.cpp:2316
PointerType * getPointerTo(unsigned AddrSpace=0) const
Return a pointer to the current type.
Definition: Type.cpp:652
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition: Type.h:197
LLVM_READONLY APFloat minimum(const APFloat &A, const APFloat &B)
Implements IEEE 754-2018 minimum semantics.
Definition: APFloat.h:1249
Windows NT (Windows on ARM)
iterator_range< const unsigned char * > bytes() const
Definition: StringRef.h:116
uint64_t getNumElements() const
Definition: DerivedTypes.h:359
This file implements a class to represent arbitrary precision integral constant values and operations...
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
Definition: STLExtras.h:267
Constant * ConstantFoldConstant(const Constant *C, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldConstant - Attempt to fold the constant using the specified DataLayout.
static Constant * getZExt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:1665
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition: Constants.cpp:85
A constant value that is initialized with an expression using other constant values.
Definition: Constants.h:889
int64_t getSExtValue() const
Get sign extended value.
Definition: APInt.h:1575
bool isInfinity() const
Definition: APFloat.h:1144
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:245
opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
Definition: APFloat.cpp:4444
ValTy * getArgOperand(unsigned i) const
Definition: CallSite.h:297
bool isNoBuiltin() const
Return true if the call should not be treated as a call to a builtin.
Definition: CallSite.h:428
bool isInBounds() const
Test whether this is an inbounds GEP, as defined by LangRef.html.
Definition: Operator.h:451
bool has(LibFunc F) const
Tests whether a library function is available.
static Constant * getSelect(Constant *C, Constant *V1, Constant *V2, Type *OnlyIfReducedTy=nullptr)
Select constant expr.
Definition: Constants.cpp:1978
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:133
bool isMathLibCallNoop(CallSite CS, const TargetLibraryInfo *TLI)
Check whether the given call has no side-effects.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:33
bool isLittleEndian() const
Layout endianness...
Definition: DataLayout.h:221
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
Definition: Instruction.h:126
static const fltSemantics & IEEEdouble() LLVM_READNONE
Definition: APFloat.cpp:123
Value * getOperand(unsigned i) const
Definition: User.h:170
Class to represent pointers.
Definition: DerivedTypes.h:467
Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
Definition: Constants.cpp:335
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return &#39;this&#39;.
Definition: Type.h:304
static Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:1773
bool isFloatTy() const
Return true if this is &#39;float&#39;, a 32-bit IEEE fp type.
Definition: Type.h:147
IntegerType * getIntPtrType(LLVMContext &C, unsigned AddressSpace=0) const
Returns an integer type with size at least as big as that of a pointer in the given address space...
Definition: DataLayout.cpp:750
static Constant * getInsertValue(Constant *Agg, Constant *Val, ArrayRef< unsigned > Idxs, Type *OnlyIfReducedTy=nullptr)
Definition: Constants.cpp:2171
bool isNegative() const
Determine sign of this APInt.
Definition: APInt.h:364
bool isStrictFP() const
Return true if the call requires strict floating point semantics.
Definition: CallSite.h:433
Type * getReturnType() const
Returns the type of the ret val.
Definition: Function.h:169
bool isNegative() const
Definition: APFloat.h:1147
APInt urem(const APInt &RHS) const
Unsigned remainder operation.
Definition: APInt.cpp:1613
bool hasName() const
Definition: Value.h:251
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:46
std::error_code status(const Twine &path, file_status &result, bool follow=true)
Get file status as if by POSIX stat().
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:149
bool isNaN() const
Definition: APFloat.h:1145
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
Definition: Constant.h:42
const APInt & getConstant() const
Returns the value when all bits have a known value.
Definition: KnownBits.h:57
This file contains the declarations for the subclasses of Constant, which represent the different fla...
bool isPointerTy() const
True if this is an instance of PointerType.
Definition: Type.h:224
static Constant * getAnd(Constant *C1, Constant *C2)
Definition: Constants.cpp:2297
ConstantFP - Floating Point Values [float, double].
Definition: Constants.h:264
bool isOneValue() const
Determine if this is a value of 1.
Definition: APInt.h:411
APInt ssub_ov(const APInt &RHS, bool &Overflow) const
Definition: APInt.cpp:1888
Constant * ConstantFoldInstruction(Instruction *I, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldInstruction - Try to constant fold the specified instruction.
double convertToDouble() const
Definition: APFloat.h:1097
static Constant * getShuffleVector(Constant *V1, Constant *V2, Constant *Mask, Type *OnlyIfReducedTy=nullptr)
Definition: Constants.cpp:2148
op_iterator op_end()
Definition: User.h:232
This file declares a class to represent arbitrary precision floating point values and provide a varie...
bool isHalfTy() const
Return true if this is &#39;half&#39;, a 16-bit IEEE fp type.
Definition: Type.h:144
bool isConstant() const
Returns true if we know the value of all bits.
Definition: KnownBits.h:50
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition: InstrTypes.h:646
bool isBinaryOp() const
Definition: Instruction.h:131
static Constant * get(StructType *T, ArrayRef< Constant *> V)
Definition: Constants.cpp:1044
op_range operands()
Definition: User.h:238
bool isX86_MMXTy() const
Return true if this is X86 MMX.
Definition: Type.h:182
Class to represent integer types.
Definition: DerivedTypes.h:40
unsigned getIndexTypeSizeInBits(Type *Ty) const
Layout size of the index used in GEP calculation.
Definition: DataLayout.cpp:662
Constant * ConstantFoldLoadFromConstPtr(Constant *C, Type *Ty, const DataLayout &DL)
ConstantFoldLoadFromConstPtr - Return the value that a load from C would produce if it is constant an...
static Constant * getAllOnesValue(Type *Ty)
Definition: Constants.cpp:319
static UndefValue * get(Type *T)
Static factory methods - Return an &#39;undef&#39; object of the specified type.
Definition: Constants.cpp:1415
const Constant * stripPointerCasts() const
Definition: Constant.h:174
unsigned getNumArgOperands() const
Definition: CallSite.h:293
bool isCast() const
Definition: Instruction.h:134
size_t size() const
Definition: SmallVector.h:53
Constant * ConstantFoldLoadThroughGEPIndices(Constant *C, ArrayRef< Constant *> Indices)
ConstantFoldLoadThroughGEPIndices - Given a constant and getelementptr indices (with an implied zero ...
static wasm::ValType getType(const TargetRegisterClass *RC)
APInt uadd_ov(const APInt &RHS, bool &Overflow) const
Definition: APInt.cpp:1882
Constant * ConstantFoldCompareInstOperands(unsigned Predicate, Constant *LHS, Constant *RHS, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldCompareInstOperands - Attempt to constant fold a compare instruction (icmp/fcmp) with the...
Value * GetUnderlyingObject(Value *V, const DataLayout &DL, unsigned MaxLookup=6)
This method strips off any GEP address adjustments and pointer casts from the specified value...
APInt ssub_sat(const APInt &RHS) const
Definition: APInt.cpp:1969
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
void copySign(const APFloat &RHS)
Definition: APFloat.h:1055
LLVM_READONLY APFloat maxnum(const APFloat &A, const APFloat &B)
Implements IEEE maxNum semantics.
Definition: APFloat.h:1238
const T * data() const
Definition: ArrayRef.h:146
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition: APInt.h:971
const APFloat & getValueAPF() const
Definition: Constants.h:303
static Constant * getPointerCast(Constant *C, Type *Ty)
Create a BitCast, AddrSpaceCast, or a PtrToInt cast constant expression.
Definition: Constants.cpp:1587
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
Definition: Type.h:227
static IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition: Type.cpp:240
Type * getSequentialElementType() const
Definition: Type.h:358
unsigned getNumOperands() const
Definition: User.h:192
This is the shared class of boolean and integer constants.
Definition: Constants.h:84
static const fltSemantics & IEEEhalf() LLVM_READNONE
Definition: APFloat.cpp:117
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type...
Definition: Type.cpp:130
double Log2(double Value)
Return the log base 2 of the specified value.
Definition: MathExtras.h:528
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:847
Provides information about what library functions are available for the current target.
bool isAggregateType() const
Return true if the type is an aggregate type.
Definition: Type.h:258
static IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition: Type.cpp:180
static Constant * getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:1637
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
Definition: Constants.cpp:622
static Constant * get(Type *Ty, double V)
This returns a ConstantFP, or a vector containing a splat of a ConstantFP, for the specified value in...
Definition: Constants.cpp:685
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition: APInt.h:1293
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:1437
static ConstantInt * getTrue(LLVMContext &Context)
Definition: Constants.cpp:578
BBTy * getParent() const
Get the basic block containing the call site.
Definition: CallSite.h:97
Intrinsic::ID getIntrinsicID() const LLVM_READONLY
getIntrinsicID - This method returns the ID number of the specified function, or Intrinsic::not_intri...
Definition: Function.h:194
unsigned getVectorNumElements() const
Definition: DerivedTypes.h:462
Class to represent vector types.
Definition: DerivedTypes.h:393
Class for arbitrary precision integers.
Definition: APInt.h:70
static Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
Definition: Constants.cpp:1530
Type * getResultElementType() const
Definition: Operator.cpp:29
bool getLibFunc(StringRef funcName, LibFunc &F) const
Searches for a particular function name.
ArrayRef< T > slice(size_t N, size_t M) const
slice(n, m) - Chop off the first N elements of the array, and keep M elements in the array...
Definition: ArrayRef.h:179
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
Definition: SmallVector.h:394
bool isNonIntegralPointerType(PointerType *PT) const
Definition: DataLayout.h:349
uint64_t getTypeSizeInBits(Type *Ty) const
Size examples:
Definition: DataLayout.h:568
uint64_t getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
Definition: DataLayout.h:436
opStatus
IEEE-754R 7: Default exception handling.
Definition: APFloat.h:185
FunTy * getCaller() const
Return the caller function for this call site.
Definition: CallSite.h:267
uint64_t getElementOffset(unsigned Idx) const
Definition: DataLayout.h:551
static Type * getIndexedType(Type *Ty, ArrayRef< Value *> IdxList)
Returns the type of the element that would be loaded with a load instruction with the specified param...
static IntegerType * getInt32Ty(LLVMContext &C)
Definition: Type.cpp:176
unsigned getIntegerBitWidth() const
Definition: DerivedTypes.h:97
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:56
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:214
Establish a view to a call site for examination.
Definition: CallSite.h:711
APInt smul_ov(const APInt &RHS, bool &Overflow) const
Definition: APInt.cpp:1907
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.
static Constant * getPtrToInt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:1747
#define I(x, y, z)
Definition: MD5.cpp:58
static Constant * getOr(Constant *C1, Constant *C2)
Definition: Constants.cpp:2301
iterator_range< value_op_iterator > operand_values()
Definition: User.h:262
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:323
Constant * ConstantFoldInstOperands(Instruction *I, ArrayRef< Constant *> Ops, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldInstOperands - Attempt to constant fold an instruction with the specified operands...
static Constant * getShl(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
Definition: Constants.cpp:2309
APInt umul_ov(const APInt &RHS, bool &Overflow) const
Definition: APInt.cpp:1917
bool getConstantStringInfo(const Value *V, StringRef &Str, uint64_t Offset=0, bool TrimAtNul=true)
This function computes the length of a null-terminated C string pointed to by V.
FunTy * getCalledFunction() const
Return the function being called if this is a direct call, otherwise return null (if it&#39;s an indirect...
Definition: CallSite.h:107
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
opStatus fusedMultiplyAdd(const APFloat &Multiplicand, const APFloat &Addend, roundingMode RM)
Definition: APFloat.h:995
APInt sadd_ov(const APInt &RHS, bool &Overflow) const
Definition: APInt.cpp:1875
unsigned getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition: Type.cpp:115
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:566
LLVM Value Representation.
Definition: Value.h:73
Constant * ConstantFoldLoadThroughBitcast(Constant *C, Type *DestTy, const DataLayout &DL)
ConstantFoldLoadThroughBitcast - try to cast constant to destination type returning null if unsuccess...
static VectorType * get(Type *ElementType, unsigned NumElements)
This static method is the primary way to construct an VectorType.
Definition: Type.cpp:606
bool canConstantFoldCallTo(ImmutableCallSite CS, const Function *F)
canConstantFoldCallTo - Return true if its even possible to fold a call to the specified function...
std::underlying_type< E >::type Mask()
Get a bitmask with 1s in all places up to the high-order bit of E&#39;s largest value.
Definition: BitmaskEnum.h:81
uint64_t getTypeAllocSizeInBits(Type *Ty) const
Returns the offset in bits between successive objects of the specified type, including alignment padd...
Definition: DataLayout.h:446
Type * getElementType() const
Definition: DerivedTypes.h:360
APInt usub_sat(const APInt &RHS) const
Definition: APInt.cpp:1979
static Constant * getExtractValue(Constant *Agg, ArrayRef< unsigned > Idxs, Type *OnlyIfReducedTy=nullptr)
Definition: Constants.cpp:2195
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Definition: InstrTypes.h:761
Type * getSourceElementType() const
Definition: Operator.cpp:23
APInt bitcastToAPInt() const
Definition: APFloat.h:1094
unsigned countLeadingZeros() const
The APInt version of the countLeadingZeros functions in MathExtras.h.
Definition: APInt.h:1596
APInt sadd_sat(const APInt &RHS) const
Definition: APInt.cpp:1950
bool isDoubleTy() const
Return true if this is &#39;double&#39;, a 64-bit IEEE fp type.
Definition: Type.h:150
Constant * ConstantFoldCall(ImmutableCallSite CS, Function *F, ArrayRef< Constant *> Operands, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldCall - Attempt to constant fold a call to the specified function with the specified argum...
static Constant * get(ArrayRef< Constant *> V)
Definition: Constants.cpp:1079
LLVM_READONLY APFloat minnum(const APFloat &A, const APFloat &B)
Implements IEEE minNum semantics.
Definition: APFloat.h:1227
int64_t getIndexedOffsetInType(Type *ElemTy, ArrayRef< Value *> Indices) const
Returns the offset from the beginning of the type for the specified indices.
Definition: DataLayout.cpp:787
PointerType * getType() const
Global values are always pointers.
Definition: GlobalValue.h:274
bool isNullValue() const
Determine if all bits are clear.
Definition: APInt.h:406
bool isStructTy() const
True if this is an instance of StructType.
Definition: Type.h:218
cmpResult compare(const APFloat &RHS) const
Definition: APFloat.h:1102
APInt sdiv_ov(const APInt &RHS, bool &Overflow) const
Definition: APInt.cpp:1901
const fltSemantics & getFltSemantics() const
Definition: Type.h:169
APInt usub_ov(const APInt &RHS, bool &Overflow) const
Definition: APInt.cpp:1895
static Constant * get(unsigned Opcode, Constant *C1, unsigned Flags=0, Type *OnlyIfReducedTy=nullptr)
get - Return a unary operator constant expression, folding if possible.
Definition: Constants.cpp:1806
Constant * ConstantFoldBinaryOpOperands(unsigned Opcode, Constant *LHS, Constant *RHS, const DataLayout &DL)
Attempt to constant fold a binary operation with the specified operands.