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