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