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     DenormalMode Mode = parseDenormalFPAttribute(Attr);
1710     bool FtzEnabled = Mode.Output != DenormalMode::IEEE;
1711 
1712     if (FtzEnabled != (Action.FtzRequirement == FTZ_MustBeOn))
1713       return nullptr;
1714   }
1715 
1716   // Simplify to target-generic intrinsic.
1717   if (Action.IID) {
1718     SmallVector<Value *, 4> Args(II->arg_operands());
1719     // All the target-generic intrinsics currently of interest to us have one
1720     // type argument, equal to that of the nvvm intrinsic's argument.
1721     Type *Tys[] = {II->getArgOperand(0)->getType()};
1722     return CallInst::Create(
1723         Intrinsic::getDeclaration(II->getModule(), *Action.IID, Tys), Args);
1724   }
1725 
1726   // Simplify to target-generic binary op.
1727   if (Action.BinaryOp)
1728     return BinaryOperator::Create(*Action.BinaryOp, II->getArgOperand(0),
1729                                   II->getArgOperand(1), II->getName());
1730 
1731   // Simplify to target-generic cast op.
1732   if (Action.CastOp)
1733     return CastInst::Create(*Action.CastOp, II->getArgOperand(0), II->getType(),
1734                             II->getName());
1735 
1736   // All that's left are the special cases.
1737   if (!Action.Special)
1738     return nullptr;
1739 
1740   switch (*Action.Special) {
1741   case SPC_Reciprocal:
1742     // Simplify reciprocal.
1743     return BinaryOperator::Create(
1744         Instruction::FDiv, ConstantFP::get(II->getArgOperand(0)->getType(), 1),
1745         II->getArgOperand(0), II->getName());
1746   }
1747   llvm_unreachable("All SpecialCase enumerators should be handled in switch.");
1748 }
1749 
1750 Instruction *InstCombiner::visitVAStartInst(VAStartInst &I) {
1751   removeTriviallyEmptyRange(I, Intrinsic::vastart, Intrinsic::vaend, *this);
1752   return nullptr;
1753 }
1754 
1755 Instruction *InstCombiner::visitVACopyInst(VACopyInst &I) {
1756   removeTriviallyEmptyRange(I, Intrinsic::vacopy, Intrinsic::vaend, *this);
1757   return nullptr;
1758 }
1759 
1760 static Instruction *canonicalizeConstantArg0ToArg1(CallInst &Call) {
1761   assert(Call.getNumArgOperands() > 1 && "Need at least 2 args to swap");
1762   Value *Arg0 = Call.getArgOperand(0), *Arg1 = Call.getArgOperand(1);
1763   if (isa<Constant>(Arg0) && !isa<Constant>(Arg1)) {
1764     Call.setArgOperand(0, Arg1);
1765     Call.setArgOperand(1, Arg0);
1766     return &Call;
1767   }
1768   return nullptr;
1769 }
1770 
1771 Instruction *InstCombiner::foldIntrinsicWithOverflowCommon(IntrinsicInst *II) {
1772   WithOverflowInst *WO = cast<WithOverflowInst>(II);
1773   Value *OperationResult = nullptr;
1774   Constant *OverflowResult = nullptr;
1775   if (OptimizeOverflowCheck(WO->getBinaryOp(), WO->isSigned(), WO->getLHS(),
1776                             WO->getRHS(), *WO, OperationResult, OverflowResult))
1777     return CreateOverflowTuple(WO, OperationResult, OverflowResult);
1778   return nullptr;
1779 }
1780 
1781 /// CallInst simplification. This mostly only handles folding of intrinsic
1782 /// instructions. For normal calls, it allows visitCallBase to do the heavy
1783 /// lifting.
1784 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
1785   if (Value *V = SimplifyCall(&CI, SQ.getWithInstruction(&CI)))
1786     return replaceInstUsesWith(CI, V);
1787 
1788   if (isFreeCall(&CI, &TLI))
1789     return visitFree(CI);
1790 
1791   // If the caller function is nounwind, mark the call as nounwind, even if the
1792   // callee isn't.
1793   if (CI.getFunction()->doesNotThrow() && !CI.doesNotThrow()) {
1794     CI.setDoesNotThrow();
1795     return &CI;
1796   }
1797 
1798   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
1799   if (!II) return visitCallBase(CI);
1800 
1801   // Intrinsics cannot occur in an invoke or a callbr, so handle them here
1802   // instead of in visitCallBase.
1803   if (auto *MI = dyn_cast<AnyMemIntrinsic>(II)) {
1804     bool Changed = false;
1805 
1806     // memmove/cpy/set of zero bytes is a noop.
1807     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
1808       if (NumBytes->isNullValue())
1809         return eraseInstFromFunction(CI);
1810 
1811       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
1812         if (CI->getZExtValue() == 1) {
1813           // Replace the instruction with just byte operations.  We would
1814           // transform other cases to loads/stores, but we don't know if
1815           // alignment is sufficient.
1816         }
1817     }
1818 
1819     // No other transformations apply to volatile transfers.
1820     if (auto *M = dyn_cast<MemIntrinsic>(MI))
1821       if (M->isVolatile())
1822         return nullptr;
1823 
1824     // If we have a memmove and the source operation is a constant global,
1825     // then the source and dest pointers can't alias, so we can change this
1826     // into a call to memcpy.
1827     if (auto *MMI = dyn_cast<AnyMemMoveInst>(MI)) {
1828       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
1829         if (GVSrc->isConstant()) {
1830           Module *M = CI.getModule();
1831           Intrinsic::ID MemCpyID =
1832               isa<AtomicMemMoveInst>(MMI)
1833                   ? Intrinsic::memcpy_element_unordered_atomic
1834                   : Intrinsic::memcpy;
1835           Type *Tys[3] = { CI.getArgOperand(0)->getType(),
1836                            CI.getArgOperand(1)->getType(),
1837                            CI.getArgOperand(2)->getType() };
1838           CI.setCalledFunction(Intrinsic::getDeclaration(M, MemCpyID, Tys));
1839           Changed = true;
1840         }
1841     }
1842 
1843     if (AnyMemTransferInst *MTI = dyn_cast<AnyMemTransferInst>(MI)) {
1844       // memmove(x,x,size) -> noop.
1845       if (MTI->getSource() == MTI->getDest())
1846         return eraseInstFromFunction(CI);
1847     }
1848 
1849     // If we can determine a pointer alignment that is bigger than currently
1850     // set, update the alignment.
1851     if (auto *MTI = dyn_cast<AnyMemTransferInst>(MI)) {
1852       if (Instruction *I = SimplifyAnyMemTransfer(MTI))
1853         return I;
1854     } else if (auto *MSI = dyn_cast<AnyMemSetInst>(MI)) {
1855       if (Instruction *I = SimplifyAnyMemSet(MSI))
1856         return I;
1857     }
1858 
1859     if (Changed) return II;
1860   }
1861 
1862   // For vector result intrinsics, use the generic demanded vector support.
1863   if (II->getType()->isVectorTy()) {
1864     auto VWidth = II->getType()->getVectorNumElements();
1865     APInt UndefElts(VWidth, 0);
1866     APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
1867     if (Value *V = SimplifyDemandedVectorElts(II, AllOnesEltMask, UndefElts)) {
1868       if (V != II)
1869         return replaceInstUsesWith(*II, V);
1870       return II;
1871     }
1872   }
1873 
1874   if (Instruction *I = SimplifyNVVMIntrinsic(II, *this))
1875     return I;
1876 
1877   auto SimplifyDemandedVectorEltsLow = [this](Value *Op, unsigned Width,
1878                                               unsigned DemandedWidth) {
1879     APInt UndefElts(Width, 0);
1880     APInt DemandedElts = APInt::getLowBitsSet(Width, DemandedWidth);
1881     return SimplifyDemandedVectorElts(Op, DemandedElts, UndefElts);
1882   };
1883 
1884   Intrinsic::ID IID = II->getIntrinsicID();
1885   switch (IID) {
1886   default: break;
1887   case Intrinsic::objectsize:
1888     if (Value *V = lowerObjectSizeCall(II, DL, &TLI, /*MustSucceed=*/false))
1889       return replaceInstUsesWith(CI, V);
1890     return nullptr;
1891   case Intrinsic::bswap: {
1892     Value *IIOperand = II->getArgOperand(0);
1893     Value *X = nullptr;
1894 
1895     // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
1896     if (match(IIOperand, m_Trunc(m_BSwap(m_Value(X))))) {
1897       unsigned C = X->getType()->getPrimitiveSizeInBits() -
1898         IIOperand->getType()->getPrimitiveSizeInBits();
1899       Value *CV = ConstantInt::get(X->getType(), C);
1900       Value *V = Builder.CreateLShr(X, CV);
1901       return new TruncInst(V, IIOperand->getType());
1902     }
1903     break;
1904   }
1905   case Intrinsic::masked_load:
1906     if (Value *SimplifiedMaskedOp = simplifyMaskedLoad(*II))
1907       return replaceInstUsesWith(CI, SimplifiedMaskedOp);
1908     break;
1909   case Intrinsic::masked_store:
1910     return simplifyMaskedStore(*II);
1911   case Intrinsic::masked_gather:
1912     return simplifyMaskedGather(*II);
1913   case Intrinsic::masked_scatter:
1914     return simplifyMaskedScatter(*II);
1915   case Intrinsic::launder_invariant_group:
1916   case Intrinsic::strip_invariant_group:
1917     if (auto *SkippedBarrier = simplifyInvariantGroupIntrinsic(*II, *this))
1918       return replaceInstUsesWith(*II, SkippedBarrier);
1919     break;
1920   case Intrinsic::powi:
1921     if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
1922       // 0 and 1 are handled in instsimplify
1923 
1924       // powi(x, -1) -> 1/x
1925       if (Power->isMinusOne())
1926         return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0),
1927                                           II->getArgOperand(0));
1928       // powi(x, 2) -> x*x
1929       if (Power->equalsInt(2))
1930         return BinaryOperator::CreateFMul(II->getArgOperand(0),
1931                                           II->getArgOperand(0));
1932     }
1933     break;
1934 
1935   case Intrinsic::cttz:
1936   case Intrinsic::ctlz:
1937     if (auto *I = foldCttzCtlz(*II, *this))
1938       return I;
1939     break;
1940 
1941   case Intrinsic::ctpop:
1942     if (auto *I = foldCtpop(*II, *this))
1943       return I;
1944     break;
1945 
1946   case Intrinsic::fshl:
1947   case Intrinsic::fshr: {
1948     Value *Op0 = II->getArgOperand(0), *Op1 = II->getArgOperand(1);
1949     Type *Ty = II->getType();
1950     unsigned BitWidth = Ty->getScalarSizeInBits();
1951     Constant *ShAmtC;
1952     if (match(II->getArgOperand(2), m_Constant(ShAmtC)) &&
1953         !isa<ConstantExpr>(ShAmtC) && !ShAmtC->containsConstantExpression()) {
1954       // Canonicalize a shift amount constant operand to modulo the bit-width.
1955       Constant *WidthC = ConstantInt::get(Ty, BitWidth);
1956       Constant *ModuloC = ConstantExpr::getURem(ShAmtC, WidthC);
1957       if (ModuloC != ShAmtC) {
1958         II->setArgOperand(2, ModuloC);
1959         return II;
1960       }
1961       assert(ConstantExpr::getICmp(ICmpInst::ICMP_UGT, WidthC, ShAmtC) ==
1962                  ConstantInt::getTrue(CmpInst::makeCmpResultType(Ty)) &&
1963              "Shift amount expected to be modulo bitwidth");
1964 
1965       // Canonicalize funnel shift right by constant to funnel shift left. This
1966       // is not entirely arbitrary. For historical reasons, the backend may
1967       // recognize rotate left patterns but miss rotate right patterns.
1968       if (IID == Intrinsic::fshr) {
1969         // fshr X, Y, C --> fshl X, Y, (BitWidth - C)
1970         Constant *LeftShiftC = ConstantExpr::getSub(WidthC, ShAmtC);
1971         Module *Mod = II->getModule();
1972         Function *Fshl = Intrinsic::getDeclaration(Mod, Intrinsic::fshl, Ty);
1973         return CallInst::Create(Fshl, { Op0, Op1, LeftShiftC });
1974       }
1975       assert(IID == Intrinsic::fshl &&
1976              "All funnel shifts by simple constants should go left");
1977 
1978       // fshl(X, 0, C) --> shl X, C
1979       // fshl(X, undef, C) --> shl X, C
1980       if (match(Op1, m_ZeroInt()) || match(Op1, m_Undef()))
1981         return BinaryOperator::CreateShl(Op0, ShAmtC);
1982 
1983       // fshl(0, X, C) --> lshr X, (BW-C)
1984       // fshl(undef, X, C) --> lshr X, (BW-C)
1985       if (match(Op0, m_ZeroInt()) || match(Op0, m_Undef()))
1986         return BinaryOperator::CreateLShr(Op1,
1987                                           ConstantExpr::getSub(WidthC, ShAmtC));
1988 
1989       // fshl i16 X, X, 8 --> bswap i16 X (reduce to more-specific form)
1990       if (Op0 == Op1 && BitWidth == 16 && match(ShAmtC, m_SpecificInt(8))) {
1991         Module *Mod = II->getModule();
1992         Function *Bswap = Intrinsic::getDeclaration(Mod, Intrinsic::bswap, Ty);
1993         return CallInst::Create(Bswap, { Op0 });
1994       }
1995     }
1996 
1997     // Left or right might be masked.
1998     if (SimplifyDemandedInstructionBits(*II))
1999       return &CI;
2000 
2001     // The shift amount (operand 2) of a funnel shift is modulo the bitwidth,
2002     // so only the low bits of the shift amount are demanded if the bitwidth is
2003     // a power-of-2.
2004     if (!isPowerOf2_32(BitWidth))
2005       break;
2006     APInt Op2Demanded = APInt::getLowBitsSet(BitWidth, Log2_32_Ceil(BitWidth));
2007     KnownBits Op2Known(BitWidth);
2008     if (SimplifyDemandedBits(II, 2, Op2Demanded, Op2Known))
2009       return &CI;
2010     break;
2011   }
2012   case Intrinsic::uadd_with_overflow:
2013   case Intrinsic::sadd_with_overflow: {
2014     if (Instruction *I = canonicalizeConstantArg0ToArg1(CI))
2015       return I;
2016     if (Instruction *I = foldIntrinsicWithOverflowCommon(II))
2017       return I;
2018 
2019     // Given 2 constant operands whose sum does not overflow:
2020     // uaddo (X +nuw C0), C1 -> uaddo X, C0 + C1
2021     // saddo (X +nsw C0), C1 -> saddo X, C0 + C1
2022     Value *X;
2023     const APInt *C0, *C1;
2024     Value *Arg0 = II->getArgOperand(0);
2025     Value *Arg1 = II->getArgOperand(1);
2026     bool IsSigned = IID == Intrinsic::sadd_with_overflow;
2027     bool HasNWAdd = IsSigned ? match(Arg0, m_NSWAdd(m_Value(X), m_APInt(C0)))
2028                              : match(Arg0, m_NUWAdd(m_Value(X), m_APInt(C0)));
2029     if (HasNWAdd && match(Arg1, m_APInt(C1))) {
2030       bool Overflow;
2031       APInt NewC =
2032           IsSigned ? C1->sadd_ov(*C0, Overflow) : C1->uadd_ov(*C0, Overflow);
2033       if (!Overflow)
2034         return replaceInstUsesWith(
2035             *II, Builder.CreateBinaryIntrinsic(
2036                      IID, X, ConstantInt::get(Arg1->getType(), NewC)));
2037     }
2038     break;
2039   }
2040 
2041   case Intrinsic::umul_with_overflow:
2042   case Intrinsic::smul_with_overflow:
2043     if (Instruction *I = canonicalizeConstantArg0ToArg1(CI))
2044       return I;
2045     LLVM_FALLTHROUGH;
2046 
2047   case Intrinsic::usub_with_overflow:
2048     if (Instruction *I = foldIntrinsicWithOverflowCommon(II))
2049       return I;
2050     break;
2051 
2052   case Intrinsic::ssub_with_overflow: {
2053     if (Instruction *I = foldIntrinsicWithOverflowCommon(II))
2054       return I;
2055 
2056     Constant *C;
2057     Value *Arg0 = II->getArgOperand(0);
2058     Value *Arg1 = II->getArgOperand(1);
2059     // Given a constant C that is not the minimum signed value
2060     // for an integer of a given bit width:
2061     //
2062     // ssubo X, C -> saddo X, -C
2063     if (match(Arg1, m_Constant(C)) && C->isNotMinSignedValue()) {
2064       Value *NegVal = ConstantExpr::getNeg(C);
2065       // Build a saddo call that is equivalent to the discovered
2066       // ssubo call.
2067       return replaceInstUsesWith(
2068           *II, Builder.CreateBinaryIntrinsic(Intrinsic::sadd_with_overflow,
2069                                              Arg0, NegVal));
2070     }
2071 
2072     break;
2073   }
2074 
2075   case Intrinsic::uadd_sat:
2076   case Intrinsic::sadd_sat:
2077     if (Instruction *I = canonicalizeConstantArg0ToArg1(CI))
2078       return I;
2079     LLVM_FALLTHROUGH;
2080   case Intrinsic::usub_sat:
2081   case Intrinsic::ssub_sat: {
2082     SaturatingInst *SI = cast<SaturatingInst>(II);
2083     Type *Ty = SI->getType();
2084     Value *Arg0 = SI->getLHS();
2085     Value *Arg1 = SI->getRHS();
2086 
2087     // Make use of known overflow information.
2088     OverflowResult OR = computeOverflow(SI->getBinaryOp(), SI->isSigned(),
2089                                         Arg0, Arg1, SI);
2090     switch (OR) {
2091       case OverflowResult::MayOverflow:
2092         break;
2093       case OverflowResult::NeverOverflows:
2094         if (SI->isSigned())
2095           return BinaryOperator::CreateNSW(SI->getBinaryOp(), Arg0, Arg1);
2096         else
2097           return BinaryOperator::CreateNUW(SI->getBinaryOp(), Arg0, Arg1);
2098       case OverflowResult::AlwaysOverflowsLow: {
2099         unsigned BitWidth = Ty->getScalarSizeInBits();
2100         APInt Min = APSInt::getMinValue(BitWidth, !SI->isSigned());
2101         return replaceInstUsesWith(*SI, ConstantInt::get(Ty, Min));
2102       }
2103       case OverflowResult::AlwaysOverflowsHigh: {
2104         unsigned BitWidth = Ty->getScalarSizeInBits();
2105         APInt Max = APSInt::getMaxValue(BitWidth, !SI->isSigned());
2106         return replaceInstUsesWith(*SI, ConstantInt::get(Ty, Max));
2107       }
2108     }
2109 
2110     // ssub.sat(X, C) -> sadd.sat(X, -C) if C != MIN
2111     Constant *C;
2112     if (IID == Intrinsic::ssub_sat && match(Arg1, m_Constant(C)) &&
2113         C->isNotMinSignedValue()) {
2114       Value *NegVal = ConstantExpr::getNeg(C);
2115       return replaceInstUsesWith(
2116           *II, Builder.CreateBinaryIntrinsic(
2117               Intrinsic::sadd_sat, Arg0, NegVal));
2118     }
2119 
2120     // sat(sat(X + Val2) + Val) -> sat(X + (Val+Val2))
2121     // sat(sat(X - Val2) - Val) -> sat(X - (Val+Val2))
2122     // if Val and Val2 have the same sign
2123     if (auto *Other = dyn_cast<IntrinsicInst>(Arg0)) {
2124       Value *X;
2125       const APInt *Val, *Val2;
2126       APInt NewVal;
2127       bool IsUnsigned =
2128           IID == Intrinsic::uadd_sat || IID == Intrinsic::usub_sat;
2129       if (Other->getIntrinsicID() == IID &&
2130           match(Arg1, m_APInt(Val)) &&
2131           match(Other->getArgOperand(0), m_Value(X)) &&
2132           match(Other->getArgOperand(1), m_APInt(Val2))) {
2133         if (IsUnsigned)
2134           NewVal = Val->uadd_sat(*Val2);
2135         else if (Val->isNonNegative() == Val2->isNonNegative()) {
2136           bool Overflow;
2137           NewVal = Val->sadd_ov(*Val2, Overflow);
2138           if (Overflow) {
2139             // Both adds together may add more than SignedMaxValue
2140             // without saturating the final result.
2141             break;
2142           }
2143         } else {
2144           // Cannot fold saturated addition with different signs.
2145           break;
2146         }
2147 
2148         return replaceInstUsesWith(
2149             *II, Builder.CreateBinaryIntrinsic(
2150                      IID, X, ConstantInt::get(II->getType(), NewVal)));
2151       }
2152     }
2153     break;
2154   }
2155 
2156   case Intrinsic::minnum:
2157   case Intrinsic::maxnum:
2158   case Intrinsic::minimum:
2159   case Intrinsic::maximum: {
2160     if (Instruction *I = canonicalizeConstantArg0ToArg1(CI))
2161       return I;
2162     Value *Arg0 = II->getArgOperand(0);
2163     Value *Arg1 = II->getArgOperand(1);
2164     Value *X, *Y;
2165     if (match(Arg0, m_FNeg(m_Value(X))) && match(Arg1, m_FNeg(m_Value(Y))) &&
2166         (Arg0->hasOneUse() || Arg1->hasOneUse())) {
2167       // If both operands are negated, invert the call and negate the result:
2168       // min(-X, -Y) --> -(max(X, Y))
2169       // max(-X, -Y) --> -(min(X, Y))
2170       Intrinsic::ID NewIID;
2171       switch (IID) {
2172       case Intrinsic::maxnum:
2173         NewIID = Intrinsic::minnum;
2174         break;
2175       case Intrinsic::minnum:
2176         NewIID = Intrinsic::maxnum;
2177         break;
2178       case Intrinsic::maximum:
2179         NewIID = Intrinsic::minimum;
2180         break;
2181       case Intrinsic::minimum:
2182         NewIID = Intrinsic::maximum;
2183         break;
2184       default:
2185         llvm_unreachable("unexpected intrinsic ID");
2186       }
2187       Value *NewCall = Builder.CreateBinaryIntrinsic(NewIID, X, Y, II);
2188       Instruction *FNeg = BinaryOperator::CreateFNeg(NewCall);
2189       FNeg->copyIRFlags(II);
2190       return FNeg;
2191     }
2192 
2193     // m(m(X, C2), C1) -> m(X, C)
2194     const APFloat *C1, *C2;
2195     if (auto *M = dyn_cast<IntrinsicInst>(Arg0)) {
2196       if (M->getIntrinsicID() == IID && match(Arg1, m_APFloat(C1)) &&
2197           ((match(M->getArgOperand(0), m_Value(X)) &&
2198             match(M->getArgOperand(1), m_APFloat(C2))) ||
2199            (match(M->getArgOperand(1), m_Value(X)) &&
2200             match(M->getArgOperand(0), m_APFloat(C2))))) {
2201         APFloat Res(0.0);
2202         switch (IID) {
2203         case Intrinsic::maxnum:
2204           Res = maxnum(*C1, *C2);
2205           break;
2206         case Intrinsic::minnum:
2207           Res = minnum(*C1, *C2);
2208           break;
2209         case Intrinsic::maximum:
2210           Res = maximum(*C1, *C2);
2211           break;
2212         case Intrinsic::minimum:
2213           Res = minimum(*C1, *C2);
2214           break;
2215         default:
2216           llvm_unreachable("unexpected intrinsic ID");
2217         }
2218         Instruction *NewCall = Builder.CreateBinaryIntrinsic(
2219             IID, X, ConstantFP::get(Arg0->getType(), Res));
2220         NewCall->copyIRFlags(II);
2221         return replaceInstUsesWith(*II, NewCall);
2222       }
2223     }
2224 
2225     break;
2226   }
2227   case Intrinsic::fmuladd: {
2228     // Canonicalize fast fmuladd to the separate fmul + fadd.
2229     if (II->isFast()) {
2230       BuilderTy::FastMathFlagGuard Guard(Builder);
2231       Builder.setFastMathFlags(II->getFastMathFlags());
2232       Value *Mul = Builder.CreateFMul(II->getArgOperand(0),
2233                                       II->getArgOperand(1));
2234       Value *Add = Builder.CreateFAdd(Mul, II->getArgOperand(2));
2235       Add->takeName(II);
2236       return replaceInstUsesWith(*II, Add);
2237     }
2238 
2239     // Try to simplify the underlying FMul.
2240     if (Value *V = SimplifyFMulInst(II->getArgOperand(0), II->getArgOperand(1),
2241                                     II->getFastMathFlags(),
2242                                     SQ.getWithInstruction(II))) {
2243       auto *FAdd = BinaryOperator::CreateFAdd(V, II->getArgOperand(2));
2244       FAdd->copyFastMathFlags(II);
2245       return FAdd;
2246     }
2247 
2248     LLVM_FALLTHROUGH;
2249   }
2250   case Intrinsic::fma: {
2251     if (Instruction *I = canonicalizeConstantArg0ToArg1(CI))
2252       return I;
2253 
2254     // fma fneg(x), fneg(y), z -> fma x, y, z
2255     Value *Src0 = II->getArgOperand(0);
2256     Value *Src1 = II->getArgOperand(1);
2257     Value *X, *Y;
2258     if (match(Src0, m_FNeg(m_Value(X))) && match(Src1, m_FNeg(m_Value(Y)))) {
2259       II->setArgOperand(0, X);
2260       II->setArgOperand(1, Y);
2261       return II;
2262     }
2263 
2264     // fma fabs(x), fabs(x), z -> fma x, x, z
2265     if (match(Src0, m_FAbs(m_Value(X))) &&
2266         match(Src1, m_FAbs(m_Specific(X)))) {
2267       II->setArgOperand(0, X);
2268       II->setArgOperand(1, X);
2269       return II;
2270     }
2271 
2272     // Try to simplify the underlying FMul. We can only apply simplifications
2273     // that do not require rounding.
2274     if (Value *V = SimplifyFMAFMul(II->getArgOperand(0), II->getArgOperand(1),
2275                                    II->getFastMathFlags(),
2276                                    SQ.getWithInstruction(II))) {
2277       auto *FAdd = BinaryOperator::CreateFAdd(V, II->getArgOperand(2));
2278       FAdd->copyFastMathFlags(II);
2279       return FAdd;
2280     }
2281 
2282     break;
2283   }
2284   case Intrinsic::copysign: {
2285     if (SignBitMustBeZero(II->getArgOperand(1), &TLI)) {
2286       // If we know that the sign argument is positive, reduce to FABS:
2287       // copysign X, Pos --> fabs X
2288       Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs,
2289                                                  II->getArgOperand(0), II);
2290       return replaceInstUsesWith(*II, Fabs);
2291     }
2292     // TODO: There should be a ValueTracking sibling like SignBitMustBeOne.
2293     const APFloat *C;
2294     if (match(II->getArgOperand(1), m_APFloat(C)) && C->isNegative()) {
2295       // If we know that the sign argument is negative, reduce to FNABS:
2296       // copysign X, Neg --> fneg (fabs X)
2297       Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs,
2298                                                  II->getArgOperand(0), II);
2299       return replaceInstUsesWith(*II, Builder.CreateFNegFMF(Fabs, II));
2300     }
2301 
2302     // Propagate sign argument through nested calls:
2303     // copysign X, (copysign ?, SignArg) --> copysign X, SignArg
2304     Value *SignArg;
2305     if (match(II->getArgOperand(1),
2306               m_Intrinsic<Intrinsic::copysign>(m_Value(), m_Value(SignArg)))) {
2307       II->setArgOperand(1, SignArg);
2308       return II;
2309     }
2310 
2311     break;
2312   }
2313   case Intrinsic::fabs: {
2314     Value *Cond;
2315     Constant *LHS, *RHS;
2316     if (match(II->getArgOperand(0),
2317               m_Select(m_Value(Cond), m_Constant(LHS), m_Constant(RHS)))) {
2318       CallInst *Call0 = Builder.CreateCall(II->getCalledFunction(), {LHS});
2319       CallInst *Call1 = Builder.CreateCall(II->getCalledFunction(), {RHS});
2320       return SelectInst::Create(Cond, Call0, Call1);
2321     }
2322 
2323     LLVM_FALLTHROUGH;
2324   }
2325   case Intrinsic::ceil:
2326   case Intrinsic::floor:
2327   case Intrinsic::round:
2328   case Intrinsic::nearbyint:
2329   case Intrinsic::rint:
2330   case Intrinsic::trunc: {
2331     Value *ExtSrc;
2332     if (match(II->getArgOperand(0), m_OneUse(m_FPExt(m_Value(ExtSrc))))) {
2333       // Narrow the call: intrinsic (fpext x) -> fpext (intrinsic x)
2334       Value *NarrowII = Builder.CreateUnaryIntrinsic(IID, ExtSrc, II);
2335       return new FPExtInst(NarrowII, II->getType());
2336     }
2337     break;
2338   }
2339   case Intrinsic::cos:
2340   case Intrinsic::amdgcn_cos: {
2341     Value *X;
2342     Value *Src = II->getArgOperand(0);
2343     if (match(Src, m_FNeg(m_Value(X))) || match(Src, m_FAbs(m_Value(X)))) {
2344       // cos(-x) -> cos(x)
2345       // cos(fabs(x)) -> cos(x)
2346       II->setArgOperand(0, X);
2347       return II;
2348     }
2349     break;
2350   }
2351   case Intrinsic::sin: {
2352     Value *X;
2353     if (match(II->getArgOperand(0), m_OneUse(m_FNeg(m_Value(X))))) {
2354       // sin(-x) --> -sin(x)
2355       Value *NewSin = Builder.CreateUnaryIntrinsic(Intrinsic::sin, X, II);
2356       Instruction *FNeg = BinaryOperator::CreateFNeg(NewSin);
2357       FNeg->copyFastMathFlags(II);
2358       return FNeg;
2359     }
2360     break;
2361   }
2362   case Intrinsic::ppc_altivec_lvx:
2363   case Intrinsic::ppc_altivec_lvxl:
2364     // Turn PPC lvx -> load if the pointer is known aligned.
2365     if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, II, &AC,
2366                                    &DT) >= 16) {
2367       Value *Ptr = Builder.CreateBitCast(II->getArgOperand(0),
2368                                          PointerType::getUnqual(II->getType()));
2369       return new LoadInst(II->getType(), Ptr);
2370     }
2371     break;
2372   case Intrinsic::ppc_vsx_lxvw4x:
2373   case Intrinsic::ppc_vsx_lxvd2x: {
2374     // Turn PPC VSX loads into normal loads.
2375     Value *Ptr = Builder.CreateBitCast(II->getArgOperand(0),
2376                                        PointerType::getUnqual(II->getType()));
2377     return new LoadInst(II->getType(), Ptr, Twine(""), false, Align(1));
2378   }
2379   case Intrinsic::ppc_altivec_stvx:
2380   case Intrinsic::ppc_altivec_stvxl:
2381     // Turn stvx -> store if the pointer is known aligned.
2382     if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, DL, II, &AC,
2383                                    &DT) >= 16) {
2384       Type *OpPtrTy =
2385         PointerType::getUnqual(II->getArgOperand(0)->getType());
2386       Value *Ptr = Builder.CreateBitCast(II->getArgOperand(1), OpPtrTy);
2387       return new StoreInst(II->getArgOperand(0), Ptr);
2388     }
2389     break;
2390   case Intrinsic::ppc_vsx_stxvw4x:
2391   case Intrinsic::ppc_vsx_stxvd2x: {
2392     // Turn PPC VSX stores into normal stores.
2393     Type *OpPtrTy = PointerType::getUnqual(II->getArgOperand(0)->getType());
2394     Value *Ptr = Builder.CreateBitCast(II->getArgOperand(1), OpPtrTy);
2395     return new StoreInst(II->getArgOperand(0), Ptr, false, Align(1));
2396   }
2397   case Intrinsic::ppc_qpx_qvlfs:
2398     // Turn PPC QPX qvlfs -> load if the pointer is known aligned.
2399     if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, II, &AC,
2400                                    &DT) >= 16) {
2401       Type *VTy = VectorType::get(Builder.getFloatTy(),
2402                                   II->getType()->getVectorNumElements());
2403       Value *Ptr = Builder.CreateBitCast(II->getArgOperand(0),
2404                                          PointerType::getUnqual(VTy));
2405       Value *Load = Builder.CreateLoad(VTy, Ptr);
2406       return new FPExtInst(Load, II->getType());
2407     }
2408     break;
2409   case Intrinsic::ppc_qpx_qvlfd:
2410     // Turn PPC QPX qvlfd -> load if the pointer is known aligned.
2411     if (getOrEnforceKnownAlignment(II->getArgOperand(0), 32, DL, II, &AC,
2412                                    &DT) >= 32) {
2413       Value *Ptr = Builder.CreateBitCast(II->getArgOperand(0),
2414                                          PointerType::getUnqual(II->getType()));
2415       return new LoadInst(II->getType(), Ptr);
2416     }
2417     break;
2418   case Intrinsic::ppc_qpx_qvstfs:
2419     // Turn PPC QPX qvstfs -> store if the pointer is known aligned.
2420     if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, DL, II, &AC,
2421                                    &DT) >= 16) {
2422       Type *VTy = VectorType::get(Builder.getFloatTy(),
2423           II->getArgOperand(0)->getType()->getVectorNumElements());
2424       Value *TOp = Builder.CreateFPTrunc(II->getArgOperand(0), VTy);
2425       Type *OpPtrTy = PointerType::getUnqual(VTy);
2426       Value *Ptr = Builder.CreateBitCast(II->getArgOperand(1), OpPtrTy);
2427       return new StoreInst(TOp, Ptr);
2428     }
2429     break;
2430   case Intrinsic::ppc_qpx_qvstfd:
2431     // Turn PPC QPX qvstfd -> store if the pointer is known aligned.
2432     if (getOrEnforceKnownAlignment(II->getArgOperand(1), 32, DL, II, &AC,
2433                                    &DT) >= 32) {
2434       Type *OpPtrTy =
2435         PointerType::getUnqual(II->getArgOperand(0)->getType());
2436       Value *Ptr = Builder.CreateBitCast(II->getArgOperand(1), OpPtrTy);
2437       return new StoreInst(II->getArgOperand(0), Ptr);
2438     }
2439     break;
2440 
2441   case Intrinsic::x86_bmi_bextr_32:
2442   case Intrinsic::x86_bmi_bextr_64:
2443   case Intrinsic::x86_tbm_bextri_u32:
2444   case Intrinsic::x86_tbm_bextri_u64:
2445     // If the RHS is a constant we can try some simplifications.
2446     if (auto *C = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
2447       uint64_t Shift = C->getZExtValue();
2448       uint64_t Length = (Shift >> 8) & 0xff;
2449       Shift &= 0xff;
2450       unsigned BitWidth = II->getType()->getIntegerBitWidth();
2451       // If the length is 0 or the shift is out of range, replace with zero.
2452       if (Length == 0 || Shift >= BitWidth)
2453         return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), 0));
2454       // If the LHS is also a constant, we can completely constant fold this.
2455       if (auto *InC = dyn_cast<ConstantInt>(II->getArgOperand(0))) {
2456         uint64_t Result = InC->getZExtValue() >> Shift;
2457         if (Length > BitWidth)
2458           Length = BitWidth;
2459         Result &= maskTrailingOnes<uint64_t>(Length);
2460         return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), Result));
2461       }
2462       // TODO should we turn this into 'and' if shift is 0? Or 'shl' if we
2463       // are only masking bits that a shift already cleared?
2464     }
2465     break;
2466 
2467   case Intrinsic::x86_bmi_bzhi_32:
2468   case Intrinsic::x86_bmi_bzhi_64:
2469     // If the RHS is a constant we can try some simplifications.
2470     if (auto *C = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
2471       uint64_t Index = C->getZExtValue() & 0xff;
2472       unsigned BitWidth = II->getType()->getIntegerBitWidth();
2473       if (Index >= BitWidth)
2474         return replaceInstUsesWith(CI, II->getArgOperand(0));
2475       if (Index == 0)
2476         return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), 0));
2477       // If the LHS is also a constant, we can completely constant fold this.
2478       if (auto *InC = dyn_cast<ConstantInt>(II->getArgOperand(0))) {
2479         uint64_t Result = InC->getZExtValue();
2480         Result &= maskTrailingOnes<uint64_t>(Index);
2481         return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), Result));
2482       }
2483       // TODO should we convert this to an AND if the RHS is constant?
2484     }
2485     break;
2486   case Intrinsic::x86_bmi_pext_32:
2487   case Intrinsic::x86_bmi_pext_64:
2488     if (auto *MaskC = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
2489       if (MaskC->isNullValue())
2490         return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), 0));
2491       if (MaskC->isAllOnesValue())
2492         return replaceInstUsesWith(CI, II->getArgOperand(0));
2493 
2494       if (auto *SrcC = dyn_cast<ConstantInt>(II->getArgOperand(0))) {
2495         uint64_t Src = SrcC->getZExtValue();
2496         uint64_t Mask = MaskC->getZExtValue();
2497         uint64_t Result = 0;
2498         uint64_t BitToSet = 1;
2499 
2500         while (Mask) {
2501           // Isolate lowest set bit.
2502           uint64_t BitToTest = Mask & -Mask;
2503           if (BitToTest & Src)
2504             Result |= BitToSet;
2505 
2506           BitToSet <<= 1;
2507           // Clear lowest set bit.
2508           Mask &= Mask - 1;
2509         }
2510 
2511         return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), Result));
2512       }
2513     }
2514     break;
2515   case Intrinsic::x86_bmi_pdep_32:
2516   case Intrinsic::x86_bmi_pdep_64:
2517     if (auto *MaskC = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
2518       if (MaskC->isNullValue())
2519         return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), 0));
2520       if (MaskC->isAllOnesValue())
2521         return replaceInstUsesWith(CI, II->getArgOperand(0));
2522 
2523       if (auto *SrcC = dyn_cast<ConstantInt>(II->getArgOperand(0))) {
2524         uint64_t Src = SrcC->getZExtValue();
2525         uint64_t Mask = MaskC->getZExtValue();
2526         uint64_t Result = 0;
2527         uint64_t BitToTest = 1;
2528 
2529         while (Mask) {
2530           // Isolate lowest set bit.
2531           uint64_t BitToSet = Mask & -Mask;
2532           if (BitToTest & Src)
2533             Result |= BitToSet;
2534 
2535           BitToTest <<= 1;
2536           // Clear lowest set bit;
2537           Mask &= Mask - 1;
2538         }
2539 
2540         return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), Result));
2541       }
2542     }
2543     break;
2544 
2545   case Intrinsic::x86_vcvtph2ps_128:
2546   case Intrinsic::x86_vcvtph2ps_256: {
2547     auto Arg = II->getArgOperand(0);
2548     auto ArgType = cast<VectorType>(Arg->getType());
2549     auto RetType = cast<VectorType>(II->getType());
2550     unsigned ArgWidth = ArgType->getNumElements();
2551     unsigned RetWidth = RetType->getNumElements();
2552     assert(RetWidth <= ArgWidth && "Unexpected input/return vector widths");
2553     assert(ArgType->isIntOrIntVectorTy() &&
2554            ArgType->getScalarSizeInBits() == 16 &&
2555            "CVTPH2PS input type should be 16-bit integer vector");
2556     assert(RetType->getScalarType()->isFloatTy() &&
2557            "CVTPH2PS output type should be 32-bit float vector");
2558 
2559     // Constant folding: Convert to generic half to single conversion.
2560     if (isa<ConstantAggregateZero>(Arg))
2561       return replaceInstUsesWith(*II, ConstantAggregateZero::get(RetType));
2562 
2563     if (isa<ConstantDataVector>(Arg)) {
2564       auto VectorHalfAsShorts = Arg;
2565       if (RetWidth < ArgWidth) {
2566         SmallVector<uint32_t, 8> SubVecMask;
2567         for (unsigned i = 0; i != RetWidth; ++i)
2568           SubVecMask.push_back((int)i);
2569         VectorHalfAsShorts = Builder.CreateShuffleVector(
2570             Arg, UndefValue::get(ArgType), SubVecMask);
2571       }
2572 
2573       auto VectorHalfType =
2574           VectorType::get(Type::getHalfTy(II->getContext()), RetWidth);
2575       auto VectorHalfs =
2576           Builder.CreateBitCast(VectorHalfAsShorts, VectorHalfType);
2577       auto VectorFloats = Builder.CreateFPExt(VectorHalfs, RetType);
2578       return replaceInstUsesWith(*II, VectorFloats);
2579     }
2580 
2581     // We only use the lowest lanes of the argument.
2582     if (Value *V = SimplifyDemandedVectorEltsLow(Arg, ArgWidth, RetWidth)) {
2583       II->setArgOperand(0, V);
2584       return II;
2585     }
2586     break;
2587   }
2588 
2589   case Intrinsic::x86_sse_cvtss2si:
2590   case Intrinsic::x86_sse_cvtss2si64:
2591   case Intrinsic::x86_sse_cvttss2si:
2592   case Intrinsic::x86_sse_cvttss2si64:
2593   case Intrinsic::x86_sse2_cvtsd2si:
2594   case Intrinsic::x86_sse2_cvtsd2si64:
2595   case Intrinsic::x86_sse2_cvttsd2si:
2596   case Intrinsic::x86_sse2_cvttsd2si64:
2597   case Intrinsic::x86_avx512_vcvtss2si32:
2598   case Intrinsic::x86_avx512_vcvtss2si64:
2599   case Intrinsic::x86_avx512_vcvtss2usi32:
2600   case Intrinsic::x86_avx512_vcvtss2usi64:
2601   case Intrinsic::x86_avx512_vcvtsd2si32:
2602   case Intrinsic::x86_avx512_vcvtsd2si64:
2603   case Intrinsic::x86_avx512_vcvtsd2usi32:
2604   case Intrinsic::x86_avx512_vcvtsd2usi64:
2605   case Intrinsic::x86_avx512_cvttss2si:
2606   case Intrinsic::x86_avx512_cvttss2si64:
2607   case Intrinsic::x86_avx512_cvttss2usi:
2608   case Intrinsic::x86_avx512_cvttss2usi64:
2609   case Intrinsic::x86_avx512_cvttsd2si:
2610   case Intrinsic::x86_avx512_cvttsd2si64:
2611   case Intrinsic::x86_avx512_cvttsd2usi:
2612   case Intrinsic::x86_avx512_cvttsd2usi64: {
2613     // These intrinsics only demand the 0th element of their input vectors. If
2614     // we can simplify the input based on that, do so now.
2615     Value *Arg = II->getArgOperand(0);
2616     unsigned VWidth = Arg->getType()->getVectorNumElements();
2617     if (Value *V = SimplifyDemandedVectorEltsLow(Arg, VWidth, 1)) {
2618       II->setArgOperand(0, V);
2619       return II;
2620     }
2621     break;
2622   }
2623 
2624   case Intrinsic::x86_mmx_pmovmskb:
2625   case Intrinsic::x86_sse_movmsk_ps:
2626   case Intrinsic::x86_sse2_movmsk_pd:
2627   case Intrinsic::x86_sse2_pmovmskb_128:
2628   case Intrinsic::x86_avx_movmsk_pd_256:
2629   case Intrinsic::x86_avx_movmsk_ps_256:
2630   case Intrinsic::x86_avx2_pmovmskb:
2631     if (Value *V = simplifyX86movmsk(*II, Builder))
2632       return replaceInstUsesWith(*II, V);
2633     break;
2634 
2635   case Intrinsic::x86_sse_comieq_ss:
2636   case Intrinsic::x86_sse_comige_ss:
2637   case Intrinsic::x86_sse_comigt_ss:
2638   case Intrinsic::x86_sse_comile_ss:
2639   case Intrinsic::x86_sse_comilt_ss:
2640   case Intrinsic::x86_sse_comineq_ss:
2641   case Intrinsic::x86_sse_ucomieq_ss:
2642   case Intrinsic::x86_sse_ucomige_ss:
2643   case Intrinsic::x86_sse_ucomigt_ss:
2644   case Intrinsic::x86_sse_ucomile_ss:
2645   case Intrinsic::x86_sse_ucomilt_ss:
2646   case Intrinsic::x86_sse_ucomineq_ss:
2647   case Intrinsic::x86_sse2_comieq_sd:
2648   case Intrinsic::x86_sse2_comige_sd:
2649   case Intrinsic::x86_sse2_comigt_sd:
2650   case Intrinsic::x86_sse2_comile_sd:
2651   case Intrinsic::x86_sse2_comilt_sd:
2652   case Intrinsic::x86_sse2_comineq_sd:
2653   case Intrinsic::x86_sse2_ucomieq_sd:
2654   case Intrinsic::x86_sse2_ucomige_sd:
2655   case Intrinsic::x86_sse2_ucomigt_sd:
2656   case Intrinsic::x86_sse2_ucomile_sd:
2657   case Intrinsic::x86_sse2_ucomilt_sd:
2658   case Intrinsic::x86_sse2_ucomineq_sd:
2659   case Intrinsic::x86_avx512_vcomi_ss:
2660   case Intrinsic::x86_avx512_vcomi_sd:
2661   case Intrinsic::x86_avx512_mask_cmp_ss:
2662   case Intrinsic::x86_avx512_mask_cmp_sd: {
2663     // These intrinsics only demand the 0th element of their input vectors. If
2664     // we can simplify the input based on that, do so now.
2665     bool MadeChange = false;
2666     Value *Arg0 = II->getArgOperand(0);
2667     Value *Arg1 = II->getArgOperand(1);
2668     unsigned VWidth = Arg0->getType()->getVectorNumElements();
2669     if (Value *V = SimplifyDemandedVectorEltsLow(Arg0, VWidth, 1)) {
2670       II->setArgOperand(0, V);
2671       MadeChange = true;
2672     }
2673     if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, 1)) {
2674       II->setArgOperand(1, V);
2675       MadeChange = true;
2676     }
2677     if (MadeChange)
2678       return II;
2679     break;
2680   }
2681   case Intrinsic::x86_avx512_cmp_pd_128:
2682   case Intrinsic::x86_avx512_cmp_pd_256:
2683   case Intrinsic::x86_avx512_cmp_pd_512:
2684   case Intrinsic::x86_avx512_cmp_ps_128:
2685   case Intrinsic::x86_avx512_cmp_ps_256:
2686   case Intrinsic::x86_avx512_cmp_ps_512: {
2687     // Folding cmp(sub(a,b),0) -> cmp(a,b) and cmp(0,sub(a,b)) -> cmp(b,a)
2688     Value *Arg0 = II->getArgOperand(0);
2689     Value *Arg1 = II->getArgOperand(1);
2690     bool Arg0IsZero = match(Arg0, m_PosZeroFP());
2691     if (Arg0IsZero)
2692       std::swap(Arg0, Arg1);
2693     Value *A, *B;
2694     // This fold requires only the NINF(not +/- inf) since inf minus
2695     // inf is nan.
2696     // NSZ(No Signed Zeros) is not needed because zeros of any sign are
2697     // equal for both compares.
2698     // NNAN is not needed because nans compare the same for both compares.
2699     // The compare intrinsic uses the above assumptions and therefore
2700     // doesn't require additional flags.
2701     if ((match(Arg0, m_OneUse(m_FSub(m_Value(A), m_Value(B)))) &&
2702          match(Arg1, m_PosZeroFP()) && isa<Instruction>(Arg0) &&
2703          cast<Instruction>(Arg0)->getFastMathFlags().noInfs())) {
2704       if (Arg0IsZero)
2705         std::swap(A, B);
2706       II->setArgOperand(0, A);
2707       II->setArgOperand(1, B);
2708       return II;
2709     }
2710     break;
2711   }
2712 
2713   case Intrinsic::x86_avx512_add_ps_512:
2714   case Intrinsic::x86_avx512_div_ps_512:
2715   case Intrinsic::x86_avx512_mul_ps_512:
2716   case Intrinsic::x86_avx512_sub_ps_512:
2717   case Intrinsic::x86_avx512_add_pd_512:
2718   case Intrinsic::x86_avx512_div_pd_512:
2719   case Intrinsic::x86_avx512_mul_pd_512:
2720   case Intrinsic::x86_avx512_sub_pd_512:
2721     // If the rounding mode is CUR_DIRECTION(4) we can turn these into regular
2722     // IR operations.
2723     if (auto *R = dyn_cast<ConstantInt>(II->getArgOperand(2))) {
2724       if (R->getValue() == 4) {
2725         Value *Arg0 = II->getArgOperand(0);
2726         Value *Arg1 = II->getArgOperand(1);
2727 
2728         Value *V;
2729         switch (IID) {
2730         default: llvm_unreachable("Case stmts out of sync!");
2731         case Intrinsic::x86_avx512_add_ps_512:
2732         case Intrinsic::x86_avx512_add_pd_512:
2733           V = Builder.CreateFAdd(Arg0, Arg1);
2734           break;
2735         case Intrinsic::x86_avx512_sub_ps_512:
2736         case Intrinsic::x86_avx512_sub_pd_512:
2737           V = Builder.CreateFSub(Arg0, Arg1);
2738           break;
2739         case Intrinsic::x86_avx512_mul_ps_512:
2740         case Intrinsic::x86_avx512_mul_pd_512:
2741           V = Builder.CreateFMul(Arg0, Arg1);
2742           break;
2743         case Intrinsic::x86_avx512_div_ps_512:
2744         case Intrinsic::x86_avx512_div_pd_512:
2745           V = Builder.CreateFDiv(Arg0, Arg1);
2746           break;
2747         }
2748 
2749         return replaceInstUsesWith(*II, V);
2750       }
2751     }
2752     break;
2753 
2754   case Intrinsic::x86_avx512_mask_add_ss_round:
2755   case Intrinsic::x86_avx512_mask_div_ss_round:
2756   case Intrinsic::x86_avx512_mask_mul_ss_round:
2757   case Intrinsic::x86_avx512_mask_sub_ss_round:
2758   case Intrinsic::x86_avx512_mask_add_sd_round:
2759   case Intrinsic::x86_avx512_mask_div_sd_round:
2760   case Intrinsic::x86_avx512_mask_mul_sd_round:
2761   case Intrinsic::x86_avx512_mask_sub_sd_round:
2762     // If the rounding mode is CUR_DIRECTION(4) we can turn these into regular
2763     // IR operations.
2764     if (auto *R = dyn_cast<ConstantInt>(II->getArgOperand(4))) {
2765       if (R->getValue() == 4) {
2766         // Extract the element as scalars.
2767         Value *Arg0 = II->getArgOperand(0);
2768         Value *Arg1 = II->getArgOperand(1);
2769         Value *LHS = Builder.CreateExtractElement(Arg0, (uint64_t)0);
2770         Value *RHS = Builder.CreateExtractElement(Arg1, (uint64_t)0);
2771 
2772         Value *V;
2773         switch (IID) {
2774         default: llvm_unreachable("Case stmts out of sync!");
2775         case Intrinsic::x86_avx512_mask_add_ss_round:
2776         case Intrinsic::x86_avx512_mask_add_sd_round:
2777           V = Builder.CreateFAdd(LHS, RHS);
2778           break;
2779         case Intrinsic::x86_avx512_mask_sub_ss_round:
2780         case Intrinsic::x86_avx512_mask_sub_sd_round:
2781           V = Builder.CreateFSub(LHS, RHS);
2782           break;
2783         case Intrinsic::x86_avx512_mask_mul_ss_round:
2784         case Intrinsic::x86_avx512_mask_mul_sd_round:
2785           V = Builder.CreateFMul(LHS, RHS);
2786           break;
2787         case Intrinsic::x86_avx512_mask_div_ss_round:
2788         case Intrinsic::x86_avx512_mask_div_sd_round:
2789           V = Builder.CreateFDiv(LHS, RHS);
2790           break;
2791         }
2792 
2793         // Handle the masking aspect of the intrinsic.
2794         Value *Mask = II->getArgOperand(3);
2795         auto *C = dyn_cast<ConstantInt>(Mask);
2796         // We don't need a select if we know the mask bit is a 1.
2797         if (!C || !C->getValue()[0]) {
2798           // Cast the mask to an i1 vector and then extract the lowest element.
2799           auto *MaskTy = VectorType::get(Builder.getInt1Ty(),
2800                              cast<IntegerType>(Mask->getType())->getBitWidth());
2801           Mask = Builder.CreateBitCast(Mask, MaskTy);
2802           Mask = Builder.CreateExtractElement(Mask, (uint64_t)0);
2803           // Extract the lowest element from the passthru operand.
2804           Value *Passthru = Builder.CreateExtractElement(II->getArgOperand(2),
2805                                                           (uint64_t)0);
2806           V = Builder.CreateSelect(Mask, V, Passthru);
2807         }
2808 
2809         // Insert the result back into the original argument 0.
2810         V = Builder.CreateInsertElement(Arg0, V, (uint64_t)0);
2811 
2812         return replaceInstUsesWith(*II, V);
2813       }
2814     }
2815     break;
2816 
2817   // Constant fold ashr( <A x Bi>, Ci ).
2818   // Constant fold lshr( <A x Bi>, Ci ).
2819   // Constant fold shl( <A x Bi>, Ci ).
2820   case Intrinsic::x86_sse2_psrai_d:
2821   case Intrinsic::x86_sse2_psrai_w:
2822   case Intrinsic::x86_avx2_psrai_d:
2823   case Intrinsic::x86_avx2_psrai_w:
2824   case Intrinsic::x86_avx512_psrai_q_128:
2825   case Intrinsic::x86_avx512_psrai_q_256:
2826   case Intrinsic::x86_avx512_psrai_d_512:
2827   case Intrinsic::x86_avx512_psrai_q_512:
2828   case Intrinsic::x86_avx512_psrai_w_512:
2829   case Intrinsic::x86_sse2_psrli_d:
2830   case Intrinsic::x86_sse2_psrli_q:
2831   case Intrinsic::x86_sse2_psrli_w:
2832   case Intrinsic::x86_avx2_psrli_d:
2833   case Intrinsic::x86_avx2_psrli_q:
2834   case Intrinsic::x86_avx2_psrli_w:
2835   case Intrinsic::x86_avx512_psrli_d_512:
2836   case Intrinsic::x86_avx512_psrli_q_512:
2837   case Intrinsic::x86_avx512_psrli_w_512:
2838   case Intrinsic::x86_sse2_pslli_d:
2839   case Intrinsic::x86_sse2_pslli_q:
2840   case Intrinsic::x86_sse2_pslli_w:
2841   case Intrinsic::x86_avx2_pslli_d:
2842   case Intrinsic::x86_avx2_pslli_q:
2843   case Intrinsic::x86_avx2_pslli_w:
2844   case Intrinsic::x86_avx512_pslli_d_512:
2845   case Intrinsic::x86_avx512_pslli_q_512:
2846   case Intrinsic::x86_avx512_pslli_w_512:
2847     if (Value *V = simplifyX86immShift(*II, Builder))
2848       return replaceInstUsesWith(*II, V);
2849     break;
2850 
2851   case Intrinsic::x86_sse2_psra_d:
2852   case Intrinsic::x86_sse2_psra_w:
2853   case Intrinsic::x86_avx2_psra_d:
2854   case Intrinsic::x86_avx2_psra_w:
2855   case Intrinsic::x86_avx512_psra_q_128:
2856   case Intrinsic::x86_avx512_psra_q_256:
2857   case Intrinsic::x86_avx512_psra_d_512:
2858   case Intrinsic::x86_avx512_psra_q_512:
2859   case Intrinsic::x86_avx512_psra_w_512:
2860   case Intrinsic::x86_sse2_psrl_d:
2861   case Intrinsic::x86_sse2_psrl_q:
2862   case Intrinsic::x86_sse2_psrl_w:
2863   case Intrinsic::x86_avx2_psrl_d:
2864   case Intrinsic::x86_avx2_psrl_q:
2865   case Intrinsic::x86_avx2_psrl_w:
2866   case Intrinsic::x86_avx512_psrl_d_512:
2867   case Intrinsic::x86_avx512_psrl_q_512:
2868   case Intrinsic::x86_avx512_psrl_w_512:
2869   case Intrinsic::x86_sse2_psll_d:
2870   case Intrinsic::x86_sse2_psll_q:
2871   case Intrinsic::x86_sse2_psll_w:
2872   case Intrinsic::x86_avx2_psll_d:
2873   case Intrinsic::x86_avx2_psll_q:
2874   case Intrinsic::x86_avx2_psll_w:
2875   case Intrinsic::x86_avx512_psll_d_512:
2876   case Intrinsic::x86_avx512_psll_q_512:
2877   case Intrinsic::x86_avx512_psll_w_512: {
2878     if (Value *V = simplifyX86immShift(*II, Builder))
2879       return replaceInstUsesWith(*II, V);
2880 
2881     // SSE2/AVX2 uses only the first 64-bits of the 128-bit vector
2882     // operand to compute the shift amount.
2883     Value *Arg1 = II->getArgOperand(1);
2884     assert(Arg1->getType()->getPrimitiveSizeInBits() == 128 &&
2885            "Unexpected packed shift size");
2886     unsigned VWidth = Arg1->getType()->getVectorNumElements();
2887 
2888     if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, VWidth / 2)) {
2889       II->setArgOperand(1, V);
2890       return II;
2891     }
2892     break;
2893   }
2894 
2895   case Intrinsic::x86_avx2_psllv_d:
2896   case Intrinsic::x86_avx2_psllv_d_256:
2897   case Intrinsic::x86_avx2_psllv_q:
2898   case Intrinsic::x86_avx2_psllv_q_256:
2899   case Intrinsic::x86_avx512_psllv_d_512:
2900   case Intrinsic::x86_avx512_psllv_q_512:
2901   case Intrinsic::x86_avx512_psllv_w_128:
2902   case Intrinsic::x86_avx512_psllv_w_256:
2903   case Intrinsic::x86_avx512_psllv_w_512:
2904   case Intrinsic::x86_avx2_psrav_d:
2905   case Intrinsic::x86_avx2_psrav_d_256:
2906   case Intrinsic::x86_avx512_psrav_q_128:
2907   case Intrinsic::x86_avx512_psrav_q_256:
2908   case Intrinsic::x86_avx512_psrav_d_512:
2909   case Intrinsic::x86_avx512_psrav_q_512:
2910   case Intrinsic::x86_avx512_psrav_w_128:
2911   case Intrinsic::x86_avx512_psrav_w_256:
2912   case Intrinsic::x86_avx512_psrav_w_512:
2913   case Intrinsic::x86_avx2_psrlv_d:
2914   case Intrinsic::x86_avx2_psrlv_d_256:
2915   case Intrinsic::x86_avx2_psrlv_q:
2916   case Intrinsic::x86_avx2_psrlv_q_256:
2917   case Intrinsic::x86_avx512_psrlv_d_512:
2918   case Intrinsic::x86_avx512_psrlv_q_512:
2919   case Intrinsic::x86_avx512_psrlv_w_128:
2920   case Intrinsic::x86_avx512_psrlv_w_256:
2921   case Intrinsic::x86_avx512_psrlv_w_512:
2922     if (Value *V = simplifyX86varShift(*II, Builder))
2923       return replaceInstUsesWith(*II, V);
2924     break;
2925 
2926   case Intrinsic::x86_sse2_packssdw_128:
2927   case Intrinsic::x86_sse2_packsswb_128:
2928   case Intrinsic::x86_avx2_packssdw:
2929   case Intrinsic::x86_avx2_packsswb:
2930   case Intrinsic::x86_avx512_packssdw_512:
2931   case Intrinsic::x86_avx512_packsswb_512:
2932     if (Value *V = simplifyX86pack(*II, Builder, true))
2933       return replaceInstUsesWith(*II, V);
2934     break;
2935 
2936   case Intrinsic::x86_sse2_packuswb_128:
2937   case Intrinsic::x86_sse41_packusdw:
2938   case Intrinsic::x86_avx2_packusdw:
2939   case Intrinsic::x86_avx2_packuswb:
2940   case Intrinsic::x86_avx512_packusdw_512:
2941   case Intrinsic::x86_avx512_packuswb_512:
2942     if (Value *V = simplifyX86pack(*II, Builder, false))
2943       return replaceInstUsesWith(*II, V);
2944     break;
2945 
2946   case Intrinsic::x86_pclmulqdq:
2947   case Intrinsic::x86_pclmulqdq_256:
2948   case Intrinsic::x86_pclmulqdq_512: {
2949     if (auto *C = dyn_cast<ConstantInt>(II->getArgOperand(2))) {
2950       unsigned Imm = C->getZExtValue();
2951 
2952       bool MadeChange = false;
2953       Value *Arg0 = II->getArgOperand(0);
2954       Value *Arg1 = II->getArgOperand(1);
2955       unsigned VWidth = Arg0->getType()->getVectorNumElements();
2956 
2957       APInt UndefElts1(VWidth, 0);
2958       APInt DemandedElts1 = APInt::getSplat(VWidth,
2959                                             APInt(2, (Imm & 0x01) ? 2 : 1));
2960       if (Value *V = SimplifyDemandedVectorElts(Arg0, DemandedElts1,
2961                                                 UndefElts1)) {
2962         II->setArgOperand(0, V);
2963         MadeChange = true;
2964       }
2965 
2966       APInt UndefElts2(VWidth, 0);
2967       APInt DemandedElts2 = APInt::getSplat(VWidth,
2968                                             APInt(2, (Imm & 0x10) ? 2 : 1));
2969       if (Value *V = SimplifyDemandedVectorElts(Arg1, DemandedElts2,
2970                                                 UndefElts2)) {
2971         II->setArgOperand(1, V);
2972         MadeChange = true;
2973       }
2974 
2975       // If either input elements are undef, the result is zero.
2976       if (DemandedElts1.isSubsetOf(UndefElts1) ||
2977           DemandedElts2.isSubsetOf(UndefElts2))
2978         return replaceInstUsesWith(*II,
2979                                    ConstantAggregateZero::get(II->getType()));
2980 
2981       if (MadeChange)
2982         return II;
2983     }
2984     break;
2985   }
2986 
2987   case Intrinsic::x86_sse41_insertps:
2988     if (Value *V = simplifyX86insertps(*II, Builder))
2989       return replaceInstUsesWith(*II, V);
2990     break;
2991 
2992   case Intrinsic::x86_sse4a_extrq: {
2993     Value *Op0 = II->getArgOperand(0);
2994     Value *Op1 = II->getArgOperand(1);
2995     unsigned VWidth0 = Op0->getType()->getVectorNumElements();
2996     unsigned VWidth1 = Op1->getType()->getVectorNumElements();
2997     assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
2998            Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth0 == 2 &&
2999            VWidth1 == 16 && "Unexpected operand sizes");
3000 
3001     // See if we're dealing with constant values.
3002     Constant *C1 = dyn_cast<Constant>(Op1);
3003     ConstantInt *CILength =
3004         C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)0))
3005            : nullptr;
3006     ConstantInt *CIIndex =
3007         C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)1))
3008            : nullptr;
3009 
3010     // Attempt to simplify to a constant, shuffle vector or EXTRQI call.
3011     if (Value *V = simplifyX86extrq(*II, Op0, CILength, CIIndex, Builder))
3012       return replaceInstUsesWith(*II, V);
3013 
3014     // EXTRQ only uses the lowest 64-bits of the first 128-bit vector
3015     // operands and the lowest 16-bits of the second.
3016     bool MadeChange = false;
3017     if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth0, 1)) {
3018       II->setArgOperand(0, V);
3019       MadeChange = true;
3020     }
3021     if (Value *V = SimplifyDemandedVectorEltsLow(Op1, VWidth1, 2)) {
3022       II->setArgOperand(1, V);
3023       MadeChange = true;
3024     }
3025     if (MadeChange)
3026       return II;
3027     break;
3028   }
3029 
3030   case Intrinsic::x86_sse4a_extrqi: {
3031     // EXTRQI: Extract Length bits starting from Index. Zero pad the remaining
3032     // bits of the lower 64-bits. The upper 64-bits are undefined.
3033     Value *Op0 = II->getArgOperand(0);
3034     unsigned VWidth = Op0->getType()->getVectorNumElements();
3035     assert(Op0->getType()->getPrimitiveSizeInBits() == 128 && VWidth == 2 &&
3036            "Unexpected operand size");
3037 
3038     // See if we're dealing with constant values.
3039     ConstantInt *CILength = dyn_cast<ConstantInt>(II->getArgOperand(1));
3040     ConstantInt *CIIndex = dyn_cast<ConstantInt>(II->getArgOperand(2));
3041 
3042     // Attempt to simplify to a constant or shuffle vector.
3043     if (Value *V = simplifyX86extrq(*II, Op0, CILength, CIIndex, Builder))
3044       return replaceInstUsesWith(*II, V);
3045 
3046     // EXTRQI only uses the lowest 64-bits of the first 128-bit vector
3047     // operand.
3048     if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth, 1)) {
3049       II->setArgOperand(0, V);
3050       return II;
3051     }
3052     break;
3053   }
3054 
3055   case Intrinsic::x86_sse4a_insertq: {
3056     Value *Op0 = II->getArgOperand(0);
3057     Value *Op1 = II->getArgOperand(1);
3058     unsigned VWidth = Op0->getType()->getVectorNumElements();
3059     assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
3060            Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth == 2 &&
3061            Op1->getType()->getVectorNumElements() == 2 &&
3062            "Unexpected operand size");
3063 
3064     // See if we're dealing with constant values.
3065     Constant *C1 = dyn_cast<Constant>(Op1);
3066     ConstantInt *CI11 =
3067         C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)1))
3068            : nullptr;
3069 
3070     // Attempt to simplify to a constant, shuffle vector or INSERTQI call.
3071     if (CI11) {
3072       const APInt &V11 = CI11->getValue();
3073       APInt Len = V11.zextOrTrunc(6);
3074       APInt Idx = V11.lshr(8).zextOrTrunc(6);
3075       if (Value *V = simplifyX86insertq(*II, Op0, Op1, Len, Idx, Builder))
3076         return replaceInstUsesWith(*II, V);
3077     }
3078 
3079     // INSERTQ only uses the lowest 64-bits of the first 128-bit vector
3080     // operand.
3081     if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth, 1)) {
3082       II->setArgOperand(0, V);
3083       return II;
3084     }
3085     break;
3086   }
3087 
3088   case Intrinsic::x86_sse4a_insertqi: {
3089     // INSERTQI: Extract lowest Length bits from lower half of second source and
3090     // insert over first source starting at Index bit. The upper 64-bits are
3091     // undefined.
3092     Value *Op0 = II->getArgOperand(0);
3093     Value *Op1 = II->getArgOperand(1);
3094     unsigned VWidth0 = Op0->getType()->getVectorNumElements();
3095     unsigned VWidth1 = Op1->getType()->getVectorNumElements();
3096     assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
3097            Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth0 == 2 &&
3098            VWidth1 == 2 && "Unexpected operand sizes");
3099 
3100     // See if we're dealing with constant values.
3101     ConstantInt *CILength = dyn_cast<ConstantInt>(II->getArgOperand(2));
3102     ConstantInt *CIIndex = dyn_cast<ConstantInt>(II->getArgOperand(3));
3103 
3104     // Attempt to simplify to a constant or shuffle vector.
3105     if (CILength && CIIndex) {
3106       APInt Len = CILength->getValue().zextOrTrunc(6);
3107       APInt Idx = CIIndex->getValue().zextOrTrunc(6);
3108       if (Value *V = simplifyX86insertq(*II, Op0, Op1, Len, Idx, Builder))
3109         return replaceInstUsesWith(*II, V);
3110     }
3111 
3112     // INSERTQI only uses the lowest 64-bits of the first two 128-bit vector
3113     // operands.
3114     bool MadeChange = false;
3115     if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth0, 1)) {
3116       II->setArgOperand(0, V);
3117       MadeChange = true;
3118     }
3119     if (Value *V = SimplifyDemandedVectorEltsLow(Op1, VWidth1, 1)) {
3120       II->setArgOperand(1, V);
3121       MadeChange = true;
3122     }
3123     if (MadeChange)
3124       return II;
3125     break;
3126   }
3127 
3128   case Intrinsic::x86_sse41_pblendvb:
3129   case Intrinsic::x86_sse41_blendvps:
3130   case Intrinsic::x86_sse41_blendvpd:
3131   case Intrinsic::x86_avx_blendv_ps_256:
3132   case Intrinsic::x86_avx_blendv_pd_256:
3133   case Intrinsic::x86_avx2_pblendvb: {
3134     // fold (blend A, A, Mask) -> A
3135     Value *Op0 = II->getArgOperand(0);
3136     Value *Op1 = II->getArgOperand(1);
3137     Value *Mask = II->getArgOperand(2);
3138     if (Op0 == Op1)
3139       return replaceInstUsesWith(CI, Op0);
3140 
3141     // Zero Mask - select 1st argument.
3142     if (isa<ConstantAggregateZero>(Mask))
3143       return replaceInstUsesWith(CI, Op0);
3144 
3145     // Constant Mask - select 1st/2nd argument lane based on top bit of mask.
3146     if (auto *ConstantMask = dyn_cast<ConstantDataVector>(Mask)) {
3147       Constant *NewSelector = getNegativeIsTrueBoolVec(ConstantMask);
3148       return SelectInst::Create(NewSelector, Op1, Op0, "blendv");
3149     }
3150 
3151     // Convert to a vector select if we can bypass casts and find a boolean
3152     // vector condition value.
3153     Value *BoolVec;
3154     Mask = peekThroughBitcast(Mask);
3155     if (match(Mask, m_SExt(m_Value(BoolVec))) &&
3156         BoolVec->getType()->isVectorTy() &&
3157         BoolVec->getType()->getScalarSizeInBits() == 1) {
3158       assert(Mask->getType()->getPrimitiveSizeInBits() ==
3159              II->getType()->getPrimitiveSizeInBits() &&
3160              "Not expecting mask and operands with different sizes");
3161 
3162       unsigned NumMaskElts = Mask->getType()->getVectorNumElements();
3163       unsigned NumOperandElts = II->getType()->getVectorNumElements();
3164       if (NumMaskElts == NumOperandElts)
3165         return SelectInst::Create(BoolVec, Op1, Op0);
3166 
3167       // If the mask has less elements than the operands, each mask bit maps to
3168       // multiple elements of the operands. Bitcast back and forth.
3169       if (NumMaskElts < NumOperandElts) {
3170         Value *CastOp0 = Builder.CreateBitCast(Op0, Mask->getType());
3171         Value *CastOp1 = Builder.CreateBitCast(Op1, Mask->getType());
3172         Value *Sel = Builder.CreateSelect(BoolVec, CastOp1, CastOp0);
3173         return new BitCastInst(Sel, II->getType());
3174       }
3175     }
3176 
3177     break;
3178   }
3179 
3180   case Intrinsic::x86_ssse3_pshuf_b_128:
3181   case Intrinsic::x86_avx2_pshuf_b:
3182   case Intrinsic::x86_avx512_pshuf_b_512:
3183     if (Value *V = simplifyX86pshufb(*II, Builder))
3184       return replaceInstUsesWith(*II, V);
3185     break;
3186 
3187   case Intrinsic::x86_avx_vpermilvar_ps:
3188   case Intrinsic::x86_avx_vpermilvar_ps_256:
3189   case Intrinsic::x86_avx512_vpermilvar_ps_512:
3190   case Intrinsic::x86_avx_vpermilvar_pd:
3191   case Intrinsic::x86_avx_vpermilvar_pd_256:
3192   case Intrinsic::x86_avx512_vpermilvar_pd_512:
3193     if (Value *V = simplifyX86vpermilvar(*II, Builder))
3194       return replaceInstUsesWith(*II, V);
3195     break;
3196 
3197   case Intrinsic::x86_avx2_permd:
3198   case Intrinsic::x86_avx2_permps:
3199   case Intrinsic::x86_avx512_permvar_df_256:
3200   case Intrinsic::x86_avx512_permvar_df_512:
3201   case Intrinsic::x86_avx512_permvar_di_256:
3202   case Intrinsic::x86_avx512_permvar_di_512:
3203   case Intrinsic::x86_avx512_permvar_hi_128:
3204   case Intrinsic::x86_avx512_permvar_hi_256:
3205   case Intrinsic::x86_avx512_permvar_hi_512:
3206   case Intrinsic::x86_avx512_permvar_qi_128:
3207   case Intrinsic::x86_avx512_permvar_qi_256:
3208   case Intrinsic::x86_avx512_permvar_qi_512:
3209   case Intrinsic::x86_avx512_permvar_sf_512:
3210   case Intrinsic::x86_avx512_permvar_si_512:
3211     if (Value *V = simplifyX86vpermv(*II, Builder))
3212       return replaceInstUsesWith(*II, V);
3213     break;
3214 
3215   case Intrinsic::x86_avx_maskload_ps:
3216   case Intrinsic::x86_avx_maskload_pd:
3217   case Intrinsic::x86_avx_maskload_ps_256:
3218   case Intrinsic::x86_avx_maskload_pd_256:
3219   case Intrinsic::x86_avx2_maskload_d:
3220   case Intrinsic::x86_avx2_maskload_q:
3221   case Intrinsic::x86_avx2_maskload_d_256:
3222   case Intrinsic::x86_avx2_maskload_q_256:
3223     if (Instruction *I = simplifyX86MaskedLoad(*II, *this))
3224       return I;
3225     break;
3226 
3227   case Intrinsic::x86_sse2_maskmov_dqu:
3228   case Intrinsic::x86_avx_maskstore_ps:
3229   case Intrinsic::x86_avx_maskstore_pd:
3230   case Intrinsic::x86_avx_maskstore_ps_256:
3231   case Intrinsic::x86_avx_maskstore_pd_256:
3232   case Intrinsic::x86_avx2_maskstore_d:
3233   case Intrinsic::x86_avx2_maskstore_q:
3234   case Intrinsic::x86_avx2_maskstore_d_256:
3235   case Intrinsic::x86_avx2_maskstore_q_256:
3236     if (simplifyX86MaskedStore(*II, *this))
3237       return nullptr;
3238     break;
3239 
3240   case Intrinsic::x86_addcarry_32:
3241   case Intrinsic::x86_addcarry_64:
3242     if (Value *V = simplifyX86addcarry(*II, Builder))
3243       return replaceInstUsesWith(*II, V);
3244     break;
3245 
3246   case Intrinsic::ppc_altivec_vperm:
3247     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
3248     // Note that ppc_altivec_vperm has a big-endian bias, so when creating
3249     // a vectorshuffle for little endian, we must undo the transformation
3250     // performed on vec_perm in altivec.h.  That is, we must complement
3251     // the permutation mask with respect to 31 and reverse the order of
3252     // V1 and V2.
3253     if (Constant *Mask = dyn_cast<Constant>(II->getArgOperand(2))) {
3254       assert(Mask->getType()->getVectorNumElements() == 16 &&
3255              "Bad type for intrinsic!");
3256 
3257       // Check that all of the elements are integer constants or undefs.
3258       bool AllEltsOk = true;
3259       for (unsigned i = 0; i != 16; ++i) {
3260         Constant *Elt = Mask->getAggregateElement(i);
3261         if (!Elt || !(isa<ConstantInt>(Elt) || isa<UndefValue>(Elt))) {
3262           AllEltsOk = false;
3263           break;
3264         }
3265       }
3266 
3267       if (AllEltsOk) {
3268         // Cast the input vectors to byte vectors.
3269         Value *Op0 = Builder.CreateBitCast(II->getArgOperand(0),
3270                                            Mask->getType());
3271         Value *Op1 = Builder.CreateBitCast(II->getArgOperand(1),
3272                                            Mask->getType());
3273         Value *Result = UndefValue::get(Op0->getType());
3274 
3275         // Only extract each element once.
3276         Value *ExtractedElts[32];
3277         memset(ExtractedElts, 0, sizeof(ExtractedElts));
3278 
3279         for (unsigned i = 0; i != 16; ++i) {
3280           if (isa<UndefValue>(Mask->getAggregateElement(i)))
3281             continue;
3282           unsigned Idx =
3283             cast<ConstantInt>(Mask->getAggregateElement(i))->getZExtValue();
3284           Idx &= 31;  // Match the hardware behavior.
3285           if (DL.isLittleEndian())
3286             Idx = 31 - Idx;
3287 
3288           if (!ExtractedElts[Idx]) {
3289             Value *Op0ToUse = (DL.isLittleEndian()) ? Op1 : Op0;
3290             Value *Op1ToUse = (DL.isLittleEndian()) ? Op0 : Op1;
3291             ExtractedElts[Idx] =
3292               Builder.CreateExtractElement(Idx < 16 ? Op0ToUse : Op1ToUse,
3293                                            Builder.getInt32(Idx&15));
3294           }
3295 
3296           // Insert this value into the result vector.
3297           Result = Builder.CreateInsertElement(Result, ExtractedElts[Idx],
3298                                                Builder.getInt32(i));
3299         }
3300         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
3301       }
3302     }
3303     break;
3304 
3305   case Intrinsic::arm_neon_vld1: {
3306     unsigned MemAlign = getKnownAlignment(II->getArgOperand(0),
3307                                           DL, II, &AC, &DT);
3308     if (Value *V = simplifyNeonVld1(*II, MemAlign, Builder))
3309       return replaceInstUsesWith(*II, V);
3310     break;
3311   }
3312 
3313   case Intrinsic::arm_neon_vld2:
3314   case Intrinsic::arm_neon_vld3:
3315   case Intrinsic::arm_neon_vld4:
3316   case Intrinsic::arm_neon_vld2lane:
3317   case Intrinsic::arm_neon_vld3lane:
3318   case Intrinsic::arm_neon_vld4lane:
3319   case Intrinsic::arm_neon_vst1:
3320   case Intrinsic::arm_neon_vst2:
3321   case Intrinsic::arm_neon_vst3:
3322   case Intrinsic::arm_neon_vst4:
3323   case Intrinsic::arm_neon_vst2lane:
3324   case Intrinsic::arm_neon_vst3lane:
3325   case Intrinsic::arm_neon_vst4lane: {
3326     unsigned MemAlign =
3327         getKnownAlignment(II->getArgOperand(0), DL, II, &AC, &DT);
3328     unsigned AlignArg = II->getNumArgOperands() - 1;
3329     ConstantInt *IntrAlign = dyn_cast<ConstantInt>(II->getArgOperand(AlignArg));
3330     if (IntrAlign && IntrAlign->getZExtValue() < MemAlign) {
3331       II->setArgOperand(AlignArg,
3332                         ConstantInt::get(Type::getInt32Ty(II->getContext()),
3333                                          MemAlign, false));
3334       return II;
3335     }
3336     break;
3337   }
3338 
3339   case Intrinsic::arm_neon_vtbl1:
3340   case Intrinsic::aarch64_neon_tbl1:
3341     if (Value *V = simplifyNeonTbl1(*II, Builder))
3342       return replaceInstUsesWith(*II, V);
3343     break;
3344 
3345   case Intrinsic::arm_neon_vmulls:
3346   case Intrinsic::arm_neon_vmullu:
3347   case Intrinsic::aarch64_neon_smull:
3348   case Intrinsic::aarch64_neon_umull: {
3349     Value *Arg0 = II->getArgOperand(0);
3350     Value *Arg1 = II->getArgOperand(1);
3351 
3352     // Handle mul by zero first:
3353     if (isa<ConstantAggregateZero>(Arg0) || isa<ConstantAggregateZero>(Arg1)) {
3354       return replaceInstUsesWith(CI, ConstantAggregateZero::get(II->getType()));
3355     }
3356 
3357     // Check for constant LHS & RHS - in this case we just simplify.
3358     bool Zext = (IID == Intrinsic::arm_neon_vmullu ||
3359                  IID == Intrinsic::aarch64_neon_umull);
3360     VectorType *NewVT = cast<VectorType>(II->getType());
3361     if (Constant *CV0 = dyn_cast<Constant>(Arg0)) {
3362       if (Constant *CV1 = dyn_cast<Constant>(Arg1)) {
3363         CV0 = ConstantExpr::getIntegerCast(CV0, NewVT, /*isSigned=*/!Zext);
3364         CV1 = ConstantExpr::getIntegerCast(CV1, NewVT, /*isSigned=*/!Zext);
3365 
3366         return replaceInstUsesWith(CI, ConstantExpr::getMul(CV0, CV1));
3367       }
3368 
3369       // Couldn't simplify - canonicalize constant to the RHS.
3370       std::swap(Arg0, Arg1);
3371     }
3372 
3373     // Handle mul by one:
3374     if (Constant *CV1 = dyn_cast<Constant>(Arg1))
3375       if (ConstantInt *Splat =
3376               dyn_cast_or_null<ConstantInt>(CV1->getSplatValue()))
3377         if (Splat->isOne())
3378           return CastInst::CreateIntegerCast(Arg0, II->getType(),
3379                                              /*isSigned=*/!Zext);
3380 
3381     break;
3382   }
3383   case Intrinsic::arm_neon_aesd:
3384   case Intrinsic::arm_neon_aese:
3385   case Intrinsic::aarch64_crypto_aesd:
3386   case Intrinsic::aarch64_crypto_aese: {
3387     Value *DataArg = II->getArgOperand(0);
3388     Value *KeyArg  = II->getArgOperand(1);
3389 
3390     // Try to use the builtin XOR in AESE and AESD to eliminate a prior XOR
3391     Value *Data, *Key;
3392     if (match(KeyArg, m_ZeroInt()) &&
3393         match(DataArg, m_Xor(m_Value(Data), m_Value(Key)))) {
3394       II->setArgOperand(0, Data);
3395       II->setArgOperand(1, Key);
3396       return II;
3397     }
3398     break;
3399   }
3400   case Intrinsic::arm_mve_pred_i2v: {
3401     Value *Arg = II->getArgOperand(0);
3402     Value *ArgArg;
3403     if (match(Arg, m_Intrinsic<Intrinsic::arm_mve_pred_v2i>(m_Value(ArgArg))) &&
3404         II->getType() == ArgArg->getType())
3405       return replaceInstUsesWith(*II, ArgArg);
3406     Constant *XorMask;
3407     if (match(Arg,
3408               m_Xor(m_Intrinsic<Intrinsic::arm_mve_pred_v2i>(m_Value(ArgArg)),
3409                     m_Constant(XorMask))) &&
3410         II->getType() == ArgArg->getType()) {
3411       if (auto *CI = dyn_cast<ConstantInt>(XorMask)) {
3412         if (CI->getValue().trunc(16).isAllOnesValue()) {
3413           auto TrueVector = Builder.CreateVectorSplat(
3414               II->getType()->getVectorNumElements(), Builder.getTrue());
3415           return BinaryOperator::Create(Instruction::Xor, ArgArg, TrueVector);
3416         }
3417       }
3418     }
3419     KnownBits ScalarKnown(32);
3420     if (SimplifyDemandedBits(II, 0, APInt::getLowBitsSet(32, 16),
3421                              ScalarKnown, 0))
3422       return II;
3423     break;
3424   }
3425   case Intrinsic::arm_mve_pred_v2i: {
3426     Value *Arg = II->getArgOperand(0);
3427     Value *ArgArg;
3428     if (match(Arg, m_Intrinsic<Intrinsic::arm_mve_pred_i2v>(m_Value(ArgArg))))
3429       return replaceInstUsesWith(*II, ArgArg);
3430     if (!II->getMetadata(LLVMContext::MD_range)) {
3431       Type *IntTy32 = Type::getInt32Ty(II->getContext());
3432       Metadata *M[] = {
3433         ConstantAsMetadata::get(ConstantInt::get(IntTy32, 0)),
3434         ConstantAsMetadata::get(ConstantInt::get(IntTy32, 0xFFFF))
3435       };
3436       II->setMetadata(LLVMContext::MD_range, MDNode::get(II->getContext(), M));
3437       return II;
3438     }
3439     break;
3440   }
3441   case Intrinsic::arm_mve_vadc:
3442   case Intrinsic::arm_mve_vadc_predicated: {
3443     unsigned CarryOp =
3444         (II->getIntrinsicID() == Intrinsic::arm_mve_vadc_predicated) ? 3 : 2;
3445     assert(II->getArgOperand(CarryOp)->getType()->getScalarSizeInBits() == 32 &&
3446            "Bad type for intrinsic!");
3447 
3448     KnownBits CarryKnown(32);
3449     if (SimplifyDemandedBits(II, CarryOp, APInt::getOneBitSet(32, 29),
3450                              CarryKnown))
3451       return II;
3452     break;
3453   }
3454   case Intrinsic::amdgcn_rcp: {
3455     Value *Src = II->getArgOperand(0);
3456 
3457     // TODO: Move to ConstantFolding/InstSimplify?
3458     if (isa<UndefValue>(Src))
3459       return replaceInstUsesWith(CI, Src);
3460 
3461     if (const ConstantFP *C = dyn_cast<ConstantFP>(Src)) {
3462       const APFloat &ArgVal = C->getValueAPF();
3463       APFloat Val(ArgVal.getSemantics(), 1);
3464       APFloat::opStatus Status = Val.divide(ArgVal,
3465                                             APFloat::rmNearestTiesToEven);
3466       // Only do this if it was exact and therefore not dependent on the
3467       // rounding mode.
3468       if (Status == APFloat::opOK)
3469         return replaceInstUsesWith(CI, ConstantFP::get(II->getContext(), Val));
3470     }
3471 
3472     break;
3473   }
3474   case Intrinsic::amdgcn_rsq: {
3475     Value *Src = II->getArgOperand(0);
3476 
3477     // TODO: Move to ConstantFolding/InstSimplify?
3478     if (isa<UndefValue>(Src))
3479       return replaceInstUsesWith(CI, Src);
3480     break;
3481   }
3482   case Intrinsic::amdgcn_frexp_mant:
3483   case Intrinsic::amdgcn_frexp_exp: {
3484     Value *Src = II->getArgOperand(0);
3485     if (const ConstantFP *C = dyn_cast<ConstantFP>(Src)) {
3486       int Exp;
3487       APFloat Significand = frexp(C->getValueAPF(), Exp,
3488                                   APFloat::rmNearestTiesToEven);
3489 
3490       if (IID == Intrinsic::amdgcn_frexp_mant) {
3491         return replaceInstUsesWith(CI, ConstantFP::get(II->getContext(),
3492                                                        Significand));
3493       }
3494 
3495       // Match instruction special case behavior.
3496       if (Exp == APFloat::IEK_NaN || Exp == APFloat::IEK_Inf)
3497         Exp = 0;
3498 
3499       return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), Exp));
3500     }
3501 
3502     if (isa<UndefValue>(Src))
3503       return replaceInstUsesWith(CI, UndefValue::get(II->getType()));
3504 
3505     break;
3506   }
3507   case Intrinsic::amdgcn_class: {
3508     enum  {
3509       S_NAN = 1 << 0,        // Signaling NaN
3510       Q_NAN = 1 << 1,        // Quiet NaN
3511       N_INFINITY = 1 << 2,   // Negative infinity
3512       N_NORMAL = 1 << 3,     // Negative normal
3513       N_SUBNORMAL = 1 << 4,  // Negative subnormal
3514       N_ZERO = 1 << 5,       // Negative zero
3515       P_ZERO = 1 << 6,       // Positive zero
3516       P_SUBNORMAL = 1 << 7,  // Positive subnormal
3517       P_NORMAL = 1 << 8,     // Positive normal
3518       P_INFINITY = 1 << 9    // Positive infinity
3519     };
3520 
3521     const uint32_t FullMask = S_NAN | Q_NAN | N_INFINITY | N_NORMAL |
3522       N_SUBNORMAL | N_ZERO | P_ZERO | P_SUBNORMAL | P_NORMAL | P_INFINITY;
3523 
3524     Value *Src0 = II->getArgOperand(0);
3525     Value *Src1 = II->getArgOperand(1);
3526     const ConstantInt *CMask = dyn_cast<ConstantInt>(Src1);
3527     if (!CMask) {
3528       if (isa<UndefValue>(Src0))
3529         return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
3530 
3531       if (isa<UndefValue>(Src1))
3532         return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), false));
3533       break;
3534     }
3535 
3536     uint32_t Mask = CMask->getZExtValue();
3537 
3538     // If all tests are made, it doesn't matter what the value is.
3539     if ((Mask & FullMask) == FullMask)
3540       return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), true));
3541 
3542     if ((Mask & FullMask) == 0)
3543       return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), false));
3544 
3545     if (Mask == (S_NAN | Q_NAN)) {
3546       // Equivalent of isnan. Replace with standard fcmp.
3547       Value *FCmp = Builder.CreateFCmpUNO(Src0, Src0);
3548       FCmp->takeName(II);
3549       return replaceInstUsesWith(*II, FCmp);
3550     }
3551 
3552     if (Mask == (N_ZERO | P_ZERO)) {
3553       // Equivalent of == 0.
3554       Value *FCmp = Builder.CreateFCmpOEQ(
3555         Src0, ConstantFP::get(Src0->getType(), 0.0));
3556 
3557       FCmp->takeName(II);
3558       return replaceInstUsesWith(*II, FCmp);
3559     }
3560 
3561     // fp_class (nnan x), qnan|snan|other -> fp_class (nnan x), other
3562     if (((Mask & S_NAN) || (Mask & Q_NAN)) && isKnownNeverNaN(Src0, &TLI)) {
3563       II->setArgOperand(1, ConstantInt::get(Src1->getType(),
3564                                             Mask & ~(S_NAN | Q_NAN)));
3565       return II;
3566     }
3567 
3568     const ConstantFP *CVal = dyn_cast<ConstantFP>(Src0);
3569     if (!CVal) {
3570       if (isa<UndefValue>(Src0))
3571         return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
3572 
3573       // Clamp mask to used bits
3574       if ((Mask & FullMask) != Mask) {
3575         CallInst *NewCall = Builder.CreateCall(II->getCalledFunction(),
3576           { Src0, ConstantInt::get(Src1->getType(), Mask & FullMask) }
3577         );
3578 
3579         NewCall->takeName(II);
3580         return replaceInstUsesWith(*II, NewCall);
3581       }
3582 
3583       break;
3584     }
3585 
3586     const APFloat &Val = CVal->getValueAPF();
3587 
3588     bool Result =
3589       ((Mask & S_NAN) && Val.isNaN() && Val.isSignaling()) ||
3590       ((Mask & Q_NAN) && Val.isNaN() && !Val.isSignaling()) ||
3591       ((Mask & N_INFINITY) && Val.isInfinity() && Val.isNegative()) ||
3592       ((Mask & N_NORMAL) && Val.isNormal() && Val.isNegative()) ||
3593       ((Mask & N_SUBNORMAL) && Val.isDenormal() && Val.isNegative()) ||
3594       ((Mask & N_ZERO) && Val.isZero() && Val.isNegative()) ||
3595       ((Mask & P_ZERO) && Val.isZero() && !Val.isNegative()) ||
3596       ((Mask & P_SUBNORMAL) && Val.isDenormal() && !Val.isNegative()) ||
3597       ((Mask & P_NORMAL) && Val.isNormal() && !Val.isNegative()) ||
3598       ((Mask & P_INFINITY) && Val.isInfinity() && !Val.isNegative());
3599 
3600     return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), Result));
3601   }
3602   case Intrinsic::amdgcn_cvt_pkrtz: {
3603     Value *Src0 = II->getArgOperand(0);
3604     Value *Src1 = II->getArgOperand(1);
3605     if (const ConstantFP *C0 = dyn_cast<ConstantFP>(Src0)) {
3606       if (const ConstantFP *C1 = dyn_cast<ConstantFP>(Src1)) {
3607         const fltSemantics &HalfSem
3608           = II->getType()->getScalarType()->getFltSemantics();
3609         bool LosesInfo;
3610         APFloat Val0 = C0->getValueAPF();
3611         APFloat Val1 = C1->getValueAPF();
3612         Val0.convert(HalfSem, APFloat::rmTowardZero, &LosesInfo);
3613         Val1.convert(HalfSem, APFloat::rmTowardZero, &LosesInfo);
3614 
3615         Constant *Folded = ConstantVector::get({
3616             ConstantFP::get(II->getContext(), Val0),
3617             ConstantFP::get(II->getContext(), Val1) });
3618         return replaceInstUsesWith(*II, Folded);
3619       }
3620     }
3621 
3622     if (isa<UndefValue>(Src0) && isa<UndefValue>(Src1))
3623       return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
3624 
3625     break;
3626   }
3627   case Intrinsic::amdgcn_cvt_pknorm_i16:
3628   case Intrinsic::amdgcn_cvt_pknorm_u16:
3629   case Intrinsic::amdgcn_cvt_pk_i16:
3630   case Intrinsic::amdgcn_cvt_pk_u16: {
3631     Value *Src0 = II->getArgOperand(0);
3632     Value *Src1 = II->getArgOperand(1);
3633 
3634     if (isa<UndefValue>(Src0) && isa<UndefValue>(Src1))
3635       return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
3636 
3637     break;
3638   }
3639   case Intrinsic::amdgcn_ubfe:
3640   case Intrinsic::amdgcn_sbfe: {
3641     // Decompose simple cases into standard shifts.
3642     Value *Src = II->getArgOperand(0);
3643     if (isa<UndefValue>(Src))
3644       return replaceInstUsesWith(*II, Src);
3645 
3646     unsigned Width;
3647     Type *Ty = II->getType();
3648     unsigned IntSize = Ty->getIntegerBitWidth();
3649 
3650     ConstantInt *CWidth = dyn_cast<ConstantInt>(II->getArgOperand(2));
3651     if (CWidth) {
3652       Width = CWidth->getZExtValue();
3653       if ((Width & (IntSize - 1)) == 0)
3654         return replaceInstUsesWith(*II, ConstantInt::getNullValue(Ty));
3655 
3656       if (Width >= IntSize) {
3657         // Hardware ignores high bits, so remove those.
3658         II->setArgOperand(2, ConstantInt::get(CWidth->getType(),
3659                                               Width & (IntSize - 1)));
3660         return II;
3661       }
3662     }
3663 
3664     unsigned Offset;
3665     ConstantInt *COffset = dyn_cast<ConstantInt>(II->getArgOperand(1));
3666     if (COffset) {
3667       Offset = COffset->getZExtValue();
3668       if (Offset >= IntSize) {
3669         II->setArgOperand(1, ConstantInt::get(COffset->getType(),
3670                                               Offset & (IntSize - 1)));
3671         return II;
3672       }
3673     }
3674 
3675     bool Signed = IID == Intrinsic::amdgcn_sbfe;
3676 
3677     if (!CWidth || !COffset)
3678       break;
3679 
3680     // The case of Width == 0 is handled above, which makes this tranformation
3681     // safe.  If Width == 0, then the ashr and lshr instructions become poison
3682     // value since the shift amount would be equal to the bit size.
3683     assert(Width != 0);
3684 
3685     // TODO: This allows folding to undef when the hardware has specific
3686     // behavior?
3687     if (Offset + Width < IntSize) {
3688       Value *Shl = Builder.CreateShl(Src, IntSize - Offset - Width);
3689       Value *RightShift = Signed ? Builder.CreateAShr(Shl, IntSize - Width)
3690                                  : Builder.CreateLShr(Shl, IntSize - Width);
3691       RightShift->takeName(II);
3692       return replaceInstUsesWith(*II, RightShift);
3693     }
3694 
3695     Value *RightShift = Signed ? Builder.CreateAShr(Src, Offset)
3696                                : Builder.CreateLShr(Src, Offset);
3697 
3698     RightShift->takeName(II);
3699     return replaceInstUsesWith(*II, RightShift);
3700   }
3701   case Intrinsic::amdgcn_exp:
3702   case Intrinsic::amdgcn_exp_compr: {
3703     ConstantInt *En = cast<ConstantInt>(II->getArgOperand(1));
3704     unsigned EnBits = En->getZExtValue();
3705     if (EnBits == 0xf)
3706       break; // All inputs enabled.
3707 
3708     bool IsCompr = IID == Intrinsic::amdgcn_exp_compr;
3709     bool Changed = false;
3710     for (int I = 0; I < (IsCompr ? 2 : 4); ++I) {
3711       if ((!IsCompr && (EnBits & (1 << I)) == 0) ||
3712           (IsCompr && ((EnBits & (0x3 << (2 * I))) == 0))) {
3713         Value *Src = II->getArgOperand(I + 2);
3714         if (!isa<UndefValue>(Src)) {
3715           II->setArgOperand(I + 2, UndefValue::get(Src->getType()));
3716           Changed = true;
3717         }
3718       }
3719     }
3720 
3721     if (Changed)
3722       return II;
3723 
3724     break;
3725   }
3726   case Intrinsic::amdgcn_fmed3: {
3727     // Note this does not preserve proper sNaN behavior if IEEE-mode is enabled
3728     // for the shader.
3729 
3730     Value *Src0 = II->getArgOperand(0);
3731     Value *Src1 = II->getArgOperand(1);
3732     Value *Src2 = II->getArgOperand(2);
3733 
3734     // Checking for NaN before canonicalization provides better fidelity when
3735     // mapping other operations onto fmed3 since the order of operands is
3736     // unchanged.
3737     CallInst *NewCall = nullptr;
3738     if (match(Src0, m_NaN()) || isa<UndefValue>(Src0)) {
3739       NewCall = Builder.CreateMinNum(Src1, Src2);
3740     } else if (match(Src1, m_NaN()) || isa<UndefValue>(Src1)) {
3741       NewCall = Builder.CreateMinNum(Src0, Src2);
3742     } else if (match(Src2, m_NaN()) || isa<UndefValue>(Src2)) {
3743       NewCall = Builder.CreateMaxNum(Src0, Src1);
3744     }
3745 
3746     if (NewCall) {
3747       NewCall->copyFastMathFlags(II);
3748       NewCall->takeName(II);
3749       return replaceInstUsesWith(*II, NewCall);
3750     }
3751 
3752     bool Swap = false;
3753     // Canonicalize constants to RHS operands.
3754     //
3755     // fmed3(c0, x, c1) -> fmed3(x, c0, c1)
3756     if (isa<Constant>(Src0) && !isa<Constant>(Src1)) {
3757       std::swap(Src0, Src1);
3758       Swap = true;
3759     }
3760 
3761     if (isa<Constant>(Src1) && !isa<Constant>(Src2)) {
3762       std::swap(Src1, Src2);
3763       Swap = true;
3764     }
3765 
3766     if (isa<Constant>(Src0) && !isa<Constant>(Src1)) {
3767       std::swap(Src0, Src1);
3768       Swap = true;
3769     }
3770 
3771     if (Swap) {
3772       II->setArgOperand(0, Src0);
3773       II->setArgOperand(1, Src1);
3774       II->setArgOperand(2, Src2);
3775       return II;
3776     }
3777 
3778     if (const ConstantFP *C0 = dyn_cast<ConstantFP>(Src0)) {
3779       if (const ConstantFP *C1 = dyn_cast<ConstantFP>(Src1)) {
3780         if (const ConstantFP *C2 = dyn_cast<ConstantFP>(Src2)) {
3781           APFloat Result = fmed3AMDGCN(C0->getValueAPF(), C1->getValueAPF(),
3782                                        C2->getValueAPF());
3783           return replaceInstUsesWith(*II,
3784             ConstantFP::get(Builder.getContext(), Result));
3785         }
3786       }
3787     }
3788 
3789     break;
3790   }
3791   case Intrinsic::amdgcn_icmp:
3792   case Intrinsic::amdgcn_fcmp: {
3793     const ConstantInt *CC = cast<ConstantInt>(II->getArgOperand(2));
3794     // Guard against invalid arguments.
3795     int64_t CCVal = CC->getZExtValue();
3796     bool IsInteger = IID == Intrinsic::amdgcn_icmp;
3797     if ((IsInteger && (CCVal < CmpInst::FIRST_ICMP_PREDICATE ||
3798                        CCVal > CmpInst::LAST_ICMP_PREDICATE)) ||
3799         (!IsInteger && (CCVal < CmpInst::FIRST_FCMP_PREDICATE ||
3800                         CCVal > CmpInst::LAST_FCMP_PREDICATE)))
3801       break;
3802 
3803     Value *Src0 = II->getArgOperand(0);
3804     Value *Src1 = II->getArgOperand(1);
3805 
3806     if (auto *CSrc0 = dyn_cast<Constant>(Src0)) {
3807       if (auto *CSrc1 = dyn_cast<Constant>(Src1)) {
3808         Constant *CCmp = ConstantExpr::getCompare(CCVal, CSrc0, CSrc1);
3809         if (CCmp->isNullValue()) {
3810           return replaceInstUsesWith(
3811               *II, ConstantExpr::getSExt(CCmp, II->getType()));
3812         }
3813 
3814         // The result of V_ICMP/V_FCMP assembly instructions (which this
3815         // intrinsic exposes) is one bit per thread, masked with the EXEC
3816         // register (which contains the bitmask of live threads). So a
3817         // comparison that always returns true is the same as a read of the
3818         // EXEC register.
3819         Function *NewF = Intrinsic::getDeclaration(
3820             II->getModule(), Intrinsic::read_register, II->getType());
3821         Metadata *MDArgs[] = {MDString::get(II->getContext(), "exec")};
3822         MDNode *MD = MDNode::get(II->getContext(), MDArgs);
3823         Value *Args[] = {MetadataAsValue::get(II->getContext(), MD)};
3824         CallInst *NewCall = Builder.CreateCall(NewF, Args);
3825         NewCall->addAttribute(AttributeList::FunctionIndex,
3826                               Attribute::Convergent);
3827         NewCall->takeName(II);
3828         return replaceInstUsesWith(*II, NewCall);
3829       }
3830 
3831       // Canonicalize constants to RHS.
3832       CmpInst::Predicate SwapPred
3833         = CmpInst::getSwappedPredicate(static_cast<CmpInst::Predicate>(CCVal));
3834       II->setArgOperand(0, Src1);
3835       II->setArgOperand(1, Src0);
3836       II->setArgOperand(2, ConstantInt::get(CC->getType(),
3837                                             static_cast<int>(SwapPred)));
3838       return II;
3839     }
3840 
3841     if (CCVal != CmpInst::ICMP_EQ && CCVal != CmpInst::ICMP_NE)
3842       break;
3843 
3844     // Canonicalize compare eq with true value to compare != 0
3845     // llvm.amdgcn.icmp(zext (i1 x), 1, eq)
3846     //   -> llvm.amdgcn.icmp(zext (i1 x), 0, ne)
3847     // llvm.amdgcn.icmp(sext (i1 x), -1, eq)
3848     //   -> llvm.amdgcn.icmp(sext (i1 x), 0, ne)
3849     Value *ExtSrc;
3850     if (CCVal == CmpInst::ICMP_EQ &&
3851         ((match(Src1, m_One()) && match(Src0, m_ZExt(m_Value(ExtSrc)))) ||
3852          (match(Src1, m_AllOnes()) && match(Src0, m_SExt(m_Value(ExtSrc))))) &&
3853         ExtSrc->getType()->isIntegerTy(1)) {
3854       II->setArgOperand(1, ConstantInt::getNullValue(Src1->getType()));
3855       II->setArgOperand(2, ConstantInt::get(CC->getType(), CmpInst::ICMP_NE));
3856       return II;
3857     }
3858 
3859     CmpInst::Predicate SrcPred;
3860     Value *SrcLHS;
3861     Value *SrcRHS;
3862 
3863     // Fold compare eq/ne with 0 from a compare result as the predicate to the
3864     // intrinsic. The typical use is a wave vote function in the library, which
3865     // will be fed from a user code condition compared with 0. Fold in the
3866     // redundant compare.
3867 
3868     // llvm.amdgcn.icmp([sz]ext ([if]cmp pred a, b), 0, ne)
3869     //   -> llvm.amdgcn.[if]cmp(a, b, pred)
3870     //
3871     // llvm.amdgcn.icmp([sz]ext ([if]cmp pred a, b), 0, eq)
3872     //   -> llvm.amdgcn.[if]cmp(a, b, inv pred)
3873     if (match(Src1, m_Zero()) &&
3874         match(Src0,
3875               m_ZExtOrSExt(m_Cmp(SrcPred, m_Value(SrcLHS), m_Value(SrcRHS))))) {
3876       if (CCVal == CmpInst::ICMP_EQ)
3877         SrcPred = CmpInst::getInversePredicate(SrcPred);
3878 
3879       Intrinsic::ID NewIID = CmpInst::isFPPredicate(SrcPred) ?
3880         Intrinsic::amdgcn_fcmp : Intrinsic::amdgcn_icmp;
3881 
3882       Type *Ty = SrcLHS->getType();
3883       if (auto *CmpType = dyn_cast<IntegerType>(Ty)) {
3884         // Promote to next legal integer type.
3885         unsigned Width = CmpType->getBitWidth();
3886         unsigned NewWidth = Width;
3887 
3888         // Don't do anything for i1 comparisons.
3889         if (Width == 1)
3890           break;
3891 
3892         if (Width <= 16)
3893           NewWidth = 16;
3894         else if (Width <= 32)
3895           NewWidth = 32;
3896         else if (Width <= 64)
3897           NewWidth = 64;
3898         else if (Width > 64)
3899           break; // Can't handle this.
3900 
3901         if (Width != NewWidth) {
3902           IntegerType *CmpTy = Builder.getIntNTy(NewWidth);
3903           if (CmpInst::isSigned(SrcPred)) {
3904             SrcLHS = Builder.CreateSExt(SrcLHS, CmpTy);
3905             SrcRHS = Builder.CreateSExt(SrcRHS, CmpTy);
3906           } else {
3907             SrcLHS = Builder.CreateZExt(SrcLHS, CmpTy);
3908             SrcRHS = Builder.CreateZExt(SrcRHS, CmpTy);
3909           }
3910         }
3911       } else if (!Ty->isFloatTy() && !Ty->isDoubleTy() && !Ty->isHalfTy())
3912         break;
3913 
3914       Function *NewF =
3915           Intrinsic::getDeclaration(II->getModule(), NewIID,
3916                                     { II->getType(),
3917                                       SrcLHS->getType() });
3918       Value *Args[] = { SrcLHS, SrcRHS,
3919                         ConstantInt::get(CC->getType(), SrcPred) };
3920       CallInst *NewCall = Builder.CreateCall(NewF, Args);
3921       NewCall->takeName(II);
3922       return replaceInstUsesWith(*II, NewCall);
3923     }
3924 
3925     break;
3926   }
3927   case Intrinsic::amdgcn_wqm_vote: {
3928     // wqm_vote is identity when the argument is constant.
3929     if (!isa<Constant>(II->getArgOperand(0)))
3930       break;
3931 
3932     return replaceInstUsesWith(*II, II->getArgOperand(0));
3933   }
3934   case Intrinsic::amdgcn_kill: {
3935     const ConstantInt *C = dyn_cast<ConstantInt>(II->getArgOperand(0));
3936     if (!C || !C->getZExtValue())
3937       break;
3938 
3939     // amdgcn.kill(i1 1) is a no-op
3940     return eraseInstFromFunction(CI);
3941   }
3942   case Intrinsic::amdgcn_update_dpp: {
3943     Value *Old = II->getArgOperand(0);
3944 
3945     auto BC = cast<ConstantInt>(II->getArgOperand(5));
3946     auto RM = cast<ConstantInt>(II->getArgOperand(3));
3947     auto BM = cast<ConstantInt>(II->getArgOperand(4));
3948     if (BC->isZeroValue() ||
3949         RM->getZExtValue() != 0xF ||
3950         BM->getZExtValue() != 0xF ||
3951         isa<UndefValue>(Old))
3952       break;
3953 
3954     // If bound_ctrl = 1, row mask = bank mask = 0xf we can omit old value.
3955     return replaceOperand(*II, 0, UndefValue::get(Old->getType()));
3956   }
3957   case Intrinsic::amdgcn_permlane16:
3958   case Intrinsic::amdgcn_permlanex16: {
3959     // Discard vdst_in if it's not going to be read.
3960     Value *VDstIn = II->getArgOperand(0);
3961    if (isa<UndefValue>(VDstIn))
3962      break;
3963 
3964     ConstantInt *FetchInvalid = cast<ConstantInt>(II->getArgOperand(4));
3965     ConstantInt *BoundCtrl = cast<ConstantInt>(II->getArgOperand(5));
3966     if (!FetchInvalid->getZExtValue() && !BoundCtrl->getZExtValue())
3967       break;
3968 
3969     return replaceOperand(*II, 0, UndefValue::get(VDstIn->getType()));
3970   }
3971   case Intrinsic::amdgcn_readfirstlane:
3972   case Intrinsic::amdgcn_readlane: {
3973     // A constant value is trivially uniform.
3974     if (Constant *C = dyn_cast<Constant>(II->getArgOperand(0)))
3975       return replaceInstUsesWith(*II, C);
3976 
3977     // The rest of these may not be safe if the exec may not be the same between
3978     // the def and use.
3979     Value *Src = II->getArgOperand(0);
3980     Instruction *SrcInst = dyn_cast<Instruction>(Src);
3981     if (SrcInst && SrcInst->getParent() != II->getParent())
3982       break;
3983 
3984     // readfirstlane (readfirstlane x) -> readfirstlane x
3985     // readlane (readfirstlane x), y -> readfirstlane x
3986     if (match(Src, m_Intrinsic<Intrinsic::amdgcn_readfirstlane>()))
3987       return replaceInstUsesWith(*II, Src);
3988 
3989     if (IID == Intrinsic::amdgcn_readfirstlane) {
3990       // readfirstlane (readlane x, y) -> readlane x, y
3991       if (match(Src, m_Intrinsic<Intrinsic::amdgcn_readlane>()))
3992         return replaceInstUsesWith(*II, Src);
3993     } else {
3994       // readlane (readlane x, y), y -> readlane x, y
3995       if (match(Src, m_Intrinsic<Intrinsic::amdgcn_readlane>(
3996                   m_Value(), m_Specific(II->getArgOperand(1)))))
3997         return replaceInstUsesWith(*II, Src);
3998     }
3999 
4000     break;
4001   }
4002   case Intrinsic::stackrestore: {
4003     // If the save is right next to the restore, remove the restore.  This can
4004     // happen when variable allocas are DCE'd.
4005     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {
4006       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
4007         // Skip over debug info.
4008         if (SS->getNextNonDebugInstruction() == II) {
4009           return eraseInstFromFunction(CI);
4010         }
4011       }
4012     }
4013 
4014     // Scan down this block to see if there is another stack restore in the
4015     // same block without an intervening call/alloca.
4016     BasicBlock::iterator BI(II);
4017     Instruction *TI = II->getParent()->getTerminator();
4018     bool CannotRemove = false;
4019     for (++BI; &*BI != TI; ++BI) {
4020       if (isa<AllocaInst>(BI)) {
4021         CannotRemove = true;
4022         break;
4023       }
4024       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
4025         if (auto *II2 = dyn_cast<IntrinsicInst>(BCI)) {
4026           // If there is a stackrestore below this one, remove this one.
4027           if (II2->getIntrinsicID() == Intrinsic::stackrestore)
4028             return eraseInstFromFunction(CI);
4029 
4030           // Bail if we cross over an intrinsic with side effects, such as
4031           // llvm.stacksave, or llvm.read_register.
4032           if (II2->mayHaveSideEffects()) {
4033             CannotRemove = true;
4034             break;
4035           }
4036         } else {
4037           // If we found a non-intrinsic call, we can't remove the stack
4038           // restore.
4039           CannotRemove = true;
4040           break;
4041         }
4042       }
4043     }
4044 
4045     // If the stack restore is in a return, resume, or unwind block and if there
4046     // are no allocas or calls between the restore and the return, nuke the
4047     // restore.
4048     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<ResumeInst>(TI)))
4049       return eraseInstFromFunction(CI);
4050     break;
4051   }
4052   case Intrinsic::lifetime_start:
4053     // Asan needs to poison memory to detect invalid access which is possible
4054     // even for empty lifetime range.
4055     if (II->getFunction()->hasFnAttribute(Attribute::SanitizeAddress) ||
4056         II->getFunction()->hasFnAttribute(Attribute::SanitizeMemory) ||
4057         II->getFunction()->hasFnAttribute(Attribute::SanitizeHWAddress))
4058       break;
4059 
4060     if (removeTriviallyEmptyRange(*II, Intrinsic::lifetime_start,
4061                                   Intrinsic::lifetime_end, *this))
4062       return nullptr;
4063     break;
4064   case Intrinsic::assume: {
4065     Value *IIOperand = II->getArgOperand(0);
4066     // Remove an assume if it is followed by an identical assume.
4067     // TODO: Do we need this? Unless there are conflicting assumptions, the
4068     // computeKnownBits(IIOperand) below here eliminates redundant assumes.
4069     Instruction *Next = II->getNextNonDebugInstruction();
4070     if (match(Next, m_Intrinsic<Intrinsic::assume>(m_Specific(IIOperand))))
4071       return eraseInstFromFunction(CI);
4072 
4073     // Canonicalize assume(a && b) -> assume(a); assume(b);
4074     // Note: New assumption intrinsics created here are registered by
4075     // the InstCombineIRInserter object.
4076     FunctionType *AssumeIntrinsicTy = II->getFunctionType();
4077     Value *AssumeIntrinsic = II->getCalledValue();
4078     Value *A, *B;
4079     if (match(IIOperand, m_And(m_Value(A), m_Value(B)))) {
4080       Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic, A, II->getName());
4081       Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic, B, II->getName());
4082       return eraseInstFromFunction(*II);
4083     }
4084     // assume(!(a || b)) -> assume(!a); assume(!b);
4085     if (match(IIOperand, m_Not(m_Or(m_Value(A), m_Value(B))))) {
4086       Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic,
4087                          Builder.CreateNot(A), II->getName());
4088       Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic,
4089                          Builder.CreateNot(B), II->getName());
4090       return eraseInstFromFunction(*II);
4091     }
4092 
4093     // assume( (load addr) != null ) -> add 'nonnull' metadata to load
4094     // (if assume is valid at the load)
4095     CmpInst::Predicate Pred;
4096     Instruction *LHS;
4097     if (match(IIOperand, m_ICmp(Pred, m_Instruction(LHS), m_Zero())) &&
4098         Pred == ICmpInst::ICMP_NE && LHS->getOpcode() == Instruction::Load &&
4099         LHS->getType()->isPointerTy() &&
4100         isValidAssumeForContext(II, LHS, &DT)) {
4101       MDNode *MD = MDNode::get(II->getContext(), None);
4102       LHS->setMetadata(LLVMContext::MD_nonnull, MD);
4103       return eraseInstFromFunction(*II);
4104 
4105       // TODO: apply nonnull return attributes to calls and invokes
4106       // TODO: apply range metadata for range check patterns?
4107     }
4108 
4109     // If there is a dominating assume with the same condition as this one,
4110     // then this one is redundant, and should be removed.
4111     KnownBits Known(1);
4112     computeKnownBits(IIOperand, Known, 0, II);
4113     if (Known.isAllOnes())
4114       return eraseInstFromFunction(*II);
4115 
4116     // Update the cache of affected values for this assumption (we might be
4117     // here because we just simplified the condition).
4118     AC.updateAffectedValues(II);
4119     break;
4120   }
4121   case Intrinsic::experimental_gc_relocate: {
4122     auto &GCR = *cast<GCRelocateInst>(II);
4123 
4124     // If we have two copies of the same pointer in the statepoint argument
4125     // list, canonicalize to one.  This may let us common gc.relocates.
4126     if (GCR.getBasePtr() == GCR.getDerivedPtr() &&
4127         GCR.getBasePtrIndex() != GCR.getDerivedPtrIndex()) {
4128       auto *OpIntTy = GCR.getOperand(2)->getType();
4129       return replaceOperand(*II, 2,
4130           ConstantInt::get(OpIntTy, GCR.getBasePtrIndex()));
4131     }
4132 
4133     // Translate facts known about a pointer before relocating into
4134     // facts about the relocate value, while being careful to
4135     // preserve relocation semantics.
4136     Value *DerivedPtr = GCR.getDerivedPtr();
4137 
4138     // Remove the relocation if unused, note that this check is required
4139     // to prevent the cases below from looping forever.
4140     if (II->use_empty())
4141       return eraseInstFromFunction(*II);
4142 
4143     // Undef is undef, even after relocation.
4144     // TODO: provide a hook for this in GCStrategy.  This is clearly legal for
4145     // most practical collectors, but there was discussion in the review thread
4146     // about whether it was legal for all possible collectors.
4147     if (isa<UndefValue>(DerivedPtr))
4148       // Use undef of gc_relocate's type to replace it.
4149       return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
4150 
4151     if (auto *PT = dyn_cast<PointerType>(II->getType())) {
4152       // The relocation of null will be null for most any collector.
4153       // TODO: provide a hook for this in GCStrategy.  There might be some
4154       // weird collector this property does not hold for.
4155       if (isa<ConstantPointerNull>(DerivedPtr))
4156         // Use null-pointer of gc_relocate's type to replace it.
4157         return replaceInstUsesWith(*II, ConstantPointerNull::get(PT));
4158 
4159       // isKnownNonNull -> nonnull attribute
4160       if (!II->hasRetAttr(Attribute::NonNull) &&
4161           isKnownNonZero(DerivedPtr, DL, 0, &AC, II, &DT)) {
4162         II->addAttribute(AttributeList::ReturnIndex, Attribute::NonNull);
4163         return II;
4164       }
4165     }
4166 
4167     // TODO: bitcast(relocate(p)) -> relocate(bitcast(p))
4168     // Canonicalize on the type from the uses to the defs
4169 
4170     // TODO: relocate((gep p, C, C2, ...)) -> gep(relocate(p), C, C2, ...)
4171     break;
4172   }
4173 
4174   case Intrinsic::experimental_guard: {
4175     // Is this guard followed by another guard?  We scan forward over a small
4176     // fixed window of instructions to handle common cases with conditions
4177     // computed between guards.
4178     Instruction *NextInst = II->getNextNonDebugInstruction();
4179     for (unsigned i = 0; i < GuardWideningWindow; i++) {
4180       // Note: Using context-free form to avoid compile time blow up
4181       if (!isSafeToSpeculativelyExecute(NextInst))
4182         break;
4183       NextInst = NextInst->getNextNonDebugInstruction();
4184     }
4185     Value *NextCond = nullptr;
4186     if (match(NextInst,
4187               m_Intrinsic<Intrinsic::experimental_guard>(m_Value(NextCond)))) {
4188       Value *CurrCond = II->getArgOperand(0);
4189 
4190       // Remove a guard that it is immediately preceded by an identical guard.
4191       // Otherwise canonicalize guard(a); guard(b) -> guard(a & b).
4192       if (CurrCond != NextCond) {
4193         Instruction *MoveI = II->getNextNonDebugInstruction();
4194         while (MoveI != NextInst) {
4195           auto *Temp = MoveI;
4196           MoveI = MoveI->getNextNonDebugInstruction();
4197           Temp->moveBefore(II);
4198         }
4199         II->setArgOperand(0, Builder.CreateAnd(CurrCond, NextCond));
4200       }
4201       eraseInstFromFunction(*NextInst);
4202       return II;
4203     }
4204     break;
4205   }
4206   }
4207   return visitCallBase(*II);
4208 }
4209 
4210 // Fence instruction simplification
4211 Instruction *InstCombiner::visitFenceInst(FenceInst &FI) {
4212   // Remove identical consecutive fences.
4213   Instruction *Next = FI.getNextNonDebugInstruction();
4214   if (auto *NFI = dyn_cast<FenceInst>(Next))
4215     if (FI.isIdenticalTo(NFI))
4216       return eraseInstFromFunction(FI);
4217   return nullptr;
4218 }
4219 
4220 // InvokeInst simplification
4221 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
4222   return visitCallBase(II);
4223 }
4224 
4225 // CallBrInst simplification
4226 Instruction *InstCombiner::visitCallBrInst(CallBrInst &CBI) {
4227   return visitCallBase(CBI);
4228 }
4229 
4230 /// If this cast does not affect the value passed through the varargs area, we
4231 /// can eliminate the use of the cast.
4232 static bool isSafeToEliminateVarargsCast(const CallBase &Call,
4233                                          const DataLayout &DL,
4234                                          const CastInst *const CI,
4235                                          const int ix) {
4236   if (!CI->isLosslessCast())
4237     return false;
4238 
4239   // If this is a GC intrinsic, avoid munging types.  We need types for
4240   // statepoint reconstruction in SelectionDAG.
4241   // TODO: This is probably something which should be expanded to all
4242   // intrinsics since the entire point of intrinsics is that
4243   // they are understandable by the optimizer.
4244   if (isStatepoint(&Call) || isGCRelocate(&Call) || isGCResult(&Call))
4245     return false;
4246 
4247   // The size of ByVal or InAlloca arguments is derived from the type, so we
4248   // can't change to a type with a different size.  If the size were
4249   // passed explicitly we could avoid this check.
4250   if (!Call.isByValOrInAllocaArgument(ix))
4251     return true;
4252 
4253   Type* SrcTy =
4254             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
4255   Type *DstTy = Call.isByValArgument(ix)
4256                     ? Call.getParamByValType(ix)
4257                     : cast<PointerType>(CI->getType())->getElementType();
4258   if (!SrcTy->isSized() || !DstTy->isSized())
4259     return false;
4260   if (DL.getTypeAllocSize(SrcTy) != DL.getTypeAllocSize(DstTy))
4261     return false;
4262   return true;
4263 }
4264 
4265 Instruction *InstCombiner::tryOptimizeCall(CallInst *CI) {
4266   if (!CI->getCalledFunction()) return nullptr;
4267 
4268   auto InstCombineRAUW = [this](Instruction *From, Value *With) {
4269     replaceInstUsesWith(*From, With);
4270   };
4271   auto InstCombineErase = [this](Instruction *I) {
4272     eraseInstFromFunction(*I);
4273   };
4274   LibCallSimplifier Simplifier(DL, &TLI, ORE, BFI, PSI, InstCombineRAUW,
4275                                InstCombineErase);
4276   if (Value *With = Simplifier.optimizeCall(CI)) {
4277     ++NumSimplified;
4278     return CI->use_empty() ? CI : replaceInstUsesWith(*CI, With);
4279   }
4280 
4281   return nullptr;
4282 }
4283 
4284 static IntrinsicInst *findInitTrampolineFromAlloca(Value *TrampMem) {
4285   // Strip off at most one level of pointer casts, looking for an alloca.  This
4286   // is good enough in practice and simpler than handling any number of casts.
4287   Value *Underlying = TrampMem->stripPointerCasts();
4288   if (Underlying != TrampMem &&
4289       (!Underlying->hasOneUse() || Underlying->user_back() != TrampMem))
4290     return nullptr;
4291   if (!isa<AllocaInst>(Underlying))
4292     return nullptr;
4293 
4294   IntrinsicInst *InitTrampoline = nullptr;
4295   for (User *U : TrampMem->users()) {
4296     IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
4297     if (!II)
4298       return nullptr;
4299     if (II->getIntrinsicID() == Intrinsic::init_trampoline) {
4300       if (InitTrampoline)
4301         // More than one init_trampoline writes to this value.  Give up.
4302         return nullptr;
4303       InitTrampoline = II;
4304       continue;
4305     }
4306     if (II->getIntrinsicID() == Intrinsic::adjust_trampoline)
4307       // Allow any number of calls to adjust.trampoline.
4308       continue;
4309     return nullptr;
4310   }
4311 
4312   // No call to init.trampoline found.
4313   if (!InitTrampoline)
4314     return nullptr;
4315 
4316   // Check that the alloca is being used in the expected way.
4317   if (InitTrampoline->getOperand(0) != TrampMem)
4318     return nullptr;
4319 
4320   return InitTrampoline;
4321 }
4322 
4323 static IntrinsicInst *findInitTrampolineFromBB(IntrinsicInst *AdjustTramp,
4324                                                Value *TrampMem) {
4325   // Visit all the previous instructions in the basic block, and try to find a
4326   // init.trampoline which has a direct path to the adjust.trampoline.
4327   for (BasicBlock::iterator I = AdjustTramp->getIterator(),
4328                             E = AdjustTramp->getParent()->begin();
4329        I != E;) {
4330     Instruction *Inst = &*--I;
4331     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
4332       if (II->getIntrinsicID() == Intrinsic::init_trampoline &&
4333           II->getOperand(0) == TrampMem)
4334         return II;
4335     if (Inst->mayWriteToMemory())
4336       return nullptr;
4337   }
4338   return nullptr;
4339 }
4340 
4341 // Given a call to llvm.adjust.trampoline, find and return the corresponding
4342 // call to llvm.init.trampoline if the call to the trampoline can be optimized
4343 // to a direct call to a function.  Otherwise return NULL.
4344 static IntrinsicInst *findInitTrampoline(Value *Callee) {
4345   Callee = Callee->stripPointerCasts();
4346   IntrinsicInst *AdjustTramp = dyn_cast<IntrinsicInst>(Callee);
4347   if (!AdjustTramp ||
4348       AdjustTramp->getIntrinsicID() != Intrinsic::adjust_trampoline)
4349     return nullptr;
4350 
4351   Value *TrampMem = AdjustTramp->getOperand(0);
4352 
4353   if (IntrinsicInst *IT = findInitTrampolineFromAlloca(TrampMem))
4354     return IT;
4355   if (IntrinsicInst *IT = findInitTrampolineFromBB(AdjustTramp, TrampMem))
4356     return IT;
4357   return nullptr;
4358 }
4359 
4360 static void annotateAnyAllocSite(CallBase &Call, const TargetLibraryInfo *TLI) {
4361   unsigned NumArgs = Call.getNumArgOperands();
4362   ConstantInt *Op0C = dyn_cast<ConstantInt>(Call.getOperand(0));
4363   ConstantInt *Op1C =
4364       (NumArgs == 1) ? nullptr : dyn_cast<ConstantInt>(Call.getOperand(1));
4365   // Bail out if the allocation size is zero.
4366   if ((Op0C && Op0C->isNullValue()) || (Op1C && Op1C->isNullValue()))
4367     return;
4368 
4369   if (isMallocLikeFn(&Call, TLI) && Op0C) {
4370     if (isOpNewLikeFn(&Call, TLI))
4371       Call.addAttribute(AttributeList::ReturnIndex,
4372                         Attribute::getWithDereferenceableBytes(
4373                             Call.getContext(), Op0C->getZExtValue()));
4374     else
4375       Call.addAttribute(AttributeList::ReturnIndex,
4376                         Attribute::getWithDereferenceableOrNullBytes(
4377                             Call.getContext(), Op0C->getZExtValue()));
4378   } else if (isReallocLikeFn(&Call, TLI) && Op1C) {
4379     Call.addAttribute(AttributeList::ReturnIndex,
4380                       Attribute::getWithDereferenceableOrNullBytes(
4381                           Call.getContext(), Op1C->getZExtValue()));
4382   } else if (isCallocLikeFn(&Call, TLI) && Op0C && Op1C) {
4383     bool Overflow;
4384     const APInt &N = Op0C->getValue();
4385     APInt Size = N.umul_ov(Op1C->getValue(), Overflow);
4386     if (!Overflow)
4387       Call.addAttribute(AttributeList::ReturnIndex,
4388                         Attribute::getWithDereferenceableOrNullBytes(
4389                             Call.getContext(), Size.getZExtValue()));
4390   } else if (isStrdupLikeFn(&Call, TLI)) {
4391     uint64_t Len = GetStringLength(Call.getOperand(0));
4392     if (Len) {
4393       // strdup
4394       if (NumArgs == 1)
4395         Call.addAttribute(AttributeList::ReturnIndex,
4396                           Attribute::getWithDereferenceableOrNullBytes(
4397                               Call.getContext(), Len));
4398       // strndup
4399       else if (NumArgs == 2 && Op1C)
4400         Call.addAttribute(
4401             AttributeList::ReturnIndex,
4402             Attribute::getWithDereferenceableOrNullBytes(
4403                 Call.getContext(), std::min(Len, Op1C->getZExtValue() + 1)));
4404     }
4405   }
4406 }
4407 
4408 /// Improvements for call, callbr and invoke instructions.
4409 Instruction *InstCombiner::visitCallBase(CallBase &Call) {
4410   if (isAllocationFn(&Call, &TLI))
4411     annotateAnyAllocSite(Call, &TLI);
4412 
4413   bool Changed = false;
4414 
4415   // Mark any parameters that are known to be non-null with the nonnull
4416   // attribute.  This is helpful for inlining calls to functions with null
4417   // checks on their arguments.
4418   SmallVector<unsigned, 4> ArgNos;
4419   unsigned ArgNo = 0;
4420 
4421   for (Value *V : Call.args()) {
4422     if (V->getType()->isPointerTy() &&
4423         !Call.paramHasAttr(ArgNo, Attribute::NonNull) &&
4424         isKnownNonZero(V, DL, 0, &AC, &Call, &DT))
4425       ArgNos.push_back(ArgNo);
4426     ArgNo++;
4427   }
4428 
4429   assert(ArgNo == Call.arg_size() && "sanity check");
4430 
4431   if (!ArgNos.empty()) {
4432     AttributeList AS = Call.getAttributes();
4433     LLVMContext &Ctx = Call.getContext();
4434     AS = AS.addParamAttribute(Ctx, ArgNos,
4435                               Attribute::get(Ctx, Attribute::NonNull));
4436     Call.setAttributes(AS);
4437     Changed = true;
4438   }
4439 
4440   // If the callee is a pointer to a function, attempt to move any casts to the
4441   // arguments of the call/callbr/invoke.
4442   Value *Callee = Call.getCalledValue();
4443   if (!isa<Function>(Callee) && transformConstExprCastCall(Call))
4444     return nullptr;
4445 
4446   if (Function *CalleeF = dyn_cast<Function>(Callee)) {
4447     // Remove the convergent attr on calls when the callee is not convergent.
4448     if (Call.isConvergent() && !CalleeF->isConvergent() &&
4449         !CalleeF->isIntrinsic()) {
4450       LLVM_DEBUG(dbgs() << "Removing convergent attr from instr " << Call
4451                         << "\n");
4452       Call.setNotConvergent();
4453       return &Call;
4454     }
4455 
4456     // If the call and callee calling conventions don't match, this call must
4457     // be unreachable, as the call is undefined.
4458     if (CalleeF->getCallingConv() != Call.getCallingConv() &&
4459         // Only do this for calls to a function with a body.  A prototype may
4460         // not actually end up matching the implementation's calling conv for a
4461         // variety of reasons (e.g. it may be written in assembly).
4462         !CalleeF->isDeclaration()) {
4463       Instruction *OldCall = &Call;
4464       CreateNonTerminatorUnreachable(OldCall);
4465       // If OldCall does not return void then replaceAllUsesWith undef.
4466       // This allows ValueHandlers and custom metadata to adjust itself.
4467       if (!OldCall->getType()->isVoidTy())
4468         replaceInstUsesWith(*OldCall, UndefValue::get(OldCall->getType()));
4469       if (isa<CallInst>(OldCall))
4470         return eraseInstFromFunction(*OldCall);
4471 
4472       // We cannot remove an invoke or a callbr, because it would change thexi
4473       // CFG, just change the callee to a null pointer.
4474       cast<CallBase>(OldCall)->setCalledFunction(
4475           CalleeF->getFunctionType(),
4476           Constant::getNullValue(CalleeF->getType()));
4477       return nullptr;
4478     }
4479   }
4480 
4481   if ((isa<ConstantPointerNull>(Callee) &&
4482        !NullPointerIsDefined(Call.getFunction())) ||
4483       isa<UndefValue>(Callee)) {
4484     // If Call does not return void then replaceAllUsesWith undef.
4485     // This allows ValueHandlers and custom metadata to adjust itself.
4486     if (!Call.getType()->isVoidTy())
4487       replaceInstUsesWith(Call, UndefValue::get(Call.getType()));
4488 
4489     if (Call.isTerminator()) {
4490       // Can't remove an invoke or callbr because we cannot change the CFG.
4491       return nullptr;
4492     }
4493 
4494     // This instruction is not reachable, just remove it.
4495     CreateNonTerminatorUnreachable(&Call);
4496     return eraseInstFromFunction(Call);
4497   }
4498 
4499   if (IntrinsicInst *II = findInitTrampoline(Callee))
4500     return transformCallThroughTrampoline(Call, *II);
4501 
4502   PointerType *PTy = cast<PointerType>(Callee->getType());
4503   FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
4504   if (FTy->isVarArg()) {
4505     int ix = FTy->getNumParams();
4506     // See if we can optimize any arguments passed through the varargs area of
4507     // the call.
4508     for (auto I = Call.arg_begin() + FTy->getNumParams(), E = Call.arg_end();
4509          I != E; ++I, ++ix) {
4510       CastInst *CI = dyn_cast<CastInst>(*I);
4511       if (CI && isSafeToEliminateVarargsCast(Call, DL, CI, ix)) {
4512         *I = CI->getOperand(0);
4513 
4514         // Update the byval type to match the argument type.
4515         if (Call.isByValArgument(ix)) {
4516           Call.removeParamAttr(ix, Attribute::ByVal);
4517           Call.addParamAttr(
4518               ix, Attribute::getWithByValType(
4519                       Call.getContext(),
4520                       CI->getOperand(0)->getType()->getPointerElementType()));
4521         }
4522         Changed = true;
4523       }
4524     }
4525   }
4526 
4527   if (isa<InlineAsm>(Callee) && !Call.doesNotThrow()) {
4528     // Inline asm calls cannot throw - mark them 'nounwind'.
4529     Call.setDoesNotThrow();
4530     Changed = true;
4531   }
4532 
4533   // Try to optimize the call if possible, we require DataLayout for most of
4534   // this.  None of these calls are seen as possibly dead so go ahead and
4535   // delete the instruction now.
4536   if (CallInst *CI = dyn_cast<CallInst>(&Call)) {
4537     Instruction *I = tryOptimizeCall(CI);
4538     // If we changed something return the result, etc. Otherwise let
4539     // the fallthrough check.
4540     if (I) return eraseInstFromFunction(*I);
4541   }
4542 
4543   if (isAllocLikeFn(&Call, &TLI))
4544     return visitAllocSite(Call);
4545 
4546   return Changed ? &Call : nullptr;
4547 }
4548 
4549 /// If the callee is a constexpr cast of a function, attempt to move the cast to
4550 /// the arguments of the call/callbr/invoke.
4551 bool InstCombiner::transformConstExprCastCall(CallBase &Call) {
4552   auto *Callee = dyn_cast<Function>(Call.getCalledValue()->stripPointerCasts());
4553   if (!Callee)
4554     return false;
4555 
4556   // If this is a call to a thunk function, don't remove the cast. Thunks are
4557   // used to transparently forward all incoming parameters and outgoing return
4558   // values, so it's important to leave the cast in place.
4559   if (Callee->hasFnAttribute("thunk"))
4560     return false;
4561 
4562   // If this is a musttail call, the callee's prototype must match the caller's
4563   // prototype with the exception of pointee types. The code below doesn't
4564   // implement that, so we can't do this transform.
4565   // TODO: Do the transform if it only requires adding pointer casts.
4566   if (Call.isMustTailCall())
4567     return false;
4568 
4569   Instruction *Caller = &Call;
4570   const AttributeList &CallerPAL = Call.getAttributes();
4571 
4572   // Okay, this is a cast from a function to a different type.  Unless doing so
4573   // would cause a type conversion of one of our arguments, change this call to
4574   // be a direct call with arguments casted to the appropriate types.
4575   FunctionType *FT = Callee->getFunctionType();
4576   Type *OldRetTy = Caller->getType();
4577   Type *NewRetTy = FT->getReturnType();
4578 
4579   // Check to see if we are changing the return type...
4580   if (OldRetTy != NewRetTy) {
4581 
4582     if (NewRetTy->isStructTy())
4583       return false; // TODO: Handle multiple return values.
4584 
4585     if (!CastInst::isBitOrNoopPointerCastable(NewRetTy, OldRetTy, DL)) {
4586       if (Callee->isDeclaration())
4587         return false;   // Cannot transform this return value.
4588 
4589       if (!Caller->use_empty() &&
4590           // void -> non-void is handled specially
4591           !NewRetTy->isVoidTy())
4592         return false;   // Cannot transform this return value.
4593     }
4594 
4595     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
4596       AttrBuilder RAttrs(CallerPAL, AttributeList::ReturnIndex);
4597       if (RAttrs.overlaps(AttributeFuncs::typeIncompatible(NewRetTy)))
4598         return false;   // Attribute not compatible with transformed value.
4599     }
4600 
4601     // If the callbase is an invoke/callbr instruction, and the return value is
4602     // used by a PHI node in a successor, we cannot change the return type of
4603     // the call because there is no place to put the cast instruction (without
4604     // breaking the critical edge).  Bail out in this case.
4605     if (!Caller->use_empty()) {
4606       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
4607         for (User *U : II->users())
4608           if (PHINode *PN = dyn_cast<PHINode>(U))
4609             if (PN->getParent() == II->getNormalDest() ||
4610                 PN->getParent() == II->getUnwindDest())
4611               return false;
4612       // FIXME: Be conservative for callbr to avoid a quadratic search.
4613       if (isa<CallBrInst>(Caller))
4614         return false;
4615     }
4616   }
4617 
4618   unsigned NumActualArgs = Call.arg_size();
4619   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
4620 
4621   // Prevent us turning:
4622   // declare void @takes_i32_inalloca(i32* inalloca)
4623   //  call void bitcast (void (i32*)* @takes_i32_inalloca to void (i32)*)(i32 0)
4624   //
4625   // into:
4626   //  call void @takes_i32_inalloca(i32* null)
4627   //
4628   //  Similarly, avoid folding away bitcasts of byval calls.
4629   if (Callee->getAttributes().hasAttrSomewhere(Attribute::InAlloca) ||
4630       Callee->getAttributes().hasAttrSomewhere(Attribute::ByVal))
4631     return false;
4632 
4633   auto AI = Call.arg_begin();
4634   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
4635     Type *ParamTy = FT->getParamType(i);
4636     Type *ActTy = (*AI)->getType();
4637 
4638     if (!CastInst::isBitOrNoopPointerCastable(ActTy, ParamTy, DL))
4639       return false;   // Cannot transform this parameter value.
4640 
4641     if (AttrBuilder(CallerPAL.getParamAttributes(i))
4642             .overlaps(AttributeFuncs::typeIncompatible(ParamTy)))
4643       return false;   // Attribute not compatible with transformed value.
4644 
4645     if (Call.isInAllocaArgument(i))
4646       return false;   // Cannot transform to and from inalloca.
4647 
4648     // If the parameter is passed as a byval argument, then we have to have a
4649     // sized type and the sized type has to have the same size as the old type.
4650     if (ParamTy != ActTy && CallerPAL.hasParamAttribute(i, Attribute::ByVal)) {
4651       PointerType *ParamPTy = dyn_cast<PointerType>(ParamTy);
4652       if (!ParamPTy || !ParamPTy->getElementType()->isSized())
4653         return false;
4654 
4655       Type *CurElTy = Call.getParamByValType(i);
4656       if (DL.getTypeAllocSize(CurElTy) !=
4657           DL.getTypeAllocSize(ParamPTy->getElementType()))
4658         return false;
4659     }
4660   }
4661 
4662   if (Callee->isDeclaration()) {
4663     // Do not delete arguments unless we have a function body.
4664     if (FT->getNumParams() < NumActualArgs && !FT->isVarArg())
4665       return false;
4666 
4667     // If the callee is just a declaration, don't change the varargsness of the
4668     // call.  We don't want to introduce a varargs call where one doesn't
4669     // already exist.
4670     PointerType *APTy = cast<PointerType>(Call.getCalledValue()->getType());
4671     if (FT->isVarArg()!=cast<FunctionType>(APTy->getElementType())->isVarArg())
4672       return false;
4673 
4674     // If both the callee and the cast type are varargs, we still have to make
4675     // sure the number of fixed parameters are the same or we have the same
4676     // ABI issues as if we introduce a varargs call.
4677     if (FT->isVarArg() &&
4678         cast<FunctionType>(APTy->getElementType())->isVarArg() &&
4679         FT->getNumParams() !=
4680         cast<FunctionType>(APTy->getElementType())->getNumParams())
4681       return false;
4682   }
4683 
4684   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
4685       !CallerPAL.isEmpty()) {
4686     // In this case we have more arguments than the new function type, but we
4687     // won't be dropping them.  Check that these extra arguments have attributes
4688     // that are compatible with being a vararg call argument.
4689     unsigned SRetIdx;
4690     if (CallerPAL.hasAttrSomewhere(Attribute::StructRet, &SRetIdx) &&
4691         SRetIdx > FT->getNumParams())
4692       return false;
4693   }
4694 
4695   // Okay, we decided that this is a safe thing to do: go ahead and start
4696   // inserting cast instructions as necessary.
4697   SmallVector<Value *, 8> Args;
4698   SmallVector<AttributeSet, 8> ArgAttrs;
4699   Args.reserve(NumActualArgs);
4700   ArgAttrs.reserve(NumActualArgs);
4701 
4702   // Get any return attributes.
4703   AttrBuilder RAttrs(CallerPAL, AttributeList::ReturnIndex);
4704 
4705   // If the return value is not being used, the type may not be compatible
4706   // with the existing attributes.  Wipe out any problematic attributes.
4707   RAttrs.remove(AttributeFuncs::typeIncompatible(NewRetTy));
4708 
4709   LLVMContext &Ctx = Call.getContext();
4710   AI = Call.arg_begin();
4711   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
4712     Type *ParamTy = FT->getParamType(i);
4713 
4714     Value *NewArg = *AI;
4715     if ((*AI)->getType() != ParamTy)
4716       NewArg = Builder.CreateBitOrPointerCast(*AI, ParamTy);
4717     Args.push_back(NewArg);
4718 
4719     // Add any parameter attributes.
4720     if (CallerPAL.hasParamAttribute(i, Attribute::ByVal)) {
4721       AttrBuilder AB(CallerPAL.getParamAttributes(i));
4722       AB.addByValAttr(NewArg->getType()->getPointerElementType());
4723       ArgAttrs.push_back(AttributeSet::get(Ctx, AB));
4724     } else
4725       ArgAttrs.push_back(CallerPAL.getParamAttributes(i));
4726   }
4727 
4728   // If the function takes more arguments than the call was taking, add them
4729   // now.
4730   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i) {
4731     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
4732     ArgAttrs.push_back(AttributeSet());
4733   }
4734 
4735   // If we are removing arguments to the function, emit an obnoxious warning.
4736   if (FT->getNumParams() < NumActualArgs) {
4737     // TODO: if (!FT->isVarArg()) this call may be unreachable. PR14722
4738     if (FT->isVarArg()) {
4739       // Add all of the arguments in their promoted form to the arg list.
4740       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
4741         Type *PTy = getPromotedType((*AI)->getType());
4742         Value *NewArg = *AI;
4743         if (PTy != (*AI)->getType()) {
4744           // Must promote to pass through va_arg area!
4745           Instruction::CastOps opcode =
4746             CastInst::getCastOpcode(*AI, false, PTy, false);
4747           NewArg = Builder.CreateCast(opcode, *AI, PTy);
4748         }
4749         Args.push_back(NewArg);
4750 
4751         // Add any parameter attributes.
4752         ArgAttrs.push_back(CallerPAL.getParamAttributes(i));
4753       }
4754     }
4755   }
4756 
4757   AttributeSet FnAttrs = CallerPAL.getFnAttributes();
4758 
4759   if (NewRetTy->isVoidTy())
4760     Caller->setName("");   // Void type should not have a name.
4761 
4762   assert((ArgAttrs.size() == FT->getNumParams() || FT->isVarArg()) &&
4763          "missing argument attributes");
4764   AttributeList NewCallerPAL = AttributeList::get(
4765       Ctx, FnAttrs, AttributeSet::get(Ctx, RAttrs), ArgAttrs);
4766 
4767   SmallVector<OperandBundleDef, 1> OpBundles;
4768   Call.getOperandBundlesAsDefs(OpBundles);
4769 
4770   CallBase *NewCall;
4771   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
4772     NewCall = Builder.CreateInvoke(Callee, II->getNormalDest(),
4773                                    II->getUnwindDest(), Args, OpBundles);
4774   } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(Caller)) {
4775     NewCall = Builder.CreateCallBr(Callee, CBI->getDefaultDest(),
4776                                    CBI->getIndirectDests(), Args, OpBundles);
4777   } else {
4778     NewCall = Builder.CreateCall(Callee, Args, OpBundles);
4779     cast<CallInst>(NewCall)->setTailCallKind(
4780         cast<CallInst>(Caller)->getTailCallKind());
4781   }
4782   NewCall->takeName(Caller);
4783   NewCall->setCallingConv(Call.getCallingConv());
4784   NewCall->setAttributes(NewCallerPAL);
4785 
4786   // Preserve the weight metadata for the new call instruction. The metadata
4787   // is used by SamplePGO to check callsite's hotness.
4788   uint64_t W;
4789   if (Caller->extractProfTotalWeight(W))
4790     NewCall->setProfWeight(W);
4791 
4792   // Insert a cast of the return type as necessary.
4793   Instruction *NC = NewCall;
4794   Value *NV = NC;
4795   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
4796     if (!NV->getType()->isVoidTy()) {
4797       NV = NC = CastInst::CreateBitOrPointerCast(NC, OldRetTy);
4798       NC->setDebugLoc(Caller->getDebugLoc());
4799 
4800       // If this is an invoke/callbr instruction, we should insert it after the
4801       // first non-phi instruction in the normal successor block.
4802       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
4803         BasicBlock::iterator I = II->getNormalDest()->getFirstInsertionPt();
4804         InsertNewInstBefore(NC, *I);
4805       } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(Caller)) {
4806         BasicBlock::iterator I = CBI->getDefaultDest()->getFirstInsertionPt();
4807         InsertNewInstBefore(NC, *I);
4808       } else {
4809         // Otherwise, it's a call, just insert cast right after the call.
4810         InsertNewInstBefore(NC, *Caller);
4811       }
4812       Worklist.pushUsersToWorkList(*Caller);
4813     } else {
4814       NV = UndefValue::get(Caller->getType());
4815     }
4816   }
4817 
4818   if (!Caller->use_empty())
4819     replaceInstUsesWith(*Caller, NV);
4820   else if (Caller->hasValueHandle()) {
4821     if (OldRetTy == NV->getType())
4822       ValueHandleBase::ValueIsRAUWd(Caller, NV);
4823     else
4824       // We cannot call ValueIsRAUWd with a different type, and the
4825       // actual tracked value will disappear.
4826       ValueHandleBase::ValueIsDeleted(Caller);
4827   }
4828 
4829   eraseInstFromFunction(*Caller);
4830   return true;
4831 }
4832 
4833 /// Turn a call to a function created by init_trampoline / adjust_trampoline
4834 /// intrinsic pair into a direct call to the underlying function.
4835 Instruction *
4836 InstCombiner::transformCallThroughTrampoline(CallBase &Call,
4837                                              IntrinsicInst &Tramp) {
4838   Value *Callee = Call.getCalledValue();
4839   Type *CalleeTy = Callee->getType();
4840   FunctionType *FTy = Call.getFunctionType();
4841   AttributeList Attrs = Call.getAttributes();
4842 
4843   // If the call already has the 'nest' attribute somewhere then give up -
4844   // otherwise 'nest' would occur twice after splicing in the chain.
4845   if (Attrs.hasAttrSomewhere(Attribute::Nest))
4846     return nullptr;
4847 
4848   Function *NestF = cast<Function>(Tramp.getArgOperand(1)->stripPointerCasts());
4849   FunctionType *NestFTy = NestF->getFunctionType();
4850 
4851   AttributeList NestAttrs = NestF->getAttributes();
4852   if (!NestAttrs.isEmpty()) {
4853     unsigned NestArgNo = 0;
4854     Type *NestTy = nullptr;
4855     AttributeSet NestAttr;
4856 
4857     // Look for a parameter marked with the 'nest' attribute.
4858     for (FunctionType::param_iterator I = NestFTy->param_begin(),
4859                                       E = NestFTy->param_end();
4860          I != E; ++NestArgNo, ++I) {
4861       AttributeSet AS = NestAttrs.getParamAttributes(NestArgNo);
4862       if (AS.hasAttribute(Attribute::Nest)) {
4863         // Record the parameter type and any other attributes.
4864         NestTy = *I;
4865         NestAttr = AS;
4866         break;
4867       }
4868     }
4869 
4870     if (NestTy) {
4871       std::vector<Value*> NewArgs;
4872       std::vector<AttributeSet> NewArgAttrs;
4873       NewArgs.reserve(Call.arg_size() + 1);
4874       NewArgAttrs.reserve(Call.arg_size());
4875 
4876       // Insert the nest argument into the call argument list, which may
4877       // mean appending it.  Likewise for attributes.
4878 
4879       {
4880         unsigned ArgNo = 0;
4881         auto I = Call.arg_begin(), E = Call.arg_end();
4882         do {
4883           if (ArgNo == NestArgNo) {
4884             // Add the chain argument and attributes.
4885             Value *NestVal = Tramp.getArgOperand(2);
4886             if (NestVal->getType() != NestTy)
4887               NestVal = Builder.CreateBitCast(NestVal, NestTy, "nest");
4888             NewArgs.push_back(NestVal);
4889             NewArgAttrs.push_back(NestAttr);
4890           }
4891 
4892           if (I == E)
4893             break;
4894 
4895           // Add the original argument and attributes.
4896           NewArgs.push_back(*I);
4897           NewArgAttrs.push_back(Attrs.getParamAttributes(ArgNo));
4898 
4899           ++ArgNo;
4900           ++I;
4901         } while (true);
4902       }
4903 
4904       // The trampoline may have been bitcast to a bogus type (FTy).
4905       // Handle this by synthesizing a new function type, equal to FTy
4906       // with the chain parameter inserted.
4907 
4908       std::vector<Type*> NewTypes;
4909       NewTypes.reserve(FTy->getNumParams()+1);
4910 
4911       // Insert the chain's type into the list of parameter types, which may
4912       // mean appending it.
4913       {
4914         unsigned ArgNo = 0;
4915         FunctionType::param_iterator I = FTy->param_begin(),
4916           E = FTy->param_end();
4917 
4918         do {
4919           if (ArgNo == NestArgNo)
4920             // Add the chain's type.
4921             NewTypes.push_back(NestTy);
4922 
4923           if (I == E)
4924             break;
4925 
4926           // Add the original type.
4927           NewTypes.push_back(*I);
4928 
4929           ++ArgNo;
4930           ++I;
4931         } while (true);
4932       }
4933 
4934       // Replace the trampoline call with a direct call.  Let the generic
4935       // code sort out any function type mismatches.
4936       FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
4937                                                 FTy->isVarArg());
4938       Constant *NewCallee =
4939         NestF->getType() == PointerType::getUnqual(NewFTy) ?
4940         NestF : ConstantExpr::getBitCast(NestF,
4941                                          PointerType::getUnqual(NewFTy));
4942       AttributeList NewPAL =
4943           AttributeList::get(FTy->getContext(), Attrs.getFnAttributes(),
4944                              Attrs.getRetAttributes(), NewArgAttrs);
4945 
4946       SmallVector<OperandBundleDef, 1> OpBundles;
4947       Call.getOperandBundlesAsDefs(OpBundles);
4948 
4949       Instruction *NewCaller;
4950       if (InvokeInst *II = dyn_cast<InvokeInst>(&Call)) {
4951         NewCaller = InvokeInst::Create(NewFTy, NewCallee,
4952                                        II->getNormalDest(), II->getUnwindDest(),
4953                                        NewArgs, OpBundles);
4954         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
4955         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
4956       } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(&Call)) {
4957         NewCaller =
4958             CallBrInst::Create(NewFTy, NewCallee, CBI->getDefaultDest(),
4959                                CBI->getIndirectDests(), NewArgs, OpBundles);
4960         cast<CallBrInst>(NewCaller)->setCallingConv(CBI->getCallingConv());
4961         cast<CallBrInst>(NewCaller)->setAttributes(NewPAL);
4962       } else {
4963         NewCaller = CallInst::Create(NewFTy, NewCallee, NewArgs, OpBundles);
4964         cast<CallInst>(NewCaller)->setTailCallKind(
4965             cast<CallInst>(Call).getTailCallKind());
4966         cast<CallInst>(NewCaller)->setCallingConv(
4967             cast<CallInst>(Call).getCallingConv());
4968         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
4969       }
4970       NewCaller->setDebugLoc(Call.getDebugLoc());
4971 
4972       return NewCaller;
4973     }
4974   }
4975 
4976   // Replace the trampoline call with a direct call.  Since there is no 'nest'
4977   // parameter, there is no need to adjust the argument list.  Let the generic
4978   // code sort out any function type mismatches.
4979   Constant *NewCallee = ConstantExpr::getBitCast(NestF, CalleeTy);
4980   Call.setCalledFunction(FTy, NewCallee);
4981   return &Call;
4982 }
4983