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