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/SmallBitVector.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/Twine.h"
26 #include "llvm/Analysis/AliasAnalysis.h"
27 #include "llvm/Analysis/AssumeBundleQueries.h"
28 #include "llvm/Analysis/AssumptionCache.h"
29 #include "llvm/Analysis/InstructionSimplify.h"
30 #include "llvm/Analysis/Loads.h"
31 #include "llvm/Analysis/MemoryBuiltins.h"
32 #include "llvm/Analysis/TargetTransformInfo.h"
33 #include "llvm/Analysis/ValueTracking.h"
34 #include "llvm/Analysis/VectorUtils.h"
35 #include "llvm/IR/Attributes.h"
36 #include "llvm/IR/BasicBlock.h"
37 #include "llvm/IR/Constant.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/DataLayout.h"
40 #include "llvm/IR/DerivedTypes.h"
41 #include "llvm/IR/Function.h"
42 #include "llvm/IR/GlobalVariable.h"
43 #include "llvm/IR/InlineAsm.h"
44 #include "llvm/IR/InstrTypes.h"
45 #include "llvm/IR/Instruction.h"
46 #include "llvm/IR/Instructions.h"
47 #include "llvm/IR/IntrinsicInst.h"
48 #include "llvm/IR/Intrinsics.h"
49 #include "llvm/IR/IntrinsicsAArch64.h"
50 #include "llvm/IR/IntrinsicsAMDGPU.h"
51 #include "llvm/IR/IntrinsicsARM.h"
52 #include "llvm/IR/IntrinsicsHexagon.h"
53 #include "llvm/IR/LLVMContext.h"
54 #include "llvm/IR/Metadata.h"
55 #include "llvm/IR/PatternMatch.h"
56 #include "llvm/IR/Statepoint.h"
57 #include "llvm/IR/Type.h"
58 #include "llvm/IR/User.h"
59 #include "llvm/IR/Value.h"
60 #include "llvm/IR/ValueHandle.h"
61 #include "llvm/Support/AtomicOrdering.h"
62 #include "llvm/Support/Casting.h"
63 #include "llvm/Support/CommandLine.h"
64 #include "llvm/Support/Compiler.h"
65 #include "llvm/Support/Debug.h"
66 #include "llvm/Support/ErrorHandling.h"
67 #include "llvm/Support/KnownBits.h"
68 #include "llvm/Support/MathExtras.h"
69 #include "llvm/Support/raw_ostream.h"
70 #include "llvm/Transforms/InstCombine/InstCombineWorklist.h"
71 #include "llvm/Transforms/InstCombine/InstCombiner.h"
72 #include "llvm/Transforms/Utils/AssumeBundleBuilder.h"
73 #include "llvm/Transforms/Utils/Local.h"
74 #include "llvm/Transforms/Utils/SimplifyLibCalls.h"
75 #include <algorithm>
76 #include <cassert>
77 #include <cstdint>
78 #include <cstring>
79 #include <utility>
80 #include <vector>
81 
82 using namespace llvm;
83 using namespace PatternMatch;
84 
85 #define DEBUG_TYPE "instcombine"
86 
87 STATISTIC(NumSimplified, "Number of library calls simplified");
88 
89 static cl::opt<unsigned> GuardWideningWindow(
90     "instcombine-guard-widening-window",
91     cl::init(3),
92     cl::desc("How wide an instruction window to bypass looking for "
93              "another guard"));
94 
95 namespace llvm {
96 /// enable preservation of attributes in assume like:
97 /// call void @llvm.assume(i1 true) [ "nonnull"(i32* %PTR) ]
98 extern cl::opt<bool> EnableKnowledgeRetention;
99 } // namespace llvm
100 
101 /// Return the specified type promoted as it would be to pass though a va_arg
102 /// area.
103 static Type *getPromotedType(Type *Ty) {
104   if (IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
105     if (ITy->getBitWidth() < 32)
106       return Type::getInt32Ty(Ty->getContext());
107   }
108   return Ty;
109 }
110 
111 Instruction *InstCombinerImpl::SimplifyAnyMemTransfer(AnyMemTransferInst *MI) {
112   Align DstAlign = getKnownAlignment(MI->getRawDest(), DL, MI, &AC, &DT);
113   MaybeAlign CopyDstAlign = MI->getDestAlign();
114   if (!CopyDstAlign || *CopyDstAlign < DstAlign) {
115     MI->setDestAlignment(DstAlign);
116     return MI;
117   }
118 
119   Align SrcAlign = getKnownAlignment(MI->getRawSource(), DL, MI, &AC, &DT);
120   MaybeAlign CopySrcAlign = MI->getSourceAlign();
121   if (!CopySrcAlign || *CopySrcAlign < SrcAlign) {
122     MI->setSourceAlignment(SrcAlign);
123     return MI;
124   }
125 
126   // If we have a store to a location which is known constant, we can conclude
127   // that the store must be storing the constant value (else the memory
128   // wouldn't be constant), and this must be a noop.
129   if (AA->pointsToConstantMemory(MI->getDest())) {
130     // Set the size of the copy to 0, it will be deleted on the next iteration.
131     MI->setLength(Constant::getNullValue(MI->getLength()->getType()));
132     return MI;
133   }
134 
135   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
136   // load/store.
137   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getLength());
138   if (!MemOpLength) return nullptr;
139 
140   // Source and destination pointer types are always "i8*" for intrinsic.  See
141   // if the size is something we can handle with a single primitive load/store.
142   // A single load+store correctly handles overlapping memory in the memmove
143   // case.
144   uint64_t Size = MemOpLength->getLimitedValue();
145   assert(Size && "0-sized memory transferring should be removed already.");
146 
147   if (Size > 8 || (Size&(Size-1)))
148     return nullptr;  // If not 1/2/4/8 bytes, exit.
149 
150   // If it is an atomic and alignment is less than the size then we will
151   // introduce the unaligned memory access which will be later transformed
152   // into libcall in CodeGen. This is not evident performance gain so disable
153   // it now.
154   if (isa<AtomicMemTransferInst>(MI))
155     if (*CopyDstAlign < Size || *CopySrcAlign < Size)
156       return nullptr;
157 
158   // Use an integer load+store unless we can find something better.
159   unsigned SrcAddrSp =
160     cast<PointerType>(MI->getArgOperand(1)->getType())->getAddressSpace();
161   unsigned DstAddrSp =
162     cast<PointerType>(MI->getArgOperand(0)->getType())->getAddressSpace();
163 
164   IntegerType* IntType = IntegerType::get(MI->getContext(), Size<<3);
165   Type *NewSrcPtrTy = PointerType::get(IntType, SrcAddrSp);
166   Type *NewDstPtrTy = PointerType::get(IntType, DstAddrSp);
167 
168   // If the memcpy has metadata describing the members, see if we can get the
169   // TBAA tag describing our copy.
170   MDNode *CopyMD = nullptr;
171   if (MDNode *M = MI->getMetadata(LLVMContext::MD_tbaa)) {
172     CopyMD = M;
173   } else if (MDNode *M = MI->getMetadata(LLVMContext::MD_tbaa_struct)) {
174     if (M->getNumOperands() == 3 && M->getOperand(0) &&
175         mdconst::hasa<ConstantInt>(M->getOperand(0)) &&
176         mdconst::extract<ConstantInt>(M->getOperand(0))->isZero() &&
177         M->getOperand(1) &&
178         mdconst::hasa<ConstantInt>(M->getOperand(1)) &&
179         mdconst::extract<ConstantInt>(M->getOperand(1))->getValue() ==
180         Size &&
181         M->getOperand(2) && isa<MDNode>(M->getOperand(2)))
182       CopyMD = cast<MDNode>(M->getOperand(2));
183   }
184 
185   Value *Src = Builder.CreateBitCast(MI->getArgOperand(1), NewSrcPtrTy);
186   Value *Dest = Builder.CreateBitCast(MI->getArgOperand(0), NewDstPtrTy);
187   LoadInst *L = Builder.CreateLoad(IntType, Src);
188   // Alignment from the mem intrinsic will be better, so use it.
189   L->setAlignment(*CopySrcAlign);
190   if (CopyMD)
191     L->setMetadata(LLVMContext::MD_tbaa, CopyMD);
192   MDNode *LoopMemParallelMD =
193     MI->getMetadata(LLVMContext::MD_mem_parallel_loop_access);
194   if (LoopMemParallelMD)
195     L->setMetadata(LLVMContext::MD_mem_parallel_loop_access, LoopMemParallelMD);
196   MDNode *AccessGroupMD = MI->getMetadata(LLVMContext::MD_access_group);
197   if (AccessGroupMD)
198     L->setMetadata(LLVMContext::MD_access_group, AccessGroupMD);
199 
200   StoreInst *S = Builder.CreateStore(L, Dest);
201   // Alignment from the mem intrinsic will be better, so use it.
202   S->setAlignment(*CopyDstAlign);
203   if (CopyMD)
204     S->setMetadata(LLVMContext::MD_tbaa, CopyMD);
205   if (LoopMemParallelMD)
206     S->setMetadata(LLVMContext::MD_mem_parallel_loop_access, LoopMemParallelMD);
207   if (AccessGroupMD)
208     S->setMetadata(LLVMContext::MD_access_group, AccessGroupMD);
209 
210   if (auto *MT = dyn_cast<MemTransferInst>(MI)) {
211     // non-atomics can be volatile
212     L->setVolatile(MT->isVolatile());
213     S->setVolatile(MT->isVolatile());
214   }
215   if (isa<AtomicMemTransferInst>(MI)) {
216     // atomics have to be unordered
217     L->setOrdering(AtomicOrdering::Unordered);
218     S->setOrdering(AtomicOrdering::Unordered);
219   }
220 
221   // Set the size of the copy to 0, it will be deleted on the next iteration.
222   MI->setLength(Constant::getNullValue(MemOpLength->getType()));
223   return MI;
224 }
225 
226 Instruction *InstCombinerImpl::SimplifyAnyMemSet(AnyMemSetInst *MI) {
227   const Align KnownAlignment =
228       getKnownAlignment(MI->getDest(), DL, MI, &AC, &DT);
229   MaybeAlign MemSetAlign = MI->getDestAlign();
230   if (!MemSetAlign || *MemSetAlign < KnownAlignment) {
231     MI->setDestAlignment(KnownAlignment);
232     return MI;
233   }
234 
235   // If we have a store to a location which is known constant, we can conclude
236   // that the store must be storing the constant value (else the memory
237   // wouldn't be constant), and this must be a noop.
238   if (AA->pointsToConstantMemory(MI->getDest())) {
239     // Set the size of the copy to 0, it will be deleted on the next iteration.
240     MI->setLength(Constant::getNullValue(MI->getLength()->getType()));
241     return MI;
242   }
243 
244   // Extract the length and alignment and fill if they are constant.
245   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
246   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
247   if (!LenC || !FillC || !FillC->getType()->isIntegerTy(8))
248     return nullptr;
249   const uint64_t Len = LenC->getLimitedValue();
250   assert(Len && "0-sized memory setting should be removed already.");
251   const Align Alignment = assumeAligned(MI->getDestAlignment());
252 
253   // If it is an atomic and alignment is less than the size then we will
254   // introduce the unaligned memory access which will be later transformed
255   // into libcall in CodeGen. This is not evident performance gain so disable
256   // it now.
257   if (isa<AtomicMemSetInst>(MI))
258     if (Alignment < Len)
259       return nullptr;
260 
261   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
262   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
263     Type *ITy = IntegerType::get(MI->getContext(), Len*8);  // n=1 -> i8.
264 
265     Value *Dest = MI->getDest();
266     unsigned DstAddrSp = cast<PointerType>(Dest->getType())->getAddressSpace();
267     Type *NewDstPtrTy = PointerType::get(ITy, DstAddrSp);
268     Dest = Builder.CreateBitCast(Dest, NewDstPtrTy);
269 
270     // Extract the fill value and store.
271     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
272     StoreInst *S = Builder.CreateStore(ConstantInt::get(ITy, Fill), Dest,
273                                        MI->isVolatile());
274     S->setAlignment(Alignment);
275     if (isa<AtomicMemSetInst>(MI))
276       S->setOrdering(AtomicOrdering::Unordered);
277 
278     // Set the size of the copy to 0, it will be deleted on the next iteration.
279     MI->setLength(Constant::getNullValue(LenC->getType()));
280     return MI;
281   }
282 
283   return nullptr;
284 }
285 
286 // TODO, Obvious Missing Transforms:
287 // * Narrow width by halfs excluding zero/undef lanes
288 Value *InstCombinerImpl::simplifyMaskedLoad(IntrinsicInst &II) {
289   Value *LoadPtr = II.getArgOperand(0);
290   const Align Alignment =
291       cast<ConstantInt>(II.getArgOperand(1))->getAlignValue();
292 
293   // If the mask is all ones or undefs, this is a plain vector load of the 1st
294   // argument.
295   if (maskIsAllOneOrUndef(II.getArgOperand(2))) {
296     LoadInst *L = Builder.CreateAlignedLoad(II.getType(), LoadPtr, Alignment,
297                                             "unmaskedload");
298     L->copyMetadata(II);
299     return L;
300   }
301 
302   // If we can unconditionally load from this address, replace with a
303   // load/select idiom. TODO: use DT for context sensitive query
304   if (isDereferenceablePointer(LoadPtr, II.getType(),
305                                II.getModule()->getDataLayout(), &II, nullptr)) {
306     LoadInst *LI = Builder.CreateAlignedLoad(II.getType(), LoadPtr, Alignment,
307                                              "unmaskedload");
308     LI->copyMetadata(II);
309     return Builder.CreateSelect(II.getArgOperand(2), LI, II.getArgOperand(3));
310   }
311 
312   return nullptr;
313 }
314 
315 // TODO, Obvious Missing Transforms:
316 // * Single constant active lane -> store
317 // * Narrow width by halfs excluding zero/undef lanes
318 Instruction *InstCombinerImpl::simplifyMaskedStore(IntrinsicInst &II) {
319   auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3));
320   if (!ConstMask)
321     return nullptr;
322 
323   // If the mask is all zeros, this instruction does nothing.
324   if (ConstMask->isNullValue())
325     return eraseInstFromFunction(II);
326 
327   // If the mask is all ones, this is a plain vector store of the 1st argument.
328   if (ConstMask->isAllOnesValue()) {
329     Value *StorePtr = II.getArgOperand(1);
330     Align Alignment = cast<ConstantInt>(II.getArgOperand(2))->getAlignValue();
331     StoreInst *S =
332         new StoreInst(II.getArgOperand(0), StorePtr, false, Alignment);
333     S->copyMetadata(II);
334     return S;
335   }
336 
337   if (isa<ScalableVectorType>(ConstMask->getType()))
338     return nullptr;
339 
340   // Use masked off lanes to simplify operands via SimplifyDemandedVectorElts
341   APInt DemandedElts = possiblyDemandedEltsInMask(ConstMask);
342   APInt UndefElts(DemandedElts.getBitWidth(), 0);
343   if (Value *V =
344           SimplifyDemandedVectorElts(II.getOperand(0), DemandedElts, UndefElts))
345     return replaceOperand(II, 0, V);
346 
347   return nullptr;
348 }
349 
350 // TODO, Obvious Missing Transforms:
351 // * Single constant active lane load -> load
352 // * Dereferenceable address & few lanes -> scalarize speculative load/selects
353 // * Adjacent vector addresses -> masked.load
354 // * Narrow width by halfs excluding zero/undef lanes
355 // * Vector splat address w/known mask -> scalar load
356 // * Vector incrementing address -> vector masked load
357 Instruction *InstCombinerImpl::simplifyMaskedGather(IntrinsicInst &II) {
358   return nullptr;
359 }
360 
361 // TODO, Obvious Missing Transforms:
362 // * Single constant active lane -> store
363 // * Adjacent vector addresses -> masked.store
364 // * Narrow store width by halfs excluding zero/undef lanes
365 // * Vector splat address w/known mask -> scalar store
366 // * Vector incrementing address -> vector masked store
367 Instruction *InstCombinerImpl::simplifyMaskedScatter(IntrinsicInst &II) {
368   auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3));
369   if (!ConstMask)
370     return nullptr;
371 
372   // If the mask is all zeros, a scatter does nothing.
373   if (ConstMask->isNullValue())
374     return eraseInstFromFunction(II);
375 
376   if (isa<ScalableVectorType>(ConstMask->getType()))
377     return nullptr;
378 
379   // Use masked off lanes to simplify operands via SimplifyDemandedVectorElts
380   APInt DemandedElts = possiblyDemandedEltsInMask(ConstMask);
381   APInt UndefElts(DemandedElts.getBitWidth(), 0);
382   if (Value *V =
383           SimplifyDemandedVectorElts(II.getOperand(0), DemandedElts, UndefElts))
384     return replaceOperand(II, 0, V);
385   if (Value *V =
386           SimplifyDemandedVectorElts(II.getOperand(1), DemandedElts, UndefElts))
387     return replaceOperand(II, 1, V);
388 
389   return nullptr;
390 }
391 
392 /// This function transforms launder.invariant.group and strip.invariant.group
393 /// like:
394 /// launder(launder(%x)) -> launder(%x)       (the result is not the argument)
395 /// launder(strip(%x)) -> launder(%x)
396 /// strip(strip(%x)) -> strip(%x)             (the result is not the argument)
397 /// strip(launder(%x)) -> strip(%x)
398 /// This is legal because it preserves the most recent information about
399 /// the presence or absence of invariant.group.
400 static Instruction *simplifyInvariantGroupIntrinsic(IntrinsicInst &II,
401                                                     InstCombinerImpl &IC) {
402   auto *Arg = II.getArgOperand(0);
403   auto *StrippedArg = Arg->stripPointerCasts();
404   auto *StrippedInvariantGroupsArg = StrippedArg;
405   while (auto *Intr = dyn_cast<IntrinsicInst>(StrippedInvariantGroupsArg)) {
406     if (Intr->getIntrinsicID() != Intrinsic::launder_invariant_group &&
407         Intr->getIntrinsicID() != Intrinsic::strip_invariant_group)
408       break;
409     StrippedInvariantGroupsArg = Intr->getArgOperand(0)->stripPointerCasts();
410   }
411   if (StrippedArg == StrippedInvariantGroupsArg)
412     return nullptr; // No launders/strips to remove.
413 
414   Value *Result = nullptr;
415 
416   if (II.getIntrinsicID() == Intrinsic::launder_invariant_group)
417     Result = IC.Builder.CreateLaunderInvariantGroup(StrippedInvariantGroupsArg);
418   else if (II.getIntrinsicID() == Intrinsic::strip_invariant_group)
419     Result = IC.Builder.CreateStripInvariantGroup(StrippedInvariantGroupsArg);
420   else
421     llvm_unreachable(
422         "simplifyInvariantGroupIntrinsic only handles launder and strip");
423   if (Result->getType()->getPointerAddressSpace() !=
424       II.getType()->getPointerAddressSpace())
425     Result = IC.Builder.CreateAddrSpaceCast(Result, II.getType());
426   if (Result->getType() != II.getType())
427     Result = IC.Builder.CreateBitCast(Result, II.getType());
428 
429   return cast<Instruction>(Result);
430 }
431 
432 static Instruction *foldCttzCtlz(IntrinsicInst &II, InstCombinerImpl &IC) {
433   assert((II.getIntrinsicID() == Intrinsic::cttz ||
434           II.getIntrinsicID() == Intrinsic::ctlz) &&
435          "Expected cttz or ctlz intrinsic");
436   bool IsTZ = II.getIntrinsicID() == Intrinsic::cttz;
437   Value *Op0 = II.getArgOperand(0);
438   Value *Op1 = II.getArgOperand(1);
439   Value *X;
440   // ctlz(bitreverse(x)) -> cttz(x)
441   // cttz(bitreverse(x)) -> ctlz(x)
442   if (match(Op0, m_BitReverse(m_Value(X)))) {
443     Intrinsic::ID ID = IsTZ ? Intrinsic::ctlz : Intrinsic::cttz;
444     Function *F = Intrinsic::getDeclaration(II.getModule(), ID, II.getType());
445     return CallInst::Create(F, {X, II.getArgOperand(1)});
446   }
447 
448   if (II.getType()->isIntOrIntVectorTy(1)) {
449     // ctlz/cttz i1 Op0 --> not Op0
450     if (match(Op1, m_Zero()))
451       return BinaryOperator::CreateNot(Op0);
452     // If zero is undef, then the input can be assumed to be "true", so the
453     // instruction simplifies to "false".
454     assert(match(Op1, m_One()) && "Expected ctlz/cttz operand to be 0 or 1");
455     return IC.replaceInstUsesWith(II, ConstantInt::getNullValue(II.getType()));
456   }
457 
458   // If the operand is a select with constant arm(s), try to hoist ctlz/cttz.
459   if (auto *Sel = dyn_cast<SelectInst>(Op0))
460     if (Instruction *R = IC.FoldOpIntoSelect(II, Sel))
461       return R;
462 
463   if (IsTZ) {
464     // cttz(-x) -> cttz(x)
465     if (match(Op0, m_Neg(m_Value(X))))
466       return IC.replaceOperand(II, 0, X);
467 
468     // cttz(sext(x)) -> cttz(zext(x))
469     if (match(Op0, m_OneUse(m_SExt(m_Value(X))))) {
470       auto *Zext = IC.Builder.CreateZExt(X, II.getType());
471       auto *CttzZext =
472           IC.Builder.CreateBinaryIntrinsic(Intrinsic::cttz, Zext, Op1);
473       return IC.replaceInstUsesWith(II, CttzZext);
474     }
475 
476     // Zext doesn't change the number of trailing zeros, so narrow:
477     // cttz(zext(x)) -> zext(cttz(x)) if the 'ZeroIsUndef' parameter is 'true'.
478     if (match(Op0, m_OneUse(m_ZExt(m_Value(X)))) && match(Op1, m_One())) {
479       auto *Cttz = IC.Builder.CreateBinaryIntrinsic(Intrinsic::cttz, X,
480                                                     IC.Builder.getTrue());
481       auto *ZextCttz = IC.Builder.CreateZExt(Cttz, II.getType());
482       return IC.replaceInstUsesWith(II, ZextCttz);
483     }
484 
485     // cttz(abs(x)) -> cttz(x)
486     // cttz(nabs(x)) -> cttz(x)
487     Value *Y;
488     SelectPatternFlavor SPF = matchSelectPattern(Op0, X, Y).Flavor;
489     if (SPF == SPF_ABS || SPF == SPF_NABS)
490       return IC.replaceOperand(II, 0, X);
491 
492     if (match(Op0, m_Intrinsic<Intrinsic::abs>(m_Value(X))))
493       return IC.replaceOperand(II, 0, X);
494   }
495 
496   KnownBits Known = IC.computeKnownBits(Op0, 0, &II);
497 
498   // Create a mask for bits above (ctlz) or below (cttz) the first known one.
499   unsigned PossibleZeros = IsTZ ? Known.countMaxTrailingZeros()
500                                 : Known.countMaxLeadingZeros();
501   unsigned DefiniteZeros = IsTZ ? Known.countMinTrailingZeros()
502                                 : Known.countMinLeadingZeros();
503 
504   // If all bits above (ctlz) or below (cttz) the first known one are known
505   // zero, this value is constant.
506   // FIXME: This should be in InstSimplify because we're replacing an
507   // instruction with a constant.
508   if (PossibleZeros == DefiniteZeros) {
509     auto *C = ConstantInt::get(Op0->getType(), DefiniteZeros);
510     return IC.replaceInstUsesWith(II, C);
511   }
512 
513   // If the input to cttz/ctlz is known to be non-zero,
514   // then change the 'ZeroIsUndef' parameter to 'true'
515   // because we know the zero behavior can't affect the result.
516   if (!Known.One.isNullValue() ||
517       isKnownNonZero(Op0, IC.getDataLayout(), 0, &IC.getAssumptionCache(), &II,
518                      &IC.getDominatorTree())) {
519     if (!match(II.getArgOperand(1), m_One()))
520       return IC.replaceOperand(II, 1, IC.Builder.getTrue());
521   }
522 
523   // Add range metadata since known bits can't completely reflect what we know.
524   // TODO: Handle splat vectors.
525   auto *IT = dyn_cast<IntegerType>(Op0->getType());
526   if (IT && IT->getBitWidth() != 1 && !II.getMetadata(LLVMContext::MD_range)) {
527     Metadata *LowAndHigh[] = {
528         ConstantAsMetadata::get(ConstantInt::get(IT, DefiniteZeros)),
529         ConstantAsMetadata::get(ConstantInt::get(IT, PossibleZeros + 1))};
530     II.setMetadata(LLVMContext::MD_range,
531                    MDNode::get(II.getContext(), LowAndHigh));
532     return &II;
533   }
534 
535   return nullptr;
536 }
537 
538 static Instruction *foldCtpop(IntrinsicInst &II, InstCombinerImpl &IC) {
539   assert(II.getIntrinsicID() == Intrinsic::ctpop &&
540          "Expected ctpop intrinsic");
541   Type *Ty = II.getType();
542   unsigned BitWidth = Ty->getScalarSizeInBits();
543   Value *Op0 = II.getArgOperand(0);
544   Value *X, *Y;
545 
546   // ctpop(bitreverse(x)) -> ctpop(x)
547   // ctpop(bswap(x)) -> ctpop(x)
548   if (match(Op0, m_BitReverse(m_Value(X))) || match(Op0, m_BSwap(m_Value(X))))
549     return IC.replaceOperand(II, 0, X);
550 
551   // ctpop(rot(x)) -> ctpop(x)
552   if ((match(Op0, m_FShl(m_Value(X), m_Value(Y), m_Value())) ||
553        match(Op0, m_FShr(m_Value(X), m_Value(Y), m_Value()))) &&
554       X == Y)
555     return IC.replaceOperand(II, 0, X);
556 
557   // ctpop(x | -x) -> bitwidth - cttz(x, false)
558   if (Op0->hasOneUse() &&
559       match(Op0, m_c_Or(m_Value(X), m_Neg(m_Deferred(X))))) {
560     Function *F =
561         Intrinsic::getDeclaration(II.getModule(), Intrinsic::cttz, Ty);
562     auto *Cttz = IC.Builder.CreateCall(F, {X, IC.Builder.getFalse()});
563     auto *Bw = ConstantInt::get(Ty, APInt(BitWidth, BitWidth));
564     return IC.replaceInstUsesWith(II, IC.Builder.CreateSub(Bw, Cttz));
565   }
566 
567   // ctpop(~x & (x - 1)) -> cttz(x, false)
568   if (match(Op0,
569             m_c_And(m_Not(m_Value(X)), m_Add(m_Deferred(X), m_AllOnes())))) {
570     Function *F =
571         Intrinsic::getDeclaration(II.getModule(), Intrinsic::cttz, Ty);
572     return CallInst::Create(F, {X, IC.Builder.getFalse()});
573   }
574 
575   // Zext doesn't change the number of set bits, so narrow:
576   // ctpop (zext X) --> zext (ctpop X)
577   if (match(Op0, m_OneUse(m_ZExt(m_Value(X))))) {
578     Value *NarrowPop = IC.Builder.CreateUnaryIntrinsic(Intrinsic::ctpop, X);
579     return CastInst::Create(Instruction::ZExt, NarrowPop, Ty);
580   }
581 
582   // If the operand is a select with constant arm(s), try to hoist ctpop.
583   if (auto *Sel = dyn_cast<SelectInst>(Op0))
584     if (Instruction *R = IC.FoldOpIntoSelect(II, Sel))
585       return R;
586 
587   KnownBits Known(BitWidth);
588   IC.computeKnownBits(Op0, Known, 0, &II);
589 
590   // If all bits are zero except for exactly one fixed bit, then the result
591   // must be 0 or 1, and we can get that answer by shifting to LSB:
592   // ctpop (X & 32) --> (X & 32) >> 5
593   if ((~Known.Zero).isPowerOf2())
594     return BinaryOperator::CreateLShr(
595         Op0, ConstantInt::get(Ty, (~Known.Zero).exactLogBase2()));
596 
597   // FIXME: Try to simplify vectors of integers.
598   auto *IT = dyn_cast<IntegerType>(Ty);
599   if (!IT)
600     return nullptr;
601 
602   // Add range metadata since known bits can't completely reflect what we know.
603   unsigned MinCount = Known.countMinPopulation();
604   unsigned MaxCount = Known.countMaxPopulation();
605   if (IT->getBitWidth() != 1 && !II.getMetadata(LLVMContext::MD_range)) {
606     Metadata *LowAndHigh[] = {
607         ConstantAsMetadata::get(ConstantInt::get(IT, MinCount)),
608         ConstantAsMetadata::get(ConstantInt::get(IT, MaxCount + 1))};
609     II.setMetadata(LLVMContext::MD_range,
610                    MDNode::get(II.getContext(), LowAndHigh));
611     return &II;
612   }
613 
614   return nullptr;
615 }
616 
617 /// Convert a table lookup to shufflevector if the mask is constant.
618 /// This could benefit tbl1 if the mask is { 7,6,5,4,3,2,1,0 }, in
619 /// which case we could lower the shufflevector with rev64 instructions
620 /// as it's actually a byte reverse.
621 static Value *simplifyNeonTbl1(const IntrinsicInst &II,
622                                InstCombiner::BuilderTy &Builder) {
623   // Bail out if the mask is not a constant.
624   auto *C = dyn_cast<Constant>(II.getArgOperand(1));
625   if (!C)
626     return nullptr;
627 
628   auto *VecTy = cast<FixedVectorType>(II.getType());
629   unsigned NumElts = VecTy->getNumElements();
630 
631   // Only perform this transformation for <8 x i8> vector types.
632   if (!VecTy->getElementType()->isIntegerTy(8) || NumElts != 8)
633     return nullptr;
634 
635   int Indexes[8];
636 
637   for (unsigned I = 0; I < NumElts; ++I) {
638     Constant *COp = C->getAggregateElement(I);
639 
640     if (!COp || !isa<ConstantInt>(COp))
641       return nullptr;
642 
643     Indexes[I] = cast<ConstantInt>(COp)->getLimitedValue();
644 
645     // Make sure the mask indices are in range.
646     if ((unsigned)Indexes[I] >= NumElts)
647       return nullptr;
648   }
649 
650   auto *V1 = II.getArgOperand(0);
651   auto *V2 = Constant::getNullValue(V1->getType());
652   return Builder.CreateShuffleVector(V1, V2, makeArrayRef(Indexes));
653 }
654 
655 // Returns true iff the 2 intrinsics have the same operands, limiting the
656 // comparison to the first NumOperands.
657 static bool haveSameOperands(const IntrinsicInst &I, const IntrinsicInst &E,
658                              unsigned NumOperands) {
659   assert(I.getNumArgOperands() >= NumOperands && "Not enough operands");
660   assert(E.getNumArgOperands() >= NumOperands && "Not enough operands");
661   for (unsigned i = 0; i < NumOperands; i++)
662     if (I.getArgOperand(i) != E.getArgOperand(i))
663       return false;
664   return true;
665 }
666 
667 // Remove trivially empty start/end intrinsic ranges, i.e. a start
668 // immediately followed by an end (ignoring debuginfo or other
669 // start/end intrinsics in between). As this handles only the most trivial
670 // cases, tracking the nesting level is not needed:
671 //
672 //   call @llvm.foo.start(i1 0)
673 //   call @llvm.foo.start(i1 0) ; This one won't be skipped: it will be removed
674 //   call @llvm.foo.end(i1 0)
675 //   call @llvm.foo.end(i1 0) ; &I
676 static bool
677 removeTriviallyEmptyRange(IntrinsicInst &EndI, InstCombinerImpl &IC,
678                           std::function<bool(const IntrinsicInst &)> IsStart) {
679   // We start from the end intrinsic and scan backwards, so that InstCombine
680   // has already processed (and potentially removed) all the instructions
681   // before the end intrinsic.
682   BasicBlock::reverse_iterator BI(EndI), BE(EndI.getParent()->rend());
683   for (; BI != BE; ++BI) {
684     if (auto *I = dyn_cast<IntrinsicInst>(&*BI)) {
685       if (isa<DbgInfoIntrinsic>(I) ||
686           I->getIntrinsicID() == EndI.getIntrinsicID())
687         continue;
688       if (IsStart(*I)) {
689         if (haveSameOperands(EndI, *I, EndI.getNumArgOperands())) {
690           IC.eraseInstFromFunction(*I);
691           IC.eraseInstFromFunction(EndI);
692           return true;
693         }
694         // Skip start intrinsics that don't pair with this end intrinsic.
695         continue;
696       }
697     }
698     break;
699   }
700 
701   return false;
702 }
703 
704 Instruction *InstCombinerImpl::visitVAEndInst(VAEndInst &I) {
705   removeTriviallyEmptyRange(I, *this, [](const IntrinsicInst &I) {
706     return I.getIntrinsicID() == Intrinsic::vastart ||
707            I.getIntrinsicID() == Intrinsic::vacopy;
708   });
709   return nullptr;
710 }
711 
712 static CallInst *canonicalizeConstantArg0ToArg1(CallInst &Call) {
713   assert(Call.getNumArgOperands() > 1 && "Need at least 2 args to swap");
714   Value *Arg0 = Call.getArgOperand(0), *Arg1 = Call.getArgOperand(1);
715   if (isa<Constant>(Arg0) && !isa<Constant>(Arg1)) {
716     Call.setArgOperand(0, Arg1);
717     Call.setArgOperand(1, Arg0);
718     return &Call;
719   }
720   return nullptr;
721 }
722 
723 /// Creates a result tuple for an overflow intrinsic \p II with a given
724 /// \p Result and a constant \p Overflow value.
725 static Instruction *createOverflowTuple(IntrinsicInst *II, Value *Result,
726                                         Constant *Overflow) {
727   Constant *V[] = {UndefValue::get(Result->getType()), Overflow};
728   StructType *ST = cast<StructType>(II->getType());
729   Constant *Struct = ConstantStruct::get(ST, V);
730   return InsertValueInst::Create(Struct, Result, 0);
731 }
732 
733 Instruction *
734 InstCombinerImpl::foldIntrinsicWithOverflowCommon(IntrinsicInst *II) {
735   WithOverflowInst *WO = cast<WithOverflowInst>(II);
736   Value *OperationResult = nullptr;
737   Constant *OverflowResult = nullptr;
738   if (OptimizeOverflowCheck(WO->getBinaryOp(), WO->isSigned(), WO->getLHS(),
739                             WO->getRHS(), *WO, OperationResult, OverflowResult))
740     return createOverflowTuple(WO, OperationResult, OverflowResult);
741   return nullptr;
742 }
743 
744 static Optional<bool> getKnownSign(Value *Op, Instruction *CxtI,
745                                    const DataLayout &DL, AssumptionCache *AC,
746                                    DominatorTree *DT) {
747   KnownBits Known = computeKnownBits(Op, DL, 0, AC, CxtI, DT);
748   if (Known.isNonNegative())
749     return false;
750   if (Known.isNegative())
751     return true;
752 
753   return isImpliedByDomCondition(
754       ICmpInst::ICMP_SLT, Op, Constant::getNullValue(Op->getType()), CxtI, DL);
755 }
756 
757 /// If we have a clamp pattern like max (min X, 42), 41 -- where the output
758 /// can only be one of two possible constant values -- turn that into a select
759 /// of constants.
760 static Instruction *foldClampRangeOfTwo(IntrinsicInst *II,
761                                         InstCombiner::BuilderTy &Builder) {
762   Value *I0 = II->getArgOperand(0), *I1 = II->getArgOperand(1);
763   Value *X;
764   const APInt *C0, *C1;
765   if (!match(I1, m_APInt(C1)) || !I0->hasOneUse())
766     return nullptr;
767 
768   CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
769   switch (II->getIntrinsicID()) {
770   case Intrinsic::smax:
771     if (match(I0, m_SMin(m_Value(X), m_APInt(C0))) && *C0 == *C1 + 1)
772       Pred = ICmpInst::ICMP_SGT;
773     break;
774   case Intrinsic::smin:
775     if (match(I0, m_SMax(m_Value(X), m_APInt(C0))) && *C1 == *C0 + 1)
776       Pred = ICmpInst::ICMP_SLT;
777     break;
778   case Intrinsic::umax:
779     if (match(I0, m_UMin(m_Value(X), m_APInt(C0))) && *C0 == *C1 + 1)
780       Pred = ICmpInst::ICMP_UGT;
781     break;
782   case Intrinsic::umin:
783     if (match(I0, m_UMax(m_Value(X), m_APInt(C0))) && *C1 == *C0 + 1)
784       Pred = ICmpInst::ICMP_ULT;
785     break;
786   default:
787     llvm_unreachable("Expected min/max intrinsic");
788   }
789   if (Pred == CmpInst::BAD_ICMP_PREDICATE)
790     return nullptr;
791 
792   // max (min X, 42), 41 --> X > 41 ? 42 : 41
793   // min (max X, 42), 43 --> X < 43 ? 42 : 43
794   Value *Cmp = Builder.CreateICmp(Pred, X, I1);
795   return SelectInst::Create(Cmp, ConstantInt::get(II->getType(), *C0), I1);
796 }
797 
798 /// CallInst simplification. This mostly only handles folding of intrinsic
799 /// instructions. For normal calls, it allows visitCallBase to do the heavy
800 /// lifting.
801 Instruction *InstCombinerImpl::visitCallInst(CallInst &CI) {
802   // Don't try to simplify calls without uses. It will not do anything useful,
803   // but will result in the following folds being skipped.
804   if (!CI.use_empty())
805     if (Value *V = SimplifyCall(&CI, SQ.getWithInstruction(&CI)))
806       return replaceInstUsesWith(CI, V);
807 
808   if (isFreeCall(&CI, &TLI))
809     return visitFree(CI);
810 
811   // If the caller function is nounwind, mark the call as nounwind, even if the
812   // callee isn't.
813   if (CI.getFunction()->doesNotThrow() && !CI.doesNotThrow()) {
814     CI.setDoesNotThrow();
815     return &CI;
816   }
817 
818   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
819   if (!II) return visitCallBase(CI);
820 
821   // For atomic unordered mem intrinsics if len is not a positive or
822   // not a multiple of element size then behavior is undefined.
823   if (auto *AMI = dyn_cast<AtomicMemIntrinsic>(II))
824     if (ConstantInt *NumBytes = dyn_cast<ConstantInt>(AMI->getLength()))
825       if (NumBytes->getSExtValue() < 0 ||
826           (NumBytes->getZExtValue() % AMI->getElementSizeInBytes() != 0)) {
827         CreateNonTerminatorUnreachable(AMI);
828         assert(AMI->getType()->isVoidTy() &&
829                "non void atomic unordered mem intrinsic");
830         return eraseInstFromFunction(*AMI);
831       }
832 
833   // Intrinsics cannot occur in an invoke or a callbr, so handle them here
834   // instead of in visitCallBase.
835   if (auto *MI = dyn_cast<AnyMemIntrinsic>(II)) {
836     bool Changed = false;
837 
838     // memmove/cpy/set of zero bytes is a noop.
839     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
840       if (NumBytes->isNullValue())
841         return eraseInstFromFunction(CI);
842 
843       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
844         if (CI->getZExtValue() == 1) {
845           // Replace the instruction with just byte operations.  We would
846           // transform other cases to loads/stores, but we don't know if
847           // alignment is sufficient.
848         }
849     }
850 
851     // No other transformations apply to volatile transfers.
852     if (auto *M = dyn_cast<MemIntrinsic>(MI))
853       if (M->isVolatile())
854         return nullptr;
855 
856     // If we have a memmove and the source operation is a constant global,
857     // then the source and dest pointers can't alias, so we can change this
858     // into a call to memcpy.
859     if (auto *MMI = dyn_cast<AnyMemMoveInst>(MI)) {
860       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
861         if (GVSrc->isConstant()) {
862           Module *M = CI.getModule();
863           Intrinsic::ID MemCpyID =
864               isa<AtomicMemMoveInst>(MMI)
865                   ? Intrinsic::memcpy_element_unordered_atomic
866                   : Intrinsic::memcpy;
867           Type *Tys[3] = { CI.getArgOperand(0)->getType(),
868                            CI.getArgOperand(1)->getType(),
869                            CI.getArgOperand(2)->getType() };
870           CI.setCalledFunction(Intrinsic::getDeclaration(M, MemCpyID, Tys));
871           Changed = true;
872         }
873     }
874 
875     if (AnyMemTransferInst *MTI = dyn_cast<AnyMemTransferInst>(MI)) {
876       // memmove(x,x,size) -> noop.
877       if (MTI->getSource() == MTI->getDest())
878         return eraseInstFromFunction(CI);
879     }
880 
881     // If we can determine a pointer alignment that is bigger than currently
882     // set, update the alignment.
883     if (auto *MTI = dyn_cast<AnyMemTransferInst>(MI)) {
884       if (Instruction *I = SimplifyAnyMemTransfer(MTI))
885         return I;
886     } else if (auto *MSI = dyn_cast<AnyMemSetInst>(MI)) {
887       if (Instruction *I = SimplifyAnyMemSet(MSI))
888         return I;
889     }
890 
891     if (Changed) return II;
892   }
893 
894   // For fixed width vector result intrinsics, use the generic demanded vector
895   // support.
896   if (auto *IIFVTy = dyn_cast<FixedVectorType>(II->getType())) {
897     auto VWidth = IIFVTy->getNumElements();
898     APInt UndefElts(VWidth, 0);
899     APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
900     if (Value *V = SimplifyDemandedVectorElts(II, AllOnesEltMask, UndefElts)) {
901       if (V != II)
902         return replaceInstUsesWith(*II, V);
903       return II;
904     }
905   }
906 
907   if (II->isCommutative()) {
908     if (CallInst *NewCall = canonicalizeConstantArg0ToArg1(CI))
909       return NewCall;
910   }
911 
912   Intrinsic::ID IID = II->getIntrinsicID();
913   switch (IID) {
914   case Intrinsic::objectsize:
915     if (Value *V = lowerObjectSizeCall(II, DL, &TLI, /*MustSucceed=*/false))
916       return replaceInstUsesWith(CI, V);
917     return nullptr;
918   case Intrinsic::abs: {
919     Value *IIOperand = II->getArgOperand(0);
920     bool IntMinIsPoison = cast<Constant>(II->getArgOperand(1))->isOneValue();
921 
922     // abs(-x) -> abs(x)
923     // TODO: Copy nsw if it was present on the neg?
924     Value *X;
925     if (match(IIOperand, m_Neg(m_Value(X))))
926       return replaceOperand(*II, 0, X);
927     if (match(IIOperand, m_Select(m_Value(), m_Value(X), m_Neg(m_Deferred(X)))))
928       return replaceOperand(*II, 0, X);
929     if (match(IIOperand, m_Select(m_Value(), m_Neg(m_Value(X)), m_Deferred(X))))
930       return replaceOperand(*II, 0, X);
931 
932     if (Optional<bool> Sign = getKnownSign(IIOperand, II, DL, &AC, &DT)) {
933       // abs(x) -> x if x >= 0
934       if (!*Sign)
935         return replaceInstUsesWith(*II, IIOperand);
936 
937       // abs(x) -> -x if x < 0
938       if (IntMinIsPoison)
939         return BinaryOperator::CreateNSWNeg(IIOperand);
940       return BinaryOperator::CreateNeg(IIOperand);
941     }
942 
943     // abs (sext X) --> zext (abs X*)
944     // Clear the IsIntMin (nsw) bit on the abs to allow narrowing.
945     if (match(IIOperand, m_OneUse(m_SExt(m_Value(X))))) {
946       Value *NarrowAbs =
947           Builder.CreateBinaryIntrinsic(Intrinsic::abs, X, Builder.getFalse());
948       return CastInst::Create(Instruction::ZExt, NarrowAbs, II->getType());
949     }
950 
951     // Match a complicated way to check if a number is odd/even:
952     // abs (srem X, 2) --> and X, 1
953     const APInt *C;
954     if (match(IIOperand, m_SRem(m_Value(X), m_APInt(C))) && *C == 2)
955       return BinaryOperator::CreateAnd(X, ConstantInt::get(II->getType(), 1));
956 
957     break;
958   }
959   case Intrinsic::umax:
960   case Intrinsic::umin: {
961     Value *I0 = II->getArgOperand(0), *I1 = II->getArgOperand(1);
962     Value *X, *Y;
963     if (match(I0, m_ZExt(m_Value(X))) && match(I1, m_ZExt(m_Value(Y))) &&
964         (I0->hasOneUse() || I1->hasOneUse()) && X->getType() == Y->getType()) {
965       Value *NarrowMaxMin = Builder.CreateBinaryIntrinsic(IID, X, Y);
966       return CastInst::Create(Instruction::ZExt, NarrowMaxMin, II->getType());
967     }
968     Constant *C;
969     if (match(I0, m_ZExt(m_Value(X))) && match(I1, m_Constant(C)) &&
970         I0->hasOneUse()) {
971       Constant *NarrowC = ConstantExpr::getTrunc(C, X->getType());
972       if (ConstantExpr::getZExt(NarrowC, II->getType()) == C) {
973         Value *NarrowMaxMin = Builder.CreateBinaryIntrinsic(IID, X, NarrowC);
974         return CastInst::Create(Instruction::ZExt, NarrowMaxMin, II->getType());
975       }
976     }
977     // If both operands of unsigned min/max are sign-extended, it is still ok
978     // to narrow the operation.
979     LLVM_FALLTHROUGH;
980   }
981   case Intrinsic::smax:
982   case Intrinsic::smin: {
983     Value *I0 = II->getArgOperand(0), *I1 = II->getArgOperand(1);
984     Value *X, *Y;
985     if (match(I0, m_SExt(m_Value(X))) && match(I1, m_SExt(m_Value(Y))) &&
986         (I0->hasOneUse() || I1->hasOneUse()) && X->getType() == Y->getType()) {
987       Value *NarrowMaxMin = Builder.CreateBinaryIntrinsic(IID, X, Y);
988       return CastInst::Create(Instruction::SExt, NarrowMaxMin, II->getType());
989     }
990 
991     Constant *C;
992     if (match(I0, m_SExt(m_Value(X))) && match(I1, m_Constant(C)) &&
993         I0->hasOneUse()) {
994       Constant *NarrowC = ConstantExpr::getTrunc(C, X->getType());
995       if (ConstantExpr::getSExt(NarrowC, II->getType()) == C) {
996         Value *NarrowMaxMin = Builder.CreateBinaryIntrinsic(IID, X, NarrowC);
997         return CastInst::Create(Instruction::SExt, NarrowMaxMin, II->getType());
998       }
999     }
1000 
1001     if (match(I0, m_Not(m_Value(X)))) {
1002       // max (not X), (not Y) --> not (min X, Y)
1003       Intrinsic::ID InvID = getInverseMinMaxIntrinsic(IID);
1004       if (match(I1, m_Not(m_Value(Y))) &&
1005           (I0->hasOneUse() || I1->hasOneUse())) {
1006         Value *InvMaxMin = Builder.CreateBinaryIntrinsic(InvID, X, Y);
1007         return BinaryOperator::CreateNot(InvMaxMin);
1008       }
1009       // max (not X), C --> not(min X, ~C)
1010       if (match(I1, m_Constant(C)) && I0->hasOneUse()) {
1011         Constant *NotC = ConstantExpr::getNot(C);
1012         Value *InvMaxMin = Builder.CreateBinaryIntrinsic(InvID, X, NotC);
1013         return BinaryOperator::CreateNot(InvMaxMin);
1014       }
1015     }
1016 
1017     // smax(X, -X) --> abs(X)
1018     // smin(X, -X) --> -abs(X)
1019     // umax(X, -X) --> -abs(X)
1020     // umin(X, -X) --> abs(X)
1021     if (isKnownNegation(I0, I1)) {
1022       // We can choose either operand as the input to abs(), but if we can
1023       // eliminate the only use of a value, that's better for subsequent
1024       // transforms/analysis.
1025       if (I0->hasOneUse() && !I1->hasOneUse())
1026         std::swap(I0, I1);
1027 
1028       // This is some variant of abs(). See if we can propagate 'nsw' to the abs
1029       // operation and potentially its negation.
1030       bool IntMinIsPoison = isKnownNegation(I0, I1, /* NeedNSW */ true);
1031       Value *Abs = Builder.CreateBinaryIntrinsic(
1032           Intrinsic::abs, I0,
1033           ConstantInt::getBool(II->getContext(), IntMinIsPoison));
1034 
1035       // We don't have a "nabs" intrinsic, so negate if needed based on the
1036       // max/min operation.
1037       if (IID == Intrinsic::smin || IID == Intrinsic::umax)
1038         Abs = Builder.CreateNeg(Abs, "nabs", /* NUW */ false, IntMinIsPoison);
1039       return replaceInstUsesWith(CI, Abs);
1040     }
1041 
1042     if (Instruction *Sel = foldClampRangeOfTwo(II, Builder))
1043       return Sel;
1044 
1045     if (match(I1, m_ImmConstant()))
1046       if (auto *Sel = dyn_cast<SelectInst>(I0))
1047         if (Instruction *R = FoldOpIntoSelect(*II, Sel))
1048           return R;
1049 
1050     break;
1051   }
1052   case Intrinsic::bswap: {
1053     Value *IIOperand = II->getArgOperand(0);
1054     Value *X = nullptr;
1055 
1056     // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
1057     if (match(IIOperand, m_Trunc(m_BSwap(m_Value(X))))) {
1058       unsigned C = X->getType()->getScalarSizeInBits() -
1059                    IIOperand->getType()->getScalarSizeInBits();
1060       Value *CV = ConstantInt::get(X->getType(), C);
1061       Value *V = Builder.CreateLShr(X, CV);
1062       return new TruncInst(V, IIOperand->getType());
1063     }
1064     break;
1065   }
1066   case Intrinsic::masked_load:
1067     if (Value *SimplifiedMaskedOp = simplifyMaskedLoad(*II))
1068       return replaceInstUsesWith(CI, SimplifiedMaskedOp);
1069     break;
1070   case Intrinsic::masked_store:
1071     return simplifyMaskedStore(*II);
1072   case Intrinsic::masked_gather:
1073     return simplifyMaskedGather(*II);
1074   case Intrinsic::masked_scatter:
1075     return simplifyMaskedScatter(*II);
1076   case Intrinsic::launder_invariant_group:
1077   case Intrinsic::strip_invariant_group:
1078     if (auto *SkippedBarrier = simplifyInvariantGroupIntrinsic(*II, *this))
1079       return replaceInstUsesWith(*II, SkippedBarrier);
1080     break;
1081   case Intrinsic::powi:
1082     if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
1083       // 0 and 1 are handled in instsimplify
1084       // powi(x, -1) -> 1/x
1085       if (Power->isMinusOne())
1086         return BinaryOperator::CreateFDivFMF(ConstantFP::get(CI.getType(), 1.0),
1087                                              II->getArgOperand(0), II);
1088       // powi(x, 2) -> x*x
1089       if (Power->equalsInt(2))
1090         return BinaryOperator::CreateFMulFMF(II->getArgOperand(0),
1091                                              II->getArgOperand(0), II);
1092     }
1093     break;
1094 
1095   case Intrinsic::cttz:
1096   case Intrinsic::ctlz:
1097     if (auto *I = foldCttzCtlz(*II, *this))
1098       return I;
1099     break;
1100 
1101   case Intrinsic::ctpop:
1102     if (auto *I = foldCtpop(*II, *this))
1103       return I;
1104     break;
1105 
1106   case Intrinsic::fshl:
1107   case Intrinsic::fshr: {
1108     Value *Op0 = II->getArgOperand(0), *Op1 = II->getArgOperand(1);
1109     Type *Ty = II->getType();
1110     unsigned BitWidth = Ty->getScalarSizeInBits();
1111     Constant *ShAmtC;
1112     if (match(II->getArgOperand(2), m_ImmConstant(ShAmtC)) &&
1113         !ShAmtC->containsConstantExpression()) {
1114       // Canonicalize a shift amount constant operand to modulo the bit-width.
1115       Constant *WidthC = ConstantInt::get(Ty, BitWidth);
1116       Constant *ModuloC = ConstantExpr::getURem(ShAmtC, WidthC);
1117       if (ModuloC != ShAmtC)
1118         return replaceOperand(*II, 2, ModuloC);
1119 
1120       assert(ConstantExpr::getICmp(ICmpInst::ICMP_UGT, WidthC, ShAmtC) ==
1121                  ConstantInt::getTrue(CmpInst::makeCmpResultType(Ty)) &&
1122              "Shift amount expected to be modulo bitwidth");
1123 
1124       // Canonicalize funnel shift right by constant to funnel shift left. This
1125       // is not entirely arbitrary. For historical reasons, the backend may
1126       // recognize rotate left patterns but miss rotate right patterns.
1127       if (IID == Intrinsic::fshr) {
1128         // fshr X, Y, C --> fshl X, Y, (BitWidth - C)
1129         Constant *LeftShiftC = ConstantExpr::getSub(WidthC, ShAmtC);
1130         Module *Mod = II->getModule();
1131         Function *Fshl = Intrinsic::getDeclaration(Mod, Intrinsic::fshl, Ty);
1132         return CallInst::Create(Fshl, { Op0, Op1, LeftShiftC });
1133       }
1134       assert(IID == Intrinsic::fshl &&
1135              "All funnel shifts by simple constants should go left");
1136 
1137       // fshl(X, 0, C) --> shl X, C
1138       // fshl(X, undef, C) --> shl X, C
1139       if (match(Op1, m_ZeroInt()) || match(Op1, m_Undef()))
1140         return BinaryOperator::CreateShl(Op0, ShAmtC);
1141 
1142       // fshl(0, X, C) --> lshr X, (BW-C)
1143       // fshl(undef, X, C) --> lshr X, (BW-C)
1144       if (match(Op0, m_ZeroInt()) || match(Op0, m_Undef()))
1145         return BinaryOperator::CreateLShr(Op1,
1146                                           ConstantExpr::getSub(WidthC, ShAmtC));
1147 
1148       // fshl i16 X, X, 8 --> bswap i16 X (reduce to more-specific form)
1149       if (Op0 == Op1 && BitWidth == 16 && match(ShAmtC, m_SpecificInt(8))) {
1150         Module *Mod = II->getModule();
1151         Function *Bswap = Intrinsic::getDeclaration(Mod, Intrinsic::bswap, Ty);
1152         return CallInst::Create(Bswap, { Op0 });
1153       }
1154     }
1155 
1156     // Left or right might be masked.
1157     if (SimplifyDemandedInstructionBits(*II))
1158       return &CI;
1159 
1160     // The shift amount (operand 2) of a funnel shift is modulo the bitwidth,
1161     // so only the low bits of the shift amount are demanded if the bitwidth is
1162     // a power-of-2.
1163     if (!isPowerOf2_32(BitWidth))
1164       break;
1165     APInt Op2Demanded = APInt::getLowBitsSet(BitWidth, Log2_32_Ceil(BitWidth));
1166     KnownBits Op2Known(BitWidth);
1167     if (SimplifyDemandedBits(II, 2, Op2Demanded, Op2Known))
1168       return &CI;
1169     break;
1170   }
1171   case Intrinsic::uadd_with_overflow:
1172   case Intrinsic::sadd_with_overflow: {
1173     if (Instruction *I = foldIntrinsicWithOverflowCommon(II))
1174       return I;
1175 
1176     // Given 2 constant operands whose sum does not overflow:
1177     // uaddo (X +nuw C0), C1 -> uaddo X, C0 + C1
1178     // saddo (X +nsw C0), C1 -> saddo X, C0 + C1
1179     Value *X;
1180     const APInt *C0, *C1;
1181     Value *Arg0 = II->getArgOperand(0);
1182     Value *Arg1 = II->getArgOperand(1);
1183     bool IsSigned = IID == Intrinsic::sadd_with_overflow;
1184     bool HasNWAdd = IsSigned ? match(Arg0, m_NSWAdd(m_Value(X), m_APInt(C0)))
1185                              : match(Arg0, m_NUWAdd(m_Value(X), m_APInt(C0)));
1186     if (HasNWAdd && match(Arg1, m_APInt(C1))) {
1187       bool Overflow;
1188       APInt NewC =
1189           IsSigned ? C1->sadd_ov(*C0, Overflow) : C1->uadd_ov(*C0, Overflow);
1190       if (!Overflow)
1191         return replaceInstUsesWith(
1192             *II, Builder.CreateBinaryIntrinsic(
1193                      IID, X, ConstantInt::get(Arg1->getType(), NewC)));
1194     }
1195     break;
1196   }
1197 
1198   case Intrinsic::umul_with_overflow:
1199   case Intrinsic::smul_with_overflow:
1200   case Intrinsic::usub_with_overflow:
1201     if (Instruction *I = foldIntrinsicWithOverflowCommon(II))
1202       return I;
1203     break;
1204 
1205   case Intrinsic::ssub_with_overflow: {
1206     if (Instruction *I = foldIntrinsicWithOverflowCommon(II))
1207       return I;
1208 
1209     Constant *C;
1210     Value *Arg0 = II->getArgOperand(0);
1211     Value *Arg1 = II->getArgOperand(1);
1212     // Given a constant C that is not the minimum signed value
1213     // for an integer of a given bit width:
1214     //
1215     // ssubo X, C -> saddo X, -C
1216     if (match(Arg1, m_Constant(C)) && C->isNotMinSignedValue()) {
1217       Value *NegVal = ConstantExpr::getNeg(C);
1218       // Build a saddo call that is equivalent to the discovered
1219       // ssubo call.
1220       return replaceInstUsesWith(
1221           *II, Builder.CreateBinaryIntrinsic(Intrinsic::sadd_with_overflow,
1222                                              Arg0, NegVal));
1223     }
1224 
1225     break;
1226   }
1227 
1228   case Intrinsic::uadd_sat:
1229   case Intrinsic::sadd_sat:
1230   case Intrinsic::usub_sat:
1231   case Intrinsic::ssub_sat: {
1232     SaturatingInst *SI = cast<SaturatingInst>(II);
1233     Type *Ty = SI->getType();
1234     Value *Arg0 = SI->getLHS();
1235     Value *Arg1 = SI->getRHS();
1236 
1237     // Make use of known overflow information.
1238     OverflowResult OR = computeOverflow(SI->getBinaryOp(), SI->isSigned(),
1239                                         Arg0, Arg1, SI);
1240     switch (OR) {
1241       case OverflowResult::MayOverflow:
1242         break;
1243       case OverflowResult::NeverOverflows:
1244         if (SI->isSigned())
1245           return BinaryOperator::CreateNSW(SI->getBinaryOp(), Arg0, Arg1);
1246         else
1247           return BinaryOperator::CreateNUW(SI->getBinaryOp(), Arg0, Arg1);
1248       case OverflowResult::AlwaysOverflowsLow: {
1249         unsigned BitWidth = Ty->getScalarSizeInBits();
1250         APInt Min = APSInt::getMinValue(BitWidth, !SI->isSigned());
1251         return replaceInstUsesWith(*SI, ConstantInt::get(Ty, Min));
1252       }
1253       case OverflowResult::AlwaysOverflowsHigh: {
1254         unsigned BitWidth = Ty->getScalarSizeInBits();
1255         APInt Max = APSInt::getMaxValue(BitWidth, !SI->isSigned());
1256         return replaceInstUsesWith(*SI, ConstantInt::get(Ty, Max));
1257       }
1258     }
1259 
1260     // ssub.sat(X, C) -> sadd.sat(X, -C) if C != MIN
1261     Constant *C;
1262     if (IID == Intrinsic::ssub_sat && match(Arg1, m_Constant(C)) &&
1263         C->isNotMinSignedValue()) {
1264       Value *NegVal = ConstantExpr::getNeg(C);
1265       return replaceInstUsesWith(
1266           *II, Builder.CreateBinaryIntrinsic(
1267               Intrinsic::sadd_sat, Arg0, NegVal));
1268     }
1269 
1270     // sat(sat(X + Val2) + Val) -> sat(X + (Val+Val2))
1271     // sat(sat(X - Val2) - Val) -> sat(X - (Val+Val2))
1272     // if Val and Val2 have the same sign
1273     if (auto *Other = dyn_cast<IntrinsicInst>(Arg0)) {
1274       Value *X;
1275       const APInt *Val, *Val2;
1276       APInt NewVal;
1277       bool IsUnsigned =
1278           IID == Intrinsic::uadd_sat || IID == Intrinsic::usub_sat;
1279       if (Other->getIntrinsicID() == IID &&
1280           match(Arg1, m_APInt(Val)) &&
1281           match(Other->getArgOperand(0), m_Value(X)) &&
1282           match(Other->getArgOperand(1), m_APInt(Val2))) {
1283         if (IsUnsigned)
1284           NewVal = Val->uadd_sat(*Val2);
1285         else if (Val->isNonNegative() == Val2->isNonNegative()) {
1286           bool Overflow;
1287           NewVal = Val->sadd_ov(*Val2, Overflow);
1288           if (Overflow) {
1289             // Both adds together may add more than SignedMaxValue
1290             // without saturating the final result.
1291             break;
1292           }
1293         } else {
1294           // Cannot fold saturated addition with different signs.
1295           break;
1296         }
1297 
1298         return replaceInstUsesWith(
1299             *II, Builder.CreateBinaryIntrinsic(
1300                      IID, X, ConstantInt::get(II->getType(), NewVal)));
1301       }
1302     }
1303     break;
1304   }
1305 
1306   case Intrinsic::minnum:
1307   case Intrinsic::maxnum:
1308   case Intrinsic::minimum:
1309   case Intrinsic::maximum: {
1310     Value *Arg0 = II->getArgOperand(0);
1311     Value *Arg1 = II->getArgOperand(1);
1312     Value *X, *Y;
1313     if (match(Arg0, m_FNeg(m_Value(X))) && match(Arg1, m_FNeg(m_Value(Y))) &&
1314         (Arg0->hasOneUse() || Arg1->hasOneUse())) {
1315       // If both operands are negated, invert the call and negate the result:
1316       // min(-X, -Y) --> -(max(X, Y))
1317       // max(-X, -Y) --> -(min(X, Y))
1318       Intrinsic::ID NewIID;
1319       switch (IID) {
1320       case Intrinsic::maxnum:
1321         NewIID = Intrinsic::minnum;
1322         break;
1323       case Intrinsic::minnum:
1324         NewIID = Intrinsic::maxnum;
1325         break;
1326       case Intrinsic::maximum:
1327         NewIID = Intrinsic::minimum;
1328         break;
1329       case Intrinsic::minimum:
1330         NewIID = Intrinsic::maximum;
1331         break;
1332       default:
1333         llvm_unreachable("unexpected intrinsic ID");
1334       }
1335       Value *NewCall = Builder.CreateBinaryIntrinsic(NewIID, X, Y, II);
1336       Instruction *FNeg = UnaryOperator::CreateFNeg(NewCall);
1337       FNeg->copyIRFlags(II);
1338       return FNeg;
1339     }
1340 
1341     // m(m(X, C2), C1) -> m(X, C)
1342     const APFloat *C1, *C2;
1343     if (auto *M = dyn_cast<IntrinsicInst>(Arg0)) {
1344       if (M->getIntrinsicID() == IID && match(Arg1, m_APFloat(C1)) &&
1345           ((match(M->getArgOperand(0), m_Value(X)) &&
1346             match(M->getArgOperand(1), m_APFloat(C2))) ||
1347            (match(M->getArgOperand(1), m_Value(X)) &&
1348             match(M->getArgOperand(0), m_APFloat(C2))))) {
1349         APFloat Res(0.0);
1350         switch (IID) {
1351         case Intrinsic::maxnum:
1352           Res = maxnum(*C1, *C2);
1353           break;
1354         case Intrinsic::minnum:
1355           Res = minnum(*C1, *C2);
1356           break;
1357         case Intrinsic::maximum:
1358           Res = maximum(*C1, *C2);
1359           break;
1360         case Intrinsic::minimum:
1361           Res = minimum(*C1, *C2);
1362           break;
1363         default:
1364           llvm_unreachable("unexpected intrinsic ID");
1365         }
1366         Instruction *NewCall = Builder.CreateBinaryIntrinsic(
1367             IID, X, ConstantFP::get(Arg0->getType(), Res), II);
1368         // TODO: Conservatively intersecting FMF. If Res == C2, the transform
1369         //       was a simplification (so Arg0 and its original flags could
1370         //       propagate?)
1371         NewCall->andIRFlags(M);
1372         return replaceInstUsesWith(*II, NewCall);
1373       }
1374     }
1375 
1376     // m((fpext X), (fpext Y)) -> fpext (m(X, Y))
1377     if (match(Arg0, m_OneUse(m_FPExt(m_Value(X)))) &&
1378         match(Arg1, m_OneUse(m_FPExt(m_Value(Y)))) &&
1379         X->getType() == Y->getType()) {
1380       Value *NewCall =
1381           Builder.CreateBinaryIntrinsic(IID, X, Y, II, II->getName());
1382       return new FPExtInst(NewCall, II->getType());
1383     }
1384 
1385     // max X, -X --> fabs X
1386     // min X, -X --> -(fabs X)
1387     // TODO: Remove one-use limitation? That is obviously better for max.
1388     //       It would be an extra instruction for min (fnabs), but that is
1389     //       still likely better for analysis and codegen.
1390     if ((match(Arg0, m_OneUse(m_FNeg(m_Value(X)))) && Arg1 == X) ||
1391         (match(Arg1, m_OneUse(m_FNeg(m_Value(X)))) && Arg0 == X)) {
1392       Value *R = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, X, II);
1393       if (IID == Intrinsic::minimum || IID == Intrinsic::minnum)
1394         R = Builder.CreateFNegFMF(R, II);
1395       return replaceInstUsesWith(*II, R);
1396     }
1397 
1398     break;
1399   }
1400   case Intrinsic::fmuladd: {
1401     // Canonicalize fast fmuladd to the separate fmul + fadd.
1402     if (II->isFast()) {
1403       BuilderTy::FastMathFlagGuard Guard(Builder);
1404       Builder.setFastMathFlags(II->getFastMathFlags());
1405       Value *Mul = Builder.CreateFMul(II->getArgOperand(0),
1406                                       II->getArgOperand(1));
1407       Value *Add = Builder.CreateFAdd(Mul, II->getArgOperand(2));
1408       Add->takeName(II);
1409       return replaceInstUsesWith(*II, Add);
1410     }
1411 
1412     // Try to simplify the underlying FMul.
1413     if (Value *V = SimplifyFMulInst(II->getArgOperand(0), II->getArgOperand(1),
1414                                     II->getFastMathFlags(),
1415                                     SQ.getWithInstruction(II))) {
1416       auto *FAdd = BinaryOperator::CreateFAdd(V, II->getArgOperand(2));
1417       FAdd->copyFastMathFlags(II);
1418       return FAdd;
1419     }
1420 
1421     LLVM_FALLTHROUGH;
1422   }
1423   case Intrinsic::fma: {
1424     // fma fneg(x), fneg(y), z -> fma x, y, z
1425     Value *Src0 = II->getArgOperand(0);
1426     Value *Src1 = II->getArgOperand(1);
1427     Value *X, *Y;
1428     if (match(Src0, m_FNeg(m_Value(X))) && match(Src1, m_FNeg(m_Value(Y)))) {
1429       replaceOperand(*II, 0, X);
1430       replaceOperand(*II, 1, Y);
1431       return II;
1432     }
1433 
1434     // fma fabs(x), fabs(x), z -> fma x, x, z
1435     if (match(Src0, m_FAbs(m_Value(X))) &&
1436         match(Src1, m_FAbs(m_Specific(X)))) {
1437       replaceOperand(*II, 0, X);
1438       replaceOperand(*II, 1, X);
1439       return II;
1440     }
1441 
1442     // Try to simplify the underlying FMul. We can only apply simplifications
1443     // that do not require rounding.
1444     if (Value *V = SimplifyFMAFMul(II->getArgOperand(0), II->getArgOperand(1),
1445                                    II->getFastMathFlags(),
1446                                    SQ.getWithInstruction(II))) {
1447       auto *FAdd = BinaryOperator::CreateFAdd(V, II->getArgOperand(2));
1448       FAdd->copyFastMathFlags(II);
1449       return FAdd;
1450     }
1451 
1452     // fma x, y, 0 -> fmul x, y
1453     // This is always valid for -0.0, but requires nsz for +0.0 as
1454     // -0.0 + 0.0 = 0.0, which would not be the same as the fmul on its own.
1455     if (match(II->getArgOperand(2), m_NegZeroFP()) ||
1456         (match(II->getArgOperand(2), m_PosZeroFP()) &&
1457          II->getFastMathFlags().noSignedZeros()))
1458       return BinaryOperator::CreateFMulFMF(Src0, Src1, II);
1459 
1460     break;
1461   }
1462   case Intrinsic::copysign: {
1463     Value *Mag = II->getArgOperand(0), *Sign = II->getArgOperand(1);
1464     if (SignBitMustBeZero(Sign, &TLI)) {
1465       // If we know that the sign argument is positive, reduce to FABS:
1466       // copysign Mag, +Sign --> fabs Mag
1467       Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, Mag, II);
1468       return replaceInstUsesWith(*II, Fabs);
1469     }
1470     // TODO: There should be a ValueTracking sibling like SignBitMustBeOne.
1471     const APFloat *C;
1472     if (match(Sign, m_APFloat(C)) && C->isNegative()) {
1473       // If we know that the sign argument is negative, reduce to FNABS:
1474       // copysign Mag, -Sign --> fneg (fabs Mag)
1475       Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, Mag, II);
1476       return replaceInstUsesWith(*II, Builder.CreateFNegFMF(Fabs, II));
1477     }
1478 
1479     // Propagate sign argument through nested calls:
1480     // copysign Mag, (copysign ?, X) --> copysign Mag, X
1481     Value *X;
1482     if (match(Sign, m_Intrinsic<Intrinsic::copysign>(m_Value(), m_Value(X))))
1483       return replaceOperand(*II, 1, X);
1484 
1485     // Peek through changes of magnitude's sign-bit. This call rewrites those:
1486     // copysign (fabs X), Sign --> copysign X, Sign
1487     // copysign (fneg X), Sign --> copysign X, Sign
1488     if (match(Mag, m_FAbs(m_Value(X))) || match(Mag, m_FNeg(m_Value(X))))
1489       return replaceOperand(*II, 0, X);
1490 
1491     break;
1492   }
1493   case Intrinsic::fabs: {
1494     Value *Cond, *TVal, *FVal;
1495     if (match(II->getArgOperand(0),
1496               m_Select(m_Value(Cond), m_Value(TVal), m_Value(FVal)))) {
1497       // fabs (select Cond, TrueC, FalseC) --> select Cond, AbsT, AbsF
1498       if (isa<Constant>(TVal) && isa<Constant>(FVal)) {
1499         CallInst *AbsT = Builder.CreateCall(II->getCalledFunction(), {TVal});
1500         CallInst *AbsF = Builder.CreateCall(II->getCalledFunction(), {FVal});
1501         return SelectInst::Create(Cond, AbsT, AbsF);
1502       }
1503       // fabs (select Cond, -FVal, FVal) --> fabs FVal
1504       if (match(TVal, m_FNeg(m_Specific(FVal))))
1505         return replaceOperand(*II, 0, FVal);
1506       // fabs (select Cond, TVal, -TVal) --> fabs TVal
1507       if (match(FVal, m_FNeg(m_Specific(TVal))))
1508         return replaceOperand(*II, 0, TVal);
1509     }
1510 
1511     LLVM_FALLTHROUGH;
1512   }
1513   case Intrinsic::ceil:
1514   case Intrinsic::floor:
1515   case Intrinsic::round:
1516   case Intrinsic::roundeven:
1517   case Intrinsic::nearbyint:
1518   case Intrinsic::rint:
1519   case Intrinsic::trunc: {
1520     Value *ExtSrc;
1521     if (match(II->getArgOperand(0), m_OneUse(m_FPExt(m_Value(ExtSrc))))) {
1522       // Narrow the call: intrinsic (fpext x) -> fpext (intrinsic x)
1523       Value *NarrowII = Builder.CreateUnaryIntrinsic(IID, ExtSrc, II);
1524       return new FPExtInst(NarrowII, II->getType());
1525     }
1526     break;
1527   }
1528   case Intrinsic::cos:
1529   case Intrinsic::amdgcn_cos: {
1530     Value *X;
1531     Value *Src = II->getArgOperand(0);
1532     if (match(Src, m_FNeg(m_Value(X))) || match(Src, m_FAbs(m_Value(X)))) {
1533       // cos(-x) -> cos(x)
1534       // cos(fabs(x)) -> cos(x)
1535       return replaceOperand(*II, 0, X);
1536     }
1537     break;
1538   }
1539   case Intrinsic::sin: {
1540     Value *X;
1541     if (match(II->getArgOperand(0), m_OneUse(m_FNeg(m_Value(X))))) {
1542       // sin(-x) --> -sin(x)
1543       Value *NewSin = Builder.CreateUnaryIntrinsic(Intrinsic::sin, X, II);
1544       Instruction *FNeg = UnaryOperator::CreateFNeg(NewSin);
1545       FNeg->copyFastMathFlags(II);
1546       return FNeg;
1547     }
1548     break;
1549   }
1550 
1551   case Intrinsic::arm_neon_vtbl1:
1552   case Intrinsic::aarch64_neon_tbl1:
1553     if (Value *V = simplifyNeonTbl1(*II, Builder))
1554       return replaceInstUsesWith(*II, V);
1555     break;
1556 
1557   case Intrinsic::arm_neon_vmulls:
1558   case Intrinsic::arm_neon_vmullu:
1559   case Intrinsic::aarch64_neon_smull:
1560   case Intrinsic::aarch64_neon_umull: {
1561     Value *Arg0 = II->getArgOperand(0);
1562     Value *Arg1 = II->getArgOperand(1);
1563 
1564     // Handle mul by zero first:
1565     if (isa<ConstantAggregateZero>(Arg0) || isa<ConstantAggregateZero>(Arg1)) {
1566       return replaceInstUsesWith(CI, ConstantAggregateZero::get(II->getType()));
1567     }
1568 
1569     // Check for constant LHS & RHS - in this case we just simplify.
1570     bool Zext = (IID == Intrinsic::arm_neon_vmullu ||
1571                  IID == Intrinsic::aarch64_neon_umull);
1572     VectorType *NewVT = cast<VectorType>(II->getType());
1573     if (Constant *CV0 = dyn_cast<Constant>(Arg0)) {
1574       if (Constant *CV1 = dyn_cast<Constant>(Arg1)) {
1575         CV0 = ConstantExpr::getIntegerCast(CV0, NewVT, /*isSigned=*/!Zext);
1576         CV1 = ConstantExpr::getIntegerCast(CV1, NewVT, /*isSigned=*/!Zext);
1577 
1578         return replaceInstUsesWith(CI, ConstantExpr::getMul(CV0, CV1));
1579       }
1580 
1581       // Couldn't simplify - canonicalize constant to the RHS.
1582       std::swap(Arg0, Arg1);
1583     }
1584 
1585     // Handle mul by one:
1586     if (Constant *CV1 = dyn_cast<Constant>(Arg1))
1587       if (ConstantInt *Splat =
1588               dyn_cast_or_null<ConstantInt>(CV1->getSplatValue()))
1589         if (Splat->isOne())
1590           return CastInst::CreateIntegerCast(Arg0, II->getType(),
1591                                              /*isSigned=*/!Zext);
1592 
1593     break;
1594   }
1595   case Intrinsic::arm_neon_aesd:
1596   case Intrinsic::arm_neon_aese:
1597   case Intrinsic::aarch64_crypto_aesd:
1598   case Intrinsic::aarch64_crypto_aese: {
1599     Value *DataArg = II->getArgOperand(0);
1600     Value *KeyArg  = II->getArgOperand(1);
1601 
1602     // Try to use the builtin XOR in AESE and AESD to eliminate a prior XOR
1603     Value *Data, *Key;
1604     if (match(KeyArg, m_ZeroInt()) &&
1605         match(DataArg, m_Xor(m_Value(Data), m_Value(Key)))) {
1606       replaceOperand(*II, 0, Data);
1607       replaceOperand(*II, 1, Key);
1608       return II;
1609     }
1610     break;
1611   }
1612   case Intrinsic::hexagon_V6_vandvrt:
1613   case Intrinsic::hexagon_V6_vandvrt_128B: {
1614     // Simplify Q -> V -> Q conversion.
1615     if (auto Op0 = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {
1616       Intrinsic::ID ID0 = Op0->getIntrinsicID();
1617       if (ID0 != Intrinsic::hexagon_V6_vandqrt &&
1618           ID0 != Intrinsic::hexagon_V6_vandqrt_128B)
1619         break;
1620       Value *Bytes = Op0->getArgOperand(1), *Mask = II->getArgOperand(1);
1621       uint64_t Bytes1 = computeKnownBits(Bytes, 0, Op0).One.getZExtValue();
1622       uint64_t Mask1 = computeKnownBits(Mask, 0, II).One.getZExtValue();
1623       // Check if every byte has common bits in Bytes and Mask.
1624       uint64_t C = Bytes1 & Mask1;
1625       if ((C & 0xFF) && (C & 0xFF00) && (C & 0xFF0000) && (C & 0xFF000000))
1626         return replaceInstUsesWith(*II, Op0->getArgOperand(0));
1627     }
1628     break;
1629   }
1630   case Intrinsic::stackrestore: {
1631     // If the save is right next to the restore, remove the restore.  This can
1632     // happen when variable allocas are DCE'd.
1633     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {
1634       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
1635         // Skip over debug info.
1636         if (SS->getNextNonDebugInstruction() == II) {
1637           return eraseInstFromFunction(CI);
1638         }
1639       }
1640     }
1641 
1642     // Scan down this block to see if there is another stack restore in the
1643     // same block without an intervening call/alloca.
1644     BasicBlock::iterator BI(II);
1645     Instruction *TI = II->getParent()->getTerminator();
1646     bool CannotRemove = false;
1647     for (++BI; &*BI != TI; ++BI) {
1648       if (isa<AllocaInst>(BI)) {
1649         CannotRemove = true;
1650         break;
1651       }
1652       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
1653         if (auto *II2 = dyn_cast<IntrinsicInst>(BCI)) {
1654           // If there is a stackrestore below this one, remove this one.
1655           if (II2->getIntrinsicID() == Intrinsic::stackrestore)
1656             return eraseInstFromFunction(CI);
1657 
1658           // Bail if we cross over an intrinsic with side effects, such as
1659           // llvm.stacksave, or llvm.read_register.
1660           if (II2->mayHaveSideEffects()) {
1661             CannotRemove = true;
1662             break;
1663           }
1664         } else {
1665           // If we found a non-intrinsic call, we can't remove the stack
1666           // restore.
1667           CannotRemove = true;
1668           break;
1669         }
1670       }
1671     }
1672 
1673     // If the stack restore is in a return, resume, or unwind block and if there
1674     // are no allocas or calls between the restore and the return, nuke the
1675     // restore.
1676     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<ResumeInst>(TI)))
1677       return eraseInstFromFunction(CI);
1678     break;
1679   }
1680   case Intrinsic::lifetime_end:
1681     // Asan needs to poison memory to detect invalid access which is possible
1682     // even for empty lifetime range.
1683     if (II->getFunction()->hasFnAttribute(Attribute::SanitizeAddress) ||
1684         II->getFunction()->hasFnAttribute(Attribute::SanitizeMemory) ||
1685         II->getFunction()->hasFnAttribute(Attribute::SanitizeHWAddress))
1686       break;
1687 
1688     if (removeTriviallyEmptyRange(*II, *this, [](const IntrinsicInst &I) {
1689           return I.getIntrinsicID() == Intrinsic::lifetime_start;
1690         }))
1691       return nullptr;
1692     break;
1693   case Intrinsic::assume: {
1694     Value *IIOperand = II->getArgOperand(0);
1695     SmallVector<OperandBundleDef, 4> OpBundles;
1696     II->getOperandBundlesAsDefs(OpBundles);
1697 
1698     /// This will remove the boolean Condition from the assume given as
1699     /// argument and remove the assume if it becomes useless.
1700     /// always returns nullptr for use as a return values.
1701     auto RemoveConditionFromAssume = [&](Instruction *Assume) -> Instruction * {
1702       assert(isa<AssumeInst>(Assume));
1703       if (isAssumeWithEmptyBundle(*cast<AssumeInst>(II)))
1704         return eraseInstFromFunction(CI);
1705       replaceUse(II->getOperandUse(0), ConstantInt::getTrue(II->getContext()));
1706       return nullptr;
1707     };
1708     // Remove an assume if it is followed by an identical assume.
1709     // TODO: Do we need this? Unless there are conflicting assumptions, the
1710     // computeKnownBits(IIOperand) below here eliminates redundant assumes.
1711     Instruction *Next = II->getNextNonDebugInstruction();
1712     if (match(Next, m_Intrinsic<Intrinsic::assume>(m_Specific(IIOperand))))
1713       return RemoveConditionFromAssume(Next);
1714 
1715     // Canonicalize assume(a && b) -> assume(a); assume(b);
1716     // Note: New assumption intrinsics created here are registered by
1717     // the InstCombineIRInserter object.
1718     FunctionType *AssumeIntrinsicTy = II->getFunctionType();
1719     Value *AssumeIntrinsic = II->getCalledOperand();
1720     Value *A, *B;
1721     if (match(IIOperand, m_LogicalAnd(m_Value(A), m_Value(B)))) {
1722       Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic, A, OpBundles,
1723                          II->getName());
1724       Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic, B, II->getName());
1725       return eraseInstFromFunction(*II);
1726     }
1727     // assume(!(a || b)) -> assume(!a); assume(!b);
1728     if (match(IIOperand, m_Not(m_LogicalOr(m_Value(A), m_Value(B))))) {
1729       Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic,
1730                          Builder.CreateNot(A), OpBundles, II->getName());
1731       Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic,
1732                          Builder.CreateNot(B), II->getName());
1733       return eraseInstFromFunction(*II);
1734     }
1735 
1736     // assume( (load addr) != null ) -> add 'nonnull' metadata to load
1737     // (if assume is valid at the load)
1738     CmpInst::Predicate Pred;
1739     Instruction *LHS;
1740     if (match(IIOperand, m_ICmp(Pred, m_Instruction(LHS), m_Zero())) &&
1741         Pred == ICmpInst::ICMP_NE && LHS->getOpcode() == Instruction::Load &&
1742         LHS->getType()->isPointerTy() &&
1743         isValidAssumeForContext(II, LHS, &DT)) {
1744       MDNode *MD = MDNode::get(II->getContext(), None);
1745       LHS->setMetadata(LLVMContext::MD_nonnull, MD);
1746       return RemoveConditionFromAssume(II);
1747 
1748       // TODO: apply nonnull return attributes to calls and invokes
1749       // TODO: apply range metadata for range check patterns?
1750     }
1751 
1752     // Convert nonnull assume like:
1753     // %A = icmp ne i32* %PTR, null
1754     // call void @llvm.assume(i1 %A)
1755     // into
1756     // call void @llvm.assume(i1 true) [ "nonnull"(i32* %PTR) ]
1757     if (EnableKnowledgeRetention &&
1758         match(IIOperand, m_Cmp(Pred, m_Value(A), m_Zero())) &&
1759         Pred == CmpInst::ICMP_NE && A->getType()->isPointerTy()) {
1760       if (auto *Replacement = buildAssumeFromKnowledge(
1761               {RetainedKnowledge{Attribute::NonNull, 0, A}}, Next, &AC, &DT)) {
1762 
1763         Replacement->insertBefore(Next);
1764         AC.registerAssumption(Replacement);
1765         return RemoveConditionFromAssume(II);
1766       }
1767     }
1768 
1769     // Convert alignment assume like:
1770     // %B = ptrtoint i32* %A to i64
1771     // %C = and i64 %B, Constant
1772     // %D = icmp eq i64 %C, 0
1773     // call void @llvm.assume(i1 %D)
1774     // into
1775     // call void @llvm.assume(i1 true) [ "align"(i32* [[A]], i64  Constant + 1)]
1776     uint64_t AlignMask;
1777     if (EnableKnowledgeRetention &&
1778         match(IIOperand,
1779               m_Cmp(Pred, m_And(m_Value(A), m_ConstantInt(AlignMask)),
1780                     m_Zero())) &&
1781         Pred == CmpInst::ICMP_EQ) {
1782       if (isPowerOf2_64(AlignMask + 1)) {
1783         uint64_t Offset = 0;
1784         match(A, m_Add(m_Value(A), m_ConstantInt(Offset)));
1785         if (match(A, m_PtrToInt(m_Value(A)))) {
1786           /// Note: this doesn't preserve the offset information but merges
1787           /// offset and alignment.
1788           /// TODO: we can generate a GEP instead of merging the alignment with
1789           /// the offset.
1790           RetainedKnowledge RK{Attribute::Alignment,
1791                                (unsigned)MinAlign(Offset, AlignMask + 1), A};
1792           if (auto *Replacement =
1793                   buildAssumeFromKnowledge(RK, Next, &AC, &DT)) {
1794 
1795             Replacement->insertAfter(II);
1796             AC.registerAssumption(Replacement);
1797           }
1798           return RemoveConditionFromAssume(II);
1799         }
1800       }
1801     }
1802 
1803     /// Canonicalize Knowledge in operand bundles.
1804     if (EnableKnowledgeRetention && II->hasOperandBundles()) {
1805       for (unsigned Idx = 0; Idx < II->getNumOperandBundles(); Idx++) {
1806         auto &BOI = II->bundle_op_info_begin()[Idx];
1807         RetainedKnowledge RK =
1808           llvm::getKnowledgeFromBundle(cast<AssumeInst>(*II), BOI);
1809         if (BOI.End - BOI.Begin > 2)
1810           continue; // Prevent reducing knowledge in an align with offset since
1811                     // extracting a RetainedKnowledge form them looses offset
1812                     // information
1813         RetainedKnowledge CanonRK =
1814           llvm::simplifyRetainedKnowledge(cast<AssumeInst>(II), RK,
1815                                           &getAssumptionCache(),
1816                                           &getDominatorTree());
1817         if (CanonRK == RK)
1818           continue;
1819         if (!CanonRK) {
1820           if (BOI.End - BOI.Begin > 0) {
1821             Worklist.pushValue(II->op_begin()[BOI.Begin]);
1822             Value::dropDroppableUse(II->op_begin()[BOI.Begin]);
1823           }
1824           continue;
1825         }
1826         assert(RK.AttrKind == CanonRK.AttrKind);
1827         if (BOI.End - BOI.Begin > 0)
1828           II->op_begin()[BOI.Begin].set(CanonRK.WasOn);
1829         if (BOI.End - BOI.Begin > 1)
1830           II->op_begin()[BOI.Begin + 1].set(ConstantInt::get(
1831               Type::getInt64Ty(II->getContext()), CanonRK.ArgValue));
1832         if (RK.WasOn)
1833           Worklist.pushValue(RK.WasOn);
1834         return II;
1835       }
1836     }
1837 
1838     // If there is a dominating assume with the same condition as this one,
1839     // then this one is redundant, and should be removed.
1840     KnownBits Known(1);
1841     computeKnownBits(IIOperand, Known, 0, II);
1842     if (Known.isAllOnes() && isAssumeWithEmptyBundle(cast<AssumeInst>(*II)))
1843       return eraseInstFromFunction(*II);
1844 
1845     // Update the cache of affected values for this assumption (we might be
1846     // here because we just simplified the condition).
1847     AC.updateAffectedValues(cast<AssumeInst>(II));
1848     break;
1849   }
1850   case Intrinsic::experimental_guard: {
1851     // Is this guard followed by another guard?  We scan forward over a small
1852     // fixed window of instructions to handle common cases with conditions
1853     // computed between guards.
1854     Instruction *NextInst = II->getNextNonDebugInstruction();
1855     for (unsigned i = 0; i < GuardWideningWindow; i++) {
1856       // Note: Using context-free form to avoid compile time blow up
1857       if (!isSafeToSpeculativelyExecute(NextInst))
1858         break;
1859       NextInst = NextInst->getNextNonDebugInstruction();
1860     }
1861     Value *NextCond = nullptr;
1862     if (match(NextInst,
1863               m_Intrinsic<Intrinsic::experimental_guard>(m_Value(NextCond)))) {
1864       Value *CurrCond = II->getArgOperand(0);
1865 
1866       // Remove a guard that it is immediately preceded by an identical guard.
1867       // Otherwise canonicalize guard(a); guard(b) -> guard(a & b).
1868       if (CurrCond != NextCond) {
1869         Instruction *MoveI = II->getNextNonDebugInstruction();
1870         while (MoveI != NextInst) {
1871           auto *Temp = MoveI;
1872           MoveI = MoveI->getNextNonDebugInstruction();
1873           Temp->moveBefore(II);
1874         }
1875         replaceOperand(*II, 0, Builder.CreateAnd(CurrCond, NextCond));
1876       }
1877       eraseInstFromFunction(*NextInst);
1878       return II;
1879     }
1880     break;
1881   }
1882   case Intrinsic::experimental_vector_insert: {
1883     Value *Vec = II->getArgOperand(0);
1884     Value *SubVec = II->getArgOperand(1);
1885     Value *Idx = II->getArgOperand(2);
1886     auto *DstTy = dyn_cast<FixedVectorType>(II->getType());
1887     auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType());
1888     auto *SubVecTy = dyn_cast<FixedVectorType>(SubVec->getType());
1889 
1890     // Only canonicalize if the destination vector, Vec, and SubVec are all
1891     // fixed vectors.
1892     if (DstTy && VecTy && SubVecTy) {
1893       unsigned DstNumElts = DstTy->getNumElements();
1894       unsigned VecNumElts = VecTy->getNumElements();
1895       unsigned SubVecNumElts = SubVecTy->getNumElements();
1896       unsigned IdxN = cast<ConstantInt>(Idx)->getZExtValue();
1897 
1898       // An insert that entirely overwrites Vec with SubVec is a nop.
1899       if (VecNumElts == SubVecNumElts) {
1900         replaceInstUsesWith(CI, SubVec);
1901         return eraseInstFromFunction(CI);
1902       }
1903 
1904       // Widen SubVec into a vector of the same width as Vec, since
1905       // shufflevector requires the two input vectors to be the same width.
1906       // Elements beyond the bounds of SubVec within the widened vector are
1907       // undefined.
1908       SmallVector<int, 8> WidenMask;
1909       unsigned i;
1910       for (i = 0; i != SubVecNumElts; ++i)
1911         WidenMask.push_back(i);
1912       for (; i != VecNumElts; ++i)
1913         WidenMask.push_back(UndefMaskElem);
1914 
1915       Value *WidenShuffle = Builder.CreateShuffleVector(SubVec, WidenMask);
1916 
1917       SmallVector<int, 8> Mask;
1918       for (unsigned i = 0; i != IdxN; ++i)
1919         Mask.push_back(i);
1920       for (unsigned i = DstNumElts; i != DstNumElts + SubVecNumElts; ++i)
1921         Mask.push_back(i);
1922       for (unsigned i = IdxN + SubVecNumElts; i != DstNumElts; ++i)
1923         Mask.push_back(i);
1924 
1925       Value *Shuffle = Builder.CreateShuffleVector(Vec, WidenShuffle, Mask);
1926       replaceInstUsesWith(CI, Shuffle);
1927       return eraseInstFromFunction(CI);
1928     }
1929     break;
1930   }
1931   case Intrinsic::experimental_vector_extract: {
1932     Value *Vec = II->getArgOperand(0);
1933     Value *Idx = II->getArgOperand(1);
1934 
1935     auto *DstTy = dyn_cast<FixedVectorType>(II->getType());
1936     auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType());
1937 
1938     // Only canonicalize if the the destination vector and Vec are fixed
1939     // vectors.
1940     if (DstTy && VecTy) {
1941       unsigned DstNumElts = DstTy->getNumElements();
1942       unsigned VecNumElts = VecTy->getNumElements();
1943       unsigned IdxN = cast<ConstantInt>(Idx)->getZExtValue();
1944 
1945       // Extracting the entirety of Vec is a nop.
1946       if (VecNumElts == DstNumElts) {
1947         replaceInstUsesWith(CI, Vec);
1948         return eraseInstFromFunction(CI);
1949       }
1950 
1951       SmallVector<int, 8> Mask;
1952       for (unsigned i = 0; i != DstNumElts; ++i)
1953         Mask.push_back(IdxN + i);
1954 
1955       Value *Shuffle = Builder.CreateShuffleVector(Vec, Mask);
1956       replaceInstUsesWith(CI, Shuffle);
1957       return eraseInstFromFunction(CI);
1958     }
1959     break;
1960   }
1961   case Intrinsic::vector_reduce_or:
1962   case Intrinsic::vector_reduce_and: {
1963     // Canonicalize logical or/and reductions:
1964     // Or reduction for i1 is represented as:
1965     // %val = bitcast <ReduxWidth x i1> to iReduxWidth
1966     // %res = cmp ne iReduxWidth %val, 0
1967     // And reduction for i1 is represented as:
1968     // %val = bitcast <ReduxWidth x i1> to iReduxWidth
1969     // %res = cmp eq iReduxWidth %val, 11111
1970     Value *Arg = II->getArgOperand(0);
1971     Type *RetTy = II->getType();
1972     if (RetTy == Builder.getInt1Ty())
1973       if (auto *FVTy = dyn_cast<FixedVectorType>(Arg->getType())) {
1974         Value *Res = Builder.CreateBitCast(
1975             Arg, Builder.getIntNTy(FVTy->getNumElements()));
1976         if (IID == Intrinsic::vector_reduce_and) {
1977           Res = Builder.CreateICmpEQ(
1978               Res, ConstantInt::getAllOnesValue(Res->getType()));
1979         } else {
1980           assert(IID == Intrinsic::vector_reduce_or &&
1981                  "Expected or reduction.");
1982           Res = Builder.CreateIsNotNull(Res);
1983         }
1984         replaceInstUsesWith(CI, Res);
1985         return eraseInstFromFunction(CI);
1986       }
1987     LLVM_FALLTHROUGH;
1988   }
1989   case Intrinsic::vector_reduce_add:
1990   case Intrinsic::vector_reduce_mul:
1991   case Intrinsic::vector_reduce_xor:
1992   case Intrinsic::vector_reduce_umax:
1993   case Intrinsic::vector_reduce_umin:
1994   case Intrinsic::vector_reduce_smax:
1995   case Intrinsic::vector_reduce_smin:
1996   case Intrinsic::vector_reduce_fmax:
1997   case Intrinsic::vector_reduce_fmin:
1998   case Intrinsic::vector_reduce_fadd:
1999   case Intrinsic::vector_reduce_fmul: {
2000     bool CanBeReassociated = (IID != Intrinsic::vector_reduce_fadd &&
2001                               IID != Intrinsic::vector_reduce_fmul) ||
2002                              II->hasAllowReassoc();
2003     const unsigned ArgIdx = (IID == Intrinsic::vector_reduce_fadd ||
2004                              IID == Intrinsic::vector_reduce_fmul)
2005                                 ? 1
2006                                 : 0;
2007     Value *Arg = II->getArgOperand(ArgIdx);
2008     Value *V;
2009     ArrayRef<int> Mask;
2010     if (!isa<FixedVectorType>(Arg->getType()) || !CanBeReassociated ||
2011         !match(Arg, m_Shuffle(m_Value(V), m_Undef(), m_Mask(Mask))) ||
2012         !cast<ShuffleVectorInst>(Arg)->isSingleSource())
2013       break;
2014     int Sz = Mask.size();
2015     SmallBitVector UsedIndices(Sz);
2016     for (int Idx : Mask) {
2017       if (Idx == UndefMaskElem || UsedIndices.test(Idx))
2018         break;
2019       UsedIndices.set(Idx);
2020     }
2021     // Can remove shuffle iff just shuffled elements, no repeats, undefs, or
2022     // other changes.
2023     if (UsedIndices.all()) {
2024       replaceUse(II->getOperandUse(ArgIdx), V);
2025       return nullptr;
2026     }
2027     break;
2028   }
2029   default: {
2030     // Handle target specific intrinsics
2031     Optional<Instruction *> V = targetInstCombineIntrinsic(*II);
2032     if (V.hasValue())
2033       return V.getValue();
2034     break;
2035   }
2036   }
2037   // Some intrinsics (like experimental_gc_statepoint) can be used in invoke
2038   // context, so it is handled in visitCallBase and we should trigger it.
2039   return visitCallBase(*II);
2040 }
2041 
2042 // Fence instruction simplification
2043 Instruction *InstCombinerImpl::visitFenceInst(FenceInst &FI) {
2044   // Remove identical consecutive fences.
2045   Instruction *Next = FI.getNextNonDebugInstruction();
2046   if (auto *NFI = dyn_cast<FenceInst>(Next))
2047     if (FI.isIdenticalTo(NFI))
2048       return eraseInstFromFunction(FI);
2049   return nullptr;
2050 }
2051 
2052 // InvokeInst simplification
2053 Instruction *InstCombinerImpl::visitInvokeInst(InvokeInst &II) {
2054   return visitCallBase(II);
2055 }
2056 
2057 // CallBrInst simplification
2058 Instruction *InstCombinerImpl::visitCallBrInst(CallBrInst &CBI) {
2059   return visitCallBase(CBI);
2060 }
2061 
2062 /// If this cast does not affect the value passed through the varargs area, we
2063 /// can eliminate the use of the cast.
2064 static bool isSafeToEliminateVarargsCast(const CallBase &Call,
2065                                          const DataLayout &DL,
2066                                          const CastInst *const CI,
2067                                          const int ix) {
2068   if (!CI->isLosslessCast())
2069     return false;
2070 
2071   // If this is a GC intrinsic, avoid munging types.  We need types for
2072   // statepoint reconstruction in SelectionDAG.
2073   // TODO: This is probably something which should be expanded to all
2074   // intrinsics since the entire point of intrinsics is that
2075   // they are understandable by the optimizer.
2076   if (isa<GCStatepointInst>(Call) || isa<GCRelocateInst>(Call) ||
2077       isa<GCResultInst>(Call))
2078     return false;
2079 
2080   // Opaque pointers are compatible with any byval types.
2081   PointerType *SrcTy = cast<PointerType>(CI->getOperand(0)->getType());
2082   if (SrcTy->isOpaque())
2083     return true;
2084 
2085   // The size of ByVal or InAlloca arguments is derived from the type, so we
2086   // can't change to a type with a different size.  If the size were
2087   // passed explicitly we could avoid this check.
2088   if (!Call.isPassPointeeByValueArgument(ix))
2089     return true;
2090 
2091   // The transform currently only handles type replacement for byval, not other
2092   // type-carrying attributes.
2093   if (!Call.isByValArgument(ix))
2094     return false;
2095 
2096   Type *SrcElemTy = SrcTy->getElementType();
2097   Type *DstElemTy = Call.getParamByValType(ix);
2098   if (!SrcElemTy->isSized() || !DstElemTy->isSized())
2099     return false;
2100   if (DL.getTypeAllocSize(SrcElemTy) != DL.getTypeAllocSize(DstElemTy))
2101     return false;
2102   return true;
2103 }
2104 
2105 Instruction *InstCombinerImpl::tryOptimizeCall(CallInst *CI) {
2106   if (!CI->getCalledFunction()) return nullptr;
2107 
2108   auto InstCombineRAUW = [this](Instruction *From, Value *With) {
2109     replaceInstUsesWith(*From, With);
2110   };
2111   auto InstCombineErase = [this](Instruction *I) {
2112     eraseInstFromFunction(*I);
2113   };
2114   LibCallSimplifier Simplifier(DL, &TLI, ORE, BFI, PSI, InstCombineRAUW,
2115                                InstCombineErase);
2116   if (Value *With = Simplifier.optimizeCall(CI, Builder)) {
2117     ++NumSimplified;
2118     return CI->use_empty() ? CI : replaceInstUsesWith(*CI, With);
2119   }
2120 
2121   return nullptr;
2122 }
2123 
2124 static IntrinsicInst *findInitTrampolineFromAlloca(Value *TrampMem) {
2125   // Strip off at most one level of pointer casts, looking for an alloca.  This
2126   // is good enough in practice and simpler than handling any number of casts.
2127   Value *Underlying = TrampMem->stripPointerCasts();
2128   if (Underlying != TrampMem &&
2129       (!Underlying->hasOneUse() || Underlying->user_back() != TrampMem))
2130     return nullptr;
2131   if (!isa<AllocaInst>(Underlying))
2132     return nullptr;
2133 
2134   IntrinsicInst *InitTrampoline = nullptr;
2135   for (User *U : TrampMem->users()) {
2136     IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
2137     if (!II)
2138       return nullptr;
2139     if (II->getIntrinsicID() == Intrinsic::init_trampoline) {
2140       if (InitTrampoline)
2141         // More than one init_trampoline writes to this value.  Give up.
2142         return nullptr;
2143       InitTrampoline = II;
2144       continue;
2145     }
2146     if (II->getIntrinsicID() == Intrinsic::adjust_trampoline)
2147       // Allow any number of calls to adjust.trampoline.
2148       continue;
2149     return nullptr;
2150   }
2151 
2152   // No call to init.trampoline found.
2153   if (!InitTrampoline)
2154     return nullptr;
2155 
2156   // Check that the alloca is being used in the expected way.
2157   if (InitTrampoline->getOperand(0) != TrampMem)
2158     return nullptr;
2159 
2160   return InitTrampoline;
2161 }
2162 
2163 static IntrinsicInst *findInitTrampolineFromBB(IntrinsicInst *AdjustTramp,
2164                                                Value *TrampMem) {
2165   // Visit all the previous instructions in the basic block, and try to find a
2166   // init.trampoline which has a direct path to the adjust.trampoline.
2167   for (BasicBlock::iterator I = AdjustTramp->getIterator(),
2168                             E = AdjustTramp->getParent()->begin();
2169        I != E;) {
2170     Instruction *Inst = &*--I;
2171     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2172       if (II->getIntrinsicID() == Intrinsic::init_trampoline &&
2173           II->getOperand(0) == TrampMem)
2174         return II;
2175     if (Inst->mayWriteToMemory())
2176       return nullptr;
2177   }
2178   return nullptr;
2179 }
2180 
2181 // Given a call to llvm.adjust.trampoline, find and return the corresponding
2182 // call to llvm.init.trampoline if the call to the trampoline can be optimized
2183 // to a direct call to a function.  Otherwise return NULL.
2184 static IntrinsicInst *findInitTrampoline(Value *Callee) {
2185   Callee = Callee->stripPointerCasts();
2186   IntrinsicInst *AdjustTramp = dyn_cast<IntrinsicInst>(Callee);
2187   if (!AdjustTramp ||
2188       AdjustTramp->getIntrinsicID() != Intrinsic::adjust_trampoline)
2189     return nullptr;
2190 
2191   Value *TrampMem = AdjustTramp->getOperand(0);
2192 
2193   if (IntrinsicInst *IT = findInitTrampolineFromAlloca(TrampMem))
2194     return IT;
2195   if (IntrinsicInst *IT = findInitTrampolineFromBB(AdjustTramp, TrampMem))
2196     return IT;
2197   return nullptr;
2198 }
2199 
2200 void InstCombinerImpl::annotateAnyAllocSite(CallBase &Call, const TargetLibraryInfo *TLI) {
2201   unsigned NumArgs = Call.getNumArgOperands();
2202   ConstantInt *Op0C = dyn_cast<ConstantInt>(Call.getOperand(0));
2203   ConstantInt *Op1C =
2204       (NumArgs == 1) ? nullptr : dyn_cast<ConstantInt>(Call.getOperand(1));
2205   // Bail out if the allocation size is zero (or an invalid alignment of zero
2206   // with aligned_alloc).
2207   if ((Op0C && Op0C->isNullValue()) || (Op1C && Op1C->isNullValue()))
2208     return;
2209 
2210   if (isMallocLikeFn(&Call, TLI) && Op0C) {
2211     if (isOpNewLikeFn(&Call, TLI))
2212       Call.addAttribute(AttributeList::ReturnIndex,
2213                         Attribute::getWithDereferenceableBytes(
2214                             Call.getContext(), Op0C->getZExtValue()));
2215     else
2216       Call.addAttribute(AttributeList::ReturnIndex,
2217                         Attribute::getWithDereferenceableOrNullBytes(
2218                             Call.getContext(), Op0C->getZExtValue()));
2219   } else if (isAlignedAllocLikeFn(&Call, TLI)) {
2220     if (Op1C)
2221       Call.addAttribute(AttributeList::ReturnIndex,
2222                         Attribute::getWithDereferenceableOrNullBytes(
2223                             Call.getContext(), Op1C->getZExtValue()));
2224     // Add alignment attribute if alignment is a power of two constant.
2225     if (Op0C && Op0C->getValue().ult(llvm::Value::MaximumAlignment) &&
2226         isKnownNonZero(Call.getOperand(1), DL, 0, &AC, &Call, &DT)) {
2227       uint64_t AlignmentVal = Op0C->getZExtValue();
2228       if (llvm::isPowerOf2_64(AlignmentVal)) {
2229         Call.removeAttribute(AttributeList::ReturnIndex, Attribute::Alignment);
2230         Call.addAttribute(AttributeList::ReturnIndex,
2231                           Attribute::getWithAlignment(Call.getContext(),
2232                                                       Align(AlignmentVal)));
2233       }
2234     }
2235   } else if (isReallocLikeFn(&Call, TLI) && Op1C) {
2236     Call.addAttribute(AttributeList::ReturnIndex,
2237                       Attribute::getWithDereferenceableOrNullBytes(
2238                           Call.getContext(), Op1C->getZExtValue()));
2239   } else if (isCallocLikeFn(&Call, TLI) && Op0C && Op1C) {
2240     bool Overflow;
2241     const APInt &N = Op0C->getValue();
2242     APInt Size = N.umul_ov(Op1C->getValue(), Overflow);
2243     if (!Overflow)
2244       Call.addAttribute(AttributeList::ReturnIndex,
2245                         Attribute::getWithDereferenceableOrNullBytes(
2246                             Call.getContext(), Size.getZExtValue()));
2247   } else if (isStrdupLikeFn(&Call, TLI)) {
2248     uint64_t Len = GetStringLength(Call.getOperand(0));
2249     if (Len) {
2250       // strdup
2251       if (NumArgs == 1)
2252         Call.addAttribute(AttributeList::ReturnIndex,
2253                           Attribute::getWithDereferenceableOrNullBytes(
2254                               Call.getContext(), Len));
2255       // strndup
2256       else if (NumArgs == 2 && Op1C)
2257         Call.addAttribute(
2258             AttributeList::ReturnIndex,
2259             Attribute::getWithDereferenceableOrNullBytes(
2260                 Call.getContext(), std::min(Len, Op1C->getZExtValue() + 1)));
2261     }
2262   }
2263 }
2264 
2265 /// Improvements for call, callbr and invoke instructions.
2266 Instruction *InstCombinerImpl::visitCallBase(CallBase &Call) {
2267   if (isAllocationFn(&Call, &TLI))
2268     annotateAnyAllocSite(Call, &TLI);
2269 
2270   bool Changed = false;
2271 
2272   // Mark any parameters that are known to be non-null with the nonnull
2273   // attribute.  This is helpful for inlining calls to functions with null
2274   // checks on their arguments.
2275   SmallVector<unsigned, 4> ArgNos;
2276   unsigned ArgNo = 0;
2277 
2278   for (Value *V : Call.args()) {
2279     if (V->getType()->isPointerTy() &&
2280         !Call.paramHasAttr(ArgNo, Attribute::NonNull) &&
2281         isKnownNonZero(V, DL, 0, &AC, &Call, &DT))
2282       ArgNos.push_back(ArgNo);
2283     ArgNo++;
2284   }
2285 
2286   assert(ArgNo == Call.arg_size() && "sanity check");
2287 
2288   if (!ArgNos.empty()) {
2289     AttributeList AS = Call.getAttributes();
2290     LLVMContext &Ctx = Call.getContext();
2291     AS = AS.addParamAttribute(Ctx, ArgNos,
2292                               Attribute::get(Ctx, Attribute::NonNull));
2293     Call.setAttributes(AS);
2294     Changed = true;
2295   }
2296 
2297   // If the callee is a pointer to a function, attempt to move any casts to the
2298   // arguments of the call/callbr/invoke.
2299   Value *Callee = Call.getCalledOperand();
2300   if (!isa<Function>(Callee) && transformConstExprCastCall(Call))
2301     return nullptr;
2302 
2303   if (Function *CalleeF = dyn_cast<Function>(Callee)) {
2304     // Remove the convergent attr on calls when the callee is not convergent.
2305     if (Call.isConvergent() && !CalleeF->isConvergent() &&
2306         !CalleeF->isIntrinsic()) {
2307       LLVM_DEBUG(dbgs() << "Removing convergent attr from instr " << Call
2308                         << "\n");
2309       Call.setNotConvergent();
2310       return &Call;
2311     }
2312 
2313     // If the call and callee calling conventions don't match, and neither one
2314     // of the calling conventions is compatible with C calling convention
2315     // this call must be unreachable, as the call is undefined.
2316     if ((CalleeF->getCallingConv() != Call.getCallingConv() &&
2317          !(CalleeF->getCallingConv() == llvm::CallingConv::C &&
2318            TargetLibraryInfoImpl::isCallingConvCCompatible(&Call)) &&
2319          !(Call.getCallingConv() == llvm::CallingConv::C &&
2320            TargetLibraryInfoImpl::isCallingConvCCompatible(CalleeF))) &&
2321         // Only do this for calls to a function with a body.  A prototype may
2322         // not actually end up matching the implementation's calling conv for a
2323         // variety of reasons (e.g. it may be written in assembly).
2324         !CalleeF->isDeclaration()) {
2325       Instruction *OldCall = &Call;
2326       CreateNonTerminatorUnreachable(OldCall);
2327       // If OldCall does not return void then replaceInstUsesWith poison.
2328       // This allows ValueHandlers and custom metadata to adjust itself.
2329       if (!OldCall->getType()->isVoidTy())
2330         replaceInstUsesWith(*OldCall, PoisonValue::get(OldCall->getType()));
2331       if (isa<CallInst>(OldCall))
2332         return eraseInstFromFunction(*OldCall);
2333 
2334       // We cannot remove an invoke or a callbr, because it would change thexi
2335       // CFG, just change the callee to a null pointer.
2336       cast<CallBase>(OldCall)->setCalledFunction(
2337           CalleeF->getFunctionType(),
2338           Constant::getNullValue(CalleeF->getType()));
2339       return nullptr;
2340     }
2341   }
2342 
2343   // Calling a null function pointer is undefined if a null address isn't
2344   // dereferenceable.
2345   if ((isa<ConstantPointerNull>(Callee) &&
2346        !NullPointerIsDefined(Call.getFunction())) ||
2347       isa<UndefValue>(Callee)) {
2348     // If Call does not return void then replaceInstUsesWith poison.
2349     // This allows ValueHandlers and custom metadata to adjust itself.
2350     if (!Call.getType()->isVoidTy())
2351       replaceInstUsesWith(Call, PoisonValue::get(Call.getType()));
2352 
2353     if (Call.isTerminator()) {
2354       // Can't remove an invoke or callbr because we cannot change the CFG.
2355       return nullptr;
2356     }
2357 
2358     // This instruction is not reachable, just remove it.
2359     CreateNonTerminatorUnreachable(&Call);
2360     return eraseInstFromFunction(Call);
2361   }
2362 
2363   if (IntrinsicInst *II = findInitTrampoline(Callee))
2364     return transformCallThroughTrampoline(Call, *II);
2365 
2366   // TODO: Drop this transform once opaque pointer transition is done.
2367   FunctionType *FTy = Call.getFunctionType();
2368   if (FTy->isVarArg()) {
2369     int ix = FTy->getNumParams();
2370     // See if we can optimize any arguments passed through the varargs area of
2371     // the call.
2372     for (auto I = Call.arg_begin() + FTy->getNumParams(), E = Call.arg_end();
2373          I != E; ++I, ++ix) {
2374       CastInst *CI = dyn_cast<CastInst>(*I);
2375       if (CI && isSafeToEliminateVarargsCast(Call, DL, CI, ix)) {
2376         replaceUse(*I, CI->getOperand(0));
2377 
2378         // Update the byval type to match the pointer type.
2379         // Not necessary for opaque pointers.
2380         PointerType *NewTy = cast<PointerType>(CI->getOperand(0)->getType());
2381         if (!NewTy->isOpaque() && Call.isByValArgument(ix)) {
2382           Call.removeParamAttr(ix, Attribute::ByVal);
2383           Call.addParamAttr(
2384               ix, Attribute::getWithByValType(
2385                       Call.getContext(), NewTy->getElementType()));
2386         }
2387         Changed = true;
2388       }
2389     }
2390   }
2391 
2392   if (isa<InlineAsm>(Callee) && !Call.doesNotThrow()) {
2393     InlineAsm *IA = cast<InlineAsm>(Callee);
2394     if (!IA->canThrow()) {
2395       // Normal inline asm calls cannot throw - mark them
2396       // 'nounwind'.
2397       Call.setDoesNotThrow();
2398       Changed = true;
2399     }
2400   }
2401 
2402   // Try to optimize the call if possible, we require DataLayout for most of
2403   // this.  None of these calls are seen as possibly dead so go ahead and
2404   // delete the instruction now.
2405   if (CallInst *CI = dyn_cast<CallInst>(&Call)) {
2406     Instruction *I = tryOptimizeCall(CI);
2407     // If we changed something return the result, etc. Otherwise let
2408     // the fallthrough check.
2409     if (I) return eraseInstFromFunction(*I);
2410   }
2411 
2412   if (!Call.use_empty() && !Call.isMustTailCall())
2413     if (Value *ReturnedArg = Call.getReturnedArgOperand()) {
2414       Type *CallTy = Call.getType();
2415       Type *RetArgTy = ReturnedArg->getType();
2416       if (RetArgTy->canLosslesslyBitCastTo(CallTy))
2417         return replaceInstUsesWith(
2418             Call, Builder.CreateBitOrPointerCast(ReturnedArg, CallTy));
2419     }
2420 
2421   if (isAllocLikeFn(&Call, &TLI))
2422     return visitAllocSite(Call);
2423 
2424   // Handle intrinsics which can be used in both call and invoke context.
2425   switch (Call.getIntrinsicID()) {
2426   case Intrinsic::experimental_gc_statepoint: {
2427     GCStatepointInst &GCSP = *cast<GCStatepointInst>(&Call);
2428     SmallPtrSet<Value *, 32> LiveGcValues;
2429     for (const GCRelocateInst *Reloc : GCSP.getGCRelocates()) {
2430       GCRelocateInst &GCR = *const_cast<GCRelocateInst *>(Reloc);
2431 
2432       // Remove the relocation if unused.
2433       if (GCR.use_empty()) {
2434         eraseInstFromFunction(GCR);
2435         continue;
2436       }
2437 
2438       Value *DerivedPtr = GCR.getDerivedPtr();
2439       Value *BasePtr = GCR.getBasePtr();
2440 
2441       // Undef is undef, even after relocation.
2442       if (isa<UndefValue>(DerivedPtr) || isa<UndefValue>(BasePtr)) {
2443         replaceInstUsesWith(GCR, UndefValue::get(GCR.getType()));
2444         eraseInstFromFunction(GCR);
2445         continue;
2446       }
2447 
2448       if (auto *PT = dyn_cast<PointerType>(GCR.getType())) {
2449         // The relocation of null will be null for most any collector.
2450         // TODO: provide a hook for this in GCStrategy.  There might be some
2451         // weird collector this property does not hold for.
2452         if (isa<ConstantPointerNull>(DerivedPtr)) {
2453           // Use null-pointer of gc_relocate's type to replace it.
2454           replaceInstUsesWith(GCR, ConstantPointerNull::get(PT));
2455           eraseInstFromFunction(GCR);
2456           continue;
2457         }
2458 
2459         // isKnownNonNull -> nonnull attribute
2460         if (!GCR.hasRetAttr(Attribute::NonNull) &&
2461             isKnownNonZero(DerivedPtr, DL, 0, &AC, &Call, &DT)) {
2462           GCR.addAttribute(AttributeList::ReturnIndex, Attribute::NonNull);
2463           // We discovered new fact, re-check users.
2464           Worklist.pushUsersToWorkList(GCR);
2465         }
2466       }
2467 
2468       // If we have two copies of the same pointer in the statepoint argument
2469       // list, canonicalize to one.  This may let us common gc.relocates.
2470       if (GCR.getBasePtr() == GCR.getDerivedPtr() &&
2471           GCR.getBasePtrIndex() != GCR.getDerivedPtrIndex()) {
2472         auto *OpIntTy = GCR.getOperand(2)->getType();
2473         GCR.setOperand(2, ConstantInt::get(OpIntTy, GCR.getBasePtrIndex()));
2474       }
2475 
2476       // TODO: bitcast(relocate(p)) -> relocate(bitcast(p))
2477       // Canonicalize on the type from the uses to the defs
2478 
2479       // TODO: relocate((gep p, C, C2, ...)) -> gep(relocate(p), C, C2, ...)
2480       LiveGcValues.insert(BasePtr);
2481       LiveGcValues.insert(DerivedPtr);
2482     }
2483     Optional<OperandBundleUse> Bundle =
2484         GCSP.getOperandBundle(LLVMContext::OB_gc_live);
2485     unsigned NumOfGCLives = LiveGcValues.size();
2486     if (!Bundle.hasValue() || NumOfGCLives == Bundle->Inputs.size())
2487       break;
2488     // We can reduce the size of gc live bundle.
2489     DenseMap<Value *, unsigned> Val2Idx;
2490     std::vector<Value *> NewLiveGc;
2491     for (unsigned I = 0, E = Bundle->Inputs.size(); I < E; ++I) {
2492       Value *V = Bundle->Inputs[I];
2493       if (Val2Idx.count(V))
2494         continue;
2495       if (LiveGcValues.count(V)) {
2496         Val2Idx[V] = NewLiveGc.size();
2497         NewLiveGc.push_back(V);
2498       } else
2499         Val2Idx[V] = NumOfGCLives;
2500     }
2501     // Update all gc.relocates
2502     for (const GCRelocateInst *Reloc : GCSP.getGCRelocates()) {
2503       GCRelocateInst &GCR = *const_cast<GCRelocateInst *>(Reloc);
2504       Value *BasePtr = GCR.getBasePtr();
2505       assert(Val2Idx.count(BasePtr) && Val2Idx[BasePtr] != NumOfGCLives &&
2506              "Missed live gc for base pointer");
2507       auto *OpIntTy1 = GCR.getOperand(1)->getType();
2508       GCR.setOperand(1, ConstantInt::get(OpIntTy1, Val2Idx[BasePtr]));
2509       Value *DerivedPtr = GCR.getDerivedPtr();
2510       assert(Val2Idx.count(DerivedPtr) && Val2Idx[DerivedPtr] != NumOfGCLives &&
2511              "Missed live gc for derived pointer");
2512       auto *OpIntTy2 = GCR.getOperand(2)->getType();
2513       GCR.setOperand(2, ConstantInt::get(OpIntTy2, Val2Idx[DerivedPtr]));
2514     }
2515     // Create new statepoint instruction.
2516     OperandBundleDef NewBundle("gc-live", NewLiveGc);
2517     return CallBase::Create(&Call, NewBundle);
2518   }
2519   default: { break; }
2520   }
2521 
2522   return Changed ? &Call : nullptr;
2523 }
2524 
2525 /// If the callee is a constexpr cast of a function, attempt to move the cast to
2526 /// the arguments of the call/callbr/invoke.
2527 bool InstCombinerImpl::transformConstExprCastCall(CallBase &Call) {
2528   auto *Callee =
2529       dyn_cast<Function>(Call.getCalledOperand()->stripPointerCasts());
2530   if (!Callee)
2531     return false;
2532 
2533   // If this is a call to a thunk function, don't remove the cast. Thunks are
2534   // used to transparently forward all incoming parameters and outgoing return
2535   // values, so it's important to leave the cast in place.
2536   if (Callee->hasFnAttribute("thunk"))
2537     return false;
2538 
2539   // If this is a musttail call, the callee's prototype must match the caller's
2540   // prototype with the exception of pointee types. The code below doesn't
2541   // implement that, so we can't do this transform.
2542   // TODO: Do the transform if it only requires adding pointer casts.
2543   if (Call.isMustTailCall())
2544     return false;
2545 
2546   Instruction *Caller = &Call;
2547   const AttributeList &CallerPAL = Call.getAttributes();
2548 
2549   // Okay, this is a cast from a function to a different type.  Unless doing so
2550   // would cause a type conversion of one of our arguments, change this call to
2551   // be a direct call with arguments casted to the appropriate types.
2552   FunctionType *FT = Callee->getFunctionType();
2553   Type *OldRetTy = Caller->getType();
2554   Type *NewRetTy = FT->getReturnType();
2555 
2556   // Check to see if we are changing the return type...
2557   if (OldRetTy != NewRetTy) {
2558 
2559     if (NewRetTy->isStructTy())
2560       return false; // TODO: Handle multiple return values.
2561 
2562     if (!CastInst::isBitOrNoopPointerCastable(NewRetTy, OldRetTy, DL)) {
2563       if (Callee->isDeclaration())
2564         return false;   // Cannot transform this return value.
2565 
2566       if (!Caller->use_empty() &&
2567           // void -> non-void is handled specially
2568           !NewRetTy->isVoidTy())
2569         return false;   // Cannot transform this return value.
2570     }
2571 
2572     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
2573       AttrBuilder RAttrs(CallerPAL, AttributeList::ReturnIndex);
2574       if (RAttrs.overlaps(AttributeFuncs::typeIncompatible(NewRetTy)))
2575         return false;   // Attribute not compatible with transformed value.
2576     }
2577 
2578     // If the callbase is an invoke/callbr instruction, and the return value is
2579     // used by a PHI node in a successor, we cannot change the return type of
2580     // the call because there is no place to put the cast instruction (without
2581     // breaking the critical edge).  Bail out in this case.
2582     if (!Caller->use_empty()) {
2583       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
2584         for (User *U : II->users())
2585           if (PHINode *PN = dyn_cast<PHINode>(U))
2586             if (PN->getParent() == II->getNormalDest() ||
2587                 PN->getParent() == II->getUnwindDest())
2588               return false;
2589       // FIXME: Be conservative for callbr to avoid a quadratic search.
2590       if (isa<CallBrInst>(Caller))
2591         return false;
2592     }
2593   }
2594 
2595   unsigned NumActualArgs = Call.arg_size();
2596   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
2597 
2598   // Prevent us turning:
2599   // declare void @takes_i32_inalloca(i32* inalloca)
2600   //  call void bitcast (void (i32*)* @takes_i32_inalloca to void (i32)*)(i32 0)
2601   //
2602   // into:
2603   //  call void @takes_i32_inalloca(i32* null)
2604   //
2605   //  Similarly, avoid folding away bitcasts of byval calls.
2606   if (Callee->getAttributes().hasAttrSomewhere(Attribute::InAlloca) ||
2607       Callee->getAttributes().hasAttrSomewhere(Attribute::Preallocated) ||
2608       Callee->getAttributes().hasAttrSomewhere(Attribute::ByVal))
2609     return false;
2610 
2611   auto AI = Call.arg_begin();
2612   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
2613     Type *ParamTy = FT->getParamType(i);
2614     Type *ActTy = (*AI)->getType();
2615 
2616     if (!CastInst::isBitOrNoopPointerCastable(ActTy, ParamTy, DL))
2617       return false;   // Cannot transform this parameter value.
2618 
2619     if (AttrBuilder(CallerPAL.getParamAttributes(i))
2620             .overlaps(AttributeFuncs::typeIncompatible(ParamTy)))
2621       return false;   // Attribute not compatible with transformed value.
2622 
2623     if (Call.isInAllocaArgument(i))
2624       return false;   // Cannot transform to and from inalloca.
2625 
2626     if (CallerPAL.hasParamAttribute(i, Attribute::SwiftError))
2627       return false;
2628 
2629     // If the parameter is passed as a byval argument, then we have to have a
2630     // sized type and the sized type has to have the same size as the old type.
2631     if (ParamTy != ActTy && CallerPAL.hasParamAttribute(i, Attribute::ByVal)) {
2632       PointerType *ParamPTy = dyn_cast<PointerType>(ParamTy);
2633       if (!ParamPTy || !ParamPTy->getElementType()->isSized())
2634         return false;
2635 
2636       Type *CurElTy = Call.getParamByValType(i);
2637       if (DL.getTypeAllocSize(CurElTy) !=
2638           DL.getTypeAllocSize(ParamPTy->getElementType()))
2639         return false;
2640     }
2641   }
2642 
2643   if (Callee->isDeclaration()) {
2644     // Do not delete arguments unless we have a function body.
2645     if (FT->getNumParams() < NumActualArgs && !FT->isVarArg())
2646       return false;
2647 
2648     // If the callee is just a declaration, don't change the varargsness of the
2649     // call.  We don't want to introduce a varargs call where one doesn't
2650     // already exist.
2651     PointerType *APTy = cast<PointerType>(Call.getCalledOperand()->getType());
2652     if (FT->isVarArg()!=cast<FunctionType>(APTy->getElementType())->isVarArg())
2653       return false;
2654 
2655     // If both the callee and the cast type are varargs, we still have to make
2656     // sure the number of fixed parameters are the same or we have the same
2657     // ABI issues as if we introduce a varargs call.
2658     if (FT->isVarArg() &&
2659         cast<FunctionType>(APTy->getElementType())->isVarArg() &&
2660         FT->getNumParams() !=
2661         cast<FunctionType>(APTy->getElementType())->getNumParams())
2662       return false;
2663   }
2664 
2665   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
2666       !CallerPAL.isEmpty()) {
2667     // In this case we have more arguments than the new function type, but we
2668     // won't be dropping them.  Check that these extra arguments have attributes
2669     // that are compatible with being a vararg call argument.
2670     unsigned SRetIdx;
2671     if (CallerPAL.hasAttrSomewhere(Attribute::StructRet, &SRetIdx) &&
2672         SRetIdx > FT->getNumParams())
2673       return false;
2674   }
2675 
2676   // Okay, we decided that this is a safe thing to do: go ahead and start
2677   // inserting cast instructions as necessary.
2678   SmallVector<Value *, 8> Args;
2679   SmallVector<AttributeSet, 8> ArgAttrs;
2680   Args.reserve(NumActualArgs);
2681   ArgAttrs.reserve(NumActualArgs);
2682 
2683   // Get any return attributes.
2684   AttrBuilder RAttrs(CallerPAL, AttributeList::ReturnIndex);
2685 
2686   // If the return value is not being used, the type may not be compatible
2687   // with the existing attributes.  Wipe out any problematic attributes.
2688   RAttrs.remove(AttributeFuncs::typeIncompatible(NewRetTy));
2689 
2690   LLVMContext &Ctx = Call.getContext();
2691   AI = Call.arg_begin();
2692   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
2693     Type *ParamTy = FT->getParamType(i);
2694 
2695     Value *NewArg = *AI;
2696     if ((*AI)->getType() != ParamTy)
2697       NewArg = Builder.CreateBitOrPointerCast(*AI, ParamTy);
2698     Args.push_back(NewArg);
2699 
2700     // Add any parameter attributes.
2701     if (CallerPAL.hasParamAttribute(i, Attribute::ByVal)) {
2702       AttrBuilder AB(CallerPAL.getParamAttributes(i));
2703       AB.addByValAttr(NewArg->getType()->getPointerElementType());
2704       ArgAttrs.push_back(AttributeSet::get(Ctx, AB));
2705     } else
2706       ArgAttrs.push_back(CallerPAL.getParamAttributes(i));
2707   }
2708 
2709   // If the function takes more arguments than the call was taking, add them
2710   // now.
2711   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i) {
2712     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
2713     ArgAttrs.push_back(AttributeSet());
2714   }
2715 
2716   // If we are removing arguments to the function, emit an obnoxious warning.
2717   if (FT->getNumParams() < NumActualArgs) {
2718     // TODO: if (!FT->isVarArg()) this call may be unreachable. PR14722
2719     if (FT->isVarArg()) {
2720       // Add all of the arguments in their promoted form to the arg list.
2721       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
2722         Type *PTy = getPromotedType((*AI)->getType());
2723         Value *NewArg = *AI;
2724         if (PTy != (*AI)->getType()) {
2725           // Must promote to pass through va_arg area!
2726           Instruction::CastOps opcode =
2727             CastInst::getCastOpcode(*AI, false, PTy, false);
2728           NewArg = Builder.CreateCast(opcode, *AI, PTy);
2729         }
2730         Args.push_back(NewArg);
2731 
2732         // Add any parameter attributes.
2733         ArgAttrs.push_back(CallerPAL.getParamAttributes(i));
2734       }
2735     }
2736   }
2737 
2738   AttributeSet FnAttrs = CallerPAL.getFnAttributes();
2739 
2740   if (NewRetTy->isVoidTy())
2741     Caller->setName("");   // Void type should not have a name.
2742 
2743   assert((ArgAttrs.size() == FT->getNumParams() || FT->isVarArg()) &&
2744          "missing argument attributes");
2745   AttributeList NewCallerPAL = AttributeList::get(
2746       Ctx, FnAttrs, AttributeSet::get(Ctx, RAttrs), ArgAttrs);
2747 
2748   SmallVector<OperandBundleDef, 1> OpBundles;
2749   Call.getOperandBundlesAsDefs(OpBundles);
2750 
2751   CallBase *NewCall;
2752   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
2753     NewCall = Builder.CreateInvoke(Callee, II->getNormalDest(),
2754                                    II->getUnwindDest(), Args, OpBundles);
2755   } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(Caller)) {
2756     NewCall = Builder.CreateCallBr(Callee, CBI->getDefaultDest(),
2757                                    CBI->getIndirectDests(), Args, OpBundles);
2758   } else {
2759     NewCall = Builder.CreateCall(Callee, Args, OpBundles);
2760     cast<CallInst>(NewCall)->setTailCallKind(
2761         cast<CallInst>(Caller)->getTailCallKind());
2762   }
2763   NewCall->takeName(Caller);
2764   NewCall->setCallingConv(Call.getCallingConv());
2765   NewCall->setAttributes(NewCallerPAL);
2766 
2767   // Preserve prof metadata if any.
2768   NewCall->copyMetadata(*Caller, {LLVMContext::MD_prof});
2769 
2770   // Insert a cast of the return type as necessary.
2771   Instruction *NC = NewCall;
2772   Value *NV = NC;
2773   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
2774     if (!NV->getType()->isVoidTy()) {
2775       NV = NC = CastInst::CreateBitOrPointerCast(NC, OldRetTy);
2776       NC->setDebugLoc(Caller->getDebugLoc());
2777 
2778       // If this is an invoke/callbr instruction, we should insert it after the
2779       // first non-phi instruction in the normal successor block.
2780       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
2781         BasicBlock::iterator I = II->getNormalDest()->getFirstInsertionPt();
2782         InsertNewInstBefore(NC, *I);
2783       } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(Caller)) {
2784         BasicBlock::iterator I = CBI->getDefaultDest()->getFirstInsertionPt();
2785         InsertNewInstBefore(NC, *I);
2786       } else {
2787         // Otherwise, it's a call, just insert cast right after the call.
2788         InsertNewInstBefore(NC, *Caller);
2789       }
2790       Worklist.pushUsersToWorkList(*Caller);
2791     } else {
2792       NV = UndefValue::get(Caller->getType());
2793     }
2794   }
2795 
2796   if (!Caller->use_empty())
2797     replaceInstUsesWith(*Caller, NV);
2798   else if (Caller->hasValueHandle()) {
2799     if (OldRetTy == NV->getType())
2800       ValueHandleBase::ValueIsRAUWd(Caller, NV);
2801     else
2802       // We cannot call ValueIsRAUWd with a different type, and the
2803       // actual tracked value will disappear.
2804       ValueHandleBase::ValueIsDeleted(Caller);
2805   }
2806 
2807   eraseInstFromFunction(*Caller);
2808   return true;
2809 }
2810 
2811 /// Turn a call to a function created by init_trampoline / adjust_trampoline
2812 /// intrinsic pair into a direct call to the underlying function.
2813 Instruction *
2814 InstCombinerImpl::transformCallThroughTrampoline(CallBase &Call,
2815                                                  IntrinsicInst &Tramp) {
2816   Value *Callee = Call.getCalledOperand();
2817   Type *CalleeTy = Callee->getType();
2818   FunctionType *FTy = Call.getFunctionType();
2819   AttributeList Attrs = Call.getAttributes();
2820 
2821   // If the call already has the 'nest' attribute somewhere then give up -
2822   // otherwise 'nest' would occur twice after splicing in the chain.
2823   if (Attrs.hasAttrSomewhere(Attribute::Nest))
2824     return nullptr;
2825 
2826   Function *NestF = cast<Function>(Tramp.getArgOperand(1)->stripPointerCasts());
2827   FunctionType *NestFTy = NestF->getFunctionType();
2828 
2829   AttributeList NestAttrs = NestF->getAttributes();
2830   if (!NestAttrs.isEmpty()) {
2831     unsigned NestArgNo = 0;
2832     Type *NestTy = nullptr;
2833     AttributeSet NestAttr;
2834 
2835     // Look for a parameter marked with the 'nest' attribute.
2836     for (FunctionType::param_iterator I = NestFTy->param_begin(),
2837                                       E = NestFTy->param_end();
2838          I != E; ++NestArgNo, ++I) {
2839       AttributeSet AS = NestAttrs.getParamAttributes(NestArgNo);
2840       if (AS.hasAttribute(Attribute::Nest)) {
2841         // Record the parameter type and any other attributes.
2842         NestTy = *I;
2843         NestAttr = AS;
2844         break;
2845       }
2846     }
2847 
2848     if (NestTy) {
2849       std::vector<Value*> NewArgs;
2850       std::vector<AttributeSet> NewArgAttrs;
2851       NewArgs.reserve(Call.arg_size() + 1);
2852       NewArgAttrs.reserve(Call.arg_size());
2853 
2854       // Insert the nest argument into the call argument list, which may
2855       // mean appending it.  Likewise for attributes.
2856 
2857       {
2858         unsigned ArgNo = 0;
2859         auto I = Call.arg_begin(), E = Call.arg_end();
2860         do {
2861           if (ArgNo == NestArgNo) {
2862             // Add the chain argument and attributes.
2863             Value *NestVal = Tramp.getArgOperand(2);
2864             if (NestVal->getType() != NestTy)
2865               NestVal = Builder.CreateBitCast(NestVal, NestTy, "nest");
2866             NewArgs.push_back(NestVal);
2867             NewArgAttrs.push_back(NestAttr);
2868           }
2869 
2870           if (I == E)
2871             break;
2872 
2873           // Add the original argument and attributes.
2874           NewArgs.push_back(*I);
2875           NewArgAttrs.push_back(Attrs.getParamAttributes(ArgNo));
2876 
2877           ++ArgNo;
2878           ++I;
2879         } while (true);
2880       }
2881 
2882       // The trampoline may have been bitcast to a bogus type (FTy).
2883       // Handle this by synthesizing a new function type, equal to FTy
2884       // with the chain parameter inserted.
2885 
2886       std::vector<Type*> NewTypes;
2887       NewTypes.reserve(FTy->getNumParams()+1);
2888 
2889       // Insert the chain's type into the list of parameter types, which may
2890       // mean appending it.
2891       {
2892         unsigned ArgNo = 0;
2893         FunctionType::param_iterator I = FTy->param_begin(),
2894           E = FTy->param_end();
2895 
2896         do {
2897           if (ArgNo == NestArgNo)
2898             // Add the chain's type.
2899             NewTypes.push_back(NestTy);
2900 
2901           if (I == E)
2902             break;
2903 
2904           // Add the original type.
2905           NewTypes.push_back(*I);
2906 
2907           ++ArgNo;
2908           ++I;
2909         } while (true);
2910       }
2911 
2912       // Replace the trampoline call with a direct call.  Let the generic
2913       // code sort out any function type mismatches.
2914       FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
2915                                                 FTy->isVarArg());
2916       Constant *NewCallee =
2917         NestF->getType() == PointerType::getUnqual(NewFTy) ?
2918         NestF : ConstantExpr::getBitCast(NestF,
2919                                          PointerType::getUnqual(NewFTy));
2920       AttributeList NewPAL =
2921           AttributeList::get(FTy->getContext(), Attrs.getFnAttributes(),
2922                              Attrs.getRetAttributes(), NewArgAttrs);
2923 
2924       SmallVector<OperandBundleDef, 1> OpBundles;
2925       Call.getOperandBundlesAsDefs(OpBundles);
2926 
2927       Instruction *NewCaller;
2928       if (InvokeInst *II = dyn_cast<InvokeInst>(&Call)) {
2929         NewCaller = InvokeInst::Create(NewFTy, NewCallee,
2930                                        II->getNormalDest(), II->getUnwindDest(),
2931                                        NewArgs, OpBundles);
2932         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
2933         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
2934       } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(&Call)) {
2935         NewCaller =
2936             CallBrInst::Create(NewFTy, NewCallee, CBI->getDefaultDest(),
2937                                CBI->getIndirectDests(), NewArgs, OpBundles);
2938         cast<CallBrInst>(NewCaller)->setCallingConv(CBI->getCallingConv());
2939         cast<CallBrInst>(NewCaller)->setAttributes(NewPAL);
2940       } else {
2941         NewCaller = CallInst::Create(NewFTy, NewCallee, NewArgs, OpBundles);
2942         cast<CallInst>(NewCaller)->setTailCallKind(
2943             cast<CallInst>(Call).getTailCallKind());
2944         cast<CallInst>(NewCaller)->setCallingConv(
2945             cast<CallInst>(Call).getCallingConv());
2946         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
2947       }
2948       NewCaller->setDebugLoc(Call.getDebugLoc());
2949 
2950       return NewCaller;
2951     }
2952   }
2953 
2954   // Replace the trampoline call with a direct call.  Since there is no 'nest'
2955   // parameter, there is no need to adjust the argument list.  Let the generic
2956   // code sort out any function type mismatches.
2957   Constant *NewCallee = ConstantExpr::getBitCast(NestF, CalleeTy);
2958   Call.setCalledFunction(FTy, NewCallee);
2959   return &Call;
2960 }
2961