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