LLVM 20.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"
21#include "llvm/ADT/Statistic.h"
26#include "llvm/Analysis/Loads.h"
31#include "llvm/IR/Attributes.h"
32#include "llvm/IR/BasicBlock.h"
33#include "llvm/IR/Constant.h"
34#include "llvm/IR/Constants.h"
35#include "llvm/IR/DataLayout.h"
36#include "llvm/IR/DebugInfo.h"
38#include "llvm/IR/Function.h"
40#include "llvm/IR/InlineAsm.h"
41#include "llvm/IR/InstrTypes.h"
42#include "llvm/IR/Instruction.h"
45#include "llvm/IR/Intrinsics.h"
46#include "llvm/IR/IntrinsicsAArch64.h"
47#include "llvm/IR/IntrinsicsAMDGPU.h"
48#include "llvm/IR/IntrinsicsARM.h"
49#include "llvm/IR/IntrinsicsHexagon.h"
50#include "llvm/IR/LLVMContext.h"
51#include "llvm/IR/Metadata.h"
53#include "llvm/IR/Statepoint.h"
54#include "llvm/IR/Type.h"
55#include "llvm/IR/User.h"
56#include "llvm/IR/Value.h"
57#include "llvm/IR/ValueHandle.h"
62#include "llvm/Support/Debug.h"
71#include <algorithm>
72#include <cassert>
73#include <cstdint>
74#include <optional>
75#include <utility>
76#include <vector>
77
78#define DEBUG_TYPE "instcombine"
80
81using namespace llvm;
82using namespace PatternMatch;
83
84STATISTIC(NumSimplified, "Number of library calls simplified");
85
87 "instcombine-guard-widening-window",
88 cl::init(3),
89 cl::desc("How wide an instruction window to bypass looking for "
90 "another guard"));
91
92/// Return the specified type promoted as it would be to pass though a va_arg
93/// area.
95 if (IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
96 if (ITy->getBitWidth() < 32)
97 return Type::getInt32Ty(Ty->getContext());
98 }
99 return Ty;
100}
101
102/// Recognize a memcpy/memmove from a trivially otherwise unused alloca.
103/// TODO: This should probably be integrated with visitAllocSites, but that
104/// requires a deeper change to allow either unread or unwritten objects.
106 auto *Src = MI->getRawSource();
107 while (isa<GetElementPtrInst>(Src)) {
108 if (!Src->hasOneUse())
109 return false;
110 Src = cast<Instruction>(Src)->getOperand(0);
111 }
112 return isa<AllocaInst>(Src) && Src->hasOneUse();
113}
114
116 Align DstAlign = getKnownAlignment(MI->getRawDest(), DL, MI, &AC, &DT);
117 MaybeAlign CopyDstAlign = MI->getDestAlign();
118 if (!CopyDstAlign || *CopyDstAlign < DstAlign) {
119 MI->setDestAlignment(DstAlign);
120 return MI;
121 }
122
123 Align SrcAlign = getKnownAlignment(MI->getRawSource(), DL, MI, &AC, &DT);
124 MaybeAlign CopySrcAlign = MI->getSourceAlign();
125 if (!CopySrcAlign || *CopySrcAlign < SrcAlign) {
126 MI->setSourceAlignment(SrcAlign);
127 return MI;
128 }
129
130 // If we have a store to a location which is known constant, we can conclude
131 // that the store must be storing the constant value (else the memory
132 // wouldn't be constant), and this must be a noop.
133 if (!isModSet(AA->getModRefInfoMask(MI->getDest()))) {
134 // Set the size of the copy to 0, it will be deleted on the next iteration.
135 MI->setLength(Constant::getNullValue(MI->getLength()->getType()));
136 return MI;
137 }
138
139 // If the source is provably undef, the memcpy/memmove doesn't do anything
140 // (unless the transfer is volatile).
141 if (hasUndefSource(MI) && !MI->isVolatile()) {
142 // Set the size of the copy to 0, it will be deleted on the next iteration.
143 MI->setLength(Constant::getNullValue(MI->getLength()->getType()));
144 return MI;
145 }
146
147 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
148 // load/store.
149 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getLength());
150 if (!MemOpLength) return nullptr;
151
152 // Source and destination pointer types are always "i8*" for intrinsic. See
153 // if the size is something we can handle with a single primitive load/store.
154 // A single load+store correctly handles overlapping memory in the memmove
155 // case.
156 uint64_t Size = MemOpLength->getLimitedValue();
157 assert(Size && "0-sized memory transferring should be removed already.");
158
159 if (Size > 8 || (Size&(Size-1)))
160 return nullptr; // If not 1/2/4/8 bytes, exit.
161
162 // If it is an atomic and alignment is less than the size then we will
163 // introduce the unaligned memory access which will be later transformed
164 // into libcall in CodeGen. This is not evident performance gain so disable
165 // it now.
166 if (isa<AtomicMemTransferInst>(MI))
167 if (*CopyDstAlign < Size || *CopySrcAlign < Size)
168 return nullptr;
169
170 // Use an integer load+store unless we can find something better.
171 IntegerType* IntType = IntegerType::get(MI->getContext(), Size<<3);
172
173 // If the memcpy has metadata describing the members, see if we can get the
174 // TBAA, scope and noalias tags describing our copy.
175 AAMDNodes AACopyMD = MI->getAAMetadata().adjustForAccess(Size);
176
177 Value *Src = MI->getArgOperand(1);
178 Value *Dest = MI->getArgOperand(0);
179 LoadInst *L = Builder.CreateLoad(IntType, Src);
180 // Alignment from the mem intrinsic will be better, so use it.
181 L->setAlignment(*CopySrcAlign);
182 L->setAAMetadata(AACopyMD);
183 MDNode *LoopMemParallelMD =
184 MI->getMetadata(LLVMContext::MD_mem_parallel_loop_access);
185 if (LoopMemParallelMD)
186 L->setMetadata(LLVMContext::MD_mem_parallel_loop_access, LoopMemParallelMD);
187 MDNode *AccessGroupMD = MI->getMetadata(LLVMContext::MD_access_group);
188 if (AccessGroupMD)
189 L->setMetadata(LLVMContext::MD_access_group, AccessGroupMD);
190
191 StoreInst *S = Builder.CreateStore(L, Dest);
192 // Alignment from the mem intrinsic will be better, so use it.
193 S->setAlignment(*CopyDstAlign);
194 S->setAAMetadata(AACopyMD);
195 if (LoopMemParallelMD)
196 S->setMetadata(LLVMContext::MD_mem_parallel_loop_access, LoopMemParallelMD);
197 if (AccessGroupMD)
198 S->setMetadata(LLVMContext::MD_access_group, AccessGroupMD);
199 S->copyMetadata(*MI, LLVMContext::MD_DIAssignID);
200
201 if (auto *MT = dyn_cast<MemTransferInst>(MI)) {
202 // non-atomics can be volatile
203 L->setVolatile(MT->isVolatile());
204 S->setVolatile(MT->isVolatile());
205 }
206 if (isa<AtomicMemTransferInst>(MI)) {
207 // atomics have to be unordered
208 L->setOrdering(AtomicOrdering::Unordered);
210 }
211
212 // Set the size of the copy to 0, it will be deleted on the next iteration.
213 MI->setLength(Constant::getNullValue(MemOpLength->getType()));
214 return MI;
215}
216
218 const Align KnownAlignment =
219 getKnownAlignment(MI->getDest(), DL, MI, &AC, &DT);
220 MaybeAlign MemSetAlign = MI->getDestAlign();
221 if (!MemSetAlign || *MemSetAlign < KnownAlignment) {
222 MI->setDestAlignment(KnownAlignment);
223 return MI;
224 }
225
226 // If we have a store to a location which is known constant, we can conclude
227 // that the store must be storing the constant value (else the memory
228 // wouldn't be constant), and this must be a noop.
229 if (!isModSet(AA->getModRefInfoMask(MI->getDest()))) {
230 // Set the size of the copy to 0, it will be deleted on the next iteration.
231 MI->setLength(Constant::getNullValue(MI->getLength()->getType()));
232 return MI;
233 }
234
235 // Remove memset with an undef value.
236 // FIXME: This is technically incorrect because it might overwrite a poison
237 // value. Change to PoisonValue once #52930 is resolved.
238 if (isa<UndefValue>(MI->getValue())) {
239 // Set the size of the copy to 0, it will be deleted on the next iteration.
240 MI->setLength(Constant::getNullValue(MI->getLength()->getType()));
241 return MI;
242 }
243
244 // Extract the length and alignment and fill if they are constant.
245 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
246 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
247 if (!LenC || !FillC || !FillC->getType()->isIntegerTy(8))
248 return nullptr;
249 const uint64_t Len = LenC->getLimitedValue();
250 assert(Len && "0-sized memory setting should be removed already.");
251 const Align Alignment = MI->getDestAlign().valueOrOne();
252
253 // If it is an atomic and alignment is less than the size then we will
254 // introduce the unaligned memory access which will be later transformed
255 // into libcall in CodeGen. This is not evident performance gain so disable
256 // it now.
257 if (isa<AtomicMemSetInst>(MI))
258 if (Alignment < Len)
259 return nullptr;
260
261 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
262 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
263 Value *Dest = MI->getDest();
264
265 // Extract the fill value and store.
266 Constant *FillVal = ConstantInt::get(
267 MI->getContext(), APInt::getSplat(Len * 8, FillC->getValue()));
268 StoreInst *S = Builder.CreateStore(FillVal, Dest, MI->isVolatile());
269 S->copyMetadata(*MI, LLVMContext::MD_DIAssignID);
270 auto replaceOpForAssignmentMarkers = [FillC, FillVal](auto *DbgAssign) {
271 if (llvm::is_contained(DbgAssign->location_ops(), FillC))
272 DbgAssign->replaceVariableLocationOp(FillC, FillVal);
273 };
274 for_each(at::getAssignmentMarkers(S), replaceOpForAssignmentMarkers);
275 for_each(at::getDVRAssignmentMarkers(S), replaceOpForAssignmentMarkers);
276
277 S->setAlignment(Alignment);
278 if (isa<AtomicMemSetInst>(MI))
280
281 // Set the size of the copy to 0, it will be deleted on the next iteration.
282 MI->setLength(Constant::getNullValue(LenC->getType()));
283 return MI;
284 }
285
286 return nullptr;
287}
288
289// TODO, Obvious Missing Transforms:
290// * Narrow width by halfs excluding zero/undef lanes
291Value *InstCombinerImpl::simplifyMaskedLoad(IntrinsicInst &II) {
292 Value *LoadPtr = II.getArgOperand(0);
293 const Align Alignment =
294 cast<ConstantInt>(II.getArgOperand(1))->getAlignValue();
295
296 // If the mask is all ones or undefs, this is a plain vector load of the 1st
297 // argument.
298 if (maskIsAllOneOrUndef(II.getArgOperand(2))) {
299 LoadInst *L = Builder.CreateAlignedLoad(II.getType(), LoadPtr, Alignment,
300 "unmaskedload");
301 L->copyMetadata(II);
302 return L;
303 }
304
305 // If we can unconditionally load from this address, replace with a
306 // load/select idiom. TODO: use DT for context sensitive query
307 if (isDereferenceablePointer(LoadPtr, II.getType(),
308 II.getDataLayout(), &II, &AC)) {
309 LoadInst *LI = Builder.CreateAlignedLoad(II.getType(), LoadPtr, Alignment,
310 "unmaskedload");
311 LI->copyMetadata(II);
312 return Builder.CreateSelect(II.getArgOperand(2), LI, II.getArgOperand(3));
313 }
314
315 return nullptr;
316}
317
318// TODO, Obvious Missing Transforms:
319// * Single constant active lane -> store
320// * Narrow width by halfs excluding zero/undef lanes
321Instruction *InstCombinerImpl::simplifyMaskedStore(IntrinsicInst &II) {
322 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3));
323 if (!ConstMask)
324 return nullptr;
325
326 // If the mask is all zeros, this instruction does nothing.
327 if (ConstMask->isNullValue())
329
330 // If the mask is all ones, this is a plain vector store of the 1st argument.
331 if (ConstMask->isAllOnesValue()) {
332 Value *StorePtr = II.getArgOperand(1);
333 Align Alignment = cast<ConstantInt>(II.getArgOperand(2))->getAlignValue();
334 StoreInst *S =
335 new StoreInst(II.getArgOperand(0), StorePtr, false, Alignment);
336 S->copyMetadata(II);
337 return S;
338 }
339
340 if (isa<ScalableVectorType>(ConstMask->getType()))
341 return nullptr;
342
343 // Use masked off lanes to simplify operands via SimplifyDemandedVectorElts
344 APInt DemandedElts = possiblyDemandedEltsInMask(ConstMask);
345 APInt PoisonElts(DemandedElts.getBitWidth(), 0);
346 if (Value *V = SimplifyDemandedVectorElts(II.getOperand(0), DemandedElts,
347 PoisonElts))
348 return replaceOperand(II, 0, V);
349
350 return nullptr;
351}
352
353// TODO, Obvious Missing Transforms:
354// * Single constant active lane load -> load
355// * Dereferenceable address & few lanes -> scalarize speculative load/selects
356// * Adjacent vector addresses -> masked.load
357// * Narrow width by halfs excluding zero/undef lanes
358// * Vector incrementing address -> vector masked load
359Instruction *InstCombinerImpl::simplifyMaskedGather(IntrinsicInst &II) {
360 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(2));
361 if (!ConstMask)
362 return nullptr;
363
364 // Vector splat address w/known mask -> scalar load
365 // Fold the gather to load the source vector first lane
366 // because it is reloading the same value each time
367 if (ConstMask->isAllOnesValue())
368 if (auto *SplatPtr = getSplatValue(II.getArgOperand(0))) {
369 auto *VecTy = cast<VectorType>(II.getType());
370 const Align Alignment =
371 cast<ConstantInt>(II.getArgOperand(1))->getAlignValue();
372 LoadInst *L = Builder.CreateAlignedLoad(VecTy->getElementType(), SplatPtr,
373 Alignment, "load.scalar");
374 Value *Shuf =
375 Builder.CreateVectorSplat(VecTy->getElementCount(), L, "broadcast");
376 return replaceInstUsesWith(II, cast<Instruction>(Shuf));
377 }
378
379 return nullptr;
380}
381
382// TODO, Obvious Missing Transforms:
383// * Single constant active lane -> store
384// * Adjacent vector addresses -> masked.store
385// * Narrow store width by halfs excluding zero/undef lanes
386// * Vector incrementing address -> vector masked store
387Instruction *InstCombinerImpl::simplifyMaskedScatter(IntrinsicInst &II) {
388 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3));
389 if (!ConstMask)
390 return nullptr;
391
392 // If the mask is all zeros, a scatter does nothing.
393 if (ConstMask->isNullValue())
395
396 // Vector splat address -> scalar store
397 if (auto *SplatPtr = getSplatValue(II.getArgOperand(1))) {
398 // scatter(splat(value), splat(ptr), non-zero-mask) -> store value, ptr
399 if (auto *SplatValue = getSplatValue(II.getArgOperand(0))) {
400 if (maskContainsAllOneOrUndef(ConstMask)) {
401 Align Alignment =
402 cast<ConstantInt>(II.getArgOperand(2))->getAlignValue();
403 StoreInst *S = new StoreInst(SplatValue, SplatPtr, /*IsVolatile=*/false,
404 Alignment);
405 S->copyMetadata(II);
406 return S;
407 }
408 }
409 // scatter(vector, splat(ptr), splat(true)) -> store extract(vector,
410 // lastlane), ptr
411 if (ConstMask->isAllOnesValue()) {
412 Align Alignment = cast<ConstantInt>(II.getArgOperand(2))->getAlignValue();
413 VectorType *WideLoadTy = cast<VectorType>(II.getArgOperand(1)->getType());
414 ElementCount VF = WideLoadTy->getElementCount();
416 Value *LastLane = Builder.CreateSub(RunTimeVF, Builder.getInt32(1));
417 Value *Extract =
418 Builder.CreateExtractElement(II.getArgOperand(0), LastLane);
419 StoreInst *S =
420 new StoreInst(Extract, SplatPtr, /*IsVolatile=*/false, Alignment);
421 S->copyMetadata(II);
422 return S;
423 }
424 }
425 if (isa<ScalableVectorType>(ConstMask->getType()))
426 return nullptr;
427
428 // Use masked off lanes to simplify operands via SimplifyDemandedVectorElts
429 APInt DemandedElts = possiblyDemandedEltsInMask(ConstMask);
430 APInt PoisonElts(DemandedElts.getBitWidth(), 0);
431 if (Value *V = SimplifyDemandedVectorElts(II.getOperand(0), DemandedElts,
432 PoisonElts))
433 return replaceOperand(II, 0, V);
434 if (Value *V = SimplifyDemandedVectorElts(II.getOperand(1), DemandedElts,
435 PoisonElts))
436 return replaceOperand(II, 1, V);
437
438 return nullptr;
439}
440
441/// This function transforms launder.invariant.group and strip.invariant.group
442/// like:
443/// launder(launder(%x)) -> launder(%x) (the result is not the argument)
444/// launder(strip(%x)) -> launder(%x)
445/// strip(strip(%x)) -> strip(%x) (the result is not the argument)
446/// strip(launder(%x)) -> strip(%x)
447/// This is legal because it preserves the most recent information about
448/// the presence or absence of invariant.group.
450 InstCombinerImpl &IC) {
451 auto *Arg = II.getArgOperand(0);
452 auto *StrippedArg = Arg->stripPointerCasts();
453 auto *StrippedInvariantGroupsArg = StrippedArg;
454 while (auto *Intr = dyn_cast<IntrinsicInst>(StrippedInvariantGroupsArg)) {
455 if (Intr->getIntrinsicID() != Intrinsic::launder_invariant_group &&
456 Intr->getIntrinsicID() != Intrinsic::strip_invariant_group)
457 break;
458 StrippedInvariantGroupsArg = Intr->getArgOperand(0)->stripPointerCasts();
459 }
460 if (StrippedArg == StrippedInvariantGroupsArg)
461 return nullptr; // No launders/strips to remove.
462
463 Value *Result = nullptr;
464
465 if (II.getIntrinsicID() == Intrinsic::launder_invariant_group)
466 Result = IC.Builder.CreateLaunderInvariantGroup(StrippedInvariantGroupsArg);
467 else if (II.getIntrinsicID() == Intrinsic::strip_invariant_group)
468 Result = IC.Builder.CreateStripInvariantGroup(StrippedInvariantGroupsArg);
469 else
471 "simplifyInvariantGroupIntrinsic only handles launder and strip");
472 if (Result->getType()->getPointerAddressSpace() !=
473 II.getType()->getPointerAddressSpace())
474 Result = IC.Builder.CreateAddrSpaceCast(Result, II.getType());
475
476 return cast<Instruction>(Result);
477}
478
480 assert((II.getIntrinsicID() == Intrinsic::cttz ||
481 II.getIntrinsicID() == Intrinsic::ctlz) &&
482 "Expected cttz or ctlz intrinsic");
483 bool IsTZ = II.getIntrinsicID() == Intrinsic::cttz;
484 Value *Op0 = II.getArgOperand(0);
485 Value *Op1 = II.getArgOperand(1);
486 Value *X;
487 // ctlz(bitreverse(x)) -> cttz(x)
488 // cttz(bitreverse(x)) -> ctlz(x)
489 if (match(Op0, m_BitReverse(m_Value(X)))) {
490 Intrinsic::ID ID = IsTZ ? Intrinsic::ctlz : Intrinsic::cttz;
491 Function *F =
492 Intrinsic::getOrInsertDeclaration(II.getModule(), ID, II.getType());
493 return CallInst::Create(F, {X, II.getArgOperand(1)});
494 }
495
496 if (II.getType()->isIntOrIntVectorTy(1)) {
497 // ctlz/cttz i1 Op0 --> not Op0
498 if (match(Op1, m_Zero()))
499 return BinaryOperator::CreateNot(Op0);
500 // If zero is poison, then the input can be assumed to be "true", so the
501 // instruction simplifies to "false".
502 assert(match(Op1, m_One()) && "Expected ctlz/cttz operand to be 0 or 1");
503 return IC.replaceInstUsesWith(II, ConstantInt::getNullValue(II.getType()));
504 }
505
506 // If ctlz/cttz is only used as a shift amount, set is_zero_poison to true.
507 if (II.hasOneUse() && match(Op1, m_Zero()) &&
508 match(II.user_back(), m_Shift(m_Value(), m_Specific(&II)))) {
509 II.dropUBImplyingAttrsAndMetadata();
510 return IC.replaceOperand(II, 1, IC.Builder.getTrue());
511 }
512
513 Constant *C;
514
515 if (IsTZ) {
516 // cttz(-x) -> cttz(x)
517 if (match(Op0, m_Neg(m_Value(X))))
518 return IC.replaceOperand(II, 0, X);
519
520 // cttz(-x & x) -> cttz(x)
521 if (match(Op0, m_c_And(m_Neg(m_Value(X)), m_Deferred(X))))
522 return IC.replaceOperand(II, 0, X);
523
524 // cttz(sext(x)) -> cttz(zext(x))
525 if (match(Op0, m_OneUse(m_SExt(m_Value(X))))) {
526 auto *Zext = IC.Builder.CreateZExt(X, II.getType());
527 auto *CttzZext =
528 IC.Builder.CreateBinaryIntrinsic(Intrinsic::cttz, Zext, Op1);
529 return IC.replaceInstUsesWith(II, CttzZext);
530 }
531
532 // Zext doesn't change the number of trailing zeros, so narrow:
533 // cttz(zext(x)) -> zext(cttz(x)) if the 'ZeroIsPoison' parameter is 'true'.
534 if (match(Op0, m_OneUse(m_ZExt(m_Value(X)))) && match(Op1, m_One())) {
535 auto *Cttz = IC.Builder.CreateBinaryIntrinsic(Intrinsic::cttz, X,
536 IC.Builder.getTrue());
537 auto *ZextCttz = IC.Builder.CreateZExt(Cttz, II.getType());
538 return IC.replaceInstUsesWith(II, ZextCttz);
539 }
540
541 // cttz(abs(x)) -> cttz(x)
542 // cttz(nabs(x)) -> cttz(x)
543 Value *Y;
545 if (SPF == SPF_ABS || SPF == SPF_NABS)
546 return IC.replaceOperand(II, 0, X);
547
548 if (match(Op0, m_Intrinsic<Intrinsic::abs>(m_Value(X))))
549 return IC.replaceOperand(II, 0, X);
550
551 // cttz(shl(%const, %val), 1) --> add(cttz(%const, 1), %val)
552 if (match(Op0, m_Shl(m_ImmConstant(C), m_Value(X))) &&
553 match(Op1, m_One())) {
554 Value *ConstCttz =
555 IC.Builder.CreateBinaryIntrinsic(Intrinsic::cttz, C, Op1);
556 return BinaryOperator::CreateAdd(ConstCttz, X);
557 }
558
559 // cttz(lshr exact (%const, %val), 1) --> sub(cttz(%const, 1), %val)
560 if (match(Op0, m_Exact(m_LShr(m_ImmConstant(C), m_Value(X)))) &&
561 match(Op1, m_One())) {
562 Value *ConstCttz =
563 IC.Builder.CreateBinaryIntrinsic(Intrinsic::cttz, C, Op1);
564 return BinaryOperator::CreateSub(ConstCttz, X);
565 }
566
567 // cttz(add(lshr(UINT_MAX, %val), 1)) --> sub(width, %val)
568 if (match(Op0, m_Add(m_LShr(m_AllOnes(), m_Value(X)), m_One()))) {
569 Value *Width =
570 ConstantInt::get(II.getType(), II.getType()->getScalarSizeInBits());
571 return BinaryOperator::CreateSub(Width, X);
572 }
573 } else {
574 // ctlz(lshr(%const, %val), 1) --> add(ctlz(%const, 1), %val)
575 if (match(Op0, m_LShr(m_ImmConstant(C), m_Value(X))) &&
576 match(Op1, m_One())) {
577 Value *ConstCtlz =
578 IC.Builder.CreateBinaryIntrinsic(Intrinsic::ctlz, C, Op1);
579 return BinaryOperator::CreateAdd(ConstCtlz, X);
580 }
581
582 // ctlz(shl nuw (%const, %val), 1) --> sub(ctlz(%const, 1), %val)
583 if (match(Op0, m_NUWShl(m_ImmConstant(C), m_Value(X))) &&
584 match(Op1, m_One())) {
585 Value *ConstCtlz =
586 IC.Builder.CreateBinaryIntrinsic(Intrinsic::ctlz, C, Op1);
587 return BinaryOperator::CreateSub(ConstCtlz, X);
588 }
589 }
590
591 // cttz(Pow2) -> Log2(Pow2)
592 // ctlz(Pow2) -> BitWidth - 1 - Log2(Pow2)
593 if (auto *R = IC.tryGetLog2(Op0, match(Op1, m_One()))) {
594 if (IsTZ)
595 return IC.replaceInstUsesWith(II, R);
596 BinaryOperator *BO = BinaryOperator::CreateSub(
597 ConstantInt::get(R->getType(), R->getType()->getScalarSizeInBits() - 1),
598 R);
599 BO->setHasNoSignedWrap();
601 return BO;
602 }
603
604 KnownBits Known = IC.computeKnownBits(Op0, 0, &II);
605
606 // Create a mask for bits above (ctlz) or below (cttz) the first known one.
607 unsigned PossibleZeros = IsTZ ? Known.countMaxTrailingZeros()
608 : Known.countMaxLeadingZeros();
609 unsigned DefiniteZeros = IsTZ ? Known.countMinTrailingZeros()
610 : Known.countMinLeadingZeros();
611
612 // If all bits above (ctlz) or below (cttz) the first known one are known
613 // zero, this value is constant.
614 // FIXME: This should be in InstSimplify because we're replacing an
615 // instruction with a constant.
616 if (PossibleZeros == DefiniteZeros) {
617 auto *C = ConstantInt::get(Op0->getType(), DefiniteZeros);
618 return IC.replaceInstUsesWith(II, C);
619 }
620
621 // If the input to cttz/ctlz is known to be non-zero,
622 // then change the 'ZeroIsPoison' parameter to 'true'
623 // because we know the zero behavior can't affect the result.
624 if (!Known.One.isZero() ||
626 if (!match(II.getArgOperand(1), m_One()))
627 return IC.replaceOperand(II, 1, IC.Builder.getTrue());
628 }
629
630 // Add range attribute since known bits can't completely reflect what we know.
631 unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
632 if (BitWidth != 1 && !II.hasRetAttr(Attribute::Range) &&
633 !II.getMetadata(LLVMContext::MD_range)) {
634 ConstantRange Range(APInt(BitWidth, DefiniteZeros),
635 APInt(BitWidth, PossibleZeros + 1));
636 II.addRangeRetAttr(Range);
637 return &II;
638 }
639
640 return nullptr;
641}
642
644 assert(II.getIntrinsicID() == Intrinsic::ctpop &&
645 "Expected ctpop intrinsic");
646 Type *Ty = II.getType();
647 unsigned BitWidth = Ty->getScalarSizeInBits();
648 Value *Op0 = II.getArgOperand(0);
649 Value *X, *Y;
650
651 // ctpop(bitreverse(x)) -> ctpop(x)
652 // ctpop(bswap(x)) -> ctpop(x)
653 if (match(Op0, m_BitReverse(m_Value(X))) || match(Op0, m_BSwap(m_Value(X))))
654 return IC.replaceOperand(II, 0, X);
655
656 // ctpop(rot(x)) -> ctpop(x)
657 if ((match(Op0, m_FShl(m_Value(X), m_Value(Y), m_Value())) ||
658 match(Op0, m_FShr(m_Value(X), m_Value(Y), m_Value()))) &&
659 X == Y)
660 return IC.replaceOperand(II, 0, X);
661
662 // ctpop(x | -x) -> bitwidth - cttz(x, false)
663 if (Op0->hasOneUse() &&
664 match(Op0, m_c_Or(m_Value(X), m_Neg(m_Deferred(X))))) {
665 auto *Cttz = IC.Builder.CreateIntrinsic(Intrinsic::cttz, Ty,
666 {X, IC.Builder.getFalse()});
667 auto *Bw = ConstantInt::get(Ty, APInt(BitWidth, BitWidth));
668 return IC.replaceInstUsesWith(II, IC.Builder.CreateSub(Bw, Cttz));
669 }
670
671 // ctpop(~x & (x - 1)) -> cttz(x, false)
672 if (match(Op0,
674 Function *F =
675 Intrinsic::getOrInsertDeclaration(II.getModule(), Intrinsic::cttz, Ty);
676 return CallInst::Create(F, {X, IC.Builder.getFalse()});
677 }
678
679 // Zext doesn't change the number of set bits, so narrow:
680 // ctpop (zext X) --> zext (ctpop X)
681 if (match(Op0, m_OneUse(m_ZExt(m_Value(X))))) {
682 Value *NarrowPop = IC.Builder.CreateUnaryIntrinsic(Intrinsic::ctpop, X);
683 return CastInst::Create(Instruction::ZExt, NarrowPop, Ty);
684 }
685
686 KnownBits Known(BitWidth);
687 IC.computeKnownBits(Op0, Known, 0, &II);
688
689 // If all bits are zero except for exactly one fixed bit, then the result
690 // must be 0 or 1, and we can get that answer by shifting to LSB:
691 // ctpop (X & 32) --> (X & 32) >> 5
692 // TODO: Investigate removing this as its likely unnecessary given the below
693 // `isKnownToBeAPowerOfTwo` check.
694 if ((~Known.Zero).isPowerOf2())
695 return BinaryOperator::CreateLShr(
696 Op0, ConstantInt::get(Ty, (~Known.Zero).exactLogBase2()));
697
698 // More generally we can also handle non-constant power of 2 patterns such as
699 // shl/shr(Pow2, X), (X & -X), etc... by transforming:
700 // ctpop(Pow2OrZero) --> icmp ne X, 0
701 if (IC.isKnownToBeAPowerOfTwo(Op0, /* OrZero */ true))
702 return CastInst::Create(Instruction::ZExt,
705 Ty);
706
707 // Add range attribute since known bits can't completely reflect what we know.
708 if (BitWidth != 1) {
709 ConstantRange OldRange =
710 II.getRange().value_or(ConstantRange::getFull(BitWidth));
711
712 unsigned Lower = Known.countMinPopulation();
713 unsigned Upper = Known.countMaxPopulation() + 1;
714
715 if (Lower == 0 && OldRange.contains(APInt::getZero(BitWidth)) &&
717 Lower = 1;
718
721
722 if (Range != OldRange) {
723 II.addRangeRetAttr(Range);
724 return &II;
725 }
726 }
727
728 return nullptr;
729}
730
731/// Convert a table lookup to shufflevector if the mask is constant.
732/// This could benefit tbl1 if the mask is { 7,6,5,4,3,2,1,0 }, in
733/// which case we could lower the shufflevector with rev64 instructions
734/// as it's actually a byte reverse.
736 InstCombiner::BuilderTy &Builder) {
737 // Bail out if the mask is not a constant.
738 auto *C = dyn_cast<Constant>(II.getArgOperand(1));
739 if (!C)
740 return nullptr;
741
742 auto *VecTy = cast<FixedVectorType>(II.getType());
743 unsigned NumElts = VecTy->getNumElements();
744
745 // Only perform this transformation for <8 x i8> vector types.
746 if (!VecTy->getElementType()->isIntegerTy(8) || NumElts != 8)
747 return nullptr;
748
749 int Indexes[8];
750
751 for (unsigned I = 0; I < NumElts; ++I) {
752 Constant *COp = C->getAggregateElement(I);
753
754 if (!COp || !isa<ConstantInt>(COp))
755 return nullptr;
756
757 Indexes[I] = cast<ConstantInt>(COp)->getLimitedValue();
758
759 // Make sure the mask indices are in range.
760 if ((unsigned)Indexes[I] >= NumElts)
761 return nullptr;
762 }
763
764 auto *V1 = II.getArgOperand(0);
765 auto *V2 = Constant::getNullValue(V1->getType());
766 return Builder.CreateShuffleVector(V1, V2, ArrayRef(Indexes));
767}
768
769// Returns true iff the 2 intrinsics have the same operands, limiting the
770// comparison to the first NumOperands.
771static bool haveSameOperands(const IntrinsicInst &I, const IntrinsicInst &E,
772 unsigned NumOperands) {
773 assert(I.arg_size() >= NumOperands && "Not enough operands");
774 assert(E.arg_size() >= NumOperands && "Not enough operands");
775 for (unsigned i = 0; i < NumOperands; i++)
776 if (I.getArgOperand(i) != E.getArgOperand(i))
777 return false;
778 return true;
779}
780
781// Remove trivially empty start/end intrinsic ranges, i.e. a start
782// immediately followed by an end (ignoring debuginfo or other
783// start/end intrinsics in between). As this handles only the most trivial
784// cases, tracking the nesting level is not needed:
785//
786// call @llvm.foo.start(i1 0)
787// call @llvm.foo.start(i1 0) ; This one won't be skipped: it will be removed
788// call @llvm.foo.end(i1 0)
789// call @llvm.foo.end(i1 0) ; &I
790static bool
792 std::function<bool(const IntrinsicInst &)> IsStart) {
793 // We start from the end intrinsic and scan backwards, so that InstCombine
794 // has already processed (and potentially removed) all the instructions
795 // before the end intrinsic.
796 BasicBlock::reverse_iterator BI(EndI), BE(EndI.getParent()->rend());
797 for (; BI != BE; ++BI) {
798 if (auto *I = dyn_cast<IntrinsicInst>(&*BI)) {
799 if (I->isDebugOrPseudoInst() ||
800 I->getIntrinsicID() == EndI.getIntrinsicID())
801 continue;
802 if (IsStart(*I)) {
803 if (haveSameOperands(EndI, *I, EndI.arg_size())) {
805 IC.eraseInstFromFunction(EndI);
806 return true;
807 }
808 // Skip start intrinsics that don't pair with this end intrinsic.
809 continue;
810 }
811 }
812 break;
813 }
814
815 return false;
816}
817
819 removeTriviallyEmptyRange(I, *this, [](const IntrinsicInst &I) {
820 return I.getIntrinsicID() == Intrinsic::vastart ||
821 I.getIntrinsicID() == Intrinsic::vacopy;
822 });
823 return nullptr;
824}
825
827 assert(Call.arg_size() > 1 && "Need at least 2 args to swap");
828 Value *Arg0 = Call.getArgOperand(0), *Arg1 = Call.getArgOperand(1);
829 if (isa<Constant>(Arg0) && !isa<Constant>(Arg1)) {
830 Call.setArgOperand(0, Arg1);
831 Call.setArgOperand(1, Arg0);
832 return &Call;
833 }
834 return nullptr;
835}
836
837/// Creates a result tuple for an overflow intrinsic \p II with a given
838/// \p Result and a constant \p Overflow value.
840 Constant *Overflow) {
841 Constant *V[] = {PoisonValue::get(Result->getType()), Overflow};
842 StructType *ST = cast<StructType>(II->getType());
844 return InsertValueInst::Create(Struct, Result, 0);
845}
846
848InstCombinerImpl::foldIntrinsicWithOverflowCommon(IntrinsicInst *II) {
849 WithOverflowInst *WO = cast<WithOverflowInst>(II);
850 Value *OperationResult = nullptr;
851 Constant *OverflowResult = nullptr;
852 if (OptimizeOverflowCheck(WO->getBinaryOp(), WO->isSigned(), WO->getLHS(),
853 WO->getRHS(), *WO, OperationResult, OverflowResult))
854 return createOverflowTuple(WO, OperationResult, OverflowResult);
855
856 // See whether we can optimize the overflow check with assumption information.
857 for (User *U : WO->users()) {
858 if (!match(U, m_ExtractValue<1>(m_Value())))
859 continue;
860
861 for (auto &AssumeVH : AC.assumptionsFor(U)) {
862 if (!AssumeVH)
863 continue;
864 CallInst *I = cast<CallInst>(AssumeVH);
865 if (!match(I->getArgOperand(0), m_Not(m_Specific(U))))
866 continue;
867 if (!isValidAssumeForContext(I, II, /*DT=*/nullptr,
868 /*AllowEphemerals=*/true))
869 continue;
870 Value *Result =
871 Builder.CreateBinOp(WO->getBinaryOp(), WO->getLHS(), WO->getRHS());
872 Result->takeName(WO);
873 if (auto *Inst = dyn_cast<Instruction>(Result)) {
874 if (WO->isSigned())
875 Inst->setHasNoSignedWrap();
876 else
877 Inst->setHasNoUnsignedWrap();
878 }
879 return createOverflowTuple(WO, Result,
880 ConstantInt::getFalse(U->getType()));
881 }
882 }
883
884 return nullptr;
885}
886
887static bool inputDenormalIsIEEE(const Function &F, const Type *Ty) {
888 Ty = Ty->getScalarType();
889 return F.getDenormalMode(Ty->getFltSemantics()).Input == DenormalMode::IEEE;
890}
891
892static bool inputDenormalIsDAZ(const Function &F, const Type *Ty) {
893 Ty = Ty->getScalarType();
894 return F.getDenormalMode(Ty->getFltSemantics()).inputsAreZero();
895}
896
897/// \returns the compare predicate type if the test performed by
898/// llvm.is.fpclass(x, \p Mask) is equivalent to fcmp o__ x, 0.0 with the
899/// floating-point environment assumed for \p F for type \p Ty
901 const Function &F, Type *Ty) {
902 switch (static_cast<unsigned>(Mask)) {
903 case fcZero:
904 if (inputDenormalIsIEEE(F, Ty))
905 return FCmpInst::FCMP_OEQ;
906 break;
907 case fcZero | fcSubnormal:
908 if (inputDenormalIsDAZ(F, Ty))
909 return FCmpInst::FCMP_OEQ;
910 break;
911 case fcPositive | fcNegZero:
912 if (inputDenormalIsIEEE(F, Ty))
913 return FCmpInst::FCMP_OGE;
914 break;
916 if (inputDenormalIsDAZ(F, Ty))
917 return FCmpInst::FCMP_OGE;
918 break;
920 if (inputDenormalIsIEEE(F, Ty))
921 return FCmpInst::FCMP_OGT;
922 break;
923 case fcNegative | fcPosZero:
924 if (inputDenormalIsIEEE(F, Ty))
925 return FCmpInst::FCMP_OLE;
926 break;
928 if (inputDenormalIsDAZ(F, Ty))
929 return FCmpInst::FCMP_OLE;
930 break;
932 if (inputDenormalIsIEEE(F, Ty))
933 return FCmpInst::FCMP_OLT;
934 break;
935 case fcPosNormal | fcPosInf:
936 if (inputDenormalIsDAZ(F, Ty))
937 return FCmpInst::FCMP_OGT;
938 break;
939 case fcNegNormal | fcNegInf:
940 if (inputDenormalIsDAZ(F, Ty))
941 return FCmpInst::FCMP_OLT;
942 break;
943 case ~fcZero & ~fcNan:
944 if (inputDenormalIsIEEE(F, Ty))
945 return FCmpInst::FCMP_ONE;
946 break;
947 case ~(fcZero | fcSubnormal) & ~fcNan:
948 if (inputDenormalIsDAZ(F, Ty))
949 return FCmpInst::FCMP_ONE;
950 break;
951 default:
952 break;
953 }
954
956}
957
958Instruction *InstCombinerImpl::foldIntrinsicIsFPClass(IntrinsicInst &II) {
959 Value *Src0 = II.getArgOperand(0);
960 Value *Src1 = II.getArgOperand(1);
961 const ConstantInt *CMask = cast<ConstantInt>(Src1);
962 FPClassTest Mask = static_cast<FPClassTest>(CMask->getZExtValue());
963 const bool IsUnordered = (Mask & fcNan) == fcNan;
964 const bool IsOrdered = (Mask & fcNan) == fcNone;
965 const FPClassTest OrderedMask = Mask & ~fcNan;
966 const FPClassTest OrderedInvertedMask = ~OrderedMask & ~fcNan;
967
968 const bool IsStrict =
969 II.getFunction()->getAttributes().hasFnAttr(Attribute::StrictFP);
970
971 Value *FNegSrc;
972 if (match(Src0, m_FNeg(m_Value(FNegSrc)))) {
973 // is.fpclass (fneg x), mask -> is.fpclass x, (fneg mask)
974
975 II.setArgOperand(1, ConstantInt::get(Src1->getType(), fneg(Mask)));
976 return replaceOperand(II, 0, FNegSrc);
977 }
978
979 Value *FAbsSrc;
980 if (match(Src0, m_FAbs(m_Value(FAbsSrc)))) {
981 II.setArgOperand(1, ConstantInt::get(Src1->getType(), inverse_fabs(Mask)));
982 return replaceOperand(II, 0, FAbsSrc);
983 }
984
985 if ((OrderedMask == fcInf || OrderedInvertedMask == fcInf) &&
986 (IsOrdered || IsUnordered) && !IsStrict) {
987 // is.fpclass(x, fcInf) -> fcmp oeq fabs(x), +inf
988 // is.fpclass(x, ~fcInf) -> fcmp one fabs(x), +inf
989 // is.fpclass(x, fcInf|fcNan) -> fcmp ueq fabs(x), +inf
990 // is.fpclass(x, ~(fcInf|fcNan)) -> fcmp une fabs(x), +inf
994 if (OrderedInvertedMask == fcInf)
995 Pred = IsUnordered ? FCmpInst::FCMP_UNE : FCmpInst::FCMP_ONE;
996
997 Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, Src0);
998 Value *CmpInf = Builder.CreateFCmp(Pred, Fabs, Inf);
999 CmpInf->takeName(&II);
1000 return replaceInstUsesWith(II, CmpInf);
1001 }
1002
1003 if ((OrderedMask == fcPosInf || OrderedMask == fcNegInf) &&
1004 (IsOrdered || IsUnordered) && !IsStrict) {
1005 // is.fpclass(x, fcPosInf) -> fcmp oeq x, +inf
1006 // is.fpclass(x, fcNegInf) -> fcmp oeq x, -inf
1007 // is.fpclass(x, fcPosInf|fcNan) -> fcmp ueq x, +inf
1008 // is.fpclass(x, fcNegInf|fcNan) -> fcmp ueq x, -inf
1009 Constant *Inf =
1010 ConstantFP::getInfinity(Src0->getType(), OrderedMask == fcNegInf);
1011 Value *EqInf = IsUnordered ? Builder.CreateFCmpUEQ(Src0, Inf)
1012 : Builder.CreateFCmpOEQ(Src0, Inf);
1013
1014 EqInf->takeName(&II);
1015 return replaceInstUsesWith(II, EqInf);
1016 }
1017
1018 if ((OrderedInvertedMask == fcPosInf || OrderedInvertedMask == fcNegInf) &&
1019 (IsOrdered || IsUnordered) && !IsStrict) {
1020 // is.fpclass(x, ~fcPosInf) -> fcmp one x, +inf
1021 // is.fpclass(x, ~fcNegInf) -> fcmp one x, -inf
1022 // is.fpclass(x, ~fcPosInf|fcNan) -> fcmp une x, +inf
1023 // is.fpclass(x, ~fcNegInf|fcNan) -> fcmp une x, -inf
1025 OrderedInvertedMask == fcNegInf);
1026 Value *NeInf = IsUnordered ? Builder.CreateFCmpUNE(Src0, Inf)
1027 : Builder.CreateFCmpONE(Src0, Inf);
1028 NeInf->takeName(&II);
1029 return replaceInstUsesWith(II, NeInf);
1030 }
1031
1032 if (Mask == fcNan && !IsStrict) {
1033 // Equivalent of isnan. Replace with standard fcmp if we don't care about FP
1034 // exceptions.
1035 Value *IsNan =
1037 IsNan->takeName(&II);
1038 return replaceInstUsesWith(II, IsNan);
1039 }
1040
1041 if (Mask == (~fcNan & fcAllFlags) && !IsStrict) {
1042 // Equivalent of !isnan. Replace with standard fcmp.
1043 Value *FCmp =
1045 FCmp->takeName(&II);
1046 return replaceInstUsesWith(II, FCmp);
1047 }
1048
1050
1051 // Try to replace with an fcmp with 0
1052 //
1053 // is.fpclass(x, fcZero) -> fcmp oeq x, 0.0
1054 // is.fpclass(x, fcZero | fcNan) -> fcmp ueq x, 0.0
1055 // is.fpclass(x, ~fcZero & ~fcNan) -> fcmp one x, 0.0
1056 // is.fpclass(x, ~fcZero) -> fcmp une x, 0.0
1057 //
1058 // is.fpclass(x, fcPosSubnormal | fcPosNormal | fcPosInf) -> fcmp ogt x, 0.0
1059 // is.fpclass(x, fcPositive | fcNegZero) -> fcmp oge x, 0.0
1060 //
1061 // is.fpclass(x, fcNegSubnormal | fcNegNormal | fcNegInf) -> fcmp olt x, 0.0
1062 // is.fpclass(x, fcNegative | fcPosZero) -> fcmp ole x, 0.0
1063 //
1064 if (!IsStrict && (IsOrdered || IsUnordered) &&
1065 (PredType = fpclassTestIsFCmp0(OrderedMask, *II.getFunction(),
1066 Src0->getType())) !=
1069 // Equivalent of == 0.
1070 Value *FCmp = Builder.CreateFCmp(
1071 IsUnordered ? FCmpInst::getUnorderedPredicate(PredType) : PredType,
1072 Src0, Zero);
1073
1074 FCmp->takeName(&II);
1075 return replaceInstUsesWith(II, FCmp);
1076 }
1077
1078 KnownFPClass Known = computeKnownFPClass(Src0, Mask, &II);
1079
1080 // Clear test bits we know must be false from the source value.
1081 // fp_class (nnan x), qnan|snan|other -> fp_class (nnan x), other
1082 // fp_class (ninf x), ninf|pinf|other -> fp_class (ninf x), other
1083 if ((Mask & Known.KnownFPClasses) != Mask) {
1084 II.setArgOperand(
1085 1, ConstantInt::get(Src1->getType(), Mask & Known.KnownFPClasses));
1086 return &II;
1087 }
1088
1089 // If none of the tests which can return false are possible, fold to true.
1090 // fp_class (nnan x), ~(qnan|snan) -> true
1091 // fp_class (ninf x), ~(ninf|pinf) -> true
1092 if (Mask == Known.KnownFPClasses)
1093 return replaceInstUsesWith(II, ConstantInt::get(II.getType(), true));
1094
1095 return nullptr;
1096}
1097
1098static std::optional<bool> getKnownSign(Value *Op, const SimplifyQuery &SQ) {
1099 KnownBits Known = computeKnownBits(Op, /*Depth=*/0, SQ);
1100 if (Known.isNonNegative())
1101 return false;
1102 if (Known.isNegative())
1103 return true;
1104
1105 Value *X, *Y;
1106 if (match(Op, m_NSWSub(m_Value(X), m_Value(Y))))
1108
1109 return std::nullopt;
1110}
1111
1112static std::optional<bool> getKnownSignOrZero(Value *Op,
1113 const SimplifyQuery &SQ) {
1114 if (std::optional<bool> Sign = getKnownSign(Op, SQ))
1115 return Sign;
1116
1117 Value *X, *Y;
1118 if (match(Op, m_NSWSub(m_Value(X), m_Value(Y))))
1120
1121 return std::nullopt;
1122}
1123
1124/// Return true if two values \p Op0 and \p Op1 are known to have the same sign.
1125static bool signBitMustBeTheSame(Value *Op0, Value *Op1,
1126 const SimplifyQuery &SQ) {
1127 std::optional<bool> Known1 = getKnownSign(Op1, SQ);
1128 if (!Known1)
1129 return false;
1130 std::optional<bool> Known0 = getKnownSign(Op0, SQ);
1131 if (!Known0)
1132 return false;
1133 return *Known0 == *Known1;
1134}
1135
1136/// Try to canonicalize min/max(X + C0, C1) as min/max(X, C1 - C0) + C0. This
1137/// can trigger other combines.
1139 InstCombiner::BuilderTy &Builder) {
1140 Intrinsic::ID MinMaxID = II->getIntrinsicID();
1141 assert((MinMaxID == Intrinsic::smax || MinMaxID == Intrinsic::smin ||
1142 MinMaxID == Intrinsic::umax || MinMaxID == Intrinsic::umin) &&
1143 "Expected a min or max intrinsic");
1144
1145 // TODO: Match vectors with undef elements, but undef may not propagate.
1146 Value *Op0 = II->getArgOperand(0), *Op1 = II->getArgOperand(1);
1147 Value *X;
1148 const APInt *C0, *C1;
1149 if (!match(Op0, m_OneUse(m_Add(m_Value(X), m_APInt(C0)))) ||
1150 !match(Op1, m_APInt(C1)))
1151 return nullptr;
1152
1153 // Check for necessary no-wrap and overflow constraints.
1154 bool IsSigned = MinMaxID == Intrinsic::smax || MinMaxID == Intrinsic::smin;
1155 auto *Add = cast<BinaryOperator>(Op0);
1156 if ((IsSigned && !Add->hasNoSignedWrap()) ||
1157 (!IsSigned && !Add->hasNoUnsignedWrap()))
1158 return nullptr;
1159
1160 // If the constant difference overflows, then instsimplify should reduce the
1161 // min/max to the add or C1.
1162 bool Overflow;
1163 APInt CDiff =
1164 IsSigned ? C1->ssub_ov(*C0, Overflow) : C1->usub_ov(*C0, Overflow);
1165 assert(!Overflow && "Expected simplify of min/max");
1166
1167 // min/max (add X, C0), C1 --> add (min/max X, C1 - C0), C0
1168 // Note: the "mismatched" no-overflow setting does not propagate.
1169 Constant *NewMinMaxC = ConstantInt::get(II->getType(), CDiff);
1170 Value *NewMinMax = Builder.CreateBinaryIntrinsic(MinMaxID, X, NewMinMaxC);
1171 return IsSigned ? BinaryOperator::CreateNSWAdd(NewMinMax, Add->getOperand(1))
1172 : BinaryOperator::CreateNUWAdd(NewMinMax, Add->getOperand(1));
1173}
1174/// Match a sadd_sat or ssub_sat which is using min/max to clamp the value.
1175Instruction *InstCombinerImpl::matchSAddSubSat(IntrinsicInst &MinMax1) {
1176 Type *Ty = MinMax1.getType();
1177
1178 // We are looking for a tree of:
1179 // max(INT_MIN, min(INT_MAX, add(sext(A), sext(B))))
1180 // Where the min and max could be reversed
1181 Instruction *MinMax2;
1183 const APInt *MinValue, *MaxValue;
1184 if (match(&MinMax1, m_SMin(m_Instruction(MinMax2), m_APInt(MaxValue)))) {
1185 if (!match(MinMax2, m_SMax(m_BinOp(AddSub), m_APInt(MinValue))))
1186 return nullptr;
1187 } else if (match(&MinMax1,
1188 m_SMax(m_Instruction(MinMax2), m_APInt(MinValue)))) {
1189 if (!match(MinMax2, m_SMin(m_BinOp(AddSub), m_APInt(MaxValue))))
1190 return nullptr;
1191 } else
1192 return nullptr;
1193
1194 // Check that the constants clamp a saturate, and that the new type would be
1195 // sensible to convert to.
1196 if (!(*MaxValue + 1).isPowerOf2() || -*MinValue != *MaxValue + 1)
1197 return nullptr;
1198 // In what bitwidth can this be treated as saturating arithmetics?
1199 unsigned NewBitWidth = (*MaxValue + 1).logBase2() + 1;
1200 // FIXME: This isn't quite right for vectors, but using the scalar type is a
1201 // good first approximation for what should be done there.
1202 if (!shouldChangeType(Ty->getScalarType()->getIntegerBitWidth(), NewBitWidth))
1203 return nullptr;
1204
1205 // Also make sure that the inner min/max and the add/sub have one use.
1206 if (!MinMax2->hasOneUse() || !AddSub->hasOneUse())
1207 return nullptr;
1208
1209 // Create the new type (which can be a vector type)
1210 Type *NewTy = Ty->getWithNewBitWidth(NewBitWidth);
1211
1212 Intrinsic::ID IntrinsicID;
1213 if (AddSub->getOpcode() == Instruction::Add)
1214 IntrinsicID = Intrinsic::sadd_sat;
1215 else if (AddSub->getOpcode() == Instruction::Sub)
1216 IntrinsicID = Intrinsic::ssub_sat;
1217 else
1218 return nullptr;
1219
1220 // The two operands of the add/sub must be nsw-truncatable to the NewTy. This
1221 // is usually achieved via a sext from a smaller type.
1222 if (ComputeMaxSignificantBits(AddSub->getOperand(0), 0, AddSub) >
1223 NewBitWidth ||
1224 ComputeMaxSignificantBits(AddSub->getOperand(1), 0, AddSub) > NewBitWidth)
1225 return nullptr;
1226
1227 // Finally create and return the sat intrinsic, truncated to the new type
1228 Value *AT = Builder.CreateTrunc(AddSub->getOperand(0), NewTy);
1229 Value *BT = Builder.CreateTrunc(AddSub->getOperand(1), NewTy);
1230 Value *Sat = Builder.CreateIntrinsic(IntrinsicID, NewTy, {AT, BT});
1231 return CastInst::Create(Instruction::SExt, Sat, Ty);
1232}
1233
1234
1235/// If we have a clamp pattern like max (min X, 42), 41 -- where the output
1236/// can only be one of two possible constant values -- turn that into a select
1237/// of constants.
1239 InstCombiner::BuilderTy &Builder) {
1240 Value *I0 = II->getArgOperand(0), *I1 = II->getArgOperand(1);
1241 Value *X;
1242 const APInt *C0, *C1;
1243 if (!match(I1, m_APInt(C1)) || !I0->hasOneUse())
1244 return nullptr;
1245
1247 switch (II->getIntrinsicID()) {
1248 case Intrinsic::smax:
1249 if (match(I0, m_SMin(m_Value(X), m_APInt(C0))) && *C0 == *C1 + 1)
1250 Pred = ICmpInst::ICMP_SGT;
1251 break;
1252 case Intrinsic::smin:
1253 if (match(I0, m_SMax(m_Value(X), m_APInt(C0))) && *C1 == *C0 + 1)
1254 Pred = ICmpInst::ICMP_SLT;
1255 break;
1256 case Intrinsic::umax:
1257 if (match(I0, m_UMin(m_Value(X), m_APInt(C0))) && *C0 == *C1 + 1)
1258 Pred = ICmpInst::ICMP_UGT;
1259 break;
1260 case Intrinsic::umin:
1261 if (match(I0, m_UMax(m_Value(X), m_APInt(C0))) && *C1 == *C0 + 1)
1262 Pred = ICmpInst::ICMP_ULT;
1263 break;
1264 default:
1265 llvm_unreachable("Expected min/max intrinsic");
1266 }
1267 if (Pred == CmpInst::BAD_ICMP_PREDICATE)
1268 return nullptr;
1269
1270 // max (min X, 42), 41 --> X > 41 ? 42 : 41
1271 // min (max X, 42), 43 --> X < 43 ? 42 : 43
1272 Value *Cmp = Builder.CreateICmp(Pred, X, I1);
1273 return SelectInst::Create(Cmp, ConstantInt::get(II->getType(), *C0), I1);
1274}
1275
1276/// If this min/max has a constant operand and an operand that is a matching
1277/// min/max with a constant operand, constant-fold the 2 constant operands.
1279 IRBuilderBase &Builder,
1280 const SimplifyQuery &SQ) {
1281 Intrinsic::ID MinMaxID = II->getIntrinsicID();
1282 auto *LHS = dyn_cast<MinMaxIntrinsic>(II->getArgOperand(0));
1283 if (!LHS)
1284 return nullptr;
1285
1286 Constant *C0, *C1;
1287 if (!match(LHS->getArgOperand(1), m_ImmConstant(C0)) ||
1288 !match(II->getArgOperand(1), m_ImmConstant(C1)))
1289 return nullptr;
1290
1291 // max (max X, C0), C1 --> max X, (max C0, C1)
1292 // min (min X, C0), C1 --> min X, (min C0, C1)
1293 // umax (smax X, nneg C0), nneg C1 --> smax X, (umax C0, C1)
1294 // smin (umin X, nneg C0), nneg C1 --> umin X, (smin C0, C1)
1295 Intrinsic::ID InnerMinMaxID = LHS->getIntrinsicID();
1296 if (InnerMinMaxID != MinMaxID &&
1297 !(((MinMaxID == Intrinsic::umax && InnerMinMaxID == Intrinsic::smax) ||
1298 (MinMaxID == Intrinsic::smin && InnerMinMaxID == Intrinsic::umin)) &&
1299 isKnownNonNegative(C0, SQ) && isKnownNonNegative(C1, SQ)))
1300 return nullptr;
1301
1303 Value *CondC = Builder.CreateICmp(Pred, C0, C1);
1304 Value *NewC = Builder.CreateSelect(CondC, C0, C1);
1305 return Builder.CreateIntrinsic(InnerMinMaxID, II->getType(),
1306 {LHS->getArgOperand(0), NewC});
1307}
1308
1309/// If this min/max has a matching min/max operand with a constant, try to push
1310/// the constant operand into this instruction. This can enable more folds.
1311static Instruction *
1313 InstCombiner::BuilderTy &Builder) {
1314 // Match and capture a min/max operand candidate.
1315 Value *X, *Y;
1316 Constant *C;
1317 Instruction *Inner;
1319 m_Instruction(Inner),
1321 m_Value(Y))))
1322 return nullptr;
1323
1324 // The inner op must match. Check for constants to avoid infinite loops.
1325 Intrinsic::ID MinMaxID = II->getIntrinsicID();
1326 auto *InnerMM = dyn_cast<IntrinsicInst>(Inner);
1327 if (!InnerMM || InnerMM->getIntrinsicID() != MinMaxID ||
1329 return nullptr;
1330
1331 // max (max X, C), Y --> max (max X, Y), C
1333 MinMaxID, II->getType());
1334 Value *NewInner = Builder.CreateBinaryIntrinsic(MinMaxID, X, Y);
1335 NewInner->takeName(Inner);
1336 return CallInst::Create(MinMax, {NewInner, C});
1337}
1338
1339/// Reduce a sequence of min/max intrinsics with a common operand.
1341 // Match 3 of the same min/max ops. Example: umin(umin(), umin()).
1342 auto *LHS = dyn_cast<IntrinsicInst>(II->getArgOperand(0));
1343 auto *RHS = dyn_cast<IntrinsicInst>(II->getArgOperand(1));
1344 Intrinsic::ID MinMaxID = II->getIntrinsicID();
1345 if (!LHS || !RHS || LHS->getIntrinsicID() != MinMaxID ||
1346 RHS->getIntrinsicID() != MinMaxID ||
1347 (!LHS->hasOneUse() && !RHS->hasOneUse()))
1348 return nullptr;
1349
1350 Value *A = LHS->getArgOperand(0);
1351 Value *B = LHS->getArgOperand(1);
1352 Value *C = RHS->getArgOperand(0);
1353 Value *D = RHS->getArgOperand(1);
1354
1355 // Look for a common operand.
1356 Value *MinMaxOp = nullptr;
1357 Value *ThirdOp = nullptr;
1358 if (LHS->hasOneUse()) {
1359 // If the LHS is only used in this chain and the RHS is used outside of it,
1360 // reuse the RHS min/max because that will eliminate the LHS.
1361 if (D == A || C == A) {
1362 // min(min(a, b), min(c, a)) --> min(min(c, a), b)
1363 // min(min(a, b), min(a, d)) --> min(min(a, d), b)
1364 MinMaxOp = RHS;
1365 ThirdOp = B;
1366 } else if (D == B || C == B) {
1367 // min(min(a, b), min(c, b)) --> min(min(c, b), a)
1368 // min(min(a, b), min(b, d)) --> min(min(b, d), a)
1369 MinMaxOp = RHS;
1370 ThirdOp = A;
1371 }
1372 } else {
1373 assert(RHS->hasOneUse() && "Expected one-use operand");
1374 // Reuse the LHS. This will eliminate the RHS.
1375 if (D == A || D == B) {
1376 // min(min(a, b), min(c, a)) --> min(min(a, b), c)
1377 // min(min(a, b), min(c, b)) --> min(min(a, b), c)
1378 MinMaxOp = LHS;
1379 ThirdOp = C;
1380 } else if (C == A || C == B) {
1381 // min(min(a, b), min(b, d)) --> min(min(a, b), d)
1382 // min(min(a, b), min(c, b)) --> min(min(a, b), d)
1383 MinMaxOp = LHS;
1384 ThirdOp = D;
1385 }
1386 }
1387
1388 if (!MinMaxOp || !ThirdOp)
1389 return nullptr;
1390
1391 Module *Mod = II->getModule();
1392 Function *MinMax =
1393 Intrinsic::getOrInsertDeclaration(Mod, MinMaxID, II->getType());
1394 return CallInst::Create(MinMax, { MinMaxOp, ThirdOp });
1395}
1396
1397/// If all arguments of the intrinsic are unary shuffles with the same mask,
1398/// try to shuffle after the intrinsic.
1399static Instruction *
1401 InstCombiner::BuilderTy &Builder) {
1402 // TODO: This should be extended to handle other intrinsics like fshl, ctpop,
1403 // etc. Use llvm::isTriviallyVectorizable() and related to determine
1404 // which intrinsics are safe to shuffle?
1405 switch (II->getIntrinsicID()) {
1406 case Intrinsic::smax:
1407 case Intrinsic::smin:
1408 case Intrinsic::umax:
1409 case Intrinsic::umin:
1410 case Intrinsic::fma:
1411 case Intrinsic::fshl:
1412 case Intrinsic::fshr:
1413 break;
1414 default:
1415 return nullptr;
1416 }
1417
1418 Value *X;
1419 ArrayRef<int> Mask;
1420 if (!match(II->getArgOperand(0),
1421 m_Shuffle(m_Value(X), m_Undef(), m_Mask(Mask))))
1422 return nullptr;
1423
1424 // At least 1 operand must have 1 use because we are creating 2 instructions.
1425 if (none_of(II->args(), [](Value *V) { return V->hasOneUse(); }))
1426 return nullptr;
1427
1428 // See if all arguments are shuffled with the same mask.
1429 SmallVector<Value *, 4> NewArgs(II->arg_size());
1430 NewArgs[0] = X;
1431 Type *SrcTy = X->getType();
1432 for (unsigned i = 1, e = II->arg_size(); i != e; ++i) {
1433 if (!match(II->getArgOperand(i),
1434 m_Shuffle(m_Value(X), m_Undef(), m_SpecificMask(Mask))) ||
1435 X->getType() != SrcTy)
1436 return nullptr;
1437 NewArgs[i] = X;
1438 }
1439
1440 // intrinsic (shuf X, M), (shuf Y, M), ... --> shuf (intrinsic X, Y, ...), M
1441 Instruction *FPI = isa<FPMathOperator>(II) ? II : nullptr;
1442 Value *NewIntrinsic =
1443 Builder.CreateIntrinsic(II->getIntrinsicID(), SrcTy, NewArgs, FPI);
1444 return new ShuffleVectorInst(NewIntrinsic, Mask);
1445}
1446
1447/// Fold the following cases and accepts bswap and bitreverse intrinsics:
1448/// bswap(logic_op(bswap(x), y)) --> logic_op(x, bswap(y))
1449/// bswap(logic_op(bswap(x), bswap(y))) --> logic_op(x, y) (ignores multiuse)
1450template <Intrinsic::ID IntrID>
1452 InstCombiner::BuilderTy &Builder) {
1453 static_assert(IntrID == Intrinsic::bswap || IntrID == Intrinsic::bitreverse,
1454 "This helper only supports BSWAP and BITREVERSE intrinsics");
1455
1456 Value *X, *Y;
1457 // Find bitwise logic op. Check that it is a BinaryOperator explicitly so we
1458 // don't match ConstantExpr that aren't meaningful for this transform.
1460 isa<BinaryOperator>(V)) {
1461 Value *OldReorderX, *OldReorderY;
1462 BinaryOperator::BinaryOps Op = cast<BinaryOperator>(V)->getOpcode();
1463
1464 // If both X and Y are bswap/bitreverse, the transform reduces the number
1465 // of instructions even if there's multiuse.
1466 // If only one operand is bswap/bitreverse, we need to ensure the operand
1467 // have only one use.
1468 if (match(X, m_Intrinsic<IntrID>(m_Value(OldReorderX))) &&
1469 match(Y, m_Intrinsic<IntrID>(m_Value(OldReorderY)))) {
1470 return BinaryOperator::Create(Op, OldReorderX, OldReorderY);
1471 }
1472
1473 if (match(X, m_OneUse(m_Intrinsic<IntrID>(m_Value(OldReorderX))))) {
1474 Value *NewReorder = Builder.CreateUnaryIntrinsic(IntrID, Y);
1475 return BinaryOperator::Create(Op, OldReorderX, NewReorder);
1476 }
1477
1478 if (match(Y, m_OneUse(m_Intrinsic<IntrID>(m_Value(OldReorderY))))) {
1479 Value *NewReorder = Builder.CreateUnaryIntrinsic(IntrID, X);
1480 return BinaryOperator::Create(Op, NewReorder, OldReorderY);
1481 }
1482 }
1483 return nullptr;
1484}
1485
1486static Value *simplifyReductionOperand(Value *Arg, bool CanReorderLanes) {
1487 if (!CanReorderLanes)
1488 return nullptr;
1489
1490 Value *V;
1491 if (match(Arg, m_VecReverse(m_Value(V))))
1492 return V;
1493
1494 ArrayRef<int> Mask;
1495 if (!isa<FixedVectorType>(Arg->getType()) ||
1496 !match(Arg, m_Shuffle(m_Value(V), m_Undef(), m_Mask(Mask))) ||
1497 !cast<ShuffleVectorInst>(Arg)->isSingleSource())
1498 return nullptr;
1499
1500 int Sz = Mask.size();
1501 SmallBitVector UsedIndices(Sz);
1502 for (int Idx : Mask) {
1503 if (Idx == PoisonMaskElem || UsedIndices.test(Idx))
1504 return nullptr;
1505 UsedIndices.set(Idx);
1506 }
1507
1508 // Can remove shuffle iff just shuffled elements, no repeats, undefs, or
1509 // other changes.
1510 return UsedIndices.all() ? V : nullptr;
1511}
1512
1513/// Fold an unsigned minimum of trailing or leading zero bits counts:
1514/// umin(cttz(CtOp, ZeroUndef), ConstOp) --> cttz(CtOp | (1 << ConstOp))
1515/// umin(ctlz(CtOp, ZeroUndef), ConstOp) --> ctlz(CtOp | (SignedMin
1516/// >> ConstOp))
1517template <Intrinsic::ID IntrID>
1518static Value *
1520 const DataLayout &DL,
1521 InstCombiner::BuilderTy &Builder) {
1522 static_assert(IntrID == Intrinsic::cttz || IntrID == Intrinsic::ctlz,
1523 "This helper only supports cttz and ctlz intrinsics");
1524
1525 Value *CtOp;
1526 Value *ZeroUndef;
1527 if (!match(I0,
1528 m_OneUse(m_Intrinsic<IntrID>(m_Value(CtOp), m_Value(ZeroUndef)))))
1529 return nullptr;
1530
1531 unsigned BitWidth = I1->getType()->getScalarSizeInBits();
1532 auto LessBitWidth = [BitWidth](auto &C) { return C.ult(BitWidth); };
1533 if (!match(I1, m_CheckedInt(LessBitWidth)))
1534 // We have a constant >= BitWidth (which can be handled by CVP)
1535 // or a non-splat vector with elements < and >= BitWidth
1536 return nullptr;
1537
1538 Type *Ty = I1->getType();
1540 IntrID == Intrinsic::cttz ? Instruction::Shl : Instruction::LShr,
1541 IntrID == Intrinsic::cttz
1542 ? ConstantInt::get(Ty, 1)
1543 : ConstantInt::get(Ty, APInt::getSignedMinValue(BitWidth)),
1544 cast<Constant>(I1), DL);
1545 return Builder.CreateBinaryIntrinsic(
1546 IntrID, Builder.CreateOr(CtOp, NewConst),
1547 ConstantInt::getTrue(ZeroUndef->getType()));
1548}
1549
1550/// Return whether "X LOp (Y ROp Z)" is always equal to
1551/// "(X LOp Y) ROp (X LOp Z)".
1553 bool HasNSW, Intrinsic::ID ROp) {
1554 switch (ROp) {
1555 case Intrinsic::umax:
1556 case Intrinsic::umin:
1557 return HasNUW && LOp == Instruction::Add;
1558 case Intrinsic::smax:
1559 case Intrinsic::smin:
1560 return HasNSW && LOp == Instruction::Add;
1561 default:
1562 return false;
1563 }
1564}
1565
1566// Attempts to factorise a common term
1567// in an instruction that has the form "(A op' B) op (C op' D)
1568// where op is an intrinsic and op' is a binop
1569static Value *
1571 InstCombiner::BuilderTy &Builder) {
1572 Value *LHS = II->getOperand(0), *RHS = II->getOperand(1);
1573 Intrinsic::ID TopLevelOpcode = II->getIntrinsicID();
1574
1575 OverflowingBinaryOperator *Op0 = dyn_cast<OverflowingBinaryOperator>(LHS);
1576 OverflowingBinaryOperator *Op1 = dyn_cast<OverflowingBinaryOperator>(RHS);
1577
1578 if (!Op0 || !Op1)
1579 return nullptr;
1580
1581 if (Op0->getOpcode() != Op1->getOpcode())
1582 return nullptr;
1583
1584 if (!Op0->hasOneUse() || !Op1->hasOneUse())
1585 return nullptr;
1586
1587 Instruction::BinaryOps InnerOpcode =
1588 static_cast<Instruction::BinaryOps>(Op0->getOpcode());
1589 bool HasNUW = Op0->hasNoUnsignedWrap() && Op1->hasNoUnsignedWrap();
1590 bool HasNSW = Op0->hasNoSignedWrap() && Op1->hasNoSignedWrap();
1591
1592 if (!leftDistributesOverRight(InnerOpcode, HasNUW, HasNSW, TopLevelOpcode))
1593 return nullptr;
1594
1595 assert(II->isCommutative() && Op0->isCommutative() &&
1596 "Only inner and outer commutative op codes are supported.");
1597
1598 Value *A = Op0->getOperand(0);
1599 Value *B = Op0->getOperand(1);
1600 Value *C = Op1->getOperand(0);
1601 Value *D = Op1->getOperand(1);
1602
1603 // Attempts to swap variables such that A always equals C
1604 if (A != C && A != D)
1605 std::swap(A, B);
1606 if (A == C || A == D) {
1607 if (A != C)
1608 std::swap(C, D);
1609 Value *NewIntrinsic = Builder.CreateBinaryIntrinsic(TopLevelOpcode, B, D);
1610 BinaryOperator *NewBinop =
1611 cast<BinaryOperator>(Builder.CreateBinOp(InnerOpcode, NewIntrinsic, A));
1612 NewBinop->setHasNoSignedWrap(HasNSW);
1613 NewBinop->setHasNoUnsignedWrap(HasNUW);
1614 return NewBinop;
1615 }
1616
1617 return nullptr;
1618}
1619
1620/// CallInst simplification. This mostly only handles folding of intrinsic
1621/// instructions. For normal calls, it allows visitCallBase to do the heavy
1622/// lifting.
1624 // Don't try to simplify calls without uses. It will not do anything useful,
1625 // but will result in the following folds being skipped.
1626 if (!CI.use_empty()) {
1627 SmallVector<Value *, 8> Args(CI.args());
1628 if (Value *V = simplifyCall(&CI, CI.getCalledOperand(), Args,
1629 SQ.getWithInstruction(&CI)))
1630 return replaceInstUsesWith(CI, V);
1631 }
1632
1633 if (Value *FreedOp = getFreedOperand(&CI, &TLI))
1634 return visitFree(CI, FreedOp);
1635
1636 // If the caller function (i.e. us, the function that contains this CallInst)
1637 // is nounwind, mark the call as nounwind, even if the callee isn't.
1638 if (CI.getFunction()->doesNotThrow() && !CI.doesNotThrow()) {
1639 CI.setDoesNotThrow();
1640 return &CI;
1641 }
1642
1643 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
1644 if (!II) return visitCallBase(CI);
1645
1646 // For atomic unordered mem intrinsics if len is not a positive or
1647 // not a multiple of element size then behavior is undefined.
1648 if (auto *AMI = dyn_cast<AtomicMemIntrinsic>(II))
1649 if (ConstantInt *NumBytes = dyn_cast<ConstantInt>(AMI->getLength()))
1650 if (NumBytes->isNegative() ||
1651 (NumBytes->getZExtValue() % AMI->getElementSizeInBytes() != 0)) {
1653 assert(AMI->getType()->isVoidTy() &&
1654 "non void atomic unordered mem intrinsic");
1655 return eraseInstFromFunction(*AMI);
1656 }
1657
1658 // Intrinsics cannot occur in an invoke or a callbr, so handle them here
1659 // instead of in visitCallBase.
1660 if (auto *MI = dyn_cast<AnyMemIntrinsic>(II)) {
1661 bool Changed = false;
1662
1663 // memmove/cpy/set of zero bytes is a noop.
1664 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
1665 if (NumBytes->isNullValue())
1666 return eraseInstFromFunction(CI);
1667 }
1668
1669 // No other transformations apply to volatile transfers.
1670 if (auto *M = dyn_cast<MemIntrinsic>(MI))
1671 if (M->isVolatile())
1672 return nullptr;
1673
1674 // If we have a memmove and the source operation is a constant global,
1675 // then the source and dest pointers can't alias, so we can change this
1676 // into a call to memcpy.
1677 if (auto *MMI = dyn_cast<AnyMemMoveInst>(MI)) {
1678 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
1679 if (GVSrc->isConstant()) {
1680 Module *M = CI.getModule();
1681 Intrinsic::ID MemCpyID =
1682 isa<AtomicMemMoveInst>(MMI)
1683 ? Intrinsic::memcpy_element_unordered_atomic
1684 : Intrinsic::memcpy;
1685 Type *Tys[3] = { CI.getArgOperand(0)->getType(),
1686 CI.getArgOperand(1)->getType(),
1687 CI.getArgOperand(2)->getType() };
1689 Intrinsic::getOrInsertDeclaration(M, MemCpyID, Tys));
1690 Changed = true;
1691 }
1692 }
1693
1694 if (AnyMemTransferInst *MTI = dyn_cast<AnyMemTransferInst>(MI)) {
1695 // memmove(x,x,size) -> noop.
1696 if (MTI->getSource() == MTI->getDest())
1697 return eraseInstFromFunction(CI);
1698 }
1699
1700 auto IsPointerUndefined = [MI](Value *Ptr) {
1701 return isa<ConstantPointerNull>(Ptr) &&
1703 MI->getFunction(),
1704 cast<PointerType>(Ptr->getType())->getAddressSpace());
1705 };
1706 bool SrcIsUndefined = false;
1707 // If we can determine a pointer alignment that is bigger than currently
1708 // set, update the alignment.
1709 if (auto *MTI = dyn_cast<AnyMemTransferInst>(MI)) {
1711 return I;
1712 SrcIsUndefined = IsPointerUndefined(MTI->getRawSource());
1713 } else if (auto *MSI = dyn_cast<AnyMemSetInst>(MI)) {
1714 if (Instruction *I = SimplifyAnyMemSet(MSI))
1715 return I;
1716 }
1717
1718 // If src/dest is null, this memory intrinsic must be a noop.
1719 if (SrcIsUndefined || IsPointerUndefined(MI->getRawDest())) {
1721 return eraseInstFromFunction(CI);
1722 }
1723
1724 if (Changed) return II;
1725 }
1726
1727 // For fixed width vector result intrinsics, use the generic demanded vector
1728 // support.
1729 if (auto *IIFVTy = dyn_cast<FixedVectorType>(II->getType())) {
1730 auto VWidth = IIFVTy->getNumElements();
1731 APInt PoisonElts(VWidth, 0);
1732 APInt AllOnesEltMask(APInt::getAllOnes(VWidth));
1733 if (Value *V = SimplifyDemandedVectorElts(II, AllOnesEltMask, PoisonElts)) {
1734 if (V != II)
1735 return replaceInstUsesWith(*II, V);
1736 return II;
1737 }
1738 }
1739
1740 if (II->isCommutative()) {
1741 if (auto Pair = matchSymmetricPair(II->getOperand(0), II->getOperand(1))) {
1742 replaceOperand(*II, 0, Pair->first);
1743 replaceOperand(*II, 1, Pair->second);
1744 return II;
1745 }
1746
1747 if (CallInst *NewCall = canonicalizeConstantArg0ToArg1(CI))
1748 return NewCall;
1749 }
1750
1751 // Unused constrained FP intrinsic calls may have declared side effect, which
1752 // prevents it from being removed. In some cases however the side effect is
1753 // actually absent. To detect this case, call SimplifyConstrainedFPCall. If it
1754 // returns a replacement, the call may be removed.
1755 if (CI.use_empty() && isa<ConstrainedFPIntrinsic>(CI)) {
1757 return eraseInstFromFunction(CI);
1758 }
1759
1760 Intrinsic::ID IID = II->getIntrinsicID();
1761 switch (IID) {
1762 case Intrinsic::objectsize: {
1763 SmallVector<Instruction *> InsertedInstructions;
1764 if (Value *V = lowerObjectSizeCall(II, DL, &TLI, AA, /*MustSucceed=*/false,
1765 &InsertedInstructions)) {
1766 for (Instruction *Inserted : InsertedInstructions)
1767 Worklist.add(Inserted);
1768 return replaceInstUsesWith(CI, V);
1769 }
1770 return nullptr;
1771 }
1772 case Intrinsic::abs: {
1773 Value *IIOperand = II->getArgOperand(0);
1774 bool IntMinIsPoison = cast<Constant>(II->getArgOperand(1))->isOneValue();
1775
1776 // abs(-x) -> abs(x)
1777 // TODO: Copy nsw if it was present on the neg?
1778 Value *X;
1779 if (match(IIOperand, m_Neg(m_Value(X))))
1780 return replaceOperand(*II, 0, X);
1781 if (match(IIOperand, m_c_Select(m_Neg(m_Value(X)), m_Deferred(X))))
1782 return replaceOperand(*II, 0, X);
1783
1784 Value *Y;
1785 // abs(a * abs(b)) -> abs(a * b)
1786 if (match(IIOperand,
1788 m_Intrinsic<Intrinsic::abs>(m_Value(Y)))))) {
1789 bool NSW =
1790 cast<Instruction>(IIOperand)->hasNoSignedWrap() && IntMinIsPoison;
1791 auto *XY = NSW ? Builder.CreateNSWMul(X, Y) : Builder.CreateMul(X, Y);
1792 return replaceOperand(*II, 0, XY);
1793 }
1794
1795 if (std::optional<bool> Known =
1797 // abs(x) -> x if x >= 0 (include abs(x-y) --> x - y where x >= y)
1798 // abs(x) -> x if x > 0 (include abs(x-y) --> x - y where x > y)
1799 if (!*Known)
1800 return replaceInstUsesWith(*II, IIOperand);
1801
1802 // abs(x) -> -x if x < 0
1803 // abs(x) -> -x if x < = 0 (include abs(x-y) --> y - x where x <= y)
1804 if (IntMinIsPoison)
1805 return BinaryOperator::CreateNSWNeg(IIOperand);
1806 return BinaryOperator::CreateNeg(IIOperand);
1807 }
1808
1809 // abs (sext X) --> zext (abs X*)
1810 // Clear the IsIntMin (nsw) bit on the abs to allow narrowing.
1811 if (match(IIOperand, m_OneUse(m_SExt(m_Value(X))))) {
1812 Value *NarrowAbs =
1813 Builder.CreateBinaryIntrinsic(Intrinsic::abs, X, Builder.getFalse());
1814 return CastInst::Create(Instruction::ZExt, NarrowAbs, II->getType());
1815 }
1816
1817 // Match a complicated way to check if a number is odd/even:
1818 // abs (srem X, 2) --> and X, 1
1819 const APInt *C;
1820 if (match(IIOperand, m_SRem(m_Value(X), m_APInt(C))) && *C == 2)
1821 return BinaryOperator::CreateAnd(X, ConstantInt::get(II->getType(), 1));
1822
1823 break;
1824 }
1825 case Intrinsic::umin: {
1826 Value *I0 = II->getArgOperand(0), *I1 = II->getArgOperand(1);
1827 // umin(x, 1) == zext(x != 0)
1828 if (match(I1, m_One())) {
1829 assert(II->getType()->getScalarSizeInBits() != 1 &&
1830 "Expected simplify of umin with max constant");
1831 Value *Zero = Constant::getNullValue(I0->getType());
1832 Value *Cmp = Builder.CreateICmpNE(I0, Zero);
1833 return CastInst::Create(Instruction::ZExt, Cmp, II->getType());
1834 }
1835 // umin(cttz(x), const) --> cttz(x | (1 << const))
1836 if (Value *FoldedCttz =
1837 foldMinimumOverTrailingOrLeadingZeroCount<Intrinsic::cttz>(
1838 I0, I1, DL, Builder))
1839 return replaceInstUsesWith(*II, FoldedCttz);
1840 // umin(ctlz(x), const) --> ctlz(x | (SignedMin >> const))
1841 if (Value *FoldedCtlz =
1842 foldMinimumOverTrailingOrLeadingZeroCount<Intrinsic::ctlz>(
1843 I0, I1, DL, Builder))
1844 return replaceInstUsesWith(*II, FoldedCtlz);
1845 [[fallthrough]];
1846 }
1847 case Intrinsic::umax: {
1848 Value *I0 = II->getArgOperand(0), *I1 = II->getArgOperand(1);
1849 Value *X, *Y;
1850 if (match(I0, m_ZExt(m_Value(X))) && match(I1, m_ZExt(m_Value(Y))) &&
1851 (I0->hasOneUse() || I1->hasOneUse()) && X->getType() == Y->getType()) {
1852 Value *NarrowMaxMin = Builder.CreateBinaryIntrinsic(IID, X, Y);
1853 return CastInst::Create(Instruction::ZExt, NarrowMaxMin, II->getType());
1854 }
1855 Constant *C;
1856 if (match(I0, m_ZExt(m_Value(X))) && match(I1, m_Constant(C)) &&
1857 I0->hasOneUse()) {
1858 if (Constant *NarrowC = getLosslessUnsignedTrunc(C, X->getType())) {
1859 Value *NarrowMaxMin = Builder.CreateBinaryIntrinsic(IID, X, NarrowC);
1860 return CastInst::Create(Instruction::ZExt, NarrowMaxMin, II->getType());
1861 }
1862 }
1863 // If both operands of unsigned min/max are sign-extended, it is still ok
1864 // to narrow the operation.
1865 [[fallthrough]];
1866 }
1867 case Intrinsic::smax:
1868 case Intrinsic::smin: {
1869 Value *I0 = II->getArgOperand(0), *I1 = II->getArgOperand(1);
1870 Value *X, *Y;
1871 if (match(I0, m_SExt(m_Value(X))) && match(I1, m_SExt(m_Value(Y))) &&
1872 (I0->hasOneUse() || I1->hasOneUse()) && X->getType() == Y->getType()) {
1873 Value *NarrowMaxMin = Builder.CreateBinaryIntrinsic(IID, X, Y);
1874 return CastInst::Create(Instruction::SExt, NarrowMaxMin, II->getType());
1875 }
1876
1877 Constant *C;
1878 if (match(I0, m_SExt(m_Value(X))) && match(I1, m_Constant(C)) &&
1879 I0->hasOneUse()) {
1880 if (Constant *NarrowC = getLosslessSignedTrunc(C, X->getType())) {
1881 Value *NarrowMaxMin = Builder.CreateBinaryIntrinsic(IID, X, NarrowC);
1882 return CastInst::Create(Instruction::SExt, NarrowMaxMin, II->getType());
1883 }
1884 }
1885
1886 // umin(i1 X, i1 Y) -> and i1 X, Y
1887 // smax(i1 X, i1 Y) -> and i1 X, Y
1888 if ((IID == Intrinsic::umin || IID == Intrinsic::smax) &&
1889 II->getType()->isIntOrIntVectorTy(1)) {
1890 return BinaryOperator::CreateAnd(I0, I1);
1891 }
1892
1893 // umax(i1 X, i1 Y) -> or i1 X, Y
1894 // smin(i1 X, i1 Y) -> or i1 X, Y
1895 if ((IID == Intrinsic::umax || IID == Intrinsic::smin) &&
1896 II->getType()->isIntOrIntVectorTy(1)) {
1897 return BinaryOperator::CreateOr(I0, I1);
1898 }
1899
1900 if (IID == Intrinsic::smax || IID == Intrinsic::smin) {
1901 // smax (neg nsw X), (neg nsw Y) --> neg nsw (smin X, Y)
1902 // smin (neg nsw X), (neg nsw Y) --> neg nsw (smax X, Y)
1903 // TODO: Canonicalize neg after min/max if I1 is constant.
1904 if (match(I0, m_NSWNeg(m_Value(X))) && match(I1, m_NSWNeg(m_Value(Y))) &&
1905 (I0->hasOneUse() || I1->hasOneUse())) {
1907 Value *InvMaxMin = Builder.CreateBinaryIntrinsic(InvID, X, Y);
1908 return BinaryOperator::CreateNSWNeg(InvMaxMin);
1909 }
1910 }
1911
1912 // (umax X, (xor X, Pow2))
1913 // -> (or X, Pow2)
1914 // (umin X, (xor X, Pow2))
1915 // -> (and X, ~Pow2)
1916 // (smax X, (xor X, Pos_Pow2))
1917 // -> (or X, Pos_Pow2)
1918 // (smin X, (xor X, Pos_Pow2))
1919 // -> (and X, ~Pos_Pow2)
1920 // (smax X, (xor X, Neg_Pow2))
1921 // -> (and X, ~Neg_Pow2)
1922 // (smin X, (xor X, Neg_Pow2))
1923 // -> (or X, Neg_Pow2)
1924 if ((match(I0, m_c_Xor(m_Specific(I1), m_Value(X))) ||
1925 match(I1, m_c_Xor(m_Specific(I0), m_Value(X)))) &&
1926 isKnownToBeAPowerOfTwo(X, /* OrZero */ true)) {
1927 bool UseOr = IID == Intrinsic::smax || IID == Intrinsic::umax;
1928 bool UseAndN = IID == Intrinsic::smin || IID == Intrinsic::umin;
1929
1930 if (IID == Intrinsic::smax || IID == Intrinsic::smin) {
1931 auto KnownSign = getKnownSign(X, SQ.getWithInstruction(II));
1932 if (KnownSign == std::nullopt) {
1933 UseOr = false;
1934 UseAndN = false;
1935 } else if (*KnownSign /* true is Signed. */) {
1936 UseOr ^= true;
1937 UseAndN ^= true;
1938 Type *Ty = I0->getType();
1939 // Negative power of 2 must be IntMin. It's possible to be able to
1940 // prove negative / power of 2 without actually having known bits, so
1941 // just get the value by hand.
1944 }
1945 }
1946 if (UseOr)
1947 return BinaryOperator::CreateOr(I0, X);
1948 else if (UseAndN)
1949 return BinaryOperator::CreateAnd(I0, Builder.CreateNot(X));
1950 }
1951
1952 // If we can eliminate ~A and Y is free to invert:
1953 // max ~A, Y --> ~(min A, ~Y)
1954 //
1955 // Examples:
1956 // max ~A, ~Y --> ~(min A, Y)
1957 // max ~A, C --> ~(min A, ~C)
1958 // max ~A, (max ~Y, ~Z) --> ~min( A, (min Y, Z))
1959 auto moveNotAfterMinMax = [&](Value *X, Value *Y) -> Instruction * {
1960 Value *A;
1961 if (match(X, m_OneUse(m_Not(m_Value(A)))) &&
1962 !isFreeToInvert(A, A->hasOneUse())) {
1963 if (Value *NotY = getFreelyInverted(Y, Y->hasOneUse(), &Builder)) {
1965 Value *InvMaxMin = Builder.CreateBinaryIntrinsic(InvID, A, NotY);
1966 return BinaryOperator::CreateNot(InvMaxMin);
1967 }
1968 }
1969 return nullptr;
1970 };
1971
1972 if (Instruction *I = moveNotAfterMinMax(I0, I1))
1973 return I;
1974 if (Instruction *I = moveNotAfterMinMax(I1, I0))
1975 return I;
1976
1978 return I;
1979
1980 // minmax (X & NegPow2C, Y & NegPow2C) --> minmax(X, Y) & NegPow2C
1981 const APInt *RHSC;
1982 if (match(I0, m_OneUse(m_And(m_Value(X), m_NegatedPower2(RHSC)))) &&
1983 match(I1, m_OneUse(m_And(m_Value(Y), m_SpecificInt(*RHSC)))))
1984 return BinaryOperator::CreateAnd(Builder.CreateBinaryIntrinsic(IID, X, Y),
1985 ConstantInt::get(II->getType(), *RHSC));
1986
1987 // smax(X, -X) --> abs(X)
1988 // smin(X, -X) --> -abs(X)
1989 // umax(X, -X) --> -abs(X)
1990 // umin(X, -X) --> abs(X)
1991 if (isKnownNegation(I0, I1)) {
1992 // We can choose either operand as the input to abs(), but if we can
1993 // eliminate the only use of a value, that's better for subsequent
1994 // transforms/analysis.
1995 if (I0->hasOneUse() && !I1->hasOneUse())
1996 std::swap(I0, I1);
1997
1998 // This is some variant of abs(). See if we can propagate 'nsw' to the abs
1999 // operation and potentially its negation.
2000 bool IntMinIsPoison = isKnownNegation(I0, I1, /* NeedNSW */ true);
2002 Intrinsic::abs, I0,
2003 ConstantInt::getBool(II->getContext(), IntMinIsPoison));
2004
2005 // We don't have a "nabs" intrinsic, so negate if needed based on the
2006 // max/min operation.
2007 if (IID == Intrinsic::smin || IID == Intrinsic::umax)
2008 Abs = Builder.CreateNeg(Abs, "nabs", IntMinIsPoison);
2009 return replaceInstUsesWith(CI, Abs);
2010 }
2011
2013 return Sel;
2014
2015 if (Instruction *SAdd = matchSAddSubSat(*II))
2016 return SAdd;
2017
2018 if (Value *NewMinMax = reassociateMinMaxWithConstants(II, Builder, SQ))
2019 return replaceInstUsesWith(*II, NewMinMax);
2020
2022 return R;
2023
2024 if (Instruction *NewMinMax = factorizeMinMaxTree(II))
2025 return NewMinMax;
2026
2027 // Try to fold minmax with constant RHS based on range information
2028 if (match(I1, m_APIntAllowPoison(RHSC))) {
2029 ICmpInst::Predicate Pred =
2031 bool IsSigned = MinMaxIntrinsic::isSigned(IID);
2033 I0, IsSigned, SQ.getWithInstruction(II));
2034 if (!LHS_CR.isFullSet()) {
2035 if (LHS_CR.icmp(Pred, *RHSC))
2036 return replaceInstUsesWith(*II, I0);
2037 if (LHS_CR.icmp(ICmpInst::getSwappedPredicate(Pred), *RHSC))
2038 return replaceInstUsesWith(*II,
2039 ConstantInt::get(II->getType(), *RHSC));
2040 }
2041 }
2042
2044 return replaceInstUsesWith(*II, V);
2045
2046 break;
2047 }
2048 case Intrinsic::scmp: {
2049 Value *I0 = II->getArgOperand(0), *I1 = II->getArgOperand(1);
2050 Value *LHS, *RHS;
2051 if (match(I0, m_NSWSub(m_Value(LHS), m_Value(RHS))) && match(I1, m_Zero()))
2052 return replaceInstUsesWith(
2053 CI,
2054 Builder.CreateIntrinsic(II->getType(), Intrinsic::scmp, {LHS, RHS}));
2055 break;
2056 }
2057 case Intrinsic::bitreverse: {
2058 Value *IIOperand = II->getArgOperand(0);
2059 // bitrev (zext i1 X to ?) --> X ? SignBitC : 0
2060 Value *X;
2061 if (match(IIOperand, m_ZExt(m_Value(X))) &&
2062 X->getType()->isIntOrIntVectorTy(1)) {
2063 Type *Ty = II->getType();
2065 return SelectInst::Create(X, ConstantInt::get(Ty, SignBit),
2067 }
2068
2069 if (Instruction *crossLogicOpFold =
2070 foldBitOrderCrossLogicOp<Intrinsic::bitreverse>(IIOperand, Builder))
2071 return crossLogicOpFold;
2072
2073 break;
2074 }
2075 case Intrinsic::bswap: {
2076 Value *IIOperand = II->getArgOperand(0);
2077
2078 // Try to canonicalize bswap-of-logical-shift-by-8-bit-multiple as
2079 // inverse-shift-of-bswap:
2080 // bswap (shl X, Y) --> lshr (bswap X), Y
2081 // bswap (lshr X, Y) --> shl (bswap X), Y
2082 Value *X, *Y;
2083 if (match(IIOperand, m_OneUse(m_LogicalShift(m_Value(X), m_Value(Y))))) {
2084 unsigned BitWidth = IIOperand->getType()->getScalarSizeInBits();
2086 Value *NewSwap = Builder.CreateUnaryIntrinsic(Intrinsic::bswap, X);
2087 BinaryOperator::BinaryOps InverseShift =
2088 cast<BinaryOperator>(IIOperand)->getOpcode() == Instruction::Shl
2089 ? Instruction::LShr
2090 : Instruction::Shl;
2091 return BinaryOperator::Create(InverseShift, NewSwap, Y);
2092 }
2093 }
2094
2095 KnownBits Known = computeKnownBits(IIOperand, 0, II);
2096 uint64_t LZ = alignDown(Known.countMinLeadingZeros(), 8);
2097 uint64_t TZ = alignDown(Known.countMinTrailingZeros(), 8);
2098 unsigned BW = Known.getBitWidth();
2099
2100 // bswap(x) -> shift(x) if x has exactly one "active byte"
2101 if (BW - LZ - TZ == 8) {
2102 assert(LZ != TZ && "active byte cannot be in the middle");
2103 if (LZ > TZ) // -> shl(x) if the "active byte" is in the low part of x
2104 return BinaryOperator::CreateNUWShl(
2105 IIOperand, ConstantInt::get(IIOperand->getType(), LZ - TZ));
2106 // -> lshr(x) if the "active byte" is in the high part of x
2107 return BinaryOperator::CreateExactLShr(
2108 IIOperand, ConstantInt::get(IIOperand->getType(), TZ - LZ));
2109 }
2110
2111 // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
2112 if (match(IIOperand, m_Trunc(m_BSwap(m_Value(X))))) {
2113 unsigned C = X->getType()->getScalarSizeInBits() - BW;
2114 Value *CV = ConstantInt::get(X->getType(), C);
2115 Value *V = Builder.CreateLShr(X, CV);
2116 return new TruncInst(V, IIOperand->getType());
2117 }
2118
2119 if (Instruction *crossLogicOpFold =
2120 foldBitOrderCrossLogicOp<Intrinsic::bswap>(IIOperand, Builder)) {
2121 return crossLogicOpFold;
2122 }
2123
2124 // Try to fold into bitreverse if bswap is the root of the expression tree.
2125 if (Instruction *BitOp = matchBSwapOrBitReverse(*II, /*MatchBSwaps*/ false,
2126 /*MatchBitReversals*/ true))
2127 return BitOp;
2128 break;
2129 }
2130 case Intrinsic::masked_load:
2131 if (Value *SimplifiedMaskedOp = simplifyMaskedLoad(*II))
2132 return replaceInstUsesWith(CI, SimplifiedMaskedOp);
2133 break;
2134 case Intrinsic::masked_store:
2135 return simplifyMaskedStore(*II);
2136 case Intrinsic::masked_gather:
2137 return simplifyMaskedGather(*II);
2138 case Intrinsic::masked_scatter:
2139 return simplifyMaskedScatter(*II);
2140 case Intrinsic::launder_invariant_group:
2141 case Intrinsic::strip_invariant_group:
2142 if (auto *SkippedBarrier = simplifyInvariantGroupIntrinsic(*II, *this))
2143 return replaceInstUsesWith(*II, SkippedBarrier);
2144 break;
2145 case Intrinsic::powi:
2146 if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
2147 // 0 and 1 are handled in instsimplify
2148 // powi(x, -1) -> 1/x
2149 if (Power->isMinusOne())
2150 return BinaryOperator::CreateFDivFMF(ConstantFP::get(CI.getType(), 1.0),
2151 II->getArgOperand(0), II);
2152 // powi(x, 2) -> x*x
2153 if (Power->equalsInt(2))
2154 return BinaryOperator::CreateFMulFMF(II->getArgOperand(0),
2155 II->getArgOperand(0), II);
2156
2157 if (!Power->getValue()[0]) {
2158 Value *X;
2159 // If power is even:
2160 // powi(-x, p) -> powi(x, p)
2161 // powi(fabs(x), p) -> powi(x, p)
2162 // powi(copysign(x, y), p) -> powi(x, p)
2163 if (match(II->getArgOperand(0), m_FNeg(m_Value(X))) ||
2164 match(II->getArgOperand(0), m_FAbs(m_Value(X))) ||
2165 match(II->getArgOperand(0),
2166 m_Intrinsic<Intrinsic::copysign>(m_Value(X), m_Value())))
2167 return replaceOperand(*II, 0, X);
2168 }
2169 }
2170 break;
2171
2172 case Intrinsic::cttz:
2173 case Intrinsic::ctlz:
2174 if (auto *I = foldCttzCtlz(*II, *this))
2175 return I;
2176 break;
2177
2178 case Intrinsic::ctpop:
2179 if (auto *I = foldCtpop(*II, *this))
2180 return I;
2181 break;
2182
2183 case Intrinsic::fshl:
2184 case Intrinsic::fshr: {
2185 Value *Op0 = II->getArgOperand(0), *Op1 = II->getArgOperand(1);
2186 Type *Ty = II->getType();
2187 unsigned BitWidth = Ty->getScalarSizeInBits();
2188 Constant *ShAmtC;
2189 if (match(II->getArgOperand(2), m_ImmConstant(ShAmtC))) {
2190 // Canonicalize a shift amount constant operand to modulo the bit-width.
2191 Constant *WidthC = ConstantInt::get(Ty, BitWidth);
2192 Constant *ModuloC =
2193 ConstantFoldBinaryOpOperands(Instruction::URem, ShAmtC, WidthC, DL);
2194 if (!ModuloC)
2195 return nullptr;
2196 if (ModuloC != ShAmtC)
2197 return replaceOperand(*II, 2, ModuloC);
2198
2200 ShAmtC, DL),
2201 m_One()) &&
2202 "Shift amount expected to be modulo bitwidth");
2203
2204 // Canonicalize funnel shift right by constant to funnel shift left. This
2205 // is not entirely arbitrary. For historical reasons, the backend may
2206 // recognize rotate left patterns but miss rotate right patterns.
2207 if (IID == Intrinsic::fshr) {
2208 // fshr X, Y, C --> fshl X, Y, (BitWidth - C) if C is not zero.
2209 if (!isKnownNonZero(ShAmtC, SQ.getWithInstruction(II)))
2210 return nullptr;
2211
2212 Constant *LeftShiftC = ConstantExpr::getSub(WidthC, ShAmtC);
2213 Module *Mod = II->getModule();
2214 Function *Fshl =
2215 Intrinsic::getOrInsertDeclaration(Mod, Intrinsic::fshl, Ty);
2216 return CallInst::Create(Fshl, { Op0, Op1, LeftShiftC });
2217 }
2218 assert(IID == Intrinsic::fshl &&
2219 "All funnel shifts by simple constants should go left");
2220
2221 // fshl(X, 0, C) --> shl X, C
2222 // fshl(X, undef, C) --> shl X, C
2223 if (match(Op1, m_ZeroInt()) || match(Op1, m_Undef()))
2224 return BinaryOperator::CreateShl(Op0, ShAmtC);
2225
2226 // fshl(0, X, C) --> lshr X, (BW-C)
2227 // fshl(undef, X, C) --> lshr X, (BW-C)
2228 if (match(Op0, m_ZeroInt()) || match(Op0, m_Undef()))
2229 return BinaryOperator::CreateLShr(Op1,
2230 ConstantExpr::getSub(WidthC, ShAmtC));
2231
2232 // fshl i16 X, X, 8 --> bswap i16 X (reduce to more-specific form)
2233 if (Op0 == Op1 && BitWidth == 16 && match(ShAmtC, m_SpecificInt(8))) {
2234 Module *Mod = II->getModule();
2235 Function *Bswap =
2236 Intrinsic::getOrInsertDeclaration(Mod, Intrinsic::bswap, Ty);
2237 return CallInst::Create(Bswap, { Op0 });
2238 }
2239 if (Instruction *BitOp =
2240 matchBSwapOrBitReverse(*II, /*MatchBSwaps*/ true,
2241 /*MatchBitReversals*/ true))
2242 return BitOp;
2243 }
2244
2245 // fshl(X, 0, Y) --> shl(X, and(Y, BitWidth - 1)) if bitwidth is a
2246 // power-of-2
2247 if (IID == Intrinsic::fshl && isPowerOf2_32(BitWidth) &&
2248 match(Op1, m_ZeroInt())) {
2249 Value *Op2 = II->getArgOperand(2);
2250 Value *And = Builder.CreateAnd(Op2, ConstantInt::get(Ty, BitWidth - 1));
2251 return BinaryOperator::CreateShl(Op0, And);
2252 }
2253
2254 // Left or right might be masked.
2256 return &CI;
2257
2258 // The shift amount (operand 2) of a funnel shift is modulo the bitwidth,
2259 // so only the low bits of the shift amount are demanded if the bitwidth is
2260 // a power-of-2.
2261 if (!isPowerOf2_32(BitWidth))
2262 break;
2264 KnownBits Op2Known(BitWidth);
2265 if (SimplifyDemandedBits(II, 2, Op2Demanded, Op2Known))
2266 return &CI;
2267 break;
2268 }
2269 case Intrinsic::ptrmask: {
2270 unsigned BitWidth = DL.getPointerTypeSizeInBits(II->getType());
2271 KnownBits Known(BitWidth);
2273 return II;
2274
2275 Value *InnerPtr, *InnerMask;
2276 bool Changed = false;
2277 // Combine:
2278 // (ptrmask (ptrmask p, A), B)
2279 // -> (ptrmask p, (and A, B))
2280 if (match(II->getArgOperand(0),
2281 m_OneUse(m_Intrinsic<Intrinsic::ptrmask>(m_Value(InnerPtr),
2282 m_Value(InnerMask))))) {
2283 assert(II->getArgOperand(1)->getType() == InnerMask->getType() &&
2284 "Mask types must match");
2285 // TODO: If InnerMask == Op1, we could copy attributes from inner
2286 // callsite -> outer callsite.
2287 Value *NewMask = Builder.CreateAnd(II->getArgOperand(1), InnerMask);
2288 replaceOperand(CI, 0, InnerPtr);
2289 replaceOperand(CI, 1, NewMask);
2290 Changed = true;
2291 }
2292
2293 // See if we can deduce non-null.
2294 if (!CI.hasRetAttr(Attribute::NonNull) &&
2295 (Known.isNonZero() ||
2296 isKnownNonZero(II, getSimplifyQuery().getWithInstruction(II)))) {
2297 CI.addRetAttr(Attribute::NonNull);
2298 Changed = true;
2299 }
2300
2301 unsigned NewAlignmentLog =
2303 std::min(BitWidth - 1, Known.countMinTrailingZeros()));
2304 // Known bits will capture if we had alignment information associated with
2305 // the pointer argument.
2306 if (NewAlignmentLog > Log2(CI.getRetAlign().valueOrOne())) {
2308 CI.getContext(), Align(uint64_t(1) << NewAlignmentLog)));
2309 Changed = true;
2310 }
2311 if (Changed)
2312 return &CI;
2313 break;
2314 }
2315 case Intrinsic::uadd_with_overflow:
2316 case Intrinsic::sadd_with_overflow: {
2317 if (Instruction *I = foldIntrinsicWithOverflowCommon(II))
2318 return I;
2319
2320 // Given 2 constant operands whose sum does not overflow:
2321 // uaddo (X +nuw C0), C1 -> uaddo X, C0 + C1
2322 // saddo (X +nsw C0), C1 -> saddo X, C0 + C1
2323 Value *X;
2324 const APInt *C0, *C1;
2325 Value *Arg0 = II->getArgOperand(0);
2326 Value *Arg1 = II->getArgOperand(1);
2327 bool IsSigned = IID == Intrinsic::sadd_with_overflow;
2328 bool HasNWAdd = IsSigned
2329 ? match(Arg0, m_NSWAddLike(m_Value(X), m_APInt(C0)))
2330 : match(Arg0, m_NUWAddLike(m_Value(X), m_APInt(C0)));
2331 if (HasNWAdd && match(Arg1, m_APInt(C1))) {
2332 bool Overflow;
2333 APInt NewC =
2334 IsSigned ? C1->sadd_ov(*C0, Overflow) : C1->uadd_ov(*C0, Overflow);
2335 if (!Overflow)
2336 return replaceInstUsesWith(
2338 IID, X, ConstantInt::get(Arg1->getType(), NewC)));
2339 }
2340 break;
2341 }
2342
2343 case Intrinsic::umul_with_overflow:
2344 case Intrinsic::smul_with_overflow:
2345 case Intrinsic::usub_with_overflow:
2346 if (Instruction *I = foldIntrinsicWithOverflowCommon(II))
2347 return I;
2348 break;
2349
2350 case Intrinsic::ssub_with_overflow: {
2351 if (Instruction *I = foldIntrinsicWithOverflowCommon(II))
2352 return I;
2353
2354 Constant *C;
2355 Value *Arg0 = II->getArgOperand(0);
2356 Value *Arg1 = II->getArgOperand(1);
2357 // Given a constant C that is not the minimum signed value
2358 // for an integer of a given bit width:
2359 //
2360 // ssubo X, C -> saddo X, -C
2361 if (match(Arg1, m_Constant(C)) && C->isNotMinSignedValue()) {
2362 Value *NegVal = ConstantExpr::getNeg(C);
2363 // Build a saddo call that is equivalent to the discovered
2364 // ssubo call.
2365 return replaceInstUsesWith(
2366 *II, Builder.CreateBinaryIntrinsic(Intrinsic::sadd_with_overflow,
2367 Arg0, NegVal));
2368 }
2369
2370 break;
2371 }
2372
2373 case Intrinsic::uadd_sat:
2374 case Intrinsic::sadd_sat:
2375 case Intrinsic::usub_sat:
2376 case Intrinsic::ssub_sat: {
2377 SaturatingInst *SI = cast<SaturatingInst>(II);
2378 Type *Ty = SI->getType();
2379 Value *Arg0 = SI->getLHS();
2380 Value *Arg1 = SI->getRHS();
2381
2382 // Make use of known overflow information.
2383 OverflowResult OR = computeOverflow(SI->getBinaryOp(), SI->isSigned(),
2384 Arg0, Arg1, SI);
2385 switch (OR) {
2387 break;
2389 if (SI->isSigned())
2390 return BinaryOperator::CreateNSW(SI->getBinaryOp(), Arg0, Arg1);
2391 else
2392 return BinaryOperator::CreateNUW(SI->getBinaryOp(), Arg0, Arg1);
2394 unsigned BitWidth = Ty->getScalarSizeInBits();
2395 APInt Min = APSInt::getMinValue(BitWidth, !SI->isSigned());
2396 return replaceInstUsesWith(*SI, ConstantInt::get(Ty, Min));
2397 }
2399 unsigned BitWidth = Ty->getScalarSizeInBits();
2400 APInt Max = APSInt::getMaxValue(BitWidth, !SI->isSigned());
2401 return replaceInstUsesWith(*SI, ConstantInt::get(Ty, Max));
2402 }
2403 }
2404
2405 // usub_sat((sub nuw C, A), C1) -> usub_sat(usub_sat(C, C1), A)
2406 // which after that:
2407 // usub_sat((sub nuw C, A), C1) -> usub_sat(C - C1, A) if C1 u< C
2408 // usub_sat((sub nuw C, A), C1) -> 0 otherwise
2409 Constant *C, *C1;
2410 Value *A;
2411 if (IID == Intrinsic::usub_sat &&
2412 match(Arg0, m_NUWSub(m_ImmConstant(C), m_Value(A))) &&
2413 match(Arg1, m_ImmConstant(C1))) {
2414 auto *NewC = Builder.CreateBinaryIntrinsic(Intrinsic::usub_sat, C, C1);
2415 auto *NewSub =
2416 Builder.CreateBinaryIntrinsic(Intrinsic::usub_sat, NewC, A);
2417 return replaceInstUsesWith(*SI, NewSub);
2418 }
2419
2420 // ssub.sat(X, C) -> sadd.sat(X, -C) if C != MIN
2421 if (IID == Intrinsic::ssub_sat && match(Arg1, m_Constant(C)) &&
2422 C->isNotMinSignedValue()) {
2423 Value *NegVal = ConstantExpr::getNeg(C);
2424 return replaceInstUsesWith(
2426 Intrinsic::sadd_sat, Arg0, NegVal));
2427 }
2428
2429 // sat(sat(X + Val2) + Val) -> sat(X + (Val+Val2))
2430 // sat(sat(X - Val2) - Val) -> sat(X - (Val+Val2))
2431 // if Val and Val2 have the same sign
2432 if (auto *Other = dyn_cast<IntrinsicInst>(Arg0)) {
2433 Value *X;
2434 const APInt *Val, *Val2;
2435 APInt NewVal;
2436 bool IsUnsigned =
2437 IID == Intrinsic::uadd_sat || IID == Intrinsic::usub_sat;
2438 if (Other->getIntrinsicID() == IID &&
2439 match(Arg1, m_APInt(Val)) &&
2440 match(Other->getArgOperand(0), m_Value(X)) &&
2441 match(Other->getArgOperand(1), m_APInt(Val2))) {
2442 if (IsUnsigned)
2443 NewVal = Val->uadd_sat(*Val2);
2444 else if (Val->isNonNegative() == Val2->isNonNegative()) {
2445 bool Overflow;
2446 NewVal = Val->sadd_ov(*Val2, Overflow);
2447 if (Overflow) {
2448 // Both adds together may add more than SignedMaxValue
2449 // without saturating the final result.
2450 break;
2451 }
2452 } else {
2453 // Cannot fold saturated addition with different signs.
2454 break;
2455 }
2456
2457 return replaceInstUsesWith(
2459 IID, X, ConstantInt::get(II->getType(), NewVal)));
2460 }
2461 }
2462 break;
2463 }
2464
2465 case Intrinsic::minnum:
2466 case Intrinsic::maxnum:
2467 case Intrinsic::minimum:
2468 case Intrinsic::maximum: {
2469 Value *Arg0 = II->getArgOperand(0);
2470 Value *Arg1 = II->getArgOperand(1);
2471 Value *X, *Y;
2472 if (match(Arg0, m_FNeg(m_Value(X))) && match(Arg1, m_FNeg(m_Value(Y))) &&
2473 (Arg0->hasOneUse() || Arg1->hasOneUse())) {
2474 // If both operands are negated, invert the call and negate the result:
2475 // min(-X, -Y) --> -(max(X, Y))
2476 // max(-X, -Y) --> -(min(X, Y))
2477 Intrinsic::ID NewIID;
2478 switch (IID) {
2479 case Intrinsic::maxnum:
2480 NewIID = Intrinsic::minnum;
2481 break;
2482 case Intrinsic::minnum:
2483 NewIID = Intrinsic::maxnum;
2484 break;
2485 case Intrinsic::maximum:
2486 NewIID = Intrinsic::minimum;
2487 break;
2488 case Intrinsic::minimum:
2489 NewIID = Intrinsic::maximum;
2490 break;
2491 default:
2492 llvm_unreachable("unexpected intrinsic ID");
2493 }
2494 Value *NewCall = Builder.CreateBinaryIntrinsic(NewIID, X, Y, II);
2495 Instruction *FNeg = UnaryOperator::CreateFNeg(NewCall);
2496 FNeg->copyIRFlags(II);
2497 return FNeg;
2498 }
2499
2500 // m(m(X, C2), C1) -> m(X, C)
2501 const APFloat *C1, *C2;
2502 if (auto *M = dyn_cast<IntrinsicInst>(Arg0)) {
2503 if (M->getIntrinsicID() == IID && match(Arg1, m_APFloat(C1)) &&
2504 ((match(M->getArgOperand(0), m_Value(X)) &&
2505 match(M->getArgOperand(1), m_APFloat(C2))) ||
2506 (match(M->getArgOperand(1), m_Value(X)) &&
2507 match(M->getArgOperand(0), m_APFloat(C2))))) {
2508 APFloat Res(0.0);
2509 switch (IID) {
2510 case Intrinsic::maxnum:
2511 Res = maxnum(*C1, *C2);
2512 break;
2513 case Intrinsic::minnum:
2514 Res = minnum(*C1, *C2);
2515 break;
2516 case Intrinsic::maximum:
2517 Res = maximum(*C1, *C2);
2518 break;
2519 case Intrinsic::minimum:
2520 Res = minimum(*C1, *C2);
2521 break;
2522 default:
2523 llvm_unreachable("unexpected intrinsic ID");
2524 }
2526 IID, X, ConstantFP::get(Arg0->getType(), Res), II);
2527 // TODO: Conservatively intersecting FMF. If Res == C2, the transform
2528 // was a simplification (so Arg0 and its original flags could
2529 // propagate?)
2530 if (auto *CI = dyn_cast<CallInst>(V))
2531 CI->andIRFlags(M);
2532 return replaceInstUsesWith(*II, V);
2533 }
2534 }
2535
2536 // m((fpext X), (fpext Y)) -> fpext (m(X, Y))
2537 if (match(Arg0, m_OneUse(m_FPExt(m_Value(X)))) &&
2538 match(Arg1, m_OneUse(m_FPExt(m_Value(Y)))) &&
2539 X->getType() == Y->getType()) {
2540 Value *NewCall =
2541 Builder.CreateBinaryIntrinsic(IID, X, Y, II, II->getName());
2542 return new FPExtInst(NewCall, II->getType());
2543 }
2544
2545 // max X, -X --> fabs X
2546 // min X, -X --> -(fabs X)
2547 // TODO: Remove one-use limitation? That is obviously better for max,
2548 // hence why we don't check for one-use for that. However,
2549 // it would be an extra instruction for min (fnabs), but
2550 // that is still likely better for analysis and codegen.
2551 auto IsMinMaxOrXNegX = [IID, &X](Value *Op0, Value *Op1) {
2552 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_Specific(X)))
2553 return Op0->hasOneUse() ||
2554 (IID != Intrinsic::minimum && IID != Intrinsic::minnum);
2555 return false;
2556 };
2557
2558 if (IsMinMaxOrXNegX(Arg0, Arg1) || IsMinMaxOrXNegX(Arg1, Arg0)) {
2559 Value *R = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, X, II);
2560 if (IID == Intrinsic::minimum || IID == Intrinsic::minnum)
2561 R = Builder.CreateFNegFMF(R, II);
2562 return replaceInstUsesWith(*II, R);
2563 }
2564
2565 break;
2566 }
2567 case Intrinsic::matrix_multiply: {
2568 // Optimize negation in matrix multiplication.
2569
2570 // -A * -B -> A * B
2571 Value *A, *B;
2572 if (match(II->getArgOperand(0), m_FNeg(m_Value(A))) &&
2573 match(II->getArgOperand(1), m_FNeg(m_Value(B)))) {
2574 replaceOperand(*II, 0, A);
2575 replaceOperand(*II, 1, B);
2576 return II;
2577 }
2578
2579 Value *Op0 = II->getOperand(0);
2580 Value *Op1 = II->getOperand(1);
2581 Value *OpNotNeg, *NegatedOp;
2582 unsigned NegatedOpArg, OtherOpArg;
2583 if (match(Op0, m_FNeg(m_Value(OpNotNeg)))) {
2584 NegatedOp = Op0;
2585 NegatedOpArg = 0;
2586 OtherOpArg = 1;
2587 } else if (match(Op1, m_FNeg(m_Value(OpNotNeg)))) {
2588 NegatedOp = Op1;
2589 NegatedOpArg = 1;
2590 OtherOpArg = 0;
2591 } else
2592 // Multiplication doesn't have a negated operand.
2593 break;
2594
2595 // Only optimize if the negated operand has only one use.
2596 if (!NegatedOp->hasOneUse())
2597 break;
2598
2599 Value *OtherOp = II->getOperand(OtherOpArg);
2600 VectorType *RetTy = cast<VectorType>(II->getType());
2601 VectorType *NegatedOpTy = cast<VectorType>(NegatedOp->getType());
2602 VectorType *OtherOpTy = cast<VectorType>(OtherOp->getType());
2603 ElementCount NegatedCount = NegatedOpTy->getElementCount();
2604 ElementCount OtherCount = OtherOpTy->getElementCount();
2605 ElementCount RetCount = RetTy->getElementCount();
2606 // (-A) * B -> A * (-B), if it is cheaper to negate B and vice versa.
2607 if (ElementCount::isKnownGT(NegatedCount, OtherCount) &&
2608 ElementCount::isKnownLT(OtherCount, RetCount)) {
2609 Value *InverseOtherOp = Builder.CreateFNeg(OtherOp);
2610 replaceOperand(*II, NegatedOpArg, OpNotNeg);
2611 replaceOperand(*II, OtherOpArg, InverseOtherOp);
2612 return II;
2613 }
2614 // (-A) * B -> -(A * B), if it is cheaper to negate the result
2615 if (ElementCount::isKnownGT(NegatedCount, RetCount)) {
2616 SmallVector<Value *, 5> NewArgs(II->args());
2617 NewArgs[NegatedOpArg] = OpNotNeg;
2618 Instruction *NewMul =
2619 Builder.CreateIntrinsic(II->getType(), IID, NewArgs, II);
2620 return replaceInstUsesWith(*II, Builder.CreateFNegFMF(NewMul, II));
2621 }
2622 break;
2623 }
2624 case Intrinsic::fmuladd: {
2625 // Try to simplify the underlying FMul.
2626 if (Value *V = simplifyFMulInst(II->getArgOperand(0), II->getArgOperand(1),
2627 II->getFastMathFlags(),
2629 auto *FAdd = BinaryOperator::CreateFAdd(V, II->getArgOperand(2));
2630 FAdd->copyFastMathFlags(II);
2631 return FAdd;
2632 }
2633
2634 [[fallthrough]];
2635 }
2636 case Intrinsic::fma: {
2637 // fma fneg(x), fneg(y), z -> fma x, y, z
2638 Value *Src0 = II->getArgOperand(0);
2639 Value *Src1 = II->getArgOperand(1);
2640 Value *Src2 = II->getArgOperand(2);
2641 Value *X, *Y;
2642 if (match(Src0, m_FNeg(m_Value(X))) && match(Src1, m_FNeg(m_Value(Y)))) {
2643 replaceOperand(*II, 0, X);
2644 replaceOperand(*II, 1, Y);
2645 return II;
2646 }
2647
2648 // fma fabs(x), fabs(x), z -> fma x, x, z
2649 if (match(Src0, m_FAbs(m_Value(X))) &&
2650 match(Src1, m_FAbs(m_Specific(X)))) {
2651 replaceOperand(*II, 0, X);
2652 replaceOperand(*II, 1, X);
2653 return II;
2654 }
2655
2656 // Try to simplify the underlying FMul. We can only apply simplifications
2657 // that do not require rounding.
2658 if (Value *V = simplifyFMAFMul(Src0, Src1, II->getFastMathFlags(),
2660 auto *FAdd = BinaryOperator::CreateFAdd(V, Src2);
2661 FAdd->copyFastMathFlags(II);
2662 return FAdd;
2663 }
2664
2665 // fma x, y, 0 -> fmul x, y
2666 // This is always valid for -0.0, but requires nsz for +0.0 as
2667 // -0.0 + 0.0 = 0.0, which would not be the same as the fmul on its own.
2668 if (match(Src2, m_NegZeroFP()) ||
2669 (match(Src2, m_PosZeroFP()) && II->getFastMathFlags().noSignedZeros()))
2670 return BinaryOperator::CreateFMulFMF(Src0, Src1, II);
2671
2672 // fma x, -1.0, y -> fsub y, x
2673 if (match(Src1, m_SpecificFP(-1.0)))
2674 return BinaryOperator::CreateFSubFMF(Src2, Src0, II);
2675
2676 break;
2677 }
2678 case Intrinsic::copysign: {
2679 Value *Mag = II->getArgOperand(0), *Sign = II->getArgOperand(1);
2680 if (std::optional<bool> KnownSignBit = computeKnownFPSignBit(
2681 Sign, /*Depth=*/0, getSimplifyQuery().getWithInstruction(II))) {
2682 if (*KnownSignBit) {
2683 // If we know that the sign argument is negative, reduce to FNABS:
2684 // copysign Mag, -Sign --> fneg (fabs Mag)
2685 Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, Mag, II);
2687 }
2688
2689 // If we know that the sign argument is positive, reduce to FABS:
2690 // copysign Mag, +Sign --> fabs Mag
2691 Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, Mag, II);
2692 return replaceInstUsesWith(*II, Fabs);
2693 }
2694
2695 // Propagate sign argument through nested calls:
2696 // copysign Mag, (copysign ?, X) --> copysign Mag, X
2697 Value *X;
2698 if (match(Sign, m_Intrinsic<Intrinsic::copysign>(m_Value(), m_Value(X)))) {
2699 Value *CopySign =
2701 return replaceInstUsesWith(*II, CopySign);
2702 }
2703
2704 // Clear sign-bit of constant magnitude:
2705 // copysign -MagC, X --> copysign MagC, X
2706 // TODO: Support constant folding for fabs
2707 const APFloat *MagC;
2708 if (match(Mag, m_APFloat(MagC)) && MagC->isNegative()) {
2709 APFloat PosMagC = *MagC;
2710 PosMagC.clearSign();
2711 return replaceOperand(*II, 0, ConstantFP::get(Mag->getType(), PosMagC));
2712 }
2713
2714 // Peek through changes of magnitude's sign-bit. This call rewrites those:
2715 // copysign (fabs X), Sign --> copysign X, Sign
2716 // copysign (fneg X), Sign --> copysign X, Sign
2717 if (match(Mag, m_FAbs(m_Value(X))) || match(Mag, m_FNeg(m_Value(X))))
2718 return replaceOperand(*II, 0, X);
2719
2720 break;
2721 }
2722 case Intrinsic::fabs: {
2723 Value *Cond, *TVal, *FVal;
2724 Value *Arg = II->getArgOperand(0);
2725 Value *X;
2726 // fabs (-X) --> fabs (X)
2727 if (match(Arg, m_FNeg(m_Value(X)))) {
2728 CallInst *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, X, II);
2729 return replaceInstUsesWith(CI, Fabs);
2730 }
2731
2732 if (match(Arg, m_Select(m_Value(Cond), m_Value(TVal), m_Value(FVal)))) {
2733 // fabs (select Cond, TrueC, FalseC) --> select Cond, AbsT, AbsF
2734 if (isa<Constant>(TVal) || isa<Constant>(FVal)) {
2735 CallInst *AbsT = Builder.CreateCall(II->getCalledFunction(), {TVal});
2736 CallInst *AbsF = Builder.CreateCall(II->getCalledFunction(), {FVal});
2737 SelectInst *SI = SelectInst::Create(Cond, AbsT, AbsF);
2738 FastMathFlags FMF1 = II->getFastMathFlags();
2739 FastMathFlags FMF2 = cast<SelectInst>(Arg)->getFastMathFlags();
2740 FMF2.setNoSignedZeros(false);
2741 SI->setFastMathFlags(FMF1 | FMF2);
2742 return SI;
2743 }
2744 // fabs (select Cond, -FVal, FVal) --> fabs FVal
2745 if (match(TVal, m_FNeg(m_Specific(FVal))))
2746 return replaceOperand(*II, 0, FVal);
2747 // fabs (select Cond, TVal, -TVal) --> fabs TVal
2748 if (match(FVal, m_FNeg(m_Specific(TVal))))
2749 return replaceOperand(*II, 0, TVal);
2750 }
2751
2752 Value *Magnitude, *Sign;
2753 if (match(II->getArgOperand(0),
2754 m_CopySign(m_Value(Magnitude), m_Value(Sign)))) {
2755 // fabs (copysign x, y) -> (fabs x)
2756 CallInst *AbsSign =
2757 Builder.CreateCall(II->getCalledFunction(), {Magnitude});
2758 AbsSign->copyFastMathFlags(II);
2759 return replaceInstUsesWith(*II, AbsSign);
2760 }
2761
2762 [[fallthrough]];
2763 }
2764 case Intrinsic::ceil:
2765 case Intrinsic::floor:
2766 case Intrinsic::round:
2767 case Intrinsic::roundeven:
2768 case Intrinsic::nearbyint:
2769 case Intrinsic::rint:
2770 case Intrinsic::trunc: {
2771 Value *ExtSrc;
2772 if (match(II->getArgOperand(0), m_OneUse(m_FPExt(m_Value(ExtSrc))))) {
2773 // Narrow the call: intrinsic (fpext x) -> fpext (intrinsic x)
2774 Value *NarrowII = Builder.CreateUnaryIntrinsic(IID, ExtSrc, II);
2775 return new FPExtInst(NarrowII, II->getType());
2776 }
2777 break;
2778 }
2779 case Intrinsic::cos:
2780 case Intrinsic::amdgcn_cos: {
2781 Value *X, *Sign;
2782 Value *Src = II->getArgOperand(0);
2783 if (match(Src, m_FNeg(m_Value(X))) || match(Src, m_FAbs(m_Value(X))) ||
2784 match(Src, m_CopySign(m_Value(X), m_Value(Sign)))) {
2785 // cos(-x) --> cos(x)
2786 // cos(fabs(x)) --> cos(x)
2787 // cos(copysign(x, y)) --> cos(x)
2788 return replaceOperand(*II, 0, X);
2789 }
2790 break;
2791 }
2792 case Intrinsic::sin:
2793 case Intrinsic::amdgcn_sin: {
2794 Value *X;
2795 if (match(II->getArgOperand(0), m_OneUse(m_FNeg(m_Value(X))))) {
2796 // sin(-x) --> -sin(x)
2797 Value *NewSin = Builder.CreateUnaryIntrinsic(IID, X, II);
2798 return UnaryOperator::CreateFNegFMF(NewSin, II);
2799 }
2800 break;
2801 }
2802 case Intrinsic::ldexp: {
2803 // ldexp(ldexp(x, a), b) -> ldexp(x, a + b)
2804 //
2805 // The danger is if the first ldexp would overflow to infinity or underflow
2806 // to zero, but the combined exponent avoids it. We ignore this with
2807 // reassoc.
2808 //
2809 // It's also safe to fold if we know both exponents are >= 0 or <= 0 since
2810 // it would just double down on the overflow/underflow which would occur
2811 // anyway.
2812 //
2813 // TODO: Could do better if we had range tracking for the input value
2814 // exponent. Also could broaden sign check to cover == 0 case.
2815 Value *Src = II->getArgOperand(0);
2816 Value *Exp = II->getArgOperand(1);
2817 Value *InnerSrc;
2818 Value *InnerExp;
2819 if (match(Src, m_OneUse(m_Intrinsic<Intrinsic::ldexp>(
2820 m_Value(InnerSrc), m_Value(InnerExp)))) &&
2821 Exp->getType() == InnerExp->getType()) {
2822 FastMathFlags FMF = II->getFastMathFlags();
2823 FastMathFlags InnerFlags = cast<FPMathOperator>(Src)->getFastMathFlags();
2824
2825 if ((FMF.allowReassoc() && InnerFlags.allowReassoc()) ||
2826 signBitMustBeTheSame(Exp, InnerExp, SQ.getWithInstruction(II))) {
2827 // TODO: Add nsw/nuw probably safe if integer type exceeds exponent
2828 // width.
2829 Value *NewExp = Builder.CreateAdd(InnerExp, Exp);
2830 II->setArgOperand(1, NewExp);
2831 II->setFastMathFlags(InnerFlags); // Or the inner flags.
2832 return replaceOperand(*II, 0, InnerSrc);
2833 }
2834 }
2835
2836 // ldexp(x, zext(i1 y)) -> fmul x, (select y, 2.0, 1.0)
2837 // ldexp(x, sext(i1 y)) -> fmul x, (select y, 0.5, 1.0)
2838 Value *ExtSrc;
2839 if (match(Exp, m_ZExt(m_Value(ExtSrc))) &&
2840 ExtSrc->getType()->getScalarSizeInBits() == 1) {
2841 Value *Select =
2842 Builder.CreateSelect(ExtSrc, ConstantFP::get(II->getType(), 2.0),
2843 ConstantFP::get(II->getType(), 1.0));
2845 }
2846 if (match(Exp, m_SExt(m_Value(ExtSrc))) &&
2847 ExtSrc->getType()->getScalarSizeInBits() == 1) {
2848 Value *Select =
2849 Builder.CreateSelect(ExtSrc, ConstantFP::get(II->getType(), 0.5),
2850 ConstantFP::get(II->getType(), 1.0));
2852 }
2853
2854 // ldexp(x, c ? exp : 0) -> c ? ldexp(x, exp) : x
2855 // ldexp(x, c ? 0 : exp) -> c ? x : ldexp(x, exp)
2856 ///
2857 // TODO: If we cared, should insert a canonicalize for x
2858 Value *SelectCond, *SelectLHS, *SelectRHS;
2859 if (match(II->getArgOperand(1),
2860 m_OneUse(m_Select(m_Value(SelectCond), m_Value(SelectLHS),
2861 m_Value(SelectRHS))))) {
2862 Value *NewLdexp = nullptr;
2863 Value *Select = nullptr;
2864 if (match(SelectRHS, m_ZeroInt())) {
2865 NewLdexp = Builder.CreateLdexp(Src, SelectLHS);
2866 Select = Builder.CreateSelect(SelectCond, NewLdexp, Src);
2867 } else if (match(SelectLHS, m_ZeroInt())) {
2868 NewLdexp = Builder.CreateLdexp(Src, SelectRHS);
2869 Select = Builder.CreateSelect(SelectCond, Src, NewLdexp);
2870 }
2871
2872 if (NewLdexp) {
2873 Select->takeName(II);
2874 cast<Instruction>(NewLdexp)->copyFastMathFlags(II);
2875 return replaceInstUsesWith(*II, Select);
2876 }
2877 }
2878
2879 break;
2880 }
2881 case Intrinsic::ptrauth_auth:
2882 case Intrinsic::ptrauth_resign: {
2883 // (sign|resign) + (auth|resign) can be folded by omitting the middle
2884 // sign+auth component if the key and discriminator match.
2885 bool NeedSign = II->getIntrinsicID() == Intrinsic::ptrauth_resign;
2886 Value *Ptr = II->getArgOperand(0);
2887 Value *Key = II->getArgOperand(1);
2888 Value *Disc = II->getArgOperand(2);
2889
2890 // AuthKey will be the key we need to end up authenticating against in
2891 // whatever we replace this sequence with.
2892 Value *AuthKey = nullptr, *AuthDisc = nullptr, *BasePtr;
2893 if (const auto *CI = dyn_cast<CallBase>(Ptr)) {
2894 BasePtr = CI->getArgOperand(0);
2895 if (CI->getIntrinsicID() == Intrinsic::ptrauth_sign) {
2896 if (CI->getArgOperand(1) != Key || CI->getArgOperand(2) != Disc)
2897 break;
2898 } else if (CI->getIntrinsicID() == Intrinsic::ptrauth_resign) {
2899 if (CI->getArgOperand(3) != Key || CI->getArgOperand(4) != Disc)
2900 break;
2901 AuthKey = CI->getArgOperand(1);
2902 AuthDisc = CI->getArgOperand(2);
2903 } else
2904 break;
2905 } else if (const auto *PtrToInt = dyn_cast<PtrToIntOperator>(Ptr)) {
2906 // ptrauth constants are equivalent to a call to @llvm.ptrauth.sign for
2907 // our purposes, so check for that too.
2908 const auto *CPA = dyn_cast<ConstantPtrAuth>(PtrToInt->getOperand(0));
2909 if (!CPA || !CPA->isKnownCompatibleWith(Key, Disc, DL))
2910 break;
2911
2912 // resign(ptrauth(p,ks,ds),ks,ds,kr,dr) -> ptrauth(p,kr,dr)
2913 if (NeedSign && isa<ConstantInt>(II->getArgOperand(4))) {
2914 auto *SignKey = cast<ConstantInt>(II->getArgOperand(3));
2915 auto *SignDisc = cast<ConstantInt>(II->getArgOperand(4));
2916 auto *SignAddrDisc = ConstantPointerNull::get(Builder.getPtrTy());
2917 auto *NewCPA = ConstantPtrAuth::get(CPA->getPointer(), SignKey,
2918 SignDisc, SignAddrDisc);
2920 *II, ConstantExpr::getPointerCast(NewCPA, II->getType()));
2921 return eraseInstFromFunction(*II);
2922 }
2923
2924 // auth(ptrauth(p,k,d),k,d) -> p
2925 BasePtr = Builder.CreatePtrToInt(CPA->getPointer(), II->getType());
2926 } else
2927 break;
2928
2929 unsigned NewIntrin;
2930 if (AuthKey && NeedSign) {
2931 // resign(0,1) + resign(1,2) = resign(0, 2)
2932 NewIntrin = Intrinsic::ptrauth_resign;
2933 } else if (AuthKey) {
2934 // resign(0,1) + auth(1) = auth(0)
2935 NewIntrin = Intrinsic::ptrauth_auth;
2936 } else if (NeedSign) {
2937 // sign(0) + resign(0, 1) = sign(1)
2938 NewIntrin = Intrinsic::ptrauth_sign;
2939 } else {
2940 // sign(0) + auth(0) = nop
2941 replaceInstUsesWith(*II, BasePtr);
2942 return eraseInstFromFunction(*II);
2943 }
2944
2945 SmallVector<Value *, 4> CallArgs;
2946 CallArgs.push_back(BasePtr);
2947 if (AuthKey) {
2948 CallArgs.push_back(AuthKey);
2949 CallArgs.push_back(AuthDisc);
2950 }
2951
2952 if (NeedSign) {
2953 CallArgs.push_back(II->getArgOperand(3));
2954 CallArgs.push_back(II->getArgOperand(4));
2955 }
2956
2957 Function *NewFn =
2958 Intrinsic::getOrInsertDeclaration(II->getModule(), NewIntrin);
2959 return CallInst::Create(NewFn, CallArgs);
2960 }
2961 case Intrinsic::arm_neon_vtbl1:
2962 case Intrinsic::aarch64_neon_tbl1:
2963 if (Value *V = simplifyNeonTbl1(*II, Builder))
2964 return replaceInstUsesWith(*II, V);
2965 break;
2966
2967 case Intrinsic::arm_neon_vmulls:
2968 case Intrinsic::arm_neon_vmullu:
2969 case Intrinsic::aarch64_neon_smull:
2970 case Intrinsic::aarch64_neon_umull: {
2971 Value *Arg0 = II->getArgOperand(0);
2972 Value *Arg1 = II->getArgOperand(1);
2973
2974 // Handle mul by zero first:
2975 if (isa<ConstantAggregateZero>(Arg0) || isa<ConstantAggregateZero>(Arg1)) {
2976 return replaceInstUsesWith(CI, ConstantAggregateZero::get(II->getType()));
2977 }
2978
2979 // Check for constant LHS & RHS - in this case we just simplify.
2980 bool Zext = (IID == Intrinsic::arm_neon_vmullu ||
2981 IID == Intrinsic::aarch64_neon_umull);
2982 VectorType *NewVT = cast<VectorType>(II->getType());
2983 if (Constant *CV0 = dyn_cast<Constant>(Arg0)) {
2984 if (Constant *CV1 = dyn_cast<Constant>(Arg1)) {
2985 Value *V0 = Builder.CreateIntCast(CV0, NewVT, /*isSigned=*/!Zext);
2986 Value *V1 = Builder.CreateIntCast(CV1, NewVT, /*isSigned=*/!Zext);
2987 return replaceInstUsesWith(CI, Builder.CreateMul(V0, V1));
2988 }
2989
2990 // Couldn't simplify - canonicalize constant to the RHS.
2991 std::swap(Arg0, Arg1);
2992 }
2993
2994 // Handle mul by one:
2995 if (Constant *CV1 = dyn_cast<Constant>(Arg1))
2996 if (ConstantInt *Splat =
2997 dyn_cast_or_null<ConstantInt>(CV1->getSplatValue()))
2998 if (Splat->isOne())
2999 return CastInst::CreateIntegerCast(Arg0, II->getType(),
3000 /*isSigned=*/!Zext);
3001
3002 break;
3003 }
3004 case Intrinsic::arm_neon_aesd:
3005 case Intrinsic::arm_neon_aese:
3006 case Intrinsic::aarch64_crypto_aesd:
3007 case Intrinsic::aarch64_crypto_aese: {
3008 Value *DataArg = II->getArgOperand(0);
3009 Value *KeyArg = II->getArgOperand(1);
3010
3011 // Try to use the builtin XOR in AESE and AESD to eliminate a prior XOR
3012 Value *Data, *Key;
3013 if (match(KeyArg, m_ZeroInt()) &&
3014 match(DataArg, m_Xor(m_Value(Data), m_Value(Key)))) {
3015 replaceOperand(*II, 0, Data);
3016 replaceOperand(*II, 1, Key);
3017 return II;
3018 }
3019 break;
3020 }
3021 case Intrinsic::hexagon_V6_vandvrt:
3022 case Intrinsic::hexagon_V6_vandvrt_128B: {
3023 // Simplify Q -> V -> Q conversion.
3024 if (auto Op0 = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {
3025 Intrinsic::ID ID0 = Op0->getIntrinsicID();
3026 if (ID0 != Intrinsic::hexagon_V6_vandqrt &&
3027 ID0 != Intrinsic::hexagon_V6_vandqrt_128B)
3028 break;
3029 Value *Bytes = Op0->getArgOperand(1), *Mask = II->getArgOperand(1);
3030 uint64_t Bytes1 = computeKnownBits(Bytes, 0, Op0).One.getZExtValue();
3031 uint64_t Mask1 = computeKnownBits(Mask, 0, II).One.getZExtValue();
3032 // Check if every byte has common bits in Bytes and Mask.
3033 uint64_t C = Bytes1 & Mask1;
3034 if ((C & 0xFF) && (C & 0xFF00) && (C & 0xFF0000) && (C & 0xFF000000))
3035 return replaceInstUsesWith(*II, Op0->getArgOperand(0));
3036 }
3037 break;
3038 }
3039 case Intrinsic::stackrestore: {
3040 enum class ClassifyResult {
3041 None,
3042 Alloca,
3043 StackRestore,
3044 CallWithSideEffects,
3045 };
3046 auto Classify = [](const Instruction *I) {
3047 if (isa<AllocaInst>(I))
3048 return ClassifyResult::Alloca;
3049
3050 if (auto *CI = dyn_cast<CallInst>(I)) {
3051 if (auto *II = dyn_cast<IntrinsicInst>(CI)) {
3052 if (II->getIntrinsicID() == Intrinsic::stackrestore)
3053 return ClassifyResult::StackRestore;
3054
3055 if (II->mayHaveSideEffects())
3056 return ClassifyResult::CallWithSideEffects;
3057 } else {
3058 // Consider all non-intrinsic calls to be side effects
3059 return ClassifyResult::CallWithSideEffects;
3060 }
3061 }
3062
3063 return ClassifyResult::None;
3064 };
3065
3066 // If the stacksave and the stackrestore are in the same BB, and there is
3067 // no intervening call, alloca, or stackrestore of a different stacksave,
3068 // remove the restore. This can happen when variable allocas are DCE'd.
3069 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {
3070 if (SS->getIntrinsicID() == Intrinsic::stacksave &&
3071 SS->getParent() == II->getParent()) {
3072 BasicBlock::iterator BI(SS);
3073 bool CannotRemove = false;
3074 for (++BI; &*BI != II; ++BI) {
3075 switch (Classify(&*BI)) {
3076 case ClassifyResult::None:
3077 // So far so good, look at next instructions.
3078 break;
3079
3080 case ClassifyResult::StackRestore:
3081 // If we found an intervening stackrestore for a different
3082 // stacksave, we can't remove the stackrestore. Otherwise, continue.
3083 if (cast<IntrinsicInst>(*BI).getArgOperand(0) != SS)
3084 CannotRemove = true;
3085 break;
3086
3087 case ClassifyResult::Alloca:
3088 case ClassifyResult::CallWithSideEffects:
3089 // If we found an alloca, a non-intrinsic call, or an intrinsic
3090 // call with side effects, we can't remove the stackrestore.
3091 CannotRemove = true;
3092 break;
3093 }
3094 if (CannotRemove)
3095 break;
3096 }
3097
3098 if (!CannotRemove)
3099 return eraseInstFromFunction(CI);
3100 }
3101 }
3102
3103 // Scan down this block to see if there is another stack restore in the
3104 // same block without an intervening call/alloca.
3106 Instruction *TI = II->getParent()->getTerminator();
3107 bool CannotRemove = false;
3108 for (++BI; &*BI != TI; ++BI) {
3109 switch (Classify(&*BI)) {
3110 case ClassifyResult::None:
3111 // So far so good, look at next instructions.
3112 break;
3113
3114 case ClassifyResult::StackRestore:
3115 // If there is a stackrestore below this one, remove this one.
3116 return eraseInstFromFunction(CI);
3117
3118 case ClassifyResult::Alloca:
3119 case ClassifyResult::CallWithSideEffects:
3120 // If we found an alloca, a non-intrinsic call, or an intrinsic call
3121 // with side effects (such as llvm.stacksave and llvm.read_register),
3122 // we can't remove the stack restore.
3123 CannotRemove = true;
3124 break;
3125 }
3126 if (CannotRemove)
3127 break;
3128 }
3129
3130 // If the stack restore is in a return, resume, or unwind block and if there
3131 // are no allocas or calls between the restore and the return, nuke the
3132 // restore.
3133 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<ResumeInst>(TI)))
3134 return eraseInstFromFunction(CI);
3135 break;
3136 }
3137 case Intrinsic::lifetime_end:
3138 // Asan needs to poison memory to detect invalid access which is possible
3139 // even for empty lifetime range.
3140 if (II->getFunction()->hasFnAttribute(Attribute::SanitizeAddress) ||
3141 II->getFunction()->hasFnAttribute(Attribute::SanitizeMemory) ||
3142 II->getFunction()->hasFnAttribute(Attribute::SanitizeHWAddress))
3143 break;
3144
3145 if (removeTriviallyEmptyRange(*II, *this, [](const IntrinsicInst &I) {
3146 return I.getIntrinsicID() == Intrinsic::lifetime_start;
3147 }))
3148 return nullptr;
3149 break;
3150 case Intrinsic::assume: {
3151 Value *IIOperand = II->getArgOperand(0);
3153 II->getOperandBundlesAsDefs(OpBundles);
3154
3155 /// This will remove the boolean Condition from the assume given as
3156 /// argument and remove the assume if it becomes useless.
3157 /// always returns nullptr for use as a return values.
3158 auto RemoveConditionFromAssume = [&](Instruction *Assume) -> Instruction * {
3159 assert(isa<AssumeInst>(Assume));
3160 if (isAssumeWithEmptyBundle(*cast<AssumeInst>(II)))
3161 return eraseInstFromFunction(CI);
3162 replaceUse(II->getOperandUse(0), ConstantInt::getTrue(II->getContext()));
3163 return nullptr;
3164 };
3165 // Remove an assume if it is followed by an identical assume.
3166 // TODO: Do we need this? Unless there are conflicting assumptions, the
3167 // computeKnownBits(IIOperand) below here eliminates redundant assumes.
3168 Instruction *Next = II->getNextNonDebugInstruction();
3169 if (match(Next, m_Intrinsic<Intrinsic::assume>(m_Specific(IIOperand))))
3170 return RemoveConditionFromAssume(Next);
3171
3172 // Canonicalize assume(a && b) -> assume(a); assume(b);
3173 // Note: New assumption intrinsics created here are registered by
3174 // the InstCombineIRInserter object.
3175 FunctionType *AssumeIntrinsicTy = II->getFunctionType();
3176 Value *AssumeIntrinsic = II->getCalledOperand();
3177 Value *A, *B;
3178 if (match(IIOperand, m_LogicalAnd(m_Value(A), m_Value(B)))) {
3179 Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic, A, OpBundles,
3180 II->getName());
3181 Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic, B, II->getName());
3182 return eraseInstFromFunction(*II);
3183 }
3184 // assume(!(a || b)) -> assume(!a); assume(!b);
3185 if (match(IIOperand, m_Not(m_LogicalOr(m_Value(A), m_Value(B))))) {
3186 Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic,
3187 Builder.CreateNot(A), OpBundles, II->getName());
3188 Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic,
3189 Builder.CreateNot(B), II->getName());
3190 return eraseInstFromFunction(*II);
3191 }
3192
3193 // assume( (load addr) != null ) -> add 'nonnull' metadata to load
3194 // (if assume is valid at the load)
3197 m_Zero())) &&
3198 LHS->getOpcode() == Instruction::Load &&
3199 LHS->getType()->isPointerTy() &&
3201 MDNode *MD = MDNode::get(II->getContext(), {});
3202 LHS->setMetadata(LLVMContext::MD_nonnull, MD);
3203 LHS->setMetadata(LLVMContext::MD_noundef, MD);
3204 return RemoveConditionFromAssume(II);
3205
3206 // TODO: apply nonnull return attributes to calls and invokes
3207 // TODO: apply range metadata for range check patterns?
3208 }
3209
3210 // Separate storage assumptions apply to the underlying allocations, not any
3211 // particular pointer within them. When evaluating the hints for AA purposes
3212 // we getUnderlyingObject them; by precomputing the answers here we can
3213 // avoid having to do so repeatedly there.
3214 for (unsigned Idx = 0; Idx < II->getNumOperandBundles(); Idx++) {
3215 OperandBundleUse OBU = II->getOperandBundleAt(Idx);
3216 if (OBU.getTagName() == "separate_storage") {
3217 assert(OBU.Inputs.size() == 2);
3218 auto MaybeSimplifyHint = [&](const Use &U) {
3219 Value *Hint = U.get();
3220 // Not having a limit is safe because InstCombine removes unreachable
3221 // code.
3222 Value *UnderlyingObject = getUnderlyingObject(Hint, /*MaxLookup*/ 0);
3223 if (Hint != UnderlyingObject)
3224 replaceUse(const_cast<Use &>(U), UnderlyingObject);
3225 };
3226 MaybeSimplifyHint(OBU.Inputs[0]);
3227 MaybeSimplifyHint(OBU.Inputs[1]);
3228 }
3229 }
3230
3231 // Convert nonnull assume like:
3232 // %A = icmp ne i32* %PTR, null
3233 // call void @llvm.assume(i1 %A)
3234 // into
3235 // call void @llvm.assume(i1 true) [ "nonnull"(i32* %PTR) ]
3237 match(IIOperand,
3239 A->getType()->isPointerTy()) {
3240 if (auto *Replacement = buildAssumeFromKnowledge(
3241 {RetainedKnowledge{Attribute::NonNull, 0, A}}, Next, &AC, &DT)) {
3242
3243 Replacement->insertBefore(Next);
3244 AC.registerAssumption(Replacement);
3245 return RemoveConditionFromAssume(II);
3246 }
3247 }
3248
3249 // Convert alignment assume like:
3250 // %B = ptrtoint i32* %A to i64
3251 // %C = and i64 %B, Constant
3252 // %D = icmp eq i64 %C, 0
3253 // call void @llvm.assume(i1 %D)
3254 // into
3255 // call void @llvm.assume(i1 true) [ "align"(i32* [[A]], i64 Constant + 1)]
3256 uint64_t AlignMask;
3258 match(IIOperand,
3260 m_And(m_Value(A), m_ConstantInt(AlignMask)),
3261 m_Zero()))) {
3262 if (isPowerOf2_64(AlignMask + 1)) {
3263 uint64_t Offset = 0;
3265 if (match(A, m_PtrToInt(m_Value(A)))) {
3266 /// Note: this doesn't preserve the offset information but merges
3267 /// offset and alignment.
3268 /// TODO: we can generate a GEP instead of merging the alignment with
3269 /// the offset.
3270 RetainedKnowledge RK{Attribute::Alignment,
3271 (unsigned)MinAlign(Offset, AlignMask + 1), A};
3272 if (auto *Replacement =
3273 buildAssumeFromKnowledge(RK, Next, &AC, &DT)) {
3274
3275 Replacement->insertAfter(II);
3276 AC.registerAssumption(Replacement);
3277 }
3278 return RemoveConditionFromAssume(II);
3279 }
3280 }
3281 }
3282
3283 /// Canonicalize Knowledge in operand bundles.
3284 if (EnableKnowledgeRetention && II->hasOperandBundles()) {
3285 for (unsigned Idx = 0; Idx < II->getNumOperandBundles(); Idx++) {
3286 auto &BOI = II->bundle_op_info_begin()[Idx];
3288 llvm::getKnowledgeFromBundle(cast<AssumeInst>(*II), BOI);
3289 if (BOI.End - BOI.Begin > 2)
3290 continue; // Prevent reducing knowledge in an align with offset since
3291 // extracting a RetainedKnowledge from them looses offset
3292 // information
3293 RetainedKnowledge CanonRK =
3294 llvm::simplifyRetainedKnowledge(cast<AssumeInst>(II), RK,
3296 &getDominatorTree());
3297 if (CanonRK == RK)
3298 continue;
3299 if (!CanonRK) {
3300 if (BOI.End - BOI.Begin > 0) {
3301 Worklist.pushValue(II->op_begin()[BOI.Begin]);
3302 Value::dropDroppableUse(II->op_begin()[BOI.Begin]);
3303 }
3304 continue;
3305 }
3306 assert(RK.AttrKind == CanonRK.AttrKind);
3307 if (BOI.End - BOI.Begin > 0)
3308 II->op_begin()[BOI.Begin].set(CanonRK.WasOn);
3309 if (BOI.End - BOI.Begin > 1)
3310 II->op_begin()[BOI.Begin + 1].set(ConstantInt::get(
3311 Type::getInt64Ty(II->getContext()), CanonRK.ArgValue));
3312 if (RK.WasOn)
3314 return II;
3315 }
3316 }
3317
3318 // If there is a dominating assume with the same condition as this one,
3319 // then this one is redundant, and should be removed.
3320 KnownBits Known(1);
3321 computeKnownBits(IIOperand, Known, 0, II);
3322 if (Known.isAllOnes() && isAssumeWithEmptyBundle(cast<AssumeInst>(*II)))
3323 return eraseInstFromFunction(*II);
3324
3325 // assume(false) is unreachable.
3326 if (match(IIOperand, m_CombineOr(m_Zero(), m_Undef()))) {
3328 return eraseInstFromFunction(*II);
3329 }
3330
3331 // Update the cache of affected values for this assumption (we might be
3332 // here because we just simplified the condition).
3333 AC.updateAffectedValues(cast<AssumeInst>(II));
3334 break;
3335 }
3336 case Intrinsic::experimental_guard: {
3337 // Is this guard followed by another guard? We scan forward over a small
3338 // fixed window of instructions to handle common cases with conditions
3339 // computed between guards.
3340 Instruction *NextInst = II->getNextNonDebugInstruction();
3341 for (unsigned i = 0; i < GuardWideningWindow; i++) {
3342 // Note: Using context-free form to avoid compile time blow up
3343 if (!isSafeToSpeculativelyExecute(NextInst))
3344 break;
3345 NextInst = NextInst->getNextNonDebugInstruction();
3346 }
3347 Value *NextCond = nullptr;
3348 if (match(NextInst,
3349 m_Intrinsic<Intrinsic::experimental_guard>(m_Value(NextCond)))) {
3350 Value *CurrCond = II->getArgOperand(0);
3351
3352 // Remove a guard that it is immediately preceded by an identical guard.
3353 // Otherwise canonicalize guard(a); guard(b) -> guard(a & b).
3354 if (CurrCond != NextCond) {
3355 Instruction *MoveI = II->getNextNonDebugInstruction();
3356 while (MoveI != NextInst) {
3357 auto *Temp = MoveI;
3358 MoveI = MoveI->getNextNonDebugInstruction();
3359 Temp->moveBefore(II);
3360 }
3361 replaceOperand(*II, 0, Builder.CreateAnd(CurrCond, NextCond));
3362 }
3363 eraseInstFromFunction(*NextInst);
3364 return II;
3365 }
3366 break;
3367 }
3368 case Intrinsic::vector_insert: {
3369 Value *Vec = II->getArgOperand(0);
3370 Value *SubVec = II->getArgOperand(1);
3371 Value *Idx = II->getArgOperand(2);
3372 auto *DstTy = dyn_cast<FixedVectorType>(II->getType());
3373 auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType());
3374 auto *SubVecTy = dyn_cast<FixedVectorType>(SubVec->getType());
3375
3376 // Only canonicalize if the destination vector, Vec, and SubVec are all
3377 // fixed vectors.
3378 if (DstTy && VecTy && SubVecTy) {
3379 unsigned DstNumElts = DstTy->getNumElements();
3380 unsigned VecNumElts = VecTy->getNumElements();
3381 unsigned SubVecNumElts = SubVecTy->getNumElements();
3382 unsigned IdxN = cast<ConstantInt>(Idx)->getZExtValue();
3383
3384 // An insert that entirely overwrites Vec with SubVec is a nop.
3385 if (VecNumElts == SubVecNumElts)
3386 return replaceInstUsesWith(CI, SubVec);
3387
3388 // Widen SubVec into a vector of the same width as Vec, since
3389 // shufflevector requires the two input vectors to be the same width.
3390 // Elements beyond the bounds of SubVec within the widened vector are
3391 // undefined.
3392 SmallVector<int, 8> WidenMask;
3393 unsigned i;
3394 for (i = 0; i != SubVecNumElts; ++i)
3395 WidenMask.push_back(i);
3396 for (; i != VecNumElts; ++i)
3397 WidenMask.push_back(PoisonMaskElem);
3398
3399 Value *WidenShuffle = Builder.CreateShuffleVector(SubVec, WidenMask);
3400
3402 for (unsigned i = 0; i != IdxN; ++i)
3403 Mask.push_back(i);
3404 for (unsigned i = DstNumElts; i != DstNumElts + SubVecNumElts; ++i)
3405 Mask.push_back(i);
3406 for (unsigned i = IdxN + SubVecNumElts; i != DstNumElts; ++i)
3407 Mask.push_back(i);
3408
3409 Value *Shuffle = Builder.CreateShuffleVector(Vec, WidenShuffle, Mask);
3410 return replaceInstUsesWith(CI, Shuffle);
3411 }
3412 break;
3413 }
3414 case Intrinsic::vector_extract: {
3415 Value *Vec = II->getArgOperand(0);
3416 Value *Idx = II->getArgOperand(1);
3417
3418 Type *ReturnType = II->getType();
3419 // (extract_vector (insert_vector InsertTuple, InsertValue, InsertIdx),
3420 // ExtractIdx)
3421 unsigned ExtractIdx = cast<ConstantInt>(Idx)->getZExtValue();
3422 Value *InsertTuple, *InsertIdx, *InsertValue;
3423 if (match(Vec, m_Intrinsic<Intrinsic::vector_insert>(m_Value(InsertTuple),
3424 m_Value(InsertValue),
3425 m_Value(InsertIdx))) &&
3426 InsertValue->getType() == ReturnType) {
3427 unsigned Index = cast<ConstantInt>(InsertIdx)->getZExtValue();
3428 // Case where we get the same index right after setting it.
3429 // extract.vector(insert.vector(InsertTuple, InsertValue, Idx), Idx) -->
3430 // InsertValue
3431 if (ExtractIdx == Index)
3432 return replaceInstUsesWith(CI, InsertValue);
3433 // If we are getting a different index than what was set in the
3434 // insert.vector intrinsic. We can just set the input tuple to the one up
3435 // in the chain. extract.vector(insert.vector(InsertTuple, InsertValue,
3436 // InsertIndex), ExtractIndex)
3437 // --> extract.vector(InsertTuple, ExtractIndex)
3438 else
3439 return replaceOperand(CI, 0, InsertTuple);
3440 }
3441
3442 auto *DstTy = dyn_cast<VectorType>(ReturnType);
3443 auto *VecTy = dyn_cast<VectorType>(Vec->getType());
3444
3445 if (DstTy && VecTy) {
3446 auto DstEltCnt = DstTy->getElementCount();
3447 auto VecEltCnt = VecTy->getElementCount();
3448 unsigned IdxN = cast<ConstantInt>(Idx)->getZExtValue();
3449
3450 // Extracting the entirety of Vec is a nop.
3451 if (DstEltCnt == VecTy->getElementCount()) {
3452 replaceInstUsesWith(CI, Vec);
3453 return eraseInstFromFunction(CI);
3454 }
3455
3456 // Only canonicalize to shufflevector if the destination vector and
3457 // Vec are fixed vectors.
3458 if (VecEltCnt.isScalable() || DstEltCnt.isScalable())
3459 break;
3460
3462 for (unsigned i = 0; i != DstEltCnt.getKnownMinValue(); ++i)
3463 Mask.push_back(IdxN + i);
3464
3465 Value *Shuffle = Builder.CreateShuffleVector(Vec, Mask);
3466 return replaceInstUsesWith(CI, Shuffle);
3467 }
3468 break;
3469 }
3470 case Intrinsic::vector_reverse: {
3471 Value *BO0, *BO1, *X, *Y;
3472 Value *Vec = II->getArgOperand(0);
3473 if (match(Vec, m_OneUse(m_BinOp(m_Value(BO0), m_Value(BO1))))) {
3474 auto *OldBinOp = cast<BinaryOperator>(Vec);
3475 if (match(BO0, m_VecReverse(m_Value(X)))) {
3476 // rev(binop rev(X), rev(Y)) --> binop X, Y
3477 if (match(BO1, m_VecReverse(m_Value(Y))))
3479 OldBinOp->getOpcode(), X, Y,
3480 OldBinOp, OldBinOp->getName(),
3481 II->getIterator()));
3482 // rev(binop rev(X), BO1Splat) --> binop X, BO1Splat
3483 if (isSplatValue(BO1))
3485 OldBinOp->getOpcode(), X, BO1,
3486 OldBinOp, OldBinOp->getName(),
3487 II->getIterator()));
3488 }
3489 // rev(binop BO0Splat, rev(Y)) --> binop BO0Splat, Y
3490 if (match(BO1, m_VecReverse(m_Value(Y))) && isSplatValue(BO0))
3491 return replaceInstUsesWith(CI,
3493 OldBinOp->getOpcode(), BO0, Y, OldBinOp,
3494 OldBinOp->getName(), II->getIterator()));
3495 }
3496 // rev(unop rev(X)) --> unop X
3497 if (match(Vec, m_OneUse(m_UnOp(m_VecReverse(m_Value(X)))))) {
3498 auto *OldUnOp = cast<UnaryOperator>(Vec);
3500 OldUnOp->getOpcode(), X, OldUnOp, OldUnOp->getName(),
3501 II->getIterator());
3502 return replaceInstUsesWith(CI, NewUnOp);
3503 }
3504 break;
3505 }
3506 case Intrinsic::vector_reduce_or:
3507 case Intrinsic::vector_reduce_and: {
3508 // Canonicalize logical or/and reductions:
3509 // Or reduction for i1 is represented as:
3510 // %val = bitcast <ReduxWidth x i1> to iReduxWidth
3511 // %res = cmp ne iReduxWidth %val, 0
3512 // And reduction for i1 is represented as:
3513 // %val = bitcast <ReduxWidth x i1> to iReduxWidth
3514 // %res = cmp eq iReduxWidth %val, 11111
3515 Value *Arg = II->getArgOperand(0);
3516 Value *Vect;
3517
3518 if (Value *NewOp =
3519 simplifyReductionOperand(Arg, /*CanReorderLanes=*/true)) {
3520 replaceUse(II->getOperandUse(0), NewOp);
3521 return II;
3522 }
3523
3524 if (match(Arg, m_ZExtOrSExtOrSelf(m_Value(Vect)))) {
3525 if (auto *FTy = dyn_cast<FixedVectorType>(Vect->getType()))
3526 if (FTy->getElementType() == Builder.getInt1Ty()) {
3528 Vect, Builder.getIntNTy(FTy->getNumElements()));
3529 if (IID == Intrinsic::vector_reduce_and) {
3530 Res = Builder.CreateICmpEQ(
3532 } else {
3533 assert(IID == Intrinsic::vector_reduce_or &&
3534 "Expected or reduction.");
3535 Res = Builder.CreateIsNotNull(Res);
3536 }
3537 if (Arg != Vect)
3538 Res = Builder.CreateCast(cast<CastInst>(Arg)->getOpcode(), Res,
3539 II->getType());
3540 return replaceInstUsesWith(CI, Res);
3541 }
3542 }
3543 [[fallthrough]];
3544 }
3545 case Intrinsic::vector_reduce_add: {
3546 if (IID == Intrinsic::vector_reduce_add) {
3547 // Convert vector_reduce_add(ZExt(<n x i1>)) to
3548 // ZExtOrTrunc(ctpop(bitcast <n x i1> to in)).
3549 // Convert vector_reduce_add(SExt(<n x i1>)) to
3550 // -ZExtOrTrunc(ctpop(bitcast <n x i1> to in)).
3551 // Convert vector_reduce_add(<n x i1>) to
3552 // Trunc(ctpop(bitcast <n x i1> to in)).
3553 Value *Arg = II->getArgOperand(0);
3554 Value *Vect;
3555
3556 if (Value *NewOp =
3557 simplifyReductionOperand(Arg, /*CanReorderLanes=*/true)) {
3558 replaceUse(II->getOperandUse(0), NewOp);
3559 return II;
3560 }
3561
3562 if (match(Arg, m_ZExtOrSExtOrSelf(m_Value(Vect)))) {
3563 if (auto *FTy = dyn_cast<FixedVectorType>(Vect->getType()))
3564 if (FTy->getElementType() == Builder.getInt1Ty()) {
3566 Vect, Builder.getIntNTy(FTy->getNumElements()));
3567 Value *Res = Builder.CreateUnaryIntrinsic(Intrinsic::ctpop, V);
3568 if (Res->getType() != II->getType())
3569 Res = Builder.CreateZExtOrTrunc(Res, II->getType());
3570 if (Arg != Vect &&
3571 cast<Instruction>(Arg)->getOpcode() == Instruction::SExt)
3572 Res = Builder.CreateNeg(Res);
3573 return replaceInstUsesWith(CI, Res);
3574 }
3575 }
3576 }
3577 [[fallthrough]];
3578 }
3579 case Intrinsic::vector_reduce_xor: {
3580 if (IID == Intrinsic::vector_reduce_xor) {
3581 // Exclusive disjunction reduction over the vector with
3582 // (potentially-extended) i1 element type is actually a
3583 // (potentially-extended) arithmetic `add` reduction over the original
3584 // non-extended value:
3585 // vector_reduce_xor(?ext(<n x i1>))
3586 // -->
3587 // ?ext(vector_reduce_add(<n x i1>))
3588 Value *Arg = II->getArgOperand(0);
3589 Value *Vect;
3590
3591 if (Value *NewOp =
3592 simplifyReductionOperand(Arg, /*CanReorderLanes=*/true)) {
3593 replaceUse(II->getOperandUse(0), NewOp);
3594 return II;
3595 }
3596
3597 if (match(Arg, m_ZExtOrSExtOrSelf(m_Value(Vect)))) {
3598 if (auto *VTy = dyn_cast<VectorType>(Vect->getType()))
3599 if (VTy->getElementType() == Builder.getInt1Ty()) {
3600 Value *Res = Builder.CreateAddReduce(Vect);
3601 if (Arg != Vect)
3602 Res = Builder.CreateCast(cast<CastInst>(Arg)->getOpcode(), Res,
3603 II->getType());
3604 return replaceInstUsesWith(CI, Res);
3605 }
3606 }
3607 }
3608 [[fallthrough]];
3609 }
3610 case Intrinsic::vector_reduce_mul: {
3611 if (IID == Intrinsic::vector_reduce_mul) {
3612 // Multiplicative reduction over the vector with (potentially-extended)
3613 // i1 element type is actually a (potentially zero-extended)
3614 // logical `and` reduction over the original non-extended value:
3615 // vector_reduce_mul(?ext(<n x i1>))
3616 // -->
3617 // zext(vector_reduce_and(<n x i1>))
3618 Value *Arg = II->getArgOperand(0);
3619 Value *Vect;
3620
3621 if (Value *NewOp =
3622 simplifyReductionOperand(Arg, /*CanReorderLanes=*/true)) {
3623 replaceUse(II->getOperandUse(0), NewOp);
3624 return II;
3625 }
3626
3627 if (match(Arg, m_ZExtOrSExtOrSelf(m_Value(Vect)))) {
3628 if (auto *VTy = dyn_cast<VectorType>(Vect->getType()))
3629 if (VTy->getElementType() == Builder.getInt1Ty()) {
3630 Value *Res = Builder.CreateAndReduce(Vect);
3631 if (Res->getType() != II->getType())
3632 Res = Builder.CreateZExt(Res, II->getType());
3633 return replaceInstUsesWith(CI, Res);
3634 }
3635 }
3636 }
3637 [[fallthrough]];
3638 }
3639 case Intrinsic::vector_reduce_umin:
3640 case Intrinsic::vector_reduce_umax: {
3641 if (IID == Intrinsic::vector_reduce_umin ||
3642 IID == Intrinsic::vector_reduce_umax) {
3643 // UMin/UMax reduction over the vector with (potentially-extended)
3644 // i1 element type is actually a (potentially-extended)
3645 // logical `and`/`or` reduction over the original non-extended value:
3646 // vector_reduce_u{min,max}(?ext(<n x i1>))
3647 // -->
3648 // ?ext(vector_reduce_{and,or}(<n x i1>))
3649 Value *Arg = II->getArgOperand(0);
3650 Value *Vect;
3651
3652 if (Value *NewOp =
3653 simplifyReductionOperand(Arg, /*CanReorderLanes=*/true)) {
3654 replaceUse(II->getOperandUse(0), NewOp);
3655 return II;
3656 }
3657
3658 if (match(Arg, m_ZExtOrSExtOrSelf(m_Value(Vect)))) {
3659 if (auto *VTy = dyn_cast<VectorType>(Vect->getType()))
3660 if (VTy->getElementType() == Builder.getInt1Ty()) {
3661 Value *Res = IID == Intrinsic::vector_reduce_umin
3662 ? Builder.CreateAndReduce(Vect)
3663 : Builder.CreateOrReduce(Vect);
3664 if (Arg != Vect)
3665 Res = Builder.CreateCast(cast<CastInst>(Arg)->getOpcode(), Res,
3666 II->getType());
3667 return replaceInstUsesWith(CI, Res);
3668 }
3669 }
3670 }
3671 [[fallthrough]];
3672 }
3673 case Intrinsic::vector_reduce_smin:
3674 case Intrinsic::vector_reduce_smax: {
3675 if (IID == Intrinsic::vector_reduce_smin ||
3676 IID == Intrinsic::vector_reduce_smax) {
3677 // SMin/SMax reduction over the vector with (potentially-extended)
3678 // i1 element type is actually a (potentially-extended)
3679 // logical `and`/`or` reduction over the original non-extended value:
3680 // vector_reduce_s{min,max}(<n x i1>)
3681 // -->
3682 // vector_reduce_{or,and}(<n x i1>)
3683 // and
3684 // vector_reduce_s{min,max}(sext(<n x i1>))
3685 // -->
3686 // sext(vector_reduce_{or,and}(<n x i1>))
3687 // and
3688 // vector_reduce_s{min,max}(zext(<n x i1>))
3689 // -->
3690 // zext(vector_reduce_{and,or}(<n x i1>))
3691 Value *Arg = II->getArgOperand(0);
3692 Value *Vect;
3693
3694 if (Value *NewOp =
3695 simplifyReductionOperand(Arg, /*CanReorderLanes=*/true)) {
3696 replaceUse(II->getOperandUse(0), NewOp);
3697 return II;
3698 }
3699
3700 if (match(Arg, m_ZExtOrSExtOrSelf(m_Value(Vect)))) {
3701 if (auto *VTy = dyn_cast<VectorType>(Vect->getType()))
3702 if (VTy->getElementType() == Builder.getInt1Ty()) {
3703 Instruction::CastOps ExtOpc = Instruction::CastOps::CastOpsEnd;
3704 if (Arg != Vect)
3705 ExtOpc = cast<CastInst>(Arg)->getOpcode();
3706 Value *Res = ((IID == Intrinsic::vector_reduce_smin) ==
3707 (ExtOpc == Instruction::CastOps::ZExt))
3708 ? Builder.CreateAndReduce(Vect)
3709 : Builder.CreateOrReduce(Vect);
3710 if (Arg != Vect)
3711 Res = Builder.CreateCast(ExtOpc, Res, II->getType());
3712 return replaceInstUsesWith(CI, Res);
3713 }
3714 }
3715 }
3716 [[fallthrough]];
3717 }
3718 case Intrinsic::vector_reduce_fmax:
3719 case Intrinsic::vector_reduce_fmin:
3720 case Intrinsic::vector_reduce_fadd:
3721 case Intrinsic::vector_reduce_fmul: {
3722 bool CanReorderLanes = (IID != Intrinsic::vector_reduce_fadd &&
3723 IID != Intrinsic::vector_reduce_fmul) ||
3724 II->hasAllowReassoc();
3725 const unsigned ArgIdx = (IID == Intrinsic::vector_reduce_fadd ||
3726 IID == Intrinsic::vector_reduce_fmul)
3727 ? 1
3728 : 0;
3729 Value *Arg = II->getArgOperand(ArgIdx);
3730 if (Value *NewOp = simplifyReductionOperand(Arg, CanReorderLanes)) {
3731 replaceUse(II->getOperandUse(ArgIdx), NewOp);
3732 return nullptr;
3733 }
3734 break;
3735 }
3736 case Intrinsic::is_fpclass: {
3737 if (Instruction *I = foldIntrinsicIsFPClass(*II))
3738 return I;
3739 break;
3740 }
3741 case Intrinsic::threadlocal_address: {
3742 Align MinAlign = getKnownAlignment(II->getArgOperand(0), DL, II, &AC, &DT);
3743 MaybeAlign Align = II->getRetAlign();
3744 if (MinAlign > Align.valueOrOne()) {
3745 II->addRetAttr(Attribute::getWithAlignment(II->getContext(), MinAlign));
3746 return II;
3747 }
3748 break;
3749 }
3750 default: {
3751 // Handle target specific intrinsics
3752 std::optional<Instruction *> V = targetInstCombineIntrinsic(*II);
3753 if (V)
3754 return *V;
3755 break;
3756 }
3757 }
3758
3759 // Try to fold intrinsic into select operands. This is legal if:
3760 // * The intrinsic is speculatable.
3761 // * The select condition is not a vector, or the intrinsic does not
3762 // perform cross-lane operations.
3765 for (Value *Op : II->args())
3766 if (auto *Sel = dyn_cast<SelectInst>(Op))
3767 if (Instruction *R = FoldOpIntoSelect(*II, Sel))
3768 return R;
3769
3771 return Shuf;
3772
3773 // Some intrinsics (like experimental_gc_statepoint) can be used in invoke
3774 // context, so it is handled in visitCallBase and we should trigger it.
3775 return visitCallBase(*II);
3776}
3777
3778// Fence instruction simplification
3780 auto *NFI = dyn_cast<FenceInst>(FI.getNextNonDebugInstruction());
3781 // This check is solely here to handle arbitrary target-dependent syncscopes.
3782 // TODO: Can remove if does not matter in practice.
3783 if (NFI && FI.isIdenticalTo(NFI))
3784 return eraseInstFromFunction(FI);
3785
3786 // Returns true if FI1 is identical or stronger fence than FI2.
3787 auto isIdenticalOrStrongerFence = [](FenceInst *FI1, FenceInst *FI2) {
3788 auto FI1SyncScope = FI1->getSyncScopeID();
3789 // Consider same scope, where scope is global or single-thread.
3790 if (FI1SyncScope != FI2->getSyncScopeID() ||
3791 (FI1SyncScope != SyncScope::System &&
3792 FI1SyncScope != SyncScope::SingleThread))
3793 return false;
3794
3795 return isAtLeastOrStrongerThan(FI1->getOrdering(), FI2->getOrdering());
3796 };
3797 if (NFI && isIdenticalOrStrongerFence(NFI, &FI))
3798 return eraseInstFromFunction(FI);
3799
3800 if (auto *PFI = dyn_cast_or_null<FenceInst>(FI.getPrevNonDebugInstruction()))
3801 if (isIdenticalOrStrongerFence(PFI, &FI))
3802 return eraseInstFromFunction(FI);
3803 return nullptr;
3804}
3805
3806// InvokeInst simplification
3808 return visitCallBase(II);
3809}
3810
3811// CallBrInst simplification
3813 return visitCallBase(CBI);
3814}
3815
3816Instruction *InstCombinerImpl::tryOptimizeCall(CallInst *CI) {
3817 if (!CI->getCalledFunction()) return nullptr;
3818
3819 // Skip optimizing notail and musttail calls so
3820 // LibCallSimplifier::optimizeCall doesn't have to preserve those invariants.
3821 // LibCallSimplifier::optimizeCall should try to preserve tail calls though.
3822 if (CI->isMustTailCall() || CI->isNoTailCall())
3823 return nullptr;
3824
3825 auto InstCombineRAUW = [this](Instruction *From, Value *With) {
3826 replaceInstUsesWith(*From, With);
3827 };
3828 auto InstCombineErase = [this](Instruction *I) {
3830 };
3831 LibCallSimplifier Simplifier(DL, &TLI, &DT, &DC, &AC, ORE, BFI, PSI,
3832 InstCombineRAUW, InstCombineErase);
3833 if (Value *With = Simplifier.optimizeCall(CI, Builder)) {
3834 ++NumSimplified;
3835 return CI->use_empty() ? CI : replaceInstUsesWith(*CI, With);
3836 }
3837
3838 return nullptr;
3839}
3840
3842 // Strip off at most one level of pointer casts, looking for an alloca. This
3843 // is good enough in practice and simpler than handling any number of casts.
3844 Value *Underlying = TrampMem->stripPointerCasts();
3845 if (Underlying != TrampMem &&
3846 (!Underlying->hasOneUse() || Underlying->user_back() != TrampMem))
3847 return nullptr;
3848 if (!isa<AllocaInst>(Underlying))
3849 return nullptr;
3850
3851 IntrinsicInst *InitTrampoline = nullptr;
3852 for (User *U : TrampMem->users()) {
3853 IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
3854 if (!II)
3855 return nullptr;
3856 if (II->getIntrinsicID() == Intrinsic::init_trampoline) {
3857 if (InitTrampoline)
3858 // More than one init_trampoline writes to this value. Give up.
3859 return nullptr;
3860 InitTrampoline = II;
3861 continue;
3862 }
3863 if (II->getIntrinsicID() == Intrinsic::adjust_trampoline)
3864 // Allow any number of calls to adjust.trampoline.
3865 continue;
3866 return nullptr;
3867 }
3868
3869 // No call to init.trampoline found.
3870 if (!InitTrampoline)
3871 return nullptr;
3872
3873 // Check that the alloca is being used in the expected way.
3874 if (InitTrampoline->getOperand(0) != TrampMem)
3875 return nullptr;
3876
3877 return InitTrampoline;
3878}
3879
3881 Value *TrampMem) {
3882 // Visit all the previous instructions in the basic block, and try to find a
3883 // init.trampoline which has a direct path to the adjust.trampoline.
3884 for (BasicBlock::iterator I = AdjustTramp->getIterator(),
3885 E = AdjustTramp->getParent()->begin();
3886 I != E;) {
3887 Instruction *Inst = &*--I;
3888 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
3889 if (II->getIntrinsicID() == Intrinsic::init_trampoline &&
3890 II->getOperand(0) == TrampMem)
3891 return II;
3892 if (Inst->mayWriteToMemory())
3893 return nullptr;
3894 }
3895 return nullptr;
3896}
3897
3898// Given a call to llvm.adjust.trampoline, find and return the corresponding
3899// call to llvm.init.trampoline if the call to the trampoline can be optimized
3900// to a direct call to a function. Otherwise return NULL.
3902 Callee = Callee->stripPointerCasts();
3903 IntrinsicInst *AdjustTramp = dyn_cast<IntrinsicInst>(Callee);
3904 if (!AdjustTramp ||
3905 AdjustTramp->getIntrinsicID() != Intrinsic::adjust_trampoline)
3906 return nullptr;
3907
3908 Value *TrampMem = AdjustTramp->getOperand(0);
3909
3911 return IT;
3912 if (IntrinsicInst *IT = findInitTrampolineFromBB(AdjustTramp, TrampMem))
3913 return IT;
3914 return nullptr;
3915}
3916
3917bool InstCombinerImpl::annotateAnyAllocSite(CallBase &Call,
3918 const TargetLibraryInfo *TLI) {
3919 // Note: We only handle cases which can't be driven from generic attributes
3920 // here. So, for example, nonnull and noalias (which are common properties
3921 // of some allocation functions) are expected to be handled via annotation
3922 // of the respective allocator declaration with generic attributes.
3923 bool Changed = false;
3924
3925 if (!Call.getType()->isPointerTy())
3926 return Changed;
3927
3928 std::optional<APInt> Size = getAllocSize(&Call, TLI);
3929 if (Size && *Size != 0) {
3930 // TODO: We really should just emit deref_or_null here and then
3931 // let the generic inference code combine that with nonnull.
3932 if (Call.hasRetAttr(Attribute::NonNull)) {
3933 Changed = !Call.hasRetAttr(Attribute::Dereferenceable);
3935 Call.getContext(), Size->getLimitedValue()));
3936 } else {
3937 Changed = !Call.hasRetAttr(Attribute::DereferenceableOrNull);
3939 Call.getContext(), Size->getLimitedValue()));
3940 }
3941 }
3942
3943 // Add alignment attribute if alignment is a power of two constant.
3944 Value *Alignment = getAllocAlignment(&Call, TLI);
3945 if (!Alignment)
3946 return Changed;
3947
3948 ConstantInt *AlignOpC = dyn_cast<ConstantInt>(Alignment);
3949 if (AlignOpC && AlignOpC->getValue().ult(llvm::Value::MaximumAlignment)) {
3950 uint64_t AlignmentVal = AlignOpC->getZExtValue();
3951 if (llvm::isPowerOf2_64(AlignmentVal)) {
3952 Align ExistingAlign = Call.getRetAlign().valueOrOne();
3953 Align NewAlign = Align(AlignmentVal);
3954 if (NewAlign > ExistingAlign) {
3955 Call.addRetAttr(
3956 Attribute::getWithAlignment(Call.getContext(), NewAlign));
3957 Changed = true;
3958 }
3959 }
3960 }
3961 return Changed;
3962}
3963
3964/// Improvements for call, callbr and invoke instructions.
3965Instruction *InstCombinerImpl::visitCallBase(CallBase &Call) {
3966 bool Changed = annotateAnyAllocSite(Call, &TLI);
3967
3968 // Mark any parameters that are known to be non-null with the nonnull
3969 // attribute. This is helpful for inlining calls to functions with null
3970 // checks on their arguments.
3972 unsigned ArgNo = 0;
3973
3974 for (Value *V : Call.args()) {
3975 if (V->getType()->isPointerTy() &&
3976 !Call.paramHasAttr(ArgNo, Attribute::NonNull) &&
3977 isKnownNonZero(V, getSimplifyQuery().getWithInstruction(&Call)))
3978 ArgNos.push_back(ArgNo);
3979 ArgNo++;
3980 }
3981
3982 assert(ArgNo == Call.arg_size() && "Call arguments not processed correctly.");
3983
3984 if (!ArgNos.empty()) {
3985 AttributeList AS = Call.getAttributes();
3986 LLVMContext &Ctx = Call.getContext();
3987 AS = AS.addParamAttribute(Ctx, ArgNos,
3988 Attribute::get(Ctx, Attribute::NonNull));
3989 Call.setAttributes(AS);
3990 Changed = true;
3991 }
3992
3993 // If the callee is a pointer to a function, attempt to move any casts to the
3994 // arguments of the call/callbr/invoke.
3995 Value *Callee = Call.getCalledOperand();
3996 Function *CalleeF = dyn_cast<Function>(Callee);
3997 if ((!CalleeF || CalleeF->getFunctionType() != Call.getFunctionType()) &&
3998 transformConstExprCastCall(Call))
3999 return nullptr;
4000
4001 if (CalleeF) {
4002 // Remove the convergent attr on calls when the callee is not convergent.
4003 if (Call.isConvergent() && !CalleeF->isConvergent() &&
4004 !CalleeF->isIntrinsic()) {
4005 LLVM_DEBUG(dbgs() << "Removing convergent attr from instr " << Call
4006 << "\n");
4007 Call.setNotConvergent();
4008 return &Call;
4009 }
4010
4011 // If the call and callee calling conventions don't match, and neither one
4012 // of the calling conventions is compatible with C calling convention
4013 // this call must be unreachable, as the call is undefined.
4014 if ((CalleeF->getCallingConv() != Call.getCallingConv() &&
4015 !(CalleeF->getCallingConv() == llvm::CallingConv::C &&
4017 !(Call.getCallingConv() == llvm::CallingConv::C &&
4019 // Only do this for calls to a function with a body. A prototype may
4020 // not actually end up matching the implementation's calling conv for a
4021 // variety of reasons (e.g. it may be written in assembly).
4022 !CalleeF->isDeclaration()) {
4023 Instruction *OldCall = &Call;
4025 // If OldCall does not return void then replaceInstUsesWith poison.
4026 // This allows ValueHandlers and custom metadata to adjust itself.
4027 if (!OldCall->getType()->isVoidTy())
4028 replaceInstUsesWith(*OldCall, PoisonValue::get(OldCall->getType()));
4029 if (isa<CallInst>(OldCall))
4030 return eraseInstFromFunction(*OldCall);
4031
4032 // We cannot remove an invoke or a callbr, because it would change thexi
4033 // CFG, just change the callee to a null pointer.
4034 cast<CallBase>(OldCall)->setCalledFunction(
4035 CalleeF->getFunctionType(),
4036 Constant::getNullValue(CalleeF->getType()));
4037 return nullptr;
4038 }
4039 }
4040
4041 // Calling a null function pointer is undefined if a null address isn't
4042 // dereferenceable.
4043 if ((isa<ConstantPointerNull>(Callee) &&
4044 !NullPointerIsDefined(Call.getFunction())) ||
4045 isa<UndefValue>(Callee)) {
4046 // If Call does not return void then replaceInstUsesWith poison.
4047 // This allows ValueHandlers and custom metadata to adjust itself.
4048 if (!Call.getType()->isVoidTy())
4049 replaceInstUsesWith(Call, PoisonValue::get(Call.getType()));
4050
4051 if (Call.isTerminator()) {
4052 // Can't remove an invoke or callbr because we cannot change the CFG.
4053 return nullptr;
4054 }
4055
4056 // This instruction is not reachable, just remove it.
4058 return eraseInstFromFunction(Call);
4059 }
4060
4061 if (IntrinsicInst *II = findInitTrampoline(Callee))
4062 return transformCallThroughTrampoline(Call, *II);
4063
4064 if (isa<InlineAsm>(Callee) && !Call.doesNotThrow()) {
4065 InlineAsm *IA = cast<InlineAsm>(Callee);
4066 if (!IA->canThrow()) {
4067 // Normal inline asm calls cannot throw - mark them
4068 // 'nounwind'.
4069 Call.setDoesNotThrow();
4070 Changed = true;
4071 }
4072 }
4073
4074 // Try to optimize the call if possible, we require DataLayout for most of
4075 // this. None of these calls are seen as possibly dead so go ahead and
4076 // delete the instruction now.
4077 if (CallInst *CI = dyn_cast<CallInst>(&Call)) {
4078 Instruction *I = tryOptimizeCall(CI);
4079 // If we changed something return the result, etc. Otherwise let
4080 // the fallthrough check.
4081 if (I) return eraseInstFromFunction(*I);
4082 }
4083
4084 if (!Call.use_empty() && !Call.isMustTailCall())
4085 if (Value *ReturnedArg = Call.getReturnedArgOperand()) {
4086 Type *CallTy = Call.getType();
4087 Type *RetArgTy = ReturnedArg->getType();
4088 if (RetArgTy->canLosslesslyBitCastTo(CallTy))
4089 return replaceInstUsesWith(
4090 Call, Builder.CreateBitOrPointerCast(ReturnedArg, CallTy));
4091 }
4092
4093 // Drop unnecessary kcfi operand bundles from calls that were converted
4094 // into direct calls.
4095 auto Bundle = Call.getOperandBundle(LLVMContext::OB_kcfi);
4096 if (Bundle && !Call.isIndirectCall()) {
4097 DEBUG_WITH_TYPE(DEBUG_TYPE "-kcfi", {
4098 if (CalleeF) {
4099 ConstantInt *FunctionType = nullptr;
4100 ConstantInt *ExpectedType = cast<ConstantInt>(Bundle->Inputs[0]);
4101
4102 if (MDNode *MD = CalleeF->getMetadata(LLVMContext::MD_kcfi_type))
4103 FunctionType = mdconst::extract<ConstantInt>(MD->getOperand(0));
4104
4105 if (FunctionType &&
4106 FunctionType->getZExtValue() != ExpectedType->getZExtValue())
4107 dbgs() << Call.getModule()->getName()
4108 << ": warning: kcfi: " << Call.getCaller()->getName()
4109 << ": call to " << CalleeF->getName()
4110 << " using a mismatching function pointer type\n";
4111 }
4112 });
4113
4115 }
4116
4117 if (isRemovableAlloc(&Call, &TLI))
4118 return visitAllocSite(Call);
4119
4120 // Handle intrinsics which can be used in both call and invoke context.
4121 switch (Call.getIntrinsicID()) {
4122 case Intrinsic::experimental_gc_statepoint: {
4123 GCStatepointInst &GCSP = *cast<GCStatepointInst>(&Call);
4124 SmallPtrSet<Value *, 32> LiveGcValues;
4125 for (const GCRelocateInst *Reloc : GCSP.getGCRelocates()) {
4126 GCRelocateInst &GCR = *const_cast<GCRelocateInst *>(Reloc);
4127
4128 // Remove the relocation if unused.
4129 if (GCR.use_empty()) {
4131 continue;
4132 }
4133
4134 Value *DerivedPtr = GCR.getDerivedPtr();
4135 Value *BasePtr = GCR.getBasePtr();
4136
4137 // Undef is undef, even after relocation.
4138 if (isa<UndefValue>(DerivedPtr) || isa<UndefValue>(BasePtr)) {
4141 continue;
4142 }
4143
4144 if (auto *PT = dyn_cast<PointerType>(GCR.getType())) {
4145 // The relocation of null will be null for most any collector.
4146 // TODO: provide a hook for this in GCStrategy. There might be some
4147 // weird collector this property does not hold for.
4148 if (isa<ConstantPointerNull>(DerivedPtr)) {
4149 // Use null-pointer of gc_relocate's type to replace it.
4152 continue;
4153 }
4154
4155 // isKnownNonNull -> nonnull attribute
4156 if (!GCR.hasRetAttr(Attribute::NonNull) &&
4157 isKnownNonZero(DerivedPtr,
4158 getSimplifyQuery().getWithInstruction(&Call))) {
4159 GCR.addRetAttr(Attribute::NonNull);
4160 // We discovered new fact, re-check users.
4162 }
4163 }
4164
4165 // If we have two copies of the same pointer in the statepoint argument
4166 // list, canonicalize to one. This may let us common gc.relocates.
4167 if (GCR.getBasePtr() == GCR.getDerivedPtr() &&
4168 GCR.getBasePtrIndex() != GCR.getDerivedPtrIndex()) {
4169 auto *OpIntTy = GCR.getOperand(2)->getType();
4170 GCR.setOperand(2, ConstantInt::get(OpIntTy, GCR.getBasePtrIndex()));
4171 }
4172
4173 // TODO: bitcast(relocate(p)) -> relocate(bitcast(p))
4174 // Canonicalize on the type from the uses to the defs
4175
4176 // TODO: relocate((gep p, C, C2, ...)) -> gep(relocate(p), C, C2, ...)
4177 LiveGcValues.insert(BasePtr);
4178 LiveGcValues.insert(DerivedPtr);
4179 }
4180 std::optional<OperandBundleUse> Bundle =
4182 unsigned NumOfGCLives = LiveGcValues.size();
4183 if (!Bundle || NumOfGCLives == Bundle->Inputs.size())
4184 break;
4185 // We can reduce the size of gc live bundle.
4187 std::vector<Value *> NewLiveGc;
4188 for (Value *V : Bundle->Inputs) {
4189 if (Val2Idx.count(V))
4190 continue;
4191 if (LiveGcValues.count(V)) {
4192 Val2Idx[V] = NewLiveGc.size();
4193 NewLiveGc.push_back(V);
4194 } else
4195 Val2Idx[V] = NumOfGCLives;
4196 }
4197 // Update all gc.relocates
4198 for (const GCRelocateInst *Reloc : GCSP.getGCRelocates()) {
4199 GCRelocateInst &GCR = *const_cast<GCRelocateInst *>(Reloc);
4200 Value *BasePtr = GCR.getBasePtr();
4201 assert(Val2Idx.count(BasePtr) && Val2Idx[BasePtr] != NumOfGCLives &&
4202 "Missed live gc for base pointer");
4203 auto *OpIntTy1 = GCR.getOperand(1)->getType();
4204 GCR.setOperand(1, ConstantInt::get(OpIntTy1, Val2Idx[BasePtr]));
4205 Value *DerivedPtr = GCR.getDerivedPtr();
4206 assert(Val2Idx.count(DerivedPtr) && Val2Idx[DerivedPtr] != NumOfGCLives &&
4207 "Missed live gc for derived pointer");
4208 auto *OpIntTy2 = GCR.getOperand(2)->getType();
4209 GCR.setOperand(2, ConstantInt::get(OpIntTy2, Val2Idx[DerivedPtr]));
4210 }
4211 // Create new statepoint instruction.
4212 OperandBundleDef NewBundle("gc-live", NewLiveGc);
4213 return CallBase::Create(&Call, NewBundle);
4214 }
4215 default: { break; }
4216 }
4217
4218 return Changed ? &Call : nullptr;
4219}
4220
4221/// If the callee is a constexpr cast of a function, attempt to move the cast to
4222/// the arguments of the call/invoke.
4223/// CallBrInst is not supported.
4224bool InstCombinerImpl::transformConstExprCastCall(CallBase &Call) {
4225 auto *Callee =
4226 dyn_cast<Function>(Call.getCalledOperand()->stripPointerCasts());
4227 if (!Callee)
4228 return false;
4229
4230 assert(!isa<CallBrInst>(Call) &&
4231 "CallBr's don't have a single point after a def to insert at");
4232
4233 // Don't perform the transform for declarations, which may not be fully
4234 // accurate. For example, void @foo() is commonly used as a placeholder for
4235 // unknown prototypes.
4236 if (Callee->isDeclaration())
4237 return false;
4238
4239 // If this is a call to a thunk function, don't remove the cast. Thunks are
4240 // used to transparently forward all incoming parameters and outgoing return
4241 // values, so it's important to leave the cast in place.
4242 if (Callee->hasFnAttribute("thunk"))
4243 return false;
4244
4245 // If this is a call to a naked function, the assembly might be
4246 // using an argument, or otherwise rely on the frame layout,
4247 // the function prototype will mismatch.
4248 if (Callee->hasFnAttribute(Attribute::Naked))
4249 return false;
4250
4251 // If this is a musttail call, the callee's prototype must match the caller's
4252 // prototype with the exception of pointee types. The code below doesn't
4253 // implement that, so we can't do this transform.
4254 // TODO: Do the transform if it only requires adding pointer casts.
4255 if (Call.isMustTailCall())
4256 return false;
4257
4259 const AttributeList &CallerPAL = Call.getAttributes();
4260
4261 // Okay, this is a cast from a function to a different type. Unless doing so
4262 // would cause a type conversion of one of our arguments, change this call to
4263 // be a direct call with arguments casted to the appropriate types.
4264 FunctionType *FT = Callee->getFunctionType();
4265 Type *OldRetTy = Caller->getType();
4266 Type *NewRetTy = FT->getReturnType();
4267
4268 // Check to see if we are changing the return type...
4269 if (OldRetTy != NewRetTy) {
4270
4271 if (NewRetTy->isStructTy())
4272 return false; // TODO: Handle multiple return values.
4273
4274 if (!CastInst::isBitOrNoopPointerCastable(NewRetTy, OldRetTy, DL)) {
4275 if (!Caller->use_empty())
4276 return false; // Cannot transform this return value.
4277 }
4278
4279 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
4280 AttrBuilder RAttrs(FT->getContext(), CallerPAL.getRetAttrs());
4281 if (RAttrs.overlaps(AttributeFuncs::typeIncompatible(
4282 NewRetTy, CallerPAL.getRetAttrs())))
4283 return false; // Attribute not compatible with transformed value.
4284 }
4285
4286 // If the callbase is an invoke instruction, and the return value is
4287 // used by a PHI node in a successor, we cannot change the return type of
4288 // the call because there is no place to put the cast instruction (without
4289 // breaking the critical edge). Bail out in this case.
4290 if (!Caller->use_empty()) {
4291 BasicBlock *PhisNotSupportedBlock = nullptr;
4292 if (auto *II = dyn_cast<InvokeInst>(Caller))
4293 PhisNotSupportedBlock = II->getNormalDest();
4294 if (PhisNotSupportedBlock)
4295 for (User *U : Caller->users())
4296 if (PHINode *PN = dyn_cast<PHINode>(U))
4297 if (PN->getParent() == PhisNotSupportedBlock)
4298 return false;
4299 }
4300 }
4301
4302 unsigned NumActualArgs = Call.arg_size();
4303 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
4304
4305 // Prevent us turning:
4306 // declare void @takes_i32_inalloca(i32* inalloca)
4307 // call void bitcast (void (i32*)* @takes_i32_inalloca to void (i32)*)(i32 0)
4308 //
4309 // into:
4310 // call void @takes_i32_inalloca(i32* null)
4311 //
4312 // Similarly, avoid folding away bitcasts of byval calls.
4313 if (Callee->getAttributes().hasAttrSomewhere(Attribute::InAlloca) ||
4314 Callee->getAttributes().hasAttrSomewhere(Attribute::Preallocated))
4315 return false;
4316
4317 auto AI = Call.arg_begin();
4318 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
4319 Type *ParamTy = FT->getParamType(i);
4320 Type *ActTy = (*AI)->getType();
4321
4322 if (!CastInst::isBitOrNoopPointerCastable(ActTy, ParamTy, DL))
4323 return false; // Cannot transform this parameter value.
4324
4325 // Check if there are any incompatible attributes we cannot drop safely.
4326 if (AttrBuilder(FT->getContext(), CallerPAL.getParamAttrs(i))
4328 ParamTy, CallerPAL.getParamAttrs(i),
4330 return false; // Attribute not compatible with transformed value.
4331
4332 if (Call.isInAllocaArgument(i) ||
4333 CallerPAL.hasParamAttr(i, Attribute::Preallocated))
4334 return false; // Cannot transform to and from inalloca/preallocated.
4335
4336 if (CallerPAL.hasParamAttr(i, Attribute::SwiftError))
4337 return false;
4338
4339 if (CallerPAL.hasParamAttr(i, Attribute::ByVal) !=
4340 Callee->getAttributes().hasParamAttr(i, Attribute::ByVal))
4341 return false; // Cannot transform to or from byval.
4342 }
4343
4344 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
4345 !CallerPAL.isEmpty()) {
4346 // In this case we have more arguments than the new function type, but we
4347 // won't be dropping them. Check that these extra arguments have attributes
4348 // that are compatible with being a vararg call argument.
4349 unsigned SRetIdx;
4350 if (CallerPAL.hasAttrSomewhere(Attribute::StructRet, &SRetIdx) &&
4351 SRetIdx - AttributeList::FirstArgIndex >= FT->getNumParams())
4352 return false;
4353 }
4354
4355 // Okay, we decided that this is a safe thing to do: go ahead and start
4356 // inserting cast instructions as necessary.
4359 Args.reserve(NumActualArgs);
4360 ArgAttrs.reserve(NumActualArgs);
4361
4362 // Get any return attributes.
4363 AttrBuilder RAttrs(FT->getContext(), CallerPAL.getRetAttrs());
4364
4365 // If the return value is not being used, the type may not be compatible
4366 // with the existing attributes. Wipe out any problematic attributes.
4367 RAttrs.remove(
4368 AttributeFuncs::typeIncompatible(NewRetTy, CallerPAL.getRetAttrs()));
4369
4370 LLVMContext &Ctx = Call.getContext();
4371 AI = Call.arg_begin();
4372 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
4373 Type *ParamTy = FT->getParamType(i);
4374
4375 Value *NewArg = *AI;
4376 if ((*AI)->getType() != ParamTy)
4377 NewArg = Builder.CreateBitOrPointerCast(*AI, ParamTy);
4378 Args.push_back(NewArg);
4379
4380 // Add any parameter attributes except the ones incompatible with the new
4381 // type. Note that we made sure all incompatible ones are safe to drop.
4383 ParamTy, CallerPAL.getParamAttrs(i), AttributeFuncs::ASK_SAFE_TO_DROP);
4384 ArgAttrs.push_back(
4385 CallerPAL.getParamAttrs(i).removeAttributes(Ctx, IncompatibleAttrs));
4386 }
4387
4388 // If the function takes more arguments than the call was taking, add them
4389 // now.
4390 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i) {
4391 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
4392 ArgAttrs.push_back(AttributeSet());
4393 }
4394
4395 // If we are removing arguments to the function, emit an obnoxious warning.
4396 if (FT->getNumParams() < NumActualArgs) {
4397 // TODO: if (!FT->isVarArg()) this call may be unreachable. PR14722
4398 if (FT->isVarArg()) {
4399 // Add all of the arguments in their promoted form to the arg list.
4400 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
4401 Type *PTy = getPromotedType((*AI)->getType());
4402 Value *NewArg = *AI;
4403 if (PTy != (*AI)->getType()) {
4404 // Must promote to pass through va_arg area!
4405 Instruction::CastOps opcode =
4406 CastInst::getCastOpcode(*AI, false, PTy, false);
4407 NewArg = Builder.CreateCast(opcode, *AI, PTy);
4408 }
4409 Args.push_back(NewArg);
4410
4411 // Add any parameter attributes.
4412 ArgAttrs.push_back(CallerPAL.getParamAttrs(i));
4413 }
4414 }
4415 }
4416
4417 AttributeSet FnAttrs = CallerPAL.getFnAttrs();
4418
4419 if (NewRetTy->isVoidTy())
4420 Caller->setName(""); // Void type should not have a name.
4421
4422 assert((ArgAttrs.size() == FT->getNumParams() || FT->isVarArg()) &&
4423 "missing argument attributes");
4424 AttributeList NewCallerPAL = AttributeList::get(
4425 Ctx, FnAttrs, AttributeSet::get(Ctx, RAttrs), ArgAttrs);
4426
4428 Call.getOperandBundlesAsDefs(OpBundles);
4429
4430 CallBase *NewCall;
4431 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
4432 NewCall = Builder.CreateInvoke(Callee, II->getNormalDest(),
4433 II->getUnwindDest(), Args, OpBundles);
4434 } else {
4435 NewCall = Builder.CreateCall(Callee, Args, OpBundles);
4436 cast<CallInst>(NewCall)->setTailCallKind(
4437 cast<CallInst>(Caller)->getTailCallKind());
4438 }
4439 NewCall->takeName(Caller);
4440 NewCall->setCallingConv(Call.getCallingConv());
4441 NewCall->setAttributes(NewCallerPAL);
4442
4443 // Preserve prof metadata if any.
4444 NewCall->copyMetadata(*Caller, {LLVMContext::MD_prof});
4445
4446 // Insert a cast of the return type as necessary.
4447 Instruction *NC = NewCall;
4448 Value *NV = NC;
4449 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
4450 assert(!NV->getType()->isVoidTy());
4452 NC->setDebugLoc(Caller->getDebugLoc());
4453
4454 auto OptInsertPt = NewCall->getInsertionPointAfterDef();
4455 assert(OptInsertPt && "No place to insert cast");
4456 InsertNewInstBefore(NC, *OptInsertPt);
4458 }
4459
4460 if (!Caller->use_empty())
4461 replaceInstUsesWith(*Caller, NV);
4462 else if (Caller->hasValueHandle()) {
4463 if (OldRetTy == NV->getType())
4465 else
4466 // We cannot call ValueIsRAUWd with a different type, and the
4467 // actual tracked value will disappear.
4469 }
4470
4471 eraseInstFromFunction(*Caller);
4472 return true;
4473}
4474
4475/// Turn a call to a function created by init_trampoline / adjust_trampoline
4476/// intrinsic pair into a direct call to the underlying function.
4478InstCombinerImpl::transformCallThroughTrampoline(CallBase &Call,
4479 IntrinsicInst &Tramp) {
4480 FunctionType *FTy = Call.getFunctionType();
4481 AttributeList Attrs = Call.getAttributes();
4482
4483 // If the call already has the 'nest' attribute somewhere then give up -
4484 // otherwise 'nest' would occur twice after splicing in the chain.
4485 if (Attrs.hasAttrSomewhere(Attribute::Nest))
4486 return nullptr;
4487
4488 Function *NestF = cast<Function>(Tramp.getArgOperand(1)->stripPointerCasts());
4489 FunctionType *NestFTy = NestF->getFunctionType();
4490
4491 AttributeList NestAttrs = NestF->getAttributes();
4492 if (!NestAttrs.isEmpty()) {
4493 unsigned NestArgNo = 0;
4494 Type *NestTy = nullptr;
4495 AttributeSet NestAttr;
4496
4497 // Look for a parameter marked with the 'nest' attribute.
4498 for (FunctionType::param_iterator I = NestFTy->param_begin(),
4499 E = NestFTy->param_end();
4500 I != E; ++NestArgNo, ++I) {
4501 AttributeSet AS = NestAttrs.getParamAttrs(NestArgNo);
4502 if (AS.hasAttribute(Attribute::Nest)) {
4503 // Record the parameter type and any other attributes.
4504 NestTy = *I;
4505 NestAttr = AS;
4506 break;
4507 }
4508 }
4509
4510 if (NestTy) {
4511 std::vector<Value*> NewArgs;
4512 std::vector<AttributeSet> NewArgAttrs;
4513 NewArgs.reserve(Call.arg_size() + 1);
4514 NewArgAttrs.reserve(Call.arg_size());
4515
4516 // Insert the nest argument into the call argument list, which may
4517 // mean appending it. Likewise for attributes.
4518
4519 {
4520 unsigned ArgNo = 0;
4521 auto I = Call.arg_begin(), E = Call.arg_end();
4522 do {
4523 if (ArgNo == NestArgNo) {
4524 // Add the chain argument and attributes.
4525 Value *NestVal = Tramp.getArgOperand(2);
4526 if (NestVal->getType() != NestTy)
4527 NestVal = Builder.CreateBitCast(NestVal, NestTy, "nest");
4528 NewArgs.push_back(NestVal);
4529 NewArgAttrs.push_back(NestAttr);
4530 }
4531
4532 if (I == E)
4533 break;
4534
4535 // Add the original argument and attributes.
4536 NewArgs.push_back(*I);
4537 NewArgAttrs.push_back(Attrs.getParamAttrs(ArgNo));
4538
4539 ++ArgNo;
4540 ++I;
4541 } while (true);
4542 }
4543
4544 // The trampoline may have been bitcast to a bogus type (FTy).
4545 // Handle this by synthesizing a new function type, equal to FTy
4546 // with the chain parameter inserted.
4547
4548 std::vector<Type*> NewTypes;
4549 NewTypes.reserve(FTy->getNumParams()+1);
4550
4551 // Insert the chain's type into the list of parameter types, which may
4552 // mean appending it.
4553 {
4554 unsigned ArgNo = 0;
4555 FunctionType::param_iterator I = FTy->param_begin(),
4556 E = FTy->param_end();
4557
4558 do {
4559 if (ArgNo == NestArgNo)
4560 // Add the chain's type.
4561 NewTypes.push_back(NestTy);
4562
4563 if (I == E)
4564 break;
4565
4566 // Add the original type.
4567 NewTypes.push_back(*I);
4568
4569 ++ArgNo;
4570 ++I;
4571 } while (true);
4572 }
4573
4574 // Replace the trampoline call with a direct call. Let the generic
4575 // code sort out any function type mismatches.
4576 FunctionType *NewFTy =
4577 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
4578 AttributeList NewPAL =
4579 AttributeList::get(FTy->getContext(), Attrs.getFnAttrs(),
4580 Attrs.getRetAttrs(), NewArgAttrs);
4581
4583 Call.getOperandBundlesAsDefs(OpBundles);
4584
4585 Instruction *NewCaller;
4586 if (InvokeInst *II = dyn_cast<InvokeInst>(&Call)) {
4587 NewCaller = InvokeInst::Create(NewFTy, NestF, II->getNormalDest(),
4588 II->getUnwindDest(), NewArgs, OpBundles);
4589 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
4590 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
4591 } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(&Call)) {
4592 NewCaller =
4593 CallBrInst::Create(NewFTy, NestF, CBI->getDefaultDest(),
4594 CBI->getIndirectDests(), NewArgs, OpBundles);
4595 cast<CallBrInst>(NewCaller)->setCallingConv(CBI->getCallingConv());
4596 cast<CallBrInst>(NewCaller)->setAttributes(NewPAL);
4597 } else {
4598 NewCaller = CallInst::Create(NewFTy, NestF, NewArgs, OpBundles);
4599 cast<CallInst>(NewCaller)->setTailCallKind(
4600 cast<CallInst>(Call).getTailCallKind());
4601 cast<CallInst>(NewCaller)->setCallingConv(
4602 cast<CallInst>(Call).getCallingConv());
4603 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
4604 }
4605 NewCaller->setDebugLoc(Call.getDebugLoc());
4606
4607 return NewCaller;
4608 }
4609 }
4610
4611 // Replace the trampoline call with a direct call. Since there is no 'nest'
4612 // parameter, there is no need to adjust the argument list. Let the generic
4613 // code sort out any function type mismatches.
4614 Call.setCalledFunction(FTy, NestF);
4615 return &Call;
4616}
unsigned Intr
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...
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...
BlockVerifier::State From
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static SDValue foldBitOrderCrossLogicOp(SDNode *N, SelectionDAG &DAG)
return RetTy
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
#define LLVM_DEBUG(...)
Definition: Debug.h:106
#define DEBUG_WITH_TYPE(TYPE,...)
DEBUG_WITH_TYPE macro - This macro should be used by passes to emit debug information.
Definition: Debug.h:64
uint64_t Size
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
#define DEBUG_TYPE
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 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 signBitMustBeTheSame(Value *Op0, Value *Op1, const SimplifyQuery &SQ)
Return true if two values Op0 and Op1 are known to have the same sign.
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 * foldShuffledIntrinsicOperands(IntrinsicInst *II, InstCombiner::BuilderTy &Builder)
If all arguments of the intrinsic are unary shuffles with the same mask, try to shuffle after the int...
static Instruction * factorizeMinMaxTree(IntrinsicInst *II)
Reduce a sequence of min/max intrinsics with a common operand.
static Value * simplifyNeonTbl1(const IntrinsicInst &II, InstCombiner::BuilderTy &Builder)
Convert a table lookup to shufflevector if the mask is constant.
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 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(CtOp, ZeroUndef),...
static Instruction * foldCtpop(IntrinsicInst &II, InstCombinerImpl &IC)
static Instruction * foldCttzCtlz(IntrinsicInst &II, InstCombinerImpl &IC)
static IntrinsicInst * findInitTrampoline(Value *Callee)
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 CallInst * canonicalizeConstantArg0ToArg1(CallInst &Call)
This file provides internal interfaces used to implement the InstCombine.
This file provides the interface for the instcombine pass implementation.
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
This file contains the declarations for metadata subclasses.
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml", "ocaml 3.10-compatible collector")
const SmallVectorImpl< MachineOperand > & Cond
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
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:166
@ Struct
static std::optional< unsigned > getOpcode(ArrayRef< VPValue * > Values)
Returns the opcode of Values or ~0 if they do not all agree.
Definition: VPlanSLP.cpp:191
static bool inputDenormalIsIEEE(const Function &F, const Type *Ty)
Return true if it's possible to assume IEEE treatment of input denormals in F for Val.
Value * RHS
Value * LHS
ModRefInfo getModRefInfoMask(const MemoryLocation &Loc, bool IgnoreLocals=false)
Returns a bitmask that should be unconditionally applied to the ModRef info of a memory location.
bool isNegative() const
Definition: APFloat.h:1445
void clearSign()
Definition: APFloat.h:1300
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:234
static APInt getSignMask(unsigned BitWidth)
Get the SignMask for a specific bit width.
Definition: APInt.h:229
APInt usub_ov(const APInt &RHS, bool &Overflow) const
Definition: APInt.cpp:1922
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition: APInt.h:380
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition: APInt.h:1468
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition: APInt.h:1111
APInt sadd_ov(const APInt &RHS, bool &Overflow) const
Definition: APInt.cpp:1902
APInt uadd_ov(const APInt &RHS, bool &Overflow) const
Definition: APInt.cpp:1909
static APInt getSplat(unsigned NewLen, const APInt &V)
Return a value containing V broadcasted over NewLen bits.
Definition: APInt.cpp:624
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition: APInt.h:219
APInt uadd_sat(const APInt &RHS) const
Definition: APInt.cpp:2010
bool isNonNegative() const
Determine if this APInt Value is non-negative (>= 0)
Definition: APInt.h:334
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition: APInt.h:306
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition: APInt.h:200
APInt ssub_ov(const APInt &RHS, bool &Overflow) const
Definition: APInt.cpp:1915
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:311
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:303
This class represents any memset intrinsic.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
void registerAssumption(AssumeInst *CI)
Add an @llvm.assume intrinsic to this function's cache.
void updateAffectedValues(AssumeInst *CI)
Update the cache of values being affected by this assumption (i.e.
MutableArrayRef< ResultElem > assumptionsFor(const Value *V)
Access the list of assumptions which affect this value.
bool overlaps(const AttributeMask &AM) const
Return true if the builder has any attribute that's in the specified builder.
AttributeSet getFnAttrs() const
The function attributes are returned.
static AttributeList get(LLVMContext &C, ArrayRef< std::pair< unsigned, Attribute > > Attrs)
Create an AttributeList with the specified parameters in it.
bool isEmpty() const
Return true if there are no attributes.
Definition: Attributes.h:1025
AttributeSet getRetAttrs() const
The attributes for the ret value are returned.
bool hasAttrSomewhere(Attribute::AttrKind Kind, unsigned *Index=nullptr) const
Return true if the specified attribute is set for at least one parameter or for the return value.
bool hasParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Return true if the attribute exists for the given argument.
Definition: Attributes.h:833
AttributeSet getParamAttrs(unsigned ArgNo) const
The attributes for the argument or parameter at the given index are returned.
AttributeList addParamAttribute(LLVMContext &C, unsigned ArgNo, Attribute::AttrKind Kind) const
Add an argument attribute to the list.
Definition: Attributes.h:628
bool hasAttribute(Attribute::AttrKind Kind) const
Return true if the attribute exists in this set.
AttributeSet removeAttributes(LLVMContext &C, const AttributeMask &AttrsToRemove) const
Remove the specified attributes from this set.
Definition: Attributes.cpp:962
static AttributeSet get(LLVMContext &C, const AttrBuilder &B)
Definition: Attributes.cpp:910
static Attribute get(LLVMContext &Context, AttrKind Kind, uint64_t Val=0)
Return a uniquified Attribute object.
Definition: Attributes.cpp:95
static Attribute getWithDereferenceableBytes(LLVMContext &Context, uint64_t Bytes)
Definition: Attributes.cpp:244
static Attribute getWithDereferenceableOrNullBytes(LLVMContext &Context, uint64_t Bytes)
Definition: Attributes.cpp:250
static Attribute getWithAlignment(LLVMContext &Context, Align Alignment)
Return a uniquified Attribute object that has the specific alignment set.
Definition: Attributes.cpp:234
LLVM Basic Block Representation.
Definition: BasicBlock.h:61
InstListType::reverse_iterator reverse_iterator
Definition: BasicBlock.h:179
InstListType::iterator iterator
Instruction iterators...
Definition: BasicBlock.h:177
Value * getRHS() const
bool isSigned() const
Whether the intrinsic is signed or unsigned.
Instruction::BinaryOps getBinaryOp() const
Returns the binary operation underlying the intrinsic.
Value * getLHS() const
static 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:278
static BinaryOperator * CreateNot(Value *Op, const Twine &Name="", InsertPosition InsertBefore=nullptr)
static 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:293
static BinaryOperator * CreateFMulFMF(Value *V1, Value *V2, FastMathFlags FMF, const Twine &Name="")
Definition: InstrTypes.h:243
static BinaryOperator * CreateFDivFMF(Value *V1, Value *V2, FastMathFlags FMF, const Twine &Name="")
Definition: InstrTypes.h:247
static BinaryOperator * CreateFSubFMF(Value *V1, Value *V2, FastMathFlags FMF, const Twine &Name="")
Definition: InstrTypes.h:239
static BinaryOperator * CreateWithCopiedFlags(BinaryOps Opc, Value *V1, Value *V2, Value *CopyO, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Definition: InstrTypes.h:218
static BinaryOperator * CreateNSWNeg(Value *Op, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Definition: InstrTypes.h:1112
void setCallingConv(CallingConv::ID CC)
Definition: InstrTypes.h:1403
void setDoesNotThrow()
Definition: InstrTypes.h:1921
MaybeAlign getRetAlign() const
Extract the alignment of the return value.
Definition: InstrTypes.h:1734
std::optional< OperandBundleUse > getOperandBundle(StringRef Name) const
Return an operand bundle by name, if present.
Definition: InstrTypes.h:2048
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
Definition: InstrTypes.h:1341
bool hasRetAttr(Attribute::AttrKind Kind) const
Determine whether the return value has the given attribute.
Definition: InstrTypes.h:1573
Value * getCalledOperand() const
Definition: InstrTypes.h:1334
void setAttributes(AttributeList A)
Set the attributes for this call.
Definition: InstrTypes.h:1420
bool doesNotThrow() const
Determine if the call cannot unwind.
Definition: InstrTypes.h:1920
void addRetAttr(Attribute::AttrKind Kind)
Adds the attribute to the return value.
Definition: InstrTypes.h:1484
Value * getArgOperand(unsigned i) const
Definition: InstrTypes.h:1286
Intrinsic::ID getIntrinsicID() const
Returns the intrinsic ID of the intrinsic called or Intrinsic::not_intrinsic if the called function i...
static 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.
Definition: InstrTypes.h:1277
static CallBase * removeOperandBundle(CallBase *CB, uint32_t ID, InsertPosition InsertPt=nullptr)
Create a clone of CB with operand bundle ID removed.
unsigned arg_size() const
Definition: InstrTypes.h:1284
void setCalledFunction(Function *Fn)
Sets the function called, including updating the function type.
Definition: InstrTypes.h:1380
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
void setTailCallKind(TailCallKind TCK)
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
bool isMustTailCall() const
static 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 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 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 CastInst * CreateBitOrPointerCast(Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Create a BitCast, a PtrToInt, or an IntToPTr cast instruction.
static 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:673
@ FCMP_OEQ
0 0 0 1 True if ordered and equal
Definition: InstrTypes.h:676
@ ICMP_SLT
signed less than
Definition: InstrTypes.h:702
@ ICMP_SLE
signed less or equal
Definition: InstrTypes.h:703
@ FCMP_OLT
0 1 0 0 True if ordered and less than
Definition: InstrTypes.h:679
@ FCMP_OGT
0 0 1 0 True if ordered and greater than
Definition: InstrTypes.h:677
@ FCMP_OGE
0 0 1 1 True if ordered and greater than or equal
Definition: InstrTypes.h:678
@ ICMP_UGT
unsigned greater than
Definition: InstrTypes.h:696
@ ICMP_SGT
signed greater than
Definition: InstrTypes.h:700
@ FCMP_ONE
0 1 1 0 True if ordered and operands are unequal
Definition: InstrTypes.h:681
@ FCMP_UEQ
1 0 0 1 True if unordered or equal
Definition: InstrTypes.h:684
@ ICMP_ULT
unsigned less than
Definition: InstrTypes.h:698
@ FCMP_OLE
0 1 0 1 True if ordered and less than or equal
Definition: InstrTypes.h:680
@ ICMP_EQ
equal
Definition: InstrTypes.h:694
@ ICMP_NE
not equal
Definition: InstrTypes.h:695
@ FCMP_UNE
1 1 1 0 True if unordered or not equal
Definition: InstrTypes.h:689
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Definition: InstrTypes.h:825
Predicate getNonStrictPredicate() const
For example, SGT -> SGE, SLT -> SLE, ULT -> ULE, UGT -> UGE.
Definition: InstrTypes.h:869
Predicate getUnorderedPredicate() const
Definition: InstrTypes.h:809
static ConstantAggregateZero * get(Type *Ty)
Definition: Constants.cpp:1672
static Constant * getPointerCast(Constant *C, Type *Ty)
Create a BitCast, AddrSpaceCast, or a PtrToInt cast constant expression.
Definition: Constants.cpp:2253
static Constant * getSub(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
Definition: Constants.cpp:2644
static Constant * getNeg(Constant *C, bool HasNSW=false)
Definition: Constants.cpp:2625
static Constant * getInfinity(Type *Ty, bool Negative=false)
Definition: Constants.cpp:1103
static Constant * getZero(Type *Ty, bool Negative=false)
Definition: Constants.cpp:1057
This is the shared class of boolean and integer constants.
Definition: Constants.h:83
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:258
static ConstantInt * getTrue(LLVMContext &Context)
Definition: Constants.cpp:866
static ConstantInt * getFalse(LLVMContext &Context)
Definition: Constants.cpp:873
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:157
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition: Constants.h:148
static ConstantInt * getBool(LLVMContext &Context, bool V)
Definition: Constants.cpp:880
static ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
Definition: Constants.cpp:1826
static ConstantPtrAuth * get(Constant *Ptr, ConstantInt *Key, ConstantInt *Disc, Constant *AddrDisc)
Return a pointer signed with the specified parameters.
Definition: Constants.cpp:2072
This class represents a range of values.
Definition: ConstantRange.h:47
bool isFullSet() const
Return true if this set contains all of the elements possible for this data-type.
bool icmp(CmpInst::Predicate Pred, const ConstantRange &Other) const
Does the predicate Pred hold between ranges this and Other? NOTE: false does not mean that inverse pr...
bool contains(const APInt &Val) const
Return true if the specified value is in the set.
ConstantRange intersectWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the intersection of this range with another range.
static Constant * get(StructType *T, ArrayRef< Constant * > V)
Definition: Constants.cpp:1378
This is an important base class in LLVM.
Definition: Constant.h:42
static 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...
Definition: Constants.cpp:403
static Constant * getAllOnesValue(Type *Ty)
Definition: Constants.cpp:420
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
Definition: Constants.cpp:373
This class represents an Operation in the Expression.
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:63
unsigned getPointerTypeSizeInBits(Type *) const
Layout pointer size, in bits, based on the type.
Definition: DataLayout.cpp:743
unsigned size() const
Definition: DenseMap.h:99
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:152
static FMFSource intersect(Value *A, Value *B)
Intersect the FMF from two instructions.
Definition: IRBuilder.h:106
This class represents an extension of floating point types.
Convenience struct for specifying and reasoning about fast-math flags.
Definition: FMF.h:20
void setNoSignedZeros(bool B=true)
Definition: FMF.h:85
bool allowReassoc() const
Flag queries.
Definition: FMF.h:65
An instruction for ordering other memory operations.
Definition: Instructions.h:424
SyncScope::ID getSyncScopeID() const
Returns the synchronization scope ID of this fence instruction.
Definition: Instructions.h:460
AtomicOrdering getOrdering() const
Returns the ordering constraint of this fence instruction.
Definition: Instructions.h:449
Class to represent function types.
Definition: DerivedTypes.h:105
Type::subtype_iterator param_iterator
Definition: DerivedTypes.h:128
static 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:611
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Definition: Function.h:216
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
Definition: Function.h:277
AttributeList getAttributes() const
Return the attribute list for this Function.
Definition: Function.h:353
bool doesNotThrow() const
Determine if the function cannot unwind.
Definition: Function.h:595
bool isIntrinsic() const
isIntrinsic - Returns true if the function's name starts with "llvm.".
Definition: Function.h:256
Represents calls to the gc.relocate intrinsic.
Value * getBasePtr() const
unsigned getBasePtrIndex() const
The index into the associate statepoint's argument list which contains the base pointer of the pointe...
Value * getDerivedPtr() const
unsigned getDerivedPtrIndex() const
The index into the associate statepoint's argument list which contains the pointer whose relocation t...
Represents a gc.statepoint intrinsic call.
Definition: Statepoint.h:61
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 current metadata attachments for the given kind, if any.
Definition: Value.h:565
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition: Globals.cpp:296
PointerType * getType() const
Global values are always pointers.
Definition: GlobalValue.h:294
Common base class shared among various IRBuilders.
Definition: IRBuilder.h:113
Value * CreateFCmpONE(Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:2334
Value * CreateLdexp(Value *Src, Value *Exp, FMFSource FMFSource={}, const Twine &Name="")
Create call to the ldexp intrinsic.
Definition: IRBuilder.h:1056
Value * CreateLaunderInvariantGroup(Value *Ptr)
Create a launder.invariant.group intrinsic call.
Definition: IRBuilder.cpp:1076
Value * CreateFCmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:2389
IntegerType * getInt1Ty()
Fetch the type representing a single bit.
Definition: IRBuilder.h:530
Value * CreateExtractElement(Value *Vec, Value *Idx, const Twine &Name="")
Definition: IRBuilder.h:2498
IntegerType * getIntNTy(unsigned N)
Fetch the type representing an N-bit integer.
Definition: IRBuilder.h:558
LoadInst * CreateAlignedLoad(Type *Ty, Value *Ptr, MaybeAlign Align, const char *Name)
Definition: IRBuilder.h:1814
Value * CreateFCmpORD(Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:2339
Value * CreateZExtOrTrunc(Value *V, Type *DestTy, const Twine &Name="")
Create a ZExt or Trunc from the integer value V to DestTy.
Definition: IRBuilder.h:2050
CallInst * CreateAndReduce(Value *Src)
Create a vector int AND reduction intrinsic of the source vector.
Definition: IRBuilder.cpp:420
CallInst * CreateAssumption(Value *Cond, ArrayRef< OperandBundleDef > OpBundles={})
Create an assume intrinsic call that allows the optimizer to assume that the provided condition will ...
Definition: IRBuilder.cpp:521
Value * CreateVectorSplat(unsigned NumElts, Value *V, const Twine &Name="")
Return a vector value that contains.
Definition: IRBuilder.cpp:1153
ConstantInt * getTrue()
Get the constant value for i1 true.
Definition: IRBuilder.h:485
Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
Definition: IRBuilder.cpp:1043
InvokeInst * CreateInvoke(FunctionType *Ty, Value *Callee, BasicBlock *NormalDest, BasicBlock *UnwindDest, ArrayRef< Value * > Args, ArrayRef< OperandBundleDef > OpBundles, const Twine &Name="")
Create an invoke instruction.
Definition: IRBuilder.h:1201
Value * CreateFCmpUNE(Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:2374
CallInst * CreateAddReduce(Value *Src)
Create a vector int add reduction intrinsic of the source vector.
Definition: IRBuilder.cpp:412
Value * CreateLShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Definition: IRBuilder.h:1479
IntegerType * getInt32Ty()
Fetch the type representing a 32-bit integer.
Definition: IRBuilder.h:545
Value * CreateCast(Instruction::CastOps Op, Value *V, Type *DestTy, const Twine &Name="", MDNode *FPMathTag=nullptr, FMFSource FMFSource={})
Definition: IRBuilder.h:2185
Value * CreateNSWMul(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1412
Value * CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:2273
Value * CreateNeg(Value *V, const Twine &Name="", bool HasNSW=false)
Definition: IRBuilder.h:1732
CallInst * CreateOrReduce(Value *Src)
Create a vector int OR reduction intrinsic of the source vector.
Definition: IRBuilder.cpp:424
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.
Definition: IRBuilder.cpp:879
CallInst * CreateIntrinsic(Intrinsic::ID ID, ArrayRef< Type * > Types, ArrayRef< Value * > Args, FMFSource FMFSource={}, const Twine &Name="")
Create a call to intrinsic ID with Args, mangled using Types.
Definition: IRBuilder.cpp:890
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
Definition: IRBuilder.h:505
Value * CreateBitOrPointerCast(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2233
Value * CreateNot(Value *V, const Twine &Name="")
Definition: IRBuilder.h:1756
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:2269
Value * CreateFCmpUEQ(Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:2349
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1386
Value * CreateBitCast(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2151
Value * CreateCopySign(Value *LHS, Value *RHS, FMFSource FMFSource={}, const Twine &Name="")
Create call to the copysign intrinsic.
Definition: IRBuilder.h:1049
CallInst * CreateUnaryIntrinsic(Intrinsic::ID ID, Value *V, FMFSource FMFSource={}, const Twine &Name="")
Create a call to intrinsic ID with 1 operand which is mangled on its type.
Definition: IRBuilder.cpp:871
LoadInst * CreateLoad(Type *Ty, Value *Ptr, const char *Name)
Provided to resolve 'CreateLoad(Ty, Ptr, "...")' correctly, instead of converting the string to 'bool...
Definition: IRBuilder.h:1797
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="", bool IsNonNeg=false)
Definition: IRBuilder.h:2032
Value * CreateShuffleVector(Value *V1, Value *V2, Value *Mask, const Twine &Name="")
Definition: IRBuilder.h:2532
Value * CreateFCmpOEQ(Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:2309
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1517
StoreInst * CreateStore(Value *Val, Value *Ptr, bool isVolatile=false)
Definition: IRBuilder.h:1810
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1369
Value * CreatePtrToInt(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2141
ConstantInt * getFalse()
Get the constant value for i1 false.
Definition: IRBuilder.h:490
Value * CreateIsNotNull(Value *Arg, const Twine &Name="")
Return a boolean value testing if Arg != 0.
Definition: IRBuilder.h:2587
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value * > Args={}, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:2448
Value * CreateTrunc(Value *V, Type *DestTy, const Twine &Name="", bool IsNUW=false, bool IsNSW=false)
Definition: IRBuilder.h:2018
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1539
PointerType * getPtrTy(unsigned AddrSpace=0)
Fetch the type representing a pointer.
Definition: IRBuilder.h:588
Value * CreateBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:1670
Value * CreateElementCount(Type *DstType, ElementCount EC)
Create an expression which evaluates to the number of elements in EC at runtime.
Definition: IRBuilder.cpp:98
Value * CreateIntCast(Value *V, Type *DestTy, bool isSigned, const Twine &Name="")
Definition: IRBuilder.h:2224
Value * CreateFCmpUNO(Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:2344
Value * CreateIsNull(Value *Arg, const Twine &Name="")
Return a boolean value testing if Arg == 0.
Definition: IRBuilder.h:2582
Value * CreateFNegFMF(Value *V, FMFSource FMFSource, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:1746
Value * CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:2379
Value * CreateFNeg(Value *V, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:1741
Value * CreateAddrSpaceCast(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2156
Value * CreateMul(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1403
Value * CreateStripInvariantGroup(Value *Ptr)
Create a strip.invariant.group intrinsic call.
Definition: IRBuilder.cpp:1092
static InsertValueInst * Create(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Instruction * FoldOpIntoSelect(Instruction &Op, SelectInst *SI, bool FoldWithMultiUse=false)
Given an instruction with a select as one operand and a constant as the other operand,...
KnownFPClass computeKnownFPClass(Value *Val, FastMathFlags FMF, FPClassTest Interested=fcAllFlags, const Instruction *CtxI=nullptr, unsigned Depth=0) const
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.
Instruction * SimplifyAnyMemSet(AnyMemSetInst *MI)
Constant * getLosslessUnsignedTrunc(Constant *C, Type *TruncTy)
Instruction * visitFree(CallInst &FI, Value *FreedOp)
Instruction * visitCallBrInst(CallBrInst &CBI)
Instruction * eraseInstFromFunction(Instruction &I) override
Combiner aware instruction erasure.
bool SimplifyDemandedBits(Instruction *I, unsigned Op, const APInt &DemandedMask, KnownBits &Known, unsigned Depth, const SimplifyQuery &Q) override
This form of SimplifyDemandedBits simplifies the specified instruction operand if possible,...
Value * tryGetLog2(Value *Op, bool AssumeNonZero)
Instruction * visitFenceInst(FenceInst &FI)
Instruction * visitInvokeInst(InvokeInst &II)
Constant * getLosslessSignedTrunc(Constant *C, Type *TruncTy)
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.
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.
SimplifyQuery SQ
Definition: InstCombiner.h:77
bool isFreeToInvert(Value *V, bool WillInvertAllUses, bool &DoesConsume)
Return true if the specified value is free to invert (apply ~ to).
Definition: InstCombiner.h:228
DominatorTree & getDominatorTree() const
Definition: InstCombiner.h:336
BlockFrequencyInfo * BFI
Definition: InstCombiner.h:79
TargetLibraryInfo & TLI
Definition: InstCombiner.h:74
bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero=false, unsigned Depth=0, const Instruction *CxtI=nullptr)
Definition: InstCombiner.h:443
Instruction * InsertNewInstBefore(Instruction *New, BasicBlock::iterator Old)
Inserts an instruction New before instruction Old.
Definition: InstCombiner.h:368
AAResults * AA
Definition: InstCombiner.h:70
Instruction * replaceInstUsesWith(Instruction &I, Value *V)
A combiner-aware RAUW-like routine.
Definition: InstCombiner.h:388
void replaceUse(Use &U, Value *NewValue)
Replace use and add the previously used value to the worklist.
Definition: InstCombiner.h:420
InstructionWorklist & Worklist
A worklist of the instructions that need to be simplified.
Definition: InstCombiner.h:65
const DataLayout & DL
Definition: InstCombiner.h:76
DomConditionCache DC
Definition: InstCombiner.h:82
std::optional< Instruction * > targetInstCombineIntrinsic(IntrinsicInst &II)
AssumptionCache & AC
Definition: InstCombiner.h:73
Instruction * replaceOperand(Instruction &I, unsigned OpNum, Value *V)
Replace operand of instruction and add old operand to the worklist.
Definition: InstCombiner.h:412
DominatorTree & DT
Definition: InstCombiner.h:75
ProfileSummaryInfo * PSI
Definition: InstCombiner.h:81
void computeKnownBits(const Value *V, KnownBits &Known, unsigned Depth, const Instruction *CxtI) const
Definition: InstCombiner.h:433
BuilderTy & Builder
Definition: InstCombiner.h:61
AssumptionCache & getAssumptionCache() const
Definition: InstCombiner.h:334
bool MaskedValueIsZero(const Value *V, const APInt &Mask, unsigned Depth=0, const Instruction *CxtI=nullptr) const
Definition: InstCombiner.h:450
OptimizationRemarkEmitter & ORE
Definition: InstCombiner.h:78
Value * getFreelyInverted(Value *V, bool WillInvertAllUses, BuilderTy *Builder, bool &DoesConsume)
Definition: InstCombiner.h:209
const SimplifyQuery & getSimplifyQuery() const
Definition: InstCombiner.h:338
unsigned ComputeMaxSignificantBits(const Value *Op, unsigned Depth=0, const Instruction *CxtI=nullptr) const
Definition: InstCombiner.h:460
void pushUsersToWorkList(Instruction &I)
When an instruction is simplified, add all users of the instruction to the work lists because they mi...
void add(Instruction *I)
Add instruction to the worklist.
void setHasNoUnsignedWrap(bool b=true)
Set or clear the nuw flag on this instruction, which must be an operator which supports this flag.
void copyFastMathFlags(FastMathFlags FMF)
Convenience function for transferring all fast-math flag values to this instruction,...
bool mayWriteToMemory() const LLVM_READONLY
Return true if this instruction may modify memory.
void copyIRFlags(const Value *V, bool IncludeWrapFlags=true)
Convenience method to copy supported exact, fast-math, and (optionally) wrapping flags from V to this...
void setHasNoSignedWrap(bool b=true)
Set or clear the nsw flag on this instruction, which must be an operator which supports this flag.
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
Definition: Instruction.cpp:68
void setAAMetadata(const AAMDNodes &N)
Sets the AA metadata on this instruction from the AAMDNodes structure.
Definition: Metadata.cpp:1764
void andIRFlags(const Value *V)
Logical 'and' of any supported wrapping, exact, and fast-math flags of V and this instruction.
const Instruction * getPrevNonDebugInstruction(bool SkipPseudoOp=false) const
Return a pointer to the previous non-debug instruction in the same basic block as 'this',...
const Function * getFunction() const
Return the function this instruction belongs to.
Definition: Instruction.cpp:72
const Instruction * getNextNonDebugInstruction(bool SkipPseudoOp=false) const
Return a pointer to the next non-debug instruction in the same basic block as 'this',...
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
Definition: Metadata.cpp:1679
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
Definition: Instruction.h:274
std::optional< InstListType::iterator > getInsertionPointAfterDef()
Get the first insertion point at which the result of this instruction is defined.
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.
Definition: Instruction.h:472
void copyMetadata(const Instruction &SrcInst, ArrayRef< unsigned > WL=ArrayRef< unsigned >())
Copy metadata from SrcInst to this instruction.
void moveBefore(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
Class to represent integer types.
Definition: DerivedTypes.h:42
static IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition: Type.cpp:311
A wrapper class for inspecting calls to intrinsic functions.
Definition: IntrinsicInst.h:48
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
Definition: IntrinsicInst.h:55
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:67
LibCallSimplifier - This class implements a collection of optimizations that replace well formed call...
An instruction for reading from memory.
Definition: Instructions.h:176
Metadata node.
Definition: Metadata.h:1069
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition: Metadata.h:1545
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:65
A container for an operand bundle being viewed as a set of values rather than a set of uses.
Definition: InstrTypes.h:1065
unsigned getOpcode() const
Return the opcode for this Instruction or ConstantExpr.
Definition: Operator.h:42
Utility class for integer operators which may exhibit overflow - Add, Sub, Mul, and Shl.
Definition: Operator.h:77
bool hasNoSignedWrap() const
Test whether this operation is known to never undergo signed overflow, aka the nsw property.
Definition: Operator.h:110
bool hasNoUnsignedWrap() const
Test whether this operation is known to never undergo unsigned overflow, aka the nuw property.
Definition: Operator.h:104
bool isCommutative() const
Return true if the instruction is commutative.
Definition: Operator.h:127
static PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Definition: Constants.cpp:1878
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, 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
bool all() const
Returns true if all bits are set.
size_type size() const
Definition: SmallPtrSet.h:94
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Definition: SmallPtrSet.h:452
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:384
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:519
bool empty() const
Definition: SmallVector.h:81
size_t size() const
Definition: SmallVector.h:78
void reserve(size_type N)
Definition: SmallVector.h:663
void push_back(const T &Elt)
Definition: SmallVector.h:413
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1196
An instruction for storing to memory.
Definition: Instructions.h:292
void setVolatile(bool V)
Specify whether this is a volatile store or not.
Definition: Instructions.h:328
void setAlignment(Align Align)
Definition: Instructions.h:337
void setOrdering(AtomicOrdering Ordering)
Sets the ordering constraint of this store instruction.
Definition: Instructions.h:348
Class to represent struct types.
Definition: DerivedTypes.h:218
static 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:45
unsigned getIntegerBitWidth() const
const fltSemantics & getFltSemantics() const
bool isPointerTy() const
True if this is an instance of PointerType.
Definition: Type.h:264
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
bool isStructTy() const
True if this is an instance of StructType.
Definition: Type.h:258
Type * getWithNewBitWidth(unsigned NewBitWidth) const
Given an integer or vector type, change the lane bitwidth to NewBitwidth, whilst keeping the old numb...
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition: Type.h:128
bool canLosslesslyBitCastTo(Type *Ty) const
Return true if this type could be converted with a lossless BitCast to type 'Ty'.
static IntegerType * getInt32Ty(LLVMContext &C)
static IntegerType * getInt64Ty(LLVMContext &C)
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition: Type.h:237
bool isVoidTy() const
Return true if this is 'void'.
Definition: Type.h:139
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition: Type.h:355
static UnaryOperator * CreateWithCopiedFlags(UnaryOps Opc, Value *V, Instruction *CopyO, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Definition: InstrTypes.h:138
static UnaryOperator * CreateFNegFMF(Value *Op, Instruction *FMFSource, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Definition: InstrTypes.h:146
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
Definition: Constants.cpp:1859
A Use represents the edge between a Value definition and its users.
Definition: Use.h:43
void setOperand(unsigned i, Value *Val)
Definition: User.h:233
Value * getOperand(unsigned i) const
Definition: User.h:228
This represents the llvm.va_end intrinsic.
static void ValueIsDeleted(Value *V)
Definition: Value.cpp:1202
static void ValueIsRAUWd(Value *Old, Value *New)
Definition: Value.cpp:1255
LLVM Value Representation.
Definition: Value.h:74
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:811
void setMetadata(unsigned KindID, MDNode *Node)
Set a particular kind of metadata attachment.
Definition: Metadata.cpp:1531
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition: Value.h:434
iterator_range< user_iterator > users()
Definition: Value.h:421
static void dropDroppableUse(Use &U)
Remove the droppable use U.
Definition: Value.cpp:217
const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
Definition: Value.cpp:694
bool use_empty() const
Definition: Value.h:344
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:1075
static constexpr unsigned MaxAlignmentExponent
The maximum alignment for instructions.
Definition: Value.h:810
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:309
void takeName(Value *V)
Transfer the name from V to this value.
Definition: Value.cpp:383
Base class of all SIMD vector types.
Definition: DerivedTypes.h:427
ElementCount getElementCount() const
Return an ElementCount instance to represent the (possibly scalable) number of elements in the vector...
Definition: DerivedTypes.h:665
Represents an op.with.overflow intrinsic.
static constexpr bool isKnownLT(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition: TypeSize.h:218
static constexpr bool isKnownGT(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition: TypeSize.h:225
const ParentTy * getParent() const
Definition: ilist_node.h:32
self_iterator getIterator()
Definition: ilist_node.h:132
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
AttributeMask typeIncompatible(Type *Ty, AttributeSet AS, AttributeSafetyKind ASK=ASK_ALL)
Which attributes cannot be applied to a type.
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.
Definition: BitmaskEnum.h:125
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > Tys={})
Look up the Function declaration of the intrinsic id in the Module M.
Definition: Intrinsics.cpp:731
cst_pred_ty< is_all_ones > m_AllOnes()
Match an integer or vector with all bits set.
Definition: PatternMatch.h:524
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
class_match< BinaryOperator > m_BinOp()
Match an arbitrary binary operation and ignore it.
Definition: PatternMatch.h:100
m_Intrinsic_Ty< Opnd0 >::Ty m_BitReverse(const Opnd0 &Op0)
class_match< Constant > m_Constant()
Match an arbitrary Constant and ignore it.
Definition: PatternMatch.h:165
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)
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.
Definition: PatternMatch.h:982
bool match(Val *V, const Pattern &P)
Definition: PatternMatch.h:49
bind_ty< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
Definition: PatternMatch.h:826
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
Definition: PatternMatch.h:885
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'.
class_match< ConstantInt > m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
Definition: PatternMatch.h:168
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
Definition: PatternMatch.h:592
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.
Definition: PatternMatch.h:782
specific_fpval m_SpecificFP(double V)
Match a specific floating point value or vector with all elements equal to the value.
Definition: PatternMatch.h:928
BinOpPred_match< LHS, RHS, is_logical_shift_op > m_LogicalShift(const LHS &L, const RHS &R)
Matches logical shift operations.
match_combine_and< LTy, RTy > m_CombineAnd(const LTy &L, const RTy &R)
Combine two pattern matchers matching L && R.
Definition: PatternMatch.h:245
MaxMin_match< ICmpInst, LHS, RHS, smin_pred_ty > m_SMin(const LHS &L, const RHS &R)
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.
deferredval_ty< 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()...
Definition: PatternMatch.h:903
cst_pred_ty< is_zero_int > m_ZeroInt()
Match an integer 0 or a vector with all elements equal to 0.
Definition: PatternMatch.h:599
apint_match m_APIntAllowPoison(const APInt *&Res)
Match APInt while allowing poison in splat vector constants.
Definition: PatternMatch.h:305
match_combine_or< match_combine_or< CastInst_match< OpTy, ZExtInst >, CastInst_match< OpTy, SExtInst > >, OpTy > m_ZExtOrSExtOrSelf(const OpTy &Op)
OneUse_match< T > m_OneUse(const T &SubPattern)
Definition: PatternMatch.h:67
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
BinaryOp_match< cst_pred_ty< is_zero_int >, ValTy, Instruction::Sub > m_Neg(const ValTy &V)
Matches a 'Neg' as 'sub 0, V'.
TwoOps_match< V1_t, V2_t, Instruction::ShuffleVector > m_Shuffle(const V1_t &v1, const V2_t &v2)
Matches ShuffleVectorInst independently of mask value.
match_combine_and< class_match< Constant >, match_unless< constantexpr_match > > m_ImmConstant()
Match an arbitrary immediate Constant and ignore it.
Definition: PatternMatch.h:864
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)
MaxMin_match< ICmpInst, LHS, RHS, umax_pred_ty > m_UMax(const LHS &L, const RHS &R)
cst_pred_ty< is_negated_power2 > m_NegatedPower2()
Match a integer or vector negated power-of-2.
Definition: PatternMatch.h:627
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.
Definition: PatternMatch.h:481
m_Intrinsic_Ty< Opnd0, Opnd1, Opnd2 >::Ty m_FShl(const Opnd0 &Op0, const Opnd1 &Op1, const Opnd2 &Op2)
match_combine_or< match_combine_or< MaxMin_match< ICmpInst, LHS, RHS, smax_pred_ty, true >, MaxMin_match< ICmpInst, LHS, RHS, smin_pred_ty, true > >, match_combine_or< MaxMin_match< ICmpInst, LHS, RHS, umax_pred_ty, true >, MaxMin_match< ICmpInst, LHS, RHS, umin_pred_ty, true > > > m_c_MaxOrMin(const LHS &L, const RHS &R)
class_match< UnaryOperator > m_UnOp()
Match an arbitrary unary operation and ignore it.
Definition: PatternMatch.h:95
OverflowingBinaryOp_match< LHS, RHS, Instruction::Sub, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWSub(const LHS &L, const RHS &R)
MaxMin_match< ICmpInst, LHS, RHS, smax_pred_ty > m_SMax(const LHS &L, const RHS &R)
apint_match m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
Definition: PatternMatch.h:299
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".
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
Definition: PatternMatch.h:92
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.
Definition: PatternMatch.h:773
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
m_Intrinsic_Ty< Opnd0 >::Ty m_VecReverse(const Opnd0 &Op0)
apfloat_match m_APFloat(const APFloat *&Res)
Match a ConstantFP or splatted ConstantVector, binding the specified pointer to the contained APFloat...
Definition: PatternMatch.h:316
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
match_combine_or< match_combine_or< MaxMin_match< ICmpInst, LHS, RHS, smax_pred_ty >, MaxMin_match< ICmpInst, LHS, RHS, smin_pred_ty > >, match_combine_or< MaxMin_match< ICmpInst, LHS, RHS, umax_pred_ty >, MaxMin_match< ICmpInst, LHS, RHS, umin_pred_ty > > > m_MaxOrMin(const LHS &L, const RHS &R)
m_Intrinsic_Ty< Opnd0, Opnd1, Opnd2 >::Ty m_FShr(const Opnd0 &Op0, const Opnd1 &Op1, const Opnd2 &Op2)
BinaryOp_match< LHS, RHS, Instruction::SRem > m_SRem(const LHS &L, const RHS &R)
auto m_Undef()
Match an arbitrary undef constant.
Definition: PatternMatch.h:152
BinaryOp_match< cst_pred_ty< is_all_ones >, ValTy, Instruction::Xor, true > m_Not(const ValTy &V)
Matches a 'Not' as 'xor V, -1' or 'xor -1, V'.
m_Intrinsic_Ty< Opnd0 >::Ty m_BSwap(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.
Definition: PatternMatch.h:612
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.
m_Intrinsic_Ty< Opnd0 >::Ty m_FAbs(const Opnd0 &Op0)
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.
m_Intrinsic_Ty< Opnd0, Opnd1 >::Ty m_CopySign(const Opnd0 &Op0, const Opnd1 &Op1)
CastOperator_match< OpTy, Instruction::PtrToInt > m_PtrToInt(const OpTy &Op)
Matches PtrToInt.
MaxMin_match< ICmpInst, LHS, RHS, umin_pred_ty > m_UMin(const LHS &L, const RHS &R)
match_combine_or< LTy, RTy > m_CombineOr(const LTy &L, const RTy &R)
Combine two pattern matchers matching L || R.
Definition: PatternMatch.h:239
@ SingleThread
Synchronized with respect to signal handlers executing in the same thread.
Definition: LLVMContext.h:54
@ System
Synchronized with respect to all concurrently executing threads.
Definition: LLVMContext.h:57
AssignmentMarkerRange getAssignmentMarkers(DIAssignID *ID)
Return a range of dbg.assign intrinsics which use \ID as an operand.
Definition: DebugInfo.cpp:1866
SmallVector< DbgVariableRecord * > getDVRAssignmentMarkers(const Instruction *Inst)
Definition: DebugInfo.h:240
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:443
constexpr double e
Definition: MathExtras.h:47
DiagnosticInfoOptimizationBase::Argument NV
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
cl::opt< bool > EnableKnowledgeRetention
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:353
@ Offset
Definition: DWP.cpp:480
OverflowResult
@ 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.
UnaryFunction for_each(R &&Range, UnaryFunction F)
Provide wrappers to std::for_each which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1732
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.
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,...
bool isSafeToSpeculativelyExecuteWithVariableReplaced(const Instruction *I)
Don't use information from its non-constant operands.
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 ...
RetainedKnowledge simplifyRetainedKnowledge(AssumeInst *Assume, RetainedKnowledge RK, AssumptionCache *AC, DominatorTree *DT)
canonicalize the RetainedKnowledge RK.
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...
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.
Value * getAllocAlignment(const CallBase *V, const TargetLibraryInfo *TLI)
Gets the alignment argument for an aligned_alloc-like function, using either built-in knowledge based...
LLVM_READONLY APFloat maximum(const APFloat &A, const APFloat &B)
Implements IEEE 754-2019 maximum semantics.
Definition: APFloat.h:1604
const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=6)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
Value * simplifyCall(CallBase *Call, Value *Callee, ArrayRef< Value * > Args, const SimplifyQuery &Q)
Given a callsite, callee, and arguments, fold the result or return null.
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:555
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition: MathExtras.h:296
bool isAssumeWithEmptyBundle(const AssumeInst &Assume)
Return true iff the operand bundles of the provided llvm.assume doesn't contain any valuable informat...
Value * getSplatValue(const Value *V)
Get splat value if the input is a splat vector or return nullptr.
constexpr T MinAlign(U A, V B)
A and B are either alignments or offsets.
Definition: MathExtras.h:366
RetainedKnowledge getKnowledgeFromBundle(AssumeInst &Assume, const CallBase::BundleOpInfo &BOI)
This extracts the Knowledge from an element of an operand bundle.
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:242
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 2019 maximumNumber semantics.
Definition: APFloat.h:1563
FPClassTest fneg(FPClassTest Mask)
Return the test mask which returns true if the value's sign bit is flipped.
SelectPatternFlavor
Specific patterns of select instructions we can match.
@ SPF_ABS
Floating point maxnum.
@ SPF_NABS
Absolute value.
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition: MathExtras.h:291
bool isModSet(const ModRefInfo MRI)
Definition: ModRef.h:48
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
@ None
Definition: CodeGenData.h:106
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...
bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
Definition: Function.cpp:1187
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
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)
AssumeInst * buildAssumeFromKnowledge(ArrayRef< RetainedKnowledge > Knowledge, Instruction *CtxI, AssumptionCache *AC=nullptr, DominatorTree *DT=nullptr)
Build and return a new assume created from the provided knowledge if the knowledge in the assume is f...
bool isSafeToSpeculativelyExecute(const Instruction *I, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr, bool UseVariableInfo=true)
Return true if the instruction does not have any effects besides calculating the result and does not ...
FPClassTest inverse_fabs(FPClassTest Mask)
Return the test mask which returns true after fabs is applied to the value.
bool isNotCrossLaneOperation(const Instruction *I)
Return true if the instruction doesn't potentially cross vector lanes.
bool maskIsAllOneOrUndef(Value *Mask)
Given a mask vector of i1, Return true if all of the elements of this predicate mask are known to be ...
Constant * ConstantFoldBinaryOpOperands(unsigned Opcode, Constant *LHS, Constant *RHS, const DataLayout &DL)
Attempt to constant fold a binary operation with the specified operands.
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.
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.
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 2019 minimumNumber semantics.
Definition: APFloat.h:1549
@ And
Bitwise or logical AND of integers.
@ Add
Sum of integers.
@ FAdd
Sum of floats.
ConstantRange computeConstantRangeIncludingKnownBits(const WithCache< const Value * > &V, bool ForSigned, const SimplifyQuery &SQ)
Combine constant ranges from computeConstantRange() and computeKnownBits().
void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
Value * getFreedOperand(const CallBase *CB, const TargetLibraryInfo *TLI)
If this if a call to a free function, return the freed operand.
constexpr unsigned BitWidth
Definition: BitmaskEnum.h:217
bool isDereferenceablePointer(const Value *V, Type *Ty, const DataLayout &DL, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr)
Return true if this is always a dereferenceable pointer.
Definition: Loads.cpp:234
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition: STLExtras.h:1903
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.
std::optional< bool > computeKnownFPSignBit(const Value *V, unsigned Depth, const SimplifyQuery &SQ)
Return false if we can prove that the specified FP value's sign bit is 0.
unsigned Log2(Align A)
Returns the log2 of the alignment.
Definition: Alignment.h:208
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 ...
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_READONLY APFloat minimum(const APFloat &A, const APFloat &B)
Implements IEEE 754-2019 minimum semantics.
Definition: APFloat.h:1577
bool isKnownNegation(const Value *X, const Value *Y, bool NeedNSW=false, bool AllowPoison=true)
Return true if the two given values are negation.
bool isKnownNonNegative(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the give value is known to be non-negative.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:860
#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:760
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.
bool isNonNegative() const
Returns true if this value is known to be non-negative.
Definition: KnownBits.h:100
unsigned countMinTrailingZeros() const
Returns the minimum number of trailing zero bits.
Definition: KnownBits.h:234
unsigned countMaxTrailingZeros() const
Returns the maximum number of trailing zero bits possible.
Definition: KnownBits.h:266
unsigned countMaxPopulation() const
Returns the maximum number of bits that could be one.
Definition: KnownBits.h:281
unsigned getBitWidth() const
Get the bit width of this value.
Definition: KnownBits.h:43
bool isNonZero() const
Returns true if this value is known to be non-zero.
Definition: KnownBits.h:103
unsigned countMinLeadingZeros() const
Returns the minimum number of leading zero bits.
Definition: KnownBits.h:240
bool isNegative() const
Returns true if this value is known to be negative.
Definition: KnownBits.h:97
unsigned countMaxLeadingZeros() const
Returns the maximum number of leading zero bits possible.
Definition: KnownBits.h:272
unsigned countMinPopulation() const
Returns the number of bits known to be one.
Definition: KnownBits.h:278
bool isAllOnes() const
Returns true if value is all one bits.
Definition: KnownBits.h:82
FPClassTest KnownFPClasses
Floating-point classes the value could be one of.
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition: Alignment.h:117
Align valueOrOne() const
For convenience, returns a valid alignment or 1 if undefined.
Definition: Alignment.h:141
A lightweight accessor for an operand bundle meant to be passed around by value.
Definition: InstrTypes.h:1007
StringRef getTagName() const
Return the tag of this operand bundle as a string.
Definition: InstrTypes.h:1026
ArrayRef< Use > Inputs
Definition: InstrTypes.h:1008
Represent one information held inside an operand bundle of an llvm.assume.
Attribute::AttrKind AttrKind
SelectPatternFlavor Flavor
const DataLayout & DL
Definition: SimplifyQuery.h:71
const Instruction * CxtI
Definition: SimplifyQuery.h:75
SimplifyQuery getWithInstruction(const Instruction *I) const