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