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 /// Return the specified type promoted as it would be to pass though a va_arg
64 /// area.
65 static Type *getPromotedType(Type *Ty) {
66   if (IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
67     if (ITy->getBitWidth() < 32)
68       return Type::getInt32Ty(Ty->getContext());
69   }
70   return Ty;
71 }
72 
73 /// Given an aggregate type which ultimately holds a single scalar element,
74 /// like {{{type}}} or [1 x type], return type.
75 static Type *reduceToSingleValueType(Type *T) {
76   while (!T->isSingleValueType()) {
77     if (StructType *STy = dyn_cast<StructType>(T)) {
78       if (STy->getNumElements() == 1)
79         T = STy->getElementType(0);
80       else
81         break;
82     } else if (ArrayType *ATy = dyn_cast<ArrayType>(T)) {
83       if (ATy->getNumElements() == 1)
84         T = ATy->getElementType();
85       else
86         break;
87     } else
88       break;
89   }
90 
91   return T;
92 }
93 
94 /// Return a constant boolean vector that has true elements in all positions
95 /// where the input constant data vector has an element with the sign bit set.
96 static Constant *getNegativeIsTrueBoolVec(ConstantDataVector *V) {
97   SmallVector<Constant *, 32> BoolVec;
98   IntegerType *BoolTy = Type::getInt1Ty(V->getContext());
99   for (unsigned I = 0, E = V->getNumElements(); I != E; ++I) {
100     Constant *Elt = V->getElementAsConstant(I);
101     assert((isa<ConstantInt>(Elt) || isa<ConstantFP>(Elt)) &&
102            "Unexpected constant data vector element type");
103     bool Sign = V->getElementType()->isIntegerTy()
104                     ? cast<ConstantInt>(Elt)->isNegative()
105                     : cast<ConstantFP>(Elt)->isNegative();
106     BoolVec.push_back(ConstantInt::get(BoolTy, Sign));
107   }
108   return ConstantVector::get(BoolVec);
109 }
110 
111 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
112   unsigned DstAlign = getKnownAlignment(MI->getArgOperand(0), DL, MI, &AC, &DT);
113   unsigned SrcAlign = getKnownAlignment(MI->getArgOperand(1), DL, MI, &AC, &DT);
114   unsigned MinAlign = std::min(DstAlign, SrcAlign);
115   unsigned CopyAlign = MI->getAlignment();
116 
117   if (CopyAlign < MinAlign) {
118     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), MinAlign, false));
119     return MI;
120   }
121 
122   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
123   // load/store.
124   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getArgOperand(2));
125   if (!MemOpLength) return nullptr;
126 
127   // Source and destination pointer types are always "i8*" for intrinsic.  See
128   // if the size is something we can handle with a single primitive load/store.
129   // A single load+store correctly handles overlapping memory in the memmove
130   // case.
131   uint64_t Size = MemOpLength->getLimitedValue();
132   assert(Size && "0-sized memory transferring should be removed already.");
133 
134   if (Size > 8 || (Size&(Size-1)))
135     return nullptr;  // If not 1/2/4/8 bytes, exit.
136 
137   // Use an integer load+store unless we can find something better.
138   unsigned SrcAddrSp =
139     cast<PointerType>(MI->getArgOperand(1)->getType())->getAddressSpace();
140   unsigned DstAddrSp =
141     cast<PointerType>(MI->getArgOperand(0)->getType())->getAddressSpace();
142 
143   IntegerType* IntType = IntegerType::get(MI->getContext(), Size<<3);
144   Type *NewSrcPtrTy = PointerType::get(IntType, SrcAddrSp);
145   Type *NewDstPtrTy = PointerType::get(IntType, DstAddrSp);
146 
147   // Memcpy forces the use of i8* for the source and destination.  That means
148   // that if you're using memcpy to move one double around, you'll get a cast
149   // from double* to i8*.  We'd much rather use a double load+store rather than
150   // an i64 load+store, here because this improves the odds that the source or
151   // dest address will be promotable.  See if we can find a better type than the
152   // integer datatype.
153   Value *StrippedDest = MI->getArgOperand(0)->stripPointerCasts();
154   MDNode *CopyMD = nullptr;
155   if (StrippedDest != MI->getArgOperand(0)) {
156     Type *SrcETy = cast<PointerType>(StrippedDest->getType())
157                                     ->getElementType();
158     if (SrcETy->isSized() && DL.getTypeStoreSize(SrcETy) == Size) {
159       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
160       // down through these levels if so.
161       SrcETy = reduceToSingleValueType(SrcETy);
162 
163       if (SrcETy->isSingleValueType()) {
164         NewSrcPtrTy = PointerType::get(SrcETy, SrcAddrSp);
165         NewDstPtrTy = PointerType::get(SrcETy, DstAddrSp);
166 
167         // If the memcpy has metadata describing the members, see if we can
168         // get the TBAA tag describing our copy.
169         if (MDNode *M = MI->getMetadata(LLVMContext::MD_tbaa_struct)) {
170           if (M->getNumOperands() == 3 && M->getOperand(0) &&
171               mdconst::hasa<ConstantInt>(M->getOperand(0)) &&
172               mdconst::extract<ConstantInt>(M->getOperand(0))->isNullValue() &&
173               M->getOperand(1) &&
174               mdconst::hasa<ConstantInt>(M->getOperand(1)) &&
175               mdconst::extract<ConstantInt>(M->getOperand(1))->getValue() ==
176                   Size &&
177               M->getOperand(2) && isa<MDNode>(M->getOperand(2)))
178             CopyMD = cast<MDNode>(M->getOperand(2));
179         }
180       }
181     }
182   }
183 
184   // If the memcpy/memmove provides better alignment info than we can
185   // infer, use it.
186   SrcAlign = std::max(SrcAlign, CopyAlign);
187   DstAlign = std::max(DstAlign, CopyAlign);
188 
189   Value *Src = Builder->CreateBitCast(MI->getArgOperand(1), NewSrcPtrTy);
190   Value *Dest = Builder->CreateBitCast(MI->getArgOperand(0), NewDstPtrTy);
191   LoadInst *L = Builder->CreateLoad(Src, MI->isVolatile());
192   L->setAlignment(SrcAlign);
193   if (CopyMD)
194     L->setMetadata(LLVMContext::MD_tbaa, CopyMD);
195   MDNode *LoopMemParallelMD =
196     MI->getMetadata(LLVMContext::MD_mem_parallel_loop_access);
197   if (LoopMemParallelMD)
198     L->setMetadata(LLVMContext::MD_mem_parallel_loop_access, LoopMemParallelMD);
199 
200   StoreInst *S = Builder->CreateStore(L, Dest, MI->isVolatile());
201   S->setAlignment(DstAlign);
202   if (CopyMD)
203     S->setMetadata(LLVMContext::MD_tbaa, CopyMD);
204   if (LoopMemParallelMD)
205     S->setMetadata(LLVMContext::MD_mem_parallel_loop_access, LoopMemParallelMD);
206 
207   // Set the size of the copy to 0, it will be deleted on the next iteration.
208   MI->setArgOperand(2, Constant::getNullValue(MemOpLength->getType()));
209   return MI;
210 }
211 
212 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
213   unsigned Alignment = getKnownAlignment(MI->getDest(), DL, MI, &AC, &DT);
214   if (MI->getAlignment() < Alignment) {
215     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
216                                              Alignment, false));
217     return MI;
218   }
219 
220   // Extract the length and alignment and fill if they are constant.
221   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
222   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
223   if (!LenC || !FillC || !FillC->getType()->isIntegerTy(8))
224     return nullptr;
225   uint64_t Len = LenC->getLimitedValue();
226   Alignment = MI->getAlignment();
227   assert(Len && "0-sized memory setting should be removed already.");
228 
229   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
230   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
231     Type *ITy = IntegerType::get(MI->getContext(), Len*8);  // n=1 -> i8.
232 
233     Value *Dest = MI->getDest();
234     unsigned DstAddrSp = cast<PointerType>(Dest->getType())->getAddressSpace();
235     Type *NewDstPtrTy = PointerType::get(ITy, DstAddrSp);
236     Dest = Builder->CreateBitCast(Dest, NewDstPtrTy);
237 
238     // Alignment 0 is identity for alignment 1 for memset, but not store.
239     if (Alignment == 0) Alignment = 1;
240 
241     // Extract the fill value and store.
242     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
243     StoreInst *S = Builder->CreateStore(ConstantInt::get(ITy, Fill), Dest,
244                                         MI->isVolatile());
245     S->setAlignment(Alignment);
246 
247     // Set the size of the copy to 0, it will be deleted on the next iteration.
248     MI->setLength(Constant::getNullValue(LenC->getType()));
249     return MI;
250   }
251 
252   return nullptr;
253 }
254 
255 static Value *simplifyX86immShift(const IntrinsicInst &II,
256                                   InstCombiner::BuilderTy &Builder) {
257   bool LogicalShift = false;
258   bool ShiftLeft = false;
259 
260   switch (II.getIntrinsicID()) {
261   default: llvm_unreachable("Unexpected intrinsic!");
262   case Intrinsic::x86_sse2_psra_d:
263   case Intrinsic::x86_sse2_psra_w:
264   case Intrinsic::x86_sse2_psrai_d:
265   case Intrinsic::x86_sse2_psrai_w:
266   case Intrinsic::x86_avx2_psra_d:
267   case Intrinsic::x86_avx2_psra_w:
268   case Intrinsic::x86_avx2_psrai_d:
269   case Intrinsic::x86_avx2_psrai_w:
270   case Intrinsic::x86_avx512_psra_q_128:
271   case Intrinsic::x86_avx512_psrai_q_128:
272   case Intrinsic::x86_avx512_psra_q_256:
273   case Intrinsic::x86_avx512_psrai_q_256:
274   case Intrinsic::x86_avx512_psra_d_512:
275   case Intrinsic::x86_avx512_psra_q_512:
276   case Intrinsic::x86_avx512_psra_w_512:
277   case Intrinsic::x86_avx512_psrai_d_512:
278   case Intrinsic::x86_avx512_psrai_q_512:
279   case Intrinsic::x86_avx512_psrai_w_512:
280     LogicalShift = false; ShiftLeft = false;
281     break;
282   case Intrinsic::x86_sse2_psrl_d:
283   case Intrinsic::x86_sse2_psrl_q:
284   case Intrinsic::x86_sse2_psrl_w:
285   case Intrinsic::x86_sse2_psrli_d:
286   case Intrinsic::x86_sse2_psrli_q:
287   case Intrinsic::x86_sse2_psrli_w:
288   case Intrinsic::x86_avx2_psrl_d:
289   case Intrinsic::x86_avx2_psrl_q:
290   case Intrinsic::x86_avx2_psrl_w:
291   case Intrinsic::x86_avx2_psrli_d:
292   case Intrinsic::x86_avx2_psrli_q:
293   case Intrinsic::x86_avx2_psrli_w:
294   case Intrinsic::x86_avx512_psrl_d_512:
295   case Intrinsic::x86_avx512_psrl_q_512:
296   case Intrinsic::x86_avx512_psrl_w_512:
297   case Intrinsic::x86_avx512_psrli_d_512:
298   case Intrinsic::x86_avx512_psrli_q_512:
299   case Intrinsic::x86_avx512_psrli_w_512:
300     LogicalShift = true; ShiftLeft = false;
301     break;
302   case Intrinsic::x86_sse2_psll_d:
303   case Intrinsic::x86_sse2_psll_q:
304   case Intrinsic::x86_sse2_psll_w:
305   case Intrinsic::x86_sse2_pslli_d:
306   case Intrinsic::x86_sse2_pslli_q:
307   case Intrinsic::x86_sse2_pslli_w:
308   case Intrinsic::x86_avx2_psll_d:
309   case Intrinsic::x86_avx2_psll_q:
310   case Intrinsic::x86_avx2_psll_w:
311   case Intrinsic::x86_avx2_pslli_d:
312   case Intrinsic::x86_avx2_pslli_q:
313   case Intrinsic::x86_avx2_pslli_w:
314   case Intrinsic::x86_avx512_psll_d_512:
315   case Intrinsic::x86_avx512_psll_q_512:
316   case Intrinsic::x86_avx512_psll_w_512:
317   case Intrinsic::x86_avx512_pslli_d_512:
318   case Intrinsic::x86_avx512_pslli_q_512:
319   case Intrinsic::x86_avx512_pslli_w_512:
320     LogicalShift = true; ShiftLeft = true;
321     break;
322   }
323   assert((LogicalShift || !ShiftLeft) && "Only logical shifts can shift left");
324 
325   // Simplify if count is constant.
326   auto Arg1 = II.getArgOperand(1);
327   auto CAZ = dyn_cast<ConstantAggregateZero>(Arg1);
328   auto CDV = dyn_cast<ConstantDataVector>(Arg1);
329   auto CInt = dyn_cast<ConstantInt>(Arg1);
330   if (!CAZ && !CDV && !CInt)
331     return nullptr;
332 
333   APInt Count(64, 0);
334   if (CDV) {
335     // SSE2/AVX2 uses all the first 64-bits of the 128-bit vector
336     // operand to compute the shift amount.
337     auto VT = cast<VectorType>(CDV->getType());
338     unsigned BitWidth = VT->getElementType()->getPrimitiveSizeInBits();
339     assert((64 % BitWidth) == 0 && "Unexpected packed shift size");
340     unsigned NumSubElts = 64 / BitWidth;
341 
342     // Concatenate the sub-elements to create the 64-bit value.
343     for (unsigned i = 0; i != NumSubElts; ++i) {
344       unsigned SubEltIdx = (NumSubElts - 1) - i;
345       auto SubElt = cast<ConstantInt>(CDV->getElementAsConstant(SubEltIdx));
346       Count = Count.shl(BitWidth);
347       Count |= SubElt->getValue().zextOrTrunc(64);
348     }
349   }
350   else if (CInt)
351     Count = CInt->getValue();
352 
353   auto Vec = II.getArgOperand(0);
354   auto VT = cast<VectorType>(Vec->getType());
355   auto SVT = VT->getElementType();
356   unsigned VWidth = VT->getNumElements();
357   unsigned BitWidth = SVT->getPrimitiveSizeInBits();
358 
359   // If shift-by-zero then just return the original value.
360   if (Count == 0)
361     return Vec;
362 
363   // Handle cases when Shift >= BitWidth.
364   if (Count.uge(BitWidth)) {
365     // If LogicalShift - just return zero.
366     if (LogicalShift)
367       return ConstantAggregateZero::get(VT);
368 
369     // If ArithmeticShift - clamp Shift to (BitWidth - 1).
370     Count = APInt(64, BitWidth - 1);
371   }
372 
373   // Get a constant vector of the same type as the first operand.
374   auto ShiftAmt = ConstantInt::get(SVT, Count.zextOrTrunc(BitWidth));
375   auto ShiftVec = Builder.CreateVectorSplat(VWidth, ShiftAmt);
376 
377   if (ShiftLeft)
378     return Builder.CreateShl(Vec, ShiftVec);
379 
380   if (LogicalShift)
381     return Builder.CreateLShr(Vec, ShiftVec);
382 
383   return Builder.CreateAShr(Vec, ShiftVec);
384 }
385 
386 // Attempt to simplify AVX2 per-element shift intrinsics to a generic IR shift.
387 // Unlike the generic IR shifts, the intrinsics have defined behaviour for out
388 // of range shift amounts (logical - set to zero, arithmetic - splat sign bit).
389 static Value *simplifyX86varShift(const IntrinsicInst &II,
390                                   InstCombiner::BuilderTy &Builder) {
391   bool LogicalShift = false;
392   bool ShiftLeft = false;
393 
394   switch (II.getIntrinsicID()) {
395   default: llvm_unreachable("Unexpected intrinsic!");
396   case Intrinsic::x86_avx2_psrav_d:
397   case Intrinsic::x86_avx2_psrav_d_256:
398   case Intrinsic::x86_avx512_psrav_q_128:
399   case Intrinsic::x86_avx512_psrav_q_256:
400   case Intrinsic::x86_avx512_psrav_d_512:
401   case Intrinsic::x86_avx512_psrav_q_512:
402   case Intrinsic::x86_avx512_psrav_w_128:
403   case Intrinsic::x86_avx512_psrav_w_256:
404   case Intrinsic::x86_avx512_psrav_w_512:
405     LogicalShift = false;
406     ShiftLeft = false;
407     break;
408   case Intrinsic::x86_avx2_psrlv_d:
409   case Intrinsic::x86_avx2_psrlv_d_256:
410   case Intrinsic::x86_avx2_psrlv_q:
411   case Intrinsic::x86_avx2_psrlv_q_256:
412   case Intrinsic::x86_avx512_psrlv_d_512:
413   case Intrinsic::x86_avx512_psrlv_q_512:
414   case Intrinsic::x86_avx512_psrlv_w_128:
415   case Intrinsic::x86_avx512_psrlv_w_256:
416   case Intrinsic::x86_avx512_psrlv_w_512:
417     LogicalShift = true;
418     ShiftLeft = false;
419     break;
420   case Intrinsic::x86_avx2_psllv_d:
421   case Intrinsic::x86_avx2_psllv_d_256:
422   case Intrinsic::x86_avx2_psllv_q:
423   case Intrinsic::x86_avx2_psllv_q_256:
424   case Intrinsic::x86_avx512_psllv_d_512:
425   case Intrinsic::x86_avx512_psllv_q_512:
426   case Intrinsic::x86_avx512_psllv_w_128:
427   case Intrinsic::x86_avx512_psllv_w_256:
428   case Intrinsic::x86_avx512_psllv_w_512:
429     LogicalShift = true;
430     ShiftLeft = true;
431     break;
432   }
433   assert((LogicalShift || !ShiftLeft) && "Only logical shifts can shift left");
434 
435   // Simplify if all shift amounts are constant/undef.
436   auto *CShift = dyn_cast<Constant>(II.getArgOperand(1));
437   if (!CShift)
438     return nullptr;
439 
440   auto Vec = II.getArgOperand(0);
441   auto VT = cast<VectorType>(II.getType());
442   auto SVT = VT->getVectorElementType();
443   int NumElts = VT->getNumElements();
444   int BitWidth = SVT->getIntegerBitWidth();
445 
446   // Collect each element's shift amount.
447   // We also collect special cases: UNDEF = -1, OUT-OF-RANGE = BitWidth.
448   bool AnyOutOfRange = false;
449   SmallVector<int, 8> ShiftAmts;
450   for (int I = 0; I < NumElts; ++I) {
451     auto *CElt = CShift->getAggregateElement(I);
452     if (CElt && isa<UndefValue>(CElt)) {
453       ShiftAmts.push_back(-1);
454       continue;
455     }
456 
457     auto *COp = dyn_cast_or_null<ConstantInt>(CElt);
458     if (!COp)
459       return nullptr;
460 
461     // Handle out of range shifts.
462     // If LogicalShift - set to BitWidth (special case).
463     // If ArithmeticShift - set to (BitWidth - 1) (sign splat).
464     APInt ShiftVal = COp->getValue();
465     if (ShiftVal.uge(BitWidth)) {
466       AnyOutOfRange = LogicalShift;
467       ShiftAmts.push_back(LogicalShift ? BitWidth : BitWidth - 1);
468       continue;
469     }
470 
471     ShiftAmts.push_back((int)ShiftVal.getZExtValue());
472   }
473 
474   // If all elements out of range or UNDEF, return vector of zeros/undefs.
475   // ArithmeticShift should only hit this if they are all UNDEF.
476   auto OutOfRange = [&](int Idx) { return (Idx < 0) || (BitWidth <= Idx); };
477   if (all_of(ShiftAmts, OutOfRange)) {
478     SmallVector<Constant *, 8> ConstantVec;
479     for (int Idx : ShiftAmts) {
480       if (Idx < 0) {
481         ConstantVec.push_back(UndefValue::get(SVT));
482       } else {
483         assert(LogicalShift && "Logical shift expected");
484         ConstantVec.push_back(ConstantInt::getNullValue(SVT));
485       }
486     }
487     return ConstantVector::get(ConstantVec);
488   }
489 
490   // We can't handle only some out of range values with generic logical shifts.
491   if (AnyOutOfRange)
492     return nullptr;
493 
494   // Build the shift amount constant vector.
495   SmallVector<Constant *, 8> ShiftVecAmts;
496   for (int Idx : ShiftAmts) {
497     if (Idx < 0)
498       ShiftVecAmts.push_back(UndefValue::get(SVT));
499     else
500       ShiftVecAmts.push_back(ConstantInt::get(SVT, Idx));
501   }
502   auto ShiftVec = ConstantVector::get(ShiftVecAmts);
503 
504   if (ShiftLeft)
505     return Builder.CreateShl(Vec, ShiftVec);
506 
507   if (LogicalShift)
508     return Builder.CreateLShr(Vec, ShiftVec);
509 
510   return Builder.CreateAShr(Vec, ShiftVec);
511 }
512 
513 static Value *simplifyX86movmsk(const IntrinsicInst &II,
514                                 InstCombiner::BuilderTy &Builder) {
515   Value *Arg = II.getArgOperand(0);
516   Type *ResTy = II.getType();
517   Type *ArgTy = Arg->getType();
518 
519   // movmsk(undef) -> zero as we must ensure the upper bits are zero.
520   if (isa<UndefValue>(Arg))
521     return Constant::getNullValue(ResTy);
522 
523   // We can't easily peek through x86_mmx types.
524   if (!ArgTy->isVectorTy())
525     return nullptr;
526 
527   auto *C = dyn_cast<Constant>(Arg);
528   if (!C)
529     return nullptr;
530 
531   // Extract signbits of the vector input and pack into integer result.
532   APInt Result(ResTy->getPrimitiveSizeInBits(), 0);
533   for (unsigned I = 0, E = ArgTy->getVectorNumElements(); I != E; ++I) {
534     auto *COp = C->getAggregateElement(I);
535     if (!COp)
536       return nullptr;
537     if (isa<UndefValue>(COp))
538       continue;
539 
540     auto *CInt = dyn_cast<ConstantInt>(COp);
541     auto *CFp = dyn_cast<ConstantFP>(COp);
542     if (!CInt && !CFp)
543       return nullptr;
544 
545     if ((CInt && CInt->isNegative()) || (CFp && CFp->isNegative()))
546       Result.setBit(I);
547   }
548 
549   return Constant::getIntegerValue(ResTy, Result);
550 }
551 
552 static Value *simplifyX86insertps(const IntrinsicInst &II,
553                                   InstCombiner::BuilderTy &Builder) {
554   auto *CInt = dyn_cast<ConstantInt>(II.getArgOperand(2));
555   if (!CInt)
556     return nullptr;
557 
558   VectorType *VecTy = cast<VectorType>(II.getType());
559   assert(VecTy->getNumElements() == 4 && "insertps with wrong vector type");
560 
561   // The immediate permute control byte looks like this:
562   //    [3:0] - zero mask for each 32-bit lane
563   //    [5:4] - select one 32-bit destination lane
564   //    [7:6] - select one 32-bit source lane
565 
566   uint8_t Imm = CInt->getZExtValue();
567   uint8_t ZMask = Imm & 0xf;
568   uint8_t DestLane = (Imm >> 4) & 0x3;
569   uint8_t SourceLane = (Imm >> 6) & 0x3;
570 
571   ConstantAggregateZero *ZeroVector = ConstantAggregateZero::get(VecTy);
572 
573   // If all zero mask bits are set, this was just a weird way to
574   // generate a zero vector.
575   if (ZMask == 0xf)
576     return ZeroVector;
577 
578   // Initialize by passing all of the first source bits through.
579   uint32_t ShuffleMask[4] = { 0, 1, 2, 3 };
580 
581   // We may replace the second operand with the zero vector.
582   Value *V1 = II.getArgOperand(1);
583 
584   if (ZMask) {
585     // If the zero mask is being used with a single input or the zero mask
586     // overrides the destination lane, this is a shuffle with the zero vector.
587     if ((II.getArgOperand(0) == II.getArgOperand(1)) ||
588         (ZMask & (1 << DestLane))) {
589       V1 = ZeroVector;
590       // We may still move 32-bits of the first source vector from one lane
591       // to another.
592       ShuffleMask[DestLane] = SourceLane;
593       // The zero mask may override the previous insert operation.
594       for (unsigned i = 0; i < 4; ++i)
595         if ((ZMask >> i) & 0x1)
596           ShuffleMask[i] = i + 4;
597     } else {
598       // TODO: Model this case as 2 shuffles or a 'logical and' plus shuffle?
599       return nullptr;
600     }
601   } else {
602     // Replace the selected destination lane with the selected source lane.
603     ShuffleMask[DestLane] = SourceLane + 4;
604   }
605 
606   return Builder.CreateShuffleVector(II.getArgOperand(0), V1, ShuffleMask);
607 }
608 
609 /// Attempt to simplify SSE4A EXTRQ/EXTRQI instructions using constant folding
610 /// or conversion to a shuffle vector.
611 static Value *simplifyX86extrq(IntrinsicInst &II, Value *Op0,
612                                ConstantInt *CILength, ConstantInt *CIIndex,
613                                InstCombiner::BuilderTy &Builder) {
614   auto LowConstantHighUndef = [&](uint64_t Val) {
615     Type *IntTy64 = Type::getInt64Ty(II.getContext());
616     Constant *Args[] = {ConstantInt::get(IntTy64, Val),
617                         UndefValue::get(IntTy64)};
618     return ConstantVector::get(Args);
619   };
620 
621   // See if we're dealing with constant values.
622   Constant *C0 = dyn_cast<Constant>(Op0);
623   ConstantInt *CI0 =
624       C0 ? dyn_cast_or_null<ConstantInt>(C0->getAggregateElement((unsigned)0))
625          : nullptr;
626 
627   // Attempt to constant fold.
628   if (CILength && CIIndex) {
629     // From AMD documentation: "The bit index and field length are each six
630     // bits in length other bits of the field are ignored."
631     APInt APIndex = CIIndex->getValue().zextOrTrunc(6);
632     APInt APLength = CILength->getValue().zextOrTrunc(6);
633 
634     unsigned Index = APIndex.getZExtValue();
635 
636     // From AMD documentation: "a value of zero in the field length is
637     // defined as length of 64".
638     unsigned Length = APLength == 0 ? 64 : APLength.getZExtValue();
639 
640     // From AMD documentation: "If the sum of the bit index + length field
641     // is greater than 64, the results are undefined".
642     unsigned End = Index + Length;
643 
644     // Note that both field index and field length are 8-bit quantities.
645     // Since variables 'Index' and 'Length' are unsigned values
646     // obtained from zero-extending field index and field length
647     // respectively, their sum should never wrap around.
648     if (End > 64)
649       return UndefValue::get(II.getType());
650 
651     // If we are inserting whole bytes, we can convert this to a shuffle.
652     // Lowering can recognize EXTRQI shuffle masks.
653     if ((Length % 8) == 0 && (Index % 8) == 0) {
654       // Convert bit indices to byte indices.
655       Length /= 8;
656       Index /= 8;
657 
658       Type *IntTy8 = Type::getInt8Ty(II.getContext());
659       Type *IntTy32 = Type::getInt32Ty(II.getContext());
660       VectorType *ShufTy = VectorType::get(IntTy8, 16);
661 
662       SmallVector<Constant *, 16> ShuffleMask;
663       for (int i = 0; i != (int)Length; ++i)
664         ShuffleMask.push_back(
665             Constant::getIntegerValue(IntTy32, APInt(32, i + Index)));
666       for (int i = Length; i != 8; ++i)
667         ShuffleMask.push_back(
668             Constant::getIntegerValue(IntTy32, APInt(32, i + 16)));
669       for (int i = 8; i != 16; ++i)
670         ShuffleMask.push_back(UndefValue::get(IntTy32));
671 
672       Value *SV = Builder.CreateShuffleVector(
673           Builder.CreateBitCast(Op0, ShufTy),
674           ConstantAggregateZero::get(ShufTy), ConstantVector::get(ShuffleMask));
675       return Builder.CreateBitCast(SV, II.getType());
676     }
677 
678     // Constant Fold - shift Index'th bit to lowest position and mask off
679     // Length bits.
680     if (CI0) {
681       APInt Elt = CI0->getValue();
682       Elt = Elt.lshr(Index).zextOrTrunc(Length);
683       return LowConstantHighUndef(Elt.getZExtValue());
684     }
685 
686     // If we were an EXTRQ call, we'll save registers if we convert to EXTRQI.
687     if (II.getIntrinsicID() == Intrinsic::x86_sse4a_extrq) {
688       Value *Args[] = {Op0, CILength, CIIndex};
689       Module *M = II.getModule();
690       Value *F = Intrinsic::getDeclaration(M, Intrinsic::x86_sse4a_extrqi);
691       return Builder.CreateCall(F, Args);
692     }
693   }
694 
695   // Constant Fold - extraction from zero is always {zero, undef}.
696   if (CI0 && CI0->equalsInt(0))
697     return LowConstantHighUndef(0);
698 
699   return nullptr;
700 }
701 
702 /// Attempt to simplify SSE4A INSERTQ/INSERTQI instructions using constant
703 /// folding or conversion to a shuffle vector.
704 static Value *simplifyX86insertq(IntrinsicInst &II, Value *Op0, Value *Op1,
705                                  APInt APLength, APInt APIndex,
706                                  InstCombiner::BuilderTy &Builder) {
707   // From AMD documentation: "The bit index and field length are each six bits
708   // in length other bits of the field are ignored."
709   APIndex = APIndex.zextOrTrunc(6);
710   APLength = APLength.zextOrTrunc(6);
711 
712   // Attempt to constant fold.
713   unsigned Index = APIndex.getZExtValue();
714 
715   // From AMD documentation: "a value of zero in the field length is
716   // defined as length of 64".
717   unsigned Length = APLength == 0 ? 64 : APLength.getZExtValue();
718 
719   // From AMD documentation: "If the sum of the bit index + length field
720   // is greater than 64, the results are undefined".
721   unsigned End = Index + Length;
722 
723   // Note that both field index and field length are 8-bit quantities.
724   // Since variables 'Index' and 'Length' are unsigned values
725   // obtained from zero-extending field index and field length
726   // respectively, their sum should never wrap around.
727   if (End > 64)
728     return UndefValue::get(II.getType());
729 
730   // If we are inserting whole bytes, we can convert this to a shuffle.
731   // Lowering can recognize INSERTQI shuffle masks.
732   if ((Length % 8) == 0 && (Index % 8) == 0) {
733     // Convert bit indices to byte indices.
734     Length /= 8;
735     Index /= 8;
736 
737     Type *IntTy8 = Type::getInt8Ty(II.getContext());
738     Type *IntTy32 = Type::getInt32Ty(II.getContext());
739     VectorType *ShufTy = VectorType::get(IntTy8, 16);
740 
741     SmallVector<Constant *, 16> ShuffleMask;
742     for (int i = 0; i != (int)Index; ++i)
743       ShuffleMask.push_back(Constant::getIntegerValue(IntTy32, APInt(32, i)));
744     for (int i = 0; i != (int)Length; ++i)
745       ShuffleMask.push_back(
746           Constant::getIntegerValue(IntTy32, APInt(32, i + 16)));
747     for (int i = Index + Length; i != 8; ++i)
748       ShuffleMask.push_back(Constant::getIntegerValue(IntTy32, APInt(32, i)));
749     for (int i = 8; i != 16; ++i)
750       ShuffleMask.push_back(UndefValue::get(IntTy32));
751 
752     Value *SV = Builder.CreateShuffleVector(Builder.CreateBitCast(Op0, ShufTy),
753                                             Builder.CreateBitCast(Op1, ShufTy),
754                                             ConstantVector::get(ShuffleMask));
755     return Builder.CreateBitCast(SV, II.getType());
756   }
757 
758   // See if we're dealing with constant values.
759   Constant *C0 = dyn_cast<Constant>(Op0);
760   Constant *C1 = dyn_cast<Constant>(Op1);
761   ConstantInt *CI00 =
762       C0 ? dyn_cast_or_null<ConstantInt>(C0->getAggregateElement((unsigned)0))
763          : nullptr;
764   ConstantInt *CI10 =
765       C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)0))
766          : nullptr;
767 
768   // Constant Fold - insert bottom Length bits starting at the Index'th bit.
769   if (CI00 && CI10) {
770     APInt V00 = CI00->getValue();
771     APInt V10 = CI10->getValue();
772     APInt Mask = APInt::getLowBitsSet(64, Length).shl(Index);
773     V00 = V00 & ~Mask;
774     V10 = V10.zextOrTrunc(Length).zextOrTrunc(64).shl(Index);
775     APInt Val = V00 | V10;
776     Type *IntTy64 = Type::getInt64Ty(II.getContext());
777     Constant *Args[] = {ConstantInt::get(IntTy64, Val.getZExtValue()),
778                         UndefValue::get(IntTy64)};
779     return ConstantVector::get(Args);
780   }
781 
782   // If we were an INSERTQ call, we'll save demanded elements if we convert to
783   // INSERTQI.
784   if (II.getIntrinsicID() == Intrinsic::x86_sse4a_insertq) {
785     Type *IntTy8 = Type::getInt8Ty(II.getContext());
786     Constant *CILength = ConstantInt::get(IntTy8, Length, false);
787     Constant *CIIndex = ConstantInt::get(IntTy8, Index, false);
788 
789     Value *Args[] = {Op0, Op1, CILength, CIIndex};
790     Module *M = II.getModule();
791     Value *F = Intrinsic::getDeclaration(M, Intrinsic::x86_sse4a_insertqi);
792     return Builder.CreateCall(F, Args);
793   }
794 
795   return nullptr;
796 }
797 
798 /// Attempt to convert pshufb* to shufflevector if the mask is constant.
799 static Value *simplifyX86pshufb(const IntrinsicInst &II,
800                                 InstCombiner::BuilderTy &Builder) {
801   Constant *V = dyn_cast<Constant>(II.getArgOperand(1));
802   if (!V)
803     return nullptr;
804 
805   auto *VecTy = cast<VectorType>(II.getType());
806   auto *MaskEltTy = Type::getInt32Ty(II.getContext());
807   unsigned NumElts = VecTy->getNumElements();
808   assert((NumElts == 16 || NumElts == 32 || NumElts == 64) &&
809          "Unexpected number of elements in shuffle mask!");
810 
811   // Construct a shuffle mask from constant integers or UNDEFs.
812   Constant *Indexes[64] = {nullptr};
813 
814   // Each byte in the shuffle control mask forms an index to permute the
815   // corresponding byte in the destination operand.
816   for (unsigned I = 0; I < NumElts; ++I) {
817     Constant *COp = V->getAggregateElement(I);
818     if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
819       return nullptr;
820 
821     if (isa<UndefValue>(COp)) {
822       Indexes[I] = UndefValue::get(MaskEltTy);
823       continue;
824     }
825 
826     int8_t Index = cast<ConstantInt>(COp)->getValue().getZExtValue();
827 
828     // If the most significant bit (bit[7]) of each byte of the shuffle
829     // control mask is set, then zero is written in the result byte.
830     // The zero vector is in the right-hand side of the resulting
831     // shufflevector.
832 
833     // The value of each index for the high 128-bit lane is the least
834     // significant 4 bits of the respective shuffle control byte.
835     Index = ((Index < 0) ? NumElts : Index & 0x0F) + (I & 0xF0);
836     Indexes[I] = ConstantInt::get(MaskEltTy, Index);
837   }
838 
839   auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, NumElts));
840   auto V1 = II.getArgOperand(0);
841   auto V2 = Constant::getNullValue(VecTy);
842   return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
843 }
844 
845 /// Attempt to convert vpermilvar* to shufflevector if the mask is constant.
846 static Value *simplifyX86vpermilvar(const IntrinsicInst &II,
847                                     InstCombiner::BuilderTy &Builder) {
848   Constant *V = dyn_cast<Constant>(II.getArgOperand(1));
849   if (!V)
850     return nullptr;
851 
852   auto *VecTy = cast<VectorType>(II.getType());
853   auto *MaskEltTy = Type::getInt32Ty(II.getContext());
854   unsigned NumElts = VecTy->getVectorNumElements();
855   bool IsPD = VecTy->getScalarType()->isDoubleTy();
856   unsigned NumLaneElts = IsPD ? 2 : 4;
857   assert(NumElts == 16 || NumElts == 8 || NumElts == 4 || NumElts == 2);
858 
859   // Construct a shuffle mask from constant integers or UNDEFs.
860   Constant *Indexes[16] = {nullptr};
861 
862   // The intrinsics only read one or two bits, clear the rest.
863   for (unsigned I = 0; I < NumElts; ++I) {
864     Constant *COp = V->getAggregateElement(I);
865     if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
866       return nullptr;
867 
868     if (isa<UndefValue>(COp)) {
869       Indexes[I] = UndefValue::get(MaskEltTy);
870       continue;
871     }
872 
873     APInt Index = cast<ConstantInt>(COp)->getValue();
874     Index = Index.zextOrTrunc(32).getLoBits(2);
875 
876     // The PD variants uses bit 1 to select per-lane element index, so
877     // shift down to convert to generic shuffle mask index.
878     if (IsPD)
879       Index = Index.lshr(1);
880 
881     // The _256 variants are a bit trickier since the mask bits always index
882     // into the corresponding 128 half. In order to convert to a generic
883     // shuffle, we have to make that explicit.
884     Index += APInt(32, (I / NumLaneElts) * NumLaneElts);
885 
886     Indexes[I] = ConstantInt::get(MaskEltTy, Index);
887   }
888 
889   auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, NumElts));
890   auto V1 = II.getArgOperand(0);
891   auto V2 = UndefValue::get(V1->getType());
892   return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
893 }
894 
895 /// Attempt to convert vpermd/vpermps to shufflevector if the mask is constant.
896 static Value *simplifyX86vpermv(const IntrinsicInst &II,
897                                 InstCombiner::BuilderTy &Builder) {
898   auto *V = dyn_cast<Constant>(II.getArgOperand(1));
899   if (!V)
900     return nullptr;
901 
902   auto *VecTy = cast<VectorType>(II.getType());
903   auto *MaskEltTy = Type::getInt32Ty(II.getContext());
904   unsigned Size = VecTy->getNumElements();
905   assert(Size == 8 && "Unexpected shuffle mask size");
906 
907   // Construct a shuffle mask from constant integers or UNDEFs.
908   Constant *Indexes[8] = {nullptr};
909 
910   for (unsigned I = 0; I < Size; ++I) {
911     Constant *COp = V->getAggregateElement(I);
912     if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
913       return nullptr;
914 
915     if (isa<UndefValue>(COp)) {
916       Indexes[I] = UndefValue::get(MaskEltTy);
917       continue;
918     }
919 
920     APInt Index = cast<ConstantInt>(COp)->getValue();
921     Index = Index.zextOrTrunc(32).getLoBits(3);
922     Indexes[I] = ConstantInt::get(MaskEltTy, Index);
923   }
924 
925   auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, Size));
926   auto V1 = II.getArgOperand(0);
927   auto V2 = UndefValue::get(VecTy);
928   return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
929 }
930 
931 /// The shuffle mask for a perm2*128 selects any two halves of two 256-bit
932 /// source vectors, unless a zero bit is set. If a zero bit is set,
933 /// then ignore that half of the mask and clear that half of the vector.
934 static Value *simplifyX86vperm2(const IntrinsicInst &II,
935                                 InstCombiner::BuilderTy &Builder) {
936   auto *CInt = dyn_cast<ConstantInt>(II.getArgOperand(2));
937   if (!CInt)
938     return nullptr;
939 
940   VectorType *VecTy = cast<VectorType>(II.getType());
941   ConstantAggregateZero *ZeroVector = ConstantAggregateZero::get(VecTy);
942 
943   // The immediate permute control byte looks like this:
944   //    [1:0] - select 128 bits from sources for low half of destination
945   //    [2]   - ignore
946   //    [3]   - zero low half of destination
947   //    [5:4] - select 128 bits from sources for high half of destination
948   //    [6]   - ignore
949   //    [7]   - zero high half of destination
950 
951   uint8_t Imm = CInt->getZExtValue();
952 
953   bool LowHalfZero = Imm & 0x08;
954   bool HighHalfZero = Imm & 0x80;
955 
956   // If both zero mask bits are set, this was just a weird way to
957   // generate a zero vector.
958   if (LowHalfZero && HighHalfZero)
959     return ZeroVector;
960 
961   // If 0 or 1 zero mask bits are set, this is a simple shuffle.
962   unsigned NumElts = VecTy->getNumElements();
963   unsigned HalfSize = NumElts / 2;
964   SmallVector<uint32_t, 8> ShuffleMask(NumElts);
965 
966   // The high bit of the selection field chooses the 1st or 2nd operand.
967   bool LowInputSelect = Imm & 0x02;
968   bool HighInputSelect = Imm & 0x20;
969 
970   // The low bit of the selection field chooses the low or high half
971   // of the selected operand.
972   bool LowHalfSelect = Imm & 0x01;
973   bool HighHalfSelect = Imm & 0x10;
974 
975   // Determine which operand(s) are actually in use for this instruction.
976   Value *V0 = LowInputSelect ? II.getArgOperand(1) : II.getArgOperand(0);
977   Value *V1 = HighInputSelect ? II.getArgOperand(1) : II.getArgOperand(0);
978 
979   // If needed, replace operands based on zero mask.
980   V0 = LowHalfZero ? ZeroVector : V0;
981   V1 = HighHalfZero ? ZeroVector : V1;
982 
983   // Permute low half of result.
984   unsigned StartIndex = LowHalfSelect ? HalfSize : 0;
985   for (unsigned i = 0; i < HalfSize; ++i)
986     ShuffleMask[i] = StartIndex + i;
987 
988   // Permute high half of result.
989   StartIndex = HighHalfSelect ? HalfSize : 0;
990   StartIndex += NumElts;
991   for (unsigned i = 0; i < HalfSize; ++i)
992     ShuffleMask[i + HalfSize] = StartIndex + i;
993 
994   return Builder.CreateShuffleVector(V0, V1, ShuffleMask);
995 }
996 
997 /// Decode XOP integer vector comparison intrinsics.
998 static Value *simplifyX86vpcom(const IntrinsicInst &II,
999                                InstCombiner::BuilderTy &Builder,
1000                                bool IsSigned) {
1001   if (auto *CInt = dyn_cast<ConstantInt>(II.getArgOperand(2))) {
1002     uint64_t Imm = CInt->getZExtValue() & 0x7;
1003     VectorType *VecTy = cast<VectorType>(II.getType());
1004     CmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1005 
1006     switch (Imm) {
1007     case 0x0:
1008       Pred = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1009       break;
1010     case 0x1:
1011       Pred = IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
1012       break;
1013     case 0x2:
1014       Pred = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1015       break;
1016     case 0x3:
1017       Pred = IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
1018       break;
1019     case 0x4:
1020       Pred = ICmpInst::ICMP_EQ; break;
1021     case 0x5:
1022       Pred = ICmpInst::ICMP_NE; break;
1023     case 0x6:
1024       return ConstantInt::getSigned(VecTy, 0); // FALSE
1025     case 0x7:
1026       return ConstantInt::getSigned(VecTy, -1); // TRUE
1027     }
1028 
1029     if (Value *Cmp = Builder.CreateICmp(Pred, II.getArgOperand(0),
1030                                         II.getArgOperand(1)))
1031       return Builder.CreateSExtOrTrunc(Cmp, VecTy);
1032   }
1033   return nullptr;
1034 }
1035 
1036 static Value *simplifyMinnumMaxnum(const IntrinsicInst &II) {
1037   Value *Arg0 = II.getArgOperand(0);
1038   Value *Arg1 = II.getArgOperand(1);
1039 
1040   // fmin(x, x) -> x
1041   if (Arg0 == Arg1)
1042     return Arg0;
1043 
1044   const auto *C1 = dyn_cast<ConstantFP>(Arg1);
1045 
1046   // fmin(x, nan) -> x
1047   if (C1 && C1->isNaN())
1048     return Arg0;
1049 
1050   // This is the value because if undef were NaN, we would return the other
1051   // value and cannot return a NaN unless both operands are.
1052   //
1053   // fmin(undef, x) -> x
1054   if (isa<UndefValue>(Arg0))
1055     return Arg1;
1056 
1057   // fmin(x, undef) -> x
1058   if (isa<UndefValue>(Arg1))
1059     return Arg0;
1060 
1061   Value *X = nullptr;
1062   Value *Y = nullptr;
1063   if (II.getIntrinsicID() == Intrinsic::minnum) {
1064     // fmin(x, fmin(x, y)) -> fmin(x, y)
1065     // fmin(y, fmin(x, y)) -> fmin(x, y)
1066     if (match(Arg1, m_FMin(m_Value(X), m_Value(Y)))) {
1067       if (Arg0 == X || Arg0 == Y)
1068         return Arg1;
1069     }
1070 
1071     // fmin(fmin(x, y), x) -> fmin(x, y)
1072     // fmin(fmin(x, y), y) -> fmin(x, y)
1073     if (match(Arg0, m_FMin(m_Value(X), m_Value(Y)))) {
1074       if (Arg1 == X || Arg1 == Y)
1075         return Arg0;
1076     }
1077 
1078     // TODO: fmin(nnan x, inf) -> x
1079     // TODO: fmin(nnan ninf x, flt_max) -> x
1080     if (C1 && C1->isInfinity()) {
1081       // fmin(x, -inf) -> -inf
1082       if (C1->isNegative())
1083         return Arg1;
1084     }
1085   } else {
1086     assert(II.getIntrinsicID() == Intrinsic::maxnum);
1087     // fmax(x, fmax(x, y)) -> fmax(x, y)
1088     // fmax(y, fmax(x, y)) -> fmax(x, y)
1089     if (match(Arg1, m_FMax(m_Value(X), m_Value(Y)))) {
1090       if (Arg0 == X || Arg0 == Y)
1091         return Arg1;
1092     }
1093 
1094     // fmax(fmax(x, y), x) -> fmax(x, y)
1095     // fmax(fmax(x, y), y) -> fmax(x, y)
1096     if (match(Arg0, m_FMax(m_Value(X), m_Value(Y)))) {
1097       if (Arg1 == X || Arg1 == Y)
1098         return Arg0;
1099     }
1100 
1101     // TODO: fmax(nnan x, -inf) -> x
1102     // TODO: fmax(nnan ninf x, -flt_max) -> x
1103     if (C1 && C1->isInfinity()) {
1104       // fmax(x, inf) -> inf
1105       if (!C1->isNegative())
1106         return Arg1;
1107     }
1108   }
1109   return nullptr;
1110 }
1111 
1112 static bool maskIsAllOneOrUndef(Value *Mask) {
1113   auto *ConstMask = dyn_cast<Constant>(Mask);
1114   if (!ConstMask)
1115     return false;
1116   if (ConstMask->isAllOnesValue() || isa<UndefValue>(ConstMask))
1117     return true;
1118   for (unsigned I = 0, E = ConstMask->getType()->getVectorNumElements(); I != E;
1119        ++I) {
1120     if (auto *MaskElt = ConstMask->getAggregateElement(I))
1121       if (MaskElt->isAllOnesValue() || isa<UndefValue>(MaskElt))
1122         continue;
1123     return false;
1124   }
1125   return true;
1126 }
1127 
1128 static Value *simplifyMaskedLoad(const IntrinsicInst &II,
1129                                  InstCombiner::BuilderTy &Builder) {
1130   // If the mask is all ones or undefs, this is a plain vector load of the 1st
1131   // argument.
1132   if (maskIsAllOneOrUndef(II.getArgOperand(2))) {
1133     Value *LoadPtr = II.getArgOperand(0);
1134     unsigned Alignment = cast<ConstantInt>(II.getArgOperand(1))->getZExtValue();
1135     return Builder.CreateAlignedLoad(LoadPtr, Alignment, "unmaskedload");
1136   }
1137 
1138   return nullptr;
1139 }
1140 
1141 static Instruction *simplifyMaskedStore(IntrinsicInst &II, InstCombiner &IC) {
1142   auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3));
1143   if (!ConstMask)
1144     return nullptr;
1145 
1146   // If the mask is all zeros, this instruction does nothing.
1147   if (ConstMask->isNullValue())
1148     return IC.eraseInstFromFunction(II);
1149 
1150   // If the mask is all ones, this is a plain vector store of the 1st argument.
1151   if (ConstMask->isAllOnesValue()) {
1152     Value *StorePtr = II.getArgOperand(1);
1153     unsigned Alignment = cast<ConstantInt>(II.getArgOperand(2))->getZExtValue();
1154     return new StoreInst(II.getArgOperand(0), StorePtr, false, Alignment);
1155   }
1156 
1157   return nullptr;
1158 }
1159 
1160 static Instruction *simplifyMaskedGather(IntrinsicInst &II, InstCombiner &IC) {
1161   // If the mask is all zeros, return the "passthru" argument of the gather.
1162   auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(2));
1163   if (ConstMask && ConstMask->isNullValue())
1164     return IC.replaceInstUsesWith(II, II.getArgOperand(3));
1165 
1166   return nullptr;
1167 }
1168 
1169 static Instruction *simplifyMaskedScatter(IntrinsicInst &II, InstCombiner &IC) {
1170   // If the mask is all zeros, a scatter does nothing.
1171   auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3));
1172   if (ConstMask && ConstMask->isNullValue())
1173     return IC.eraseInstFromFunction(II);
1174 
1175   return nullptr;
1176 }
1177 
1178 static Instruction *foldCttzCtlz(IntrinsicInst &II, InstCombiner &IC) {
1179   assert((II.getIntrinsicID() == Intrinsic::cttz ||
1180           II.getIntrinsicID() == Intrinsic::ctlz) &&
1181          "Expected cttz or ctlz intrinsic");
1182   Value *Op0 = II.getArgOperand(0);
1183   // FIXME: Try to simplify vectors of integers.
1184   auto *IT = dyn_cast<IntegerType>(Op0->getType());
1185   if (!IT)
1186     return nullptr;
1187 
1188   unsigned BitWidth = IT->getBitWidth();
1189   APInt KnownZero(BitWidth, 0);
1190   APInt KnownOne(BitWidth, 0);
1191   IC.computeKnownBits(Op0, KnownZero, KnownOne, 0, &II);
1192 
1193   // Create a mask for bits above (ctlz) or below (cttz) the first known one.
1194   bool IsTZ = II.getIntrinsicID() == Intrinsic::cttz;
1195   unsigned NumMaskBits = IsTZ ? KnownOne.countTrailingZeros()
1196                               : KnownOne.countLeadingZeros();
1197   APInt Mask = IsTZ ? APInt::getLowBitsSet(BitWidth, NumMaskBits)
1198                     : APInt::getHighBitsSet(BitWidth, NumMaskBits);
1199 
1200   // If all bits above (ctlz) or below (cttz) the first known one are known
1201   // zero, this value is constant.
1202   // FIXME: This should be in InstSimplify because we're replacing an
1203   // instruction with a constant.
1204   if ((Mask & KnownZero) == Mask) {
1205     auto *C = ConstantInt::get(IT, APInt(BitWidth, NumMaskBits));
1206     return IC.replaceInstUsesWith(II, C);
1207   }
1208 
1209   // If the input to cttz/ctlz is known to be non-zero,
1210   // then change the 'ZeroIsUndef' parameter to 'true'
1211   // because we know the zero behavior can't affect the result.
1212   if (KnownOne != 0 || isKnownNonZero(Op0, IC.getDataLayout())) {
1213     if (!match(II.getArgOperand(1), m_One())) {
1214       II.setOperand(1, IC.Builder->getTrue());
1215       return &II;
1216     }
1217   }
1218 
1219   return nullptr;
1220 }
1221 
1222 // TODO: If the x86 backend knew how to convert a bool vector mask back to an
1223 // XMM register mask efficiently, we could transform all x86 masked intrinsics
1224 // to LLVM masked intrinsics and remove the x86 masked intrinsic defs.
1225 static Instruction *simplifyX86MaskedLoad(IntrinsicInst &II, InstCombiner &IC) {
1226   Value *Ptr = II.getOperand(0);
1227   Value *Mask = II.getOperand(1);
1228   Constant *ZeroVec = Constant::getNullValue(II.getType());
1229 
1230   // Special case a zero mask since that's not a ConstantDataVector.
1231   // This masked load instruction creates a zero vector.
1232   if (isa<ConstantAggregateZero>(Mask))
1233     return IC.replaceInstUsesWith(II, ZeroVec);
1234 
1235   auto *ConstMask = dyn_cast<ConstantDataVector>(Mask);
1236   if (!ConstMask)
1237     return nullptr;
1238 
1239   // The mask is constant. Convert this x86 intrinsic to the LLVM instrinsic
1240   // to allow target-independent optimizations.
1241 
1242   // First, cast the x86 intrinsic scalar pointer to a vector pointer to match
1243   // the LLVM intrinsic definition for the pointer argument.
1244   unsigned AddrSpace = cast<PointerType>(Ptr->getType())->getAddressSpace();
1245   PointerType *VecPtrTy = PointerType::get(II.getType(), AddrSpace);
1246   Value *PtrCast = IC.Builder->CreateBitCast(Ptr, VecPtrTy, "castvec");
1247 
1248   // Second, convert the x86 XMM integer vector mask to a vector of bools based
1249   // on each element's most significant bit (the sign bit).
1250   Constant *BoolMask = getNegativeIsTrueBoolVec(ConstMask);
1251 
1252   // The pass-through vector for an x86 masked load is a zero vector.
1253   CallInst *NewMaskedLoad =
1254       IC.Builder->CreateMaskedLoad(PtrCast, 1, BoolMask, ZeroVec);
1255   return IC.replaceInstUsesWith(II, NewMaskedLoad);
1256 }
1257 
1258 // TODO: If the x86 backend knew how to convert a bool vector mask back to an
1259 // XMM register mask efficiently, we could transform all x86 masked intrinsics
1260 // to LLVM masked intrinsics and remove the x86 masked intrinsic defs.
1261 static bool simplifyX86MaskedStore(IntrinsicInst &II, InstCombiner &IC) {
1262   Value *Ptr = II.getOperand(0);
1263   Value *Mask = II.getOperand(1);
1264   Value *Vec = II.getOperand(2);
1265 
1266   // Special case a zero mask since that's not a ConstantDataVector:
1267   // this masked store instruction does nothing.
1268   if (isa<ConstantAggregateZero>(Mask)) {
1269     IC.eraseInstFromFunction(II);
1270     return true;
1271   }
1272 
1273   // The SSE2 version is too weird (eg, unaligned but non-temporal) to do
1274   // anything else at this level.
1275   if (II.getIntrinsicID() == Intrinsic::x86_sse2_maskmov_dqu)
1276     return false;
1277 
1278   auto *ConstMask = dyn_cast<ConstantDataVector>(Mask);
1279   if (!ConstMask)
1280     return false;
1281 
1282   // The mask is constant. Convert this x86 intrinsic to the LLVM instrinsic
1283   // to allow target-independent optimizations.
1284 
1285   // First, cast the x86 intrinsic scalar pointer to a vector pointer to match
1286   // the LLVM intrinsic definition for the pointer argument.
1287   unsigned AddrSpace = cast<PointerType>(Ptr->getType())->getAddressSpace();
1288   PointerType *VecPtrTy = PointerType::get(Vec->getType(), AddrSpace);
1289   Value *PtrCast = IC.Builder->CreateBitCast(Ptr, VecPtrTy, "castvec");
1290 
1291   // Second, convert the x86 XMM integer vector mask to a vector of bools based
1292   // on each element's most significant bit (the sign bit).
1293   Constant *BoolMask = getNegativeIsTrueBoolVec(ConstMask);
1294 
1295   IC.Builder->CreateMaskedStore(Vec, PtrCast, 1, BoolMask);
1296 
1297   // 'Replace uses' doesn't work for stores. Erase the original masked store.
1298   IC.eraseInstFromFunction(II);
1299   return true;
1300 }
1301 
1302 // Returns true iff the 2 intrinsics have the same operands, limiting the
1303 // comparison to the first NumOperands.
1304 static bool haveSameOperands(const IntrinsicInst &I, const IntrinsicInst &E,
1305                              unsigned NumOperands) {
1306   assert(I.getNumArgOperands() >= NumOperands && "Not enough operands");
1307   assert(E.getNumArgOperands() >= NumOperands && "Not enough operands");
1308   for (unsigned i = 0; i < NumOperands; i++)
1309     if (I.getArgOperand(i) != E.getArgOperand(i))
1310       return false;
1311   return true;
1312 }
1313 
1314 // Remove trivially empty start/end intrinsic ranges, i.e. a start
1315 // immediately followed by an end (ignoring debuginfo or other
1316 // start/end intrinsics in between). As this handles only the most trivial
1317 // cases, tracking the nesting level is not needed:
1318 //
1319 //   call @llvm.foo.start(i1 0) ; &I
1320 //   call @llvm.foo.start(i1 0)
1321 //   call @llvm.foo.end(i1 0) ; This one will not be skipped: it will be removed
1322 //   call @llvm.foo.end(i1 0)
1323 static bool removeTriviallyEmptyRange(IntrinsicInst &I, unsigned StartID,
1324                                       unsigned EndID, InstCombiner &IC) {
1325   assert(I.getIntrinsicID() == StartID &&
1326          "Start intrinsic does not have expected ID");
1327   BasicBlock::iterator BI(I), BE(I.getParent()->end());
1328   for (++BI; BI != BE; ++BI) {
1329     if (auto *E = dyn_cast<IntrinsicInst>(BI)) {
1330       if (isa<DbgInfoIntrinsic>(E) || E->getIntrinsicID() == StartID)
1331         continue;
1332       if (E->getIntrinsicID() == EndID &&
1333           haveSameOperands(I, *E, E->getNumArgOperands())) {
1334         IC.eraseInstFromFunction(*E);
1335         IC.eraseInstFromFunction(I);
1336         return true;
1337       }
1338     }
1339     break;
1340   }
1341 
1342   return false;
1343 }
1344 
1345 Instruction *InstCombiner::visitVAStartInst(VAStartInst &I) {
1346   removeTriviallyEmptyRange(I, Intrinsic::vastart, Intrinsic::vaend, *this);
1347   return nullptr;
1348 }
1349 
1350 Instruction *InstCombiner::visitVACopyInst(VACopyInst &I) {
1351   removeTriviallyEmptyRange(I, Intrinsic::vacopy, Intrinsic::vaend, *this);
1352   return nullptr;
1353 }
1354 
1355 /// CallInst simplification. This mostly only handles folding of intrinsic
1356 /// instructions. For normal calls, it allows visitCallSite to do the heavy
1357 /// lifting.
1358 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
1359   auto Args = CI.arg_operands();
1360   if (Value *V = SimplifyCall(CI.getCalledValue(), Args.begin(), Args.end(), DL,
1361                               &TLI, &DT, &AC))
1362     return replaceInstUsesWith(CI, V);
1363 
1364   if (isFreeCall(&CI, &TLI))
1365     return visitFree(CI);
1366 
1367   // If the caller function is nounwind, mark the call as nounwind, even if the
1368   // callee isn't.
1369   if (CI.getFunction()->doesNotThrow() && !CI.doesNotThrow()) {
1370     CI.setDoesNotThrow();
1371     return &CI;
1372   }
1373 
1374   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
1375   if (!II) return visitCallSite(&CI);
1376 
1377   // Intrinsics cannot occur in an invoke, so handle them here instead of in
1378   // visitCallSite.
1379   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
1380     bool Changed = false;
1381 
1382     // memmove/cpy/set of zero bytes is a noop.
1383     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
1384       if (NumBytes->isNullValue())
1385         return eraseInstFromFunction(CI);
1386 
1387       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
1388         if (CI->getZExtValue() == 1) {
1389           // Replace the instruction with just byte operations.  We would
1390           // transform other cases to loads/stores, but we don't know if
1391           // alignment is sufficient.
1392         }
1393     }
1394 
1395     // No other transformations apply to volatile transfers.
1396     if (MI->isVolatile())
1397       return nullptr;
1398 
1399     // If we have a memmove and the source operation is a constant global,
1400     // then the source and dest pointers can't alias, so we can change this
1401     // into a call to memcpy.
1402     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
1403       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
1404         if (GVSrc->isConstant()) {
1405           Module *M = CI.getModule();
1406           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
1407           Type *Tys[3] = { CI.getArgOperand(0)->getType(),
1408                            CI.getArgOperand(1)->getType(),
1409                            CI.getArgOperand(2)->getType() };
1410           CI.setCalledFunction(Intrinsic::getDeclaration(M, MemCpyID, Tys));
1411           Changed = true;
1412         }
1413     }
1414 
1415     if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
1416       // memmove(x,x,size) -> noop.
1417       if (MTI->getSource() == MTI->getDest())
1418         return eraseInstFromFunction(CI);
1419     }
1420 
1421     // If we can determine a pointer alignment that is bigger than currently
1422     // set, update the alignment.
1423     if (isa<MemTransferInst>(MI)) {
1424       if (Instruction *I = SimplifyMemTransfer(MI))
1425         return I;
1426     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
1427       if (Instruction *I = SimplifyMemSet(MSI))
1428         return I;
1429     }
1430 
1431     if (Changed) return II;
1432   }
1433 
1434   auto SimplifyDemandedVectorEltsLow = [this](Value *Op, unsigned Width,
1435                                               unsigned DemandedWidth) {
1436     APInt UndefElts(Width, 0);
1437     APInt DemandedElts = APInt::getLowBitsSet(Width, DemandedWidth);
1438     return SimplifyDemandedVectorElts(Op, DemandedElts, UndefElts);
1439   };
1440   auto SimplifyDemandedVectorEltsHigh = [this](Value *Op, unsigned Width,
1441                                               unsigned DemandedWidth) {
1442     APInt UndefElts(Width, 0);
1443     APInt DemandedElts = APInt::getHighBitsSet(Width, DemandedWidth);
1444     return SimplifyDemandedVectorElts(Op, DemandedElts, UndefElts);
1445   };
1446 
1447   switch (II->getIntrinsicID()) {
1448   default: break;
1449   case Intrinsic::objectsize: {
1450     uint64_t Size;
1451     if (getObjectSize(II->getArgOperand(0), Size, DL, &TLI)) {
1452       APInt APSize(II->getType()->getIntegerBitWidth(), Size);
1453       // Equality check to be sure that `Size` can fit in a value of type
1454       // `II->getType()`
1455       if (APSize == Size)
1456         return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), APSize));
1457     }
1458     return nullptr;
1459   }
1460   case Intrinsic::bswap: {
1461     Value *IIOperand = II->getArgOperand(0);
1462     Value *X = nullptr;
1463 
1464     // bswap(bswap(x)) -> x
1465     if (match(IIOperand, m_BSwap(m_Value(X))))
1466         return replaceInstUsesWith(CI, X);
1467 
1468     // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
1469     if (match(IIOperand, m_Trunc(m_BSwap(m_Value(X))))) {
1470       unsigned C = X->getType()->getPrimitiveSizeInBits() -
1471         IIOperand->getType()->getPrimitiveSizeInBits();
1472       Value *CV = ConstantInt::get(X->getType(), C);
1473       Value *V = Builder->CreateLShr(X, CV);
1474       return new TruncInst(V, IIOperand->getType());
1475     }
1476     break;
1477   }
1478 
1479   case Intrinsic::bitreverse: {
1480     Value *IIOperand = II->getArgOperand(0);
1481     Value *X = nullptr;
1482 
1483     // bitreverse(bitreverse(x)) -> x
1484     if (match(IIOperand, m_Intrinsic<Intrinsic::bitreverse>(m_Value(X))))
1485       return replaceInstUsesWith(CI, X);
1486     break;
1487   }
1488 
1489   case Intrinsic::masked_load:
1490     if (Value *SimplifiedMaskedOp = simplifyMaskedLoad(*II, *Builder))
1491       return replaceInstUsesWith(CI, SimplifiedMaskedOp);
1492     break;
1493   case Intrinsic::masked_store:
1494     return simplifyMaskedStore(*II, *this);
1495   case Intrinsic::masked_gather:
1496     return simplifyMaskedGather(*II, *this);
1497   case Intrinsic::masked_scatter:
1498     return simplifyMaskedScatter(*II, *this);
1499 
1500   case Intrinsic::powi:
1501     if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
1502       // powi(x, 0) -> 1.0
1503       if (Power->isZero())
1504         return replaceInstUsesWith(CI, ConstantFP::get(CI.getType(), 1.0));
1505       // powi(x, 1) -> x
1506       if (Power->isOne())
1507         return replaceInstUsesWith(CI, II->getArgOperand(0));
1508       // powi(x, -1) -> 1/x
1509       if (Power->isAllOnesValue())
1510         return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0),
1511                                           II->getArgOperand(0));
1512     }
1513     break;
1514 
1515   case Intrinsic::cttz:
1516   case Intrinsic::ctlz:
1517     if (auto *I = foldCttzCtlz(*II, *this))
1518       return I;
1519     break;
1520 
1521   case Intrinsic::uadd_with_overflow:
1522   case Intrinsic::sadd_with_overflow:
1523   case Intrinsic::umul_with_overflow:
1524   case Intrinsic::smul_with_overflow:
1525     if (isa<Constant>(II->getArgOperand(0)) &&
1526         !isa<Constant>(II->getArgOperand(1))) {
1527       // Canonicalize constants into the RHS.
1528       Value *LHS = II->getArgOperand(0);
1529       II->setArgOperand(0, II->getArgOperand(1));
1530       II->setArgOperand(1, LHS);
1531       return II;
1532     }
1533     LLVM_FALLTHROUGH;
1534 
1535   case Intrinsic::usub_with_overflow:
1536   case Intrinsic::ssub_with_overflow: {
1537     OverflowCheckFlavor OCF =
1538         IntrinsicIDToOverflowCheckFlavor(II->getIntrinsicID());
1539     assert(OCF != OCF_INVALID && "unexpected!");
1540 
1541     Value *OperationResult = nullptr;
1542     Constant *OverflowResult = nullptr;
1543     if (OptimizeOverflowCheck(OCF, II->getArgOperand(0), II->getArgOperand(1),
1544                               *II, OperationResult, OverflowResult))
1545       return CreateOverflowTuple(II, OperationResult, OverflowResult);
1546 
1547     break;
1548   }
1549 
1550   case Intrinsic::minnum:
1551   case Intrinsic::maxnum: {
1552     Value *Arg0 = II->getArgOperand(0);
1553     Value *Arg1 = II->getArgOperand(1);
1554     // Canonicalize constants to the RHS.
1555     if (isa<ConstantFP>(Arg0) && !isa<ConstantFP>(Arg1)) {
1556       II->setArgOperand(0, Arg1);
1557       II->setArgOperand(1, Arg0);
1558       return II;
1559     }
1560     if (Value *V = simplifyMinnumMaxnum(*II))
1561       return replaceInstUsesWith(*II, V);
1562     break;
1563   }
1564   case Intrinsic::ppc_altivec_lvx:
1565   case Intrinsic::ppc_altivec_lvxl:
1566     // Turn PPC lvx -> load if the pointer is known aligned.
1567     if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, II, &AC,
1568                                    &DT) >= 16) {
1569       Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
1570                                          PointerType::getUnqual(II->getType()));
1571       return new LoadInst(Ptr);
1572     }
1573     break;
1574   case Intrinsic::ppc_vsx_lxvw4x:
1575   case Intrinsic::ppc_vsx_lxvd2x: {
1576     // Turn PPC VSX loads into normal loads.
1577     Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
1578                                         PointerType::getUnqual(II->getType()));
1579     return new LoadInst(Ptr, Twine(""), false, 1);
1580   }
1581   case Intrinsic::ppc_altivec_stvx:
1582   case Intrinsic::ppc_altivec_stvxl:
1583     // Turn stvx -> store if the pointer is known aligned.
1584     if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, DL, II, &AC,
1585                                    &DT) >= 16) {
1586       Type *OpPtrTy =
1587         PointerType::getUnqual(II->getArgOperand(0)->getType());
1588       Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
1589       return new StoreInst(II->getArgOperand(0), Ptr);
1590     }
1591     break;
1592   case Intrinsic::ppc_vsx_stxvw4x:
1593   case Intrinsic::ppc_vsx_stxvd2x: {
1594     // Turn PPC VSX stores into normal stores.
1595     Type *OpPtrTy = PointerType::getUnqual(II->getArgOperand(0)->getType());
1596     Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
1597     return new StoreInst(II->getArgOperand(0), Ptr, false, 1);
1598   }
1599   case Intrinsic::ppc_qpx_qvlfs:
1600     // Turn PPC QPX qvlfs -> load if the pointer is known aligned.
1601     if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, II, &AC,
1602                                    &DT) >= 16) {
1603       Type *VTy = VectorType::get(Builder->getFloatTy(),
1604                                   II->getType()->getVectorNumElements());
1605       Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
1606                                          PointerType::getUnqual(VTy));
1607       Value *Load = Builder->CreateLoad(Ptr);
1608       return new FPExtInst(Load, II->getType());
1609     }
1610     break;
1611   case Intrinsic::ppc_qpx_qvlfd:
1612     // Turn PPC QPX qvlfd -> load if the pointer is known aligned.
1613     if (getOrEnforceKnownAlignment(II->getArgOperand(0), 32, DL, II, &AC,
1614                                    &DT) >= 32) {
1615       Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
1616                                          PointerType::getUnqual(II->getType()));
1617       return new LoadInst(Ptr);
1618     }
1619     break;
1620   case Intrinsic::ppc_qpx_qvstfs:
1621     // Turn PPC QPX qvstfs -> store if the pointer is known aligned.
1622     if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, DL, II, &AC,
1623                                    &DT) >= 16) {
1624       Type *VTy = VectorType::get(Builder->getFloatTy(),
1625           II->getArgOperand(0)->getType()->getVectorNumElements());
1626       Value *TOp = Builder->CreateFPTrunc(II->getArgOperand(0), VTy);
1627       Type *OpPtrTy = PointerType::getUnqual(VTy);
1628       Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
1629       return new StoreInst(TOp, Ptr);
1630     }
1631     break;
1632   case Intrinsic::ppc_qpx_qvstfd:
1633     // Turn PPC QPX qvstfd -> store if the pointer is known aligned.
1634     if (getOrEnforceKnownAlignment(II->getArgOperand(1), 32, DL, II, &AC,
1635                                    &DT) >= 32) {
1636       Type *OpPtrTy =
1637         PointerType::getUnqual(II->getArgOperand(0)->getType());
1638       Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
1639       return new StoreInst(II->getArgOperand(0), Ptr);
1640     }
1641     break;
1642 
1643   case Intrinsic::x86_vcvtph2ps_128:
1644   case Intrinsic::x86_vcvtph2ps_256: {
1645     auto Arg = II->getArgOperand(0);
1646     auto ArgType = cast<VectorType>(Arg->getType());
1647     auto RetType = cast<VectorType>(II->getType());
1648     unsigned ArgWidth = ArgType->getNumElements();
1649     unsigned RetWidth = RetType->getNumElements();
1650     assert(RetWidth <= ArgWidth && "Unexpected input/return vector widths");
1651     assert(ArgType->isIntOrIntVectorTy() &&
1652            ArgType->getScalarSizeInBits() == 16 &&
1653            "CVTPH2PS input type should be 16-bit integer vector");
1654     assert(RetType->getScalarType()->isFloatTy() &&
1655            "CVTPH2PS output type should be 32-bit float vector");
1656 
1657     // Constant folding: Convert to generic half to single conversion.
1658     if (isa<ConstantAggregateZero>(Arg))
1659       return replaceInstUsesWith(*II, ConstantAggregateZero::get(RetType));
1660 
1661     if (isa<ConstantDataVector>(Arg)) {
1662       auto VectorHalfAsShorts = Arg;
1663       if (RetWidth < ArgWidth) {
1664         SmallVector<uint32_t, 8> SubVecMask;
1665         for (unsigned i = 0; i != RetWidth; ++i)
1666           SubVecMask.push_back((int)i);
1667         VectorHalfAsShorts = Builder->CreateShuffleVector(
1668             Arg, UndefValue::get(ArgType), SubVecMask);
1669       }
1670 
1671       auto VectorHalfType =
1672           VectorType::get(Type::getHalfTy(II->getContext()), RetWidth);
1673       auto VectorHalfs =
1674           Builder->CreateBitCast(VectorHalfAsShorts, VectorHalfType);
1675       auto VectorFloats = Builder->CreateFPExt(VectorHalfs, RetType);
1676       return replaceInstUsesWith(*II, VectorFloats);
1677     }
1678 
1679     // We only use the lowest lanes of the argument.
1680     if (Value *V = SimplifyDemandedVectorEltsLow(Arg, ArgWidth, RetWidth)) {
1681       II->setArgOperand(0, V);
1682       return II;
1683     }
1684     break;
1685   }
1686 
1687   case Intrinsic::x86_sse_cvtss2si:
1688   case Intrinsic::x86_sse_cvtss2si64:
1689   case Intrinsic::x86_sse_cvttss2si:
1690   case Intrinsic::x86_sse_cvttss2si64:
1691   case Intrinsic::x86_sse2_cvtsd2si:
1692   case Intrinsic::x86_sse2_cvtsd2si64:
1693   case Intrinsic::x86_sse2_cvttsd2si:
1694   case Intrinsic::x86_sse2_cvttsd2si64: {
1695     // These intrinsics only demand the 0th element of their input vectors. If
1696     // we can simplify the input based on that, do so now.
1697     Value *Arg = II->getArgOperand(0);
1698     unsigned VWidth = Arg->getType()->getVectorNumElements();
1699     if (Value *V = SimplifyDemandedVectorEltsLow(Arg, VWidth, 1)) {
1700       II->setArgOperand(0, V);
1701       return II;
1702     }
1703     break;
1704   }
1705 
1706   case Intrinsic::x86_mmx_pmovmskb:
1707   case Intrinsic::x86_sse_movmsk_ps:
1708   case Intrinsic::x86_sse2_movmsk_pd:
1709   case Intrinsic::x86_sse2_pmovmskb_128:
1710   case Intrinsic::x86_avx_movmsk_pd_256:
1711   case Intrinsic::x86_avx_movmsk_ps_256:
1712   case Intrinsic::x86_avx2_pmovmskb: {
1713     if (Value *V = simplifyX86movmsk(*II, *Builder))
1714       return replaceInstUsesWith(*II, V);
1715     break;
1716   }
1717 
1718   case Intrinsic::x86_sse_comieq_ss:
1719   case Intrinsic::x86_sse_comige_ss:
1720   case Intrinsic::x86_sse_comigt_ss:
1721   case Intrinsic::x86_sse_comile_ss:
1722   case Intrinsic::x86_sse_comilt_ss:
1723   case Intrinsic::x86_sse_comineq_ss:
1724   case Intrinsic::x86_sse_ucomieq_ss:
1725   case Intrinsic::x86_sse_ucomige_ss:
1726   case Intrinsic::x86_sse_ucomigt_ss:
1727   case Intrinsic::x86_sse_ucomile_ss:
1728   case Intrinsic::x86_sse_ucomilt_ss:
1729   case Intrinsic::x86_sse_ucomineq_ss:
1730   case Intrinsic::x86_sse2_comieq_sd:
1731   case Intrinsic::x86_sse2_comige_sd:
1732   case Intrinsic::x86_sse2_comigt_sd:
1733   case Intrinsic::x86_sse2_comile_sd:
1734   case Intrinsic::x86_sse2_comilt_sd:
1735   case Intrinsic::x86_sse2_comineq_sd:
1736   case Intrinsic::x86_sse2_ucomieq_sd:
1737   case Intrinsic::x86_sse2_ucomige_sd:
1738   case Intrinsic::x86_sse2_ucomigt_sd:
1739   case Intrinsic::x86_sse2_ucomile_sd:
1740   case Intrinsic::x86_sse2_ucomilt_sd:
1741   case Intrinsic::x86_sse2_ucomineq_sd:
1742   case Intrinsic::x86_avx512_mask_cmp_ss:
1743   case Intrinsic::x86_avx512_mask_cmp_sd: {
1744     // These intrinsics only demand the 0th element of their input vectors. If
1745     // we can simplify the input based on that, do so now.
1746     bool MadeChange = false;
1747     Value *Arg0 = II->getArgOperand(0);
1748     Value *Arg1 = II->getArgOperand(1);
1749     unsigned VWidth = Arg0->getType()->getVectorNumElements();
1750     if (Value *V = SimplifyDemandedVectorEltsLow(Arg0, VWidth, 1)) {
1751       II->setArgOperand(0, V);
1752       MadeChange = true;
1753     }
1754     if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, 1)) {
1755       II->setArgOperand(1, V);
1756       MadeChange = true;
1757     }
1758     if (MadeChange)
1759       return II;
1760     break;
1761   }
1762 
1763   case Intrinsic::x86_sse_min_ss:
1764   case Intrinsic::x86_sse_max_ss:
1765   case Intrinsic::x86_sse_cmp_ss:
1766   case Intrinsic::x86_sse2_min_sd:
1767   case Intrinsic::x86_sse2_max_sd:
1768   case Intrinsic::x86_sse2_cmp_sd: {
1769     // These intrinsics only demand the lowest element of the second input
1770     // vector.
1771     Value *Arg1 = II->getArgOperand(1);
1772     unsigned VWidth = Arg1->getType()->getVectorNumElements();
1773     if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, 1)) {
1774       II->setArgOperand(1, V);
1775       return II;
1776     }
1777     break;
1778   }
1779 
1780   case Intrinsic::x86_fma_vfmadd_ss:
1781   case Intrinsic::x86_fma_vfmsub_ss:
1782   case Intrinsic::x86_fma_vfnmadd_ss:
1783   case Intrinsic::x86_fma_vfnmsub_ss:
1784   case Intrinsic::x86_fma_vfmadd_sd:
1785   case Intrinsic::x86_fma_vfmsub_sd:
1786   case Intrinsic::x86_fma_vfnmadd_sd:
1787   case Intrinsic::x86_fma_vfnmsub_sd:
1788   case Intrinsic::x86_avx512_mask_add_ss_round:
1789   case Intrinsic::x86_avx512_mask_div_ss_round:
1790   case Intrinsic::x86_avx512_mask_mul_ss_round:
1791   case Intrinsic::x86_avx512_mask_sub_ss_round:
1792   case Intrinsic::x86_avx512_mask_max_ss_round:
1793   case Intrinsic::x86_avx512_mask_min_ss_round:
1794   case Intrinsic::x86_avx512_mask_add_sd_round:
1795   case Intrinsic::x86_avx512_mask_div_sd_round:
1796   case Intrinsic::x86_avx512_mask_mul_sd_round:
1797   case Intrinsic::x86_avx512_mask_sub_sd_round:
1798   case Intrinsic::x86_avx512_mask_max_sd_round:
1799   case Intrinsic::x86_avx512_mask_min_sd_round: {
1800     // These intrinsics only demand the lowest element of the second and third
1801     // input vector.
1802     bool MadeChange = false;
1803     Value *Arg1 = II->getArgOperand(1);
1804     Value *Arg2 = II->getArgOperand(2);
1805     unsigned VWidth = Arg1->getType()->getVectorNumElements();
1806     if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, 1)) {
1807       II->setArgOperand(1, V);
1808       MadeChange = true;
1809     }
1810     if (Value *V = SimplifyDemandedVectorEltsLow(Arg2, VWidth, 1)) {
1811       II->setArgOperand(2, V);
1812       MadeChange = true;
1813     }
1814     if (MadeChange)
1815       return II;
1816     break;
1817   }
1818 
1819   case Intrinsic::x86_sse41_round_ss:
1820   case Intrinsic::x86_sse41_round_sd: {
1821     // These intrinsics demand the upper elements of the first input vector and
1822     // the lowest element of the second input vector.
1823     bool MadeChange = false;
1824     Value *Arg0 = II->getArgOperand(0);
1825     Value *Arg1 = II->getArgOperand(1);
1826     unsigned VWidth = Arg0->getType()->getVectorNumElements();
1827     if (Value *V = SimplifyDemandedVectorEltsHigh(Arg0, VWidth, VWidth - 1)) {
1828       II->setArgOperand(0, V);
1829       MadeChange = true;
1830     }
1831     if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, 1)) {
1832       II->setArgOperand(1, V);
1833       MadeChange = true;
1834     }
1835     if (MadeChange)
1836       return II;
1837     break;
1838   }
1839 
1840   // Constant fold ashr( <A x Bi>, Ci ).
1841   // Constant fold lshr( <A x Bi>, Ci ).
1842   // Constant fold shl( <A x Bi>, Ci ).
1843   case Intrinsic::x86_sse2_psrai_d:
1844   case Intrinsic::x86_sse2_psrai_w:
1845   case Intrinsic::x86_avx2_psrai_d:
1846   case Intrinsic::x86_avx2_psrai_w:
1847   case Intrinsic::x86_avx512_psrai_q_128:
1848   case Intrinsic::x86_avx512_psrai_q_256:
1849   case Intrinsic::x86_avx512_psrai_d_512:
1850   case Intrinsic::x86_avx512_psrai_q_512:
1851   case Intrinsic::x86_avx512_psrai_w_512:
1852   case Intrinsic::x86_sse2_psrli_d:
1853   case Intrinsic::x86_sse2_psrli_q:
1854   case Intrinsic::x86_sse2_psrli_w:
1855   case Intrinsic::x86_avx2_psrli_d:
1856   case Intrinsic::x86_avx2_psrli_q:
1857   case Intrinsic::x86_avx2_psrli_w:
1858   case Intrinsic::x86_avx512_psrli_d_512:
1859   case Intrinsic::x86_avx512_psrli_q_512:
1860   case Intrinsic::x86_avx512_psrli_w_512:
1861   case Intrinsic::x86_sse2_pslli_d:
1862   case Intrinsic::x86_sse2_pslli_q:
1863   case Intrinsic::x86_sse2_pslli_w:
1864   case Intrinsic::x86_avx2_pslli_d:
1865   case Intrinsic::x86_avx2_pslli_q:
1866   case Intrinsic::x86_avx2_pslli_w:
1867   case Intrinsic::x86_avx512_pslli_d_512:
1868   case Intrinsic::x86_avx512_pslli_q_512:
1869   case Intrinsic::x86_avx512_pslli_w_512:
1870     if (Value *V = simplifyX86immShift(*II, *Builder))
1871       return replaceInstUsesWith(*II, V);
1872     break;
1873 
1874   case Intrinsic::x86_sse2_psra_d:
1875   case Intrinsic::x86_sse2_psra_w:
1876   case Intrinsic::x86_avx2_psra_d:
1877   case Intrinsic::x86_avx2_psra_w:
1878   case Intrinsic::x86_avx512_psra_q_128:
1879   case Intrinsic::x86_avx512_psra_q_256:
1880   case Intrinsic::x86_avx512_psra_d_512:
1881   case Intrinsic::x86_avx512_psra_q_512:
1882   case Intrinsic::x86_avx512_psra_w_512:
1883   case Intrinsic::x86_sse2_psrl_d:
1884   case Intrinsic::x86_sse2_psrl_q:
1885   case Intrinsic::x86_sse2_psrl_w:
1886   case Intrinsic::x86_avx2_psrl_d:
1887   case Intrinsic::x86_avx2_psrl_q:
1888   case Intrinsic::x86_avx2_psrl_w:
1889   case Intrinsic::x86_avx512_psrl_d_512:
1890   case Intrinsic::x86_avx512_psrl_q_512:
1891   case Intrinsic::x86_avx512_psrl_w_512:
1892   case Intrinsic::x86_sse2_psll_d:
1893   case Intrinsic::x86_sse2_psll_q:
1894   case Intrinsic::x86_sse2_psll_w:
1895   case Intrinsic::x86_avx2_psll_d:
1896   case Intrinsic::x86_avx2_psll_q:
1897   case Intrinsic::x86_avx2_psll_w:
1898   case Intrinsic::x86_avx512_psll_d_512:
1899   case Intrinsic::x86_avx512_psll_q_512:
1900   case Intrinsic::x86_avx512_psll_w_512: {
1901     if (Value *V = simplifyX86immShift(*II, *Builder))
1902       return replaceInstUsesWith(*II, V);
1903 
1904     // SSE2/AVX2 uses only the first 64-bits of the 128-bit vector
1905     // operand to compute the shift amount.
1906     Value *Arg1 = II->getArgOperand(1);
1907     assert(Arg1->getType()->getPrimitiveSizeInBits() == 128 &&
1908            "Unexpected packed shift size");
1909     unsigned VWidth = Arg1->getType()->getVectorNumElements();
1910 
1911     if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, VWidth / 2)) {
1912       II->setArgOperand(1, V);
1913       return II;
1914     }
1915     break;
1916   }
1917 
1918   case Intrinsic::x86_avx2_psllv_d:
1919   case Intrinsic::x86_avx2_psllv_d_256:
1920   case Intrinsic::x86_avx2_psllv_q:
1921   case Intrinsic::x86_avx2_psllv_q_256:
1922   case Intrinsic::x86_avx512_psllv_d_512:
1923   case Intrinsic::x86_avx512_psllv_q_512:
1924   case Intrinsic::x86_avx512_psllv_w_128:
1925   case Intrinsic::x86_avx512_psllv_w_256:
1926   case Intrinsic::x86_avx512_psllv_w_512:
1927   case Intrinsic::x86_avx2_psrav_d:
1928   case Intrinsic::x86_avx2_psrav_d_256:
1929   case Intrinsic::x86_avx512_psrav_q_128:
1930   case Intrinsic::x86_avx512_psrav_q_256:
1931   case Intrinsic::x86_avx512_psrav_d_512:
1932   case Intrinsic::x86_avx512_psrav_q_512:
1933   case Intrinsic::x86_avx512_psrav_w_128:
1934   case Intrinsic::x86_avx512_psrav_w_256:
1935   case Intrinsic::x86_avx512_psrav_w_512:
1936   case Intrinsic::x86_avx2_psrlv_d:
1937   case Intrinsic::x86_avx2_psrlv_d_256:
1938   case Intrinsic::x86_avx2_psrlv_q:
1939   case Intrinsic::x86_avx2_psrlv_q_256:
1940   case Intrinsic::x86_avx512_psrlv_d_512:
1941   case Intrinsic::x86_avx512_psrlv_q_512:
1942   case Intrinsic::x86_avx512_psrlv_w_128:
1943   case Intrinsic::x86_avx512_psrlv_w_256:
1944   case Intrinsic::x86_avx512_psrlv_w_512:
1945     if (Value *V = simplifyX86varShift(*II, *Builder))
1946       return replaceInstUsesWith(*II, V);
1947     break;
1948 
1949   case Intrinsic::x86_sse41_insertps:
1950     if (Value *V = simplifyX86insertps(*II, *Builder))
1951       return replaceInstUsesWith(*II, V);
1952     break;
1953 
1954   case Intrinsic::x86_sse4a_extrq: {
1955     Value *Op0 = II->getArgOperand(0);
1956     Value *Op1 = II->getArgOperand(1);
1957     unsigned VWidth0 = Op0->getType()->getVectorNumElements();
1958     unsigned VWidth1 = Op1->getType()->getVectorNumElements();
1959     assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
1960            Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth0 == 2 &&
1961            VWidth1 == 16 && "Unexpected operand sizes");
1962 
1963     // See if we're dealing with constant values.
1964     Constant *C1 = dyn_cast<Constant>(Op1);
1965     ConstantInt *CILength =
1966         C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)0))
1967            : nullptr;
1968     ConstantInt *CIIndex =
1969         C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)1))
1970            : nullptr;
1971 
1972     // Attempt to simplify to a constant, shuffle vector or EXTRQI call.
1973     if (Value *V = simplifyX86extrq(*II, Op0, CILength, CIIndex, *Builder))
1974       return replaceInstUsesWith(*II, V);
1975 
1976     // EXTRQ only uses the lowest 64-bits of the first 128-bit vector
1977     // operands and the lowest 16-bits of the second.
1978     bool MadeChange = false;
1979     if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth0, 1)) {
1980       II->setArgOperand(0, V);
1981       MadeChange = true;
1982     }
1983     if (Value *V = SimplifyDemandedVectorEltsLow(Op1, VWidth1, 2)) {
1984       II->setArgOperand(1, V);
1985       MadeChange = true;
1986     }
1987     if (MadeChange)
1988       return II;
1989     break;
1990   }
1991 
1992   case Intrinsic::x86_sse4a_extrqi: {
1993     // EXTRQI: Extract Length bits starting from Index. Zero pad the remaining
1994     // bits of the lower 64-bits. The upper 64-bits are undefined.
1995     Value *Op0 = II->getArgOperand(0);
1996     unsigned VWidth = Op0->getType()->getVectorNumElements();
1997     assert(Op0->getType()->getPrimitiveSizeInBits() == 128 && VWidth == 2 &&
1998            "Unexpected operand size");
1999 
2000     // See if we're dealing with constant values.
2001     ConstantInt *CILength = dyn_cast<ConstantInt>(II->getArgOperand(1));
2002     ConstantInt *CIIndex = dyn_cast<ConstantInt>(II->getArgOperand(2));
2003 
2004     // Attempt to simplify to a constant or shuffle vector.
2005     if (Value *V = simplifyX86extrq(*II, Op0, CILength, CIIndex, *Builder))
2006       return replaceInstUsesWith(*II, V);
2007 
2008     // EXTRQI only uses the lowest 64-bits of the first 128-bit vector
2009     // operand.
2010     if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth, 1)) {
2011       II->setArgOperand(0, V);
2012       return II;
2013     }
2014     break;
2015   }
2016 
2017   case Intrinsic::x86_sse4a_insertq: {
2018     Value *Op0 = II->getArgOperand(0);
2019     Value *Op1 = II->getArgOperand(1);
2020     unsigned VWidth = Op0->getType()->getVectorNumElements();
2021     assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
2022            Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth == 2 &&
2023            Op1->getType()->getVectorNumElements() == 2 &&
2024            "Unexpected operand size");
2025 
2026     // See if we're dealing with constant values.
2027     Constant *C1 = dyn_cast<Constant>(Op1);
2028     ConstantInt *CI11 =
2029         C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)1))
2030            : nullptr;
2031 
2032     // Attempt to simplify to a constant, shuffle vector or INSERTQI call.
2033     if (CI11) {
2034       const APInt &V11 = CI11->getValue();
2035       APInt Len = V11.zextOrTrunc(6);
2036       APInt Idx = V11.lshr(8).zextOrTrunc(6);
2037       if (Value *V = simplifyX86insertq(*II, Op0, Op1, Len, Idx, *Builder))
2038         return replaceInstUsesWith(*II, V);
2039     }
2040 
2041     // INSERTQ only uses the lowest 64-bits of the first 128-bit vector
2042     // operand.
2043     if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth, 1)) {
2044       II->setArgOperand(0, V);
2045       return II;
2046     }
2047     break;
2048   }
2049 
2050   case Intrinsic::x86_sse4a_insertqi: {
2051     // INSERTQI: Extract lowest Length bits from lower half of second source and
2052     // insert over first source starting at Index bit. The upper 64-bits are
2053     // undefined.
2054     Value *Op0 = II->getArgOperand(0);
2055     Value *Op1 = II->getArgOperand(1);
2056     unsigned VWidth0 = Op0->getType()->getVectorNumElements();
2057     unsigned VWidth1 = Op1->getType()->getVectorNumElements();
2058     assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
2059            Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth0 == 2 &&
2060            VWidth1 == 2 && "Unexpected operand sizes");
2061 
2062     // See if we're dealing with constant values.
2063     ConstantInt *CILength = dyn_cast<ConstantInt>(II->getArgOperand(2));
2064     ConstantInt *CIIndex = dyn_cast<ConstantInt>(II->getArgOperand(3));
2065 
2066     // Attempt to simplify to a constant or shuffle vector.
2067     if (CILength && CIIndex) {
2068       APInt Len = CILength->getValue().zextOrTrunc(6);
2069       APInt Idx = CIIndex->getValue().zextOrTrunc(6);
2070       if (Value *V = simplifyX86insertq(*II, Op0, Op1, Len, Idx, *Builder))
2071         return replaceInstUsesWith(*II, V);
2072     }
2073 
2074     // INSERTQI only uses the lowest 64-bits of the first two 128-bit vector
2075     // operands.
2076     bool MadeChange = false;
2077     if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth0, 1)) {
2078       II->setArgOperand(0, V);
2079       MadeChange = true;
2080     }
2081     if (Value *V = SimplifyDemandedVectorEltsLow(Op1, VWidth1, 1)) {
2082       II->setArgOperand(1, V);
2083       MadeChange = true;
2084     }
2085     if (MadeChange)
2086       return II;
2087     break;
2088   }
2089 
2090   case Intrinsic::x86_sse41_pblendvb:
2091   case Intrinsic::x86_sse41_blendvps:
2092   case Intrinsic::x86_sse41_blendvpd:
2093   case Intrinsic::x86_avx_blendv_ps_256:
2094   case Intrinsic::x86_avx_blendv_pd_256:
2095   case Intrinsic::x86_avx2_pblendvb: {
2096     // Convert blendv* to vector selects if the mask is constant.
2097     // This optimization is convoluted because the intrinsic is defined as
2098     // getting a vector of floats or doubles for the ps and pd versions.
2099     // FIXME: That should be changed.
2100 
2101     Value *Op0 = II->getArgOperand(0);
2102     Value *Op1 = II->getArgOperand(1);
2103     Value *Mask = II->getArgOperand(2);
2104 
2105     // fold (blend A, A, Mask) -> A
2106     if (Op0 == Op1)
2107       return replaceInstUsesWith(CI, Op0);
2108 
2109     // Zero Mask - select 1st argument.
2110     if (isa<ConstantAggregateZero>(Mask))
2111       return replaceInstUsesWith(CI, Op0);
2112 
2113     // Constant Mask - select 1st/2nd argument lane based on top bit of mask.
2114     if (auto *ConstantMask = dyn_cast<ConstantDataVector>(Mask)) {
2115       Constant *NewSelector = getNegativeIsTrueBoolVec(ConstantMask);
2116       return SelectInst::Create(NewSelector, Op1, Op0, "blendv");
2117     }
2118     break;
2119   }
2120 
2121   case Intrinsic::x86_ssse3_pshuf_b_128:
2122   case Intrinsic::x86_avx2_pshuf_b:
2123   case Intrinsic::x86_avx512_pshuf_b_512:
2124     if (Value *V = simplifyX86pshufb(*II, *Builder))
2125       return replaceInstUsesWith(*II, V);
2126     break;
2127 
2128   case Intrinsic::x86_avx_vpermilvar_ps:
2129   case Intrinsic::x86_avx_vpermilvar_ps_256:
2130   case Intrinsic::x86_avx512_vpermilvar_ps_512:
2131   case Intrinsic::x86_avx_vpermilvar_pd:
2132   case Intrinsic::x86_avx_vpermilvar_pd_256:
2133   case Intrinsic::x86_avx512_vpermilvar_pd_512:
2134     if (Value *V = simplifyX86vpermilvar(*II, *Builder))
2135       return replaceInstUsesWith(*II, V);
2136     break;
2137 
2138   case Intrinsic::x86_avx2_permd:
2139   case Intrinsic::x86_avx2_permps:
2140     if (Value *V = simplifyX86vpermv(*II, *Builder))
2141       return replaceInstUsesWith(*II, V);
2142     break;
2143 
2144   case Intrinsic::x86_avx_vperm2f128_pd_256:
2145   case Intrinsic::x86_avx_vperm2f128_ps_256:
2146   case Intrinsic::x86_avx_vperm2f128_si_256:
2147   case Intrinsic::x86_avx2_vperm2i128:
2148     if (Value *V = simplifyX86vperm2(*II, *Builder))
2149       return replaceInstUsesWith(*II, V);
2150     break;
2151 
2152   case Intrinsic::x86_avx_maskload_ps:
2153   case Intrinsic::x86_avx_maskload_pd:
2154   case Intrinsic::x86_avx_maskload_ps_256:
2155   case Intrinsic::x86_avx_maskload_pd_256:
2156   case Intrinsic::x86_avx2_maskload_d:
2157   case Intrinsic::x86_avx2_maskload_q:
2158   case Intrinsic::x86_avx2_maskload_d_256:
2159   case Intrinsic::x86_avx2_maskload_q_256:
2160     if (Instruction *I = simplifyX86MaskedLoad(*II, *this))
2161       return I;
2162     break;
2163 
2164   case Intrinsic::x86_sse2_maskmov_dqu:
2165   case Intrinsic::x86_avx_maskstore_ps:
2166   case Intrinsic::x86_avx_maskstore_pd:
2167   case Intrinsic::x86_avx_maskstore_ps_256:
2168   case Intrinsic::x86_avx_maskstore_pd_256:
2169   case Intrinsic::x86_avx2_maskstore_d:
2170   case Intrinsic::x86_avx2_maskstore_q:
2171   case Intrinsic::x86_avx2_maskstore_d_256:
2172   case Intrinsic::x86_avx2_maskstore_q_256:
2173     if (simplifyX86MaskedStore(*II, *this))
2174       return nullptr;
2175     break;
2176 
2177   case Intrinsic::x86_xop_vpcomb:
2178   case Intrinsic::x86_xop_vpcomd:
2179   case Intrinsic::x86_xop_vpcomq:
2180   case Intrinsic::x86_xop_vpcomw:
2181     if (Value *V = simplifyX86vpcom(*II, *Builder, true))
2182       return replaceInstUsesWith(*II, V);
2183     break;
2184 
2185   case Intrinsic::x86_xop_vpcomub:
2186   case Intrinsic::x86_xop_vpcomud:
2187   case Intrinsic::x86_xop_vpcomuq:
2188   case Intrinsic::x86_xop_vpcomuw:
2189     if (Value *V = simplifyX86vpcom(*II, *Builder, false))
2190       return replaceInstUsesWith(*II, V);
2191     break;
2192 
2193   case Intrinsic::ppc_altivec_vperm:
2194     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
2195     // Note that ppc_altivec_vperm has a big-endian bias, so when creating
2196     // a vectorshuffle for little endian, we must undo the transformation
2197     // performed on vec_perm in altivec.h.  That is, we must complement
2198     // the permutation mask with respect to 31 and reverse the order of
2199     // V1 and V2.
2200     if (Constant *Mask = dyn_cast<Constant>(II->getArgOperand(2))) {
2201       assert(Mask->getType()->getVectorNumElements() == 16 &&
2202              "Bad type for intrinsic!");
2203 
2204       // Check that all of the elements are integer constants or undefs.
2205       bool AllEltsOk = true;
2206       for (unsigned i = 0; i != 16; ++i) {
2207         Constant *Elt = Mask->getAggregateElement(i);
2208         if (!Elt || !(isa<ConstantInt>(Elt) || isa<UndefValue>(Elt))) {
2209           AllEltsOk = false;
2210           break;
2211         }
2212       }
2213 
2214       if (AllEltsOk) {
2215         // Cast the input vectors to byte vectors.
2216         Value *Op0 = Builder->CreateBitCast(II->getArgOperand(0),
2217                                             Mask->getType());
2218         Value *Op1 = Builder->CreateBitCast(II->getArgOperand(1),
2219                                             Mask->getType());
2220         Value *Result = UndefValue::get(Op0->getType());
2221 
2222         // Only extract each element once.
2223         Value *ExtractedElts[32];
2224         memset(ExtractedElts, 0, sizeof(ExtractedElts));
2225 
2226         for (unsigned i = 0; i != 16; ++i) {
2227           if (isa<UndefValue>(Mask->getAggregateElement(i)))
2228             continue;
2229           unsigned Idx =
2230             cast<ConstantInt>(Mask->getAggregateElement(i))->getZExtValue();
2231           Idx &= 31;  // Match the hardware behavior.
2232           if (DL.isLittleEndian())
2233             Idx = 31 - Idx;
2234 
2235           if (!ExtractedElts[Idx]) {
2236             Value *Op0ToUse = (DL.isLittleEndian()) ? Op1 : Op0;
2237             Value *Op1ToUse = (DL.isLittleEndian()) ? Op0 : Op1;
2238             ExtractedElts[Idx] =
2239               Builder->CreateExtractElement(Idx < 16 ? Op0ToUse : Op1ToUse,
2240                                             Builder->getInt32(Idx&15));
2241           }
2242 
2243           // Insert this value into the result vector.
2244           Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
2245                                                 Builder->getInt32(i));
2246         }
2247         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
2248       }
2249     }
2250     break;
2251 
2252   case Intrinsic::arm_neon_vld1:
2253   case Intrinsic::arm_neon_vld2:
2254   case Intrinsic::arm_neon_vld3:
2255   case Intrinsic::arm_neon_vld4:
2256   case Intrinsic::arm_neon_vld2lane:
2257   case Intrinsic::arm_neon_vld3lane:
2258   case Intrinsic::arm_neon_vld4lane:
2259   case Intrinsic::arm_neon_vst1:
2260   case Intrinsic::arm_neon_vst2:
2261   case Intrinsic::arm_neon_vst3:
2262   case Intrinsic::arm_neon_vst4:
2263   case Intrinsic::arm_neon_vst2lane:
2264   case Intrinsic::arm_neon_vst3lane:
2265   case Intrinsic::arm_neon_vst4lane: {
2266     unsigned MemAlign =
2267         getKnownAlignment(II->getArgOperand(0), DL, II, &AC, &DT);
2268     unsigned AlignArg = II->getNumArgOperands() - 1;
2269     ConstantInt *IntrAlign = dyn_cast<ConstantInt>(II->getArgOperand(AlignArg));
2270     if (IntrAlign && IntrAlign->getZExtValue() < MemAlign) {
2271       II->setArgOperand(AlignArg,
2272                         ConstantInt::get(Type::getInt32Ty(II->getContext()),
2273                                          MemAlign, false));
2274       return II;
2275     }
2276     break;
2277   }
2278 
2279   case Intrinsic::arm_neon_vmulls:
2280   case Intrinsic::arm_neon_vmullu:
2281   case Intrinsic::aarch64_neon_smull:
2282   case Intrinsic::aarch64_neon_umull: {
2283     Value *Arg0 = II->getArgOperand(0);
2284     Value *Arg1 = II->getArgOperand(1);
2285 
2286     // Handle mul by zero first:
2287     if (isa<ConstantAggregateZero>(Arg0) || isa<ConstantAggregateZero>(Arg1)) {
2288       return replaceInstUsesWith(CI, ConstantAggregateZero::get(II->getType()));
2289     }
2290 
2291     // Check for constant LHS & RHS - in this case we just simplify.
2292     bool Zext = (II->getIntrinsicID() == Intrinsic::arm_neon_vmullu ||
2293                  II->getIntrinsicID() == Intrinsic::aarch64_neon_umull);
2294     VectorType *NewVT = cast<VectorType>(II->getType());
2295     if (Constant *CV0 = dyn_cast<Constant>(Arg0)) {
2296       if (Constant *CV1 = dyn_cast<Constant>(Arg1)) {
2297         CV0 = ConstantExpr::getIntegerCast(CV0, NewVT, /*isSigned=*/!Zext);
2298         CV1 = ConstantExpr::getIntegerCast(CV1, NewVT, /*isSigned=*/!Zext);
2299 
2300         return replaceInstUsesWith(CI, ConstantExpr::getMul(CV0, CV1));
2301       }
2302 
2303       // Couldn't simplify - canonicalize constant to the RHS.
2304       std::swap(Arg0, Arg1);
2305     }
2306 
2307     // Handle mul by one:
2308     if (Constant *CV1 = dyn_cast<Constant>(Arg1))
2309       if (ConstantInt *Splat =
2310               dyn_cast_or_null<ConstantInt>(CV1->getSplatValue()))
2311         if (Splat->isOne())
2312           return CastInst::CreateIntegerCast(Arg0, II->getType(),
2313                                              /*isSigned=*/!Zext);
2314 
2315     break;
2316   }
2317 
2318   case Intrinsic::amdgcn_rcp: {
2319     if (const ConstantFP *C = dyn_cast<ConstantFP>(II->getArgOperand(0))) {
2320       const APFloat &ArgVal = C->getValueAPF();
2321       APFloat Val(ArgVal.getSemantics(), 1.0);
2322       APFloat::opStatus Status = Val.divide(ArgVal,
2323                                             APFloat::rmNearestTiesToEven);
2324       // Only do this if it was exact and therefore not dependent on the
2325       // rounding mode.
2326       if (Status == APFloat::opOK)
2327         return replaceInstUsesWith(CI, ConstantFP::get(II->getContext(), Val));
2328     }
2329 
2330     break;
2331   }
2332   case Intrinsic::amdgcn_frexp_mant:
2333   case Intrinsic::amdgcn_frexp_exp: {
2334     Value *Src = II->getArgOperand(0);
2335     if (const ConstantFP *C = dyn_cast<ConstantFP>(Src)) {
2336       int Exp;
2337       APFloat Significand = frexp(C->getValueAPF(), Exp,
2338                                   APFloat::rmNearestTiesToEven);
2339 
2340       if (II->getIntrinsicID() == Intrinsic::amdgcn_frexp_mant) {
2341         return replaceInstUsesWith(CI, ConstantFP::get(II->getContext(),
2342                                                        Significand));
2343       }
2344 
2345       // Match instruction special case behavior.
2346       if (Exp == APFloat::IEK_NaN || Exp == APFloat::IEK_Inf)
2347         Exp = 0;
2348 
2349       return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), Exp));
2350     }
2351 
2352     if (isa<UndefValue>(Src))
2353       return replaceInstUsesWith(CI, UndefValue::get(II->getType()));
2354 
2355     break;
2356   }
2357   case Intrinsic::amdgcn_class: {
2358     enum  {
2359       S_NAN = 1 << 0,        // Signaling NaN
2360       Q_NAN = 1 << 1,        // Quiet NaN
2361       N_INFINITY = 1 << 2,   // Negative infinity
2362       N_NORMAL = 1 << 3,     // Negative normal
2363       N_SUBNORMAL = 1 << 4,  // Negative subnormal
2364       N_ZERO = 1 << 5,       // Negative zero
2365       P_ZERO = 1 << 6,       // Positive zero
2366       P_SUBNORMAL = 1 << 7,  // Positive subnormal
2367       P_NORMAL = 1 << 8,     // Positive normal
2368       P_INFINITY = 1 << 9    // Positive infinity
2369     };
2370 
2371     const uint32_t FullMask = S_NAN | Q_NAN | N_INFINITY | N_NORMAL |
2372       N_SUBNORMAL | N_ZERO | P_ZERO | P_SUBNORMAL | P_NORMAL | P_INFINITY;
2373 
2374     Value *Src0 = II->getArgOperand(0);
2375     Value *Src1 = II->getArgOperand(1);
2376     const ConstantInt *CMask = dyn_cast<ConstantInt>(Src1);
2377     if (!CMask) {
2378       if (isa<UndefValue>(Src0))
2379         return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
2380 
2381       if (isa<UndefValue>(Src1))
2382         return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), false));
2383       break;
2384     }
2385 
2386     uint32_t Mask = CMask->getZExtValue();
2387 
2388     // If all tests are made, it doesn't matter what the value is.
2389     if ((Mask & FullMask) == FullMask)
2390       return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), true));
2391 
2392     if ((Mask & FullMask) == 0)
2393       return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), false));
2394 
2395     if (Mask == (S_NAN | Q_NAN)) {
2396       // Equivalent of isnan. Replace with standard fcmp.
2397       Value *FCmp = Builder->CreateFCmpUNO(Src0, Src0);
2398       FCmp->takeName(II);
2399       return replaceInstUsesWith(*II, FCmp);
2400     }
2401 
2402     const ConstantFP *CVal = dyn_cast<ConstantFP>(Src0);
2403     if (!CVal) {
2404       if (isa<UndefValue>(Src0))
2405         return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
2406 
2407       // Clamp mask to used bits
2408       if ((Mask & FullMask) != Mask) {
2409         CallInst *NewCall = Builder->CreateCall(II->getCalledFunction(),
2410           { Src0, ConstantInt::get(Src1->getType(), Mask & FullMask) }
2411         );
2412 
2413         NewCall->takeName(II);
2414         return replaceInstUsesWith(*II, NewCall);
2415       }
2416 
2417       break;
2418     }
2419 
2420     const APFloat &Val = CVal->getValueAPF();
2421 
2422     bool Result =
2423       ((Mask & S_NAN) && Val.isNaN() && Val.isSignaling()) ||
2424       ((Mask & Q_NAN) && Val.isNaN() && !Val.isSignaling()) ||
2425       ((Mask & N_INFINITY) && Val.isInfinity() && Val.isNegative()) ||
2426       ((Mask & N_NORMAL) && Val.isNormal() && Val.isNegative()) ||
2427       ((Mask & N_SUBNORMAL) && Val.isDenormal() && Val.isNegative()) ||
2428       ((Mask & N_ZERO) && Val.isZero() && Val.isNegative()) ||
2429       ((Mask & P_ZERO) && Val.isZero() && !Val.isNegative()) ||
2430       ((Mask & P_SUBNORMAL) && Val.isDenormal() && !Val.isNegative()) ||
2431       ((Mask & P_NORMAL) && Val.isNormal() && !Val.isNegative()) ||
2432       ((Mask & P_INFINITY) && Val.isInfinity() && !Val.isNegative());
2433 
2434     return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), Result));
2435   }
2436   case Intrinsic::stackrestore: {
2437     // If the save is right next to the restore, remove the restore.  This can
2438     // happen when variable allocas are DCE'd.
2439     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {
2440       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
2441         if (&*++SS->getIterator() == II)
2442           return eraseInstFromFunction(CI);
2443       }
2444     }
2445 
2446     // Scan down this block to see if there is another stack restore in the
2447     // same block without an intervening call/alloca.
2448     BasicBlock::iterator BI(II);
2449     TerminatorInst *TI = II->getParent()->getTerminator();
2450     bool CannotRemove = false;
2451     for (++BI; &*BI != TI; ++BI) {
2452       if (isa<AllocaInst>(BI)) {
2453         CannotRemove = true;
2454         break;
2455       }
2456       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
2457         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
2458           // If there is a stackrestore below this one, remove this one.
2459           if (II->getIntrinsicID() == Intrinsic::stackrestore)
2460             return eraseInstFromFunction(CI);
2461 
2462           // Bail if we cross over an intrinsic with side effects, such as
2463           // llvm.stacksave, llvm.read_register, or llvm.setjmp.
2464           if (II->mayHaveSideEffects()) {
2465             CannotRemove = true;
2466             break;
2467           }
2468         } else {
2469           // If we found a non-intrinsic call, we can't remove the stack
2470           // restore.
2471           CannotRemove = true;
2472           break;
2473         }
2474       }
2475     }
2476 
2477     // If the stack restore is in a return, resume, or unwind block and if there
2478     // are no allocas or calls between the restore and the return, nuke the
2479     // restore.
2480     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<ResumeInst>(TI)))
2481       return eraseInstFromFunction(CI);
2482     break;
2483   }
2484   case Intrinsic::lifetime_start:
2485     // Asan needs to poison memory to detect invalid access which is possible
2486     // even for empty lifetime range.
2487     if (II->getFunction()->hasFnAttribute(Attribute::SanitizeAddress))
2488       break;
2489 
2490     if (removeTriviallyEmptyRange(*II, Intrinsic::lifetime_start,
2491                                   Intrinsic::lifetime_end, *this))
2492       return nullptr;
2493     break;
2494   case Intrinsic::assume: {
2495     Value *IIOperand = II->getArgOperand(0);
2496     // Remove an assume if it is immediately followed by an identical assume.
2497     if (match(II->getNextNode(),
2498               m_Intrinsic<Intrinsic::assume>(m_Specific(IIOperand))))
2499       return eraseInstFromFunction(CI);
2500 
2501     // Canonicalize assume(a && b) -> assume(a); assume(b);
2502     // Note: New assumption intrinsics created here are registered by
2503     // the InstCombineIRInserter object.
2504     Value *AssumeIntrinsic = II->getCalledValue(), *A, *B;
2505     if (match(IIOperand, m_And(m_Value(A), m_Value(B)))) {
2506       Builder->CreateCall(AssumeIntrinsic, A, II->getName());
2507       Builder->CreateCall(AssumeIntrinsic, B, II->getName());
2508       return eraseInstFromFunction(*II);
2509     }
2510     // assume(!(a || b)) -> assume(!a); assume(!b);
2511     if (match(IIOperand, m_Not(m_Or(m_Value(A), m_Value(B))))) {
2512       Builder->CreateCall(AssumeIntrinsic, Builder->CreateNot(A),
2513                           II->getName());
2514       Builder->CreateCall(AssumeIntrinsic, Builder->CreateNot(B),
2515                           II->getName());
2516       return eraseInstFromFunction(*II);
2517     }
2518 
2519     // assume( (load addr) != null ) -> add 'nonnull' metadata to load
2520     // (if assume is valid at the load)
2521     if (ICmpInst* ICmp = dyn_cast<ICmpInst>(IIOperand)) {
2522       Value *LHS = ICmp->getOperand(0);
2523       Value *RHS = ICmp->getOperand(1);
2524       if (ICmpInst::ICMP_NE == ICmp->getPredicate() &&
2525           isa<LoadInst>(LHS) &&
2526           isa<Constant>(RHS) &&
2527           RHS->getType()->isPointerTy() &&
2528           cast<Constant>(RHS)->isNullValue()) {
2529         LoadInst* LI = cast<LoadInst>(LHS);
2530         if (isValidAssumeForContext(II, LI, &DT)) {
2531           MDNode *MD = MDNode::get(II->getContext(), None);
2532           LI->setMetadata(LLVMContext::MD_nonnull, MD);
2533           return eraseInstFromFunction(*II);
2534         }
2535       }
2536       // TODO: apply nonnull return attributes to calls and invokes
2537       // TODO: apply range metadata for range check patterns?
2538     }
2539     // If there is a dominating assume with the same condition as this one,
2540     // then this one is redundant, and should be removed.
2541     APInt KnownZero(1, 0), KnownOne(1, 0);
2542     computeKnownBits(IIOperand, KnownZero, KnownOne, 0, II);
2543     if (KnownOne.isAllOnesValue())
2544       return eraseInstFromFunction(*II);
2545 
2546     break;
2547   }
2548   case Intrinsic::experimental_gc_relocate: {
2549     // Translate facts known about a pointer before relocating into
2550     // facts about the relocate value, while being careful to
2551     // preserve relocation semantics.
2552     Value *DerivedPtr = cast<GCRelocateInst>(II)->getDerivedPtr();
2553 
2554     // Remove the relocation if unused, note that this check is required
2555     // to prevent the cases below from looping forever.
2556     if (II->use_empty())
2557       return eraseInstFromFunction(*II);
2558 
2559     // Undef is undef, even after relocation.
2560     // TODO: provide a hook for this in GCStrategy.  This is clearly legal for
2561     // most practical collectors, but there was discussion in the review thread
2562     // about whether it was legal for all possible collectors.
2563     if (isa<UndefValue>(DerivedPtr))
2564       // Use undef of gc_relocate's type to replace it.
2565       return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
2566 
2567     if (auto *PT = dyn_cast<PointerType>(II->getType())) {
2568       // The relocation of null will be null for most any collector.
2569       // TODO: provide a hook for this in GCStrategy.  There might be some
2570       // weird collector this property does not hold for.
2571       if (isa<ConstantPointerNull>(DerivedPtr))
2572         // Use null-pointer of gc_relocate's type to replace it.
2573         return replaceInstUsesWith(*II, ConstantPointerNull::get(PT));
2574 
2575       // isKnownNonNull -> nonnull attribute
2576       if (isKnownNonNullAt(DerivedPtr, II, &DT))
2577         II->addAttribute(AttributeSet::ReturnIndex, Attribute::NonNull);
2578     }
2579 
2580     // TODO: bitcast(relocate(p)) -> relocate(bitcast(p))
2581     // Canonicalize on the type from the uses to the defs
2582 
2583     // TODO: relocate((gep p, C, C2, ...)) -> gep(relocate(p), C, C2, ...)
2584     break;
2585   }
2586   }
2587 
2588   return visitCallSite(II);
2589 }
2590 
2591 // InvokeInst simplification
2592 //
2593 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
2594   return visitCallSite(&II);
2595 }
2596 
2597 /// If this cast does not affect the value passed through the varargs area, we
2598 /// can eliminate the use of the cast.
2599 static bool isSafeToEliminateVarargsCast(const CallSite CS,
2600                                          const DataLayout &DL,
2601                                          const CastInst *const CI,
2602                                          const int ix) {
2603   if (!CI->isLosslessCast())
2604     return false;
2605 
2606   // If this is a GC intrinsic, avoid munging types.  We need types for
2607   // statepoint reconstruction in SelectionDAG.
2608   // TODO: This is probably something which should be expanded to all
2609   // intrinsics since the entire point of intrinsics is that
2610   // they are understandable by the optimizer.
2611   if (isStatepoint(CS) || isGCRelocate(CS) || isGCResult(CS))
2612     return false;
2613 
2614   // The size of ByVal or InAlloca arguments is derived from the type, so we
2615   // can't change to a type with a different size.  If the size were
2616   // passed explicitly we could avoid this check.
2617   if (!CS.isByValOrInAllocaArgument(ix))
2618     return true;
2619 
2620   Type* SrcTy =
2621             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
2622   Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
2623   if (!SrcTy->isSized() || !DstTy->isSized())
2624     return false;
2625   if (DL.getTypeAllocSize(SrcTy) != DL.getTypeAllocSize(DstTy))
2626     return false;
2627   return true;
2628 }
2629 
2630 Instruction *InstCombiner::tryOptimizeCall(CallInst *CI) {
2631   if (!CI->getCalledFunction()) return nullptr;
2632 
2633   auto InstCombineRAUW = [this](Instruction *From, Value *With) {
2634     replaceInstUsesWith(*From, With);
2635   };
2636   LibCallSimplifier Simplifier(DL, &TLI, InstCombineRAUW);
2637   if (Value *With = Simplifier.optimizeCall(CI)) {
2638     ++NumSimplified;
2639     return CI->use_empty() ? CI : replaceInstUsesWith(*CI, With);
2640   }
2641 
2642   return nullptr;
2643 }
2644 
2645 static IntrinsicInst *findInitTrampolineFromAlloca(Value *TrampMem) {
2646   // Strip off at most one level of pointer casts, looking for an alloca.  This
2647   // is good enough in practice and simpler than handling any number of casts.
2648   Value *Underlying = TrampMem->stripPointerCasts();
2649   if (Underlying != TrampMem &&
2650       (!Underlying->hasOneUse() || Underlying->user_back() != TrampMem))
2651     return nullptr;
2652   if (!isa<AllocaInst>(Underlying))
2653     return nullptr;
2654 
2655   IntrinsicInst *InitTrampoline = nullptr;
2656   for (User *U : TrampMem->users()) {
2657     IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
2658     if (!II)
2659       return nullptr;
2660     if (II->getIntrinsicID() == Intrinsic::init_trampoline) {
2661       if (InitTrampoline)
2662         // More than one init_trampoline writes to this value.  Give up.
2663         return nullptr;
2664       InitTrampoline = II;
2665       continue;
2666     }
2667     if (II->getIntrinsicID() == Intrinsic::adjust_trampoline)
2668       // Allow any number of calls to adjust.trampoline.
2669       continue;
2670     return nullptr;
2671   }
2672 
2673   // No call to init.trampoline found.
2674   if (!InitTrampoline)
2675     return nullptr;
2676 
2677   // Check that the alloca is being used in the expected way.
2678   if (InitTrampoline->getOperand(0) != TrampMem)
2679     return nullptr;
2680 
2681   return InitTrampoline;
2682 }
2683 
2684 static IntrinsicInst *findInitTrampolineFromBB(IntrinsicInst *AdjustTramp,
2685                                                Value *TrampMem) {
2686   // Visit all the previous instructions in the basic block, and try to find a
2687   // init.trampoline which has a direct path to the adjust.trampoline.
2688   for (BasicBlock::iterator I = AdjustTramp->getIterator(),
2689                             E = AdjustTramp->getParent()->begin();
2690        I != E;) {
2691     Instruction *Inst = &*--I;
2692     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2693       if (II->getIntrinsicID() == Intrinsic::init_trampoline &&
2694           II->getOperand(0) == TrampMem)
2695         return II;
2696     if (Inst->mayWriteToMemory())
2697       return nullptr;
2698   }
2699   return nullptr;
2700 }
2701 
2702 // Given a call to llvm.adjust.trampoline, find and return the corresponding
2703 // call to llvm.init.trampoline if the call to the trampoline can be optimized
2704 // to a direct call to a function.  Otherwise return NULL.
2705 //
2706 static IntrinsicInst *findInitTrampoline(Value *Callee) {
2707   Callee = Callee->stripPointerCasts();
2708   IntrinsicInst *AdjustTramp = dyn_cast<IntrinsicInst>(Callee);
2709   if (!AdjustTramp ||
2710       AdjustTramp->getIntrinsicID() != Intrinsic::adjust_trampoline)
2711     return nullptr;
2712 
2713   Value *TrampMem = AdjustTramp->getOperand(0);
2714 
2715   if (IntrinsicInst *IT = findInitTrampolineFromAlloca(TrampMem))
2716     return IT;
2717   if (IntrinsicInst *IT = findInitTrampolineFromBB(AdjustTramp, TrampMem))
2718     return IT;
2719   return nullptr;
2720 }
2721 
2722 /// Improvements for call and invoke instructions.
2723 Instruction *InstCombiner::visitCallSite(CallSite CS) {
2724   if (isAllocLikeFn(CS.getInstruction(), &TLI))
2725     return visitAllocSite(*CS.getInstruction());
2726 
2727   bool Changed = false;
2728 
2729   // Mark any parameters that are known to be non-null with the nonnull
2730   // attribute.  This is helpful for inlining calls to functions with null
2731   // checks on their arguments.
2732   SmallVector<unsigned, 4> Indices;
2733   unsigned ArgNo = 0;
2734 
2735   for (Value *V : CS.args()) {
2736     if (V->getType()->isPointerTy() &&
2737         !CS.paramHasAttr(ArgNo + 1, Attribute::NonNull) &&
2738         isKnownNonNullAt(V, CS.getInstruction(), &DT))
2739       Indices.push_back(ArgNo + 1);
2740     ArgNo++;
2741   }
2742 
2743   assert(ArgNo == CS.arg_size() && "sanity check");
2744 
2745   if (!Indices.empty()) {
2746     AttributeSet AS = CS.getAttributes();
2747     LLVMContext &Ctx = CS.getInstruction()->getContext();
2748     AS = AS.addAttribute(Ctx, Indices,
2749                          Attribute::get(Ctx, Attribute::NonNull));
2750     CS.setAttributes(AS);
2751     Changed = true;
2752   }
2753 
2754   // If the callee is a pointer to a function, attempt to move any casts to the
2755   // arguments of the call/invoke.
2756   Value *Callee = CS.getCalledValue();
2757   if (!isa<Function>(Callee) && transformConstExprCastCall(CS))
2758     return nullptr;
2759 
2760   if (Function *CalleeF = dyn_cast<Function>(Callee)) {
2761     // Remove the convergent attr on calls when the callee is not convergent.
2762     if (CS.isConvergent() && !CalleeF->isConvergent() &&
2763         !CalleeF->isIntrinsic()) {
2764       DEBUG(dbgs() << "Removing convergent attr from instr "
2765                    << CS.getInstruction() << "\n");
2766       CS.setNotConvergent();
2767       return CS.getInstruction();
2768     }
2769 
2770     // If the call and callee calling conventions don't match, this call must
2771     // be unreachable, as the call is undefined.
2772     if (CalleeF->getCallingConv() != CS.getCallingConv() &&
2773         // Only do this for calls to a function with a body.  A prototype may
2774         // not actually end up matching the implementation's calling conv for a
2775         // variety of reasons (e.g. it may be written in assembly).
2776         !CalleeF->isDeclaration()) {
2777       Instruction *OldCall = CS.getInstruction();
2778       new StoreInst(ConstantInt::getTrue(Callee->getContext()),
2779                 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
2780                                   OldCall);
2781       // If OldCall does not return void then replaceAllUsesWith undef.
2782       // This allows ValueHandlers and custom metadata to adjust itself.
2783       if (!OldCall->getType()->isVoidTy())
2784         replaceInstUsesWith(*OldCall, UndefValue::get(OldCall->getType()));
2785       if (isa<CallInst>(OldCall))
2786         return eraseInstFromFunction(*OldCall);
2787 
2788       // We cannot remove an invoke, because it would change the CFG, just
2789       // change the callee to a null pointer.
2790       cast<InvokeInst>(OldCall)->setCalledFunction(
2791                                     Constant::getNullValue(CalleeF->getType()));
2792       return nullptr;
2793     }
2794   }
2795 
2796   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
2797     // If CS does not return void then replaceAllUsesWith undef.
2798     // This allows ValueHandlers and custom metadata to adjust itself.
2799     if (!CS.getInstruction()->getType()->isVoidTy())
2800       replaceInstUsesWith(*CS.getInstruction(),
2801                           UndefValue::get(CS.getInstruction()->getType()));
2802 
2803     if (isa<InvokeInst>(CS.getInstruction())) {
2804       // Can't remove an invoke because we cannot change the CFG.
2805       return nullptr;
2806     }
2807 
2808     // This instruction is not reachable, just remove it.  We insert a store to
2809     // undef so that we know that this code is not reachable, despite the fact
2810     // that we can't modify the CFG here.
2811     new StoreInst(ConstantInt::getTrue(Callee->getContext()),
2812                   UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
2813                   CS.getInstruction());
2814 
2815     return eraseInstFromFunction(*CS.getInstruction());
2816   }
2817 
2818   if (IntrinsicInst *II = findInitTrampoline(Callee))
2819     return transformCallThroughTrampoline(CS, II);
2820 
2821   PointerType *PTy = cast<PointerType>(Callee->getType());
2822   FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
2823   if (FTy->isVarArg()) {
2824     int ix = FTy->getNumParams();
2825     // See if we can optimize any arguments passed through the varargs area of
2826     // the call.
2827     for (CallSite::arg_iterator I = CS.arg_begin() + FTy->getNumParams(),
2828            E = CS.arg_end(); I != E; ++I, ++ix) {
2829       CastInst *CI = dyn_cast<CastInst>(*I);
2830       if (CI && isSafeToEliminateVarargsCast(CS, DL, CI, ix)) {
2831         *I = CI->getOperand(0);
2832         Changed = true;
2833       }
2834     }
2835   }
2836 
2837   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
2838     // Inline asm calls cannot throw - mark them 'nounwind'.
2839     CS.setDoesNotThrow();
2840     Changed = true;
2841   }
2842 
2843   // Try to optimize the call if possible, we require DataLayout for most of
2844   // this.  None of these calls are seen as possibly dead so go ahead and
2845   // delete the instruction now.
2846   if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) {
2847     Instruction *I = tryOptimizeCall(CI);
2848     // If we changed something return the result, etc. Otherwise let
2849     // the fallthrough check.
2850     if (I) return eraseInstFromFunction(*I);
2851   }
2852 
2853   return Changed ? CS.getInstruction() : nullptr;
2854 }
2855 
2856 /// If the callee is a constexpr cast of a function, attempt to move the cast to
2857 /// the arguments of the call/invoke.
2858 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
2859   auto *Callee = dyn_cast<Function>(CS.getCalledValue()->stripPointerCasts());
2860   if (!Callee)
2861     return false;
2862 
2863   // The prototype of a thunk is a lie. Don't directly call such a function.
2864   if (Callee->hasFnAttribute("thunk"))
2865     return false;
2866 
2867   Instruction *Caller = CS.getInstruction();
2868   const AttributeSet &CallerPAL = CS.getAttributes();
2869 
2870   // Okay, this is a cast from a function to a different type.  Unless doing so
2871   // would cause a type conversion of one of our arguments, change this call to
2872   // be a direct call with arguments casted to the appropriate types.
2873   //
2874   FunctionType *FT = Callee->getFunctionType();
2875   Type *OldRetTy = Caller->getType();
2876   Type *NewRetTy = FT->getReturnType();
2877 
2878   // Check to see if we are changing the return type...
2879   if (OldRetTy != NewRetTy) {
2880 
2881     if (NewRetTy->isStructTy())
2882       return false; // TODO: Handle multiple return values.
2883 
2884     if (!CastInst::isBitOrNoopPointerCastable(NewRetTy, OldRetTy, DL)) {
2885       if (Callee->isDeclaration())
2886         return false;   // Cannot transform this return value.
2887 
2888       if (!Caller->use_empty() &&
2889           // void -> non-void is handled specially
2890           !NewRetTy->isVoidTy())
2891         return false;   // Cannot transform this return value.
2892     }
2893 
2894     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
2895       AttrBuilder RAttrs(CallerPAL, AttributeSet::ReturnIndex);
2896       if (RAttrs.overlaps(AttributeFuncs::typeIncompatible(NewRetTy)))
2897         return false;   // Attribute not compatible with transformed value.
2898     }
2899 
2900     // If the callsite is an invoke instruction, and the return value is used by
2901     // a PHI node in a successor, we cannot change the return type of the call
2902     // because there is no place to put the cast instruction (without breaking
2903     // the critical edge).  Bail out in this case.
2904     if (!Caller->use_empty())
2905       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
2906         for (User *U : II->users())
2907           if (PHINode *PN = dyn_cast<PHINode>(U))
2908             if (PN->getParent() == II->getNormalDest() ||
2909                 PN->getParent() == II->getUnwindDest())
2910               return false;
2911   }
2912 
2913   unsigned NumActualArgs = CS.arg_size();
2914   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
2915 
2916   // Prevent us turning:
2917   // declare void @takes_i32_inalloca(i32* inalloca)
2918   //  call void bitcast (void (i32*)* @takes_i32_inalloca to void (i32)*)(i32 0)
2919   //
2920   // into:
2921   //  call void @takes_i32_inalloca(i32* null)
2922   //
2923   //  Similarly, avoid folding away bitcasts of byval calls.
2924   if (Callee->getAttributes().hasAttrSomewhere(Attribute::InAlloca) ||
2925       Callee->getAttributes().hasAttrSomewhere(Attribute::ByVal))
2926     return false;
2927 
2928   CallSite::arg_iterator AI = CS.arg_begin();
2929   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
2930     Type *ParamTy = FT->getParamType(i);
2931     Type *ActTy = (*AI)->getType();
2932 
2933     if (!CastInst::isBitOrNoopPointerCastable(ActTy, ParamTy, DL))
2934       return false;   // Cannot transform this parameter value.
2935 
2936     if (AttrBuilder(CallerPAL.getParamAttributes(i + 1), i + 1).
2937           overlaps(AttributeFuncs::typeIncompatible(ParamTy)))
2938       return false;   // Attribute not compatible with transformed value.
2939 
2940     if (CS.isInAllocaArgument(i))
2941       return false;   // Cannot transform to and from inalloca.
2942 
2943     // If the parameter is passed as a byval argument, then we have to have a
2944     // sized type and the sized type has to have the same size as the old type.
2945     if (ParamTy != ActTy &&
2946         CallerPAL.getParamAttributes(i + 1).hasAttribute(i + 1,
2947                                                          Attribute::ByVal)) {
2948       PointerType *ParamPTy = dyn_cast<PointerType>(ParamTy);
2949       if (!ParamPTy || !ParamPTy->getElementType()->isSized())
2950         return false;
2951 
2952       Type *CurElTy = ActTy->getPointerElementType();
2953       if (DL.getTypeAllocSize(CurElTy) !=
2954           DL.getTypeAllocSize(ParamPTy->getElementType()))
2955         return false;
2956     }
2957   }
2958 
2959   if (Callee->isDeclaration()) {
2960     // Do not delete arguments unless we have a function body.
2961     if (FT->getNumParams() < NumActualArgs && !FT->isVarArg())
2962       return false;
2963 
2964     // If the callee is just a declaration, don't change the varargsness of the
2965     // call.  We don't want to introduce a varargs call where one doesn't
2966     // already exist.
2967     PointerType *APTy = cast<PointerType>(CS.getCalledValue()->getType());
2968     if (FT->isVarArg()!=cast<FunctionType>(APTy->getElementType())->isVarArg())
2969       return false;
2970 
2971     // If both the callee and the cast type are varargs, we still have to make
2972     // sure the number of fixed parameters are the same or we have the same
2973     // ABI issues as if we introduce a varargs call.
2974     if (FT->isVarArg() &&
2975         cast<FunctionType>(APTy->getElementType())->isVarArg() &&
2976         FT->getNumParams() !=
2977         cast<FunctionType>(APTy->getElementType())->getNumParams())
2978       return false;
2979   }
2980 
2981   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
2982       !CallerPAL.isEmpty())
2983     // In this case we have more arguments than the new function type, but we
2984     // won't be dropping them.  Check that these extra arguments have attributes
2985     // that are compatible with being a vararg call argument.
2986     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
2987       unsigned Index = CallerPAL.getSlotIndex(i - 1);
2988       if (Index <= FT->getNumParams())
2989         break;
2990 
2991       // Check if it has an attribute that's incompatible with varargs.
2992       AttributeSet PAttrs = CallerPAL.getSlotAttributes(i - 1);
2993       if (PAttrs.hasAttribute(Index, Attribute::StructRet))
2994         return false;
2995     }
2996 
2997 
2998   // Okay, we decided that this is a safe thing to do: go ahead and start
2999   // inserting cast instructions as necessary.
3000   std::vector<Value*> Args;
3001   Args.reserve(NumActualArgs);
3002   SmallVector<AttributeSet, 8> attrVec;
3003   attrVec.reserve(NumCommonArgs);
3004 
3005   // Get any return attributes.
3006   AttrBuilder RAttrs(CallerPAL, AttributeSet::ReturnIndex);
3007 
3008   // If the return value is not being used, the type may not be compatible
3009   // with the existing attributes.  Wipe out any problematic attributes.
3010   RAttrs.remove(AttributeFuncs::typeIncompatible(NewRetTy));
3011 
3012   // Add the new return attributes.
3013   if (RAttrs.hasAttributes())
3014     attrVec.push_back(AttributeSet::get(Caller->getContext(),
3015                                         AttributeSet::ReturnIndex, RAttrs));
3016 
3017   AI = CS.arg_begin();
3018   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
3019     Type *ParamTy = FT->getParamType(i);
3020 
3021     if ((*AI)->getType() == ParamTy) {
3022       Args.push_back(*AI);
3023     } else {
3024       Args.push_back(Builder->CreateBitOrPointerCast(*AI, ParamTy));
3025     }
3026 
3027     // Add any parameter attributes.
3028     AttrBuilder PAttrs(CallerPAL.getParamAttributes(i + 1), i + 1);
3029     if (PAttrs.hasAttributes())
3030       attrVec.push_back(AttributeSet::get(Caller->getContext(), i + 1,
3031                                           PAttrs));
3032   }
3033 
3034   // If the function takes more arguments than the call was taking, add them
3035   // now.
3036   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
3037     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
3038 
3039   // If we are removing arguments to the function, emit an obnoxious warning.
3040   if (FT->getNumParams() < NumActualArgs) {
3041     // TODO: if (!FT->isVarArg()) this call may be unreachable. PR14722
3042     if (FT->isVarArg()) {
3043       // Add all of the arguments in their promoted form to the arg list.
3044       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
3045         Type *PTy = getPromotedType((*AI)->getType());
3046         if (PTy != (*AI)->getType()) {
3047           // Must promote to pass through va_arg area!
3048           Instruction::CastOps opcode =
3049             CastInst::getCastOpcode(*AI, false, PTy, false);
3050           Args.push_back(Builder->CreateCast(opcode, *AI, PTy));
3051         } else {
3052           Args.push_back(*AI);
3053         }
3054 
3055         // Add any parameter attributes.
3056         AttrBuilder PAttrs(CallerPAL.getParamAttributes(i + 1), i + 1);
3057         if (PAttrs.hasAttributes())
3058           attrVec.push_back(AttributeSet::get(FT->getContext(), i + 1,
3059                                               PAttrs));
3060       }
3061     }
3062   }
3063 
3064   AttributeSet FnAttrs = CallerPAL.getFnAttributes();
3065   if (CallerPAL.hasAttributes(AttributeSet::FunctionIndex))
3066     attrVec.push_back(AttributeSet::get(Callee->getContext(), FnAttrs));
3067 
3068   if (NewRetTy->isVoidTy())
3069     Caller->setName("");   // Void type should not have a name.
3070 
3071   const AttributeSet &NewCallerPAL = AttributeSet::get(Callee->getContext(),
3072                                                        attrVec);
3073 
3074   SmallVector<OperandBundleDef, 1> OpBundles;
3075   CS.getOperandBundlesAsDefs(OpBundles);
3076 
3077   Instruction *NC;
3078   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
3079     NC = Builder->CreateInvoke(Callee, II->getNormalDest(), II->getUnwindDest(),
3080                                Args, OpBundles);
3081     NC->takeName(II);
3082     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
3083     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
3084   } else {
3085     CallInst *CI = cast<CallInst>(Caller);
3086     NC = Builder->CreateCall(Callee, Args, OpBundles);
3087     NC->takeName(CI);
3088     cast<CallInst>(NC)->setTailCallKind(CI->getTailCallKind());
3089     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
3090     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
3091   }
3092 
3093   // Insert a cast of the return type as necessary.
3094   Value *NV = NC;
3095   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
3096     if (!NV->getType()->isVoidTy()) {
3097       NV = NC = CastInst::CreateBitOrPointerCast(NC, OldRetTy);
3098       NC->setDebugLoc(Caller->getDebugLoc());
3099 
3100       // If this is an invoke instruction, we should insert it after the first
3101       // non-phi, instruction in the normal successor block.
3102       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
3103         BasicBlock::iterator I = II->getNormalDest()->getFirstInsertionPt();
3104         InsertNewInstBefore(NC, *I);
3105       } else {
3106         // Otherwise, it's a call, just insert cast right after the call.
3107         InsertNewInstBefore(NC, *Caller);
3108       }
3109       Worklist.AddUsersToWorkList(*Caller);
3110     } else {
3111       NV = UndefValue::get(Caller->getType());
3112     }
3113   }
3114 
3115   if (!Caller->use_empty())
3116     replaceInstUsesWith(*Caller, NV);
3117   else if (Caller->hasValueHandle()) {
3118     if (OldRetTy == NV->getType())
3119       ValueHandleBase::ValueIsRAUWd(Caller, NV);
3120     else
3121       // We cannot call ValueIsRAUWd with a different type, and the
3122       // actual tracked value will disappear.
3123       ValueHandleBase::ValueIsDeleted(Caller);
3124   }
3125 
3126   eraseInstFromFunction(*Caller);
3127   return true;
3128 }
3129 
3130 /// Turn a call to a function created by init_trampoline / adjust_trampoline
3131 /// intrinsic pair into a direct call to the underlying function.
3132 Instruction *
3133 InstCombiner::transformCallThroughTrampoline(CallSite CS,
3134                                              IntrinsicInst *Tramp) {
3135   Value *Callee = CS.getCalledValue();
3136   PointerType *PTy = cast<PointerType>(Callee->getType());
3137   FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
3138   const AttributeSet &Attrs = CS.getAttributes();
3139 
3140   // If the call already has the 'nest' attribute somewhere then give up -
3141   // otherwise 'nest' would occur twice after splicing in the chain.
3142   if (Attrs.hasAttrSomewhere(Attribute::Nest))
3143     return nullptr;
3144 
3145   assert(Tramp &&
3146          "transformCallThroughTrampoline called with incorrect CallSite.");
3147 
3148   Function *NestF =cast<Function>(Tramp->getArgOperand(1)->stripPointerCasts());
3149   FunctionType *NestFTy = cast<FunctionType>(NestF->getValueType());
3150 
3151   const AttributeSet &NestAttrs = NestF->getAttributes();
3152   if (!NestAttrs.isEmpty()) {
3153     unsigned NestIdx = 1;
3154     Type *NestTy = nullptr;
3155     AttributeSet NestAttr;
3156 
3157     // Look for a parameter marked with the 'nest' attribute.
3158     for (FunctionType::param_iterator I = NestFTy->param_begin(),
3159          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
3160       if (NestAttrs.hasAttribute(NestIdx, Attribute::Nest)) {
3161         // Record the parameter type and any other attributes.
3162         NestTy = *I;
3163         NestAttr = NestAttrs.getParamAttributes(NestIdx);
3164         break;
3165       }
3166 
3167     if (NestTy) {
3168       Instruction *Caller = CS.getInstruction();
3169       std::vector<Value*> NewArgs;
3170       NewArgs.reserve(CS.arg_size() + 1);
3171 
3172       SmallVector<AttributeSet, 8> NewAttrs;
3173       NewAttrs.reserve(Attrs.getNumSlots() + 1);
3174 
3175       // Insert the nest argument into the call argument list, which may
3176       // mean appending it.  Likewise for attributes.
3177 
3178       // Add any result attributes.
3179       if (Attrs.hasAttributes(AttributeSet::ReturnIndex))
3180         NewAttrs.push_back(AttributeSet::get(Caller->getContext(),
3181                                              Attrs.getRetAttributes()));
3182 
3183       {
3184         unsigned Idx = 1;
3185         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
3186         do {
3187           if (Idx == NestIdx) {
3188             // Add the chain argument and attributes.
3189             Value *NestVal = Tramp->getArgOperand(2);
3190             if (NestVal->getType() != NestTy)
3191               NestVal = Builder->CreateBitCast(NestVal, NestTy, "nest");
3192             NewArgs.push_back(NestVal);
3193             NewAttrs.push_back(AttributeSet::get(Caller->getContext(),
3194                                                  NestAttr));
3195           }
3196 
3197           if (I == E)
3198             break;
3199 
3200           // Add the original argument and attributes.
3201           NewArgs.push_back(*I);
3202           AttributeSet Attr = Attrs.getParamAttributes(Idx);
3203           if (Attr.hasAttributes(Idx)) {
3204             AttrBuilder B(Attr, Idx);
3205             NewAttrs.push_back(AttributeSet::get(Caller->getContext(),
3206                                                  Idx + (Idx >= NestIdx), B));
3207           }
3208 
3209           ++Idx;
3210           ++I;
3211         } while (true);
3212       }
3213 
3214       // Add any function attributes.
3215       if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
3216         NewAttrs.push_back(AttributeSet::get(FTy->getContext(),
3217                                              Attrs.getFnAttributes()));
3218 
3219       // The trampoline may have been bitcast to a bogus type (FTy).
3220       // Handle this by synthesizing a new function type, equal to FTy
3221       // with the chain parameter inserted.
3222 
3223       std::vector<Type*> NewTypes;
3224       NewTypes.reserve(FTy->getNumParams()+1);
3225 
3226       // Insert the chain's type into the list of parameter types, which may
3227       // mean appending it.
3228       {
3229         unsigned Idx = 1;
3230         FunctionType::param_iterator I = FTy->param_begin(),
3231           E = FTy->param_end();
3232 
3233         do {
3234           if (Idx == NestIdx)
3235             // Add the chain's type.
3236             NewTypes.push_back(NestTy);
3237 
3238           if (I == E)
3239             break;
3240 
3241           // Add the original type.
3242           NewTypes.push_back(*I);
3243 
3244           ++Idx;
3245           ++I;
3246         } while (true);
3247       }
3248 
3249       // Replace the trampoline call with a direct call.  Let the generic
3250       // code sort out any function type mismatches.
3251       FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
3252                                                 FTy->isVarArg());
3253       Constant *NewCallee =
3254         NestF->getType() == PointerType::getUnqual(NewFTy) ?
3255         NestF : ConstantExpr::getBitCast(NestF,
3256                                          PointerType::getUnqual(NewFTy));
3257       const AttributeSet &NewPAL =
3258           AttributeSet::get(FTy->getContext(), NewAttrs);
3259 
3260       SmallVector<OperandBundleDef, 1> OpBundles;
3261       CS.getOperandBundlesAsDefs(OpBundles);
3262 
3263       Instruction *NewCaller;
3264       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
3265         NewCaller = InvokeInst::Create(NewCallee,
3266                                        II->getNormalDest(), II->getUnwindDest(),
3267                                        NewArgs, OpBundles);
3268         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
3269         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
3270       } else {
3271         NewCaller = CallInst::Create(NewCallee, NewArgs, OpBundles);
3272         cast<CallInst>(NewCaller)->setTailCallKind(
3273             cast<CallInst>(Caller)->getTailCallKind());
3274         cast<CallInst>(NewCaller)->setCallingConv(
3275             cast<CallInst>(Caller)->getCallingConv());
3276         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
3277       }
3278 
3279       return NewCaller;
3280     }
3281   }
3282 
3283   // Replace the trampoline call with a direct call.  Since there is no 'nest'
3284   // parameter, there is no need to adjust the argument list.  Let the generic
3285   // code sort out any function type mismatches.
3286   Constant *NewCallee =
3287     NestF->getType() == PTy ? NestF :
3288                               ConstantExpr::getBitCast(NestF, PTy);
3289   CS.setCalledFunction(NewCallee);
3290   return CS.getInstruction();
3291 }
3292