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