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