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 KnownBits Known = IC.computeKnownBits(Op0, 0, &II);
592
593 // Create a mask for bits above (ctlz) or below (cttz) the first known one.
594 unsigned PossibleZeros = IsTZ ? Known.countMaxTrailingZeros()
595 : Known.countMaxLeadingZeros();
596 unsigned DefiniteZeros = IsTZ ? Known.countMinTrailingZeros()
597 : Known.countMinLeadingZeros();
598
599 // If all bits above (ctlz) or below (cttz) the first known one are known
600 // zero, this value is constant.
601 // FIXME: This should be in InstSimplify because we're replacing an
602 // instruction with a constant.
603 if (PossibleZeros == DefiniteZeros) {
604 auto *C = ConstantInt::get(Op0->getType(), DefiniteZeros);
605 return IC.replaceInstUsesWith(II, C);
606 }
607
608 // If the input to cttz/ctlz is known to be non-zero,
609 // then change the 'ZeroIsPoison' parameter to 'true'
610 // because we know the zero behavior can't affect the result.
611 if (!Known.One.isZero() ||
613 if (!match(II.getArgOperand(1), m_One()))
614 return IC.replaceOperand(II, 1, IC.Builder.getTrue());
615 }
616
617 // Add range attribute since known bits can't completely reflect what we know.
618 unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
619 if (BitWidth != 1 && !II.hasRetAttr(Attribute::Range) &&
620 !II.getMetadata(LLVMContext::MD_range)) {
621 ConstantRange Range(APInt(BitWidth, DefiniteZeros),
622 APInt(BitWidth, PossibleZeros + 1));
623 II.addRangeRetAttr(Range);
624 return &II;
625 }
626
627 return nullptr;
628}
629
631 assert(II.getIntrinsicID() == Intrinsic::ctpop &&
632 "Expected ctpop intrinsic");
633 Type *Ty = II.getType();
634 unsigned BitWidth = Ty->getScalarSizeInBits();
635 Value *Op0 = II.getArgOperand(0);
636 Value *X, *Y;
637
638 // ctpop(bitreverse(x)) -> ctpop(x)
639 // ctpop(bswap(x)) -> ctpop(x)
640 if (match(Op0, m_BitReverse(m_Value(X))) || match(Op0, m_BSwap(m_Value(X))))
641 return IC.replaceOperand(II, 0, X);
642
643 // ctpop(rot(x)) -> ctpop(x)
644 if ((match(Op0, m_FShl(m_Value(X), m_Value(Y), m_Value())) ||
645 match(Op0, m_FShr(m_Value(X), m_Value(Y), m_Value()))) &&
646 X == Y)
647 return IC.replaceOperand(II, 0, X);
648
649 // ctpop(x | -x) -> bitwidth - cttz(x, false)
650 if (Op0->hasOneUse() &&
651 match(Op0, m_c_Or(m_Value(X), m_Neg(m_Deferred(X))))) {
652 auto *Cttz = IC.Builder.CreateIntrinsic(Intrinsic::cttz, Ty,
653 {X, IC.Builder.getFalse()});
654 auto *Bw = ConstantInt::get(Ty, APInt(BitWidth, BitWidth));
655 return IC.replaceInstUsesWith(II, IC.Builder.CreateSub(Bw, Cttz));
656 }
657
658 // ctpop(~x & (x - 1)) -> cttz(x, false)
659 if (match(Op0,
661 Function *F =
662 Intrinsic::getOrInsertDeclaration(II.getModule(), Intrinsic::cttz, Ty);
663 return CallInst::Create(F, {X, IC.Builder.getFalse()});
664 }
665
666 // Zext doesn't change the number of set bits, so narrow:
667 // ctpop (zext X) --> zext (ctpop X)
668 if (match(Op0, m_OneUse(m_ZExt(m_Value(X))))) {
669 Value *NarrowPop = IC.Builder.CreateUnaryIntrinsic(Intrinsic::ctpop, X);
670 return CastInst::Create(Instruction::ZExt, NarrowPop, Ty);
671 }
672
673 KnownBits Known(BitWidth);
674 IC.computeKnownBits(Op0, Known, 0, &II);
675
676 // If all bits are zero except for exactly one fixed bit, then the result
677 // must be 0 or 1, and we can get that answer by shifting to LSB:
678 // ctpop (X & 32) --> (X & 32) >> 5
679 // TODO: Investigate removing this as its likely unnecessary given the below
680 // `isKnownToBeAPowerOfTwo` check.
681 if ((~Known.Zero).isPowerOf2())
682 return BinaryOperator::CreateLShr(
683 Op0, ConstantInt::get(Ty, (~Known.Zero).exactLogBase2()));
684
685 // More generally we can also handle non-constant power of 2 patterns such as
686 // shl/shr(Pow2, X), (X & -X), etc... by transforming:
687 // ctpop(Pow2OrZero) --> icmp ne X, 0
688 if (IC.isKnownToBeAPowerOfTwo(Op0, /* OrZero */ true))
689 return CastInst::Create(Instruction::ZExt,
692 Ty);
693
694 // Add range attribute since known bits can't completely reflect what we know.
695 if (BitWidth != 1) {
696 ConstantRange OldRange =
697 II.getRange().value_or(ConstantRange::getFull(BitWidth));
698
699 unsigned Lower = Known.countMinPopulation();
700 unsigned Upper = Known.countMaxPopulation() + 1;
701
702 if (Lower == 0 && OldRange.contains(APInt::getZero(BitWidth)) &&
704 Lower = 1;
705
708
709 if (Range != OldRange) {
710 II.addRangeRetAttr(Range);
711 return &II;
712 }
713 }
714
715 return nullptr;
716}
717
718/// Convert a table lookup to shufflevector if the mask is constant.
719/// This could benefit tbl1 if the mask is { 7,6,5,4,3,2,1,0 }, in
720/// which case we could lower the shufflevector with rev64 instructions
721/// as it's actually a byte reverse.
723 InstCombiner::BuilderTy &Builder) {
724 // Bail out if the mask is not a constant.
725 auto *C = dyn_cast<Constant>(II.getArgOperand(1));
726 if (!C)
727 return nullptr;
728
729 auto *VecTy = cast<FixedVectorType>(II.getType());
730 unsigned NumElts = VecTy->getNumElements();
731
732 // Only perform this transformation for <8 x i8> vector types.
733 if (!VecTy->getElementType()->isIntegerTy(8) || NumElts != 8)
734 return nullptr;
735
736 int Indexes[8];
737
738 for (unsigned I = 0; I < NumElts; ++I) {
739 Constant *COp = C->getAggregateElement(I);
740
741 if (!COp || !isa<ConstantInt>(COp))
742 return nullptr;
743
744 Indexes[I] = cast<ConstantInt>(COp)->getLimitedValue();
745
746 // Make sure the mask indices are in range.
747 if ((unsigned)Indexes[I] >= NumElts)
748 return nullptr;
749 }
750
751 auto *V1 = II.getArgOperand(0);
752 auto *V2 = Constant::getNullValue(V1->getType());
753 return Builder.CreateShuffleVector(V1, V2, ArrayRef(Indexes));
754}
755
756// Returns true iff the 2 intrinsics have the same operands, limiting the
757// comparison to the first NumOperands.
758static bool haveSameOperands(const IntrinsicInst &I, const IntrinsicInst &E,
759 unsigned NumOperands) {
760 assert(I.arg_size() >= NumOperands && "Not enough operands");
761 assert(E.arg_size() >= NumOperands && "Not enough operands");
762 for (unsigned i = 0; i < NumOperands; i++)
763 if (I.getArgOperand(i) != E.getArgOperand(i))
764 return false;
765 return true;
766}
767
768// Remove trivially empty start/end intrinsic ranges, i.e. a start
769// immediately followed by an end (ignoring debuginfo or other
770// start/end intrinsics in between). As this handles only the most trivial
771// cases, tracking the nesting level is not needed:
772//
773// call @llvm.foo.start(i1 0)
774// call @llvm.foo.start(i1 0) ; This one won't be skipped: it will be removed
775// call @llvm.foo.end(i1 0)
776// call @llvm.foo.end(i1 0) ; &I
777static bool
779 std::function<bool(const IntrinsicInst &)> IsStart) {
780 // We start from the end intrinsic and scan backwards, so that InstCombine
781 // has already processed (and potentially removed) all the instructions
782 // before the end intrinsic.
783 BasicBlock::reverse_iterator BI(EndI), BE(EndI.getParent()->rend());
784 for (; BI != BE; ++BI) {
785 if (auto *I = dyn_cast<IntrinsicInst>(&*BI)) {
786 if (I->isDebugOrPseudoInst() ||
787 I->getIntrinsicID() == EndI.getIntrinsicID())
788 continue;
789 if (IsStart(*I)) {
790 if (haveSameOperands(EndI, *I, EndI.arg_size())) {
792 IC.eraseInstFromFunction(EndI);
793 return true;
794 }
795 // Skip start intrinsics that don't pair with this end intrinsic.
796 continue;
797 }
798 }
799 break;
800 }
801
802 return false;
803}
804
806 removeTriviallyEmptyRange(I, *this, [](const IntrinsicInst &I) {
807 return I.getIntrinsicID() == Intrinsic::vastart ||
808 I.getIntrinsicID() == Intrinsic::vacopy;
809 });
810 return nullptr;
811}
812
814 assert(Call.arg_size() > 1 && "Need at least 2 args to swap");
815 Value *Arg0 = Call.getArgOperand(0), *Arg1 = Call.getArgOperand(1);
816 if (isa<Constant>(Arg0) && !isa<Constant>(Arg1)) {
817 Call.setArgOperand(0, Arg1);
818 Call.setArgOperand(1, Arg0);
819 return &Call;
820 }
821 return nullptr;
822}
823
824/// Creates a result tuple for an overflow intrinsic \p II with a given
825/// \p Result and a constant \p Overflow value.
827 Constant *Overflow) {
828 Constant *V[] = {PoisonValue::get(Result->getType()), Overflow};
829 StructType *ST = cast<StructType>(II->getType());
831 return InsertValueInst::Create(Struct, Result, 0);
832}
833
835InstCombinerImpl::foldIntrinsicWithOverflowCommon(IntrinsicInst *II) {
836 WithOverflowInst *WO = cast<WithOverflowInst>(II);
837 Value *OperationResult = nullptr;
838 Constant *OverflowResult = nullptr;
839 if (OptimizeOverflowCheck(WO->getBinaryOp(), WO->isSigned(), WO->getLHS(),
840 WO->getRHS(), *WO, OperationResult, OverflowResult))
841 return createOverflowTuple(WO, OperationResult, OverflowResult);
842 return nullptr;
843}
844
845static bool inputDenormalIsIEEE(const Function &F, const Type *Ty) {
846 Ty = Ty->getScalarType();
847 return F.getDenormalMode(Ty->getFltSemantics()).Input == DenormalMode::IEEE;
848}
849
850static bool inputDenormalIsDAZ(const Function &F, const Type *Ty) {
851 Ty = Ty->getScalarType();
852 return F.getDenormalMode(Ty->getFltSemantics()).inputsAreZero();
853}
854
855/// \returns the compare predicate type if the test performed by
856/// llvm.is.fpclass(x, \p Mask) is equivalent to fcmp o__ x, 0.0 with the
857/// floating-point environment assumed for \p F for type \p Ty
859 const Function &F, Type *Ty) {
860 switch (static_cast<unsigned>(Mask)) {
861 case fcZero:
862 if (inputDenormalIsIEEE(F, Ty))
863 return FCmpInst::FCMP_OEQ;
864 break;
865 case fcZero | fcSubnormal:
866 if (inputDenormalIsDAZ(F, Ty))
867 return FCmpInst::FCMP_OEQ;
868 break;
869 case fcPositive | fcNegZero:
870 if (inputDenormalIsIEEE(F, Ty))
871 return FCmpInst::FCMP_OGE;
872 break;
874 if (inputDenormalIsDAZ(F, Ty))
875 return FCmpInst::FCMP_OGE;
876 break;
878 if (inputDenormalIsIEEE(F, Ty))
879 return FCmpInst::FCMP_OGT;
880 break;
881 case fcNegative | fcPosZero:
882 if (inputDenormalIsIEEE(F, Ty))
883 return FCmpInst::FCMP_OLE;
884 break;
886 if (inputDenormalIsDAZ(F, Ty))
887 return FCmpInst::FCMP_OLE;
888 break;
890 if (inputDenormalIsIEEE(F, Ty))
891 return FCmpInst::FCMP_OLT;
892 break;
893 case fcPosNormal | fcPosInf:
894 if (inputDenormalIsDAZ(F, Ty))
895 return FCmpInst::FCMP_OGT;
896 break;
897 case fcNegNormal | fcNegInf:
898 if (inputDenormalIsDAZ(F, Ty))
899 return FCmpInst::FCMP_OLT;
900 break;
901 case ~fcZero & ~fcNan:
902 if (inputDenormalIsIEEE(F, Ty))
903 return FCmpInst::FCMP_ONE;
904 break;
905 case ~(fcZero | fcSubnormal) & ~fcNan:
906 if (inputDenormalIsDAZ(F, Ty))
907 return FCmpInst::FCMP_ONE;
908 break;
909 default:
910 break;
911 }
912
914}
915
916Instruction *InstCombinerImpl::foldIntrinsicIsFPClass(IntrinsicInst &II) {
917 Value *Src0 = II.getArgOperand(0);
918 Value *Src1 = II.getArgOperand(1);
919 const ConstantInt *CMask = cast<ConstantInt>(Src1);
920 FPClassTest Mask = static_cast<FPClassTest>(CMask->getZExtValue());
921 const bool IsUnordered = (Mask & fcNan) == fcNan;
922 const bool IsOrdered = (Mask & fcNan) == fcNone;
923 const FPClassTest OrderedMask = Mask & ~fcNan;
924 const FPClassTest OrderedInvertedMask = ~OrderedMask & ~fcNan;
925
926 const bool IsStrict =
927 II.getFunction()->getAttributes().hasFnAttr(Attribute::StrictFP);
928
929 Value *FNegSrc;
930 if (match(Src0, m_FNeg(m_Value(FNegSrc)))) {
931 // is.fpclass (fneg x), mask -> is.fpclass x, (fneg mask)
932
933 II.setArgOperand(1, ConstantInt::get(Src1->getType(), fneg(Mask)));
934 return replaceOperand(II, 0, FNegSrc);
935 }
936
937 Value *FAbsSrc;
938 if (match(Src0, m_FAbs(m_Value(FAbsSrc)))) {
939 II.setArgOperand(1, ConstantInt::get(Src1->getType(), inverse_fabs(Mask)));
940 return replaceOperand(II, 0, FAbsSrc);
941 }
942
943 if ((OrderedMask == fcInf || OrderedInvertedMask == fcInf) &&
944 (IsOrdered || IsUnordered) && !IsStrict) {
945 // is.fpclass(x, fcInf) -> fcmp oeq fabs(x), +inf
946 // is.fpclass(x, ~fcInf) -> fcmp one fabs(x), +inf
947 // is.fpclass(x, fcInf|fcNan) -> fcmp ueq fabs(x), +inf
948 // is.fpclass(x, ~(fcInf|fcNan)) -> fcmp une fabs(x), +inf
952 if (OrderedInvertedMask == fcInf)
953 Pred = IsUnordered ? FCmpInst::FCMP_UNE : FCmpInst::FCMP_ONE;
954
955 Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, Src0);
956 Value *CmpInf = Builder.CreateFCmp(Pred, Fabs, Inf);
957 CmpInf->takeName(&II);
958 return replaceInstUsesWith(II, CmpInf);
959 }
960
961 if ((OrderedMask == fcPosInf || OrderedMask == fcNegInf) &&
962 (IsOrdered || IsUnordered) && !IsStrict) {
963 // is.fpclass(x, fcPosInf) -> fcmp oeq x, +inf
964 // is.fpclass(x, fcNegInf) -> fcmp oeq x, -inf
965 // is.fpclass(x, fcPosInf|fcNan) -> fcmp ueq x, +inf
966 // is.fpclass(x, fcNegInf|fcNan) -> fcmp ueq x, -inf
967 Constant *Inf =
968 ConstantFP::getInfinity(Src0->getType(), OrderedMask == fcNegInf);
969 Value *EqInf = IsUnordered ? Builder.CreateFCmpUEQ(Src0, Inf)
970 : Builder.CreateFCmpOEQ(Src0, Inf);
971
972 EqInf->takeName(&II);
973 return replaceInstUsesWith(II, EqInf);
974 }
975
976 if ((OrderedInvertedMask == fcPosInf || OrderedInvertedMask == fcNegInf) &&
977 (IsOrdered || IsUnordered) && !IsStrict) {
978 // is.fpclass(x, ~fcPosInf) -> fcmp one x, +inf
979 // is.fpclass(x, ~fcNegInf) -> fcmp one x, -inf
980 // is.fpclass(x, ~fcPosInf|fcNan) -> fcmp une x, +inf
981 // is.fpclass(x, ~fcNegInf|fcNan) -> fcmp une x, -inf
983 OrderedInvertedMask == fcNegInf);
984 Value *NeInf = IsUnordered ? Builder.CreateFCmpUNE(Src0, Inf)
985 : Builder.CreateFCmpONE(Src0, Inf);
986 NeInf->takeName(&II);
987 return replaceInstUsesWith(II, NeInf);
988 }
989
990 if (Mask == fcNan && !IsStrict) {
991 // Equivalent of isnan. Replace with standard fcmp if we don't care about FP
992 // exceptions.
993 Value *IsNan =
995 IsNan->takeName(&II);
996 return replaceInstUsesWith(II, IsNan);
997 }
998
999 if (Mask == (~fcNan & fcAllFlags) && !IsStrict) {
1000 // Equivalent of !isnan. Replace with standard fcmp.
1001 Value *FCmp =
1003 FCmp->takeName(&II);
1004 return replaceInstUsesWith(II, FCmp);
1005 }
1006
1008
1009 // Try to replace with an fcmp with 0
1010 //
1011 // is.fpclass(x, fcZero) -> fcmp oeq x, 0.0
1012 // is.fpclass(x, fcZero | fcNan) -> fcmp ueq x, 0.0
1013 // is.fpclass(x, ~fcZero & ~fcNan) -> fcmp one x, 0.0
1014 // is.fpclass(x, ~fcZero) -> fcmp une x, 0.0
1015 //
1016 // is.fpclass(x, fcPosSubnormal | fcPosNormal | fcPosInf) -> fcmp ogt x, 0.0
1017 // is.fpclass(x, fcPositive | fcNegZero) -> fcmp oge x, 0.0
1018 //
1019 // is.fpclass(x, fcNegSubnormal | fcNegNormal | fcNegInf) -> fcmp olt x, 0.0
1020 // is.fpclass(x, fcNegative | fcPosZero) -> fcmp ole x, 0.0
1021 //
1022 if (!IsStrict && (IsOrdered || IsUnordered) &&
1023 (PredType = fpclassTestIsFCmp0(OrderedMask, *II.getFunction(),
1024 Src0->getType())) !=
1027 // Equivalent of == 0.
1028 Value *FCmp = Builder.CreateFCmp(
1029 IsUnordered ? FCmpInst::getUnorderedPredicate(PredType) : PredType,
1030 Src0, Zero);
1031
1032 FCmp->takeName(&II);
1033 return replaceInstUsesWith(II, FCmp);
1034 }
1035
1036 KnownFPClass Known = computeKnownFPClass(Src0, Mask, &II);
1037
1038 // Clear test bits we know must be false from the source value.
1039 // fp_class (nnan x), qnan|snan|other -> fp_class (nnan x), other
1040 // fp_class (ninf x), ninf|pinf|other -> fp_class (ninf x), other
1041 if ((Mask & Known.KnownFPClasses) != Mask) {
1042 II.setArgOperand(
1043 1, ConstantInt::get(Src1->getType(), Mask & Known.KnownFPClasses));
1044 return &II;
1045 }
1046
1047 // If none of the tests which can return false are possible, fold to true.
1048 // fp_class (nnan x), ~(qnan|snan) -> true
1049 // fp_class (ninf x), ~(ninf|pinf) -> true
1050 if (Mask == Known.KnownFPClasses)
1051 return replaceInstUsesWith(II, ConstantInt::get(II.getType(), true));
1052
1053 return nullptr;
1054}
1055
1056static std::optional<bool> getKnownSign(Value *Op, const SimplifyQuery &SQ) {
1057 KnownBits Known = computeKnownBits(Op, /*Depth=*/0, SQ);
1058 if (Known.isNonNegative())
1059 return false;
1060 if (Known.isNegative())
1061 return true;
1062
1063 Value *X, *Y;
1064 if (match(Op, m_NSWSub(m_Value(X), m_Value(Y))))
1066
1067 return std::nullopt;
1068}
1069
1070static std::optional<bool> getKnownSignOrZero(Value *Op,
1071 const SimplifyQuery &SQ) {
1072 if (std::optional<bool> Sign = getKnownSign(Op, SQ))
1073 return Sign;
1074
1075 Value *X, *Y;
1076 if (match(Op, m_NSWSub(m_Value(X), m_Value(Y))))
1078
1079 return std::nullopt;
1080}
1081
1082/// Return true if two values \p Op0 and \p Op1 are known to have the same sign.
1083static bool signBitMustBeTheSame(Value *Op0, Value *Op1,
1084 const SimplifyQuery &SQ) {
1085 std::optional<bool> Known1 = getKnownSign(Op1, SQ);
1086 if (!Known1)
1087 return false;
1088 std::optional<bool> Known0 = getKnownSign(Op0, SQ);
1089 if (!Known0)
1090 return false;
1091 return *Known0 == *Known1;
1092}
1093
1094/// Try to canonicalize min/max(X + C0, C1) as min/max(X, C1 - C0) + C0. This
1095/// can trigger other combines.
1097 InstCombiner::BuilderTy &Builder) {
1098 Intrinsic::ID MinMaxID = II->getIntrinsicID();
1099 assert((MinMaxID == Intrinsic::smax || MinMaxID == Intrinsic::smin ||
1100 MinMaxID == Intrinsic::umax || MinMaxID == Intrinsic::umin) &&
1101 "Expected a min or max intrinsic");
1102
1103 // TODO: Match vectors with undef elements, but undef may not propagate.
1104 Value *Op0 = II->getArgOperand(0), *Op1 = II->getArgOperand(1);
1105 Value *X;
1106 const APInt *C0, *C1;
1107 if (!match(Op0, m_OneUse(m_Add(m_Value(X), m_APInt(C0)))) ||
1108 !match(Op1, m_APInt(C1)))
1109 return nullptr;
1110
1111 // Check for necessary no-wrap and overflow constraints.
1112 bool IsSigned = MinMaxID == Intrinsic::smax || MinMaxID == Intrinsic::smin;
1113 auto *Add = cast<BinaryOperator>(Op0);
1114 if ((IsSigned && !Add->hasNoSignedWrap()) ||
1115 (!IsSigned && !Add->hasNoUnsignedWrap()))
1116 return nullptr;
1117
1118 // If the constant difference overflows, then instsimplify should reduce the
1119 // min/max to the add or C1.
1120 bool Overflow;
1121 APInt CDiff =
1122 IsSigned ? C1->ssub_ov(*C0, Overflow) : C1->usub_ov(*C0, Overflow);
1123 assert(!Overflow && "Expected simplify of min/max");
1124
1125 // min/max (add X, C0), C1 --> add (min/max X, C1 - C0), C0
1126 // Note: the "mismatched" no-overflow setting does not propagate.
1127 Constant *NewMinMaxC = ConstantInt::get(II->getType(), CDiff);
1128 Value *NewMinMax = Builder.CreateBinaryIntrinsic(MinMaxID, X, NewMinMaxC);
1129 return IsSigned ? BinaryOperator::CreateNSWAdd(NewMinMax, Add->getOperand(1))
1130 : BinaryOperator::CreateNUWAdd(NewMinMax, Add->getOperand(1));
1131}
1132/// Match a sadd_sat or ssub_sat which is using min/max to clamp the value.
1133Instruction *InstCombinerImpl::matchSAddSubSat(IntrinsicInst &MinMax1) {
1134 Type *Ty = MinMax1.getType();
1135
1136 // We are looking for a tree of:
1137 // max(INT_MIN, min(INT_MAX, add(sext(A), sext(B))))
1138 // Where the min and max could be reversed
1139 Instruction *MinMax2;
1141 const APInt *MinValue, *MaxValue;
1142 if (match(&MinMax1, m_SMin(m_Instruction(MinMax2), m_APInt(MaxValue)))) {
1143 if (!match(MinMax2, m_SMax(m_BinOp(AddSub), m_APInt(MinValue))))
1144 return nullptr;
1145 } else if (match(&MinMax1,
1146 m_SMax(m_Instruction(MinMax2), m_APInt(MinValue)))) {
1147 if (!match(MinMax2, m_SMin(m_BinOp(AddSub), m_APInt(MaxValue))))
1148 return nullptr;
1149 } else
1150 return nullptr;
1151
1152 // Check that the constants clamp a saturate, and that the new type would be
1153 // sensible to convert to.
1154 if (!(*MaxValue + 1).isPowerOf2() || -*MinValue != *MaxValue + 1)
1155 return nullptr;
1156 // In what bitwidth can this be treated as saturating arithmetics?
1157 unsigned NewBitWidth = (*MaxValue + 1).logBase2() + 1;
1158 // FIXME: This isn't quite right for vectors, but using the scalar type is a
1159 // good first approximation for what should be done there.
1160 if (!shouldChangeType(Ty->getScalarType()->getIntegerBitWidth(), NewBitWidth))
1161 return nullptr;
1162
1163 // Also make sure that the inner min/max and the add/sub have one use.
1164 if (!MinMax2->hasOneUse() || !AddSub->hasOneUse())
1165 return nullptr;
1166
1167 // Create the new type (which can be a vector type)
1168 Type *NewTy = Ty->getWithNewBitWidth(NewBitWidth);
1169
1170 Intrinsic::ID IntrinsicID;
1171 if (AddSub->getOpcode() == Instruction::Add)
1172 IntrinsicID = Intrinsic::sadd_sat;
1173 else if (AddSub->getOpcode() == Instruction::Sub)
1174 IntrinsicID = Intrinsic::ssub_sat;
1175 else
1176 return nullptr;
1177
1178 // The two operands of the add/sub must be nsw-truncatable to the NewTy. This
1179 // is usually achieved via a sext from a smaller type.
1180 if (ComputeMaxSignificantBits(AddSub->getOperand(0), 0, AddSub) >
1181 NewBitWidth ||
1182 ComputeMaxSignificantBits(AddSub->getOperand(1), 0, AddSub) > NewBitWidth)
1183 return nullptr;
1184
1185 // Finally create and return the sat intrinsic, truncated to the new type
1186 Value *AT = Builder.CreateTrunc(AddSub->getOperand(0), NewTy);
1187 Value *BT = Builder.CreateTrunc(AddSub->getOperand(1), NewTy);
1188 Value *Sat = Builder.CreateIntrinsic(IntrinsicID, NewTy, {AT, BT});
1189 return CastInst::Create(Instruction::SExt, Sat, Ty);
1190}
1191
1192
1193/// If we have a clamp pattern like max (min X, 42), 41 -- where the output
1194/// can only be one of two possible constant values -- turn that into a select
1195/// of constants.
1197 InstCombiner::BuilderTy &Builder) {
1198 Value *I0 = II->getArgOperand(0), *I1 = II->getArgOperand(1);
1199 Value *X;
1200 const APInt *C0, *C1;
1201 if (!match(I1, m_APInt(C1)) || !I0->hasOneUse())
1202 return nullptr;
1203
1205 switch (II->getIntrinsicID()) {
1206 case Intrinsic::smax:
1207 if (match(I0, m_SMin(m_Value(X), m_APInt(C0))) && *C0 == *C1 + 1)
1208 Pred = ICmpInst::ICMP_SGT;
1209 break;
1210 case Intrinsic::smin:
1211 if (match(I0, m_SMax(m_Value(X), m_APInt(C0))) && *C1 == *C0 + 1)
1212 Pred = ICmpInst::ICMP_SLT;
1213 break;
1214 case Intrinsic::umax:
1215 if (match(I0, m_UMin(m_Value(X), m_APInt(C0))) && *C0 == *C1 + 1)
1216 Pred = ICmpInst::ICMP_UGT;
1217 break;
1218 case Intrinsic::umin:
1219 if (match(I0, m_UMax(m_Value(X), m_APInt(C0))) && *C1 == *C0 + 1)
1220 Pred = ICmpInst::ICMP_ULT;
1221 break;
1222 default:
1223 llvm_unreachable("Expected min/max intrinsic");
1224 }
1225 if (Pred == CmpInst::BAD_ICMP_PREDICATE)
1226 return nullptr;
1227
1228 // max (min X, 42), 41 --> X > 41 ? 42 : 41
1229 // min (max X, 42), 43 --> X < 43 ? 42 : 43
1230 Value *Cmp = Builder.CreateICmp(Pred, X, I1);
1231 return SelectInst::Create(Cmp, ConstantInt::get(II->getType(), *C0), I1);
1232}
1233
1234/// If this min/max has a constant operand and an operand that is a matching
1235/// min/max with a constant operand, constant-fold the 2 constant operands.
1237 IRBuilderBase &Builder,
1238 const SimplifyQuery &SQ) {
1239 Intrinsic::ID MinMaxID = II->getIntrinsicID();
1240 auto *LHS = dyn_cast<MinMaxIntrinsic>(II->getArgOperand(0));
1241 if (!LHS)
1242 return nullptr;
1243
1244 Constant *C0, *C1;
1245 if (!match(LHS->getArgOperand(1), m_ImmConstant(C0)) ||
1246 !match(II->getArgOperand(1), m_ImmConstant(C1)))
1247 return nullptr;
1248
1249 // max (max X, C0), C1 --> max X, (max C0, C1)
1250 // min (min X, C0), C1 --> min X, (min C0, C1)
1251 // umax (smax X, nneg C0), nneg C1 --> smax X, (umax C0, C1)
1252 // smin (umin X, nneg C0), nneg C1 --> umin X, (smin C0, C1)
1253 Intrinsic::ID InnerMinMaxID = LHS->getIntrinsicID();
1254 if (InnerMinMaxID != MinMaxID &&
1255 !(((MinMaxID == Intrinsic::umax && InnerMinMaxID == Intrinsic::smax) ||
1256 (MinMaxID == Intrinsic::smin && InnerMinMaxID == Intrinsic::umin)) &&
1257 isKnownNonNegative(C0, SQ) && isKnownNonNegative(C1, SQ)))
1258 return nullptr;
1259
1261 Value *CondC = Builder.CreateICmp(Pred, C0, C1);
1262 Value *NewC = Builder.CreateSelect(CondC, C0, C1);
1263 return Builder.CreateIntrinsic(InnerMinMaxID, II->getType(),
1264 {LHS->getArgOperand(0), NewC});
1265}
1266
1267/// If this min/max has a matching min/max operand with a constant, try to push
1268/// the constant operand into this instruction. This can enable more folds.
1269static Instruction *
1271 InstCombiner::BuilderTy &Builder) {
1272 // Match and capture a min/max operand candidate.
1273 Value *X, *Y;
1274 Constant *C;
1275 Instruction *Inner;
1277 m_Instruction(Inner),
1279 m_Value(Y))))
1280 return nullptr;
1281
1282 // The inner op must match. Check for constants to avoid infinite loops.
1283 Intrinsic::ID MinMaxID = II->getIntrinsicID();
1284 auto *InnerMM = dyn_cast<IntrinsicInst>(Inner);
1285 if (!InnerMM || InnerMM->getIntrinsicID() != MinMaxID ||
1287 return nullptr;
1288
1289 // max (max X, C), Y --> max (max X, Y), C
1291 MinMaxID, II->getType());
1292 Value *NewInner = Builder.CreateBinaryIntrinsic(MinMaxID, X, Y);
1293 NewInner->takeName(Inner);
1294 return CallInst::Create(MinMax, {NewInner, C});
1295}
1296
1297/// Reduce a sequence of min/max intrinsics with a common operand.
1299 // Match 3 of the same min/max ops. Example: umin(umin(), umin()).
1300 auto *LHS = dyn_cast<IntrinsicInst>(II->getArgOperand(0));
1301 auto *RHS = dyn_cast<IntrinsicInst>(II->getArgOperand(1));
1302 Intrinsic::ID MinMaxID = II->getIntrinsicID();
1303 if (!LHS || !RHS || LHS->getIntrinsicID() != MinMaxID ||
1304 RHS->getIntrinsicID() != MinMaxID ||
1305 (!LHS->hasOneUse() && !RHS->hasOneUse()))
1306 return nullptr;
1307
1308 Value *A = LHS->getArgOperand(0);
1309 Value *B = LHS->getArgOperand(1);
1310 Value *C = RHS->getArgOperand(0);
1311 Value *D = RHS->getArgOperand(1);
1312
1313 // Look for a common operand.
1314 Value *MinMaxOp = nullptr;
1315 Value *ThirdOp = nullptr;
1316 if (LHS->hasOneUse()) {
1317 // If the LHS is only used in this chain and the RHS is used outside of it,
1318 // reuse the RHS min/max because that will eliminate the LHS.
1319 if (D == A || C == A) {
1320 // min(min(a, b), min(c, a)) --> min(min(c, a), b)
1321 // min(min(a, b), min(a, d)) --> min(min(a, d), b)
1322 MinMaxOp = RHS;
1323 ThirdOp = B;
1324 } else if (D == B || C == B) {
1325 // min(min(a, b), min(c, b)) --> min(min(c, b), a)
1326 // min(min(a, b), min(b, d)) --> min(min(b, d), a)
1327 MinMaxOp = RHS;
1328 ThirdOp = A;
1329 }
1330 } else {
1331 assert(RHS->hasOneUse() && "Expected one-use operand");
1332 // Reuse the LHS. This will eliminate the RHS.
1333 if (D == A || D == B) {
1334 // min(min(a, b), min(c, a)) --> min(min(a, b), c)
1335 // min(min(a, b), min(c, b)) --> min(min(a, b), c)
1336 MinMaxOp = LHS;
1337 ThirdOp = C;
1338 } else if (C == A || C == B) {
1339 // min(min(a, b), min(b, d)) --> min(min(a, b), d)
1340 // min(min(a, b), min(c, b)) --> min(min(a, b), d)
1341 MinMaxOp = LHS;
1342 ThirdOp = D;
1343 }
1344 }
1345
1346 if (!MinMaxOp || !ThirdOp)
1347 return nullptr;
1348
1349 Module *Mod = II->getModule();
1350 Function *MinMax =
1351 Intrinsic::getOrInsertDeclaration(Mod, MinMaxID, II->getType());
1352 return CallInst::Create(MinMax, { MinMaxOp, ThirdOp });
1353}
1354
1355/// If all arguments of the intrinsic are unary shuffles with the same mask,
1356/// try to shuffle after the intrinsic.
1357static Instruction *
1359 InstCombiner::BuilderTy &Builder) {
1360 // TODO: This should be extended to handle other intrinsics like fshl, ctpop,
1361 // etc. Use llvm::isTriviallyVectorizable() and related to determine
1362 // which intrinsics are safe to shuffle?
1363 switch (II->getIntrinsicID()) {
1364 case Intrinsic::smax:
1365 case Intrinsic::smin:
1366 case Intrinsic::umax:
1367 case Intrinsic::umin:
1368 case Intrinsic::fma:
1369 case Intrinsic::fshl:
1370 case Intrinsic::fshr:
1371 break;
1372 default:
1373 return nullptr;
1374 }
1375
1376 Value *X;
1377 ArrayRef<int> Mask;
1378 if (!match(II->getArgOperand(0),
1379 m_Shuffle(m_Value(X), m_Undef(), m_Mask(Mask))))
1380 return nullptr;
1381
1382 // At least 1 operand must have 1 use because we are creating 2 instructions.
1383 if (none_of(II->args(), [](Value *V) { return V->hasOneUse(); }))
1384 return nullptr;
1385
1386 // See if all arguments are shuffled with the same mask.
1387 SmallVector<Value *, 4> NewArgs(II->arg_size());
1388 NewArgs[0] = X;
1389 Type *SrcTy = X->getType();
1390 for (unsigned i = 1, e = II->arg_size(); i != e; ++i) {
1391 if (!match(II->getArgOperand(i),
1392 m_Shuffle(m_Value(X), m_Undef(), m_SpecificMask(Mask))) ||
1393 X->getType() != SrcTy)
1394 return nullptr;
1395 NewArgs[i] = X;
1396 }
1397
1398 // intrinsic (shuf X, M), (shuf Y, M), ... --> shuf (intrinsic X, Y, ...), M
1399 Instruction *FPI = isa<FPMathOperator>(II) ? II : nullptr;
1400 Value *NewIntrinsic =
1401 Builder.CreateIntrinsic(II->getIntrinsicID(), SrcTy, NewArgs, FPI);
1402 return new ShuffleVectorInst(NewIntrinsic, Mask);
1403}
1404
1405/// Fold the following cases and accepts bswap and bitreverse intrinsics:
1406/// bswap(logic_op(bswap(x), y)) --> logic_op(x, bswap(y))
1407/// bswap(logic_op(bswap(x), bswap(y))) --> logic_op(x, y) (ignores multiuse)
1408template <Intrinsic::ID IntrID>
1410 InstCombiner::BuilderTy &Builder) {
1411 static_assert(IntrID == Intrinsic::bswap || IntrID == Intrinsic::bitreverse,
1412 "This helper only supports BSWAP and BITREVERSE intrinsics");
1413
1414 Value *X, *Y;
1415 // Find bitwise logic op. Check that it is a BinaryOperator explicitly so we
1416 // don't match ConstantExpr that aren't meaningful for this transform.
1418 isa<BinaryOperator>(V)) {
1419 Value *OldReorderX, *OldReorderY;
1420 BinaryOperator::BinaryOps Op = cast<BinaryOperator>(V)->getOpcode();
1421
1422 // If both X and Y are bswap/bitreverse, the transform reduces the number
1423 // of instructions even if there's multiuse.
1424 // If only one operand is bswap/bitreverse, we need to ensure the operand
1425 // have only one use.
1426 if (match(X, m_Intrinsic<IntrID>(m_Value(OldReorderX))) &&
1427 match(Y, m_Intrinsic<IntrID>(m_Value(OldReorderY)))) {
1428 return BinaryOperator::Create(Op, OldReorderX, OldReorderY);
1429 }
1430
1431 if (match(X, m_OneUse(m_Intrinsic<IntrID>(m_Value(OldReorderX))))) {
1432 Value *NewReorder = Builder.CreateUnaryIntrinsic(IntrID, Y);
1433 return BinaryOperator::Create(Op, OldReorderX, NewReorder);
1434 }
1435
1436 if (match(Y, m_OneUse(m_Intrinsic<IntrID>(m_Value(OldReorderY))))) {
1437 Value *NewReorder = Builder.CreateUnaryIntrinsic(IntrID, X);
1438 return BinaryOperator::Create(Op, NewReorder, OldReorderY);
1439 }
1440 }
1441 return nullptr;
1442}
1443
1444static Value *simplifyReductionOperand(Value *Arg, bool CanReorderLanes) {
1445 if (!CanReorderLanes)
1446 return nullptr;
1447
1448 Value *V;
1449 if (match(Arg, m_VecReverse(m_Value(V))))
1450 return V;
1451
1452 ArrayRef<int> Mask;
1453 if (!isa<FixedVectorType>(Arg->getType()) ||
1454 !match(Arg, m_Shuffle(m_Value(V), m_Undef(), m_Mask(Mask))) ||
1455 !cast<ShuffleVectorInst>(Arg)->isSingleSource())
1456 return nullptr;
1457
1458 int Sz = Mask.size();
1459 SmallBitVector UsedIndices(Sz);
1460 for (int Idx : Mask) {
1461 if (Idx == PoisonMaskElem || UsedIndices.test(Idx))
1462 return nullptr;
1463 UsedIndices.set(Idx);
1464 }
1465
1466 // Can remove shuffle iff just shuffled elements, no repeats, undefs, or
1467 // other changes.
1468 return UsedIndices.all() ? V : nullptr;
1469}
1470
1471/// Fold an unsigned minimum of trailing or leading zero bits counts:
1472/// umin(cttz(CtOp, ZeroUndef), ConstOp) --> cttz(CtOp | (1 << ConstOp))
1473/// umin(ctlz(CtOp, ZeroUndef), ConstOp) --> ctlz(CtOp | (SignedMin
1474/// >> ConstOp))
1475template <Intrinsic::ID IntrID>
1476static Value *
1478 const DataLayout &DL,
1479 InstCombiner::BuilderTy &Builder) {
1480 static_assert(IntrID == Intrinsic::cttz || IntrID == Intrinsic::ctlz,
1481 "This helper only supports cttz and ctlz intrinsics");
1482
1483 Value *CtOp;
1484 Value *ZeroUndef;
1485 if (!match(I0,
1486 m_OneUse(m_Intrinsic<IntrID>(m_Value(CtOp), m_Value(ZeroUndef)))))
1487 return nullptr;
1488
1489 unsigned BitWidth = I1->getType()->getScalarSizeInBits();
1490 auto LessBitWidth = [BitWidth](auto &C) { return C.ult(BitWidth); };
1491 if (!match(I1, m_CheckedInt(LessBitWidth)))
1492 // We have a constant >= BitWidth (which can be handled by CVP)
1493 // or a non-splat vector with elements < and >= BitWidth
1494 return nullptr;
1495
1496 Type *Ty = I1->getType();
1498 IntrID == Intrinsic::cttz ? Instruction::Shl : Instruction::LShr,
1499 IntrID == Intrinsic::cttz
1500 ? ConstantInt::get(Ty, 1)
1501 : ConstantInt::get(Ty, APInt::getSignedMinValue(BitWidth)),
1502 cast<Constant>(I1), DL);
1503 return Builder.CreateBinaryIntrinsic(
1504 IntrID, Builder.CreateOr(CtOp, NewConst),
1505 ConstantInt::getTrue(ZeroUndef->getType()));
1506}
1507
1508/// Return whether "X LOp (Y ROp Z)" is always equal to
1509/// "(X LOp Y) ROp (X LOp Z)".
1511 bool HasNSW, Intrinsic::ID ROp) {
1512 switch (ROp) {
1513 case Intrinsic::umax:
1514 case Intrinsic::umin:
1515 return HasNUW && LOp == Instruction::Add;
1516 case Intrinsic::smax:
1517 case Intrinsic::smin:
1518 return HasNSW && LOp == Instruction::Add;
1519 default:
1520 return false;
1521 }
1522}
1523
1524// Attempts to factorise a common term
1525// in an instruction that has the form "(A op' B) op (C op' D)
1526// where op is an intrinsic and op' is a binop
1527static Value *
1529 InstCombiner::BuilderTy &Builder) {
1530 Value *LHS = II->getOperand(0), *RHS = II->getOperand(1);
1531 Intrinsic::ID TopLevelOpcode = II->getIntrinsicID();
1532
1533 OverflowingBinaryOperator *Op0 = dyn_cast<OverflowingBinaryOperator>(LHS);
1534 OverflowingBinaryOperator *Op1 = dyn_cast<OverflowingBinaryOperator>(RHS);
1535
1536 if (!Op0 || !Op1)
1537 return nullptr;
1538
1539 if (Op0->getOpcode() != Op1->getOpcode())
1540 return nullptr;
1541
1542 if (!Op0->hasOneUse() || !Op1->hasOneUse())
1543 return nullptr;
1544
1545 Instruction::BinaryOps InnerOpcode =
1546 static_cast<Instruction::BinaryOps>(Op0->getOpcode());
1547 bool HasNUW = Op0->hasNoUnsignedWrap() && Op1->hasNoUnsignedWrap();
1548 bool HasNSW = Op0->hasNoSignedWrap() && Op1->hasNoSignedWrap();
1549
1550 if (!leftDistributesOverRight(InnerOpcode, HasNUW, HasNSW, TopLevelOpcode))
1551 return nullptr;
1552
1553 assert(II->isCommutative() && Op0->isCommutative() &&
1554 "Only inner and outer commutative op codes are supported.");
1555
1556 Value *A = Op0->getOperand(0);
1557 Value *B = Op0->getOperand(1);
1558 Value *C = Op1->getOperand(0);
1559 Value *D = Op1->getOperand(1);
1560
1561 // Attempts to swap variables such that A always equals C
1562 if (A != C && A != D)
1563 std::swap(A, B);
1564 if (A == C || A == D) {
1565 if (A != C)
1566 std::swap(C, D);
1567 Value *NewIntrinsic = Builder.CreateBinaryIntrinsic(TopLevelOpcode, B, D);
1568 BinaryOperator *NewBinop =
1569 cast<BinaryOperator>(Builder.CreateBinOp(InnerOpcode, NewIntrinsic, A));
1570 NewBinop->setHasNoSignedWrap(HasNSW);
1571 NewBinop->setHasNoUnsignedWrap(HasNUW);
1572 return NewBinop;
1573 }
1574
1575 return nullptr;
1576}
1577
1578/// CallInst simplification. This mostly only handles folding of intrinsic
1579/// instructions. For normal calls, it allows visitCallBase to do the heavy
1580/// lifting.
1582 // Don't try to simplify calls without uses. It will not do anything useful,
1583 // but will result in the following folds being skipped.
1584 if (!CI.use_empty()) {
1585 SmallVector<Value *, 8> Args(CI.args());
1586 if (Value *V = simplifyCall(&CI, CI.getCalledOperand(), Args,
1587 SQ.getWithInstruction(&CI)))
1588 return replaceInstUsesWith(CI, V);
1589 }
1590
1591 if (Value *FreedOp = getFreedOperand(&CI, &TLI))
1592 return visitFree(CI, FreedOp);
1593
1594 // If the caller function (i.e. us, the function that contains this CallInst)
1595 // is nounwind, mark the call as nounwind, even if the callee isn't.
1596 if (CI.getFunction()->doesNotThrow() && !CI.doesNotThrow()) {
1597 CI.setDoesNotThrow();
1598 return &CI;
1599 }
1600
1601 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
1602 if (!II) return visitCallBase(CI);
1603
1604 // For atomic unordered mem intrinsics if len is not a positive or
1605 // not a multiple of element size then behavior is undefined.
1606 if (auto *AMI = dyn_cast<AtomicMemIntrinsic>(II))
1607 if (ConstantInt *NumBytes = dyn_cast<ConstantInt>(AMI->getLength()))
1608 if (NumBytes->isNegative() ||
1609 (NumBytes->getZExtValue() % AMI->getElementSizeInBytes() != 0)) {
1611 assert(AMI->getType()->isVoidTy() &&
1612 "non void atomic unordered mem intrinsic");
1613 return eraseInstFromFunction(*AMI);
1614 }
1615
1616 // Intrinsics cannot occur in an invoke or a callbr, so handle them here
1617 // instead of in visitCallBase.
1618 if (auto *MI = dyn_cast<AnyMemIntrinsic>(II)) {
1619 bool Changed = false;
1620
1621 // memmove/cpy/set of zero bytes is a noop.
1622 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
1623 if (NumBytes->isNullValue())
1624 return eraseInstFromFunction(CI);
1625 }
1626
1627 // No other transformations apply to volatile transfers.
1628 if (auto *M = dyn_cast<MemIntrinsic>(MI))
1629 if (M->isVolatile())
1630 return nullptr;
1631
1632 // If we have a memmove and the source operation is a constant global,
1633 // then the source and dest pointers can't alias, so we can change this
1634 // into a call to memcpy.
1635 if (auto *MMI = dyn_cast<AnyMemMoveInst>(MI)) {
1636 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
1637 if (GVSrc->isConstant()) {
1638 Module *M = CI.getModule();
1639 Intrinsic::ID MemCpyID =
1640 isa<AtomicMemMoveInst>(MMI)
1641 ? Intrinsic::memcpy_element_unordered_atomic
1642 : Intrinsic::memcpy;
1643 Type *Tys[3] = { CI.getArgOperand(0)->getType(),
1644 CI.getArgOperand(1)->getType(),
1645 CI.getArgOperand(2)->getType() };
1647 Intrinsic::getOrInsertDeclaration(M, MemCpyID, Tys));
1648 Changed = true;
1649 }
1650 }
1651
1652 if (AnyMemTransferInst *MTI = dyn_cast<AnyMemTransferInst>(MI)) {
1653 // memmove(x,x,size) -> noop.
1654 if (MTI->getSource() == MTI->getDest())
1655 return eraseInstFromFunction(CI);
1656 }
1657
1658 auto IsPointerUndefined = [MI](Value *Ptr) {
1659 return isa<ConstantPointerNull>(Ptr) &&
1661 MI->getFunction(),
1662 cast<PointerType>(Ptr->getType())->getAddressSpace());
1663 };
1664 bool SrcIsUndefined = false;
1665 // If we can determine a pointer alignment that is bigger than currently
1666 // set, update the alignment.
1667 if (auto *MTI = dyn_cast<AnyMemTransferInst>(MI)) {
1669 return I;
1670 SrcIsUndefined = IsPointerUndefined(MTI->getRawSource());
1671 } else if (auto *MSI = dyn_cast<AnyMemSetInst>(MI)) {
1672 if (Instruction *I = SimplifyAnyMemSet(MSI))
1673 return I;
1674 }
1675
1676 // If src/dest is null, this memory intrinsic must be a noop.
1677 if (SrcIsUndefined || IsPointerUndefined(MI->getRawDest())) {
1679 return eraseInstFromFunction(CI);
1680 }
1681
1682 if (Changed) return II;
1683 }
1684
1685 // For fixed width vector result intrinsics, use the generic demanded vector
1686 // support.
1687 if (auto *IIFVTy = dyn_cast<FixedVectorType>(II->getType())) {
1688 auto VWidth = IIFVTy->getNumElements();
1689 APInt PoisonElts(VWidth, 0);
1690 APInt AllOnesEltMask(APInt::getAllOnes(VWidth));
1691 if (Value *V = SimplifyDemandedVectorElts(II, AllOnesEltMask, PoisonElts)) {
1692 if (V != II)
1693 return replaceInstUsesWith(*II, V);
1694 return II;
1695 }
1696 }
1697
1698 if (II->isCommutative()) {
1699 if (auto Pair = matchSymmetricPair(II->getOperand(0), II->getOperand(1))) {
1700 replaceOperand(*II, 0, Pair->first);
1701 replaceOperand(*II, 1, Pair->second);
1702 return II;
1703 }
1704
1705 if (CallInst *NewCall = canonicalizeConstantArg0ToArg1(CI))
1706 return NewCall;
1707 }
1708
1709 // Unused constrained FP intrinsic calls may have declared side effect, which
1710 // prevents it from being removed. In some cases however the side effect is
1711 // actually absent. To detect this case, call SimplifyConstrainedFPCall. If it
1712 // returns a replacement, the call may be removed.
1713 if (CI.use_empty() && isa<ConstrainedFPIntrinsic>(CI)) {
1715 return eraseInstFromFunction(CI);
1716 }
1717
1718 Intrinsic::ID IID = II->getIntrinsicID();
1719 switch (IID) {
1720 case Intrinsic::objectsize: {
1721 SmallVector<Instruction *> InsertedInstructions;
1722 if (Value *V = lowerObjectSizeCall(II, DL, &TLI, AA, /*MustSucceed=*/false,
1723 &InsertedInstructions)) {
1724 for (Instruction *Inserted : InsertedInstructions)
1725 Worklist.add(Inserted);
1726 return replaceInstUsesWith(CI, V);
1727 }
1728 return nullptr;
1729 }
1730 case Intrinsic::abs: {
1731 Value *IIOperand = II->getArgOperand(0);
1732 bool IntMinIsPoison = cast<Constant>(II->getArgOperand(1))->isOneValue();
1733
1734 // abs(-x) -> abs(x)
1735 // TODO: Copy nsw if it was present on the neg?
1736 Value *X;
1737 if (match(IIOperand, m_Neg(m_Value(X))))
1738 return replaceOperand(*II, 0, X);
1739 if (match(IIOperand, m_c_Select(m_Neg(m_Value(X)), m_Deferred(X))))
1740 return replaceOperand(*II, 0, X);
1741
1742 Value *Y;
1743 // abs(a * abs(b)) -> abs(a * b)
1744 if (match(IIOperand,
1746 m_Intrinsic<Intrinsic::abs>(m_Value(Y)))))) {
1747 bool NSW =
1748 cast<Instruction>(IIOperand)->hasNoSignedWrap() && IntMinIsPoison;
1749 auto *XY = NSW ? Builder.CreateNSWMul(X, Y) : Builder.CreateMul(X, Y);
1750 return replaceOperand(*II, 0, XY);
1751 }
1752
1753 if (std::optional<bool> Known =
1755 // abs(x) -> x if x >= 0 (include abs(x-y) --> x - y where x >= y)
1756 // abs(x) -> x if x > 0 (include abs(x-y) --> x - y where x > y)
1757 if (!*Known)
1758 return replaceInstUsesWith(*II, IIOperand);
1759
1760 // abs(x) -> -x if x < 0
1761 // abs(x) -> -x if x < = 0 (include abs(x-y) --> y - x where x <= y)
1762 if (IntMinIsPoison)
1763 return BinaryOperator::CreateNSWNeg(IIOperand);
1764 return BinaryOperator::CreateNeg(IIOperand);
1765 }
1766
1767 // abs (sext X) --> zext (abs X*)
1768 // Clear the IsIntMin (nsw) bit on the abs to allow narrowing.
1769 if (match(IIOperand, m_OneUse(m_SExt(m_Value(X))))) {
1770 Value *NarrowAbs =
1771 Builder.CreateBinaryIntrinsic(Intrinsic::abs, X, Builder.getFalse());
1772 return CastInst::Create(Instruction::ZExt, NarrowAbs, II->getType());
1773 }
1774
1775 // Match a complicated way to check if a number is odd/even:
1776 // abs (srem X, 2) --> and X, 1
1777 const APInt *C;
1778 if (match(IIOperand, m_SRem(m_Value(X), m_APInt(C))) && *C == 2)
1779 return BinaryOperator::CreateAnd(X, ConstantInt::get(II->getType(), 1));
1780
1781 break;
1782 }
1783 case Intrinsic::umin: {
1784 Value *I0 = II->getArgOperand(0), *I1 = II->getArgOperand(1);
1785 // umin(x, 1) == zext(x != 0)
1786 if (match(I1, m_One())) {
1787 assert(II->getType()->getScalarSizeInBits() != 1 &&
1788 "Expected simplify of umin with max constant");
1789 Value *Zero = Constant::getNullValue(I0->getType());
1790 Value *Cmp = Builder.CreateICmpNE(I0, Zero);
1791 return CastInst::Create(Instruction::ZExt, Cmp, II->getType());
1792 }
1793 // umin(cttz(x), const) --> cttz(x | (1 << const))
1794 if (Value *FoldedCttz =
1795 foldMinimumOverTrailingOrLeadingZeroCount<Intrinsic::cttz>(
1796 I0, I1, DL, Builder))
1797 return replaceInstUsesWith(*II, FoldedCttz);
1798 // umin(ctlz(x), const) --> ctlz(x | (SignedMin >> const))
1799 if (Value *FoldedCtlz =
1800 foldMinimumOverTrailingOrLeadingZeroCount<Intrinsic::ctlz>(
1801 I0, I1, DL, Builder))
1802 return replaceInstUsesWith(*II, FoldedCtlz);
1803 [[fallthrough]];
1804 }
1805 case Intrinsic::umax: {
1806 Value *I0 = II->getArgOperand(0), *I1 = II->getArgOperand(1);
1807 Value *X, *Y;
1808 if (match(I0, m_ZExt(m_Value(X))) && match(I1, m_ZExt(m_Value(Y))) &&
1809 (I0->hasOneUse() || I1->hasOneUse()) && X->getType() == Y->getType()) {
1810 Value *NarrowMaxMin = Builder.CreateBinaryIntrinsic(IID, X, Y);
1811 return CastInst::Create(Instruction::ZExt, NarrowMaxMin, II->getType());
1812 }
1813 Constant *C;
1814 if (match(I0, m_ZExt(m_Value(X))) && match(I1, m_Constant(C)) &&
1815 I0->hasOneUse()) {
1816 if (Constant *NarrowC = getLosslessUnsignedTrunc(C, X->getType())) {
1817 Value *NarrowMaxMin = Builder.CreateBinaryIntrinsic(IID, X, NarrowC);
1818 return CastInst::Create(Instruction::ZExt, NarrowMaxMin, II->getType());
1819 }
1820 }
1821 // If both operands of unsigned min/max are sign-extended, it is still ok
1822 // to narrow the operation.
1823 [[fallthrough]];
1824 }
1825 case Intrinsic::smax:
1826 case Intrinsic::smin: {
1827 Value *I0 = II->getArgOperand(0), *I1 = II->getArgOperand(1);
1828 Value *X, *Y;
1829 if (match(I0, m_SExt(m_Value(X))) && match(I1, m_SExt(m_Value(Y))) &&
1830 (I0->hasOneUse() || I1->hasOneUse()) && X->getType() == Y->getType()) {
1831 Value *NarrowMaxMin = Builder.CreateBinaryIntrinsic(IID, X, Y);
1832 return CastInst::Create(Instruction::SExt, NarrowMaxMin, II->getType());
1833 }
1834
1835 Constant *C;
1836 if (match(I0, m_SExt(m_Value(X))) && match(I1, m_Constant(C)) &&
1837 I0->hasOneUse()) {
1838 if (Constant *NarrowC = getLosslessSignedTrunc(C, X->getType())) {
1839 Value *NarrowMaxMin = Builder.CreateBinaryIntrinsic(IID, X, NarrowC);
1840 return CastInst::Create(Instruction::SExt, NarrowMaxMin, II->getType());
1841 }
1842 }
1843
1844 // umin(i1 X, i1 Y) -> and i1 X, Y
1845 // smax(i1 X, i1 Y) -> and i1 X, Y
1846 if ((IID == Intrinsic::umin || IID == Intrinsic::smax) &&
1847 II->getType()->isIntOrIntVectorTy(1)) {
1848 return BinaryOperator::CreateAnd(I0, I1);
1849 }
1850
1851 // umax(i1 X, i1 Y) -> or i1 X, Y
1852 // smin(i1 X, i1 Y) -> or i1 X, Y
1853 if ((IID == Intrinsic::umax || IID == Intrinsic::smin) &&
1854 II->getType()->isIntOrIntVectorTy(1)) {
1855 return BinaryOperator::CreateOr(I0, I1);
1856 }
1857
1858 if (IID == Intrinsic::smax || IID == Intrinsic::smin) {
1859 // smax (neg nsw X), (neg nsw Y) --> neg nsw (smin X, Y)
1860 // smin (neg nsw X), (neg nsw Y) --> neg nsw (smax X, Y)
1861 // TODO: Canonicalize neg after min/max if I1 is constant.
1862 if (match(I0, m_NSWNeg(m_Value(X))) && match(I1, m_NSWNeg(m_Value(Y))) &&
1863 (I0->hasOneUse() || I1->hasOneUse())) {
1865 Value *InvMaxMin = Builder.CreateBinaryIntrinsic(InvID, X, Y);
1866 return BinaryOperator::CreateNSWNeg(InvMaxMin);
1867 }
1868 }
1869
1870 // (umax X, (xor X, Pow2))
1871 // -> (or X, Pow2)
1872 // (umin X, (xor X, Pow2))
1873 // -> (and X, ~Pow2)
1874 // (smax X, (xor X, Pos_Pow2))
1875 // -> (or X, Pos_Pow2)
1876 // (smin X, (xor X, Pos_Pow2))
1877 // -> (and X, ~Pos_Pow2)
1878 // (smax X, (xor X, Neg_Pow2))
1879 // -> (and X, ~Neg_Pow2)
1880 // (smin X, (xor X, Neg_Pow2))
1881 // -> (or X, Neg_Pow2)
1882 if ((match(I0, m_c_Xor(m_Specific(I1), m_Value(X))) ||
1883 match(I1, m_c_Xor(m_Specific(I0), m_Value(X)))) &&
1884 isKnownToBeAPowerOfTwo(X, /* OrZero */ true)) {
1885 bool UseOr = IID == Intrinsic::smax || IID == Intrinsic::umax;
1886 bool UseAndN = IID == Intrinsic::smin || IID == Intrinsic::umin;
1887
1888 if (IID == Intrinsic::smax || IID == Intrinsic::smin) {
1889 auto KnownSign = getKnownSign(X, SQ.getWithInstruction(II));
1890 if (KnownSign == std::nullopt) {
1891 UseOr = false;
1892 UseAndN = false;
1893 } else if (*KnownSign /* true is Signed. */) {
1894 UseOr ^= true;
1895 UseAndN ^= true;
1896 Type *Ty = I0->getType();
1897 // Negative power of 2 must be IntMin. It's possible to be able to
1898 // prove negative / power of 2 without actually having known bits, so
1899 // just get the value by hand.
1902 }
1903 }
1904 if (UseOr)
1905 return BinaryOperator::CreateOr(I0, X);
1906 else if (UseAndN)
1907 return BinaryOperator::CreateAnd(I0, Builder.CreateNot(X));
1908 }
1909
1910 // If we can eliminate ~A and Y is free to invert:
1911 // max ~A, Y --> ~(min A, ~Y)
1912 //
1913 // Examples:
1914 // max ~A, ~Y --> ~(min A, Y)
1915 // max ~A, C --> ~(min A, ~C)
1916 // max ~A, (max ~Y, ~Z) --> ~min( A, (min Y, Z))
1917 auto moveNotAfterMinMax = [&](Value *X, Value *Y) -> Instruction * {
1918 Value *A;
1919 if (match(X, m_OneUse(m_Not(m_Value(A)))) &&
1920 !isFreeToInvert(A, A->hasOneUse())) {
1921 if (Value *NotY = getFreelyInverted(Y, Y->hasOneUse(), &Builder)) {
1923 Value *InvMaxMin = Builder.CreateBinaryIntrinsic(InvID, A, NotY);
1924 return BinaryOperator::CreateNot(InvMaxMin);
1925 }
1926 }
1927 return nullptr;
1928 };
1929
1930 if (Instruction *I = moveNotAfterMinMax(I0, I1))
1931 return I;
1932 if (Instruction *I = moveNotAfterMinMax(I1, I0))
1933 return I;
1934
1936 return I;
1937
1938 // minmax (X & NegPow2C, Y & NegPow2C) --> minmax(X, Y) & NegPow2C
1939 const APInt *RHSC;
1940 if (match(I0, m_OneUse(m_And(m_Value(X), m_NegatedPower2(RHSC)))) &&
1941 match(I1, m_OneUse(m_And(m_Value(Y), m_SpecificInt(*RHSC)))))
1942 return BinaryOperator::CreateAnd(Builder.CreateBinaryIntrinsic(IID, X, Y),
1943 ConstantInt::get(II->getType(), *RHSC));
1944
1945 // smax(X, -X) --> abs(X)
1946 // smin(X, -X) --> -abs(X)
1947 // umax(X, -X) --> -abs(X)
1948 // umin(X, -X) --> abs(X)
1949 if (isKnownNegation(I0, I1)) {
1950 // We can choose either operand as the input to abs(), but if we can
1951 // eliminate the only use of a value, that's better for subsequent
1952 // transforms/analysis.
1953 if (I0->hasOneUse() && !I1->hasOneUse())
1954 std::swap(I0, I1);
1955
1956 // This is some variant of abs(). See if we can propagate 'nsw' to the abs
1957 // operation and potentially its negation.
1958 bool IntMinIsPoison = isKnownNegation(I0, I1, /* NeedNSW */ true);
1960 Intrinsic::abs, I0,
1961 ConstantInt::getBool(II->getContext(), IntMinIsPoison));
1962
1963 // We don't have a "nabs" intrinsic, so negate if needed based on the
1964 // max/min operation.
1965 if (IID == Intrinsic::smin || IID == Intrinsic::umax)
1966 Abs = Builder.CreateNeg(Abs, "nabs", IntMinIsPoison);
1967 return replaceInstUsesWith(CI, Abs);
1968 }
1969
1971 return Sel;
1972
1973 if (Instruction *SAdd = matchSAddSubSat(*II))
1974 return SAdd;
1975
1976 if (Value *NewMinMax = reassociateMinMaxWithConstants(II, Builder, SQ))
1977 return replaceInstUsesWith(*II, NewMinMax);
1978
1980 return R;
1981
1982 if (Instruction *NewMinMax = factorizeMinMaxTree(II))
1983 return NewMinMax;
1984
1985 // Try to fold minmax with constant RHS based on range information
1986 if (match(I1, m_APIntAllowPoison(RHSC))) {
1987 ICmpInst::Predicate Pred =
1989 bool IsSigned = MinMaxIntrinsic::isSigned(IID);
1991 I0, IsSigned, SQ.getWithInstruction(II));
1992 if (!LHS_CR.isFullSet()) {
1993 if (LHS_CR.icmp(Pred, *RHSC))
1994 return replaceInstUsesWith(*II, I0);
1995 if (LHS_CR.icmp(ICmpInst::getSwappedPredicate(Pred), *RHSC))
1996 return replaceInstUsesWith(*II,
1997 ConstantInt::get(II->getType(), *RHSC));
1998 }
1999 }
2000
2002 return replaceInstUsesWith(*II, V);
2003
2004 break;
2005 }
2006 case Intrinsic::scmp: {
2007 Value *I0 = II->getArgOperand(0), *I1 = II->getArgOperand(1);
2008 Value *LHS, *RHS;
2009 if (match(I0, m_NSWSub(m_Value(LHS), m_Value(RHS))) && match(I1, m_Zero()))
2010 return replaceInstUsesWith(
2011 CI,
2012 Builder.CreateIntrinsic(II->getType(), Intrinsic::scmp, {LHS, RHS}));
2013 break;
2014 }
2015 case Intrinsic::bitreverse: {
2016 Value *IIOperand = II->getArgOperand(0);
2017 // bitrev (zext i1 X to ?) --> X ? SignBitC : 0
2018 Value *X;
2019 if (match(IIOperand, m_ZExt(m_Value(X))) &&
2020 X->getType()->isIntOrIntVectorTy(1)) {
2021 Type *Ty = II->getType();
2023 return SelectInst::Create(X, ConstantInt::get(Ty, SignBit),
2025 }
2026
2027 if (Instruction *crossLogicOpFold =
2028 foldBitOrderCrossLogicOp<Intrinsic::bitreverse>(IIOperand, Builder))
2029 return crossLogicOpFold;
2030
2031 break;
2032 }
2033 case Intrinsic::bswap: {
2034 Value *IIOperand = II->getArgOperand(0);
2035
2036 // Try to canonicalize bswap-of-logical-shift-by-8-bit-multiple as
2037 // inverse-shift-of-bswap:
2038 // bswap (shl X, Y) --> lshr (bswap X), Y
2039 // bswap (lshr X, Y) --> shl (bswap X), Y
2040 Value *X, *Y;
2041 if (match(IIOperand, m_OneUse(m_LogicalShift(m_Value(X), m_Value(Y))))) {
2042 unsigned BitWidth = IIOperand->getType()->getScalarSizeInBits();
2044 Value *NewSwap = Builder.CreateUnaryIntrinsic(Intrinsic::bswap, X);
2045 BinaryOperator::BinaryOps InverseShift =
2046 cast<BinaryOperator>(IIOperand)->getOpcode() == Instruction::Shl
2047 ? Instruction::LShr
2048 : Instruction::Shl;
2049 return BinaryOperator::Create(InverseShift, NewSwap, Y);
2050 }
2051 }
2052
2053 KnownBits Known = computeKnownBits(IIOperand, 0, II);
2054 uint64_t LZ = alignDown(Known.countMinLeadingZeros(), 8);
2055 uint64_t TZ = alignDown(Known.countMinTrailingZeros(), 8);
2056 unsigned BW = Known.getBitWidth();
2057
2058 // bswap(x) -> shift(x) if x has exactly one "active byte"
2059 if (BW - LZ - TZ == 8) {
2060 assert(LZ != TZ && "active byte cannot be in the middle");
2061 if (LZ > TZ) // -> shl(x) if the "active byte" is in the low part of x
2062 return BinaryOperator::CreateNUWShl(
2063 IIOperand, ConstantInt::get(IIOperand->getType(), LZ - TZ));
2064 // -> lshr(x) if the "active byte" is in the high part of x
2065 return BinaryOperator::CreateExactLShr(
2066 IIOperand, ConstantInt::get(IIOperand->getType(), TZ - LZ));
2067 }
2068
2069 // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
2070 if (match(IIOperand, m_Trunc(m_BSwap(m_Value(X))))) {
2071 unsigned C = X->getType()->getScalarSizeInBits() - BW;
2072 Value *CV = ConstantInt::get(X->getType(), C);
2073 Value *V = Builder.CreateLShr(X, CV);
2074 return new TruncInst(V, IIOperand->getType());
2075 }
2076
2077 if (Instruction *crossLogicOpFold =
2078 foldBitOrderCrossLogicOp<Intrinsic::bswap>(IIOperand, Builder)) {
2079 return crossLogicOpFold;
2080 }
2081
2082 // Try to fold into bitreverse if bswap is the root of the expression tree.
2083 if (Instruction *BitOp = matchBSwapOrBitReverse(*II, /*MatchBSwaps*/ false,
2084 /*MatchBitReversals*/ true))
2085 return BitOp;
2086 break;
2087 }
2088 case Intrinsic::masked_load:
2089 if (Value *SimplifiedMaskedOp = simplifyMaskedLoad(*II))
2090 return replaceInstUsesWith(CI, SimplifiedMaskedOp);
2091 break;
2092 case Intrinsic::masked_store:
2093 return simplifyMaskedStore(*II);
2094 case Intrinsic::masked_gather:
2095 return simplifyMaskedGather(*II);
2096 case Intrinsic::masked_scatter:
2097 return simplifyMaskedScatter(*II);
2098 case Intrinsic::launder_invariant_group:
2099 case Intrinsic::strip_invariant_group:
2100 if (auto *SkippedBarrier = simplifyInvariantGroupIntrinsic(*II, *this))
2101 return replaceInstUsesWith(*II, SkippedBarrier);
2102 break;
2103 case Intrinsic::powi:
2104 if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
2105 // 0 and 1 are handled in instsimplify
2106 // powi(x, -1) -> 1/x
2107 if (Power->isMinusOne())
2108 return BinaryOperator::CreateFDivFMF(ConstantFP::get(CI.getType(), 1.0),
2109 II->getArgOperand(0), II);
2110 // powi(x, 2) -> x*x
2111 if (Power->equalsInt(2))
2112 return BinaryOperator::CreateFMulFMF(II->getArgOperand(0),
2113 II->getArgOperand(0), II);
2114
2115 if (!Power->getValue()[0]) {
2116 Value *X;
2117 // If power is even:
2118 // powi(-x, p) -> powi(x, p)
2119 // powi(fabs(x), p) -> powi(x, p)
2120 // powi(copysign(x, y), p) -> powi(x, p)
2121 if (match(II->getArgOperand(0), m_FNeg(m_Value(X))) ||
2122 match(II->getArgOperand(0), m_FAbs(m_Value(X))) ||
2123 match(II->getArgOperand(0),
2124 m_Intrinsic<Intrinsic::copysign>(m_Value(X), m_Value())))
2125 return replaceOperand(*II, 0, X);
2126 }
2127 }
2128 break;
2129
2130 case Intrinsic::cttz:
2131 case Intrinsic::ctlz:
2132 if (auto *I = foldCttzCtlz(*II, *this))
2133 return I;
2134 break;
2135
2136 case Intrinsic::ctpop:
2137 if (auto *I = foldCtpop(*II, *this))
2138 return I;
2139 break;
2140
2141 case Intrinsic::fshl:
2142 case Intrinsic::fshr: {
2143 Value *Op0 = II->getArgOperand(0), *Op1 = II->getArgOperand(1);
2144 Type *Ty = II->getType();
2145 unsigned BitWidth = Ty->getScalarSizeInBits();
2146 Constant *ShAmtC;
2147 if (match(II->getArgOperand(2), m_ImmConstant(ShAmtC))) {
2148 // Canonicalize a shift amount constant operand to modulo the bit-width.
2149 Constant *WidthC = ConstantInt::get(Ty, BitWidth);
2150 Constant *ModuloC =
2151 ConstantFoldBinaryOpOperands(Instruction::URem, ShAmtC, WidthC, DL);
2152 if (!ModuloC)
2153 return nullptr;
2154 if (ModuloC != ShAmtC)
2155 return replaceOperand(*II, 2, ModuloC);
2156
2158 ShAmtC, DL),
2159 m_One()) &&
2160 "Shift amount expected to be modulo bitwidth");
2161
2162 // Canonicalize funnel shift right by constant to funnel shift left. This
2163 // is not entirely arbitrary. For historical reasons, the backend may
2164 // recognize rotate left patterns but miss rotate right patterns.
2165 if (IID == Intrinsic::fshr) {
2166 // fshr X, Y, C --> fshl X, Y, (BitWidth - C) if C is not zero.
2167 if (!isKnownNonZero(ShAmtC, SQ.getWithInstruction(II)))
2168 return nullptr;
2169
2170 Constant *LeftShiftC = ConstantExpr::getSub(WidthC, ShAmtC);
2171 Module *Mod = II->getModule();
2172 Function *Fshl =
2173 Intrinsic::getOrInsertDeclaration(Mod, Intrinsic::fshl, Ty);
2174 return CallInst::Create(Fshl, { Op0, Op1, LeftShiftC });
2175 }
2176 assert(IID == Intrinsic::fshl &&
2177 "All funnel shifts by simple constants should go left");
2178
2179 // fshl(X, 0, C) --> shl X, C
2180 // fshl(X, undef, C) --> shl X, C
2181 if (match(Op1, m_ZeroInt()) || match(Op1, m_Undef()))
2182 return BinaryOperator::CreateShl(Op0, ShAmtC);
2183
2184 // fshl(0, X, C) --> lshr X, (BW-C)
2185 // fshl(undef, X, C) --> lshr X, (BW-C)
2186 if (match(Op0, m_ZeroInt()) || match(Op0, m_Undef()))
2187 return BinaryOperator::CreateLShr(Op1,
2188 ConstantExpr::getSub(WidthC, ShAmtC));
2189
2190 // fshl i16 X, X, 8 --> bswap i16 X (reduce to more-specific form)
2191 if (Op0 == Op1 && BitWidth == 16 && match(ShAmtC, m_SpecificInt(8))) {
2192 Module *Mod = II->getModule();
2193 Function *Bswap =
2194 Intrinsic::getOrInsertDeclaration(Mod, Intrinsic::bswap, Ty);
2195 return CallInst::Create(Bswap, { Op0 });
2196 }
2197 if (Instruction *BitOp =
2198 matchBSwapOrBitReverse(*II, /*MatchBSwaps*/ true,
2199 /*MatchBitReversals*/ true))
2200 return BitOp;
2201 }
2202
2203 // Left or right might be masked.
2205 return &CI;
2206
2207 // The shift amount (operand 2) of a funnel shift is modulo the bitwidth,
2208 // so only the low bits of the shift amount are demanded if the bitwidth is
2209 // a power-of-2.
2210 if (!isPowerOf2_32(BitWidth))
2211 break;
2213 KnownBits Op2Known(BitWidth);
2214 if (SimplifyDemandedBits(II, 2, Op2Demanded, Op2Known))
2215 return &CI;
2216 break;
2217 }
2218 case Intrinsic::ptrmask: {
2219 unsigned BitWidth = DL.getPointerTypeSizeInBits(II->getType());
2220 KnownBits Known(BitWidth);
2222 return II;
2223
2224 Value *InnerPtr, *InnerMask;
2225 bool Changed = false;
2226 // Combine:
2227 // (ptrmask (ptrmask p, A), B)
2228 // -> (ptrmask p, (and A, B))
2229 if (match(II->getArgOperand(0),
2230 m_OneUse(m_Intrinsic<Intrinsic::ptrmask>(m_Value(InnerPtr),
2231 m_Value(InnerMask))))) {
2232 assert(II->getArgOperand(1)->getType() == InnerMask->getType() &&
2233 "Mask types must match");
2234 // TODO: If InnerMask == Op1, we could copy attributes from inner
2235 // callsite -> outer callsite.
2236 Value *NewMask = Builder.CreateAnd(II->getArgOperand(1), InnerMask);
2237 replaceOperand(CI, 0, InnerPtr);
2238 replaceOperand(CI, 1, NewMask);
2239 Changed = true;
2240 }
2241
2242 // See if we can deduce non-null.
2243 if (!CI.hasRetAttr(Attribute::NonNull) &&
2244 (Known.isNonZero() ||
2245 isKnownNonZero(II, getSimplifyQuery().getWithInstruction(II)))) {
2246 CI.addRetAttr(Attribute::NonNull);
2247 Changed = true;
2248 }
2249
2250 unsigned NewAlignmentLog =
2252 std::min(BitWidth - 1, Known.countMinTrailingZeros()));
2253 // Known bits will capture if we had alignment information associated with
2254 // the pointer argument.
2255 if (NewAlignmentLog > Log2(CI.getRetAlign().valueOrOne())) {
2257 CI.getContext(), Align(uint64_t(1) << NewAlignmentLog)));
2258 Changed = true;
2259 }
2260 if (Changed)
2261 return &CI;
2262 break;
2263 }
2264 case Intrinsic::uadd_with_overflow:
2265 case Intrinsic::sadd_with_overflow: {
2266 if (Instruction *I = foldIntrinsicWithOverflowCommon(II))
2267 return I;
2268
2269 // Given 2 constant operands whose sum does not overflow:
2270 // uaddo (X +nuw C0), C1 -> uaddo X, C0 + C1
2271 // saddo (X +nsw C0), C1 -> saddo X, C0 + C1
2272 Value *X;
2273 const APInt *C0, *C1;
2274 Value *Arg0 = II->getArgOperand(0);
2275 Value *Arg1 = II->getArgOperand(1);
2276 bool IsSigned = IID == Intrinsic::sadd_with_overflow;
2277 bool HasNWAdd = IsSigned
2278 ? match(Arg0, m_NSWAddLike(m_Value(X), m_APInt(C0)))
2279 : match(Arg0, m_NUWAddLike(m_Value(X), m_APInt(C0)));
2280 if (HasNWAdd && match(Arg1, m_APInt(C1))) {
2281 bool Overflow;
2282 APInt NewC =
2283 IsSigned ? C1->sadd_ov(*C0, Overflow) : C1->uadd_ov(*C0, Overflow);
2284 if (!Overflow)
2285 return replaceInstUsesWith(
2287 IID, X, ConstantInt::get(Arg1->getType(), NewC)));
2288 }
2289 break;
2290 }
2291
2292 case Intrinsic::umul_with_overflow:
2293 case Intrinsic::smul_with_overflow:
2294 case Intrinsic::usub_with_overflow:
2295 if (Instruction *I = foldIntrinsicWithOverflowCommon(II))
2296 return I;
2297 break;
2298
2299 case Intrinsic::ssub_with_overflow: {
2300 if (Instruction *I = foldIntrinsicWithOverflowCommon(II))
2301 return I;
2302
2303 Constant *C;
2304 Value *Arg0 = II->getArgOperand(0);
2305 Value *Arg1 = II->getArgOperand(1);
2306 // Given a constant C that is not the minimum signed value
2307 // for an integer of a given bit width:
2308 //
2309 // ssubo X, C -> saddo X, -C
2310 if (match(Arg1, m_Constant(C)) && C->isNotMinSignedValue()) {
2311 Value *NegVal = ConstantExpr::getNeg(C);
2312 // Build a saddo call that is equivalent to the discovered
2313 // ssubo call.
2314 return replaceInstUsesWith(
2315 *II, Builder.CreateBinaryIntrinsic(Intrinsic::sadd_with_overflow,
2316 Arg0, NegVal));
2317 }
2318
2319 break;
2320 }
2321
2322 case Intrinsic::uadd_sat:
2323 case Intrinsic::sadd_sat:
2324 case Intrinsic::usub_sat:
2325 case Intrinsic::ssub_sat: {
2326 SaturatingInst *SI = cast<SaturatingInst>(II);
2327 Type *Ty = SI->getType();
2328 Value *Arg0 = SI->getLHS();
2329 Value *Arg1 = SI->getRHS();
2330
2331 // Make use of known overflow information.
2332 OverflowResult OR = computeOverflow(SI->getBinaryOp(), SI->isSigned(),
2333 Arg0, Arg1, SI);
2334 switch (OR) {
2336 break;
2338 if (SI->isSigned())
2339 return BinaryOperator::CreateNSW(SI->getBinaryOp(), Arg0, Arg1);
2340 else
2341 return BinaryOperator::CreateNUW(SI->getBinaryOp(), Arg0, Arg1);
2343 unsigned BitWidth = Ty->getScalarSizeInBits();
2344 APInt Min = APSInt::getMinValue(BitWidth, !SI->isSigned());
2345 return replaceInstUsesWith(*SI, ConstantInt::get(Ty, Min));
2346 }
2348 unsigned BitWidth = Ty->getScalarSizeInBits();
2349 APInt Max = APSInt::getMaxValue(BitWidth, !SI->isSigned());
2350 return replaceInstUsesWith(*SI, ConstantInt::get(Ty, Max));
2351 }
2352 }
2353
2354 // usub_sat((sub nuw C, A), C1) -> usub_sat(usub_sat(C, C1), A)
2355 // which after that:
2356 // usub_sat((sub nuw C, A), C1) -> usub_sat(C - C1, A) if C1 u< C
2357 // usub_sat((sub nuw C, A), C1) -> 0 otherwise
2358 Constant *C, *C1;
2359 Value *A;
2360 if (IID == Intrinsic::usub_sat &&
2361 match(Arg0, m_NUWSub(m_ImmConstant(C), m_Value(A))) &&
2362 match(Arg1, m_ImmConstant(C1))) {
2363 auto *NewC = Builder.CreateBinaryIntrinsic(Intrinsic::usub_sat, C, C1);
2364 auto *NewSub =
2365 Builder.CreateBinaryIntrinsic(Intrinsic::usub_sat, NewC, A);
2366 return replaceInstUsesWith(*SI, NewSub);
2367 }
2368
2369 // ssub.sat(X, C) -> sadd.sat(X, -C) if C != MIN
2370 if (IID == Intrinsic::ssub_sat && match(Arg1, m_Constant(C)) &&
2371 C->isNotMinSignedValue()) {
2372 Value *NegVal = ConstantExpr::getNeg(C);
2373 return replaceInstUsesWith(
2375 Intrinsic::sadd_sat, Arg0, NegVal));
2376 }
2377
2378 // sat(sat(X + Val2) + Val) -> sat(X + (Val+Val2))
2379 // sat(sat(X - Val2) - Val) -> sat(X - (Val+Val2))
2380 // if Val and Val2 have the same sign
2381 if (auto *Other = dyn_cast<IntrinsicInst>(Arg0)) {
2382 Value *X;
2383 const APInt *Val, *Val2;
2384 APInt NewVal;
2385 bool IsUnsigned =
2386 IID == Intrinsic::uadd_sat || IID == Intrinsic::usub_sat;
2387 if (Other->getIntrinsicID() == IID &&
2388 match(Arg1, m_APInt(Val)) &&
2389 match(Other->getArgOperand(0), m_Value(X)) &&
2390 match(Other->getArgOperand(1), m_APInt(Val2))) {
2391 if (IsUnsigned)
2392 NewVal = Val->uadd_sat(*Val2);
2393 else if (Val->isNonNegative() == Val2->isNonNegative()) {
2394 bool Overflow;
2395 NewVal = Val->sadd_ov(*Val2, Overflow);
2396 if (Overflow) {
2397 // Both adds together may add more than SignedMaxValue
2398 // without saturating the final result.
2399 break;
2400 }
2401 } else {
2402 // Cannot fold saturated addition with different signs.
2403 break;
2404 }
2405
2406 return replaceInstUsesWith(
2408 IID, X, ConstantInt::get(II->getType(), NewVal)));
2409 }
2410 }
2411 break;
2412 }
2413
2414 case Intrinsic::minnum:
2415 case Intrinsic::maxnum:
2416 case Intrinsic::minimum:
2417 case Intrinsic::maximum: {
2418 Value *Arg0 = II->getArgOperand(0);
2419 Value *Arg1 = II->getArgOperand(1);
2420 Value *X, *Y;
2421 if (match(Arg0, m_FNeg(m_Value(X))) && match(Arg1, m_FNeg(m_Value(Y))) &&
2422 (Arg0->hasOneUse() || Arg1->hasOneUse())) {
2423 // If both operands are negated, invert the call and negate the result:
2424 // min(-X, -Y) --> -(max(X, Y))
2425 // max(-X, -Y) --> -(min(X, Y))
2426 Intrinsic::ID NewIID;
2427 switch (IID) {
2428 case Intrinsic::maxnum:
2429 NewIID = Intrinsic::minnum;
2430 break;
2431 case Intrinsic::minnum:
2432 NewIID = Intrinsic::maxnum;
2433 break;
2434 case Intrinsic::maximum:
2435 NewIID = Intrinsic::minimum;
2436 break;
2437 case Intrinsic::minimum:
2438 NewIID = Intrinsic::maximum;
2439 break;
2440 default:
2441 llvm_unreachable("unexpected intrinsic ID");
2442 }
2443 Value *NewCall = Builder.CreateBinaryIntrinsic(NewIID, X, Y, II);
2444 Instruction *FNeg = UnaryOperator::CreateFNeg(NewCall);
2445 FNeg->copyIRFlags(II);
2446 return FNeg;
2447 }
2448
2449 // m(m(X, C2), C1) -> m(X, C)
2450 const APFloat *C1, *C2;
2451 if (auto *M = dyn_cast<IntrinsicInst>(Arg0)) {
2452 if (M->getIntrinsicID() == IID && match(Arg1, m_APFloat(C1)) &&
2453 ((match(M->getArgOperand(0), m_Value(X)) &&
2454 match(M->getArgOperand(1), m_APFloat(C2))) ||
2455 (match(M->getArgOperand(1), m_Value(X)) &&
2456 match(M->getArgOperand(0), m_APFloat(C2))))) {
2457 APFloat Res(0.0);
2458 switch (IID) {
2459 case Intrinsic::maxnum:
2460 Res = maxnum(*C1, *C2);
2461 break;
2462 case Intrinsic::minnum:
2463 Res = minnum(*C1, *C2);
2464 break;
2465 case Intrinsic::maximum:
2466 Res = maximum(*C1, *C2);
2467 break;
2468 case Intrinsic::minimum:
2469 Res = minimum(*C1, *C2);
2470 break;
2471 default:
2472 llvm_unreachable("unexpected intrinsic ID");
2473 }
2475 IID, X, ConstantFP::get(Arg0->getType(), Res), II);
2476 // TODO: Conservatively intersecting FMF. If Res == C2, the transform
2477 // was a simplification (so Arg0 and its original flags could
2478 // propagate?)
2479 if (auto *CI = dyn_cast<CallInst>(V))
2480 CI->andIRFlags(M);
2481 return replaceInstUsesWith(*II, V);
2482 }
2483 }
2484
2485 // m((fpext X), (fpext Y)) -> fpext (m(X, Y))
2486 if (match(Arg0, m_OneUse(m_FPExt(m_Value(X)))) &&
2487 match(Arg1, m_OneUse(m_FPExt(m_Value(Y)))) &&
2488 X->getType() == Y->getType()) {
2489 Value *NewCall =
2490 Builder.CreateBinaryIntrinsic(IID, X, Y, II, II->getName());
2491 return new FPExtInst(NewCall, II->getType());
2492 }
2493
2494 // max X, -X --> fabs X
2495 // min X, -X --> -(fabs X)
2496 // TODO: Remove one-use limitation? That is obviously better for max,
2497 // hence why we don't check for one-use for that. However,
2498 // it would be an extra instruction for min (fnabs), but
2499 // that is still likely better for analysis and codegen.
2500 auto IsMinMaxOrXNegX = [IID, &X](Value *Op0, Value *Op1) {
2501 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_Specific(X)))
2502 return Op0->hasOneUse() ||
2503 (IID != Intrinsic::minimum && IID != Intrinsic::minnum);
2504 return false;
2505 };
2506
2507 if (IsMinMaxOrXNegX(Arg0, Arg1) || IsMinMaxOrXNegX(Arg1, Arg0)) {
2508 Value *R = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, X, II);
2509 if (IID == Intrinsic::minimum || IID == Intrinsic::minnum)
2510 R = Builder.CreateFNegFMF(R, II);
2511 return replaceInstUsesWith(*II, R);
2512 }
2513
2514 break;
2515 }
2516 case Intrinsic::matrix_multiply: {
2517 // Optimize negation in matrix multiplication.
2518
2519 // -A * -B -> A * B
2520 Value *A, *B;
2521 if (match(II->getArgOperand(0), m_FNeg(m_Value(A))) &&
2522 match(II->getArgOperand(1), m_FNeg(m_Value(B)))) {
2523 replaceOperand(*II, 0, A);
2524 replaceOperand(*II, 1, B);
2525 return II;
2526 }
2527
2528 Value *Op0 = II->getOperand(0);
2529 Value *Op1 = II->getOperand(1);
2530 Value *OpNotNeg, *NegatedOp;
2531 unsigned NegatedOpArg, OtherOpArg;
2532 if (match(Op0, m_FNeg(m_Value(OpNotNeg)))) {
2533 NegatedOp = Op0;
2534 NegatedOpArg = 0;
2535 OtherOpArg = 1;
2536 } else if (match(Op1, m_FNeg(m_Value(OpNotNeg)))) {
2537 NegatedOp = Op1;
2538 NegatedOpArg = 1;
2539 OtherOpArg = 0;
2540 } else
2541 // Multiplication doesn't have a negated operand.
2542 break;
2543
2544 // Only optimize if the negated operand has only one use.
2545 if (!NegatedOp->hasOneUse())
2546 break;
2547
2548 Value *OtherOp = II->getOperand(OtherOpArg);
2549 VectorType *RetTy = cast<VectorType>(II->getType());
2550 VectorType *NegatedOpTy = cast<VectorType>(NegatedOp->getType());
2551 VectorType *OtherOpTy = cast<VectorType>(OtherOp->getType());
2552 ElementCount NegatedCount = NegatedOpTy->getElementCount();
2553 ElementCount OtherCount = OtherOpTy->getElementCount();
2554 ElementCount RetCount = RetTy->getElementCount();
2555 // (-A) * B -> A * (-B), if it is cheaper to negate B and vice versa.
2556 if (ElementCount::isKnownGT(NegatedCount, OtherCount) &&
2557 ElementCount::isKnownLT(OtherCount, RetCount)) {
2558 Value *InverseOtherOp = Builder.CreateFNeg(OtherOp);
2559 replaceOperand(*II, NegatedOpArg, OpNotNeg);
2560 replaceOperand(*II, OtherOpArg, InverseOtherOp);
2561 return II;
2562 }
2563 // (-A) * B -> -(A * B), if it is cheaper to negate the result
2564 if (ElementCount::isKnownGT(NegatedCount, RetCount)) {
2565 SmallVector<Value *, 5> NewArgs(II->args());
2566 NewArgs[NegatedOpArg] = OpNotNeg;
2567 Instruction *NewMul =
2568 Builder.CreateIntrinsic(II->getType(), IID, NewArgs, II);
2569 return replaceInstUsesWith(*II, Builder.CreateFNegFMF(NewMul, II));
2570 }
2571 break;
2572 }
2573 case Intrinsic::fmuladd: {
2574 // Try to simplify the underlying FMul.
2575 if (Value *V = simplifyFMulInst(II->getArgOperand(0), II->getArgOperand(1),
2576 II->getFastMathFlags(),
2578 auto *FAdd = BinaryOperator::CreateFAdd(V, II->getArgOperand(2));
2579 FAdd->copyFastMathFlags(II);
2580 return FAdd;
2581 }
2582
2583 [[fallthrough]];
2584 }
2585 case Intrinsic::fma: {
2586 // fma fneg(x), fneg(y), z -> fma x, y, z
2587 Value *Src0 = II->getArgOperand(0);
2588 Value *Src1 = II->getArgOperand(1);
2589 Value *Src2 = II->getArgOperand(2);
2590 Value *X, *Y;
2591 if (match(Src0, m_FNeg(m_Value(X))) && match(Src1, m_FNeg(m_Value(Y)))) {
2592 replaceOperand(*II, 0, X);
2593 replaceOperand(*II, 1, Y);
2594 return II;
2595 }
2596
2597 // fma fabs(x), fabs(x), z -> fma x, x, z
2598 if (match(Src0, m_FAbs(m_Value(X))) &&
2599 match(Src1, m_FAbs(m_Specific(X)))) {
2600 replaceOperand(*II, 0, X);
2601 replaceOperand(*II, 1, X);
2602 return II;
2603 }
2604
2605 // Try to simplify the underlying FMul. We can only apply simplifications
2606 // that do not require rounding.
2607 if (Value *V = simplifyFMAFMul(Src0, Src1, II->getFastMathFlags(),
2609 auto *FAdd = BinaryOperator::CreateFAdd(V, Src2);
2610 FAdd->copyFastMathFlags(II);
2611 return FAdd;
2612 }
2613
2614 // fma x, y, 0 -> fmul x, y
2615 // This is always valid for -0.0, but requires nsz for +0.0 as
2616 // -0.0 + 0.0 = 0.0, which would not be the same as the fmul on its own.
2617 if (match(Src2, m_NegZeroFP()) ||
2618 (match(Src2, m_PosZeroFP()) && II->getFastMathFlags().noSignedZeros()))
2619 return BinaryOperator::CreateFMulFMF(Src0, Src1, II);
2620
2621 // fma x, -1.0, y -> fsub y, x
2622 if (match(Src1, m_SpecificFP(-1.0)))
2623 return BinaryOperator::CreateFSubFMF(Src2, Src0, II);
2624
2625 break;
2626 }
2627 case Intrinsic::copysign: {
2628 Value *Mag = II->getArgOperand(0), *Sign = II->getArgOperand(1);
2629 if (std::optional<bool> KnownSignBit = computeKnownFPSignBit(
2630 Sign, /*Depth=*/0, getSimplifyQuery().getWithInstruction(II))) {
2631 if (*KnownSignBit) {
2632 // If we know that the sign argument is negative, reduce to FNABS:
2633 // copysign Mag, -Sign --> fneg (fabs Mag)
2634 Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, Mag, II);
2636 }
2637
2638 // If we know that the sign argument is positive, reduce to FABS:
2639 // copysign Mag, +Sign --> fabs Mag
2640 Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, Mag, II);
2641 return replaceInstUsesWith(*II, Fabs);
2642 }
2643
2644 // Propagate sign argument through nested calls:
2645 // copysign Mag, (copysign ?, X) --> copysign Mag, X
2646 Value *X;
2647 if (match(Sign, m_Intrinsic<Intrinsic::copysign>(m_Value(), m_Value(X))))
2648 return replaceOperand(*II, 1, X);
2649
2650 // Clear sign-bit of constant magnitude:
2651 // copysign -MagC, X --> copysign MagC, X
2652 // TODO: Support constant folding for fabs
2653 const APFloat *MagC;
2654 if (match(Mag, m_APFloat(MagC)) && MagC->isNegative()) {
2655 APFloat PosMagC = *MagC;
2656 PosMagC.clearSign();
2657 return replaceOperand(*II, 0, ConstantFP::get(Mag->getType(), PosMagC));
2658 }
2659
2660 // Peek through changes of magnitude's sign-bit. This call rewrites those:
2661 // copysign (fabs X), Sign --> copysign X, Sign
2662 // copysign (fneg X), Sign --> copysign X, Sign
2663 if (match(Mag, m_FAbs(m_Value(X))) || match(Mag, m_FNeg(m_Value(X))))
2664 return replaceOperand(*II, 0, X);
2665
2666 break;
2667 }
2668 case Intrinsic::fabs: {
2669 Value *Cond, *TVal, *FVal;
2670 Value *Arg = II->getArgOperand(0);
2671 Value *X;
2672 // fabs (-X) --> fabs (X)
2673 if (match(Arg, m_FNeg(m_Value(X)))) {
2674 CallInst *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, X, II);
2675 return replaceInstUsesWith(CI, Fabs);
2676 }
2677
2678 if (match(Arg, m_Select(m_Value(Cond), m_Value(TVal), m_Value(FVal)))) {
2679 // fabs (select Cond, TrueC, FalseC) --> select Cond, AbsT, AbsF
2680 if (isa<Constant>(TVal) || isa<Constant>(FVal)) {
2681 CallInst *AbsT = Builder.CreateCall(II->getCalledFunction(), {TVal});
2682 CallInst *AbsF = Builder.CreateCall(II->getCalledFunction(), {FVal});
2683 SelectInst *SI = SelectInst::Create(Cond, AbsT, AbsF);
2684 FastMathFlags FMF1 = II->getFastMathFlags();
2685 FastMathFlags FMF2 = cast<SelectInst>(Arg)->getFastMathFlags();
2686 FMF2.setNoSignedZeros(false);
2687 SI->setFastMathFlags(FMF1 | FMF2);
2688 return SI;
2689 }
2690 // fabs (select Cond, -FVal, FVal) --> fabs FVal
2691 if (match(TVal, m_FNeg(m_Specific(FVal))))
2692 return replaceOperand(*II, 0, FVal);
2693 // fabs (select Cond, TVal, -TVal) --> fabs TVal
2694 if (match(FVal, m_FNeg(m_Specific(TVal))))
2695 return replaceOperand(*II, 0, TVal);
2696 }
2697
2698 Value *Magnitude, *Sign;
2699 if (match(II->getArgOperand(0),
2700 m_CopySign(m_Value(Magnitude), m_Value(Sign)))) {
2701 // fabs (copysign x, y) -> (fabs x)
2702 CallInst *AbsSign =
2703 Builder.CreateCall(II->getCalledFunction(), {Magnitude});
2704 AbsSign->copyFastMathFlags(II);
2705 return replaceInstUsesWith(*II, AbsSign);
2706 }
2707
2708 [[fallthrough]];
2709 }
2710 case Intrinsic::ceil:
2711 case Intrinsic::floor:
2712 case Intrinsic::round:
2713 case Intrinsic::roundeven:
2714 case Intrinsic::nearbyint:
2715 case Intrinsic::rint:
2716 case Intrinsic::trunc: {
2717 Value *ExtSrc;
2718 if (match(II->getArgOperand(0), m_OneUse(m_FPExt(m_Value(ExtSrc))))) {
2719 // Narrow the call: intrinsic (fpext x) -> fpext (intrinsic x)
2720 Value *NarrowII = Builder.CreateUnaryIntrinsic(IID, ExtSrc, II);
2721 return new FPExtInst(NarrowII, II->getType());
2722 }
2723 break;
2724 }
2725 case Intrinsic::cos:
2726 case Intrinsic::amdgcn_cos: {
2727 Value *X, *Sign;
2728 Value *Src = II->getArgOperand(0);
2729 if (match(Src, m_FNeg(m_Value(X))) || match(Src, m_FAbs(m_Value(X))) ||
2730 match(Src, m_CopySign(m_Value(X), m_Value(Sign)))) {
2731 // cos(-x) --> cos(x)
2732 // cos(fabs(x)) --> cos(x)
2733 // cos(copysign(x, y)) --> cos(x)
2734 return replaceOperand(*II, 0, X);
2735 }
2736 break;
2737 }
2738 case Intrinsic::sin:
2739 case Intrinsic::amdgcn_sin: {
2740 Value *X;
2741 if (match(II->getArgOperand(0), m_OneUse(m_FNeg(m_Value(X))))) {
2742 // sin(-x) --> -sin(x)
2743 Value *NewSin = Builder.CreateUnaryIntrinsic(IID, X, II);
2744 return UnaryOperator::CreateFNegFMF(NewSin, II);
2745 }
2746 break;
2747 }
2748 case Intrinsic::ldexp: {
2749 // ldexp(ldexp(x, a), b) -> ldexp(x, a + b)
2750 //
2751 // The danger is if the first ldexp would overflow to infinity or underflow
2752 // to zero, but the combined exponent avoids it. We ignore this with
2753 // reassoc.
2754 //
2755 // It's also safe to fold if we know both exponents are >= 0 or <= 0 since
2756 // it would just double down on the overflow/underflow which would occur
2757 // anyway.
2758 //
2759 // TODO: Could do better if we had range tracking for the input value
2760 // exponent. Also could broaden sign check to cover == 0 case.
2761 Value *Src = II->getArgOperand(0);
2762 Value *Exp = II->getArgOperand(1);
2763 Value *InnerSrc;
2764 Value *InnerExp;
2765 if (match(Src, m_OneUse(m_Intrinsic<Intrinsic::ldexp>(
2766 m_Value(InnerSrc), m_Value(InnerExp)))) &&
2767 Exp->getType() == InnerExp->getType()) {
2768 FastMathFlags FMF = II->getFastMathFlags();
2769 FastMathFlags InnerFlags = cast<FPMathOperator>(Src)->getFastMathFlags();
2770
2771 if ((FMF.allowReassoc() && InnerFlags.allowReassoc()) ||
2772 signBitMustBeTheSame(Exp, InnerExp, SQ.getWithInstruction(II))) {
2773 // TODO: Add nsw/nuw probably safe if integer type exceeds exponent
2774 // width.
2775 Value *NewExp = Builder.CreateAdd(InnerExp, Exp);
2776 II->setArgOperand(1, NewExp);
2777 II->setFastMathFlags(InnerFlags); // Or the inner flags.
2778 return replaceOperand(*II, 0, InnerSrc);
2779 }
2780 }
2781
2782 // ldexp(x, zext(i1 y)) -> fmul x, (select y, 2.0, 1.0)
2783 // ldexp(x, sext(i1 y)) -> fmul x, (select y, 0.5, 1.0)
2784 Value *ExtSrc;
2785 if (match(Exp, m_ZExt(m_Value(ExtSrc))) &&
2786 ExtSrc->getType()->getScalarSizeInBits() == 1) {
2787 Value *Select =
2788 Builder.CreateSelect(ExtSrc, ConstantFP::get(II->getType(), 2.0),
2789 ConstantFP::get(II->getType(), 1.0));
2791 }
2792 if (match(Exp, m_SExt(m_Value(ExtSrc))) &&
2793 ExtSrc->getType()->getScalarSizeInBits() == 1) {
2794 Value *Select =
2795 Builder.CreateSelect(ExtSrc, ConstantFP::get(II->getType(), 0.5),
2796 ConstantFP::get(II->getType(), 1.0));
2798 }
2799
2800 // ldexp(x, c ? exp : 0) -> c ? ldexp(x, exp) : x
2801 // ldexp(x, c ? 0 : exp) -> c ? x : ldexp(x, exp)
2802 ///
2803 // TODO: If we cared, should insert a canonicalize for x
2804 Value *SelectCond, *SelectLHS, *SelectRHS;
2805 if (match(II->getArgOperand(1),
2806 m_OneUse(m_Select(m_Value(SelectCond), m_Value(SelectLHS),
2807 m_Value(SelectRHS))))) {
2808 Value *NewLdexp = nullptr;
2809 Value *Select = nullptr;
2810 if (match(SelectRHS, m_ZeroInt())) {
2811 NewLdexp = Builder.CreateLdexp(Src, SelectLHS);
2812 Select = Builder.CreateSelect(SelectCond, NewLdexp, Src);
2813 } else if (match(SelectLHS, m_ZeroInt())) {
2814 NewLdexp = Builder.CreateLdexp(Src, SelectRHS);
2815 Select = Builder.CreateSelect(SelectCond, Src, NewLdexp);
2816 }
2817
2818 if (NewLdexp) {
2819 Select->takeName(II);
2820 cast<Instruction>(NewLdexp)->copyFastMathFlags(II);
2821 return replaceInstUsesWith(*II, Select);
2822 }
2823 }
2824
2825 break;
2826 }
2827 case Intrinsic::ptrauth_auth:
2828 case Intrinsic::ptrauth_resign: {
2829 // (sign|resign) + (auth|resign) can be folded by omitting the middle
2830 // sign+auth component if the key and discriminator match.
2831 bool NeedSign = II->getIntrinsicID() == Intrinsic::ptrauth_resign;
2832 Value *Ptr = II->getArgOperand(0);
2833 Value *Key = II->getArgOperand(1);
2834 Value *Disc = II->getArgOperand(2);
2835
2836 // AuthKey will be the key we need to end up authenticating against in
2837 // whatever we replace this sequence with.
2838 Value *AuthKey = nullptr, *AuthDisc = nullptr, *BasePtr;
2839 if (const auto *CI = dyn_cast<CallBase>(Ptr)) {
2840 BasePtr = CI->getArgOperand(0);
2841 if (CI->getIntrinsicID() == Intrinsic::ptrauth_sign) {
2842 if (CI->getArgOperand(1) != Key || CI->getArgOperand(2) != Disc)
2843 break;
2844 } else if (CI->getIntrinsicID() == Intrinsic::ptrauth_resign) {
2845 if (CI->getArgOperand(3) != Key || CI->getArgOperand(4) != Disc)
2846 break;
2847 AuthKey = CI->getArgOperand(1);
2848 AuthDisc = CI->getArgOperand(2);
2849 } else
2850 break;
2851 } else if (const auto *PtrToInt = dyn_cast<PtrToIntOperator>(Ptr)) {
2852 // ptrauth constants are equivalent to a call to @llvm.ptrauth.sign for
2853 // our purposes, so check for that too.
2854 const auto *CPA = dyn_cast<ConstantPtrAuth>(PtrToInt->getOperand(0));
2855 if (!CPA || !CPA->isKnownCompatibleWith(Key, Disc, DL))
2856 break;
2857
2858 // resign(ptrauth(p,ks,ds),ks,ds,kr,dr) -> ptrauth(p,kr,dr)
2859 if (NeedSign && isa<ConstantInt>(II->getArgOperand(4))) {
2860 auto *SignKey = cast<ConstantInt>(II->getArgOperand(3));
2861 auto *SignDisc = cast<ConstantInt>(II->getArgOperand(4));
2862 auto *SignAddrDisc = ConstantPointerNull::get(Builder.getPtrTy());
2863 auto *NewCPA = ConstantPtrAuth::get(CPA->getPointer(), SignKey,
2864 SignDisc, SignAddrDisc);
2866 *II, ConstantExpr::getPointerCast(NewCPA, II->getType()));
2867 return eraseInstFromFunction(*II);
2868 }
2869
2870 // auth(ptrauth(p,k,d),k,d) -> p
2871 BasePtr = Builder.CreatePtrToInt(CPA->getPointer(), II->getType());
2872 } else
2873 break;
2874
2875 unsigned NewIntrin;
2876 if (AuthKey && NeedSign) {
2877 // resign(0,1) + resign(1,2) = resign(0, 2)
2878 NewIntrin = Intrinsic::ptrauth_resign;
2879 } else if (AuthKey) {
2880 // resign(0,1) + auth(1) = auth(0)
2881 NewIntrin = Intrinsic::ptrauth_auth;
2882 } else if (NeedSign) {
2883 // sign(0) + resign(0, 1) = sign(1)
2884 NewIntrin = Intrinsic::ptrauth_sign;
2885 } else {
2886 // sign(0) + auth(0) = nop
2887 replaceInstUsesWith(*II, BasePtr);
2888 return eraseInstFromFunction(*II);
2889 }
2890
2891 SmallVector<Value *, 4> CallArgs;
2892 CallArgs.push_back(BasePtr);
2893 if (AuthKey) {
2894 CallArgs.push_back(AuthKey);
2895 CallArgs.push_back(AuthDisc);
2896 }
2897
2898 if (NeedSign) {
2899 CallArgs.push_back(II->getArgOperand(3));
2900 CallArgs.push_back(II->getArgOperand(4));
2901 }
2902
2903 Function *NewFn =
2904 Intrinsic::getOrInsertDeclaration(II->getModule(), NewIntrin);
2905 return CallInst::Create(NewFn, CallArgs);
2906 }
2907 case Intrinsic::arm_neon_vtbl1:
2908 case Intrinsic::aarch64_neon_tbl1:
2909 if (Value *V = simplifyNeonTbl1(*II, Builder))
2910 return replaceInstUsesWith(*II, V);
2911 break;
2912
2913 case Intrinsic::arm_neon_vmulls:
2914 case Intrinsic::arm_neon_vmullu:
2915 case Intrinsic::aarch64_neon_smull:
2916 case Intrinsic::aarch64_neon_umull: {
2917 Value *Arg0 = II->getArgOperand(0);
2918 Value *Arg1 = II->getArgOperand(1);
2919
2920 // Handle mul by zero first:
2921 if (isa<ConstantAggregateZero>(Arg0) || isa<ConstantAggregateZero>(Arg1)) {
2922 return replaceInstUsesWith(CI, ConstantAggregateZero::get(II->getType()));
2923 }
2924
2925 // Check for constant LHS & RHS - in this case we just simplify.
2926 bool Zext = (IID == Intrinsic::arm_neon_vmullu ||
2927 IID == Intrinsic::aarch64_neon_umull);
2928 VectorType *NewVT = cast<VectorType>(II->getType());
2929 if (Constant *CV0 = dyn_cast<Constant>(Arg0)) {
2930 if (Constant *CV1 = dyn_cast<Constant>(Arg1)) {
2931 Value *V0 = Builder.CreateIntCast(CV0, NewVT, /*isSigned=*/!Zext);
2932 Value *V1 = Builder.CreateIntCast(CV1, NewVT, /*isSigned=*/!Zext);
2933 return replaceInstUsesWith(CI, Builder.CreateMul(V0, V1));
2934 }
2935
2936 // Couldn't simplify - canonicalize constant to the RHS.
2937 std::swap(Arg0, Arg1);
2938 }
2939
2940 // Handle mul by one:
2941 if (Constant *CV1 = dyn_cast<Constant>(Arg1))
2942 if (ConstantInt *Splat =
2943 dyn_cast_or_null<ConstantInt>(CV1->getSplatValue()))
2944 if (Splat->isOne())
2945 return CastInst::CreateIntegerCast(Arg0, II->getType(),
2946 /*isSigned=*/!Zext);
2947
2948 break;
2949 }
2950 case Intrinsic::arm_neon_aesd:
2951 case Intrinsic::arm_neon_aese:
2952 case Intrinsic::aarch64_crypto_aesd:
2953 case Intrinsic::aarch64_crypto_aese: {
2954 Value *DataArg = II->getArgOperand(0);
2955 Value *KeyArg = II->getArgOperand(1);
2956
2957 // Try to use the builtin XOR in AESE and AESD to eliminate a prior XOR
2958 Value *Data, *Key;
2959 if (match(KeyArg, m_ZeroInt()) &&
2960 match(DataArg, m_Xor(m_Value(Data), m_Value(Key)))) {
2961 replaceOperand(*II, 0, Data);
2962 replaceOperand(*II, 1, Key);
2963 return II;
2964 }
2965 break;
2966 }
2967 case Intrinsic::hexagon_V6_vandvrt:
2968 case Intrinsic::hexagon_V6_vandvrt_128B: {
2969 // Simplify Q -> V -> Q conversion.
2970 if (auto Op0 = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {
2971 Intrinsic::ID ID0 = Op0->getIntrinsicID();
2972 if (ID0 != Intrinsic::hexagon_V6_vandqrt &&
2973 ID0 != Intrinsic::hexagon_V6_vandqrt_128B)
2974 break;
2975 Value *Bytes = Op0->getArgOperand(1), *Mask = II->getArgOperand(1);
2976 uint64_t Bytes1 = computeKnownBits(Bytes, 0, Op0).One.getZExtValue();
2977 uint64_t Mask1 = computeKnownBits(Mask, 0, II).One.getZExtValue();
2978 // Check if every byte has common bits in Bytes and Mask.
2979 uint64_t C = Bytes1 & Mask1;
2980 if ((C & 0xFF) && (C & 0xFF00) && (C & 0xFF0000) && (C & 0xFF000000))
2981 return replaceInstUsesWith(*II, Op0->getArgOperand(0));
2982 }
2983 break;
2984 }
2985 case Intrinsic::stackrestore: {
2986 enum class ClassifyResult {
2987 None,
2988 Alloca,
2989 StackRestore,
2990 CallWithSideEffects,
2991 };
2992 auto Classify = [](const Instruction *I) {
2993 if (isa<AllocaInst>(I))
2994 return ClassifyResult::Alloca;
2995
2996 if (auto *CI = dyn_cast<CallInst>(I)) {
2997 if (auto *II = dyn_cast<IntrinsicInst>(CI)) {
2998 if (II->getIntrinsicID() == Intrinsic::stackrestore)
2999 return ClassifyResult::StackRestore;
3000
3001 if (II->mayHaveSideEffects())
3002 return ClassifyResult::CallWithSideEffects;
3003 } else {
3004 // Consider all non-intrinsic calls to be side effects
3005 return ClassifyResult::CallWithSideEffects;
3006 }
3007 }
3008
3009 return ClassifyResult::None;
3010 };
3011
3012 // If the stacksave and the stackrestore are in the same BB, and there is
3013 // no intervening call, alloca, or stackrestore of a different stacksave,
3014 // remove the restore. This can happen when variable allocas are DCE'd.
3015 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {
3016 if (SS->getIntrinsicID() == Intrinsic::stacksave &&
3017 SS->getParent() == II->getParent()) {
3018 BasicBlock::iterator BI(SS);
3019 bool CannotRemove = false;
3020 for (++BI; &*BI != II; ++BI) {
3021 switch (Classify(&*BI)) {
3022 case ClassifyResult::None:
3023 // So far so good, look at next instructions.
3024 break;
3025
3026 case ClassifyResult::StackRestore:
3027 // If we found an intervening stackrestore for a different
3028 // stacksave, we can't remove the stackrestore. Otherwise, continue.
3029 if (cast<IntrinsicInst>(*BI).getArgOperand(0) != SS)
3030 CannotRemove = true;
3031 break;
3032
3033 case ClassifyResult::Alloca:
3034 case ClassifyResult::CallWithSideEffects:
3035 // If we found an alloca, a non-intrinsic call, or an intrinsic
3036 // call with side effects, we can't remove the stackrestore.
3037 CannotRemove = true;
3038 break;
3039 }
3040 if (CannotRemove)
3041 break;
3042 }
3043
3044 if (!CannotRemove)
3045 return eraseInstFromFunction(CI);
3046 }
3047 }
3048
3049 // Scan down this block to see if there is another stack restore in the
3050 // same block without an intervening call/alloca.
3052 Instruction *TI = II->getParent()->getTerminator();
3053 bool CannotRemove = false;
3054 for (++BI; &*BI != TI; ++BI) {
3055 switch (Classify(&*BI)) {
3056 case ClassifyResult::None:
3057 // So far so good, look at next instructions.
3058 break;
3059
3060 case ClassifyResult::StackRestore:
3061 // If there is a stackrestore below this one, remove this one.
3062 return eraseInstFromFunction(CI);
3063
3064 case ClassifyResult::Alloca:
3065 case ClassifyResult::CallWithSideEffects:
3066 // If we found an alloca, a non-intrinsic call, or an intrinsic call
3067 // with side effects (such as llvm.stacksave and llvm.read_register),
3068 // we can't remove the stack restore.
3069 CannotRemove = true;
3070 break;
3071 }
3072 if (CannotRemove)
3073 break;
3074 }
3075
3076 // If the stack restore is in a return, resume, or unwind block and if there
3077 // are no allocas or calls between the restore and the return, nuke the
3078 // restore.
3079 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<ResumeInst>(TI)))
3080 return eraseInstFromFunction(CI);
3081 break;
3082 }
3083 case Intrinsic::lifetime_end:
3084 // Asan needs to poison memory to detect invalid access which is possible
3085 // even for empty lifetime range.
3086 if (II->getFunction()->hasFnAttribute(Attribute::SanitizeAddress) ||
3087 II->getFunction()->hasFnAttribute(Attribute::SanitizeMemory) ||
3088 II->getFunction()->hasFnAttribute(Attribute::SanitizeHWAddress))
3089 break;
3090
3091 if (removeTriviallyEmptyRange(*II, *this, [](const IntrinsicInst &I) {
3092 return I.getIntrinsicID() == Intrinsic::lifetime_start;
3093 }))
3094 return nullptr;
3095 break;
3096 case Intrinsic::assume: {
3097 Value *IIOperand = II->getArgOperand(0);
3099 II->getOperandBundlesAsDefs(OpBundles);
3100
3101 /// This will remove the boolean Condition from the assume given as
3102 /// argument and remove the assume if it becomes useless.
3103 /// always returns nullptr for use as a return values.
3104 auto RemoveConditionFromAssume = [&](Instruction *Assume) -> Instruction * {
3105 assert(isa<AssumeInst>(Assume));
3106 if (isAssumeWithEmptyBundle(*cast<AssumeInst>(II)))
3107 return eraseInstFromFunction(CI);
3108 replaceUse(II->getOperandUse(0), ConstantInt::getTrue(II->getContext()));
3109 return nullptr;
3110 };
3111 // Remove an assume if it is followed by an identical assume.
3112 // TODO: Do we need this? Unless there are conflicting assumptions, the
3113 // computeKnownBits(IIOperand) below here eliminates redundant assumes.
3114 Instruction *Next = II->getNextNonDebugInstruction();
3115 if (match(Next, m_Intrinsic<Intrinsic::assume>(m_Specific(IIOperand))))
3116 return RemoveConditionFromAssume(Next);
3117
3118 // Canonicalize assume(a && b) -> assume(a); assume(b);
3119 // Note: New assumption intrinsics created here are registered by
3120 // the InstCombineIRInserter object.
3121 FunctionType *AssumeIntrinsicTy = II->getFunctionType();
3122 Value *AssumeIntrinsic = II->getCalledOperand();
3123 Value *A, *B;
3124 if (match(IIOperand, m_LogicalAnd(m_Value(A), m_Value(B)))) {
3125 Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic, A, OpBundles,
3126 II->getName());
3127 Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic, B, II->getName());
3128 return eraseInstFromFunction(*II);
3129 }
3130 // assume(!(a || b)) -> assume(!a); assume(!b);
3131 if (match(IIOperand, m_Not(m_LogicalOr(m_Value(A), m_Value(B))))) {
3132 Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic,
3133 Builder.CreateNot(A), OpBundles, II->getName());
3134 Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic,
3135 Builder.CreateNot(B), II->getName());
3136 return eraseInstFromFunction(*II);
3137 }
3138
3139 // assume( (load addr) != null ) -> add 'nonnull' metadata to load
3140 // (if assume is valid at the load)
3143 m_Zero())) &&
3144 LHS->getOpcode() == Instruction::Load &&
3145 LHS->getType()->isPointerTy() &&
3147 MDNode *MD = MDNode::get(II->getContext(), {});
3148 LHS->setMetadata(LLVMContext::MD_nonnull, MD);
3149 LHS->setMetadata(LLVMContext::MD_noundef, MD);
3150 return RemoveConditionFromAssume(II);
3151
3152 // TODO: apply nonnull return attributes to calls and invokes
3153 // TODO: apply range metadata for range check patterns?
3154 }
3155
3156 // Separate storage assumptions apply to the underlying allocations, not any
3157 // particular pointer within them. When evaluating the hints for AA purposes
3158 // we getUnderlyingObject them; by precomputing the answers here we can
3159 // avoid having to do so repeatedly there.
3160 for (unsigned Idx = 0; Idx < II->getNumOperandBundles(); Idx++) {
3161 OperandBundleUse OBU = II->getOperandBundleAt(Idx);
3162 if (OBU.getTagName() == "separate_storage") {
3163 assert(OBU.Inputs.size() == 2);
3164 auto MaybeSimplifyHint = [&](const Use &U) {
3165 Value *Hint = U.get();
3166 // Not having a limit is safe because InstCombine removes unreachable
3167 // code.
3168 Value *UnderlyingObject = getUnderlyingObject(Hint, /*MaxLookup*/ 0);
3169 if (Hint != UnderlyingObject)
3170 replaceUse(const_cast<Use &>(U), UnderlyingObject);
3171 };
3172 MaybeSimplifyHint(OBU.Inputs[0]);
3173 MaybeSimplifyHint(OBU.Inputs[1]);
3174 }
3175 }
3176
3177 // Convert nonnull assume like:
3178 // %A = icmp ne i32* %PTR, null
3179 // call void @llvm.assume(i1 %A)
3180 // into
3181 // call void @llvm.assume(i1 true) [ "nonnull"(i32* %PTR) ]
3183 match(IIOperand,
3185 A->getType()->isPointerTy()) {
3186 if (auto *Replacement = buildAssumeFromKnowledge(
3187 {RetainedKnowledge{Attribute::NonNull, 0, A}}, Next, &AC, &DT)) {
3188
3189 Replacement->insertBefore(Next);
3190 AC.registerAssumption(Replacement);
3191 return RemoveConditionFromAssume(II);
3192 }
3193 }
3194
3195 // Convert alignment assume like:
3196 // %B = ptrtoint i32* %A to i64
3197 // %C = and i64 %B, Constant
3198 // %D = icmp eq i64 %C, 0
3199 // call void @llvm.assume(i1 %D)
3200 // into
3201 // call void @llvm.assume(i1 true) [ "align"(i32* [[A]], i64 Constant + 1)]
3202 uint64_t AlignMask;
3204 match(IIOperand,
3206 m_And(m_Value(A), m_ConstantInt(AlignMask)),
3207 m_Zero()))) {
3208 if (isPowerOf2_64(AlignMask + 1)) {
3209 uint64_t Offset = 0;
3211 if (match(A, m_PtrToInt(m_Value(A)))) {
3212 /// Note: this doesn't preserve the offset information but merges
3213 /// offset and alignment.
3214 /// TODO: we can generate a GEP instead of merging the alignment with
3215 /// the offset.
3216 RetainedKnowledge RK{Attribute::Alignment,
3217 (unsigned)MinAlign(Offset, AlignMask + 1), A};
3218 if (auto *Replacement =
3219 buildAssumeFromKnowledge(RK, Next, &AC, &DT)) {
3220
3221 Replacement->insertAfter(II);
3222 AC.registerAssumption(Replacement);
3223 }
3224 return RemoveConditionFromAssume(II);
3225 }
3226 }
3227 }
3228
3229 /// Canonicalize Knowledge in operand bundles.
3230 if (EnableKnowledgeRetention && II->hasOperandBundles()) {
3231 for (unsigned Idx = 0; Idx < II->getNumOperandBundles(); Idx++) {
3232 auto &BOI = II->bundle_op_info_begin()[Idx];
3234 llvm::getKnowledgeFromBundle(cast<AssumeInst>(*II), BOI);
3235 if (BOI.End - BOI.Begin > 2)
3236 continue; // Prevent reducing knowledge in an align with offset since
3237 // extracting a RetainedKnowledge from them looses offset
3238 // information
3239 RetainedKnowledge CanonRK =
3240 llvm::simplifyRetainedKnowledge(cast<AssumeInst>(II), RK,
3242 &getDominatorTree());
3243 if (CanonRK == RK)
3244 continue;
3245 if (!CanonRK) {
3246 if (BOI.End - BOI.Begin > 0) {
3247 Worklist.pushValue(II->op_begin()[BOI.Begin]);
3248 Value::dropDroppableUse(II->op_begin()[BOI.Begin]);
3249 }
3250 continue;
3251 }
3252 assert(RK.AttrKind == CanonRK.AttrKind);
3253 if (BOI.End - BOI.Begin > 0)
3254 II->op_begin()[BOI.Begin].set(CanonRK.WasOn);
3255 if (BOI.End - BOI.Begin > 1)
3256 II->op_begin()[BOI.Begin + 1].set(ConstantInt::get(
3257 Type::getInt64Ty(II->getContext()), CanonRK.ArgValue));
3258 if (RK.WasOn)
3260 return II;
3261 }
3262 }
3263
3264 // If there is a dominating assume with the same condition as this one,
3265 // then this one is redundant, and should be removed.
3266 KnownBits Known(1);
3267 computeKnownBits(IIOperand, Known, 0, II);
3268 if (Known.isAllOnes() && isAssumeWithEmptyBundle(cast<AssumeInst>(*II)))
3269 return eraseInstFromFunction(*II);
3270
3271 // assume(false) is unreachable.
3272 if (match(IIOperand, m_CombineOr(m_Zero(), m_Undef()))) {
3274 return eraseInstFromFunction(*II);
3275 }
3276
3277 // Update the cache of affected values for this assumption (we might be
3278 // here because we just simplified the condition).
3279 AC.updateAffectedValues(cast<AssumeInst>(II));
3280 break;
3281 }
3282 case Intrinsic::experimental_guard: {
3283 // Is this guard followed by another guard? We scan forward over a small
3284 // fixed window of instructions to handle common cases with conditions
3285 // computed between guards.
3286 Instruction *NextInst = II->getNextNonDebugInstruction();
3287 for (unsigned i = 0; i < GuardWideningWindow; i++) {
3288 // Note: Using context-free form to avoid compile time blow up
3289 if (!isSafeToSpeculativelyExecute(NextInst))
3290 break;
3291 NextInst = NextInst->getNextNonDebugInstruction();
3292 }
3293 Value *NextCond = nullptr;
3294 if (match(NextInst,
3295 m_Intrinsic<Intrinsic::experimental_guard>(m_Value(NextCond)))) {
3296 Value *CurrCond = II->getArgOperand(0);
3297
3298 // Remove a guard that it is immediately preceded by an identical guard.
3299 // Otherwise canonicalize guard(a); guard(b) -> guard(a & b).
3300 if (CurrCond != NextCond) {
3301 Instruction *MoveI = II->getNextNonDebugInstruction();
3302 while (MoveI != NextInst) {
3303 auto *Temp = MoveI;
3304 MoveI = MoveI->getNextNonDebugInstruction();
3305 Temp->moveBefore(II);
3306 }
3307 replaceOperand(*II, 0, Builder.CreateAnd(CurrCond, NextCond));
3308 }
3309 eraseInstFromFunction(*NextInst);
3310 return II;
3311 }
3312 break;
3313 }
3314 case Intrinsic::vector_insert: {
3315 Value *Vec = II->getArgOperand(0);
3316 Value *SubVec = II->getArgOperand(1);
3317 Value *Idx = II->getArgOperand(2);
3318 auto *DstTy = dyn_cast<FixedVectorType>(II->getType());
3319 auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType());
3320 auto *SubVecTy = dyn_cast<FixedVectorType>(SubVec->getType());
3321
3322 // Only canonicalize if the destination vector, Vec, and SubVec are all
3323 // fixed vectors.
3324 if (DstTy && VecTy && SubVecTy) {
3325 unsigned DstNumElts = DstTy->getNumElements();
3326 unsigned VecNumElts = VecTy->getNumElements();
3327 unsigned SubVecNumElts = SubVecTy->getNumElements();
3328 unsigned IdxN = cast<ConstantInt>(Idx)->getZExtValue();
3329
3330 // An insert that entirely overwrites Vec with SubVec is a nop.
3331 if (VecNumElts == SubVecNumElts)
3332 return replaceInstUsesWith(CI, SubVec);
3333
3334 // Widen SubVec into a vector of the same width as Vec, since
3335 // shufflevector requires the two input vectors to be the same width.
3336 // Elements beyond the bounds of SubVec within the widened vector are
3337 // undefined.
3338 SmallVector<int, 8> WidenMask;
3339 unsigned i;
3340 for (i = 0; i != SubVecNumElts; ++i)
3341 WidenMask.push_back(i);
3342 for (; i != VecNumElts; ++i)
3343 WidenMask.push_back(PoisonMaskElem);
3344
3345 Value *WidenShuffle = Builder.CreateShuffleVector(SubVec, WidenMask);
3346
3348 for (unsigned i = 0; i != IdxN; ++i)
3349 Mask.push_back(i);
3350 for (unsigned i = DstNumElts; i != DstNumElts + SubVecNumElts; ++i)
3351 Mask.push_back(i);
3352 for (unsigned i = IdxN + SubVecNumElts; i != DstNumElts; ++i)
3353 Mask.push_back(i);
3354
3355 Value *Shuffle = Builder.CreateShuffleVector(Vec, WidenShuffle, Mask);
3356 return replaceInstUsesWith(CI, Shuffle);
3357 }
3358 break;
3359 }
3360 case Intrinsic::vector_extract: {
3361 Value *Vec = II->getArgOperand(0);
3362 Value *Idx = II->getArgOperand(1);
3363
3364 Type *ReturnType = II->getType();
3365 // (extract_vector (insert_vector InsertTuple, InsertValue, InsertIdx),
3366 // ExtractIdx)
3367 unsigned ExtractIdx = cast<ConstantInt>(Idx)->getZExtValue();
3368 Value *InsertTuple, *InsertIdx, *InsertValue;
3369 if (match(Vec, m_Intrinsic<Intrinsic::vector_insert>(m_Value(InsertTuple),
3370 m_Value(InsertValue),
3371 m_Value(InsertIdx))) &&
3372 InsertValue->getType() == ReturnType) {
3373 unsigned Index = cast<ConstantInt>(InsertIdx)->getZExtValue();
3374 // Case where we get the same index right after setting it.
3375 // extract.vector(insert.vector(InsertTuple, InsertValue, Idx), Idx) -->
3376 // InsertValue
3377 if (ExtractIdx == Index)
3378 return replaceInstUsesWith(CI, InsertValue);
3379 // If we are getting a different index than what was set in the
3380 // insert.vector intrinsic. We can just set the input tuple to the one up
3381 // in the chain. extract.vector(insert.vector(InsertTuple, InsertValue,
3382 // InsertIndex), ExtractIndex)
3383 // --> extract.vector(InsertTuple, ExtractIndex)
3384 else
3385 return replaceOperand(CI, 0, InsertTuple);
3386 }
3387
3388 auto *DstTy = dyn_cast<VectorType>(ReturnType);
3389 auto *VecTy = dyn_cast<VectorType>(Vec->getType());
3390
3391 if (DstTy && VecTy) {
3392 auto DstEltCnt = DstTy->getElementCount();
3393 auto VecEltCnt = VecTy->getElementCount();
3394 unsigned IdxN = cast<ConstantInt>(Idx)->getZExtValue();
3395
3396 // Extracting the entirety of Vec is a nop.
3397 if (DstEltCnt == VecTy->getElementCount()) {
3398 replaceInstUsesWith(CI, Vec);
3399 return eraseInstFromFunction(CI);
3400 }
3401
3402 // Only canonicalize to shufflevector if the destination vector and
3403 // Vec are fixed vectors.
3404 if (VecEltCnt.isScalable() || DstEltCnt.isScalable())
3405 break;
3406
3408 for (unsigned i = 0; i != DstEltCnt.getKnownMinValue(); ++i)
3409 Mask.push_back(IdxN + i);
3410
3411 Value *Shuffle = Builder.CreateShuffleVector(Vec, Mask);
3412 return replaceInstUsesWith(CI, Shuffle);
3413 }
3414 break;
3415 }
3416 case Intrinsic::vector_reverse: {
3417 Value *BO0, *BO1, *X, *Y;
3418 Value *Vec = II->getArgOperand(0);
3419 if (match(Vec, m_OneUse(m_BinOp(m_Value(BO0), m_Value(BO1))))) {
3420 auto *OldBinOp = cast<BinaryOperator>(Vec);
3421 if (match(BO0, m_VecReverse(m_Value(X)))) {
3422 // rev(binop rev(X), rev(Y)) --> binop X, Y
3423 if (match(BO1, m_VecReverse(m_Value(Y))))
3425 OldBinOp->getOpcode(), X, Y,
3426 OldBinOp, OldBinOp->getName(),
3427 II->getIterator()));
3428 // rev(binop rev(X), BO1Splat) --> binop X, BO1Splat
3429 if (isSplatValue(BO1))
3431 OldBinOp->getOpcode(), X, BO1,
3432 OldBinOp, OldBinOp->getName(),
3433 II->getIterator()));
3434 }
3435 // rev(binop BO0Splat, rev(Y)) --> binop BO0Splat, Y
3436 if (match(BO1, m_VecReverse(m_Value(Y))) && isSplatValue(BO0))
3437 return replaceInstUsesWith(CI,
3439 OldBinOp->getOpcode(), BO0, Y, OldBinOp,
3440 OldBinOp->getName(), II->getIterator()));
3441 }
3442 // rev(unop rev(X)) --> unop X
3443 if (match(Vec, m_OneUse(m_UnOp(m_VecReverse(m_Value(X)))))) {
3444 auto *OldUnOp = cast<UnaryOperator>(Vec);
3446 OldUnOp->getOpcode(), X, OldUnOp, OldUnOp->getName(),
3447 II->getIterator());
3448 return replaceInstUsesWith(CI, NewUnOp);
3449 }
3450 break;
3451 }
3452 case Intrinsic::vector_reduce_or:
3453 case Intrinsic::vector_reduce_and: {
3454 // Canonicalize logical or/and reductions:
3455 // Or reduction for i1 is represented as:
3456 // %val = bitcast <ReduxWidth x i1> to iReduxWidth
3457 // %res = cmp ne iReduxWidth %val, 0
3458 // And reduction for i1 is represented as:
3459 // %val = bitcast <ReduxWidth x i1> to iReduxWidth
3460 // %res = cmp eq iReduxWidth %val, 11111
3461 Value *Arg = II->getArgOperand(0);
3462 Value *Vect;
3463
3464 if (Value *NewOp =
3465 simplifyReductionOperand(Arg, /*CanReorderLanes=*/true)) {
3466 replaceUse(II->getOperandUse(0), NewOp);
3467 return II;
3468 }
3469
3470 if (match(Arg, m_ZExtOrSExtOrSelf(m_Value(Vect)))) {
3471 if (auto *FTy = dyn_cast<FixedVectorType>(Vect->getType()))
3472 if (FTy->getElementType() == Builder.getInt1Ty()) {
3474 Vect, Builder.getIntNTy(FTy->getNumElements()));
3475 if (IID == Intrinsic::vector_reduce_and) {
3476 Res = Builder.CreateICmpEQ(
3478 } else {
3479 assert(IID == Intrinsic::vector_reduce_or &&
3480 "Expected or reduction.");
3481 Res = Builder.CreateIsNotNull(Res);
3482 }
3483 if (Arg != Vect)
3484 Res = Builder.CreateCast(cast<CastInst>(Arg)->getOpcode(), Res,
3485 II->getType());
3486 return replaceInstUsesWith(CI, Res);
3487 }
3488 }
3489 [[fallthrough]];
3490 }
3491 case Intrinsic::vector_reduce_add: {
3492 if (IID == Intrinsic::vector_reduce_add) {
3493 // Convert vector_reduce_add(ZExt(<n x i1>)) to
3494 // ZExtOrTrunc(ctpop(bitcast <n x i1> to in)).
3495 // Convert vector_reduce_add(SExt(<n x i1>)) to
3496 // -ZExtOrTrunc(ctpop(bitcast <n x i1> to in)).
3497 // Convert vector_reduce_add(<n x i1>) to
3498 // Trunc(ctpop(bitcast <n x i1> to in)).
3499 Value *Arg = II->getArgOperand(0);
3500 Value *Vect;
3501
3502 if (Value *NewOp =
3503 simplifyReductionOperand(Arg, /*CanReorderLanes=*/true)) {
3504 replaceUse(II->getOperandUse(0), NewOp);
3505 return II;
3506 }
3507
3508 if (match(Arg, m_ZExtOrSExtOrSelf(m_Value(Vect)))) {
3509 if (auto *FTy = dyn_cast<FixedVectorType>(Vect->getType()))
3510 if (FTy->getElementType() == Builder.getInt1Ty()) {
3512 Vect, Builder.getIntNTy(FTy->getNumElements()));
3513 Value *Res = Builder.CreateUnaryIntrinsic(Intrinsic::ctpop, V);
3514 if (Res->getType() != II->getType())
3515 Res = Builder.CreateZExtOrTrunc(Res, II->getType());
3516 if (Arg != Vect &&
3517 cast<Instruction>(Arg)->getOpcode() == Instruction::SExt)
3518 Res = Builder.CreateNeg(Res);
3519 return replaceInstUsesWith(CI, Res);
3520 }
3521 }
3522 }
3523 [[fallthrough]];
3524 }
3525 case Intrinsic::vector_reduce_xor: {
3526 if (IID == Intrinsic::vector_reduce_xor) {
3527 // Exclusive disjunction reduction over the vector with
3528 // (potentially-extended) i1 element type is actually a
3529 // (potentially-extended) arithmetic `add` reduction over the original
3530 // non-extended value:
3531 // vector_reduce_xor(?ext(<n x i1>))
3532 // -->
3533 // ?ext(vector_reduce_add(<n x i1>))
3534 Value *Arg = II->getArgOperand(0);
3535 Value *Vect;
3536
3537 if (Value *NewOp =
3538 simplifyReductionOperand(Arg, /*CanReorderLanes=*/true)) {
3539 replaceUse(II->getOperandUse(0), NewOp);
3540 return II;
3541 }
3542
3543 if (match(Arg, m_ZExtOrSExtOrSelf(m_Value(Vect)))) {
3544 if (auto *VTy = dyn_cast<VectorType>(Vect->getType()))
3545 if (VTy->getElementType() == Builder.getInt1Ty()) {
3546 Value *Res = Builder.CreateAddReduce(Vect);
3547 if (Arg != Vect)
3548 Res = Builder.CreateCast(cast<CastInst>(Arg)->getOpcode(), Res,
3549 II->getType());
3550 return replaceInstUsesWith(CI, Res);
3551 }
3552 }
3553 }
3554 [[fallthrough]];
3555 }
3556 case Intrinsic::vector_reduce_mul: {
3557 if (IID == Intrinsic::vector_reduce_mul) {
3558 // Multiplicative reduction over the vector with (potentially-extended)
3559 // i1 element type is actually a (potentially zero-extended)
3560 // logical `and` reduction over the original non-extended value:
3561 // vector_reduce_mul(?ext(<n x i1>))
3562 // -->
3563 // zext(vector_reduce_and(<n x i1>))
3564 Value *Arg = II->getArgOperand(0);
3565 Value *Vect;
3566
3567 if (Value *NewOp =
3568 simplifyReductionOperand(Arg, /*CanReorderLanes=*/true)) {
3569 replaceUse(II->getOperandUse(0), NewOp);
3570 return II;
3571 }
3572
3573 if (match(Arg, m_ZExtOrSExtOrSelf(m_Value(Vect)))) {
3574 if (auto *VTy = dyn_cast<VectorType>(Vect->getType()))
3575 if (VTy->getElementType() == Builder.getInt1Ty()) {
3576 Value *Res = Builder.CreateAndReduce(Vect);
3577 if (Res->getType() != II->getType())
3578 Res = Builder.CreateZExt(Res, II->getType());
3579 return replaceInstUsesWith(CI, Res);
3580 }
3581 }
3582 }
3583 [[fallthrough]];
3584 }
3585 case Intrinsic::vector_reduce_umin:
3586 case Intrinsic::vector_reduce_umax: {
3587 if (IID == Intrinsic::vector_reduce_umin ||
3588 IID == Intrinsic::vector_reduce_umax) {
3589 // UMin/UMax reduction over the vector with (potentially-extended)
3590 // i1 element type is actually a (potentially-extended)
3591 // logical `and`/`or` reduction over the original non-extended value:
3592 // vector_reduce_u{min,max}(?ext(<n x i1>))
3593 // -->
3594 // ?ext(vector_reduce_{and,or}(<n x i1>))
3595 Value *Arg = II->getArgOperand(0);
3596 Value *Vect;
3597
3598 if (Value *NewOp =
3599 simplifyReductionOperand(Arg, /*CanReorderLanes=*/true)) {
3600 replaceUse(II->getOperandUse(0), NewOp);
3601 return II;
3602 }
3603
3604 if (match(Arg, m_ZExtOrSExtOrSelf(m_Value(Vect)))) {
3605 if (auto *VTy = dyn_cast<VectorType>(Vect->getType()))
3606 if (VTy->getElementType() == Builder.getInt1Ty()) {
3607 Value *Res = IID == Intrinsic::vector_reduce_umin
3608 ? Builder.CreateAndReduce(Vect)
3609 : Builder.CreateOrReduce(Vect);
3610 if (Arg != Vect)
3611 Res = Builder.CreateCast(cast<CastInst>(Arg)->getOpcode(), Res,
3612 II->getType());
3613 return replaceInstUsesWith(CI, Res);
3614 }
3615 }
3616 }
3617 [[fallthrough]];
3618 }
3619 case Intrinsic::vector_reduce_smin:
3620 case Intrinsic::vector_reduce_smax: {
3621 if (IID == Intrinsic::vector_reduce_smin ||
3622 IID == Intrinsic::vector_reduce_smax) {
3623 // SMin/SMax reduction over the vector with (potentially-extended)
3624 // i1 element type is actually a (potentially-extended)
3625 // logical `and`/`or` reduction over the original non-extended value:
3626 // vector_reduce_s{min,max}(<n x i1>)
3627 // -->
3628 // vector_reduce_{or,and}(<n x i1>)
3629 // and
3630 // vector_reduce_s{min,max}(sext(<n x i1>))
3631 // -->
3632 // sext(vector_reduce_{or,and}(<n x i1>))
3633 // and
3634 // vector_reduce_s{min,max}(zext(<n x i1>))
3635 // -->
3636 // zext(vector_reduce_{and,or}(<n x i1>))
3637 Value *Arg = II->getArgOperand(0);
3638 Value *Vect;
3639
3640 if (Value *NewOp =
3641 simplifyReductionOperand(Arg, /*CanReorderLanes=*/true)) {
3642 replaceUse(II->getOperandUse(0), NewOp);
3643 return II;
3644 }
3645
3646 if (match(Arg, m_ZExtOrSExtOrSelf(m_Value(Vect)))) {
3647 if (auto *VTy = dyn_cast<VectorType>(Vect->getType()))
3648 if (VTy->getElementType() == Builder.getInt1Ty()) {
3649 Instruction::CastOps ExtOpc = Instruction::CastOps::CastOpsEnd;
3650 if (Arg != Vect)
3651 ExtOpc = cast<CastInst>(Arg)->getOpcode();
3652 Value *Res = ((IID == Intrinsic::vector_reduce_smin) ==
3653 (ExtOpc == Instruction::CastOps::ZExt))
3654 ? Builder.CreateAndReduce(Vect)
3655 : Builder.CreateOrReduce(Vect);
3656 if (Arg != Vect)
3657 Res = Builder.CreateCast(ExtOpc, Res, II->getType());
3658 return replaceInstUsesWith(CI, Res);
3659 }
3660 }
3661 }
3662 [[fallthrough]];
3663 }
3664 case Intrinsic::vector_reduce_fmax:
3665 case Intrinsic::vector_reduce_fmin:
3666 case Intrinsic::vector_reduce_fadd:
3667 case Intrinsic::vector_reduce_fmul: {
3668 bool CanReorderLanes = (IID != Intrinsic::vector_reduce_fadd &&
3669 IID != Intrinsic::vector_reduce_fmul) ||
3670 II->hasAllowReassoc();
3671 const unsigned ArgIdx = (IID == Intrinsic::vector_reduce_fadd ||
3672 IID == Intrinsic::vector_reduce_fmul)
3673 ? 1
3674 : 0;
3675 Value *Arg = II->getArgOperand(ArgIdx);
3676 if (Value *NewOp = simplifyReductionOperand(Arg, CanReorderLanes)) {
3677 replaceUse(II->getOperandUse(ArgIdx), NewOp);
3678 return nullptr;
3679 }
3680 break;
3681 }
3682 case Intrinsic::is_fpclass: {
3683 if (Instruction *I = foldIntrinsicIsFPClass(*II))
3684 return I;
3685 break;
3686 }
3687 case Intrinsic::threadlocal_address: {
3688 Align MinAlign = getKnownAlignment(II->getArgOperand(0), DL, II, &AC, &DT);
3689 MaybeAlign Align = II->getRetAlign();
3690 if (MinAlign > Align.valueOrOne()) {
3691 II->addRetAttr(Attribute::getWithAlignment(II->getContext(), MinAlign));
3692 return II;
3693 }
3694 break;
3695 }
3696 default: {
3697 // Handle target specific intrinsics
3698 std::optional<Instruction *> V = targetInstCombineIntrinsic(*II);
3699 if (V)
3700 return *V;
3701 break;
3702 }
3703 }
3704
3705 // Try to fold intrinsic into select operands. This is legal if:
3706 // * The intrinsic is speculatable.
3707 // * The select condition is not a vector, or the intrinsic does not
3708 // perform cross-lane operations.
3711 for (Value *Op : II->args())
3712 if (auto *Sel = dyn_cast<SelectInst>(Op))
3713 if (Instruction *R = FoldOpIntoSelect(*II, Sel))
3714 return R;
3715
3717 return Shuf;
3718
3719 // Some intrinsics (like experimental_gc_statepoint) can be used in invoke
3720 // context, so it is handled in visitCallBase and we should trigger it.
3721 return visitCallBase(*II);
3722}
3723
3724// Fence instruction simplification
3726 auto *NFI = dyn_cast<FenceInst>(FI.getNextNonDebugInstruction());
3727 // This check is solely here to handle arbitrary target-dependent syncscopes.
3728 // TODO: Can remove if does not matter in practice.
3729 if (NFI && FI.isIdenticalTo(NFI))
3730 return eraseInstFromFunction(FI);
3731
3732 // Returns true if FI1 is identical or stronger fence than FI2.
3733 auto isIdenticalOrStrongerFence = [](FenceInst *FI1, FenceInst *FI2) {
3734 auto FI1SyncScope = FI1->getSyncScopeID();
3735 // Consider same scope, where scope is global or single-thread.
3736 if (FI1SyncScope != FI2->getSyncScopeID() ||
3737 (FI1SyncScope != SyncScope::System &&
3738 FI1SyncScope != SyncScope::SingleThread))
3739 return false;
3740
3741 return isAtLeastOrStrongerThan(FI1->getOrdering(), FI2->getOrdering());
3742 };
3743 if (NFI && isIdenticalOrStrongerFence(NFI, &FI))
3744 return eraseInstFromFunction(FI);
3745
3746 if (auto *PFI = dyn_cast_or_null<FenceInst>(FI.getPrevNonDebugInstruction()))
3747 if (isIdenticalOrStrongerFence(PFI, &FI))
3748 return eraseInstFromFunction(FI);
3749 return nullptr;
3750}
3751
3752// InvokeInst simplification
3754 return visitCallBase(II);
3755}
3756
3757// CallBrInst simplification
3759 return visitCallBase(CBI);
3760}
3761
3762Instruction *InstCombinerImpl::tryOptimizeCall(CallInst *CI) {
3763 if (!CI->getCalledFunction()) return nullptr;
3764
3765 // Skip optimizing notail and musttail calls so
3766 // LibCallSimplifier::optimizeCall doesn't have to preserve those invariants.
3767 // LibCallSimplifier::optimizeCall should try to preserve tail calls though.
3768 if (CI->isMustTailCall() || CI->isNoTailCall())
3769 return nullptr;
3770
3771 auto InstCombineRAUW = [this](Instruction *From, Value *With) {
3772 replaceInstUsesWith(*From, With);
3773 };
3774 auto InstCombineErase = [this](Instruction *I) {
3776 };
3777 LibCallSimplifier Simplifier(DL, &TLI, &DT, &DC, &AC, ORE, BFI, PSI,
3778 InstCombineRAUW, InstCombineErase);
3779 if (Value *With = Simplifier.optimizeCall(CI, Builder)) {
3780 ++NumSimplified;
3781 return CI->use_empty() ? CI : replaceInstUsesWith(*CI, With);
3782 }
3783
3784 return nullptr;
3785}
3786
3788 // Strip off at most one level of pointer casts, looking for an alloca. This
3789 // is good enough in practice and simpler than handling any number of casts.
3790 Value *Underlying = TrampMem->stripPointerCasts();
3791 if (Underlying != TrampMem &&
3792 (!Underlying->hasOneUse() || Underlying->user_back() != TrampMem))
3793 return nullptr;
3794 if (!isa<AllocaInst>(Underlying))
3795 return nullptr;
3796
3797 IntrinsicInst *InitTrampoline = nullptr;
3798 for (User *U : TrampMem->users()) {
3799 IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
3800 if (!II)
3801 return nullptr;
3802 if (II->getIntrinsicID() == Intrinsic::init_trampoline) {
3803 if (InitTrampoline)
3804 // More than one init_trampoline writes to this value. Give up.
3805 return nullptr;
3806 InitTrampoline = II;
3807 continue;
3808 }
3809 if (II->getIntrinsicID() == Intrinsic::adjust_trampoline)
3810 // Allow any number of calls to adjust.trampoline.
3811 continue;
3812 return nullptr;
3813 }
3814
3815 // No call to init.trampoline found.
3816 if (!InitTrampoline)
3817 return nullptr;
3818
3819 // Check that the alloca is being used in the expected way.
3820 if (InitTrampoline->getOperand(0) != TrampMem)
3821 return nullptr;
3822
3823 return InitTrampoline;
3824}
3825
3827 Value *TrampMem) {
3828 // Visit all the previous instructions in the basic block, and try to find a
3829 // init.trampoline which has a direct path to the adjust.trampoline.
3830 for (BasicBlock::iterator I = AdjustTramp->getIterator(),
3831 E = AdjustTramp->getParent()->begin();
3832 I != E;) {
3833 Instruction *Inst = &*--I;
3834 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
3835 if (II->getIntrinsicID() == Intrinsic::init_trampoline &&
3836 II->getOperand(0) == TrampMem)
3837 return II;
3838 if (Inst->mayWriteToMemory())
3839 return nullptr;
3840 }
3841 return nullptr;
3842}
3843
3844// Given a call to llvm.adjust.trampoline, find and return the corresponding
3845// call to llvm.init.trampoline if the call to the trampoline can be optimized
3846// to a direct call to a function. Otherwise return NULL.
3848 Callee = Callee->stripPointerCasts();
3849 IntrinsicInst *AdjustTramp = dyn_cast<IntrinsicInst>(Callee);
3850 if (!AdjustTramp ||
3851 AdjustTramp->getIntrinsicID() != Intrinsic::adjust_trampoline)
3852 return nullptr;
3853
3854 Value *TrampMem = AdjustTramp->getOperand(0);
3855
3857 return IT;
3858 if (IntrinsicInst *IT = findInitTrampolineFromBB(AdjustTramp, TrampMem))
3859 return IT;
3860 return nullptr;
3861}
3862
3863bool InstCombinerImpl::annotateAnyAllocSite(CallBase &Call,
3864 const TargetLibraryInfo *TLI) {
3865 // Note: We only handle cases which can't be driven from generic attributes
3866 // here. So, for example, nonnull and noalias (which are common properties
3867 // of some allocation functions) are expected to be handled via annotation
3868 // of the respective allocator declaration with generic attributes.
3869 bool Changed = false;
3870
3871 if (!Call.getType()->isPointerTy())
3872 return Changed;
3873
3874 std::optional<APInt> Size = getAllocSize(&Call, TLI);
3875 if (Size && *Size != 0) {
3876 // TODO: We really should just emit deref_or_null here and then
3877 // let the generic inference code combine that with nonnull.
3878 if (Call.hasRetAttr(Attribute::NonNull)) {
3879 Changed = !Call.hasRetAttr(Attribute::Dereferenceable);
3881 Call.getContext(), Size->getLimitedValue()));
3882 } else {
3883 Changed = !Call.hasRetAttr(Attribute::DereferenceableOrNull);
3885 Call.getContext(), Size->getLimitedValue()));
3886 }
3887 }
3888
3889 // Add alignment attribute if alignment is a power of two constant.
3890 Value *Alignment = getAllocAlignment(&Call, TLI);
3891 if (!Alignment)
3892 return Changed;
3893
3894 ConstantInt *AlignOpC = dyn_cast<ConstantInt>(Alignment);
3895 if (AlignOpC && AlignOpC->getValue().ult(llvm::Value::MaximumAlignment)) {
3896 uint64_t AlignmentVal = AlignOpC->getZExtValue();
3897 if (llvm::isPowerOf2_64(AlignmentVal)) {
3898 Align ExistingAlign = Call.getRetAlign().valueOrOne();
3899 Align NewAlign = Align(AlignmentVal);
3900 if (NewAlign > ExistingAlign) {
3901 Call.addRetAttr(
3902 Attribute::getWithAlignment(Call.getContext(), NewAlign));
3903 Changed = true;
3904 }
3905 }
3906 }
3907 return Changed;
3908}
3909
3910/// Improvements for call, callbr and invoke instructions.
3911Instruction *InstCombinerImpl::visitCallBase(CallBase &Call) {
3912 bool Changed = annotateAnyAllocSite(Call, &TLI);
3913
3914 // Mark any parameters that are known to be non-null with the nonnull
3915 // attribute. This is helpful for inlining calls to functions with null
3916 // checks on their arguments.
3918 unsigned ArgNo = 0;
3919
3920 for (Value *V : Call.args()) {
3921 if (V->getType()->isPointerTy() &&
3922 !Call.paramHasAttr(ArgNo, Attribute::NonNull) &&
3923 isKnownNonZero(V, getSimplifyQuery().getWithInstruction(&Call)))
3924 ArgNos.push_back(ArgNo);
3925 ArgNo++;
3926 }
3927
3928 assert(ArgNo == Call.arg_size() && "Call arguments not processed correctly.");
3929
3930 if (!ArgNos.empty()) {
3931 AttributeList AS = Call.getAttributes();
3932 LLVMContext &Ctx = Call.getContext();
3933 AS = AS.addParamAttribute(Ctx, ArgNos,
3934 Attribute::get(Ctx, Attribute::NonNull));
3935 Call.setAttributes(AS);
3936 Changed = true;
3937 }
3938
3939 // If the callee is a pointer to a function, attempt to move any casts to the
3940 // arguments of the call/callbr/invoke.
3941 Value *Callee = Call.getCalledOperand();
3942 Function *CalleeF = dyn_cast<Function>(Callee);
3943 if ((!CalleeF || CalleeF->getFunctionType() != Call.getFunctionType()) &&
3944 transformConstExprCastCall(Call))
3945 return nullptr;
3946
3947 if (CalleeF) {
3948 // Remove the convergent attr on calls when the callee is not convergent.
3949 if (Call.isConvergent() && !CalleeF->isConvergent() &&
3950 !CalleeF->isIntrinsic()) {
3951 LLVM_DEBUG(dbgs() << "Removing convergent attr from instr " << Call
3952 << "\n");
3953 Call.setNotConvergent();
3954 return &Call;
3955 }
3956
3957 // If the call and callee calling conventions don't match, and neither one
3958 // of the calling conventions is compatible with C calling convention
3959 // this call must be unreachable, as the call is undefined.
3960 if ((CalleeF->getCallingConv() != Call.getCallingConv() &&
3961 !(CalleeF->getCallingConv() == llvm::CallingConv::C &&
3963 !(Call.getCallingConv() == llvm::CallingConv::C &&
3965 // Only do this for calls to a function with a body. A prototype may
3966 // not actually end up matching the implementation's calling conv for a
3967 // variety of reasons (e.g. it may be written in assembly).
3968 !CalleeF->isDeclaration()) {
3969 Instruction *OldCall = &Call;
3971 // If OldCall does not return void then replaceInstUsesWith poison.
3972 // This allows ValueHandlers and custom metadata to adjust itself.
3973 if (!OldCall->getType()->isVoidTy())
3974 replaceInstUsesWith(*OldCall, PoisonValue::get(OldCall->getType()));
3975 if (isa<CallInst>(OldCall))
3976 return eraseInstFromFunction(*OldCall);
3977
3978 // We cannot remove an invoke or a callbr, because it would change thexi
3979 // CFG, just change the callee to a null pointer.
3980 cast<CallBase>(OldCall)->setCalledFunction(
3981 CalleeF->getFunctionType(),
3982 Constant::getNullValue(CalleeF->getType()));
3983 return nullptr;
3984 }
3985 }
3986
3987 // Calling a null function pointer is undefined if a null address isn't
3988 // dereferenceable.
3989 if ((isa<ConstantPointerNull>(Callee) &&
3990 !NullPointerIsDefined(Call.getFunction())) ||
3991 isa<UndefValue>(Callee)) {
3992 // If Call does not return void then replaceInstUsesWith poison.
3993 // This allows ValueHandlers and custom metadata to adjust itself.
3994 if (!Call.getType()->isVoidTy())
3995 replaceInstUsesWith(Call, PoisonValue::get(Call.getType()));
3996
3997 if (Call.isTerminator()) {
3998 // Can't remove an invoke or callbr because we cannot change the CFG.
3999 return nullptr;
4000 }
4001
4002 // This instruction is not reachable, just remove it.
4004 return eraseInstFromFunction(Call);
4005 }
4006
4007 if (IntrinsicInst *II = findInitTrampoline(Callee))
4008 return transformCallThroughTrampoline(Call, *II);
4009
4010 if (isa<InlineAsm>(Callee) && !Call.doesNotThrow()) {
4011 InlineAsm *IA = cast<InlineAsm>(Callee);
4012 if (!IA->canThrow()) {
4013 // Normal inline asm calls cannot throw - mark them
4014 // 'nounwind'.
4015 Call.setDoesNotThrow();
4016 Changed = true;
4017 }
4018 }
4019
4020 // Try to optimize the call if possible, we require DataLayout for most of
4021 // this. None of these calls are seen as possibly dead so go ahead and
4022 // delete the instruction now.
4023 if (CallInst *CI = dyn_cast<CallInst>(&Call)) {
4024 Instruction *I = tryOptimizeCall(CI);
4025 // If we changed something return the result, etc. Otherwise let
4026 // the fallthrough check.
4027 if (I) return eraseInstFromFunction(*I);
4028 }
4029
4030 if (!Call.use_empty() && !Call.isMustTailCall())
4031 if (Value *ReturnedArg = Call.getReturnedArgOperand()) {
4032 Type *CallTy = Call.getType();
4033 Type *RetArgTy = ReturnedArg->getType();
4034 if (RetArgTy->canLosslesslyBitCastTo(CallTy))
4035 return replaceInstUsesWith(
4036 Call, Builder.CreateBitOrPointerCast(ReturnedArg, CallTy));
4037 }
4038
4039 // Drop unnecessary kcfi operand bundles from calls that were converted
4040 // into direct calls.
4041 auto Bundle = Call.getOperandBundle(LLVMContext::OB_kcfi);
4042 if (Bundle && !Call.isIndirectCall()) {
4043 DEBUG_WITH_TYPE(DEBUG_TYPE "-kcfi", {
4044 if (CalleeF) {
4045 ConstantInt *FunctionType = nullptr;
4046 ConstantInt *ExpectedType = cast<ConstantInt>(Bundle->Inputs[0]);
4047
4048 if (MDNode *MD = CalleeF->getMetadata(LLVMContext::MD_kcfi_type))
4049 FunctionType = mdconst::extract<ConstantInt>(MD->getOperand(0));
4050
4051 if (FunctionType &&
4052 FunctionType->getZExtValue() != ExpectedType->getZExtValue())
4053 dbgs() << Call.getModule()->getName()
4054 << ": warning: kcfi: " << Call.getCaller()->getName()
4055 << ": call to " << CalleeF->getName()
4056 << " using a mismatching function pointer type\n";
4057 }
4058 });
4059
4061 }
4062
4063 if (isRemovableAlloc(&Call, &TLI))
4064 return visitAllocSite(Call);
4065
4066 // Handle intrinsics which can be used in both call and invoke context.
4067 switch (Call.getIntrinsicID()) {
4068 case Intrinsic::experimental_gc_statepoint: {
4069 GCStatepointInst &GCSP = *cast<GCStatepointInst>(&Call);
4070 SmallPtrSet<Value *, 32> LiveGcValues;
4071 for (const GCRelocateInst *Reloc : GCSP.getGCRelocates()) {
4072 GCRelocateInst &GCR = *const_cast<GCRelocateInst *>(Reloc);
4073
4074 // Remove the relocation if unused.
4075 if (GCR.use_empty()) {
4077 continue;
4078 }
4079
4080 Value *DerivedPtr = GCR.getDerivedPtr();
4081 Value *BasePtr = GCR.getBasePtr();
4082
4083 // Undef is undef, even after relocation.
4084 if (isa<UndefValue>(DerivedPtr) || isa<UndefValue>(BasePtr)) {
4087 continue;
4088 }
4089
4090 if (auto *PT = dyn_cast<PointerType>(GCR.getType())) {
4091 // The relocation of null will be null for most any collector.
4092 // TODO: provide a hook for this in GCStrategy. There might be some
4093 // weird collector this property does not hold for.
4094 if (isa<ConstantPointerNull>(DerivedPtr)) {
4095 // Use null-pointer of gc_relocate's type to replace it.
4098 continue;
4099 }
4100
4101 // isKnownNonNull -> nonnull attribute
4102 if (!GCR.hasRetAttr(Attribute::NonNull) &&
4103 isKnownNonZero(DerivedPtr,
4104 getSimplifyQuery().getWithInstruction(&Call))) {
4105 GCR.addRetAttr(Attribute::NonNull);
4106 // We discovered new fact, re-check users.
4108 }
4109 }
4110
4111 // If we have two copies of the same pointer in the statepoint argument
4112 // list, canonicalize to one. This may let us common gc.relocates.
4113 if (GCR.getBasePtr() == GCR.getDerivedPtr() &&
4114 GCR.getBasePtrIndex() != GCR.getDerivedPtrIndex()) {
4115 auto *OpIntTy = GCR.getOperand(2)->getType();
4116 GCR.setOperand(2, ConstantInt::get(OpIntTy, GCR.getBasePtrIndex()));
4117 }
4118
4119 // TODO: bitcast(relocate(p)) -> relocate(bitcast(p))
4120 // Canonicalize on the type from the uses to the defs
4121
4122 // TODO: relocate((gep p, C, C2, ...)) -> gep(relocate(p), C, C2, ...)
4123 LiveGcValues.insert(BasePtr);
4124 LiveGcValues.insert(DerivedPtr);
4125 }
4126 std::optional<OperandBundleUse> Bundle =
4128 unsigned NumOfGCLives = LiveGcValues.size();
4129 if (!Bundle || NumOfGCLives == Bundle->Inputs.size())
4130 break;
4131 // We can reduce the size of gc live bundle.
4133 std::vector<Value *> NewLiveGc;
4134 for (Value *V : Bundle->Inputs) {
4135 if (Val2Idx.count(V))
4136 continue;
4137 if (LiveGcValues.count(V)) {
4138 Val2Idx[V] = NewLiveGc.size();
4139 NewLiveGc.push_back(V);
4140 } else
4141 Val2Idx[V] = NumOfGCLives;
4142 }
4143 // Update all gc.relocates
4144 for (const GCRelocateInst *Reloc : GCSP.getGCRelocates()) {
4145 GCRelocateInst &GCR = *const_cast<GCRelocateInst *>(Reloc);
4146 Value *BasePtr = GCR.getBasePtr();
4147 assert(Val2Idx.count(BasePtr) && Val2Idx[BasePtr] != NumOfGCLives &&
4148 "Missed live gc for base pointer");
4149 auto *OpIntTy1 = GCR.getOperand(1)->getType();
4150 GCR.setOperand(1, ConstantInt::get(OpIntTy1, Val2Idx[BasePtr]));
4151 Value *DerivedPtr = GCR.getDerivedPtr();
4152 assert(Val2Idx.count(DerivedPtr) && Val2Idx[DerivedPtr] != NumOfGCLives &&
4153 "Missed live gc for derived pointer");
4154 auto *OpIntTy2 = GCR.getOperand(2)->getType();
4155 GCR.setOperand(2, ConstantInt::get(OpIntTy2, Val2Idx[DerivedPtr]));
4156 }
4157 // Create new statepoint instruction.
4158 OperandBundleDef NewBundle("gc-live", NewLiveGc);
4159 return CallBase::Create(&Call, NewBundle);
4160 }
4161 default: { break; }
4162 }
4163
4164 return Changed ? &Call : nullptr;
4165}
4166
4167/// If the callee is a constexpr cast of a function, attempt to move the cast to
4168/// the arguments of the call/invoke.
4169/// CallBrInst is not supported.
4170bool InstCombinerImpl::transformConstExprCastCall(CallBase &Call) {
4171 auto *Callee =
4172 dyn_cast<Function>(Call.getCalledOperand()->stripPointerCasts());
4173 if (!Callee)
4174 return false;
4175
4176 assert(!isa<CallBrInst>(Call) &&
4177 "CallBr's don't have a single point after a def to insert at");
4178
4179 // Don't perform the transform for declarations, which may not be fully
4180 // accurate. For example, void @foo() is commonly used as a placeholder for
4181 // unknown prototypes.
4182 if (Callee->isDeclaration())
4183 return false;
4184
4185 // If this is a call to a thunk function, don't remove the cast. Thunks are
4186 // used to transparently forward all incoming parameters and outgoing return
4187 // values, so it's important to leave the cast in place.
4188 if (Callee->hasFnAttribute("thunk"))
4189 return false;
4190
4191 // If this is a call to a naked function, the assembly might be
4192 // using an argument, or otherwise rely on the frame layout,
4193 // the function prototype will mismatch.
4194 if (Callee->hasFnAttribute(Attribute::Naked))
4195 return false;
4196
4197 // If this is a musttail call, the callee's prototype must match the caller's
4198 // prototype with the exception of pointee types. The code below doesn't
4199 // implement that, so we can't do this transform.
4200 // TODO: Do the transform if it only requires adding pointer casts.
4201 if (Call.isMustTailCall())
4202 return false;
4203
4205 const AttributeList &CallerPAL = Call.getAttributes();
4206
4207 // Okay, this is a cast from a function to a different type. Unless doing so
4208 // would cause a type conversion of one of our arguments, change this call to
4209 // be a direct call with arguments casted to the appropriate types.
4210 FunctionType *FT = Callee->getFunctionType();
4211 Type *OldRetTy = Caller->getType();
4212 Type *NewRetTy = FT->getReturnType();
4213
4214 // Check to see if we are changing the return type...
4215 if (OldRetTy != NewRetTy) {
4216
4217 if (NewRetTy->isStructTy())
4218 return false; // TODO: Handle multiple return values.
4219
4220 if (!CastInst::isBitOrNoopPointerCastable(NewRetTy, OldRetTy, DL)) {
4221 if (!Caller->use_empty())
4222 return false; // Cannot transform this return value.
4223 }
4224
4225 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
4226 AttrBuilder RAttrs(FT->getContext(), CallerPAL.getRetAttrs());
4227 if (RAttrs.overlaps(AttributeFuncs::typeIncompatible(
4228 NewRetTy, CallerPAL.getRetAttrs())))
4229 return false; // Attribute not compatible with transformed value.
4230 }
4231
4232 // If the callbase is an invoke instruction, and the return value is
4233 // used by a PHI node in a successor, we cannot change the return type of
4234 // the call because there is no place to put the cast instruction (without
4235 // breaking the critical edge). Bail out in this case.
4236 if (!Caller->use_empty()) {
4237 BasicBlock *PhisNotSupportedBlock = nullptr;
4238 if (auto *II = dyn_cast<InvokeInst>(Caller))
4239 PhisNotSupportedBlock = II->getNormalDest();
4240 if (PhisNotSupportedBlock)
4241 for (User *U : Caller->users())
4242 if (PHINode *PN = dyn_cast<PHINode>(U))
4243 if (PN->getParent() == PhisNotSupportedBlock)
4244 return false;
4245 }
4246 }
4247
4248 unsigned NumActualArgs = Call.arg_size();
4249 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
4250
4251 // Prevent us turning:
4252 // declare void @takes_i32_inalloca(i32* inalloca)
4253 // call void bitcast (void (i32*)* @takes_i32_inalloca to void (i32)*)(i32 0)
4254 //
4255 // into:
4256 // call void @takes_i32_inalloca(i32* null)
4257 //
4258 // Similarly, avoid folding away bitcasts of byval calls.
4259 if (Callee->getAttributes().hasAttrSomewhere(Attribute::InAlloca) ||
4260 Callee->getAttributes().hasAttrSomewhere(Attribute::Preallocated))
4261 return false;
4262
4263 auto AI = Call.arg_begin();
4264 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
4265 Type *ParamTy = FT->getParamType(i);
4266 Type *ActTy = (*AI)->getType();
4267
4268 if (!CastInst::isBitOrNoopPointerCastable(ActTy, ParamTy, DL))
4269 return false; // Cannot transform this parameter value.
4270
4271 // Check if there are any incompatible attributes we cannot drop safely.
4272 if (AttrBuilder(FT->getContext(), CallerPAL.getParamAttrs(i))
4274 ParamTy, CallerPAL.getParamAttrs(i),
4276 return false; // Attribute not compatible with transformed value.
4277
4278 if (Call.isInAllocaArgument(i) ||
4279 CallerPAL.hasParamAttr(i, Attribute::Preallocated))
4280 return false; // Cannot transform to and from inalloca/preallocated.
4281
4282 if (CallerPAL.hasParamAttr(i, Attribute::SwiftError))
4283 return false;
4284
4285 if (CallerPAL.hasParamAttr(i, Attribute::ByVal) !=
4286 Callee->getAttributes().hasParamAttr(i, Attribute::ByVal))
4287 return false; // Cannot transform to or from byval.
4288 }
4289
4290 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
4291 !CallerPAL.isEmpty()) {
4292 // In this case we have more arguments than the new function type, but we
4293 // won't be dropping them. Check that these extra arguments have attributes
4294 // that are compatible with being a vararg call argument.
4295 unsigned SRetIdx;
4296 if (CallerPAL.hasAttrSomewhere(Attribute::StructRet, &SRetIdx) &&
4297 SRetIdx - AttributeList::FirstArgIndex >= FT->getNumParams())
4298 return false;
4299 }
4300
4301 // Okay, we decided that this is a safe thing to do: go ahead and start
4302 // inserting cast instructions as necessary.
4305 Args.reserve(NumActualArgs);
4306 ArgAttrs.reserve(NumActualArgs);
4307
4308 // Get any return attributes.
4309 AttrBuilder RAttrs(FT->getContext(), CallerPAL.getRetAttrs());
4310
4311 // If the return value is not being used, the type may not be compatible
4312 // with the existing attributes. Wipe out any problematic attributes.
4313 RAttrs.remove(
4314 AttributeFuncs::typeIncompatible(NewRetTy, CallerPAL.getRetAttrs()));
4315
4316 LLVMContext &Ctx = Call.getContext();
4317 AI = Call.arg_begin();
4318 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
4319 Type *ParamTy = FT->getParamType(i);
4320
4321 Value *NewArg = *AI;
4322 if ((*AI)->getType() != ParamTy)
4323 NewArg = Builder.CreateBitOrPointerCast(*AI, ParamTy);
4324 Args.push_back(NewArg);
4325
4326 // Add any parameter attributes except the ones incompatible with the new
4327 // type. Note that we made sure all incompatible ones are safe to drop.
4329 ParamTy, CallerPAL.getParamAttrs(i), AttributeFuncs::ASK_SAFE_TO_DROP);
4330 ArgAttrs.push_back(
4331 CallerPAL.getParamAttrs(i).removeAttributes(Ctx, IncompatibleAttrs));
4332 }
4333
4334 // If the function takes more arguments than the call was taking, add them
4335 // now.
4336 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i) {
4337 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
4338 ArgAttrs.push_back(AttributeSet());
4339 }
4340
4341 // If we are removing arguments to the function, emit an obnoxious warning.
4342 if (FT->getNumParams() < NumActualArgs) {
4343 // TODO: if (!FT->isVarArg()) this call may be unreachable. PR14722
4344 if (FT->isVarArg()) {
4345 // Add all of the arguments in their promoted form to the arg list.
4346 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
4347 Type *PTy = getPromotedType((*AI)->getType());
4348 Value *NewArg = *AI;
4349 if (PTy != (*AI)->getType()) {
4350 // Must promote to pass through va_arg area!
4351 Instruction::CastOps opcode =
4352 CastInst::getCastOpcode(*AI, false, PTy, false);
4353 NewArg = Builder.CreateCast(opcode, *AI, PTy);
4354 }
4355 Args.push_back(NewArg);
4356
4357 // Add any parameter attributes.
4358 ArgAttrs.push_back(CallerPAL.getParamAttrs(i));
4359 }
4360 }
4361 }
4362
4363 AttributeSet FnAttrs = CallerPAL.getFnAttrs();
4364
4365 if (NewRetTy->isVoidTy())
4366 Caller->setName(""); // Void type should not have a name.
4367
4368 assert((ArgAttrs.size() == FT->getNumParams() || FT->isVarArg()) &&
4369 "missing argument attributes");
4370 AttributeList NewCallerPAL = AttributeList::get(
4371 Ctx, FnAttrs, AttributeSet::get(Ctx, RAttrs), ArgAttrs);
4372
4374 Call.getOperandBundlesAsDefs(OpBundles);
4375
4376 CallBase *NewCall;
4377 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
4378 NewCall = Builder.CreateInvoke(Callee, II->getNormalDest(),
4379 II->getUnwindDest(), Args, OpBundles);
4380 } else {
4381 NewCall = Builder.CreateCall(Callee, Args, OpBundles);
4382 cast<CallInst>(NewCall)->setTailCallKind(
4383 cast<CallInst>(Caller)->getTailCallKind());
4384 }
4385 NewCall->takeName(Caller);
4386 NewCall->setCallingConv(Call.getCallingConv());
4387 NewCall->setAttributes(NewCallerPAL);
4388
4389 // Preserve prof metadata if any.
4390 NewCall->copyMetadata(*Caller, {LLVMContext::MD_prof});
4391
4392 // Insert a cast of the return type as necessary.
4393 Instruction *NC = NewCall;
4394 Value *NV = NC;
4395 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
4396 assert(!NV->getType()->isVoidTy());
4398 NC->setDebugLoc(Caller->getDebugLoc());
4399
4400 auto OptInsertPt = NewCall->getInsertionPointAfterDef();
4401 assert(OptInsertPt && "No place to insert cast");
4402 InsertNewInstBefore(NC, *OptInsertPt);
4404 }
4405
4406 if (!Caller->use_empty())
4407 replaceInstUsesWith(*Caller, NV);
4408 else if (Caller->hasValueHandle()) {
4409 if (OldRetTy == NV->getType())
4411 else
4412 // We cannot call ValueIsRAUWd with a different type, and the
4413 // actual tracked value will disappear.
4415 }
4416
4417 eraseInstFromFunction(*Caller);
4418 return true;
4419}
4420
4421/// Turn a call to a function created by init_trampoline / adjust_trampoline
4422/// intrinsic pair into a direct call to the underlying function.
4424InstCombinerImpl::transformCallThroughTrampoline(CallBase &Call,
4425 IntrinsicInst &Tramp) {
4426 FunctionType *FTy = Call.getFunctionType();
4427 AttributeList Attrs = Call.getAttributes();
4428
4429 // If the call already has the 'nest' attribute somewhere then give up -
4430 // otherwise 'nest' would occur twice after splicing in the chain.
4431 if (Attrs.hasAttrSomewhere(Attribute::Nest))
4432 return nullptr;
4433
4434 Function *NestF = cast<Function>(Tramp.getArgOperand(1)->stripPointerCasts());
4435 FunctionType *NestFTy = NestF->getFunctionType();
4436
4437 AttributeList NestAttrs = NestF->getAttributes();
4438 if (!NestAttrs.isEmpty()) {
4439 unsigned NestArgNo = 0;
4440 Type *NestTy = nullptr;
4441 AttributeSet NestAttr;
4442
4443 // Look for a parameter marked with the 'nest' attribute.
4444 for (FunctionType::param_iterator I = NestFTy->param_begin(),
4445 E = NestFTy->param_end();
4446 I != E; ++NestArgNo, ++I) {
4447 AttributeSet AS = NestAttrs.getParamAttrs(NestArgNo);
4448 if (AS.hasAttribute(Attribute::Nest)) {
4449 // Record the parameter type and any other attributes.
4450 NestTy = *I;
4451 NestAttr = AS;
4452 break;
4453 }
4454 }
4455
4456 if (NestTy) {
4457 std::vector<Value*> NewArgs;
4458 std::vector<AttributeSet> NewArgAttrs;
4459 NewArgs.reserve(Call.arg_size() + 1);
4460 NewArgAttrs.reserve(Call.arg_size());
4461
4462 // Insert the nest argument into the call argument list, which may
4463 // mean appending it. Likewise for attributes.
4464
4465 {
4466 unsigned ArgNo = 0;
4467 auto I = Call.arg_begin(), E = Call.arg_end();
4468 do {
4469 if (ArgNo == NestArgNo) {
4470 // Add the chain argument and attributes.
4471 Value *NestVal = Tramp.getArgOperand(2);
4472 if (NestVal->getType() != NestTy)
4473 NestVal = Builder.CreateBitCast(NestVal, NestTy, "nest");
4474 NewArgs.push_back(NestVal);
4475 NewArgAttrs.push_back(NestAttr);
4476 }
4477
4478 if (I == E)
4479 break;
4480
4481 // Add the original argument and attributes.
4482 NewArgs.push_back(*I);
4483 NewArgAttrs.push_back(Attrs.getParamAttrs(ArgNo));
4484
4485 ++ArgNo;
4486 ++I;
4487 } while (true);
4488 }
4489
4490 // The trampoline may have been bitcast to a bogus type (FTy).
4491 // Handle this by synthesizing a new function type, equal to FTy
4492 // with the chain parameter inserted.
4493
4494 std::vector<Type*> NewTypes;
4495 NewTypes.reserve(FTy->getNumParams()+1);
4496
4497 // Insert the chain's type into the list of parameter types, which may
4498 // mean appending it.
4499 {
4500 unsigned ArgNo = 0;
4501 FunctionType::param_iterator I = FTy->param_begin(),
4502 E = FTy->param_end();
4503
4504 do {
4505 if (ArgNo == NestArgNo)
4506 // Add the chain's type.
4507 NewTypes.push_back(NestTy);
4508
4509 if (I == E)
4510 break;
4511
4512 // Add the original type.
4513 NewTypes.push_back(*I);
4514
4515 ++ArgNo;
4516 ++I;
4517 } while (true);
4518 }
4519
4520 // Replace the trampoline call with a direct call. Let the generic
4521 // code sort out any function type mismatches.
4522 FunctionType *NewFTy =
4523 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
4524 AttributeList NewPAL =
4525 AttributeList::get(FTy->getContext(), Attrs.getFnAttrs(),
4526 Attrs.getRetAttrs(), NewArgAttrs);
4527
4529 Call.getOperandBundlesAsDefs(OpBundles);
4530
4531 Instruction *NewCaller;
4532 if (InvokeInst *II = dyn_cast<InvokeInst>(&Call)) {
4533 NewCaller = InvokeInst::Create(NewFTy, NestF, II->getNormalDest(),
4534 II->getUnwindDest(), NewArgs, OpBundles);
4535 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
4536 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
4537 } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(&Call)) {
4538 NewCaller =
4539 CallBrInst::Create(NewFTy, NestF, CBI->getDefaultDest(),
4540 CBI->getIndirectDests(), NewArgs, OpBundles);
4541 cast<CallBrInst>(NewCaller)->setCallingConv(CBI->getCallingConv());
4542 cast<CallBrInst>(NewCaller)->setAttributes(NewPAL);
4543 } else {
4544 NewCaller = CallInst::Create(NewFTy, NestF, NewArgs, OpBundles);
4545 cast<CallInst>(NewCaller)->setTailCallKind(
4546 cast<CallInst>(Call).getTailCallKind());
4547 cast<CallInst>(NewCaller)->setCallingConv(
4548 cast<CallInst>(Call).getCallingConv());
4549 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
4550 }
4551 NewCaller->setDebugLoc(Call.getDebugLoc());
4552
4553 return NewCaller;
4554 }
4555 }
4556
4557 // Replace the trampoline call with a direct call. Since there is no 'nest'
4558 // parameter, there is no need to adjust the argument list. Let the generic
4559 // code sort out any function type mismatches.
4560 Call.setCalledFunction(FTy, NestF);
4561 return &Call;
4562}
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:1440
void clearSign()
Definition: APFloat.h:1295
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.
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:1021
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:829
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:624
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:949
static AttributeSet get(LLVMContext &C, const AttrBuilder &B)
Definition: Attributes.cpp:897
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:1120
void setCallingConv(CallingConv::ID CC)
Definition: InstrTypes.h:1411
void setDoesNotThrow()
Definition: InstrTypes.h:1924
MaybeAlign getRetAlign() const
Extract the alignment of the return value.
Definition: InstrTypes.h:1737
std::optional< OperandBundleUse > getOperandBundle(StringRef Name) const
Return an operand bundle by name, if present.
Definition: InstrTypes.h:2051
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
Definition: InstrTypes.h:1349
bool hasRetAttr(Attribute::AttrKind Kind) const
Determine whether the return value has the given attribute.
Definition: InstrTypes.h:1581
Value * getCalledOperand() const
Definition: InstrTypes.h:1342
void setAttributes(AttributeList A)
Set the attributes for this call.
Definition: InstrTypes.h:1428
bool doesNotThrow() const
Determine if the call cannot unwind.
Definition: InstrTypes.h:1923
void addRetAttr(Attribute::AttrKind Kind)
Adds the attribute to the return value.
Definition: InstrTypes.h:1492
Value * getArgOperand(unsigned i) const
Definition: InstrTypes.h:1294
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:1285
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:1292
void setCalledFunction(Function *Fn)
Sets the function called, including updating the function type.
Definition: InstrTypes.h:1388
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
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
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:91
Value * CreateFCmpONE(Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:2338
CallInst * CreateUnaryIntrinsic(Intrinsic::ID ID, Value *V, Instruction *FMFSource=nullptr, const Twine &Name="")
Create a call to intrinsic ID with 1 operand which is mangled on its type.
Definition: IRBuilder.cpp:871
Value * CreateLaunderInvariantGroup(Value *Ptr)
Create a launder.invariant.group intrinsic call.
Definition: IRBuilder.cpp:1075
Value * CreateBinaryIntrinsic(Intrinsic::ID ID, Value *LHS, Value *RHS, Instruction *FMFSource=nullptr, const Twine &Name="")
Create a call to intrinsic ID with 2 operands which is mangled on the first type.
Definition: IRBuilder.cpp:879
Value * CreateFCmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:2393
IntegerType * getInt1Ty()
Fetch the type representing a single bit.
Definition: IRBuilder.h:508
Value * CreateExtractElement(Value *Vec, Value *Idx, const Twine &Name="")
Definition: IRBuilder.h:2491
IntegerType * getIntNTy(unsigned N)
Fetch the type representing an N-bit integer.
Definition: IRBuilder.h:536
LoadInst * CreateAlignedLoad(Type *Ty, Value *Ptr, MaybeAlign Align, const char *Name)
Definition: IRBuilder.h:1830
Value * CreateFCmpORD(Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:2343
Value * CreateZExtOrTrunc(Value *V, Type *DestTy, const Twine &Name="")
Create a ZExt or Trunc from the integer value V to DestTy.
Definition: IRBuilder.h:2066
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:1152
ConstantInt * getTrue()
Get the constant value for i1 true.
Definition: IRBuilder.h:463
CallInst * CreateIntrinsic(Intrinsic::ID ID, ArrayRef< Type * > Types, ArrayRef< Value * > Args, Instruction *FMFSource=nullptr, const Twine &Name="")
Create a call to intrinsic ID with Args, mangled using Types.
Definition: IRBuilder.cpp:890
Value * CreateFNegFMF(Value *V, Instruction *FMFSource, const Twine &Name="")
Copy fast-math-flags from an instruction rather than using the builder's default FMF.
Definition: IRBuilder.h:1763
Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
Definition: IRBuilder.cpp:1048
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:1182
Value * CreateFCmpUNE(Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:2378
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:1460
IntegerType * getInt32Ty()
Fetch the type representing a 32-bit integer.
Definition: IRBuilder.h:523
Value * CreateNSWMul(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1393
Value * CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:2277
Value * CreateNeg(Value *V, const Twine &Name="", bool HasNSW=false)
Definition: IRBuilder.h:1744
CallInst * CreateOrReduce(Value *Src)
Create a vector int OR reduction intrinsic of the source vector.
Definition: IRBuilder.cpp:424
Value * CreateLdexp(Value *Src, Value *Exp, Instruction *FMFSource=nullptr, const Twine &Name="")
Create call to the ldexp intrinsic.
Definition: IRBuilder.h:1037
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
Definition: IRBuilder.h:483
Value * CreateBitOrPointerCast(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2236
Value * CreateNot(Value *V, const Twine &Name="")
Definition: IRBuilder.h:1772
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:2273
Value * CreateFCmpUEQ(Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:2353
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1367
Value * CreateBitCast(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2155
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:1813
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="", bool IsNonNeg=false)
Definition: IRBuilder.h:2048
Value * CreateShuffleVector(Value *V1, Value *V2, Value *Mask, const Twine &Name="")
Definition: IRBuilder.h:2525
Value * CreateFCmpOEQ(Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:2313
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1498
Value * CreateCast(Instruction::CastOps Op, Value *V, Type *DestTy, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:2189
StoreInst * CreateStore(Value *Val, Value *Ptr, bool isVolatile=false)
Definition: IRBuilder.h:1826
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1350
Value * CreatePtrToInt(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2145
ConstantInt * getFalse()
Get the constant value for i1 false.
Definition: IRBuilder.h:468
Value * CreateIsNotNull(Value *Arg, const Twine &Name="")
Return a boolean value testing if Arg != 0.
Definition: IRBuilder.h:2580
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value * > Args={}, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:2444
Value * CreateTrunc(Value *V, Type *DestTy, const Twine &Name="", bool IsNUW=false, bool IsNSW=false)
Definition: IRBuilder.h:2034
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1520
PointerType * getPtrTy(unsigned AddrSpace=0)
Fetch the type representing a pointer.
Definition: IRBuilder.h:566
Value * CreateBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:1689
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:2227
Value * CreateFCmpUNO(Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:2348
Value * CreateIsNull(Value *Arg, const Twine &Name="")
Return a boolean value testing if Arg == 0.
Definition: IRBuilder.h:2575
Value * CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:2383
Value * CreateFNeg(Value *V, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:1753
Value * CreateAddrSpaceCast(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2160
Value * CreateMul(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1384
Value * CreateStripInvariantGroup(Value *Ptr)
Create a strip.invariant.group intrinsic call.
Definition: IRBuilder.cpp:1091
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,...
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:234
DominatorTree & getDominatorTree() const
Definition: InstCombiner.h:342
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:449
Instruction * InsertNewInstBefore(Instruction *New, BasicBlock::iterator Old)
Inserts an instruction New before instruction Old.
Definition: InstCombiner.h:374
AAResults * AA
Definition: InstCombiner.h:70
Instruction * replaceInstUsesWith(Instruction &I, Value *V)
A combiner-aware RAUW-like routine.
Definition: InstCombiner.h:394
void replaceUse(Use &U, Value *NewValue)
Replace use and add the previously used value to the worklist.
Definition: InstCombiner.h:426
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:418
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:439
BuilderTy & Builder
Definition: InstCombiner.h:61
AssumptionCache & getAssumptionCache() const
Definition: InstCombiner.h:340
bool MaskedValueIsZero(const Value *V, const APInt &Mask, unsigned Depth=0, const Instruction *CxtI=nullptr) const
Definition: InstCombiner.h:456
OptimizationRemarkEmitter & ORE
Definition: InstCombiner.h:78
Value * getFreelyInverted(Value *V, bool WillInvertAllUses, BuilderTy *Builder, bool &DoesConsume)
Definition: InstCombiner.h:215
const SimplifyQuery & getSimplifyQuery() const
Definition: InstCombiner.h:344
unsigned ComputeMaxSignificantBits(const Value *Op, unsigned Depth=0, const Instruction *CxtI=nullptr) const
Definition: InstCombiner.h:466
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:66
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:70
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:468
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:1543
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:1073
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:1599
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:1558
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:1544
@ 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:235
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:1572
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:1015
StringRef getTagName() const
Return the tag of this operand bundle as a string.
Definition: InstrTypes.h:1034
ArrayRef< Use > Inputs
Definition: InstrTypes.h:1016
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