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