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/Bitset.h"
19#include "llvm/ADT/STLFunctionalExtras.h"
20#include "llvm/ADT/SmallBitVector.h"
21#include "llvm/ADT/SmallVector.h"
22#include "llvm/ADT/Statistic.h"
23#include "llvm/ADT/StringExtras.h"
24#include "llvm/Analysis/AliasAnalysis.h"
25#include "llvm/Analysis/AssumeBundleQueries.h"
26#include "llvm/Analysis/AssumptionCache.h"
27#include "llvm/Analysis/InstructionSimplify.h"
28#include "llvm/Analysis/Loads.h"
29#include "llvm/Analysis/MemoryBuiltins.h"
30#include "llvm/Analysis/ValueTracking.h"
31#include "llvm/Analysis/VectorUtils.h"
32#include "llvm/IR/AttributeMask.h"
33#include "llvm/IR/Attributes.h"
34#include "llvm/IR/BasicBlock.h"
35#include "llvm/IR/BundleAttributes.h"
36#include "llvm/IR/Constant.h"
37#include "llvm/IR/Constants.h"
38#include "llvm/IR/DataLayout.h"
39#include "llvm/IR/DebugInfo.h"
40#include "llvm/IR/DerivedTypes.h"
41#include "llvm/IR/Function.h"
42#include "llvm/IR/GlobalVariable.h"
43#include "llvm/IR/InlineAsm.h"
44#include "llvm/IR/InstrTypes.h"
45#include "llvm/IR/Instruction.h"
46#include "llvm/IR/Instructions.h"
47#include "llvm/IR/IntrinsicInst.h"
48#include "llvm/IR/Intrinsics.h"
49#include "llvm/IR/IntrinsicsAArch64.h"
50#include "llvm/IR/IntrinsicsAMDGPU.h"
51#include "llvm/IR/IntrinsicsARM.h"
52#include "llvm/IR/IntrinsicsHexagon.h"
53#include "llvm/IR/LLVMContext.h"
54#include "llvm/IR/Metadata.h"
55#include "llvm/IR/PatternMatch.h"
56#include "llvm/IR/ProfDataUtils.h"
57#include "llvm/IR/Statepoint.h"
58#include "llvm/IR/Type.h"
59#include "llvm/IR/User.h"
60#include "llvm/IR/Value.h"
61#include "llvm/IR/ValueHandle.h"
62#include "llvm/Support/AtomicOrdering.h"
63#include "llvm/Support/Casting.h"
64#include "llvm/Support/CommandLine.h"
65#include "llvm/Support/Compiler.h"
66#include "llvm/Support/Debug.h"
67#include "llvm/Support/ErrorHandling.h"
68#include "llvm/Support/KnownBits.h"
69#include "llvm/Support/KnownFPClass.h"
70#include "llvm/Support/MathExtras.h"
71#include "llvm/Support/TypeSize.h"
72#include "llvm/Support/raw_ostream.h"
73#include "llvm/Transforms/InstCombine/InstCombiner.h"
74#include "llvm/Transforms/Utils/AssumeBundleBuilder.h"
75#include "llvm/Transforms/Utils/Local.h"
76#include "llvm/Transforms/Utils/SimplifyLibCalls.h"
77#include <algorithm>
78#include <cassert>
79#include <cstdint>
80#include <optional>
81#include <utility>
82#include <vector>
83
84#define DEBUG_TYPE "instcombine"
85#include "llvm/Transforms/Utils/InstructionWorklist.h"
86
87using namespace llvm;
88using namespace PatternMatch;
89
90STATISTIC(NumSimplified, "Number of library calls simplified");
91
92static cl::opt<unsigned> GuardWideningWindow(
93 "instcombine-guard-widening-window",
94 cl::init(Val: 3),
95 cl::desc("How wide an instruction window to bypass looking for "
96 "another guard"));
97
98/// Return the specified type promoted as it would be to pass though a va_arg
99/// area.
100static Type *getPromotedType(Type *Ty) {
101 if (IntegerType* ITy = dyn_cast<IntegerType>(Val: Ty)) {
102 if (ITy->getBitWidth() < 32)
103 return Type::getInt32Ty(C&: Ty->getContext());
104 }
105 return Ty;
106}
107
108/// Recognize a memcpy/memmove from a trivially otherwise unused alloca.
109/// TODO: This should probably be integrated with visitAllocSites, but that
110/// requires a deeper change to allow either unread or unwritten objects.
111static bool hasUndefSource(AnyMemTransferInst *MI) {
112 auto *Src = MI->getRawSource();
113 while (isa<GetElementPtrInst>(Val: Src)) {
114 if (!Src->hasOneUse())
115 return false;
116 Src = cast<Instruction>(Val: Src)->getOperand(i: 0);
117 }
118 return isa<AllocaInst>(Val: Src) && Src->hasOneUse();
119}
120
121Instruction *InstCombinerImpl::SimplifyAnyMemTransfer(AnyMemTransferInst *MI) {
122 Align DstAlign = getKnownAlignment(V: MI->getRawDest(), DL, CxtI: MI, AC: &AC, DT: &DT);
123 MaybeAlign CopyDstAlign = MI->getDestAlign();
124 if (!CopyDstAlign || *CopyDstAlign < DstAlign) {
125 MI->setDestAlignment(DstAlign);
126 return MI;
127 }
128
129 Align SrcAlign = getKnownAlignment(V: MI->getRawSource(), DL, CxtI: MI, AC: &AC, DT: &DT);
130 MaybeAlign CopySrcAlign = MI->getSourceAlign();
131 if (!CopySrcAlign || *CopySrcAlign < SrcAlign) {
132 MI->setSourceAlignment(SrcAlign);
133 return MI;
134 }
135
136 // If we have a store to a location which is known constant, we can conclude
137 // that the store must be storing the constant value (else the memory
138 // wouldn't be constant), and this must be a noop.
139 if (!isModSet(MRI: AA->getModRefInfoMask(P: MI->getDest()))) {
140 // Set the size of the copy to 0, it will be deleted on the next iteration.
141 MI->setLength((uint64_t)0);
142 return MI;
143 }
144
145 // If the source is provably undef, the memcpy/memmove doesn't do anything
146 // (unless the transfer is volatile).
147 if (hasUndefSource(MI) && !MI->isVolatile()) {
148 // Set the size of the copy to 0, it will be deleted on the next iteration.
149 MI->setLength((uint64_t)0);
150 return MI;
151 }
152
153 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
154 // load/store.
155 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(Val: MI->getLength());
156 if (!MemOpLength) return nullptr;
157
158 // Source and destination pointer types are always "i8*" for intrinsic. See
159 // if the size is something we can handle with a single primitive load/store.
160 // A single load+store correctly handles overlapping memory in the memmove
161 // case.
162 uint64_t Size = MemOpLength->getLimitedValue();
163 assert(Size && "0-sized memory transferring should be removed already.");
164
165 if (Size > 8 || (Size&(Size-1)))
166 return nullptr; // If not 1/2/4/8 bytes, exit.
167
168 // If it is an atomic and alignment is less than the size then we will
169 // introduce the unaligned memory access which will be later transformed
170 // into libcall in CodeGen. This is not evident performance gain so disable
171 // it now.
172 if (MI->isAtomic())
173 if (*CopyDstAlign < Size || *CopySrcAlign < Size)
174 return nullptr;
175
176 // Use an integer load+store unless we can find something better.
177 IntegerType* IntType = IntegerType::get(C&: MI->getContext(), NumBits: Size<<3);
178
179 // If the memcpy has metadata describing the members, see if we can get the
180 // TBAA, scope and noalias tags describing our copy.
181 AAMDNodes AACopyMD = MI->getAAMetadata().adjustForAccess(AccessSize: Size);
182
183 Value *Src = MI->getArgOperand(i: 1);
184 Value *Dest = MI->getArgOperand(i: 0);
185 LoadInst *L = Builder.CreateLoad(Ty: IntType, Ptr: Src);
186 // Alignment from the mem intrinsic will be better, so use it.
187 L->setAlignment(*CopySrcAlign);
188 L->setAAMetadata(AACopyMD);
189 MDNode *LoopMemParallelMD =
190 MI->getMetadata(KindID: LLVMContext::MD_mem_parallel_loop_access);
191 if (LoopMemParallelMD)
192 L->setMetadata(KindID: LLVMContext::MD_mem_parallel_loop_access, Node: LoopMemParallelMD);
193 MDNode *AccessGroupMD = MI->getMetadata(KindID: LLVMContext::MD_access_group);
194 if (AccessGroupMD)
195 L->setMetadata(KindID: LLVMContext::MD_access_group, Node: AccessGroupMD);
196
197 StoreInst *S = Builder.CreateStore(Val: L, Ptr: Dest);
198 // Alignment from the mem intrinsic will be better, so use it.
199 S->setAlignment(*CopyDstAlign);
200 S->setAAMetadata(AACopyMD);
201 if (LoopMemParallelMD)
202 S->setMetadata(KindID: LLVMContext::MD_mem_parallel_loop_access, Node: LoopMemParallelMD);
203 if (AccessGroupMD)
204 S->setMetadata(KindID: LLVMContext::MD_access_group, Node: AccessGroupMD);
205 S->copyMetadata(SrcInst: *MI, WL: LLVMContext::MD_DIAssignID);
206
207 if (auto *MT = dyn_cast<MemTransferInst>(Val: MI)) {
208 // non-atomics can be volatile
209 L->setVolatile(MT->isVolatile());
210 S->setVolatile(MT->isVolatile());
211 }
212 if (MI->isAtomic()) {
213 // atomics have to be unordered
214 L->setOrdering(AtomicOrdering::Unordered);
215 S->setOrdering(AtomicOrdering::Unordered);
216 }
217
218 // Set the size of the copy to 0, it will be deleted on the next iteration.
219 MI->setLength((uint64_t)0);
220 return MI;
221}
222
223Instruction *InstCombinerImpl::SimplifyAnyMemSet(AnyMemSetInst *MI) {
224 const Align KnownAlignment =
225 getKnownAlignment(V: MI->getDest(), DL, CxtI: MI, AC: &AC, DT: &DT);
226 MaybeAlign MemSetAlign = MI->getDestAlign();
227 if (!MemSetAlign || *MemSetAlign < KnownAlignment) {
228 MI->setDestAlignment(KnownAlignment);
229 return MI;
230 }
231
232 // If we have a store to a location which is known constant, we can conclude
233 // that the store must be storing the constant value (else the memory
234 // wouldn't be constant), and this must be a noop.
235 if (!isModSet(MRI: AA->getModRefInfoMask(P: MI->getDest()))) {
236 // Set the size of the copy to 0, it will be deleted on the next iteration.
237 MI->setLength((uint64_t)0);
238 return MI;
239 }
240
241 // Remove memset with an undef value.
242 // FIXME: This is technically incorrect because it might overwrite a poison
243 // value. Change to PoisonValue once #52930 is resolved.
244 if (isa<UndefValue>(Val: MI->getValue())) {
245 // Set the size of the copy to 0, it will be deleted on the next iteration.
246 MI->setLength((uint64_t)0);
247 return MI;
248 }
249
250 // Extract the length and alignment and fill if they are constant.
251 ConstantInt *LenC = dyn_cast<ConstantInt>(Val: MI->getLength());
252 ConstantInt *FillC = dyn_cast<ConstantInt>(Val: MI->getValue());
253 if (!LenC || !FillC || !FillC->getType()->isIntegerTy(BitWidth: 8))
254 return nullptr;
255 const uint64_t Len = LenC->getLimitedValue();
256 assert(Len && "0-sized memory setting should be removed already.");
257 const Align Alignment = MI->getDestAlign().valueOrOne();
258
259 // If it is an atomic and alignment is less than the size then we will
260 // introduce the unaligned memory access which will be later transformed
261 // into libcall in CodeGen. This is not evident performance gain so disable
262 // it now.
263 if (MI->isAtomic() && Alignment < Len)
264 return nullptr;
265
266 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
267 if (Len <= 8 && isPowerOf2_32(Value: (uint32_t)Len)) {
268 Value *Dest = MI->getDest();
269
270 // Extract the fill value and store.
271 Constant *FillVal = ConstantInt::get(
272 Context&: MI->getContext(), V: APInt::getSplat(NewLen: Len * 8, V: FillC->getValue()));
273 StoreInst *S = Builder.CreateStore(Val: FillVal, Ptr: Dest, isVolatile: MI->isVolatile());
274 S->copyMetadata(SrcInst: *MI, WL: LLVMContext::MD_DIAssignID);
275 for (DbgVariableRecord *DbgAssign : at::getDVRAssignmentMarkers(Inst: S)) {
276 if (llvm::is_contained(Range: DbgAssign->location_ops(), Element: FillC))
277 DbgAssign->replaceVariableLocationOp(OldValue: FillC, NewValue: FillVal);
278 }
279
280 S->setAlignment(Alignment);
281 if (MI->isAtomic())
282 S->setOrdering(AtomicOrdering::Unordered);
283
284 // Set the size of the copy to 0, it will be deleted on the next iteration.
285 MI->setLength((uint64_t)0);
286 return MI;
287 }
288
289 return nullptr;
290}
291
292// TODO, Obvious Missing Transforms:
293// * Narrow width by halfs excluding zero/undef lanes
294Value *InstCombinerImpl::simplifyMaskedLoad(IntrinsicInst &II) {
295 Value *LoadPtr = II.getArgOperand(i: 0);
296 const Align Alignment = II.getParamAlign(ArgNo: 0).valueOrOne();
297 Value *Mask = II.getArgOperand(i: 1);
298
299 // If the mask is all ones or poison, this is a plain vector load of the 1st
300 // argument.
301 if (match(V: Mask, P: m_AllOnesOrPoison())) {
302 LoadInst *L = Builder.CreateAlignedLoad(Ty: II.getType(), Ptr: LoadPtr, Align: Alignment,
303 Name: "unmaskedload");
304 L->copyMetadata(SrcInst: II);
305 return L;
306 }
307
308 // If we can unconditionally load from this address, replace with a
309 // load/select idiom.
310 if (isDereferenceablePointer(V: LoadPtr, Ty: II.getType(),
311 Q: SQ.getWithInstruction(I: &II))) {
312 LoadInst *LI = Builder.CreateAlignedLoad(Ty: II.getType(), Ptr: LoadPtr, Align: Alignment,
313 Name: "unmaskedload");
314 LI->copyMetadata(SrcInst: II);
315 return Builder.CreateSelect(C: II.getArgOperand(i: 1), True: LI, False: II.getArgOperand(i: 2));
316 }
317
318 return nullptr;
319}
320
321// TODO, Obvious Missing Transforms:
322// * Single constant active lane -> store
323// * Narrow width by halfs excluding zero/undef lanes
324Instruction *InstCombinerImpl::simplifyMaskedStore(IntrinsicInst &II) {
325 Value *StorePtr = II.getArgOperand(i: 1);
326 Align Alignment = II.getParamAlign(ArgNo: 1).valueOrOne();
327 auto *ConstMask = dyn_cast<Constant>(Val: II.getArgOperand(i: 2));
328 if (!ConstMask)
329 return nullptr;
330
331 // If the mask is all zeros or poison, this instruction does nothing.
332 if (match(V: ConstMask, P: m_ZeroOrPoison()))
333 return eraseInstFromFunction(I&: II);
334
335 // If the mask is all ones or poison, this is a plain vector store of the 1st
336 // argument.
337 if (match(V: ConstMask, P: m_AllOnesOrPoison())) {
338 StoreInst *S =
339 new StoreInst(II.getArgOperand(i: 0), StorePtr, false, Alignment);
340 S->copyMetadata(SrcInst: II);
341 return S;
342 }
343
344 if (isa<ScalableVectorType>(Val: ConstMask->getType()))
345 return nullptr;
346
347 // Use masked off lanes to simplify operands via SimplifyDemandedVectorElts
348 APInt DemandedElts = possiblyDemandedEltsInMask(Mask: ConstMask);
349 APInt PoisonElts(DemandedElts.getBitWidth(), 0);
350 if (Value *V = SimplifyDemandedVectorElts(V: II.getOperand(i_nocapture: 0), DemandedElts,
351 PoisonElts))
352 return replaceOperand(I&: II, OpNum: 0, V);
353
354 return nullptr;
355}
356
357// TODO, Obvious Missing Transforms:
358// * Single constant active lane load -> load
359// * Dereferenceable address & few lanes -> scalarize speculative load/selects
360// * Adjacent vector addresses -> masked.load
361// * Narrow width by halfs excluding zero/undef lanes
362// * Vector incrementing address -> vector masked load
363Instruction *InstCombinerImpl::simplifyMaskedGather(IntrinsicInst &II) {
364 auto *ConstMask = dyn_cast<Constant>(Val: II.getArgOperand(i: 1));
365 if (!ConstMask)
366 return nullptr;
367
368 // Vector splat address w/known mask -> scalar load
369 // Fold the gather to load the source vector first lane
370 // because it is reloading the same value each time
371 if (ConstMask->isAllOnesValue())
372 if (auto *SplatPtr = getSplatValue(V: II.getArgOperand(i: 0))) {
373 auto *VecTy = cast<VectorType>(Val: II.getType());
374 const Align Alignment = II.getParamAlign(ArgNo: 0).valueOrOne();
375 LoadInst *L = Builder.CreateAlignedLoad(Ty: VecTy->getElementType(), Ptr: SplatPtr,
376 Align: Alignment, Name: "load.scalar");
377 Value *Shuf =
378 Builder.CreateVectorSplat(EC: VecTy->getElementCount(), V: L, Name: "broadcast");
379 return replaceInstUsesWith(I&: II, V: cast<Instruction>(Val: Shuf));
380 }
381
382 return nullptr;
383}
384
385// TODO, Obvious Missing Transforms:
386// * Single constant active lane -> store
387// * Adjacent vector addresses -> masked.store
388// * Narrow store width by halfs excluding zero/undef lanes
389// * Vector incrementing address -> vector masked store
390Instruction *InstCombinerImpl::simplifyMaskedScatter(IntrinsicInst &II) {
391 auto *ConstMask = dyn_cast<Constant>(Val: II.getArgOperand(i: 2));
392 if (!ConstMask)
393 return nullptr;
394
395 // If the mask is all zeros or poison, a scatter does nothing.
396 if (match(V: ConstMask, P: m_ZeroOrPoison()))
397 return eraseInstFromFunction(I&: II);
398
399 // Vector splat address -> scalar store
400 if (auto *SplatPtr = getSplatValue(V: II.getArgOperand(i: 1))) {
401 // scatter(splat(value), splat(ptr), non-zero-mask) -> store value, ptr
402 if (auto *SplatValue = getSplatValue(V: II.getArgOperand(i: 0))) {
403 if (maskContainsAllOneOrUndef(Mask: ConstMask)) {
404 Align Alignment = II.getParamAlign(ArgNo: 1).valueOrOne();
405 StoreInst *S = new StoreInst(SplatValue, SplatPtr, /*IsVolatile=*/false,
406 Alignment);
407 S->copyMetadata(SrcInst: II);
408 return S;
409 }
410 }
411 // scatter(vector, splat(ptr), splat(true)) -> store extract(vector,
412 // lastlane), ptr
413 if (ConstMask->isAllOnesValue()) {
414 Align Alignment = II.getParamAlign(ArgNo: 1).valueOrOne();
415 VectorType *WideLoadTy = cast<VectorType>(Val: II.getArgOperand(i: 1)->getType());
416 ElementCount VF = WideLoadTy->getElementCount();
417 Value *RunTimeVF = Builder.CreateElementCount(Ty: Builder.getInt32Ty(), EC: VF);
418 Value *LastLane = Builder.CreateSub(LHS: RunTimeVF, RHS: Builder.getInt32(C: 1));
419 Value *Extract =
420 Builder.CreateExtractElement(Vec: II.getArgOperand(i: 0), Idx: LastLane);
421 StoreInst *S =
422 new StoreInst(Extract, SplatPtr, /*IsVolatile=*/false, Alignment);
423 S->copyMetadata(SrcInst: II);
424 return S;
425 }
426 }
427 if (isa<ScalableVectorType>(Val: ConstMask->getType()))
428 return nullptr;
429
430 // Use masked off lanes to simplify operands via SimplifyDemandedVectorElts
431 APInt DemandedElts = possiblyDemandedEltsInMask(Mask: ConstMask);
432 APInt PoisonElts(DemandedElts.getBitWidth(), 0);
433 if (Value *V = SimplifyDemandedVectorElts(V: II.getOperand(i_nocapture: 0), DemandedElts,
434 PoisonElts))
435 return replaceOperand(I&: II, OpNum: 0, V);
436 if (Value *V = SimplifyDemandedVectorElts(V: II.getOperand(i_nocapture: 1), DemandedElts,
437 PoisonElts))
438 return replaceOperand(I&: II, OpNum: 1, V);
439
440 return nullptr;
441}
442
443/// This function transforms launder.invariant.group and strip.invariant.group
444/// like:
445/// launder(launder(%x)) -> launder(%x) (the result is not the argument)
446/// launder(strip(%x)) -> launder(%x)
447/// strip(strip(%x)) -> strip(%x) (the result is not the argument)
448/// strip(launder(%x)) -> strip(%x)
449/// This is legal because it preserves the most recent information about
450/// the presence or absence of invariant.group.
451static Instruction *simplifyInvariantGroupIntrinsic(IntrinsicInst &II,
452 InstCombinerImpl &IC) {
453 auto *Arg = II.getArgOperand(i: 0);
454 auto *StrippedArg = Arg->stripPointerCasts();
455 auto *StrippedInvariantGroupsArg = StrippedArg;
456 while (auto *Intr = dyn_cast<IntrinsicInst>(Val: StrippedInvariantGroupsArg)) {
457 if (Intr->getIntrinsicID() != Intrinsic::launder_invariant_group &&
458 Intr->getIntrinsicID() != Intrinsic::strip_invariant_group)
459 break;
460 StrippedInvariantGroupsArg = Intr->getArgOperand(i: 0)->stripPointerCasts();
461 }
462 if (StrippedArg == StrippedInvariantGroupsArg)
463 return nullptr; // No launders/strips to remove.
464
465 Value *Result = nullptr;
466
467 if (II.getIntrinsicID() == Intrinsic::launder_invariant_group)
468 Result = IC.Builder.CreateLaunderInvariantGroup(Ptr: StrippedInvariantGroupsArg);
469 else if (II.getIntrinsicID() == Intrinsic::strip_invariant_group)
470 Result = IC.Builder.CreateStripInvariantGroup(Ptr: StrippedInvariantGroupsArg);
471 else
472 llvm_unreachable(
473 "simplifyInvariantGroupIntrinsic only handles launder and strip");
474 if (Result->getType()->getPointerAddressSpace() !=
475 II.getType()->getPointerAddressSpace())
476 Result = IC.Builder.CreateAddrSpaceCast(V: Result, DestTy: II.getType());
477
478 return cast<Instruction>(Val: Result);
479}
480
481static Instruction *foldCttzCtlz(IntrinsicInst &II, InstCombinerImpl &IC) {
482 assert((II.getIntrinsicID() == Intrinsic::cttz ||
483 II.getIntrinsicID() == Intrinsic::ctlz) &&
484 "Expected cttz or ctlz intrinsic");
485 bool IsTZ = II.getIntrinsicID() == Intrinsic::cttz;
486 Value *Op0 = II.getArgOperand(i: 0);
487 Value *Op1 = II.getArgOperand(i: 1);
488 Value *X;
489 // ctlz(bitreverse(x)) -> cttz(x)
490 // cttz(bitreverse(x)) -> ctlz(x)
491 if (match(V: Op0, P: m_BitReverse(Op0: m_Value(V&: X)))) {
492 Intrinsic::ID ID = IsTZ ? Intrinsic::ctlz : Intrinsic::cttz;
493 Function *F =
494 Intrinsic::getOrInsertDeclaration(M: II.getModule(), id: ID, OverloadTys: II.getType());
495 return CallInst::Create(Func: F, Args: {X, II.getArgOperand(i: 1)});
496 }
497
498 if (II.getType()->isIntOrIntVectorTy(BitWidth: 1)) {
499 // ctlz/cttz i1 Op0 --> not Op0
500 if (match(V: Op1, P: m_Zero()))
501 return BinaryOperator::CreateNot(Op: Op0);
502 // If zero is poison, then the input can be assumed to be "true", so the
503 // instruction simplifies to "false".
504 assert(match(Op1, m_One()) && "Expected ctlz/cttz operand to be 0 or 1");
505 return IC.replaceInstUsesWith(I&: II, V: ConstantInt::getNullValue(Ty: II.getType()));
506 }
507
508 // If ctlz/cttz is only used as a shift amount, set is_zero_poison to true.
509 if (II.hasOneUse() && match(V: Op1, P: m_Zero()) &&
510 match(V: II.user_back(), P: m_Shift(L: m_Value(), R: m_Specific(V: &II))))
511 return CallInst::Create(Func: II.getCalledFunction(),
512 Args: {Op0, IC.Builder.getTrue()});
513
514 Constant *C;
515
516 if (IsTZ) {
517 // cttz(-x) -> cttz(x)
518 if (match(V: Op0, P: m_Neg(V: m_Value(V&: X))))
519 return CallInst::Create(Func: II.getCalledFunction(), Args: {X, Op1});
520
521 // cttz(-x & x) -> cttz(x)
522 if (match(V: Op0, P: m_c_And(L: m_Neg(V: m_Value(V&: X)), R: m_Deferred(V: X))))
523 return CallInst::Create(Func: II.getCalledFunction(), Args: {X, Op1});
524
525 // cttz(sext(x)) -> cttz(zext(x))
526 if (match(V: Op0, P: m_OneUse(SubPattern: m_SExt(Op: m_Value(V&: X))))) {
527 auto *Zext = IC.Builder.CreateZExt(V: X, DestTy: II.getType());
528 auto *CttzZext =
529 IC.Builder.CreateBinaryIntrinsic(ID: Intrinsic::cttz, LHS: Zext, RHS: Op1);
530 return IC.replaceInstUsesWith(I&: II, V: CttzZext);
531 }
532
533 // Zext doesn't change the number of trailing zeros, so narrow:
534 // cttz(zext(x)) -> zext(cttz(x)) if the 'ZeroIsPoison' parameter is 'true'.
535 if (match(V: Op0, P: m_OneUse(SubPattern: m_ZExt(Op: m_Value(V&: X)))) && match(V: Op1, P: m_One())) {
536 auto *Cttz = IC.Builder.CreateBinaryIntrinsic(ID: Intrinsic::cttz, LHS: X,
537 RHS: IC.Builder.getTrue());
538 auto *ZextCttz = IC.Builder.CreateZExt(V: Cttz, DestTy: II.getType());
539 return IC.replaceInstUsesWith(I&: II, V: ZextCttz);
540 }
541
542 // cttz(abs(x)) -> cttz(x)
543 // cttz(nabs(x)) -> cttz(x)
544 Value *Y;
545 SelectPatternFlavor SPF = matchSelectPattern(V: Op0, LHS&: X, RHS&: Y).Flavor;
546 if (SPF == SPF_ABS || SPF == SPF_NABS)
547 return CallInst::Create(Func: II.getCalledFunction(), Args: {X, Op1});
548
549 if (match(V: Op0, P: m_Intrinsic<Intrinsic::abs>(Ops: m_Value(V&: X))))
550 return CallInst::Create(Func: II.getCalledFunction(), Args: {X, Op1});
551
552 // cttz(shl(%const, %val), 1) --> add(cttz(%const, 1), %val)
553 if (match(V: Op0, P: m_Shl(L: m_ImmConstant(C), R: m_Value(V&: X))) &&
554 match(V: Op1, P: m_One())) {
555 Value *ConstCttz =
556 IC.Builder.CreateBinaryIntrinsic(ID: Intrinsic::cttz, LHS: C, RHS: Op1);
557 return BinaryOperator::CreateAdd(V1: ConstCttz, V2: X);
558 }
559
560 // cttz(lshr exact (%const, %val), 1) --> sub(cttz(%const, 1), %val)
561 if (match(V: Op0, P: m_Exact(SubPattern: m_LShr(L: m_ImmConstant(C), R: m_Value(V&: X)))) &&
562 match(V: Op1, P: m_One())) {
563 Value *ConstCttz =
564 IC.Builder.CreateBinaryIntrinsic(ID: Intrinsic::cttz, LHS: C, RHS: Op1);
565 return BinaryOperator::CreateSub(V1: ConstCttz, V2: X);
566 }
567
568 // cttz(add(lshr(UINT_MAX, %val), 1)) --> sub(width, %val)
569 if (match(V: Op0, P: m_Add(L: m_LShr(L: m_AllOnes(), R: m_Value(V&: X)), R: m_One()))) {
570 Value *Width =
571 ConstantInt::get(Ty: II.getType(), V: II.getType()->getScalarSizeInBits());
572 return BinaryOperator::CreateSub(V1: Width, V2: X);
573 }
574 } else {
575 // ctlz(lshr(%const, %val), 1) --> add(ctlz(%const, 1), %val)
576 if (match(V: Op0, P: m_LShr(L: m_ImmConstant(C), R: m_Value(V&: X))) &&
577 match(V: Op1, P: m_One())) {
578 Value *ConstCtlz =
579 IC.Builder.CreateBinaryIntrinsic(ID: Intrinsic::ctlz, LHS: C, RHS: Op1);
580 return BinaryOperator::CreateAdd(V1: ConstCtlz, V2: X);
581 }
582
583 // ctlz(shl nuw (%const, %val), 1) --> sub(ctlz(%const, 1), %val)
584 if (match(V: Op0, P: m_NUWShl(L: m_ImmConstant(C), R: m_Value(V&: X))) &&
585 match(V: Op1, P: m_One())) {
586 Value *ConstCtlz =
587 IC.Builder.CreateBinaryIntrinsic(ID: Intrinsic::ctlz, LHS: C, RHS: Op1);
588 return BinaryOperator::CreateSub(V1: ConstCtlz, V2: X);
589 }
590
591 // ctlz(~x & (x - 1)) -> bitwidth - cttz(x, false)
592 if (Op0->hasOneUse() &&
593 match(V: Op0,
594 P: m_c_And(L: m_Not(V: m_Value(V&: X)), R: m_Add(L: m_Deferred(V: X), R: m_AllOnes())))) {
595 Type *Ty = II.getType();
596 unsigned BitWidth = Ty->getScalarSizeInBits();
597 auto *Cttz = IC.Builder.CreateIntrinsic(ID: Intrinsic::cttz, OverloadTypes: Ty,
598 Args: {X, IC.Builder.getFalse()});
599 auto *Bw = ConstantInt::get(Ty, V: APInt(BitWidth, BitWidth));
600 return IC.replaceInstUsesWith(I&: II, V: IC.Builder.CreateSub(LHS: Bw, RHS: Cttz));
601 }
602 }
603
604 // cttz(Pow2) -> Log2(Pow2)
605 // ctlz(Pow2) -> BitWidth - 1 - Log2(Pow2)
606 if (auto *R = IC.tryGetLog2(Op: Op0, AssumeNonZero: match(V: Op1, P: m_One()))) {
607 if (IsTZ)
608 return IC.replaceInstUsesWith(I&: II, V: R);
609 BinaryOperator *BO = BinaryOperator::CreateSub(
610 V1: ConstantInt::get(Ty: R->getType(), V: R->getType()->getScalarSizeInBits() - 1),
611 V2: R);
612 BO->setHasNoSignedWrap();
613 BO->setHasNoUnsignedWrap();
614 return BO;
615 }
616
617 KnownBits Known = IC.computeKnownBits(V: Op0, CxtI: &II);
618
619 // Create a mask for bits above (ctlz) or below (cttz) the first known one.
620 unsigned PossibleZeros = IsTZ ? Known.countMaxTrailingZeros()
621 : Known.countMaxLeadingZeros();
622 unsigned DefiniteZeros = IsTZ ? Known.countMinTrailingZeros()
623 : Known.countMinLeadingZeros();
624
625 // If all bits above (ctlz) or below (cttz) the first known one are known
626 // zero, this value is constant.
627 // FIXME: This should be in InstSimplify because we're replacing an
628 // instruction with a constant.
629 if (PossibleZeros == DefiniteZeros) {
630 auto *C = ConstantInt::get(Ty: Op0->getType(), V: DefiniteZeros);
631 return IC.replaceInstUsesWith(I&: II, V: C);
632 }
633
634 // If the input to cttz/ctlz is known to be non-zero,
635 // then change the 'ZeroIsPoison' parameter to 'true'
636 // because we know the zero behavior can't affect the result.
637 if (!Known.One.isZero() ||
638 isKnownNonZero(V: Op0, Q: IC.getSimplifyQuery().getWithInstruction(I: &II))) {
639 if (!match(V: II.getArgOperand(i: 1), P: m_One()))
640 return CallInst::Create(Func: II.getCalledFunction(),
641 Args: {Op0, IC.Builder.getTrue()});
642 }
643
644 // Add range attribute since known bits can't completely reflect what we know.
645 unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
646 if (BitWidth != 1 && !II.hasRetAttr(Kind: Attribute::Range) &&
647 !II.getMetadata(KindID: LLVMContext::MD_range)) {
648 ConstantRange Range(APInt(BitWidth, DefiniteZeros),
649 APInt(BitWidth, PossibleZeros + 1));
650 II.addRangeRetAttr(CR: Range);
651 return &II;
652 }
653
654 return nullptr;
655}
656
657static Instruction *foldCtpop(IntrinsicInst &II, InstCombinerImpl &IC) {
658 assert(II.getIntrinsicID() == Intrinsic::ctpop &&
659 "Expected ctpop intrinsic");
660 Type *Ty = II.getType();
661 unsigned BitWidth = Ty->getScalarSizeInBits();
662 Value *Op0 = II.getArgOperand(i: 0);
663 Value *X, *Y;
664
665 // ctpop(bitreverse(x)) -> ctpop(x)
666 // ctpop(bswap(x)) -> ctpop(x)
667 if (match(V: Op0, P: m_BitReverse(Op0: m_Value(V&: X))) || match(V: Op0, P: m_BSwap(Op0: m_Value(V&: X))))
668 return CallInst::Create(Func: II.getCalledFunction(), Args: X);
669
670 // ctpop(rot(x)) -> ctpop(x)
671 if ((match(V: Op0, P: m_FShl(Op0: m_Value(V&: X), Op1: m_Value(V&: Y), Op2: m_Value())) ||
672 match(V: Op0, P: m_FShr(Op0: m_Value(V&: X), Op1: m_Value(V&: Y), Op2: m_Value()))) &&
673 X == Y)
674 return CallInst::Create(Func: II.getCalledFunction(), Args: X);
675
676 // ctpop(x | -x) -> bitwidth - cttz(x, false)
677 if (Op0->hasOneUse() &&
678 match(V: Op0, P: m_c_Or(L: m_Value(V&: X), R: m_Neg(V: m_Deferred(V: X))))) {
679 auto *Cttz = IC.Builder.CreateIntrinsic(ID: Intrinsic::cttz, OverloadTypes: Ty,
680 Args: {X, IC.Builder.getFalse()});
681 auto *Bw = ConstantInt::get(Ty, V: APInt(BitWidth, BitWidth));
682 return IC.replaceInstUsesWith(I&: II, V: IC.Builder.CreateSub(LHS: Bw, RHS: Cttz));
683 }
684
685 // ctpop(~x & (x - 1)) -> cttz(x, false)
686 if (match(V: Op0,
687 P: m_c_And(L: m_Not(V: m_Value(V&: X)), R: m_Add(L: m_Deferred(V: X), R: m_AllOnes())))) {
688 Function *F =
689 Intrinsic::getOrInsertDeclaration(M: II.getModule(), id: Intrinsic::cttz, OverloadTys: Ty);
690 return CallInst::Create(Func: F, Args: {X, IC.Builder.getFalse()});
691 }
692
693 // Zext doesn't change the number of set bits, so narrow:
694 // ctpop (zext X) --> zext (ctpop X)
695 if (match(V: Op0, P: m_OneUse(SubPattern: m_ZExt(Op: m_Value(V&: X))))) {
696 Value *NarrowPop = IC.Builder.CreateUnaryIntrinsic(ID: Intrinsic::ctpop, Op: X);
697 return CastInst::Create(Instruction::ZExt, S: NarrowPop, Ty);
698 }
699
700 KnownBits Known(BitWidth);
701 IC.computeKnownBits(V: Op0, Known, CxtI: &II);
702
703 // If all bits are zero except for exactly one fixed bit, then the result
704 // must be 0 or 1, and we can get that answer by shifting to LSB:
705 // ctpop (X & 32) --> (X & 32) >> 5
706 // TODO: Investigate removing this as its likely unnecessary given the below
707 // `isKnownToBeAPowerOfTwo` check.
708 if ((~Known.Zero).isPowerOf2())
709 return BinaryOperator::CreateLShr(
710 V1: Op0, V2: ConstantInt::get(Ty, V: (~Known.Zero).exactLogBase2()));
711
712 // More generally we can also handle non-constant power of 2 patterns such as
713 // shl/shr(Pow2, X), (X & -X), etc... by transforming:
714 // ctpop(Pow2OrZero) --> icmp ne X, 0
715 if (IC.isKnownToBeAPowerOfTwo(V: Op0, /* OrZero */ true))
716 return CastInst::Create(Instruction::ZExt,
717 S: IC.Builder.CreateICmp(P: ICmpInst::ICMP_NE, LHS: Op0,
718 RHS: Constant::getNullValue(Ty)),
719 Ty);
720
721 // Add range attribute since known bits can't completely reflect what we know.
722 if (BitWidth != 1) {
723 ConstantRange OldRange =
724 II.getRange().value_or(u: ConstantRange::getFull(BitWidth));
725
726 unsigned Lower = Known.countMinPopulation();
727 unsigned Upper = Known.countMaxPopulation() + 1;
728
729 if (Lower == 0 && OldRange.contains(Val: APInt::getZero(numBits: BitWidth)) &&
730 isKnownNonZero(V: Op0, Q: IC.getSimplifyQuery().getWithInstruction(I: &II)))
731 Lower = 1;
732
733 ConstantRange Range(APInt(BitWidth, Lower), APInt(BitWidth, Upper));
734 Range = Range.intersectWith(CR: OldRange, Type: ConstantRange::Unsigned);
735
736 if (Range != OldRange) {
737 II.addRangeRetAttr(CR: Range);
738 return &II;
739 }
740 }
741
742 return nullptr;
743}
744
745/// Convert `tbl`/`tbx` intrinsics to shufflevector if the mask is constant, and
746/// at most two source operands are actually referenced.
747static Instruction *simplifyNeonTbl(IntrinsicInst &II, InstCombiner &IC,
748 bool IsExtension) {
749 // Bail out if the mask is not a constant.
750 auto *C = dyn_cast<Constant>(Val: II.getArgOperand(i: II.arg_size() - 1));
751 if (!C)
752 return nullptr;
753
754 auto *RetTy = cast<FixedVectorType>(Val: II.getType());
755 unsigned NumIndexes = RetTy->getNumElements();
756
757 // Only perform this transformation for <8 x i8> and <16 x i8> vector types.
758 if (!RetTy->getElementType()->isIntegerTy(BitWidth: 8) ||
759 (NumIndexes != 8 && NumIndexes != 16))
760 return nullptr;
761
762 // For tbx instructions, the first argument is the "fallback" vector, which
763 // has the same length as the mask and return type.
764 unsigned int StartIndex = (unsigned)IsExtension;
765 auto *SourceTy =
766 cast<FixedVectorType>(Val: II.getArgOperand(i: StartIndex)->getType());
767 // Note that the element count of each source vector does *not* need to be the
768 // same as the element count of the return type and mask! All source vectors
769 // must have the same element count as each other, though.
770 unsigned NumElementsPerSource = SourceTy->getNumElements();
771
772 // There are no tbl/tbx intrinsics for which the destination size exceeds the
773 // source size. However, our definitions of the intrinsics, at least in
774 // IntrinsicsAArch64.td, allow for arbitrary destination vector sizes, so it
775 // *could* technically happen.
776 if (NumIndexes > NumElementsPerSource)
777 return nullptr;
778
779 // The tbl/tbx intrinsics take several source operands followed by a mask
780 // operand.
781 unsigned int NumSourceOperands = II.arg_size() - 1 - (unsigned)IsExtension;
782
783 // Map input operands to shuffle indices. This also helpfully deduplicates the
784 // input arguments, in case the same value is passed as an argument multiple
785 // times.
786 SmallDenseMap<Value *, unsigned, 2> ValueToShuffleSlot;
787 Value *ShuffleOperands[2] = {PoisonValue::get(T: SourceTy),
788 PoisonValue::get(T: SourceTy)};
789
790 int Indexes[16];
791 for (unsigned I = 0; I < NumIndexes; ++I) {
792 Constant *COp = C->getAggregateElement(Elt: I);
793
794 if (!COp || (!isa<UndefValue>(Val: COp) && !isa<ConstantInt>(Val: COp)))
795 return nullptr;
796
797 if (isa<UndefValue>(Val: COp)) {
798 Indexes[I] = -1;
799 continue;
800 }
801
802 uint64_t Index = cast<ConstantInt>(Val: COp)->getZExtValue();
803 // The index of the input argument that this index references (0 = first
804 // source argument, etc).
805 unsigned SourceOperandIndex = Index / NumElementsPerSource;
806 // The index of the element at that source operand.
807 unsigned SourceOperandElementIndex = Index % NumElementsPerSource;
808
809 Value *SourceOperand;
810 if (SourceOperandIndex >= NumSourceOperands) {
811 // This index is out of bounds. Map it to index into either the fallback
812 // vector (tbx) or vector of zeroes (tbl).
813 SourceOperandIndex = NumSourceOperands;
814 if (IsExtension) {
815 // For out-of-bounds indices in tbx, choose the `I`th element of the
816 // fallback.
817 SourceOperand = II.getArgOperand(i: 0);
818 SourceOperandElementIndex = I;
819 } else {
820 // Otherwise, choose some element from the dummy vector of zeroes (we'll
821 // always choose the first).
822 SourceOperand = Constant::getNullValue(Ty: SourceTy);
823 SourceOperandElementIndex = 0;
824 }
825 } else {
826 SourceOperand = II.getArgOperand(i: SourceOperandIndex + StartIndex);
827 }
828
829 // The source operand may be the fallback vector, which may not have the
830 // same number of elements as the source vector. In that case, we *could*
831 // choose to extend its length with another shufflevector, but it's simpler
832 // to just bail instead.
833 if (cast<FixedVectorType>(Val: SourceOperand->getType())->getNumElements() !=
834 NumElementsPerSource)
835 return nullptr;
836
837 // We now know the source operand referenced by this index. Make it a
838 // shufflevector operand, if it isn't already.
839 unsigned NumSlots = ValueToShuffleSlot.size();
840 // This shuffle references more than two sources, and hence cannot be
841 // represented as a shufflevector.
842 if (NumSlots == 2 && !ValueToShuffleSlot.contains(Val: SourceOperand))
843 return nullptr;
844
845 auto [It, Inserted] =
846 ValueToShuffleSlot.try_emplace(Key: SourceOperand, Args&: NumSlots);
847 if (Inserted)
848 ShuffleOperands[It->getSecond()] = SourceOperand;
849
850 unsigned RemappedIndex =
851 (It->getSecond() * NumElementsPerSource) + SourceOperandElementIndex;
852 Indexes[I] = RemappedIndex;
853 }
854
855 Value *Shuf = IC.Builder.CreateShuffleVector(
856 V1: ShuffleOperands[0], V2: ShuffleOperands[1], Mask: ArrayRef(Indexes, NumIndexes));
857 return IC.replaceInstUsesWith(I&: II, V: Shuf);
858}
859
860// Returns true iff the 2 intrinsics have the same operands, limiting the
861// comparison to the first NumOperands.
862static bool haveSameOperands(const IntrinsicInst &I, const IntrinsicInst &E,
863 unsigned NumOperands) {
864 assert(I.arg_size() >= NumOperands && "Not enough operands");
865 assert(E.arg_size() >= NumOperands && "Not enough operands");
866 for (unsigned i = 0; i < NumOperands; i++)
867 if (I.getArgOperand(i) != E.getArgOperand(i))
868 return false;
869 return true;
870}
871
872// Remove trivially empty start/end intrinsic ranges, i.e. a start
873// immediately followed by an end (ignoring debuginfo or other
874// start/end intrinsics in between). As this handles only the most trivial
875// cases, tracking the nesting level is not needed:
876//
877// call @llvm.foo.start(i1 0)
878// call @llvm.foo.start(i1 0) ; This one won't be skipped: it will be removed
879// call @llvm.foo.end(i1 0)
880// call @llvm.foo.end(i1 0) ; &I
881static bool
882removeTriviallyEmptyRange(IntrinsicInst &EndI, InstCombinerImpl &IC,
883 std::function<bool(const IntrinsicInst &)> IsStart) {
884 // We start from the end intrinsic and scan backwards, so that InstCombine
885 // has already processed (and potentially removed) all the instructions
886 // before the end intrinsic.
887 BasicBlock::reverse_iterator BI(EndI), BE(EndI.getParent()->rend());
888 for (; BI != BE; ++BI) {
889 if (auto *I = dyn_cast<IntrinsicInst>(Val: &*BI)) {
890 if (I->isDebugOrPseudoInst() ||
891 I->getIntrinsicID() == EndI.getIntrinsicID())
892 continue;
893 if (IsStart(*I)) {
894 if (haveSameOperands(I: EndI, E: *I, NumOperands: EndI.arg_size())) {
895 IC.eraseInstFromFunction(I&: *I);
896 IC.eraseInstFromFunction(I&: EndI);
897 return true;
898 }
899 // Skip start intrinsics that don't pair with this end intrinsic.
900 continue;
901 }
902 }
903 break;
904 }
905
906 return false;
907}
908
909Instruction *InstCombinerImpl::visitVAEndInst(VAEndInst &I) {
910 removeTriviallyEmptyRange(EndI&: I, IC&: *this, IsStart: [&I](const IntrinsicInst &II) {
911 // Bail out on the case where the source va_list of a va_copy is destroyed
912 // immediately by a follow-up va_end.
913 return II.getIntrinsicID() == Intrinsic::vastart ||
914 (II.getIntrinsicID() == Intrinsic::vacopy &&
915 I.getArgOperand(i: 0) != II.getArgOperand(i: 1));
916 });
917 return nullptr;
918}
919
920static CallInst *canonicalizeConstantArg0ToArg1(CallInst &Call) {
921 assert(Call.arg_size() > 1 && "Need at least 2 args to swap");
922 Value *Arg0 = Call.getArgOperand(i: 0), *Arg1 = Call.getArgOperand(i: 1);
923 if (isa<Constant>(Val: Arg0) && !isa<Constant>(Val: Arg1)) {
924 Call.setArgOperand(i: 0, v: Arg1);
925 Call.setArgOperand(i: 1, v: Arg0);
926 AttributeList CallAttr = Call.getAttributes();
927 AttributeSet LHSAttr = CallAttr.getParamAttrs(ArgNo: 0);
928 AttributeSet RHSAttr = CallAttr.getParamAttrs(ArgNo: 1);
929 LLVMContext &Ctx = Call.getContext();
930 Call.setAttributes(CallAttr
931 .setAttributesAtIndex(
932 C&: Ctx, Index: AttributeList::FirstArgIndex + 0, Attrs: RHSAttr)
933 .setAttributesAtIndex(
934 C&: Ctx, Index: AttributeList::FirstArgIndex + 1, Attrs: LHSAttr));
935 return &Call;
936 }
937 return nullptr;
938}
939
940/// Creates a result tuple for an overflow intrinsic \p II with a given
941/// \p Result and a constant \p Overflow value.
942static Instruction *createOverflowTuple(IntrinsicInst *II, Value *Result,
943 Constant *Overflow) {
944 Constant *V[] = {PoisonValue::get(T: Result->getType()), Overflow};
945 StructType *ST = cast<StructType>(Val: II->getType());
946 Constant *Struct = ConstantStruct::get(T: ST, V);
947 return InsertValueInst::Create(Agg: Struct, Val: Result, Idxs: 0);
948}
949
950Instruction *
951InstCombinerImpl::foldIntrinsicWithOverflowCommon(IntrinsicInst *II) {
952 WithOverflowInst *WO = cast<WithOverflowInst>(Val: II);
953 Value *OperationResult = nullptr;
954 Constant *OverflowResult = nullptr;
955 if (OptimizeOverflowCheck(BinaryOp: WO->getBinaryOp(), IsSigned: WO->isSigned(), LHS: WO->getLHS(),
956 RHS: WO->getRHS(), CtxI&: *WO, OperationResult, OverflowResult))
957 return createOverflowTuple(II: WO, Result: OperationResult, Overflow: OverflowResult);
958
959 // See whether we can optimize the overflow check with assumption information.
960 for (User *U : WO->users()) {
961 if (!match(V: U, P: m_ExtractValue<1>(V: m_Value())))
962 continue;
963
964 for (auto &AssumeVH : AC.assumptionsFor(V: U)) {
965 if (!AssumeVH)
966 continue;
967 CallInst *I = cast<CallInst>(Val&: AssumeVH);
968 if (!match(V: I->getArgOperand(i: 0), P: m_Not(V: m_Specific(V: U))))
969 continue;
970 if (!isValidAssumeForContext(I, CxtI: II, /*DT=*/nullptr,
971 /*AllowEphemerals=*/true))
972 continue;
973 Value *Result =
974 Builder.CreateBinOp(Opc: WO->getBinaryOp(), LHS: WO->getLHS(), RHS: WO->getRHS());
975 Result->takeName(V: WO);
976 if (auto *Inst = dyn_cast<Instruction>(Val: Result)) {
977 if (WO->isSigned())
978 Inst->setHasNoSignedWrap();
979 else
980 Inst->setHasNoUnsignedWrap();
981 }
982 return createOverflowTuple(II: WO, Result,
983 Overflow: ConstantInt::getFalse(Ty: U->getType()));
984 }
985 }
986
987 return nullptr;
988}
989
990static bool inputDenormalIsIEEE(const Function &F, const Type *Ty) {
991 Ty = Ty->getScalarType();
992 return F.getDenormalMode(FPType: Ty->getFltSemantics()).Input == DenormalMode::IEEE;
993}
994
995static bool inputDenormalIsDAZ(const Function &F, const Type *Ty) {
996 Ty = Ty->getScalarType();
997 return F.getDenormalMode(FPType: Ty->getFltSemantics()).inputsAreZero();
998}
999
1000/// \returns the compare predicate type if the test performed by
1001/// llvm.is.fpclass(x, \p Mask) is equivalent to fcmp o__ x, 0.0 with the
1002/// floating-point environment assumed for \p F for type \p Ty
1003static FCmpInst::Predicate fpclassTestIsFCmp0(FPClassTest Mask,
1004 const Function &F, Type *Ty) {
1005 switch (static_cast<unsigned>(Mask)) {
1006 case fcZero:
1007 if (inputDenormalIsIEEE(F, Ty))
1008 return FCmpInst::FCMP_OEQ;
1009 break;
1010 case fcZero | fcSubnormal:
1011 if (inputDenormalIsDAZ(F, Ty))
1012 return FCmpInst::FCMP_OEQ;
1013 break;
1014 case fcPositive | fcNegZero:
1015 if (inputDenormalIsIEEE(F, Ty))
1016 return FCmpInst::FCMP_OGE;
1017 break;
1018 case fcPositive | fcNegZero | fcNegSubnormal:
1019 if (inputDenormalIsDAZ(F, Ty))
1020 return FCmpInst::FCMP_OGE;
1021 break;
1022 case fcPosSubnormal | fcPosNormal | fcPosInf:
1023 if (inputDenormalIsIEEE(F, Ty))
1024 return FCmpInst::FCMP_OGT;
1025 break;
1026 case fcNegative | fcPosZero:
1027 if (inputDenormalIsIEEE(F, Ty))
1028 return FCmpInst::FCMP_OLE;
1029 break;
1030 case fcNegative | fcPosZero | fcPosSubnormal:
1031 if (inputDenormalIsDAZ(F, Ty))
1032 return FCmpInst::FCMP_OLE;
1033 break;
1034 case fcNegSubnormal | fcNegNormal | fcNegInf:
1035 if (inputDenormalIsIEEE(F, Ty))
1036 return FCmpInst::FCMP_OLT;
1037 break;
1038 case fcPosNormal | fcPosInf:
1039 if (inputDenormalIsDAZ(F, Ty))
1040 return FCmpInst::FCMP_OGT;
1041 break;
1042 case fcNegNormal | fcNegInf:
1043 if (inputDenormalIsDAZ(F, Ty))
1044 return FCmpInst::FCMP_OLT;
1045 break;
1046 case ~fcZero & ~fcNan:
1047 if (inputDenormalIsIEEE(F, Ty))
1048 return FCmpInst::FCMP_ONE;
1049 break;
1050 case ~(fcZero | fcSubnormal) & ~fcNan:
1051 if (inputDenormalIsDAZ(F, Ty))
1052 return FCmpInst::FCMP_ONE;
1053 break;
1054 default:
1055 break;
1056 }
1057
1058 return FCmpInst::BAD_FCMP_PREDICATE;
1059}
1060
1061Instruction *InstCombinerImpl::foldIntrinsicIsFPClass(IntrinsicInst &II) {
1062 Value *Src0 = II.getArgOperand(i: 0);
1063 Value *Src1 = II.getArgOperand(i: 1);
1064 const ConstantInt *CMask = cast<ConstantInt>(Val: Src1);
1065 FPClassTest Mask = static_cast<FPClassTest>(CMask->getZExtValue());
1066 const bool IsUnordered = (Mask & fcNan) == fcNan;
1067 const bool IsOrdered = (Mask & fcNan) == fcNone;
1068 const FPClassTest OrderedMask = Mask & ~fcNan;
1069 const FPClassTest OrderedInvertedMask = ~OrderedMask & ~fcNan;
1070
1071 const bool IsStrict =
1072 II.getFunction()->getAttributes().hasFnAttr(Kind: Attribute::StrictFP);
1073
1074 Value *FNegSrc;
1075 // is.fpclass (fneg x), mask -> is.fpclass x, (fneg mask)
1076 if (match(V: Src0, P: m_FNeg(X: m_Value(V&: FNegSrc))))
1077 return CallInst::Create(
1078 Func: II.getCalledFunction(),
1079 Args: {FNegSrc, ConstantInt::get(Ty: Src1->getType(), V: fneg(Mask))});
1080
1081 Value *FAbsSrc;
1082 if (match(V: Src0, P: m_FAbs(Op0: m_Value(V&: FAbsSrc))))
1083 return CallInst::Create(
1084 Func: II.getCalledFunction(),
1085 Args: {FAbsSrc, ConstantInt::get(Ty: Src1->getType(), V: inverse_fabs(Mask))});
1086
1087 if ((OrderedMask == fcInf || OrderedInvertedMask == fcInf) &&
1088 (IsOrdered || IsUnordered) && !IsStrict) {
1089 // is.fpclass(x, fcInf) -> fcmp oeq fabs(x), +inf
1090 // is.fpclass(x, ~fcInf) -> fcmp one fabs(x), +inf
1091 // is.fpclass(x, fcInf|fcNan) -> fcmp ueq fabs(x), +inf
1092 // is.fpclass(x, ~(fcInf|fcNan)) -> fcmp une fabs(x), +inf
1093 Constant *Inf = ConstantFP::getInfinity(Ty: Src0->getType());
1094 FCmpInst::Predicate Pred =
1095 IsUnordered ? FCmpInst::FCMP_UEQ : FCmpInst::FCMP_OEQ;
1096 if (OrderedInvertedMask == fcInf)
1097 Pred = IsUnordered ? FCmpInst::FCMP_UNE : FCmpInst::FCMP_ONE;
1098
1099 Value *Fabs = Builder.CreateFAbs(V: Src0);
1100 Value *CmpInf = Builder.CreateFCmp(P: Pred, LHS: Fabs, RHS: Inf);
1101 CmpInf->takeName(V: &II);
1102 return replaceInstUsesWith(I&: II, V: CmpInf);
1103 }
1104
1105 if ((OrderedMask == fcPosInf || OrderedMask == fcNegInf) &&
1106 (IsOrdered || IsUnordered) && !IsStrict) {
1107 // is.fpclass(x, fcPosInf) -> fcmp oeq x, +inf
1108 // is.fpclass(x, fcNegInf) -> fcmp oeq x, -inf
1109 // is.fpclass(x, fcPosInf|fcNan) -> fcmp ueq x, +inf
1110 // is.fpclass(x, fcNegInf|fcNan) -> fcmp ueq x, -inf
1111 Constant *Inf =
1112 ConstantFP::getInfinity(Ty: Src0->getType(), Negative: OrderedMask == fcNegInf);
1113 Value *EqInf = IsUnordered ? Builder.CreateFCmpUEQ(LHS: Src0, RHS: Inf)
1114 : Builder.CreateFCmpOEQ(LHS: Src0, RHS: Inf);
1115
1116 EqInf->takeName(V: &II);
1117 return replaceInstUsesWith(I&: II, V: EqInf);
1118 }
1119
1120 if ((OrderedInvertedMask == fcPosInf || OrderedInvertedMask == fcNegInf) &&
1121 (IsOrdered || IsUnordered) && !IsStrict) {
1122 // is.fpclass(x, ~fcPosInf) -> fcmp one x, +inf
1123 // is.fpclass(x, ~fcNegInf) -> fcmp one x, -inf
1124 // is.fpclass(x, ~fcPosInf|fcNan) -> fcmp une x, +inf
1125 // is.fpclass(x, ~fcNegInf|fcNan) -> fcmp une x, -inf
1126 Constant *Inf = ConstantFP::getInfinity(Ty: Src0->getType(),
1127 Negative: OrderedInvertedMask == fcNegInf);
1128 Value *NeInf = IsUnordered ? Builder.CreateFCmpUNE(LHS: Src0, RHS: Inf)
1129 : Builder.CreateFCmpONE(LHS: Src0, RHS: Inf);
1130 NeInf->takeName(V: &II);
1131 return replaceInstUsesWith(I&: II, V: NeInf);
1132 }
1133
1134 if (Mask == fcNan && !IsStrict) {
1135 // Equivalent of isnan. Replace with standard fcmp if we don't care about FP
1136 // exceptions.
1137 Value *IsNan =
1138 Builder.CreateFCmpUNO(LHS: Src0, RHS: ConstantFP::getZero(Ty: Src0->getType()));
1139 IsNan->takeName(V: &II);
1140 return replaceInstUsesWith(I&: II, V: IsNan);
1141 }
1142
1143 if (Mask == (~fcNan & fcAllFlags) && !IsStrict) {
1144 // Equivalent of !isnan. Replace with standard fcmp.
1145 Value *FCmp =
1146 Builder.CreateFCmpORD(LHS: Src0, RHS: ConstantFP::getZero(Ty: Src0->getType()));
1147 FCmp->takeName(V: &II);
1148 return replaceInstUsesWith(I&: II, V: FCmp);
1149 }
1150
1151 FCmpInst::Predicate PredType = FCmpInst::BAD_FCMP_PREDICATE;
1152
1153 // Try to replace with an fcmp with 0
1154 //
1155 // is.fpclass(x, fcZero) -> fcmp oeq x, 0.0
1156 // is.fpclass(x, fcZero | fcNan) -> fcmp ueq x, 0.0
1157 // is.fpclass(x, ~fcZero & ~fcNan) -> fcmp one x, 0.0
1158 // is.fpclass(x, ~fcZero) -> fcmp une x, 0.0
1159 //
1160 // is.fpclass(x, fcPosSubnormal | fcPosNormal | fcPosInf) -> fcmp ogt x, 0.0
1161 // is.fpclass(x, fcPositive | fcNegZero) -> fcmp oge x, 0.0
1162 //
1163 // is.fpclass(x, fcNegSubnormal | fcNegNormal | fcNegInf) -> fcmp olt x, 0.0
1164 // is.fpclass(x, fcNegative | fcPosZero) -> fcmp ole x, 0.0
1165 //
1166 if (!IsStrict && (IsOrdered || IsUnordered) &&
1167 (PredType = fpclassTestIsFCmp0(Mask: OrderedMask, F: *II.getFunction(),
1168 Ty: Src0->getType())) !=
1169 FCmpInst::BAD_FCMP_PREDICATE) {
1170 Constant *Zero = ConstantFP::getZero(Ty: Src0->getType());
1171 // Equivalent of == 0.
1172 Value *FCmp = Builder.CreateFCmp(
1173 P: IsUnordered ? FCmpInst::getUnorderedPredicate(Pred: PredType) : PredType,
1174 LHS: Src0, RHS: Zero);
1175
1176 FCmp->takeName(V: &II);
1177 return replaceInstUsesWith(I&: II, V: FCmp);
1178 }
1179
1180 KnownFPClass Known =
1181 computeKnownFPClass(V: Src0, InterestedClasses: Mask, SQ: SQ.getWithInstruction(I: &II));
1182
1183 // Clear test bits we know must be false from the source value.
1184 // fp_class (nnan x), qnan|snan|other -> fp_class (nnan x), other
1185 // fp_class (ninf x), ninf|pinf|other -> fp_class (ninf x), other
1186 if ((Mask & Known.KnownFPClasses) != Mask) {
1187 II.setArgOperand(
1188 i: 1, v: ConstantInt::get(Ty: Src1->getType(), V: Mask & Known.KnownFPClasses));
1189 return &II;
1190 }
1191
1192 // If none of the tests which can return false are possible, fold to true.
1193 // fp_class (nnan x), ~(qnan|snan) -> true
1194 // fp_class (ninf x), ~(ninf|pinf) -> true
1195 if (Mask == Known.KnownFPClasses)
1196 return replaceInstUsesWith(I&: II, V: ConstantInt::get(Ty: II.getType(), V: true));
1197
1198 return nullptr;
1199}
1200
1201static std::optional<bool> getKnownSign(Value *Op, const SimplifyQuery &SQ) {
1202 KnownBits Known = computeKnownBits(V: Op, Q: SQ);
1203 if (Known.isNonNegative())
1204 return false;
1205 if (Known.isNegative())
1206 return true;
1207
1208 Value *X, *Y;
1209 if (match(V: Op, P: m_NSWSub(L: m_Value(V&: X), R: m_Value(V&: Y))))
1210 return isImpliedByDomCondition(Pred: ICmpInst::ICMP_SLT, LHS: X, RHS: Y, ContextI: SQ.CxtI, DL: SQ.DL);
1211
1212 return std::nullopt;
1213}
1214
1215static std::optional<bool> getKnownSignOrZero(Value *Op,
1216 const SimplifyQuery &SQ) {
1217 if (std::optional<bool> Sign = getKnownSign(Op, SQ))
1218 return Sign;
1219
1220 Value *X, *Y;
1221 if (match(V: Op, P: m_NSWSub(L: m_Value(V&: X), R: m_Value(V&: Y))))
1222 return isImpliedByDomCondition(Pred: ICmpInst::ICMP_SLE, LHS: X, RHS: Y, ContextI: SQ.CxtI, DL: SQ.DL);
1223
1224 return std::nullopt;
1225}
1226
1227/// Return true if two values \p Op0 and \p Op1 are known to have the same sign.
1228static bool signBitMustBeTheSame(Value *Op0, Value *Op1,
1229 const SimplifyQuery &SQ) {
1230 std::optional<bool> Known1 = getKnownSign(Op: Op1, SQ);
1231 if (!Known1)
1232 return false;
1233 std::optional<bool> Known0 = getKnownSign(Op: Op0, SQ);
1234 if (!Known0)
1235 return false;
1236 return *Known0 == *Known1;
1237}
1238
1239// Determines if ldexp(ldexp(x, a), b) -> ldexp(x, sadd.sat(a, b)) is safe.
1240//
1241// This is true if, when the add saturates, the resulting ldexp is guaranteed to
1242// produce 0 or inf.
1243static bool ldexpSaturatingAddIsSafe(Type *FpTy, Type *ExpTy) {
1244 const fltSemantics &FltSem = FpTy->getScalarType()->getFltSemantics();
1245 if (!APFloat::semanticsHasInf(FltSem))
1246 return false;
1247
1248 // Cap ExpBits at 32 because scalbn takes an int. This is sufficient for any
1249 // reasonable fp type (for example, `double` only has 11 exponent bits).
1250 unsigned ExpBits = std::min(a: ExpTy->getScalarSizeInBits(), b: 32u);
1251 int SignedMax = static_cast<int>(maxIntN(N: ExpBits));
1252 int SignedMin = static_cast<int>(minIntN(N: ExpBits));
1253 APFloat ScaledUp = scalbn(X: APFloat::getSmallest(Sem: FltSem), Exp: SignedMax,
1254 RM: APFloat::rmNearestTiesToEven);
1255 APFloat ScaledDown = scalbn(X: APFloat::getLargest(Sem: FltSem), Exp: SignedMin,
1256 RM: APFloat::rmNearestTiesToEven);
1257 return ScaledUp.isInfinity() && ScaledDown.isZero();
1258}
1259
1260/// Try to canonicalize min/max(X + C0, C1) as min/max(X, C1 - C0) + C0. This
1261/// can trigger other combines.
1262static Instruction *moveAddAfterMinMax(IntrinsicInst *II,
1263 InstCombiner::BuilderTy &Builder) {
1264 Intrinsic::ID MinMaxID = II->getIntrinsicID();
1265 assert((MinMaxID == Intrinsic::smax || MinMaxID == Intrinsic::smin ||
1266 MinMaxID == Intrinsic::umax || MinMaxID == Intrinsic::umin) &&
1267 "Expected a min or max intrinsic");
1268
1269 // TODO: Match vectors with undef elements, but undef may not propagate.
1270 Value *Op0 = II->getArgOperand(i: 0), *Op1 = II->getArgOperand(i: 1);
1271 Value *X;
1272 const APInt *C0, *C1;
1273 if (!match(V: Op0, P: m_OneUse(SubPattern: m_Add(L: m_Value(V&: X), R: m_APInt(Res&: C0)))) ||
1274 !match(V: Op1, P: m_APInt(Res&: C1)))
1275 return nullptr;
1276
1277 // Check for necessary no-wrap and overflow constraints.
1278 bool IsSigned = MinMaxID == Intrinsic::smax || MinMaxID == Intrinsic::smin;
1279 auto *Add = cast<BinaryOperator>(Val: Op0);
1280 if ((IsSigned && !Add->hasNoSignedWrap()) ||
1281 (!IsSigned && !Add->hasNoUnsignedWrap()))
1282 return nullptr;
1283
1284 // If the constant difference overflows, then instsimplify should reduce the
1285 // min/max to the add or C1.
1286 bool Overflow;
1287 APInt CDiff =
1288 IsSigned ? C1->ssub_ov(RHS: *C0, Overflow) : C1->usub_ov(RHS: *C0, Overflow);
1289 assert(!Overflow && "Expected simplify of min/max");
1290
1291 // min/max (add X, C0), C1 --> add (min/max X, C1 - C0), C0
1292 // Note: the "mismatched" no-overflow setting does not propagate.
1293 Constant *NewMinMaxC = ConstantInt::get(Ty: II->getType(), V: CDiff);
1294 Value *NewMinMax = Builder.CreateBinaryIntrinsic(ID: MinMaxID, LHS: X, RHS: NewMinMaxC);
1295 return IsSigned ? BinaryOperator::CreateNSWAdd(V1: NewMinMax, V2: Add->getOperand(i_nocapture: 1))
1296 : BinaryOperator::CreateNUWAdd(V1: NewMinMax, V2: Add->getOperand(i_nocapture: 1));
1297}
1298/// Match a sadd_sat or ssub_sat which is using min/max to clamp the value.
1299Instruction *InstCombinerImpl::matchSAddSubSat(IntrinsicInst &MinMax1) {
1300 Type *Ty = MinMax1.getType();
1301
1302 // We are looking for a tree of:
1303 // max(INT_MIN, min(INT_MAX, add(sext(A), sext(B))))
1304 // Where the min and max could be reversed
1305 Instruction *MinMax2;
1306 BinaryOperator *AddSub;
1307 const APInt *MinValue, *MaxValue;
1308 if (match(V: &MinMax1, P: m_SMin(Op0: m_Instruction(I&: MinMax2), Op1: m_APInt(Res&: MaxValue)))) {
1309 if (!match(V: MinMax2, P: m_SMax(Op0: m_BinOp(I&: AddSub), Op1: m_APInt(Res&: MinValue))))
1310 return nullptr;
1311 } else if (match(V: &MinMax1,
1312 P: m_SMax(Op0: m_Instruction(I&: MinMax2), Op1: m_APInt(Res&: MinValue)))) {
1313 if (!match(V: MinMax2, P: m_SMin(Op0: m_BinOp(I&: AddSub), Op1: m_APInt(Res&: MaxValue))))
1314 return nullptr;
1315 } else
1316 return nullptr;
1317
1318 // Check that the constants clamp a saturate, and that the new type would be
1319 // sensible to convert to.
1320 if (!(*MaxValue + 1).isPowerOf2() || -*MinValue != *MaxValue + 1)
1321 return nullptr;
1322 // In what bitwidth can this be treated as saturating arithmetics?
1323 unsigned NewBitWidth = (*MaxValue + 1).logBase2() + 1;
1324 // FIXME: This isn't quite right for vectors, but using the scalar type is a
1325 // good first approximation for what should be done there.
1326 if (!shouldChangeType(FromBitWidth: Ty->getScalarType()->getIntegerBitWidth(), ToBitWidth: NewBitWidth))
1327 return nullptr;
1328
1329 // Also make sure that the inner min/max and the add/sub have one use.
1330 if (!MinMax2->hasOneUse() || !AddSub->hasOneUse())
1331 return nullptr;
1332
1333 // Create the new type (which can be a vector type)
1334 Type *NewTy = Ty->getWithNewBitWidth(NewBitWidth);
1335
1336 Intrinsic::ID IntrinsicID;
1337 if (AddSub->getOpcode() == Instruction::Add)
1338 IntrinsicID = Intrinsic::sadd_sat;
1339 else if (AddSub->getOpcode() == Instruction::Sub)
1340 IntrinsicID = Intrinsic::ssub_sat;
1341 else
1342 return nullptr;
1343
1344 // The two operands of the add/sub must be nsw-truncatable to the NewTy. This
1345 // is usually achieved via a sext from a smaller type.
1346 if (ComputeMaxSignificantBits(Op: AddSub->getOperand(i_nocapture: 0), CxtI: AddSub) > NewBitWidth ||
1347 ComputeMaxSignificantBits(Op: AddSub->getOperand(i_nocapture: 1), CxtI: AddSub) > NewBitWidth)
1348 return nullptr;
1349
1350 // Finally create and return the sat intrinsic, truncated to the new type
1351 Value *AT = Builder.CreateTrunc(V: AddSub->getOperand(i_nocapture: 0), DestTy: NewTy);
1352 Value *BT = Builder.CreateTrunc(V: AddSub->getOperand(i_nocapture: 1), DestTy: NewTy);
1353 Value *Sat = Builder.CreateIntrinsic(ID: IntrinsicID, OverloadTypes: NewTy, Args: {AT, BT});
1354 return CastInst::Create(Instruction::SExt, S: Sat, Ty);
1355}
1356
1357
1358/// If we have a clamp pattern like max (min X, 42), 41 -- where the output
1359/// can only be one of two possible constant values -- turn that into a select
1360/// of constants.
1361static Instruction *foldClampRangeOfTwo(IntrinsicInst *II,
1362 InstCombiner::BuilderTy &Builder) {
1363 Value *I0 = II->getArgOperand(i: 0), *I1 = II->getArgOperand(i: 1);
1364 Value *X;
1365 const APInt *C0, *C1;
1366 if (!match(V: I1, P: m_APInt(Res&: C1)) || !I0->hasOneUse())
1367 return nullptr;
1368
1369 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
1370 switch (II->getIntrinsicID()) {
1371 case Intrinsic::smax:
1372 if (match(V: I0, P: m_SMin(Op0: m_Value(V&: X), Op1: m_APInt(Res&: C0))) && *C0 == *C1 + 1)
1373 Pred = ICmpInst::ICMP_SGT;
1374 break;
1375 case Intrinsic::smin:
1376 if (match(V: I0, P: m_SMax(Op0: m_Value(V&: X), Op1: m_APInt(Res&: C0))) && *C1 == *C0 + 1)
1377 Pred = ICmpInst::ICMP_SLT;
1378 break;
1379 case Intrinsic::umax:
1380 if (match(V: I0, P: m_UMin(Op0: m_Value(V&: X), Op1: m_APInt(Res&: C0))) && *C0 == *C1 + 1)
1381 Pred = ICmpInst::ICMP_UGT;
1382 break;
1383 case Intrinsic::umin:
1384 if (match(V: I0, P: m_UMax(Op0: m_Value(V&: X), Op1: m_APInt(Res&: C0))) && *C1 == *C0 + 1)
1385 Pred = ICmpInst::ICMP_ULT;
1386 break;
1387 default:
1388 llvm_unreachable("Expected min/max intrinsic");
1389 }
1390 if (Pred == CmpInst::BAD_ICMP_PREDICATE)
1391 return nullptr;
1392
1393 // max (min X, 42), 41 --> X > 41 ? 42 : 41
1394 // min (max X, 42), 43 --> X < 43 ? 42 : 43
1395 Value *Cmp = Builder.CreateICmp(P: Pred, LHS: X, RHS: I1);
1396 return SelectInst::Create(C: Cmp, S1: ConstantInt::get(Ty: II->getType(), V: *C0), S2: I1);
1397}
1398
1399/// If this min/max has a constant operand and an operand that is a matching
1400/// min/max with a constant operand, constant-fold the 2 constant operands.
1401static Value *reassociateMinMaxWithConstants(IntrinsicInst *II,
1402 IRBuilderBase &Builder,
1403 const SimplifyQuery &SQ) {
1404 Intrinsic::ID MinMaxID = II->getIntrinsicID();
1405 auto *LHS = dyn_cast<MinMaxIntrinsic>(Val: II->getArgOperand(i: 0));
1406 if (!LHS)
1407 return nullptr;
1408
1409 Constant *C0, *C1;
1410 if (!match(V: LHS->getArgOperand(i: 1), P: m_ImmConstant(C&: C0)) ||
1411 !match(V: II->getArgOperand(i: 1), P: m_ImmConstant(C&: C1)))
1412 return nullptr;
1413
1414 // max (max X, C0), C1 --> max X, (max C0, C1)
1415 // min (min X, C0), C1 --> min X, (min C0, C1)
1416 // umax (smax X, nneg C0), nneg C1 --> smax X, (umax C0, C1)
1417 // smin (umin X, nneg C0), nneg C1 --> umin X, (smin C0, C1)
1418 Intrinsic::ID InnerMinMaxID = LHS->getIntrinsicID();
1419 if (InnerMinMaxID != MinMaxID &&
1420 !(((MinMaxID == Intrinsic::umax && InnerMinMaxID == Intrinsic::smax) ||
1421 (MinMaxID == Intrinsic::smin && InnerMinMaxID == Intrinsic::umin)) &&
1422 isKnownNonNegative(V: C0, SQ) && isKnownNonNegative(V: C1, SQ)))
1423 return nullptr;
1424
1425 ICmpInst::Predicate Pred = MinMaxIntrinsic::getPredicate(ID: MinMaxID);
1426 Value *CondC = Builder.CreateICmp(P: Pred, LHS: C0, RHS: C1);
1427 Value *NewC = Builder.CreateSelect(C: CondC, True: C0, False: C1);
1428 return Builder.CreateIntrinsic(ID: InnerMinMaxID, OverloadTypes: II->getType(),
1429 Args: {LHS->getArgOperand(i: 0), NewC});
1430}
1431
1432/// If this min/max has a matching min/max operand with a constant, try to push
1433/// the constant operand into this instruction. This can enable more folds.
1434static Instruction *
1435reassociateMinMaxWithConstantInOperand(IntrinsicInst *II,
1436 InstCombiner::BuilderTy &Builder) {
1437 // Match and capture a min/max operand candidate.
1438 Value *X, *Y;
1439 Constant *C;
1440 Instruction *Inner;
1441 if (!match(V: II, P: m_c_MaxOrMin(L: m_OneUse(SubPattern: m_CombineAnd(
1442 Ps: m_Instruction(I&: Inner),
1443 Ps: m_MaxOrMin(Op0: m_Value(V&: X), Op1: m_ImmConstant(C)))),
1444 R: m_Value(V&: Y))))
1445 return nullptr;
1446
1447 // The inner op must match. Check for constants to avoid infinite loops.
1448 Intrinsic::ID MinMaxID = II->getIntrinsicID();
1449 auto *InnerMM = dyn_cast<IntrinsicInst>(Val: Inner);
1450 if (!InnerMM || InnerMM->getIntrinsicID() != MinMaxID ||
1451 match(V: X, P: m_ImmConstant()) || match(V: Y, P: m_ImmConstant()))
1452 return nullptr;
1453
1454 // max (max X, C), Y --> max (max X, Y), C
1455 Function *MinMax = Intrinsic::getOrInsertDeclaration(M: II->getModule(),
1456 id: MinMaxID, OverloadTys: II->getType());
1457 Value *NewInner = Builder.CreateBinaryIntrinsic(ID: MinMaxID, LHS: X, RHS: Y);
1458 NewInner->takeName(V: Inner);
1459 return CallInst::Create(Func: MinMax, Args: {NewInner, C});
1460}
1461
1462/// Reduce a sequence of min/max intrinsics with a common operand.
1463static Instruction *factorizeMinMaxTree(IntrinsicInst *II) {
1464 // Match 3 of the same min/max ops. Example: umin(umin(), umin()).
1465 auto *LHS = dyn_cast<IntrinsicInst>(Val: II->getArgOperand(i: 0));
1466 auto *RHS = dyn_cast<IntrinsicInst>(Val: II->getArgOperand(i: 1));
1467 Intrinsic::ID MinMaxID = II->getIntrinsicID();
1468 if (!LHS || !RHS || LHS->getIntrinsicID() != MinMaxID ||
1469 RHS->getIntrinsicID() != MinMaxID ||
1470 (!LHS->hasOneUse() && !RHS->hasOneUse()))
1471 return nullptr;
1472
1473 Value *A = LHS->getArgOperand(i: 0);
1474 Value *B = LHS->getArgOperand(i: 1);
1475 Value *C = RHS->getArgOperand(i: 0);
1476 Value *D = RHS->getArgOperand(i: 1);
1477
1478 // Look for a common operand.
1479 Value *MinMaxOp = nullptr;
1480 Value *ThirdOp = nullptr;
1481 if (LHS->hasOneUse()) {
1482 // If the LHS is only used in this chain and the RHS is used outside of it,
1483 // reuse the RHS min/max because that will eliminate the LHS.
1484 if (D == A || C == A) {
1485 // min(min(a, b), min(c, a)) --> min(min(c, a), b)
1486 // min(min(a, b), min(a, d)) --> min(min(a, d), b)
1487 MinMaxOp = RHS;
1488 ThirdOp = B;
1489 } else if (D == B || C == B) {
1490 // min(min(a, b), min(c, b)) --> min(min(c, b), a)
1491 // min(min(a, b), min(b, d)) --> min(min(b, d), a)
1492 MinMaxOp = RHS;
1493 ThirdOp = A;
1494 }
1495 } else {
1496 assert(RHS->hasOneUse() && "Expected one-use operand");
1497 // Reuse the LHS. This will eliminate the RHS.
1498 if (D == A || D == B) {
1499 // min(min(a, b), min(c, a)) --> min(min(a, b), c)
1500 // min(min(a, b), min(c, b)) --> min(min(a, b), c)
1501 MinMaxOp = LHS;
1502 ThirdOp = C;
1503 } else if (C == A || C == B) {
1504 // min(min(a, b), min(b, d)) --> min(min(a, b), d)
1505 // min(min(a, b), min(c, b)) --> min(min(a, b), d)
1506 MinMaxOp = LHS;
1507 ThirdOp = D;
1508 }
1509 }
1510
1511 if (!MinMaxOp || !ThirdOp)
1512 return nullptr;
1513
1514 Module *Mod = II->getModule();
1515 Function *MinMax =
1516 Intrinsic::getOrInsertDeclaration(M: Mod, id: MinMaxID, OverloadTys: II->getType());
1517 return CallInst::Create(Func: MinMax, Args: { MinMaxOp, ThirdOp });
1518}
1519
1520/// If all arguments of the intrinsic are unary shuffles with the same mask,
1521/// try to shuffle after the intrinsic.
1522Instruction *
1523InstCombinerImpl::foldShuffledIntrinsicOperands(IntrinsicInst *II) {
1524 if (!II->getType()->isVectorTy() ||
1525 !isTriviallyVectorizable(ID: II->getIntrinsicID()) ||
1526 !II->getCalledFunction()->isSpeculatable())
1527 return nullptr;
1528
1529 Value *X;
1530 Constant *C;
1531 ArrayRef<int> Mask;
1532 auto *NonConstArg = find_if_not(Range: II->args(), P: [&II](Use &Arg) {
1533 return isa<Constant>(Val: Arg.get()) ||
1534 isVectorIntrinsicWithScalarOpAtArg(ID: II->getIntrinsicID(),
1535 ScalarOpdIdx: Arg.getOperandNo(), TTI: nullptr);
1536 });
1537 if (!NonConstArg ||
1538 !match(V: NonConstArg, P: m_Shuffle(v1: m_Value(V&: X), v2: m_Poison(), mask: m_Mask(Mask))))
1539 return nullptr;
1540
1541 // At least 1 operand must be a shuffle with 1 use because we are creating 2
1542 // instructions.
1543 if (none_of(Range: II->args(), P: match_fn(P: m_OneUse(SubPattern: m_Shuffle(v1: m_Value(), v2: m_Value())))))
1544 return nullptr;
1545
1546 // See if all arguments are shuffled with the same mask.
1547 SmallVector<Value *, 4> NewArgs;
1548 Type *SrcTy = X->getType();
1549 for (Use &Arg : II->args()) {
1550 if (isVectorIntrinsicWithScalarOpAtArg(ID: II->getIntrinsicID(),
1551 ScalarOpdIdx: Arg.getOperandNo(), TTI: nullptr))
1552 NewArgs.push_back(Elt: Arg);
1553 else if (match(V: &Arg,
1554 P: m_Shuffle(v1: m_Value(V&: X), v2: m_Poison(), mask: m_SpecificMask(Mask))) &&
1555 X->getType() == SrcTy)
1556 NewArgs.push_back(Elt: X);
1557 else if (match(V: &Arg, P: m_ImmConstant(C))) {
1558 // If it's a constant, try find the constant that would be shuffled to C.
1559 if (Constant *ShuffledC =
1560 unshuffleConstant(ShMask: Mask, C, NewCTy: cast<VectorType>(Val: SrcTy)))
1561 NewArgs.push_back(Elt: ShuffledC);
1562 else
1563 return nullptr;
1564 } else
1565 return nullptr;
1566 }
1567
1568 // intrinsic (shuf X, M), (shuf Y, M), ... --> shuf (intrinsic X, Y, ...), M
1569 Instruction *FPI = isa<FPMathOperator>(Val: II) ? II : nullptr;
1570 // Result type might be a different vector width.
1571 // TODO: Check that the result type isn't widened?
1572 VectorType *ResTy =
1573 VectorType::get(ElementType: II->getType()->getScalarType(), Other: cast<VectorType>(Val: SrcTy));
1574 Value *NewIntrinsic =
1575 Builder.CreateIntrinsic(RetTy: ResTy, ID: II->getIntrinsicID(), Args: NewArgs, FMFSource: FPI);
1576 return new ShuffleVectorInst(NewIntrinsic, Mask);
1577}
1578
1579/// If all arguments of the intrinsic are reverses, try to pull the reverse
1580/// after the intrinsic.
1581Value *InstCombinerImpl::foldReversedIntrinsicOperands(IntrinsicInst *II) {
1582 if (!II->getType()->isVectorTy() ||
1583 !isTriviallyVectorizable(ID: II->getIntrinsicID()))
1584 return nullptr;
1585
1586 // At least 1 operand must be a reverse with 1 use because we are creating 2
1587 // instructions.
1588 if (none_of(Range: II->args(), P: [](Value *V) {
1589 return match(V, P: m_OneUse(SubPattern: m_VecReverse(Op0: m_Value())));
1590 }))
1591 return nullptr;
1592
1593 Value *X;
1594 Constant *C;
1595 SmallVector<Value *> NewArgs;
1596 for (Use &Arg : II->args()) {
1597 if (isVectorIntrinsicWithScalarOpAtArg(ID: II->getIntrinsicID(),
1598 ScalarOpdIdx: Arg.getOperandNo(), TTI: nullptr))
1599 NewArgs.push_back(Elt: Arg);
1600 else if (match(V: &Arg, P: m_VecReverse(Op0: m_Value(V&: X))))
1601 NewArgs.push_back(Elt: X);
1602 else if (isSplatValue(V: Arg))
1603 NewArgs.push_back(Elt: Arg);
1604 else if (match(V: &Arg, P: m_ImmConstant(C)))
1605 NewArgs.push_back(Elt: Builder.CreateVectorReverse(V: C));
1606 else
1607 return nullptr;
1608 }
1609
1610 // intrinsic (reverse X), (reverse Y), ... --> reverse (intrinsic X, Y, ...)
1611 Instruction *FPI = isa<FPMathOperator>(Val: II) ? II : nullptr;
1612 Value *NewIntrinsic = Builder.CreateIntrinsic(
1613 RetTy: II->getType(), ID: II->getIntrinsicID(), Args: NewArgs, FMFSource: FPI);
1614 return Builder.CreateVectorReverse(V: NewIntrinsic);
1615}
1616
1617/// Fold the following cases and accepts bswap and bitreverse intrinsics:
1618/// bswap(logic_op(bswap(x), y)) --> logic_op(x, bswap(y))
1619/// bswap(logic_op(bswap(x), bswap(y))) --> logic_op(x, y) (ignores multiuse)
1620template <Intrinsic::ID IntrID>
1621static Instruction *foldBitOrderCrossLogicOp(Value *V,
1622 InstCombiner::BuilderTy &Builder) {
1623 static_assert(IntrID == Intrinsic::bswap || IntrID == Intrinsic::bitreverse,
1624 "This helper only supports BSWAP and BITREVERSE intrinsics");
1625
1626 Value *X, *Y;
1627 // Find bitwise logic op. Check that it is a BinaryOperator explicitly so we
1628 // don't match ConstantExpr that aren't meaningful for this transform.
1629 if (match(V, P: m_OneUse(SubPattern: m_BitwiseLogic(L: m_Value(V&: X), R: m_Value(V&: Y)))) &&
1630 isa<BinaryOperator>(Val: V)) {
1631 Value *OldReorderX, *OldReorderY;
1632 BinaryOperator::BinaryOps Op = cast<BinaryOperator>(Val: V)->getOpcode();
1633
1634 // If both X and Y are bswap/bitreverse, the transform reduces the number
1635 // of instructions even if there's multiuse.
1636 // If only one operand is bswap/bitreverse, we need to ensure the operand
1637 // have only one use.
1638 if (match(X, m_Intrinsic<IntrID>(m_Value(V&: OldReorderX))) &&
1639 match(Y, m_Intrinsic<IntrID>(m_Value(V&: OldReorderY)))) {
1640 return BinaryOperator::Create(Op, S1: OldReorderX, S2: OldReorderY);
1641 }
1642
1643 if (match(X, m_OneUse(m_Intrinsic<IntrID>(m_Value(V&: OldReorderX))))) {
1644 Value *NewReorder = Builder.CreateUnaryIntrinsic(ID: IntrID, Op: Y);
1645 return BinaryOperator::Create(Op, S1: OldReorderX, S2: NewReorder);
1646 }
1647
1648 if (match(Y, m_OneUse(m_Intrinsic<IntrID>(m_Value(V&: OldReorderY))))) {
1649 Value *NewReorder = Builder.CreateUnaryIntrinsic(ID: IntrID, Op: X);
1650 return BinaryOperator::Create(Op, S1: NewReorder, S2: OldReorderY);
1651 }
1652 }
1653 return nullptr;
1654}
1655
1656/// Helper to match idempotent binary intrinsics, namely, intrinsics where
1657/// `f(f(x, y), y) == f(x, y)` holds.
1658static bool isIdempotentBinaryIntrinsic(Intrinsic::ID IID) {
1659 switch (IID) {
1660 case Intrinsic::smax:
1661 case Intrinsic::smin:
1662 case Intrinsic::umax:
1663 case Intrinsic::umin:
1664 case Intrinsic::maximum:
1665 case Intrinsic::minimum:
1666 case Intrinsic::maximumnum:
1667 case Intrinsic::minimumnum:
1668 case Intrinsic::maxnum:
1669 case Intrinsic::minnum:
1670 return true;
1671 default:
1672 return false;
1673 }
1674}
1675
1676/// Attempt to simplify value-accumulating recurrences of kind:
1677/// %umax.acc = phi i8 [ %umax, %backedge ], [ %a, %entry ]
1678/// %umax = call i8 @llvm.umax.i8(i8 %umax.acc, i8 %b)
1679/// And let the idempotent binary intrinsic be hoisted, when the operands are
1680/// known to be loop-invariant.
1681static Value *foldIdempotentBinaryIntrinsicRecurrence(InstCombinerImpl &IC,
1682 IntrinsicInst *II) {
1683 PHINode *PN;
1684 Value *Init, *OtherOp;
1685
1686 // A binary intrinsic recurrence with loop-invariant operands is equivalent to
1687 // `call @llvm.binary.intrinsic(Init, OtherOp)`.
1688 auto IID = II->getIntrinsicID();
1689 if (!isIdempotentBinaryIntrinsic(IID) ||
1690 !matchSimpleBinaryIntrinsicRecurrence(I: II, P&: PN, Init, OtherOp) ||
1691 !IC.getDominatorTree().dominates(Def: OtherOp, User: PN))
1692 return nullptr;
1693
1694 auto *InvariantBinaryInst =
1695 IC.Builder.CreateBinaryIntrinsic(ID: IID, LHS: Init, RHS: OtherOp);
1696 if (isa<FPMathOperator>(Val: InvariantBinaryInst))
1697 cast<Instruction>(Val: InvariantBinaryInst)->copyFastMathFlags(I: II);
1698 return InvariantBinaryInst;
1699}
1700
1701static Value *simplifyReductionOperand(Value *Arg, bool CanReorderLanes) {
1702 if (!CanReorderLanes)
1703 return nullptr;
1704
1705 Value *V;
1706 if (match(V: Arg, P: m_VecReverse(Op0: m_Value(V))))
1707 return V;
1708
1709 ArrayRef<int> Mask;
1710 if (!isa<FixedVectorType>(Val: Arg->getType()) ||
1711 !match(V: Arg, P: m_Shuffle(v1: m_Value(V), v2: m_Undef(), mask: m_Mask(Mask))) ||
1712 !cast<ShuffleVectorInst>(Val: Arg)->isSingleSource())
1713 return nullptr;
1714
1715 int Sz = Mask.size();
1716 SmallBitVector UsedIndices(Sz);
1717 for (int Idx : Mask) {
1718 if (Idx == PoisonMaskElem || UsedIndices.test(Idx))
1719 return nullptr;
1720 UsedIndices.set(Idx);
1721 }
1722
1723 // Can remove shuffle iff just shuffled elements, no repeats, undefs, or
1724 // other changes.
1725 return UsedIndices.all() ? V : nullptr;
1726}
1727
1728/// Fold an unsigned minimum of trailing or leading zero bits counts:
1729/// umin(cttz(CtOp1, ZeroUndef), ConstOp) --> cttz(CtOp1 | (1 << ConstOp))
1730/// umin(ctlz(CtOp1, ZeroUndef), ConstOp) --> ctlz(CtOp1 | (SignedMin
1731/// >> ConstOp))
1732/// umin(cttz(CtOp1), cttz(CtOp2)) --> cttz(CtOp1 | CtOp2)
1733/// umin(ctlz(CtOp1), ctlz(CtOp2)) --> ctlz(CtOp1 | CtOp2)
1734template <Intrinsic::ID IntrID>
1735static Value *
1736foldMinimumOverTrailingOrLeadingZeroCount(Value *I0, Value *I1,
1737 const DataLayout &DL,
1738 InstCombiner::BuilderTy &Builder) {
1739 static_assert(IntrID == Intrinsic::cttz || IntrID == Intrinsic::ctlz,
1740 "This helper only supports cttz and ctlz intrinsics");
1741
1742 Value *CtOp1, *CtOp2;
1743 Value *ZeroUndef1, *ZeroUndef2;
1744 if (!match(I0, m_OneUse(
1745 m_Intrinsic<IntrID>(m_Value(V&: CtOp1), m_Value(V&: ZeroUndef1)))))
1746 return nullptr;
1747
1748 if (match(I1,
1749 m_OneUse(m_Intrinsic<IntrID>(m_Value(V&: CtOp2), m_Value(V&: ZeroUndef2)))))
1750 return Builder.CreateBinaryIntrinsic(
1751 ID: IntrID, LHS: Builder.CreateOr(LHS: CtOp1, RHS: CtOp2),
1752 RHS: Builder.CreateOr(LHS: ZeroUndef1, RHS: ZeroUndef2));
1753
1754 unsigned BitWidth = I1->getType()->getScalarSizeInBits();
1755 auto LessBitWidth = [BitWidth](auto &C) { return C.ult(BitWidth); };
1756 if (!match(I1, m_CheckedInt(LessBitWidth)))
1757 // We have a constant >= BitWidth (which can be handled by CVP)
1758 // or a non-splat vector with elements < and >= BitWidth
1759 return nullptr;
1760
1761 Type *Ty = I1->getType();
1762 Constant *NewConst = ConstantFoldBinaryOpOperands(
1763 Opcode: IntrID == Intrinsic::cttz ? Instruction::Shl : Instruction::LShr,
1764 LHS: IntrID == Intrinsic::cttz
1765 ? ConstantInt::get(Ty, V: 1)
1766 : ConstantInt::get(Ty, V: APInt::getSignedMinValue(numBits: BitWidth)),
1767 RHS: cast<Constant>(Val: I1), DL);
1768 return Builder.CreateBinaryIntrinsic(
1769 ID: IntrID, LHS: Builder.CreateOr(LHS: CtOp1, RHS: NewConst),
1770 RHS: ConstantInt::getTrue(Ty: ZeroUndef1->getType()));
1771}
1772
1773/// Return whether "X LOp (Y ROp Z)" is always equal to
1774/// "(X LOp Y) ROp (X LOp Z)".
1775static bool leftDistributesOverRight(Instruction::BinaryOps LOp, bool HasNUW,
1776 bool HasNSW, Intrinsic::ID ROp) {
1777 switch (ROp) {
1778 case Intrinsic::umax:
1779 case Intrinsic::umin:
1780 if (HasNUW && LOp == Instruction::Add)
1781 return true;
1782 if (HasNUW && LOp == Instruction::Shl)
1783 return true;
1784 return false;
1785 case Intrinsic::smax:
1786 case Intrinsic::smin:
1787 return HasNSW && LOp == Instruction::Add;
1788 default:
1789 return false;
1790 }
1791}
1792
1793/// Return whether "(X ROp Y) LOp Z" is always equal to
1794/// "(X LOp Z) ROp (Y LOp Z)".
1795static bool rightDistributesOverLeft(Instruction::BinaryOps LOp, bool HasNUW,
1796 bool HasNSW, Intrinsic::ID ROp) {
1797 if (Instruction::isCommutative(Opcode: LOp) || LOp == Instruction::Shl)
1798 return leftDistributesOverRight(LOp, HasNUW, HasNSW, ROp);
1799 switch (ROp) {
1800 case Intrinsic::umax:
1801 case Intrinsic::umin:
1802 return HasNUW && LOp == Instruction::Sub;
1803 case Intrinsic::smax:
1804 case Intrinsic::smin:
1805 return HasNSW && LOp == Instruction::Sub;
1806 default:
1807 return false;
1808 }
1809}
1810
1811// Attempts to factorise a common term
1812// in an instruction that has the form "(A op' B) op (C op' D)
1813// where op is an intrinsic and op' is a binop
1814static Value *
1815foldIntrinsicUsingDistributiveLaws(IntrinsicInst *II,
1816 InstCombiner::BuilderTy &Builder) {
1817 Value *LHS = II->getOperand(i_nocapture: 0), *RHS = II->getOperand(i_nocapture: 1);
1818 Intrinsic::ID TopLevelOpcode = II->getIntrinsicID();
1819
1820 OverflowingBinaryOperator *Op0 = dyn_cast<OverflowingBinaryOperator>(Val: LHS);
1821 OverflowingBinaryOperator *Op1 = dyn_cast<OverflowingBinaryOperator>(Val: RHS);
1822
1823 if (!Op0 || !Op1)
1824 return nullptr;
1825
1826 if (Op0->getOpcode() != Op1->getOpcode())
1827 return nullptr;
1828
1829 if (!Op0->hasOneUse() || !Op1->hasOneUse())
1830 return nullptr;
1831
1832 Instruction::BinaryOps InnerOpcode =
1833 static_cast<Instruction::BinaryOps>(Op0->getOpcode());
1834 bool HasNUW = Op0->hasNoUnsignedWrap() && Op1->hasNoUnsignedWrap();
1835 bool HasNSW = Op0->hasNoSignedWrap() && Op1->hasNoSignedWrap();
1836
1837 Value *A = Op0->getOperand(i_nocapture: 0);
1838 Value *B = Op0->getOperand(i_nocapture: 1);
1839 Value *C = Op1->getOperand(i_nocapture: 0);
1840 Value *D = Op1->getOperand(i_nocapture: 1);
1841
1842 // Attempts to swap variables such that A equals C or B equals D,
1843 // if the inner operation is commutative.
1844 if (Op0->isCommutative() && A != C && B != D) {
1845 if (A == D || B == C)
1846 std::swap(a&: C, b&: D);
1847 else
1848 return nullptr;
1849 }
1850
1851 BinaryOperator *NewBinop;
1852 if (A == C &&
1853 leftDistributesOverRight(LOp: InnerOpcode, HasNUW, HasNSW, ROp: TopLevelOpcode)) {
1854 Value *NewIntrinsic = Builder.CreateBinaryIntrinsic(ID: TopLevelOpcode, LHS: B, RHS: D);
1855 NewBinop =
1856 cast<BinaryOperator>(Val: Builder.CreateBinOp(Opc: InnerOpcode, LHS: A, RHS: NewIntrinsic));
1857 } else if (B == D && rightDistributesOverLeft(LOp: InnerOpcode, HasNUW, HasNSW,
1858 ROp: TopLevelOpcode)) {
1859 Value *NewIntrinsic = Builder.CreateBinaryIntrinsic(ID: TopLevelOpcode, LHS: A, RHS: C);
1860 NewBinop =
1861 cast<BinaryOperator>(Val: Builder.CreateBinOp(Opc: InnerOpcode, LHS: NewIntrinsic, RHS: B));
1862 } else {
1863 return nullptr;
1864 }
1865
1866 NewBinop->setHasNoUnsignedWrap(HasNUW);
1867 NewBinop->setHasNoSignedWrap(HasNSW);
1868
1869 return NewBinop;
1870}
1871
1872static Instruction *foldNeonShift(IntrinsicInst *II, InstCombinerImpl &IC) {
1873 Value *Arg0 = II->getArgOperand(i: 0);
1874 auto *ShiftConst = dyn_cast<Constant>(Val: II->getArgOperand(i: 1));
1875 if (!ShiftConst)
1876 return nullptr;
1877
1878 int ElemBits = Arg0->getType()->getScalarSizeInBits();
1879 bool AllPositive = true;
1880 bool AllNegative = true;
1881
1882 auto Check = [&](Constant *C) -> bool {
1883 if (auto *CI = dyn_cast_or_null<ConstantInt>(Val: C)) {
1884 const APInt &V = CI->getValue();
1885 if (V.isNonNegative()) {
1886 AllNegative = false;
1887 return AllPositive && V.ult(RHS: ElemBits);
1888 }
1889 AllPositive = false;
1890 return AllNegative && V.sgt(RHS: -ElemBits);
1891 }
1892 return false;
1893 };
1894
1895 if (auto *VTy = dyn_cast<FixedVectorType>(Val: Arg0->getType())) {
1896 for (unsigned I = 0, E = VTy->getNumElements(); I < E; ++I) {
1897 if (!Check(ShiftConst->getAggregateElement(Elt: I)))
1898 return nullptr;
1899 }
1900
1901 } else if (!Check(ShiftConst))
1902 return nullptr;
1903
1904 IRBuilderBase &B = IC.Builder;
1905 if (AllPositive)
1906 return IC.replaceInstUsesWith(I&: *II, V: B.CreateShl(LHS: Arg0, RHS: ShiftConst));
1907
1908 Value *NegAmt = B.CreateNeg(V: ShiftConst);
1909 Intrinsic::ID IID = II->getIntrinsicID();
1910 const bool IsSigned =
1911 IID == Intrinsic::arm_neon_vshifts || IID == Intrinsic::aarch64_neon_sshl;
1912 Value *Result =
1913 IsSigned ? B.CreateAShr(LHS: Arg0, RHS: NegAmt) : B.CreateLShr(LHS: Arg0, RHS: NegAmt);
1914 return IC.replaceInstUsesWith(I&: *II, V: Result);
1915}
1916
1917// If II is llvm.sin(x) or llvm.cos(x), and there is a matching
1918// llvm.cos(x) or llvm.sin(x) using the same argument, combine them
1919// into a single llvm.sincos(x) call. Returns the result for II
1920// extracted from sincos, or nullptr if no match is found.
1921static Value *foldSinAndCosToSinCos(IntrinsicInst *II, IRBuilderBase &B,
1922 InstCombinerImpl &IC) {
1923 Intrinsic::ID IID = II->getIntrinsicID();
1924 bool IsSin = IID == Intrinsic::sin;
1925 Intrinsic::ID MatchID = IsSin ? Intrinsic::cos : Intrinsic::sin;
1926
1927 Value *Arg = II->getArgOperand(i: 0);
1928
1929 // Don't bother looking through uses of constants.
1930 if (isa<Constant>(Val: Arg))
1931 return nullptr;
1932
1933 // Look for a matching cos/sin intrinsic with the same argument.
1934 IntrinsicInst *Match = nullptr;
1935 for (User *U : Arg->users()) {
1936 if (auto *Cand = dyn_cast<IntrinsicInst>(Val: U)) {
1937 if (Cand != II && !Cand->use_empty() &&
1938 Cand->getIntrinsicID() == MatchID) {
1939 Match = Cand;
1940 break;
1941 }
1942 }
1943 }
1944
1945 if (!Match)
1946 return nullptr;
1947
1948 // Insert sincos right after the argument definition.
1949 IRBuilderBase::InsertPointGuard Guard(B);
1950 if (auto *ArgInst = dyn_cast<Instruction>(Val: Arg)) {
1951 std::optional<BasicBlock::iterator> InsertPt =
1952 ArgInst->getInsertionPointAfterDef();
1953 if (!InsertPt)
1954 return nullptr;
1955 B.SetInsertPoint(*InsertPt);
1956 } else {
1957 BasicBlock &EntryBB = II->getFunction()->getEntryBlock();
1958 B.SetInsertPoint(TheBB: &EntryBB, IP: EntryBB.begin());
1959 }
1960
1961 Function *SinCosFunc = Intrinsic::getOrInsertDeclaration(
1962 M: II->getModule(), id: Intrinsic::sincos, OverloadTys: Arg->getType());
1963 CallInst *SinCos = B.CreateCall(Callee: SinCosFunc, Args: Arg, Name: "sincos");
1964 // Intersect fast-math flags from the two calls.
1965 SinCos->setFastMathFlags(II->getFastMathFlags() & Match->getFastMathFlags());
1966 // Propagate the most-generic fpmath metadata from the two original calls.
1967 if (MDNode *MD = MDNode::getMostGenericFPMath(
1968 A: II->getMetadata(KindID: LLVMContext::MD_fpmath),
1969 B: Match->getMetadata(KindID: LLVMContext::MD_fpmath)))
1970 SinCos->setMetadata(KindID: LLVMContext::MD_fpmath, Node: MD);
1971 Value *Sin = B.CreateExtractValue(Agg: SinCos, Idxs: 0, Name: "sin");
1972 Value *Cos = B.CreateExtractValue(Agg: SinCos, Idxs: 1, Name: "cos");
1973
1974 // Replace the matching call and erase it.
1975 IC.replaceInstUsesWith(I&: *Match, V: IsSin ? Cos : Sin);
1976 IC.eraseInstFromFunction(I&: *Match);
1977 return IsSin ? Sin : Cos;
1978}
1979
1980/// CallInst simplification. This mostly only handles folding of intrinsic
1981/// instructions. For normal calls, it allows visitCallBase to do the heavy
1982/// lifting.
1983Instruction *InstCombinerImpl::visitCallInst(CallInst &CI) {
1984 // Don't try to simplify calls without uses. It will not do anything useful,
1985 // but will result in the following folds being skipped.
1986 if (!CI.use_empty()) {
1987 SmallVector<Value *, 8> Args(CI.args());
1988 if (Value *V = simplifyCall(Call: &CI, Callee: CI.getCalledOperand(), Args,
1989 Q: SQ.getWithInstruction(I: &CI)))
1990 return replaceInstUsesWith(I&: CI, V);
1991 }
1992
1993 if (Value *FreedOp = getFreedOperand(CB: &CI, TLI: &TLI))
1994 return visitFree(FI&: CI, FreedOp);
1995
1996 // If the caller function (i.e. us, the function that contains this CallInst)
1997 // is nounwind, mark the call as nounwind, even if the callee isn't.
1998 if (CI.getFunction()->doesNotThrow() && !CI.doesNotThrow()) {
1999 CI.setDoesNotThrow();
2000 return &CI;
2001 }
2002
2003 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Val: &CI);
2004 if (!II)
2005 return visitCallBase(Call&: CI);
2006
2007 // Intrinsics cannot occur in an invoke or a callbr, so handle them here
2008 // instead of in visitCallBase.
2009 if (auto *MI = dyn_cast<AnyMemIntrinsic>(Val: II)) {
2010 if (auto NumBytes = MI->getLengthInBytes()) {
2011 // memmove/cpy/set of zero bytes is a noop.
2012 if (NumBytes->isZero())
2013 return eraseInstFromFunction(I&: CI);
2014
2015 // For atomic unordered mem intrinsics if len is not a positive or
2016 // not a multiple of element size then behavior is undefined.
2017 if (MI->isAtomic() &&
2018 (NumBytes->isNegative() ||
2019 (NumBytes->getZExtValue() % MI->getElementSizeInBytes() != 0))) {
2020 CreateNonTerminatorUnreachable(InsertAt: MI);
2021 assert(MI->getType()->isVoidTy() &&
2022 "non void atomic unordered mem intrinsic");
2023 return eraseInstFromFunction(I&: *MI);
2024 }
2025 }
2026
2027 // No other transformations apply to volatile transfers.
2028 if (MI->isVolatile())
2029 return nullptr;
2030
2031 if (AnyMemTransferInst *MTI = dyn_cast<AnyMemTransferInst>(Val: MI)) {
2032 // memmove(x,x,size) -> noop.
2033 if (MTI->getSource() == MTI->getDest())
2034 return eraseInstFromFunction(I&: CI);
2035 }
2036
2037 auto IsPointerUndefined = [MI](Value *Ptr) {
2038 return isa<ConstantPointerNull>(Val: Ptr) &&
2039 !NullPointerIsDefined(
2040 F: MI->getFunction(),
2041 AS: cast<PointerType>(Val: Ptr->getType())->getAddressSpace());
2042 };
2043 bool SrcIsUndefined = false;
2044 // If we can determine a pointer alignment that is bigger than currently
2045 // set, update the alignment.
2046 if (auto *MTI = dyn_cast<AnyMemTransferInst>(Val: MI)) {
2047 if (Instruction *I = SimplifyAnyMemTransfer(MI: MTI))
2048 return I;
2049 SrcIsUndefined = IsPointerUndefined(MTI->getRawSource());
2050 } else if (auto *MSI = dyn_cast<AnyMemSetInst>(Val: MI)) {
2051 if (Instruction *I = SimplifyAnyMemSet(MI: MSI))
2052 return I;
2053 }
2054
2055 // If src/dest is null, this memory intrinsic must be a noop.
2056 if (SrcIsUndefined || IsPointerUndefined(MI->getRawDest())) {
2057 Builder.CreateAssumption(Cond: Builder.CreateIsNull(Arg: MI->getLength()));
2058 return eraseInstFromFunction(I&: CI);
2059 }
2060
2061 // If we have a memmove and the source operation is a constant global,
2062 // then the source and dest pointers can't alias, so we can change this
2063 // into a call to memcpy.
2064 if (auto *MMI = dyn_cast<AnyMemMoveInst>(Val: MI)) {
2065 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(Val: MMI->getSource()))
2066 if (GVSrc->isConstant()) {
2067 Module *M = CI.getModule();
2068 Intrinsic::ID MemCpyID =
2069 MMI->isAtomic()
2070 ? Intrinsic::memcpy_element_unordered_atomic
2071 : Intrinsic::memcpy;
2072 Type *Tys[3] = { CI.getArgOperand(i: 0)->getType(),
2073 CI.getArgOperand(i: 1)->getType(),
2074 CI.getArgOperand(i: 2)->getType() };
2075 CI.setCalledFunction(
2076 Intrinsic::getOrInsertDeclaration(M, id: MemCpyID, OverloadTys: Tys));
2077 return II;
2078 }
2079 }
2080 }
2081
2082 // For fixed width vector result intrinsics, use the generic demanded vector
2083 // support.
2084 if (auto *IIFVTy = dyn_cast<FixedVectorType>(Val: II->getType())) {
2085 auto VWidth = IIFVTy->getNumElements();
2086 APInt PoisonElts(VWidth, 0);
2087 APInt AllOnesEltMask(APInt::getAllOnes(numBits: VWidth));
2088 if (Value *V = SimplifyDemandedVectorElts(V: II, DemandedElts: AllOnesEltMask, PoisonElts)) {
2089 if (V != II)
2090 return replaceInstUsesWith(I&: *II, V);
2091 return II;
2092 }
2093 }
2094
2095 if (II->isCommutative()) {
2096 if (auto Pair = matchSymmetricPair(LHS: II->getOperand(i_nocapture: 0), RHS: II->getOperand(i_nocapture: 1))) {
2097 replaceOperand(I&: *II, OpNum: 0, V: Pair->first);
2098 replaceOperand(I&: *II, OpNum: 1, V: Pair->second);
2099 II->dropPoisonGeneratingAnnotations();
2100 II->dropUBImplyingAttrsAndMetadata();
2101 return II;
2102 }
2103
2104 if (CallInst *NewCall = canonicalizeConstantArg0ToArg1(Call&: CI))
2105 return NewCall;
2106 }
2107
2108 // Unused constrained FP intrinsic calls may have declared side effect, which
2109 // prevents it from being removed. In some cases however the side effect is
2110 // actually absent. To detect this case, call SimplifyConstrainedFPCall. If it
2111 // returns a replacement, the call may be removed.
2112 if (CI.use_empty() && isa<ConstrainedFPIntrinsic>(Val: CI)) {
2113 if (simplifyConstrainedFPCall(Call: &CI, Q: SQ.getWithInstruction(I: &CI)))
2114 return eraseInstFromFunction(I&: CI);
2115 }
2116
2117 Intrinsic::ID IID = II->getIntrinsicID();
2118 switch (IID) {
2119 case Intrinsic::objectsize: {
2120 SmallVector<Instruction *> InsertedInstructions;
2121 if (Value *V = lowerObjectSizeCall(ObjectSize: II, DL, TLI: &TLI, AA, /*MustSucceed=*/false,
2122 InsertedInstructions: &InsertedInstructions)) {
2123 for (Instruction *Inserted : InsertedInstructions)
2124 Worklist.add(I: Inserted);
2125 return replaceInstUsesWith(I&: CI, V);
2126 }
2127 return nullptr;
2128 }
2129 case Intrinsic::abs: {
2130 Value *IIOperand = II->getArgOperand(i: 0);
2131 bool IntMinIsPoison = cast<Constant>(Val: II->getArgOperand(i: 1))->isOneValue();
2132
2133 // abs(-x) -> abs(x)
2134 Value *X;
2135 if (match(V: IIOperand, P: m_Neg(V: m_Value(V&: X))))
2136 return CallInst::Create(
2137 Func: II->getCalledFunction(),
2138 Args: {X,
2139 Builder.getInt1(V: IntMinIsPoison ||
2140 cast<Instruction>(Val: IIOperand)->hasNoSignedWrap())});
2141
2142 if (match(V: IIOperand, P: m_c_Select(L: m_Neg(V: m_Value(V&: X)), R: m_Deferred(V: X))))
2143 return CallInst::Create(Func: II->getCalledFunction(),
2144 Args: {X, II->getArgOperand(i: 1)});
2145
2146 Value *Y;
2147 // abs(a * abs(b)) -> abs(a * b)
2148 if (match(V: IIOperand,
2149 P: m_OneUse(SubPattern: m_c_Mul(L: m_Value(V&: X),
2150 R: m_Intrinsic<Intrinsic::abs>(Ops: m_Value(V&: Y)))))) {
2151 bool NSW =
2152 cast<Instruction>(Val: IIOperand)->hasNoSignedWrap() && IntMinIsPoison;
2153 auto *XY = NSW ? Builder.CreateNSWMul(LHS: X, RHS: Y) : Builder.CreateMul(LHS: X, RHS: Y);
2154 return CallInst::Create(Func: II->getCalledFunction(),
2155 Args: {XY, II->getArgOperand(i: 1)});
2156 }
2157
2158 if (std::optional<bool> Known =
2159 getKnownSignOrZero(Op: IIOperand, SQ: SQ.getWithInstruction(I: II))) {
2160 // abs(x) -> x if x >= 0 (include abs(x-y) --> x - y where x >= y)
2161 // abs(x) -> x if x > 0 (include abs(x-y) --> x - y where x > y)
2162 if (!*Known)
2163 return replaceInstUsesWith(I&: *II, V: IIOperand);
2164
2165 // abs(x) -> -x if x < 0
2166 // abs(x) -> -x if x < = 0 (include abs(x-y) --> y - x where x <= y)
2167 if (IntMinIsPoison)
2168 return BinaryOperator::CreateNSWNeg(Op: IIOperand);
2169 return BinaryOperator::CreateNeg(Op: IIOperand);
2170 }
2171
2172 // abs (sext X) --> zext (abs X*)
2173 // Clear the IsIntMin (nsw) bit on the abs to allow narrowing.
2174 if (match(V: IIOperand, P: m_OneUse(SubPattern: m_SExt(Op: m_Value(V&: X))))) {
2175 Value *NarrowAbs =
2176 Builder.CreateBinaryIntrinsic(ID: Intrinsic::abs, LHS: X, RHS: Builder.getFalse());
2177 return CastInst::Create(Instruction::ZExt, S: NarrowAbs, Ty: II->getType());
2178 }
2179
2180 // Match a complicated way to check if a number is odd/even:
2181 // abs (srem X, 2) --> and X, 1
2182 const APInt *C;
2183 if (match(V: IIOperand, P: m_SRem(L: m_Value(V&: X), R: m_APInt(Res&: C))) && *C == 2)
2184 return BinaryOperator::CreateAnd(V1: X, V2: ConstantInt::get(Ty: II->getType(), V: 1));
2185
2186 break;
2187 }
2188 case Intrinsic::umin: {
2189 Value *I0 = II->getArgOperand(i: 0), *I1 = II->getArgOperand(i: 1);
2190 // umin(x, 1) == zext(x != 0)
2191 if (match(V: I1, P: m_One())) {
2192 assert(II->getType()->getScalarSizeInBits() != 1 &&
2193 "Expected simplify of umin with max constant");
2194 Value *Zero = Constant::getNullValue(Ty: I0->getType());
2195 Value *Cmp = Builder.CreateICmpNE(LHS: I0, RHS: Zero);
2196 return CastInst::Create(Instruction::ZExt, S: Cmp, Ty: II->getType());
2197 }
2198 // umin(cttz(x), const) --> cttz(x | (1 << const))
2199 if (Value *FoldedCttz =
2200 foldMinimumOverTrailingOrLeadingZeroCount<Intrinsic::cttz>(
2201 I0, I1, DL, Builder))
2202 return replaceInstUsesWith(I&: *II, V: FoldedCttz);
2203 // umin(ctlz(x), const) --> ctlz(x | (SignedMin >> const))
2204 if (Value *FoldedCtlz =
2205 foldMinimumOverTrailingOrLeadingZeroCount<Intrinsic::ctlz>(
2206 I0, I1, DL, Builder))
2207 return replaceInstUsesWith(I&: *II, V: FoldedCtlz);
2208 [[fallthrough]];
2209 }
2210 case Intrinsic::umax: {
2211 Value *I0 = II->getArgOperand(i: 0), *I1 = II->getArgOperand(i: 1);
2212 Value *X, *Y;
2213 if (match(V: I0, P: m_ZExt(Op: m_Value(V&: X))) && match(V: I1, P: m_ZExt(Op: m_Value(V&: Y))) &&
2214 (I0->hasOneUse() || I1->hasOneUse()) && X->getType() == Y->getType()) {
2215 Value *NarrowMaxMin = Builder.CreateBinaryIntrinsic(ID: IID, LHS: X, RHS: Y);
2216 return CastInst::Create(Instruction::ZExt, S: NarrowMaxMin, Ty: II->getType());
2217 }
2218 Constant *C;
2219 if (match(V: I0, P: m_ZExt(Op: m_Value(V&: X))) && match(V: I1, P: m_Constant(C)) &&
2220 I0->hasOneUse()) {
2221 if (Constant *NarrowC = getLosslessUnsignedTrunc(C, DestTy: X->getType(), DL)) {
2222 Value *NarrowMaxMin = Builder.CreateBinaryIntrinsic(ID: IID, LHS: X, RHS: NarrowC);
2223 return CastInst::Create(Instruction::ZExt, S: NarrowMaxMin, Ty: II->getType());
2224 }
2225 }
2226 // If C is not 0:
2227 // umax(nuw_shl(x, C), x + 1) -> x == 0 ? 1 : nuw_shl(x, C)
2228 // If C is not 0 or 1:
2229 // umax(nuw_mul(x, C), x + 1) -> x == 0 ? 1 : nuw_mul(x, C)
2230 auto foldMaxMulShift = [&](Value *A, Value *B) -> Instruction * {
2231 const APInt *C;
2232 Value *X;
2233 if (!match(V: A, P: m_NUWShl(L: m_Value(V&: X), R: m_APInt(Res&: C))) &&
2234 !(match(V: A, P: m_NUWMul(L: m_Value(V&: X), R: m_APInt(Res&: C))) && !C->isOne()))
2235 return nullptr;
2236 if (C->isZero())
2237 return nullptr;
2238 if (!match(V: B, P: m_OneUse(SubPattern: m_Add(L: m_Specific(V: X), R: m_One()))))
2239 return nullptr;
2240
2241 Value *Cmp = Builder.CreateICmpEQ(LHS: X, RHS: ConstantInt::get(Ty: X->getType(), V: 0));
2242 Value *NewSelect = nullptr;
2243 NewSelect = Builder.CreateSelectWithUnknownProfile(
2244 C: Cmp, True: ConstantInt::get(Ty: X->getType(), V: 1), False: A, DEBUG_TYPE);
2245 return replaceInstUsesWith(I&: *II, V: NewSelect);
2246 };
2247
2248 if (IID == Intrinsic::umax) {
2249 if (Instruction *I = foldMaxMulShift(I0, I1))
2250 return I;
2251 if (Instruction *I = foldMaxMulShift(I1, I0))
2252 return I;
2253 }
2254
2255 // If both operands of unsigned min/max are sign-extended, it is still ok
2256 // to narrow the operation.
2257 [[fallthrough]];
2258 }
2259 case Intrinsic::smax:
2260 case Intrinsic::smin: {
2261 Value *I0 = II->getArgOperand(i: 0), *I1 = II->getArgOperand(i: 1);
2262 Value *X, *Y;
2263 if (match(V: I0, P: m_SExt(Op: m_Value(V&: X))) && match(V: I1, P: m_SExt(Op: m_Value(V&: Y))) &&
2264 (I0->hasOneUse() || I1->hasOneUse()) && X->getType() == Y->getType()) {
2265 Value *NarrowMaxMin = Builder.CreateBinaryIntrinsic(ID: IID, LHS: X, RHS: Y);
2266 return CastInst::Create(Instruction::SExt, S: NarrowMaxMin, Ty: II->getType());
2267 }
2268
2269 Constant *C;
2270 if (match(V: I0, P: m_SExt(Op: m_Value(V&: X))) && match(V: I1, P: m_Constant(C)) &&
2271 I0->hasOneUse()) {
2272 if (Constant *NarrowC = getLosslessSignedTrunc(C, DestTy: X->getType(), DL)) {
2273 Value *NarrowMaxMin = Builder.CreateBinaryIntrinsic(ID: IID, LHS: X, RHS: NarrowC);
2274 return CastInst::Create(Instruction::SExt, S: NarrowMaxMin, Ty: II->getType());
2275 }
2276 }
2277
2278 // smax(smin(X, MinC), MaxC) -> smin(smax(X, MaxC), MinC) if MinC s>= MaxC
2279 // umax(umin(X, MinC), MaxC) -> umin(umax(X, MaxC), MinC) if MinC u>= MaxC
2280 const APInt *MinC, *MaxC;
2281 auto CreateCanonicalClampForm = [&](bool IsSigned) {
2282 auto MaxIID = IsSigned ? Intrinsic::smax : Intrinsic::umax;
2283 auto MinIID = IsSigned ? Intrinsic::smin : Intrinsic::umin;
2284 Value *NewMax = Builder.CreateBinaryIntrinsic(
2285 ID: MaxIID, LHS: X, RHS: ConstantInt::get(Ty: X->getType(), V: *MaxC));
2286 return replaceInstUsesWith(
2287 I&: *II, V: Builder.CreateBinaryIntrinsic(
2288 ID: MinIID, LHS: NewMax, RHS: ConstantInt::get(Ty: X->getType(), V: *MinC)));
2289 };
2290 if (IID == Intrinsic::smax &&
2291 match(V: I0, P: m_OneUse(SubPattern: m_Intrinsic<Intrinsic::smin>(Ops: m_Value(V&: X),
2292 Ops: m_APInt(Res&: MinC)))) &&
2293 match(V: I1, P: m_APInt(Res&: MaxC)) && MinC->sgt(RHS: *MaxC))
2294 return CreateCanonicalClampForm(true);
2295 if (IID == Intrinsic::umax &&
2296 match(V: I0, P: m_OneUse(SubPattern: m_Intrinsic<Intrinsic::umin>(Ops: m_Value(V&: X),
2297 Ops: m_APInt(Res&: MinC)))) &&
2298 match(V: I1, P: m_APInt(Res&: MaxC)) && MinC->ugt(RHS: *MaxC))
2299 return CreateCanonicalClampForm(false);
2300
2301 // umin(i1 X, i1 Y) -> and i1 X, Y
2302 // smax(i1 X, i1 Y) -> and i1 X, Y
2303 if ((IID == Intrinsic::umin || IID == Intrinsic::smax) &&
2304 II->getType()->isIntOrIntVectorTy(BitWidth: 1)) {
2305 return BinaryOperator::CreateAnd(V1: I0, V2: I1);
2306 }
2307
2308 // umax(i1 X, i1 Y) -> or i1 X, Y
2309 // smin(i1 X, i1 Y) -> or i1 X, Y
2310 if ((IID == Intrinsic::umax || IID == Intrinsic::smin) &&
2311 II->getType()->isIntOrIntVectorTy(BitWidth: 1)) {
2312 return BinaryOperator::CreateOr(V1: I0, V2: I1);
2313 }
2314
2315 // smin(smax(X, -1), 1) -> scmp(X, 0)
2316 // smax(smin(X, 1), -1) -> scmp(X, 0)
2317 // At this point, smax(smin(X, 1), -1) is changed to smin(smax(X, -1)
2318 // And i1's have been changed to and/ors
2319 // So we only need to check for smin
2320 if (IID == Intrinsic::smin) {
2321 if (match(V: I0, P: m_OneUse(SubPattern: m_SMax(Op0: m_Value(V&: X), Op1: m_AllOnes()))) &&
2322 match(V: I1, P: m_One())) {
2323 Value *Zero = ConstantInt::get(Ty: X->getType(), V: 0);
2324 return replaceInstUsesWith(
2325 I&: CI,
2326 V: Builder.CreateIntrinsic(RetTy: II->getType(), ID: Intrinsic::scmp, Args: {X, Zero}));
2327 }
2328 }
2329
2330 if (IID == Intrinsic::smax || IID == Intrinsic::smin) {
2331 // smax (neg nsw X), (neg nsw Y) --> neg nsw (smin X, Y)
2332 // smin (neg nsw X), (neg nsw Y) --> neg nsw (smax X, Y)
2333 // TODO: Canonicalize neg after min/max if I1 is constant.
2334 if (match(V: I0, P: m_NSWNeg(V: m_Value(V&: X))) && match(V: I1, P: m_NSWNeg(V: m_Value(V&: Y))) &&
2335 (I0->hasOneUse() || I1->hasOneUse())) {
2336 Intrinsic::ID InvID = getInverseMinMaxIntrinsic(MinMaxID: IID);
2337 Value *InvMaxMin = Builder.CreateBinaryIntrinsic(ID: InvID, LHS: X, RHS: Y);
2338 return BinaryOperator::CreateNSWNeg(Op: InvMaxMin);
2339 }
2340 }
2341
2342 // (umax X, (xor X, Pow2))
2343 // -> (or X, Pow2)
2344 // (umin X, (xor X, Pow2))
2345 // -> (and X, ~Pow2)
2346 // (smax X, (xor X, Pos_Pow2))
2347 // -> (or X, Pos_Pow2)
2348 // (smin X, (xor X, Pos_Pow2))
2349 // -> (and X, ~Pos_Pow2)
2350 // (smax X, (xor X, Neg_Pow2))
2351 // -> (and X, ~Neg_Pow2)
2352 // (smin X, (xor X, Neg_Pow2))
2353 // -> (or X, Neg_Pow2)
2354 if ((match(V: I0, P: m_c_Xor(L: m_Specific(V: I1), R: m_Value(V&: X))) ||
2355 match(V: I1, P: m_c_Xor(L: m_Specific(V: I0), R: m_Value(V&: X)))) &&
2356 isKnownToBeAPowerOfTwo(V: X, /* OrZero */ true)) {
2357 bool UseOr = IID == Intrinsic::smax || IID == Intrinsic::umax;
2358 bool UseAndN = IID == Intrinsic::smin || IID == Intrinsic::umin;
2359
2360 if (IID == Intrinsic::smax || IID == Intrinsic::smin) {
2361 auto KnownSign = getKnownSign(Op: X, SQ: SQ.getWithInstruction(I: II));
2362 if (KnownSign == std::nullopt) {
2363 UseOr = false;
2364 UseAndN = false;
2365 } else if (*KnownSign /* true is Signed. */) {
2366 UseOr ^= true;
2367 UseAndN ^= true;
2368 Type *Ty = I0->getType();
2369 // Negative power of 2 must be IntMin. It's possible to be able to
2370 // prove negative / power of 2 without actually having known bits, so
2371 // just get the value by hand.
2372 X = Constant::getIntegerValue(
2373 Ty, V: APInt::getSignedMinValue(numBits: Ty->getScalarSizeInBits()));
2374 }
2375 }
2376 if (UseOr)
2377 return BinaryOperator::CreateOr(V1: I0, V2: X);
2378 else if (UseAndN)
2379 return BinaryOperator::CreateAnd(V1: I0, V2: Builder.CreateNot(V: X));
2380 }
2381
2382 // If we can eliminate ~A and Y is free to invert:
2383 // max ~A, Y --> ~(min A, ~Y)
2384 //
2385 // Examples:
2386 // max ~A, ~Y --> ~(min A, Y)
2387 // max ~A, C --> ~(min A, ~C)
2388 // max ~A, (max ~Y, ~Z) --> ~min( A, (min Y, Z))
2389 auto moveNotAfterMinMax = [&](Value *X, Value *Y) -> Instruction * {
2390 Value *A;
2391 if (match(V: X, P: m_OneUse(SubPattern: m_Not(V: m_Value(V&: A)))) &&
2392 !isFreeToInvert(V: A, WillInvertAllUses: A->hasOneUse())) {
2393 if (Value *NotY = getFreelyInverted(V: Y, WillInvertAllUses: Y->hasOneUse(), Builder: &Builder)) {
2394 Intrinsic::ID InvID = getInverseMinMaxIntrinsic(MinMaxID: IID);
2395 Value *InvMaxMin = Builder.CreateBinaryIntrinsic(ID: InvID, LHS: A, RHS: NotY);
2396 return BinaryOperator::CreateNot(Op: InvMaxMin);
2397 }
2398 }
2399 return nullptr;
2400 };
2401
2402 if (Instruction *I = moveNotAfterMinMax(I0, I1))
2403 return I;
2404 if (Instruction *I = moveNotAfterMinMax(I1, I0))
2405 return I;
2406
2407 if (Instruction *I = moveAddAfterMinMax(II, Builder))
2408 return I;
2409
2410 // minmax (X & NegPow2C, Y & NegPow2C) --> minmax(X, Y) & NegPow2C
2411 const APInt *RHSC;
2412 if (match(V: I0, P: m_OneUse(SubPattern: m_And(L: m_Value(V&: X), R: m_NegatedPower2(V&: RHSC)))) &&
2413 match(V: I1, P: m_OneUse(SubPattern: m_And(L: m_Value(V&: Y), R: m_SpecificInt(V: *RHSC)))))
2414 return BinaryOperator::CreateAnd(V1: Builder.CreateBinaryIntrinsic(ID: IID, LHS: X, RHS: Y),
2415 V2: ConstantInt::get(Ty: II->getType(), V: *RHSC));
2416
2417 // smax(X, -X) --> abs(X)
2418 // smin(X, -X) --> -abs(X)
2419 // umax(X, -X) --> -abs(X)
2420 // umin(X, -X) --> abs(X)
2421 if (isKnownNegation(X: I0, Y: I1)) {
2422 // We can choose either operand as the input to abs(), but if we can
2423 // eliminate the only use of a value, that's better for subsequent
2424 // transforms/analysis.
2425 if (I0->hasOneUse() && !I1->hasOneUse())
2426 std::swap(a&: I0, b&: I1);
2427
2428 // This is some variant of abs(). See if we can propagate 'nsw' to the abs
2429 // operation and potentially its negation.
2430 bool IntMinIsPoison = isKnownNegation(X: I0, Y: I1, /* NeedNSW */ true);
2431 Value *Abs = Builder.CreateBinaryIntrinsic(
2432 ID: Intrinsic::abs, LHS: I0,
2433 RHS: ConstantInt::getBool(Context&: II->getContext(), V: IntMinIsPoison));
2434
2435 // We don't have a "nabs" intrinsic, so negate if needed based on the
2436 // max/min operation.
2437 if (IID == Intrinsic::smin || IID == Intrinsic::umax)
2438 Abs = Builder.CreateNeg(V: Abs, Name: "nabs", HasNSW: IntMinIsPoison);
2439 return replaceInstUsesWith(I&: CI, V: Abs);
2440 }
2441
2442 if (Instruction *Sel = foldClampRangeOfTwo(II, Builder))
2443 return Sel;
2444
2445 if (Instruction *SAdd = matchSAddSubSat(MinMax1&: *II))
2446 return SAdd;
2447
2448 if (Value *NewMinMax = reassociateMinMaxWithConstants(II, Builder, SQ))
2449 return replaceInstUsesWith(I&: *II, V: NewMinMax);
2450
2451 if (Instruction *R = reassociateMinMaxWithConstantInOperand(II, Builder))
2452 return R;
2453
2454 if (Instruction *NewMinMax = factorizeMinMaxTree(II))
2455 return NewMinMax;
2456
2457 // Try to fold minmax with constant RHS based on range information
2458 if (match(V: I1, P: m_APIntAllowPoison(Res&: RHSC))) {
2459 ICmpInst::Predicate Pred =
2460 ICmpInst::getNonStrictPredicate(pred: MinMaxIntrinsic::getPredicate(ID: IID));
2461 bool IsSigned = MinMaxIntrinsic::isSigned(ID: IID);
2462 ConstantRange LHS_CR = computeConstantRangeIncludingKnownBits(
2463 V: I0, ForSigned: IsSigned, SQ: SQ.getWithInstruction(I: II));
2464 if (!LHS_CR.isFullSet()) {
2465 if (LHS_CR.icmp(Pred, Other: *RHSC))
2466 return replaceInstUsesWith(I&: *II, V: I0);
2467 if (LHS_CR.icmp(Pred: ICmpInst::getSwappedPredicate(pred: Pred), Other: *RHSC))
2468 return replaceInstUsesWith(I&: *II,
2469 V: ConstantInt::get(Ty: II->getType(), V: *RHSC));
2470 }
2471 }
2472
2473 if (Value *V = foldIntrinsicUsingDistributiveLaws(II, Builder))
2474 return replaceInstUsesWith(I&: *II, V);
2475
2476 break;
2477 }
2478 case Intrinsic::scmp: {
2479 Value *I0 = II->getArgOperand(i: 0), *I1 = II->getArgOperand(i: 1);
2480 Value *LHS, *RHS;
2481 if (match(V: I0, P: m_NSWSub(L: m_Value(V&: LHS), R: m_Value(V&: RHS))) && match(V: I1, P: m_Zero()))
2482 return replaceInstUsesWith(
2483 I&: CI,
2484 V: Builder.CreateIntrinsic(RetTy: II->getType(), ID: Intrinsic::scmp, Args: {LHS, RHS}));
2485 break;
2486 }
2487 case Intrinsic::bitreverse: {
2488 Value *IIOperand = II->getArgOperand(i: 0);
2489 // bitrev (zext i1 X to ?) --> X ? SignBitC : 0
2490 Value *X;
2491 if (match(V: IIOperand, P: m_ZExt(Op: m_Value(V&: X))) &&
2492 X->getType()->isIntOrIntVectorTy(BitWidth: 1)) {
2493 Type *Ty = II->getType();
2494 APInt SignBit = APInt::getSignMask(BitWidth: Ty->getScalarSizeInBits());
2495 return SelectInst::Create(C: X, S1: ConstantInt::get(Ty, V: SignBit),
2496 S2: ConstantInt::getNullValue(Ty));
2497 }
2498
2499 if (Instruction *crossLogicOpFold =
2500 foldBitOrderCrossLogicOp<Intrinsic::bitreverse>(V: IIOperand, Builder))
2501 return crossLogicOpFold;
2502
2503 break;
2504 }
2505 case Intrinsic::bswap: {
2506 Value *IIOperand = II->getArgOperand(i: 0);
2507
2508 // Try to canonicalize bswap-of-logical-shift-by-8-bit-multiple as
2509 // inverse-shift-of-bswap:
2510 // bswap (shl X, Y) --> lshr (bswap X), Y
2511 // bswap (lshr X, Y) --> shl (bswap X), Y
2512 Value *X, *Y;
2513 if (match(V: IIOperand, P: m_OneUse(SubPattern: m_LogicalShift(L: m_Value(V&: X), R: m_Value(V&: Y))))) {
2514 unsigned BitWidth = IIOperand->getType()->getScalarSizeInBits();
2515 if (MaskedValueIsZero(V: Y, Mask: APInt::getLowBitsSet(numBits: BitWidth, loBitsSet: 3))) {
2516 Value *NewSwap = Builder.CreateUnaryIntrinsic(ID: Intrinsic::bswap, Op: X);
2517 BinaryOperator::BinaryOps InverseShift =
2518 cast<BinaryOperator>(Val: IIOperand)->getOpcode() == Instruction::Shl
2519 ? Instruction::LShr
2520 : Instruction::Shl;
2521 return BinaryOperator::Create(Op: InverseShift, S1: NewSwap, S2: Y);
2522 }
2523 }
2524
2525 KnownBits Known = computeKnownBits(V: IIOperand, CxtI: II);
2526 uint64_t LZ = alignDown(Value: Known.countMinLeadingZeros(), Align: 8);
2527 uint64_t TZ = alignDown(Value: Known.countMinTrailingZeros(), Align: 8);
2528 unsigned BW = Known.getBitWidth();
2529
2530 // bswap(x) -> shift(x) if x has exactly one "active byte"
2531 if (BW - LZ - TZ == 8) {
2532 assert(LZ != TZ && "active byte cannot be in the middle");
2533 if (LZ > TZ) // -> shl(x) if the "active byte" is in the low part of x
2534 return BinaryOperator::CreateNUWShl(
2535 V1: IIOperand, V2: ConstantInt::get(Ty: IIOperand->getType(), V: LZ - TZ));
2536 // -> lshr(x) if the "active byte" is in the high part of x
2537 return BinaryOperator::CreateExactLShr(
2538 V1: IIOperand, V2: ConstantInt::get(Ty: IIOperand->getType(), V: TZ - LZ));
2539 }
2540
2541 // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
2542 if (match(V: IIOperand, P: m_Trunc(Op: m_BSwap(Op0: m_Value(V&: X))))) {
2543 unsigned C = X->getType()->getScalarSizeInBits() - BW;
2544 Value *CV = ConstantInt::get(Ty: X->getType(), V: C);
2545 Value *V = Builder.CreateLShr(LHS: X, RHS: CV);
2546 return new TruncInst(V, IIOperand->getType());
2547 }
2548
2549 if (Instruction *crossLogicOpFold =
2550 foldBitOrderCrossLogicOp<Intrinsic::bswap>(V: IIOperand, Builder)) {
2551 return crossLogicOpFold;
2552 }
2553
2554 // Try to fold into bitreverse if bswap is the root of the expression tree.
2555 if (Instruction *BitOp = matchBSwapOrBitReverse(I&: *II, /*MatchBSwaps*/ false,
2556 /*MatchBitReversals*/ true))
2557 return BitOp;
2558 break;
2559 }
2560 case Intrinsic::masked_load:
2561 if (Value *SimplifiedMaskedOp = simplifyMaskedLoad(II&: *II))
2562 return replaceInstUsesWith(I&: CI, V: SimplifiedMaskedOp);
2563 break;
2564 case Intrinsic::masked_store:
2565 return simplifyMaskedStore(II&: *II);
2566 case Intrinsic::masked_gather:
2567 return simplifyMaskedGather(II&: *II);
2568 case Intrinsic::masked_scatter:
2569 return simplifyMaskedScatter(II&: *II);
2570 case Intrinsic::launder_invariant_group:
2571 case Intrinsic::strip_invariant_group:
2572 if (auto *SkippedBarrier = simplifyInvariantGroupIntrinsic(II&: *II, IC&: *this))
2573 return replaceInstUsesWith(I&: *II, V: SkippedBarrier);
2574 break;
2575 case Intrinsic::powi: {
2576 if (ConstantInt *Power = dyn_cast<ConstantInt>(Val: II->getArgOperand(i: 1))) {
2577 // 0 and 1 are handled in instsimplify
2578 // powi(x, -1) -> 1/x
2579 if (Power->isMinusOne())
2580 return BinaryOperator::CreateFDivFMF(V1: ConstantFP::get(Ty: CI.getType(), V: 1.0),
2581 V2: II->getArgOperand(i: 0), FMFSource: II);
2582 // powi(x, 2) -> x*x
2583 if (Power->equalsInt(V: 2))
2584 return BinaryOperator::CreateFMulFMF(V1: II->getArgOperand(i: 0),
2585 V2: II->getArgOperand(i: 0), FMFSource: II);
2586
2587 if (!Power->getValue()[0]) {
2588 Value *X;
2589 // If power is even:
2590 // powi(-x, p) -> powi(x, p)
2591 // powi(fabs(x), p) -> powi(x, p)
2592 // powi(copysign(x, y), p) -> powi(x, p)
2593 if (match(V: II->getArgOperand(i: 0), P: m_FNeg(X: m_Value(V&: X))) ||
2594 match(V: II->getArgOperand(i: 0), P: m_FAbs(Op0: m_Value(V&: X))) ||
2595 match(V: II->getArgOperand(i: 0),
2596 P: m_Intrinsic<Intrinsic::copysign>(Ops: m_Value(V&: X), Ops: m_Value())))
2597 return CallInst::Create(Func: II->getCalledFunction(), Args: {X, Power});
2598 }
2599 }
2600 if (ConstantFP *Base = dyn_cast<ConstantFP>(Val: II->getArgOperand(i: 0))) {
2601 Value *Exp = II->getArgOperand(i: 1);
2602 Type *Ty = Base->getType();
2603 // powi(2.0, p) -> ldexp(1.0, p)
2604 if (II->hasApproxFunc() && Base->isExactlyValue(V: 2.0)) {
2605 ConstantFP *One = ConstantFP::get(Ty, V: 1.0);
2606 if (auto *VTy = dyn_cast<VectorType>(Val: Ty))
2607 Exp = Builder.CreateVectorSplat(EC: VTy->getElementCount(), V: Exp);
2608 Value *Ldexp = Builder.CreateLdexp(Src: One, Exp, FMFSource: II);
2609 return replaceInstUsesWith(I&: *II, V: Ldexp);
2610 }
2611 }
2612 break;
2613 }
2614
2615 case Intrinsic::cttz:
2616 case Intrinsic::ctlz:
2617 if (auto *I = foldCttzCtlz(II&: *II, IC&: *this))
2618 return I;
2619 break;
2620
2621 case Intrinsic::ctpop:
2622 if (auto *I = foldCtpop(II&: *II, IC&: *this))
2623 return I;
2624 break;
2625
2626 case Intrinsic::fshl:
2627 case Intrinsic::fshr: {
2628 Value *Op0 = II->getArgOperand(i: 0), *Op1 = II->getArgOperand(i: 1);
2629 Type *Ty = II->getType();
2630 unsigned BitWidth = Ty->getScalarSizeInBits();
2631 Constant *ShAmtC;
2632 if (match(V: II->getArgOperand(i: 2), P: m_ImmConstant(C&: ShAmtC))) {
2633 // Canonicalize a shift amount constant operand to modulo the bit-width.
2634 Constant *WidthC = ConstantInt::get(Ty, V: BitWidth);
2635 Constant *ModuloC =
2636 ConstantFoldBinaryOpOperands(Opcode: Instruction::URem, LHS: ShAmtC, RHS: WidthC, DL);
2637 if (!ModuloC)
2638 return nullptr;
2639 if (ModuloC != ShAmtC)
2640 return CallInst::Create(Func: II->getCalledFunction(), Args: {Op0, Op1, ModuloC});
2641
2642 assert(match(ConstantFoldCompareInstOperands(ICmpInst::ICMP_UGT, WidthC,
2643 ShAmtC, DL),
2644 m_One()) &&
2645 "Shift amount expected to be modulo bitwidth");
2646
2647 // Canonicalize funnel shift right by constant to funnel shift left. This
2648 // is not entirely arbitrary. For historical reasons, the backend may
2649 // recognize rotate left patterns but miss rotate right patterns.
2650 if (IID == Intrinsic::fshr) {
2651 // fshr X, Y, C --> fshl X, Y, (BitWidth - C) if C is not zero.
2652 if (!isKnownNonZero(V: ShAmtC, Q: SQ.getWithInstruction(I: II)))
2653 return nullptr;
2654
2655 Constant *LeftShiftC = ConstantExpr::getSub(C1: WidthC, C2: ShAmtC);
2656 Module *Mod = II->getModule();
2657 Function *Fshl =
2658 Intrinsic::getOrInsertDeclaration(M: Mod, id: Intrinsic::fshl, OverloadTys: Ty);
2659 return CallInst::Create(Func: Fshl, Args: { Op0, Op1, LeftShiftC });
2660 }
2661 assert(IID == Intrinsic::fshl &&
2662 "All funnel shifts by simple constants should go left");
2663
2664 // fshl(X, 0, C) --> shl X, C
2665 // fshl(X, undef, C) --> shl X, C
2666 if (match(V: Op1, P: m_ZeroInt()) || match(V: Op1, P: m_Undef()))
2667 return BinaryOperator::CreateShl(V1: Op0, V2: ShAmtC);
2668
2669 // fshl(0, X, C) --> lshr X, (BW-C)
2670 // fshl(undef, X, C) --> lshr X, (BW-C)
2671 // Similar to fshr -> fshl fold above, this is only valid if C is not zero
2672 if ((match(V: Op0, P: m_ZeroInt()) || match(V: Op0, P: m_Undef())) &&
2673 isKnownNonZero(V: ShAmtC, Q: SQ.getWithInstruction(I: II)))
2674 return BinaryOperator::CreateLShr(V1: Op1,
2675 V2: ConstantExpr::getSub(C1: WidthC, C2: ShAmtC));
2676
2677 // fshl i16 X, X, 8 --> bswap i16 X (reduce to more-specific form)
2678 if (Op0 == Op1 && BitWidth == 16 && match(V: ShAmtC, P: m_SpecificInt(V: 8))) {
2679 Module *Mod = II->getModule();
2680 Function *Bswap =
2681 Intrinsic::getOrInsertDeclaration(M: Mod, id: Intrinsic::bswap, OverloadTys: Ty);
2682 return CallInst::Create(Func: Bswap, Args: { Op0 });
2683 }
2684 if (Instruction *BitOp =
2685 matchBSwapOrBitReverse(I&: *II, /*MatchBSwaps*/ true,
2686 /*MatchBitReversals*/ true))
2687 return BitOp;
2688
2689 // R = fshl(X, X, C2)
2690 // fshl(R, R, C1) --> fshl(X, X, (C1 + C2) % bitsize)
2691 Value *InnerOp;
2692 const APInt *ShAmtInnerC, *ShAmtOuterC;
2693 if (match(V: Op0, P: m_FShl(Op0: m_Value(V&: InnerOp), Op1: m_Deferred(V: InnerOp),
2694 Op2: m_APInt(Res&: ShAmtInnerC))) &&
2695 match(V: ShAmtC, P: m_APInt(Res&: ShAmtOuterC)) && Op0 == Op1) {
2696 APInt Sum = *ShAmtOuterC + *ShAmtInnerC;
2697 APInt Modulo = Sum.urem(RHS: APInt(Sum.getBitWidth(), BitWidth));
2698 if (Modulo.isZero())
2699 return replaceInstUsesWith(I&: *II, V: InnerOp);
2700 Constant *ModuloC = ConstantInt::get(Ty, V: Modulo);
2701 return CallInst::Create(Func: cast<IntrinsicInst>(Val: Op0)->getCalledFunction(),
2702 Args: {InnerOp, InnerOp, ModuloC});
2703 }
2704 }
2705
2706 // fshl(X, X, Neg(Y)) --> fshr(X, X, Y)
2707 // fshr(X, X, Neg(Y)) --> fshl(X, X, Y)
2708 // if BitWidth is a power-of-2
2709 Value *Y;
2710 if (Op0 == Op1 && isPowerOf2_32(Value: BitWidth) &&
2711 match(V: II->getArgOperand(i: 2), P: m_Neg(V: m_Value(V&: Y)))) {
2712 Module *Mod = II->getModule();
2713 Function *OppositeShift = Intrinsic::getOrInsertDeclaration(
2714 M: Mod, id: IID == Intrinsic::fshl ? Intrinsic::fshr : Intrinsic::fshl, OverloadTys: Ty);
2715 return CallInst::Create(Func: OppositeShift, Args: {Op0, Op1, Y});
2716 }
2717
2718 // fshl(X, 0, Y) --> shl(X, and(Y, BitWidth - 1)) if bitwidth is a
2719 // power-of-2
2720 if (IID == Intrinsic::fshl && isPowerOf2_32(Value: BitWidth) &&
2721 match(V: Op1, P: m_ZeroInt())) {
2722 Value *Op2 = II->getArgOperand(i: 2);
2723 Value *And = Builder.CreateAnd(LHS: Op2, RHS: ConstantInt::get(Ty, V: BitWidth - 1));
2724 return BinaryOperator::CreateShl(V1: Op0, V2: And);
2725 }
2726
2727 // Left or right might be masked.
2728 if (SimplifyDemandedInstructionBits(Inst&: *II))
2729 return &CI;
2730
2731 // The shift amount (operand 2) of a funnel shift is modulo the bitwidth,
2732 // so only the low bits of the shift amount are demanded if the bitwidth is
2733 // a power-of-2.
2734 if (!isPowerOf2_32(Value: BitWidth))
2735 break;
2736 APInt Op2Demanded = APInt::getLowBitsSet(numBits: BitWidth, loBitsSet: Log2_32_Ceil(Value: BitWidth));
2737 KnownBits Op2Known(BitWidth);
2738 if (SimplifyDemandedBits(I: II, OpNo: 2, DemandedMask: Op2Demanded, Known&: Op2Known))
2739 return &CI;
2740 break;
2741 }
2742 case Intrinsic::pdep: {
2743 const APInt *MaskC;
2744 if (match(V: II->getArgOperand(i: 1), P: m_APInt(Res&: MaskC))) {
2745 unsigned MaskIdx, MaskLen;
2746 if (MaskC->isShiftedMask(MaskIdx, MaskLen)) {
2747 // any single contiguous sequence of 1s anywhere in the mask simply
2748 // describes a subset of the input bits shifted to the appropriate
2749 // position. Replace with the straight forward IR.
2750 Value *Input = II->getArgOperand(i: 0);
2751 Value *ShiftAmt = ConstantInt::get(Ty: II->getType(), V: MaskIdx);
2752 Value *Shifted = Builder.CreateShl(LHS: Input, RHS: ShiftAmt);
2753 Value *Masked = Builder.CreateAnd(LHS: Shifted, RHS: II->getArgOperand(i: 1));
2754 return replaceInstUsesWith(I&: *II, V: Masked);
2755 }
2756 }
2757 break;
2758 }
2759 case Intrinsic::pext: {
2760 const APInt *MaskC;
2761 if (match(V: II->getArgOperand(i: 1), P: m_APInt(Res&: MaskC))) {
2762 unsigned MaskIdx, MaskLen;
2763 if (MaskC->isShiftedMask(MaskIdx, MaskLen)) {
2764 // any single contiguous sequence of 1s anywhere in the mask simply
2765 // describes a subset of the input bits shifted to the appropriate
2766 // position. Replace with the straight forward IR.
2767 Value *Input = II->getArgOperand(i: 0);
2768 Value *Masked = Builder.CreateAnd(LHS: Input, RHS: II->getArgOperand(i: 1));
2769 Value *ShiftAmt = ConstantInt::get(Ty: II->getType(), V: MaskIdx);
2770 Value *Shifted = Builder.CreateLShr(LHS: Masked, RHS: ShiftAmt);
2771 return replaceInstUsesWith(I&: *II, V: Shifted);
2772 }
2773 }
2774 break;
2775 }
2776 case Intrinsic::ptrmask: {
2777 unsigned BitWidth = DL.getPointerTypeSizeInBits(II->getType());
2778 KnownBits Known(BitWidth);
2779 if (SimplifyDemandedInstructionBits(Inst&: *II, Known))
2780 return II;
2781
2782 Value *InnerPtr, *InnerMask;
2783 bool Changed = false;
2784 // Combine:
2785 // (ptrmask (ptrmask p, A), B)
2786 // -> (ptrmask p, (and A, B))
2787 if (match(V: II->getArgOperand(i: 0),
2788 P: m_OneUse(SubPattern: m_Intrinsic<Intrinsic::ptrmask>(Ops: m_Value(V&: InnerPtr),
2789 Ops: m_Value(V&: InnerMask))))) {
2790 assert(II->getArgOperand(1)->getType() == InnerMask->getType() &&
2791 "Mask types must match");
2792 // TODO: If InnerMask == Op1, we could copy attributes from inner
2793 // callsite -> outer callsite.
2794 Value *NewMask = Builder.CreateAnd(LHS: II->getArgOperand(i: 1), RHS: InnerMask);
2795 replaceOperand(I&: CI, OpNum: 0, V: InnerPtr);
2796 replaceOperand(I&: CI, OpNum: 1, V: NewMask);
2797 Changed = true;
2798 }
2799
2800 // See if we can deduce non-null.
2801 if (!CI.hasRetAttr(Kind: Attribute::NonNull) &&
2802 (Known.isNonZero() ||
2803 isKnownNonZero(V: II, Q: getSimplifyQuery().getWithInstruction(I: II)))) {
2804 CI.addRetAttr(Kind: Attribute::NonNull);
2805 Changed = true;
2806 }
2807
2808 unsigned NewAlignmentLog =
2809 std::min(a: Value::MaxAlignmentExponent,
2810 b: std::min(a: BitWidth - 1, b: Known.countMinTrailingZeros()));
2811 // Known bits will capture if we had alignment information associated with
2812 // the pointer argument.
2813 if (NewAlignmentLog > Log2(A: CI.getRetAlign().valueOrOne())) {
2814 CI.addRetAttr(Attr: Attribute::getWithAlignment(
2815 Context&: CI.getContext(), Alignment: Align(uint64_t(1) << NewAlignmentLog)));
2816 Changed = true;
2817 }
2818 if (Changed)
2819 return &CI;
2820 break;
2821 }
2822 case Intrinsic::uadd_with_overflow:
2823 case Intrinsic::sadd_with_overflow: {
2824 if (Instruction *I = foldIntrinsicWithOverflowCommon(II))
2825 return I;
2826
2827 // Given 2 constant operands whose sum does not overflow:
2828 // uaddo (X +nuw C0), C1 -> uaddo X, C0 + C1
2829 // saddo (X +nsw C0), C1 -> saddo X, C0 + C1
2830 Value *X;
2831 const APInt *C0, *C1;
2832 Value *Arg0 = II->getArgOperand(i: 0);
2833 Value *Arg1 = II->getArgOperand(i: 1);
2834 bool IsSigned = IID == Intrinsic::sadd_with_overflow;
2835 bool HasNWAdd = IsSigned
2836 ? match(V: Arg0, P: m_NSWAddLike(L: m_Value(V&: X), R: m_APInt(Res&: C0)))
2837 : match(V: Arg0, P: m_NUWAddLike(L: m_Value(V&: X), R: m_APInt(Res&: C0)));
2838 if (HasNWAdd && match(V: Arg1, P: m_APInt(Res&: C1))) {
2839 bool Overflow;
2840 APInt NewC =
2841 IsSigned ? C1->sadd_ov(RHS: *C0, Overflow) : C1->uadd_ov(RHS: *C0, Overflow);
2842 if (!Overflow)
2843 return replaceInstUsesWith(
2844 I&: *II, V: Builder.CreateBinaryIntrinsic(
2845 ID: IID, LHS: X, RHS: ConstantInt::get(Ty: Arg1->getType(), V: NewC)));
2846 }
2847 break;
2848 }
2849
2850 case Intrinsic::umul_with_overflow:
2851 case Intrinsic::smul_with_overflow:
2852 case Intrinsic::usub_with_overflow:
2853 if (Instruction *I = foldIntrinsicWithOverflowCommon(II))
2854 return I;
2855 break;
2856
2857 case Intrinsic::ssub_with_overflow: {
2858 if (Instruction *I = foldIntrinsicWithOverflowCommon(II))
2859 return I;
2860
2861 Constant *C;
2862 Value *Arg0 = II->getArgOperand(i: 0);
2863 Value *Arg1 = II->getArgOperand(i: 1);
2864 // Given a constant C that is not the minimum signed value
2865 // for an integer of a given bit width:
2866 //
2867 // ssubo X, C -> saddo X, -C
2868 if (match(V: Arg1, P: m_Constant(C)) && C->isNotMinSignedValue()) {
2869 Value *NegVal = ConstantExpr::getNeg(C);
2870 // Build a saddo call that is equivalent to the discovered
2871 // ssubo call.
2872 return replaceInstUsesWith(
2873 I&: *II, V: Builder.CreateBinaryIntrinsic(ID: Intrinsic::sadd_with_overflow,
2874 LHS: Arg0, RHS: NegVal));
2875 }
2876
2877 break;
2878 }
2879
2880 case Intrinsic::uadd_sat:
2881 case Intrinsic::sadd_sat:
2882 case Intrinsic::usub_sat:
2883 case Intrinsic::ssub_sat: {
2884 SaturatingInst *SI = cast<SaturatingInst>(Val: II);
2885 Type *Ty = SI->getType();
2886 Value *Arg0 = SI->getLHS();
2887 Value *Arg1 = SI->getRHS();
2888
2889 // Make use of known overflow information.
2890 OverflowResult OR = computeOverflow(BinaryOp: SI->getBinaryOp(), IsSigned: SI->isSigned(),
2891 LHS: Arg0, RHS: Arg1, CxtI: SI);
2892 switch (OR) {
2893 case OverflowResult::MayOverflow:
2894 break;
2895 case OverflowResult::NeverOverflows:
2896 if (SI->isSigned())
2897 return BinaryOperator::CreateNSW(Opc: SI->getBinaryOp(), V1: Arg0, V2: Arg1);
2898 else
2899 return BinaryOperator::CreateNUW(Opc: SI->getBinaryOp(), V1: Arg0, V2: Arg1);
2900 case OverflowResult::AlwaysOverflowsLow: {
2901 unsigned BitWidth = Ty->getScalarSizeInBits();
2902 APInt Min = APSInt::getMinValue(numBits: BitWidth, Unsigned: !SI->isSigned());
2903 return replaceInstUsesWith(I&: *SI, V: ConstantInt::get(Ty, V: Min));
2904 }
2905 case OverflowResult::AlwaysOverflowsHigh: {
2906 unsigned BitWidth = Ty->getScalarSizeInBits();
2907 APInt Max = APSInt::getMaxValue(numBits: BitWidth, Unsigned: !SI->isSigned());
2908 return replaceInstUsesWith(I&: *SI, V: ConstantInt::get(Ty, V: Max));
2909 }
2910 }
2911
2912 // usub_sat((sub nuw C, A), C1) -> usub_sat(usub_sat(C, C1), A)
2913 // which after that:
2914 // usub_sat((sub nuw C, A), C1) -> usub_sat(C - C1, A) if C1 u< C
2915 // usub_sat((sub nuw C, A), C1) -> 0 otherwise
2916 Constant *C, *C1;
2917 Value *A;
2918 if (IID == Intrinsic::usub_sat &&
2919 match(V: Arg0, P: m_NUWSub(L: m_ImmConstant(C), R: m_Value(V&: A))) &&
2920 match(V: Arg1, P: m_ImmConstant(C&: C1))) {
2921 auto *NewC = Builder.CreateBinaryIntrinsic(ID: Intrinsic::usub_sat, LHS: C, RHS: C1);
2922 auto *NewSub =
2923 Builder.CreateBinaryIntrinsic(ID: Intrinsic::usub_sat, LHS: NewC, RHS: A);
2924 return replaceInstUsesWith(I&: *SI, V: NewSub);
2925 }
2926
2927 // ssub.sat(X, C) -> sadd.sat(X, -C) if C != MIN
2928 if (IID == Intrinsic::ssub_sat && match(V: Arg1, P: m_Constant(C)) &&
2929 C->isNotMinSignedValue()) {
2930 Value *NegVal = ConstantExpr::getNeg(C);
2931 return replaceInstUsesWith(
2932 I&: *II, V: Builder.CreateBinaryIntrinsic(
2933 ID: Intrinsic::sadd_sat, LHS: Arg0, RHS: NegVal));
2934 }
2935
2936 // sat(sat(X + Val2) + Val) -> sat(X + (Val+Val2))
2937 // sat(sat(X - Val2) - Val) -> sat(X - (Val+Val2))
2938 // if Val and Val2 have the same sign
2939 if (auto *Other = dyn_cast<IntrinsicInst>(Val: Arg0)) {
2940 Value *X;
2941 const APInt *Val, *Val2;
2942 APInt NewVal;
2943 bool IsUnsigned =
2944 IID == Intrinsic::uadd_sat || IID == Intrinsic::usub_sat;
2945 if (Other->getIntrinsicID() == IID &&
2946 match(V: Arg1, P: m_APInt(Res&: Val)) &&
2947 match(V: Other->getArgOperand(i: 0), P: m_Value(V&: X)) &&
2948 match(V: Other->getArgOperand(i: 1), P: m_APInt(Res&: Val2))) {
2949 if (IsUnsigned)
2950 NewVal = Val->uadd_sat(RHS: *Val2);
2951 else if (Val->isNonNegative() == Val2->isNonNegative()) {
2952 bool Overflow;
2953 NewVal = Val->sadd_ov(RHS: *Val2, Overflow);
2954 if (Overflow) {
2955 // Both adds together may add more than SignedMaxValue
2956 // without saturating the final result.
2957 break;
2958 }
2959 } else {
2960 // Cannot fold saturated addition with different signs.
2961 break;
2962 }
2963
2964 return replaceInstUsesWith(
2965 I&: *II, V: Builder.CreateBinaryIntrinsic(
2966 ID: IID, LHS: X, RHS: ConstantInt::get(Ty: II->getType(), V: NewVal)));
2967 }
2968 }
2969 break;
2970 }
2971
2972 case Intrinsic::minnum:
2973 case Intrinsic::maxnum:
2974 case Intrinsic::minimumnum:
2975 case Intrinsic::maximumnum:
2976 case Intrinsic::minimum:
2977 case Intrinsic::maximum: {
2978 Value *Arg0 = II->getArgOperand(i: 0);
2979 Value *Arg1 = II->getArgOperand(i: 1);
2980 Value *X, *Y;
2981 if (match(V: Arg0, P: m_FNeg(X: m_Value(V&: X))) && match(V: Arg1, P: m_FNeg(X: m_Value(V&: Y))) &&
2982 (Arg0->hasOneUse() || Arg1->hasOneUse())) {
2983 // If both operands are negated, invert the call and negate the result:
2984 // min(-X, -Y) --> -(max(X, Y))
2985 // max(-X, -Y) --> -(min(X, Y))
2986 Intrinsic::ID NewIID;
2987 switch (IID) {
2988 case Intrinsic::maxnum:
2989 NewIID = Intrinsic::minnum;
2990 break;
2991 case Intrinsic::minnum:
2992 NewIID = Intrinsic::maxnum;
2993 break;
2994 case Intrinsic::maximumnum:
2995 NewIID = Intrinsic::minimumnum;
2996 break;
2997 case Intrinsic::minimumnum:
2998 NewIID = Intrinsic::maximumnum;
2999 break;
3000 case Intrinsic::maximum:
3001 NewIID = Intrinsic::minimum;
3002 break;
3003 case Intrinsic::minimum:
3004 NewIID = Intrinsic::maximum;
3005 break;
3006 default:
3007 llvm_unreachable("unexpected intrinsic ID");
3008 }
3009 Value *NewCall = Builder.CreateBinaryIntrinsic(ID: NewIID, LHS: X, RHS: Y, FMFSource: II);
3010 Instruction *FNeg = UnaryOperator::CreateFNeg(V: NewCall);
3011 FNeg->copyIRFlags(V: II);
3012 return FNeg;
3013 }
3014
3015 // m(m(X, C2), C1) -> m(X, C)
3016 const APFloat *C1, *C2;
3017 if (auto *M = dyn_cast<IntrinsicInst>(Val: Arg0)) {
3018 if (M->getIntrinsicID() == IID && match(V: Arg1, P: m_APFloat(Res&: C1)) &&
3019 ((match(V: M->getArgOperand(i: 0), P: m_Value(V&: X)) &&
3020 match(V: M->getArgOperand(i: 1), P: m_APFloat(Res&: C2))) ||
3021 (match(V: M->getArgOperand(i: 1), P: m_Value(V&: X)) &&
3022 match(V: M->getArgOperand(i: 0), P: m_APFloat(Res&: C2))))) {
3023 APFloat Res(0.0);
3024 switch (IID) {
3025 case Intrinsic::maxnum:
3026 Res = maxnum(A: *C1, B: *C2);
3027 break;
3028 case Intrinsic::minnum:
3029 Res = minnum(A: *C1, B: *C2);
3030 break;
3031 case Intrinsic::maximumnum:
3032 Res = maximumnum(A: *C1, B: *C2);
3033 break;
3034 case Intrinsic::minimumnum:
3035 Res = minimumnum(A: *C1, B: *C2);
3036 break;
3037 case Intrinsic::maximum:
3038 Res = maximum(A: *C1, B: *C2);
3039 break;
3040 case Intrinsic::minimum:
3041 Res = minimum(A: *C1, B: *C2);
3042 break;
3043 default:
3044 llvm_unreachable("unexpected intrinsic ID");
3045 }
3046 // TODO: Conservatively intersecting FMF. If Res == C2, the transform
3047 // was a simplification (so Arg0 and its original flags could
3048 // propagate?)
3049 Value *V = Builder.CreateBinaryIntrinsic(
3050 ID: IID, LHS: X, RHS: ConstantFP::get(Ty: Arg0->getType(), V: Res),
3051 FMFSource: FMFSource::intersect(A: II, B: M));
3052 return replaceInstUsesWith(I&: *II, V);
3053 }
3054 }
3055
3056 // m((fpext X), (fpext Y)) -> fpext (m(X, Y))
3057 if (match(V: Arg0, P: m_FPExt(Op: m_Value(V&: X))) && match(V: Arg1, P: m_FPExt(Op: m_Value(V&: Y))) &&
3058 (Arg0->hasOneUse() || Arg1->hasOneUse()) &&
3059 X->getType() == Y->getType()) {
3060 Value *NewCall =
3061 Builder.CreateBinaryIntrinsic(ID: IID, LHS: X, RHS: Y, FMFSource: II, Name: II->getName());
3062 return new FPExtInst(NewCall, II->getType());
3063 }
3064
3065 // m(fpext X, C) -> fpext m(X, TruncC) if C can be losslessly truncated.
3066 Constant *C;
3067 if (match(V: Arg0, P: m_OneUse(SubPattern: m_FPExt(Op: m_Value(V&: X)))) &&
3068 match(V: Arg1, P: m_ImmConstant(C))) {
3069 if (Constant *TruncC =
3070 getLosslessInvCast(C, InvCastTo: X->getType(), CastOp: Instruction::FPExt, DL)) {
3071 Value *NewCall =
3072 Builder.CreateBinaryIntrinsic(ID: IID, LHS: X, RHS: TruncC, FMFSource: II, Name: II->getName());
3073 return new FPExtInst(NewCall, II->getType());
3074 }
3075 }
3076
3077 // max X, -X --> fabs X
3078 // min X, -X --> -(fabs X)
3079 // TODO: Remove one-use limitation? That is obviously better for max,
3080 // hence why we don't check for one-use for that. However,
3081 // it would be an extra instruction for min (fnabs), but
3082 // that is still likely better for analysis and codegen.
3083 auto IsMinMaxOrXNegX = [IID, &X](Value *Op0, Value *Op1) {
3084 if (match(V: Op0, P: m_FNeg(X: m_Value(V&: X))) && match(V: Op1, P: m_Specific(V: X)))
3085 return Op0->hasOneUse() ||
3086 (IID != Intrinsic::minimum && IID != Intrinsic::minnum &&
3087 IID != Intrinsic::minimumnum);
3088 return false;
3089 };
3090
3091 if (IsMinMaxOrXNegX(Arg0, Arg1) || IsMinMaxOrXNegX(Arg1, Arg0)) {
3092 Value *R = Builder.CreateFAbs(V: X, FMFSource: II);
3093 if (IID == Intrinsic::minimum || IID == Intrinsic::minnum ||
3094 IID == Intrinsic::minimumnum)
3095 R = Builder.CreateFNegFMF(V: R, FMFSource: II);
3096 return replaceInstUsesWith(I&: *II, V: R);
3097 }
3098
3099 break;
3100 }
3101 case Intrinsic::matrix_multiply: {
3102 // Optimize negation in matrix multiplication.
3103
3104 // -A * -B -> A * B
3105 Value *A, *B;
3106 if (match(V: II->getArgOperand(i: 0), P: m_FNeg(X: m_Value(V&: A))) &&
3107 match(V: II->getArgOperand(i: 1), P: m_FNeg(X: m_Value(V&: B)))) {
3108 replaceOperand(I&: *II, OpNum: 0, V: A);
3109 replaceOperand(I&: *II, OpNum: 1, V: B);
3110 return II;
3111 }
3112
3113 Value *Op0 = II->getOperand(i_nocapture: 0);
3114 Value *Op1 = II->getOperand(i_nocapture: 1);
3115 Value *OpNotNeg, *NegatedOp;
3116 unsigned NegatedOpArg, OtherOpArg;
3117 if (match(V: Op0, P: m_FNeg(X: m_Value(V&: OpNotNeg)))) {
3118 NegatedOp = Op0;
3119 NegatedOpArg = 0;
3120 OtherOpArg = 1;
3121 } else if (match(V: Op1, P: m_FNeg(X: m_Value(V&: OpNotNeg)))) {
3122 NegatedOp = Op1;
3123 NegatedOpArg = 1;
3124 OtherOpArg = 0;
3125 } else
3126 // Multiplication doesn't have a negated operand.
3127 break;
3128
3129 // Only optimize if the negated operand has only one use.
3130 if (!NegatedOp->hasOneUse())
3131 break;
3132
3133 Value *OtherOp = II->getOperand(i_nocapture: OtherOpArg);
3134 VectorType *RetTy = cast<VectorType>(Val: II->getType());
3135 VectorType *NegatedOpTy = cast<VectorType>(Val: NegatedOp->getType());
3136 VectorType *OtherOpTy = cast<VectorType>(Val: OtherOp->getType());
3137 ElementCount NegatedCount = NegatedOpTy->getElementCount();
3138 ElementCount OtherCount = OtherOpTy->getElementCount();
3139 ElementCount RetCount = RetTy->getElementCount();
3140 // (-A) * B -> A * (-B), if it is cheaper to negate B and vice versa.
3141 if (ElementCount::isKnownGT(LHS: NegatedCount, RHS: OtherCount) &&
3142 ElementCount::isKnownLT(LHS: OtherCount, RHS: RetCount)) {
3143 Value *InverseOtherOp = Builder.CreateFNeg(V: OtherOp);
3144 replaceOperand(I&: *II, OpNum: NegatedOpArg, V: OpNotNeg);
3145 replaceOperand(I&: *II, OpNum: OtherOpArg, V: InverseOtherOp);
3146 return II;
3147 }
3148 // (-A) * B -> -(A * B), if it is cheaper to negate the result
3149 if (ElementCount::isKnownGT(LHS: NegatedCount, RHS: RetCount)) {
3150 SmallVector<Value *, 5> NewArgs(II->args());
3151 NewArgs[NegatedOpArg] = OpNotNeg;
3152 Value *NewMul = Builder.CreateIntrinsic(RetTy: II->getType(), ID: IID, Args: NewArgs, FMFSource: II);
3153 return replaceInstUsesWith(I&: *II, V: Builder.CreateFNegFMF(V: NewMul, FMFSource: II));
3154 }
3155 break;
3156 }
3157 case Intrinsic::fmuladd: {
3158 // Try to simplify the underlying FMul.
3159 if (Value *V =
3160 simplifyFMulInst(LHS: II->getArgOperand(i: 0), RHS: II->getArgOperand(i: 1),
3161 FMF: II->getFastMathFlags(), Q: SQ.getWithInstruction(I: II)))
3162 return BinaryOperator::CreateFAddFMF(V1: V, V2: II->getArgOperand(i: 2),
3163 FMF: II->getFastMathFlags());
3164
3165 [[fallthrough]];
3166 }
3167 case Intrinsic::fma: {
3168 // fma fneg(x), fneg(y), z -> fma x, y, z
3169 Value *Src0 = II->getArgOperand(i: 0);
3170 Value *Src1 = II->getArgOperand(i: 1);
3171 Value *Src2 = II->getArgOperand(i: 2);
3172 Value *X, *Y;
3173 if (match(V: Src0, P: m_FNeg(X: m_Value(V&: X))) && match(V: Src1, P: m_FNeg(X: m_Value(V&: Y))))
3174 return replaceInstUsesWith(
3175 I&: *II, V: Builder.CreateIntrinsic(ID: IID, OverloadTypes: II->getType(), Args: {X, Y, Src2}, FMFSource: II));
3176
3177 // fma fabs(x), fabs(x), z -> fma x, x, z
3178 if (match(V: Src0, P: m_FAbs(Op0: m_Value(V&: X))) && match(V: Src1, P: m_FAbs(Op0: m_Specific(V: X))))
3179 return replaceInstUsesWith(
3180 I&: *II, V: Builder.CreateIntrinsic(ID: IID, OverloadTypes: II->getType(), Args: {X, X, Src2}, FMFSource: II));
3181
3182 // Try to simplify the underlying FMul. We can only apply simplifications
3183 // that do not require rounding.
3184 if (Value *V = simplifyFMAFMul(LHS: Src0, RHS: Src1, FMF: II->getFastMathFlags(),
3185 Q: SQ.getWithInstruction(I: II)))
3186 return BinaryOperator::CreateFAddFMF(V1: V, V2: Src2, FMF: II->getFastMathFlags());
3187
3188 // fma x, y, 0 -> fmul x, y
3189 // This is always valid for -0.0, but requires nsz for +0.0 as
3190 // -0.0 + 0.0 = 0.0, which would not be the same as the fmul on its own.
3191 if (match(V: Src2, P: m_NegZeroFP()) ||
3192 (match(V: Src2, P: m_PosZeroFP()) && II->getFastMathFlags().noSignedZeros()))
3193 return BinaryOperator::CreateFMulFMF(V1: Src0, V2: Src1, FMFSource: II);
3194
3195 // fma x, -1.0, y -> fsub y, x
3196 if (match(V: Src1, P: m_SpecificFP(V: -1.0)))
3197 return BinaryOperator::CreateFSubFMF(V1: Src2, V2: Src0, FMFSource: II);
3198
3199 break;
3200 }
3201 case Intrinsic::copysign: {
3202 Value *Mag = II->getArgOperand(i: 0), *Sign = II->getArgOperand(i: 1);
3203 if (std::optional<bool> KnownSignBit = computeKnownFPSignBit(
3204 V: Sign, SQ: getSimplifyQuery().getWithInstruction(I: II))) {
3205 if (*KnownSignBit) {
3206 // If we know that the sign argument is negative, reduce to FNABS:
3207 // copysign Mag, -Sign --> fneg (fabs Mag)
3208 Value *Fabs = Builder.CreateFAbs(V: Mag, FMFSource: II);
3209 return replaceInstUsesWith(I&: *II, V: Builder.CreateFNegFMF(V: Fabs, FMFSource: II));
3210 }
3211
3212 // If we know that the sign argument is positive, reduce to FABS:
3213 // copysign Mag, +Sign --> fabs Mag
3214 Value *Fabs = Builder.CreateFAbs(V: Mag, FMFSource: II);
3215 return replaceInstUsesWith(I&: *II, V: Fabs);
3216 }
3217
3218 // Propagate sign argument through nested calls:
3219 // copysign Mag, (copysign ?, X) --> copysign Mag, X
3220 Value *X;
3221 if (match(V: Sign, P: m_Intrinsic<Intrinsic::copysign>(Ops: m_Value(), Ops: m_Value(V&: X)))) {
3222 Value *CopySign =
3223 Builder.CreateCopySign(LHS: Mag, RHS: X, FMFSource: FMFSource::intersect(A: II, B: Sign));
3224 return replaceInstUsesWith(I&: *II, V: CopySign);
3225 }
3226
3227 // Clear sign-bit of constant magnitude:
3228 // copysign -MagC, X --> copysign MagC, X
3229 // TODO: Support constant folding for fabs
3230 const APFloat *MagC;
3231 if (match(V: Mag, P: m_APFloat(Res&: MagC)) && MagC->isNegative()) {
3232 APFloat PosMagC = *MagC;
3233 PosMagC.clearSign();
3234 return replaceInstUsesWith(
3235 I&: *II, V: Builder.CreateCopySign(LHS: ConstantFP::get(Ty: Mag->getType(), V: PosMagC),
3236 RHS: Sign, FMFSource: II));
3237 }
3238
3239 // Peek through changes of magnitude's sign-bit. This call rewrites those:
3240 // copysign (fabs X), Sign --> copysign X, Sign
3241 // copysign (fneg X), Sign --> copysign X, Sign
3242 if (match(V: Mag, P: m_FAbs(Op0: m_Value(V&: X))) || match(V: Mag, P: m_FNeg(X: m_Value(V&: X))))
3243 return replaceInstUsesWith(I&: *II, V: Builder.CreateCopySign(LHS: X, RHS: Sign, FMFSource: II));
3244
3245 // copysign(floor(fabs(X)), X) --> copysign(trunc(X), X)
3246 // copysign ignores the sign bit of its magnitude argument (implicit fabs),
3247 // so replacing floor(fabs(X)) with trunc(X) is correct for all inputs
3248 // including NaN without requiring nnan. The m_FAbs match also ensures
3249 // the floor argument is non-negative, so floor == trunc.
3250 Value *FAbsArg;
3251 if (match(V: Mag, P: m_Intrinsic<Intrinsic::floor>(Ops: m_FAbs(Op0: m_Value(V&: FAbsArg)))) &&
3252 FAbsArg == Sign) {
3253 Value *Trunc = Builder.CreateUnaryIntrinsic(ID: Intrinsic::trunc, Op: Sign, FMFSource: II);
3254 return replaceInstUsesWith(I&: *II, V: Builder.CreateCopySign(LHS: Trunc, RHS: Sign, FMFSource: II));
3255 }
3256
3257 Type *SignEltTy = Sign->getType()->getScalarType();
3258
3259 Value *CastSrc;
3260 if (match(V: Sign,
3261 P: m_OneUse(SubPattern: m_ElementWiseBitCast(Op: m_OneUse(SubPattern: m_Value(V&: CastSrc))))) &&
3262 CastSrc->getType()->isIntOrIntVectorTy() &&
3263 APFloat::hasSignBitInMSB(SignEltTy->getFltSemantics())) {
3264 KnownBits Known(SignEltTy->getPrimitiveSizeInBits());
3265 if (SimplifyDemandedBits(I: cast<Instruction>(Val: Sign), Op: 0,
3266 DemandedMask: APInt::getSignMask(BitWidth: Known.getBitWidth()), Known,
3267 Q: SQ))
3268 return II;
3269 }
3270
3271 break;
3272 }
3273 case Intrinsic::fabs: {
3274 Value *Cond, *TVal, *FVal;
3275 Value *Arg = II->getArgOperand(i: 0);
3276 Value *X;
3277 // fabs (-X) --> fabs (X)
3278 if (match(V: Arg, P: m_FNeg(X: m_Value(V&: X)))) {
3279 Value *Fabs = Builder.CreateFAbs(V: X, FMFSource: II);
3280 return replaceInstUsesWith(I&: CI, V: Fabs);
3281 }
3282
3283 if (match(V: Arg, P: m_Select(C: m_Value(V&: Cond), L: m_Value(V&: TVal), R: m_Value(V&: FVal)))) {
3284 // fabs (select Cond, TrueC, FalseC) --> select Cond, AbsT, AbsF
3285 if (Arg->hasOneUse() ? (isa<Constant>(Val: TVal) || isa<Constant>(Val: FVal))
3286 : (isa<Constant>(Val: TVal) && isa<Constant>(Val: FVal))) {
3287 CallInst *AbsT = Builder.CreateCall(Callee: II->getCalledFunction(), Args: {TVal});
3288 CallInst *AbsF = Builder.CreateCall(Callee: II->getCalledFunction(), Args: {FVal});
3289 SelectInst *SI = SelectInst::Create(C: Cond, S1: AbsT, S2: AbsF);
3290 SI->setFastMathFlags(II->getFastMathFlags() |
3291 cast<SelectInst>(Val: Arg)->getFastMathFlags());
3292 // Can't copy nsz to select, as even with the nsz flag the fabs result
3293 // always has the sign bit unset.
3294 SI->setHasNoSignedZeros(false);
3295 return SI;
3296 }
3297 // fabs (select Cond, -FVal, FVal) --> fabs FVal
3298 if (match(V: TVal, P: m_FNeg(X: m_Specific(V: FVal))))
3299 return replaceInstUsesWith(I&: *II, V: Builder.CreateFAbs(V: FVal, FMFSource: II));
3300 // fabs (select Cond, TVal, -TVal) --> fabs TVal
3301 if (match(V: FVal, P: m_FNeg(X: m_Specific(V: TVal))))
3302 return replaceInstUsesWith(I&: *II, V: Builder.CreateFAbs(V: TVal, FMFSource: II));
3303 }
3304
3305 Value *Magnitude, *Sign;
3306 if (match(V: II->getArgOperand(i: 0),
3307 P: m_CopySign(Op0: m_Value(V&: Magnitude), Op1: m_Value(V&: Sign)))) {
3308 // fabs (copysign x, y) -> (fabs x)
3309 Value *AbsSign = Builder.CreateFAbs(V: Magnitude, FMFSource: II);
3310 return replaceInstUsesWith(I&: *II, V: AbsSign);
3311 }
3312
3313 [[fallthrough]];
3314 }
3315 case Intrinsic::ceil:
3316 case Intrinsic::floor:
3317 case Intrinsic::round:
3318 case Intrinsic::roundeven:
3319 case Intrinsic::nearbyint:
3320 case Intrinsic::rint:
3321 case Intrinsic::trunc: {
3322 Value *ExtSrc;
3323 if (match(V: II->getArgOperand(i: 0), P: m_OneUse(SubPattern: m_FPExt(Op: m_Value(V&: ExtSrc))))) {
3324 // Narrow the call: intrinsic (fpext x) -> fpext (intrinsic x)
3325 Value *NarrowII = Builder.CreateUnaryIntrinsic(ID: IID, Op: ExtSrc, FMFSource: II);
3326 return new FPExtInst(NarrowII, II->getType());
3327 }
3328 break;
3329 }
3330 case Intrinsic::cos:
3331 case Intrinsic::amdgcn_cos:
3332 case Intrinsic::cosh: {
3333 Value *X, *Sign;
3334 Value *Src = II->getArgOperand(i: 0);
3335 if (match(V: Src, P: m_FNeg(X: m_Value(V&: X))) || match(V: Src, P: m_FAbs(Op0: m_Value(V&: X))) ||
3336 match(V: Src, P: m_CopySign(Op0: m_Value(V&: X), Op1: m_Value(V&: Sign)))) {
3337 // f(-x) --> f(x)
3338 // f(fabs(x)) --> f(x)
3339 // f(copysign(x, y)) --> f(x)
3340 // for f in {cos, cosh}
3341 return replaceInstUsesWith(I&: *II, V: Builder.CreateUnaryIntrinsic(ID: IID, Op: X, FMFSource: II));
3342 }
3343 if (IID == Intrinsic::cos) {
3344 if (Value *Result = foldSinAndCosToSinCos(II, B&: Builder, IC&: *this))
3345 return replaceInstUsesWith(I&: *II, V: Result);
3346 }
3347 break;
3348 }
3349 case Intrinsic::sin:
3350 case Intrinsic::amdgcn_sin:
3351 case Intrinsic::sinh:
3352 case Intrinsic::tan:
3353 case Intrinsic::tanh: {
3354 Value *X;
3355 if (match(V: II->getArgOperand(i: 0), P: m_OneUse(SubPattern: m_FNeg(X: m_Value(V&: X))))) {
3356 // f(-x) --> -f(x)
3357 // for f in {sin, sinh, tan, tanh}
3358 Value *NewFunc = Builder.CreateUnaryIntrinsic(ID: IID, Op: X, FMFSource: II);
3359 return UnaryOperator::CreateFNegFMF(Op: NewFunc, FMFSource: II);
3360 }
3361 if (IID == Intrinsic::sin) {
3362 if (Value *Result = foldSinAndCosToSinCos(II, B&: Builder, IC&: *this))
3363 return replaceInstUsesWith(I&: *II, V: Result);
3364 }
3365 break;
3366 }
3367 case Intrinsic::ldexp: {
3368 Value *Src = II->getArgOperand(i: 0);
3369 Value *Exp = II->getArgOperand(i: 1);
3370
3371 // ldexp(x, K) -> fmul x, 2^K
3372 uint64_t ConstExp;
3373 if (match(V: Exp, P: m_ConstantInt(V&: ConstExp))) {
3374 const fltSemantics &FPTy =
3375 Src->getType()->getScalarType()->getFltSemantics();
3376
3377 APFloat Scaled = scalbn(X: APFloat::getOne(Sem: FPTy), Exp: static_cast<int>(ConstExp),
3378 RM: APFloat::rmNearestTiesToEven);
3379 if (!Scaled.isZero() && !Scaled.isInfinity()) {
3380 // Skip overflow and underflow cases.
3381 Constant *FPConst = ConstantFP::get(Ty: Src->getType(), V: Scaled);
3382 return BinaryOperator::CreateFMulFMF(V1: Src, V2: FPConst, FMFSource: II);
3383 }
3384 }
3385
3386 // ldexp(ldexp(x, a), b) -> ldexp(x, sadd.sat(a, b))
3387 //
3388 // A danger is if the first ldexp would overflow to infinity or underflow to
3389 // zero, but the combined exponent avoids it.
3390 //
3391 // We ignore this with reassoc, or if we know both exponents have the same
3392 // sign (since then we'd just double down on the over/underflow which would
3393 // occur anyway).
3394 //
3395 // ldexp can take arbitrary integer types, so we also need to ensure that
3396 // our exponent type is wide enough so that if sadd.sat(a, b) saturates,
3397 // then ldexp at the saturated exponent saturates to inf or zero as well.
3398 //
3399 // TODO: Could do better if we had range tracking for the input value
3400 // exponent. Also could broaden sign check to cover == 0 case.
3401 Value *InnerSrc;
3402 Value *InnerExp;
3403 if (match(V: Src, P: m_OneUse(SubPattern: m_Intrinsic<Intrinsic::ldexp>(
3404 Ops: m_Value(V&: InnerSrc), Ops: m_Value(V&: InnerExp)))) &&
3405 Exp->getType() == InnerExp->getType()) {
3406 FastMathFlags FMF = II->getFastMathFlags();
3407 FastMathFlags InnerFlags = cast<FPMathOperator>(Val: Src)->getFastMathFlags();
3408
3409 if (ldexpSaturatingAddIsSafe(FpTy: II->getType(), ExpTy: Exp->getType()) &&
3410 ((FMF.allowReassoc() && InnerFlags.allowReassoc()) ||
3411 signBitMustBeTheSame(Op0: Exp, Op1: InnerExp, SQ: SQ.getWithInstruction(I: II)))) {
3412 Value *NewExp =
3413 Builder.CreateBinaryIntrinsic(ID: Intrinsic::sadd_sat, LHS: InnerExp, RHS: Exp);
3414 return replaceInstUsesWith(
3415 I&: *II, V: Builder.CreateLdexp(Src: InnerSrc, Exp: NewExp, FMFSource: FMF | InnerFlags));
3416 }
3417 }
3418
3419 // ldexp(x, zext(i1 y)) -> fmul x, (select y, 2.0, 1.0)
3420 // ldexp(x, sext(i1 y)) -> fmul x, (select y, 0.5, 1.0)
3421 Value *ExtSrc;
3422 if (match(V: Exp, P: m_ZExt(Op: m_Value(V&: ExtSrc))) &&
3423 ExtSrc->getType()->getScalarSizeInBits() == 1) {
3424 Value *Select =
3425 Builder.CreateSelect(C: ExtSrc, True: ConstantFP::get(Ty: II->getType(), V: 2.0),
3426 False: ConstantFP::get(Ty: II->getType(), V: 1.0));
3427 return BinaryOperator::CreateFMulFMF(V1: Src, V2: Select, FMFSource: II);
3428 }
3429 if (match(V: Exp, P: m_SExt(Op: m_Value(V&: ExtSrc))) &&
3430 ExtSrc->getType()->getScalarSizeInBits() == 1) {
3431 Value *Select =
3432 Builder.CreateSelect(C: ExtSrc, True: ConstantFP::get(Ty: II->getType(), V: 0.5),
3433 False: ConstantFP::get(Ty: II->getType(), V: 1.0));
3434 return BinaryOperator::CreateFMulFMF(V1: Src, V2: Select, FMFSource: II);
3435 }
3436
3437 // ldexp(x, c ? exp : 0) -> c ? ldexp(x, exp) : x
3438 // ldexp(x, c ? 0 : exp) -> c ? x : ldexp(x, exp)
3439 ///
3440 // TODO: If we cared, should insert a canonicalize for x
3441 Value *SelectCond, *SelectLHS, *SelectRHS;
3442 if (match(V: II->getArgOperand(i: 1),
3443 P: m_OneUse(SubPattern: m_Select(C: m_Value(V&: SelectCond), L: m_Value(V&: SelectLHS),
3444 R: m_Value(V&: SelectRHS))))) {
3445 Value *NewLdexp = nullptr;
3446 Value *Select = nullptr;
3447 if (match(V: SelectRHS, P: m_ZeroInt())) {
3448 NewLdexp = Builder.CreateLdexp(Src, Exp: SelectLHS, FMFSource: II);
3449 Select = Builder.CreateSelect(C: SelectCond, True: NewLdexp, False: Src);
3450 } else if (match(V: SelectLHS, P: m_ZeroInt())) {
3451 NewLdexp = Builder.CreateLdexp(Src, Exp: SelectRHS, FMFSource: II);
3452 Select = Builder.CreateSelect(C: SelectCond, True: Src, False: NewLdexp);
3453 }
3454
3455 if (NewLdexp) {
3456 Select->takeName(V: II);
3457 return replaceInstUsesWith(I&: *II, V: Select);
3458 }
3459 }
3460
3461 break;
3462 }
3463 case Intrinsic::ptrauth_auth:
3464 case Intrinsic::ptrauth_resign: {
3465 // (sign|resign) + (auth|resign) can be folded by omitting the middle
3466 // sign+auth component if the key and discriminator match.
3467 bool NeedSign = II->getIntrinsicID() == Intrinsic::ptrauth_resign;
3468 Value *Ptr = II->getArgOperand(i: 0);
3469 Value *Key = II->getArgOperand(i: 1);
3470 Value *Disc = II->getArgOperand(i: 2);
3471 Value *DS = nullptr;
3472 if (auto Bundle = II->getOperandBundle(ID: LLVMContext::OB_deactivation_symbol))
3473 DS = Bundle->Inputs[0];
3474
3475 // AuthKey will be the key we need to end up authenticating against in
3476 // whatever we replace this sequence with.
3477 Value *AuthKey = nullptr, *AuthDisc = nullptr, *BasePtr;
3478 if (const auto *CI = dyn_cast<CallBase>(Val: Ptr)) {
3479 Value *OtherDS = nullptr;
3480 if (auto Bundle =
3481 CI->getOperandBundle(ID: LLVMContext::OB_deactivation_symbol))
3482 OtherDS = Bundle->Inputs[0];
3483 if (DS != OtherDS)
3484 break;
3485
3486 if (CI->getIntrinsicID() == Intrinsic::ptrauth_sign) {
3487 if (CI->getArgOperand(i: 1) != Key || CI->getArgOperand(i: 2) != Disc)
3488 break;
3489 } else if (CI->getIntrinsicID() == Intrinsic::ptrauth_resign) {
3490 // The resign intrinsic does not support deactivation symbols.
3491 assert(!DS);
3492 if (CI->getArgOperand(i: 3) != Key || CI->getArgOperand(i: 4) != Disc)
3493 break;
3494 AuthKey = CI->getArgOperand(i: 1);
3495 AuthDisc = CI->getArgOperand(i: 2);
3496 } else
3497 break;
3498 BasePtr = CI->getArgOperand(i: 0);
3499 } else if (const auto *PtrToInt = dyn_cast<PtrToIntOperator>(Val: Ptr)) {
3500 // ptrauth constants are equivalent to a call to @llvm.ptrauth.sign for
3501 // our purposes, so check for that too.
3502 const auto *CPA = dyn_cast<ConstantPtrAuth>(Val: PtrToInt->getOperand(i_nocapture: 0));
3503 if (!CPA || DS || !CPA->isKnownCompatibleWith(Key, Discriminator: Disc, DL))
3504 break;
3505
3506 // resign(ptrauth(p,ks,ds),ks,ds,kr,dr) -> ptrauth(p,kr,dr)
3507 if (NeedSign && isa<ConstantInt>(Val: II->getArgOperand(i: 4))) {
3508 auto *SignKey = cast<ConstantInt>(Val: II->getArgOperand(i: 3));
3509 auto *SignDisc = cast<ConstantInt>(Val: II->getArgOperand(i: 4));
3510 auto *Null = ConstantPointerNull::get(T: Builder.getPtrTy());
3511 auto *NewCPA = ConstantPtrAuth::get(Ptr: CPA->getPointer(), Key: SignKey,
3512 Disc: SignDisc, /*AddrDisc=*/Null,
3513 /*DeactivationSymbol=*/Null);
3514 replaceInstUsesWith(
3515 I&: *II, V: ConstantExpr::getPointerCast(C: NewCPA, Ty: II->getType()));
3516 return eraseInstFromFunction(I&: *II);
3517 }
3518
3519 // auth(ptrauth(p,k,d),k,d) -> p
3520 BasePtr = Builder.CreatePtrToInt(V: CPA->getPointer(), DestTy: II->getType());
3521 } else
3522 break;
3523
3524 unsigned NewIntrin;
3525 if (AuthKey && NeedSign) {
3526 // resign(0,1) + resign(1,2) = resign(0, 2)
3527 NewIntrin = Intrinsic::ptrauth_resign;
3528 } else if (AuthKey) {
3529 // resign(0,1) + auth(1) = auth(0)
3530 NewIntrin = Intrinsic::ptrauth_auth;
3531 } else if (NeedSign) {
3532 // sign(0) + resign(0, 1) = sign(1)
3533 NewIntrin = Intrinsic::ptrauth_sign;
3534 } else {
3535 // sign(0) + auth(0) = nop
3536 replaceInstUsesWith(I&: *II, V: BasePtr);
3537 return eraseInstFromFunction(I&: *II);
3538 }
3539
3540 SmallVector<Value *, 4> CallArgs;
3541 CallArgs.push_back(Elt: BasePtr);
3542 if (AuthKey) {
3543 CallArgs.push_back(Elt: AuthKey);
3544 CallArgs.push_back(Elt: AuthDisc);
3545 }
3546
3547 if (NeedSign) {
3548 CallArgs.push_back(Elt: II->getArgOperand(i: 3));
3549 CallArgs.push_back(Elt: II->getArgOperand(i: 4));
3550 }
3551
3552 std::vector<OperandBundleDef> Bundles;
3553 if (DS)
3554 Bundles.push_back(x: OperandBundleDef("deactivation-symbol", DS));
3555
3556 Function *NewFn =
3557 Intrinsic::getOrInsertDeclaration(M: II->getModule(), id: NewIntrin);
3558 return CallInst::Create(Func: NewFn, Args: CallArgs, Bundles);
3559 }
3560 case Intrinsic::arm_neon_vtbl1:
3561 case Intrinsic::arm_neon_vtbl2:
3562 case Intrinsic::arm_neon_vtbl3:
3563 case Intrinsic::arm_neon_vtbl4:
3564 case Intrinsic::aarch64_neon_tbl1:
3565 case Intrinsic::aarch64_neon_tbl2:
3566 case Intrinsic::aarch64_neon_tbl3:
3567 case Intrinsic::aarch64_neon_tbl4:
3568 return simplifyNeonTbl(II&: *II, IC&: *this, /*IsExtension=*/false);
3569 case Intrinsic::arm_neon_vtbx1:
3570 case Intrinsic::arm_neon_vtbx2:
3571 case Intrinsic::arm_neon_vtbx3:
3572 case Intrinsic::arm_neon_vtbx4:
3573 case Intrinsic::aarch64_neon_tbx1:
3574 case Intrinsic::aarch64_neon_tbx2:
3575 case Intrinsic::aarch64_neon_tbx3:
3576 case Intrinsic::aarch64_neon_tbx4:
3577 return simplifyNeonTbl(II&: *II, IC&: *this, /*IsExtension=*/true);
3578
3579 case Intrinsic::arm_neon_vmulls:
3580 case Intrinsic::arm_neon_vmullu:
3581 case Intrinsic::aarch64_neon_smull:
3582 case Intrinsic::aarch64_neon_umull: {
3583 Value *Arg0 = II->getArgOperand(i: 0);
3584 Value *Arg1 = II->getArgOperand(i: 1);
3585
3586 // Handle mul by zero first:
3587 if (isa<ConstantAggregateZero>(Val: Arg0) || isa<ConstantAggregateZero>(Val: Arg1)) {
3588 return replaceInstUsesWith(I&: CI, V: ConstantAggregateZero::get(Ty: II->getType()));
3589 }
3590
3591 // Check for constant LHS & RHS - in this case we just simplify.
3592 bool Zext = (IID == Intrinsic::arm_neon_vmullu ||
3593 IID == Intrinsic::aarch64_neon_umull);
3594 VectorType *NewVT = cast<VectorType>(Val: II->getType());
3595 if (Constant *CV0 = dyn_cast<Constant>(Val: Arg0)) {
3596 if (Constant *CV1 = dyn_cast<Constant>(Val: Arg1)) {
3597 Value *V0 = Builder.CreateIntCast(V: CV0, DestTy: NewVT, /*isSigned=*/!Zext);
3598 Value *V1 = Builder.CreateIntCast(V: CV1, DestTy: NewVT, /*isSigned=*/!Zext);
3599 return replaceInstUsesWith(I&: CI, V: Builder.CreateMul(LHS: V0, RHS: V1));
3600 }
3601
3602 // Couldn't simplify - canonicalize constant to the RHS.
3603 std::swap(a&: Arg0, b&: Arg1);
3604 }
3605
3606 // Handle mul by one:
3607 if (Constant *CV1 = dyn_cast<Constant>(Val: Arg1))
3608 if (ConstantInt *Splat =
3609 dyn_cast_or_null<ConstantInt>(Val: CV1->getSplatValue()))
3610 if (Splat->isOne())
3611 return CastInst::CreateIntegerCast(S: Arg0, Ty: II->getType(),
3612 /*isSigned=*/!Zext);
3613
3614 break;
3615 }
3616 case Intrinsic::arm_neon_aesd:
3617 case Intrinsic::arm_neon_aese:
3618 case Intrinsic::aarch64_crypto_aesd:
3619 case Intrinsic::aarch64_crypto_aese:
3620 case Intrinsic::aarch64_sve_aesd:
3621 case Intrinsic::aarch64_sve_aese: {
3622 Value *DataArg = II->getArgOperand(i: 0);
3623 Value *KeyArg = II->getArgOperand(i: 1);
3624
3625 // Accept zero on either operand.
3626 if (!match(V: KeyArg, P: m_ZeroInt()))
3627 std::swap(a&: KeyArg, b&: DataArg);
3628
3629 // Try to use the builtin XOR in AESE and AESD to eliminate a prior XOR
3630 Value *Data, *Key;
3631 if (match(V: KeyArg, P: m_ZeroInt()) &&
3632 match(V: DataArg, P: m_Xor(L: m_Value(V&: Data), R: m_Value(V&: Key)))) {
3633 replaceOperand(I&: *II, OpNum: 0, V: Data);
3634 replaceOperand(I&: *II, OpNum: 1, V: Key);
3635 return II;
3636 }
3637 break;
3638 }
3639 case Intrinsic::arm_neon_vshifts:
3640 case Intrinsic::arm_neon_vshiftu:
3641 case Intrinsic::aarch64_neon_sshl:
3642 case Intrinsic::aarch64_neon_ushl:
3643 return foldNeonShift(II, IC&: *this);
3644 case Intrinsic::hexagon_V6_vandvrt:
3645 case Intrinsic::hexagon_V6_vandvrt_128B: {
3646 // Simplify Q -> V -> Q conversion.
3647 if (auto Op0 = dyn_cast<IntrinsicInst>(Val: II->getArgOperand(i: 0))) {
3648 Intrinsic::ID ID0 = Op0->getIntrinsicID();
3649 if (ID0 != Intrinsic::hexagon_V6_vandqrt &&
3650 ID0 != Intrinsic::hexagon_V6_vandqrt_128B)
3651 break;
3652 Value *Bytes = Op0->getArgOperand(i: 1), *Mask = II->getArgOperand(i: 1);
3653 uint64_t Bytes1 = computeKnownBits(V: Bytes, CxtI: Op0).One.getZExtValue();
3654 uint64_t Mask1 = computeKnownBits(V: Mask, CxtI: II).One.getZExtValue();
3655 // Check if every byte has common bits in Bytes and Mask.
3656 uint64_t C = Bytes1 & Mask1;
3657 if ((C & 0xFF) && (C & 0xFF00) && (C & 0xFF0000) && (C & 0xFF000000))
3658 return replaceInstUsesWith(I&: *II, V: Op0->getArgOperand(i: 0));
3659 }
3660 break;
3661 }
3662 case Intrinsic::stackrestore: {
3663 enum class ClassifyResult {
3664 None,
3665 Alloca,
3666 StackRestore,
3667 CallWithSideEffects,
3668 };
3669 auto Classify = [](const Instruction *I) {
3670 if (isa<AllocaInst>(Val: I))
3671 return ClassifyResult::Alloca;
3672
3673 if (auto *CI = dyn_cast<CallInst>(Val: I)) {
3674 if (auto *II = dyn_cast<IntrinsicInst>(Val: CI)) {
3675 if (II->getIntrinsicID() == Intrinsic::stackrestore)
3676 return ClassifyResult::StackRestore;
3677
3678 if (II->mayHaveSideEffects())
3679 return ClassifyResult::CallWithSideEffects;
3680 } else {
3681 // Consider all non-intrinsic calls to be side effects
3682 return ClassifyResult::CallWithSideEffects;
3683 }
3684 }
3685
3686 return ClassifyResult::None;
3687 };
3688
3689 // If the stacksave and the stackrestore are in the same BB, and there is
3690 // no intervening call, alloca, or stackrestore of a different stacksave,
3691 // remove the restore. This can happen when variable allocas are DCE'd.
3692 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(Val: II->getArgOperand(i: 0))) {
3693 if (SS->getIntrinsicID() == Intrinsic::stacksave &&
3694 SS->getParent() == II->getParent()) {
3695 BasicBlock::iterator BI(SS);
3696 bool CannotRemove = false;
3697 for (++BI; &*BI != II; ++BI) {
3698 switch (Classify(&*BI)) {
3699 case ClassifyResult::None:
3700 // So far so good, look at next instructions.
3701 break;
3702
3703 case ClassifyResult::StackRestore:
3704 // If we found an intervening stackrestore for a different
3705 // stacksave, we can't remove the stackrestore. Otherwise, continue.
3706 if (cast<IntrinsicInst>(Val&: *BI).getArgOperand(i: 0) != SS)
3707 CannotRemove = true;
3708 break;
3709
3710 case ClassifyResult::Alloca:
3711 case ClassifyResult::CallWithSideEffects:
3712 // If we found an alloca, a non-intrinsic call, or an intrinsic
3713 // call with side effects, we can't remove the stackrestore.
3714 CannotRemove = true;
3715 break;
3716 }
3717 if (CannotRemove)
3718 break;
3719 }
3720
3721 if (!CannotRemove)
3722 return eraseInstFromFunction(I&: CI);
3723 }
3724 }
3725
3726 // Scan down this block to see if there is another stack restore in the
3727 // same block without an intervening call/alloca.
3728 BasicBlock::iterator BI(II);
3729 Instruction *TI = II->getParent()->getTerminator();
3730 bool CannotRemove = false;
3731 for (++BI; &*BI != TI; ++BI) {
3732 switch (Classify(&*BI)) {
3733 case ClassifyResult::None:
3734 // So far so good, look at next instructions.
3735 break;
3736
3737 case ClassifyResult::StackRestore:
3738 // If there is a stackrestore below this one, remove this one.
3739 return eraseInstFromFunction(I&: CI);
3740
3741 case ClassifyResult::Alloca:
3742 case ClassifyResult::CallWithSideEffects:
3743 // If we found an alloca, a non-intrinsic call, or an intrinsic call
3744 // with side effects (such as llvm.stacksave and llvm.read_register),
3745 // we can't remove the stack restore.
3746 CannotRemove = true;
3747 break;
3748 }
3749 if (CannotRemove)
3750 break;
3751 }
3752
3753 // If the stack restore is in a return, resume, or unwind block and if there
3754 // are no allocas or calls between the restore and the return, nuke the
3755 // restore.
3756 if (!CannotRemove && (isa<ReturnInst>(Val: TI) || isa<ResumeInst>(Val: TI)))
3757 return eraseInstFromFunction(I&: CI);
3758 break;
3759 }
3760 case Intrinsic::lifetime_end:
3761 // Asan needs to poison memory to detect invalid access which is possible
3762 // even for empty lifetime range.
3763 if (II->getFunction()->hasFnAttribute(Kind: Attribute::SanitizeAddress) ||
3764 II->getFunction()->hasFnAttribute(Kind: Attribute::SanitizeMemory) ||
3765 II->getFunction()->hasFnAttribute(Kind: Attribute::SanitizeHWAddress) ||
3766 II->getFunction()->hasFnAttribute(Kind: Attribute::SanitizeMemTag))
3767 break;
3768
3769 if (removeTriviallyEmptyRange(EndI&: *II, IC&: *this, IsStart: [](const IntrinsicInst &I) {
3770 return I.getIntrinsicID() == Intrinsic::lifetime_start;
3771 }))
3772 return nullptr;
3773 break;
3774 case Intrinsic::assume: {
3775 for (auto [Idx, OBU] : llvm::enumerate(First: II->operand_bundles())) {
3776 auto RemoveBundle = [&, Idx = Idx]() -> Instruction * {
3777 if (II->getNumOperandBundles() == 1)
3778 return eraseInstFromFunction(I&: *II);
3779 return CallBase::removeOperandBundleAt(CB: II, Offset: Idx);
3780 };
3781
3782 switch (getBundleAttrFromOBU(OBU)) {
3783 case BundleAttr::None:
3784 llvm_unreachable("Unexpected Attribute");
3785 case BundleAttr::Align: {
3786 // Try to remove redundant alignment assumptions.
3787 auto [Ptr, _, OffsetPtr, Alignment, Offset] = getAssumeAlignInfo(OBU);
3788
3789 if (!Alignment)
3790 break;
3791
3792 // Remove align 1 and non-power-of-two bundles; they don't add any
3793 // useful information.
3794 if (*Alignment == 1 || !isPowerOf2_64(Value: *Alignment))
3795 return RemoveBundle();
3796
3797 if (auto *GEP = dyn_cast<GEPOperator>(Val: Ptr);
3798 GEP &&
3799 GEP->getMaxPreservedAlignment(DL: getDataLayout()) >= *Alignment) {
3800 Builder.CreateAlignmentAssumption(
3801 DL: getDataLayout(), PtrValue: GEP->getPointerOperand(), Alignment: *Alignment,
3802 OffsetValue: OffsetPtr ? const_cast<Value *>(OffsetPtr->get()) : nullptr);
3803 return RemoveBundle();
3804 }
3805
3806 if (!Offset)
3807 break;
3808
3809 Value *BasePtr;
3810 const APInt *PtrOffset;
3811 if (match(V: Ptr.get(), P: m_PtrAdd(PointerOp: m_Value(V&: BasePtr), OffsetOp: m_APInt(Res&: PtrOffset)))) {
3812 auto PtrOffsetVal =
3813 PtrOffset->sextOrTrunc(width: DL.getIndexTypeSizeInBits(Ty: Ptr->getType()))
3814 .trySExtValue();
3815 if (!PtrOffsetVal)
3816 break;
3817 Builder.CreateAlignmentAssumption(
3818 DL, PtrValue: BasePtr, Alignment: *Alignment,
3819 OffsetValue: Builder.getInt64(C: *Offset - *PtrOffsetVal));
3820 return RemoveBundle();
3821 }
3822
3823 // Don't try to remove align assumptions for pointers derived from
3824 // arguments. We might lose information if the function gets inline and
3825 // the align argument attribute disappears.
3826 Value *UO = getUnderlyingObject(V: Ptr);
3827 if (!UO || isa<Argument>(Val: UO))
3828 break;
3829
3830 // Compute known bits for the pointer and drop the assume if the
3831 // known alignment isn't increased by it.
3832 auto AlignMask = (*Alignment - 1);
3833 if (KnownBits KB = computeKnownBits(V: Ptr, CxtI: II);
3834 (KB.Zero & AlignMask) == (~*Offset & AlignMask) &&
3835 (KB.One & AlignMask) == (*Offset & AlignMask))
3836 return RemoveBundle();
3837 break;
3838 }
3839
3840 case BundleAttr::Dereferenceable: {
3841 auto [Ptr, _, Count] = getAssumeDereferenceableInfo(OBU);
3842
3843 if (!Count)
3844 break;
3845
3846 if (*Count == 0 ||
3847 isDereferenceablePointer(V: Ptr, Size: APInt(64, *Count),
3848 Q: getSimplifyQuery().getWithInstruction(I: II)))
3849 return RemoveBundle();
3850
3851 break;
3852 }
3853
3854 case BundleAttr::Ignore:
3855 return RemoveBundle();
3856
3857 case BundleAttr::NonNull: {
3858 auto [Ptr] = llvm::getAssumeNonNullInfo(OBU);
3859
3860 // Drop assume if we can prove nonnull without it
3861 if (isKnownNonZero(V: Ptr, Q: getSimplifyQuery().getWithInstruction(I: II)))
3862 return RemoveBundle();
3863
3864 // Fold the assume into metadata if it's valid at the load
3865 if (auto *LI = dyn_cast<LoadInst>(Val: Ptr);
3866 LI &&
3867 isValidAssumeForContext(I: II, CxtI: LI, DT: &DT, /*AllowEphemerals=*/true)) {
3868 MDNode *MD = MDNode::get(Context&: II->getContext(), MDs: {});
3869 LI->setMetadata(KindID: LLVMContext::MD_nonnull, Node: MD);
3870 LI->setMetadata(KindID: LLVMContext::MD_noundef, Node: MD);
3871 return RemoveBundle();
3872 }
3873
3874 if (auto *GEP = dyn_cast<GEPOperator>(Val: Ptr);
3875 GEP && GEP->isInBounds() &&
3876 !NullPointerIsDefined(F: II->getFunction(),
3877 AS: Ptr->getType()->getPointerAddressSpace())) {
3878 Builder.CreateNonnullAssumption(PtrValue: GEP->stripInBoundsOffsets());
3879 return RemoveBundle();
3880 }
3881
3882 // TODO: apply nonnull return attributes to calls and invokes
3883 break;
3884 }
3885
3886 case BundleAttr::NoUndef: {
3887 auto [Val] = getAssumeNoUndefInfo(OBU);
3888
3889 if (isGuaranteedNotToBeUndefOrPoison(V: Val, AC: &AC, CtxI: II, DT: &DT))
3890 return RemoveBundle();
3891
3892 if (auto *LI = dyn_cast<LoadInst>(Val);
3893 LI &&
3894 isValidAssumeForContext(I: II, CxtI: LI, DT: &DT, /*AllowEphemerals=*/true)) {
3895 LI->setMetadata(KindID: LLVMContext::MD_noundef,
3896 Node: MDNode::get(Context&: II->getContext(), MDs: {}));
3897 return RemoveBundle();
3898 }
3899
3900 } break;
3901
3902 case BundleAttr::SeparateStorage: {
3903 auto [Ptr1, Ptr2] = getAssumeSeparateStorageInfo(OBU);
3904 // Separate storage assumptions apply to the underlying allocations, not
3905 // any particular pointer within them. When evaluating the hints for AA
3906 // purposes we getUnderlyingObject them; by precomputing the answers
3907 // here we can avoid having to do so repeatedly there.
3908 auto MaybeSimplifyHint = [&](const Use &U) {
3909 Value *Hint = U.get();
3910 // Not having a limit is safe because InstCombine removes unreachable
3911 // code.
3912 Value *UnderlyingObject = getUnderlyingObject(V: Hint, /*MaxLookup*/ 0);
3913 if (Hint != UnderlyingObject)
3914 replaceUse(U&: const_cast<Use &>(U), NewValue: UnderlyingObject);
3915 };
3916 MaybeSimplifyHint(Ptr1);
3917 MaybeSimplifyHint(Ptr2);
3918 } break;
3919
3920 // TODO: Drop these assumes when they are redundant
3921 case BundleAttr::DereferenceableOrNull:
3922 break;
3923
3924 // This cannot be simplified
3925 case BundleAttr::Cold:
3926 break;
3927 }
3928 }
3929
3930 // If the assume has operand bundles, the folds below will never work, so
3931 // don't bother trying.
3932 if (II->hasOperandBundles())
3933 break;
3934
3935 Value *IIOperand = II->getArgOperand(i: 0);
3936
3937 // Canonicalize assume(a && b) -> assume(a); assume(b);
3938 // Note: New assumption intrinsics created here are registered by
3939 // the InstCombineIRInserter object.
3940 Value *A, *B;
3941 if (match(V: IIOperand, P: m_LogicalAnd(L: m_Value(V&: A), R: m_Value(V&: B)))) {
3942 Builder.CreateAssumption(Cond: A);
3943 Builder.CreateAssumption(Cond: B);
3944 return eraseInstFromFunction(I&: *II);
3945 }
3946 // assume(!(a || b)) -> assume(!a); assume(!b);
3947 if (match(V: IIOperand, P: m_Not(V: m_LogicalOr(L: m_Value(V&: A), R: m_Value(V&: B))))) {
3948 Builder.CreateAssumption(Cond: Builder.CreateNot(V: A));
3949 Builder.CreateAssumption(Cond: Builder.CreateNot(V: B));
3950 return eraseInstFromFunction(I&: *II);
3951 }
3952
3953 // Convert nonnull assume like:
3954 // %A = icmp ne i32* %PTR, null
3955 // call void @llvm.assume(i1 %A)
3956 // into
3957 // call void @llvm.assume(i1 true) [ "nonnull"(i32* %PTR) ]
3958 if (match(V: IIOperand,
3959 P: m_SpecificICmp(MatchPred: ICmpInst::ICMP_NE, L: m_Value(V&: A), R: m_Zero())) &&
3960 A->getType()->isPointerTy()) {
3961 Builder.CreateNonnullAssumption(PtrValue: A);
3962 return eraseInstFromFunction(I&: *II);
3963 }
3964
3965 // Convert alignment assume like:
3966 // %B = ptrtoint ptr %A to i64
3967 // %C = and i64 %B, Constant
3968 // %D = icmp eq i64 %C, 0
3969 // call void @llvm.assume(i1 %D)
3970 // into
3971 // call void @llvm.assume(i1 true) [ "align"(ptr [[A]], i64 Constant + 1)]
3972 uint64_t AlignMask = 1;
3973 if ((match(V: IIOperand, P: m_Not(V: m_Trunc(Op: m_Value(V&: A)))) ||
3974 match(V: IIOperand,
3975 P: m_SpecificICmp(MatchPred: ICmpInst::ICMP_EQ,
3976 L: m_And(L: m_Value(V&: A), R: m_ConstantInt(V&: AlignMask)),
3977 R: m_Zero())))) {
3978 if (isPowerOf2_64(Value: AlignMask + 1) &&
3979 match(V: A, P: m_PtrToIntOrAddr(Op: m_Value(V&: A)))) {
3980 Builder.CreateAlignmentAssumption(DL: getDataLayout(), PtrValue: A, Alignment: AlignMask + 1);
3981 return eraseInstFromFunction(I&: *II);
3982 }
3983 }
3984
3985 // Remove assumes on true/false
3986 if (auto *CI = dyn_cast<ConstantInt>(Val: IIOperand);
3987 CI || isa<UndefValue, PoisonValue>(Val: IIOperand)) {
3988 if (!CI || CI->isZero())
3989 CreateNonTerminatorUnreachable(InsertAt: II);
3990 return eraseInstFromFunction(I&: *II);
3991 }
3992
3993 // Update the cache of affected values for this assumption (we might be
3994 // here because we just simplified the condition).
3995 AC.updateAffectedValues(CI: cast<AssumeInst>(Val: II));
3996 break;
3997 }
3998 case Intrinsic::experimental_guard: {
3999 // Is this guard followed by another guard? We scan forward over a small
4000 // fixed window of instructions to handle common cases with conditions
4001 // computed between guards.
4002 Instruction *NextInst = II->getNextNode();
4003 for (unsigned i = 0; i < GuardWideningWindow; i++) {
4004 // Note: Using context-free form to avoid compile time blow up
4005 if (!isSafeToSpeculativelyExecute(I: NextInst))
4006 break;
4007 NextInst = NextInst->getNextNode();
4008 }
4009 Value *NextCond = nullptr;
4010 if (match(V: NextInst,
4011 P: m_Intrinsic<Intrinsic::experimental_guard>(Ops: m_Value(V&: NextCond)))) {
4012 Value *CurrCond = II->getArgOperand(i: 0);
4013
4014 // Remove a guard that it is immediately preceded by an identical guard.
4015 // Otherwise canonicalize guard(a); guard(b) -> guard(a & b).
4016 if (CurrCond != NextCond) {
4017 Instruction *MoveI = II->getNextNode();
4018 while (MoveI != NextInst) {
4019 auto *Temp = MoveI;
4020 MoveI = MoveI->getNextNode();
4021 Temp->moveBefore(InsertPos: II->getIterator());
4022 }
4023 replaceOperand(I&: *II, OpNum: 0, V: Builder.CreateAnd(LHS: CurrCond, RHS: NextCond));
4024 }
4025 eraseInstFromFunction(I&: *NextInst);
4026 return II;
4027 }
4028 break;
4029 }
4030 case Intrinsic::vector_insert: {
4031 Value *Vec = II->getArgOperand(i: 0);
4032 Value *SubVec = II->getArgOperand(i: 1);
4033 Value *Idx = II->getArgOperand(i: 2);
4034 auto *DstTy = dyn_cast<FixedVectorType>(Val: II->getType());
4035 auto *VecTy = dyn_cast<FixedVectorType>(Val: Vec->getType());
4036 auto *SubVecTy = dyn_cast<FixedVectorType>(Val: SubVec->getType());
4037
4038 // Only canonicalize if the destination vector, Vec, and SubVec are all
4039 // fixed vectors.
4040 if (DstTy && VecTy && SubVecTy) {
4041 unsigned DstNumElts = DstTy->getNumElements();
4042 unsigned VecNumElts = VecTy->getNumElements();
4043 unsigned SubVecNumElts = SubVecTy->getNumElements();
4044 unsigned IdxN = cast<ConstantInt>(Val: Idx)->getZExtValue();
4045
4046 // An insert that entirely overwrites Vec with SubVec is a nop.
4047 if (VecNumElts == SubVecNumElts)
4048 return replaceInstUsesWith(I&: CI, V: SubVec);
4049
4050 // Widen SubVec into a vector of the same width as Vec, since
4051 // shufflevector requires the two input vectors to be the same width.
4052 // Elements beyond the bounds of SubVec within the widened vector are
4053 // undefined.
4054 SmallVector<int, 8> WidenMask;
4055 unsigned i;
4056 for (i = 0; i != SubVecNumElts; ++i)
4057 WidenMask.push_back(Elt: i);
4058 for (; i != VecNumElts; ++i)
4059 WidenMask.push_back(Elt: PoisonMaskElem);
4060
4061 Value *WidenShuffle = Builder.CreateShuffleVector(V: SubVec, Mask: WidenMask);
4062
4063 SmallVector<int, 8> Mask;
4064 for (unsigned i = 0; i != IdxN; ++i)
4065 Mask.push_back(Elt: i);
4066 for (unsigned i = DstNumElts; i != DstNumElts + SubVecNumElts; ++i)
4067 Mask.push_back(Elt: i);
4068 for (unsigned i = IdxN + SubVecNumElts; i != DstNumElts; ++i)
4069 Mask.push_back(Elt: i);
4070
4071 Value *Shuffle = Builder.CreateShuffleVector(V1: Vec, V2: WidenShuffle, Mask);
4072 return replaceInstUsesWith(I&: CI, V: Shuffle);
4073 }
4074 break;
4075 }
4076 case Intrinsic::vector_extract: {
4077 Value *Vec = II->getArgOperand(i: 0);
4078 Value *Idx = II->getArgOperand(i: 1);
4079
4080 Type *ReturnType = II->getType();
4081 // (extract_vector (insert_vector InsertTuple, InsertValue, InsertIdx),
4082 // ExtractIdx)
4083 unsigned ExtractIdx = cast<ConstantInt>(Val: Idx)->getZExtValue();
4084 Value *InsertTuple, *InsertIdx, *InsertValue;
4085 if (match(V: Vec, P: m_Intrinsic<Intrinsic::vector_insert>(Ops: m_Value(V&: InsertTuple),
4086 Ops: m_Value(V&: InsertValue),
4087 Ops: m_Value(V&: InsertIdx))) &&
4088 InsertValue->getType() == ReturnType) {
4089 unsigned Index = cast<ConstantInt>(Val: InsertIdx)->getZExtValue();
4090 // Case where we get the same index right after setting it.
4091 // extract.vector(insert.vector(InsertTuple, InsertValue, Idx), Idx) -->
4092 // InsertValue
4093 if (ExtractIdx == Index)
4094 return replaceInstUsesWith(I&: CI, V: InsertValue);
4095 // If we are getting a different index than what was set in the
4096 // insert.vector intrinsic. We can just set the input tuple to the one up
4097 // in the chain. extract.vector(insert.vector(InsertTuple, InsertValue,
4098 // InsertIndex), ExtractIndex)
4099 // --> extract.vector(InsertTuple, ExtractIndex)
4100 else
4101 return replaceOperand(I&: CI, OpNum: 0, V: InsertTuple);
4102 }
4103
4104 ConstantInt *ALMUpperBound;
4105 if (match(V: Vec, P: m_Intrinsic<Intrinsic::get_active_lane_mask>(
4106 Ops: m_Value(), Ops: m_ConstantInt(CI&: ALMUpperBound)))) {
4107 const auto &Attrs = II->getFunction()->getAttributes().getFnAttrs();
4108 unsigned VScaleMin = Attrs.getVScaleRangeMin();
4109 unsigned ScaleFactor =
4110 cast<VectorType>(Val: ReturnType)->isScalableTy() ? VScaleMin : 1;
4111 if (ExtractIdx * ScaleFactor >= ALMUpperBound->getZExtValue())
4112 return replaceInstUsesWith(I&: CI,
4113 V: ConstantVector::getNullValue(Ty: ReturnType));
4114 }
4115
4116 auto *DstTy = dyn_cast<VectorType>(Val: ReturnType);
4117 auto *VecTy = dyn_cast<VectorType>(Val: Vec->getType());
4118
4119 if (DstTy && VecTy) {
4120 auto DstEltCnt = DstTy->getElementCount();
4121 auto VecEltCnt = VecTy->getElementCount();
4122 unsigned IdxN = cast<ConstantInt>(Val: Idx)->getZExtValue();
4123
4124 // Extracting the entirety of Vec is a nop.
4125 if (DstEltCnt == VecTy->getElementCount()) {
4126 replaceInstUsesWith(I&: CI, V: Vec);
4127 return eraseInstFromFunction(I&: CI);
4128 }
4129
4130 // Only canonicalize to shufflevector if the destination vector and
4131 // Vec are fixed vectors.
4132 if (VecEltCnt.isScalable() || DstEltCnt.isScalable())
4133 break;
4134
4135 SmallVector<int, 8> Mask;
4136 for (unsigned i = 0; i != DstEltCnt.getKnownMinValue(); ++i)
4137 Mask.push_back(Elt: IdxN + i);
4138
4139 Value *Shuffle = Builder.CreateShuffleVector(V: Vec, Mask);
4140 return replaceInstUsesWith(I&: CI, V: Shuffle);
4141 }
4142 break;
4143 }
4144 case Intrinsic::experimental_vp_reverse: {
4145 Value *X;
4146 Value *Vec = II->getArgOperand(i: 0);
4147 Value *Mask = II->getArgOperand(i: 1);
4148 if (!match(V: Mask, P: m_AllOnes()))
4149 break;
4150 Value *EVL = II->getArgOperand(i: 2);
4151 // TODO: Canonicalize experimental.vp.reverse after unop/binops?
4152 // rev(unop rev(X)) --> unop X
4153 if (match(V: Vec,
4154 P: m_OneUse(SubPattern: m_UnOp(X: m_Intrinsic<Intrinsic::experimental_vp_reverse>(
4155 Ops: m_Value(V&: X), Ops: m_AllOnes(), Ops: m_Specific(V: EVL)))))) {
4156 auto *OldUnOp = cast<UnaryOperator>(Val: Vec);
4157 auto *NewUnOp = UnaryOperator::CreateWithCopiedFlags(
4158 Opc: OldUnOp->getOpcode(), V: X, CopyO: OldUnOp, Name: OldUnOp->getName(),
4159 InsertBefore: II->getIterator());
4160 return replaceInstUsesWith(I&: CI, V: NewUnOp);
4161 }
4162 break;
4163 }
4164 case Intrinsic::vector_reduce_or:
4165 case Intrinsic::vector_reduce_and: {
4166 // Canonicalize logical or/and reductions:
4167 // Or reduction for i1 is represented as:
4168 // %val = bitcast <ReduxWidth x i1> to iReduxWidth
4169 // %res = cmp ne iReduxWidth %val, 0
4170 // And reduction for i1 is represented as:
4171 // %val = bitcast <ReduxWidth x i1> to iReduxWidth
4172 // %res = cmp eq iReduxWidth %val, 11111
4173 Value *Arg = II->getArgOperand(i: 0);
4174 Value *Vect;
4175
4176 if (Value *NewOp =
4177 simplifyReductionOperand(Arg, /*CanReorderLanes=*/true)) {
4178 replaceUse(U&: II->getOperandUse(i: 0), NewValue: NewOp);
4179 return II;
4180 }
4181
4182 if (match(V: Arg, P: m_ZExtOrSExtOrSelf(Op: m_Value(V&: Vect)))) {
4183 if (auto *FTy = dyn_cast<FixedVectorType>(Val: Vect->getType()))
4184 if (FTy->getElementType() == Builder.getInt1Ty()) {
4185 Value *Res = Builder.CreateBitCast(
4186 V: Vect, DestTy: Builder.getIntNTy(N: FTy->getNumElements()));
4187 if (IID == Intrinsic::vector_reduce_and) {
4188 Res = Builder.CreateICmpEQ(
4189 LHS: Res, RHS: ConstantInt::getAllOnesValue(Ty: Res->getType()));
4190 } else {
4191 assert(IID == Intrinsic::vector_reduce_or &&
4192 "Expected or reduction.");
4193 Res = Builder.CreateIsNotNull(Arg: Res);
4194 }
4195 if (Arg != Vect)
4196 Res = Builder.CreateCast(Op: cast<CastInst>(Val: Arg)->getOpcode(), V: Res,
4197 DestTy: II->getType());
4198 return replaceInstUsesWith(I&: CI, V: Res);
4199 }
4200 }
4201 [[fallthrough]];
4202 }
4203 case Intrinsic::vector_reduce_add: {
4204 if (IID == Intrinsic::vector_reduce_add) {
4205 // Convert vector_reduce_add(ZExt(<n x i1>)) to
4206 // ZExtOrTrunc(ctpop(bitcast <n x i1> to in)).
4207 // Convert vector_reduce_add(SExt(<n x i1>)) to
4208 // -ZExtOrTrunc(ctpop(bitcast <n x i1> to in)).
4209 // Convert vector_reduce_add(<n x i1>) to
4210 // Trunc(ctpop(bitcast <n x i1> to in)).
4211 Value *Arg = II->getArgOperand(i: 0);
4212 Value *Vect;
4213
4214 if (Value *NewOp =
4215 simplifyReductionOperand(Arg, /*CanReorderLanes=*/true)) {
4216 replaceUse(U&: II->getOperandUse(i: 0), NewValue: NewOp);
4217 return II;
4218 }
4219
4220 // vector.reduce.add.vNiM(splat(%x)) -> mul(%x, N)
4221 if (Value *Splat = getSplatValue(V: Arg)) {
4222 ElementCount VecToReduceCount =
4223 cast<VectorType>(Val: Arg->getType())->getElementCount();
4224 if (VecToReduceCount.isFixed()) {
4225 unsigned VectorSize = VecToReduceCount.getFixedValue();
4226 return BinaryOperator::CreateMul(
4227 V1: Splat,
4228 V2: ConstantInt::get(Ty: Splat->getType(), V: VectorSize, /*IsSigned=*/false,
4229 /*ImplicitTrunc=*/true));
4230 }
4231 }
4232
4233 if (match(V: Arg, P: m_ZExtOrSExtOrSelf(Op: m_Value(V&: Vect)))) {
4234 if (auto *FTy = dyn_cast<FixedVectorType>(Val: Vect->getType()))
4235 if (FTy->getElementType() == Builder.getInt1Ty()) {
4236 Value *V = Builder.CreateBitCast(
4237 V: Vect, DestTy: Builder.getIntNTy(N: FTy->getNumElements()));
4238 Value *Res = Builder.CreateUnaryIntrinsic(ID: Intrinsic::ctpop, Op: V);
4239 Res = Builder.CreateZExtOrTrunc(V: Res, DestTy: II->getType());
4240 if (Arg != Vect &&
4241 cast<Instruction>(Val: Arg)->getOpcode() == Instruction::SExt)
4242 Res = Builder.CreateNeg(V: Res);
4243 return replaceInstUsesWith(I&: CI, V: Res);
4244 }
4245 }
4246 }
4247 [[fallthrough]];
4248 }
4249 case Intrinsic::vector_reduce_xor: {
4250 if (IID == Intrinsic::vector_reduce_xor) {
4251 // Exclusive disjunction reduction over the vector with
4252 // (potentially-extended) i1 element type is actually a
4253 // (potentially-extended) arithmetic `add` reduction over the original
4254 // non-extended value:
4255 // vector_reduce_xor(?ext(<n x i1>))
4256 // -->
4257 // ?ext(vector_reduce_add(<n x i1>))
4258 Value *Arg = II->getArgOperand(i: 0);
4259 Value *Vect;
4260
4261 if (Value *NewOp =
4262 simplifyReductionOperand(Arg, /*CanReorderLanes=*/true)) {
4263 replaceUse(U&: II->getOperandUse(i: 0), NewValue: NewOp);
4264 return II;
4265 }
4266
4267 if (match(V: Arg, P: m_ZExtOrSExtOrSelf(Op: m_Value(V&: Vect)))) {
4268 if (auto *VTy = dyn_cast<VectorType>(Val: Vect->getType()))
4269 if (VTy->getElementType() == Builder.getInt1Ty()) {
4270 Value *Res = Builder.CreateAddReduce(Src: Vect);
4271 if (Arg != Vect)
4272 Res = Builder.CreateCast(Op: cast<CastInst>(Val: Arg)->getOpcode(), V: Res,
4273 DestTy: II->getType());
4274 return replaceInstUsesWith(I&: CI, V: Res);
4275 }
4276 }
4277 }
4278 [[fallthrough]];
4279 }
4280 case Intrinsic::vector_reduce_mul: {
4281 if (IID == Intrinsic::vector_reduce_mul) {
4282 Value *Arg = II->getArgOperand(i: 0);
4283
4284 if (Value *NewOp =
4285 simplifyReductionOperand(Arg, /*CanReorderLanes=*/true)) {
4286 replaceUse(U&: II->getOperandUse(i: 0), NewValue: NewOp);
4287 return II;
4288 }
4289
4290 // vector_reduce_mul(zext(<n x i1>)), or
4291 // vector_reduce_mul(sext(<n x i1>)) (if n is even) -->
4292 // zext(vector_reduce_and(<n x i1>)).
4293 // (The sext case doesn't work if n is odd because multiplying an odd
4294 // number of -1's produces -1, not 1.)
4295 Value *Vect;
4296 bool IsZext = match(V: Arg, P: m_ZExt(Op: m_Value(V&: Vect))) &&
4297 Vect->getType()->isIntOrIntVectorTy(BitWidth: 1);
4298 bool IsSext =
4299 match(V: Arg, P: m_SExt(Op: m_Value(V&: Vect))) &&
4300 Vect->getType()->isIntOrIntVectorTy(BitWidth: 1) &&
4301 cast<VectorType>(Val: Vect->getType())->getElementCount().isKnownEven();
4302 if (IsZext || IsSext) {
4303 Value *Res = Builder.CreateAndReduce(Src: Vect);
4304 return CastInst::Create(Instruction::ZExt, S: Res, Ty: II->getType());
4305 }
4306
4307 // vector_reduce_mul(<n x i1>) --> vector_reduce_and(<n x i1>)
4308 if (Arg->getType()->isIntOrIntVectorTy(BitWidth: 1))
4309 return replaceInstUsesWith(I&: CI, V: Builder.CreateAndReduce(Src: Arg));
4310 }
4311 [[fallthrough]];
4312 }
4313 case Intrinsic::vector_reduce_umin:
4314 case Intrinsic::vector_reduce_umax: {
4315 if (IID == Intrinsic::vector_reduce_umin ||
4316 IID == Intrinsic::vector_reduce_umax) {
4317 // UMin/UMax reduction over the vector with (potentially-extended)
4318 // i1 element type is actually a (potentially-extended)
4319 // logical `and`/`or` reduction over the original non-extended value:
4320 // vector_reduce_u{min,max}(?ext(<n x i1>))
4321 // -->
4322 // ?ext(vector_reduce_{and,or}(<n x i1>))
4323 Value *Arg = II->getArgOperand(i: 0);
4324 Value *Vect;
4325
4326 if (Value *NewOp =
4327 simplifyReductionOperand(Arg, /*CanReorderLanes=*/true)) {
4328 replaceUse(U&: II->getOperandUse(i: 0), NewValue: NewOp);
4329 return II;
4330 }
4331
4332 if (match(V: Arg, P: m_ZExtOrSExtOrSelf(Op: m_Value(V&: Vect)))) {
4333 if (auto *VTy = dyn_cast<VectorType>(Val: Vect->getType()))
4334 if (VTy->getElementType() == Builder.getInt1Ty()) {
4335 Value *Res = IID == Intrinsic::vector_reduce_umin
4336 ? Builder.CreateAndReduce(Src: Vect)
4337 : Builder.CreateOrReduce(Src: Vect);
4338 if (Arg != Vect)
4339 Res = Builder.CreateCast(Op: cast<CastInst>(Val: Arg)->getOpcode(), V: Res,
4340 DestTy: II->getType());
4341 return replaceInstUsesWith(I&: CI, V: Res);
4342 }
4343 }
4344 }
4345 [[fallthrough]];
4346 }
4347 case Intrinsic::vector_reduce_smin:
4348 case Intrinsic::vector_reduce_smax: {
4349 if (IID == Intrinsic::vector_reduce_smin ||
4350 IID == Intrinsic::vector_reduce_smax) {
4351 // SMin/SMax reduction over the vector with (potentially-extended)
4352 // i1 element type is actually a (potentially-extended)
4353 // logical `and`/`or` reduction over the original non-extended value:
4354 // vector_reduce_s{min,max}(<n x i1>)
4355 // -->
4356 // vector_reduce_{or,and}(<n x i1>)
4357 // and
4358 // vector_reduce_s{min,max}(sext(<n x i1>))
4359 // -->
4360 // sext(vector_reduce_{or,and}(<n x i1>))
4361 // and
4362 // vector_reduce_s{min,max}(zext(<n x i1>))
4363 // -->
4364 // zext(vector_reduce_{and,or}(<n x i1>))
4365 Value *Arg = II->getArgOperand(i: 0);
4366 Value *Vect;
4367
4368 if (Value *NewOp =
4369 simplifyReductionOperand(Arg, /*CanReorderLanes=*/true)) {
4370 replaceUse(U&: II->getOperandUse(i: 0), NewValue: NewOp);
4371 return II;
4372 }
4373
4374 if (match(V: Arg, P: m_ZExtOrSExtOrSelf(Op: m_Value(V&: Vect)))) {
4375 if (auto *VTy = dyn_cast<VectorType>(Val: Vect->getType()))
4376 if (VTy->getElementType() == Builder.getInt1Ty()) {
4377 Instruction::CastOps ExtOpc = Instruction::CastOps::CastOpsEnd;
4378 if (Arg != Vect)
4379 ExtOpc = cast<CastInst>(Val: Arg)->getOpcode();
4380 Value *Res = ((IID == Intrinsic::vector_reduce_smin) ==
4381 (ExtOpc == Instruction::CastOps::ZExt))
4382 ? Builder.CreateAndReduce(Src: Vect)
4383 : Builder.CreateOrReduce(Src: Vect);
4384 if (Arg != Vect)
4385 Res = Builder.CreateCast(Op: ExtOpc, V: Res, DestTy: II->getType());
4386 return replaceInstUsesWith(I&: CI, V: Res);
4387 }
4388 }
4389 }
4390 [[fallthrough]];
4391 }
4392 case Intrinsic::vector_reduce_fmax:
4393 case Intrinsic::vector_reduce_fmin:
4394 case Intrinsic::vector_reduce_fadd:
4395 case Intrinsic::vector_reduce_fmul: {
4396 bool CanReorderLanes = (IID != Intrinsic::vector_reduce_fadd &&
4397 IID != Intrinsic::vector_reduce_fmul) ||
4398 II->hasAllowReassoc();
4399 const unsigned ArgIdx = (IID == Intrinsic::vector_reduce_fadd ||
4400 IID == Intrinsic::vector_reduce_fmul)
4401 ? 1
4402 : 0;
4403 Value *Arg = II->getArgOperand(i: ArgIdx);
4404 if (Value *NewOp = simplifyReductionOperand(Arg, CanReorderLanes)) {
4405 replaceUse(U&: II->getOperandUse(i: ArgIdx), NewValue: NewOp);
4406 return nullptr;
4407 }
4408 break;
4409 }
4410 case Intrinsic::is_fpclass: {
4411 if (Instruction *I = foldIntrinsicIsFPClass(II&: *II))
4412 return I;
4413 break;
4414 }
4415 case Intrinsic::threadlocal_address: {
4416 Align MinAlign = getKnownAlignment(V: II->getArgOperand(i: 0), DL, CxtI: II, AC: &AC, DT: &DT);
4417 MaybeAlign Align = II->getRetAlign();
4418 if (MinAlign > Align.valueOrOne()) {
4419 II->addRetAttr(Attr: Attribute::getWithAlignment(Context&: II->getContext(), Alignment: MinAlign));
4420 return II;
4421 }
4422 break;
4423 }
4424 case Intrinsic::fptoui_sat:
4425 case Intrinsic::fptosi_sat:
4426 if (Instruction *I = foldItoFPtoI(FI&: *II))
4427 return I;
4428 break;
4429 case Intrinsic::frexp: {
4430 // frexp(frexp(x).fract) -> { frexp(x).fract, 0 }: the fraction operand is
4431 // already normalized, so the first result is idempotent and the second is
4432 // zero.
4433 if (match(V: II->getArgOperand(i: 0),
4434 P: m_ExtractValue<0>(V: m_Intrinsic<Intrinsic::frexp>(Ops: m_Value())))) {
4435 Value *Res = Builder.CreateInsertValue(Agg: PoisonValue::get(T: II->getType()),
4436 Val: II->getArgOperand(i: 0), Idxs: 0);
4437 Res = Builder.CreateInsertValue(
4438 Agg: Res, Val: Constant::getNullValue(Ty: II->getType()->getStructElementType(N: 1)),
4439 Idxs: 1);
4440 return replaceInstUsesWith(I&: *II, V: Res);
4441 }
4442 break;
4443 }
4444 case Intrinsic::get_active_lane_mask: {
4445 const APInt *Op0, *Op1;
4446 if (match(V: II->getOperand(i_nocapture: 0), P: m_StrictlyPositive(V&: Op0)) &&
4447 match(V: II->getOperand(i_nocapture: 1), P: m_APInt(Res&: Op1))) {
4448 Type *OpTy = II->getOperand(i_nocapture: 0)->getType();
4449 return replaceInstUsesWith(
4450 I&: *II, V: Builder.CreateIntrinsic(
4451 RetTy: II->getType(), ID: Intrinsic::get_active_lane_mask,
4452 Args: {Constant::getNullValue(Ty: OpTy),
4453 ConstantInt::get(Ty: OpTy, V: Op1->usub_sat(RHS: *Op0))}));
4454 }
4455 break;
4456 }
4457 case Intrinsic::experimental_get_vector_length: {
4458 // get.vector.length(Cnt, MaxLanes) --> Cnt when Cnt <= MaxLanes
4459 unsigned BitWidth =
4460 std::max(a: II->getArgOperand(i: 0)->getType()->getScalarSizeInBits(),
4461 b: II->getType()->getScalarSizeInBits());
4462 ConstantRange Cnt =
4463 computeConstantRangeIncludingKnownBits(V: II->getArgOperand(i: 0), ForSigned: false,
4464 SQ: SQ.getWithInstruction(I: II))
4465 .zextOrTrunc(BitWidth);
4466 ConstantRange MaxLanes = cast<ConstantInt>(Val: II->getArgOperand(i: 1))
4467 ->getValue()
4468 .zextOrTrunc(width: Cnt.getBitWidth());
4469 if (cast<ConstantInt>(Val: II->getArgOperand(i: 2))->isOne())
4470 MaxLanes = MaxLanes.multiply(
4471 Other: getVScaleRange(F: II->getFunction(), BitWidth: Cnt.getBitWidth()));
4472
4473 if (Cnt.icmp(Pred: CmpInst::ICMP_ULE, Other: MaxLanes))
4474 return replaceInstUsesWith(
4475 I&: *II, V: Builder.CreateZExtOrTrunc(V: II->getArgOperand(i: 0), DestTy: II->getType()));
4476 return nullptr;
4477 }
4478 default: {
4479 // Handle target specific intrinsics
4480 std::optional<Instruction *> V = targetInstCombineIntrinsic(II&: *II);
4481 if (V)
4482 return *V;
4483 break;
4484 }
4485 }
4486
4487 // Try to fold intrinsic into select/phi operands. This is legal if:
4488 // * The intrinsic is speculatable.
4489 // * The operand is one of the following:
4490 // - a phi.
4491 // - a select with a scalar condition.
4492 // - a select with a vector condition and II is not a cross lane operation.
4493 if (isSafeToSpeculativelyExecuteWithVariableReplaced(I: &CI)) {
4494 for (Value *Op : II->args()) {
4495 if (auto *Sel = dyn_cast<SelectInst>(Val: Op)) {
4496 bool IsVectorCond = Sel->getCondition()->getType()->isVectorTy();
4497 if (IsVectorCond &&
4498 (!isNotCrossLaneOperation(I: II) || !II->getType()->isVectorTy()))
4499 continue;
4500 // Don't replace a scalar select with a more expensive vector select if
4501 // we can't simplify both arms of the select.
4502 bool SimplifyBothArms =
4503 !Op->getType()->isVectorTy() && II->getType()->isVectorTy();
4504 if (Instruction *R = FoldOpIntoSelect(
4505 Op&: *II, SI: Sel, /*FoldWithMultiUse=*/false, SimplifyBothArms))
4506 return R;
4507 }
4508 if (auto *Phi = dyn_cast<PHINode>(Val: Op))
4509 if (Instruction *R = foldOpIntoPhi(I&: *II, PN: Phi))
4510 return R;
4511 }
4512 }
4513
4514 if (Instruction *Shuf = foldShuffledIntrinsicOperands(II))
4515 return Shuf;
4516
4517 if (Value *Reverse = foldReversedIntrinsicOperands(II))
4518 return replaceInstUsesWith(I&: *II, V: Reverse);
4519
4520 if (Value *Res = foldIdempotentBinaryIntrinsicRecurrence(IC&: *this, II))
4521 return replaceInstUsesWith(I&: *II, V: Res);
4522
4523 // Some intrinsics (like experimental_gc_statepoint) can be used in invoke
4524 // context, so it is handled in visitCallBase and we should trigger it.
4525 return visitCallBase(Call&: *II);
4526}
4527
4528// Fence instruction simplification
4529Instruction *InstCombinerImpl::visitFenceInst(FenceInst &FI) {
4530 auto *NFI = dyn_cast<FenceInst>(Val: FI.getNextNode());
4531 // This check is solely here to handle arbitrary target-dependent syncscopes.
4532 // TODO: Can remove if does not matter in practice.
4533 if (NFI && FI.isIdenticalTo(I: NFI))
4534 return eraseInstFromFunction(I&: FI);
4535
4536 // Returns true if FI1 is identical or stronger fence than FI2.
4537 auto isIdenticalOrStrongerFence = [](FenceInst *FI1, FenceInst *FI2) {
4538 auto FI1SyncScope = FI1->getSyncScopeID();
4539 // Consider same scope, where scope is global or single-thread.
4540 if (FI1SyncScope != FI2->getSyncScopeID() ||
4541 (FI1SyncScope != SyncScope::System &&
4542 FI1SyncScope != SyncScope::SingleThread))
4543 return false;
4544
4545 return isAtLeastOrStrongerThan(AO: FI1->getOrdering(), Other: FI2->getOrdering());
4546 };
4547 if (NFI && isIdenticalOrStrongerFence(NFI, &FI))
4548 return eraseInstFromFunction(I&: FI);
4549
4550 if (auto *PFI = dyn_cast_or_null<FenceInst>(Val: FI.getPrevNode()))
4551 if (isIdenticalOrStrongerFence(PFI, &FI))
4552 return eraseInstFromFunction(I&: FI);
4553 return nullptr;
4554}
4555
4556// InvokeInst simplification
4557Instruction *InstCombinerImpl::visitInvokeInst(InvokeInst &II) {
4558 return visitCallBase(Call&: II);
4559}
4560
4561// CallBrInst simplification
4562Instruction *InstCombinerImpl::visitCallBrInst(CallBrInst &CBI) {
4563 return visitCallBase(Call&: CBI);
4564}
4565
4566// A simple parser for format string specifiers for the purposes of the
4567// modular-format attribute. In the case of malformed format strings this might
4568// under or over report the specifiers present, but such cases are undefined
4569// behavior.
4570static Bitset<256> parseFormatStringSpecifiers(StringRef FormatStr) {
4571 Bitset<256> Specifiers;
4572 for (size_t I = 0; I < FormatStr.size(); ++I) {
4573 if (FormatStr[I] != '%')
4574 continue;
4575
4576 // Check for escaped '%'.
4577 if (I + 1 < FormatStr.size() && FormatStr[I + 1] == '%') {
4578 ++I; // Skip the second '%'.
4579 continue;
4580 }
4581
4582 // Scan past allowed prefix characters.
4583 size_t J =
4584 FormatStr.find_first_not_of(Chars: "0123456789-+ #0$.*'hlLjztqwvI", From: I + 1);
4585 if (J == StringRef::npos)
4586 break;
4587
4588 Specifiers.set(static_cast<unsigned char>(FormatStr[J]));
4589 I = J; // Resume search from after the specifier.
4590 }
4591 return Specifiers;
4592}
4593
4594static bool isAspectNeeded(StringRef Aspect, CallInst *CI,
4595 std::optional<unsigned> FirstArgIdx,
4596 const std::optional<Bitset<256>> &Specifiers) {
4597 if (Aspect == "float") {
4598 if (Specifiers) {
4599 static constexpr Bitset<256> FloatSpecifiers{'f', 'F', 'e', 'E',
4600 'g', 'G', 'a', 'A'};
4601 return (*Specifiers & FloatSpecifiers).any();
4602 }
4603 // Fallback to type-based check for dynamic format string.
4604 if (!FirstArgIdx)
4605 return true;
4606 return llvm::any_of(
4607 Range: llvm::make_range(x: std::next(x: CI->arg_begin(), n: *FirstArgIdx),
4608 y: CI->arg_end()),
4609 P: [](Value *V) { return V->getType()->isFloatingPointTy(); });
4610 }
4611 if (Aspect == "fixed") {
4612 if (Specifiers) {
4613 static constexpr Bitset<256> FixedSpecifiers{'r', 'R', 'k', 'K'};
4614 return (*Specifiers & FixedSpecifiers).any();
4615 }
4616 // Fallback for fixed-point: assume needed if format is dynamic.
4617 return true;
4618 }
4619 // Unknown aspects are always considered to be needed.
4620 return true;
4621}
4622
4623static void referenceAspect(StringRef Aspect, StringRef ImplName, Module *M,
4624 IRBuilderBase &B) {
4625 SmallString<20> Name = ImplName;
4626 Name += '_';
4627 Name += Aspect;
4628 LLVMContext &Ctx = M->getContext();
4629 Function *RelocNoneFn =
4630 Intrinsic::getOrInsertDeclaration(M, id: Intrinsic::reloc_none);
4631 B.CreateCall(Callee: RelocNoneFn,
4632 Args: {MetadataAsValue::get(Context&: Ctx, MD: MDString::get(Context&: Ctx, Str: Name))});
4633}
4634
4635static Value *optimizeModularFormat(CallInst *CI, IRBuilderBase &B) {
4636 if (!CI->hasFnAttr(Kind: "modular-format"))
4637 return nullptr;
4638
4639 SmallVector<StringRef> Args(
4640 llvm::split(Str: CI->getFnAttr(Kind: "modular-format").getValueAsString(), Separator: ','));
4641 if (Args.size() < 5)
4642 return nullptr;
4643
4644 StringRef FormatIdxStr = Args[1];
4645 StringRef FirstArgIdxStr = Args[2];
4646 StringRef FnName = Args[3];
4647 StringRef ImplName = Args[4];
4648 ArrayRef<StringRef> AllAspects = ArrayRef<StringRef>(Args).drop_front(N: 5);
4649
4650 unsigned FormatIdx;
4651 std::optional<unsigned> FirstArgIdx;
4652 [[maybe_unused]] bool Error;
4653 Error = FormatIdxStr.getAsInteger(Radix: 10, Result&: FormatIdx);
4654 assert(!Error && "invalid format arg index");
4655 --FormatIdx; // 1-based to 0-based
4656
4657 FirstArgIdx.emplace();
4658 Error = FirstArgIdxStr.getAsInteger(Radix: 10, Result&: *FirstArgIdx);
4659 assert(!Error && "invalid first arg index");
4660 if (*FirstArgIdx > 0)
4661 --*FirstArgIdx; // 1-based to 0-based
4662 else
4663 FirstArgIdx.reset();
4664
4665 if (AllAspects.empty())
4666 return nullptr;
4667
4668 Value *FormatVal = CI->getArgOperand(i: FormatIdx);
4669 StringRef FormatStr;
4670
4671 std::optional<Bitset<256>> Specifiers;
4672 if (getConstantStringInfo(V: FormatVal, Str&: FormatStr))
4673 Specifiers = parseFormatStringSpecifiers(FormatStr);
4674
4675 SmallVector<StringRef> NeededAspects;
4676 for (StringRef Aspect : AllAspects)
4677 if (isAspectNeeded(Aspect, CI, FirstArgIdx, Specifiers))
4678 NeededAspects.push_back(Elt: Aspect);
4679
4680 if (NeededAspects.size() == AllAspects.size())
4681 return nullptr;
4682
4683 Module *M = CI->getModule();
4684 LLVMContext &Ctx = M->getContext();
4685 Function *Callee = CI->getCalledFunction();
4686 FunctionCallee ModularFn = M->getOrInsertFunction(
4687 Name: FnName, T: Callee->getFunctionType(),
4688 AttributeList: Callee->getAttributes().removeFnAttribute(C&: Ctx, Kind: "modular-format"));
4689 CallInst *New = cast<CallInst>(Val: CI->clone());
4690 New->setCalledFunction(ModularFn);
4691 New->removeFnAttr(Kind: "modular-format");
4692 B.Insert(I: New);
4693
4694 llvm::sort(C&: NeededAspects);
4695 for (StringRef Request : NeededAspects)
4696 referenceAspect(Aspect: Request, ImplName, M, B);
4697
4698 return New;
4699}
4700
4701Instruction *InstCombinerImpl::tryOptimizeCall(CallInst *CI) {
4702 if (!CI->getCalledFunction()) return nullptr;
4703
4704 // Skip optimizing notail and musttail calls so
4705 // LibCallSimplifier::optimizeCall doesn't have to preserve those invariants.
4706 // LibCallSimplifier::optimizeCall should try to preserve tail calls though.
4707 if (CI->isMustTailCall() || CI->isNoTailCall())
4708 return nullptr;
4709
4710 auto InstCombineRAUW = [this](Instruction *From, Value *With) {
4711 replaceInstUsesWith(I&: *From, V: With);
4712 };
4713 auto InstCombineErase = [this](Instruction *I) {
4714 eraseInstFromFunction(I&: *I);
4715 };
4716 LibCallSimplifier Simplifier(DL, &TLI, &DT, &DC, &AC, ORE, BFI, PSI,
4717 InstCombineRAUW, InstCombineErase);
4718 if (Value *With = Simplifier.optimizeCall(CI, B&: Builder)) {
4719 ++NumSimplified;
4720 return CI->use_empty() ? CI : replaceInstUsesWith(I&: *CI, V: With);
4721 }
4722 if (Value *With = optimizeModularFormat(CI, B&: Builder)) {
4723 ++NumSimplified;
4724 return CI->use_empty() ? CI : replaceInstUsesWith(I&: *CI, V: With);
4725 }
4726
4727 return nullptr;
4728}
4729
4730static IntrinsicInst *findInitTrampolineFromAlloca(Value *TrampMem) {
4731 // Strip off at most one level of pointer casts, looking for an alloca. This
4732 // is good enough in practice and simpler than handling any number of casts.
4733 Value *Underlying = TrampMem->stripPointerCasts();
4734 if (Underlying != TrampMem &&
4735 (!Underlying->hasOneUse() || Underlying->user_back() != TrampMem))
4736 return nullptr;
4737 if (!isa<AllocaInst>(Val: Underlying))
4738 return nullptr;
4739
4740 IntrinsicInst *InitTrampoline = nullptr;
4741 for (User *U : TrampMem->users()) {
4742 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Val: U);
4743 if (!II)
4744 return nullptr;
4745 if (II->getIntrinsicID() == Intrinsic::init_trampoline) {
4746 if (InitTrampoline)
4747 // More than one init_trampoline writes to this value. Give up.
4748 return nullptr;
4749 InitTrampoline = II;
4750 continue;
4751 }
4752 if (II->getIntrinsicID() == Intrinsic::adjust_trampoline)
4753 // Allow any number of calls to adjust.trampoline.
4754 continue;
4755 return nullptr;
4756 }
4757
4758 // No call to init.trampoline found.
4759 if (!InitTrampoline)
4760 return nullptr;
4761
4762 // Check that the alloca is being used in the expected way.
4763 if (InitTrampoline->getOperand(i_nocapture: 0) != TrampMem)
4764 return nullptr;
4765
4766 return InitTrampoline;
4767}
4768
4769static IntrinsicInst *findInitTrampolineFromBB(IntrinsicInst *AdjustTramp,
4770 Value *TrampMem) {
4771 // Visit all the previous instructions in the basic block, and try to find a
4772 // init.trampoline which has a direct path to the adjust.trampoline.
4773 for (BasicBlock::iterator I = AdjustTramp->getIterator(),
4774 E = AdjustTramp->getParent()->begin();
4775 I != E;) {
4776 Instruction *Inst = &*--I;
4777 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Val&: I))
4778 if (II->getIntrinsicID() == Intrinsic::init_trampoline &&
4779 II->getOperand(i_nocapture: 0) == TrampMem)
4780 return II;
4781 if (Inst->mayWriteToMemory())
4782 return nullptr;
4783 }
4784 return nullptr;
4785}
4786
4787// Given a call to llvm.adjust.trampoline, find and return the corresponding
4788// call to llvm.init.trampoline if the call to the trampoline can be optimized
4789// to a direct call to a function. Otherwise return NULL.
4790static IntrinsicInst *findInitTrampoline(Value *Callee) {
4791 Callee = Callee->stripPointerCasts();
4792 IntrinsicInst *AdjustTramp = dyn_cast<IntrinsicInst>(Val: Callee);
4793 if (!AdjustTramp ||
4794 AdjustTramp->getIntrinsicID() != Intrinsic::adjust_trampoline)
4795 return nullptr;
4796
4797 Value *TrampMem = AdjustTramp->getOperand(i_nocapture: 0);
4798
4799 if (IntrinsicInst *IT = findInitTrampolineFromAlloca(TrampMem))
4800 return IT;
4801 if (IntrinsicInst *IT = findInitTrampolineFromBB(AdjustTramp, TrampMem))
4802 return IT;
4803 return nullptr;
4804}
4805
4806Instruction *InstCombinerImpl::foldPtrAuthIntrinsicCallee(CallBase &Call) {
4807 const Value *Callee = Call.getCalledOperand();
4808 const auto *IPC = dyn_cast<IntToPtrInst>(Val: Callee);
4809 if (!IPC || !IPC->isNoopCast(DL))
4810 return nullptr;
4811
4812 const auto *II = dyn_cast<IntrinsicInst>(Val: IPC->getOperand(i_nocapture: 0));
4813 if (!II)
4814 return nullptr;
4815
4816 Intrinsic::ID IIID = II->getIntrinsicID();
4817 if (IIID != Intrinsic::ptrauth_resign && IIID != Intrinsic::ptrauth_sign)
4818 return nullptr;
4819
4820 // Isolate the ptrauth bundle from the others.
4821 std::optional<OperandBundleUse> PtrAuthBundleOrNone;
4822 SmallVector<OperandBundleDef, 2> NewBundles;
4823 for (unsigned BI = 0, BE = Call.getNumOperandBundles(); BI != BE; ++BI) {
4824 OperandBundleUse Bundle = Call.getOperandBundleAt(Index: BI);
4825 if (Bundle.getTagID() == LLVMContext::OB_ptrauth)
4826 PtrAuthBundleOrNone = Bundle;
4827 else
4828 NewBundles.emplace_back(Args&: Bundle);
4829 }
4830
4831 if (!PtrAuthBundleOrNone)
4832 return nullptr;
4833
4834 Value *NewCallee = nullptr;
4835 switch (IIID) {
4836 // call(ptrauth.resign(p)), ["ptrauth"()] -> call p, ["ptrauth"()]
4837 // assuming the call bundle and the sign operands match.
4838 case Intrinsic::ptrauth_resign: {
4839 // Resign result key should match bundle.
4840 if (II->getOperand(i_nocapture: 3) != PtrAuthBundleOrNone->Inputs[0])
4841 return nullptr;
4842 // Resign result discriminator should match bundle.
4843 if (II->getOperand(i_nocapture: 4) != PtrAuthBundleOrNone->Inputs[1])
4844 return nullptr;
4845
4846 // Resign input (auth) key should also match: we can't change the key on
4847 // the new call we're generating, because we don't know what keys are valid.
4848 if (II->getOperand(i_nocapture: 1) != PtrAuthBundleOrNone->Inputs[0])
4849 return nullptr;
4850
4851 Value *NewBundleOps[] = {II->getOperand(i_nocapture: 1), II->getOperand(i_nocapture: 2)};
4852 NewBundles.emplace_back(Args: "ptrauth", Args&: NewBundleOps);
4853 NewCallee = II->getOperand(i_nocapture: 0);
4854 break;
4855 }
4856
4857 // call(ptrauth.sign(p)), ["ptrauth"()] -> call p
4858 // assuming the call bundle and the sign operands match.
4859 // Non-ptrauth indirect calls are undesirable, but so is ptrauth.sign.
4860 case Intrinsic::ptrauth_sign: {
4861 // Sign key should match bundle.
4862 if (II->getOperand(i_nocapture: 1) != PtrAuthBundleOrNone->Inputs[0])
4863 return nullptr;
4864 // Sign discriminator should match bundle.
4865 if (II->getOperand(i_nocapture: 2) != PtrAuthBundleOrNone->Inputs[1])
4866 return nullptr;
4867 NewCallee = II->getOperand(i_nocapture: 0);
4868 break;
4869 }
4870 default:
4871 llvm_unreachable("unexpected intrinsic ID");
4872 }
4873
4874 if (!NewCallee)
4875 return nullptr;
4876
4877 NewCallee = Builder.CreateBitOrPointerCast(V: NewCallee, DestTy: Callee->getType());
4878 CallBase *NewCall = CallBase::Create(CB: &Call, Bundles: NewBundles);
4879 NewCall->setCalledOperand(NewCallee);
4880 return NewCall;
4881}
4882
4883Instruction *InstCombinerImpl::foldPtrAuthConstantCallee(CallBase &Call) {
4884 auto *CPA = dyn_cast<ConstantPtrAuth>(Val: Call.getCalledOperand());
4885 if (!CPA)
4886 return nullptr;
4887
4888 auto *CalleeF = dyn_cast<Function>(Val: CPA->getPointer());
4889 // If the ptrauth constant isn't based on a function pointer, bail out.
4890 if (!CalleeF)
4891 return nullptr;
4892
4893 // Inspect the call ptrauth bundle to check it matches the ptrauth constant.
4894 auto PAB = Call.getOperandBundle(ID: LLVMContext::OB_ptrauth);
4895 if (!PAB)
4896 return nullptr;
4897
4898 auto *Key = cast<ConstantInt>(Val: PAB->Inputs[0]);
4899 Value *Discriminator = PAB->Inputs[1];
4900
4901 // If the bundle doesn't match, this is probably going to fail to auth.
4902 if (!CPA->isKnownCompatibleWith(Key, Discriminator, DL))
4903 return nullptr;
4904
4905 // If the bundle matches the constant, proceed in making this a direct call.
4906 auto *NewCall = CallBase::removeOperandBundle(CB: &Call, ID: LLVMContext::OB_ptrauth);
4907 NewCall->setCalledOperand(CalleeF);
4908 return NewCall;
4909}
4910
4911bool InstCombinerImpl::annotateAnyAllocSite(CallBase &Call,
4912 const TargetLibraryInfo *TLI) {
4913 // Note: We only handle cases which can't be driven from generic attributes
4914 // here. So, for example, nonnull and noalias (which are common properties
4915 // of some allocation functions) are expected to be handled via annotation
4916 // of the respective allocator declaration with generic attributes.
4917 bool Changed = false;
4918
4919 if (!Call.getType()->isPointerTy())
4920 return Changed;
4921
4922 std::optional<APInt> Size = getAllocSize(CB: &Call, TLI);
4923 if (Size && *Size != 0) {
4924 // TODO: We really should just emit deref_or_null here and then
4925 // let the generic inference code combine that with nonnull.
4926 if (Call.hasRetAttr(Kind: Attribute::NonNull)) {
4927 Changed = !Call.hasRetAttr(Kind: Attribute::Dereferenceable);
4928 Call.addRetAttr(Attr: Attribute::getWithDereferenceableBytes(
4929 Context&: Call.getContext(), Bytes: Size->getLimitedValue()));
4930 } else {
4931 Changed = !Call.hasRetAttr(Kind: Attribute::DereferenceableOrNull);
4932 Call.addRetAttr(Attr: Attribute::getWithDereferenceableOrNullBytes(
4933 Context&: Call.getContext(), Bytes: Size->getLimitedValue()));
4934 }
4935 }
4936
4937 // Add alignment attribute if alignment is a power of two constant.
4938 Value *Alignment = getAllocAlignment(V: &Call, TLI);
4939 if (!Alignment)
4940 return Changed;
4941
4942 ConstantInt *AlignOpC = dyn_cast<ConstantInt>(Val: Alignment);
4943 if (AlignOpC && AlignOpC->getValue().ult(RHS: llvm::Value::MaximumAlignment)) {
4944 uint64_t AlignmentVal = AlignOpC->getZExtValue();
4945 if (llvm::isPowerOf2_64(Value: AlignmentVal)) {
4946 Align ExistingAlign = Call.getRetAlign().valueOrOne();
4947 Align NewAlign = Align(AlignmentVal);
4948 if (NewAlign > ExistingAlign) {
4949 Call.addRetAttr(
4950 Attr: Attribute::getWithAlignment(Context&: Call.getContext(), Alignment: NewAlign));
4951 Changed = true;
4952 }
4953 }
4954 }
4955 return Changed;
4956}
4957
4958/// Improvements for call, callbr and invoke instructions.
4959Instruction *InstCombinerImpl::visitCallBase(CallBase &Call) {
4960 bool Changed = annotateAnyAllocSite(Call, TLI: &TLI);
4961
4962 // Mark any parameters that are known to be non-null with the nonnull
4963 // attribute. This is helpful for inlining calls to functions with null
4964 // checks on their arguments.
4965 SmallVector<unsigned, 4> ArgNos;
4966 unsigned ArgNo = 0;
4967
4968 for (Value *V : Call.args()) {
4969 if (V->getType()->isPointerTy()) {
4970 // Simplify the nonnull operand if the parameter is known to be nonnull.
4971 // Otherwise, try to infer nonnull for it.
4972 bool HasDereferenceable = Call.getParamDereferenceableBytes(i: ArgNo) > 0;
4973 if (Call.paramHasAttr(ArgNo, Kind: Attribute::NonNull) ||
4974 (HasDereferenceable &&
4975 !NullPointerIsDefined(F: Call.getFunction(),
4976 AS: V->getType()->getPointerAddressSpace()))) {
4977 if (Value *Res = simplifyNonNullOperand(V, HasDereferenceable)) {
4978 replaceOperand(I&: Call, OpNum: ArgNo, V: Res);
4979 Changed = true;
4980 }
4981 } else if (isKnownNonZero(V,
4982 Q: getSimplifyQuery().getWithInstruction(I: &Call))) {
4983 ArgNos.push_back(Elt: ArgNo);
4984 }
4985 }
4986 ArgNo++;
4987 }
4988
4989 assert(ArgNo == Call.arg_size() && "Call arguments not processed correctly.");
4990
4991 if (!ArgNos.empty()) {
4992 AttributeList AS = Call.getAttributes();
4993 LLVMContext &Ctx = Call.getContext();
4994 AS = AS.addParamAttribute(C&: Ctx, ArgNos,
4995 A: Attribute::get(Context&: Ctx, Kind: Attribute::NonNull));
4996 Call.setAttributes(AS);
4997 Changed = true;
4998 }
4999
5000 // If the callee is a pointer to a function, attempt to move any casts to the
5001 // arguments of the call/callbr/invoke.
5002 Value *Callee = Call.getCalledOperand();
5003 Function *CalleeF = dyn_cast<Function>(Val: Callee);
5004 if ((!CalleeF || CalleeF->getFunctionType() != Call.getFunctionType()) &&
5005 transformConstExprCastCall(Call))
5006 return nullptr;
5007
5008 if (CalleeF) {
5009 // Remove the convergent attr on calls when the callee is not convergent.
5010 if (Call.isConvergent() && !CalleeF->isConvergent() &&
5011 !CalleeF->isIntrinsic()) {
5012 LLVM_DEBUG(dbgs() << "Removing convergent attr from instr " << Call
5013 << "\n");
5014 Call.setNotConvergent();
5015 return &Call;
5016 }
5017
5018 // If the call and callee calling conventions don't match, and neither one
5019 // of the calling conventions is compatible with C calling convention
5020 // this call must be unreachable, as the call is undefined.
5021 if ((CalleeF->getCallingConv() != Call.getCallingConv() &&
5022 !(CalleeF->getCallingConv() == llvm::CallingConv::C &&
5023 TargetLibraryInfoImpl::isCallingConvCCompatible(CI: &Call)) &&
5024 !(Call.getCallingConv() == llvm::CallingConv::C &&
5025 TargetLibraryInfoImpl::isCallingConvCCompatible(Callee: CalleeF))) &&
5026 // Only do this for calls to a function with a body. A prototype may
5027 // not actually end up matching the implementation's calling conv for a
5028 // variety of reasons (e.g. it may be written in assembly).
5029 !CalleeF->isDeclaration()) {
5030 Instruction *OldCall = &Call;
5031 CreateNonTerminatorUnreachable(InsertAt: OldCall);
5032 // If OldCall does not return void then replaceInstUsesWith poison.
5033 // This allows ValueHandlers and custom metadata to adjust itself.
5034 if (!OldCall->getType()->isVoidTy())
5035 replaceInstUsesWith(I&: *OldCall, V: PoisonValue::get(T: OldCall->getType()));
5036 if (isa<CallInst>(Val: OldCall))
5037 return eraseInstFromFunction(I&: *OldCall);
5038
5039 // We cannot remove an invoke or a callbr, because it would change thexi
5040 // CFG, just change the callee to a null pointer.
5041 cast<CallBase>(Val: OldCall)->setCalledFunction(
5042 FTy: CalleeF->getFunctionType(),
5043 Fn: Constant::getNullValue(Ty: CalleeF->getType()));
5044 return nullptr;
5045 }
5046 }
5047
5048 // Calling a null function pointer is undefined if a null address isn't
5049 // dereferenceable.
5050 if ((isa<ConstantPointerNull>(Val: Callee) &&
5051 !NullPointerIsDefined(F: Call.getFunction())) ||
5052 isa<UndefValue>(Val: Callee)) {
5053 // If Call does not return void then replaceInstUsesWith poison.
5054 // This allows ValueHandlers and custom metadata to adjust itself.
5055 if (!Call.getType()->isVoidTy())
5056 replaceInstUsesWith(I&: Call, V: PoisonValue::get(T: Call.getType()));
5057
5058 if (Call.isTerminator()) {
5059 // Can't remove an invoke or callbr because we cannot change the CFG.
5060 return nullptr;
5061 }
5062
5063 // This instruction is not reachable, just remove it.
5064 CreateNonTerminatorUnreachable(InsertAt: &Call);
5065 return eraseInstFromFunction(I&: Call);
5066 }
5067
5068 if (IntrinsicInst *II = findInitTrampoline(Callee))
5069 return transformCallThroughTrampoline(Call, Tramp&: *II);
5070
5071 // Combine calls involving pointer authentication intrinsics.
5072 if (Instruction *NewCall = foldPtrAuthIntrinsicCallee(Call))
5073 return NewCall;
5074
5075 // Combine calls to ptrauth constants.
5076 if (Instruction *NewCall = foldPtrAuthConstantCallee(Call))
5077 return NewCall;
5078
5079 if (isa<InlineAsm>(Val: Callee) && !Call.doesNotThrow()) {
5080 InlineAsm *IA = cast<InlineAsm>(Val: Callee);
5081 if (!IA->canThrow()) {
5082 // Normal inline asm calls cannot throw - mark them
5083 // 'nounwind'.
5084 Call.setDoesNotThrow();
5085 Changed = true;
5086 }
5087 }
5088
5089 // Try to optimize the call if possible, we require DataLayout for most of
5090 // this. None of these calls are seen as possibly dead so go ahead and
5091 // delete the instruction now.
5092 if (CallInst *CI = dyn_cast<CallInst>(Val: &Call)) {
5093 Instruction *I = tryOptimizeCall(CI);
5094 // If we changed something return the result, etc. Otherwise let
5095 // the fallthrough check.
5096 if (I) return eraseInstFromFunction(I&: *I);
5097 }
5098
5099 if (!Call.use_empty() && !Call.isMustTailCall())
5100 if (Value *ReturnedArg = Call.getReturnedArgOperand()) {
5101 Type *CallTy = Call.getType();
5102 Type *RetArgTy = ReturnedArg->getType();
5103 if (RetArgTy->canLosslesslyBitCastTo(Ty: CallTy))
5104 return replaceInstUsesWith(
5105 I&: Call, V: Builder.CreateBitOrPointerCast(V: ReturnedArg, DestTy: CallTy));
5106 }
5107
5108 // Drop unnecessary callee_type metadata from calls that were converted
5109 // into direct calls.
5110 if (Call.getMetadata(KindID: LLVMContext::MD_callee_type) && !Call.isIndirectCall()) {
5111 Call.setMetadata(KindID: LLVMContext::MD_callee_type, Node: nullptr);
5112 Changed = true;
5113 }
5114
5115 // Drop unnecessary kcfi operand bundles from calls that were converted
5116 // into direct calls.
5117 auto Bundle = Call.getOperandBundle(ID: LLVMContext::OB_kcfi);
5118 if (Bundle && !Call.isIndirectCall()) {
5119 DEBUG_WITH_TYPE(DEBUG_TYPE "-kcfi", {
5120 if (CalleeF) {
5121 ConstantInt *FunctionType = nullptr;
5122 ConstantInt *ExpectedType = cast<ConstantInt>(Bundle->Inputs[0]);
5123
5124 if (MDNode *MD = CalleeF->getMetadata(LLVMContext::MD_kcfi_type))
5125 FunctionType = mdconst::extract<ConstantInt>(MD->getOperand(0));
5126
5127 if (FunctionType &&
5128 FunctionType->getZExtValue() != ExpectedType->getZExtValue())
5129 dbgs() << Call.getModule()->getName()
5130 << ": warning: kcfi: " << Call.getCaller()->getName()
5131 << ": call to " << CalleeF->getName()
5132 << " using a mismatching function pointer type\n";
5133 }
5134 });
5135
5136 return CallBase::removeOperandBundle(CB: &Call, ID: LLVMContext::OB_kcfi);
5137 }
5138
5139 if (isRemovableAlloc(V: &Call, TLI: &TLI))
5140 return visitAllocSite(FI&: Call);
5141
5142 // Handle intrinsics which can be used in both call and invoke context.
5143 switch (Call.getIntrinsicID()) {
5144 case Intrinsic::experimental_gc_statepoint: {
5145 GCStatepointInst &GCSP = *cast<GCStatepointInst>(Val: &Call);
5146 SmallPtrSet<Value *, 32> LiveGcValues;
5147 for (const GCRelocateInst *Reloc : GCSP.getGCRelocates()) {
5148 GCRelocateInst &GCR = *const_cast<GCRelocateInst *>(Reloc);
5149
5150 // Remove the relocation if unused.
5151 if (GCR.use_empty()) {
5152 eraseInstFromFunction(I&: GCR);
5153 continue;
5154 }
5155
5156 Value *DerivedPtr = GCR.getDerivedPtr();
5157 Value *BasePtr = GCR.getBasePtr();
5158
5159 // Undef is undef, even after relocation.
5160 if (isa<UndefValue>(Val: DerivedPtr) || isa<UndefValue>(Val: BasePtr)) {
5161 replaceInstUsesWith(I&: GCR, V: UndefValue::get(T: GCR.getType()));
5162 eraseInstFromFunction(I&: GCR);
5163 continue;
5164 }
5165
5166 if (auto *PT = dyn_cast<PointerType>(Val: GCR.getType())) {
5167 // The relocation of null will be null for most any collector.
5168 // TODO: provide a hook for this in GCStrategy. There might be some
5169 // weird collector this property does not hold for.
5170 if (isa<ConstantPointerNull>(Val: DerivedPtr)) {
5171 // Use null-pointer of gc_relocate's type to replace it.
5172 replaceInstUsesWith(I&: GCR, V: ConstantPointerNull::get(T: PT));
5173 eraseInstFromFunction(I&: GCR);
5174 continue;
5175 }
5176
5177 // isKnownNonNull -> nonnull attribute
5178 if (!GCR.hasRetAttr(Kind: Attribute::NonNull) &&
5179 isKnownNonZero(V: DerivedPtr,
5180 Q: getSimplifyQuery().getWithInstruction(I: &Call))) {
5181 GCR.addRetAttr(Kind: Attribute::NonNull);
5182 // We discovered new fact, re-check users.
5183 Worklist.pushUsersToWorkList(I&: GCR);
5184 }
5185 }
5186
5187 // If we have two copies of the same pointer in the statepoint argument
5188 // list, canonicalize to one. This may let us common gc.relocates.
5189 if (GCR.getBasePtr() == GCR.getDerivedPtr() &&
5190 GCR.getBasePtrIndex() != GCR.getDerivedPtrIndex()) {
5191 auto *OpIntTy = GCR.getOperand(i_nocapture: 2)->getType();
5192 GCR.setOperand(i_nocapture: 2, Val_nocapture: ConstantInt::get(Ty: OpIntTy, V: GCR.getBasePtrIndex()));
5193 }
5194
5195 // TODO: bitcast(relocate(p)) -> relocate(bitcast(p))
5196 // Canonicalize on the type from the uses to the defs
5197
5198 // TODO: relocate((gep p, C, C2, ...)) -> gep(relocate(p), C, C2, ...)
5199 LiveGcValues.insert(Ptr: BasePtr);
5200 LiveGcValues.insert(Ptr: DerivedPtr);
5201 }
5202 std::optional<OperandBundleUse> Bundle =
5203 GCSP.getOperandBundle(ID: LLVMContext::OB_gc_live);
5204 unsigned NumOfGCLives = LiveGcValues.size();
5205 if (!Bundle || NumOfGCLives == Bundle->Inputs.size())
5206 break;
5207 // We can reduce the size of gc live bundle.
5208 DenseMap<Value *, unsigned> Val2Idx;
5209 std::vector<Value *> NewLiveGc;
5210 for (Value *V : Bundle->Inputs) {
5211 auto [It, Inserted] = Val2Idx.try_emplace(Key: V);
5212 if (!Inserted)
5213 continue;
5214 if (LiveGcValues.count(Ptr: V)) {
5215 It->second = NewLiveGc.size();
5216 NewLiveGc.push_back(x: V);
5217 } else
5218 It->second = NumOfGCLives;
5219 }
5220 // Update all gc.relocates
5221 for (const GCRelocateInst *Reloc : GCSP.getGCRelocates()) {
5222 GCRelocateInst &GCR = *const_cast<GCRelocateInst *>(Reloc);
5223 Value *BasePtr = GCR.getBasePtr();
5224 assert(Val2Idx.count(BasePtr) && Val2Idx[BasePtr] != NumOfGCLives &&
5225 "Missed live gc for base pointer");
5226 auto *OpIntTy1 = GCR.getOperand(i_nocapture: 1)->getType();
5227 GCR.setOperand(i_nocapture: 1, Val_nocapture: ConstantInt::get(Ty: OpIntTy1, V: Val2Idx[BasePtr]));
5228 Value *DerivedPtr = GCR.getDerivedPtr();
5229 assert(Val2Idx.count(DerivedPtr) && Val2Idx[DerivedPtr] != NumOfGCLives &&
5230 "Missed live gc for derived pointer");
5231 auto *OpIntTy2 = GCR.getOperand(i_nocapture: 2)->getType();
5232 GCR.setOperand(i_nocapture: 2, Val_nocapture: ConstantInt::get(Ty: OpIntTy2, V: Val2Idx[DerivedPtr]));
5233 }
5234 // Create new statepoint instruction.
5235 OperandBundleDef NewBundle("gc-live", std::move(NewLiveGc));
5236 return CallBase::Create(CB: &Call, Bundle: NewBundle);
5237 }
5238 default: { break; }
5239 }
5240
5241 return Changed ? &Call : nullptr;
5242}
5243
5244/// If the callee is a constexpr cast of a function, attempt to move the cast to
5245/// the arguments of the call/invoke.
5246/// CallBrInst is not supported.
5247bool InstCombinerImpl::transformConstExprCastCall(CallBase &Call) {
5248 auto *Callee =
5249 dyn_cast<Function>(Val: Call.getCalledOperand()->stripPointerCasts());
5250 if (!Callee)
5251 return false;
5252
5253 assert(!isa<CallBrInst>(Call) &&
5254 "CallBr's don't have a single point after a def to insert at");
5255
5256 // Don't perform the transform for declarations, which may not be fully
5257 // accurate. For example, void @foo() is commonly used as a placeholder for
5258 // unknown prototypes.
5259 if (Callee->isDeclaration())
5260 return false;
5261
5262 // If this is a call to a thunk function, don't remove the cast. Thunks are
5263 // used to transparently forward all incoming parameters and outgoing return
5264 // values, so it's important to leave the cast in place.
5265 if (Callee->hasFnAttribute(Kind: "thunk"))
5266 return false;
5267
5268 // If this is a call to a naked function, the assembly might be
5269 // using an argument, or otherwise rely on the frame layout,
5270 // the function prototype will mismatch.
5271 if (Callee->hasFnAttribute(Kind: Attribute::Naked))
5272 return false;
5273
5274 // If this is a musttail call, the callee's prototype must match the caller's
5275 // prototype with the exception of pointee types. The code below doesn't
5276 // implement that, so we can't do this transform.
5277 // TODO: Do the transform if it only requires adding pointer casts.
5278 if (Call.isMustTailCall())
5279 return false;
5280
5281 Instruction *Caller = &Call;
5282 const AttributeList &CallerPAL = Call.getAttributes();
5283
5284 // Okay, this is a cast from a function to a different type. Unless doing so
5285 // would cause a type conversion of one of our arguments, change this call to
5286 // be a direct call with arguments casted to the appropriate types.
5287 FunctionType *FT = Callee->getFunctionType();
5288 Type *OldRetTy = Caller->getType();
5289 Type *NewRetTy = FT->getReturnType();
5290
5291 // Check to see if we are changing the return type...
5292 if (OldRetTy != NewRetTy) {
5293
5294 if (NewRetTy->isStructTy())
5295 return false; // TODO: Handle multiple return values.
5296
5297 if (!CastInst::isBitOrNoopPointerCastable(SrcTy: NewRetTy, DestTy: OldRetTy, DL)) {
5298 if (!Caller->use_empty())
5299 return false; // Cannot transform this return value.
5300 }
5301
5302 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
5303 AttrBuilder RAttrs(FT->getContext(), CallerPAL.getRetAttrs());
5304 if (RAttrs.overlaps(AM: AttributeFuncs::typeIncompatible(
5305 Ty: NewRetTy, AS: CallerPAL.getRetAttrs())))
5306 return false; // Attribute not compatible with transformed value.
5307 }
5308
5309 // If the callbase is an invoke instruction, and the return value is
5310 // used by a PHI node in a successor, we cannot change the return type of
5311 // the call because there is no place to put the cast instruction (without
5312 // breaking the critical edge). Bail out in this case.
5313 if (!Caller->use_empty()) {
5314 BasicBlock *PhisNotSupportedBlock = nullptr;
5315 if (auto *II = dyn_cast<InvokeInst>(Val: Caller))
5316 PhisNotSupportedBlock = II->getNormalDest();
5317 if (PhisNotSupportedBlock)
5318 for (User *U : Caller->users())
5319 if (PHINode *PN = dyn_cast<PHINode>(Val: U))
5320 if (PN->getParent() == PhisNotSupportedBlock)
5321 return false;
5322 }
5323 }
5324
5325 unsigned NumActualArgs = Call.arg_size();
5326 unsigned NumCommonArgs = std::min(a: FT->getNumParams(), b: NumActualArgs);
5327
5328 // Prevent us turning:
5329 // declare void @takes_i32_inalloca(i32* inalloca)
5330 // call void bitcast (void (i32*)* @takes_i32_inalloca to void (i32)*)(i32 0)
5331 //
5332 // into:
5333 // call void @takes_i32_inalloca(i32* null)
5334 //
5335 // Similarly, avoid folding away bitcasts of byval calls.
5336 if (Callee->getAttributes().hasAttrSomewhere(Kind: Attribute::InAlloca) ||
5337 Callee->getAttributes().hasAttrSomewhere(Kind: Attribute::Preallocated))
5338 return false;
5339
5340 auto AI = Call.arg_begin();
5341 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
5342 Type *ParamTy = FT->getParamType(i);
5343 Type *ActTy = (*AI)->getType();
5344
5345 if (!CastInst::isBitOrNoopPointerCastable(SrcTy: ActTy, DestTy: ParamTy, DL))
5346 return false; // Cannot transform this parameter value.
5347
5348 // Check if there are any incompatible attributes we cannot drop safely.
5349 if (AttrBuilder(FT->getContext(), CallerPAL.getParamAttrs(ArgNo: i))
5350 .overlaps(AM: AttributeFuncs::typeIncompatible(
5351 Ty: ParamTy, AS: CallerPAL.getParamAttrs(ArgNo: i),
5352 ASK: AttributeFuncs::ASK_UNSAFE_TO_DROP)))
5353 return false; // Attribute not compatible with transformed value.
5354
5355 if (Call.isInAllocaArgument(ArgNo: i) ||
5356 CallerPAL.hasParamAttr(ArgNo: i, Kind: Attribute::Preallocated))
5357 return false; // Cannot transform to and from inalloca/preallocated.
5358
5359 if (CallerPAL.hasParamAttr(ArgNo: i, Kind: Attribute::SwiftError))
5360 return false;
5361
5362 if (CallerPAL.hasParamAttr(ArgNo: i, Kind: Attribute::ByVal) !=
5363 Callee->getAttributes().hasParamAttr(ArgNo: i, Kind: Attribute::ByVal))
5364 return false; // Cannot transform to or from byval.
5365 }
5366
5367 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
5368 !CallerPAL.isEmpty()) {
5369 // In this case we have more arguments than the new function type, but we
5370 // won't be dropping them. Check that these extra arguments have attributes
5371 // that are compatible with being a vararg call argument.
5372 unsigned SRetIdx;
5373 if (CallerPAL.hasAttrSomewhere(Kind: Attribute::StructRet, Index: &SRetIdx) &&
5374 SRetIdx - AttributeList::FirstArgIndex >= FT->getNumParams())
5375 return false;
5376 }
5377
5378 // Okay, we decided that this is a safe thing to do: go ahead and start
5379 // inserting cast instructions as necessary.
5380 SmallVector<Value *, 8> Args;
5381 SmallVector<AttributeSet, 8> ArgAttrs;
5382 Args.reserve(N: NumActualArgs);
5383 ArgAttrs.reserve(N: NumActualArgs);
5384
5385 // Get any return attributes.
5386 AttrBuilder RAttrs(FT->getContext(), CallerPAL.getRetAttrs());
5387
5388 // If the return value is not being used, the type may not be compatible
5389 // with the existing attributes. Wipe out any problematic attributes.
5390 RAttrs.remove(
5391 AM: AttributeFuncs::typeIncompatible(Ty: NewRetTy, AS: CallerPAL.getRetAttrs()));
5392
5393 LLVMContext &Ctx = Call.getContext();
5394 AI = Call.arg_begin();
5395 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
5396 Type *ParamTy = FT->getParamType(i);
5397
5398 Value *NewArg = *AI;
5399 if ((*AI)->getType() != ParamTy)
5400 NewArg = Builder.CreateBitOrPointerCast(V: *AI, DestTy: ParamTy);
5401 Args.push_back(Elt: NewArg);
5402
5403 // Add any parameter attributes except the ones incompatible with the new
5404 // type. Note that we made sure all incompatible ones are safe to drop.
5405 AttributeMask IncompatibleAttrs = AttributeFuncs::typeIncompatible(
5406 Ty: ParamTy, AS: CallerPAL.getParamAttrs(ArgNo: i), ASK: AttributeFuncs::ASK_SAFE_TO_DROP);
5407 ArgAttrs.push_back(
5408 Elt: CallerPAL.getParamAttrs(ArgNo: i).removeAttributes(C&: Ctx, AttrsToRemove: IncompatibleAttrs));
5409 }
5410
5411 // If the function takes more arguments than the call was taking, add them
5412 // now.
5413 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i) {
5414 Args.push_back(Elt: Constant::getNullValue(Ty: FT->getParamType(i)));
5415 ArgAttrs.push_back(Elt: AttributeSet());
5416 }
5417
5418 // If we are removing arguments to the function, emit an obnoxious warning.
5419 if (FT->getNumParams() < NumActualArgs) {
5420 // TODO: if (!FT->isVarArg()) this call may be unreachable. PR14722
5421 if (FT->isVarArg()) {
5422 // Add all of the arguments in their promoted form to the arg list.
5423 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
5424 Type *PTy = getPromotedType(Ty: (*AI)->getType());
5425 Value *NewArg = *AI;
5426 if (PTy != (*AI)->getType()) {
5427 // Must promote to pass through va_arg area!
5428 Instruction::CastOps opcode =
5429 CastInst::getCastOpcode(Val: *AI, SrcIsSigned: false, Ty: PTy, DstIsSigned: false);
5430 NewArg = Builder.CreateCast(Op: opcode, V: *AI, DestTy: PTy);
5431 }
5432 Args.push_back(Elt: NewArg);
5433
5434 // Add any parameter attributes.
5435 ArgAttrs.push_back(Elt: CallerPAL.getParamAttrs(ArgNo: i));
5436 }
5437 }
5438 }
5439
5440 AttributeSet FnAttrs = CallerPAL.getFnAttrs();
5441
5442 if (NewRetTy->isVoidTy())
5443 Caller->setName(""); // Void type should not have a name.
5444
5445 assert((ArgAttrs.size() == FT->getNumParams() || FT->isVarArg()) &&
5446 "missing argument attributes");
5447 AttributeList NewCallerPAL = AttributeList::get(
5448 C&: Ctx, FnAttrs, RetAttrs: AttributeSet::get(C&: Ctx, B: RAttrs), ArgAttrs);
5449
5450 SmallVector<OperandBundleDef, 1> OpBundles;
5451 Call.getOperandBundlesAsDefs(Defs&: OpBundles);
5452
5453 CallBase *NewCall;
5454 if (InvokeInst *II = dyn_cast<InvokeInst>(Val: Caller)) {
5455 NewCall = Builder.CreateInvoke(Callee, NormalDest: II->getNormalDest(),
5456 UnwindDest: II->getUnwindDest(), Args, OpBundles);
5457 } else {
5458 NewCall = Builder.CreateCall(Callee, Args, OpBundles);
5459 cast<CallInst>(Val: NewCall)->setTailCallKind(
5460 cast<CallInst>(Val: Caller)->getTailCallKind());
5461 }
5462 NewCall->takeName(V: Caller);
5463 NewCall->setCallingConv(Call.getCallingConv());
5464 NewCall->setAttributes(NewCallerPAL);
5465
5466 // Preserve prof metadata if any.
5467 NewCall->copyMetadata(SrcInst: *Caller, WL: {LLVMContext::MD_prof});
5468
5469 // Insert a cast of the return type as necessary.
5470 Instruction *NC = NewCall;
5471 Value *NV = NC;
5472 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
5473 assert(!NV->getType()->isVoidTy());
5474 NV = NC = CastInst::CreateBitOrPointerCast(S: NC, Ty: OldRetTy);
5475 NC->setDebugLoc(Caller->getDebugLoc());
5476
5477 auto OptInsertPt = NewCall->getInsertionPointAfterDef();
5478 assert(OptInsertPt && "No place to insert cast");
5479 InsertNewInstBefore(New: NC, Old: *OptInsertPt);
5480 Worklist.pushUsersToWorkList(I&: *Caller);
5481 }
5482
5483 if (!Caller->use_empty())
5484 replaceInstUsesWith(I&: *Caller, V: NV);
5485 else if (Caller->hasValueHandle()) {
5486 if (OldRetTy == NV->getType())
5487 ValueHandleBase::ValueIsRAUWd(Old: Caller, New: NV);
5488 else
5489 // We cannot call ValueIsRAUWd with a different type, and the
5490 // actual tracked value will disappear.
5491 ValueHandleBase::ValueIsDeleted(V: Caller);
5492 }
5493
5494 eraseInstFromFunction(I&: *Caller);
5495 return true;
5496}
5497
5498/// Turn a call to a function created by init_trampoline / adjust_trampoline
5499/// intrinsic pair into a direct call to the underlying function.
5500Instruction *
5501InstCombinerImpl::transformCallThroughTrampoline(CallBase &Call,
5502 IntrinsicInst &Tramp) {
5503 FunctionType *FTy = Call.getFunctionType();
5504 AttributeList Attrs = Call.getAttributes();
5505
5506 // If the call already has the 'nest' attribute somewhere then give up -
5507 // otherwise 'nest' would occur twice after splicing in the chain.
5508 if (Attrs.hasAttrSomewhere(Kind: Attribute::Nest))
5509 return nullptr;
5510
5511 Function *NestF = cast<Function>(Val: Tramp.getArgOperand(i: 1)->stripPointerCasts());
5512 FunctionType *NestFTy = NestF->getFunctionType();
5513
5514 AttributeList NestAttrs = NestF->getAttributes();
5515 if (!NestAttrs.isEmpty()) {
5516 unsigned NestArgNo = 0;
5517 Type *NestTy = nullptr;
5518 AttributeSet NestAttr;
5519
5520 // Look for a parameter marked with the 'nest' attribute.
5521 for (FunctionType::param_iterator I = NestFTy->param_begin(),
5522 E = NestFTy->param_end();
5523 I != E; ++NestArgNo, ++I) {
5524 AttributeSet AS = NestAttrs.getParamAttrs(ArgNo: NestArgNo);
5525 if (AS.hasAttribute(Kind: Attribute::Nest)) {
5526 // Record the parameter type and any other attributes.
5527 NestTy = *I;
5528 NestAttr = AS;
5529 break;
5530 }
5531 }
5532
5533 if (NestTy) {
5534 std::vector<Value*> NewArgs;
5535 std::vector<AttributeSet> NewArgAttrs;
5536 NewArgs.reserve(n: Call.arg_size() + 1);
5537 NewArgAttrs.reserve(n: Call.arg_size());
5538
5539 // Insert the nest argument into the call argument list, which may
5540 // mean appending it. Likewise for attributes.
5541
5542 {
5543 unsigned ArgNo = 0;
5544 auto I = Call.arg_begin(), E = Call.arg_end();
5545 do {
5546 if (ArgNo == NestArgNo) {
5547 // Add the chain argument and attributes.
5548 Value *NestVal = Tramp.getArgOperand(i: 2);
5549 if (NestVal->getType() != NestTy)
5550 NestVal = Builder.CreateBitCast(V: NestVal, DestTy: NestTy, Name: "nest");
5551 NewArgs.push_back(x: NestVal);
5552 NewArgAttrs.push_back(x: NestAttr);
5553 }
5554
5555 if (I == E)
5556 break;
5557
5558 // Add the original argument and attributes.
5559 NewArgs.push_back(x: *I);
5560 NewArgAttrs.push_back(x: Attrs.getParamAttrs(ArgNo));
5561
5562 ++ArgNo;
5563 ++I;
5564 } while (true);
5565 }
5566
5567 // The trampoline may have been bitcast to a bogus type (FTy).
5568 // Handle this by synthesizing a new function type, equal to FTy
5569 // with the chain parameter inserted.
5570
5571 std::vector<Type*> NewTypes;
5572 NewTypes.reserve(n: FTy->getNumParams()+1);
5573
5574 // Insert the chain's type into the list of parameter types, which may
5575 // mean appending it.
5576 {
5577 unsigned ArgNo = 0;
5578 FunctionType::param_iterator I = FTy->param_begin(),
5579 E = FTy->param_end();
5580
5581 do {
5582 if (ArgNo == NestArgNo)
5583 // Add the chain's type.
5584 NewTypes.push_back(x: NestTy);
5585
5586 if (I == E)
5587 break;
5588
5589 // Add the original type.
5590 NewTypes.push_back(x: *I);
5591
5592 ++ArgNo;
5593 ++I;
5594 } while (true);
5595 }
5596
5597 // Replace the trampoline call with a direct call. Let the generic
5598 // code sort out any function type mismatches.
5599 FunctionType *NewFTy =
5600 FunctionType::get(Result: FTy->getReturnType(), Params: NewTypes, isVarArg: FTy->isVarArg());
5601 AttributeList NewPAL =
5602 AttributeList::get(C&: FTy->getContext(), FnAttrs: Attrs.getFnAttrs(),
5603 RetAttrs: Attrs.getRetAttrs(), ArgAttrs: NewArgAttrs);
5604
5605 SmallVector<OperandBundleDef, 1> OpBundles;
5606 Call.getOperandBundlesAsDefs(Defs&: OpBundles);
5607
5608 Instruction *NewCaller;
5609 if (InvokeInst *II = dyn_cast<InvokeInst>(Val: &Call)) {
5610 NewCaller = InvokeInst::Create(Ty: NewFTy, Func: NestF, IfNormal: II->getNormalDest(),
5611 IfException: II->getUnwindDest(), Args: NewArgs, Bundles: OpBundles);
5612 cast<InvokeInst>(Val: NewCaller)->setCallingConv(II->getCallingConv());
5613 cast<InvokeInst>(Val: NewCaller)->setAttributes(NewPAL);
5614 } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(Val: &Call)) {
5615 NewCaller =
5616 CallBrInst::Create(Ty: NewFTy, Func: NestF, DefaultDest: CBI->getDefaultDest(),
5617 IndirectDests: CBI->getIndirectDests(), Args: NewArgs, Bundles: OpBundles);
5618 cast<CallBrInst>(Val: NewCaller)->setCallingConv(CBI->getCallingConv());
5619 cast<CallBrInst>(Val: NewCaller)->setAttributes(NewPAL);
5620 } else {
5621 NewCaller = CallInst::Create(Ty: NewFTy, Func: NestF, Args: NewArgs, Bundles: OpBundles);
5622 cast<CallInst>(Val: NewCaller)->setTailCallKind(
5623 cast<CallInst>(Val&: Call).getTailCallKind());
5624 cast<CallInst>(Val: NewCaller)->setCallingConv(
5625 cast<CallInst>(Val&: Call).getCallingConv());
5626 cast<CallInst>(Val: NewCaller)->setAttributes(NewPAL);
5627 }
5628 NewCaller->setDebugLoc(Call.getDebugLoc());
5629
5630 return NewCaller;
5631 }
5632 }
5633
5634 // Replace the trampoline call with a direct call. Since there is no 'nest'
5635 // parameter, there is no need to adjust the argument list. Let the generic
5636 // code sort out any function type mismatches.
5637 Call.setCalledFunction(FTy, Fn: NestF);
5638 return &Call;
5639}
5640