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