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