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