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