LLVM  9.0.0svn
InstCombineCalls.cpp
Go to the documentation of this file.
1 //===- InstCombineCalls.cpp -----------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the visitCall, visitInvoke, and visitCallBr functions.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "InstCombineInternal.h"
14 #include "llvm/ADT/APFloat.h"
15 #include "llvm/ADT/APInt.h"
16 #include "llvm/ADT/APSInt.h"
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/None.h"
19 #include "llvm/ADT/Optional.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/ADT/Twine.h"
26 #include "llvm/Analysis/Loads.h"
30 #include "llvm/IR/Attributes.h"
31 #include "llvm/IR/BasicBlock.h"
32 #include "llvm/IR/Constant.h"
33 #include "llvm/IR/Constants.h"
34 #include "llvm/IR/DataLayout.h"
35 #include "llvm/IR/DerivedTypes.h"
36 #include "llvm/IR/Function.h"
37 #include "llvm/IR/GlobalVariable.h"
38 #include "llvm/IR/InstrTypes.h"
39 #include "llvm/IR/Instruction.h"
40 #include "llvm/IR/Instructions.h"
41 #include "llvm/IR/IntrinsicInst.h"
42 #include "llvm/IR/Intrinsics.h"
43 #include "llvm/IR/LLVMContext.h"
44 #include "llvm/IR/Metadata.h"
45 #include "llvm/IR/PatternMatch.h"
46 #include "llvm/IR/Statepoint.h"
47 #include "llvm/IR/Type.h"
48 #include "llvm/IR/User.h"
49 #include "llvm/IR/Value.h"
50 #include "llvm/IR/ValueHandle.h"
52 #include "llvm/Support/Casting.h"
54 #include "llvm/Support/Compiler.h"
55 #include "llvm/Support/Debug.h"
57 #include "llvm/Support/KnownBits.h"
63 #include <algorithm>
64 #include <cassert>
65 #include <cstdint>
66 #include <cstring>
67 #include <utility>
68 #include <vector>
69 
70 using namespace llvm;
71 using namespace PatternMatch;
72 
73 #define DEBUG_TYPE "instcombine"
74 
75 STATISTIC(NumSimplified, "Number of library calls simplified");
76 
78  "instcombine-guard-widening-window",
79  cl::init(3),
80  cl::desc("How wide an instruction window to bypass looking for "
81  "another guard"));
82 
83 /// Return the specified type promoted as it would be to pass though a va_arg
84 /// area.
85 static Type *getPromotedType(Type *Ty) {
86  if (IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
87  if (ITy->getBitWidth() < 32)
88  return Type::getInt32Ty(Ty->getContext());
89  }
90  return Ty;
91 }
92 
93 /// Return a constant boolean vector that has true elements in all positions
94 /// where the input constant data vector has an element with the sign bit set.
97  IntegerType *BoolTy = Type::getInt1Ty(V->getContext());
98  for (unsigned I = 0, E = V->getNumElements(); I != E; ++I) {
99  Constant *Elt = V->getElementAsConstant(I);
100  assert((isa<ConstantInt>(Elt) || isa<ConstantFP>(Elt)) &&
101  "Unexpected constant data vector element type");
102  bool Sign = V->getElementType()->isIntegerTy()
103  ? cast<ConstantInt>(Elt)->isNegative()
104  : cast<ConstantFP>(Elt)->isNegative();
105  BoolVec.push_back(ConstantInt::get(BoolTy, Sign));
106  }
107  return ConstantVector::get(BoolVec);
108 }
109 
110 Instruction *InstCombiner::SimplifyAnyMemTransfer(AnyMemTransferInst *MI) {
111  unsigned DstAlign = getKnownAlignment(MI->getRawDest(), DL, MI, &AC, &DT);
112  unsigned CopyDstAlign = MI->getDestAlignment();
113  if (CopyDstAlign < DstAlign){
114  MI->setDestAlignment(DstAlign);
115  return MI;
116  }
117 
118  unsigned SrcAlign = getKnownAlignment(MI->getRawSource(), DL, MI, &AC, &DT);
119  unsigned CopySrcAlign = MI->getSourceAlignment();
120  if (CopySrcAlign < SrcAlign) {
121  MI->setSourceAlignment(SrcAlign);
122  return MI;
123  }
124 
125  // If we have a store to a location which is known constant, we can conclude
126  // that the store must be storing the constant value (else the memory
127  // wouldn't be constant), and this must be a noop.
128  if (AA->pointsToConstantMemory(MI->getDest())) {
129  // Set the size of the copy to 0, it will be deleted on the next iteration.
130  MI->setLength(Constant::getNullValue(MI->getLength()->getType()));
131  return MI;
132  }
133 
134  // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
135  // load/store.
136  ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getLength());
137  if (!MemOpLength) return nullptr;
138 
139  // Source and destination pointer types are always "i8*" for intrinsic. See
140  // if the size is something we can handle with a single primitive load/store.
141  // A single load+store correctly handles overlapping memory in the memmove
142  // case.
143  uint64_t Size = MemOpLength->getLimitedValue();
144  assert(Size && "0-sized memory transferring should be removed already.");
145 
146  if (Size > 8 || (Size&(Size-1)))
147  return nullptr; // If not 1/2/4/8 bytes, exit.
148 
149  // If it is an atomic and alignment is less than the size then we will
150  // introduce the unaligned memory access which will be later transformed
151  // into libcall in CodeGen. This is not evident performance gain so disable
152  // it now.
153  if (isa<AtomicMemTransferInst>(MI))
154  if (CopyDstAlign < Size || CopySrcAlign < Size)
155  return nullptr;
156 
157  // Use an integer load+store unless we can find something better.
158  unsigned SrcAddrSp =
159  cast<PointerType>(MI->getArgOperand(1)->getType())->getAddressSpace();
160  unsigned DstAddrSp =
161  cast<PointerType>(MI->getArgOperand(0)->getType())->getAddressSpace();
162 
163  IntegerType* IntType = IntegerType::get(MI->getContext(), Size<<3);
164  Type *NewSrcPtrTy = PointerType::get(IntType, SrcAddrSp);
165  Type *NewDstPtrTy = PointerType::get(IntType, DstAddrSp);
166 
167  // If the memcpy has metadata describing the members, see if we can get the
168  // TBAA tag describing our copy.
169  MDNode *CopyMD = nullptr;
170  if (MDNode *M = MI->getMetadata(LLVMContext::MD_tbaa)) {
171  CopyMD = M;
172  } else if (MDNode *M = MI->getMetadata(LLVMContext::MD_tbaa_struct)) {
173  if (M->getNumOperands() == 3 && M->getOperand(0) &&
174  mdconst::hasa<ConstantInt>(M->getOperand(0)) &&
175  mdconst::extract<ConstantInt>(M->getOperand(0))->isZero() &&
176  M->getOperand(1) &&
177  mdconst::hasa<ConstantInt>(M->getOperand(1)) &&
178  mdconst::extract<ConstantInt>(M->getOperand(1))->getValue() ==
179  Size &&
180  M->getOperand(2) && isa<MDNode>(M->getOperand(2)))
181  CopyMD = cast<MDNode>(M->getOperand(2));
182  }
183 
184  Value *Src = Builder.CreateBitCast(MI->getArgOperand(1), NewSrcPtrTy);
185  Value *Dest = Builder.CreateBitCast(MI->getArgOperand(0), NewDstPtrTy);
186  LoadInst *L = Builder.CreateLoad(IntType, Src);
187  // Alignment from the mem intrinsic will be better, so use it.
188  L->setAlignment(CopySrcAlign);
189  if (CopyMD)
190  L->setMetadata(LLVMContext::MD_tbaa, CopyMD);
191  MDNode *LoopMemParallelMD =
193  if (LoopMemParallelMD)
195  MDNode *AccessGroupMD = MI->getMetadata(LLVMContext::MD_access_group);
196  if (AccessGroupMD)
197  L->setMetadata(LLVMContext::MD_access_group, AccessGroupMD);
198 
199  StoreInst *S = Builder.CreateStore(L, Dest);
200  // Alignment from the mem intrinsic will be better, so use it.
201  S->setAlignment(CopyDstAlign);
202  if (CopyMD)
203  S->setMetadata(LLVMContext::MD_tbaa, CopyMD);
204  if (LoopMemParallelMD)
206  if (AccessGroupMD)
207  S->setMetadata(LLVMContext::MD_access_group, AccessGroupMD);
208 
209  if (auto *MT = dyn_cast<MemTransferInst>(MI)) {
210  // non-atomics can be volatile
211  L->setVolatile(MT->isVolatile());
212  S->setVolatile(MT->isVolatile());
213  }
214  if (isa<AtomicMemTransferInst>(MI)) {
215  // atomics have to be unordered
218  }
219 
220  // Set the size of the copy to 0, it will be deleted on the next iteration.
221  MI->setLength(Constant::getNullValue(MemOpLength->getType()));
222  return MI;
223 }
224 
225 Instruction *InstCombiner::SimplifyAnyMemSet(AnyMemSetInst *MI) {
226  unsigned Alignment = getKnownAlignment(MI->getDest(), DL, MI, &AC, &DT);
227  if (MI->getDestAlignment() < Alignment) {
228  MI->setDestAlignment(Alignment);
229  return MI;
230  }
231 
232  // If we have a store to a location which is known constant, we can conclude
233  // that the store must be storing the constant value (else the memory
234  // wouldn't be constant), and this must be a noop.
235  if (AA->pointsToConstantMemory(MI->getDest())) {
236  // Set the size of the copy to 0, it will be deleted on the next iteration.
237  MI->setLength(Constant::getNullValue(MI->getLength()->getType()));
238  return MI;
239  }
240 
241  // Extract the length and alignment and fill if they are constant.
242  ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
243  ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
244  if (!LenC || !FillC || !FillC->getType()->isIntegerTy(8))
245  return nullptr;
246  uint64_t Len = LenC->getLimitedValue();
247  Alignment = MI->getDestAlignment();
248  assert(Len && "0-sized memory setting should be removed already.");
249 
250  // Alignment 0 is identity for alignment 1 for memset, but not store.
251  if (Alignment == 0)
252  Alignment = 1;
253 
254  // If it is an atomic and alignment is less than the size then we will
255  // introduce the unaligned memory access which will be later transformed
256  // into libcall in CodeGen. This is not evident performance gain so disable
257  // it now.
258  if (isa<AtomicMemSetInst>(MI))
259  if (Alignment < Len)
260  return nullptr;
261 
262  // memset(s,c,n) -> store s, c (for n=1,2,4,8)
263  if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
264  Type *ITy = IntegerType::get(MI->getContext(), Len*8); // n=1 -> i8.
265 
266  Value *Dest = MI->getDest();
267  unsigned DstAddrSp = cast<PointerType>(Dest->getType())->getAddressSpace();
268  Type *NewDstPtrTy = PointerType::get(ITy, DstAddrSp);
269  Dest = Builder.CreateBitCast(Dest, NewDstPtrTy);
270 
271  // Extract the fill value and store.
272  uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
273  StoreInst *S = Builder.CreateStore(ConstantInt::get(ITy, Fill), Dest,
274  MI->isVolatile());
275  S->setAlignment(Alignment);
276  if (isa<AtomicMemSetInst>(MI))
278 
279  // Set the size of the copy to 0, it will be deleted on the next iteration.
280  MI->setLength(Constant::getNullValue(LenC->getType()));
281  return MI;
282  }
283 
284  return nullptr;
285 }
286 
288  InstCombiner::BuilderTy &Builder) {
289  bool LogicalShift = false;
290  bool ShiftLeft = false;
291 
292  switch (II.getIntrinsicID()) {
293  default: llvm_unreachable("Unexpected intrinsic!");
294  case Intrinsic::x86_sse2_psra_d:
295  case Intrinsic::x86_sse2_psra_w:
296  case Intrinsic::x86_sse2_psrai_d:
297  case Intrinsic::x86_sse2_psrai_w:
298  case Intrinsic::x86_avx2_psra_d:
299  case Intrinsic::x86_avx2_psra_w:
300  case Intrinsic::x86_avx2_psrai_d:
301  case Intrinsic::x86_avx2_psrai_w:
302  case Intrinsic::x86_avx512_psra_q_128:
303  case Intrinsic::x86_avx512_psrai_q_128:
304  case Intrinsic::x86_avx512_psra_q_256:
305  case Intrinsic::x86_avx512_psrai_q_256:
306  case Intrinsic::x86_avx512_psra_d_512:
307  case Intrinsic::x86_avx512_psra_q_512:
308  case Intrinsic::x86_avx512_psra_w_512:
309  case Intrinsic::x86_avx512_psrai_d_512:
310  case Intrinsic::x86_avx512_psrai_q_512:
311  case Intrinsic::x86_avx512_psrai_w_512:
312  LogicalShift = false; ShiftLeft = false;
313  break;
314  case Intrinsic::x86_sse2_psrl_d:
315  case Intrinsic::x86_sse2_psrl_q:
316  case Intrinsic::x86_sse2_psrl_w:
317  case Intrinsic::x86_sse2_psrli_d:
318  case Intrinsic::x86_sse2_psrli_q:
319  case Intrinsic::x86_sse2_psrli_w:
320  case Intrinsic::x86_avx2_psrl_d:
321  case Intrinsic::x86_avx2_psrl_q:
322  case Intrinsic::x86_avx2_psrl_w:
323  case Intrinsic::x86_avx2_psrli_d:
324  case Intrinsic::x86_avx2_psrli_q:
325  case Intrinsic::x86_avx2_psrli_w:
326  case Intrinsic::x86_avx512_psrl_d_512:
327  case Intrinsic::x86_avx512_psrl_q_512:
328  case Intrinsic::x86_avx512_psrl_w_512:
329  case Intrinsic::x86_avx512_psrli_d_512:
330  case Intrinsic::x86_avx512_psrli_q_512:
331  case Intrinsic::x86_avx512_psrli_w_512:
332  LogicalShift = true; ShiftLeft = false;
333  break;
334  case Intrinsic::x86_sse2_psll_d:
335  case Intrinsic::x86_sse2_psll_q:
336  case Intrinsic::x86_sse2_psll_w:
337  case Intrinsic::x86_sse2_pslli_d:
338  case Intrinsic::x86_sse2_pslli_q:
339  case Intrinsic::x86_sse2_pslli_w:
340  case Intrinsic::x86_avx2_psll_d:
341  case Intrinsic::x86_avx2_psll_q:
342  case Intrinsic::x86_avx2_psll_w:
343  case Intrinsic::x86_avx2_pslli_d:
344  case Intrinsic::x86_avx2_pslli_q:
345  case Intrinsic::x86_avx2_pslli_w:
346  case Intrinsic::x86_avx512_psll_d_512:
347  case Intrinsic::x86_avx512_psll_q_512:
348  case Intrinsic::x86_avx512_psll_w_512:
349  case Intrinsic::x86_avx512_pslli_d_512:
350  case Intrinsic::x86_avx512_pslli_q_512:
351  case Intrinsic::x86_avx512_pslli_w_512:
352  LogicalShift = true; ShiftLeft = true;
353  break;
354  }
355  assert((LogicalShift || !ShiftLeft) && "Only logical shifts can shift left");
356 
357  // Simplify if count is constant.
358  auto Arg1 = II.getArgOperand(1);
359  auto CAZ = dyn_cast<ConstantAggregateZero>(Arg1);
360  auto CDV = dyn_cast<ConstantDataVector>(Arg1);
361  auto CInt = dyn_cast<ConstantInt>(Arg1);
362  if (!CAZ && !CDV && !CInt)
363  return nullptr;
364 
365  APInt Count(64, 0);
366  if (CDV) {
367  // SSE2/AVX2 uses all the first 64-bits of the 128-bit vector
368  // operand to compute the shift amount.
369  auto VT = cast<VectorType>(CDV->getType());
370  unsigned BitWidth = VT->getElementType()->getPrimitiveSizeInBits();
371  assert((64 % BitWidth) == 0 && "Unexpected packed shift size");
372  unsigned NumSubElts = 64 / BitWidth;
373 
374  // Concatenate the sub-elements to create the 64-bit value.
375  for (unsigned i = 0; i != NumSubElts; ++i) {
376  unsigned SubEltIdx = (NumSubElts - 1) - i;
377  auto SubElt = cast<ConstantInt>(CDV->getElementAsConstant(SubEltIdx));
378  Count <<= BitWidth;
379  Count |= SubElt->getValue().zextOrTrunc(64);
380  }
381  }
382  else if (CInt)
383  Count = CInt->getValue();
384 
385  auto Vec = II.getArgOperand(0);
386  auto VT = cast<VectorType>(Vec->getType());
387  auto SVT = VT->getElementType();
388  unsigned VWidth = VT->getNumElements();
389  unsigned BitWidth = SVT->getPrimitiveSizeInBits();
390 
391  // If shift-by-zero then just return the original value.
392  if (Count.isNullValue())
393  return Vec;
394 
395  // Handle cases when Shift >= BitWidth.
396  if (Count.uge(BitWidth)) {
397  // If LogicalShift - just return zero.
398  if (LogicalShift)
399  return ConstantAggregateZero::get(VT);
400 
401  // If ArithmeticShift - clamp Shift to (BitWidth - 1).
402  Count = APInt(64, BitWidth - 1);
403  }
404 
405  // Get a constant vector of the same type as the first operand.
406  auto ShiftAmt = ConstantInt::get(SVT, Count.zextOrTrunc(BitWidth));
407  auto ShiftVec = Builder.CreateVectorSplat(VWidth, ShiftAmt);
408 
409  if (ShiftLeft)
410  return Builder.CreateShl(Vec, ShiftVec);
411 
412  if (LogicalShift)
413  return Builder.CreateLShr(Vec, ShiftVec);
414 
415  return Builder.CreateAShr(Vec, ShiftVec);
416 }
417 
418 // Attempt to simplify AVX2 per-element shift intrinsics to a generic IR shift.
419 // Unlike the generic IR shifts, the intrinsics have defined behaviour for out
420 // of range shift amounts (logical - set to zero, arithmetic - splat sign bit).
422  InstCombiner::BuilderTy &Builder) {
423  bool LogicalShift = false;
424  bool ShiftLeft = false;
425 
426  switch (II.getIntrinsicID()) {
427  default: llvm_unreachable("Unexpected intrinsic!");
428  case Intrinsic::x86_avx2_psrav_d:
429  case Intrinsic::x86_avx2_psrav_d_256:
430  case Intrinsic::x86_avx512_psrav_q_128:
431  case Intrinsic::x86_avx512_psrav_q_256:
432  case Intrinsic::x86_avx512_psrav_d_512:
433  case Intrinsic::x86_avx512_psrav_q_512:
434  case Intrinsic::x86_avx512_psrav_w_128:
435  case Intrinsic::x86_avx512_psrav_w_256:
436  case Intrinsic::x86_avx512_psrav_w_512:
437  LogicalShift = false;
438  ShiftLeft = false;
439  break;
440  case Intrinsic::x86_avx2_psrlv_d:
441  case Intrinsic::x86_avx2_psrlv_d_256:
442  case Intrinsic::x86_avx2_psrlv_q:
443  case Intrinsic::x86_avx2_psrlv_q_256:
444  case Intrinsic::x86_avx512_psrlv_d_512:
445  case Intrinsic::x86_avx512_psrlv_q_512:
446  case Intrinsic::x86_avx512_psrlv_w_128:
447  case Intrinsic::x86_avx512_psrlv_w_256:
448  case Intrinsic::x86_avx512_psrlv_w_512:
449  LogicalShift = true;
450  ShiftLeft = false;
451  break;
452  case Intrinsic::x86_avx2_psllv_d:
453  case Intrinsic::x86_avx2_psllv_d_256:
454  case Intrinsic::x86_avx2_psllv_q:
455  case Intrinsic::x86_avx2_psllv_q_256:
456  case Intrinsic::x86_avx512_psllv_d_512:
457  case Intrinsic::x86_avx512_psllv_q_512:
458  case Intrinsic::x86_avx512_psllv_w_128:
459  case Intrinsic::x86_avx512_psllv_w_256:
460  case Intrinsic::x86_avx512_psllv_w_512:
461  LogicalShift = true;
462  ShiftLeft = true;
463  break;
464  }
465  assert((LogicalShift || !ShiftLeft) && "Only logical shifts can shift left");
466 
467  // Simplify if all shift amounts are constant/undef.
468  auto *CShift = dyn_cast<Constant>(II.getArgOperand(1));
469  if (!CShift)
470  return nullptr;
471 
472  auto Vec = II.getArgOperand(0);
473  auto VT = cast<VectorType>(II.getType());
474  auto SVT = VT->getVectorElementType();
475  int NumElts = VT->getNumElements();
476  int BitWidth = SVT->getIntegerBitWidth();
477 
478  // Collect each element's shift amount.
479  // We also collect special cases: UNDEF = -1, OUT-OF-RANGE = BitWidth.
480  bool AnyOutOfRange = false;
481  SmallVector<int, 8> ShiftAmts;
482  for (int I = 0; I < NumElts; ++I) {
483  auto *CElt = CShift->getAggregateElement(I);
484  if (CElt && isa<UndefValue>(CElt)) {
485  ShiftAmts.push_back(-1);
486  continue;
487  }
488 
489  auto *COp = dyn_cast_or_null<ConstantInt>(CElt);
490  if (!COp)
491  return nullptr;
492 
493  // Handle out of range shifts.
494  // If LogicalShift - set to BitWidth (special case).
495  // If ArithmeticShift - set to (BitWidth - 1) (sign splat).
496  APInt ShiftVal = COp->getValue();
497  if (ShiftVal.uge(BitWidth)) {
498  AnyOutOfRange = LogicalShift;
499  ShiftAmts.push_back(LogicalShift ? BitWidth : BitWidth - 1);
500  continue;
501  }
502 
503  ShiftAmts.push_back((int)ShiftVal.getZExtValue());
504  }
505 
506  // If all elements out of range or UNDEF, return vector of zeros/undefs.
507  // ArithmeticShift should only hit this if they are all UNDEF.
508  auto OutOfRange = [&](int Idx) { return (Idx < 0) || (BitWidth <= Idx); };
509  if (llvm::all_of(ShiftAmts, OutOfRange)) {
510  SmallVector<Constant *, 8> ConstantVec;
511  for (int Idx : ShiftAmts) {
512  if (Idx < 0) {
513  ConstantVec.push_back(UndefValue::get(SVT));
514  } else {
515  assert(LogicalShift && "Logical shift expected");
516  ConstantVec.push_back(ConstantInt::getNullValue(SVT));
517  }
518  }
519  return ConstantVector::get(ConstantVec);
520  }
521 
522  // We can't handle only some out of range values with generic logical shifts.
523  if (AnyOutOfRange)
524  return nullptr;
525 
526  // Build the shift amount constant vector.
527  SmallVector<Constant *, 8> ShiftVecAmts;
528  for (int Idx : ShiftAmts) {
529  if (Idx < 0)
530  ShiftVecAmts.push_back(UndefValue::get(SVT));
531  else
532  ShiftVecAmts.push_back(ConstantInt::get(SVT, Idx));
533  }
534  auto ShiftVec = ConstantVector::get(ShiftVecAmts);
535 
536  if (ShiftLeft)
537  return Builder.CreateShl(Vec, ShiftVec);
538 
539  if (LogicalShift)
540  return Builder.CreateLShr(Vec, ShiftVec);
541 
542  return Builder.CreateAShr(Vec, ShiftVec);
543 }
544 
546  InstCombiner::BuilderTy &Builder, bool IsSigned) {
547  Value *Arg0 = II.getArgOperand(0);
548  Value *Arg1 = II.getArgOperand(1);
549  Type *ResTy = II.getType();
550 
551  // Fast all undef handling.
552  if (isa<UndefValue>(Arg0) && isa<UndefValue>(Arg1))
553  return UndefValue::get(ResTy);
554 
555  Type *ArgTy = Arg0->getType();
556  unsigned NumLanes = ResTy->getPrimitiveSizeInBits() / 128;
557  unsigned NumSrcElts = ArgTy->getVectorNumElements();
558  assert(ResTy->getVectorNumElements() == (2 * NumSrcElts) &&
559  "Unexpected packing types");
560 
561  unsigned NumSrcEltsPerLane = NumSrcElts / NumLanes;
562  unsigned DstScalarSizeInBits = ResTy->getScalarSizeInBits();
563  unsigned SrcScalarSizeInBits = ArgTy->getScalarSizeInBits();
564  assert(SrcScalarSizeInBits == (2 * DstScalarSizeInBits) &&
565  "Unexpected packing types");
566 
567  // Constant folding.
568  if (!isa<Constant>(Arg0) || !isa<Constant>(Arg1))
569  return nullptr;
570 
571  // Clamp Values - signed/unsigned both use signed clamp values, but they
572  // differ on the min/max values.
573  APInt MinValue, MaxValue;
574  if (IsSigned) {
575  // PACKSS: Truncate signed value with signed saturation.
576  // Source values less than dst minint are saturated to minint.
577  // Source values greater than dst maxint are saturated to maxint.
578  MinValue =
579  APInt::getSignedMinValue(DstScalarSizeInBits).sext(SrcScalarSizeInBits);
580  MaxValue =
581  APInt::getSignedMaxValue(DstScalarSizeInBits).sext(SrcScalarSizeInBits);
582  } else {
583  // PACKUS: Truncate signed value with unsigned saturation.
584  // Source values less than zero are saturated to zero.
585  // Source values greater than dst maxuint are saturated to maxuint.
586  MinValue = APInt::getNullValue(SrcScalarSizeInBits);
587  MaxValue = APInt::getLowBitsSet(SrcScalarSizeInBits, DstScalarSizeInBits);
588  }
589 
590  auto *MinC = Constant::getIntegerValue(ArgTy, MinValue);
591  auto *MaxC = Constant::getIntegerValue(ArgTy, MaxValue);
592  Arg0 = Builder.CreateSelect(Builder.CreateICmpSLT(Arg0, MinC), MinC, Arg0);
593  Arg1 = Builder.CreateSelect(Builder.CreateICmpSLT(Arg1, MinC), MinC, Arg1);
594  Arg0 = Builder.CreateSelect(Builder.CreateICmpSGT(Arg0, MaxC), MaxC, Arg0);
595  Arg1 = Builder.CreateSelect(Builder.CreateICmpSGT(Arg1, MaxC), MaxC, Arg1);
596 
597  // Shuffle clamped args together at the lane level.
598  SmallVector<unsigned, 32> PackMask;
599  for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
600  for (unsigned Elt = 0; Elt != NumSrcEltsPerLane; ++Elt)
601  PackMask.push_back(Elt + (Lane * NumSrcEltsPerLane));
602  for (unsigned Elt = 0; Elt != NumSrcEltsPerLane; ++Elt)
603  PackMask.push_back(Elt + (Lane * NumSrcEltsPerLane) + NumSrcElts);
604  }
605  auto *Shuffle = Builder.CreateShuffleVector(Arg0, Arg1, PackMask);
606 
607  // Truncate to dst size.
608  return Builder.CreateTrunc(Shuffle, ResTy);
609 }
610 
612  InstCombiner::BuilderTy &Builder) {
613  Value *Arg = II.getArgOperand(0);
614  Type *ResTy = II.getType();
615  Type *ArgTy = Arg->getType();
616 
617  // movmsk(undef) -> zero as we must ensure the upper bits are zero.
618  if (isa<UndefValue>(Arg))
619  return Constant::getNullValue(ResTy);
620 
621  // We can't easily peek through x86_mmx types.
622  if (!ArgTy->isVectorTy())
623  return nullptr;
624 
625  // Expand MOVMSK to compare/bitcast/zext:
626  // e.g. PMOVMSKB(v16i8 x):
627  // %cmp = icmp slt <16 x i8> %x, zeroinitializer
628  // %int = bitcast <16 x i1> %cmp to i16
629  // %res = zext i16 %int to i32
630  unsigned NumElts = ArgTy->getVectorNumElements();
631  Type *IntegerVecTy = VectorType::getInteger(cast<VectorType>(ArgTy));
632  Type *IntegerTy = Builder.getIntNTy(NumElts);
633 
634  Value *Res = Builder.CreateBitCast(Arg, IntegerVecTy);
635  Res = Builder.CreateICmpSLT(Res, Constant::getNullValue(IntegerVecTy));
636  Res = Builder.CreateBitCast(Res, IntegerTy);
637  Res = Builder.CreateZExtOrTrunc(Res, ResTy);
638  return Res;
639 }
640 
642  InstCombiner::BuilderTy &Builder) {
643  Value *CarryIn = II.getArgOperand(0);
644  Value *Op1 = II.getArgOperand(1);
645  Value *Op2 = II.getArgOperand(2);
646  Type *RetTy = II.getType();
647  Type *OpTy = Op1->getType();
648  assert(RetTy->getStructElementType(0)->isIntegerTy(8) &&
649  RetTy->getStructElementType(1) == OpTy && OpTy == Op2->getType() &&
650  "Unexpected types for x86 addcarry");
651 
652  // If carry-in is zero, this is just an unsigned add with overflow.
653  if (match(CarryIn, m_ZeroInt())) {
654  Value *UAdd = Builder.CreateIntrinsic(Intrinsic::uadd_with_overflow, OpTy,
655  { Op1, Op2 });
656  // The types have to be adjusted to match the x86 call types.
657  Value *UAddResult = Builder.CreateExtractValue(UAdd, 0);
658  Value *UAddOV = Builder.CreateZExt(Builder.CreateExtractValue(UAdd, 1),
659  Builder.getInt8Ty());
660  Value *Res = UndefValue::get(RetTy);
661  Res = Builder.CreateInsertValue(Res, UAddOV, 0);
662  return Builder.CreateInsertValue(Res, UAddResult, 1);
663  }
664 
665  return nullptr;
666 }
667 
669  InstCombiner::BuilderTy &Builder) {
670  auto *CInt = dyn_cast<ConstantInt>(II.getArgOperand(2));
671  if (!CInt)
672  return nullptr;
673 
674  VectorType *VecTy = cast<VectorType>(II.getType());
675  assert(VecTy->getNumElements() == 4 && "insertps with wrong vector type");
676 
677  // The immediate permute control byte looks like this:
678  // [3:0] - zero mask for each 32-bit lane
679  // [5:4] - select one 32-bit destination lane
680  // [7:6] - select one 32-bit source lane
681 
682  uint8_t Imm = CInt->getZExtValue();
683  uint8_t ZMask = Imm & 0xf;
684  uint8_t DestLane = (Imm >> 4) & 0x3;
685  uint8_t SourceLane = (Imm >> 6) & 0x3;
686 
688 
689  // If all zero mask bits are set, this was just a weird way to
690  // generate a zero vector.
691  if (ZMask == 0xf)
692  return ZeroVector;
693 
694  // Initialize by passing all of the first source bits through.
695  uint32_t ShuffleMask[4] = { 0, 1, 2, 3 };
696 
697  // We may replace the second operand with the zero vector.
698  Value *V1 = II.getArgOperand(1);
699 
700  if (ZMask) {
701  // If the zero mask is being used with a single input or the zero mask
702  // overrides the destination lane, this is a shuffle with the zero vector.
703  if ((II.getArgOperand(0) == II.getArgOperand(1)) ||
704  (ZMask & (1 << DestLane))) {
705  V1 = ZeroVector;
706  // We may still move 32-bits of the first source vector from one lane
707  // to another.
708  ShuffleMask[DestLane] = SourceLane;
709  // The zero mask may override the previous insert operation.
710  for (unsigned i = 0; i < 4; ++i)
711  if ((ZMask >> i) & 0x1)
712  ShuffleMask[i] = i + 4;
713  } else {
714  // TODO: Model this case as 2 shuffles or a 'logical and' plus shuffle?
715  return nullptr;
716  }
717  } else {
718  // Replace the selected destination lane with the selected source lane.
719  ShuffleMask[DestLane] = SourceLane + 4;
720  }
721 
722  return Builder.CreateShuffleVector(II.getArgOperand(0), V1, ShuffleMask);
723 }
724 
725 /// Attempt to simplify SSE4A EXTRQ/EXTRQI instructions using constant folding
726 /// or conversion to a shuffle vector.
728  ConstantInt *CILength, ConstantInt *CIIndex,
729  InstCombiner::BuilderTy &Builder) {
730  auto LowConstantHighUndef = [&](uint64_t Val) {
731  Type *IntTy64 = Type::getInt64Ty(II.getContext());
732  Constant *Args[] = {ConstantInt::get(IntTy64, Val),
733  UndefValue::get(IntTy64)};
734  return ConstantVector::get(Args);
735  };
736 
737  // See if we're dealing with constant values.
738  Constant *C0 = dyn_cast<Constant>(Op0);
739  ConstantInt *CI0 =
740  C0 ? dyn_cast_or_null<ConstantInt>(C0->getAggregateElement((unsigned)0))
741  : nullptr;
742 
743  // Attempt to constant fold.
744  if (CILength && CIIndex) {
745  // From AMD documentation: "The bit index and field length are each six
746  // bits in length other bits of the field are ignored."
747  APInt APIndex = CIIndex->getValue().zextOrTrunc(6);
748  APInt APLength = CILength->getValue().zextOrTrunc(6);
749 
750  unsigned Index = APIndex.getZExtValue();
751 
752  // From AMD documentation: "a value of zero in the field length is
753  // defined as length of 64".
754  unsigned Length = APLength == 0 ? 64 : APLength.getZExtValue();
755 
756  // From AMD documentation: "If the sum of the bit index + length field
757  // is greater than 64, the results are undefined".
758  unsigned End = Index + Length;
759 
760  // Note that both field index and field length are 8-bit quantities.
761  // Since variables 'Index' and 'Length' are unsigned values
762  // obtained from zero-extending field index and field length
763  // respectively, their sum should never wrap around.
764  if (End > 64)
765  return UndefValue::get(II.getType());
766 
767  // If we are inserting whole bytes, we can convert this to a shuffle.
768  // Lowering can recognize EXTRQI shuffle masks.
769  if ((Length % 8) == 0 && (Index % 8) == 0) {
770  // Convert bit indices to byte indices.
771  Length /= 8;
772  Index /= 8;
773 
774  Type *IntTy8 = Type::getInt8Ty(II.getContext());
775  Type *IntTy32 = Type::getInt32Ty(II.getContext());
776  VectorType *ShufTy = VectorType::get(IntTy8, 16);
777 
778  SmallVector<Constant *, 16> ShuffleMask;
779  for (int i = 0; i != (int)Length; ++i)
780  ShuffleMask.push_back(
781  Constant::getIntegerValue(IntTy32, APInt(32, i + Index)));
782  for (int i = Length; i != 8; ++i)
783  ShuffleMask.push_back(
784  Constant::getIntegerValue(IntTy32, APInt(32, i + 16)));
785  for (int i = 8; i != 16; ++i)
786  ShuffleMask.push_back(UndefValue::get(IntTy32));
787 
788  Value *SV = Builder.CreateShuffleVector(
789  Builder.CreateBitCast(Op0, ShufTy),
790  ConstantAggregateZero::get(ShufTy), ConstantVector::get(ShuffleMask));
791  return Builder.CreateBitCast(SV, II.getType());
792  }
793 
794  // Constant Fold - shift Index'th bit to lowest position and mask off
795  // Length bits.
796  if (CI0) {
797  APInt Elt = CI0->getValue();
798  Elt.lshrInPlace(Index);
799  Elt = Elt.zextOrTrunc(Length);
800  return LowConstantHighUndef(Elt.getZExtValue());
801  }
802 
803  // If we were an EXTRQ call, we'll save registers if we convert to EXTRQI.
804  if (II.getIntrinsicID() == Intrinsic::x86_sse4a_extrq) {
805  Value *Args[] = {Op0, CILength, CIIndex};
806  Module *M = II.getModule();
807  Function *F = Intrinsic::getDeclaration(M, Intrinsic::x86_sse4a_extrqi);
808  return Builder.CreateCall(F, Args);
809  }
810  }
811 
812  // Constant Fold - extraction from zero is always {zero, undef}.
813  if (CI0 && CI0->isZero())
814  return LowConstantHighUndef(0);
815 
816  return nullptr;
817 }
818 
819 /// Attempt to simplify SSE4A INSERTQ/INSERTQI instructions using constant
820 /// folding or conversion to a shuffle vector.
822  APInt APLength, APInt APIndex,
823  InstCombiner::BuilderTy &Builder) {
824  // From AMD documentation: "The bit index and field length are each six bits
825  // in length other bits of the field are ignored."
826  APIndex = APIndex.zextOrTrunc(6);
827  APLength = APLength.zextOrTrunc(6);
828 
829  // Attempt to constant fold.
830  unsigned Index = APIndex.getZExtValue();
831 
832  // From AMD documentation: "a value of zero in the field length is
833  // defined as length of 64".
834  unsigned Length = APLength == 0 ? 64 : APLength.getZExtValue();
835 
836  // From AMD documentation: "If the sum of the bit index + length field
837  // is greater than 64, the results are undefined".
838  unsigned End = Index + Length;
839 
840  // Note that both field index and field length are 8-bit quantities.
841  // Since variables 'Index' and 'Length' are unsigned values
842  // obtained from zero-extending field index and field length
843  // respectively, their sum should never wrap around.
844  if (End > 64)
845  return UndefValue::get(II.getType());
846 
847  // If we are inserting whole bytes, we can convert this to a shuffle.
848  // Lowering can recognize INSERTQI shuffle masks.
849  if ((Length % 8) == 0 && (Index % 8) == 0) {
850  // Convert bit indices to byte indices.
851  Length /= 8;
852  Index /= 8;
853 
854  Type *IntTy8 = Type::getInt8Ty(II.getContext());
855  Type *IntTy32 = Type::getInt32Ty(II.getContext());
856  VectorType *ShufTy = VectorType::get(IntTy8, 16);
857 
858  SmallVector<Constant *, 16> ShuffleMask;
859  for (int i = 0; i != (int)Index; ++i)
860  ShuffleMask.push_back(Constant::getIntegerValue(IntTy32, APInt(32, i)));
861  for (int i = 0; i != (int)Length; ++i)
862  ShuffleMask.push_back(
863  Constant::getIntegerValue(IntTy32, APInt(32, i + 16)));
864  for (int i = Index + Length; i != 8; ++i)
865  ShuffleMask.push_back(Constant::getIntegerValue(IntTy32, APInt(32, i)));
866  for (int i = 8; i != 16; ++i)
867  ShuffleMask.push_back(UndefValue::get(IntTy32));
868 
869  Value *SV = Builder.CreateShuffleVector(Builder.CreateBitCast(Op0, ShufTy),
870  Builder.CreateBitCast(Op1, ShufTy),
871  ConstantVector::get(ShuffleMask));
872  return Builder.CreateBitCast(SV, II.getType());
873  }
874 
875  // See if we're dealing with constant values.
876  Constant *C0 = dyn_cast<Constant>(Op0);
877  Constant *C1 = dyn_cast<Constant>(Op1);
878  ConstantInt *CI00 =
879  C0 ? dyn_cast_or_null<ConstantInt>(C0->getAggregateElement((unsigned)0))
880  : nullptr;
881  ConstantInt *CI10 =
882  C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)0))
883  : nullptr;
884 
885  // Constant Fold - insert bottom Length bits starting at the Index'th bit.
886  if (CI00 && CI10) {
887  APInt V00 = CI00->getValue();
888  APInt V10 = CI10->getValue();
889  APInt Mask = APInt::getLowBitsSet(64, Length).shl(Index);
890  V00 = V00 & ~Mask;
891  V10 = V10.zextOrTrunc(Length).zextOrTrunc(64).shl(Index);
892  APInt Val = V00 | V10;
893  Type *IntTy64 = Type::getInt64Ty(II.getContext());
894  Constant *Args[] = {ConstantInt::get(IntTy64, Val.getZExtValue()),
895  UndefValue::get(IntTy64)};
896  return ConstantVector::get(Args);
897  }
898 
899  // If we were an INSERTQ call, we'll save demanded elements if we convert to
900  // INSERTQI.
901  if (II.getIntrinsicID() == Intrinsic::x86_sse4a_insertq) {
902  Type *IntTy8 = Type::getInt8Ty(II.getContext());
903  Constant *CILength = ConstantInt::get(IntTy8, Length, false);
904  Constant *CIIndex = ConstantInt::get(IntTy8, Index, false);
905 
906  Value *Args[] = {Op0, Op1, CILength, CIIndex};
907  Module *M = II.getModule();
908  Function *F = Intrinsic::getDeclaration(M, Intrinsic::x86_sse4a_insertqi);
909  return Builder.CreateCall(F, Args);
910  }
911 
912  return nullptr;
913 }
914 
915 /// Attempt to convert pshufb* to shufflevector if the mask is constant.
917  InstCombiner::BuilderTy &Builder) {
919  if (!V)
920  return nullptr;
921 
922  auto *VecTy = cast<VectorType>(II.getType());
923  auto *MaskEltTy = Type::getInt32Ty(II.getContext());
924  unsigned NumElts = VecTy->getNumElements();
925  assert((NumElts == 16 || NumElts == 32 || NumElts == 64) &&
926  "Unexpected number of elements in shuffle mask!");
927 
928  // Construct a shuffle mask from constant integers or UNDEFs.
929  Constant *Indexes[64] = {nullptr};
930 
931  // Each byte in the shuffle control mask forms an index to permute the
932  // corresponding byte in the destination operand.
933  for (unsigned I = 0; I < NumElts; ++I) {
934  Constant *COp = V->getAggregateElement(I);
935  if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
936  return nullptr;
937 
938  if (isa<UndefValue>(COp)) {
939  Indexes[I] = UndefValue::get(MaskEltTy);
940  continue;
941  }
942 
943  int8_t Index = cast<ConstantInt>(COp)->getValue().getZExtValue();
944 
945  // If the most significant bit (bit[7]) of each byte of the shuffle
946  // control mask is set, then zero is written in the result byte.
947  // The zero vector is in the right-hand side of the resulting
948  // shufflevector.
949 
950  // The value of each index for the high 128-bit lane is the least
951  // significant 4 bits of the respective shuffle control byte.
952  Index = ((Index < 0) ? NumElts : Index & 0x0F) + (I & 0xF0);
953  Indexes[I] = ConstantInt::get(MaskEltTy, Index);
954  }
955 
956  auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, NumElts));
957  auto V1 = II.getArgOperand(0);
958  auto V2 = Constant::getNullValue(VecTy);
959  return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
960 }
961 
962 /// Attempt to convert vpermilvar* to shufflevector if the mask is constant.
964  InstCombiner::BuilderTy &Builder) {
966  if (!V)
967  return nullptr;
968 
969  auto *VecTy = cast<VectorType>(II.getType());
970  auto *MaskEltTy = Type::getInt32Ty(II.getContext());
971  unsigned NumElts = VecTy->getVectorNumElements();
972  bool IsPD = VecTy->getScalarType()->isDoubleTy();
973  unsigned NumLaneElts = IsPD ? 2 : 4;
974  assert(NumElts == 16 || NumElts == 8 || NumElts == 4 || NumElts == 2);
975 
976  // Construct a shuffle mask from constant integers or UNDEFs.
977  Constant *Indexes[16] = {nullptr};
978 
979  // The intrinsics only read one or two bits, clear the rest.
980  for (unsigned I = 0; I < NumElts; ++I) {
981  Constant *COp = V->getAggregateElement(I);
982  if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
983  return nullptr;
984 
985  if (isa<UndefValue>(COp)) {
986  Indexes[I] = UndefValue::get(MaskEltTy);
987  continue;
988  }
989 
990  APInt Index = cast<ConstantInt>(COp)->getValue();
991  Index = Index.zextOrTrunc(32).getLoBits(2);
992 
993  // The PD variants uses bit 1 to select per-lane element index, so
994  // shift down to convert to generic shuffle mask index.
995  if (IsPD)
996  Index.lshrInPlace(1);
997 
998  // The _256 variants are a bit trickier since the mask bits always index
999  // into the corresponding 128 half. In order to convert to a generic
1000  // shuffle, we have to make that explicit.
1001  Index += APInt(32, (I / NumLaneElts) * NumLaneElts);
1002 
1003  Indexes[I] = ConstantInt::get(MaskEltTy, Index);
1004  }
1005 
1006  auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, NumElts));
1007  auto V1 = II.getArgOperand(0);
1008  auto V2 = UndefValue::get(V1->getType());
1009  return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
1010 }
1011 
1012 /// Attempt to convert vpermd/vpermps to shufflevector if the mask is constant.
1014  InstCombiner::BuilderTy &Builder) {
1015  auto *V = dyn_cast<Constant>(II.getArgOperand(1));
1016  if (!V)
1017  return nullptr;
1018 
1019  auto *VecTy = cast<VectorType>(II.getType());
1020  auto *MaskEltTy = Type::getInt32Ty(II.getContext());
1021  unsigned Size = VecTy->getNumElements();
1022  assert((Size == 4 || Size == 8 || Size == 16 || Size == 32 || Size == 64) &&
1023  "Unexpected shuffle mask size");
1024 
1025  // Construct a shuffle mask from constant integers or UNDEFs.
1026  Constant *Indexes[64] = {nullptr};
1027 
1028  for (unsigned I = 0; I < Size; ++I) {
1029  Constant *COp = V->getAggregateElement(I);
1030  if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
1031  return nullptr;
1032 
1033  if (isa<UndefValue>(COp)) {
1034  Indexes[I] = UndefValue::get(MaskEltTy);
1035  continue;
1036  }
1037 
1038  uint32_t Index = cast<ConstantInt>(COp)->getZExtValue();
1039  Index &= Size - 1;
1040  Indexes[I] = ConstantInt::get(MaskEltTy, Index);
1041  }
1042 
1043  auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, Size));
1044  auto V1 = II.getArgOperand(0);
1045  auto V2 = UndefValue::get(VecTy);
1046  return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
1047 }
1048 
1049 // TODO, Obvious Missing Transforms:
1050 // * Narrow width by halfs excluding zero/undef lanes
1051 Value *InstCombiner::simplifyMaskedLoad(IntrinsicInst &II) {
1052  Value *LoadPtr = II.getArgOperand(0);
1053  unsigned Alignment = cast<ConstantInt>(II.getArgOperand(1))->getZExtValue();
1054 
1055  // If the mask is all ones or undefs, this is a plain vector load of the 1st
1056  // argument.
1058  return Builder.CreateAlignedLoad(II.getType(), LoadPtr, Alignment,
1059  "unmaskedload");
1060 
1061  // If we can unconditionally load from this address, replace with a
1062  // load/select idiom. TODO: use DT for context sensitive query
1063  if (isDereferenceableAndAlignedPointer(LoadPtr, Alignment,
1064  II.getModule()->getDataLayout(),
1065  &II, nullptr)) {
1066  Value *LI = Builder.CreateAlignedLoad(II.getType(), LoadPtr, Alignment,
1067  "unmaskedload");
1068  return Builder.CreateSelect(II.getArgOperand(2), LI, II.getArgOperand(3));
1069  }
1070 
1071  return nullptr;
1072 }
1073 
1074 // TODO, Obvious Missing Transforms:
1075 // * Single constant active lane -> store
1076 // * Narrow width by halfs excluding zero/undef lanes
1077 Instruction *InstCombiner::simplifyMaskedStore(IntrinsicInst &II) {
1078  auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3));
1079  if (!ConstMask)
1080  return nullptr;
1081 
1082  // If the mask is all zeros, this instruction does nothing.
1083  if (ConstMask->isNullValue())
1084  return eraseInstFromFunction(II);
1085 
1086  // If the mask is all ones, this is a plain vector store of the 1st argument.
1087  if (ConstMask->isAllOnesValue()) {
1088  Value *StorePtr = II.getArgOperand(1);
1089  unsigned Alignment = cast<ConstantInt>(II.getArgOperand(2))->getZExtValue();
1090  return new StoreInst(II.getArgOperand(0), StorePtr, false, Alignment);
1091  }
1092 
1093  // Use masked off lanes to simplify operands via SimplifyDemandedVectorElts
1094  APInt DemandedElts = possiblyDemandedEltsInMask(ConstMask);
1095  APInt UndefElts(DemandedElts.getBitWidth(), 0);
1096  if (Value *V = SimplifyDemandedVectorElts(II.getOperand(0),
1097  DemandedElts, UndefElts)) {
1098  II.setOperand(0, V);
1099  return &II;
1100  }
1101 
1102  return nullptr;
1103 }
1104 
1105 // TODO, Obvious Missing Transforms:
1106 // * Single constant active lane load -> load
1107 // * Dereferenceable address & few lanes -> scalarize speculative load/selects
1108 // * Adjacent vector addresses -> masked.load
1109 // * Narrow width by halfs excluding zero/undef lanes
1110 // * Vector splat address w/known mask -> scalar load
1111 // * Vector incrementing address -> vector masked load
1112 Instruction *InstCombiner::simplifyMaskedGather(IntrinsicInst &II) {
1113  return nullptr;
1114 }
1115 
1116 // TODO, Obvious Missing Transforms:
1117 // * Single constant active lane -> store
1118 // * Adjacent vector addresses -> masked.store
1119 // * Narrow store width by halfs excluding zero/undef lanes
1120 // * Vector splat address w/known mask -> scalar store
1121 // * Vector incrementing address -> vector masked store
1122 Instruction *InstCombiner::simplifyMaskedScatter(IntrinsicInst &II) {
1123  auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3));
1124  if (!ConstMask)
1125  return nullptr;
1126 
1127  // If the mask is all zeros, a scatter does nothing.
1128  if (ConstMask->isNullValue())
1129  return eraseInstFromFunction(II);
1130 
1131  // Use masked off lanes to simplify operands via SimplifyDemandedVectorElts
1132  APInt DemandedElts = possiblyDemandedEltsInMask(ConstMask);
1133  APInt UndefElts(DemandedElts.getBitWidth(), 0);
1134  if (Value *V = SimplifyDemandedVectorElts(II.getOperand(0),
1135  DemandedElts, UndefElts)) {
1136  II.setOperand(0, V);
1137  return &II;
1138  }
1139  if (Value *V = SimplifyDemandedVectorElts(II.getOperand(1),
1140  DemandedElts, UndefElts)) {
1141  II.setOperand(1, V);
1142  return &II;
1143  }
1144 
1145  return nullptr;
1146 }
1147 
1148 /// This function transforms launder.invariant.group and strip.invariant.group
1149 /// like:
1150 /// launder(launder(%x)) -> launder(%x) (the result is not the argument)
1151 /// launder(strip(%x)) -> launder(%x)
1152 /// strip(strip(%x)) -> strip(%x) (the result is not the argument)
1153 /// strip(launder(%x)) -> strip(%x)
1154 /// This is legal because it preserves the most recent information about
1155 /// the presence or absence of invariant.group.
1157  InstCombiner &IC) {
1158  auto *Arg = II.getArgOperand(0);
1159  auto *StrippedArg = Arg->stripPointerCasts();
1160  auto *StrippedInvariantGroupsArg = Arg->stripPointerCastsAndInvariantGroups();
1161  if (StrippedArg == StrippedInvariantGroupsArg)
1162  return nullptr; // No launders/strips to remove.
1163 
1164  Value *Result = nullptr;
1165 
1166  if (II.getIntrinsicID() == Intrinsic::launder_invariant_group)
1167  Result = IC.Builder.CreateLaunderInvariantGroup(StrippedInvariantGroupsArg);
1168  else if (II.getIntrinsicID() == Intrinsic::strip_invariant_group)
1169  Result = IC.Builder.CreateStripInvariantGroup(StrippedInvariantGroupsArg);
1170  else
1172  "simplifyInvariantGroupIntrinsic only handles launder and strip");
1173  if (Result->getType()->getPointerAddressSpace() !=
1175  Result = IC.Builder.CreateAddrSpaceCast(Result, II.getType());
1176  if (Result->getType() != II.getType())
1177  Result = IC.Builder.CreateBitCast(Result, II.getType());
1178 
1179  return cast<Instruction>(Result);
1180 }
1181 
1183  assert((II.getIntrinsicID() == Intrinsic::cttz ||
1184  II.getIntrinsicID() == Intrinsic::ctlz) &&
1185  "Expected cttz or ctlz intrinsic");
1186  bool IsTZ = II.getIntrinsicID() == Intrinsic::cttz;
1187  Value *Op0 = II.getArgOperand(0);
1188  Value *X;
1189  // ctlz(bitreverse(x)) -> cttz(x)
1190  // cttz(bitreverse(x)) -> ctlz(x)
1191  if (match(Op0, m_BitReverse(m_Value(X)))) {
1192  Intrinsic::ID ID = IsTZ ? Intrinsic::ctlz : Intrinsic::cttz;
1194  return CallInst::Create(F, {X, II.getArgOperand(1)});
1195  }
1196 
1197  KnownBits Known = IC.computeKnownBits(Op0, 0, &II);
1198 
1199  // Create a mask for bits above (ctlz) or below (cttz) the first known one.
1200  unsigned PossibleZeros = IsTZ ? Known.countMaxTrailingZeros()
1201  : Known.countMaxLeadingZeros();
1202  unsigned DefiniteZeros = IsTZ ? Known.countMinTrailingZeros()
1203  : Known.countMinLeadingZeros();
1204 
1205  // If all bits above (ctlz) or below (cttz) the first known one are known
1206  // zero, this value is constant.
1207  // FIXME: This should be in InstSimplify because we're replacing an
1208  // instruction with a constant.
1209  if (PossibleZeros == DefiniteZeros) {
1210  auto *C = ConstantInt::get(Op0->getType(), DefiniteZeros);
1211  return IC.replaceInstUsesWith(II, C);
1212  }
1213 
1214  // If the input to cttz/ctlz is known to be non-zero,
1215  // then change the 'ZeroIsUndef' parameter to 'true'
1216  // because we know the zero behavior can't affect the result.
1217  if (!Known.One.isNullValue() ||
1218  isKnownNonZero(Op0, IC.getDataLayout(), 0, &IC.getAssumptionCache(), &II,
1219  &IC.getDominatorTree())) {
1220  if (!match(II.getArgOperand(1), m_One())) {
1221  II.setOperand(1, IC.Builder.getTrue());
1222  return &II;
1223  }
1224  }
1225 
1226  // Add range metadata since known bits can't completely reflect what we know.
1227  // TODO: Handle splat vectors.
1228  auto *IT = dyn_cast<IntegerType>(Op0->getType());
1229  if (IT && IT->getBitWidth() != 1 && !II.getMetadata(LLVMContext::MD_range)) {
1230  Metadata *LowAndHigh[] = {
1231  ConstantAsMetadata::get(ConstantInt::get(IT, DefiniteZeros)),
1232  ConstantAsMetadata::get(ConstantInt::get(IT, PossibleZeros + 1))};
1235  return &II;
1236  }
1237 
1238  return nullptr;
1239 }
1240 
1242  assert(II.getIntrinsicID() == Intrinsic::ctpop &&
1243  "Expected ctpop intrinsic");
1244  Value *Op0 = II.getArgOperand(0);
1245  Value *X;
1246  // ctpop(bitreverse(x)) -> ctpop(x)
1247  // ctpop(bswap(x)) -> ctpop(x)
1248  if (match(Op0, m_BitReverse(m_Value(X))) || match(Op0, m_BSwap(m_Value(X)))) {
1249  II.setOperand(0, X);
1250  return &II;
1251  }
1252 
1253  // FIXME: Try to simplify vectors of integers.
1254  auto *IT = dyn_cast<IntegerType>(Op0->getType());
1255  if (!IT)
1256  return nullptr;
1257 
1258  unsigned BitWidth = IT->getBitWidth();
1259  KnownBits Known(BitWidth);
1260  IC.computeKnownBits(Op0, Known, 0, &II);
1261 
1262  unsigned MinCount = Known.countMinPopulation();
1263  unsigned MaxCount = Known.countMaxPopulation();
1264 
1265  // Add range metadata since known bits can't completely reflect what we know.
1266  if (IT->getBitWidth() != 1 && !II.getMetadata(LLVMContext::MD_range)) {
1267  Metadata *LowAndHigh[] = {
1269  ConstantAsMetadata::get(ConstantInt::get(IT, MaxCount + 1))};
1272  return &II;
1273  }
1274 
1275  return nullptr;
1276 }
1277 
1278 // TODO: If the x86 backend knew how to convert a bool vector mask back to an
1279 // XMM register mask efficiently, we could transform all x86 masked intrinsics
1280 // to LLVM masked intrinsics and remove the x86 masked intrinsic defs.
1282  Value *Ptr = II.getOperand(0);
1283  Value *Mask = II.getOperand(1);
1284  Constant *ZeroVec = Constant::getNullValue(II.getType());
1285 
1286  // Special case a zero mask since that's not a ConstantDataVector.
1287  // This masked load instruction creates a zero vector.
1288  if (isa<ConstantAggregateZero>(Mask))
1289  return IC.replaceInstUsesWith(II, ZeroVec);
1290 
1291  auto *ConstMask = dyn_cast<ConstantDataVector>(Mask);
1292  if (!ConstMask)
1293  return nullptr;
1294 
1295  // The mask is constant. Convert this x86 intrinsic to the LLVM instrinsic
1296  // to allow target-independent optimizations.
1297 
1298  // First, cast the x86 intrinsic scalar pointer to a vector pointer to match
1299  // the LLVM intrinsic definition for the pointer argument.
1300  unsigned AddrSpace = cast<PointerType>(Ptr->getType())->getAddressSpace();
1301  PointerType *VecPtrTy = PointerType::get(II.getType(), AddrSpace);
1302  Value *PtrCast = IC.Builder.CreateBitCast(Ptr, VecPtrTy, "castvec");
1303 
1304  // Second, convert the x86 XMM integer vector mask to a vector of bools based
1305  // on each element's most significant bit (the sign bit).
1306  Constant *BoolMask = getNegativeIsTrueBoolVec(ConstMask);
1307 
1308  // The pass-through vector for an x86 masked load is a zero vector.
1309  CallInst *NewMaskedLoad =
1310  IC.Builder.CreateMaskedLoad(PtrCast, 1, BoolMask, ZeroVec);
1311  return IC.replaceInstUsesWith(II, NewMaskedLoad);
1312 }
1313 
1314 // TODO: If the x86 backend knew how to convert a bool vector mask back to an
1315 // XMM register mask efficiently, we could transform all x86 masked intrinsics
1316 // to LLVM masked intrinsics and remove the x86 masked intrinsic defs.
1318  Value *Ptr = II.getOperand(0);
1319  Value *Mask = II.getOperand(1);
1320  Value *Vec = II.getOperand(2);
1321 
1322  // Special case a zero mask since that's not a ConstantDataVector:
1323  // this masked store instruction does nothing.
1324  if (isa<ConstantAggregateZero>(Mask)) {
1325  IC.eraseInstFromFunction(II);
1326  return true;
1327  }
1328 
1329  // The SSE2 version is too weird (eg, unaligned but non-temporal) to do
1330  // anything else at this level.
1331  if (II.getIntrinsicID() == Intrinsic::x86_sse2_maskmov_dqu)
1332  return false;
1333 
1334  auto *ConstMask = dyn_cast<ConstantDataVector>(Mask);
1335  if (!ConstMask)
1336  return false;
1337 
1338  // The mask is constant. Convert this x86 intrinsic to the LLVM instrinsic
1339  // to allow target-independent optimizations.
1340 
1341  // First, cast the x86 intrinsic scalar pointer to a vector pointer to match
1342  // the LLVM intrinsic definition for the pointer argument.
1343  unsigned AddrSpace = cast<PointerType>(Ptr->getType())->getAddressSpace();
1344  PointerType *VecPtrTy = PointerType::get(Vec->getType(), AddrSpace);
1345  Value *PtrCast = IC.Builder.CreateBitCast(Ptr, VecPtrTy, "castvec");
1346 
1347  // Second, convert the x86 XMM integer vector mask to a vector of bools based
1348  // on each element's most significant bit (the sign bit).
1349  Constant *BoolMask = getNegativeIsTrueBoolVec(ConstMask);
1350 
1351  IC.Builder.CreateMaskedStore(Vec, PtrCast, 1, BoolMask);
1352 
1353  // 'Replace uses' doesn't work for stores. Erase the original masked store.
1354  IC.eraseInstFromFunction(II);
1355  return true;
1356 }
1357 
1358 // Constant fold llvm.amdgcn.fmed3 intrinsics for standard inputs.
1359 //
1360 // A single NaN input is folded to minnum, so we rely on that folding for
1361 // handling NaNs.
1362 static APFloat fmed3AMDGCN(const APFloat &Src0, const APFloat &Src1,
1363  const APFloat &Src2) {
1364  APFloat Max3 = maxnum(maxnum(Src0, Src1), Src2);
1365 
1366  APFloat::cmpResult Cmp0 = Max3.compare(Src0);
1367  assert(Cmp0 != APFloat::cmpUnordered && "nans handled separately");
1368  if (Cmp0 == APFloat::cmpEqual)
1369  return maxnum(Src1, Src2);
1370 
1371  APFloat::cmpResult Cmp1 = Max3.compare(Src1);
1372  assert(Cmp1 != APFloat::cmpUnordered && "nans handled separately");
1373  if (Cmp1 == APFloat::cmpEqual)
1374  return maxnum(Src0, Src2);
1375 
1376  return maxnum(Src0, Src1);
1377 }
1378 
1379 /// Convert a table lookup to shufflevector if the mask is constant.
1380 /// This could benefit tbl1 if the mask is { 7,6,5,4,3,2,1,0 }, in
1381 /// which case we could lower the shufflevector with rev64 instructions
1382 /// as it's actually a byte reverse.
1384  InstCombiner::BuilderTy &Builder) {
1385  // Bail out if the mask is not a constant.
1386  auto *C = dyn_cast<Constant>(II.getArgOperand(1));
1387  if (!C)
1388  return nullptr;
1389 
1390  auto *VecTy = cast<VectorType>(II.getType());
1391  unsigned NumElts = VecTy->getNumElements();
1392 
1393  // Only perform this transformation for <8 x i8> vector types.
1394  if (!VecTy->getElementType()->isIntegerTy(8) || NumElts != 8)
1395  return nullptr;
1396 
1397  uint32_t Indexes[8];
1398 
1399  for (unsigned I = 0; I < NumElts; ++I) {
1400  Constant *COp = C->getAggregateElement(I);
1401 
1402  if (!COp || !isa<ConstantInt>(COp))
1403  return nullptr;
1404 
1405  Indexes[I] = cast<ConstantInt>(COp)->getLimitedValue();
1406 
1407  // Make sure the mask indices are in range.
1408  if (Indexes[I] >= NumElts)
1409  return nullptr;
1410  }
1411 
1412  auto *ShuffleMask = ConstantDataVector::get(II.getContext(),
1413  makeArrayRef(Indexes));
1414  auto *V1 = II.getArgOperand(0);
1415  auto *V2 = Constant::getNullValue(V1->getType());
1416  return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
1417 }
1418 
1419 /// Convert a vector load intrinsic into a simple llvm load instruction.
1420 /// This is beneficial when the underlying object being addressed comes
1421 /// from a constant, since we get constant-folding for free.
1423  unsigned MemAlign,
1424  InstCombiner::BuilderTy &Builder) {
1425  auto *IntrAlign = dyn_cast<ConstantInt>(II.getArgOperand(1));
1426 
1427  if (!IntrAlign)
1428  return nullptr;
1429 
1430  unsigned Alignment = IntrAlign->getLimitedValue() < MemAlign ?
1431  MemAlign : IntrAlign->getLimitedValue();
1432 
1433  if (!isPowerOf2_32(Alignment))
1434  return nullptr;
1435 
1436  auto *BCastInst = Builder.CreateBitCast(II.getArgOperand(0),
1437  PointerType::get(II.getType(), 0));
1438  return Builder.CreateAlignedLoad(II.getType(), BCastInst, Alignment);
1439 }
1440 
1441 // Returns true iff the 2 intrinsics have the same operands, limiting the
1442 // comparison to the first NumOperands.
1443 static bool haveSameOperands(const IntrinsicInst &I, const IntrinsicInst &E,
1444  unsigned NumOperands) {
1445  assert(I.getNumArgOperands() >= NumOperands && "Not enough operands");
1446  assert(E.getNumArgOperands() >= NumOperands && "Not enough operands");
1447  for (unsigned i = 0; i < NumOperands; i++)
1448  if (I.getArgOperand(i) != E.getArgOperand(i))
1449  return false;
1450  return true;
1451 }
1452 
1453 // Remove trivially empty start/end intrinsic ranges, i.e. a start
1454 // immediately followed by an end (ignoring debuginfo or other
1455 // start/end intrinsics in between). As this handles only the most trivial
1456 // cases, tracking the nesting level is not needed:
1457 //
1458 // call @llvm.foo.start(i1 0) ; &I
1459 // call @llvm.foo.start(i1 0)
1460 // call @llvm.foo.end(i1 0) ; This one will not be skipped: it will be removed
1461 // call @llvm.foo.end(i1 0)
1462 static bool removeTriviallyEmptyRange(IntrinsicInst &I, unsigned StartID,
1463  unsigned EndID, InstCombiner &IC) {
1464  assert(I.getIntrinsicID() == StartID &&
1465  "Start intrinsic does not have expected ID");
1466  BasicBlock::iterator BI(I), BE(I.getParent()->end());
1467  for (++BI; BI != BE; ++BI) {
1468  if (auto *E = dyn_cast<IntrinsicInst>(BI)) {
1469  if (isa<DbgInfoIntrinsic>(E) || E->getIntrinsicID() == StartID)
1470  continue;
1471  if (E->getIntrinsicID() == EndID &&
1472  haveSameOperands(I, *E, E->getNumArgOperands())) {
1473  IC.eraseInstFromFunction(*E);
1474  IC.eraseInstFromFunction(I);
1475  return true;
1476  }
1477  }
1478  break;
1479  }
1480 
1481  return false;
1482 }
1483 
1484 // Convert NVVM intrinsics to target-generic LLVM code where possible.
1486  // Each NVVM intrinsic we can simplify can be replaced with one of:
1487  //
1488  // * an LLVM intrinsic,
1489  // * an LLVM cast operation,
1490  // * an LLVM binary operation, or
1491  // * ad-hoc LLVM IR for the particular operation.
1492 
1493  // Some transformations are only valid when the module's
1494  // flush-denormals-to-zero (ftz) setting is true/false, whereas other
1495  // transformations are valid regardless of the module's ftz setting.
1496  enum FtzRequirementTy {
1497  FTZ_Any, // Any ftz setting is ok.
1498  FTZ_MustBeOn, // Transformation is valid only if ftz is on.
1499  FTZ_MustBeOff, // Transformation is valid only if ftz is off.
1500  };
1501  // Classes of NVVM intrinsics that can't be replaced one-to-one with a
1502  // target-generic intrinsic, cast op, or binary op but that we can nonetheless
1503  // simplify.
1504  enum SpecialCase {
1505  SPC_Reciprocal,
1506  };
1507 
1508  // SimplifyAction is a poor-man's variant (plus an additional flag) that
1509  // represents how to replace an NVVM intrinsic with target-generic LLVM IR.
1510  struct SimplifyAction {
1511  // Invariant: At most one of these Optionals has a value.
1515  Optional<SpecialCase> Special;
1516 
1517  FtzRequirementTy FtzRequirement = FTZ_Any;
1518 
1519  SimplifyAction() = default;
1520 
1521  SimplifyAction(Intrinsic::ID IID, FtzRequirementTy FtzReq)
1522  : IID(IID), FtzRequirement(FtzReq) {}
1523 
1524  // Cast operations don't have anything to do with FTZ, so we skip that
1525  // argument.
1526  SimplifyAction(Instruction::CastOps CastOp) : CastOp(CastOp) {}
1527 
1528  SimplifyAction(Instruction::BinaryOps BinaryOp, FtzRequirementTy FtzReq)
1529  : BinaryOp(BinaryOp), FtzRequirement(FtzReq) {}
1530 
1531  SimplifyAction(SpecialCase Special, FtzRequirementTy FtzReq)
1532  : Special(Special), FtzRequirement(FtzReq) {}
1533  };
1534 
1535  // Try to generate a SimplifyAction describing how to replace our
1536  // IntrinsicInstr with target-generic LLVM IR.
1537  const SimplifyAction Action = [II]() -> SimplifyAction {
1538  switch (II->getIntrinsicID()) {
1539  // NVVM intrinsics that map directly to LLVM intrinsics.
1540  case Intrinsic::nvvm_ceil_d:
1541  return {Intrinsic::ceil, FTZ_Any};
1542  case Intrinsic::nvvm_ceil_f:
1543  return {Intrinsic::ceil, FTZ_MustBeOff};
1544  case Intrinsic::nvvm_ceil_ftz_f:
1545  return {Intrinsic::ceil, FTZ_MustBeOn};
1546  case Intrinsic::nvvm_fabs_d:
1547  return {Intrinsic::fabs, FTZ_Any};
1548  case Intrinsic::nvvm_fabs_f:
1549  return {Intrinsic::fabs, FTZ_MustBeOff};
1550  case Intrinsic::nvvm_fabs_ftz_f:
1551  return {Intrinsic::fabs, FTZ_MustBeOn};
1552  case Intrinsic::nvvm_floor_d:
1553  return {Intrinsic::floor, FTZ_Any};
1554  case Intrinsic::nvvm_floor_f:
1555  return {Intrinsic::floor, FTZ_MustBeOff};
1556  case Intrinsic::nvvm_floor_ftz_f:
1557  return {Intrinsic::floor, FTZ_MustBeOn};
1558  case Intrinsic::nvvm_fma_rn_d:
1559  return {Intrinsic::fma, FTZ_Any};
1560  case Intrinsic::nvvm_fma_rn_f:
1561  return {Intrinsic::fma, FTZ_MustBeOff};
1562  case Intrinsic::nvvm_fma_rn_ftz_f:
1563  return {Intrinsic::fma, FTZ_MustBeOn};
1564  case Intrinsic::nvvm_fmax_d:
1565  return {Intrinsic::maxnum, FTZ_Any};
1566  case Intrinsic::nvvm_fmax_f:
1567  return {Intrinsic::maxnum, FTZ_MustBeOff};
1568  case Intrinsic::nvvm_fmax_ftz_f:
1569  return {Intrinsic::maxnum, FTZ_MustBeOn};
1570  case Intrinsic::nvvm_fmin_d:
1571  return {Intrinsic::minnum, FTZ_Any};
1572  case Intrinsic::nvvm_fmin_f:
1573  return {Intrinsic::minnum, FTZ_MustBeOff};
1574  case Intrinsic::nvvm_fmin_ftz_f:
1575  return {Intrinsic::minnum, FTZ_MustBeOn};
1576  case Intrinsic::nvvm_round_d:
1577  return {Intrinsic::round, FTZ_Any};
1578  case Intrinsic::nvvm_round_f:
1579  return {Intrinsic::round, FTZ_MustBeOff};
1580  case Intrinsic::nvvm_round_ftz_f:
1581  return {Intrinsic::round, FTZ_MustBeOn};
1582  case Intrinsic::nvvm_sqrt_rn_d:
1583  return {Intrinsic::sqrt, FTZ_Any};
1584  case Intrinsic::nvvm_sqrt_f:
1585  // nvvm_sqrt_f is a special case. For most intrinsics, foo_ftz_f is the
1586  // ftz version, and foo_f is the non-ftz version. But nvvm_sqrt_f adopts
1587  // the ftz-ness of the surrounding code. sqrt_rn_f and sqrt_rn_ftz_f are
1588  // the versions with explicit ftz-ness.
1589  return {Intrinsic::sqrt, FTZ_Any};
1590  case Intrinsic::nvvm_sqrt_rn_f:
1591  return {Intrinsic::sqrt, FTZ_MustBeOff};
1592  case Intrinsic::nvvm_sqrt_rn_ftz_f:
1593  return {Intrinsic::sqrt, FTZ_MustBeOn};
1594  case Intrinsic::nvvm_trunc_d:
1595  return {Intrinsic::trunc, FTZ_Any};
1596  case Intrinsic::nvvm_trunc_f:
1597  return {Intrinsic::trunc, FTZ_MustBeOff};
1598  case Intrinsic::nvvm_trunc_ftz_f:
1599  return {Intrinsic::trunc, FTZ_MustBeOn};
1600 
1601  // NVVM intrinsics that map to LLVM cast operations.
1602  //
1603  // Note that llvm's target-generic conversion operators correspond to the rz
1604  // (round to zero) versions of the nvvm conversion intrinsics, even though
1605  // most everything else here uses the rn (round to nearest even) nvvm ops.
1606  case Intrinsic::nvvm_d2i_rz:
1607  case Intrinsic::nvvm_f2i_rz:
1608  case Intrinsic::nvvm_d2ll_rz:
1609  case Intrinsic::nvvm_f2ll_rz:
1610  return {Instruction::FPToSI};
1611  case Intrinsic::nvvm_d2ui_rz:
1612  case Intrinsic::nvvm_f2ui_rz:
1613  case Intrinsic::nvvm_d2ull_rz:
1614  case Intrinsic::nvvm_f2ull_rz:
1615  return {Instruction::FPToUI};
1616  case Intrinsic::nvvm_i2d_rz:
1617  case Intrinsic::nvvm_i2f_rz:
1618  case Intrinsic::nvvm_ll2d_rz:
1619  case Intrinsic::nvvm_ll2f_rz:
1620  return {Instruction::SIToFP};
1621  case Intrinsic::nvvm_ui2d_rz:
1622  case Intrinsic::nvvm_ui2f_rz:
1623  case Intrinsic::nvvm_ull2d_rz:
1624  case Intrinsic::nvvm_ull2f_rz:
1625  return {Instruction::UIToFP};
1626 
1627  // NVVM intrinsics that map to LLVM binary ops.
1628  case Intrinsic::nvvm_add_rn_d:
1629  return {Instruction::FAdd, FTZ_Any};
1630  case Intrinsic::nvvm_add_rn_f:
1631  return {Instruction::FAdd, FTZ_MustBeOff};
1632  case Intrinsic::nvvm_add_rn_ftz_f:
1633  return {Instruction::FAdd, FTZ_MustBeOn};
1634  case Intrinsic::nvvm_mul_rn_d:
1635  return {Instruction::FMul, FTZ_Any};
1636  case Intrinsic::nvvm_mul_rn_f:
1637  return {Instruction::FMul, FTZ_MustBeOff};
1638  case Intrinsic::nvvm_mul_rn_ftz_f:
1639  return {Instruction::FMul, FTZ_MustBeOn};
1640  case Intrinsic::nvvm_div_rn_d:
1641  return {Instruction::FDiv, FTZ_Any};
1642  case Intrinsic::nvvm_div_rn_f:
1643  return {Instruction::FDiv, FTZ_MustBeOff};
1644  case Intrinsic::nvvm_div_rn_ftz_f:
1645  return {Instruction::FDiv, FTZ_MustBeOn};
1646 
1647  // The remainder of cases are NVVM intrinsics that map to LLVM idioms, but
1648  // need special handling.
1649  //
1650  // We seem to be missing intrinsics for rcp.approx.{ftz.}f32, which is just
1651  // as well.
1652  case Intrinsic::nvvm_rcp_rn_d:
1653  return {SPC_Reciprocal, FTZ_Any};
1654  case Intrinsic::nvvm_rcp_rn_f:
1655  return {SPC_Reciprocal, FTZ_MustBeOff};
1656  case Intrinsic::nvvm_rcp_rn_ftz_f:
1657  return {SPC_Reciprocal, FTZ_MustBeOn};
1658 
1659  // We do not currently simplify intrinsics that give an approximate answer.
1660  // These include:
1661  //
1662  // - nvvm_cos_approx_{f,ftz_f}
1663  // - nvvm_ex2_approx_{d,f,ftz_f}
1664  // - nvvm_lg2_approx_{d,f,ftz_f}
1665  // - nvvm_sin_approx_{f,ftz_f}
1666  // - nvvm_sqrt_approx_{f,ftz_f}
1667  // - nvvm_rsqrt_approx_{d,f,ftz_f}
1668  // - nvvm_div_approx_{ftz_d,ftz_f,f}
1669  // - nvvm_rcp_approx_ftz_d
1670  //
1671  // Ideally we'd encode them as e.g. "fast call @llvm.cos", where "fast"
1672  // means that fastmath is enabled in the intrinsic. Unfortunately only
1673  // binary operators (currently) have a fastmath bit in SelectionDAG, so this
1674  // information gets lost and we can't select on it.
1675  //
1676  // TODO: div and rcp are lowered to a binary op, so these we could in theory
1677  // lower them to "fast fdiv".
1678 
1679  default:
1680  return {};
1681  }
1682  }();
1683 
1684  // If Action.FtzRequirementTy is not satisfied by the module's ftz state, we
1685  // can bail out now. (Notice that in the case that IID is not an NVVM
1686  // intrinsic, we don't have to look up any module metadata, as
1687  // FtzRequirementTy will be FTZ_Any.)
1688  if (Action.FtzRequirement != FTZ_Any) {
1689  bool FtzEnabled =
1690  II->getFunction()->getFnAttribute("nvptx-f32ftz").getValueAsString() ==
1691  "true";
1692 
1693  if (FtzEnabled != (Action.FtzRequirement == FTZ_MustBeOn))
1694  return nullptr;
1695  }
1696 
1697  // Simplify to target-generic intrinsic.
1698  if (Action.IID) {
1700  // All the target-generic intrinsics currently of interest to us have one
1701  // type argument, equal to that of the nvvm intrinsic's argument.
1702  Type *Tys[] = {II->getArgOperand(0)->getType()};
1703  return CallInst::Create(
1704  Intrinsic::getDeclaration(II->getModule(), *Action.IID, Tys), Args);
1705  }
1706 
1707  // Simplify to target-generic binary op.
1708  if (Action.BinaryOp)
1709  return BinaryOperator::Create(*Action.BinaryOp, II->getArgOperand(0),
1710  II->getArgOperand(1), II->getName());
1711 
1712  // Simplify to target-generic cast op.
1713  if (Action.CastOp)
1714  return CastInst::Create(*Action.CastOp, II->getArgOperand(0), II->getType(),
1715  II->getName());
1716 
1717  // All that's left are the special cases.
1718  if (!Action.Special)
1719  return nullptr;
1720 
1721  switch (*Action.Special) {
1722  case SPC_Reciprocal:
1723  // Simplify reciprocal.
1724  return BinaryOperator::Create(
1725  Instruction::FDiv, ConstantFP::get(II->getArgOperand(0)->getType(), 1),
1726  II->getArgOperand(0), II->getName());
1727  }
1728  llvm_unreachable("All SpecialCase enumerators should be handled in switch.");
1729 }
1730 
1732  removeTriviallyEmptyRange(I, Intrinsic::vastart, Intrinsic::vaend, *this);
1733  return nullptr;
1734 }
1735 
1737  removeTriviallyEmptyRange(I, Intrinsic::vacopy, Intrinsic::vaend, *this);
1738  return nullptr;
1739 }
1740 
1742  assert(Call.getNumArgOperands() > 1 && "Need at least 2 args to swap");
1743  Value *Arg0 = Call.getArgOperand(0), *Arg1 = Call.getArgOperand(1);
1744  if (isa<Constant>(Arg0) && !isa<Constant>(Arg1)) {
1745  Call.setArgOperand(0, Arg1);
1746  Call.setArgOperand(1, Arg0);
1747  return &Call;
1748  }
1749  return nullptr;
1750 }
1751 
1752 Instruction *InstCombiner::foldIntrinsicWithOverflowCommon(IntrinsicInst *II) {
1753  WithOverflowInst *WO = cast<WithOverflowInst>(II);
1754  Value *OperationResult = nullptr;
1755  Constant *OverflowResult = nullptr;
1756  if (OptimizeOverflowCheck(WO->getBinaryOp(), WO->isSigned(), WO->getLHS(),
1757  WO->getRHS(), *WO, OperationResult, OverflowResult))
1758  return CreateOverflowTuple(WO, OperationResult, OverflowResult);
1759  return nullptr;
1760 }
1761 
1762 /// CallInst simplification. This mostly only handles folding of intrinsic
1763 /// instructions. For normal calls, it allows visitCallBase to do the heavy
1764 /// lifting.
1766  if (Value *V = SimplifyCall(&CI, SQ.getWithInstruction(&CI)))
1767  return replaceInstUsesWith(CI, V);
1768 
1769  if (isFreeCall(&CI, &TLI))
1770  return visitFree(CI);
1771 
1772  // If the caller function is nounwind, mark the call as nounwind, even if the
1773  // callee isn't.
1774  if (CI.getFunction()->doesNotThrow() && !CI.doesNotThrow()) {
1775  CI.setDoesNotThrow();
1776  return &CI;
1777  }
1778 
1779  IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
1780  if (!II) return visitCallBase(CI);
1781 
1782  // Intrinsics cannot occur in an invoke or a callbr, so handle them here
1783  // instead of in visitCallBase.
1784  if (auto *MI = dyn_cast<AnyMemIntrinsic>(II)) {
1785  bool Changed = false;
1786 
1787  // memmove/cpy/set of zero bytes is a noop.
1788  if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
1789  if (NumBytes->isNullValue())
1790  return eraseInstFromFunction(CI);
1791 
1792  if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
1793  if (CI->getZExtValue() == 1) {
1794  // Replace the instruction with just byte operations. We would
1795  // transform other cases to loads/stores, but we don't know if
1796  // alignment is sufficient.
1797  }
1798  }
1799 
1800  // No other transformations apply to volatile transfers.
1801  if (auto *M = dyn_cast<MemIntrinsic>(MI))
1802  if (M->isVolatile())
1803  return nullptr;
1804 
1805  // If we have a memmove and the source operation is a constant global,
1806  // then the source and dest pointers can't alias, so we can change this
1807  // into a call to memcpy.
1808  if (auto *MMI = dyn_cast<AnyMemMoveInst>(MI)) {
1809  if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
1810  if (GVSrc->isConstant()) {
1811  Module *M = CI.getModule();
1812  Intrinsic::ID MemCpyID =
1813  isa<AtomicMemMoveInst>(MMI)
1814  ? Intrinsic::memcpy_element_unordered_atomic
1815  : Intrinsic::memcpy;
1816  Type *Tys[3] = { CI.getArgOperand(0)->getType(),
1817  CI.getArgOperand(1)->getType(),
1818  CI.getArgOperand(2)->getType() };
1819  CI.setCalledFunction(Intrinsic::getDeclaration(M, MemCpyID, Tys));
1820  Changed = true;
1821  }
1822  }
1823 
1824  if (AnyMemTransferInst *MTI = dyn_cast<AnyMemTransferInst>(MI)) {
1825  // memmove(x,x,size) -> noop.
1826  if (MTI->getSource() == MTI->getDest())
1827  return eraseInstFromFunction(CI);
1828  }
1829 
1830  // If we can determine a pointer alignment that is bigger than currently
1831  // set, update the alignment.
1832  if (auto *MTI = dyn_cast<AnyMemTransferInst>(MI)) {
1833  if (Instruction *I = SimplifyAnyMemTransfer(MTI))
1834  return I;
1835  } else if (auto *MSI = dyn_cast<AnyMemSetInst>(MI)) {
1836  if (Instruction *I = SimplifyAnyMemSet(MSI))
1837  return I;
1838  }
1839 
1840  if (Changed) return II;
1841  }
1842 
1843  // For vector result intrinsics, use the generic demanded vector support.
1844  if (II->getType()->isVectorTy()) {
1845  auto VWidth = II->getType()->getVectorNumElements();
1846  APInt UndefElts(VWidth, 0);
1847  APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
1848  if (Value *V = SimplifyDemandedVectorElts(II, AllOnesEltMask, UndefElts)) {
1849  if (V != II)
1850  return replaceInstUsesWith(*II, V);
1851  return II;
1852  }
1853  }
1854 
1855  if (Instruction *I = SimplifyNVVMIntrinsic(II, *this))
1856  return I;
1857 
1858  auto SimplifyDemandedVectorEltsLow = [this](Value *Op, unsigned Width,
1859  unsigned DemandedWidth) {
1860  APInt UndefElts(Width, 0);
1861  APInt DemandedElts = APInt::getLowBitsSet(Width, DemandedWidth);
1862  return SimplifyDemandedVectorElts(Op, DemandedElts, UndefElts);
1863  };
1864 
1865  Intrinsic::ID IID = II->getIntrinsicID();
1866  switch (IID) {
1867  default: break;
1868  case Intrinsic::objectsize:
1869  if (Value *V = lowerObjectSizeCall(II, DL, &TLI, /*MustSucceed=*/false))
1870  return replaceInstUsesWith(CI, V);
1871  return nullptr;
1872  case Intrinsic::bswap: {
1873  Value *IIOperand = II->getArgOperand(0);
1874  Value *X = nullptr;
1875 
1876  // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
1877  if (match(IIOperand, m_Trunc(m_BSwap(m_Value(X))))) {
1878  unsigned C = X->getType()->getPrimitiveSizeInBits() -
1879  IIOperand->getType()->getPrimitiveSizeInBits();
1880  Value *CV = ConstantInt::get(X->getType(), C);
1881  Value *V = Builder.CreateLShr(X, CV);
1882  return new TruncInst(V, IIOperand->getType());
1883  }
1884  break;
1885  }
1886  case Intrinsic::masked_load:
1887  if (Value *SimplifiedMaskedOp = simplifyMaskedLoad(*II))
1888  return replaceInstUsesWith(CI, SimplifiedMaskedOp);
1889  break;
1890  case Intrinsic::masked_store:
1891  return simplifyMaskedStore(*II);
1892  case Intrinsic::masked_gather:
1893  return simplifyMaskedGather(*II);
1894  case Intrinsic::masked_scatter:
1895  return simplifyMaskedScatter(*II);
1896  case Intrinsic::launder_invariant_group:
1897  case Intrinsic::strip_invariant_group:
1898  if (auto *SkippedBarrier = simplifyInvariantGroupIntrinsic(*II, *this))
1899  return replaceInstUsesWith(*II, SkippedBarrier);
1900  break;
1901  case Intrinsic::powi:
1902  if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
1903  // 0 and 1 are handled in instsimplify
1904 
1905  // powi(x, -1) -> 1/x
1906  if (Power->isMinusOne())
1907  return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0),
1908  II->getArgOperand(0));
1909  // powi(x, 2) -> x*x
1910  if (Power->equalsInt(2))
1911  return BinaryOperator::CreateFMul(II->getArgOperand(0),
1912  II->getArgOperand(0));
1913  }
1914  break;
1915 
1916  case Intrinsic::cttz:
1917  case Intrinsic::ctlz:
1918  if (auto *I = foldCttzCtlz(*II, *this))
1919  return I;
1920  break;
1921 
1922  case Intrinsic::ctpop:
1923  if (auto *I = foldCtpop(*II, *this))
1924  return I;
1925  break;
1926 
1927  case Intrinsic::fshl:
1928  case Intrinsic::fshr: {
1929  Value *Op0 = II->getArgOperand(0), *Op1 = II->getArgOperand(1);
1930  Type *Ty = II->getType();
1931  unsigned BitWidth = Ty->getScalarSizeInBits();
1932  Constant *ShAmtC;
1933  if (match(II->getArgOperand(2), m_Constant(ShAmtC)) &&
1934  !isa<ConstantExpr>(ShAmtC) && !ShAmtC->containsConstantExpression()) {
1935  // Canonicalize a shift amount constant operand to modulo the bit-width.
1936  Constant *WidthC = ConstantInt::get(Ty, BitWidth);
1937  Constant *ModuloC = ConstantExpr::getURem(ShAmtC, WidthC);
1938  if (ModuloC != ShAmtC) {
1939  II->setArgOperand(2, ModuloC);
1940  return II;
1941  }
1942  assert(ConstantExpr::getICmp(ICmpInst::ICMP_UGT, WidthC, ShAmtC) ==
1944  "Shift amount expected to be modulo bitwidth");
1945 
1946  // Canonicalize funnel shift right by constant to funnel shift left. This
1947  // is not entirely arbitrary. For historical reasons, the backend may
1948  // recognize rotate left patterns but miss rotate right patterns.
1949  if (IID == Intrinsic::fshr) {
1950  // fshr X, Y, C --> fshl X, Y, (BitWidth - C)
1951  Constant *LeftShiftC = ConstantExpr::getSub(WidthC, ShAmtC);
1952  Module *Mod = II->getModule();
1953  Function *Fshl = Intrinsic::getDeclaration(Mod, Intrinsic::fshl, Ty);
1954  return CallInst::Create(Fshl, { Op0, Op1, LeftShiftC });
1955  }
1956  assert(IID == Intrinsic::fshl &&
1957  "All funnel shifts by simple constants should go left");
1958 
1959  // fshl(X, 0, C) --> shl X, C
1960  // fshl(X, undef, C) --> shl X, C
1961  if (match(Op1, m_ZeroInt()) || match(Op1, m_Undef()))
1962  return BinaryOperator::CreateShl(Op0, ShAmtC);
1963 
1964  // fshl(0, X, C) --> lshr X, (BW-C)
1965  // fshl(undef, X, C) --> lshr X, (BW-C)
1966  if (match(Op0, m_ZeroInt()) || match(Op0, m_Undef()))
1967  return BinaryOperator::CreateLShr(Op1,
1968  ConstantExpr::getSub(WidthC, ShAmtC));
1969  }
1970 
1971  // Left or right might be masked.
1972  if (SimplifyDemandedInstructionBits(*II))
1973  return &CI;
1974 
1975  // The shift amount (operand 2) of a funnel shift is modulo the bitwidth,
1976  // so only the low bits of the shift amount are demanded if the bitwidth is
1977  // a power-of-2.
1978  if (!isPowerOf2_32(BitWidth))
1979  break;
1980  APInt Op2Demanded = APInt::getLowBitsSet(BitWidth, Log2_32_Ceil(BitWidth));
1981  KnownBits Op2Known(BitWidth);
1982  if (SimplifyDemandedBits(II, 2, Op2Demanded, Op2Known))
1983  return &CI;
1984  break;
1985  }
1986  case Intrinsic::uadd_with_overflow:
1987  case Intrinsic::sadd_with_overflow: {
1989  return I;
1990  if (Instruction *I = foldIntrinsicWithOverflowCommon(II))
1991  return I;
1992 
1993  // Given 2 constant operands whose sum does not overflow:
1994  // uaddo (X +nuw C0), C1 -> uaddo X, C0 + C1
1995  // saddo (X +nsw C0), C1 -> saddo X, C0 + C1
1996  Value *X;
1997  const APInt *C0, *C1;
1998  Value *Arg0 = II->getArgOperand(0);
1999  Value *Arg1 = II->getArgOperand(1);
2000  bool IsSigned = IID == Intrinsic::sadd_with_overflow;
2001  bool HasNWAdd = IsSigned ? match(Arg0, m_NSWAdd(m_Value(X), m_APInt(C0)))
2002  : match(Arg0, m_NUWAdd(m_Value(X), m_APInt(C0)));
2003  if (HasNWAdd && match(Arg1, m_APInt(C1))) {
2004  bool Overflow;
2005  APInt NewC =
2006  IsSigned ? C1->sadd_ov(*C0, Overflow) : C1->uadd_ov(*C0, Overflow);
2007  if (!Overflow)
2008  return replaceInstUsesWith(
2009  *II, Builder.CreateBinaryIntrinsic(
2010  IID, X, ConstantInt::get(Arg1->getType(), NewC)));
2011  }
2012  break;
2013  }
2014 
2015  case Intrinsic::umul_with_overflow:
2016  case Intrinsic::smul_with_overflow:
2018  return I;
2020 
2021  case Intrinsic::usub_with_overflow:
2022  if (Instruction *I = foldIntrinsicWithOverflowCommon(II))
2023  return I;
2024  break;
2025 
2026  case Intrinsic::ssub_with_overflow: {
2027  if (Instruction *I = foldIntrinsicWithOverflowCommon(II))
2028  return I;
2029 
2030  Constant *C;
2031  Value *Arg0 = II->getArgOperand(0);
2032  Value *Arg1 = II->getArgOperand(1);
2033  // Given a constant C that is not the minimum signed value
2034  // for an integer of a given bit width:
2035  //
2036  // ssubo X, C -> saddo X, -C
2037  if (match(Arg1, m_Constant(C)) && C->isNotMinSignedValue()) {
2038  Value *NegVal = ConstantExpr::getNeg(C);
2039  // Build a saddo call that is equivalent to the discovered
2040  // ssubo call.
2041  return replaceInstUsesWith(
2042  *II, Builder.CreateBinaryIntrinsic(Intrinsic::sadd_with_overflow,
2043  Arg0, NegVal));
2044  }
2045 
2046  break;
2047  }
2048 
2049  case Intrinsic::uadd_sat:
2050  case Intrinsic::sadd_sat:
2052  return I;
2054  case Intrinsic::usub_sat:
2055  case Intrinsic::ssub_sat: {
2056  SaturatingInst *SI = cast<SaturatingInst>(II);
2057  Type *Ty = SI->getType();
2058  Value *Arg0 = SI->getLHS();
2059  Value *Arg1 = SI->getRHS();
2060 
2061  // Make use of known overflow information.
2062  OverflowResult OR = computeOverflow(SI->getBinaryOp(), SI->isSigned(),
2063  Arg0, Arg1, SI);
2064  switch (OR) {
2066  break;
2068  if (SI->isSigned())
2069  return BinaryOperator::CreateNSW(SI->getBinaryOp(), Arg0, Arg1);
2070  else
2071  return BinaryOperator::CreateNUW(SI->getBinaryOp(), Arg0, Arg1);
2073  unsigned BitWidth = Ty->getScalarSizeInBits();
2074  APInt Min = APSInt::getMinValue(BitWidth, !SI->isSigned());
2075  return replaceInstUsesWith(*SI, ConstantInt::get(Ty, Min));
2076  }
2078  unsigned BitWidth = Ty->getScalarSizeInBits();
2079  APInt Max = APSInt::getMaxValue(BitWidth, !SI->isSigned());
2080  return replaceInstUsesWith(*SI, ConstantInt::get(Ty, Max));
2081  }
2082  }
2083 
2084  // ssub.sat(X, C) -> sadd.sat(X, -C) if C != MIN
2085  Constant *C;
2086  if (IID == Intrinsic::ssub_sat && match(Arg1, m_Constant(C)) &&
2087  C->isNotMinSignedValue()) {
2088  Value *NegVal = ConstantExpr::getNeg(C);
2089  return replaceInstUsesWith(
2090  *II, Builder.CreateBinaryIntrinsic(
2091  Intrinsic::sadd_sat, Arg0, NegVal));
2092  }
2093 
2094  // sat(sat(X + Val2) + Val) -> sat(X + (Val+Val2))
2095  // sat(sat(X - Val2) - Val) -> sat(X - (Val+Val2))
2096  // if Val and Val2 have the same sign
2097  if (auto *Other = dyn_cast<IntrinsicInst>(Arg0)) {
2098  Value *X;
2099  const APInt *Val, *Val2;
2100  APInt NewVal;
2101  bool IsUnsigned =
2102  IID == Intrinsic::uadd_sat || IID == Intrinsic::usub_sat;
2103  if (Other->getIntrinsicID() == IID &&
2104  match(Arg1, m_APInt(Val)) &&
2105  match(Other->getArgOperand(0), m_Value(X)) &&
2106  match(Other->getArgOperand(1), m_APInt(Val2))) {
2107  if (IsUnsigned)
2108  NewVal = Val->uadd_sat(*Val2);
2109  else if (Val->isNonNegative() == Val2->isNonNegative()) {
2110  bool Overflow;
2111  NewVal = Val->sadd_ov(*Val2, Overflow);
2112  if (Overflow) {
2113  // Both adds together may add more than SignedMaxValue
2114  // without saturating the final result.
2115  break;
2116  }
2117  } else {
2118  // Cannot fold saturated addition with different signs.
2119  break;
2120  }
2121 
2122  return replaceInstUsesWith(
2123  *II, Builder.CreateBinaryIntrinsic(
2124  IID, X, ConstantInt::get(II->getType(), NewVal)));
2125  }
2126  }
2127  break;
2128  }
2129 
2130  case Intrinsic::minnum:
2131  case Intrinsic::maxnum:
2132  case Intrinsic::minimum:
2133  case Intrinsic::maximum: {
2135  return I;
2136  Value *Arg0 = II->getArgOperand(0);
2137  Value *Arg1 = II->getArgOperand(1);
2138  Value *X, *Y;
2139  if (match(Arg0, m_FNeg(m_Value(X))) && match(Arg1, m_FNeg(m_Value(Y))) &&
2140  (Arg0->hasOneUse() || Arg1->hasOneUse())) {
2141  // If both operands are negated, invert the call and negate the result:
2142  // min(-X, -Y) --> -(max(X, Y))
2143  // max(-X, -Y) --> -(min(X, Y))
2144  Intrinsic::ID NewIID;
2145  switch (IID) {
2146  case Intrinsic::maxnum:
2147  NewIID = Intrinsic::minnum;
2148  break;
2149  case Intrinsic::minnum:
2150  NewIID = Intrinsic::maxnum;
2151  break;
2152  case Intrinsic::maximum:
2153  NewIID = Intrinsic::minimum;
2154  break;
2155  case Intrinsic::minimum:
2156  NewIID = Intrinsic::maximum;
2157  break;
2158  default:
2159  llvm_unreachable("unexpected intrinsic ID");
2160  }
2161  Value *NewCall = Builder.CreateBinaryIntrinsic(NewIID, X, Y, II);
2162  Instruction *FNeg = BinaryOperator::CreateFNeg(NewCall);
2163  FNeg->copyIRFlags(II);
2164  return FNeg;
2165  }
2166 
2167  // m(m(X, C2), C1) -> m(X, C)
2168  const APFloat *C1, *C2;
2169  if (auto *M = dyn_cast<IntrinsicInst>(Arg0)) {
2170  if (M->getIntrinsicID() == IID && match(Arg1, m_APFloat(C1)) &&
2171  ((match(M->getArgOperand(0), m_Value(X)) &&
2172  match(M->getArgOperand(1), m_APFloat(C2))) ||
2173  (match(M->getArgOperand(1), m_Value(X)) &&
2174  match(M->getArgOperand(0), m_APFloat(C2))))) {
2175  APFloat Res(0.0);
2176  switch (IID) {
2177  case Intrinsic::maxnum:
2178  Res = maxnum(*C1, *C2);
2179  break;
2180  case Intrinsic::minnum:
2181  Res = minnum(*C1, *C2);
2182  break;
2183  case Intrinsic::maximum:
2184  Res = maximum(*C1, *C2);
2185  break;
2186  case Intrinsic::minimum:
2187  Res = minimum(*C1, *C2);
2188  break;
2189  default:
2190  llvm_unreachable("unexpected intrinsic ID");
2191  }
2192  Instruction *NewCall = Builder.CreateBinaryIntrinsic(
2193  IID, X, ConstantFP::get(Arg0->getType(), Res));
2194  NewCall->copyIRFlags(II);
2195  return replaceInstUsesWith(*II, NewCall);
2196  }
2197  }
2198 
2199  break;
2200  }
2201  case Intrinsic::fmuladd: {
2202  // Canonicalize fast fmuladd to the separate fmul + fadd.
2203  if (II->isFast()) {
2204  BuilderTy::FastMathFlagGuard Guard(Builder);
2205  Builder.setFastMathFlags(II->getFastMathFlags());
2206  Value *Mul = Builder.CreateFMul(II->getArgOperand(0),
2207  II->getArgOperand(1));
2208  Value *Add = Builder.CreateFAdd(Mul, II->getArgOperand(2));
2209  Add->takeName(II);
2210  return replaceInstUsesWith(*II, Add);
2211  }
2212 
2214  }
2215  case Intrinsic::fma: {
2217  return I;
2218 
2219  // fma fneg(x), fneg(y), z -> fma x, y, z
2220  Value *Src0 = II->getArgOperand(0);
2221  Value *Src1 = II->getArgOperand(1);
2222  Value *X, *Y;
2223  if (match(Src0, m_FNeg(m_Value(X))) && match(Src1, m_FNeg(m_Value(Y)))) {
2224  II->setArgOperand(0, X);
2225  II->setArgOperand(1, Y);
2226  return II;
2227  }
2228 
2229  // fma fabs(x), fabs(x), z -> fma x, x, z
2230  if (match(Src0, m_FAbs(m_Value(X))) &&
2231  match(Src1, m_FAbs(m_Specific(X)))) {
2232  II->setArgOperand(0, X);
2233  II->setArgOperand(1, X);
2234  return II;
2235  }
2236 
2237  // fma x, 1, z -> fadd x, z
2238  if (match(Src1, m_FPOne())) {
2239  auto *FAdd = BinaryOperator::CreateFAdd(Src0, II->getArgOperand(2));
2240  FAdd->copyFastMathFlags(II);
2241  return FAdd;
2242  }
2243 
2244  break;
2245  }
2246  case Intrinsic::fabs: {
2247  Value *Cond;
2248  Constant *LHS, *RHS;
2249  if (match(II->getArgOperand(0),
2250  m_Select(m_Value(Cond), m_Constant(LHS), m_Constant(RHS)))) {
2251  CallInst *Call0 = Builder.CreateCall(II->getCalledFunction(), {LHS});
2252  CallInst *Call1 = Builder.CreateCall(II->getCalledFunction(), {RHS});
2253  return SelectInst::Create(Cond, Call0, Call1);
2254  }
2255 
2257  }
2258  case Intrinsic::ceil:
2259  case Intrinsic::floor:
2260  case Intrinsic::round:
2261  case Intrinsic::nearbyint:
2262  case Intrinsic::rint:
2263  case Intrinsic::trunc: {
2264  Value *ExtSrc;
2265  if (match(II->getArgOperand(0), m_OneUse(m_FPExt(m_Value(ExtSrc))))) {
2266  // Narrow the call: intrinsic (fpext x) -> fpext (intrinsic x)
2267  Value *NarrowII = Builder.CreateUnaryIntrinsic(IID, ExtSrc, II);
2268  return new FPExtInst(NarrowII, II->getType());
2269  }
2270  break;
2271  }
2272  case Intrinsic::cos:
2273  case Intrinsic::amdgcn_cos: {
2274  Value *X;
2275  Value *Src = II->getArgOperand(0);
2276  if (match(Src, m_FNeg(m_Value(X))) || match(Src, m_FAbs(m_Value(X)))) {
2277  // cos(-x) -> cos(x)
2278  // cos(fabs(x)) -> cos(x)
2279  II->setArgOperand(0, X);
2280  return II;
2281  }
2282  break;
2283  }
2284  case Intrinsic::sin: {
2285  Value *X;
2286  if (match(II->getArgOperand(0), m_OneUse(m_FNeg(m_Value(X))))) {
2287  // sin(-x) --> -sin(x)
2288  Value *NewSin = Builder.CreateUnaryIntrinsic(Intrinsic::sin, X, II);
2289  Instruction *FNeg = BinaryOperator::CreateFNeg(NewSin);
2290  FNeg->copyFastMathFlags(II);
2291  return FNeg;
2292  }
2293  break;
2294  }
2295  case Intrinsic::ppc_altivec_lvx:
2296  case Intrinsic::ppc_altivec_lvxl:
2297  // Turn PPC lvx -> load if the pointer is known aligned.
2298  if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, II, &AC,
2299  &DT) >= 16) {
2300  Value *Ptr = Builder.CreateBitCast(II->getArgOperand(0),
2301  PointerType::getUnqual(II->getType()));
2302  return new LoadInst(II->getType(), Ptr);
2303  }
2304  break;
2305  case Intrinsic::ppc_vsx_lxvw4x:
2306  case Intrinsic::ppc_vsx_lxvd2x: {
2307  // Turn PPC VSX loads into normal loads.
2308  Value *Ptr = Builder.CreateBitCast(II->getArgOperand(0),
2309  PointerType::getUnqual(II->getType()));
2310  return new LoadInst(II->getType(), Ptr, Twine(""), false, 1);
2311  }
2312  case Intrinsic::ppc_altivec_stvx:
2313  case Intrinsic::ppc_altivec_stvxl:
2314  // Turn stvx -> store if the pointer is known aligned.
2315  if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, DL, II, &AC,
2316  &DT) >= 16) {
2317  Type *OpPtrTy =
2318  PointerType::getUnqual(II->getArgOperand(0)->getType());
2319  Value *Ptr = Builder.CreateBitCast(II->getArgOperand(1), OpPtrTy);
2320  return new StoreInst(II->getArgOperand(0), Ptr);
2321  }
2322  break;
2323  case Intrinsic::ppc_vsx_stxvw4x:
2324  case Intrinsic::ppc_vsx_stxvd2x: {
2325  // Turn PPC VSX stores into normal stores.
2326  Type *OpPtrTy = PointerType::getUnqual(II->getArgOperand(0)->getType());
2327  Value *Ptr = Builder.CreateBitCast(II->getArgOperand(1), OpPtrTy);
2328  return new StoreInst(II->getArgOperand(0), Ptr, false, 1);
2329  }
2330  case Intrinsic::ppc_qpx_qvlfs:
2331  // Turn PPC QPX qvlfs -> load if the pointer is known aligned.
2332  if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, II, &AC,
2333  &DT) >= 16) {
2334  Type *VTy = VectorType::get(Builder.getFloatTy(),
2335  II->getType()->getVectorNumElements());
2336  Value *Ptr = Builder.CreateBitCast(II->getArgOperand(0),
2337  PointerType::getUnqual(VTy));
2338  Value *Load = Builder.CreateLoad(VTy, Ptr);
2339  return new FPExtInst(Load, II->getType());
2340  }
2341  break;
2342  case Intrinsic::ppc_qpx_qvlfd:
2343  // Turn PPC QPX qvlfd -> load if the pointer is known aligned.
2344  if (getOrEnforceKnownAlignment(II->getArgOperand(0), 32, DL, II, &AC,
2345  &DT) >= 32) {
2346  Value *Ptr = Builder.CreateBitCast(II->getArgOperand(0),
2347  PointerType::getUnqual(II->getType()));
2348  return new LoadInst(II->getType(), Ptr);
2349  }
2350  break;
2351  case Intrinsic::ppc_qpx_qvstfs:
2352  // Turn PPC QPX qvstfs -> store if the pointer is known aligned.
2353  if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, DL, II, &AC,
2354  &DT) >= 16) {
2355  Type *VTy = VectorType::get(Builder.getFloatTy(),
2356  II->getArgOperand(0)->getType()->getVectorNumElements());
2357  Value *TOp = Builder.CreateFPTrunc(II->getArgOperand(0), VTy);
2358  Type *OpPtrTy = PointerType::getUnqual(VTy);
2359  Value *Ptr = Builder.CreateBitCast(II->getArgOperand(1), OpPtrTy);
2360  return new StoreInst(TOp, Ptr);
2361  }
2362  break;
2363  case Intrinsic::ppc_qpx_qvstfd:
2364  // Turn PPC QPX qvstfd -> store if the pointer is known aligned.
2365  if (getOrEnforceKnownAlignment(II->getArgOperand(1), 32, DL, II, &AC,
2366  &DT) >= 32) {
2367  Type *OpPtrTy =
2368  PointerType::getUnqual(II->getArgOperand(0)->getType());
2369  Value *Ptr = Builder.CreateBitCast(II->getArgOperand(1), OpPtrTy);
2370  return new StoreInst(II->getArgOperand(0), Ptr);
2371  }
2372  break;
2373 
2374  case Intrinsic::x86_bmi_bextr_32:
2375  case Intrinsic::x86_bmi_bextr_64:
2376  case Intrinsic::x86_tbm_bextri_u32:
2377  case Intrinsic::x86_tbm_bextri_u64:
2378  // If the RHS is a constant we can try some simplifications.
2379  if (auto *C = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
2380  uint64_t Shift = C->getZExtValue();
2381  uint64_t Length = (Shift >> 8) & 0xff;
2382  Shift &= 0xff;
2383  unsigned BitWidth = II->getType()->getIntegerBitWidth();
2384  // If the length is 0 or the shift is out of range, replace with zero.
2385  if (Length == 0 || Shift >= BitWidth)
2386  return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), 0));
2387  // If the LHS is also a constant, we can completely constant fold this.
2388  if (auto *InC = dyn_cast<ConstantInt>(II->getArgOperand(0))) {
2389  uint64_t Result = InC->getZExtValue() >> Shift;
2390  if (Length > BitWidth)
2391  Length = BitWidth;
2392  Result &= maskTrailingOnes<uint64_t>(Length);
2393  return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), Result));
2394  }
2395  // TODO should we turn this into 'and' if shift is 0? Or 'shl' if we
2396  // are only masking bits that a shift already cleared?
2397  }
2398  break;
2399 
2400  case Intrinsic::x86_bmi_bzhi_32:
2401  case Intrinsic::x86_bmi_bzhi_64:
2402  // If the RHS is a constant we can try some simplifications.
2403  if (auto *C = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
2404  uint64_t Index = C->getZExtValue() & 0xff;
2405  unsigned BitWidth = II->getType()->getIntegerBitWidth();
2406  if (Index >= BitWidth)
2407  return replaceInstUsesWith(CI, II->getArgOperand(0));
2408  if (Index == 0)
2409  return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), 0));
2410  // If the LHS is also a constant, we can completely constant fold this.
2411  if (auto *InC = dyn_cast<ConstantInt>(II->getArgOperand(0))) {
2412  uint64_t Result = InC->getZExtValue();
2413  Result &= maskTrailingOnes<uint64_t>(Index);
2414  return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), Result));
2415  }
2416  // TODO should we convert this to an AND if the RHS is constant?
2417  }
2418  break;
2419 
2420  case Intrinsic::x86_vcvtph2ps_128:
2421  case Intrinsic::x86_vcvtph2ps_256: {
2422  auto Arg = II->getArgOperand(0);
2423  auto ArgType = cast<VectorType>(Arg->getType());
2424  auto RetType = cast<VectorType>(II->getType());
2425  unsigned ArgWidth = ArgType->getNumElements();
2426  unsigned RetWidth = RetType->getNumElements();
2427  assert(RetWidth <= ArgWidth && "Unexpected input/return vector widths");
2428  assert(ArgType->isIntOrIntVectorTy() &&
2429  ArgType->getScalarSizeInBits() == 16 &&
2430  "CVTPH2PS input type should be 16-bit integer vector");
2431  assert(RetType->getScalarType()->isFloatTy() &&
2432  "CVTPH2PS output type should be 32-bit float vector");
2433 
2434  // Constant folding: Convert to generic half to single conversion.
2435  if (isa<ConstantAggregateZero>(Arg))
2436  return replaceInstUsesWith(*II, ConstantAggregateZero::get(RetType));
2437 
2438  if (isa<ConstantDataVector>(Arg)) {
2439  auto VectorHalfAsShorts = Arg;
2440  if (RetWidth < ArgWidth) {
2441  SmallVector<uint32_t, 8> SubVecMask;
2442  for (unsigned i = 0; i != RetWidth; ++i)
2443  SubVecMask.push_back((int)i);
2444  VectorHalfAsShorts = Builder.CreateShuffleVector(
2445  Arg, UndefValue::get(ArgType), SubVecMask);
2446  }
2447 
2448  auto VectorHalfType =
2449  VectorType::get(Type::getHalfTy(II->getContext()), RetWidth);
2450  auto VectorHalfs =
2451  Builder.CreateBitCast(VectorHalfAsShorts, VectorHalfType);
2452  auto VectorFloats = Builder.CreateFPExt(VectorHalfs, RetType);
2453  return replaceInstUsesWith(*II, VectorFloats);
2454  }
2455 
2456  // We only use the lowest lanes of the argument.
2457  if (Value *V = SimplifyDemandedVectorEltsLow(Arg, ArgWidth, RetWidth)) {
2458  II->setArgOperand(0, V);
2459  return II;
2460  }
2461  break;
2462  }
2463 
2464  case Intrinsic::x86_sse_cvtss2si:
2465  case Intrinsic::x86_sse_cvtss2si64:
2466  case Intrinsic::x86_sse_cvttss2si:
2467  case Intrinsic::x86_sse_cvttss2si64:
2468  case Intrinsic::x86_sse2_cvtsd2si:
2469  case Intrinsic::x86_sse2_cvtsd2si64:
2470  case Intrinsic::x86_sse2_cvttsd2si:
2471  case Intrinsic::x86_sse2_cvttsd2si64:
2472  case Intrinsic::x86_avx512_vcvtss2si32:
2473  case Intrinsic::x86_avx512_vcvtss2si64:
2474  case Intrinsic::x86_avx512_vcvtss2usi32:
2475  case Intrinsic::x86_avx512_vcvtss2usi64:
2476  case Intrinsic::x86_avx512_vcvtsd2si32:
2477  case Intrinsic::x86_avx512_vcvtsd2si64:
2478  case Intrinsic::x86_avx512_vcvtsd2usi32:
2479  case Intrinsic::x86_avx512_vcvtsd2usi64:
2480  case Intrinsic::x86_avx512_cvttss2si:
2481  case Intrinsic::x86_avx512_cvttss2si64:
2482  case Intrinsic::x86_avx512_cvttss2usi:
2483  case Intrinsic::x86_avx512_cvttss2usi64:
2484  case Intrinsic::x86_avx512_cvttsd2si:
2485  case Intrinsic::x86_avx512_cvttsd2si64:
2486  case Intrinsic::x86_avx512_cvttsd2usi:
2487  case Intrinsic::x86_avx512_cvttsd2usi64: {
2488  // These intrinsics only demand the 0th element of their input vectors. If
2489  // we can simplify the input based on that, do so now.
2490  Value *Arg = II->getArgOperand(0);
2491  unsigned VWidth = Arg->getType()->getVectorNumElements();
2492  if (Value *V = SimplifyDemandedVectorEltsLow(Arg, VWidth, 1)) {
2493  II->setArgOperand(0, V);
2494  return II;
2495  }
2496  break;
2497  }
2498 
2499  case Intrinsic::x86_mmx_pmovmskb:
2500  case Intrinsic::x86_sse_movmsk_ps:
2501  case Intrinsic::x86_sse2_movmsk_pd:
2502  case Intrinsic::x86_sse2_pmovmskb_128:
2503  case Intrinsic::x86_avx_movmsk_pd_256:
2504  case Intrinsic::x86_avx_movmsk_ps_256:
2505  case Intrinsic::x86_avx2_pmovmskb:
2506  if (Value *V = simplifyX86movmsk(*II, Builder))
2507  return replaceInstUsesWith(*II, V);
2508  break;
2509 
2510  case Intrinsic::x86_sse_comieq_ss:
2511  case Intrinsic::x86_sse_comige_ss:
2512  case Intrinsic::x86_sse_comigt_ss:
2513  case Intrinsic::x86_sse_comile_ss:
2514  case Intrinsic::x86_sse_comilt_ss:
2515  case Intrinsic::x86_sse_comineq_ss:
2516  case Intrinsic::x86_sse_ucomieq_ss:
2517  case Intrinsic::x86_sse_ucomige_ss:
2518  case Intrinsic::x86_sse_ucomigt_ss:
2519  case Intrinsic::x86_sse_ucomile_ss:
2520  case Intrinsic::x86_sse_ucomilt_ss:
2521  case Intrinsic::x86_sse_ucomineq_ss:
2522  case Intrinsic::x86_sse2_comieq_sd:
2523  case Intrinsic::x86_sse2_comige_sd:
2524  case Intrinsic::x86_sse2_comigt_sd:
2525  case Intrinsic::x86_sse2_comile_sd:
2526  case Intrinsic::x86_sse2_comilt_sd:
2527  case Intrinsic::x86_sse2_comineq_sd:
2528  case Intrinsic::x86_sse2_ucomieq_sd:
2529  case Intrinsic::x86_sse2_ucomige_sd:
2530  case Intrinsic::x86_sse2_ucomigt_sd:
2531  case Intrinsic::x86_sse2_ucomile_sd:
2532  case Intrinsic::x86_sse2_ucomilt_sd:
2533  case Intrinsic::x86_sse2_ucomineq_sd:
2534  case Intrinsic::x86_avx512_vcomi_ss:
2535  case Intrinsic::x86_avx512_vcomi_sd:
2536  case Intrinsic::x86_avx512_mask_cmp_ss:
2537  case Intrinsic::x86_avx512_mask_cmp_sd: {
2538  // These intrinsics only demand the 0th element of their input vectors. If
2539  // we can simplify the input based on that, do so now.
2540  bool MadeChange = false;
2541  Value *Arg0 = II->getArgOperand(0);
2542  Value *Arg1 = II->getArgOperand(1);
2543  unsigned VWidth = Arg0->getType()->getVectorNumElements();
2544  if (Value *V = SimplifyDemandedVectorEltsLow(Arg0, VWidth, 1)) {
2545  II->setArgOperand(0, V);
2546  MadeChange = true;
2547  }
2548  if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, 1)) {
2549  II->setArgOperand(1, V);
2550  MadeChange = true;
2551  }
2552  if (MadeChange)
2553  return II;
2554  break;
2555  }
2556  case Intrinsic::x86_avx512_cmp_pd_128:
2557  case Intrinsic::x86_avx512_cmp_pd_256:
2558  case Intrinsic::x86_avx512_cmp_pd_512:
2559  case Intrinsic::x86_avx512_cmp_ps_128:
2560  case Intrinsic::x86_avx512_cmp_ps_256:
2561  case Intrinsic::x86_avx512_cmp_ps_512: {
2562  // Folding cmp(sub(a,b),0) -> cmp(a,b) and cmp(0,sub(a,b)) -> cmp(b,a)
2563  Value *Arg0 = II->getArgOperand(0);
2564  Value *Arg1 = II->getArgOperand(1);
2565  bool Arg0IsZero = match(Arg0, m_PosZeroFP());
2566  if (Arg0IsZero)
2567  std::swap(Arg0, Arg1);
2568  Value *A, *B;
2569  // This fold requires only the NINF(not +/- inf) since inf minus
2570  // inf is nan.
2571  // NSZ(No Signed Zeros) is not needed because zeros of any sign are
2572  // equal for both compares.
2573  // NNAN is not needed because nans compare the same for both compares.
2574  // The compare intrinsic uses the above assumptions and therefore
2575  // doesn't require additional flags.
2576  if ((match(Arg0, m_OneUse(m_FSub(m_Value(A), m_Value(B)))) &&
2577  match(Arg1, m_PosZeroFP()) && isa<Instruction>(Arg0) &&
2578  cast<Instruction>(Arg0)->getFastMathFlags().noInfs())) {
2579  if (Arg0IsZero)
2580  std::swap(A, B);
2581  II->setArgOperand(0, A);
2582  II->setArgOperand(1, B);
2583  return II;
2584  }
2585  break;
2586  }
2587 
2588  case Intrinsic::x86_avx512_add_ps_512:
2589  case Intrinsic::x86_avx512_div_ps_512:
2590  case Intrinsic::x86_avx512_mul_ps_512:
2591  case Intrinsic::x86_avx512_sub_ps_512:
2592  case Intrinsic::x86_avx512_add_pd_512:
2593  case Intrinsic::x86_avx512_div_pd_512:
2594  case Intrinsic::x86_avx512_mul_pd_512:
2595  case Intrinsic::x86_avx512_sub_pd_512:
2596  // If the rounding mode is CUR_DIRECTION(4) we can turn these into regular
2597  // IR operations.
2598  if (auto *R = dyn_cast<ConstantInt>(II->getArgOperand(2))) {
2599  if (R->getValue() == 4) {
2600  Value *Arg0 = II->getArgOperand(0);
2601  Value *Arg1 = II->getArgOperand(1);
2602 
2603  Value *V;
2604  switch (IID) {
2605  default: llvm_unreachable("Case stmts out of sync!");
2606  case Intrinsic::x86_avx512_add_ps_512:
2607  case Intrinsic::x86_avx512_add_pd_512:
2608  V = Builder.CreateFAdd(Arg0, Arg1);
2609  break;
2610  case Intrinsic::x86_avx512_sub_ps_512:
2611  case Intrinsic::x86_avx512_sub_pd_512:
2612  V = Builder.CreateFSub(Arg0, Arg1);
2613  break;
2614  case Intrinsic::x86_avx512_mul_ps_512:
2615  case Intrinsic::x86_avx512_mul_pd_512:
2616  V = Builder.CreateFMul(Arg0, Arg1);
2617  break;
2618  case Intrinsic::x86_avx512_div_ps_512:
2619  case Intrinsic::x86_avx512_div_pd_512:
2620  V = Builder.CreateFDiv(Arg0, Arg1);
2621  break;
2622  }
2623 
2624  return replaceInstUsesWith(*II, V);
2625  }
2626  }
2627  break;
2628 
2629  case Intrinsic::x86_avx512_mask_add_ss_round:
2630  case Intrinsic::x86_avx512_mask_div_ss_round:
2631  case Intrinsic::x86_avx512_mask_mul_ss_round:
2632  case Intrinsic::x86_avx512_mask_sub_ss_round:
2633  case Intrinsic::x86_avx512_mask_add_sd_round:
2634  case Intrinsic::x86_avx512_mask_div_sd_round:
2635  case Intrinsic::x86_avx512_mask_mul_sd_round:
2636  case Intrinsic::x86_avx512_mask_sub_sd_round:
2637  // If the rounding mode is CUR_DIRECTION(4) we can turn these into regular
2638  // IR operations.
2639  if (auto *R = dyn_cast<ConstantInt>(II->getArgOperand(4))) {
2640  if (R->getValue() == 4) {
2641  // Extract the element as scalars.
2642  Value *Arg0 = II->getArgOperand(0);
2643  Value *Arg1 = II->getArgOperand(1);
2644  Value *LHS = Builder.CreateExtractElement(Arg0, (uint64_t)0);
2645  Value *RHS = Builder.CreateExtractElement(Arg1, (uint64_t)0);
2646 
2647  Value *V;
2648  switch (IID) {
2649  default: llvm_unreachable("Case stmts out of sync!");
2650  case Intrinsic::x86_avx512_mask_add_ss_round:
2651  case Intrinsic::x86_avx512_mask_add_sd_round:
2652  V = Builder.CreateFAdd(LHS, RHS);
2653  break;
2654  case Intrinsic::x86_avx512_mask_sub_ss_round:
2655  case Intrinsic::x86_avx512_mask_sub_sd_round:
2656  V = Builder.CreateFSub(LHS, RHS);
2657  break;
2658  case Intrinsic::x86_avx512_mask_mul_ss_round:
2659  case Intrinsic::x86_avx512_mask_mul_sd_round:
2660  V = Builder.CreateFMul(LHS, RHS);
2661  break;
2662  case Intrinsic::x86_avx512_mask_div_ss_round:
2663  case Intrinsic::x86_avx512_mask_div_sd_round:
2664  V = Builder.CreateFDiv(LHS, RHS);
2665  break;
2666  }
2667 
2668  // Handle the masking aspect of the intrinsic.
2669  Value *Mask = II->getArgOperand(3);
2670  auto *C = dyn_cast<ConstantInt>(Mask);
2671  // We don't need a select if we know the mask bit is a 1.
2672  if (!C || !C->getValue()[0]) {
2673  // Cast the mask to an i1 vector and then extract the lowest element.
2674  auto *MaskTy = VectorType::get(Builder.getInt1Ty(),
2675  cast<IntegerType>(Mask->getType())->getBitWidth());
2676  Mask = Builder.CreateBitCast(Mask, MaskTy);
2677  Mask = Builder.CreateExtractElement(Mask, (uint64_t)0);
2678  // Extract the lowest element from the passthru operand.
2679  Value *Passthru = Builder.CreateExtractElement(II->getArgOperand(2),
2680  (uint64_t)0);
2681  V = Builder.CreateSelect(Mask, V, Passthru);
2682  }
2683 
2684  // Insert the result back into the original argument 0.
2685  V = Builder.CreateInsertElement(Arg0, V, (uint64_t)0);
2686 
2687  return replaceInstUsesWith(*II, V);
2688  }
2689  }
2690  break;
2691 
2692  // Constant fold ashr( <A x Bi>, Ci ).
2693  // Constant fold lshr( <A x Bi>, Ci ).
2694  // Constant fold shl( <A x Bi>, Ci ).
2695  case Intrinsic::x86_sse2_psrai_d:
2696  case Intrinsic::x86_sse2_psrai_w:
2697  case Intrinsic::x86_avx2_psrai_d:
2698  case Intrinsic::x86_avx2_psrai_w:
2699  case Intrinsic::x86_avx512_psrai_q_128:
2700  case Intrinsic::x86_avx512_psrai_q_256:
2701  case Intrinsic::x86_avx512_psrai_d_512:
2702  case Intrinsic::x86_avx512_psrai_q_512:
2703  case Intrinsic::x86_avx512_psrai_w_512:
2704  case Intrinsic::x86_sse2_psrli_d:
2705  case Intrinsic::x86_sse2_psrli_q:
2706  case Intrinsic::x86_sse2_psrli_w:
2707  case Intrinsic::x86_avx2_psrli_d:
2708  case Intrinsic::x86_avx2_psrli_q:
2709  case Intrinsic::x86_avx2_psrli_w:
2710  case Intrinsic::x86_avx512_psrli_d_512:
2711  case Intrinsic::x86_avx512_psrli_q_512:
2712  case Intrinsic::x86_avx512_psrli_w_512:
2713  case Intrinsic::x86_sse2_pslli_d:
2714  case Intrinsic::x86_sse2_pslli_q:
2715  case Intrinsic::x86_sse2_pslli_w:
2716  case Intrinsic::x86_avx2_pslli_d:
2717  case Intrinsic::x86_avx2_pslli_q:
2718  case Intrinsic::x86_avx2_pslli_w:
2719  case Intrinsic::x86_avx512_pslli_d_512:
2720  case Intrinsic::x86_avx512_pslli_q_512:
2721  case Intrinsic::x86_avx512_pslli_w_512:
2722  if (Value *V = simplifyX86immShift(*II, Builder))
2723  return replaceInstUsesWith(*II, V);
2724  break;
2725 
2726  case Intrinsic::x86_sse2_psra_d:
2727  case Intrinsic::x86_sse2_psra_w:
2728  case Intrinsic::x86_avx2_psra_d:
2729  case Intrinsic::x86_avx2_psra_w:
2730  case Intrinsic::x86_avx512_psra_q_128:
2731  case Intrinsic::x86_avx512_psra_q_256:
2732  case Intrinsic::x86_avx512_psra_d_512:
2733  case Intrinsic::x86_avx512_psra_q_512:
2734  case Intrinsic::x86_avx512_psra_w_512:
2735  case Intrinsic::x86_sse2_psrl_d:
2736  case Intrinsic::x86_sse2_psrl_q:
2737  case Intrinsic::x86_sse2_psrl_w:
2738  case Intrinsic::x86_avx2_psrl_d:
2739  case Intrinsic::x86_avx2_psrl_q:
2740  case Intrinsic::x86_avx2_psrl_w:
2741  case Intrinsic::x86_avx512_psrl_d_512:
2742  case Intrinsic::x86_avx512_psrl_q_512:
2743  case Intrinsic::x86_avx512_psrl_w_512:
2744  case Intrinsic::x86_sse2_psll_d:
2745  case Intrinsic::x86_sse2_psll_q:
2746  case Intrinsic::x86_sse2_psll_w:
2747  case Intrinsic::x86_avx2_psll_d:
2748  case Intrinsic::x86_avx2_psll_q:
2749  case Intrinsic::x86_avx2_psll_w:
2750  case Intrinsic::x86_avx512_psll_d_512:
2751  case Intrinsic::x86_avx512_psll_q_512:
2752  case Intrinsic::x86_avx512_psll_w_512: {
2753  if (Value *V = simplifyX86immShift(*II, Builder))
2754  return replaceInstUsesWith(*II, V);
2755 
2756  // SSE2/AVX2 uses only the first 64-bits of the 128-bit vector
2757  // operand to compute the shift amount.
2758  Value *Arg1 = II->getArgOperand(1);
2759  assert(Arg1->getType()->getPrimitiveSizeInBits() == 128 &&
2760  "Unexpected packed shift size");
2761  unsigned VWidth = Arg1->getType()->getVectorNumElements();
2762 
2763  if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, VWidth / 2)) {
2764  II->setArgOperand(1, V);
2765  return II;
2766  }
2767  break;
2768  }
2769 
2770  case Intrinsic::x86_avx2_psllv_d:
2771  case Intrinsic::x86_avx2_psllv_d_256:
2772  case Intrinsic::x86_avx2_psllv_q:
2773  case Intrinsic::x86_avx2_psllv_q_256:
2774  case Intrinsic::x86_avx512_psllv_d_512:
2775  case Intrinsic::x86_avx512_psllv_q_512:
2776  case Intrinsic::x86_avx512_psllv_w_128:
2777  case Intrinsic::x86_avx512_psllv_w_256:
2778  case Intrinsic::x86_avx512_psllv_w_512:
2779  case Intrinsic::x86_avx2_psrav_d:
2780  case Intrinsic::x86_avx2_psrav_d_256:
2781  case Intrinsic::x86_avx512_psrav_q_128:
2782  case Intrinsic::x86_avx512_psrav_q_256:
2783  case Intrinsic::x86_avx512_psrav_d_512:
2784  case Intrinsic::x86_avx512_psrav_q_512:
2785  case Intrinsic::x86_avx512_psrav_w_128:
2786  case Intrinsic::x86_avx512_psrav_w_256:
2787  case Intrinsic::x86_avx512_psrav_w_512:
2788  case Intrinsic::x86_avx2_psrlv_d:
2789  case Intrinsic::x86_avx2_psrlv_d_256:
2790  case Intrinsic::x86_avx2_psrlv_q:
2791  case Intrinsic::x86_avx2_psrlv_q_256:
2792  case Intrinsic::x86_avx512_psrlv_d_512:
2793  case Intrinsic::x86_avx512_psrlv_q_512:
2794  case Intrinsic::x86_avx512_psrlv_w_128:
2795  case Intrinsic::x86_avx512_psrlv_w_256:
2796  case Intrinsic::x86_avx512_psrlv_w_512:
2797  if (Value *V = simplifyX86varShift(*II, Builder))
2798  return replaceInstUsesWith(*II, V);
2799  break;
2800 
2801  case Intrinsic::x86_sse2_packssdw_128:
2802  case Intrinsic::x86_sse2_packsswb_128:
2803  case Intrinsic::x86_avx2_packssdw:
2804  case Intrinsic::x86_avx2_packsswb:
2805  case Intrinsic::x86_avx512_packssdw_512:
2806  case Intrinsic::x86_avx512_packsswb_512:
2807  if (Value *V = simplifyX86pack(*II, Builder, true))
2808  return replaceInstUsesWith(*II, V);
2809  break;
2810 
2811  case Intrinsic::x86_sse2_packuswb_128:
2812  case Intrinsic::x86_sse41_packusdw:
2813  case Intrinsic::x86_avx2_packusdw:
2814  case Intrinsic::x86_avx2_packuswb:
2815  case Intrinsic::x86_avx512_packusdw_512:
2816  case Intrinsic::x86_avx512_packuswb_512:
2817  if (Value *V = simplifyX86pack(*II, Builder, false))
2818  return replaceInstUsesWith(*II, V);
2819  break;
2820 
2821  case Intrinsic::x86_pclmulqdq:
2822  case Intrinsic::x86_pclmulqdq_256:
2823  case Intrinsic::x86_pclmulqdq_512: {
2824  if (auto *C = dyn_cast<ConstantInt>(II->getArgOperand(2))) {
2825  unsigned Imm = C->getZExtValue();
2826 
2827  bool MadeChange = false;
2828  Value *Arg0 = II->getArgOperand(0);
2829  Value *Arg1 = II->getArgOperand(1);
2830  unsigned VWidth = Arg0->getType()->getVectorNumElements();
2831 
2832  APInt UndefElts1(VWidth, 0);
2833  APInt DemandedElts1 = APInt::getSplat(VWidth,
2834  APInt(2, (Imm & 0x01) ? 2 : 1));
2835  if (Value *V = SimplifyDemandedVectorElts(Arg0, DemandedElts1,
2836  UndefElts1)) {
2837  II->setArgOperand(0, V);
2838  MadeChange = true;
2839  }
2840 
2841  APInt UndefElts2(VWidth, 0);
2842  APInt DemandedElts2 = APInt::getSplat(VWidth,
2843  APInt(2, (Imm & 0x10) ? 2 : 1));
2844  if (Value *V = SimplifyDemandedVectorElts(Arg1, DemandedElts2,
2845  UndefElts2)) {
2846  II->setArgOperand(1, V);
2847  MadeChange = true;
2848  }
2849 
2850  // If either input elements are undef, the result is zero.
2851  if (DemandedElts1.isSubsetOf(UndefElts1) ||
2852  DemandedElts2.isSubsetOf(UndefElts2))
2853  return replaceInstUsesWith(*II,
2854  ConstantAggregateZero::get(II->getType()));
2855 
2856  if (MadeChange)
2857  return II;
2858  }
2859  break;
2860  }
2861 
2862  case Intrinsic::x86_sse41_insertps:
2863  if (Value *V = simplifyX86insertps(*II, Builder))
2864  return replaceInstUsesWith(*II, V);
2865  break;
2866 
2867  case Intrinsic::x86_sse4a_extrq: {
2868  Value *Op0 = II->getArgOperand(0);
2869  Value *Op1 = II->getArgOperand(1);
2870  unsigned VWidth0 = Op0->getType()->getVectorNumElements();
2871  unsigned VWidth1 = Op1->getType()->getVectorNumElements();
2872  assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
2873  Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth0 == 2 &&
2874  VWidth1 == 16 && "Unexpected operand sizes");
2875 
2876  // See if we're dealing with constant values.
2877  Constant *C1 = dyn_cast<Constant>(Op1);
2878  ConstantInt *CILength =
2879  C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)0))
2880  : nullptr;
2881  ConstantInt *CIIndex =
2882  C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)1))
2883  : nullptr;
2884 
2885  // Attempt to simplify to a constant, shuffle vector or EXTRQI call.
2886  if (Value *V = simplifyX86extrq(*II, Op0, CILength, CIIndex, Builder))
2887  return replaceInstUsesWith(*II, V);
2888 
2889  // EXTRQ only uses the lowest 64-bits of the first 128-bit vector
2890  // operands and the lowest 16-bits of the second.
2891  bool MadeChange = false;
2892  if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth0, 1)) {
2893  II->setArgOperand(0, V);
2894  MadeChange = true;
2895  }
2896  if (Value *V = SimplifyDemandedVectorEltsLow(Op1, VWidth1, 2)) {
2897  II->setArgOperand(1, V);
2898  MadeChange = true;
2899  }
2900  if (MadeChange)
2901  return II;
2902  break;
2903  }
2904 
2905  case Intrinsic::x86_sse4a_extrqi: {
2906  // EXTRQI: Extract Length bits starting from Index. Zero pad the remaining
2907  // bits of the lower 64-bits. The upper 64-bits are undefined.
2908  Value *Op0 = II->getArgOperand(0);
2909  unsigned VWidth = Op0->getType()->getVectorNumElements();
2910  assert(Op0->getType()->getPrimitiveSizeInBits() == 128 && VWidth == 2 &&
2911  "Unexpected operand size");
2912 
2913  // See if we're dealing with constant values.
2914  ConstantInt *CILength = dyn_cast<ConstantInt>(II->getArgOperand(1));
2915  ConstantInt *CIIndex = dyn_cast<ConstantInt>(II->getArgOperand(2));
2916 
2917  // Attempt to simplify to a constant or shuffle vector.
2918  if (Value *V = simplifyX86extrq(*II, Op0, CILength, CIIndex, Builder))
2919  return replaceInstUsesWith(*II, V);
2920 
2921  // EXTRQI only uses the lowest 64-bits of the first 128-bit vector
2922  // operand.
2923  if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth, 1)) {
2924  II->setArgOperand(0, V);
2925  return II;
2926  }
2927  break;
2928  }
2929 
2930  case Intrinsic::x86_sse4a_insertq: {
2931  Value *Op0 = II->getArgOperand(0);
2932  Value *Op1 = II->getArgOperand(1);
2933  unsigned VWidth = Op0->getType()->getVectorNumElements();
2934  assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
2935  Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth == 2 &&
2936  Op1->getType()->getVectorNumElements() == 2 &&
2937  "Unexpected operand size");
2938 
2939  // See if we're dealing with constant values.
2940  Constant *C1 = dyn_cast<Constant>(Op1);
2941  ConstantInt *CI11 =
2942  C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)1))
2943  : nullptr;
2944 
2945  // Attempt to simplify to a constant, shuffle vector or INSERTQI call.
2946  if (CI11) {
2947  const APInt &V11 = CI11->getValue();
2948  APInt Len = V11.zextOrTrunc(6);
2949  APInt Idx = V11.lshr(8).zextOrTrunc(6);
2950  if (Value *V = simplifyX86insertq(*II, Op0, Op1, Len, Idx, Builder))
2951  return replaceInstUsesWith(*II, V);
2952  }
2953 
2954  // INSERTQ only uses the lowest 64-bits of the first 128-bit vector
2955  // operand.
2956  if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth, 1)) {
2957  II->setArgOperand(0, V);
2958  return II;
2959  }
2960  break;
2961  }
2962 
2963  case Intrinsic::x86_sse4a_insertqi: {
2964  // INSERTQI: Extract lowest Length bits from lower half of second source and
2965  // insert over first source starting at Index bit. The upper 64-bits are
2966  // undefined.
2967  Value *Op0 = II->getArgOperand(0);
2968  Value *Op1 = II->getArgOperand(1);
2969  unsigned VWidth0 = Op0->getType()->getVectorNumElements();
2970  unsigned VWidth1 = Op1->getType()->getVectorNumElements();
2971  assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
2972  Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth0 == 2 &&
2973  VWidth1 == 2 && "Unexpected operand sizes");
2974 
2975  // See if we're dealing with constant values.
2976  ConstantInt *CILength = dyn_cast<ConstantInt>(II->getArgOperand(2));
2977  ConstantInt *CIIndex = dyn_cast<ConstantInt>(II->getArgOperand(3));
2978 
2979  // Attempt to simplify to a constant or shuffle vector.
2980  if (CILength && CIIndex) {
2981  APInt Len = CILength->getValue().zextOrTrunc(6);
2982  APInt Idx = CIIndex->getValue().zextOrTrunc(6);
2983  if (Value *V = simplifyX86insertq(*II, Op0, Op1, Len, Idx, Builder))
2984  return replaceInstUsesWith(*II, V);
2985  }
2986 
2987  // INSERTQI only uses the lowest 64-bits of the first two 128-bit vector
2988  // operands.
2989  bool MadeChange = false;
2990  if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth0, 1)) {
2991  II->setArgOperand(0, V);
2992  MadeChange = true;
2993  }
2994  if (Value *V = SimplifyDemandedVectorEltsLow(Op1, VWidth1, 1)) {
2995  II->setArgOperand(1, V);
2996  MadeChange = true;
2997  }
2998  if (MadeChange)
2999  return II;
3000  break;
3001  }
3002 
3003  case Intrinsic::x86_sse41_pblendvb:
3004  case Intrinsic::x86_sse41_blendvps:
3005  case Intrinsic::x86_sse41_blendvpd:
3006  case Intrinsic::x86_avx_blendv_ps_256:
3007  case Intrinsic::x86_avx_blendv_pd_256:
3008  case Intrinsic::x86_avx2_pblendvb: {
3009  // fold (blend A, A, Mask) -> A
3010  Value *Op0 = II->getArgOperand(0);
3011  Value *Op1 = II->getArgOperand(1);
3012  Value *Mask = II->getArgOperand(2);
3013  if (Op0 == Op1)
3014  return replaceInstUsesWith(CI, Op0);
3015 
3016  // Zero Mask - select 1st argument.
3017  if (isa<ConstantAggregateZero>(Mask))
3018  return replaceInstUsesWith(CI, Op0);
3019 
3020  // Constant Mask - select 1st/2nd argument lane based on top bit of mask.
3021  if (auto *ConstantMask = dyn_cast<ConstantDataVector>(Mask)) {
3022  Constant *NewSelector = getNegativeIsTrueBoolVec(ConstantMask);
3023  return SelectInst::Create(NewSelector, Op1, Op0, "blendv");
3024  }
3025 
3026  // Convert to a vector select if we can bypass casts and find a boolean
3027  // vector condition value.
3028  Value *BoolVec;
3029  Mask = peekThroughBitcast(Mask);
3030  if (match(Mask, m_SExt(m_Value(BoolVec))) &&
3031  BoolVec->getType()->isVectorTy() &&
3032  BoolVec->getType()->getScalarSizeInBits() == 1) {
3033  assert(Mask->getType()->getPrimitiveSizeInBits() ==
3034  II->getType()->getPrimitiveSizeInBits() &&
3035  "Not expecting mask and operands with different sizes");
3036 
3037  unsigned NumMaskElts = Mask->getType()->getVectorNumElements();
3038  unsigned NumOperandElts = II->getType()->getVectorNumElements();
3039  if (NumMaskElts == NumOperandElts)
3040  return SelectInst::Create(BoolVec, Op1, Op0);
3041 
3042  // If the mask has less elements than the operands, each mask bit maps to
3043  // multiple elements of the operands. Bitcast back and forth.
3044  if (NumMaskElts < NumOperandElts) {
3045  Value *CastOp0 = Builder.CreateBitCast(Op0, Mask->getType());
3046  Value *CastOp1 = Builder.CreateBitCast(Op1, Mask->getType());
3047  Value *Sel = Builder.CreateSelect(BoolVec, CastOp1, CastOp0);
3048  return new BitCastInst(Sel, II->getType());
3049  }
3050  }
3051 
3052  break;
3053  }
3054 
3055  case Intrinsic::x86_ssse3_pshuf_b_128:
3056  case Intrinsic::x86_avx2_pshuf_b:
3057  case Intrinsic::x86_avx512_pshuf_b_512:
3058  if (Value *V = simplifyX86pshufb(*II, Builder))
3059  return replaceInstUsesWith(*II, V);
3060  break;
3061 
3062  case Intrinsic::x86_avx_vpermilvar_ps:
3063  case Intrinsic::x86_avx_vpermilvar_ps_256:
3064  case Intrinsic::x86_avx512_vpermilvar_ps_512:
3065  case Intrinsic::x86_avx_vpermilvar_pd:
3066  case Intrinsic::x86_avx_vpermilvar_pd_256:
3067  case Intrinsic::x86_avx512_vpermilvar_pd_512:
3068  if (Value *V = simplifyX86vpermilvar(*II, Builder))
3069  return replaceInstUsesWith(*II, V);
3070  break;
3071 
3072  case Intrinsic::x86_avx2_permd:
3073  case Intrinsic::x86_avx2_permps:
3074  case Intrinsic::x86_avx512_permvar_df_256:
3075  case Intrinsic::x86_avx512_permvar_df_512:
3076  case Intrinsic::x86_avx512_permvar_di_256:
3077  case Intrinsic::x86_avx512_permvar_di_512:
3078  case Intrinsic::x86_avx512_permvar_hi_128:
3079  case Intrinsic::x86_avx512_permvar_hi_256:
3080  case Intrinsic::x86_avx512_permvar_hi_512:
3081  case Intrinsic::x86_avx512_permvar_qi_128:
3082  case Intrinsic::x86_avx512_permvar_qi_256:
3083  case Intrinsic::x86_avx512_permvar_qi_512:
3084  case Intrinsic::x86_avx512_permvar_sf_512:
3085  case Intrinsic::x86_avx512_permvar_si_512:
3086  if (Value *V = simplifyX86vpermv(*II, Builder))
3087  return replaceInstUsesWith(*II, V);
3088  break;
3089 
3090  case Intrinsic::x86_avx_maskload_ps:
3091  case Intrinsic::x86_avx_maskload_pd:
3092  case Intrinsic::x86_avx_maskload_ps_256:
3093  case Intrinsic::x86_avx_maskload_pd_256:
3094  case Intrinsic::x86_avx2_maskload_d:
3095  case Intrinsic::x86_avx2_maskload_q:
3096  case Intrinsic::x86_avx2_maskload_d_256:
3097  case Intrinsic::x86_avx2_maskload_q_256:
3098  if (Instruction *I = simplifyX86MaskedLoad(*II, *this))
3099  return I;
3100  break;
3101 
3102  case Intrinsic::x86_sse2_maskmov_dqu:
3103  case Intrinsic::x86_avx_maskstore_ps:
3104  case Intrinsic::x86_avx_maskstore_pd:
3105  case Intrinsic::x86_avx_maskstore_ps_256:
3106  case Intrinsic::x86_avx_maskstore_pd_256:
3107  case Intrinsic::x86_avx2_maskstore_d:
3108  case Intrinsic::x86_avx2_maskstore_q:
3109  case Intrinsic::x86_avx2_maskstore_d_256:
3110  case Intrinsic::x86_avx2_maskstore_q_256:
3111  if (simplifyX86MaskedStore(*II, *this))
3112  return nullptr;
3113  break;
3114 
3115  case Intrinsic::x86_addcarry_32:
3116  case Intrinsic::x86_addcarry_64:
3117  if (Value *V = simplifyX86addcarry(*II, Builder))
3118  return replaceInstUsesWith(*II, V);
3119  break;
3120 
3121  case Intrinsic::ppc_altivec_vperm:
3122  // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
3123  // Note that ppc_altivec_vperm has a big-endian bias, so when creating
3124  // a vectorshuffle for little endian, we must undo the transformation
3125  // performed on vec_perm in altivec.h. That is, we must complement
3126  // the permutation mask with respect to 31 and reverse the order of
3127  // V1 and V2.
3128  if (Constant *Mask = dyn_cast<Constant>(II->getArgOperand(2))) {
3129  assert(Mask->getType()->getVectorNumElements() == 16 &&
3130  "Bad type for intrinsic!");
3131 
3132  // Check that all of the elements are integer constants or undefs.
3133  bool AllEltsOk = true;
3134  for (unsigned i = 0; i != 16; ++i) {
3135  Constant *Elt = Mask->getAggregateElement(i);
3136  if (!Elt || !(isa<ConstantInt>(Elt) || isa<UndefValue>(Elt))) {
3137  AllEltsOk = false;
3138  break;
3139  }
3140  }
3141 
3142  if (AllEltsOk) {
3143  // Cast the input vectors to byte vectors.
3144  Value *Op0 = Builder.CreateBitCast(II->getArgOperand(0),
3145  Mask->getType());
3146  Value *Op1 = Builder.CreateBitCast(II->getArgOperand(1),
3147  Mask->getType());
3148  Value *Result = UndefValue::get(Op0->getType());
3149 
3150  // Only extract each element once.
3151  Value *ExtractedElts[32];
3152  memset(ExtractedElts, 0, sizeof(ExtractedElts));
3153 
3154  for (unsigned i = 0; i != 16; ++i) {
3155  if (isa<UndefValue>(Mask->getAggregateElement(i)))
3156  continue;
3157  unsigned Idx =
3158  cast<ConstantInt>(Mask->getAggregateElement(i))->getZExtValue();
3159  Idx &= 31; // Match the hardware behavior.
3160  if (DL.isLittleEndian())
3161  Idx = 31 - Idx;
3162 
3163  if (!ExtractedElts[Idx]) {
3164  Value *Op0ToUse = (DL.isLittleEndian()) ? Op1 : Op0;
3165  Value *Op1ToUse = (DL.isLittleEndian()) ? Op0 : Op1;
3166  ExtractedElts[Idx] =
3167  Builder.CreateExtractElement(Idx < 16 ? Op0ToUse : Op1ToUse,
3168  Builder.getInt32(Idx&15));
3169  }
3170 
3171  // Insert this value into the result vector.
3172  Result = Builder.CreateInsertElement(Result, ExtractedElts[Idx],
3173  Builder.getInt32(i));
3174  }
3175  return CastInst::Create(Instruction::BitCast, Result, CI.getType());
3176  }
3177  }
3178  break;
3179 
3180  case Intrinsic::arm_neon_vld1: {
3181  unsigned MemAlign = getKnownAlignment(II->getArgOperand(0),
3182  DL, II, &AC, &DT);
3183  if (Value *V = simplifyNeonVld1(*II, MemAlign, Builder))
3184  return replaceInstUsesWith(*II, V);
3185  break;
3186  }
3187 
3188  case Intrinsic::arm_neon_vld2:
3189  case Intrinsic::arm_neon_vld3:
3190  case Intrinsic::arm_neon_vld4:
3191  case Intrinsic::arm_neon_vld2lane:
3192  case Intrinsic::arm_neon_vld3lane:
3193  case Intrinsic::arm_neon_vld4lane:
3194  case Intrinsic::arm_neon_vst1:
3195  case Intrinsic::arm_neon_vst2:
3196  case Intrinsic::arm_neon_vst3:
3197  case Intrinsic::arm_neon_vst4:
3198  case Intrinsic::arm_neon_vst2lane:
3199  case Intrinsic::arm_neon_vst3lane:
3200  case Intrinsic::arm_neon_vst4lane: {
3201  unsigned MemAlign =
3202  getKnownAlignment(II->getArgOperand(0), DL, II, &AC, &DT);
3203  unsigned AlignArg = II->getNumArgOperands() - 1;
3204  ConstantInt *IntrAlign = dyn_cast<ConstantInt>(II->getArgOperand(AlignArg));
3205  if (IntrAlign && IntrAlign->getZExtValue() < MemAlign) {
3206  II->setArgOperand(AlignArg,
3207  ConstantInt::get(Type::getInt32Ty(II->getContext()),
3208  MemAlign, false));
3209  return II;
3210  }
3211  break;
3212  }
3213 
3214  case Intrinsic::arm_neon_vtbl1:
3215  case Intrinsic::aarch64_neon_tbl1:
3216  if (Value *V = simplifyNeonTbl1(*II, Builder))
3217  return replaceInstUsesWith(*II, V);
3218  break;
3219 
3220  case Intrinsic::arm_neon_vmulls:
3221  case Intrinsic::arm_neon_vmullu:
3222  case Intrinsic::aarch64_neon_smull:
3223  case Intrinsic::aarch64_neon_umull: {
3224  Value *Arg0 = II->getArgOperand(0);
3225  Value *Arg1 = II->getArgOperand(1);
3226 
3227  // Handle mul by zero first:
3228  if (isa<ConstantAggregateZero>(Arg0) || isa<ConstantAggregateZero>(Arg1)) {
3229  return replaceInstUsesWith(CI, ConstantAggregateZero::get(II->getType()));
3230  }
3231 
3232  // Check for constant LHS & RHS - in this case we just simplify.
3233  bool Zext = (IID == Intrinsic::arm_neon_vmullu ||
3234  IID == Intrinsic::aarch64_neon_umull);
3235  VectorType *NewVT = cast<VectorType>(II->getType());
3236  if (Constant *CV0 = dyn_cast<Constant>(Arg0)) {
3237  if (Constant *CV1 = dyn_cast<Constant>(Arg1)) {
3238  CV0 = ConstantExpr::getIntegerCast(CV0, NewVT, /*isSigned=*/!Zext);
3239  CV1 = ConstantExpr::getIntegerCast(CV1, NewVT, /*isSigned=*/!Zext);
3240 
3241  return replaceInstUsesWith(CI, ConstantExpr::getMul(CV0, CV1));
3242  }
3243 
3244  // Couldn't simplify - canonicalize constant to the RHS.
3245  std::swap(Arg0, Arg1);
3246  }
3247 
3248  // Handle mul by one:
3249  if (Constant *CV1 = dyn_cast<Constant>(Arg1))
3250  if (ConstantInt *Splat =
3251  dyn_cast_or_null<ConstantInt>(CV1->getSplatValue()))
3252  if (Splat->isOne())
3253  return CastInst::CreateIntegerCast(Arg0, II->getType(),
3254  /*isSigned=*/!Zext);
3255 
3256  break;
3257  }
3258  case Intrinsic::arm_neon_aesd:
3259  case Intrinsic::arm_neon_aese:
3260  case Intrinsic::aarch64_crypto_aesd:
3261  case Intrinsic::aarch64_crypto_aese: {
3262  Value *DataArg = II->getArgOperand(0);
3263  Value *KeyArg = II->getArgOperand(1);
3264 
3265  // Try to use the builtin XOR in AESE and AESD to eliminate a prior XOR
3266  Value *Data, *Key;
3267  if (match(KeyArg, m_ZeroInt()) &&
3268  match(DataArg, m_Xor(m_Value(Data), m_Value(Key)))) {
3269  II->setArgOperand(0, Data);
3270  II->setArgOperand(1, Key);
3271  return II;
3272  }
3273  break;
3274  }
3275  case Intrinsic::amdgcn_rcp: {
3276  Value *Src = II->getArgOperand(0);
3277 
3278  // TODO: Move to ConstantFolding/InstSimplify?
3279  if (isa<UndefValue>(Src))
3280  return replaceInstUsesWith(CI, Src);
3281 
3282  if (const ConstantFP *C = dyn_cast<ConstantFP>(Src)) {
3283  const APFloat &ArgVal = C->getValueAPF();
3284  APFloat Val(ArgVal.getSemantics(), 1.0);
3285  APFloat::opStatus Status = Val.divide(ArgVal,
3287  // Only do this if it was exact and therefore not dependent on the
3288  // rounding mode.
3289  if (Status == APFloat::opOK)
3290  return replaceInstUsesWith(CI, ConstantFP::get(II->getContext(), Val));
3291  }
3292 
3293  break;
3294  }
3295  case Intrinsic::amdgcn_rsq: {
3296  Value *Src = II->getArgOperand(0);
3297 
3298  // TODO: Move to ConstantFolding/InstSimplify?
3299  if (isa<UndefValue>(Src))
3300  return replaceInstUsesWith(CI, Src);
3301  break;
3302  }
3303  case Intrinsic::amdgcn_frexp_mant:
3304  case Intrinsic::amdgcn_frexp_exp: {
3305  Value *Src = II->getArgOperand(0);
3306  if (const ConstantFP *C = dyn_cast<ConstantFP>(Src)) {
3307  int Exp;
3308  APFloat Significand = frexp(C->getValueAPF(), Exp,
3310 
3311  if (IID == Intrinsic::amdgcn_frexp_mant) {
3312  return replaceInstUsesWith(CI, ConstantFP::get(II->getContext(),
3313  Significand));
3314  }
3315 
3316  // Match instruction special case behavior.
3317  if (Exp == APFloat::IEK_NaN || Exp == APFloat::IEK_Inf)
3318  Exp = 0;
3319 
3320  return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), Exp));
3321  }
3322 
3323  if (isa<UndefValue>(Src))
3324  return replaceInstUsesWith(CI, UndefValue::get(II->getType()));
3325 
3326  break;
3327  }
3328  case Intrinsic::amdgcn_class: {
3329  enum {
3330  S_NAN = 1 << 0, // Signaling NaN
3331  Q_NAN = 1 << 1, // Quiet NaN
3332  N_INFINITY = 1 << 2, // Negative infinity
3333  N_NORMAL = 1 << 3, // Negative normal
3334  N_SUBNORMAL = 1 << 4, // Negative subnormal
3335  N_ZERO = 1 << 5, // Negative zero
3336  P_ZERO = 1 << 6, // Positive zero
3337  P_SUBNORMAL = 1 << 7, // Positive subnormal
3338  P_NORMAL = 1 << 8, // Positive normal
3339  P_INFINITY = 1 << 9 // Positive infinity
3340  };
3341 
3342  const uint32_t FullMask = S_NAN | Q_NAN | N_INFINITY | N_NORMAL |
3344 
3345  Value *Src0 = II->getArgOperand(0);
3346  Value *Src1 = II->getArgOperand(1);
3347  const ConstantInt *CMask = dyn_cast<ConstantInt>(Src1);
3348  if (!CMask) {
3349  if (isa<UndefValue>(Src0))
3350  return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
3351 
3352  if (isa<UndefValue>(Src1))
3353  return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), false));
3354  break;
3355  }
3356 
3357  uint32_t Mask = CMask->getZExtValue();
3358 
3359  // If all tests are made, it doesn't matter what the value is.
3360  if ((Mask & FullMask) == FullMask)
3361  return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), true));
3362 
3363  if ((Mask & FullMask) == 0)
3364  return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), false));
3365 
3366  if (Mask == (S_NAN | Q_NAN)) {
3367  // Equivalent of isnan. Replace with standard fcmp.
3368  Value *FCmp = Builder.CreateFCmpUNO(Src0, Src0);
3369  FCmp->takeName(II);
3370  return replaceInstUsesWith(*II, FCmp);
3371  }
3372 
3373  if (Mask == (N_ZERO | P_ZERO)) {
3374  // Equivalent of == 0.
3375  Value *FCmp = Builder.CreateFCmpOEQ(
3376  Src0, ConstantFP::get(Src0->getType(), 0.0));
3377 
3378  FCmp->takeName(II);
3379  return replaceInstUsesWith(*II, FCmp);
3380  }
3381 
3382  // fp_class (nnan x), qnan|snan|other -> fp_class (nnan x), other
3383  if (((Mask & S_NAN) || (Mask & Q_NAN)) && isKnownNeverNaN(Src0, &TLI)) {
3384  II->setArgOperand(1, ConstantInt::get(Src1->getType(),
3385  Mask & ~(S_NAN | Q_NAN)));
3386  return II;
3387  }
3388 
3389  const ConstantFP *CVal = dyn_cast<ConstantFP>(Src0);
3390  if (!CVal) {
3391  if (isa<UndefValue>(Src0))
3392  return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
3393 
3394  // Clamp mask to used bits
3395  if ((Mask & FullMask) != Mask) {
3396  CallInst *NewCall = Builder.CreateCall(II->getCalledFunction(),
3397  { Src0, ConstantInt::get(Src1->getType(), Mask & FullMask) }
3398  );
3399 
3400  NewCall->takeName(II);
3401  return replaceInstUsesWith(*II, NewCall);
3402  }
3403 
3404  break;
3405  }
3406 
3407  const APFloat &Val = CVal->getValueAPF();
3408 
3409  bool Result =
3410  ((Mask & S_NAN) && Val.isNaN() && Val.isSignaling()) ||
3411  ((Mask & Q_NAN) && Val.isNaN() && !Val.isSignaling()) ||
3412  ((Mask & N_INFINITY) && Val.isInfinity() && Val.isNegative()) ||
3413  ((Mask & N_NORMAL) && Val.isNormal() && Val.isNegative()) ||
3414  ((Mask & N_SUBNORMAL) && Val.isDenormal() && Val.isNegative()) ||
3415  ((Mask & N_ZERO) && Val.isZero() && Val.isNegative()) ||
3416  ((Mask & P_ZERO) && Val.isZero() && !Val.isNegative()) ||
3417  ((Mask & P_SUBNORMAL) && Val.isDenormal() && !Val.isNegative()) ||
3418  ((Mask & P_NORMAL) && Val.isNormal() && !Val.isNegative()) ||
3419  ((Mask & P_INFINITY) && Val.isInfinity() && !Val.isNegative());
3420 
3421  return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), Result));
3422  }
3423  case Intrinsic::amdgcn_cvt_pkrtz: {
3424  Value *Src0 = II->getArgOperand(0);
3425  Value *Src1 = II->getArgOperand(1);
3426  if (const ConstantFP *C0 = dyn_cast<ConstantFP>(Src0)) {
3427  if (const ConstantFP *C1 = dyn_cast<ConstantFP>(Src1)) {
3428  const fltSemantics &HalfSem
3429  = II->getType()->getScalarType()->getFltSemantics();
3430  bool LosesInfo;
3431  APFloat Val0 = C0->getValueAPF();
3432  APFloat Val1 = C1->getValueAPF();
3433  Val0.convert(HalfSem, APFloat::rmTowardZero, &LosesInfo);
3434  Val1.convert(HalfSem, APFloat::rmTowardZero, &LosesInfo);
3435 
3436  Constant *Folded = ConstantVector::get({
3437  ConstantFP::get(II->getContext(), Val0),
3438  ConstantFP::get(II->getContext(), Val1) });
3439  return replaceInstUsesWith(*II, Folded);
3440  }
3441  }
3442 
3443  if (isa<UndefValue>(Src0) && isa<UndefValue>(Src1))
3444  return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
3445 
3446  break;
3447  }
3448  case Intrinsic::amdgcn_cvt_pknorm_i16:
3449  case Intrinsic::amdgcn_cvt_pknorm_u16:
3450  case Intrinsic::amdgcn_cvt_pk_i16:
3451  case Intrinsic::amdgcn_cvt_pk_u16: {
3452  Value *Src0 = II->getArgOperand(0);
3453  Value *Src1 = II->getArgOperand(1);
3454 
3455  if (isa<UndefValue>(Src0) && isa<UndefValue>(Src1))
3456  return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
3457 
3458  break;
3459  }
3460  case Intrinsic::amdgcn_ubfe:
3461  case Intrinsic::amdgcn_sbfe: {
3462  // Decompose simple cases into standard shifts.
3463  Value *Src = II->getArgOperand(0);
3464  if (isa<UndefValue>(Src))
3465  return replaceInstUsesWith(*II, Src);
3466 
3467  unsigned Width;
3468  Type *Ty = II->getType();
3469  unsigned IntSize = Ty->getIntegerBitWidth();
3470 
3471  ConstantInt *CWidth = dyn_cast<ConstantInt>(II->getArgOperand(2));
3472  if (CWidth) {
3473  Width = CWidth->getZExtValue();
3474  if ((Width & (IntSize - 1)) == 0)
3475  return replaceInstUsesWith(*II, ConstantInt::getNullValue(Ty));
3476 
3477  if (Width >= IntSize) {
3478  // Hardware ignores high bits, so remove those.
3479  II->setArgOperand(2, ConstantInt::get(CWidth->getType(),
3480  Width & (IntSize - 1)));
3481  return II;
3482  }
3483  }
3484 
3485  unsigned Offset;
3486  ConstantInt *COffset = dyn_cast<ConstantInt>(II->getArgOperand(1));
3487  if (COffset) {
3488  Offset = COffset->getZExtValue();
3489  if (Offset >= IntSize) {
3490  II->setArgOperand(1, ConstantInt::get(COffset->getType(),
3491  Offset & (IntSize - 1)));
3492  return II;
3493  }
3494  }
3495 
3496  bool Signed = IID == Intrinsic::amdgcn_sbfe;
3497 
3498  if (!CWidth || !COffset)
3499  break;
3500 
3501  // The case of Width == 0 is handled above, which makes this tranformation
3502  // safe. If Width == 0, then the ashr and lshr instructions become poison
3503  // value since the shift amount would be equal to the bit size.
3504  assert(Width != 0);
3505 
3506  // TODO: This allows folding to undef when the hardware has specific
3507  // behavior?
3508  if (Offset + Width < IntSize) {
3509  Value *Shl = Builder.CreateShl(Src, IntSize - Offset - Width);
3510  Value *RightShift = Signed ? Builder.CreateAShr(Shl, IntSize - Width)
3511  : Builder.CreateLShr(Shl, IntSize - Width);
3512  RightShift->takeName(II);
3513  return replaceInstUsesWith(*II, RightShift);
3514  }
3515 
3516  Value *RightShift = Signed ? Builder.CreateAShr(Src, Offset)
3517  : Builder.CreateLShr(Src, Offset);
3518 
3519  RightShift->takeName(II);
3520  return replaceInstUsesWith(*II, RightShift);
3521  }
3522  case Intrinsic::amdgcn_exp:
3523  case Intrinsic::amdgcn_exp_compr: {
3524  ConstantInt *En = cast<ConstantInt>(II->getArgOperand(1));
3525  unsigned EnBits = En->getZExtValue();
3526  if (EnBits == 0xf)
3527  break; // All inputs enabled.
3528 
3529  bool IsCompr = IID == Intrinsic::amdgcn_exp_compr;
3530  bool Changed = false;
3531  for (int I = 0; I < (IsCompr ? 2 : 4); ++I) {
3532  if ((!IsCompr && (EnBits & (1 << I)) == 0) ||
3533  (IsCompr && ((EnBits & (0x3 << (2 * I))) == 0))) {
3534  Value *Src = II->getArgOperand(I + 2);
3535  if (!isa<UndefValue>(Src)) {
3536  II->setArgOperand(I + 2, UndefValue::get(Src->getType()));
3537  Changed = true;
3538  }
3539  }
3540  }
3541 
3542  if (Changed)
3543  return II;
3544 
3545  break;
3546  }
3547  case Intrinsic::amdgcn_fmed3: {
3548  // Note this does not preserve proper sNaN behavior if IEEE-mode is enabled
3549  // for the shader.
3550 
3551  Value *Src0 = II->getArgOperand(0);
3552  Value *Src1 = II->getArgOperand(1);
3553  Value *Src2 = II->getArgOperand(2);
3554 
3555  // Checking for NaN before canonicalization provides better fidelity when
3556  // mapping other operations onto fmed3 since the order of operands is
3557  // unchanged.
3558  CallInst *NewCall = nullptr;
3559  if (match(Src0, m_NaN()) || isa<UndefValue>(Src0)) {
3560  NewCall = Builder.CreateMinNum(Src1, Src2);
3561  } else if (match(Src1, m_NaN()) || isa<UndefValue>(Src1)) {
3562  NewCall = Builder.CreateMinNum(Src0, Src2);
3563  } else if (match(Src2, m_NaN()) || isa<UndefValue>(Src2)) {
3564  NewCall = Builder.CreateMaxNum(Src0, Src1);
3565  }
3566 
3567  if (NewCall) {
3568  NewCall->copyFastMathFlags(II);
3569  NewCall->takeName(II);
3570  return replaceInstUsesWith(*II, NewCall);
3571  }
3572 
3573  bool Swap = false;
3574  // Canonicalize constants to RHS operands.
3575  //
3576  // fmed3(c0, x, c1) -> fmed3(x, c0, c1)
3577  if (isa<Constant>(Src0) && !isa<Constant>(Src1)) {
3578  std::swap(Src0, Src1);
3579  Swap = true;
3580  }
3581 
3582  if (isa<Constant>(Src1) && !isa<Constant>(Src2)) {
3583  std::swap(Src1, Src2);
3584  Swap = true;
3585  }
3586 
3587  if (isa<Constant>(Src0) && !isa<Constant>(Src1)) {
3588  std::swap(Src0, Src1);
3589  Swap = true;
3590  }
3591 
3592  if (Swap) {
3593  II->setArgOperand(0, Src0);
3594  II->setArgOperand(1, Src1);
3595  II->setArgOperand(2, Src2);
3596  return II;
3597  }
3598 
3599  if (const ConstantFP *C0 = dyn_cast<ConstantFP>(Src0)) {
3600  if (const ConstantFP *C1 = dyn_cast<ConstantFP>(Src1)) {
3601  if (const ConstantFP *C2 = dyn_cast<ConstantFP>(Src2)) {
3602  APFloat Result = fmed3AMDGCN(C0->getValueAPF(), C1->getValueAPF(),
3603  C2->getValueAPF());
3604  return replaceInstUsesWith(*II,
3605  ConstantFP::get(Builder.getContext(), Result));
3606  }
3607  }
3608  }
3609 
3610  break;
3611  }
3612  case Intrinsic::amdgcn_icmp:
3613  case Intrinsic::amdgcn_fcmp: {
3614  const ConstantInt *CC = cast<ConstantInt>(II->getArgOperand(2));
3615  // Guard against invalid arguments.
3616  int64_t CCVal = CC->getZExtValue();
3617  bool IsInteger = IID == Intrinsic::amdgcn_icmp;
3618  if ((IsInteger && (CCVal < CmpInst::FIRST_ICMP_PREDICATE ||
3619  CCVal > CmpInst::LAST_ICMP_PREDICATE)) ||
3620  (!IsInteger && (CCVal < CmpInst::FIRST_FCMP_PREDICATE ||
3621  CCVal > CmpInst::LAST_FCMP_PREDICATE)))
3622  break;
3623 
3624  Value *Src0 = II->getArgOperand(0);
3625  Value *Src1 = II->getArgOperand(1);
3626 
3627  if (auto *CSrc0 = dyn_cast<Constant>(Src0)) {
3628  if (auto *CSrc1 = dyn_cast<Constant>(Src1)) {
3629  Constant *CCmp = ConstantExpr::getCompare(CCVal, CSrc0, CSrc1);
3630  if (CCmp->isNullValue()) {
3631  return replaceInstUsesWith(
3632  *II, ConstantExpr::getSExt(CCmp, II->getType()));
3633  }
3634 
3635  // The result of V_ICMP/V_FCMP assembly instructions (which this
3636  // intrinsic exposes) is one bit per thread, masked with the EXEC
3637  // register (which contains the bitmask of live threads). So a
3638  // comparison that always returns true is the same as a read of the
3639  // EXEC register.
3641  II->getModule(), Intrinsic::read_register, II->getType());
3642  Metadata *MDArgs[] = {MDString::get(II->getContext(), "exec")};
3643  MDNode *MD = MDNode::get(II->getContext(), MDArgs);
3644  Value *Args[] = {MetadataAsValue::get(II->getContext(), MD)};
3645  CallInst *NewCall = Builder.CreateCall(NewF, Args);
3648  NewCall->takeName(II);
3649  return replaceInstUsesWith(*II, NewCall);
3650  }
3651 
3652  // Canonicalize constants to RHS.
3653  CmpInst::Predicate SwapPred
3654  = CmpInst::getSwappedPredicate(static_cast<CmpInst::Predicate>(CCVal));
3655  II->setArgOperand(0, Src1);
3656  II->setArgOperand(1, Src0);
3657  II->setArgOperand(2, ConstantInt::get(CC->getType(),
3658  static_cast<int>(SwapPred)));
3659  return II;
3660  }
3661 
3662  if (CCVal != CmpInst::ICMP_EQ && CCVal != CmpInst::ICMP_NE)
3663  break;
3664 
3665  // Canonicalize compare eq with true value to compare != 0
3666  // llvm.amdgcn.icmp(zext (i1 x), 1, eq)
3667  // -> llvm.amdgcn.icmp(zext (i1 x), 0, ne)
3668  // llvm.amdgcn.icmp(sext (i1 x), -1, eq)
3669  // -> llvm.amdgcn.icmp(sext (i1 x), 0, ne)
3670  Value *ExtSrc;
3671  if (CCVal == CmpInst::ICMP_EQ &&
3672  ((match(Src1, m_One()) && match(Src0, m_ZExt(m_Value(ExtSrc)))) ||
3673  (match(Src1, m_AllOnes()) && match(Src0, m_SExt(m_Value(ExtSrc))))) &&
3674  ExtSrc->getType()->isIntegerTy(1)) {
3675  II->setArgOperand(1, ConstantInt::getNullValue(Src1->getType()));
3676  II->setArgOperand(2, ConstantInt::get(CC->getType(), CmpInst::ICMP_NE));
3677  return II;
3678  }
3679 
3680  CmpInst::Predicate SrcPred;
3681  Value *SrcLHS;
3682  Value *SrcRHS;
3683 
3684  // Fold compare eq/ne with 0 from a compare result as the predicate to the
3685  // intrinsic. The typical use is a wave vote function in the library, which
3686  // will be fed from a user code condition compared with 0. Fold in the
3687  // redundant compare.
3688 
3689  // llvm.amdgcn.icmp([sz]ext ([if]cmp pred a, b), 0, ne)
3690  // -> llvm.amdgcn.[if]cmp(a, b, pred)
3691  //
3692  // llvm.amdgcn.icmp([sz]ext ([if]cmp pred a, b), 0, eq)
3693  // -> llvm.amdgcn.[if]cmp(a, b, inv pred)
3694  if (match(Src1, m_Zero()) &&
3695  match(Src0,
3696  m_ZExtOrSExt(m_Cmp(SrcPred, m_Value(SrcLHS), m_Value(SrcRHS))))) {
3697  if (CCVal == CmpInst::ICMP_EQ)
3698  SrcPred = CmpInst::getInversePredicate(SrcPred);
3699 
3700  Intrinsic::ID NewIID = CmpInst::isFPPredicate(SrcPred) ?
3701  Intrinsic::amdgcn_fcmp : Intrinsic::amdgcn_icmp;
3702 
3703  Type *Ty = SrcLHS->getType();
3704  if (auto *CmpType = dyn_cast<IntegerType>(Ty)) {
3705  // Promote to next legal integer type.
3706  unsigned Width = CmpType->getBitWidth();
3707  unsigned NewWidth = Width;
3708 
3709  // Don't do anything for i1 comparisons.
3710  if (Width == 1)
3711  break;
3712 
3713  if (Width <= 16)
3714  NewWidth = 16;
3715  else if (Width <= 32)
3716  NewWidth = 32;
3717  else if (Width <= 64)
3718  NewWidth = 64;
3719  else if (Width > 64)
3720  break; // Can't handle this.
3721 
3722  if (Width != NewWidth) {
3723  IntegerType *CmpTy = Builder.getIntNTy(NewWidth);
3724  if (CmpInst::isSigned(SrcPred)) {
3725  SrcLHS = Builder.CreateSExt(SrcLHS, CmpTy);
3726  SrcRHS = Builder.CreateSExt(SrcRHS, CmpTy);
3727  } else {
3728  SrcLHS = Builder.CreateZExt(SrcLHS, CmpTy);
3729  SrcRHS = Builder.CreateZExt(SrcRHS, CmpTy);
3730  }
3731  }
3732  } else if (!Ty->isFloatTy() && !Ty->isDoubleTy() && !Ty->isHalfTy())
3733  break;
3734 
3735  Function *NewF =
3736  Intrinsic::getDeclaration(II->getModule(), NewIID,
3737  { II->getType(),
3738  SrcLHS->getType() });
3739  Value *Args[] = { SrcLHS, SrcRHS,
3740  ConstantInt::get(CC->getType(), SrcPred) };
3741  CallInst *NewCall = Builder.CreateCall(NewF, Args);
3742  NewCall->takeName(II);
3743  return replaceInstUsesWith(*II, NewCall);
3744  }
3745 
3746  break;
3747  }
3748  case Intrinsic::amdgcn_wqm_vote: {
3749  // wqm_vote is identity when the argument is constant.
3750  if (!isa<Constant>(II->getArgOperand(0)))
3751  break;
3752 
3753  return replaceInstUsesWith(*II, II->getArgOperand(0));
3754  }
3755  case Intrinsic::amdgcn_kill: {
3756  const ConstantInt *C = dyn_cast<ConstantInt>(II->getArgOperand(0));
3757  if (!C || !C->getZExtValue())
3758  break;
3759 
3760  // amdgcn.kill(i1 1) is a no-op
3761  return eraseInstFromFunction(CI);
3762  }
3763  case Intrinsic::amdgcn_update_dpp: {
3764  Value *Old = II->getArgOperand(0);
3765 
3766  auto BC = cast<ConstantInt>(II->getArgOperand(5));
3767  auto RM = cast<ConstantInt>(II->getArgOperand(3));
3768  auto BM = cast<ConstantInt>(II->getArgOperand(4));
3769  if (BC->isZeroValue() ||
3770  RM->getZExtValue() != 0xF ||
3771  BM->getZExtValue() != 0xF ||
3772  isa<UndefValue>(Old))
3773  break;
3774 
3775  // If bound_ctrl = 1, row mask = bank mask = 0xf we can omit old value.
3776  II->setOperand(0, UndefValue::get(Old->getType()));
3777  return II;
3778  }
3779  case Intrinsic::amdgcn_readfirstlane:
3780  case Intrinsic::amdgcn_readlane: {
3781  // A constant value is trivially uniform.
3782  if (Constant *C = dyn_cast<Constant>(II->getArgOperand(0)))
3783  return replaceInstUsesWith(*II, C);
3784 
3785  // The rest of these may not be safe if the exec may not be the same between
3786  // the def and use.
3787  Value *Src = II->getArgOperand(0);
3788  Instruction *SrcInst = dyn_cast<Instruction>(Src);
3789  if (SrcInst && SrcInst->getParent() != II->getParent())
3790  break;
3791 
3792  // readfirstlane (readfirstlane x) -> readfirstlane x
3793  // readlane (readfirstlane x), y -> readfirstlane x
3794  if (match(Src, m_Intrinsic<Intrinsic::amdgcn_readfirstlane>()))
3795  return replaceInstUsesWith(*II, Src);
3796 
3797  if (IID == Intrinsic::amdgcn_readfirstlane) {
3798  // readfirstlane (readlane x, y) -> readlane x, y
3799  if (match(Src, m_Intrinsic<Intrinsic::amdgcn_readlane>()))
3800  return replaceInstUsesWith(*II, Src);
3801  } else {
3802  // readlane (readlane x, y), y -> readlane x, y
3803  if (match(Src, m_Intrinsic<Intrinsic::amdgcn_readlane>(
3804  m_Value(), m_Specific(II->getArgOperand(1)))))
3805  return replaceInstUsesWith(*II, Src);
3806  }
3807 
3808  break;
3809  }
3810  case Intrinsic::stackrestore: {
3811  // If the save is right next to the restore, remove the restore. This can
3812  // happen when variable allocas are DCE'd.
3813  if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {
3814  if (SS->getIntrinsicID() == Intrinsic::stacksave) {
3815  // Skip over debug info.
3816  if (SS->getNextNonDebugInstruction() == II) {
3817  return eraseInstFromFunction(CI);
3818  }
3819  }
3820  }
3821 
3822  // Scan down this block to see if there is another stack restore in the
3823  // same block without an intervening call/alloca.
3824  BasicBlock::iterator BI(II);
3825  Instruction *TI = II->getParent()->getTerminator();
3826  bool CannotRemove = false;
3827  for (++BI; &*BI != TI; ++BI) {
3828  if (isa<AllocaInst>(BI)) {
3829  CannotRemove = true;
3830  break;
3831  }
3832  if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
3833  if (auto *II2 = dyn_cast<IntrinsicInst>(BCI)) {
3834  // If there is a stackrestore below this one, remove this one.
3835  if (II2->getIntrinsicID() == Intrinsic::stackrestore)
3836  return eraseInstFromFunction(CI);
3837 
3838  // Bail if we cross over an intrinsic with side effects, such as
3839  // llvm.stacksave, llvm.read_register, or llvm.setjmp.
3840  if (II2->mayHaveSideEffects()) {
3841  CannotRemove = true;
3842  break;
3843  }
3844  } else {
3845  // If we found a non-intrinsic call, we can't remove the stack
3846  // restore.
3847  CannotRemove = true;
3848  break;
3849  }
3850  }
3851  }
3852 
3853  // If the stack restore is in a return, resume, or unwind block and if there
3854  // are no allocas or calls between the restore and the return, nuke the
3855  // restore.
3856  if (!CannotRemove && (isa<ReturnInst>(TI) || isa<ResumeInst>(TI)))
3857  return eraseInstFromFunction(CI);
3858  break;
3859  }
3860  case Intrinsic::lifetime_start:
3861  // Asan needs to poison memory to detect invalid access which is possible
3862  // even for empty lifetime range.
3863  if (II->getFunction()->hasFnAttribute(Attribute::SanitizeAddress) ||
3864  II->getFunction()->hasFnAttribute(Attribute::SanitizeHWAddress))
3865  break;
3866 
3867  if (removeTriviallyEmptyRange(*II, Intrinsic::lifetime_start,
3868  Intrinsic::lifetime_end, *this))
3869  return nullptr;
3870  break;
3871  case Intrinsic::assume: {
3872  Value *IIOperand = II->getArgOperand(0);
3873  // Remove an assume if it is followed by an identical assume.
3874  // TODO: Do we need this? Unless there are conflicting assumptions, the
3875  // computeKnownBits(IIOperand) below here eliminates redundant assumes.
3877  if (match(Next, m_Intrinsic<Intrinsic::assume>(m_Specific(IIOperand))))
3878  return eraseInstFromFunction(CI);
3879 
3880  // Canonicalize assume(a && b) -> assume(a); assume(b);
3881  // Note: New assumption intrinsics created here are registered by
3882  // the InstCombineIRInserter object.
3883  FunctionType *AssumeIntrinsicTy = II->getFunctionType();
3884  Value *AssumeIntrinsic = II->getCalledValue();
3885  Value *A, *B;
3886  if (match(IIOperand, m_And(m_Value(A), m_Value(B)))) {
3887  Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic, A, II->getName());
3888  Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic, B, II->getName());
3889  return eraseInstFromFunction(*II);
3890  }
3891  // assume(!(a || b)) -> assume(!a); assume(!b);
3892  if (match(IIOperand, m_Not(m_Or(m_Value(A), m_Value(B))))) {
3893  Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic,
3894  Builder.CreateNot(A), II->getName());
3895  Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic,
3896  Builder.CreateNot(B), II->getName());
3897  return eraseInstFromFunction(*II);
3898  }
3899 
3900  // assume( (load addr) != null ) -> add 'nonnull' metadata to load
3901  // (if assume is valid at the load)
3902  CmpInst::Predicate Pred;
3903  Instruction *LHS;
3904  if (match(IIOperand, m_ICmp(Pred, m_Instruction(LHS), m_Zero())) &&
3905  Pred == ICmpInst::ICMP_NE && LHS->getOpcode() == Instruction::Load &&
3906  LHS->getType()->isPointerTy() &&
3907  isValidAssumeForContext(II, LHS, &DT)) {
3908  MDNode *MD = MDNode::get(II->getContext(), None);
3910  return eraseInstFromFunction(*II);
3911 
3912  // TODO: apply nonnull return attributes to calls and invokes
3913  // TODO: apply range metadata for range check patterns?
3914  }
3915 
3916  // If there is a dominating assume with the same condition as this one,
3917  // then this one is redundant, and should be removed.
3918  KnownBits Known(1);
3919  computeKnownBits(IIOperand, Known, 0, II);
3920  if (Known.isAllOnes())
3921  return eraseInstFromFunction(*II);
3922 
3923  // Update the cache of affected values for this assumption (we might be
3924  // here because we just simplified the condition).
3925  AC.updateAffectedValues(II);
3926  break;
3927  }
3928  case Intrinsic::experimental_gc_relocate: {
3929  // Translate facts known about a pointer before relocating into
3930  // facts about the relocate value, while being careful to
3931  // preserve relocation semantics.
3932  Value *DerivedPtr = cast<GCRelocateInst>(II)->getDerivedPtr();
3933 
3934  // Remove the relocation if unused, note that this check is required
3935  // to prevent the cases below from looping forever.
3936  if (II->use_empty())
3937  return eraseInstFromFunction(*II);
3938 
3939  // Undef is undef, even after relocation.
3940  // TODO: provide a hook for this in GCStrategy. This is clearly legal for
3941  // most practical collectors, but there was discussion in the review thread
3942  // about whether it was legal for all possible collectors.
3943  if (isa<UndefValue>(DerivedPtr))
3944  // Use undef of gc_relocate's type to replace it.
3945  return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
3946 
3947  if (auto *PT = dyn_cast<PointerType>(II->getType())) {
3948  // The relocation of null will be null for most any collector.
3949  // TODO: provide a hook for this in GCStrategy. There might be some
3950  // weird collector this property does not hold for.
3951  if (isa<ConstantPointerNull>(DerivedPtr))
3952  // Use null-pointer of gc_relocate's type to replace it.
3953  return replaceInstUsesWith(*II, ConstantPointerNull::get(PT));
3954 
3955  // isKnownNonNull -> nonnull attribute
3956  if (!II->hasRetAttr(Attribute::NonNull) &&
3957  isKnownNonZero(DerivedPtr, DL, 0, &AC, II, &DT)) {
3958  II->addAttribute(AttributeList::ReturnIndex, Attribute::NonNull);
3959  return II;
3960  }
3961  }
3962 
3963  // TODO: bitcast(relocate(p)) -> relocate(bitcast(p))
3964  // Canonicalize on the type from the uses to the defs
3965 
3966  // TODO: relocate((gep p, C, C2, ...)) -> gep(relocate(p), C, C2, ...)
3967  break;
3968  }
3969 
3970  case Intrinsic::experimental_guard: {
3971  // Is this guard followed by another guard? We scan forward over a small
3972  // fixed window of instructions to handle common cases with conditions
3973  // computed between guards.
3974  Instruction *NextInst = II->getNextNode();
3975  for (unsigned i = 0; i < GuardWideningWindow; i++) {
3976  // Note: Using context-free form to avoid compile time blow up
3977  if (!isSafeToSpeculativelyExecute(NextInst))
3978  break;
3979  NextInst = NextInst->getNextNode();
3980  }
3981  Value *NextCond = nullptr;
3982  if (match(NextInst,
3983  m_Intrinsic<Intrinsic::experimental_guard>(m_Value(NextCond)))) {
3984  Value *CurrCond = II->getArgOperand(0);
3985 
3986  // Remove a guard that it is immediately preceded by an identical guard.
3987  if (CurrCond == NextCond)
3988  return eraseInstFromFunction(*NextInst);
3989 
3990  // Otherwise canonicalize guard(a); guard(b) -> guard(a & b).
3991  Instruction* MoveI = II->getNextNode();
3992  while (MoveI != NextInst) {
3993  auto *Temp = MoveI;
3994  MoveI = MoveI->getNextNode();
3995  Temp->moveBefore(II);
3996  }
3997  II->setArgOperand(0, Builder.CreateAnd(CurrCond, NextCond));
3998  return eraseInstFromFunction(*NextInst);
3999  }
4000  break;
4001  }
4002  }
4003  return visitCallBase(*II);
4004 }
4005 
4006 // Fence instruction simplification
4008  // Remove identical consecutive fences.
4010  if (auto *NFI = dyn_cast<FenceInst>(Next))
4011  if (FI.isIdenticalTo(NFI))
4012  return eraseInstFromFunction(FI);
4013  return nullptr;
4014 }
4015 
4016 // InvokeInst simplification
4018  return visitCallBase(II);
4019 }
4020 
4021 // CallBrInst simplification
4023  return visitCallBase(CBI);
4024 }
4025 
4026 /// If this cast does not affect the value passed through the varargs area, we
4027 /// can eliminate the use of the cast.
4028 static bool isSafeToEliminateVarargsCast(const CallBase &Call,
4029  const DataLayout &DL,
4030  const CastInst *const CI,
4031  const int ix) {
4032  if (!CI->isLosslessCast())
4033  return false;
4034 
4035  // If this is a GC intrinsic, avoid munging types. We need types for
4036  // statepoint reconstruction in SelectionDAG.
4037  // TODO: This is probably something which should be expanded to all
4038  // intrinsics since the entire point of intrinsics is that
4039  // they are understandable by the optimizer.
4040  if (isStatepoint(&Call) || isGCRelocate(&Call) || isGCResult(&Call))
4041  return false;
4042 
4043  // The size of ByVal or InAlloca arguments is derived from the type, so we
4044  // can't change to a type with a different size. If the size were
4045  // passed explicitly we could avoid this check.
4046  if (!Call.isByValOrInAllocaArgument(ix))
4047  return true;
4048 
4049  Type* SrcTy =
4050  cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
4051  Type *DstTy = Call.isByValArgument(ix)
4052  ? Call.getParamByValType(ix)
4053  : cast<PointerType>(CI->getType())->getElementType();
4054  if (!SrcTy->isSized() || !DstTy->isSized())
4055  return false;
4056  if (DL.getTypeAllocSize(SrcTy) != DL.getTypeAllocSize(DstTy))
4057  return false;
4058  return true;
4059 }
4060 
4061 Instruction *InstCombiner::tryOptimizeCall(CallInst *CI) {
4062  if (!CI->getCalledFunction()) return nullptr;
4063 
4064  auto InstCombineRAUW = [this](Instruction *From, Value *With) {
4065  replaceInstUsesWith(*From, With);
4066  };
4067  auto InstCombineErase = [this](Instruction *I) {
4068  eraseInstFromFunction(*I);
4069  };
4070  LibCallSimplifier Simplifier(DL, &TLI, ORE, BFI, PSI, InstCombineRAUW,
4071  InstCombineErase);
4072  if (Value *With = Simplifier.optimizeCall(CI)) {
4073  ++NumSimplified;
4074  return CI->use_empty() ? CI : replaceInstUsesWith(*CI, With);
4075  }
4076 
4077  return nullptr;
4078 }
4079 
4081  // Strip off at most one level of pointer casts, looking for an alloca. This
4082  // is good enough in practice and simpler than handling any number of casts.
4083  Value *Underlying = TrampMem->stripPointerCasts();
4084  if (Underlying != TrampMem &&
4085  (!Underlying->hasOneUse() || Underlying->user_back() != TrampMem))
4086  return nullptr;
4087  if (!isa<AllocaInst>(Underlying))
4088  return nullptr;
4089 
4090  IntrinsicInst *InitTrampoline = nullptr;
4091  for (User *U : TrampMem->users()) {
4093  if (!II)
4094  return nullptr;
4095  if (II->getIntrinsicID() == Intrinsic::init_trampoline) {
4096  if (InitTrampoline)
4097  // More than one init_trampoline writes to this value. Give up.
4098  return nullptr;
4099  InitTrampoline = II;
4100  continue;
4101  }
4102  if (II->getIntrinsicID() == Intrinsic::adjust_trampoline)
4103  // Allow any number of calls to adjust.trampoline.
4104  continue;
4105  return nullptr;
4106  }
4107 
4108  // No call to init.trampoline found.
4109  if (!InitTrampoline)
4110  return nullptr;
4111 
4112  // Check that the alloca is being used in the expected way.
4113  if (InitTrampoline->getOperand(0) != TrampMem)
4114  return nullptr;
4115 
4116  return InitTrampoline;
4117 }
4118 
4120  Value *TrampMem) {
4121  // Visit all the previous instructions in the basic block, and try to find a
4122  // init.trampoline which has a direct path to the adjust.trampoline.
4123  for (BasicBlock::iterator I = AdjustTramp->getIterator(),
4124  E = AdjustTramp->getParent()->begin();
4125  I != E;) {
4126  Instruction *Inst = &*--I;
4127  if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
4128  if (II->getIntrinsicID() == Intrinsic::init_trampoline &&
4129  II->getOperand(0) == TrampMem)
4130  return II;
4131  if (Inst->mayWriteToMemory())
4132  return nullptr;
4133  }
4134  return nullptr;
4135 }
4136 
4137 // Given a call to llvm.adjust.trampoline, find and return the corresponding
4138 // call to llvm.init.trampoline if the call to the trampoline can be optimized
4139 // to a direct call to a function. Otherwise return NULL.
4141  Callee = Callee->stripPointerCasts();
4142  IntrinsicInst *AdjustTramp = dyn_cast<IntrinsicInst>(Callee);
4143  if (!AdjustTramp ||
4144  AdjustTramp->getIntrinsicID() != Intrinsic::adjust_trampoline)
4145  return nullptr;
4146 
4147  Value *TrampMem = AdjustTramp->getOperand(0);
4148 
4150  return IT;
4151  if (IntrinsicInst *IT = findInitTrampolineFromBB(AdjustTramp, TrampMem))
4152  return IT;
4153  return nullptr;
4154 }
4155 
4156 /// Improvements for call, callbr and invoke instructions.
4157 Instruction *InstCombiner::visitCallBase(CallBase &Call) {
4158  if (isAllocLikeFn(&Call, &TLI))
4159  return visitAllocSite(Call);
4160 
4161  bool Changed = false;
4162 
4163  // Mark any parameters that are known to be non-null with the nonnull
4164  // attribute. This is helpful for inlining calls to functions with null
4165  // checks on their arguments.
4166  SmallVector<unsigned, 4> ArgNos;
4167  unsigned ArgNo = 0;
4168 
4169  for (Value *V : Call.args()) {
4170  if (V->getType()->isPointerTy() &&
4171  !Call.paramHasAttr(ArgNo, Attribute::NonNull) &&
4172  isKnownNonZero(V, DL, 0, &AC, &Call, &DT))
4173  ArgNos.push_back(ArgNo);
4174  ArgNo++;
4175  }
4176 
4177  assert(ArgNo == Call.arg_size() && "sanity check");
4178 
4179  if (!ArgNos.empty()) {
4180  AttributeList AS = Call.getAttributes();
4181  LLVMContext &Ctx = Call.getContext();
4182  AS = AS.addParamAttribute(Ctx, ArgNos,
4183  Attribute::get(Ctx, Attribute::NonNull));
4184  Call.setAttributes(AS);
4185  Changed = true;
4186  }
4187 
4188  // If the callee is a pointer to a function, attempt to move any casts to the
4189  // arguments of the call/callbr/invoke.
4190  Value *Callee = Call.getCalledValue();
4191  if (!isa<Function>(Callee) && transformConstExprCastCall(Call))
4192  return nullptr;
4193 
4194  if (Function *CalleeF = dyn_cast<Function>(Callee)) {
4195  // Remove the convergent attr on calls when the callee is not convergent.
4196  if (Call.isConvergent() && !CalleeF->isConvergent() &&
4197  !CalleeF->isIntrinsic()) {
4198  LLVM_DEBUG(dbgs() << "Removing convergent attr from instr " << Call
4199  << "\n");
4200  Call.setNotConvergent();
4201  return &Call;
4202  }
4203 
4204  // If the call and callee calling conventions don't match, this call must
4205  // be unreachable, as the call is undefined.
4206  if (CalleeF->getCallingConv() != Call.getCallingConv() &&
4207  // Only do this for calls to a function with a body. A prototype may
4208  // not actually end up matching the implementation's calling conv for a
4209  // variety of reasons (e.g. it may be written in assembly).
4210  !CalleeF->isDeclaration()) {
4211  Instruction *OldCall = &Call;
4212  CreateNonTerminatorUnreachable(OldCall);
4213  // If OldCall does not return void then replaceAllUsesWith undef.
4214  // This allows ValueHandlers and custom metadata to adjust itself.
4215  if (!OldCall->getType()->isVoidTy())
4216  replaceInstUsesWith(*OldCall, UndefValue::get(OldCall->getType()));
4217  if (isa<CallInst>(OldCall))
4218  return eraseInstFromFunction(*OldCall);
4219 
4220  // We cannot remove an invoke or a callbr, because it would change thexi
4221  // CFG, just change the callee to a null pointer.
4222  cast<CallBase>(OldCall)->setCalledFunction(
4223  CalleeF->getFunctionType(),
4224  Constant::getNullValue(CalleeF->getType()));
4225  return nullptr;
4226  }
4227  }
4228 
4229  if ((isa<ConstantPointerNull>(Callee) &&
4230  !NullPointerIsDefined(Call.getFunction())) ||
4231  isa<UndefValue>(Callee)) {
4232  // If Call does not return void then replaceAllUsesWith undef.
4233  // This allows ValueHandlers and custom metadata to adjust itself.
4234  if (!Call.getType()->isVoidTy())
4235  replaceInstUsesWith(Call, UndefValue::get(Call.getType()));
4236 
4237  if (Call.isTerminator()) {
4238  // Can't remove an invoke or callbr because we cannot change the CFG.
4239  return nullptr;
4240  }
4241 
4242  // This instruction is not reachable, just remove it.
4243  CreateNonTerminatorUnreachable(&Call);
4244  return eraseInstFromFunction(Call);
4245  }
4246 
4247  if (IntrinsicInst *II = findInitTrampoline(Callee))
4248  return transformCallThroughTrampoline(Call, *II);
4249 
4250  PointerType *PTy = cast<PointerType>(Callee->getType());
4251  FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
4252  if (FTy->isVarArg()) {
4253  int ix = FTy->getNumParams();
4254  // See if we can optimize any arguments passed through the varargs area of
4255  // the call.
4256  for (auto I = Call.arg_begin() + FTy->getNumParams(), E = Call.arg_end();
4257  I != E; ++I, ++ix) {
4258  CastInst *CI = dyn_cast<CastInst>(*I);
4259  if (CI && isSafeToEliminateVarargsCast(Call, DL, CI, ix)) {
4260  *I = CI->getOperand(0);
4261 
4262  // Update the byval type to match the argument type.
4263  if (Call.isByValArgument(ix)) {
4264  Call.removeParamAttr(ix, Attribute::ByVal);
4265  Call.addParamAttr(
4267  Call.getContext(),
4268  CI->getOperand(0)->getType()->getPointerElementType()));
4269  }
4270  Changed = true;
4271  }
4272  }
4273  }
4274 
4275  if (isa<InlineAsm>(Callee) && !Call.doesNotThrow()) {
4276  // Inline asm calls cannot throw - mark them 'nounwind'.
4277  Call.setDoesNotThrow();
4278  Changed = true;
4279  }
4280 
4281  // Try to optimize the call if possible, we require DataLayout for most of
4282  // this. None of these calls are seen as possibly dead so go ahead and
4283  // delete the instruction now.
4284  if (CallInst *CI = dyn_cast<CallInst>(&Call)) {
4285  Instruction *I = tryOptimizeCall(CI);
4286  // If we changed something return the result, etc. Otherwise let
4287  // the fallthrough check.
4288  if (I) return eraseInstFromFunction(*I);
4289  }
4290 
4291  return Changed ? &Call : nullptr;
4292 }
4293 
4294 /// If the callee is a constexpr cast of a function, attempt to move the cast to
4295 /// the arguments of the call/callbr/invoke.
4296 bool InstCombiner::transformConstExprCastCall(CallBase &Call) {
4298  if (!Callee)
4299  return false;
4300 
4301  // If this is a call to a thunk function, don't remove the cast. Thunks are
4302  // used to transparently forward all incoming parameters and outgoing return
4303  // values, so it's important to leave the cast in place.
4304  if (Callee->hasFnAttribute("thunk"))
4305  return false;
4306 
4307  // If this is a musttail call, the callee's prototype must match the caller's
4308  // prototype with the exception of pointee types. The code below doesn't
4309  // implement that, so we can't do this transform.
4310  // TODO: Do the transform if it only requires adding pointer casts.
4311  if (Call.isMustTailCall())
4312  return false;
4313 
4314  Instruction *Caller = &Call;
4315  const AttributeList &CallerPAL = Call.getAttributes();
4316 
4317  // Okay, this is a cast from a function to a different type. Unless doing so
4318  // would cause a type conversion of one of our arguments, change this call to
4319  // be a direct call with arguments casted to the appropriate types.
4321  Type *OldRetTy = Caller->getType();
4322  Type *NewRetTy = FT->getReturnType();
4323 
4324  // Check to see if we are changing the return type...
4325  if (OldRetTy != NewRetTy) {
4326 
4327  if (NewRetTy->isStructTy())
4328  return false; // TODO: Handle multiple return values.
4329 
4330  if (!CastInst::isBitOrNoopPointerCastable(NewRetTy, OldRetTy, DL)) {
4331  if (Callee->isDeclaration())
4332  return false; // Cannot transform this return value.
4333 
4334  if (!Caller->use_empty() &&
4335  // void -> non-void is handled specially
4336  !NewRetTy->isVoidTy())
4337  return false; // Cannot transform this return value.
4338  }
4339 
4340  if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
4341  AttrBuilder RAttrs(CallerPAL, AttributeList::ReturnIndex);
4342  if (RAttrs.overlaps(AttributeFuncs::typeIncompatible(NewRetTy)))
4343  return false; // Attribute not compatible with transformed value.
4344  }
4345 
4346  // If the callbase is an invoke/callbr instruction, and the return value is
4347  // used by a PHI node in a successor, we cannot change the return type of
4348  // the call because there is no place to put the cast instruction (without
4349  // breaking the critical edge). Bail out in this case.
4350  if (!Caller->use_empty()) {
4351  if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
4352  for (User *U : II->users())
4353  if (PHINode *PN = dyn_cast<PHINode>(U))
4354  if (PN->getParent() == II->getNormalDest() ||
4355  PN->getParent() == II->getUnwindDest())
4356  return false;
4357  // FIXME: Be conservative for callbr to avoid a quadratic search.
4358  if (isa<CallBrInst>(Caller))
4359  return false;
4360  }
4361  }
4362 
4363  unsigned NumActualArgs = Call.arg_size();
4364  unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
4365 
4366  // Prevent us turning:
4367  // declare void @takes_i32_inalloca(i32* inalloca)
4368  // call void bitcast (void (i32*)* @takes_i32_inalloca to void (i32)*)(i32 0)
4369  //
4370  // into:
4371  // call void @takes_i32_inalloca(i32* null)
4372  //
4373  // Similarly, avoid folding away bitcasts of byval calls.
4374  if (Callee->getAttributes().hasAttrSomewhere(Attribute::InAlloca) ||
4375  Callee->getAttributes().hasAttrSomewhere(Attribute::ByVal))
4376  return false;
4377 
4378  auto AI = Call.arg_begin();
4379  for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
4380  Type *ParamTy = FT->getParamType(i);
4381  Type *ActTy = (*AI)->getType();
4382 
4383  if (!CastInst::isBitOrNoopPointerCastable(ActTy, ParamTy, DL))
4384  return false; // Cannot transform this parameter value.
4385 
4386  if (AttrBuilder(CallerPAL.getParamAttributes(i))
4387  .overlaps(AttributeFuncs::typeIncompatible(ParamTy)))
4388  return false; // Attribute not compatible with transformed value.
4389 
4390  if (Call.isInAllocaArgument(i))
4391  return false; // Cannot transform to and from inalloca.
4392 
4393  // If the parameter is passed as a byval argument, then we have to have a
4394  // sized type and the sized type has to have the same size as the old type.
4395  if (ParamTy != ActTy && CallerPAL.hasParamAttribute(i, Attribute::ByVal)) {
4396  PointerType *ParamPTy = dyn_cast<PointerType>(ParamTy);
4397  if (!ParamPTy || !ParamPTy->getElementType()->isSized())
4398  return false;
4399 
4400  Type *CurElTy = Call.getParamByValType(i);
4401  if (DL.getTypeAllocSize(CurElTy) !=
4402  DL.getTypeAllocSize(ParamPTy->getElementType()))
4403  return false;
4404  }
4405  }
4406 
4407  if (Callee->isDeclaration()) {
4408  // Do not delete arguments unless we have a function body.
4409  if (FT->getNumParams() < NumActualArgs && !FT->isVarArg())
4410  return false;
4411 
4412  // If the callee is just a declaration, don't change the varargsness of the
4413  // call. We don't want to introduce a varargs call where one doesn't
4414  // already exist.
4415  PointerType *APTy = cast<PointerType>(Call.getCalledValue()->getType());
4416  if (FT->isVarArg()!=cast<FunctionType>(APTy->getElementType())->isVarArg())
4417  return false;
4418 
4419  // If both the callee and the cast type are varargs, we still have to make
4420  // sure the number of fixed parameters are the same or we have the same
4421  // ABI issues as if we introduce a varargs call.
4422  if (FT->isVarArg() &&
4423  cast<FunctionType>(APTy->getElementType())->isVarArg() &&
4424  FT->getNumParams() !=
4425  cast<FunctionType>(APTy->getElementType())->getNumParams())
4426  return false;
4427  }
4428 
4429  if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
4430  !CallerPAL.isEmpty()) {
4431  // In this case we have more arguments than the new function type, but we
4432  // won't be dropping them. Check that these extra arguments have attributes
4433  // that are compatible with being a vararg call argument.
4434  unsigned SRetIdx;
4435  if (CallerPAL.hasAttrSomewhere(Attribute::StructRet, &SRetIdx) &&
4436  SRetIdx > FT->getNumParams())
4437  return false;
4438  }
4439 
4440  // Okay, we decided that this is a safe thing to do: go ahead and start
4441  // inserting cast instructions as necessary.
4444  Args.reserve(NumActualArgs);
4445  ArgAttrs.reserve(NumActualArgs);
4446 
4447  // Get any return attributes.
4448  AttrBuilder RAttrs(CallerPAL, AttributeList::ReturnIndex);
4449 
4450  // If the return value is not being used, the type may not be compatible
4451  // with the existing attributes. Wipe out any problematic attributes.
4452  RAttrs.remove(AttributeFuncs::typeIncompatible(NewRetTy));
4453 
4454  LLVMContext &Ctx = Call.getContext();
4455  AI = Call.arg_begin();
4456  for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
4457  Type *ParamTy = FT->getParamType(i);
4458 
4459  Value *NewArg = *AI;
4460  if ((*AI)->getType() != ParamTy)
4461  NewArg = Builder.CreateBitOrPointerCast(*AI, ParamTy);
4462  Args.push_back(NewArg);
4463 
4464  // Add any parameter attributes.
4465  if (CallerPAL.hasParamAttribute(i, Attribute::ByVal)) {
4466  AttrBuilder AB(CallerPAL.getParamAttributes(i));
4467  AB.addByValAttr(NewArg->getType()->getPointerElementType());
4468  ArgAttrs.push_back(AttributeSet::get(Ctx, AB));
4469  } else
4470  ArgAttrs.push_back(CallerPAL.getParamAttributes(i));
4471  }
4472 
4473  // If the function takes more arguments than the call was taking, add them
4474  // now.
4475  for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i) {
4477  ArgAttrs.push_back(AttributeSet());
4478  }
4479 
4480  // If we are removing arguments to the function, emit an obnoxious warning.
4481  if (FT->getNumParams() < NumActualArgs) {
4482  // TODO: if (!FT->isVarArg()) this call may be unreachable. PR14722
4483  if (FT->isVarArg()) {
4484  // Add all of the arguments in their promoted form to the arg list.
4485  for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
4486  Type *PTy = getPromotedType((*AI)->getType());
4487  Value *NewArg = *AI;
4488  if (PTy != (*AI)->getType()) {
4489  // Must promote to pass through va_arg area!
4490  Instruction::CastOps opcode =
4491  CastInst::getCastOpcode(*AI, false, PTy, false);
4492  NewArg = Builder.CreateCast(opcode, *AI, PTy);
4493  }
4494  Args.push_back(NewArg);
4495 
4496  // Add any parameter attributes.
4497  ArgAttrs.push_back(CallerPAL.getParamAttributes(i));
4498  }
4499  }
4500  }
4501 
4502  AttributeSet FnAttrs = CallerPAL.getFnAttributes();
4503 
4504  if (NewRetTy->isVoidTy())
4505  Caller->setName(""); // Void type should not have a name.
4506 
4507  assert((ArgAttrs.size() == FT->getNumParams() || FT->isVarArg()) &&
4508  "missing argument attributes");
4509  AttributeList NewCallerPAL = AttributeList::get(
4510  Ctx, FnAttrs, AttributeSet::get(Ctx, RAttrs), ArgAttrs);
4511 
4513  Call.getOperandBundlesAsDefs(OpBundles);
4514 
4515  CallBase *NewCall;
4516  if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
4517  NewCall = Builder.CreateInvoke(Callee, II->getNormalDest(),
4518  II->getUnwindDest(), Args, OpBundles);
4519  } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(Caller)) {
4520  NewCall = Builder.CreateCallBr(Callee, CBI->getDefaultDest(),
4521  CBI->getIndirectDests(), Args, OpBundles);
4522  } else {
4523  NewCall = Builder.CreateCall(Callee, Args, OpBundles);
4524  cast<CallInst>(NewCall)->setTailCallKind(
4525  cast<CallInst>(Caller)->getTailCallKind());
4526  }
4527  NewCall->takeName(Caller);
4528  NewCall->setCallingConv(Call.getCallingConv());
4529  NewCall->setAttributes(NewCallerPAL);
4530 
4531  // Preserve the weight metadata for the new call instruction. The metadata
4532  // is used by SamplePGO to check callsite's hotness.
4533  uint64_t W;
4534  if (Caller->extractProfTotalWeight(W))
4535  NewCall->setProfWeight(W);
4536 
4537  // Insert a cast of the return type as necessary.
4538  Instruction *NC = NewCall;
4539  Value *NV = NC;
4540  if (OldRetTy != NV->getType() && !Caller->use_empty()) {
4541  if (!NV->getType()->isVoidTy()) {
4542  NV = NC = CastInst::CreateBitOrPointerCast(NC, OldRetTy);
4543  NC->setDebugLoc(Caller->getDebugLoc());
4544 
4545  // If this is an invoke/callbr instruction, we should insert it after the
4546  // first non-phi instruction in the normal successor block.
4547  if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
4548  BasicBlock::iterator I = II->getNormalDest()->getFirstInsertionPt();
4549  InsertNewInstBefore(NC, *I);
4550  } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(Caller)) {
4551  BasicBlock::iterator I = CBI->getDefaultDest()->getFirstInsertionPt();
4552  InsertNewInstBefore(NC, *I);
4553  } else {
4554  // Otherwise, it's a call, just insert cast right after the call.
4555  InsertNewInstBefore(NC, *Caller);
4556  }
4557  Worklist.AddUsersToWorkList(*Caller);
4558  } else {
4559  NV = UndefValue::get(Caller->getType());
4560  }
4561  }
4562 
4563  if (!Caller->use_empty())
4564  replaceInstUsesWith(*Caller, NV);
4565  else if (Caller->hasValueHandle()) {
4566  if (OldRetTy == NV->getType())
4567  ValueHandleBase::ValueIsRAUWd(Caller, NV);
4568  else
4569  // We cannot call ValueIsRAUWd with a different type, and the
4570  // actual tracked value will disappear.
4572  }
4573 
4574  eraseInstFromFunction(*Caller);
4575  return true;
4576 }
4577 
4578 /// Turn a call to a function created by init_trampoline / adjust_trampoline
4579 /// intrinsic pair into a direct call to the underlying function.
4580 Instruction *
4581 InstCombiner::transformCallThroughTrampoline(CallBase &Call,
4582  IntrinsicInst &Tramp) {
4583  Value *Callee = Call.getCalledValue();
4584  Type *CalleeTy = Callee->getType();
4585  FunctionType *FTy = Call.getFunctionType();
4587 
4588  // If the call already has the 'nest' attribute somewhere then give up -
4589  // otherwise 'nest' would occur twice after splicing in the chain.
4590  if (Attrs.hasAttrSomewhere(Attribute::Nest))
4591  return nullptr;
4592 
4593  Function *NestF = cast<Function>(Tramp.getArgOperand(1)->stripPointerCasts());
4594  FunctionType *NestFTy = NestF->getFunctionType();
4595 
4596  AttributeList NestAttrs = NestF->getAttributes();
4597  if (!NestAttrs.isEmpty()) {
4598  unsigned NestArgNo = 0;
4599  Type *NestTy = nullptr;
4600  AttributeSet NestAttr;
4601 
4602  // Look for a parameter marked with the 'nest' attribute.
4603  for (FunctionType::param_iterator I = NestFTy->param_begin(),
4604  E = NestFTy->param_end();
4605  I != E; ++NestArgNo, ++I) {
4606  AttributeSet AS = NestAttrs.getParamAttributes(NestArgNo);
4607  if (AS.hasAttribute(Attribute::Nest)) {
4608  // Record the parameter type and any other attributes.
4609  NestTy = *I;
4610  NestAttr = AS;
4611  break;
4612  }
4613  }
4614 
4615  if (NestTy) {
4616  std::vector<Value*> NewArgs;
4617  std::vector<AttributeSet> NewArgAttrs;
4618  NewArgs.reserve(Call.arg_size() + 1);
4619  NewArgAttrs.reserve(Call.arg_size());
4620 
4621  // Insert the nest argument into the call argument list, which may
4622  // mean appending it. Likewise for attributes.
4623 
4624  {
4625  unsigned ArgNo = 0;
4626  auto I = Call.arg_begin(), E = Call.arg_end();
4627  do {
4628  if (ArgNo == NestArgNo) {
4629  // Add the chain argument and attributes.
4630  Value *NestVal = Tramp.getArgOperand(2);
4631  if (NestVal->getType() != NestTy)
4632  NestVal = Builder.CreateBitCast(NestVal, NestTy, "nest");
4633  NewArgs.push_back(NestVal);
4634  NewArgAttrs.push_back(NestAttr);
4635  }
4636 
4637  if (I == E)
4638  break;
4639 
4640  // Add the original argument and attributes.
4641  NewArgs.push_back(*I);
4642  NewArgAttrs.push_back(Attrs.getParamAttributes(ArgNo));
4643 
4644  ++ArgNo;
4645  ++I;
4646  } while (true);
4647  }
4648 
4649  // The trampoline may have been bitcast to a bogus type (FTy).
4650  // Handle this by synthesizing a new function type, equal to FTy
4651  // with the chain parameter inserted.
4652 
4653  std::vector<Type*> NewTypes;
4654  NewTypes.reserve(FTy->getNumParams()+1);
4655 
4656  // Insert the chain's type into the list of parameter types, which may
4657  // mean appending it.
4658  {
4659  unsigned ArgNo = 0;
4661  E = FTy->param_end();
4662 
4663  do {
4664  if (ArgNo == NestArgNo)
4665  // Add the chain's type.
4666  NewTypes.push_back(NestTy);
4667 
4668  if (I == E)
4669  break;
4670 
4671  // Add the original type.
4672  NewTypes.push_back(*I);
4673 
4674  ++ArgNo;
4675  ++I;
4676  } while (true);
4677  }
4678 
4679  // Replace the trampoline call with a direct call. Let the generic
4680  // code sort out any function type mismatches.
4681  FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
4682  FTy->isVarArg());
4683  Constant *NewCallee =
4684  NestF->getType() == PointerType::getUnqual(NewFTy) ?
4685  NestF : ConstantExpr::getBitCast(NestF,
4686  PointerType::getUnqual(NewFTy));
4687  AttributeList NewPAL =
4689  Attrs.getRetAttributes(), NewArgAttrs);
4690 
4692  Call.getOperandBundlesAsDefs(OpBundles);
4693 
4694  Instruction *NewCaller;
4695  if (InvokeInst *II = dyn_cast<InvokeInst>(&Call)) {
4696  NewCaller = InvokeInst::Create(NewFTy, NewCallee,
4697  II->getNormalDest(), II->getUnwindDest(),
4698  NewArgs, OpBundles);
4699  cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
4700  cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
4701  } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(&Call)) {
4702  NewCaller =
4703  CallBrInst::Create(NewFTy, NewCallee, CBI->getDefaultDest(),
4704  CBI->getIndirectDests(), NewArgs, OpBundles);
4705  cast<CallBrInst>(NewCaller)->setCallingConv(CBI->getCallingConv());
4706  cast<CallBrInst>(NewCaller)->setAttributes(NewPAL);
4707  } else {
4708  NewCaller = CallInst::Create(NewFTy, NewCallee, NewArgs, OpBundles);
4709  cast<CallInst>(NewCaller)->setTailCallKind(
4710  cast<CallInst>(Call).getTailCallKind());
4711  cast<CallInst>(NewCaller)->setCallingConv(
4712  cast<CallInst>(Call).getCallingConv());
4713  cast<CallInst>(NewCaller)->setAttributes(NewPAL);
4714  }
4715  NewCaller->setDebugLoc(Call.getDebugLoc());
4716 
4717  return NewCaller;
4718  }
4719  }
4720 
4721  // Replace the trampoline call with a direct call. Since there is no 'nest'
4722  // parameter, there is no need to adjust the argument list. Let the generic
4723  // code sort out any function type mismatches.
4724  Constant *NewCallee = ConstantExpr::getBitCast(NestF, CalleeTy);
4725  Call.setCalledFunction(FTy, NewCallee);
4726  return &Call;
4727 }
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
bool isFPPredicate() const
Definition: InstrTypes.h:824
const NoneType None
Definition: None.h:23
A vector constant whose element type is a simple 1/2/4/8-byte integer or float/double, and whose elements are just simple data values (i.e.
Definition: Constants.h:761
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
Definition: PatternMatch.h:756
uint64_t CallInst * C
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...
LibCallSimplifier - This class implements a collection of optimizations that replace well formed call...
IntegerType * getType() const
getType - Specialize the getType() method to always return an IntegerType, which reduces the amount o...
Definition: Constants.h:171
unsigned Log2_32_Ceil(uint32_t Value)
Return the ceil log base 2 of the specified value, 32 if the value is zero.
Definition: MathExtras.h:551
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:110
void computeKnownBits(const Value *V, KnownBits &Known, unsigned Depth, const Instruction *CxtI) const
void copyFastMathFlags(FastMathFlags FMF)
Convenience function for transferring all fast-math flag values to this instruction, which must be an operator which supports these flags.
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
Definition: PatternMatch.h:70
static void ValueIsDeleted(Value *V)
Definition: Value.cpp:847
class_match< UndefValue > m_Undef()
Match an arbitrary undef constant.
Definition: PatternMatch.h:86
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
bool isZero() const
Definition: APFloat.h:1153
static IntegerType * getInt1Ty(LLVMContext &C)
Definition: Type.cpp:172
class_match< CmpInst > m_Cmp()
Matches any compare instruction and ignore it.
Definition: PatternMatch.h:78
uint64_t getZExtValue() const
Get zero extended value.
Definition: APInt.h:1562
unsigned getOrEnforceKnownAlignment(Value *V, unsigned PrefAlign, const DataLayout &DL, const Instruction *CxtI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr)
Try to ensure that the alignment of V is at least PrefAlign bytes.
Definition: Local.cpp:1200
APInt sext(unsigned width) const
Sign extend to a new width.
Definition: APInt.cpp:833
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
static Value * simplifyX86immShift(const IntrinsicInst &II, InstCombiner::BuilderTy &Builder)
static APInt getAllOnesValue(unsigned numBits)
Get the all-ones value.
Definition: APInt.h:561
is_zero m_Zero()
Match any null constant or a vector with all elements equal to 0.
Definition: PatternMatch.h:375
DiagnosticInfoOptimizationBase::Argument NV
Atomic ordering constants.
Value * CreateAddrSpaceCast(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:1814
Value * CreateZExtOrTrunc(Value *V, Type *DestTy, const Twine &Name="")
Create a ZExt or Trunc from the integer value V to DestTy.
Definition: IRBuilder.h:1746
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition: ilist_node.h:288
static Type * makeCmpResultType(Type *opnd_type)
Create a result type for fcmp/icmp.
Definition: InstrTypes.h:975
This class represents lattice values for constants.
Definition: AllocatorList.h:23
Type * getParamType(unsigned i) const
Parameter type accessors.
Definition: DerivedTypes.h:135
Constant * getElementAsConstant(unsigned i) const
Return a Constant for a specified index&#39;s element.
Definition: Constants.cpp:2751
unsigned countMinPopulation() const
Returns the number of bits known to be one.
Definition: KnownBits.h:196
static Value * simplifyX86pack(IntrinsicInst &II, InstCombiner::BuilderTy &Builder, bool IsSigned)
Represents an op.with.overflow intrinsic.
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:65
m_Intrinsic_Ty< Opnd0 >::Ty m_BitReverse(const Opnd0 &Op0)
Instruction * visitCallInst(CallInst &CI)
CallInst simplification.
bool isSized(SmallPtrSetImpl< Type *> *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition: Type.h:264
LoadInst * CreateAlignedLoad(Type *Ty, Value *Ptr, unsigned Align, const char *Name)
Provided to resolve &#39;CreateAlignedLoad(Ptr, Align, "...")&#39; correctly, instead of converting the strin...
Definition: IRBuilder.h:1470
bool isConvergent() const
Determine if the invoke is convergent.
Definition: InstrTypes.h:1695
An instruction for ordering other memory operations.
Definition: Instructions.h:454
static MDString * get(LLVMContext &Context, StringRef Str)
Definition: Metadata.cpp:453
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Instruction * visitVACopyInst(VACopyInst &I)
static Instruction * simplifyInvariantGroupIntrinsic(IntrinsicInst &II, InstCombiner &IC)
This function transforms launder.invariant.group and strip.invariant.group like: launder(launder(x)) ...
static ConstantAggregateZero * get(Type *Ty)
Definition: Constants.cpp:1341
void setProfWeight(uint64_t W)
Sets the branch_weights metadata to W for CallInst.
Value * CreateICmpSLT(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1948
APInt uadd_sat(const APInt &RHS) const
Definition: APInt.cpp:1966
static bool simplifyX86MaskedStore(IntrinsicInst &II, InstCombiner &IC)
This class represents a function call, abstracting a target machine&#39;s calling convention.
m_Intrinsic_Ty< Opnd0 >::Ty m_FAbs(const Opnd0 &Op0)
This file contains the declarations for metadata subclasses.
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Get a value with low bits set.
Definition: APInt.h:647
void setOrdering(AtomicOrdering Ordering)
Sets the ordering constraint of this load instruction.
Definition: Instructions.h:253
class_match< Constant > m_Constant()
Match an arbitrary Constant and ignore it.
Definition: PatternMatch.h:89
static PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space...
Definition: Type.cpp:628
static uint64_t round(uint64_t Acc, uint64_t Input)
Definition: xxhash.cpp:57
m_Intrinsic_Ty< Opnd0 >::Ty m_BSwap(const Opnd0 &Op0)
bool hasValueHandle() const
Return true if there is a value handle associated with this value.
Definition: Value.h:485
bool mayWriteToMemory() const
Return true if this instruction may modify memory.
bool isSubsetOf(const APInt &RHS) const
This operation checks that all bits set in this APInt are also set in RHS.
Definition: APInt.h:1328
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", Instruction *InsertBefore=nullptr, Instruction *MDFrom=nullptr)
static Instruction * foldCttzCtlz(IntrinsicInst &II, InstCombiner &IC)
Always overflows in the direction of signed/unsigned min value.
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:720
bool isTerminator() const
Definition: Instruction.h:128
static CastInst * CreateBitOrPointerCast(Value *S, Type *Ty, const Twine &Name="", Instruction *InsertBefore=nullptr)
Create a BitCast, a PtrToInt, or an IntToPTr cast instruction.
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:1192
bool isValidAssumeForContext(const Instruction *I, const Instruction *CxtI, const DominatorTree *DT=nullptr)
Return true if it is valid to use the assumptions provided by an assume intrinsic, I, at the point in the control-flow identified by the context instruction, CxtI.
STATISTIC(NumFunctions, "Total number of functions")
void setArgOperand(unsigned i, Value *v)
Definition: InstrTypes.h:1246
Metadata node.
Definition: Metadata.h:863
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Definition: InstrTypes.h:1100
F(f)
Type * getStructElementType(unsigned N) const
Definition: DerivedTypes.h:365
User::op_iterator arg_end()
Return the iterator pointing to the end of the argument list.
Definition: InstrTypes.h:1212
const fltSemantics & getSemantics() const
Definition: APFloat.h:1165
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
Definition: DerivedTypes.h:580
param_iterator param_end() const
Definition: DerivedTypes.h:129
BinaryOp_match< LHS, RHS, Instruction::FSub > m_FSub(const LHS &L, const RHS &R)
Definition: PatternMatch.h:659
An instruction for reading from memory.
Definition: Instructions.h:167
static IntegerType * getInt64Ty(LLVMContext &C)
Definition: Type.cpp:176
APInt zextOrTrunc(unsigned width) const
Zero extend or truncate to width.
Definition: APInt.cpp:875
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:1946
static Constant * getSub(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
Definition: Constants.cpp:2239
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.cpp:137
bool isVectorTy() const
True if this is an instance of VectorType.
Definition: Type.h:229
LLVM_READONLY APFloat maximum(const APFloat &A, const APFloat &B)
Implements IEEE 754-2018 maximum semantics.
Definition: APFloat.h:1272
void reserve(size_type N)
Definition: SmallVector.h:369
void addAttribute(unsigned i, Attribute::AttrKind Kind)
adds the attribute to the list of attributes.
Definition: InstrTypes.h:1383
Value * getLength() const
void copyIRFlags(const Value *V, bool IncludeWrapFlags=true)
Convenience method to copy supported exact, fast-math, and (optionally) wrapping flags from V to this...
static CallBrInst * Create(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest, ArrayRef< BasicBlock *> IndirectDests, ArrayRef< Value *> Args, const Twine &NameStr, Instruction *InsertBefore=nullptr)
cst_pred_ty< is_zero_int > m_ZeroInt()
Match an integer 0 or a vector with all elements equal to 0.
Definition: PatternMatch.h:363
Instruction * visitVAStartInst(VAStartInst &I)
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition: APInt.h:534
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition: APInt.h:1508
Value * CreateLaunderInvariantGroup(Value *Ptr)
Create a launder.invariant.group intrinsic call.
Definition: IRBuilder.h:2222
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition: Type.h:129
const CallInst * isFreeCall(const Value *I, const TargetLibraryInfo *TLI)
isFreeCall - Returns non-null if the value is a call to the builtin free()
static Constant * getNullValue(Type *Ty)
Constructor to create a &#39;0&#39; constant of arbitrary type.
Definition: Constants.cpp:274
static bool isBitOrNoopPointerCastable(Type *SrcTy, Type *DestTy, const DataLayout &DL)
Check whether a bitcast, inttoptr, or ptrtoint cast between these types is valid and a no-op...
Value * getDest() const
This is just like getRawDest, but it strips off any cast instructions (including addrspacecast) that ...
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:268
bool isIdenticalTo(const Instruction *I) const
Return true if the specified instruction is exactly identical to the current one. ...
Value * getArgOperand(unsigned i) const
Definition: InstrTypes.h:1241
static BinaryOperator * CreateNSW(BinaryOps Opc, Value *V1, Value *V2, const Twine &Name="")
Definition: InstrTypes.h:289
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml", "ocaml 3.10-compatible collector")
opStatus divide(const APFloat &RHS, roundingMode RM)
Definition: APFloat.h:978
static Instruction * SimplifyNVVMIntrinsic(IntrinsicInst *II, InstCombiner &IC)
bool match(Val *V, const Pattern &P)
Definition: PatternMatch.h:47
Instruction * visitInvokeInst(InvokeInst &II)
static Constant * getIntegerCast(Constant *C, Type *Ty, bool isSigned)
Create a ZExt, Bitcast or Trunc for integer -> integer casts.
Definition: Constants.cpp:1622
bool isSigned() const
Definition: InstrTypes.h:902
APInt getLoBits(unsigned numBits) const
Compute an APInt containing numBits lowbits from this APInt.
Definition: APInt.cpp:515
static APFloat fmed3AMDGCN(const APFloat &Src0, const APFloat &Src1, const APFloat &Src2)
BinaryOp_match< LHS, RHS, Instruction::Xor > m_Xor(const LHS &L, const RHS &R)
Definition: PatternMatch.h:768
Type * getPointerElementType() const
Definition: Type.h:376
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE, etc.
Definition: InstrTypes.h:831
const DataLayout & getDataLayout() const
Get the data layout for the module&#39;s target platform.
Definition: Module.cpp:369
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:80
static Value * simplifyX86movmsk(const IntrinsicInst &II, InstCombiner::BuilderTy &Builder)
This is the base class for all instructions that perform data casts.
Definition: InstrTypes.h:439
bool isNonNegative() const
Determine if this APInt Value is non-negative (>= 0)
Definition: APInt.h:368
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
Definition: ArrayRef.h:450
APInt shl(unsigned shiftAmt) const
Left-shift function.
Definition: APInt.h:992
static Value * simplifyNeonTbl1(const IntrinsicInst &II, InstCombiner::BuilderTy &Builder)
Convert a table lookup to shufflevector if the mask is constant.
Instruction * eraseInstFromFunction(Instruction &I)
Combiner aware instruction erasure.
CastClass_match< OpTy, Instruction::Trunc > m_Trunc(const OpTy &Op)
Matches Trunc.
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition: Type.h:196
The core instruction combiner logic.
This file contains the simple types necessary to represent the attributes associated with functions a...
LLVM_READONLY APFloat minimum(const APFloat &A, const APFloat &B)
Implements IEEE 754-2018 minimum semantics.
Definition: APFloat.h:1259
AttributeSet getRetAttributes() const
The attributes for the ret value are returned.
static Constant * getSExt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:1660
AttrBuilder & addByValAttr(Type *Ty)
This turns a byval type into the form used internally in Attribute.
void setName(const Twine &Name)
Change the name of the value.
Definition: Value.cpp:285
Value * CreateICmpSGT(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1940
uint64_t getNumElements() const
For scalable vectors, this will return the minimum number of elements in the vector.
Definition: DerivedTypes.h:393
void lshrInPlace(unsigned ShiftAmt)
Logical right-shift this APInt by ShiftAmt in place.
Definition: APInt.h:977
bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Determine whether the argument or parameter has the given attribute.
ELFYAML::ELF_STO Other
Definition: ELFYAML.cpp:870
This file implements a class to represent arbitrary precision integral constant values and operations...
All zero aggregate value.
Definition: Constants.h:340
static Value * simplifyX86vpermv(const IntrinsicInst &II, InstCombiner::BuilderTy &Builder)
Attempt to convert vpermd/vpermps to shufflevector if the mask is constant.
Metadata * LowAndHigh[]
static Value * simplifyX86addcarry(const IntrinsicInst &II, InstCombiner::BuilderTy &Builder)
Value * lowerObjectSizeCall(IntrinsicInst *ObjectSize, const DataLayout &DL, const TargetLibraryInfo *TLI, bool MustSucceed)
Try to turn a call to @llvm.objectsize into an integer value of the given Type.
static bool haveSameOperands(const IntrinsicInst &I, const IntrinsicInst &E, unsigned NumOperands)
DominatorTree & getDominatorTree() const
unsigned countMaxPopulation() const
Returns the maximum number of bits that could be one.
Definition: KnownBits.h:201
Key
PAL metadata keys.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWAdd(const LHS &L, const RHS &R)
Definition: PatternMatch.h:852
bool doesNotThrow() const
Determine if the call cannot unwind.
Definition: InstrTypes.h:1683
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition: Constants.cpp:84
Class to represent function types.
Definition: DerivedTypes.h:103
static Value * peekThroughBitcast(Value *V, bool OneUseOnly=false)
Return the source operand of a potentially bitcasted value while optionally checking if it has one us...
Value * CreateBitCast(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:1809
bool isInfinity() const
Definition: APFloat.h:1154
FastMathFlags getFastMathFlags() const
Convenience function for getting all the fast-math flags, which must be an operator which supports th...
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:244
cstfp_pred_ty< is_nan > m_NaN()
Match an arbitrary NaN constant.
Definition: PatternMatch.h:426
apfloat_match m_APFloat(const APFloat *&Res)
Match a ConstantFP or splatted ConstantVector, binding the specified pointer to the contained APFloat...
Definition: PatternMatch.h:179
This represents the llvm.va_start intrinsic.
CastClass_match< OpTy, Instruction::FPExt > m_FPExt(const OpTy &Op)
Matches FPExt.
opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
Definition: APFloat.cpp:4483
May or may not overflow.
bool isStatepoint(const CallBase *Call)
Definition: Statepoint.cpp:20
void setCalledFunction(Function *Fn)
Sets the function called, including updating the function type.
Definition: InstrTypes.h:1323
CastClass_match< OpTy, Instruction::ZExt > m_ZExt(const OpTy &Op)
Matches ZExt.
AttributeSet getParamAttributes(unsigned ArgNo) const
The attributes for the argument or parameter at the given index are returned.
bool isVarArg() const
Definition: DerivedTypes.h:123
This class represents a no-op cast from one type to another.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
Definition: Instruction.h:234
Value * CreateVectorSplat(unsigned NumElts, Value *V, const Twine &Name="")
Return a vector value that contains.
Definition: IRBuilder.h:2276
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition: Constants.h:137
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
Definition: Instruction.h:125
bool maskIsAllOneOrUndef(Value *Mask)
Given a mask vector of the form <Y x="" i1>="">, Return true if all of the elements of this predicate...
cstfp_pred_ty< is_pos_zero_fp > m_PosZeroFP()
Match a floating-point positive zero.
Definition: PatternMatch.h:444
iterator_range< User::op_iterator > arg_operands()
Definition: InstrTypes.h:1233
AttrBuilder & remove(const AttrBuilder &B)
Remove the attributes from the builder.
AttributeList getAttributes() const
Return the attribute list for this Function.
Definition: Function.h:223
cmpResult
IEEE-754R 5.11: Floating Point Comparison Relations.
Definition: APFloat.h:176
An instruction for storing to memory.
Definition: Instructions.h:320
bool extractProfTotalWeight(uint64_t &TotalVal) const
Retrieve total raw weight values of a branch.
Definition: Metadata.cpp:1336
Value * getRHS() const
static void ValueIsRAUWd(Value *Old, Value *New)
Definition: Value.cpp:900
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:1736
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
void takeName(Value *V)
Transfer the name from V to this value.
Definition: Value.cpp:291
static ConstantAsMetadata * get(Constant *C)
Definition: Metadata.h:409
Function * getDeclaration(Module *M, ID id, ArrayRef< Type *> Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
Definition: Function.cpp:1044
This class represents a truncation of integer types.
Type * getElementType() const
Return the element type of the array/vector.
Definition: Constants.cpp:2411
Value * getOperand(unsigned i) const
Definition: User.h:169
Class to represent pointers.
Definition: DerivedTypes.h:544
bool hasAttribute(Attribute::AttrKind Kind) const
Return true if the attribute exists in this set.
Definition: Attributes.cpp:649
Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
Definition: Constants.cpp:344
const DataLayout & getDataLayout() const
static MetadataAsValue * get(LLVMContext &Context, Metadata *MD)
Definition: Metadata.cpp:105
static Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:1782
bool isVoidTy() const
Return true if this is &#39;void&#39;.
Definition: Type.h:140
bool isFloatTy() const
Return true if this is &#39;float&#39;, a 32-bit IEEE fp type.
Definition: Type.h:146
bool hasAttrSomewhere(Attribute::AttrKind Kind, unsigned *Index=nullptr) const
Return true if the specified attribute is set for at least one parameter or for the return value...
OneUse_match< T > m_OneUse(const T &SubPattern)
Definition: PatternMatch.h:61
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata *> MDs)
Definition: Metadata.h:1165
Instruction * visitFenceInst(FenceInst &FI)
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:432
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition: Constants.h:148
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static AttributeSet get(LLVMContext &C, const AttrBuilder &B)
Definition: Attributes.cpp:584
apint_match m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt...
Definition: PatternMatch.h:175
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
Definition: Instruction.h:318
bool isNegative() const
Definition: APFloat.h:1157
static ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
Definition: Constants.cpp:1410
Value * CreateAShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Definition: IRBuilder.h:1179
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition: MathExtras.h:428
unsigned arg_size() const
Definition: InstrTypes.h:1229
Value * getCalledValue() const
Definition: InstrTypes.h:1280
LLVM_NODISCARD AttributeList addParamAttribute(LLVMContext &C, unsigned ArgNo, Attribute::AttrKind Kind) const
Add an argument attribute to the list.
Definition: Attributes.h:412
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:45
BinaryOp_match< LHS, RHS, Instruction::Or > m_Or(const LHS &L, const RHS &R)
Definition: PatternMatch.h:762
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:64
ConstantInt * getTrue()
Get the constant value for i1 true.
Definition: IRBuilder.h:286
bool isNaN() const
Definition: APFloat.h:1155
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
Definition: Constant.h:41
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
Definition: IRBuilder.h:2099
bool isPointerTy() const
True if this is an instance of PointerType.
Definition: Type.h:223
bool isSigned() const
Whether the intrinsic is signed or unsigned.
static BinaryOperator * CreateNUW(BinaryOps Opc, Value *V1, Value *V2, const Twine &Name="")
Definition: InstrTypes.h:308
FunctionType * getFunctionType() const
Definition: InstrTypes.h:1144
static ManagedStatic< OptionRegistry > OR
Definition: Options.cpp:30
unsigned getNumParams() const
Return the number of fixed parameters this function type requires.
Definition: DerivedTypes.h:139
ConstantFP - Floating Point Values [float, double].
Definition: Constants.h:263
cst_pred_ty< is_all_ones > m_AllOnes()
Match an integer or vector with all bits set.
Definition: PatternMatch.h:308
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
Definition: PatternMatch.h:501
Instruction * visitCallBrInst(CallBrInst &CBI)
const Instruction * getNextNonDebugInstruction() const
Return a pointer to the next non-debug instruction in the same basic block as &#39;this&#39;, or nullptr if no such instruction exists.
param_iterator param_begin() const
Definition: DerivedTypes.h:128
This file declares a class to represent arbitrary precision floating point values and provide a varie...
static VectorType * getInteger(VectorType *VTy)
This static method gets a VectorType with the same number of elements as the input type...
Definition: DerivedTypes.h:463
bool isFast() const
Determine whether all fast-math-flags are set.
std::underlying_type< E >::type Underlying(E Val)
Check that Val is in range for E, and return Val cast to E&#39;s underlying type.
Definition: BitmaskEnum.h:90
static IntrinsicInst * findInitTrampolineFromBB(IntrinsicInst *AdjustTramp, Value *TrampMem)
bool isHalfTy() const
Return true if this is &#39;half&#39;, a 16-bit IEEE fp type.
Definition: Type.h:143
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition: InstrTypes.h:732
void setCallingConv(CallingConv::ID CC)
Definition: InstrTypes.h:1348
match_combine_or< CastClass_match< OpTy, Instruction::ZExt >, CastClass_match< OpTy, Instruction::SExt > > m_ZExtOrSExt(const OpTy &Op)
bool isAllOnes() const
Returns true if value is all one bits.
Definition: KnownBits.h:77
This class represents any memset intrinsic.
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
static FunctionType * get(Type *Result, ArrayRef< Type *> Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
Definition: Type.cpp:296
static Attribute getWithByValType(LLVMContext &Context, Type *Ty)
Definition: Attributes.cpp:170
static Constant * getICmp(unsigned short pred, Constant *LHS, Constant *RHS, bool OnlyIfReduced=false)
get* - Return some common constants without having to specify the full Instruction::OPCODE identifier...
Definition: Constants.cpp:2043
self_iterator getIterator()
Definition: ilist_node.h:81
Value * SimplifyCall(CallBase *Call, const SimplifyQuery &Q)
Given a callsite, fold the result or return null.
Class to represent integer types.
Definition: DerivedTypes.h:40
IntegerType * getIntNTy(unsigned N)
Fetch the type representing an N-bit integer.
Definition: IRBuilder.h:359
const Function * getFunction() const
Return the function this instruction belongs to.
Definition: Instruction.cpp:59
void setAlignment(unsigned Align)
static Value * simplifyX86varShift(const IntrinsicInst &II, InstCombiner::BuilderTy &Builder)
bool isByValOrInAllocaArgument(unsigned ArgNo) const
Determine whether this argument is passed by value or in an alloca.
Definition: InstrTypes.h:1538
static UndefValue * get(Type *T)
Static factory methods - Return an &#39;undef&#39; object of the specified type.
Definition: Constants.cpp:1424
const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs, address space casts, and aliases.
Definition: Value.cpp:535
Value * CreateExtractValue(Value *Agg, ArrayRef< unsigned > Idxs, const Twine &Name="")
Definition: IRBuilder.h:2163
size_t size() const
Definition: SmallVector.h:52
APInt uadd_ov(const APInt &RHS, bool &Overflow) const
Definition: APInt.cpp:1881
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
Definition: InstrTypes.h:1222
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
Definition: Metadata.cpp:1222
LLVM_READONLY APFloat maxnum(const APFloat &A, const APFloat &B)
Implements IEEE maxNum semantics.
Definition: APFloat.h:1248
Value * CreateTrunc(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:1732
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition: APInt.h:970
bool isByValArgument(unsigned ArgNo) const
Determine whether this argument is passed by value.
Definition: InstrTypes.h:1528
CallBr instruction, tracking function calls that may not return control but instead transfer it to a ...
static Constant * getIntegerValue(Type *Ty, const APInt &V)
Return the value for an integer or pointer constant, or a vector thereof, with the given scalar value...
Definition: Constants.cpp:311
static Value * simplifyX86extrq(IntrinsicInst &II, Value *Op0, ConstantInt *CILength, ConstantInt *CIIndex, InstCombiner::BuilderTy &Builder)
Attempt to simplify SSE4A EXTRQ/EXTRQI instructions using constant folding or conversion to a shuffle...
bool isGCRelocate(const CallBase *Call)
Definition: Statepoint.cpp:36
const APFloat & getValueAPF() const
Definition: Constants.h:302
CastClass_match< OpTy, Instruction::SExt > m_SExt(const OpTy &Op)
Matches SExt.
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
Definition: IntrinsicInst.h:50
bool doesNotThrow() const
Determine if the function cannot unwind.
Definition: Function.h:533
static BinaryOperator * CreateFNeg(Value *Op, const Twine &Name="", Instruction *InsertBefore=nullptr)
static Type * getHalfTy(LLVMContext &C)
Definition: Type.cpp:162
static IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition: Type.cpp:239
void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind)
Adds the attribute to the indicated argument.
Definition: InstrTypes.h:1397
static CastInst * CreateIntegerCast(Value *S, Type *Ty, bool isSigned, const Twine &Name="", Instruction *InsertBefore=nullptr)
Create a ZExt, BitCast, or Trunc for int -> int casts.
Iterator for intrusive lists based on ilist_node.
bool hasParamAttribute(unsigned ArgNo, Attribute::AttrKind Kind) const
Equivalent to hasAttribute(ArgNo + FirstArgIndex, Kind).
static cl::opt< unsigned > GuardWideningWindow("instcombine-guard-widening-window", cl::init(3), cl::desc("How wide an instruction window to bypass looking for " "another guard"))
uint64_t getLimitedValue(uint64_t Limit=~0ULL) const
getLimitedValue - If the value is smaller than the specified limit, return it, otherwise return the l...
Definition: Constants.h:250
static PointerType * getUnqual(Type *ElementType)
This constructs a pointer to an object of the specified type in the generic address space (address sp...
Definition: DerivedTypes.h:559
This is the shared class of boolean and integer constants.
Definition: Constants.h:83
static APSInt getMaxValue(uint32_t numBits, bool Unsigned)
getMaxValue - Return the APSInt representing the maximum integer value with the given bit width and s...
Definition: APSInt.h:287
BlockVerifier::State From
static Value * simplifyX86vpermilvar(const IntrinsicInst &II, InstCombiner::BuilderTy &Builder)
Attempt to convert vpermilvar* to shufflevector if the mask is constant.
static APSInt getMinValue(uint32_t numBits, bool Unsigned)
getMinValue - Return the APSInt representing the minimum integer value with the given bit width and s...
Definition: APSInt.h:294
iterator end()
Definition: BasicBlock.h:270
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type...
Definition: Type.cpp:129
static IntrinsicInst * findInitTrampolineFromAlloca(Value *TrampMem)
bool isInAllocaArgument(unsigned ArgNo) const
Determine whether this argument is passed in an alloca.
Definition: InstrTypes.h:1533
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:837
CallInst * CreateIntrinsic(Intrinsic::ID ID, ArrayRef< Type *> Types, ArrayRef< Value *> Args, Instruction *FMFSource=nullptr, const Twine &Name="")
Create a call to intrinsic ID with args, mangled using Types.
Definition: IRBuilder.cpp:748
Represents a saturating add/sub intrinsic.
static APInt getSplat(unsigned NewLen, const APInt &V)
Return a value containing V broadcasted over NewLen bits.
Definition: APInt.cpp:522
static Instruction * canonicalizeConstantArg0ToArg1(CallInst &Call)
Type::subtype_iterator param_iterator
Definition: DerivedTypes.h:126
bool overlaps(const AttrBuilder &B) const
Return true if the builder has any attribute that&#39;s in the specified builder.