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