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     KnownBits Known = computeKnownBits(IIOperand, 0, II);
1219     uint64_t LZ = alignDown(Known.countMinLeadingZeros(), 8);
1220     uint64_t TZ = alignDown(Known.countMinTrailingZeros(), 8);
1221 
1222     // bswap(x) -> shift(x) if x has exactly one "active byte"
1223     if (Known.getBitWidth() - LZ - TZ == 8) {
1224       assert(LZ != TZ && "active byte cannot be in the middle");
1225       if (LZ > TZ)  // -> shl(x) if the "active byte" is in the low part of x
1226         return BinaryOperator::CreateNUWShl(
1227             IIOperand, ConstantInt::get(IIOperand->getType(), LZ - TZ));
1228       // -> lshr(x) if the "active byte" is in the high part of x
1229       return BinaryOperator::CreateExactLShr(
1230             IIOperand, ConstantInt::get(IIOperand->getType(), TZ - LZ));
1231     }
1232 
1233     // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
1234     if (match(IIOperand, m_Trunc(m_BSwap(m_Value(X))))) {
1235       unsigned C = X->getType()->getScalarSizeInBits() -
1236                    IIOperand->getType()->getScalarSizeInBits();
1237       Value *CV = ConstantInt::get(X->getType(), C);
1238       Value *V = Builder.CreateLShr(X, CV);
1239       return new TruncInst(V, IIOperand->getType());
1240     }
1241     break;
1242   }
1243   case Intrinsic::masked_load:
1244     if (Value *SimplifiedMaskedOp = simplifyMaskedLoad(*II))
1245       return replaceInstUsesWith(CI, SimplifiedMaskedOp);
1246     break;
1247   case Intrinsic::masked_store:
1248     return simplifyMaskedStore(*II);
1249   case Intrinsic::masked_gather:
1250     return simplifyMaskedGather(*II);
1251   case Intrinsic::masked_scatter:
1252     return simplifyMaskedScatter(*II);
1253   case Intrinsic::launder_invariant_group:
1254   case Intrinsic::strip_invariant_group:
1255     if (auto *SkippedBarrier = simplifyInvariantGroupIntrinsic(*II, *this))
1256       return replaceInstUsesWith(*II, SkippedBarrier);
1257     break;
1258   case Intrinsic::powi:
1259     if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
1260       // 0 and 1 are handled in instsimplify
1261       // powi(x, -1) -> 1/x
1262       if (Power->isMinusOne())
1263         return BinaryOperator::CreateFDivFMF(ConstantFP::get(CI.getType(), 1.0),
1264                                              II->getArgOperand(0), II);
1265       // powi(x, 2) -> x*x
1266       if (Power->equalsInt(2))
1267         return BinaryOperator::CreateFMulFMF(II->getArgOperand(0),
1268                                              II->getArgOperand(0), II);
1269 
1270       if (!Power->getValue()[0]) {
1271         Value *X;
1272         // If power is even:
1273         // powi(-x, p) -> powi(x, p)
1274         // powi(fabs(x), p) -> powi(x, p)
1275         // powi(copysign(x, y), p) -> powi(x, p)
1276         if (match(II->getArgOperand(0), m_FNeg(m_Value(X))) ||
1277             match(II->getArgOperand(0), m_FAbs(m_Value(X))) ||
1278             match(II->getArgOperand(0),
1279                   m_Intrinsic<Intrinsic::copysign>(m_Value(X), m_Value())))
1280           return replaceOperand(*II, 0, X);
1281       }
1282     }
1283     break;
1284 
1285   case Intrinsic::cttz:
1286   case Intrinsic::ctlz:
1287     if (auto *I = foldCttzCtlz(*II, *this))
1288       return I;
1289     break;
1290 
1291   case Intrinsic::ctpop:
1292     if (auto *I = foldCtpop(*II, *this))
1293       return I;
1294     break;
1295 
1296   case Intrinsic::fshl:
1297   case Intrinsic::fshr: {
1298     Value *Op0 = II->getArgOperand(0), *Op1 = II->getArgOperand(1);
1299     Type *Ty = II->getType();
1300     unsigned BitWidth = Ty->getScalarSizeInBits();
1301     Constant *ShAmtC;
1302     if (match(II->getArgOperand(2), m_ImmConstant(ShAmtC)) &&
1303         !ShAmtC->containsConstantExpression()) {
1304       // Canonicalize a shift amount constant operand to modulo the bit-width.
1305       Constant *WidthC = ConstantInt::get(Ty, BitWidth);
1306       Constant *ModuloC = ConstantExpr::getURem(ShAmtC, WidthC);
1307       if (ModuloC != ShAmtC)
1308         return replaceOperand(*II, 2, ModuloC);
1309 
1310       assert(ConstantExpr::getICmp(ICmpInst::ICMP_UGT, WidthC, ShAmtC) ==
1311                  ConstantInt::getTrue(CmpInst::makeCmpResultType(Ty)) &&
1312              "Shift amount expected to be modulo bitwidth");
1313 
1314       // Canonicalize funnel shift right by constant to funnel shift left. This
1315       // is not entirely arbitrary. For historical reasons, the backend may
1316       // recognize rotate left patterns but miss rotate right patterns.
1317       if (IID == Intrinsic::fshr) {
1318         // fshr X, Y, C --> fshl X, Y, (BitWidth - C)
1319         Constant *LeftShiftC = ConstantExpr::getSub(WidthC, ShAmtC);
1320         Module *Mod = II->getModule();
1321         Function *Fshl = Intrinsic::getDeclaration(Mod, Intrinsic::fshl, Ty);
1322         return CallInst::Create(Fshl, { Op0, Op1, LeftShiftC });
1323       }
1324       assert(IID == Intrinsic::fshl &&
1325              "All funnel shifts by simple constants should go left");
1326 
1327       // fshl(X, 0, C) --> shl X, C
1328       // fshl(X, undef, C) --> shl X, C
1329       if (match(Op1, m_ZeroInt()) || match(Op1, m_Undef()))
1330         return BinaryOperator::CreateShl(Op0, ShAmtC);
1331 
1332       // fshl(0, X, C) --> lshr X, (BW-C)
1333       // fshl(undef, X, C) --> lshr X, (BW-C)
1334       if (match(Op0, m_ZeroInt()) || match(Op0, m_Undef()))
1335         return BinaryOperator::CreateLShr(Op1,
1336                                           ConstantExpr::getSub(WidthC, ShAmtC));
1337 
1338       // fshl i16 X, X, 8 --> bswap i16 X (reduce to more-specific form)
1339       if (Op0 == Op1 && BitWidth == 16 && match(ShAmtC, m_SpecificInt(8))) {
1340         Module *Mod = II->getModule();
1341         Function *Bswap = Intrinsic::getDeclaration(Mod, Intrinsic::bswap, Ty);
1342         return CallInst::Create(Bswap, { Op0 });
1343       }
1344     }
1345 
1346     // Left or right might be masked.
1347     if (SimplifyDemandedInstructionBits(*II))
1348       return &CI;
1349 
1350     // The shift amount (operand 2) of a funnel shift is modulo the bitwidth,
1351     // so only the low bits of the shift amount are demanded if the bitwidth is
1352     // a power-of-2.
1353     if (!isPowerOf2_32(BitWidth))
1354       break;
1355     APInt Op2Demanded = APInt::getLowBitsSet(BitWidth, Log2_32_Ceil(BitWidth));
1356     KnownBits Op2Known(BitWidth);
1357     if (SimplifyDemandedBits(II, 2, Op2Demanded, Op2Known))
1358       return &CI;
1359     break;
1360   }
1361   case Intrinsic::uadd_with_overflow:
1362   case Intrinsic::sadd_with_overflow: {
1363     if (Instruction *I = foldIntrinsicWithOverflowCommon(II))
1364       return I;
1365 
1366     // Given 2 constant operands whose sum does not overflow:
1367     // uaddo (X +nuw C0), C1 -> uaddo X, C0 + C1
1368     // saddo (X +nsw C0), C1 -> saddo X, C0 + C1
1369     Value *X;
1370     const APInt *C0, *C1;
1371     Value *Arg0 = II->getArgOperand(0);
1372     Value *Arg1 = II->getArgOperand(1);
1373     bool IsSigned = IID == Intrinsic::sadd_with_overflow;
1374     bool HasNWAdd = IsSigned ? match(Arg0, m_NSWAdd(m_Value(X), m_APInt(C0)))
1375                              : match(Arg0, m_NUWAdd(m_Value(X), m_APInt(C0)));
1376     if (HasNWAdd && match(Arg1, m_APInt(C1))) {
1377       bool Overflow;
1378       APInt NewC =
1379           IsSigned ? C1->sadd_ov(*C0, Overflow) : C1->uadd_ov(*C0, Overflow);
1380       if (!Overflow)
1381         return replaceInstUsesWith(
1382             *II, Builder.CreateBinaryIntrinsic(
1383                      IID, X, ConstantInt::get(Arg1->getType(), NewC)));
1384     }
1385     break;
1386   }
1387 
1388   case Intrinsic::umul_with_overflow:
1389   case Intrinsic::smul_with_overflow:
1390   case Intrinsic::usub_with_overflow:
1391     if (Instruction *I = foldIntrinsicWithOverflowCommon(II))
1392       return I;
1393     break;
1394 
1395   case Intrinsic::ssub_with_overflow: {
1396     if (Instruction *I = foldIntrinsicWithOverflowCommon(II))
1397       return I;
1398 
1399     Constant *C;
1400     Value *Arg0 = II->getArgOperand(0);
1401     Value *Arg1 = II->getArgOperand(1);
1402     // Given a constant C that is not the minimum signed value
1403     // for an integer of a given bit width:
1404     //
1405     // ssubo X, C -> saddo X, -C
1406     if (match(Arg1, m_Constant(C)) && C->isNotMinSignedValue()) {
1407       Value *NegVal = ConstantExpr::getNeg(C);
1408       // Build a saddo call that is equivalent to the discovered
1409       // ssubo call.
1410       return replaceInstUsesWith(
1411           *II, Builder.CreateBinaryIntrinsic(Intrinsic::sadd_with_overflow,
1412                                              Arg0, NegVal));
1413     }
1414 
1415     break;
1416   }
1417 
1418   case Intrinsic::uadd_sat:
1419   case Intrinsic::sadd_sat:
1420   case Intrinsic::usub_sat:
1421   case Intrinsic::ssub_sat: {
1422     SaturatingInst *SI = cast<SaturatingInst>(II);
1423     Type *Ty = SI->getType();
1424     Value *Arg0 = SI->getLHS();
1425     Value *Arg1 = SI->getRHS();
1426 
1427     // Make use of known overflow information.
1428     OverflowResult OR = computeOverflow(SI->getBinaryOp(), SI->isSigned(),
1429                                         Arg0, Arg1, SI);
1430     switch (OR) {
1431       case OverflowResult::MayOverflow:
1432         break;
1433       case OverflowResult::NeverOverflows:
1434         if (SI->isSigned())
1435           return BinaryOperator::CreateNSW(SI->getBinaryOp(), Arg0, Arg1);
1436         else
1437           return BinaryOperator::CreateNUW(SI->getBinaryOp(), Arg0, Arg1);
1438       case OverflowResult::AlwaysOverflowsLow: {
1439         unsigned BitWidth = Ty->getScalarSizeInBits();
1440         APInt Min = APSInt::getMinValue(BitWidth, !SI->isSigned());
1441         return replaceInstUsesWith(*SI, ConstantInt::get(Ty, Min));
1442       }
1443       case OverflowResult::AlwaysOverflowsHigh: {
1444         unsigned BitWidth = Ty->getScalarSizeInBits();
1445         APInt Max = APSInt::getMaxValue(BitWidth, !SI->isSigned());
1446         return replaceInstUsesWith(*SI, ConstantInt::get(Ty, Max));
1447       }
1448     }
1449 
1450     // ssub.sat(X, C) -> sadd.sat(X, -C) if C != MIN
1451     Constant *C;
1452     if (IID == Intrinsic::ssub_sat && match(Arg1, m_Constant(C)) &&
1453         C->isNotMinSignedValue()) {
1454       Value *NegVal = ConstantExpr::getNeg(C);
1455       return replaceInstUsesWith(
1456           *II, Builder.CreateBinaryIntrinsic(
1457               Intrinsic::sadd_sat, Arg0, NegVal));
1458     }
1459 
1460     // sat(sat(X + Val2) + Val) -> sat(X + (Val+Val2))
1461     // sat(sat(X - Val2) - Val) -> sat(X - (Val+Val2))
1462     // if Val and Val2 have the same sign
1463     if (auto *Other = dyn_cast<IntrinsicInst>(Arg0)) {
1464       Value *X;
1465       const APInt *Val, *Val2;
1466       APInt NewVal;
1467       bool IsUnsigned =
1468           IID == Intrinsic::uadd_sat || IID == Intrinsic::usub_sat;
1469       if (Other->getIntrinsicID() == IID &&
1470           match(Arg1, m_APInt(Val)) &&
1471           match(Other->getArgOperand(0), m_Value(X)) &&
1472           match(Other->getArgOperand(1), m_APInt(Val2))) {
1473         if (IsUnsigned)
1474           NewVal = Val->uadd_sat(*Val2);
1475         else if (Val->isNonNegative() == Val2->isNonNegative()) {
1476           bool Overflow;
1477           NewVal = Val->sadd_ov(*Val2, Overflow);
1478           if (Overflow) {
1479             // Both adds together may add more than SignedMaxValue
1480             // without saturating the final result.
1481             break;
1482           }
1483         } else {
1484           // Cannot fold saturated addition with different signs.
1485           break;
1486         }
1487 
1488         return replaceInstUsesWith(
1489             *II, Builder.CreateBinaryIntrinsic(
1490                      IID, X, ConstantInt::get(II->getType(), NewVal)));
1491       }
1492     }
1493     break;
1494   }
1495 
1496   case Intrinsic::minnum:
1497   case Intrinsic::maxnum:
1498   case Intrinsic::minimum:
1499   case Intrinsic::maximum: {
1500     Value *Arg0 = II->getArgOperand(0);
1501     Value *Arg1 = II->getArgOperand(1);
1502     Value *X, *Y;
1503     if (match(Arg0, m_FNeg(m_Value(X))) && match(Arg1, m_FNeg(m_Value(Y))) &&
1504         (Arg0->hasOneUse() || Arg1->hasOneUse())) {
1505       // If both operands are negated, invert the call and negate the result:
1506       // min(-X, -Y) --> -(max(X, Y))
1507       // max(-X, -Y) --> -(min(X, Y))
1508       Intrinsic::ID NewIID;
1509       switch (IID) {
1510       case Intrinsic::maxnum:
1511         NewIID = Intrinsic::minnum;
1512         break;
1513       case Intrinsic::minnum:
1514         NewIID = Intrinsic::maxnum;
1515         break;
1516       case Intrinsic::maximum:
1517         NewIID = Intrinsic::minimum;
1518         break;
1519       case Intrinsic::minimum:
1520         NewIID = Intrinsic::maximum;
1521         break;
1522       default:
1523         llvm_unreachable("unexpected intrinsic ID");
1524       }
1525       Value *NewCall = Builder.CreateBinaryIntrinsic(NewIID, X, Y, II);
1526       Instruction *FNeg = UnaryOperator::CreateFNeg(NewCall);
1527       FNeg->copyIRFlags(II);
1528       return FNeg;
1529     }
1530 
1531     // m(m(X, C2), C1) -> m(X, C)
1532     const APFloat *C1, *C2;
1533     if (auto *M = dyn_cast<IntrinsicInst>(Arg0)) {
1534       if (M->getIntrinsicID() == IID && match(Arg1, m_APFloat(C1)) &&
1535           ((match(M->getArgOperand(0), m_Value(X)) &&
1536             match(M->getArgOperand(1), m_APFloat(C2))) ||
1537            (match(M->getArgOperand(1), m_Value(X)) &&
1538             match(M->getArgOperand(0), m_APFloat(C2))))) {
1539         APFloat Res(0.0);
1540         switch (IID) {
1541         case Intrinsic::maxnum:
1542           Res = maxnum(*C1, *C2);
1543           break;
1544         case Intrinsic::minnum:
1545           Res = minnum(*C1, *C2);
1546           break;
1547         case Intrinsic::maximum:
1548           Res = maximum(*C1, *C2);
1549           break;
1550         case Intrinsic::minimum:
1551           Res = minimum(*C1, *C2);
1552           break;
1553         default:
1554           llvm_unreachable("unexpected intrinsic ID");
1555         }
1556         Instruction *NewCall = Builder.CreateBinaryIntrinsic(
1557             IID, X, ConstantFP::get(Arg0->getType(), Res), II);
1558         // TODO: Conservatively intersecting FMF. If Res == C2, the transform
1559         //       was a simplification (so Arg0 and its original flags could
1560         //       propagate?)
1561         NewCall->andIRFlags(M);
1562         return replaceInstUsesWith(*II, NewCall);
1563       }
1564     }
1565 
1566     // m((fpext X), (fpext Y)) -> fpext (m(X, Y))
1567     if (match(Arg0, m_OneUse(m_FPExt(m_Value(X)))) &&
1568         match(Arg1, m_OneUse(m_FPExt(m_Value(Y)))) &&
1569         X->getType() == Y->getType()) {
1570       Value *NewCall =
1571           Builder.CreateBinaryIntrinsic(IID, X, Y, II, II->getName());
1572       return new FPExtInst(NewCall, II->getType());
1573     }
1574 
1575     // max X, -X --> fabs X
1576     // min X, -X --> -(fabs X)
1577     // TODO: Remove one-use limitation? That is obviously better for max.
1578     //       It would be an extra instruction for min (fnabs), but that is
1579     //       still likely better for analysis and codegen.
1580     if ((match(Arg0, m_OneUse(m_FNeg(m_Value(X)))) && Arg1 == X) ||
1581         (match(Arg1, m_OneUse(m_FNeg(m_Value(X)))) && Arg0 == X)) {
1582       Value *R = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, X, II);
1583       if (IID == Intrinsic::minimum || IID == Intrinsic::minnum)
1584         R = Builder.CreateFNegFMF(R, II);
1585       return replaceInstUsesWith(*II, R);
1586     }
1587 
1588     break;
1589   }
1590   case Intrinsic::fmuladd: {
1591     // Canonicalize fast fmuladd to the separate fmul + fadd.
1592     if (II->isFast()) {
1593       BuilderTy::FastMathFlagGuard Guard(Builder);
1594       Builder.setFastMathFlags(II->getFastMathFlags());
1595       Value *Mul = Builder.CreateFMul(II->getArgOperand(0),
1596                                       II->getArgOperand(1));
1597       Value *Add = Builder.CreateFAdd(Mul, II->getArgOperand(2));
1598       Add->takeName(II);
1599       return replaceInstUsesWith(*II, Add);
1600     }
1601 
1602     // Try to simplify the underlying FMul.
1603     if (Value *V = SimplifyFMulInst(II->getArgOperand(0), II->getArgOperand(1),
1604                                     II->getFastMathFlags(),
1605                                     SQ.getWithInstruction(II))) {
1606       auto *FAdd = BinaryOperator::CreateFAdd(V, II->getArgOperand(2));
1607       FAdd->copyFastMathFlags(II);
1608       return FAdd;
1609     }
1610 
1611     LLVM_FALLTHROUGH;
1612   }
1613   case Intrinsic::fma: {
1614     // fma fneg(x), fneg(y), z -> fma x, y, z
1615     Value *Src0 = II->getArgOperand(0);
1616     Value *Src1 = II->getArgOperand(1);
1617     Value *X, *Y;
1618     if (match(Src0, m_FNeg(m_Value(X))) && match(Src1, m_FNeg(m_Value(Y)))) {
1619       replaceOperand(*II, 0, X);
1620       replaceOperand(*II, 1, Y);
1621       return II;
1622     }
1623 
1624     // fma fabs(x), fabs(x), z -> fma x, x, z
1625     if (match(Src0, m_FAbs(m_Value(X))) &&
1626         match(Src1, m_FAbs(m_Specific(X)))) {
1627       replaceOperand(*II, 0, X);
1628       replaceOperand(*II, 1, X);
1629       return II;
1630     }
1631 
1632     // Try to simplify the underlying FMul. We can only apply simplifications
1633     // that do not require rounding.
1634     if (Value *V = SimplifyFMAFMul(II->getArgOperand(0), II->getArgOperand(1),
1635                                    II->getFastMathFlags(),
1636                                    SQ.getWithInstruction(II))) {
1637       auto *FAdd = BinaryOperator::CreateFAdd(V, II->getArgOperand(2));
1638       FAdd->copyFastMathFlags(II);
1639       return FAdd;
1640     }
1641 
1642     // fma x, y, 0 -> fmul x, y
1643     // This is always valid for -0.0, but requires nsz for +0.0 as
1644     // -0.0 + 0.0 = 0.0, which would not be the same as the fmul on its own.
1645     if (match(II->getArgOperand(2), m_NegZeroFP()) ||
1646         (match(II->getArgOperand(2), m_PosZeroFP()) &&
1647          II->getFastMathFlags().noSignedZeros()))
1648       return BinaryOperator::CreateFMulFMF(Src0, Src1, II);
1649 
1650     break;
1651   }
1652   case Intrinsic::copysign: {
1653     Value *Mag = II->getArgOperand(0), *Sign = II->getArgOperand(1);
1654     if (SignBitMustBeZero(Sign, &TLI)) {
1655       // If we know that the sign argument is positive, reduce to FABS:
1656       // copysign Mag, +Sign --> fabs Mag
1657       Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, Mag, II);
1658       return replaceInstUsesWith(*II, Fabs);
1659     }
1660     // TODO: There should be a ValueTracking sibling like SignBitMustBeOne.
1661     const APFloat *C;
1662     if (match(Sign, m_APFloat(C)) && C->isNegative()) {
1663       // If we know that the sign argument is negative, reduce to FNABS:
1664       // copysign Mag, -Sign --> fneg (fabs Mag)
1665       Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, Mag, II);
1666       return replaceInstUsesWith(*II, Builder.CreateFNegFMF(Fabs, II));
1667     }
1668 
1669     // Propagate sign argument through nested calls:
1670     // copysign Mag, (copysign ?, X) --> copysign Mag, X
1671     Value *X;
1672     if (match(Sign, m_Intrinsic<Intrinsic::copysign>(m_Value(), m_Value(X))))
1673       return replaceOperand(*II, 1, X);
1674 
1675     // Peek through changes of magnitude's sign-bit. This call rewrites those:
1676     // copysign (fabs X), Sign --> copysign X, Sign
1677     // copysign (fneg X), Sign --> copysign X, Sign
1678     if (match(Mag, m_FAbs(m_Value(X))) || match(Mag, m_FNeg(m_Value(X))))
1679       return replaceOperand(*II, 0, X);
1680 
1681     break;
1682   }
1683   case Intrinsic::fabs: {
1684     Value *Cond, *TVal, *FVal;
1685     if (match(II->getArgOperand(0),
1686               m_Select(m_Value(Cond), m_Value(TVal), m_Value(FVal)))) {
1687       // fabs (select Cond, TrueC, FalseC) --> select Cond, AbsT, AbsF
1688       if (isa<Constant>(TVal) && isa<Constant>(FVal)) {
1689         CallInst *AbsT = Builder.CreateCall(II->getCalledFunction(), {TVal});
1690         CallInst *AbsF = Builder.CreateCall(II->getCalledFunction(), {FVal});
1691         return SelectInst::Create(Cond, AbsT, AbsF);
1692       }
1693       // fabs (select Cond, -FVal, FVal) --> fabs FVal
1694       if (match(TVal, m_FNeg(m_Specific(FVal))))
1695         return replaceOperand(*II, 0, FVal);
1696       // fabs (select Cond, TVal, -TVal) --> fabs TVal
1697       if (match(FVal, m_FNeg(m_Specific(TVal))))
1698         return replaceOperand(*II, 0, TVal);
1699     }
1700 
1701     LLVM_FALLTHROUGH;
1702   }
1703   case Intrinsic::ceil:
1704   case Intrinsic::floor:
1705   case Intrinsic::round:
1706   case Intrinsic::roundeven:
1707   case Intrinsic::nearbyint:
1708   case Intrinsic::rint:
1709   case Intrinsic::trunc: {
1710     Value *ExtSrc;
1711     if (match(II->getArgOperand(0), m_OneUse(m_FPExt(m_Value(ExtSrc))))) {
1712       // Narrow the call: intrinsic (fpext x) -> fpext (intrinsic x)
1713       Value *NarrowII = Builder.CreateUnaryIntrinsic(IID, ExtSrc, II);
1714       return new FPExtInst(NarrowII, II->getType());
1715     }
1716     break;
1717   }
1718   case Intrinsic::cos:
1719   case Intrinsic::amdgcn_cos: {
1720     Value *X;
1721     Value *Src = II->getArgOperand(0);
1722     if (match(Src, m_FNeg(m_Value(X))) || match(Src, m_FAbs(m_Value(X)))) {
1723       // cos(-x) -> cos(x)
1724       // cos(fabs(x)) -> cos(x)
1725       return replaceOperand(*II, 0, X);
1726     }
1727     break;
1728   }
1729   case Intrinsic::sin: {
1730     Value *X;
1731     if (match(II->getArgOperand(0), m_OneUse(m_FNeg(m_Value(X))))) {
1732       // sin(-x) --> -sin(x)
1733       Value *NewSin = Builder.CreateUnaryIntrinsic(Intrinsic::sin, X, II);
1734       Instruction *FNeg = UnaryOperator::CreateFNeg(NewSin);
1735       FNeg->copyFastMathFlags(II);
1736       return FNeg;
1737     }
1738     break;
1739   }
1740 
1741   case Intrinsic::arm_neon_vtbl1:
1742   case Intrinsic::aarch64_neon_tbl1:
1743     if (Value *V = simplifyNeonTbl1(*II, Builder))
1744       return replaceInstUsesWith(*II, V);
1745     break;
1746 
1747   case Intrinsic::arm_neon_vmulls:
1748   case Intrinsic::arm_neon_vmullu:
1749   case Intrinsic::aarch64_neon_smull:
1750   case Intrinsic::aarch64_neon_umull: {
1751     Value *Arg0 = II->getArgOperand(0);
1752     Value *Arg1 = II->getArgOperand(1);
1753 
1754     // Handle mul by zero first:
1755     if (isa<ConstantAggregateZero>(Arg0) || isa<ConstantAggregateZero>(Arg1)) {
1756       return replaceInstUsesWith(CI, ConstantAggregateZero::get(II->getType()));
1757     }
1758 
1759     // Check for constant LHS & RHS - in this case we just simplify.
1760     bool Zext = (IID == Intrinsic::arm_neon_vmullu ||
1761                  IID == Intrinsic::aarch64_neon_umull);
1762     VectorType *NewVT = cast<VectorType>(II->getType());
1763     if (Constant *CV0 = dyn_cast<Constant>(Arg0)) {
1764       if (Constant *CV1 = dyn_cast<Constant>(Arg1)) {
1765         CV0 = ConstantExpr::getIntegerCast(CV0, NewVT, /*isSigned=*/!Zext);
1766         CV1 = ConstantExpr::getIntegerCast(CV1, NewVT, /*isSigned=*/!Zext);
1767 
1768         return replaceInstUsesWith(CI, ConstantExpr::getMul(CV0, CV1));
1769       }
1770 
1771       // Couldn't simplify - canonicalize constant to the RHS.
1772       std::swap(Arg0, Arg1);
1773     }
1774 
1775     // Handle mul by one:
1776     if (Constant *CV1 = dyn_cast<Constant>(Arg1))
1777       if (ConstantInt *Splat =
1778               dyn_cast_or_null<ConstantInt>(CV1->getSplatValue()))
1779         if (Splat->isOne())
1780           return CastInst::CreateIntegerCast(Arg0, II->getType(),
1781                                              /*isSigned=*/!Zext);
1782 
1783     break;
1784   }
1785   case Intrinsic::arm_neon_aesd:
1786   case Intrinsic::arm_neon_aese:
1787   case Intrinsic::aarch64_crypto_aesd:
1788   case Intrinsic::aarch64_crypto_aese: {
1789     Value *DataArg = II->getArgOperand(0);
1790     Value *KeyArg  = II->getArgOperand(1);
1791 
1792     // Try to use the builtin XOR in AESE and AESD to eliminate a prior XOR
1793     Value *Data, *Key;
1794     if (match(KeyArg, m_ZeroInt()) &&
1795         match(DataArg, m_Xor(m_Value(Data), m_Value(Key)))) {
1796       replaceOperand(*II, 0, Data);
1797       replaceOperand(*II, 1, Key);
1798       return II;
1799     }
1800     break;
1801   }
1802   case Intrinsic::hexagon_V6_vandvrt:
1803   case Intrinsic::hexagon_V6_vandvrt_128B: {
1804     // Simplify Q -> V -> Q conversion.
1805     if (auto Op0 = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {
1806       Intrinsic::ID ID0 = Op0->getIntrinsicID();
1807       if (ID0 != Intrinsic::hexagon_V6_vandqrt &&
1808           ID0 != Intrinsic::hexagon_V6_vandqrt_128B)
1809         break;
1810       Value *Bytes = Op0->getArgOperand(1), *Mask = II->getArgOperand(1);
1811       uint64_t Bytes1 = computeKnownBits(Bytes, 0, Op0).One.getZExtValue();
1812       uint64_t Mask1 = computeKnownBits(Mask, 0, II).One.getZExtValue();
1813       // Check if every byte has common bits in Bytes and Mask.
1814       uint64_t C = Bytes1 & Mask1;
1815       if ((C & 0xFF) && (C & 0xFF00) && (C & 0xFF0000) && (C & 0xFF000000))
1816         return replaceInstUsesWith(*II, Op0->getArgOperand(0));
1817     }
1818     break;
1819   }
1820   case Intrinsic::stackrestore: {
1821     enum class ClassifyResult {
1822       None,
1823       Alloca,
1824       StackRestore,
1825       CallWithSideEffects,
1826     };
1827     auto Classify = [](const Instruction *I) {
1828       if (isa<AllocaInst>(I))
1829         return ClassifyResult::Alloca;
1830 
1831       if (auto *CI = dyn_cast<CallInst>(I)) {
1832         if (auto *II = dyn_cast<IntrinsicInst>(CI)) {
1833           if (II->getIntrinsicID() == Intrinsic::stackrestore)
1834             return ClassifyResult::StackRestore;
1835 
1836           if (II->mayHaveSideEffects())
1837             return ClassifyResult::CallWithSideEffects;
1838         } else {
1839           // Consider all non-intrinsic calls to be side effects
1840           return ClassifyResult::CallWithSideEffects;
1841         }
1842       }
1843 
1844       return ClassifyResult::None;
1845     };
1846 
1847     // If the stacksave and the stackrestore are in the same BB, and there is
1848     // no intervening call, alloca, or stackrestore of a different stacksave,
1849     // remove the restore. This can happen when variable allocas are DCE'd.
1850     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {
1851       if (SS->getIntrinsicID() == Intrinsic::stacksave &&
1852           SS->getParent() == II->getParent()) {
1853         BasicBlock::iterator BI(SS);
1854         bool CannotRemove = false;
1855         for (++BI; &*BI != II; ++BI) {
1856           switch (Classify(&*BI)) {
1857           case ClassifyResult::None:
1858             // So far so good, look at next instructions.
1859             break;
1860 
1861           case ClassifyResult::StackRestore:
1862             // If we found an intervening stackrestore for a different
1863             // stacksave, we can't remove the stackrestore. Otherwise, continue.
1864             if (cast<IntrinsicInst>(*BI).getArgOperand(0) != SS)
1865               CannotRemove = true;
1866             break;
1867 
1868           case ClassifyResult::Alloca:
1869           case ClassifyResult::CallWithSideEffects:
1870             // If we found an alloca, a non-intrinsic call, or an intrinsic
1871             // call with side effects, we can't remove the stackrestore.
1872             CannotRemove = true;
1873             break;
1874           }
1875           if (CannotRemove)
1876             break;
1877         }
1878 
1879         if (!CannotRemove)
1880           return eraseInstFromFunction(CI);
1881       }
1882     }
1883 
1884     // Scan down this block to see if there is another stack restore in the
1885     // same block without an intervening call/alloca.
1886     BasicBlock::iterator BI(II);
1887     Instruction *TI = II->getParent()->getTerminator();
1888     bool CannotRemove = false;
1889     for (++BI; &*BI != TI; ++BI) {
1890       switch (Classify(&*BI)) {
1891       case ClassifyResult::None:
1892         // So far so good, look at next instructions.
1893         break;
1894 
1895       case ClassifyResult::StackRestore:
1896         // If there is a stackrestore below this one, remove this one.
1897         return eraseInstFromFunction(CI);
1898 
1899       case ClassifyResult::Alloca:
1900       case ClassifyResult::CallWithSideEffects:
1901         // If we found an alloca, a non-intrinsic call, or an intrinsic call
1902         // with side effects (such as llvm.stacksave and llvm.read_register),
1903         // we can't remove the stack restore.
1904         CannotRemove = true;
1905         break;
1906       }
1907       if (CannotRemove)
1908         break;
1909     }
1910 
1911     // If the stack restore is in a return, resume, or unwind block and if there
1912     // are no allocas or calls between the restore and the return, nuke the
1913     // restore.
1914     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<ResumeInst>(TI)))
1915       return eraseInstFromFunction(CI);
1916     break;
1917   }
1918   case Intrinsic::lifetime_end:
1919     // Asan needs to poison memory to detect invalid access which is possible
1920     // even for empty lifetime range.
1921     if (II->getFunction()->hasFnAttribute(Attribute::SanitizeAddress) ||
1922         II->getFunction()->hasFnAttribute(Attribute::SanitizeMemory) ||
1923         II->getFunction()->hasFnAttribute(Attribute::SanitizeHWAddress))
1924       break;
1925 
1926     if (removeTriviallyEmptyRange(*II, *this, [](const IntrinsicInst &I) {
1927           return I.getIntrinsicID() == Intrinsic::lifetime_start;
1928         }))
1929       return nullptr;
1930     break;
1931   case Intrinsic::assume: {
1932     Value *IIOperand = II->getArgOperand(0);
1933     SmallVector<OperandBundleDef, 4> OpBundles;
1934     II->getOperandBundlesAsDefs(OpBundles);
1935 
1936     /// This will remove the boolean Condition from the assume given as
1937     /// argument and remove the assume if it becomes useless.
1938     /// always returns nullptr for use as a return values.
1939     auto RemoveConditionFromAssume = [&](Instruction *Assume) -> Instruction * {
1940       assert(isa<AssumeInst>(Assume));
1941       if (isAssumeWithEmptyBundle(*cast<AssumeInst>(II)))
1942         return eraseInstFromFunction(CI);
1943       replaceUse(II->getOperandUse(0), ConstantInt::getTrue(II->getContext()));
1944       return nullptr;
1945     };
1946     // Remove an assume if it is followed by an identical assume.
1947     // TODO: Do we need this? Unless there are conflicting assumptions, the
1948     // computeKnownBits(IIOperand) below here eliminates redundant assumes.
1949     Instruction *Next = II->getNextNonDebugInstruction();
1950     if (match(Next, m_Intrinsic<Intrinsic::assume>(m_Specific(IIOperand))))
1951       return RemoveConditionFromAssume(Next);
1952 
1953     // Canonicalize assume(a && b) -> assume(a); assume(b);
1954     // Note: New assumption intrinsics created here are registered by
1955     // the InstCombineIRInserter object.
1956     FunctionType *AssumeIntrinsicTy = II->getFunctionType();
1957     Value *AssumeIntrinsic = II->getCalledOperand();
1958     Value *A, *B;
1959     if (match(IIOperand, m_LogicalAnd(m_Value(A), m_Value(B)))) {
1960       Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic, A, OpBundles,
1961                          II->getName());
1962       Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic, B, II->getName());
1963       return eraseInstFromFunction(*II);
1964     }
1965     // assume(!(a || b)) -> assume(!a); assume(!b);
1966     if (match(IIOperand, m_Not(m_LogicalOr(m_Value(A), m_Value(B))))) {
1967       Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic,
1968                          Builder.CreateNot(A), OpBundles, II->getName());
1969       Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic,
1970                          Builder.CreateNot(B), II->getName());
1971       return eraseInstFromFunction(*II);
1972     }
1973 
1974     // assume( (load addr) != null ) -> add 'nonnull' metadata to load
1975     // (if assume is valid at the load)
1976     CmpInst::Predicate Pred;
1977     Instruction *LHS;
1978     if (match(IIOperand, m_ICmp(Pred, m_Instruction(LHS), m_Zero())) &&
1979         Pred == ICmpInst::ICMP_NE && LHS->getOpcode() == Instruction::Load &&
1980         LHS->getType()->isPointerTy() &&
1981         isValidAssumeForContext(II, LHS, &DT)) {
1982       MDNode *MD = MDNode::get(II->getContext(), None);
1983       LHS->setMetadata(LLVMContext::MD_nonnull, MD);
1984       return RemoveConditionFromAssume(II);
1985 
1986       // TODO: apply nonnull return attributes to calls and invokes
1987       // TODO: apply range metadata for range check patterns?
1988     }
1989 
1990     // Convert nonnull assume like:
1991     // %A = icmp ne i32* %PTR, null
1992     // call void @llvm.assume(i1 %A)
1993     // into
1994     // call void @llvm.assume(i1 true) [ "nonnull"(i32* %PTR) ]
1995     if (EnableKnowledgeRetention &&
1996         match(IIOperand, m_Cmp(Pred, m_Value(A), m_Zero())) &&
1997         Pred == CmpInst::ICMP_NE && A->getType()->isPointerTy()) {
1998       if (auto *Replacement = buildAssumeFromKnowledge(
1999               {RetainedKnowledge{Attribute::NonNull, 0, A}}, Next, &AC, &DT)) {
2000 
2001         Replacement->insertBefore(Next);
2002         AC.registerAssumption(Replacement);
2003         return RemoveConditionFromAssume(II);
2004       }
2005     }
2006 
2007     // Convert alignment assume like:
2008     // %B = ptrtoint i32* %A to i64
2009     // %C = and i64 %B, Constant
2010     // %D = icmp eq i64 %C, 0
2011     // call void @llvm.assume(i1 %D)
2012     // into
2013     // call void @llvm.assume(i1 true) [ "align"(i32* [[A]], i64  Constant + 1)]
2014     uint64_t AlignMask;
2015     if (EnableKnowledgeRetention &&
2016         match(IIOperand,
2017               m_Cmp(Pred, m_And(m_Value(A), m_ConstantInt(AlignMask)),
2018                     m_Zero())) &&
2019         Pred == CmpInst::ICMP_EQ) {
2020       if (isPowerOf2_64(AlignMask + 1)) {
2021         uint64_t Offset = 0;
2022         match(A, m_Add(m_Value(A), m_ConstantInt(Offset)));
2023         if (match(A, m_PtrToInt(m_Value(A)))) {
2024           /// Note: this doesn't preserve the offset information but merges
2025           /// offset and alignment.
2026           /// TODO: we can generate a GEP instead of merging the alignment with
2027           /// the offset.
2028           RetainedKnowledge RK{Attribute::Alignment,
2029                                (unsigned)MinAlign(Offset, AlignMask + 1), A};
2030           if (auto *Replacement =
2031                   buildAssumeFromKnowledge(RK, Next, &AC, &DT)) {
2032 
2033             Replacement->insertAfter(II);
2034             AC.registerAssumption(Replacement);
2035           }
2036           return RemoveConditionFromAssume(II);
2037         }
2038       }
2039     }
2040 
2041     /// Canonicalize Knowledge in operand bundles.
2042     if (EnableKnowledgeRetention && II->hasOperandBundles()) {
2043       for (unsigned Idx = 0; Idx < II->getNumOperandBundles(); Idx++) {
2044         auto &BOI = II->bundle_op_info_begin()[Idx];
2045         RetainedKnowledge RK =
2046           llvm::getKnowledgeFromBundle(cast<AssumeInst>(*II), BOI);
2047         if (BOI.End - BOI.Begin > 2)
2048           continue; // Prevent reducing knowledge in an align with offset since
2049                     // extracting a RetainedKnowledge form them looses offset
2050                     // information
2051         RetainedKnowledge CanonRK =
2052           llvm::simplifyRetainedKnowledge(cast<AssumeInst>(II), RK,
2053                                           &getAssumptionCache(),
2054                                           &getDominatorTree());
2055         if (CanonRK == RK)
2056           continue;
2057         if (!CanonRK) {
2058           if (BOI.End - BOI.Begin > 0) {
2059             Worklist.pushValue(II->op_begin()[BOI.Begin]);
2060             Value::dropDroppableUse(II->op_begin()[BOI.Begin]);
2061           }
2062           continue;
2063         }
2064         assert(RK.AttrKind == CanonRK.AttrKind);
2065         if (BOI.End - BOI.Begin > 0)
2066           II->op_begin()[BOI.Begin].set(CanonRK.WasOn);
2067         if (BOI.End - BOI.Begin > 1)
2068           II->op_begin()[BOI.Begin + 1].set(ConstantInt::get(
2069               Type::getInt64Ty(II->getContext()), CanonRK.ArgValue));
2070         if (RK.WasOn)
2071           Worklist.pushValue(RK.WasOn);
2072         return II;
2073       }
2074     }
2075 
2076     // If there is a dominating assume with the same condition as this one,
2077     // then this one is redundant, and should be removed.
2078     KnownBits Known(1);
2079     computeKnownBits(IIOperand, Known, 0, II);
2080     if (Known.isAllOnes() && isAssumeWithEmptyBundle(cast<AssumeInst>(*II)))
2081       return eraseInstFromFunction(*II);
2082 
2083     // Update the cache of affected values for this assumption (we might be
2084     // here because we just simplified the condition).
2085     AC.updateAffectedValues(cast<AssumeInst>(II));
2086     break;
2087   }
2088   case Intrinsic::experimental_guard: {
2089     // Is this guard followed by another guard?  We scan forward over a small
2090     // fixed window of instructions to handle common cases with conditions
2091     // computed between guards.
2092     Instruction *NextInst = II->getNextNonDebugInstruction();
2093     for (unsigned i = 0; i < GuardWideningWindow; i++) {
2094       // Note: Using context-free form to avoid compile time blow up
2095       if (!isSafeToSpeculativelyExecute(NextInst))
2096         break;
2097       NextInst = NextInst->getNextNonDebugInstruction();
2098     }
2099     Value *NextCond = nullptr;
2100     if (match(NextInst,
2101               m_Intrinsic<Intrinsic::experimental_guard>(m_Value(NextCond)))) {
2102       Value *CurrCond = II->getArgOperand(0);
2103 
2104       // Remove a guard that it is immediately preceded by an identical guard.
2105       // Otherwise canonicalize guard(a); guard(b) -> guard(a & b).
2106       if (CurrCond != NextCond) {
2107         Instruction *MoveI = II->getNextNonDebugInstruction();
2108         while (MoveI != NextInst) {
2109           auto *Temp = MoveI;
2110           MoveI = MoveI->getNextNonDebugInstruction();
2111           Temp->moveBefore(II);
2112         }
2113         replaceOperand(*II, 0, Builder.CreateAnd(CurrCond, NextCond));
2114       }
2115       eraseInstFromFunction(*NextInst);
2116       return II;
2117     }
2118     break;
2119   }
2120   case Intrinsic::experimental_vector_insert: {
2121     Value *Vec = II->getArgOperand(0);
2122     Value *SubVec = II->getArgOperand(1);
2123     Value *Idx = II->getArgOperand(2);
2124     auto *DstTy = dyn_cast<FixedVectorType>(II->getType());
2125     auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType());
2126     auto *SubVecTy = dyn_cast<FixedVectorType>(SubVec->getType());
2127 
2128     // Only canonicalize if the destination vector, Vec, and SubVec are all
2129     // fixed vectors.
2130     if (DstTy && VecTy && SubVecTy) {
2131       unsigned DstNumElts = DstTy->getNumElements();
2132       unsigned VecNumElts = VecTy->getNumElements();
2133       unsigned SubVecNumElts = SubVecTy->getNumElements();
2134       unsigned IdxN = cast<ConstantInt>(Idx)->getZExtValue();
2135 
2136       // An insert that entirely overwrites Vec with SubVec is a nop.
2137       if (VecNumElts == SubVecNumElts)
2138         return replaceInstUsesWith(CI, SubVec);
2139 
2140       // Widen SubVec into a vector of the same width as Vec, since
2141       // shufflevector requires the two input vectors to be the same width.
2142       // Elements beyond the bounds of SubVec within the widened vector are
2143       // undefined.
2144       SmallVector<int, 8> WidenMask;
2145       unsigned i;
2146       for (i = 0; i != SubVecNumElts; ++i)
2147         WidenMask.push_back(i);
2148       for (; i != VecNumElts; ++i)
2149         WidenMask.push_back(UndefMaskElem);
2150 
2151       Value *WidenShuffle = Builder.CreateShuffleVector(SubVec, WidenMask);
2152 
2153       SmallVector<int, 8> Mask;
2154       for (unsigned i = 0; i != IdxN; ++i)
2155         Mask.push_back(i);
2156       for (unsigned i = DstNumElts; i != DstNumElts + SubVecNumElts; ++i)
2157         Mask.push_back(i);
2158       for (unsigned i = IdxN + SubVecNumElts; i != DstNumElts; ++i)
2159         Mask.push_back(i);
2160 
2161       Value *Shuffle = Builder.CreateShuffleVector(Vec, WidenShuffle, Mask);
2162       return replaceInstUsesWith(CI, Shuffle);
2163     }
2164     break;
2165   }
2166   case Intrinsic::experimental_vector_extract: {
2167     Value *Vec = II->getArgOperand(0);
2168     Value *Idx = II->getArgOperand(1);
2169 
2170     auto *DstTy = dyn_cast<FixedVectorType>(II->getType());
2171     auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType());
2172 
2173     // Only canonicalize if the the destination vector and Vec are fixed
2174     // vectors.
2175     if (DstTy && VecTy) {
2176       unsigned DstNumElts = DstTy->getNumElements();
2177       unsigned VecNumElts = VecTy->getNumElements();
2178       unsigned IdxN = cast<ConstantInt>(Idx)->getZExtValue();
2179 
2180       // Extracting the entirety of Vec is a nop.
2181       if (VecNumElts == DstNumElts) {
2182         replaceInstUsesWith(CI, Vec);
2183         return eraseInstFromFunction(CI);
2184       }
2185 
2186       SmallVector<int, 8> Mask;
2187       for (unsigned i = 0; i != DstNumElts; ++i)
2188         Mask.push_back(IdxN + i);
2189 
2190       Value *Shuffle = Builder.CreateShuffleVector(Vec, Mask);
2191       return replaceInstUsesWith(CI, Shuffle);
2192     }
2193     break;
2194   }
2195   case Intrinsic::experimental_vector_reverse: {
2196     Value *BO0, *BO1, *X, *Y;
2197     Value *Vec = II->getArgOperand(0);
2198     if (match(Vec, m_OneUse(m_BinOp(m_Value(BO0), m_Value(BO1))))) {
2199       auto *OldBinOp = cast<BinaryOperator>(Vec);
2200       if (match(BO0, m_Intrinsic<Intrinsic::experimental_vector_reverse>(
2201                          m_Value(X)))) {
2202         // rev(binop rev(X), rev(Y)) --> binop X, Y
2203         if (match(BO1, m_Intrinsic<Intrinsic::experimental_vector_reverse>(
2204                            m_Value(Y))))
2205           return replaceInstUsesWith(CI,
2206                                      BinaryOperator::CreateWithCopiedFlags(
2207                                          OldBinOp->getOpcode(), X, Y, OldBinOp,
2208                                          OldBinOp->getName(), II));
2209         // rev(binop rev(X), BO1Splat) --> binop X, BO1Splat
2210         if (isSplatValue(BO1))
2211           return replaceInstUsesWith(CI,
2212                                      BinaryOperator::CreateWithCopiedFlags(
2213                                          OldBinOp->getOpcode(), X, BO1,
2214                                          OldBinOp, OldBinOp->getName(), II));
2215       }
2216       // rev(binop BO0Splat, rev(Y)) --> binop BO0Splat, Y
2217       if (match(BO1, m_Intrinsic<Intrinsic::experimental_vector_reverse>(
2218                          m_Value(Y))) &&
2219           isSplatValue(BO0))
2220         return replaceInstUsesWith(CI, BinaryOperator::CreateWithCopiedFlags(
2221                                            OldBinOp->getOpcode(), BO0, Y,
2222                                            OldBinOp, OldBinOp->getName(), II));
2223     }
2224     // rev(unop rev(X)) --> unop X
2225     if (match(Vec, m_OneUse(m_UnOp(
2226                        m_Intrinsic<Intrinsic::experimental_vector_reverse>(
2227                            m_Value(X)))))) {
2228       auto *OldUnOp = cast<UnaryOperator>(Vec);
2229       auto *NewUnOp = UnaryOperator::CreateWithCopiedFlags(
2230           OldUnOp->getOpcode(), X, OldUnOp, OldUnOp->getName(), II);
2231       return replaceInstUsesWith(CI, NewUnOp);
2232     }
2233     break;
2234   }
2235   case Intrinsic::vector_reduce_or:
2236   case Intrinsic::vector_reduce_and: {
2237     // Canonicalize logical or/and reductions:
2238     // Or reduction for i1 is represented as:
2239     // %val = bitcast <ReduxWidth x i1> to iReduxWidth
2240     // %res = cmp ne iReduxWidth %val, 0
2241     // And reduction for i1 is represented as:
2242     // %val = bitcast <ReduxWidth x i1> to iReduxWidth
2243     // %res = cmp eq iReduxWidth %val, 11111
2244     Value *Arg = II->getArgOperand(0);
2245     Value *Vect;
2246     if (match(Arg, m_ZExtOrSExtOrSelf(m_Value(Vect)))) {
2247       if (auto *FTy = dyn_cast<FixedVectorType>(Vect->getType()))
2248         if (FTy->getElementType() == Builder.getInt1Ty()) {
2249           Value *Res = Builder.CreateBitCast(
2250               Vect, Builder.getIntNTy(FTy->getNumElements()));
2251           if (IID == Intrinsic::vector_reduce_and) {
2252             Res = Builder.CreateICmpEQ(
2253                 Res, ConstantInt::getAllOnesValue(Res->getType()));
2254           } else {
2255             assert(IID == Intrinsic::vector_reduce_or &&
2256                    "Expected or reduction.");
2257             Res = Builder.CreateIsNotNull(Res);
2258           }
2259           if (Arg != Vect)
2260             Res = Builder.CreateCast(cast<CastInst>(Arg)->getOpcode(), Res,
2261                                      II->getType());
2262           return replaceInstUsesWith(CI, Res);
2263         }
2264     }
2265     LLVM_FALLTHROUGH;
2266   }
2267   case Intrinsic::vector_reduce_add: {
2268     if (IID == Intrinsic::vector_reduce_add) {
2269       // Convert vector_reduce_add(ZExt(<n x i1>)) to
2270       // ZExtOrTrunc(ctpop(bitcast <n x i1> to in)).
2271       // Convert vector_reduce_add(SExt(<n x i1>)) to
2272       // -ZExtOrTrunc(ctpop(bitcast <n x i1> to in)).
2273       // Convert vector_reduce_add(<n x i1>) to
2274       // Trunc(ctpop(bitcast <n x i1> to in)).
2275       Value *Arg = II->getArgOperand(0);
2276       Value *Vect;
2277       if (match(Arg, m_ZExtOrSExtOrSelf(m_Value(Vect)))) {
2278         if (auto *FTy = dyn_cast<FixedVectorType>(Vect->getType()))
2279           if (FTy->getElementType() == Builder.getInt1Ty()) {
2280             Value *V = Builder.CreateBitCast(
2281                 Vect, Builder.getIntNTy(FTy->getNumElements()));
2282             Value *Res = Builder.CreateUnaryIntrinsic(Intrinsic::ctpop, V);
2283             if (Res->getType() != II->getType())
2284               Res = Builder.CreateZExtOrTrunc(Res, II->getType());
2285             if (Arg != Vect &&
2286                 cast<Instruction>(Arg)->getOpcode() == Instruction::SExt)
2287               Res = Builder.CreateNeg(Res);
2288             return replaceInstUsesWith(CI, Res);
2289           }
2290       }
2291     }
2292     LLVM_FALLTHROUGH;
2293   }
2294   case Intrinsic::vector_reduce_xor: {
2295     if (IID == Intrinsic::vector_reduce_xor) {
2296       // Exclusive disjunction reduction over the vector with
2297       // (potentially-extended) i1 element type is actually a
2298       // (potentially-extended) arithmetic `add` reduction over the original
2299       // non-extended value:
2300       //   vector_reduce_xor(?ext(<n x i1>))
2301       //     -->
2302       //   ?ext(vector_reduce_add(<n x i1>))
2303       Value *Arg = II->getArgOperand(0);
2304       Value *Vect;
2305       if (match(Arg, m_ZExtOrSExtOrSelf(m_Value(Vect)))) {
2306         if (auto *FTy = dyn_cast<FixedVectorType>(Vect->getType()))
2307           if (FTy->getElementType() == Builder.getInt1Ty()) {
2308             Value *Res = Builder.CreateAddReduce(Vect);
2309             if (Arg != Vect)
2310               Res = Builder.CreateCast(cast<CastInst>(Arg)->getOpcode(), Res,
2311                                        II->getType());
2312             return replaceInstUsesWith(CI, Res);
2313           }
2314       }
2315     }
2316     LLVM_FALLTHROUGH;
2317   }
2318   case Intrinsic::vector_reduce_mul: {
2319     if (IID == Intrinsic::vector_reduce_mul) {
2320       // Multiplicative reduction over the vector with (potentially-extended)
2321       // i1 element type is actually a (potentially zero-extended)
2322       // logical `and` reduction over the original non-extended value:
2323       //   vector_reduce_mul(?ext(<n x i1>))
2324       //     -->
2325       //   zext(vector_reduce_and(<n x i1>))
2326       Value *Arg = II->getArgOperand(0);
2327       Value *Vect;
2328       if (match(Arg, m_ZExtOrSExtOrSelf(m_Value(Vect)))) {
2329         if (auto *FTy = dyn_cast<FixedVectorType>(Vect->getType()))
2330           if (FTy->getElementType() == Builder.getInt1Ty()) {
2331             Value *Res = Builder.CreateAndReduce(Vect);
2332             if (Res->getType() != II->getType())
2333               Res = Builder.CreateZExt(Res, II->getType());
2334             return replaceInstUsesWith(CI, Res);
2335           }
2336       }
2337     }
2338     LLVM_FALLTHROUGH;
2339   }
2340   case Intrinsic::vector_reduce_umin:
2341   case Intrinsic::vector_reduce_umax: {
2342     if (IID == Intrinsic::vector_reduce_umin ||
2343         IID == Intrinsic::vector_reduce_umax) {
2344       // UMin/UMax reduction over the vector with (potentially-extended)
2345       // i1 element type is actually a (potentially-extended)
2346       // logical `and`/`or` reduction over the original non-extended value:
2347       //   vector_reduce_u{min,max}(?ext(<n x i1>))
2348       //     -->
2349       //   ?ext(vector_reduce_{and,or}(<n x i1>))
2350       Value *Arg = II->getArgOperand(0);
2351       Value *Vect;
2352       if (match(Arg, m_ZExtOrSExtOrSelf(m_Value(Vect)))) {
2353         if (auto *FTy = dyn_cast<FixedVectorType>(Vect->getType()))
2354           if (FTy->getElementType() == Builder.getInt1Ty()) {
2355             Value *Res = IID == Intrinsic::vector_reduce_umin
2356                              ? Builder.CreateAndReduce(Vect)
2357                              : Builder.CreateOrReduce(Vect);
2358             if (Arg != Vect)
2359               Res = Builder.CreateCast(cast<CastInst>(Arg)->getOpcode(), Res,
2360                                        II->getType());
2361             return replaceInstUsesWith(CI, Res);
2362           }
2363       }
2364     }
2365     LLVM_FALLTHROUGH;
2366   }
2367   case Intrinsic::vector_reduce_smin:
2368   case Intrinsic::vector_reduce_smax: {
2369     if (IID == Intrinsic::vector_reduce_smin ||
2370         IID == Intrinsic::vector_reduce_smax) {
2371       // SMin/SMax reduction over the vector with (potentially-extended)
2372       // i1 element type is actually a (potentially-extended)
2373       // logical `and`/`or` reduction over the original non-extended value:
2374       //   vector_reduce_s{min,max}(<n x i1>)
2375       //     -->
2376       //   vector_reduce_{or,and}(<n x i1>)
2377       // and
2378       //   vector_reduce_s{min,max}(sext(<n x i1>))
2379       //     -->
2380       //   sext(vector_reduce_{or,and}(<n x i1>))
2381       // and
2382       //   vector_reduce_s{min,max}(zext(<n x i1>))
2383       //     -->
2384       //   zext(vector_reduce_{and,or}(<n x i1>))
2385       Value *Arg = II->getArgOperand(0);
2386       Value *Vect;
2387       if (match(Arg, m_ZExtOrSExtOrSelf(m_Value(Vect)))) {
2388         if (auto *FTy = dyn_cast<FixedVectorType>(Vect->getType()))
2389           if (FTy->getElementType() == Builder.getInt1Ty()) {
2390             Instruction::CastOps ExtOpc = Instruction::CastOps::CastOpsEnd;
2391             if (Arg != Vect)
2392               ExtOpc = cast<CastInst>(Arg)->getOpcode();
2393             Value *Res = ((IID == Intrinsic::vector_reduce_smin) ==
2394                           (ExtOpc == Instruction::CastOps::ZExt))
2395                              ? Builder.CreateAndReduce(Vect)
2396                              : Builder.CreateOrReduce(Vect);
2397             if (Arg != Vect)
2398               Res = Builder.CreateCast(ExtOpc, Res, II->getType());
2399             return replaceInstUsesWith(CI, Res);
2400           }
2401       }
2402     }
2403     LLVM_FALLTHROUGH;
2404   }
2405   case Intrinsic::vector_reduce_fmax:
2406   case Intrinsic::vector_reduce_fmin:
2407   case Intrinsic::vector_reduce_fadd:
2408   case Intrinsic::vector_reduce_fmul: {
2409     bool CanBeReassociated = (IID != Intrinsic::vector_reduce_fadd &&
2410                               IID != Intrinsic::vector_reduce_fmul) ||
2411                              II->hasAllowReassoc();
2412     const unsigned ArgIdx = (IID == Intrinsic::vector_reduce_fadd ||
2413                              IID == Intrinsic::vector_reduce_fmul)
2414                                 ? 1
2415                                 : 0;
2416     Value *Arg = II->getArgOperand(ArgIdx);
2417     Value *V;
2418     ArrayRef<int> Mask;
2419     if (!isa<FixedVectorType>(Arg->getType()) || !CanBeReassociated ||
2420         !match(Arg, m_Shuffle(m_Value(V), m_Undef(), m_Mask(Mask))) ||
2421         !cast<ShuffleVectorInst>(Arg)->isSingleSource())
2422       break;
2423     int Sz = Mask.size();
2424     SmallBitVector UsedIndices(Sz);
2425     for (int Idx : Mask) {
2426       if (Idx == UndefMaskElem || UsedIndices.test(Idx))
2427         break;
2428       UsedIndices.set(Idx);
2429     }
2430     // Can remove shuffle iff just shuffled elements, no repeats, undefs, or
2431     // other changes.
2432     if (UsedIndices.all()) {
2433       replaceUse(II->getOperandUse(ArgIdx), V);
2434       return nullptr;
2435     }
2436     break;
2437   }
2438   default: {
2439     // Handle target specific intrinsics
2440     Optional<Instruction *> V = targetInstCombineIntrinsic(*II);
2441     if (V.hasValue())
2442       return V.getValue();
2443     break;
2444   }
2445   }
2446   // Some intrinsics (like experimental_gc_statepoint) can be used in invoke
2447   // context, so it is handled in visitCallBase and we should trigger it.
2448   return visitCallBase(*II);
2449 }
2450 
2451 // Fence instruction simplification
2452 Instruction *InstCombinerImpl::visitFenceInst(FenceInst &FI) {
2453   // Remove identical consecutive fences.
2454   Instruction *Next = FI.getNextNonDebugInstruction();
2455   if (auto *NFI = dyn_cast<FenceInst>(Next))
2456     if (FI.isIdenticalTo(NFI))
2457       return eraseInstFromFunction(FI);
2458   return nullptr;
2459 }
2460 
2461 // InvokeInst simplification
2462 Instruction *InstCombinerImpl::visitInvokeInst(InvokeInst &II) {
2463   return visitCallBase(II);
2464 }
2465 
2466 // CallBrInst simplification
2467 Instruction *InstCombinerImpl::visitCallBrInst(CallBrInst &CBI) {
2468   return visitCallBase(CBI);
2469 }
2470 
2471 /// If this cast does not affect the value passed through the varargs area, we
2472 /// can eliminate the use of the cast.
2473 static bool isSafeToEliminateVarargsCast(const CallBase &Call,
2474                                          const DataLayout &DL,
2475                                          const CastInst *const CI,
2476                                          const int ix) {
2477   if (!CI->isLosslessCast())
2478     return false;
2479 
2480   // If this is a GC intrinsic, avoid munging types.  We need types for
2481   // statepoint reconstruction in SelectionDAG.
2482   // TODO: This is probably something which should be expanded to all
2483   // intrinsics since the entire point of intrinsics is that
2484   // they are understandable by the optimizer.
2485   if (isa<GCStatepointInst>(Call) || isa<GCRelocateInst>(Call) ||
2486       isa<GCResultInst>(Call))
2487     return false;
2488 
2489   // Opaque pointers are compatible with any byval types.
2490   PointerType *SrcTy = cast<PointerType>(CI->getOperand(0)->getType());
2491   if (SrcTy->isOpaque())
2492     return true;
2493 
2494   // The size of ByVal or InAlloca arguments is derived from the type, so we
2495   // can't change to a type with a different size.  If the size were
2496   // passed explicitly we could avoid this check.
2497   if (!Call.isPassPointeeByValueArgument(ix))
2498     return true;
2499 
2500   // The transform currently only handles type replacement for byval, not other
2501   // type-carrying attributes.
2502   if (!Call.isByValArgument(ix))
2503     return false;
2504 
2505   Type *SrcElemTy = SrcTy->getElementType();
2506   Type *DstElemTy = Call.getParamByValType(ix);
2507   if (!SrcElemTy->isSized() || !DstElemTy->isSized())
2508     return false;
2509   if (DL.getTypeAllocSize(SrcElemTy) != DL.getTypeAllocSize(DstElemTy))
2510     return false;
2511   return true;
2512 }
2513 
2514 Instruction *InstCombinerImpl::tryOptimizeCall(CallInst *CI) {
2515   if (!CI->getCalledFunction()) return nullptr;
2516 
2517   // Skip optimizing notail and musttail calls so
2518   // LibCallSimplifier::optimizeCall doesn't have to preserve those invariants.
2519   // LibCallSimplifier::optimizeCall should try to preseve tail calls though.
2520   if (CI->isMustTailCall() || CI->isNoTailCall())
2521     return nullptr;
2522 
2523   auto InstCombineRAUW = [this](Instruction *From, Value *With) {
2524     replaceInstUsesWith(*From, With);
2525   };
2526   auto InstCombineErase = [this](Instruction *I) {
2527     eraseInstFromFunction(*I);
2528   };
2529   LibCallSimplifier Simplifier(DL, &TLI, ORE, BFI, PSI, InstCombineRAUW,
2530                                InstCombineErase);
2531   if (Value *With = Simplifier.optimizeCall(CI, Builder)) {
2532     ++NumSimplified;
2533     return CI->use_empty() ? CI : replaceInstUsesWith(*CI, With);
2534   }
2535 
2536   return nullptr;
2537 }
2538 
2539 static IntrinsicInst *findInitTrampolineFromAlloca(Value *TrampMem) {
2540   // Strip off at most one level of pointer casts, looking for an alloca.  This
2541   // is good enough in practice and simpler than handling any number of casts.
2542   Value *Underlying = TrampMem->stripPointerCasts();
2543   if (Underlying != TrampMem &&
2544       (!Underlying->hasOneUse() || Underlying->user_back() != TrampMem))
2545     return nullptr;
2546   if (!isa<AllocaInst>(Underlying))
2547     return nullptr;
2548 
2549   IntrinsicInst *InitTrampoline = nullptr;
2550   for (User *U : TrampMem->users()) {
2551     IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
2552     if (!II)
2553       return nullptr;
2554     if (II->getIntrinsicID() == Intrinsic::init_trampoline) {
2555       if (InitTrampoline)
2556         // More than one init_trampoline writes to this value.  Give up.
2557         return nullptr;
2558       InitTrampoline = II;
2559       continue;
2560     }
2561     if (II->getIntrinsicID() == Intrinsic::adjust_trampoline)
2562       // Allow any number of calls to adjust.trampoline.
2563       continue;
2564     return nullptr;
2565   }
2566 
2567   // No call to init.trampoline found.
2568   if (!InitTrampoline)
2569     return nullptr;
2570 
2571   // Check that the alloca is being used in the expected way.
2572   if (InitTrampoline->getOperand(0) != TrampMem)
2573     return nullptr;
2574 
2575   return InitTrampoline;
2576 }
2577 
2578 static IntrinsicInst *findInitTrampolineFromBB(IntrinsicInst *AdjustTramp,
2579                                                Value *TrampMem) {
2580   // Visit all the previous instructions in the basic block, and try to find a
2581   // init.trampoline which has a direct path to the adjust.trampoline.
2582   for (BasicBlock::iterator I = AdjustTramp->getIterator(),
2583                             E = AdjustTramp->getParent()->begin();
2584        I != E;) {
2585     Instruction *Inst = &*--I;
2586     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2587       if (II->getIntrinsicID() == Intrinsic::init_trampoline &&
2588           II->getOperand(0) == TrampMem)
2589         return II;
2590     if (Inst->mayWriteToMemory())
2591       return nullptr;
2592   }
2593   return nullptr;
2594 }
2595 
2596 // Given a call to llvm.adjust.trampoline, find and return the corresponding
2597 // call to llvm.init.trampoline if the call to the trampoline can be optimized
2598 // to a direct call to a function.  Otherwise return NULL.
2599 static IntrinsicInst *findInitTrampoline(Value *Callee) {
2600   Callee = Callee->stripPointerCasts();
2601   IntrinsicInst *AdjustTramp = dyn_cast<IntrinsicInst>(Callee);
2602   if (!AdjustTramp ||
2603       AdjustTramp->getIntrinsicID() != Intrinsic::adjust_trampoline)
2604     return nullptr;
2605 
2606   Value *TrampMem = AdjustTramp->getOperand(0);
2607 
2608   if (IntrinsicInst *IT = findInitTrampolineFromAlloca(TrampMem))
2609     return IT;
2610   if (IntrinsicInst *IT = findInitTrampolineFromBB(AdjustTramp, TrampMem))
2611     return IT;
2612   return nullptr;
2613 }
2614 
2615 void InstCombinerImpl::annotateAnyAllocSite(CallBase &Call, const TargetLibraryInfo *TLI) {
2616   // Note: We only handle cases which can't be driven from generic attributes
2617   // here.  So, for example, nonnull and noalias (which are common properties
2618   // of some allocation functions) are expected to be handled via annotation
2619   // of the respective allocator declaration with generic attributes.
2620 
2621   uint64_t Size;
2622   ObjectSizeOpts Opts;
2623   if (getObjectSize(&Call, Size, DL, TLI, Opts) && Size > 0) {
2624     // TODO: We really should just emit deref_or_null here and then
2625     // let the generic inference code combine that with nonnull.
2626     if (Call.hasRetAttr(Attribute::NonNull))
2627       Call.addRetAttr(Attribute::getWithDereferenceableBytes(
2628           Call.getContext(), Size));
2629     else
2630       Call.addRetAttr(Attribute::getWithDereferenceableOrNullBytes(
2631           Call.getContext(), Size));
2632   }
2633 
2634   // Add alignment attribute if alignment is a power of two constant.
2635   Value *Alignment = getAllocAlignment(&Call, TLI);
2636   if (!Alignment)
2637     return;
2638 
2639   ConstantInt *AlignOpC = dyn_cast<ConstantInt>(Alignment);
2640   if (AlignOpC && AlignOpC->getValue().ult(llvm::Value::MaximumAlignment)) {
2641     uint64_t AlignmentVal = AlignOpC->getZExtValue();
2642     if (llvm::isPowerOf2_64(AlignmentVal)) {
2643       Call.removeRetAttr(Attribute::Alignment);
2644       Call.addRetAttr(Attribute::getWithAlignment(Call.getContext(),
2645                                                   Align(AlignmentVal)));
2646     }
2647   }
2648 }
2649 
2650 /// Improvements for call, callbr and invoke instructions.
2651 Instruction *InstCombinerImpl::visitCallBase(CallBase &Call) {
2652   if (isAllocationFn(&Call, &TLI))
2653     annotateAnyAllocSite(Call, &TLI);
2654 
2655   bool Changed = false;
2656 
2657   // Mark any parameters that are known to be non-null with the nonnull
2658   // attribute.  This is helpful for inlining calls to functions with null
2659   // checks on their arguments.
2660   SmallVector<unsigned, 4> ArgNos;
2661   unsigned ArgNo = 0;
2662 
2663   for (Value *V : Call.args()) {
2664     if (V->getType()->isPointerTy() &&
2665         !Call.paramHasAttr(ArgNo, Attribute::NonNull) &&
2666         isKnownNonZero(V, DL, 0, &AC, &Call, &DT))
2667       ArgNos.push_back(ArgNo);
2668     ArgNo++;
2669   }
2670 
2671   assert(ArgNo == Call.arg_size() && "Call arguments not processed correctly.");
2672 
2673   if (!ArgNos.empty()) {
2674     AttributeList AS = Call.getAttributes();
2675     LLVMContext &Ctx = Call.getContext();
2676     AS = AS.addParamAttribute(Ctx, ArgNos,
2677                               Attribute::get(Ctx, Attribute::NonNull));
2678     Call.setAttributes(AS);
2679     Changed = true;
2680   }
2681 
2682   // If the callee is a pointer to a function, attempt to move any casts to the
2683   // arguments of the call/callbr/invoke.
2684   Value *Callee = Call.getCalledOperand();
2685   if (!isa<Function>(Callee) && transformConstExprCastCall(Call))
2686     return nullptr;
2687 
2688   if (Function *CalleeF = dyn_cast<Function>(Callee)) {
2689     // Remove the convergent attr on calls when the callee is not convergent.
2690     if (Call.isConvergent() && !CalleeF->isConvergent() &&
2691         !CalleeF->isIntrinsic()) {
2692       LLVM_DEBUG(dbgs() << "Removing convergent attr from instr " << Call
2693                         << "\n");
2694       Call.setNotConvergent();
2695       return &Call;
2696     }
2697 
2698     // If the call and callee calling conventions don't match, and neither one
2699     // of the calling conventions is compatible with C calling convention
2700     // this call must be unreachable, as the call is undefined.
2701     if ((CalleeF->getCallingConv() != Call.getCallingConv() &&
2702          !(CalleeF->getCallingConv() == llvm::CallingConv::C &&
2703            TargetLibraryInfoImpl::isCallingConvCCompatible(&Call)) &&
2704          !(Call.getCallingConv() == llvm::CallingConv::C &&
2705            TargetLibraryInfoImpl::isCallingConvCCompatible(CalleeF))) &&
2706         // Only do this for calls to a function with a body.  A prototype may
2707         // not actually end up matching the implementation's calling conv for a
2708         // variety of reasons (e.g. it may be written in assembly).
2709         !CalleeF->isDeclaration()) {
2710       Instruction *OldCall = &Call;
2711       CreateNonTerminatorUnreachable(OldCall);
2712       // If OldCall does not return void then replaceInstUsesWith poison.
2713       // This allows ValueHandlers and custom metadata to adjust itself.
2714       if (!OldCall->getType()->isVoidTy())
2715         replaceInstUsesWith(*OldCall, PoisonValue::get(OldCall->getType()));
2716       if (isa<CallInst>(OldCall))
2717         return eraseInstFromFunction(*OldCall);
2718 
2719       // We cannot remove an invoke or a callbr, because it would change thexi
2720       // CFG, just change the callee to a null pointer.
2721       cast<CallBase>(OldCall)->setCalledFunction(
2722           CalleeF->getFunctionType(),
2723           Constant::getNullValue(CalleeF->getType()));
2724       return nullptr;
2725     }
2726   }
2727 
2728   // Calling a null function pointer is undefined if a null address isn't
2729   // dereferenceable.
2730   if ((isa<ConstantPointerNull>(Callee) &&
2731        !NullPointerIsDefined(Call.getFunction())) ||
2732       isa<UndefValue>(Callee)) {
2733     // If Call does not return void then replaceInstUsesWith poison.
2734     // This allows ValueHandlers and custom metadata to adjust itself.
2735     if (!Call.getType()->isVoidTy())
2736       replaceInstUsesWith(Call, PoisonValue::get(Call.getType()));
2737 
2738     if (Call.isTerminator()) {
2739       // Can't remove an invoke or callbr because we cannot change the CFG.
2740       return nullptr;
2741     }
2742 
2743     // This instruction is not reachable, just remove it.
2744     CreateNonTerminatorUnreachable(&Call);
2745     return eraseInstFromFunction(Call);
2746   }
2747 
2748   if (IntrinsicInst *II = findInitTrampoline(Callee))
2749     return transformCallThroughTrampoline(Call, *II);
2750 
2751   // TODO: Drop this transform once opaque pointer transition is done.
2752   FunctionType *FTy = Call.getFunctionType();
2753   if (FTy->isVarArg()) {
2754     int ix = FTy->getNumParams();
2755     // See if we can optimize any arguments passed through the varargs area of
2756     // the call.
2757     for (auto I = Call.arg_begin() + FTy->getNumParams(), E = Call.arg_end();
2758          I != E; ++I, ++ix) {
2759       CastInst *CI = dyn_cast<CastInst>(*I);
2760       if (CI && isSafeToEliminateVarargsCast(Call, DL, CI, ix)) {
2761         replaceUse(*I, CI->getOperand(0));
2762 
2763         // Update the byval type to match the pointer type.
2764         // Not necessary for opaque pointers.
2765         PointerType *NewTy = cast<PointerType>(CI->getOperand(0)->getType());
2766         if (!NewTy->isOpaque() && Call.isByValArgument(ix)) {
2767           Call.removeParamAttr(ix, Attribute::ByVal);
2768           Call.addParamAttr(
2769               ix, Attribute::getWithByValType(
2770                       Call.getContext(), NewTy->getElementType()));
2771         }
2772         Changed = true;
2773       }
2774     }
2775   }
2776 
2777   if (isa<InlineAsm>(Callee) && !Call.doesNotThrow()) {
2778     InlineAsm *IA = cast<InlineAsm>(Callee);
2779     if (!IA->canThrow()) {
2780       // Normal inline asm calls cannot throw - mark them
2781       // 'nounwind'.
2782       Call.setDoesNotThrow();
2783       Changed = true;
2784     }
2785   }
2786 
2787   // Try to optimize the call if possible, we require DataLayout for most of
2788   // this.  None of these calls are seen as possibly dead so go ahead and
2789   // delete the instruction now.
2790   if (CallInst *CI = dyn_cast<CallInst>(&Call)) {
2791     Instruction *I = tryOptimizeCall(CI);
2792     // If we changed something return the result, etc. Otherwise let
2793     // the fallthrough check.
2794     if (I) return eraseInstFromFunction(*I);
2795   }
2796 
2797   if (!Call.use_empty() && !Call.isMustTailCall())
2798     if (Value *ReturnedArg = Call.getReturnedArgOperand()) {
2799       Type *CallTy = Call.getType();
2800       Type *RetArgTy = ReturnedArg->getType();
2801       if (RetArgTy->canLosslesslyBitCastTo(CallTy))
2802         return replaceInstUsesWith(
2803             Call, Builder.CreateBitOrPointerCast(ReturnedArg, CallTy));
2804     }
2805 
2806   if (isAllocationFn(&Call, &TLI) &&
2807       isAllocRemovable(&cast<CallBase>(Call), &TLI))
2808     return visitAllocSite(Call);
2809 
2810   // Handle intrinsics which can be used in both call and invoke context.
2811   switch (Call.getIntrinsicID()) {
2812   case Intrinsic::experimental_gc_statepoint: {
2813     GCStatepointInst &GCSP = *cast<GCStatepointInst>(&Call);
2814     SmallPtrSet<Value *, 32> LiveGcValues;
2815     for (const GCRelocateInst *Reloc : GCSP.getGCRelocates()) {
2816       GCRelocateInst &GCR = *const_cast<GCRelocateInst *>(Reloc);
2817 
2818       // Remove the relocation if unused.
2819       if (GCR.use_empty()) {
2820         eraseInstFromFunction(GCR);
2821         continue;
2822       }
2823 
2824       Value *DerivedPtr = GCR.getDerivedPtr();
2825       Value *BasePtr = GCR.getBasePtr();
2826 
2827       // Undef is undef, even after relocation.
2828       if (isa<UndefValue>(DerivedPtr) || isa<UndefValue>(BasePtr)) {
2829         replaceInstUsesWith(GCR, UndefValue::get(GCR.getType()));
2830         eraseInstFromFunction(GCR);
2831         continue;
2832       }
2833 
2834       if (auto *PT = dyn_cast<PointerType>(GCR.getType())) {
2835         // The relocation of null will be null for most any collector.
2836         // TODO: provide a hook for this in GCStrategy.  There might be some
2837         // weird collector this property does not hold for.
2838         if (isa<ConstantPointerNull>(DerivedPtr)) {
2839           // Use null-pointer of gc_relocate's type to replace it.
2840           replaceInstUsesWith(GCR, ConstantPointerNull::get(PT));
2841           eraseInstFromFunction(GCR);
2842           continue;
2843         }
2844 
2845         // isKnownNonNull -> nonnull attribute
2846         if (!GCR.hasRetAttr(Attribute::NonNull) &&
2847             isKnownNonZero(DerivedPtr, DL, 0, &AC, &Call, &DT)) {
2848           GCR.addRetAttr(Attribute::NonNull);
2849           // We discovered new fact, re-check users.
2850           Worklist.pushUsersToWorkList(GCR);
2851         }
2852       }
2853 
2854       // If we have two copies of the same pointer in the statepoint argument
2855       // list, canonicalize to one.  This may let us common gc.relocates.
2856       if (GCR.getBasePtr() == GCR.getDerivedPtr() &&
2857           GCR.getBasePtrIndex() != GCR.getDerivedPtrIndex()) {
2858         auto *OpIntTy = GCR.getOperand(2)->getType();
2859         GCR.setOperand(2, ConstantInt::get(OpIntTy, GCR.getBasePtrIndex()));
2860       }
2861 
2862       // TODO: bitcast(relocate(p)) -> relocate(bitcast(p))
2863       // Canonicalize on the type from the uses to the defs
2864 
2865       // TODO: relocate((gep p, C, C2, ...)) -> gep(relocate(p), C, C2, ...)
2866       LiveGcValues.insert(BasePtr);
2867       LiveGcValues.insert(DerivedPtr);
2868     }
2869     Optional<OperandBundleUse> Bundle =
2870         GCSP.getOperandBundle(LLVMContext::OB_gc_live);
2871     unsigned NumOfGCLives = LiveGcValues.size();
2872     if (!Bundle.hasValue() || NumOfGCLives == Bundle->Inputs.size())
2873       break;
2874     // We can reduce the size of gc live bundle.
2875     DenseMap<Value *, unsigned> Val2Idx;
2876     std::vector<Value *> NewLiveGc;
2877     for (unsigned I = 0, E = Bundle->Inputs.size(); I < E; ++I) {
2878       Value *V = Bundle->Inputs[I];
2879       if (Val2Idx.count(V))
2880         continue;
2881       if (LiveGcValues.count(V)) {
2882         Val2Idx[V] = NewLiveGc.size();
2883         NewLiveGc.push_back(V);
2884       } else
2885         Val2Idx[V] = NumOfGCLives;
2886     }
2887     // Update all gc.relocates
2888     for (const GCRelocateInst *Reloc : GCSP.getGCRelocates()) {
2889       GCRelocateInst &GCR = *const_cast<GCRelocateInst *>(Reloc);
2890       Value *BasePtr = GCR.getBasePtr();
2891       assert(Val2Idx.count(BasePtr) && Val2Idx[BasePtr] != NumOfGCLives &&
2892              "Missed live gc for base pointer");
2893       auto *OpIntTy1 = GCR.getOperand(1)->getType();
2894       GCR.setOperand(1, ConstantInt::get(OpIntTy1, Val2Idx[BasePtr]));
2895       Value *DerivedPtr = GCR.getDerivedPtr();
2896       assert(Val2Idx.count(DerivedPtr) && Val2Idx[DerivedPtr] != NumOfGCLives &&
2897              "Missed live gc for derived pointer");
2898       auto *OpIntTy2 = GCR.getOperand(2)->getType();
2899       GCR.setOperand(2, ConstantInt::get(OpIntTy2, Val2Idx[DerivedPtr]));
2900     }
2901     // Create new statepoint instruction.
2902     OperandBundleDef NewBundle("gc-live", NewLiveGc);
2903     return CallBase::Create(&Call, NewBundle);
2904   }
2905   default: { break; }
2906   }
2907 
2908   return Changed ? &Call : nullptr;
2909 }
2910 
2911 /// If the callee is a constexpr cast of a function, attempt to move the cast to
2912 /// the arguments of the call/callbr/invoke.
2913 bool InstCombinerImpl::transformConstExprCastCall(CallBase &Call) {
2914   auto *Callee =
2915       dyn_cast<Function>(Call.getCalledOperand()->stripPointerCasts());
2916   if (!Callee)
2917     return false;
2918 
2919   // If this is a call to a thunk function, don't remove the cast. Thunks are
2920   // used to transparently forward all incoming parameters and outgoing return
2921   // values, so it's important to leave the cast in place.
2922   if (Callee->hasFnAttribute("thunk"))
2923     return false;
2924 
2925   // If this is a musttail call, the callee's prototype must match the caller's
2926   // prototype with the exception of pointee types. The code below doesn't
2927   // implement that, so we can't do this transform.
2928   // TODO: Do the transform if it only requires adding pointer casts.
2929   if (Call.isMustTailCall())
2930     return false;
2931 
2932   Instruction *Caller = &Call;
2933   const AttributeList &CallerPAL = Call.getAttributes();
2934 
2935   // Okay, this is a cast from a function to a different type.  Unless doing so
2936   // would cause a type conversion of one of our arguments, change this call to
2937   // be a direct call with arguments casted to the appropriate types.
2938   FunctionType *FT = Callee->getFunctionType();
2939   Type *OldRetTy = Caller->getType();
2940   Type *NewRetTy = FT->getReturnType();
2941 
2942   // Check to see if we are changing the return type...
2943   if (OldRetTy != NewRetTy) {
2944 
2945     if (NewRetTy->isStructTy())
2946       return false; // TODO: Handle multiple return values.
2947 
2948     if (!CastInst::isBitOrNoopPointerCastable(NewRetTy, OldRetTy, DL)) {
2949       if (Callee->isDeclaration())
2950         return false;   // Cannot transform this return value.
2951 
2952       if (!Caller->use_empty() &&
2953           // void -> non-void is handled specially
2954           !NewRetTy->isVoidTy())
2955         return false;   // Cannot transform this return value.
2956     }
2957 
2958     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
2959       AttrBuilder RAttrs(FT->getContext(), CallerPAL.getRetAttrs());
2960       if (RAttrs.overlaps(AttributeFuncs::typeIncompatible(NewRetTy)))
2961         return false;   // Attribute not compatible with transformed value.
2962     }
2963 
2964     // If the callbase is an invoke/callbr instruction, and the return value is
2965     // used by a PHI node in a successor, we cannot change the return type of
2966     // the call because there is no place to put the cast instruction (without
2967     // breaking the critical edge).  Bail out in this case.
2968     if (!Caller->use_empty()) {
2969       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
2970         for (User *U : II->users())
2971           if (PHINode *PN = dyn_cast<PHINode>(U))
2972             if (PN->getParent() == II->getNormalDest() ||
2973                 PN->getParent() == II->getUnwindDest())
2974               return false;
2975       // FIXME: Be conservative for callbr to avoid a quadratic search.
2976       if (isa<CallBrInst>(Caller))
2977         return false;
2978     }
2979   }
2980 
2981   unsigned NumActualArgs = Call.arg_size();
2982   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
2983 
2984   // Prevent us turning:
2985   // declare void @takes_i32_inalloca(i32* inalloca)
2986   //  call void bitcast (void (i32*)* @takes_i32_inalloca to void (i32)*)(i32 0)
2987   //
2988   // into:
2989   //  call void @takes_i32_inalloca(i32* null)
2990   //
2991   //  Similarly, avoid folding away bitcasts of byval calls.
2992   if (Callee->getAttributes().hasAttrSomewhere(Attribute::InAlloca) ||
2993       Callee->getAttributes().hasAttrSomewhere(Attribute::Preallocated) ||
2994       Callee->getAttributes().hasAttrSomewhere(Attribute::ByVal))
2995     return false;
2996 
2997   auto AI = Call.arg_begin();
2998   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
2999     Type *ParamTy = FT->getParamType(i);
3000     Type *ActTy = (*AI)->getType();
3001 
3002     if (!CastInst::isBitOrNoopPointerCastable(ActTy, ParamTy, DL))
3003       return false;   // Cannot transform this parameter value.
3004 
3005     if (AttrBuilder(FT->getContext(), CallerPAL.getParamAttrs(i))
3006             .overlaps(AttributeFuncs::typeIncompatible(ParamTy)))
3007       return false;   // Attribute not compatible with transformed value.
3008 
3009     if (Call.isInAllocaArgument(i))
3010       return false;   // Cannot transform to and from inalloca.
3011 
3012     if (CallerPAL.hasParamAttr(i, Attribute::SwiftError))
3013       return false;
3014 
3015     // If the parameter is passed as a byval argument, then we have to have a
3016     // sized type and the sized type has to have the same size as the old type.
3017     if (ParamTy != ActTy && CallerPAL.hasParamAttr(i, Attribute::ByVal)) {
3018       PointerType *ParamPTy = dyn_cast<PointerType>(ParamTy);
3019       if (!ParamPTy || !ParamPTy->getElementType()->isSized())
3020         return false;
3021 
3022       Type *CurElTy = Call.getParamByValType(i);
3023       if (DL.getTypeAllocSize(CurElTy) !=
3024           DL.getTypeAllocSize(ParamPTy->getElementType()))
3025         return false;
3026     }
3027   }
3028 
3029   if (Callee->isDeclaration()) {
3030     // Do not delete arguments unless we have a function body.
3031     if (FT->getNumParams() < NumActualArgs && !FT->isVarArg())
3032       return false;
3033 
3034     // If the callee is just a declaration, don't change the varargsness of the
3035     // call.  We don't want to introduce a varargs call where one doesn't
3036     // already exist.
3037     PointerType *APTy = cast<PointerType>(Call.getCalledOperand()->getType());
3038     if (FT->isVarArg()!=cast<FunctionType>(APTy->getElementType())->isVarArg())
3039       return false;
3040 
3041     // If both the callee and the cast type are varargs, we still have to make
3042     // sure the number of fixed parameters are the same or we have the same
3043     // ABI issues as if we introduce a varargs call.
3044     if (FT->isVarArg() &&
3045         cast<FunctionType>(APTy->getElementType())->isVarArg() &&
3046         FT->getNumParams() !=
3047         cast<FunctionType>(APTy->getElementType())->getNumParams())
3048       return false;
3049   }
3050 
3051   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
3052       !CallerPAL.isEmpty()) {
3053     // In this case we have more arguments than the new function type, but we
3054     // won't be dropping them.  Check that these extra arguments have attributes
3055     // that are compatible with being a vararg call argument.
3056     unsigned SRetIdx;
3057     if (CallerPAL.hasAttrSomewhere(Attribute::StructRet, &SRetIdx) &&
3058         SRetIdx - AttributeList::FirstArgIndex >= FT->getNumParams())
3059       return false;
3060   }
3061 
3062   // Okay, we decided that this is a safe thing to do: go ahead and start
3063   // inserting cast instructions as necessary.
3064   SmallVector<Value *, 8> Args;
3065   SmallVector<AttributeSet, 8> ArgAttrs;
3066   Args.reserve(NumActualArgs);
3067   ArgAttrs.reserve(NumActualArgs);
3068 
3069   // Get any return attributes.
3070   AttrBuilder RAttrs(FT->getContext(), CallerPAL.getRetAttrs());
3071 
3072   // If the return value is not being used, the type may not be compatible
3073   // with the existing attributes.  Wipe out any problematic attributes.
3074   RAttrs.remove(AttributeFuncs::typeIncompatible(NewRetTy));
3075 
3076   LLVMContext &Ctx = Call.getContext();
3077   AI = Call.arg_begin();
3078   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
3079     Type *ParamTy = FT->getParamType(i);
3080 
3081     Value *NewArg = *AI;
3082     if ((*AI)->getType() != ParamTy)
3083       NewArg = Builder.CreateBitOrPointerCast(*AI, ParamTy);
3084     Args.push_back(NewArg);
3085 
3086     // Add any parameter attributes.
3087     if (CallerPAL.hasParamAttr(i, Attribute::ByVal)) {
3088       AttrBuilder AB(FT->getContext(), CallerPAL.getParamAttrs(i));
3089       AB.addByValAttr(NewArg->getType()->getPointerElementType());
3090       ArgAttrs.push_back(AttributeSet::get(Ctx, AB));
3091     } else
3092       ArgAttrs.push_back(CallerPAL.getParamAttrs(i));
3093   }
3094 
3095   // If the function takes more arguments than the call was taking, add them
3096   // now.
3097   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i) {
3098     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
3099     ArgAttrs.push_back(AttributeSet());
3100   }
3101 
3102   // If we are removing arguments to the function, emit an obnoxious warning.
3103   if (FT->getNumParams() < NumActualArgs) {
3104     // TODO: if (!FT->isVarArg()) this call may be unreachable. PR14722
3105     if (FT->isVarArg()) {
3106       // Add all of the arguments in their promoted form to the arg list.
3107       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
3108         Type *PTy = getPromotedType((*AI)->getType());
3109         Value *NewArg = *AI;
3110         if (PTy != (*AI)->getType()) {
3111           // Must promote to pass through va_arg area!
3112           Instruction::CastOps opcode =
3113             CastInst::getCastOpcode(*AI, false, PTy, false);
3114           NewArg = Builder.CreateCast(opcode, *AI, PTy);
3115         }
3116         Args.push_back(NewArg);
3117 
3118         // Add any parameter attributes.
3119         ArgAttrs.push_back(CallerPAL.getParamAttrs(i));
3120       }
3121     }
3122   }
3123 
3124   AttributeSet FnAttrs = CallerPAL.getFnAttrs();
3125 
3126   if (NewRetTy->isVoidTy())
3127     Caller->setName("");   // Void type should not have a name.
3128 
3129   assert((ArgAttrs.size() == FT->getNumParams() || FT->isVarArg()) &&
3130          "missing argument attributes");
3131   AttributeList NewCallerPAL = AttributeList::get(
3132       Ctx, FnAttrs, AttributeSet::get(Ctx, RAttrs), ArgAttrs);
3133 
3134   SmallVector<OperandBundleDef, 1> OpBundles;
3135   Call.getOperandBundlesAsDefs(OpBundles);
3136 
3137   CallBase *NewCall;
3138   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
3139     NewCall = Builder.CreateInvoke(Callee, II->getNormalDest(),
3140                                    II->getUnwindDest(), Args, OpBundles);
3141   } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(Caller)) {
3142     NewCall = Builder.CreateCallBr(Callee, CBI->getDefaultDest(),
3143                                    CBI->getIndirectDests(), Args, OpBundles);
3144   } else {
3145     NewCall = Builder.CreateCall(Callee, Args, OpBundles);
3146     cast<CallInst>(NewCall)->setTailCallKind(
3147         cast<CallInst>(Caller)->getTailCallKind());
3148   }
3149   NewCall->takeName(Caller);
3150   NewCall->setCallingConv(Call.getCallingConv());
3151   NewCall->setAttributes(NewCallerPAL);
3152 
3153   // Preserve prof metadata if any.
3154   NewCall->copyMetadata(*Caller, {LLVMContext::MD_prof});
3155 
3156   // Insert a cast of the return type as necessary.
3157   Instruction *NC = NewCall;
3158   Value *NV = NC;
3159   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
3160     if (!NV->getType()->isVoidTy()) {
3161       NV = NC = CastInst::CreateBitOrPointerCast(NC, OldRetTy);
3162       NC->setDebugLoc(Caller->getDebugLoc());
3163 
3164       // If this is an invoke/callbr instruction, we should insert it after the
3165       // first non-phi instruction in the normal successor block.
3166       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
3167         BasicBlock::iterator I = II->getNormalDest()->getFirstInsertionPt();
3168         InsertNewInstBefore(NC, *I);
3169       } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(Caller)) {
3170         BasicBlock::iterator I = CBI->getDefaultDest()->getFirstInsertionPt();
3171         InsertNewInstBefore(NC, *I);
3172       } else {
3173         // Otherwise, it's a call, just insert cast right after the call.
3174         InsertNewInstBefore(NC, *Caller);
3175       }
3176       Worklist.pushUsersToWorkList(*Caller);
3177     } else {
3178       NV = UndefValue::get(Caller->getType());
3179     }
3180   }
3181 
3182   if (!Caller->use_empty())
3183     replaceInstUsesWith(*Caller, NV);
3184   else if (Caller->hasValueHandle()) {
3185     if (OldRetTy == NV->getType())
3186       ValueHandleBase::ValueIsRAUWd(Caller, NV);
3187     else
3188       // We cannot call ValueIsRAUWd with a different type, and the
3189       // actual tracked value will disappear.
3190       ValueHandleBase::ValueIsDeleted(Caller);
3191   }
3192 
3193   eraseInstFromFunction(*Caller);
3194   return true;
3195 }
3196 
3197 /// Turn a call to a function created by init_trampoline / adjust_trampoline
3198 /// intrinsic pair into a direct call to the underlying function.
3199 Instruction *
3200 InstCombinerImpl::transformCallThroughTrampoline(CallBase &Call,
3201                                                  IntrinsicInst &Tramp) {
3202   Value *Callee = Call.getCalledOperand();
3203   Type *CalleeTy = Callee->getType();
3204   FunctionType *FTy = Call.getFunctionType();
3205   AttributeList Attrs = Call.getAttributes();
3206 
3207   // If the call already has the 'nest' attribute somewhere then give up -
3208   // otherwise 'nest' would occur twice after splicing in the chain.
3209   if (Attrs.hasAttrSomewhere(Attribute::Nest))
3210     return nullptr;
3211 
3212   Function *NestF = cast<Function>(Tramp.getArgOperand(1)->stripPointerCasts());
3213   FunctionType *NestFTy = NestF->getFunctionType();
3214 
3215   AttributeList NestAttrs = NestF->getAttributes();
3216   if (!NestAttrs.isEmpty()) {
3217     unsigned NestArgNo = 0;
3218     Type *NestTy = nullptr;
3219     AttributeSet NestAttr;
3220 
3221     // Look for a parameter marked with the 'nest' attribute.
3222     for (FunctionType::param_iterator I = NestFTy->param_begin(),
3223                                       E = NestFTy->param_end();
3224          I != E; ++NestArgNo, ++I) {
3225       AttributeSet AS = NestAttrs.getParamAttrs(NestArgNo);
3226       if (AS.hasAttribute(Attribute::Nest)) {
3227         // Record the parameter type and any other attributes.
3228         NestTy = *I;
3229         NestAttr = AS;
3230         break;
3231       }
3232     }
3233 
3234     if (NestTy) {
3235       std::vector<Value*> NewArgs;
3236       std::vector<AttributeSet> NewArgAttrs;
3237       NewArgs.reserve(Call.arg_size() + 1);
3238       NewArgAttrs.reserve(Call.arg_size());
3239 
3240       // Insert the nest argument into the call argument list, which may
3241       // mean appending it.  Likewise for attributes.
3242 
3243       {
3244         unsigned ArgNo = 0;
3245         auto I = Call.arg_begin(), E = Call.arg_end();
3246         do {
3247           if (ArgNo == NestArgNo) {
3248             // Add the chain argument and attributes.
3249             Value *NestVal = Tramp.getArgOperand(2);
3250             if (NestVal->getType() != NestTy)
3251               NestVal = Builder.CreateBitCast(NestVal, NestTy, "nest");
3252             NewArgs.push_back(NestVal);
3253             NewArgAttrs.push_back(NestAttr);
3254           }
3255 
3256           if (I == E)
3257             break;
3258 
3259           // Add the original argument and attributes.
3260           NewArgs.push_back(*I);
3261           NewArgAttrs.push_back(Attrs.getParamAttrs(ArgNo));
3262 
3263           ++ArgNo;
3264           ++I;
3265         } while (true);
3266       }
3267 
3268       // The trampoline may have been bitcast to a bogus type (FTy).
3269       // Handle this by synthesizing a new function type, equal to FTy
3270       // with the chain parameter inserted.
3271 
3272       std::vector<Type*> NewTypes;
3273       NewTypes.reserve(FTy->getNumParams()+1);
3274 
3275       // Insert the chain's type into the list of parameter types, which may
3276       // mean appending it.
3277       {
3278         unsigned ArgNo = 0;
3279         FunctionType::param_iterator I = FTy->param_begin(),
3280           E = FTy->param_end();
3281 
3282         do {
3283           if (ArgNo == NestArgNo)
3284             // Add the chain's type.
3285             NewTypes.push_back(NestTy);
3286 
3287           if (I == E)
3288             break;
3289 
3290           // Add the original type.
3291           NewTypes.push_back(*I);
3292 
3293           ++ArgNo;
3294           ++I;
3295         } while (true);
3296       }
3297 
3298       // Replace the trampoline call with a direct call.  Let the generic
3299       // code sort out any function type mismatches.
3300       FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
3301                                                 FTy->isVarArg());
3302       Constant *NewCallee =
3303         NestF->getType() == PointerType::getUnqual(NewFTy) ?
3304         NestF : ConstantExpr::getBitCast(NestF,
3305                                          PointerType::getUnqual(NewFTy));
3306       AttributeList NewPAL =
3307           AttributeList::get(FTy->getContext(), Attrs.getFnAttrs(),
3308                              Attrs.getRetAttrs(), NewArgAttrs);
3309 
3310       SmallVector<OperandBundleDef, 1> OpBundles;
3311       Call.getOperandBundlesAsDefs(OpBundles);
3312 
3313       Instruction *NewCaller;
3314       if (InvokeInst *II = dyn_cast<InvokeInst>(&Call)) {
3315         NewCaller = InvokeInst::Create(NewFTy, NewCallee,
3316                                        II->getNormalDest(), II->getUnwindDest(),
3317                                        NewArgs, OpBundles);
3318         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
3319         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
3320       } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(&Call)) {
3321         NewCaller =
3322             CallBrInst::Create(NewFTy, NewCallee, CBI->getDefaultDest(),
3323                                CBI->getIndirectDests(), NewArgs, OpBundles);
3324         cast<CallBrInst>(NewCaller)->setCallingConv(CBI->getCallingConv());
3325         cast<CallBrInst>(NewCaller)->setAttributes(NewPAL);
3326       } else {
3327         NewCaller = CallInst::Create(NewFTy, NewCallee, NewArgs, OpBundles);
3328         cast<CallInst>(NewCaller)->setTailCallKind(
3329             cast<CallInst>(Call).getTailCallKind());
3330         cast<CallInst>(NewCaller)->setCallingConv(
3331             cast<CallInst>(Call).getCallingConv());
3332         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
3333       }
3334       NewCaller->setDebugLoc(Call.getDebugLoc());
3335 
3336       return NewCaller;
3337     }
3338   }
3339 
3340   // Replace the trampoline call with a direct call.  Since there is no 'nest'
3341   // parameter, there is no need to adjust the argument list.  Let the generic
3342   // code sort out any function type mismatches.
3343   Constant *NewCallee = ConstantExpr::getBitCast(NestF, CalleeTy);
3344   Call.setCalledFunction(FTy, NewCallee);
3345   return &Call;
3346 }
3347