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