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