LLVM 24.0.0git
InstructionCombining.cpp
Go to the documentation of this file.
1//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
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// InstructionCombining - Combine instructions to form fewer, simple
10// instructions. This pass does not modify the CFG. This pass is where
11// algebraic simplification happens.
12//
13// This pass combines things like:
14// %Y = add i32 %X, 1
15// %Z = add i32 %Y, 1
16// into:
17// %Z = add i32 %X, 2
18//
19// This is a simple worklist driven algorithm.
20//
21// This pass guarantees that the following canonicalizations are performed on
22// the program:
23// 1. If a binary operator has a constant operand, it is moved to the RHS
24// 2. Bitwise operators with constant operands are always grouped so that
25// shifts are performed first, then or's, then and's, then xor's.
26// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
27// 4. All cmp instructions on boolean values are replaced with logical ops
28// 5. add X, X is represented as (X*2) => (X << 1)
29// 6. Multiplies with a power-of-two constant argument are transformed into
30// shifts.
31// ... etc.
32//
33//===----------------------------------------------------------------------===//
34
35#include "InstCombineInternal.h"
36#include "llvm/ADT/APFloat.h"
37#include "llvm/ADT/APInt.h"
38#include "llvm/ADT/ArrayRef.h"
39#include "llvm/ADT/DenseMap.h"
43#include "llvm/ADT/Statistic.h"
48#include "llvm/Analysis/CFG.h"
63#include "llvm/IR/BasicBlock.h"
64#include "llvm/IR/CFG.h"
65#include "llvm/IR/Constant.h"
66#include "llvm/IR/Constants.h"
67#include "llvm/IR/DIBuilder.h"
68#include "llvm/IR/DataLayout.h"
69#include "llvm/IR/DebugInfo.h"
71#include "llvm/IR/Dominators.h"
73#include "llvm/IR/Function.h"
75#include "llvm/IR/IRBuilder.h"
76#include "llvm/IR/InstrTypes.h"
77#include "llvm/IR/Instruction.h"
80#include "llvm/IR/Intrinsics.h"
81#include "llvm/IR/LLVMContext.h"
82#include "llvm/IR/Metadata.h"
83#include "llvm/IR/Operator.h"
84#include "llvm/IR/PassManager.h"
87#include "llvm/IR/Type.h"
88#include "llvm/IR/Use.h"
89#include "llvm/IR/User.h"
90#include "llvm/IR/Value.h"
91#include "llvm/IR/ValueHandle.h"
95#include "llvm/Support/Debug.h"
104#include <algorithm>
105#include <cassert>
106#include <cstdint>
107#include <memory>
108#include <optional>
109#include <string>
110#include <utility>
111
112#define DEBUG_TYPE "instcombine"
114#include <optional>
115
116using namespace llvm;
117using namespace llvm::PatternMatch;
118
119STATISTIC(NumWorklistIterations,
120 "Number of instruction combining iterations performed");
121STATISTIC(NumOneIteration, "Number of functions with one iteration");
122STATISTIC(NumTwoIterations, "Number of functions with two iterations");
123STATISTIC(NumThreeIterations, "Number of functions with three iterations");
124STATISTIC(NumFourOrMoreIterations,
125 "Number of functions with four or more iterations");
126
127STATISTIC(NumCombined , "Number of insts combined");
128STATISTIC(NumConstProp, "Number of constant folds");
129STATISTIC(NumDeadInst , "Number of dead inst eliminated");
130STATISTIC(NumSunkInst , "Number of instructions sunk");
131STATISTIC(NumExpand, "Number of expansions");
132STATISTIC(NumFactor , "Number of factorizations");
133STATISTIC(NumReassoc , "Number of reassociations");
134DEBUG_COUNTER(VisitCounter, "instcombine-visit",
135 "Controls which instructions are visited");
136
137void InstCombiner::IRBuilderInstCombineInserter::InsertHelper(
138 Instruction *I, const Twine &Name, BasicBlock::iterator InsertPt) const {
140 IC.Worklist.add(I);
141 if (auto *Assume = dyn_cast<AssumeInst>(I))
142 IC.AC.registerAssumption(Assume);
143 if (IC.AnnotationMetadataSource)
144 I->copyMetadata(*IC.AnnotationMetadataSource, LLVMContext::MD_annotation);
145}
146
147std::optional<Instruction *>
149 // Handle target specific intrinsics
150 if (II.getCalledFunction()->isTargetIntrinsic()) {
151 return TTIForTargetIntrinsicsOnly.instCombineIntrinsic(*this, II);
152 }
153 return std::nullopt;
154}
155
157 IntrinsicInst &II, APInt DemandedMask, KnownBits &Known,
158 bool &KnownBitsComputed) {
159 // Handle target specific intrinsics
160 if (II.getCalledFunction()->isTargetIntrinsic()) {
161 return TTIForTargetIntrinsicsOnly.simplifyDemandedUseBitsIntrinsic(
162 *this, II, DemandedMask, Known, KnownBitsComputed);
163 }
164 return std::nullopt;
165}
166
168 IntrinsicInst &II, APInt DemandedElts, APInt &PoisonElts,
169 APInt &PoisonElts2, APInt &PoisonElts3,
170 std::function<void(Instruction *, unsigned, APInt, APInt &)>
171 SimplifyAndSetOp) {
172 // Handle target specific intrinsics
173 if (II.getCalledFunction()->isTargetIntrinsic()) {
174 return TTIForTargetIntrinsicsOnly.simplifyDemandedVectorEltsIntrinsic(
175 *this, II, DemandedElts, PoisonElts, PoisonElts2, PoisonElts3,
176 SimplifyAndSetOp);
177 }
178 return std::nullopt;
179}
180
181bool InstCombiner::isValidAddrSpaceCast(unsigned FromAS, unsigned ToAS) const {
182 // Approved exception for TTI use: This queries a legality property of the
183 // target, not an profitability heuristic. Ideally this should be part of
184 // DataLayout instead.
185 return TTIForTargetIntrinsicsOnly.isValidAddrSpaceCast(FromAS, ToAS);
186}
187
188Value *InstCombinerImpl::EmitGEPOffset(GEPOperator *GEP, bool RewriteGEP) {
189 if (!RewriteGEP)
190 return llvm::emitGEPOffset(&Builder, DL, GEP);
191
192 IRBuilderBase::InsertPointGuard Guard(Builder);
193 auto *Inst = dyn_cast<Instruction>(GEP);
194 if (Inst)
195 Builder.SetInsertPoint(Inst);
196
197 Value *Offset = EmitGEPOffset(GEP);
198 // Rewrite non-trivial GEPs to avoid duplicating the offset arithmetic.
199 if (Inst && !GEP->hasAllConstantIndices() &&
200 !GEP->getSourceElementType()->isIntegerTy(8)) {
202 *Inst, Builder.CreateGEP(Builder.getInt8Ty(), GEP->getPointerOperand(),
203 Offset, "", GEP->getNoWrapFlags()));
205 }
206 return Offset;
207}
208
209Value *InstCombinerImpl::EmitGEPOffsets(ArrayRef<GEPOperator *> GEPs,
210 GEPNoWrapFlags NW, Type *IdxTy,
211 bool RewriteGEPs) {
212 auto Add = [&](Value *Sum, Value *Offset) -> Value * {
213 if (Sum)
214 return Builder.CreateAdd(Sum, Offset, "", NW.hasNoUnsignedWrap(),
215 NW.isInBounds());
216 else
217 return Offset;
218 };
219
220 Value *Sum = nullptr;
221 Value *OneUseSum = nullptr;
222 Value *OneUseBase = nullptr;
223 GEPNoWrapFlags OneUseFlags = GEPNoWrapFlags::all();
224 for (GEPOperator *GEP : reverse(GEPs)) {
225 Value *Offset;
226 {
227 // Expand the offset at the point of the previous GEP to enable rewriting.
228 // However, use the original insertion point for calculating Sum.
229 IRBuilderBase::InsertPointGuard Guard(Builder);
230 auto *Inst = dyn_cast<Instruction>(GEP);
231 if (RewriteGEPs && Inst)
232 Builder.SetInsertPoint(Inst);
233
235 if (Offset->getType() != IdxTy)
236 Offset = Builder.CreateVectorSplat(
237 cast<VectorType>(IdxTy)->getElementCount(), Offset);
238 if (GEP->hasOneUse()) {
239 // Offsets of one-use GEPs will be merged into the next multi-use GEP.
240 OneUseSum = Add(OneUseSum, Offset);
241 OneUseFlags = OneUseFlags.intersectForOffsetAdd(GEP->getNoWrapFlags());
242 if (!OneUseBase)
243 OneUseBase = GEP->getPointerOperand();
244 continue;
245 }
246
247 if (OneUseSum)
248 Offset = Add(OneUseSum, Offset);
249
250 // Rewrite the GEP to reuse the computed offset. This also includes
251 // offsets from preceding one-use GEPs of matched type.
252 if (RewriteGEPs && Inst &&
253 Offset->getType()->isVectorTy() == GEP->getType()->isVectorTy() &&
254 !(GEP->getSourceElementType()->isIntegerTy(8) &&
255 GEP->getOperand(1) == Offset)) {
257 *Inst,
258 Builder.CreatePtrAdd(
259 OneUseBase ? OneUseBase : GEP->getPointerOperand(), Offset, "",
260 OneUseFlags.intersectForOffsetAdd(GEP->getNoWrapFlags())));
262 }
263 }
264
265 Sum = Add(Sum, Offset);
266 OneUseSum = OneUseBase = nullptr;
267 OneUseFlags = GEPNoWrapFlags::all();
268 }
269 if (OneUseSum)
270 Sum = Add(Sum, OneUseSum);
271 if (!Sum)
272 return Constant::getNullValue(IdxTy);
273 return Sum;
274}
275
276/// Legal integers and common types are considered desirable. This is used to
277/// avoid creating instructions with types that may not be supported well by the
278/// the backend.
279/// NOTE: This treats i8, i16 and i32 specially because they are common
280/// types in frontend languages.
281bool InstCombinerImpl::isDesirableIntType(unsigned BitWidth) const {
282 switch (BitWidth) {
283 case 8:
284 case 16:
285 case 32:
286 return true;
287 default:
288 return DL.isLegalInteger(BitWidth);
289 }
290}
291
292/// Return true if it is desirable to convert an integer computation from a
293/// given bit width to a new bit width.
294/// We don't want to convert from a legal or desirable type (like i8) to an
295/// illegal type or from a smaller to a larger illegal type. A width of '1'
296/// is always treated as a desirable type because i1 is a fundamental type in
297/// IR, and there are many specialized optimizations for i1 types.
298/// Common/desirable widths are equally treated as legal to convert to, in
299/// order to open up more combining opportunities.
300bool InstCombinerImpl::shouldChangeType(unsigned FromWidth,
301 unsigned ToWidth) const {
302 bool FromLegal = FromWidth == 1 || DL.isLegalInteger(FromWidth);
303 bool ToLegal = ToWidth == 1 || DL.isLegalInteger(ToWidth);
304
305 // Convert to desirable widths even if they are not legal types.
306 // Only shrink types, to prevent infinite loops.
307 if (ToWidth < FromWidth && isDesirableIntType(ToWidth))
308 return true;
309
310 // If this is a legal or desiable integer from type, and the result would be
311 // an illegal type, don't do the transformation.
312 if ((FromLegal || isDesirableIntType(FromWidth)) && !ToLegal)
313 return false;
314
315 // Otherwise, if both are illegal, do not increase the size of the result. We
316 // do allow things like i160 -> i64, but not i64 -> i160.
317 if (!FromLegal && !ToLegal && ToWidth > FromWidth)
318 return false;
319
320 return true;
321}
322
323/// Return true if it is desirable to convert a computation from 'From' to 'To'.
324/// We don't want to convert from a legal to an illegal type or from a smaller
325/// to a larger illegal type. i1 is always treated as a legal type because it is
326/// a fundamental type in IR, and there are many specialized optimizations for
327/// i1 types.
328bool InstCombinerImpl::shouldChangeType(Type *From, Type *To) const {
329 // TODO: This could be extended to allow vectors. Datalayout changes might be
330 // needed to properly support that.
331 if (!From->isIntegerTy() || !To->isIntegerTy())
332 return false;
333
334 unsigned FromWidth = From->getPrimitiveSizeInBits();
335 unsigned ToWidth = To->getPrimitiveSizeInBits();
336 return shouldChangeType(FromWidth, ToWidth);
337}
338
339// Return true, if No Signed Wrap should be maintained for I.
340// The No Signed Wrap flag can be kept if the operation "B (I.getOpcode) C",
341// where both B and C should be ConstantInts, results in a constant that does
342// not overflow. This function only handles the Add/Sub/Mul opcodes. For
343// all other opcodes, the function conservatively returns false.
346 if (!OBO || !OBO->hasNoSignedWrap())
347 return false;
348
349 const APInt *BVal, *CVal;
350 if (!match(B, m_APInt(BVal)) || !match(C, m_APInt(CVal)))
351 return false;
352
353 // We reason about Add/Sub/Mul Only.
354 bool Overflow = false;
355 switch (I.getOpcode()) {
356 case Instruction::Add:
357 (void)BVal->sadd_ov(*CVal, Overflow);
358 break;
359 case Instruction::Sub:
360 (void)BVal->ssub_ov(*CVal, Overflow);
361 break;
362 case Instruction::Mul:
363 (void)BVal->smul_ov(*CVal, Overflow);
364 break;
365 default:
366 // Conservatively return false for other opcodes.
367 return false;
368 }
369 return !Overflow;
370}
371
374 return OBO && OBO->hasNoUnsignedWrap();
375}
376
379 return OBO && OBO->hasNoSignedWrap();
380}
381
382/// Combine constant operands of associative operations either before or after a
383/// cast to eliminate one of the associative operations:
384/// (op (cast (op X, C2)), C1) --> (cast (op X, op (C1, C2)))
385/// (op (cast (op X, C2)), C1) --> (op (cast X), op (C1, C2))
387 InstCombinerImpl &IC) {
388 auto *Cast = dyn_cast<CastInst>(BinOp1->getOperand(0));
389 if (!Cast || !Cast->hasOneUse())
390 return false;
391
392 // TODO: Enhance logic for other casts and remove this check.
393 auto CastOpcode = Cast->getOpcode();
394 if (CastOpcode != Instruction::ZExt)
395 return false;
396
397 // TODO: Enhance logic for other BinOps and remove this check.
398 if (!BinOp1->isBitwiseLogicOp())
399 return false;
400
401 auto AssocOpcode = BinOp1->getOpcode();
402 auto *BinOp2 = dyn_cast<BinaryOperator>(Cast->getOperand(0));
403 if (!BinOp2 || !BinOp2->hasOneUse() || BinOp2->getOpcode() != AssocOpcode)
404 return false;
405
406 Constant *C1, *C2;
407 if (!match(BinOp1->getOperand(1), m_Constant(C1)) ||
408 !match(BinOp2->getOperand(1), m_Constant(C2)))
409 return false;
410
411 // TODO: This assumes a zext cast.
412 // Eg, if it was a trunc, we'd cast C1 to the source type because casting C2
413 // to the destination type might lose bits.
414
415 // Fold the constants together in the destination type:
416 // (op (cast (op X, C2)), C1) --> (op (cast X), FoldedC)
417 const DataLayout &DL = IC.getDataLayout();
418 Type *DestTy = C1->getType();
419 Constant *CastC2 = ConstantFoldCastOperand(CastOpcode, C2, DestTy, DL);
420 if (!CastC2)
421 return false;
422 Constant *FoldedC = ConstantFoldBinaryOpOperands(AssocOpcode, C1, CastC2, DL);
423 if (!FoldedC)
424 return false;
425
426 IC.replaceOperand(*Cast, 0, BinOp2->getOperand(0));
427 IC.replaceOperand(*BinOp1, 1, FoldedC);
429 Cast->dropPoisonGeneratingFlags();
430 return true;
431}
432
433// Simplifies IntToPtr/PtrToInt RoundTrip Cast.
434// inttoptr ( ptrtoint (x) ) --> x
435Value *InstCombinerImpl::simplifyIntToPtrRoundTripCast(Value *Val) {
436 auto *IntToPtr = dyn_cast<IntToPtrInst>(Val);
437 if (IntToPtr && DL.getTypeSizeInBits(IntToPtr->getDestTy()) ==
438 DL.getTypeSizeInBits(IntToPtr->getSrcTy())) {
439 auto *PtrToInt = dyn_cast<PtrToIntInst>(IntToPtr->getOperand(0));
440 Type *CastTy = IntToPtr->getDestTy();
441 if (PtrToInt &&
442 CastTy->getPointerAddressSpace() ==
443 PtrToInt->getSrcTy()->getPointerAddressSpace() &&
444 DL.getTypeSizeInBits(PtrToInt->getSrcTy()) ==
445 DL.getTypeSizeInBits(PtrToInt->getDestTy()))
446 return PtrToInt->getOperand(0);
447 }
448 return nullptr;
449}
450
451/// This performs a few simplifications for operators that are associative or
452/// commutative:
453///
454/// Commutative operators:
455///
456/// 1. Order operands such that they are listed from right (least complex) to
457/// left (most complex). This puts constants before unary operators before
458/// binary operators.
459///
460/// Associative operators:
461///
462/// 2. Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
463/// 3. Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
464///
465/// Associative and commutative operators:
466///
467/// 4. Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
468/// 5. Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
469/// 6. Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
470/// if C1 and C2 are constants.
472 Instruction::BinaryOps Opcode = I.getOpcode();
473 bool Changed = false;
474
475 do {
476 // Order operands such that they are listed from right (least complex) to
477 // left (most complex). This puts constants before unary operators before
478 // binary operators.
479 if (I.isCommutative() && getComplexity(I.getOperand(0)) <
480 getComplexity(I.getOperand(1)))
481 Changed = !I.swapOperands();
482
483 if (I.isCommutative()) {
484 if (auto Pair = matchSymmetricPair(I.getOperand(0), I.getOperand(1))) {
485 replaceOperand(I, 0, Pair->first);
486 replaceOperand(I, 1, Pair->second);
487 Changed = true;
488 }
489 }
490
491 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(I.getOperand(0));
492 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1));
493
494 if (I.isAssociative()) {
495 // Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
496 if (Op0 && Op0->getOpcode() == Opcode) {
497 Value *A = Op0->getOperand(0);
498 Value *B = Op0->getOperand(1);
499 Value *C = I.getOperand(1);
500
501 if (tryReassociateAndFoldSymmetricPair(I, *Op0, A, B, C)) {
502 I.swapOperands();
503 Changed = true;
504 ++NumReassoc;
505 continue;
506 }
507
508 // Does "B op C" simplify?
509 if (Value *V = simplifyBinOp(Opcode, B, C, SQ.getWithInstruction(&I))) {
510 // It simplifies to V. Form "A op V".
511 replaceOperand(I, 0, A);
512 replaceOperand(I, 1, V);
513 bool IsNUW = hasNoUnsignedWrap(I) && hasNoUnsignedWrap(*Op0);
514 bool IsNSW = maintainNoSignedWrap(I, B, C) && hasNoSignedWrap(*Op0);
515
516 // Conservatively clear all optional flags since they may not be
517 // preserved by the reassociation. Reset nsw/nuw based on the above
518 // analysis.
519 if (auto *PDI = dyn_cast<PossiblyDisjointInst>(&I))
520 PDI->setIsDisjoint(false);
521
522 // Note: this is only valid because SimplifyBinOp doesn't look at
523 // the operands to Op0.
525 I.setHasNoUnsignedWrap(IsNUW);
526 I.setHasNoSignedWrap(IsNSW);
527 }
528
529 Changed = true;
530 ++NumReassoc;
531 continue;
532 }
533 }
534
535 // Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
536 if (Op1 && Op1->getOpcode() == Opcode) {
537 Value *A = I.getOperand(0);
538 Value *B = Op1->getOperand(0);
539 Value *C = Op1->getOperand(1);
540
541 if (tryReassociateAndFoldSymmetricPair(I, *Op1, C, B, A)) {
542 I.swapOperands();
543 Changed = true;
544 ++NumReassoc;
545 continue;
546 }
547
548 // Does "A op B" simplify?
549 if (Value *V = simplifyBinOp(Opcode, A, B, SQ.getWithInstruction(&I))) {
550 // It simplifies to V. Form "V op C".
551 replaceOperand(I, 0, V);
552 replaceOperand(I, 1, C);
553 // Conservatively clear the optional flags, since they may not be
554 // preserved by the reassociation.
556 I.dropPoisonGeneratingFlags();
557 Changed = true;
558 ++NumReassoc;
559 continue;
560 }
561 }
562 }
563
564 if (I.isAssociative() && I.isCommutative()) {
565 if (simplifyAssocCastAssoc(&I, *this)) {
566 Changed = true;
567 ++NumReassoc;
568 continue;
569 }
570
571 // Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
572 if (Op0 && Op0->getOpcode() == Opcode) {
573 Value *A = Op0->getOperand(0);
574 Value *B = Op0->getOperand(1);
575 Value *C = I.getOperand(1);
576
577 if (tryReassociateAndFoldSymmetricPair(I, *Op0, B, A, C)) {
578 Changed = true;
579 ++NumReassoc;
580 continue;
581 }
582
583 // Does "C op A" simplify?
584 if (Value *V = simplifyBinOp(Opcode, C, A, SQ.getWithInstruction(&I))) {
585 // It simplifies to V. Form "V op B".
586 replaceOperand(I, 0, V);
587 replaceOperand(I, 1, B);
588 // Conservatively clear the optional flags, since they may not be
589 // preserved by the reassociation.
591 I.dropPoisonGeneratingFlags();
592 Changed = true;
593 ++NumReassoc;
594 continue;
595 }
596 }
597
598 // Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
599 if (Op1 && Op1->getOpcode() == Opcode) {
600 Value *A = I.getOperand(0);
601 Value *B = Op1->getOperand(0);
602 Value *C = Op1->getOperand(1);
603
604 if (tryReassociateAndFoldSymmetricPair(I, *Op1, B, C, A)) {
605 Changed = true;
606 ++NumReassoc;
607 continue;
608 }
609
610 // Does "C op A" simplify?
611 if (Value *V = simplifyBinOp(Opcode, C, A, SQ.getWithInstruction(&I))) {
612 // It simplifies to V. Form "B op V".
613 replaceOperand(I, 0, B);
614 replaceOperand(I, 1, V);
615 // Conservatively clear the optional flags, since they may not be
616 // preserved by the reassociation.
618 I.dropPoisonGeneratingFlags();
619 Changed = true;
620 ++NumReassoc;
621 continue;
622 }
623 }
624
625 // Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
626 // if C1 and C2 are constants.
627 Value *A, *B;
628 Constant *C1, *C2, *CRes;
629 if (Op0 && Op1 &&
630 Op0->getOpcode() == Opcode && Op1->getOpcode() == Opcode &&
632 match(Op1, m_OneUse(m_BinOp(m_Value(B), m_Constant(C2)))) &&
633 (CRes = ConstantFoldBinaryOpOperands(Opcode, C1, C2, DL))) {
634 bool IsNUW = hasNoUnsignedWrap(I) &&
635 hasNoUnsignedWrap(*Op0) &&
636 hasNoUnsignedWrap(*Op1);
637 BinaryOperator *NewBO = (IsNUW && Opcode == Instruction::Add) ?
638 BinaryOperator::CreateNUW(Opcode, A, B) :
639 BinaryOperator::Create(Opcode, A, B);
640
641 if (isa<FPMathOperator>(NewBO)) {
642 FastMathFlags Flags = I.getFastMathFlags() &
643 Op0->getFastMathFlags() &
644 Op1->getFastMathFlags();
645 NewBO->setFastMathFlags(Flags);
646 }
647 InsertNewInstWith(NewBO, I.getIterator());
648 NewBO->takeName(Op1);
649 replaceOperand(I, 0, NewBO);
650 replaceOperand(I, 1, CRes);
651 // Conservatively clear the optional flags, since they may not be
652 // preserved by the reassociation.
654 I.dropPoisonGeneratingFlags();
655 if (IsNUW)
656 I.setHasNoUnsignedWrap(true);
657
658 Changed = true;
659 continue;
660 }
661 }
662
663 // No further simplifications.
664 return Changed;
665 } while (true);
666}
667
668/// Return whether "X LOp (Y ROp Z)" is always equal to
669/// "(X LOp Y) ROp (X LOp Z)".
672 // X & (Y | Z) <--> (X & Y) | (X & Z)
673 // X & (Y ^ Z) <--> (X & Y) ^ (X & Z)
674 if (LOp == Instruction::And)
675 return ROp == Instruction::Or || ROp == Instruction::Xor;
676
677 // X | (Y & Z) <--> (X | Y) & (X | Z)
678 if (LOp == Instruction::Or)
679 return ROp == Instruction::And;
680
681 // X * (Y + Z) <--> (X * Y) + (X * Z)
682 // X * (Y - Z) <--> (X * Y) - (X * Z)
683 if (LOp == Instruction::Mul)
684 return ROp == Instruction::Add || ROp == Instruction::Sub;
685
686 return false;
687}
688
689/// Return whether "(X LOp Y) ROp Z" is always equal to
690/// "(X ROp Z) LOp (Y ROp Z)".
694 return leftDistributesOverRight(ROp, LOp);
695
696 // (X {&|^} Y) >> Z <--> (X >> Z) {&|^} (Y >> Z) for all shifts.
698
699 // TODO: It would be nice to handle division, aka "(X + Y)/Z = X/Z + Y/Z",
700 // but this requires knowing that the addition does not overflow and other
701 // such subtleties.
702}
703
704/// This function returns identity value for given opcode, which can be used to
705/// factor patterns like (X * 2) + X ==> (X * 2) + (X * 1) ==> X * (2 + 1).
707 if (isa<Constant>(V))
708 return nullptr;
709
710 return ConstantExpr::getBinOpIdentity(Opcode, V->getType());
711}
712
713/// This function predicates factorization using distributive laws. By default,
714/// it just returns the 'Op' inputs. But for special-cases like
715/// 'add(shl(X, 5), ...)', this function will have TopOpcode == Instruction::Add
716/// and Op = shl(X, 5). The 'shl' is treated as the more general 'mul X, 32' to
717/// allow more factorization opportunities.
720 Value *&LHS, Value *&RHS, BinaryOperator *OtherOp) {
721 assert(Op && "Expected a binary operator");
722 LHS = Op->getOperand(0);
723 RHS = Op->getOperand(1);
724 if (TopOpcode == Instruction::Add || TopOpcode == Instruction::Sub) {
725 Constant *C;
726 if (match(Op, m_Shl(m_Value(), m_ImmConstant(C)))) {
727 // X << C --> X * (1 << C)
729 Instruction::Shl, ConstantInt::get(Op->getType(), 1), C);
730 assert(RHS && "Constant folding of immediate constants failed");
731 return Instruction::Mul;
732 }
733 // TODO: We can add other conversions e.g. shr => div etc.
734 }
735 if (Instruction::isBitwiseLogicOp(TopOpcode)) {
736 if (OtherOp && OtherOp->getOpcode() == Instruction::AShr &&
738 // lshr nneg C, X --> ashr nneg C, X
739 return Instruction::AShr;
740 }
741 }
742 return Op->getOpcode();
743}
744
745/// This tries to simplify binary operations by factorizing out common terms
746/// (e. g. "(A*B)+(A*C)" -> "A*(B+C)").
749 Instruction::BinaryOps InnerOpcode, Value *A,
750 Value *B, Value *C, Value *D) {
751 assert(A && B && C && D && "All values must be provided");
752
753 Value *V = nullptr;
754 Value *RetVal = nullptr;
755 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
756 Instruction::BinaryOps TopLevelOpcode = I.getOpcode();
757
758 // Does "X op' Y" always equal "Y op' X"?
759 bool InnerCommutative = Instruction::isCommutative(InnerOpcode);
760
761 // Does "X op' (Y op Z)" always equal "(X op' Y) op (X op' Z)"?
762 if (leftDistributesOverRight(InnerOpcode, TopLevelOpcode)) {
763 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
764 // commutative case, "(A op' B) op (C op' A)"?
765 if (A == C || (InnerCommutative && A == D)) {
766 if (A != C)
767 std::swap(C, D);
768 // Consider forming "A op' (B op D)".
769 // If "B op D" simplifies then it can be formed with no cost.
770 V = simplifyBinOp(TopLevelOpcode, B, D, SQ.getWithInstruction(&I));
771
772 // If "B op D" doesn't simplify then only go on if one of the existing
773 // operations "A op' B" and "C op' D" will be zapped as no longer used.
774 if (!V && (LHS->hasOneUse() || RHS->hasOneUse()))
775 V = Builder.CreateBinOp(TopLevelOpcode, B, D, RHS->getName());
776 if (V)
777 RetVal = Builder.CreateBinOp(InnerOpcode, A, V);
778 }
779 }
780
781 // Does "(X op Y) op' Z" always equal "(X op' Z) op (Y op' Z)"?
782 if (!RetVal && rightDistributesOverLeft(TopLevelOpcode, InnerOpcode)) {
783 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
784 // commutative case, "(A op' B) op (B op' D)"?
785 if (B == D || (InnerCommutative && B == C)) {
786 if (B != D)
787 std::swap(C, D);
788 // Consider forming "(A op C) op' B".
789 // If "A op C" simplifies then it can be formed with no cost.
790 V = simplifyBinOp(TopLevelOpcode, A, C, SQ.getWithInstruction(&I));
791
792 // If "A op C" doesn't simplify then only go on if one of the existing
793 // operations "A op' B" and "C op' D" will be zapped as no longer used.
794 if (!V && (LHS->hasOneUse() || RHS->hasOneUse()))
795 V = Builder.CreateBinOp(TopLevelOpcode, A, C, LHS->getName());
796 if (V)
797 RetVal = Builder.CreateBinOp(InnerOpcode, V, B);
798 }
799 }
800
801 if (!RetVal)
802 return nullptr;
803
804 ++NumFactor;
805 RetVal->takeName(&I);
806
807 // Try to add no-overflow flags to the final value.
808 if (isa<BinaryOperator>(RetVal)) {
809 bool HasNSW = false;
810 bool HasNUW = false;
812 HasNSW = I.hasNoSignedWrap();
813 HasNUW = I.hasNoUnsignedWrap();
814 }
815 if (auto *LOBO = dyn_cast<OverflowingBinaryOperator>(LHS)) {
816 HasNSW &= LOBO->hasNoSignedWrap();
817 HasNUW &= LOBO->hasNoUnsignedWrap();
818 }
819
820 if (auto *ROBO = dyn_cast<OverflowingBinaryOperator>(RHS)) {
821 HasNSW &= ROBO->hasNoSignedWrap();
822 HasNUW &= ROBO->hasNoUnsignedWrap();
823 }
824
825 if (TopLevelOpcode == Instruction::Add && InnerOpcode == Instruction::Mul) {
826 // We can propagate 'nsw' if we know that
827 // %Y = mul nsw i16 %X, C
828 // %Z = add nsw i16 %Y, %X
829 // =>
830 // %Z = mul nsw i16 %X, C+1
831 //
832 // iff C+1 isn't INT_MIN
833 const APInt *CInt;
834 if (match(V, m_APInt(CInt)) && !CInt->isMinSignedValue())
835 cast<Instruction>(RetVal)->setHasNoSignedWrap(HasNSW);
836
837 // nuw can be propagated with any constant or nuw value.
838 cast<Instruction>(RetVal)->setHasNoUnsignedWrap(HasNUW);
839 }
840 }
841 return RetVal;
842}
843
844// If `I` has one Const operand and the other matches `(ctpop (not x))`,
845// replace `(ctpop (not x))` with `(sub nuw nsw BitWidth(x), (ctpop x))`.
846// This is only useful is the new subtract can fold so we only handle the
847// following cases:
848// 1) (add/sub/disjoint_or C, (ctpop (not x))
849// -> (add/sub/disjoint_or C', (ctpop x))
850// 1) (cmp pred C, (ctpop (not x))
851// -> (cmp pred C', (ctpop x))
853 unsigned Opc = I->getOpcode();
854 unsigned ConstIdx = 1;
855 switch (Opc) {
856 default:
857 return nullptr;
858 // (ctpop (not x)) <-> (sub nuw nsw BitWidth(x) - (ctpop x))
859 // We can fold the BitWidth(x) with add/sub/icmp as long the other operand
860 // is constant.
861 case Instruction::Sub:
862 ConstIdx = 0;
863 break;
864 case Instruction::ICmp:
865 // Signed predicates aren't correct in some edge cases like for i2 types, as
866 // well since (ctpop x) is known [0, log2(BitWidth(x))] almost all signed
867 // comparisons against it are simplfied to unsigned.
868 if (cast<ICmpInst>(I)->isSigned())
869 return nullptr;
870 break;
871 case Instruction::Or:
872 if (!match(I, m_DisjointOr(m_Value(), m_Value())))
873 return nullptr;
874 [[fallthrough]];
875 case Instruction::Add:
876 break;
877 }
878
879 Value *Op;
880 // Find ctpop.
881 if (!match(I->getOperand(1 - ConstIdx), m_OneUse(m_Ctpop(m_Value(Op)))))
882 return nullptr;
883
884 Constant *C;
885 // Check other operand is ImmConstant.
886 if (!match(I->getOperand(ConstIdx), m_ImmConstant(C)))
887 return nullptr;
888
889 Type *Ty = Op->getType();
890 Constant *BitWidthC = ConstantInt::get(Ty, Ty->getScalarSizeInBits());
891 // Need extra check for icmp. Note if this check is true, it generally means
892 // the icmp will simplify to true/false.
893 if (Opc == Instruction::ICmp && !cast<ICmpInst>(I)->isEquality()) {
894 Constant *Cmp =
896 if (!Cmp || !Cmp->isNullValue())
897 return nullptr;
898 }
899
900 // Check we can invert `(not x)` for free.
901 bool Consumes = false;
902 if (!isFreeToInvert(Op, Op->hasOneUse(), Consumes) || !Consumes)
903 return nullptr;
904 Value *NotOp = getFreelyInverted(Op, Op->hasOneUse(), &Builder);
905 assert(NotOp != nullptr &&
906 "Desync between isFreeToInvert and getFreelyInverted");
907
908 Value *CtpopOfNotOp = Builder.CreateIntrinsic(Ty, Intrinsic::ctpop, NotOp);
909
910 Value *R = nullptr;
911
912 // Do the transformation here to avoid potentially introducing an infinite
913 // loop.
914 switch (Opc) {
915 case Instruction::Sub:
916 R = Builder.CreateAdd(CtpopOfNotOp, ConstantExpr::getSub(C, BitWidthC));
917 break;
918 case Instruction::Or:
919 case Instruction::Add:
920 R = Builder.CreateSub(ConstantExpr::getAdd(C, BitWidthC), CtpopOfNotOp);
921 break;
922 case Instruction::ICmp:
923 R = Builder.CreateICmp(cast<ICmpInst>(I)->getSwappedPredicate(),
924 CtpopOfNotOp, ConstantExpr::getSub(BitWidthC, C));
925 break;
926 default:
927 llvm_unreachable("Unhandled Opcode");
928 }
929 assert(R != nullptr);
930 return replaceInstUsesWith(*I, R);
931}
932
933// (Binop1 (Binop2 (logic_shift X, C), C1), (logic_shift Y, C))
934// IFF
935// 1) the logic_shifts match
936// 2) either both binops are binops and one is `and` or
937// BinOp1 is `and`
938// (logic_shift (inv_logic_shift C1, C), C) == C1 or
939//
940// -> (logic_shift (Binop1 (Binop2 X, inv_logic_shift(C1, C)), Y), C)
941//
942// (Binop1 (Binop2 (logic_shift X, Amt), Mask), (logic_shift Y, Amt))
943// IFF
944// 1) the logic_shifts match
945// 2) BinOp1 == BinOp2 (if BinOp == `add`, then also requires `shl`).
946//
947// -> (BinOp (logic_shift (BinOp X, Y)), Mask)
948//
949// (Binop1 (Binop2 (arithmetic_shift X, Amt), Mask), (arithmetic_shift Y, Amt))
950// IFF
951// 1) Binop1 is bitwise logical operator `and`, `or` or `xor`
952// 2) Binop2 is `not`
953//
954// -> (arithmetic_shift Binop1((not X), Y), Amt)
955
957 const DataLayout &DL = I.getDataLayout();
958 auto IsValidBinOpc = [](unsigned Opc) {
959 switch (Opc) {
960 default:
961 return false;
962 case Instruction::And:
963 case Instruction::Or:
964 case Instruction::Xor:
965 case Instruction::Add:
966 // Skip Sub as we only match constant masks which will canonicalize to use
967 // add.
968 return true;
969 }
970 };
971
972 // Check if we can distribute binop arbitrarily. `add` + `lshr` has extra
973 // constraints.
974 auto IsCompletelyDistributable = [](unsigned BinOpc1, unsigned BinOpc2,
975 unsigned ShOpc) {
976 assert(ShOpc != Instruction::AShr);
977 return (BinOpc1 != Instruction::Add && BinOpc2 != Instruction::Add) ||
978 ShOpc == Instruction::Shl;
979 };
980
981 auto GetInvShift = [](unsigned ShOpc) {
982 assert(ShOpc != Instruction::AShr);
983 return ShOpc == Instruction::LShr ? Instruction::Shl : Instruction::LShr;
984 };
985
986 auto CanDistributeBinops = [&](unsigned BinOpc1, unsigned BinOpc2,
987 unsigned ShOpc, Constant *CMask,
988 Constant *CShift) {
989 // If the BinOp1 is `and` we don't need to check the mask.
990 if (BinOpc1 == Instruction::And)
991 return true;
992
993 // For all other possible transfers we need complete distributable
994 // binop/shift (anything but `add` + `lshr`).
995 if (!IsCompletelyDistributable(BinOpc1, BinOpc2, ShOpc))
996 return false;
997
998 // If BinOp2 is `and`, any mask works (this only really helps for non-splat
999 // vecs, otherwise the mask will be simplified and the following check will
1000 // handle it).
1001 if (BinOpc2 == Instruction::And)
1002 return true;
1003
1004 // Otherwise, need mask that meets the below requirement.
1005 // (logic_shift (inv_logic_shift Mask, ShAmt), ShAmt) == Mask
1006 Constant *MaskInvShift =
1007 ConstantFoldBinaryOpOperands(GetInvShift(ShOpc), CMask, CShift, DL);
1008 return ConstantFoldBinaryOpOperands(ShOpc, MaskInvShift, CShift, DL) ==
1009 CMask;
1010 };
1011
1012 auto MatchBinOp = [&](unsigned ShOpnum) -> Instruction * {
1013 Constant *CMask, *CShift;
1014 Value *X, *Y, *ShiftedX, *Mask, *Shift;
1015 if (!match(I.getOperand(ShOpnum),
1016 m_OneUse(m_Shift(m_Value(Y), m_Value(Shift)))))
1017 return nullptr;
1018 if (!match(
1019 I.getOperand(1 - ShOpnum),
1022 m_Value(ShiftedX)),
1023 m_Value(Mask)))))
1024 return nullptr;
1025 // Make sure we are matching instruction shifts and not ConstantExpr
1026 auto *IY = dyn_cast<Instruction>(I.getOperand(ShOpnum));
1027 auto *IX = dyn_cast<Instruction>(ShiftedX);
1028 if (!IY || !IX)
1029 return nullptr;
1030
1031 // LHS and RHS need same shift opcode
1032 unsigned ShOpc = IY->getOpcode();
1033 if (ShOpc != IX->getOpcode())
1034 return nullptr;
1035
1036 // Make sure binop is real instruction and not ConstantExpr
1037 auto *BO2 = dyn_cast<Instruction>(I.getOperand(1 - ShOpnum));
1038 if (!BO2)
1039 return nullptr;
1040
1041 unsigned BinOpc = BO2->getOpcode();
1042 // Make sure we have valid binops.
1043 if (!IsValidBinOpc(I.getOpcode()) || !IsValidBinOpc(BinOpc))
1044 return nullptr;
1045
1046 if (ShOpc == Instruction::AShr) {
1047 if (Instruction::isBitwiseLogicOp(I.getOpcode()) &&
1048 BinOpc == Instruction::Xor && match(Mask, m_AllOnes())) {
1049 Value *NotX = Builder.CreateNot(X);
1050 Value *NewBinOp = Builder.CreateBinOp(I.getOpcode(), Y, NotX);
1052 static_cast<Instruction::BinaryOps>(ShOpc), NewBinOp, Shift);
1053 }
1054
1055 return nullptr;
1056 }
1057
1058 // If BinOp1 == BinOp2 and it's bitwise or shl with add, then just
1059 // distribute to drop the shift irrelevant of constants.
1060 if (BinOpc == I.getOpcode() &&
1061 IsCompletelyDistributable(I.getOpcode(), BinOpc, ShOpc)) {
1062 Value *NewBinOp2 = Builder.CreateBinOp(I.getOpcode(), X, Y);
1063 Value *NewBinOp1 = Builder.CreateBinOp(
1064 static_cast<Instruction::BinaryOps>(ShOpc), NewBinOp2, Shift);
1065 return BinaryOperator::Create(I.getOpcode(), NewBinOp1, Mask);
1066 }
1067
1068 // Otherwise we can only distribute by constant shifting the mask, so
1069 // ensure we have constants.
1070 if (!match(Shift, m_ImmConstant(CShift)))
1071 return nullptr;
1072 if (!match(Mask, m_ImmConstant(CMask)))
1073 return nullptr;
1074
1075 // Check if we can distribute the binops.
1076 if (!CanDistributeBinops(I.getOpcode(), BinOpc, ShOpc, CMask, CShift))
1077 return nullptr;
1078
1079 Constant *NewCMask =
1080 ConstantFoldBinaryOpOperands(GetInvShift(ShOpc), CMask, CShift, DL);
1081 Value *NewBinOp2 = Builder.CreateBinOp(
1082 static_cast<Instruction::BinaryOps>(BinOpc), X, NewCMask);
1083 Value *NewBinOp1 = Builder.CreateBinOp(I.getOpcode(), Y, NewBinOp2);
1084 return BinaryOperator::Create(static_cast<Instruction::BinaryOps>(ShOpc),
1085 NewBinOp1, CShift);
1086 };
1087
1088 if (Instruction *R = MatchBinOp(0))
1089 return R;
1090 return MatchBinOp(1);
1091}
1092
1093// (Binop (zext C), (select C, T, F))
1094// -> (select C, (binop 1, T), (binop 0, F))
1095//
1096// (Binop (sext C), (select C, T, F))
1097// -> (select C, (binop -1, T), (binop 0, F))
1098//
1099// Attempt to simplify binary operations into a select with folded args, when
1100// one operand of the binop is a select instruction and the other operand is a
1101// zext/sext extension, whose value is the select condition.
1104 // TODO: this simplification may be extended to any speculatable instruction,
1105 // not just binops, and would possibly be handled better in FoldOpIntoSelect.
1106 Instruction::BinaryOps Opc = I.getOpcode();
1107 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1108 Value *A, *CondVal, *TrueVal, *FalseVal;
1109 Value *CastOp;
1110 Constant *CastTrueVal, *CastFalseVal;
1111
1112 auto MatchSelectAndCast = [&](Value *CastOp, Value *SelectOp) {
1113 return match(CastOp, m_SelectLike(m_Value(A), m_Constant(CastTrueVal),
1114 m_Constant(CastFalseVal))) &&
1115 match(SelectOp, m_Select(m_Value(CondVal), m_Value(TrueVal),
1116 m_Value(FalseVal)));
1117 };
1118
1119 // Make sure one side of the binop is a select instruction, and the other is a
1120 // zero/sign extension operating on a i1.
1121 if (MatchSelectAndCast(LHS, RHS))
1122 CastOp = LHS;
1123 else if (MatchSelectAndCast(RHS, LHS))
1124 CastOp = RHS;
1125 else
1126 return nullptr;
1127
1128 SelectInst *SI = cast<SelectInst>(CastOp == LHS ? RHS : LHS);
1129
1130 auto NewFoldedConst = [&](bool IsTrueArm, Value *V) {
1131 bool IsCastOpRHS = (CastOp == RHS);
1132 Value *CastVal = IsTrueArm ? CastFalseVal : CastTrueVal;
1133
1134 return IsCastOpRHS ? Builder.CreateBinOp(Opc, V, CastVal)
1135 : Builder.CreateBinOp(Opc, CastVal, V);
1136 };
1137
1138 // If the value used in the zext/sext is the select condition, or the negated
1139 // of the select condition, the binop can be simplified.
1140 if (CondVal == A) {
1141 Value *NewTrueVal = NewFoldedConst(false, TrueVal);
1142 return SelectInst::Create(CondVal, NewTrueVal,
1143 NewFoldedConst(true, FalseVal), "", nullptr, SI);
1144 }
1145 if (match(A, m_Not(m_Specific(CondVal)))) {
1146 Value *NewTrueVal = NewFoldedConst(true, TrueVal);
1147 return SelectInst::Create(CondVal, NewTrueVal,
1148 NewFoldedConst(false, FalseVal), "", nullptr, SI);
1149 }
1150
1151 return nullptr;
1152}
1153
1155 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1158 Instruction::BinaryOps TopLevelOpcode = I.getOpcode();
1159 Value *A, *B, *C, *D;
1160 Instruction::BinaryOps LHSOpcode, RHSOpcode;
1161
1162 if (Op0)
1163 LHSOpcode = getBinOpsForFactorization(TopLevelOpcode, Op0, A, B, Op1);
1164 if (Op1)
1165 RHSOpcode = getBinOpsForFactorization(TopLevelOpcode, Op1, C, D, Op0);
1166
1167 // The instruction has the form "(A op' B) op (C op' D)". Try to factorize
1168 // a common term.
1169 if (Op0 && Op1 && LHSOpcode == RHSOpcode)
1170 if (Value *V = tryFactorization(I, SQ, Builder, LHSOpcode, A, B, C, D))
1171 return V;
1172
1173 // The instruction has the form "(A op' B) op (C)". Try to factorize common
1174 // term.
1175 if (Op0)
1176 if (Value *Ident = getIdentityValue(LHSOpcode, RHS))
1177 if (Value *V =
1178 tryFactorization(I, SQ, Builder, LHSOpcode, A, B, RHS, Ident))
1179 return V;
1180
1181 // The instruction has the form "(B) op (C op' D)". Try to factorize common
1182 // term.
1183 if (Op1)
1184 if (Value *Ident = getIdentityValue(RHSOpcode, LHS))
1185 if (Value *V =
1186 tryFactorization(I, SQ, Builder, RHSOpcode, LHS, Ident, C, D))
1187 return V;
1188
1189 return nullptr;
1190}
1191
1192/// This tries to simplify binary operations which some other binary operation
1193/// distributes over either by factorizing out common terms
1194/// (eg "(A*B)+(A*C)" -> "A*(B+C)") or expanding out if this results in
1195/// simplifications (eg: "A & (B | C) -> (A&B) | (A&C)" if this is a win).
1196/// Returns the simplified value, or null if it didn't simplify.
1198 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1201 Instruction::BinaryOps TopLevelOpcode = I.getOpcode();
1202
1203 // Factorization.
1204 if (Value *R = tryFactorizationFolds(I))
1205 return R;
1206
1207 // Expansion.
1208 if (Op0 && rightDistributesOverLeft(Op0->getOpcode(), TopLevelOpcode)) {
1209 // The instruction has the form "(A op' B) op C". See if expanding it out
1210 // to "(A op C) op' (B op C)" results in simplifications.
1211 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
1212 Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op'
1213
1214 // Disable the use of undef because it's not safe to distribute undef.
1215 auto SQDistributive = SQ.getWithInstruction(&I).getWithoutUndef();
1216 Value *L = simplifyBinOp(TopLevelOpcode, A, C, SQDistributive);
1217 Value *R = simplifyBinOp(TopLevelOpcode, B, C, SQDistributive);
1218
1219 // Do "A op C" and "B op C" both simplify?
1220 if (L && R) {
1221 // They do! Return "L op' R".
1222 ++NumExpand;
1223 C = Builder.CreateBinOp(InnerOpcode, L, R);
1224 C->takeName(&I);
1225 return C;
1226 }
1227
1228 // Does "A op C" simplify to the identity value for the inner opcode?
1229 if (L && L == ConstantExpr::getBinOpIdentity(InnerOpcode, L->getType())) {
1230 // They do! Return "B op C".
1231 ++NumExpand;
1232 C = Builder.CreateBinOp(TopLevelOpcode, B, C);
1233 C->takeName(&I);
1234 return C;
1235 }
1236
1237 // Does "B op C" simplify to the identity value for the inner opcode?
1238 if (R && R == ConstantExpr::getBinOpIdentity(InnerOpcode, R->getType())) {
1239 // They do! Return "A op C".
1240 ++NumExpand;
1241 C = Builder.CreateBinOp(TopLevelOpcode, A, C);
1242 C->takeName(&I);
1243 return C;
1244 }
1245 }
1246
1247 if (Op1 && leftDistributesOverRight(TopLevelOpcode, Op1->getOpcode())) {
1248 // The instruction has the form "A op (B op' C)". See if expanding it out
1249 // to "(A op B) op' (A op C)" results in simplifications.
1250 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
1251 Instruction::BinaryOps InnerOpcode = Op1->getOpcode(); // op'
1252
1253 // Disable the use of undef because it's not safe to distribute undef.
1254 auto SQDistributive = SQ.getWithInstruction(&I).getWithoutUndef();
1255 Value *L = simplifyBinOp(TopLevelOpcode, A, B, SQDistributive);
1256 Value *R = simplifyBinOp(TopLevelOpcode, A, C, SQDistributive);
1257
1258 // Do "A op B" and "A op C" both simplify?
1259 if (L && R) {
1260 // They do! Return "L op' R".
1261 ++NumExpand;
1262 A = Builder.CreateBinOp(InnerOpcode, L, R);
1263 A->takeName(&I);
1264 return A;
1265 }
1266
1267 // Does "A op B" simplify to the identity value for the inner opcode?
1268 if (L && L == ConstantExpr::getBinOpIdentity(InnerOpcode, L->getType())) {
1269 // They do! Return "A op C".
1270 ++NumExpand;
1271 A = Builder.CreateBinOp(TopLevelOpcode, A, C);
1272 A->takeName(&I);
1273 return A;
1274 }
1275
1276 // Does "A op C" simplify to the identity value for the inner opcode?
1277 if (R && R == ConstantExpr::getBinOpIdentity(InnerOpcode, R->getType())) {
1278 // They do! Return "A op B".
1279 ++NumExpand;
1280 A = Builder.CreateBinOp(TopLevelOpcode, A, B);
1281 A->takeName(&I);
1282 return A;
1283 }
1284 }
1285
1286 return SimplifySelectsFeedingBinaryOp(I, LHS, RHS);
1287}
1288
1289static std::optional<std::pair<Value *, Value *>>
1291 if (LHS->getParent() != RHS->getParent())
1292 return std::nullopt;
1293
1294 if (LHS->getNumIncomingValues() < 2)
1295 return std::nullopt;
1296
1297 if (!equal(LHS->blocks(), RHS->blocks()))
1298 return std::nullopt;
1299
1300 Value *L0 = LHS->getIncomingValue(0);
1301 Value *R0 = RHS->getIncomingValue(0);
1302
1303 for (unsigned I = 1, E = LHS->getNumIncomingValues(); I != E; ++I) {
1304 Value *L1 = LHS->getIncomingValue(I);
1305 Value *R1 = RHS->getIncomingValue(I);
1306
1307 if ((L0 == L1 && R0 == R1) || (L0 == R1 && R0 == L1))
1308 continue;
1309
1310 return std::nullopt;
1311 }
1312
1313 return std::optional(std::pair(L0, R0));
1314}
1315
1316std::optional<std::pair<Value *, Value *>>
1317InstCombinerImpl::matchSymmetricPair(Value *LHS, Value *RHS) {
1320 if (!LHSInst || !RHSInst || LHSInst->getOpcode() != RHSInst->getOpcode())
1321 return std::nullopt;
1322 switch (LHSInst->getOpcode()) {
1323 case Instruction::PHI:
1325 case Instruction::Select: {
1326 Value *Cond = LHSInst->getOperand(0);
1327 Value *TrueVal = LHSInst->getOperand(1);
1328 Value *FalseVal = LHSInst->getOperand(2);
1329 if (Cond == RHSInst->getOperand(0) && TrueVal == RHSInst->getOperand(2) &&
1330 FalseVal == RHSInst->getOperand(1))
1331 return std::pair(TrueVal, FalseVal);
1332 return std::nullopt;
1333 }
1334 case Instruction::Call: {
1335 // Match min(a, b) and max(a, b)
1336 MinMaxIntrinsic *LHSMinMax = dyn_cast<MinMaxIntrinsic>(LHSInst);
1337 MinMaxIntrinsic *RHSMinMax = dyn_cast<MinMaxIntrinsic>(RHSInst);
1338 if (LHSMinMax && RHSMinMax &&
1339 LHSMinMax->getPredicate() ==
1341 ((LHSMinMax->getLHS() == RHSMinMax->getLHS() &&
1342 LHSMinMax->getRHS() == RHSMinMax->getRHS()) ||
1343 (LHSMinMax->getLHS() == RHSMinMax->getRHS() &&
1344 LHSMinMax->getRHS() == RHSMinMax->getLHS())))
1345 return std::pair(LHSMinMax->getLHS(), LHSMinMax->getRHS());
1346 return std::nullopt;
1347 }
1348 default:
1349 return std::nullopt;
1350 }
1351}
1352
1354 BinaryOperator &OuterOp, BinaryOperator &InnerOp, Value *InnerVal0,
1355 Value *InnerVal1, Value *OuterVal) {
1356 assert(OuterOp.isCommutative() && OuterOp.isAssociative() &&
1357 "OuterOp must be commutative and associative");
1358 assert(OuterOp.getOpcode() == InnerOp.getOpcode() &&
1359 "OuterOp and InnerOp must have same opcode");
1360 if (!InnerOp.isAssociative() || !InnerOp.hasOneUse())
1361 return false;
1362
1363 unsigned OuterValIdx = OuterOp.getOperand(0) == OuterVal ? 0 : 1;
1364 assert(OuterOp.getOperand(OuterValIdx) == OuterVal &&
1365 "OuterVal must be an operand of OuterOp");
1366
1367 auto Pair = matchSymmetricPair(InnerVal1, OuterVal);
1368 if (!Pair)
1369 return false;
1370
1371 replaceOperand(InnerOp, 0, Pair->first);
1372 replaceOperand(InnerOp, 1, Pair->second);
1375 replaceOperand(OuterOp, OuterValIdx, InnerVal0);
1376 if (!isa<FPMathOperator>(OuterOp))
1377 OuterOp.dropPoisonGeneratingFlags();
1379 return true;
1380}
1381
1382/// Distribute a binop over a select:
1383/// (Cond ? TVal : FVal) op Other --> Cond ? (TVal op Other) : (FVal op Other)
1384/// (or with the operands swapped if \p SelIsLHS is false).
1385/// If \p Other is a select whose condition is implied by Cond (or its
1386/// negation), it is resolved to the corresponding arm on that side first.
1387/// \p True and \p False are set to the simplified arms, or null if an arm did
1388/// not simplify.
1391 SelectInst *Sel, Value *Other,
1392 bool SelIsLHS, FastMathFlags FMF,
1393 const SimplifyQuery &SQ, Value *&True,
1394 Value *&False) {
1395 // If V is a select whose condition is implied by Cond, try to resolve it to
1396 // the appropriate arm for this value of Cond.
1397 auto SimplifySelectWithImpliedCond = [&](Value *V, Value *Cond,
1398 bool CondIsTrue) -> Value * {
1399 auto *InnerSI = dyn_cast<SelectInst>(V);
1400 if (!InnerSI || Cond->getType() != InnerSI->getCondition()->getType())
1401 return V;
1402
1403 if (Value *Arm = IC.simplifyNestedSelectsUsingImpliedCond(*InnerSI, Cond,
1404 CondIsTrue))
1405 return Arm;
1406 return V;
1407 };
1408
1409 Value *Cond = Sel->getCondition();
1410 Value *TVal = Sel->getTrueValue(), *FVal = Sel->getFalseValue();
1411 Value *OtherT = SimplifySelectWithImpliedCond(Other, Cond, true);
1412 Value *OtherF = SimplifySelectWithImpliedCond(Other, Cond, false);
1413 Value *LHSTrueArm = TVal, *RHSTrueArm = OtherT;
1414 Value *LHSFalseArm = FVal, *RHSFalseArm = OtherF;
1415 if (!SelIsLHS) {
1416 std::swap(LHSTrueArm, RHSTrueArm);
1417 std::swap(LHSFalseArm, RHSFalseArm);
1418 }
1419
1420 True = simplifyBinOp(Opcode, LHSTrueArm, RHSTrueArm, FMF, SQ);
1421 False = simplifyBinOp(Opcode, LHSFalseArm, RHSFalseArm, FMF, SQ);
1422
1423 if (!Other->hasOneUse())
1424 return;
1425
1426 if (True && !False && OtherT != Other)
1427 False = IC.Builder.CreateBinOp(Opcode, LHSFalseArm, RHSFalseArm);
1428 else if (False && !True && OtherF != Other)
1429 True = IC.Builder.CreateBinOp(Opcode, LHSTrueArm, RHSTrueArm);
1430}
1431
1433 Value *LHS,
1434 Value *RHS) {
1435 Value *A, *B, *C, *D, *E, *F;
1436 bool LHSIsSelect = match(LHS, m_Select(m_Value(A), m_Value(B), m_Value(C)));
1437 bool RHSIsSelect = match(RHS, m_Select(m_Value(D), m_Value(E), m_Value(F)));
1438 if (!LHSIsSelect && !RHSIsSelect)
1439 return nullptr;
1440
1441 SelectInst *SI = cast<SelectInst>(LHSIsSelect ? LHS : RHS);
1442
1443 FastMathFlags FMF;
1445 if (const auto *FPOp = dyn_cast<FPMathOperator>(&I)) {
1446 FMF = FPOp->getFastMathFlags();
1447 Builder.setFastMathFlags(FMF);
1448 }
1449
1450 Instruction::BinaryOps Opcode = I.getOpcode();
1451 SimplifyQuery Q = SQ.getWithInstruction(&I);
1452
1453 Value *Cond, *True = nullptr, *False = nullptr;
1454
1455 // Special-case for add/negate combination. Replace the zero in the negation
1456 // with the trailing add operand:
1457 // (Cond ? TVal : -N) + Z --> Cond ? True : (Z - N)
1458 // (Cond ? -N : FVal) + Z --> Cond ? (Z - N) : False
1459 auto foldAddNegate = [&](Value *TVal, Value *FVal, Value *Z) -> Value * {
1460 // We need an 'add' and exactly 1 arm of the select to have been simplified.
1461 if (Opcode != Instruction::Add || (!True && !False) || (True && False))
1462 return nullptr;
1463 Value *N;
1464 if (True && match(FVal, m_Neg(m_Value(N)))) {
1465 Value *Sub = Builder.CreateSub(Z, N);
1466 return Builder.CreateSelect(Cond, True, Sub, I.getName(), SI);
1467 }
1468 if (False && match(TVal, m_Neg(m_Value(N)))) {
1469 Value *Sub = Builder.CreateSub(Z, N);
1470 return Builder.CreateSelect(Cond, Sub, False, I.getName(), SI);
1471 }
1472 return nullptr;
1473 };
1474
1475 if (LHSIsSelect && RHSIsSelect && A == D) {
1476 // (A ? B : C) op (A ? E : F) -> A ? (B op E) : (C op F)
1477 Cond = A;
1478 True = simplifyBinOp(Opcode, B, E, FMF, Q);
1479 False = simplifyBinOp(Opcode, C, F, FMF, Q);
1480
1481 if (LHS->hasOneUse() && RHS->hasOneUse()) {
1482 if (False && !True)
1483 True = Builder.CreateBinOp(Opcode, B, E);
1484 else if (True && !False)
1485 False = Builder.CreateBinOp(Opcode, C, F);
1486 }
1487 } else {
1488 // Prefer distributing over the LHS select.
1489 if (LHSIsSelect && LHS->hasOneUse()) {
1490 Cond = A;
1491 distributeBinOpOverSelect(*this, Opcode, SI, RHS, /*SelIsLHS=*/true, FMF,
1492 Q, True, False);
1493 if (Value *NewSel = foldAddNegate(B, C, RHS))
1494 return NewSel;
1495 }
1496
1497 bool Folded = True && False;
1498 if (!Folded && RHSIsSelect && RHS->hasOneUse()) {
1499 // The LHS select did not fold, or there was none. Try the RHS one.
1500 SI = cast<SelectInst>(RHS);
1501 Cond = D;
1502 distributeBinOpOverSelect(*this, Opcode, SI, LHS, /*SelIsLHS=*/false, FMF,
1503 Q, True, False);
1504 if (Value *NewSel = foldAddNegate(E, F, LHS))
1505 return NewSel;
1506 }
1507 }
1508
1509 if (!True || !False)
1510 return nullptr;
1511
1512 Value *NewSI = Builder.CreateSelect(Cond, True, False, I.getName(), SI);
1513 NewSI->takeName(&I);
1514 return NewSI;
1515}
1516
1517/// Freely adapt every user of V as-if V was changed to !V.
1518/// WARNING: only if canFreelyInvertAllUsersOf() said this can be done.
1520 assert(!isa<Constant>(I) && "Shouldn't invert users of constant");
1521 for (User *U : make_early_inc_range(I->users())) {
1522 if (U == IgnoredUser)
1523 continue; // Don't consider this user.
1524 switch (cast<Instruction>(U)->getOpcode()) {
1525 case Instruction::Select: {
1526 auto *SI = cast<SelectInst>(U);
1527 SI->swapValues();
1528 SI->swapProfMetadata();
1529 break;
1530 }
1531 case Instruction::CondBr: {
1533 BI->swapSuccessors(); // swaps prof metadata too
1534 if (BPI)
1535 BPI->swapSuccEdgesProbabilities(BI->getParent());
1536 break;
1537 }
1538 case Instruction::Xor:
1540 // Add to worklist for DCE.
1542 break;
1543 default:
1544 llvm_unreachable("Got unexpected user - out of sync with "
1545 "canFreelyInvertAllUsersOf() ?");
1546 }
1547 }
1548
1549 // Update pre-existing debug value uses.
1550 SmallVector<DbgVariableRecord *, 4> DbgVariableRecords;
1551 llvm::findDbgValues(I, DbgVariableRecords);
1552
1553 for (DbgVariableRecord *DbgVal : DbgVariableRecords) {
1554 SmallVector<uint64_t, 1> Ops = {dwarf::DW_OP_not};
1555 for (unsigned Idx = 0, End = DbgVal->getNumVariableLocationOps();
1556 Idx != End; ++Idx)
1557 if (DbgVal->getVariableLocationOp(Idx) == I)
1558 DbgVal->setExpression(
1559 DIExpression::appendOpsToArg(DbgVal->getExpression(), Ops, Idx));
1560 }
1561}
1562
1563/// Given a 'sub' instruction, return the RHS of the instruction if the LHS is a
1564/// constant zero (which is the 'negate' form).
1565Value *InstCombinerImpl::dyn_castNegVal(Value *V) const {
1566 Value *NegV;
1567 if (match(V, m_Neg(m_Value(NegV))))
1568 return NegV;
1569
1570 // Constants can be considered to be negated values if they can be folded.
1572 return ConstantExpr::getNeg(C);
1573
1575 if (C->getType()->getElementType()->isIntegerTy())
1576 return ConstantExpr::getNeg(C);
1577
1579 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
1580 Constant *Elt = CV->getAggregateElement(i);
1581 if (!Elt)
1582 return nullptr;
1583
1584 if (isa<UndefValue>(Elt))
1585 continue;
1586
1587 if (!isa<ConstantInt>(Elt))
1588 return nullptr;
1589 }
1590 return ConstantExpr::getNeg(CV);
1591 }
1592
1593 // Negate integer vector splats.
1594 if (auto *CV = dyn_cast<Constant>(V))
1595 if (CV->getType()->isVectorTy() &&
1596 CV->getType()->getScalarType()->isIntegerTy() && CV->getSplatValue())
1597 return ConstantExpr::getNeg(CV);
1598
1599 return nullptr;
1600}
1601
1602// Try to fold:
1603// 1) (fp_binop ({s|u}itofp x), ({s|u}itofp y))
1604// -> ({s|u}itofp (int_binop x, y))
1605// 2) (fp_binop ({s|u}itofp x), FpC)
1606// -> ({s|u}itofp (int_binop x, (fpto{s|u}i FpC)))
1607//
1608// Assuming the sign of the cast for x/y is `OpsFromSigned`.
1609Instruction *InstCombinerImpl::foldFBinOpOfIntCastsFromSign(
1610 BinaryOperator &BO, bool OpsFromSigned, std::array<Value *, 2> IntOps,
1612
1613 Type *FPTy = BO.getType();
1614 Type *IntTy = IntOps[0]->getType();
1615
1616 unsigned IntSz = IntTy->getScalarSizeInBits();
1617 // This is the maximum number of inuse bits by the integer where the int -> fp
1618 // casts are exact.
1619 unsigned MaxRepresentableBits =
1621
1622 // Preserve known number of leading bits. This can allow us to trivial nsw/nuw
1623 // checks later on.
1624 unsigned NumUsedLeadingBits[2] = {IntSz, IntSz};
1625
1626 // NB: This only comes up if OpsFromSigned is true, so there is no need to
1627 // cache if between calls to `foldFBinOpOfIntCastsFromSign`.
1628 auto IsNonZero = [&](unsigned OpNo) -> bool {
1629 if (OpsKnown[OpNo].hasKnownBits() &&
1630 OpsKnown[OpNo].getKnownBits(SQ).isNonZero())
1631 return true;
1632 return isKnownNonZero(IntOps[OpNo], SQ);
1633 };
1634
1635 auto IsNonNeg = [&](unsigned OpNo) -> bool {
1636 // NB: This matches the impl in ValueTracking, we just try to use cached
1637 // knownbits here. If we ever start supporting WithCache for
1638 // `isKnownNonNegative`, change this to an explicit call.
1639 return OpsKnown[OpNo].getKnownBits(SQ).isNonNegative();
1640 };
1641
1642 // Check if we know for certain that ({s|u}itofp op) is exact.
1643 auto IsValidPromotion = [&](unsigned OpNo) -> bool {
1644 // Can we treat this operand as the desired sign?
1645 if (OpsFromSigned != isa<SIToFPInst>(BO.getOperand(OpNo)) &&
1646 !IsNonNeg(OpNo))
1647 return false;
1648
1649 // If fp precision >= bitwidth(op) then its exact.
1650 // NB: This is slightly conservative for `sitofp`. For signed conversion, we
1651 // can handle `MaxRepresentableBits == IntSz - 1` as the sign bit will be
1652 // handled specially. We can't, however, increase the bound arbitrarily for
1653 // `sitofp` as for larger sizes, it won't sign extend.
1654 if (MaxRepresentableBits < IntSz) {
1655 // Otherwise if its signed cast check that fp precisions >= bitwidth(op) -
1656 // numSignBits(op).
1657 // TODO: If we add support for `WithCache` in `ComputeNumSignBits`, change
1658 // `IntOps[OpNo]` arguments to `KnownOps[OpNo]`.
1659 if (OpsFromSigned)
1660 NumUsedLeadingBits[OpNo] = IntSz - ComputeNumSignBits(IntOps[OpNo]);
1661 // Finally for unsigned check that fp precision >= bitwidth(op) -
1662 // numLeadingZeros(op).
1663 else {
1664 NumUsedLeadingBits[OpNo] =
1665 IntSz - OpsKnown[OpNo].getKnownBits(SQ).countMinLeadingZeros();
1666 }
1667 }
1668 // NB: We could also check if op is known to be a power of 2 or zero (which
1669 // will always be representable). Its unlikely, however, that is we are
1670 // unable to bound op in any way we will be able to pass the overflow checks
1671 // later on.
1672
1673 if (MaxRepresentableBits < NumUsedLeadingBits[OpNo])
1674 return false;
1675 // Signed + Mul also requires that op is non-zero to avoid -0 cases.
1676 return !OpsFromSigned || BO.getOpcode() != Instruction::FMul ||
1677 IsNonZero(OpNo);
1678 };
1679
1680 // If we have a constant rhs, see if we can losslessly convert it to an int.
1681 if (Op1FpC != nullptr) {
1682 // Signed + Mul req non-zero
1683 if (OpsFromSigned && BO.getOpcode() == Instruction::FMul &&
1684 !match(Op1FpC, m_NonZeroFP()))
1685 return nullptr;
1686
1688 OpsFromSigned ? Instruction::FPToSI : Instruction::FPToUI, Op1FpC,
1689 IntTy, DL);
1690 if (Op1IntC == nullptr)
1691 return nullptr;
1692 if (ConstantFoldCastOperand(OpsFromSigned ? Instruction::SIToFP
1693 : Instruction::UIToFP,
1694 Op1IntC, FPTy, DL) != Op1FpC)
1695 return nullptr;
1696
1697 // First try to keep sign of cast the same.
1698 IntOps[1] = Op1IntC;
1699 }
1700
1701 // Ensure lhs/rhs integer types match.
1702 if (IntTy != IntOps[1]->getType())
1703 return nullptr;
1704
1705 if (Op1FpC == nullptr) {
1706 if (!IsValidPromotion(1))
1707 return nullptr;
1708 }
1709 if (!IsValidPromotion(0))
1710 return nullptr;
1711
1712 // Final we check if the integer version of the binop will not overflow.
1714 // Because of the precision check, we can often rule out overflows.
1715 bool NeedsOverflowCheck = true;
1716 // Try to conservatively rule out overflow based on the already done precision
1717 // checks.
1718 unsigned OverflowMaxOutputBits = OpsFromSigned ? 2 : 1;
1719 unsigned OverflowMaxCurBits =
1720 std::max(NumUsedLeadingBits[0], NumUsedLeadingBits[1]);
1721 bool OutputSigned = OpsFromSigned;
1722 switch (BO.getOpcode()) {
1723 case Instruction::FAdd:
1724 IntOpc = Instruction::Add;
1725 OverflowMaxOutputBits += OverflowMaxCurBits;
1726 break;
1727 case Instruction::FSub:
1728 IntOpc = Instruction::Sub;
1729 OverflowMaxOutputBits += OverflowMaxCurBits;
1730 break;
1731 case Instruction::FMul:
1732 IntOpc = Instruction::Mul;
1733 OverflowMaxOutputBits += OverflowMaxCurBits * 2;
1734 break;
1735 default:
1736 llvm_unreachable("Unsupported binop");
1737 }
1738 // The precision check may have already ruled out overflow.
1739 if (OverflowMaxOutputBits < IntSz) {
1740 NeedsOverflowCheck = false;
1741 // We can bound unsigned overflow from sub to in range signed value (this is
1742 // what allows us to avoid the overflow check for sub).
1743 if (IntOpc == Instruction::Sub)
1744 OutputSigned = true;
1745 }
1746
1747 // Precision check did not rule out overflow, so need to check.
1748 // TODO: If we add support for `WithCache` in `willNotOverflow`, change
1749 // `IntOps[...]` arguments to `KnownOps[...]`.
1750 if (NeedsOverflowCheck &&
1751 !willNotOverflow(IntOpc, IntOps[0], IntOps[1], BO, OutputSigned))
1752 return nullptr;
1753
1754 Value *IntBinOp = Builder.CreateBinOp(IntOpc, IntOps[0], IntOps[1]);
1755 if (auto *IntBO = dyn_cast<BinaryOperator>(IntBinOp)) {
1756 IntBO->setHasNoSignedWrap(OutputSigned);
1757 IntBO->setHasNoUnsignedWrap(!OutputSigned);
1758 }
1759 if (OutputSigned)
1760 return new SIToFPInst(IntBinOp, FPTy);
1761 return new UIToFPInst(IntBinOp, FPTy);
1762}
1763
1764// Try to fold:
1765// 1) (fp_binop ({s|u}itofp x), ({s|u}itofp y))
1766// -> ({s|u}itofp (int_binop x, y))
1767// 2) (fp_binop ({s|u}itofp x), FpC)
1768// -> ({s|u}itofp (int_binop x, (fpto{s|u}i FpC)))
1769Instruction *InstCombinerImpl::foldFBinOpOfIntCasts(BinaryOperator &BO) {
1770 // Don't perform the fold on vectors, as the integer operation may be much
1771 // more expensive than the float operation in that case.
1772 if (BO.getType()->isVectorTy())
1773 return nullptr;
1774
1775 std::array<Value *, 2> IntOps = {nullptr, nullptr};
1776 Constant *Op1FpC = nullptr;
1777 // Check for:
1778 // 1) (binop ({s|u}itofp x), ({s|u}itofp y))
1779 // 2) (binop ({s|u}itofp x), FpC)
1780 if (!match(BO.getOperand(0), m_IToFP(m_Value(IntOps[0]))))
1781 return nullptr;
1782
1783 if (!match(BO.getOperand(1), m_Constant(Op1FpC)) &&
1784 !match(BO.getOperand(1), m_IToFP(m_Value(IntOps[1]))))
1785 return nullptr;
1786
1787 // Cache KnownBits a bit to potentially save some analysis.
1788 SmallVector<WithCache<const Value *>, 2> OpsKnown = {IntOps[0], IntOps[1]};
1789
1790 // Try treating x/y as coming from both `uitofp` and `sitofp`. There are
1791 // different constraints depending on the sign of the cast.
1792 // NB: `(uitofp nneg X)` == `(sitofp nneg X)`.
1793 if (Instruction *R = foldFBinOpOfIntCastsFromSign(BO, /*OpsFromSigned=*/false,
1794 IntOps, Op1FpC, OpsKnown))
1795 return R;
1796 return foldFBinOpOfIntCastsFromSign(BO, /*OpsFromSigned=*/true, IntOps,
1797 Op1FpC, OpsKnown);
1798}
1799
1800/// A binop with a constant operand and a sign-extended boolean operand may be
1801/// converted into a select of constants by applying the binary operation to
1802/// the constant with the two possible values of the extended boolean (0 or -1).
1803Instruction *InstCombinerImpl::foldBinopOfSextBoolToSelect(BinaryOperator &BO) {
1804 // TODO: Handle non-commutative binop (constant is operand 0).
1805 // TODO: Handle zext.
1806 // TODO: Peek through 'not' of cast.
1807 Value *BO0 = BO.getOperand(0);
1808 Value *BO1 = BO.getOperand(1);
1809 Value *X;
1810 Constant *C;
1811 if (!match(BO0, m_SExt(m_Value(X))) || !match(BO1, m_ImmConstant(C)) ||
1812 !X->getType()->isIntOrIntVectorTy(1))
1813 return nullptr;
1814
1815 // bo (sext i1 X), C --> select X, (bo -1, C), (bo 0, C)
1818 Value *TVal = Builder.CreateBinOp(BO.getOpcode(), Ones, C);
1819 Value *FVal = Builder.CreateBinOp(BO.getOpcode(), Zero, C);
1820 return createSelectInstWithUnknownProfile(X, TVal, FVal);
1821}
1822
1824 bool IsTrueArm) {
1826 for (Value *Op : I.operands()) {
1827 Value *V = nullptr;
1828 if (Op == SI) {
1829 V = IsTrueArm ? SI->getTrueValue() : SI->getFalseValue();
1830 } else if (match(SI->getCondition(),
1833 m_Specific(Op), m_Value(V))) &&
1835 // Pass
1836 } else if (match(Op, m_ZExt(m_Specific(SI->getCondition())))) {
1837 V = IsTrueArm ? ConstantInt::get(Op->getType(), 1)
1838 : ConstantInt::getNullValue(Op->getType());
1839 } else {
1840 V = Op;
1841 }
1842 Ops.push_back(V);
1843 }
1844
1845 return simplifyInstructionWithOperands(&I, Ops, I.getDataLayout());
1846}
1847
1849 Value *NewOp, InstCombiner &IC) {
1850 Instruction *Clone = I.clone();
1851 Clone->replaceUsesOfWith(SI, NewOp);
1853 IC.InsertNewInstBefore(Clone, I.getIterator());
1854 return Clone;
1855}
1856
1858 bool FoldWithMultiUse,
1859 bool SimplifyBothArms) {
1860 // Don't modify shared select instructions unless set FoldWithMultiUse
1861 if (!SI->hasOneUser() && !FoldWithMultiUse)
1862 return nullptr;
1863
1864 Value *TV = SI->getTrueValue();
1865 Value *FV = SI->getFalseValue();
1866
1867 // Bool selects with constant operands can be folded to logical ops.
1868 if (SI->getType()->isIntOrIntVectorTy(1))
1869 return nullptr;
1870
1871 // Avoid breaking min/max reduction pattern,
1872 // which is necessary for vectorization later.
1874 for (Value *IntrinOp : Op.operands())
1875 if (auto *PN = dyn_cast<PHINode>(IntrinOp))
1876 for (Value *PhiOp : PN->operands())
1877 if (PhiOp == &Op)
1878 return nullptr;
1879
1880 // Test if a FCmpInst instruction is used exclusively by a select as
1881 // part of a minimum or maximum operation. If so, refrain from doing
1882 // any other folding. This helps out other analyses which understand
1883 // non-obfuscated minimum and maximum idioms. And in this case, at
1884 // least one of the comparison operands has at least one user besides
1885 // the compare (the select), which would often largely negate the
1886 // benefit of folding anyway.
1887 if (auto *CI = dyn_cast<FCmpInst>(SI->getCondition())) {
1888 if (CI->hasOneUse()) {
1889 Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
1890 if (((TV == Op0 && FV == Op1) || (FV == Op0 && TV == Op1)) &&
1891 !CI->isCommutative())
1892 return nullptr;
1893 }
1894 }
1895
1896 // Make sure that one of the select arms folds successfully.
1897 Value *NewTV = simplifyOperationIntoSelectOperand(Op, SI, /*IsTrueArm=*/true);
1898 Value *NewFV =
1899 simplifyOperationIntoSelectOperand(Op, SI, /*IsTrueArm=*/false);
1900 if (!NewTV && !NewFV)
1901 return nullptr;
1902
1903 if (SimplifyBothArms && !(NewTV && NewFV))
1904 return nullptr;
1905
1906 // Create an instruction for the arm that did not fold.
1907 if (!NewTV)
1908 NewTV = foldOperationIntoSelectOperand(Op, SI, TV, *this);
1909 if (!NewFV)
1910 NewFV = foldOperationIntoSelectOperand(Op, SI, FV, *this);
1911
1912 SelectInst *NewSel = SelectInst::Create(SI->getCondition(), NewTV, NewFV);
1913
1914 // Preserve metadata that remains valid for the transformed select including
1915 // source location information.
1916 NewSel->copyMetadata(*SI,
1917 {LLVMContext::MD_prof, LLVMContext::MD_unpredictable,
1918 LLVMContext::MD_dbg});
1919
1920 return NewSel;
1921}
1922
1924 Value *InValue, BasicBlock *InBB,
1925 const DataLayout &DL,
1926 const SimplifyQuery SQ) {
1927 // NB: It is a precondition of this transform that the operands be
1928 // phi translatable!
1930 for (Value *Op : I.operands()) {
1931 if (Op == PN)
1932 Ops.push_back(InValue);
1933 else
1934 Ops.push_back(Op->DoPHITranslation(PN->getParent(), InBB));
1935 }
1936
1937 // Don't consider the simplification successful if we get back a constant
1938 // expression. That's just an instruction in hiding.
1939 // Also reject the case where we simplify back to the phi node. We wouldn't
1940 // be able to remove it in that case.
1942 &I, Ops, SQ.getWithInstruction(InBB->getTerminator()));
1943 if (NewVal && NewVal != PN && !match(NewVal, m_ConstantExpr()))
1944 return NewVal;
1945
1946 // Check if incoming PHI value can be replaced with constant
1947 // based on implied condition.
1948 CondBrInst *TerminatorBI = dyn_cast<CondBrInst>(InBB->getTerminator());
1949 const ICmpInst *ICmp = dyn_cast<ICmpInst>(&I);
1950 if (TerminatorBI &&
1951 TerminatorBI->getSuccessor(0) != TerminatorBI->getSuccessor(1) && ICmp) {
1952 bool LHSIsTrue = TerminatorBI->getSuccessor(0) == PN->getParent();
1953 std::optional<bool> ImpliedCond = isImpliedCondition(
1954 TerminatorBI->getCondition(), ICmp->getCmpPredicate(), Ops[0], Ops[1],
1955 DL, LHSIsTrue);
1956 if (ImpliedCond)
1957 return ConstantInt::getBool(I.getType(), ImpliedCond.value());
1958 }
1959
1960 return nullptr;
1961}
1962
1963/// In some cases it is beneficial to fold a select into a binary operator.
1964/// For example:
1965/// %1 = or %in, 4
1966/// %2 = select %cond, %1, %in
1967/// %3 = or %2, 1
1968/// =>
1969/// %1 = select i1 %cond, 5, 1
1970/// %2 = or %1, %in
1972 assert(Op.isAssociative() && "The operation must be associative!");
1973
1974 SelectInst *SI = dyn_cast<SelectInst>(Op.getOperand(0));
1975
1976 Constant *Const;
1977 if (!SI || !match(Op.getOperand(1), m_ImmConstant(Const)) ||
1978 !Op.hasOneUse() || !SI->hasOneUse())
1979 return nullptr;
1980
1981 Value *TV = SI->getTrueValue();
1982 Value *FV = SI->getFalseValue();
1983 Value *Input, *NewTV, *NewFV;
1984 Constant *Const2;
1985
1986 if (TV->hasOneUse() && match(TV, m_BinOp(Op.getOpcode(), m_Specific(FV),
1987 m_ImmConstant(Const2)))) {
1988 NewTV = ConstantFoldBinaryInstruction(Op.getOpcode(), Const, Const2);
1989 NewFV = Const;
1990 Input = FV;
1991 } else if (FV->hasOneUse() &&
1992 match(FV, m_BinOp(Op.getOpcode(), m_Specific(TV),
1993 m_ImmConstant(Const2)))) {
1994 NewTV = Const;
1995 NewFV = ConstantFoldBinaryInstruction(Op.getOpcode(), Const, Const2);
1996 Input = TV;
1997 } else
1998 return nullptr;
1999
2000 if (!NewTV || !NewFV)
2001 return nullptr;
2002
2003 Value *NewSI = Builder.CreateSelect(SI->getCondition(), NewTV, NewFV, "", SI);
2004 return BinaryOperator::Create(Op.getOpcode(), NewSI, Input);
2005}
2006
2008 bool AllowMultipleUses) {
2009 unsigned NumPHIValues = PN->getNumIncomingValues();
2010 if (NumPHIValues == 0)
2011 return nullptr;
2012
2013 // We normally only transform phis with a single use. However, if a PHI has
2014 // multiple uses and they are all the same operation, we can fold *all* of the
2015 // uses into the PHI.
2016 bool OneUse = PN->hasOneUse();
2017 bool IdenticalUsers = false;
2018 if (!AllowMultipleUses && !OneUse) {
2019 // Walk the use list for the instruction, comparing them to I.
2020 for (Instruction *UI : PN->users()) {
2021 if (UI != &I && !I.isIdenticalTo(UI))
2022 return nullptr;
2023 }
2024 // Otherwise, we can replace *all* users with the new PHI we form.
2025 IdenticalUsers = true;
2026 }
2027
2028 // Check that all operands are phi-translatable.
2029 for (Value *Op : I.operands()) {
2030 if (Op == PN)
2031 continue;
2032
2033 // Non-instructions never require phi-translation.
2034 auto *I = dyn_cast<Instruction>(Op);
2035 if (!I)
2036 continue;
2037
2038 // Phi-translate can handle phi nodes in the same block.
2039 if (isa<PHINode>(I))
2040 if (I->getParent() == PN->getParent())
2041 continue;
2042
2043 // Operand dominates the block, no phi-translation necessary.
2044 if (DT.dominates(I, PN->getParent()))
2045 continue;
2046
2047 // Not phi-translatable, bail out.
2048 return nullptr;
2049 }
2050
2051 // Check to see whether the instruction can be folded into each phi operand.
2052 // If there is one operand that does not fold, remember the BB it is in.
2053 SmallVector<Value *> NewPhiValues;
2054 SmallVector<unsigned int> OpsToMoveUseToIncomingBB;
2055 bool SeenNonSimplifiedInVal = false;
2056 for (unsigned i = 0; i != NumPHIValues; ++i) {
2057 Value *InVal = PN->getIncomingValue(i);
2058 BasicBlock *InBB = PN->getIncomingBlock(i);
2059
2060 if (auto *NewVal = simplifyInstructionWithPHI(I, PN, InVal, InBB, DL, SQ)) {
2061 NewPhiValues.push_back(NewVal);
2062 continue;
2063 }
2064
2065 // Handle some cases that can't be fully simplified, but where we know that
2066 // the two instructions will fold into one.
2067 auto WillFold = [&]() {
2068 if (!InVal->hasUseList() || !InVal->hasOneUser())
2069 return false;
2070
2071 // icmp of ucmp/scmp with constant will fold to icmp.
2072 const APInt *Ignored;
2073 if (isa<CmpIntrinsic>(InVal) &&
2074 match(&I, m_ICmp(m_Specific(PN), m_APInt(Ignored))))
2075 return true;
2076
2077 // icmp eq zext(bool), 0 will fold to !bool.
2078 if (isa<ZExtInst>(InVal) &&
2079 cast<ZExtInst>(InVal)->getSrcTy()->isIntOrIntVectorTy(1) &&
2080 match(&I,
2082 return true;
2083
2084 return false;
2085 };
2086
2087 if (WillFold()) {
2088 OpsToMoveUseToIncomingBB.push_back(i);
2089 NewPhiValues.push_back(nullptr);
2090 continue;
2091 }
2092
2093 if (!OneUse && !IdenticalUsers)
2094 return nullptr;
2095
2096 if (SeenNonSimplifiedInVal)
2097 return nullptr; // More than one non-simplified value.
2098 SeenNonSimplifiedInVal = true;
2099
2100 // If there is exactly one non-simplified value, we can insert a copy of the
2101 // operation in that block. However, if this is a critical edge, we would
2102 // be inserting the computation on some other paths (e.g. inside a loop).
2103 // Only do this if the pred block is unconditionally branching into the phi
2104 // block. Also, make sure that the pred block is not dead code.
2106 if (!BI || !DT.isReachableFromEntry(InBB))
2107 return nullptr;
2108
2109 NewPhiValues.push_back(nullptr);
2110 OpsToMoveUseToIncomingBB.push_back(i);
2111
2112 // Do not push the operation across a loop backedge. This could result in
2113 // an infinite combine loop, and is generally non-profitable (especially
2114 // if the operation was originally outside the loop).
2115 if (isBackEdge(InBB, PN->getParent()))
2116 return nullptr;
2117 }
2118
2119 // Clone the instruction that uses the phi node and move it into the incoming
2120 // BB because we know that the next iteration of InstCombine will simplify it.
2122 for (auto OpIndex : OpsToMoveUseToIncomingBB) {
2123 Value *Op = PN->getIncomingValue(OpIndex);
2124 BasicBlock *OpBB = PN->getIncomingBlock(OpIndex);
2125
2126 Instruction *Clone = Clones.lookup(OpBB);
2127 if (!Clone) {
2128 Clone = I.clone();
2129 for (Use &U : Clone->operands()) {
2130 if (U == PN)
2131 U = Op;
2132 else
2133 U = U->DoPHITranslation(PN->getParent(), OpBB);
2134 }
2135 Clone = InsertNewInstBefore(Clone, OpBB->getTerminator()->getIterator());
2136 Clones.insert({OpBB, Clone});
2137 // We may have speculated the instruction.
2139 }
2140
2141 NewPhiValues[OpIndex] = Clone;
2142 }
2143
2144 // Okay, we can do the transformation: create the new PHI node.
2145 PHINode *NewPN = PHINode::Create(I.getType(), PN->getNumIncomingValues());
2146 InsertNewInstBefore(NewPN, PN->getIterator());
2147 NewPN->takeName(PN);
2148 NewPN->setDebugLoc(PN->getDebugLoc());
2149
2150 for (unsigned i = 0; i != NumPHIValues; ++i)
2151 NewPN->addIncoming(NewPhiValues[i], PN->getIncomingBlock(i));
2152
2153 if (IdenticalUsers) {
2154 // Collect and deduplicate users up-front to avoid iterator invalidation.
2156 for (Instruction *User : PN->users()) {
2157 if (User == &I)
2158 continue;
2159 ToReplace.insert(User);
2160 }
2161 for (Instruction *I : ToReplace) {
2162 replaceInstUsesWith(*I, NewPN);
2164 }
2165 OneUse = true;
2166 }
2167
2168 if (OneUse) {
2169 replaceAllDbgUsesWith(*PN, *NewPN, *PN, DT);
2170 }
2171 return replaceInstUsesWith(I, NewPN);
2172}
2173
2175 if (!BO.isAssociative())
2176 return nullptr;
2177
2178 // Find the interleaved binary ops.
2179 auto Opc = BO.getOpcode();
2180 auto *BO0 = dyn_cast<BinaryOperator>(BO.getOperand(0));
2181 auto *BO1 = dyn_cast<BinaryOperator>(BO.getOperand(1));
2182 if (!BO0 || !BO1 || !BO0->hasNUses(2) || !BO1->hasNUses(2) ||
2183 BO0->getOpcode() != Opc || BO1->getOpcode() != Opc ||
2184 !BO0->isAssociative() || !BO1->isAssociative() ||
2185 BO0->getParent() != BO1->getParent())
2186 return nullptr;
2187
2188 assert(BO.isCommutative() && BO0->isCommutative() && BO1->isCommutative() &&
2189 "Expected commutative instructions!");
2190
2191 // Find the matching phis, forming the recurrences.
2192 PHINode *PN0, *PN1;
2193 Value *Start0, *Step0, *Start1, *Step1;
2194 if (!matchSimpleRecurrence(BO0, PN0, Start0, Step0) || !PN0->hasOneUse() ||
2195 !matchSimpleRecurrence(BO1, PN1, Start1, Step1) || !PN1->hasOneUse() ||
2196 PN0->getParent() != PN1->getParent())
2197 return nullptr;
2198
2199 assert(PN0->getNumIncomingValues() == 2 && PN1->getNumIncomingValues() == 2 &&
2200 "Expected PHIs with two incoming values!");
2201
2202 // Convert the start and step values to constants.
2203 auto *Init0 = dyn_cast<Constant>(Start0);
2204 auto *Init1 = dyn_cast<Constant>(Start1);
2205 auto *C0 = dyn_cast<Constant>(Step0);
2206 auto *C1 = dyn_cast<Constant>(Step1);
2207 if (!Init0 || !Init1 || !C0 || !C1)
2208 return nullptr;
2209
2210 // Fold the recurrence constants.
2211 auto *Init = ConstantFoldBinaryInstruction(Opc, Init0, Init1);
2213 if (!Init || !C)
2214 return nullptr;
2215
2216 // Create the reduced PHI.
2217 auto *NewPN = PHINode::Create(PN0->getType(), PN0->getNumIncomingValues(),
2218 "reduced.phi");
2219
2220 // Create the new binary op.
2221 auto *NewBO = BinaryOperator::Create(Opc, NewPN, C);
2222 if (Opc == Instruction::FAdd || Opc == Instruction::FMul) {
2223 // Intersect FMF flags for FADD and FMUL.
2224 FastMathFlags Intersect = BO0->getFastMathFlags() &
2225 BO1->getFastMathFlags() & BO.getFastMathFlags();
2226 NewBO->setFastMathFlags(Intersect);
2227 } else {
2228 OverflowTracking Flags;
2229 Flags.AllKnownNonNegative = false;
2230 Flags.AllKnownNonZero = false;
2231 Flags.mergeFlags(*BO0);
2232 Flags.mergeFlags(*BO1);
2233 Flags.mergeFlags(BO);
2234 Flags.applyFlags(*NewBO);
2235 }
2236 NewBO->takeName(&BO);
2237
2238 for (unsigned I = 0, E = PN0->getNumIncomingValues(); I != E; ++I) {
2239 auto *V = PN0->getIncomingValue(I);
2240 auto *BB = PN0->getIncomingBlock(I);
2241 if (V == Init0) {
2242 assert(((PN1->getIncomingValue(0) == Init1 &&
2243 PN1->getIncomingBlock(0) == BB) ||
2244 (PN1->getIncomingValue(1) == Init1 &&
2245 PN1->getIncomingBlock(1) == BB)) &&
2246 "Invalid incoming block!");
2247 NewPN->addIncoming(Init, BB);
2248 } else if (V == BO0) {
2249 assert(((PN1->getIncomingValue(0) == BO1 &&
2250 PN1->getIncomingBlock(0) == BB) ||
2251 (PN1->getIncomingValue(1) == BO1 &&
2252 PN1->getIncomingBlock(1) == BB)) &&
2253 "Invalid incoming block!");
2254 NewPN->addIncoming(NewBO, BB);
2255 } else
2256 llvm_unreachable("Unexpected incoming value!");
2257 }
2258
2259 LLVM_DEBUG(dbgs() << " Combined " << *PN0 << "\n " << *BO0
2260 << "\n with " << *PN1 << "\n " << *BO1
2261 << '\n');
2262
2263 // Insert the new recurrence and remove the old (dead) ones.
2264 InsertNewInstWith(NewPN, PN0->getIterator());
2265 InsertNewInstWith(NewBO, BO0->getIterator());
2266
2273
2274 return replaceInstUsesWith(BO, NewBO);
2275}
2276
2278 // Attempt to fold binary operators whose operands are simple recurrences.
2279 if (auto *NewBO = foldBinopWithRecurrence(BO))
2280 return NewBO;
2281
2282 // TODO: This should be similar to the incoming values check in foldOpIntoPhi:
2283 // we are guarding against replicating the binop in >1 predecessor.
2284 // This could miss matching a phi with 2 constant incoming values.
2285 auto *Phi0 = dyn_cast<PHINode>(BO.getOperand(0));
2286 auto *Phi1 = dyn_cast<PHINode>(BO.getOperand(1));
2287 if (!Phi0 || !Phi1 || !Phi0->hasOneUse() || !Phi1->hasOneUse() ||
2288 Phi0->getNumOperands() != Phi1->getNumOperands())
2289 return nullptr;
2290
2291 // TODO: Remove the restriction for binop being in the same block as the phis.
2292 if (BO.getParent() != Phi0->getParent() ||
2293 BO.getParent() != Phi1->getParent())
2294 return nullptr;
2295
2296 // Fold if there is at least one specific constant value in phi0 or phi1's
2297 // incoming values that comes from the same block and this specific constant
2298 // value can be used to do optimization for specific binary operator.
2299 // For example:
2300 // %phi0 = phi i32 [0, %bb0], [%i, %bb1]
2301 // %phi1 = phi i32 [%j, %bb0], [0, %bb1]
2302 // %add = add i32 %phi0, %phi1
2303 // ==>
2304 // %add = phi i32 [%j, %bb0], [%i, %bb1]
2306 /*AllowRHSConstant*/ false);
2307 if (C) {
2308 SmallVector<Value *, 4> NewIncomingValues;
2309 auto CanFoldIncomingValuePair = [&](std::tuple<Use &, Use &> T) {
2310 auto &Phi0Use = std::get<0>(T);
2311 auto &Phi1Use = std::get<1>(T);
2312 if (Phi0->getIncomingBlock(Phi0Use) != Phi1->getIncomingBlock(Phi1Use))
2313 return false;
2314 Value *Phi0UseV = Phi0Use.get();
2315 Value *Phi1UseV = Phi1Use.get();
2316 if (Phi0UseV == C)
2317 NewIncomingValues.push_back(Phi1UseV);
2318 else if (Phi1UseV == C)
2319 NewIncomingValues.push_back(Phi0UseV);
2320 else
2321 return false;
2322 return true;
2323 };
2324
2325 if (all_of(zip(Phi0->operands(), Phi1->operands()),
2326 CanFoldIncomingValuePair)) {
2327 PHINode *NewPhi =
2328 PHINode::Create(Phi0->getType(), Phi0->getNumOperands());
2329 assert(NewIncomingValues.size() == Phi0->getNumOperands() &&
2330 "The number of collected incoming values should equal the number "
2331 "of the original PHINode operands!");
2332 for (unsigned I = 0; I < Phi0->getNumOperands(); I++)
2333 NewPhi->addIncoming(NewIncomingValues[I], Phi0->getIncomingBlock(I));
2334 return NewPhi;
2335 }
2336 }
2337
2338 if (Phi0->getNumOperands() != 2 || Phi1->getNumOperands() != 2)
2339 return nullptr;
2340
2341 // Match a pair of incoming constants for one of the predecessor blocks.
2342 BasicBlock *ConstBB, *OtherBB;
2343 Constant *C0, *C1;
2344 if (match(Phi0->getIncomingValue(0), m_ImmConstant(C0))) {
2345 ConstBB = Phi0->getIncomingBlock(0);
2346 OtherBB = Phi0->getIncomingBlock(1);
2347 } else if (match(Phi0->getIncomingValue(1), m_ImmConstant(C0))) {
2348 ConstBB = Phi0->getIncomingBlock(1);
2349 OtherBB = Phi0->getIncomingBlock(0);
2350 } else {
2351 return nullptr;
2352 }
2353 if (!match(Phi1->getIncomingValueForBlock(ConstBB), m_ImmConstant(C1)))
2354 return nullptr;
2355
2356 // The block that we are hoisting to must reach here unconditionally.
2357 // Otherwise, we could be speculatively executing an expensive or
2358 // non-speculative op.
2359 auto *PredBlockBranch = dyn_cast<UncondBrInst>(OtherBB->getTerminator());
2360 if (!PredBlockBranch || !DT.isReachableFromEntry(OtherBB))
2361 return nullptr;
2362
2363 // TODO: This check could be tightened to only apply to binops (div/rem) that
2364 // are not safe to speculatively execute. But that could allow hoisting
2365 // potentially expensive instructions (fdiv for example).
2366 for (auto BBIter = BO.getParent()->begin(); &*BBIter != &BO; ++BBIter)
2368 return nullptr;
2369
2370 // Fold constants for the predecessor block with constant incoming values.
2372 if (!NewC)
2373 return nullptr;
2374
2375 // Make a new binop in the predecessor block with the non-constant incoming
2376 // values.
2377 Builder.SetInsertPoint(PredBlockBranch);
2378 Value *NewBO = Builder.CreateBinOp(BO.getOpcode(),
2379 Phi0->getIncomingValueForBlock(OtherBB),
2380 Phi1->getIncomingValueForBlock(OtherBB));
2381 if (auto *NotFoldedNewBO = dyn_cast<BinaryOperator>(NewBO))
2382 NotFoldedNewBO->copyIRFlags(&BO);
2383
2384 // Replace the binop with a phi of the new values. The old phis are dead.
2385 PHINode *NewPhi = PHINode::Create(BO.getType(), 2);
2386 NewPhi->addIncoming(NewBO, OtherBB);
2387 NewPhi->addIncoming(NewC, ConstBB);
2388 return NewPhi;
2389}
2390
2392 auto TryFoldOperand = [&](unsigned OpIdx,
2393 bool IsOtherParamConst) -> Instruction * {
2394 if (auto *Sel = dyn_cast<SelectInst>(I.getOperand(OpIdx)))
2395 return FoldOpIntoSelect(I, Sel, false, !IsOtherParamConst);
2396 if (auto *PN = dyn_cast<PHINode>(I.getOperand(OpIdx)))
2397 return foldOpIntoPhi(I, PN);
2398 return nullptr;
2399 };
2400
2401 if (Instruction *NewI =
2402 TryFoldOperand(/*OpIdx=*/0, isa<Constant>(I.getOperand(1))))
2403 return NewI;
2404 return TryFoldOperand(/*OpIdx=*/1, isa<Constant>(I.getOperand(0)));
2405}
2406
2408 // If this GEP has only 0 indices, it is the same pointer as
2409 // Src. If Src is not a trivial GEP too, don't combine
2410 // the indices.
2411 if (GEP.hasAllZeroIndices() && !Src.hasAllZeroIndices() &&
2412 !Src.hasOneUse())
2413 return false;
2414 return true;
2415}
2416
2417/// Find a constant NewC that has property:
2418/// shuffle(NewC, poison, ShMask) = C
2419/// for lanes that select NewC. Lanes that select the poison operand are not
2420/// constrained.
2421/// Returns nullptr if such a constant does not exist e.g. ShMask=<0,0> C=<1,2>
2422///
2423/// A 1-to-1 mapping is not required. Example:
2424/// ShMask = <1,1,2,2> and C = <5,5,6,6> --> NewC = <poison,5,6,poison>
2426 VectorType *NewCTy) {
2427 if (isa<ScalableVectorType>(NewCTy)) {
2428 Constant *Splat = C->getSplatValue();
2429 if (!Splat)
2430 return nullptr;
2432 }
2433
2434 if (cast<FixedVectorType>(NewCTy)->getNumElements() >
2435 cast<FixedVectorType>(C->getType())->getNumElements())
2436 return nullptr;
2437
2438 unsigned NewCNumElts = cast<FixedVectorType>(NewCTy)->getNumElements();
2439 PoisonValue *PoisonScalar = PoisonValue::get(C->getType()->getScalarType());
2440 SmallVector<Constant *, 16> NewVecC(NewCNumElts, PoisonScalar);
2441 unsigned NumElts = cast<FixedVectorType>(C->getType())->getNumElements();
2442 for (unsigned I = 0; I < NumElts; ++I) {
2443 Constant *CElt = C->getAggregateElement(I);
2444 if (ShMask[I] >= 0) {
2445 int MaskElt = ShMask[I];
2446 if (MaskElt >= (int)NewCNumElts)
2447 continue;
2448
2449 Constant *NewCElt = NewVecC[MaskElt];
2450 // Bail out if:
2451 // 1. The constant vector contains a constant expression.
2452 // 2. The shuffle needs an element of the constant vector that can't
2453 // be mapped to a new constant vector.
2454 // 3. This is a widening shuffle that copies elements of V1 into the
2455 // extended elements (extending with poison is allowed).
2456 if (!CElt || (!isa<PoisonValue>(NewCElt) && NewCElt != CElt) ||
2457 I >= NewCNumElts)
2458 return nullptr;
2459 NewVecC[MaskElt] = CElt;
2460 }
2461 }
2462 return ConstantVector::get(NewVecC);
2463}
2464
2465// Get the result of `Vector Op Splat` (or Splat Op Vector if \p SplatLHS).
2467 Constant *Splat, bool SplatLHS,
2468 const DataLayout &DL) {
2469 ElementCount EC = cast<VectorType>(Vector->getType())->getElementCount();
2471 Constant *RHS = Vector;
2472 if (!SplatLHS)
2473 std::swap(LHS, RHS);
2474 return ConstantFoldBinaryOpOperands(Opcode, LHS, RHS, DL);
2475}
2476
2477template <Intrinsic::ID SpliceID>
2479 InstCombiner::BuilderTy &Builder) {
2480 Value *LHS = Inst.getOperand(0), *RHS = Inst.getOperand(1);
2481 auto CreateBinOpSplice = [&](Value *X, Value *Y, Value *Offset) {
2482 Value *V = Builder.CreateBinOp(Inst.getOpcode(), X, Y, Inst.getName());
2483 if (auto *BO = dyn_cast<BinaryOperator>(V))
2484 BO->copyIRFlags(&Inst);
2485 Module *M = Inst.getModule();
2486 Function *F = Intrinsic::getOrInsertDeclaration(M, SpliceID, V->getType());
2487 return CallInst::Create(F, {V, PoisonValue::get(V->getType()), Offset});
2488 };
2489 Value *V1, *V2, *Offset;
2490 if (match(LHS,
2492 // Op(splice(V1, poison, offset), splice(V2, poison, offset))
2493 // -> splice(Op(V1, V2), poison, offset)
2495 m_Specific(Offset))) &&
2496 (LHS->hasOneUse() || RHS->hasOneUse() ||
2497 (LHS == RHS && LHS->hasNUses(2))))
2498 return CreateBinOpSplice(V1, V2, Offset);
2499
2500 // Op(splice(V1, poison, offset), RHSSplat)
2501 // -> splice(Op(V1, RHSSplat), poison, offset)
2502 if (LHS->hasOneUse() && isSplatValue(RHS))
2503 return CreateBinOpSplice(V1, RHS, Offset);
2504 }
2505 // Op(LHSSplat, splice(V2, poison, offset))
2506 // -> splice(Op(LHSSplat, V2), poison, offset)
2507 else if (isSplatValue(LHS) &&
2509 m_Value(Offset)))))
2510 return CreateBinOpSplice(LHS, V2, Offset);
2511
2512 // TODO: Fold binops of the form
2513 // Op(splice(poison, V1, offset), splice(poison, V2, offset))
2514 // -> splice(poison, Op(V1, V2), offset)
2515
2516 return nullptr;
2517}
2518
2520 if (!isa<VectorType>(Inst.getType()))
2521 return nullptr;
2522
2523 BinaryOperator::BinaryOps Opcode = Inst.getOpcode();
2524 Value *LHS = Inst.getOperand(0), *RHS = Inst.getOperand(1);
2525 assert(cast<VectorType>(LHS->getType())->getElementCount() ==
2526 cast<VectorType>(Inst.getType())->getElementCount());
2527 assert(cast<VectorType>(RHS->getType())->getElementCount() ==
2528 cast<VectorType>(Inst.getType())->getElementCount());
2529
2530 auto foldConstantsThroughSubVectorInsertSplat =
2531 [&](Value *MaybeSubVector, Value *MaybeSplat,
2532 bool SplatLHS) -> Instruction * {
2533 Value *Idx;
2534 Constant *Splat, *SubVector, *Dest;
2535 if (!match(MaybeSplat, m_Splat(m_Constant(Splat))) ||
2536 !match(MaybeSubVector,
2537 m_VectorInsert(m_Constant(Dest), m_Constant(SubVector),
2538 m_Value(Idx))))
2539 return nullptr;
2540 SubVector =
2541 constantFoldBinOpWithSplat(Opcode, SubVector, Splat, SplatLHS, DL);
2542 Dest = constantFoldBinOpWithSplat(Opcode, Dest, Splat, SplatLHS, DL);
2543 if (!SubVector || !Dest)
2544 return nullptr;
2545 auto *InsertVector =
2546 Builder.CreateInsertVector(Dest->getType(), Dest, SubVector, Idx);
2547 return replaceInstUsesWith(Inst, InsertVector);
2548 };
2549
2550 // If one operand is a constant splat and the other operand is a
2551 // `vector.insert` where both the destination and subvector are constant,
2552 // apply the operation to both the destination and subvector, returning a new
2553 // constant `vector.insert`. This helps constant folding for scalable vectors.
2554 if (Instruction *Folded = foldConstantsThroughSubVectorInsertSplat(
2555 /*MaybeSubVector=*/LHS, /*MaybeSplat=*/RHS, /*SplatLHS=*/false))
2556 return Folded;
2557 if (Instruction *Folded = foldConstantsThroughSubVectorInsertSplat(
2558 /*MaybeSubVector=*/RHS, /*MaybeSplat=*/LHS, /*SplatLHS=*/true))
2559 return Folded;
2560
2561 auto createBinOpReverse = [&](Value *X, Value *Y) {
2562 Value *V = Builder.CreateBinOp(Opcode, X, Y, Inst.getName());
2563 if (auto *BO = dyn_cast<BinaryOperator>(V))
2564 BO->copyIRFlags(&Inst);
2565 Module *M = Inst.getModule();
2567 M, Intrinsic::vector_reverse, V->getType());
2568 return CallInst::Create(F, V);
2569 };
2570
2571 // NOTE: Reverse shuffles don't require the speculative execution protection
2572 // below because they don't affect which lanes take part in the computation.
2573
2574 Value *V1, *V2;
2575 if (match(LHS, m_VecReverse(m_Value(V1)))) {
2576 // Op(rev(V1), rev(V2)) -> rev(Op(V1, V2))
2577 if (match(RHS, m_VecReverse(m_Value(V2))) &&
2578 (LHS->hasOneUse() || RHS->hasOneUse() ||
2579 (LHS == RHS && LHS->hasNUses(2))))
2580 return createBinOpReverse(V1, V2);
2581
2582 // Op(rev(V1), RHSSplat)) -> rev(Op(V1, RHSSplat))
2583 if (LHS->hasOneUse() && isSplatValue(RHS))
2584 return createBinOpReverse(V1, RHS);
2585 }
2586 // Op(LHSSplat, rev(V2)) -> rev(Op(LHSSplat, V2))
2587 else if (isSplatValue(LHS) && match(RHS, m_OneUse(m_VecReverse(m_Value(V2)))))
2588 return createBinOpReverse(LHS, V2);
2589
2590 auto createBinOpVPReverse = [&](Value *X, Value *Y, Value *EVL) {
2591 Value *V = Builder.CreateBinOp(Opcode, X, Y, Inst.getName());
2592 if (auto *BO = dyn_cast<BinaryOperator>(V))
2593 BO->copyIRFlags(&Inst);
2594
2595 ElementCount EC = cast<VectorType>(V->getType())->getElementCount();
2596 Value *AllTrueMask = Builder.CreateVectorSplat(EC, Builder.getTrue());
2597 Module *M = Inst.getModule();
2599 M, Intrinsic::experimental_vp_reverse, V->getType());
2600 return CallInst::Create(F, {V, AllTrueMask, EVL});
2601 };
2602
2603 Value *EVL;
2605 m_Value(V1), m_AllOnes(), m_Value(EVL)))) {
2606 // Op(rev(V1), rev(V2)) -> rev(Op(V1, V2))
2608 m_Value(V2), m_AllOnes(), m_Specific(EVL))) &&
2609 (LHS->hasOneUse() || RHS->hasOneUse() ||
2610 (LHS == RHS && LHS->hasNUses(2))))
2611 return createBinOpVPReverse(V1, V2, EVL);
2612
2613 // Op(rev(V1), RHSSplat)) -> rev(Op(V1, RHSSplat))
2614 if (LHS->hasOneUse() && isSplatValue(RHS))
2615 return createBinOpVPReverse(V1, RHS, EVL);
2616 }
2617 // Op(LHSSplat, rev(V2)) -> rev(Op(LHSSplat, V2))
2618 else if (isSplatValue(LHS) &&
2620 m_Value(V2), m_AllOnes(), m_Value(EVL))))
2621 return createBinOpVPReverse(LHS, V2, EVL);
2622
2623 if (Instruction *Folded =
2625 return Folded;
2626 if (Instruction *Folded =
2628 return Folded;
2629
2630 // It may not be safe to reorder shuffles and things like div, urem, etc.
2631 // because we may trap when executing those ops on unknown vector elements.
2632 // See PR20059.
2634 return nullptr;
2635
2636 auto createBinOpShuffle = [&](Value *X, Value *Y, ArrayRef<int> M) {
2637 Value *XY = Builder.CreateBinOp(Opcode, X, Y);
2638 if (auto *BO = dyn_cast<BinaryOperator>(XY))
2639 BO->copyIRFlags(&Inst);
2640 return new ShuffleVectorInst(XY, M);
2641 };
2642
2643 // If both arguments of the binary operation are shuffles that use the same
2644 // mask and shuffle within a single vector, move the shuffle after the binop.
2645 ArrayRef<int> Mask;
2646 if (match(LHS, m_Shuffle(m_Value(V1), m_Poison(), m_Mask(Mask))) &&
2647 match(RHS, m_Shuffle(m_Value(V2), m_Poison(), m_SpecificMask(Mask))) &&
2648 Inst.getType() == V1->getType() && V1->getType() == V2->getType() &&
2649 (LHS->hasOneUse() || RHS->hasOneUse() || LHS == RHS)) {
2650 // Op(shuffle(V1, Mask), shuffle(V2, Mask)) -> shuffle(Op(V1, V2), Mask)
2651 return createBinOpShuffle(V1, V2, Mask);
2652 }
2653
2654 // If both arguments of a commutative binop are select-shuffles that use the
2655 // same mask with commuted operands, the shuffles are unnecessary.
2656 if (Inst.isCommutative() &&
2657 match(LHS, m_Shuffle(m_Value(V1), m_Value(V2), m_Mask(Mask))) &&
2658 match(RHS,
2660 auto *LShuf = cast<ShuffleVectorInst>(LHS);
2661 auto *RShuf = cast<ShuffleVectorInst>(RHS);
2662 // TODO: Allow shuffles that contain undefs in the mask?
2663 // That is legal, but it reduces undef knowledge.
2664 // TODO: Allow arbitrary shuffles by shuffling after binop?
2665 // That might be legal, but we have to deal with poison.
2666 if (LShuf->isSelect() &&
2667 !is_contained(LShuf->getShuffleMask(), PoisonMaskElem) &&
2668 RShuf->isSelect() &&
2669 !is_contained(RShuf->getShuffleMask(), PoisonMaskElem)) {
2670 // Example:
2671 // LHS = shuffle V1, V2, <0, 5, 6, 3>
2672 // RHS = shuffle V2, V1, <0, 5, 6, 3>
2673 // LHS + RHS --> (V10+V20, V21+V11, V22+V12, V13+V23) --> V1 + V2
2674 Instruction *NewBO = BinaryOperator::Create(Opcode, V1, V2);
2675 NewBO->copyIRFlags(&Inst);
2676 return NewBO;
2677 }
2678 }
2679
2680 // If one argument is a shuffle within one vector and the other is a constant,
2681 // try moving the shuffle after the binary operation. This canonicalization
2682 // intends to move shuffles closer to other shuffles and binops closer to
2683 // other binops, so they can be folded. It may also enable demanded elements
2684 // transforms.
2685 Constant *C;
2687 m_Mask(Mask))),
2688 m_ImmConstant(C)))) {
2689 assert(Inst.getType()->getScalarType() == V1->getType()->getScalarType() &&
2690 "Shuffle should not change scalar type");
2691
2692 bool ConstOp1 = isa<Constant>(RHS);
2693 if (Constant *NewC =
2694 unshuffleConstant(Mask, C, cast<VectorType>(V1->getType()))) {
2695 // For fixed vectors, lanes of NewC not used by the shuffle will be poison
2696 // which will cause UB for div/rem. Mask them with a safe constant.
2697 if (isa<FixedVectorType>(V1->getType()) && Inst.isIntDivRem())
2698 NewC = getSafeVectorConstantForBinop(Opcode, NewC, ConstOp1);
2699
2700 // Op(shuffle(V1, Mask), C) -> shuffle(Op(V1, NewC), Mask)
2701 // Op(C, shuffle(V1, Mask)) -> shuffle(Op(NewC, V1), Mask)
2702 Value *NewLHS = ConstOp1 ? V1 : NewC;
2703 Value *NewRHS = ConstOp1 ? NewC : V1;
2704 return createBinOpShuffle(NewLHS, NewRHS, Mask);
2705 }
2706 }
2707
2708 // Try to reassociate to sink a splat shuffle after a binary operation.
2709 if (Inst.isAssociative() && Inst.isCommutative()) {
2710 // Canonicalize shuffle operand as LHS.
2711 if (isa<ShuffleVectorInst>(RHS))
2712 std::swap(LHS, RHS);
2713
2714 Value *X;
2715 ArrayRef<int> MaskC;
2716 int SplatIndex;
2717 Value *Y, *OtherOp;
2718 if (!match(LHS,
2719 m_OneUse(m_Shuffle(m_Value(X), m_Undef(), m_Mask(MaskC)))) ||
2720 !match(MaskC, m_SplatOrPoisonMask(SplatIndex)) ||
2721 X->getType() != Inst.getType() ||
2722 !match(RHS, m_OneUse(m_BinOp(Opcode, m_Value(Y), m_Value(OtherOp)))))
2723 return nullptr;
2724
2725 // FIXME: This may not be safe if the analysis allows undef elements. By
2726 // moving 'Y' before the splat shuffle, we are implicitly assuming
2727 // that it is not undef/poison at the splat index.
2728 if (isSplatValue(OtherOp, SplatIndex)) {
2729 std::swap(Y, OtherOp);
2730 } else if (!isSplatValue(Y, SplatIndex)) {
2731 return nullptr;
2732 }
2733
2734 // X and Y are splatted values, so perform the binary operation on those
2735 // values followed by a splat followed by the 2nd binary operation:
2736 // bo (splat X), (bo Y, OtherOp) --> bo (splat (bo X, Y)), OtherOp
2737 Value *NewBO = Builder.CreateBinOp(Opcode, X, Y);
2738 SmallVector<int, 8> NewMask(MaskC.size(), SplatIndex);
2739 Value *NewSplat = Builder.CreateShuffleVector(NewBO, NewMask);
2740 Instruction *R = BinaryOperator::Create(Opcode, NewSplat, OtherOp);
2741
2742 // Intersect FMF on both new binops. Other (poison-generating) flags are
2743 // dropped to be safe.
2744 if (isa<FPMathOperator>(R)) {
2745 R->copyFastMathFlags(&Inst);
2746 R->andIRFlags(RHS);
2747 }
2748 if (auto *NewInstBO = dyn_cast<BinaryOperator>(NewBO))
2749 NewInstBO->copyIRFlags(R);
2750 return R;
2751 }
2752
2753 return nullptr;
2754}
2755
2756/// Try to narrow the width of a binop if at least 1 operand is an extend of
2757/// of a value. This requires a potentially expensive known bits check to make
2758/// sure the narrow op does not overflow.
2759Instruction *InstCombinerImpl::narrowMathIfNoOverflow(BinaryOperator &BO) {
2760 // We need at least one extended operand.
2761 Value *Op0 = BO.getOperand(0), *Op1 = BO.getOperand(1);
2762
2763 // If this is a sub, we swap the operands since we always want an extension
2764 // on the RHS. The LHS can be an extension or a constant.
2765 if (BO.getOpcode() == Instruction::Sub)
2766 std::swap(Op0, Op1);
2767
2768 Value *X;
2769 bool IsSext = match(Op0, m_SExt(m_Value(X)));
2770 if (!IsSext && !match(Op0, m_ZExt(m_Value(X))))
2771 return nullptr;
2772
2773 // If both operands are the same extension from the same source type and we
2774 // can eliminate at least one (hasOneUse), this might work.
2775 CastInst::CastOps CastOpc = IsSext ? Instruction::SExt : Instruction::ZExt;
2776 Value *Y;
2777 if (!(match(Op1, m_ZExtOrSExt(m_Value(Y))) && X->getType() == Y->getType() &&
2778 cast<Operator>(Op1)->getOpcode() == CastOpc &&
2779 (Op0->hasOneUse() || Op1->hasOneUse()))) {
2780 // If that did not match, see if we have a suitable constant operand.
2781 // Truncating and extending must produce the same constant.
2782 Constant *WideC;
2783 if (!Op0->hasOneUse() || !match(Op1, m_Constant(WideC)))
2784 return nullptr;
2785 Constant *NarrowC = getLosslessInvCast(WideC, X->getType(), CastOpc, DL);
2786 if (!NarrowC)
2787 return nullptr;
2788 Y = NarrowC;
2789 }
2790
2791 // Swap back now that we found our operands.
2792 if (BO.getOpcode() == Instruction::Sub)
2793 std::swap(X, Y);
2794
2795 // Both operands have narrow versions. Last step: the math must not overflow
2796 // in the narrow width.
2797 if (!willNotOverflow(BO.getOpcode(), X, Y, BO, IsSext))
2798 return nullptr;
2799
2800 // bo (ext X), (ext Y) --> ext (bo X, Y)
2801 // bo (ext X), C --> ext (bo X, C')
2802 Value *NarrowBO = Builder.CreateBinOp(BO.getOpcode(), X, Y, "narrow");
2803 if (auto *NewBinOp = dyn_cast<BinaryOperator>(NarrowBO)) {
2804 if (IsSext)
2805 NewBinOp->setHasNoSignedWrap();
2806 else
2807 NewBinOp->setHasNoUnsignedWrap();
2808 }
2809 return CastInst::Create(CastOpc, NarrowBO, BO.getType());
2810}
2811
2812/// Determine nowrap flags for (gep (gep p, x), y) to (gep p, (x + y))
2813/// transform.
2818
2819/// Thread a GEP operation with constant indices through the constant true/false
2820/// arms of a select.
2822 InstCombiner::BuilderTy &Builder) {
2823 if (!GEP.hasAllConstantIndices())
2824 return nullptr;
2825
2826 Instruction *Sel;
2827 Value *Cond;
2828 Constant *TrueC, *FalseC;
2829 if (!match(GEP.getPointerOperand(), m_OneUse(m_Instruction(Sel))) ||
2830 !match(Sel,
2831 m_Select(m_Value(Cond), m_Constant(TrueC), m_Constant(FalseC))))
2832 return nullptr;
2833
2834 // gep (select Cond, TrueC, FalseC), IndexC --> select Cond, TrueC', FalseC'
2835 // Propagate 'inbounds' and metadata from existing instructions.
2836 // Note: using IRBuilder to create the constants for efficiency.
2837 SmallVector<Value *, 4> IndexC(GEP.indices());
2838 GEPNoWrapFlags NW = GEP.getNoWrapFlags();
2839 Type *Ty = GEP.getSourceElementType();
2840 Value *NewTrueC = Builder.CreateGEP(Ty, TrueC, IndexC, "", NW);
2841 Value *NewFalseC = Builder.CreateGEP(Ty, FalseC, IndexC, "", NW);
2842 return SelectInst::Create(Cond, NewTrueC, NewFalseC, "", nullptr, Sel);
2843}
2844
2845// Canonicalization:
2846// gep T, (gep i8, base, C1), (Index + C2) into
2847// gep T, (gep i8, base, C1 + C2 * sizeof(T)), Index
2849 GEPOperator *Src,
2850 InstCombinerImpl &IC) {
2851 if (GEP.getNumIndices() != 1)
2852 return nullptr;
2853 auto &DL = IC.getDataLayout();
2854 Value *Base;
2855 const APInt *C1;
2856 if (!match(Src, m_PtrAdd(DL, m_Value(Base), m_APInt(C1))))
2857 return nullptr;
2858 Value *VarIndex;
2859 const APInt *C2;
2860 Type *PtrTy = Src->getType()->getScalarType();
2861 unsigned IndexSizeInBits = DL.getIndexTypeSizeInBits(PtrTy);
2862 if (!match(GEP.getOperand(1), m_AddLike(m_Value(VarIndex), m_APInt(C2))))
2863 return nullptr;
2864 if (C2->getBitWidth() != IndexSizeInBits)
2865 return nullptr;
2866 Type *BaseType = GEP.getSourceElementType();
2868 return nullptr;
2869 APInt TypeSize(IndexSizeInBits, DL.getTypeAllocSize(BaseType));
2870 APInt NewOffset = TypeSize * *C2 + *C1;
2871 if (NewOffset.isZero() ||
2872 (Src->hasOneUse() && GEP.getOperand(1)->hasOneUse())) {
2874 if (GEP.hasNoUnsignedWrap() &&
2875 cast<GEPOperator>(Src)->hasNoUnsignedWrap() &&
2876 match(GEP.getOperand(1), m_NUWAddLike(m_Value(), m_Value()))) {
2878 if (GEP.isInBounds() && cast<GEPOperator>(Src)->isInBounds())
2879 Flags |= GEPNoWrapFlags::inBounds();
2880 }
2881
2882 Value *GEPConst =
2883 IC.Builder.CreatePtrAdd(Base, IC.Builder.getInt(NewOffset), "", Flags);
2884 return GetElementPtrInst::Create(BaseType, GEPConst, VarIndex, Flags);
2885 }
2886
2887 return nullptr;
2888}
2889
2890/// Combine constant offsets separated by variable offsets.
2891/// ptradd (ptradd (ptradd p, C1), x), C2 -> ptradd (ptradd p, x), C1+C2
2893 InstCombinerImpl &IC) {
2894 if (!GEP.hasAllConstantIndices())
2895 return nullptr;
2896
2899 auto *InnerGEP = dyn_cast<GetElementPtrInst>(GEP.getPointerOperand());
2900 while (true) {
2901 if (!InnerGEP)
2902 return nullptr;
2903
2904 NW = NW.intersectForReassociate(InnerGEP->getNoWrapFlags());
2905 if (InnerGEP->hasAllConstantIndices())
2906 break;
2907
2908 if (!InnerGEP->hasOneUse())
2909 return nullptr;
2910
2911 Skipped.push_back(InnerGEP);
2912 InnerGEP = dyn_cast<GetElementPtrInst>(InnerGEP->getPointerOperand());
2913 }
2914
2915 // The two constant offset GEPs are directly adjacent: Let normal offset
2916 // merging handle it.
2917 if (Skipped.empty())
2918 return nullptr;
2919
2920 // FIXME: This one-use check is not strictly necessary. Consider relaxing it
2921 // if profitable.
2922 if (!InnerGEP->hasOneUse())
2923 return nullptr;
2924
2925 // Don't bother with vector splats.
2926 Type *Ty = GEP.getType();
2927 if (InnerGEP->getType() != Ty)
2928 return nullptr;
2929
2930 const DataLayout &DL = IC.getDataLayout();
2931 APInt Offset(DL.getIndexTypeSizeInBits(Ty), 0);
2932 if (!GEP.accumulateConstantOffset(DL, Offset) ||
2933 !InnerGEP->accumulateConstantOffset(DL, Offset))
2934 return nullptr;
2935
2936 IC.replaceOperand(*Skipped.back(), 0, InnerGEP->getPointerOperand());
2937 for (GetElementPtrInst *SkippedGEP : Skipped)
2938 SkippedGEP->setNoWrapFlags(NW);
2939
2940 return IC.replaceInstUsesWith(
2941 GEP,
2942 IC.Builder.CreatePtrAdd(Skipped.front(), IC.Builder.getInt(Offset), "",
2943 NW.intersectForOffsetAdd(GEP.getNoWrapFlags())));
2944}
2945
2947 GEPOperator *Src) {
2948 // Combine Indices - If the source pointer to this getelementptr instruction
2949 // is a getelementptr instruction with matching element type, combine the
2950 // indices of the two getelementptr instructions into a single instruction.
2951 if (!shouldMergeGEPs(*cast<GEPOperator>(&GEP), *Src))
2952 return nullptr;
2953
2954 if (auto *I = canonicalizeGEPOfConstGEPI8(GEP, Src, *this))
2955 return I;
2956
2957 if (auto *I = combineConstantOffsets(GEP, *this))
2958 return I;
2959
2960 if (Src->getResultElementType() != GEP.getSourceElementType())
2961 return nullptr;
2962
2963 // Fold chained GEP with constant base into single GEP:
2964 // gep i8, (gep i8, %base, C1), (select Cond, C2, C3)
2965 // -> gep i8, %base, (select Cond, C1+C2, C1+C3)
2966 if (Src->hasOneUse() && GEP.getNumIndices() == 1 &&
2967 Src->getNumIndices() == 1) {
2968 Value *SrcIdx = *Src->idx_begin();
2969 Value *GEPIdx = *GEP.idx_begin();
2970 const APInt *ConstOffset, *TrueVal, *FalseVal;
2971 Value *Cond;
2972
2973 if ((match(SrcIdx, m_APInt(ConstOffset)) &&
2974 match(GEPIdx,
2975 m_Select(m_Value(Cond), m_APInt(TrueVal), m_APInt(FalseVal)))) ||
2976 (match(GEPIdx, m_APInt(ConstOffset)) &&
2977 match(SrcIdx,
2978 m_Select(m_Value(Cond), m_APInt(TrueVal), m_APInt(FalseVal))))) {
2979 auto *Select = isa<SelectInst>(GEPIdx) ? cast<SelectInst>(GEPIdx)
2980 : cast<SelectInst>(SrcIdx);
2981
2982 // Make sure the select has only one use.
2983 if (!Select->hasOneUse())
2984 return nullptr;
2985
2986 if (TrueVal->getBitWidth() != ConstOffset->getBitWidth() ||
2987 FalseVal->getBitWidth() != ConstOffset->getBitWidth())
2988 return nullptr;
2989
2990 APInt NewTrueVal = *ConstOffset + *TrueVal;
2991 APInt NewFalseVal = *ConstOffset + *FalseVal;
2992 Constant *NewTrue = ConstantInt::get(Select->getType(), NewTrueVal);
2993 Constant *NewFalse = ConstantInt::get(Select->getType(), NewFalseVal);
2994 Value *NewSelect =
2995 Builder.CreateSelect(Cond, NewTrue, NewFalse, /*Name=*/"",
2996 /*MDFrom=*/Select);
2997 GEPNoWrapFlags Flags =
2999 return replaceInstUsesWith(GEP,
3000 Builder.CreateGEP(GEP.getResultElementType(),
3001 Src->getPointerOperand(),
3002 NewSelect, "", Flags));
3003 }
3004 }
3005
3006 // Find out whether the last index in the source GEP is a sequential idx.
3007 bool EndsWithSequential = false;
3008 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
3009 I != E; ++I)
3010 EndsWithSequential = I.isSequential();
3011 if (!EndsWithSequential)
3012 return nullptr;
3013
3014 // Replace: gep (gep %P, long B), long A, ...
3015 // With: T = long A+B; gep %P, T, ...
3016 Value *SO1 = Src->getOperand(Src->getNumOperands() - 1);
3017 Value *GO1 = GEP.getOperand(1);
3018
3019 // If they aren't the same type, then the input hasn't been processed
3020 // by the loop above yet (which canonicalizes sequential index types to
3021 // intptr_t). Just avoid transforming this until the input has been
3022 // normalized.
3023 if (SO1->getType() != GO1->getType())
3024 return nullptr;
3025
3026 Value *Sum =
3027 simplifyAddInst(GO1, SO1, false, false, SQ.getWithInstruction(&GEP));
3028 // Only do the combine when we are sure the cost after the
3029 // merge is never more than that before the merge.
3030 if (Sum == nullptr)
3031 return nullptr;
3032
3034 Indices.append(Src->op_begin() + 1, Src->op_end() - 1);
3035 Indices.push_back(Sum);
3036 Indices.append(GEP.op_begin() + 2, GEP.op_end());
3037
3038 // Don't create GEPs with more than one non-zero index.
3039 unsigned NumNonZeroIndices = count_if(Indices, [](Value *Idx) {
3040 auto *C = dyn_cast<Constant>(Idx);
3041 return !C || !C->isNullValue();
3042 });
3043 if (NumNonZeroIndices > 1)
3044 return nullptr;
3045
3046 return replaceInstUsesWith(
3047 GEP, Builder.CreateGEP(
3048 Src->getSourceElementType(), Src->getOperand(0), Indices, "",
3050}
3051
3054 bool &DoesConsume, unsigned Depth) {
3055 static Value *const NonNull = reinterpret_cast<Value *>(uintptr_t(1));
3056 // ~(~(X)) -> X.
3057 Value *A, *B;
3058 if (match(V, m_Not(m_Value(A)))) {
3059 DoesConsume = true;
3060 return A;
3061 }
3062
3063 Constant *C;
3064 // Constants can be considered to be not'ed values.
3065 if (match(V, m_ImmConstant(C)))
3066 return ConstantExpr::getNot(C);
3067
3069 return nullptr;
3070
3071 // The rest of the cases require that we invert all uses so don't bother
3072 // doing the analysis if we know we can't use the result.
3073 if (!WillInvertAllUses)
3074 return nullptr;
3075
3076 // Compares can be inverted if all of their uses are being modified to use
3077 // the ~V.
3078 if (auto *I = dyn_cast<CmpInst>(V)) {
3079 if (Builder != nullptr)
3080 return Builder->CreateCmp(I->getInversePredicate(), I->getOperand(0),
3081 I->getOperand(1));
3082 return NonNull;
3083 }
3084
3085 // If `V` is of the form `A + B` then `-1 - V` can be folded into
3086 // `(-1 - B) - A` if we are willing to invert all of the uses.
3087 if (match(V, m_Add(m_Value(A), m_Value(B)))) {
3088 if (auto *BV = getFreelyInvertedImpl(B, B->hasOneUse(), Builder,
3089 DoesConsume, Depth))
3090 return Builder ? Builder->CreateSub(BV, A) : NonNull;
3091 if (auto *AV = getFreelyInvertedImpl(A, A->hasOneUse(), Builder,
3092 DoesConsume, Depth))
3093 return Builder ? Builder->CreateSub(AV, B) : NonNull;
3094 return nullptr;
3095 }
3096
3097 // If `V` is of the form `A ^ ~B` then `~(A ^ ~B)` can be folded
3098 // into `A ^ B` if we are willing to invert all of the uses.
3099 if (match(V, m_Xor(m_Value(A), m_Value(B)))) {
3100 if (auto *BV = getFreelyInvertedImpl(B, B->hasOneUse(), Builder,
3101 DoesConsume, Depth))
3102 return Builder ? Builder->CreateXor(A, BV) : NonNull;
3103 if (auto *AV = getFreelyInvertedImpl(A, A->hasOneUse(), Builder,
3104 DoesConsume, Depth))
3105 return Builder ? Builder->CreateXor(AV, B) : NonNull;
3106 return nullptr;
3107 }
3108
3109 // If `V` is of the form `B - A` then `-1 - V` can be folded into
3110 // `A + (-1 - B)` if we are willing to invert all of the uses.
3111 if (match(V, m_Sub(m_Value(A), m_Value(B)))) {
3112 if (auto *AV = getFreelyInvertedImpl(A, A->hasOneUse(), Builder,
3113 DoesConsume, Depth))
3114 return Builder ? Builder->CreateAdd(AV, B) : NonNull;
3115 return nullptr;
3116 }
3117
3118 // If `V` is of the form `(~A) s>> B` then `~((~A) s>> B)` can be folded
3119 // into `A s>> B` if we are willing to invert all of the uses.
3120 if (match(V, m_AShr(m_Value(A), m_Value(B)))) {
3121 if (auto *AV = getFreelyInvertedImpl(A, A->hasOneUse(), Builder,
3122 DoesConsume, Depth))
3123 return Builder ? Builder->CreateAShr(AV, B) : NonNull;
3124 return nullptr;
3125 }
3126
3127 Value *Cond;
3128 // LogicOps are special in that we canonicalize them at the cost of an
3129 // instruction.
3130 bool IsSelect = match(V, m_Select(m_Value(Cond), m_Value(A), m_Value(B))) &&
3132 // Selects/min/max with invertible operands are freely invertible
3133 if (IsSelect || match(V, m_MaxOrMin(m_Value(A), m_Value(B)))) {
3134 bool LocalDoesConsume = DoesConsume;
3135 if (!getFreelyInvertedImpl(B, B->hasOneUse(), /*Builder*/ nullptr,
3136 LocalDoesConsume, Depth))
3137 return nullptr;
3138 if (Value *NotA = getFreelyInvertedImpl(A, A->hasOneUse(), Builder,
3139 LocalDoesConsume, Depth)) {
3140 DoesConsume = LocalDoesConsume;
3141 if (Builder != nullptr) {
3142 Value *NotB = getFreelyInvertedImpl(B, B->hasOneUse(), Builder,
3143 DoesConsume, Depth);
3144 assert(NotB != nullptr &&
3145 "Unable to build inverted value for known freely invertable op");
3146 if (auto *II = dyn_cast<IntrinsicInst>(V))
3147 return Builder->CreateBinaryIntrinsic(
3148 getInverseMinMaxIntrinsic(II->getIntrinsicID()), NotA, NotB);
3149 return Builder->CreateSelect(Cond, NotA, NotB, "",
3151 }
3152 return NonNull;
3153 }
3154 }
3155
3156 if (PHINode *PN = dyn_cast<PHINode>(V)) {
3157 bool LocalDoesConsume = DoesConsume;
3159 for (Use &U : PN->operands()) {
3160 BasicBlock *IncomingBlock = PN->getIncomingBlock(U);
3161 Value *NewIncomingVal = getFreelyInvertedImpl(
3162 U.get(), /*WillInvertAllUses=*/false,
3163 /*Builder=*/nullptr, LocalDoesConsume, MaxAnalysisRecursionDepth - 1);
3164 if (NewIncomingVal == nullptr)
3165 return nullptr;
3166 // Make sure that we can safely erase the original PHI node.
3167 if (NewIncomingVal == V)
3168 return nullptr;
3169 if (Builder != nullptr)
3170 IncomingValues.emplace_back(NewIncomingVal, IncomingBlock);
3171 }
3172
3173 DoesConsume = LocalDoesConsume;
3174 if (Builder != nullptr) {
3176 Builder->SetInsertPoint(PN);
3177 PHINode *NewPN =
3178 Builder->CreatePHI(PN->getType(), PN->getNumIncomingValues());
3179 for (auto [Val, Pred] : IncomingValues)
3180 NewPN->addIncoming(Val, Pred);
3181 return NewPN;
3182 }
3183 return NonNull;
3184 }
3185
3186 if (match(V, m_SExtLike(m_Value(A)))) {
3187 if (auto *AV = getFreelyInvertedImpl(A, A->hasOneUse(), Builder,
3188 DoesConsume, Depth))
3189 return Builder ? Builder->CreateSExt(AV, V->getType()) : NonNull;
3190 return nullptr;
3191 }
3192
3193 if (match(V, m_Trunc(m_Value(A)))) {
3194 if (auto *AV = getFreelyInvertedImpl(A, A->hasOneUse(), Builder,
3195 DoesConsume, Depth))
3196 return Builder ? Builder->CreateTrunc(AV, V->getType()) : NonNull;
3197 return nullptr;
3198 }
3199
3200 // De Morgan's Laws:
3201 // (~(A | B)) -> (~A & ~B)
3202 // (~(A & B)) -> (~A | ~B)
3203 auto TryInvertAndOrUsingDeMorgan = [&](Instruction::BinaryOps Opcode,
3204 bool IsLogical, Value *A,
3205 Value *B) -> Value * {
3206 bool LocalDoesConsume = DoesConsume;
3207 if (!getFreelyInvertedImpl(B, B->hasOneUse(), /*Builder=*/nullptr,
3208 LocalDoesConsume, Depth))
3209 return nullptr;
3210 if (auto *NotA = getFreelyInvertedImpl(A, A->hasOneUse(), Builder,
3211 LocalDoesConsume, Depth)) {
3212 auto *NotB = getFreelyInvertedImpl(B, B->hasOneUse(), Builder,
3213 LocalDoesConsume, Depth);
3214 DoesConsume = LocalDoesConsume;
3215 if (!Builder)
3216 return NonNull;
3217 if (IsLogical) {
3218 Value *InvertedLogicalOp = Builder->CreateLogicalOp(
3219 Opcode, NotA, NotB, "",
3221 if (auto *SI = dyn_cast<SelectInst>(InvertedLogicalOp))
3222 SI->swapProfMetadata();
3223 return InvertedLogicalOp;
3224 }
3225 return Builder->CreateBinOp(Opcode, NotA, NotB);
3226 }
3227
3228 return nullptr;
3229 };
3230
3231 if (match(V, m_Or(m_Value(A), m_Value(B))))
3232 return TryInvertAndOrUsingDeMorgan(Instruction::And, /*IsLogical=*/false, A,
3233 B);
3234
3235 if (match(V, m_And(m_Value(A), m_Value(B))))
3236 return TryInvertAndOrUsingDeMorgan(Instruction::Or, /*IsLogical=*/false, A,
3237 B);
3238
3239 if (match(V, m_LogicalOr(m_Value(A), m_Value(B))))
3240 return TryInvertAndOrUsingDeMorgan(Instruction::And, /*IsLogical=*/true, A,
3241 B);
3242
3243 if (match(V, m_LogicalAnd(m_Value(A), m_Value(B))))
3244 return TryInvertAndOrUsingDeMorgan(Instruction::Or, /*IsLogical=*/true, A,
3245 B);
3246
3247 return nullptr;
3248}
3249
3250/// Return true if we should canonicalize the gep to an i8 ptradd.
3252 Value *PtrOp = GEP.getOperand(0);
3253 Type *GEPEltType = GEP.getSourceElementType();
3254 if (GEPEltType->isIntegerTy(8))
3255 return false;
3256
3257 // Canonicalize scalable GEPs to an explicit offset using the llvm.vscale
3258 // intrinsic. This has better support in BasicAA.
3259 if (GEPEltType->isScalableTy())
3260 return true;
3261
3262 // gep i32 p, mul(O, C) -> gep i8, p, mul(O, C*4) to fold the two multiplies
3263 // together.
3264 if (GEP.getNumIndices() == 1 &&
3265 match(GEP.getOperand(1),
3267 m_Shl(m_Value(), m_ConstantInt())))))
3268 return true;
3269
3270 // gep (gep %p, C1), %x, C2 is expanded so the two constants can
3271 // possibly be merged together.
3272 auto PtrOpGep = dyn_cast<GEPOperator>(PtrOp);
3273 return PtrOpGep && PtrOpGep->hasAllConstantIndices() &&
3274 any_of(GEP.indices(), [](Value *V) {
3275 const APInt *C;
3276 return match(V, m_APInt(C)) && !C->isZero();
3277 });
3278}
3279
3281 IRBuilderBase &Builder) {
3282 auto *Op1 = dyn_cast<GetElementPtrInst>(PN->getOperand(0));
3283 if (!Op1)
3284 return nullptr;
3285
3286 // Don't fold a GEP into itself through a PHI node. This can only happen
3287 // through the back-edge of a loop. Folding a GEP into itself means that
3288 // the value of the previous iteration needs to be stored in the meantime,
3289 // thus requiring an additional register variable to be live, but not
3290 // actually achieving anything (the GEP still needs to be executed once per
3291 // loop iteration).
3292 if (Op1 == &GEP)
3293 return nullptr;
3294 GEPNoWrapFlags NW = Op1->getNoWrapFlags();
3295
3296 int DI = -1;
3297
3298 for (auto I = PN->op_begin()+1, E = PN->op_end(); I !=E; ++I) {
3299 auto *Op2 = dyn_cast<GetElementPtrInst>(*I);
3300 if (!Op2 || Op1->getNumOperands() != Op2->getNumOperands() ||
3301 Op1->getSourceElementType() != Op2->getSourceElementType())
3302 return nullptr;
3303
3304 // As for Op1 above, don't try to fold a GEP into itself.
3305 if (Op2 == &GEP)
3306 return nullptr;
3307
3308 // Keep track of the type as we walk the GEP.
3309 Type *CurTy = nullptr;
3310
3311 for (unsigned J = 0, F = Op1->getNumOperands(); J != F; ++J) {
3312 if (Op1->getOperand(J)->getType() != Op2->getOperand(J)->getType())
3313 return nullptr;
3314
3315 if (Op1->getOperand(J) != Op2->getOperand(J)) {
3316 if (DI == -1) {
3317 // We have not seen any differences yet in the GEPs feeding the
3318 // PHI yet, so we record this one if it is allowed to be a
3319 // variable.
3320
3321 // The first two arguments can vary for any GEP, the rest have to be
3322 // static for struct slots
3323 if (J > 1) {
3324 assert(CurTy && "No current type?");
3325 if (CurTy->isStructTy())
3326 return nullptr;
3327 }
3328
3329 DI = J;
3330 } else {
3331 // The GEP is different by more than one input. While this could be
3332 // extended to support GEPs that vary by more than one variable it
3333 // doesn't make sense since it greatly increases the complexity and
3334 // would result in an R+R+R addressing mode which no backend
3335 // directly supports and would need to be broken into several
3336 // simpler instructions anyway.
3337 return nullptr;
3338 }
3339 }
3340
3341 // Sink down a layer of the type for the next iteration.
3342 if (J > 0) {
3343 if (J == 1) {
3344 CurTy = Op1->getSourceElementType();
3345 } else {
3346 CurTy =
3347 GetElementPtrInst::getTypeAtIndex(CurTy, Op1->getOperand(J));
3348 }
3349 }
3350 }
3351
3352 NW &= Op2->getNoWrapFlags();
3353 }
3354
3355 // If not all GEPs are identical we'll have to create a new PHI node.
3356 // Check that the old PHI node has only one use so that it will get
3357 // removed.
3358 if (DI != -1 && !PN->hasOneUse())
3359 return nullptr;
3360
3361 auto *NewGEP = cast<GetElementPtrInst>(Op1->clone());
3362 NewGEP->setNoWrapFlags(NW);
3363
3364 if (DI == -1) {
3365 // All the GEPs feeding the PHI are identical. Clone one down into our
3366 // BB so that it can be merged with the current GEP.
3367 } else {
3368 // All the GEPs feeding the PHI differ at a single offset. Clone a GEP
3369 // into the current block so it can be merged, and create a new PHI to
3370 // set that index.
3371 PHINode *NewPN;
3372 {
3373 IRBuilderBase::InsertPointGuard Guard(Builder);
3374 Builder.SetInsertPoint(PN);
3375 NewPN = Builder.CreatePHI(Op1->getOperand(DI)->getType(),
3376 PN->getNumOperands());
3377 }
3378
3379 for (auto &I : PN->operands())
3380 NewPN->addIncoming(cast<GEPOperator>(I)->getOperand(DI),
3381 PN->getIncomingBlock(I));
3382
3383 NewGEP->setOperand(DI, NewPN);
3384 }
3385
3386 NewGEP->insertBefore(*GEP.getParent(), GEP.getParent()->getFirstInsertionPt());
3387 return NewGEP;
3388}
3389
3391 Value *PtrOp = GEP.getOperand(0);
3392 SmallVector<Value *, 8> Indices(GEP.indices());
3393 Type *GEPType = GEP.getType();
3394 Type *GEPEltType = GEP.getSourceElementType();
3395 if (Value *V =
3396 simplifyGEPInst(GEPEltType, PtrOp, Indices, GEP.getNoWrapFlags(),
3397 SQ.getWithInstruction(&GEP)))
3398 return replaceInstUsesWith(GEP, V);
3399
3400 // For vector geps, use the generic demanded vector support.
3401 // Skip if GEP return type is scalable. The number of elements is unknown at
3402 // compile-time.
3403 if (auto *GEPFVTy = dyn_cast<FixedVectorType>(GEPType)) {
3404 auto VWidth = GEPFVTy->getNumElements();
3405 APInt PoisonElts(VWidth, 0);
3406 APInt AllOnesEltMask(APInt::getAllOnes(VWidth));
3407 if (Value *V = SimplifyDemandedVectorElts(&GEP, AllOnesEltMask,
3408 PoisonElts)) {
3409 if (V != &GEP)
3410 return replaceInstUsesWith(GEP, V);
3411 return &GEP;
3412 }
3413 }
3414
3415 // Eliminate unneeded casts for indices, and replace indices which displace
3416 // by multiples of a zero size type with zero.
3417 bool MadeChange = false;
3418
3419 // Index width may not be the same width as pointer width.
3420 // Data layout chooses the right type based on supported integer types.
3421 Type *NewScalarIndexTy =
3422 DL.getIndexType(GEP.getPointerOperandType()->getScalarType());
3423
3425 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end(); I != E;
3426 ++I, ++GTI) {
3427 // Skip indices into struct types.
3428 if (GTI.isStruct())
3429 continue;
3430
3431 Type *IndexTy = (*I)->getType();
3432 Type *NewIndexType =
3433 IndexTy->isVectorTy()
3434 ? VectorType::get(NewScalarIndexTy,
3435 cast<VectorType>(IndexTy)->getElementCount())
3436 : NewScalarIndexTy;
3437
3438 // If the element type has zero size then any index over it is equivalent
3439 // to an index of zero, so replace it with zero if it is not zero already.
3440 Type *EltTy = GTI.getIndexedType();
3441 if (EltTy->isSized() && DL.getTypeAllocSize(EltTy).isZero())
3442 if (!isa<Constant>(*I) || !match(I->get(), m_Zero())) {
3443 *I = Constant::getNullValue(NewIndexType);
3444 MadeChange = true;
3445 }
3446
3447 if (IndexTy != NewIndexType) {
3448 // If we are using a wider index than needed for this platform, shrink
3449 // it to what we need. If narrower, sign-extend it to what we need.
3450 // This explicit cast can make subsequent optimizations more obvious.
3451 if (IndexTy->getScalarSizeInBits() <
3452 NewIndexType->getScalarSizeInBits()) {
3453 if (GEP.hasNoUnsignedWrap() && GEP.hasNoUnsignedSignedWrap())
3454 *I = Builder.CreateZExt(*I, NewIndexType, "", /*IsNonNeg=*/true);
3455 else
3456 *I = Builder.CreateSExt(*I, NewIndexType);
3457 } else {
3458 *I = Builder.CreateTrunc(*I, NewIndexType, "", GEP.hasNoUnsignedWrap(),
3459 GEP.hasNoUnsignedSignedWrap());
3460 }
3461 MadeChange = true;
3462 }
3463 }
3464 if (MadeChange)
3465 return &GEP;
3466
3467 // Canonicalize constant GEPs to i8 type.
3468 if (!GEPEltType->isIntegerTy(8) && GEP.hasAllConstantIndices()) {
3469 APInt Offset(DL.getIndexTypeSizeInBits(GEPType), 0);
3470 if (GEP.accumulateConstantOffset(DL, Offset))
3471 return replaceInstUsesWith(
3472 GEP, Builder.CreatePtrAdd(PtrOp, Builder.getInt(Offset), "",
3473 GEP.getNoWrapFlags()));
3474 }
3475
3477 Value *Offset = EmitGEPOffset(cast<GEPOperator>(&GEP));
3478 Value *NewGEP =
3479 Builder.CreatePtrAdd(PtrOp, Offset, "", GEP.getNoWrapFlags());
3480 return replaceInstUsesWith(GEP, NewGEP);
3481 }
3482
3483 // Canonicalize to getelementptr i8 or getelementptr [Stride x i8]
3484 // via IRBuilder.
3485 auto IsCanonicalType = [](Type *Ty) {
3486 if (auto *AT = dyn_cast<ArrayType>(Ty))
3487 Ty = AT->getElementType();
3488 return Ty->isIntegerTy(8);
3489 };
3490 if (!IsCanonicalType(GEPEltType) || Indices.size() != 1)
3491 return replaceInstUsesWith(GEP,
3492 Builder.CreateGEP(GEPEltType, PtrOp, Indices, "",
3493 GEP.getNoWrapFlags()));
3494
3495 // Scalarize vector operands; prefer splat-of-gep.as canonical form.
3496 // Note that this looses information about undef lanes; we run it after
3497 // demanded bits to partially mitigate that loss.
3498 if (GEPType->isVectorTy() && llvm::any_of(GEP.operands(), [](Value *Op) {
3499 return Op->getType()->isVectorTy() && getSplatValue(Op);
3500 })) {
3501 SmallVector<Value *> NewOps;
3502 for (auto &Op : GEP.operands()) {
3503 if (Op->getType()->isVectorTy())
3504 if (Value *Scalar = getSplatValue(Op)) {
3505 NewOps.push_back(Scalar);
3506 continue;
3507 }
3508 NewOps.push_back(Op);
3509 }
3510
3511 Value *Res = Builder.CreateGEP(GEP.getSourceElementType(), NewOps[0],
3512 ArrayRef(NewOps).drop_front(), GEP.getName(),
3513 GEP.getNoWrapFlags());
3514 if (!Res->getType()->isVectorTy()) {
3515 ElementCount EC = cast<VectorType>(GEPType)->getElementCount();
3516 Res = Builder.CreateVectorSplat(EC, Res);
3517 }
3518 return replaceInstUsesWith(GEP, Res);
3519 }
3520
3521 // Check to see if the inputs to the PHI node are getelementptr instructions.
3522 if (auto *PN = dyn_cast<PHINode>(PtrOp)) {
3523 if (Value *NewPtrOp = foldGEPOfPhi(GEP, PN, Builder))
3524 return replaceOperand(GEP, 0, NewPtrOp);
3525 }
3526
3527 if (auto *Src = dyn_cast<GEPOperator>(PtrOp))
3528 if (Instruction *I = visitGEPOfGEP(GEP, Src))
3529 return I;
3530
3531 if (GEP.getNumIndices() == 1) {
3532 unsigned AS = GEP.getPointerAddressSpace();
3533 if (GEP.getOperand(1)->getType()->getScalarSizeInBits() ==
3534 DL.getIndexSizeInBits(AS)) {
3535 uint64_t TyAllocSize = DL.getTypeAllocSize(GEPEltType).getFixedValue();
3536
3537 if (TyAllocSize == 1) {
3538 // Canonicalize (gep i8* X, (ptrtoint Y)-(ptrtoint X)) to (bitcast Y),
3539 // but only if the result pointer is only used as if it were an integer.
3540 // (The case where the underlying object is the same is handled by
3541 // InstSimplify.)
3542 Value *X = GEP.getPointerOperand();
3543 Value *Y;
3544 if (match(GEP.getOperand(1), m_Sub(m_PtrToIntOrAddr(m_Value(Y)),
3546 GEPType == Y->getType()) {
3547 bool HasNonAddressBits =
3548 DL.getAddressSizeInBits(AS) != DL.getPointerSizeInBits(AS);
3549 bool Changed = GEP.replaceUsesWithIf(Y, [&](Use &U) {
3550 return isa<PtrToAddrInst, ICmpInst>(U.getUser()) ||
3551 (!HasNonAddressBits && isa<PtrToIntInst>(U.getUser()));
3552 });
3553 return Changed ? &GEP : nullptr;
3554 }
3555 } else if (auto *ExactIns =
3556 dyn_cast<PossiblyExactOperator>(GEP.getOperand(1))) {
3557 // Canonicalize (gep T* X, V / sizeof(T)) to (gep i8* X, V)
3558 Value *V;
3559 if (ExactIns->isExact()) {
3560 if ((has_single_bit(TyAllocSize) &&
3561 match(GEP.getOperand(1),
3562 m_Shr(m_Value(V),
3563 m_SpecificInt(countr_zero(TyAllocSize))))) ||
3564 match(GEP.getOperand(1),
3565 m_IDiv(m_Value(V), m_SpecificInt(TyAllocSize)))) {
3566 return GetElementPtrInst::Create(Builder.getInt8Ty(),
3567 GEP.getPointerOperand(), V,
3568 GEP.getNoWrapFlags());
3569 }
3570 }
3571 if (ExactIns->isExact() && ExactIns->hasOneUse()) {
3572 // Try to canonicalize non-i8 element type to i8 if the index is an
3573 // exact instruction. If the index is an exact instruction (div/shr)
3574 // with a constant RHS, we can fold the non-i8 element scale into the
3575 // div/shr (similiar to the mul case, just inverted).
3576 const APInt *C;
3577 std::optional<APInt> NewC;
3578 if (has_single_bit(TyAllocSize) &&
3579 match(ExactIns, m_Shr(m_Value(V), m_APInt(C))) &&
3580 C->uge(countr_zero(TyAllocSize)))
3581 NewC = *C - countr_zero(TyAllocSize);
3582 else if (match(ExactIns, m_UDiv(m_Value(V), m_APInt(C)))) {
3583 APInt Quot;
3584 uint64_t Rem;
3585 APInt::udivrem(*C, TyAllocSize, Quot, Rem);
3586 if (Rem == 0)
3587 NewC = Quot;
3588 } else if (match(ExactIns, m_SDiv(m_Value(V), m_APInt(C)))) {
3589 APInt Quot;
3590 int64_t Rem;
3591 APInt::sdivrem(*C, TyAllocSize, Quot, Rem);
3592 // For sdiv we need to make sure we arent creating INT_MIN / -1.
3593 if (!Quot.isAllOnes() && Rem == 0)
3594 NewC = Quot;
3595 }
3596
3597 if (NewC.has_value()) {
3598 Value *NewOp = Builder.CreateExactBinOp(
3599 static_cast<Instruction::BinaryOps>(ExactIns->getOpcode()), V,
3600 ConstantInt::get(V->getType(), *NewC), /*IsExact=*/true);
3601 return GetElementPtrInst::Create(Builder.getInt8Ty(),
3602 GEP.getPointerOperand(), NewOp,
3603 GEP.getNoWrapFlags());
3604 }
3605 }
3606 }
3607 }
3608 }
3609 // We do not handle pointer-vector geps here.
3610 if (GEPType->isVectorTy())
3611 return nullptr;
3612
3613 if (!GEP.isInBounds()) {
3614 unsigned IdxWidth =
3615 DL.getIndexSizeInBits(PtrOp->getType()->getPointerAddressSpace());
3616 APInt BasePtrOffset(IdxWidth, 0);
3617 Value *UnderlyingPtrOp =
3618 PtrOp->stripAndAccumulateInBoundsConstantOffsets(DL, BasePtrOffset);
3619 bool CanBeNull;
3620 uint64_t DerefBytes = UnderlyingPtrOp->getPointerDereferenceableBytes(
3621 DL, CanBeNull, /*CanBeFreed=*/nullptr);
3622 // We can ignore CanBeFreed here, because inbounds is explicitly allowed to
3623 // refer to a deallocated object.
3624 if (!CanBeNull && DerefBytes != 0) {
3625 if (GEP.accumulateConstantOffset(DL, BasePtrOffset) &&
3626 BasePtrOffset.isNonNegative()) {
3627 APInt AllocSize(IdxWidth, DerefBytes);
3628 if (BasePtrOffset.ule(AllocSize)) {
3630 GEP.getSourceElementType(), PtrOp, Indices, GEP.getName());
3631 }
3632 }
3633 }
3634 }
3635
3636 // nusw + nneg -> nuw
3637 if (GEP.hasNoUnsignedSignedWrap() && !GEP.hasNoUnsignedWrap() &&
3638 all_of(GEP.indices(), [&](Value *Idx) {
3639 return isKnownNonNegative(Idx, SQ.getWithInstruction(&GEP));
3640 })) {
3641 GEP.setNoWrapFlags(GEP.getNoWrapFlags() | GEPNoWrapFlags::noUnsignedWrap());
3642 return &GEP;
3643 }
3644
3645 // These rewrites are trying to preserve inbounds/nuw attributes. So we want
3646 // to do this after having tried to derive "nuw" above.
3647 if (GEP.getNumIndices() == 1) {
3648 // Given (gep p, x+y) we want to determine the common nowrap flags for both
3649 // geps if transforming into (gep (gep p, x), y).
3650 auto GetPreservedNoWrapFlags = [&](bool AddIsNUW) {
3651 // We can preserve both "inbounds nuw", "nusw nuw" and "nuw" if we know
3652 // that x + y does not have unsigned wrap.
3653 if (GEP.hasNoUnsignedWrap() && AddIsNUW)
3654 return GEP.getNoWrapFlags();
3655 return GEPNoWrapFlags::none();
3656 };
3657
3658 // Try to replace ADD + GEP with GEP + GEP.
3659 Value *Idx1, *Idx2;
3660 if (match(GEP.getOperand(1),
3661 m_OneUse(m_AddLike(m_Value(Idx1), m_Value(Idx2))))) {
3662 // %idx = add i64 %idx1, %idx2
3663 // %gep = getelementptr i32, ptr %ptr, i64 %idx
3664 // as:
3665 // %newptr = getelementptr i32, ptr %ptr, i64 %idx1
3666 // %newgep = getelementptr i32, ptr %newptr, i64 %idx2
3667 bool NUW = match(GEP.getOperand(1), m_NUWAddLike(m_Value(), m_Value()));
3668 GEPNoWrapFlags NWFlags = GetPreservedNoWrapFlags(NUW);
3669 auto *NewPtr =
3670 Builder.CreateGEP(GEP.getSourceElementType(), GEP.getPointerOperand(),
3671 Idx1, "", NWFlags);
3672 return replaceInstUsesWith(GEP,
3673 Builder.CreateGEP(GEP.getSourceElementType(),
3674 NewPtr, Idx2, "", NWFlags));
3675 }
3676 ConstantInt *C;
3677 if (match(GEP.getOperand(1), m_OneUse(m_SExtLike(m_OneUse(m_NSWAddLike(
3678 m_Value(Idx1), m_ConstantInt(C))))))) {
3679 // %add = add nsw i32 %idx1, idx2
3680 // %sidx = sext i32 %add to i64
3681 // %gep = getelementptr i32, ptr %ptr, i64 %sidx
3682 // as:
3683 // %newptr = getelementptr i32, ptr %ptr, i32 %idx1
3684 // %newgep = getelementptr i32, ptr %newptr, i32 idx2
3685 bool NUW = match(GEP.getOperand(1),
3687 GEPNoWrapFlags NWFlags = GetPreservedNoWrapFlags(NUW);
3688 auto *NewPtr = Builder.CreateGEP(
3689 GEP.getSourceElementType(), GEP.getPointerOperand(),
3690 Builder.CreateSExt(Idx1, GEP.getOperand(1)->getType()), "", NWFlags);
3691 return replaceInstUsesWith(
3692 GEP,
3693 Builder.CreateGEP(GEP.getSourceElementType(), NewPtr,
3694 Builder.CreateSExt(C, GEP.getOperand(1)->getType()),
3695 "", NWFlags));
3696 }
3697 }
3698
3700 return R;
3701
3702 // srem -> (and/urem) for inbounds+nuw GEP
3703 if (Indices.size() == 1 && GEP.isInBounds() && GEP.hasNoUnsignedWrap()) {
3704 Value *X, *Y;
3705
3706 // Match: idx = srem X, Y -- where Y is a power-of-two value.
3707 if (match(Indices[0], m_OneUse(m_SRem(m_Value(X), m_Value(Y)))) &&
3708 isKnownToBeAPowerOfTwo(Y, /*OrZero=*/true, &GEP)) {
3709 // If GEP is inbounds+nuw, the offset cannot be negative
3710 // -> srem by power-of-two can be treated as urem,
3711 // and urem by power-of-two folds to 'and' later.
3712 // OrZero=true is fine here because division by zero is UB.
3713 Instruction *OldIdxI = cast<Instruction>(Indices[0]);
3714 Value *NewIdx = Builder.CreateURem(X, Y, OldIdxI->getName());
3715
3716 return GetElementPtrInst::Create(GEPEltType, PtrOp, {NewIdx},
3717 GEP.getNoWrapFlags());
3718 }
3719 }
3720
3721 return nullptr;
3722}
3723
3726 return true;
3727 if (auto *LI = dyn_cast<LoadInst>(V))
3728 return isa<GlobalVariable>(LI->getPointerOperand());
3729 // Two distinct allocations will never be equal.
3730 return isAllocLikeFn(V) && V != AI;
3731}
3732
3733/// Given a call CB which uses an address UsedV, return true if we can prove the
3734/// call's only possible effect is storing to V.
3735static bool isRemovableWrite(CallBase &CB, Value *UsedV,
3736 const TargetLibraryInfo &TLI) {
3737 if (!CB.use_empty())
3738 // TODO: add recursion if returned attribute is present
3739 return false;
3740
3741 if (CB.isTerminator())
3742 // TODO: remove implementation restriction
3743 return false;
3744
3745 if (!CB.willReturn() || !CB.doesNotThrow())
3746 return false;
3747
3748 // If the only possible side effect of the call is writing to the alloca,
3749 // and the result isn't used, we can safely remove any reads implied by the
3750 // call including those which might read the alloca itself.
3751 std::optional<MemoryLocation> Dest = MemoryLocation::getForDest(&CB, TLI);
3752 return Dest && Dest->Ptr == UsedV;
3753}
3754
3755static std::optional<ModRefInfo>
3757 const TargetLibraryInfo &TLI, bool KnowInit,
3758 unsigned MaxUsers) {
3760 const std::optional<StringRef> Family = getAllocationFamily(AI);
3761 Worklist.push_back(AI);
3763
3764 do {
3765 Instruction *PI = Worklist.pop_back_val();
3766 for (Instruction *I : PI->users()) {
3767 if (Users.size() >= MaxUsers)
3768 return std::nullopt;
3769 switch (I->getOpcode()) {
3770 default:
3771 // Give up the moment we see something we can't handle.
3772 return std::nullopt;
3773
3774 case Instruction::AddrSpaceCast:
3775 case Instruction::BitCast:
3776 case Instruction::GetElementPtr:
3777 Users.emplace_back(I);
3778 Worklist.push_back(I);
3779 continue;
3780
3781 case Instruction::ICmp: {
3782 ICmpInst *ICI = cast<ICmpInst>(I);
3783 // We can fold eq/ne comparisons with null to false/true, respectively.
3784 // We also fold comparisons in some conditions provided the alloc has
3785 // not escaped (see isNeverEqualToUnescapedAlloc).
3786 if (!ICI->isEquality())
3787 return std::nullopt;
3788 unsigned OtherIndex = (ICI->getOperand(0) == PI) ? 1 : 0;
3789 if (!isNeverEqualToUnescapedAlloc(ICI->getOperand(OtherIndex), AI))
3790 return std::nullopt;
3791
3792 // Do not fold compares to aligned_alloc calls, as they may have to
3793 // return null in case the required alignment cannot be satisfied,
3794 // unless we can prove that both alignment and size are valid.
3795 auto AlignmentAndSizeKnownValid = [](CallBase *CB) {
3796 // Check if alignment and size of a call to aligned_alloc is valid,
3797 // that is alignment is a power-of-2 and the size is a multiple of the
3798 // alignment.
3799 const APInt *Alignment;
3800 const APInt *Size;
3801 return match(CB->getArgOperand(0), m_APInt(Alignment)) &&
3802 match(CB->getArgOperand(1), m_APInt(Size)) &&
3803 Alignment->isPowerOf2() && Size->urem(*Alignment).isZero();
3804 };
3805 auto *CB = dyn_cast<CallBase>(AI);
3806 if (CB &&
3807 TLI.getLibFunc(*CB->getCalledFunction()) == LibFunc_aligned_alloc &&
3808 TLI.has(LibFunc_aligned_alloc) && !AlignmentAndSizeKnownValid(CB))
3809 return std::nullopt;
3810 Users.emplace_back(I);
3811 continue;
3812 }
3813
3814 case Instruction::Call:
3815 // Ignore no-op and store intrinsics.
3817 switch (II->getIntrinsicID()) {
3818 default:
3819 return std::nullopt;
3820
3821 case Intrinsic::memmove:
3822 case Intrinsic::memcpy:
3823 case Intrinsic::memset: {
3825 if (MI->isVolatile())
3826 return std::nullopt;
3827 // Note: this could also be ModRef, but we can still interpret that
3828 // as just Mod in that case.
3829 ModRefInfo NewAccess =
3830 MI->getRawDest() == PI ? ModRefInfo::Mod : ModRefInfo::Ref;
3831 if ((Access & ~NewAccess) != ModRefInfo::NoModRef)
3832 return std::nullopt;
3833 Access |= NewAccess;
3834 [[fallthrough]];
3835 }
3836 case Intrinsic::assume:
3837 case Intrinsic::invariant_start:
3838 case Intrinsic::invariant_end:
3839 case Intrinsic::lifetime_start:
3840 case Intrinsic::lifetime_end:
3841 case Intrinsic::objectsize:
3842 Users.emplace_back(I);
3843 continue;
3844 case Intrinsic::launder_invariant_group:
3845 Users.emplace_back(I);
3846 Worklist.push_back(I);
3847 continue;
3848 }
3849 }
3850
3851 if (Family && getFreedOperand(cast<CallBase>(I)) == PI &&
3852 getAllocationFamily(I) == Family) {
3853 Users.emplace_back(I);
3854 continue;
3855 }
3856
3857 if (Family && getReallocatedOperand(cast<CallBase>(I)) == PI &&
3858 getAllocationFamily(I) == Family) {
3859 Users.emplace_back(I);
3860 Worklist.push_back(I);
3861 continue;
3862 }
3863
3864 if (!isRefSet(Access) &&
3867 Users.emplace_back(I);
3868 continue;
3869 }
3870
3871 return std::nullopt;
3872
3873 case Instruction::Store: {
3875 if (SI->isVolatile() || SI->getPointerOperand() != PI)
3876 return std::nullopt;
3877 if (isRefSet(Access))
3878 return std::nullopt;
3880 Users.emplace_back(I);
3881 continue;
3882 }
3883
3884 case Instruction::Load: {
3885 LoadInst *LI = cast<LoadInst>(I);
3886 if (LI->isVolatile() || LI->getPointerOperand() != PI)
3887 return std::nullopt;
3888 if (isModSet(Access))
3889 return std::nullopt;
3891 Users.emplace_back(I);
3892 continue;
3893 }
3894 }
3895 llvm_unreachable("missing a return?");
3896 }
3897 } while (!Worklist.empty());
3898
3900 return Access;
3901}
3902
3905
3906 // If we have a malloc call which is only used in any amount of comparisons to
3907 // null and free calls, delete the calls and replace the comparisons with true
3908 // or false as appropriate.
3909
3910 // This is based on the principle that we can substitute our own allocation
3911 // function (which will never return null) rather than knowledge of the
3912 // specific function being called. In some sense this can change the permitted
3913 // outputs of a program (when we convert a malloc to an alloca, the fact that
3914 // the allocation is now on the stack is potentially visible, for example),
3915 // but we believe in a permissible manner.
3916 //
3917 // Collect into Instruction* first to avoid expensive WeakTrackingVH
3918 // register/unregister overhead; convert to WeakTrackingVH only when the
3919 // site is actually removable.
3921
3922 // If we are removing an alloca with a dbg.declare, insert dbg.value calls
3923 // before each store.
3925 std::unique_ptr<DIBuilder> DIB;
3926 if (isa<AllocaInst>(MI)) {
3927 findDbgUsers(&MI, DVRs);
3928 DIB.reset(new DIBuilder(*MI.getModule(), /*AllowUnresolved=*/false));
3929 }
3930
3931 // Determine what getInitialValueOfAllocation would return without actually
3932 // allocating the result.
3933 bool KnowInitUndef = false;
3934 bool KnowInitZero = false;
3935 Constant *Init =
3937 if (Init) {
3938 if (isa<UndefValue>(Init))
3939 KnowInitUndef = true;
3940 else if (Init->isNullValue())
3941 KnowInitZero = true;
3942 }
3943 // The various sanitizers don't actually return undef memory, but rather
3944 // memory initialized with special forms of runtime poison
3945 auto &F = *MI.getFunction();
3946 if (F.hasFnAttribute(Attribute::SanitizeMemory) ||
3947 F.hasFnAttribute(Attribute::SanitizeAddress))
3948 KnowInitUndef = false;
3949
3950 auto Removable =
3951 isAllocSiteRemovable(&MI, RawUsers, TLI, KnowInitZero | KnowInitUndef,
3952 CLOpts.max_allocsite_removable_users);
3953 if (Removable) {
3954 SmallVector<WeakTrackingVH, 64> Users(RawUsers.begin(), RawUsers.end());
3955 for (WeakTrackingVH &User : Users) {
3956 // Lowering all @llvm.objectsize and MTI calls first because they may use
3957 // a bitcast/GEP of the alloca we are removing.
3958 if (!User)
3959 continue;
3960
3962
3964 if (II->getIntrinsicID() == Intrinsic::objectsize) {
3965 SmallVector<Instruction *> InsertedInstructions;
3966 Value *Result = lowerObjectSizeCall(
3967 II, DL, &TLI, AA, /*MustSucceed=*/true, &InsertedInstructions);
3968 for (Instruction *Inserted : InsertedInstructions)
3969 Worklist.add(Inserted);
3970 replaceInstUsesWith(*I, Result);
3972 User = nullptr; // Skip examining in the next loop.
3973 continue;
3974 }
3975 if (auto *MTI = dyn_cast<MemTransferInst>(I)) {
3976 if (KnowInitZero && isRefSet(*Removable)) {
3978 Builder.SetInsertPoint(MTI);
3979 auto *M = Builder.CreateMemSet(
3980 MTI->getRawDest(),
3981 ConstantInt::get(Type::getInt8Ty(MI.getContext()), 0),
3982 MTI->getLength(), MTI->getDestAlign());
3983 M->copyMetadata(*MTI);
3984 }
3985 }
3986 }
3987 }
3988 for (WeakTrackingVH &User : Users) {
3989 if (!User)
3990 continue;
3991
3993
3994 if (ICmpInst *C = dyn_cast<ICmpInst>(I)) {
3996 *C, ConstantInt::get(C->getType(), C->isFalseWhenEqual()));
3997 } else if (auto *SI = dyn_cast<StoreInst>(I)) {
3998 for (auto *DVR : DVRs)
3999 if (DVR->isAddressOfVariable())
4001 } else {
4002 // Casts, GEP, or anything else: we're about to delete this instruction,
4003 // so it can not have any valid uses.
4005 if (isa<LoadInst>(I)) {
4006 assert(KnowInitZero || KnowInitUndef);
4007 Replace = KnowInitUndef ? UndefValue::get(I->getType())
4008 : Constant::getNullValue(I->getType());
4009 } else if (Constant *Result = getElidedFreeResult(I))
4010 Replace = Result;
4011 else
4012 Replace = PoisonValue::get(I->getType());
4014 }
4016 }
4017
4019 // Replace invoke with a NOP intrinsic to maintain the original CFG
4020 Module *M = II->getModule();
4021 Function *F = Intrinsic::getOrInsertDeclaration(M, Intrinsic::donothing);
4022 auto *NewII = InvokeInst::Create(
4023 F, II->getNormalDest(), II->getUnwindDest(), {}, "", II->getParent());
4024 NewII->setDebugLoc(II->getDebugLoc());
4025 }
4026
4027 // Remove debug intrinsics which describe the value contained within the
4028 // alloca. In addition to removing dbg.{declare,addr} which simply point to
4029 // the alloca, remove dbg.value(<alloca>, ..., DW_OP_deref)'s as well, e.g.:
4030 //
4031 // ```
4032 // define void @foo(i32 %0) {
4033 // %a = alloca i32 ; Deleted.
4034 // store i32 %0, i32* %a
4035 // dbg.value(i32 %0, "arg0") ; Not deleted.
4036 // dbg.value(i32* %a, "arg0", DW_OP_deref) ; Deleted.
4037 // call void @trivially_inlinable_no_op(i32* %a)
4038 // ret void
4039 // }
4040 // ```
4041 //
4042 // This may not be required if we stop describing the contents of allocas
4043 // using dbg.value(<alloca>, ..., DW_OP_deref), but we currently do this in
4044 // the LowerDbgDeclare utility.
4045 //
4046 // If there is a dead store to `%a` in @trivially_inlinable_no_op, the
4047 // "arg0" dbg.value may be stale after the call. However, failing to remove
4048 // the DW_OP_deref dbg.value causes large gaps in location coverage.
4049 //
4050 // FIXME: the Assignment Tracking project has now likely made this
4051 // redundant (and it's sometimes harmful).
4052 for (auto *DVR : DVRs)
4053 if (DVR->isAddressOfVariable() || DVR->getExpression()->startsWithDeref())
4054 DVR->eraseFromParent();
4055
4056 return eraseInstFromFunction(MI);
4057 }
4058 return nullptr;
4059}
4060
4061/// Move the call to free before a NULL test.
4062///
4063/// Check if this free is accessed after its argument has been test
4064/// against NULL (property 0).
4065/// If yes, it is legal to move this call in its predecessor block.
4066///
4067/// The move is performed only if the block containing the call to free
4068/// will be removed, i.e.:
4069/// 1. it has only one predecessor P, and P has two successors
4070/// 2. it contains the call, noops, and an unconditional branch
4071/// 3. its successor is the same as its predecessor's successor
4072///
4073/// The profitability is out-of concern here and this function should
4074/// be called only if the caller knows this transformation would be
4075/// profitable (e.g., for code size).
4077 const DataLayout &DL) {
4078 Value *Op = FI.getArgOperand(0);
4079 BasicBlock *FreeInstrBB = FI.getParent();
4080 BasicBlock *PredBB = FreeInstrBB->getSinglePredecessor();
4081
4082 // Validate part of constraint #1: Only one predecessor
4083 // FIXME: We can extend the number of predecessor, but in that case, we
4084 // would duplicate the call to free in each predecessor and it may
4085 // not be profitable even for code size.
4086 if (!PredBB)
4087 return nullptr;
4088
4089 // Validate constraint #2: Does this block contains only the call to
4090 // free, noops, and an unconditional branch?
4091 BasicBlock *SuccBB;
4092 Instruction *FreeInstrBBTerminator = FreeInstrBB->getTerminator();
4093 if (!match(FreeInstrBBTerminator, m_UnconditionalBr(SuccBB)))
4094 return nullptr;
4095
4096 // If there are only 2 instructions in the block, at this point,
4097 // this is the call to free and unconditional.
4098 // If there are more than 2 instructions, check that they are noops
4099 // i.e., they won't hurt the performance of the generated code.
4100 if (FreeInstrBB->size() != 2) {
4101 for (const Instruction &Inst : *FreeInstrBB) {
4102 if (&Inst == &FI || &Inst == FreeInstrBBTerminator ||
4104 continue;
4105 auto *Cast = dyn_cast<CastInst>(&Inst);
4106 if (!Cast || !Cast->isNoopCast(DL))
4107 return nullptr;
4108 }
4109 }
4110 // Validate the rest of constraint #1 by matching on the pred branch.
4111 Instruction *TI = PredBB->getTerminator();
4112 BasicBlock *TrueBB, *FalseBB;
4114 if (!match(TI, m_Br(m_ICmp(Pred,
4116 m_Specific(Op->stripPointerCasts())),
4117 m_Zero()),
4118 TrueBB, FalseBB)))
4119 return nullptr;
4121 return nullptr;
4122
4123 // Validate constraint #3: Ensure the null case just falls through.
4124 if (SuccBB != (Pred == ICmpInst::ICMP_EQ ? TrueBB : FalseBB))
4125 return nullptr;
4126 assert(FreeInstrBB == (Pred == ICmpInst::ICMP_EQ ? FalseBB : TrueBB) &&
4127 "Broken CFG: missing edge from predecessor to successor");
4128
4129 // At this point, we know that everything in FreeInstrBB can be moved
4130 // before TI.
4131 for (Instruction &Instr : llvm::make_early_inc_range(*FreeInstrBB)) {
4132 if (&Instr == FreeInstrBBTerminator)
4133 break;
4134 Instr.moveBeforePreserving(TI->getIterator());
4135 }
4136 assert(FreeInstrBB->size() == 1 &&
4137 "Only the branch instruction should remain");
4138
4139 // Now that we've moved the call to free before the NULL check, we have to
4140 // remove any attributes on its parameter that imply it's non-null, because
4141 // those attributes might have only been valid because of the NULL check, and
4142 // we can get miscompiles if we keep them. This is conservative if non-null is
4143 // also implied by something other than the NULL check, but it's guaranteed to
4144 // be correct, and the conservativeness won't matter in practice, since the
4145 // attributes are irrelevant for the call to free itself and the pointer
4146 // shouldn't be used after the call.
4147 AttributeList Attrs = FI.getAttributes();
4148 Attrs = Attrs.removeParamAttribute(FI.getContext(), 0, Attribute::NonNull);
4149 Attribute Dereferenceable = Attrs.getParamAttr(0, Attribute::Dereferenceable);
4150 if (Dereferenceable.isValid()) {
4151 uint64_t Bytes = Dereferenceable.getDereferenceableBytes();
4152 Attrs = Attrs.removeParamAttribute(FI.getContext(), 0,
4153 Attribute::Dereferenceable);
4154 Attrs = Attrs.addDereferenceableOrNullParamAttr(FI.getContext(), 0, Bytes);
4155 }
4156 FI.setAttributes(Attrs);
4157
4158 return &FI;
4159}
4160
4162 // free undef -> unreachable.
4163 if (isa<UndefValue>(Op)) {
4164 // Leave a marker since we can't modify the CFG here.
4167 return eraseInstFromFunction(FI);
4168 }
4169
4170 // If we have 'free null' delete the instruction. This can happen in stl code
4171 // when lots of inlining happens.
4173 return eraseInstFromFunction(FI);
4174
4175 // If we had free(realloc(...)) with no intervening uses, then eliminate the
4176 // realloc() entirely.
4178 if (CI && CI->hasOneUse())
4179 if (Value *ReallocatedOp = getReallocatedOperand(CI))
4180 return eraseInstFromFunction(*replaceInstUsesWith(*CI, ReallocatedOp));
4181
4182 // If we optimize for code size, try to move the call to free before the null
4183 // test so that simplify cfg can remove the empty block and dead code
4184 // elimination the branch. I.e., helps to turn something like:
4185 // if (foo) free(foo);
4186 // into
4187 // free(foo);
4188 //
4189 // Note that we can only do this for 'free' and not for any flavor of
4190 // 'operator delete'; there is no 'operator delete' symbol for which we are
4191 // permitted to invent a call, even if we're passing in a null pointer.
4192 if (MinimizeSize) {
4193 if (TLI.getLibFunc(FI) == LibFunc_free && TLI.has(LibFunc_free))
4195 return I;
4196 }
4197
4198 return nullptr;
4199}
4200
4202 Value *RetVal = RI.getReturnValue();
4203 if (!RetVal)
4204 return nullptr;
4205
4206 Function *F = RI.getFunction();
4207 Type *RetTy = RetVal->getType();
4208 if (RetTy->isPointerTy()) {
4209 bool UseProvenance =
4210 F->getAttributes().getRetDereferenceableBytes() > 0 &&
4212 if (F->hasRetAttribute(Attribute::NonNull) || UseProvenance) {
4213 if (Value *V = simplifyNonNullOperand(RetVal, UseProvenance))
4214 return replaceOperand(RI, 0, V);
4215 }
4216 }
4217
4218 if (!AttributeFuncs::isNoFPClassCompatibleType(RetTy))
4219 return nullptr;
4220
4221 FPClassTest ReturnClass = F->getAttributes().getRetNoFPClass();
4222 if (ReturnClass == fcNone)
4223 return nullptr;
4224
4225 KnownFPClass KnownClass;
4226 if (SimplifyDemandedFPClass(&RI, 0, ~ReturnClass, KnownClass,
4227 SQ.getWithInstruction(&RI)))
4228 return &RI;
4229
4230 return nullptr;
4231}
4232
4233// WARNING: keep in sync with SimplifyCFGOpt::simplifyUnreachable()!
4235 // Try to remove the previous instruction if it must lead to unreachable.
4236 // This includes instructions like stores and "llvm.assume" that may not get
4237 // removed by simple dead code elimination.
4238 bool Changed = false;
4239 while (Instruction *Prev = I.getPrevNode()) {
4240 // While we theoretically can erase EH, that would result in a block that
4241 // used to start with an EH no longer starting with EH, which is invalid.
4242 // To make it valid, we'd need to fixup predecessors to no longer refer to
4243 // this block, but that changes CFG, which is not allowed in InstCombine.
4244 if (Prev->isEHPad())
4245 break; // Can not drop any more instructions. We're done here.
4246
4248 break; // Can not drop any more instructions. We're done here.
4249 // Otherwise, this instruction can be freely erased,
4250 // even if it is not side-effect free.
4251
4252 // A value may still have uses before we process it here (for example, in
4253 // another unreachable block), so convert those to poison.
4254 replaceInstUsesWith(*Prev, PoisonValue::get(Prev->getType()));
4255 eraseInstFromFunction(*Prev);
4256 Changed = true;
4257 }
4258 return Changed;
4259}
4260
4265
4267 // If this store is the second-to-last instruction in the basic block
4268 // (excluding debug info) and if the block ends with
4269 // an unconditional branch, try to move the store to the successor block.
4270
4271 auto GetLastSinkableStore = [](BasicBlock::iterator BBI) {
4272 BasicBlock::iterator FirstInstr = BBI->getParent()->begin();
4273 do {
4274 if (BBI != FirstInstr)
4275 --BBI;
4276 } while (BBI != FirstInstr && isa<PseudoProbeInst>(BBI));
4277
4278 return dyn_cast<StoreInst>(BBI);
4279 };
4280
4281 if (StoreInst *SI = GetLastSinkableStore(BasicBlock::iterator(BI)))
4283 return &BI;
4284
4285 return nullptr;
4286}
4287
4290 if (!DeadEdges.insert({From, To}).second)
4291 return;
4292
4293 // Replace phi node operands in successor with poison.
4294 for (PHINode &PN : To->phis())
4295 for (Use &U : PN.incoming_values())
4296 if (PN.getIncomingBlock(U) == From && !isa<PoisonValue>(U)) {
4297 replaceUse(U, PoisonValue::get(PN.getType()));
4298 addToWorklist(&PN);
4299 MadeIRChange = true;
4300 }
4301
4302 Worklist.push_back(To);
4303}
4304
4305// Under the assumption that I is unreachable, remove it and following
4306// instructions. Changes are reported directly to MadeIRChange.
4309 BasicBlock *BB = I->getParent();
4310 for (Instruction &Inst : make_early_inc_range(
4311 make_range(std::next(BB->getTerminator()->getReverseIterator()),
4312 std::next(I->getReverseIterator())))) {
4313 if (!Inst.use_empty() && !Inst.getType()->isTokenTy()) {
4314 replaceInstUsesWith(Inst, PoisonValue::get(Inst.getType()));
4315 MadeIRChange = true;
4316 }
4317 if (Inst.isEHPad() || Inst.getType()->isTokenTy())
4318 continue;
4319 // RemoveDIs: erase debug-info on this instruction manually.
4320 Inst.dropDbgRecords();
4322 MadeIRChange = true;
4323 }
4324
4327 MadeIRChange = true;
4328 for (Value *V : Changed)
4330 }
4331
4332 // Handle potentially dead successors.
4333 for (BasicBlock *Succ : successors(BB))
4334 addDeadEdge(BB, Succ, Worklist);
4335}
4336
4339 while (!Worklist.empty()) {
4340 BasicBlock *BB = Worklist.pop_back_val();
4341 if (!all_of(predecessors(BB), [&](BasicBlock *Pred) {
4342 return DeadEdges.contains({Pred, BB}) || DT.dominates(BB, Pred);
4343 }))
4344 continue;
4345
4347 }
4348}
4349
4351 BasicBlock *LiveSucc) {
4353 for (BasicBlock *Succ : successors(BB)) {
4354 // The live successor isn't dead.
4355 if (Succ == LiveSucc)
4356 continue;
4357
4358 addDeadEdge(BB, Succ, Worklist);
4359 }
4360
4362}
4363
4365 // Change br (not X), label True, label False to: br X, label False, True
4366 Value *Cond = BI.getCondition();
4367 Value *X;
4368 if (match(Cond, m_Not(m_Value(X))) && !isa<Constant>(X)) {
4369 // Swap Destinations and condition...
4370 BI.swapSuccessors();
4371 if (BPI)
4372 BPI->swapSuccEdgesProbabilities(BI.getParent());
4373 return replaceOperand(BI, 0, X);
4374 }
4375
4376 // Canonicalize logical-and-with-invert as logical-or-with-invert.
4377 // This is done by inverting the condition and swapping successors:
4378 // br (X && !Y), T, F --> br !(X && !Y), F, T --> br (!X || Y), F, T
4379 Value *Y;
4380 if (isa<SelectInst>(Cond) &&
4381 match(Cond,
4383 Value *NotX = Builder.CreateNot(X, "not." + X->getName());
4384 Value *Or = Builder.CreateLogicalOr(NotX, Y);
4385
4386 // Set weights for the new OR select instruction too.
4387 if (auto *OrInst = dyn_cast<Instruction>(Or)) {
4388 if (auto *CondInst = dyn_cast<Instruction>(Cond)) {
4389 SmallVector<uint32_t> Weights;
4390 if (extractBranchWeights(*CondInst, Weights)) {
4391 assert(Weights.size() == 2 && "Unexpected number of branch weights!");
4392 std::swap(Weights[0], Weights[1]);
4393 setBranchWeights(*OrInst, Weights, /*IsExpected=*/false);
4394 }
4395 }
4396 }
4397 BI.swapSuccessors();
4398 if (BPI)
4399 BPI->swapSuccEdgesProbabilities(BI.getParent());
4400 return replaceOperand(BI, 0, Or);
4401 }
4402
4403 // If the condition is irrelevant, remove the use so that other
4404 // transforms on the condition become more effective.
4405 if (!isa<ConstantInt>(Cond) && BI.getSuccessor(0) == BI.getSuccessor(1))
4406 return replaceOperand(BI, 0, ConstantInt::getFalse(Cond->getType()));
4407
4408 // Canonicalize, for example, fcmp_one -> fcmp_oeq.
4409 CmpPredicate Pred;
4410 if (match(Cond, m_OneUse(m_FCmp(Pred, m_Value(), m_Value()))) &&
4411 !isCanonicalPredicate(Pred)) {
4412 // Swap destinations and condition.
4413 auto *Cmp = cast<CmpInst>(Cond);
4414 Cmp->setPredicate(CmpInst::getInversePredicate(Pred));
4415 BI.swapSuccessors();
4416 if (BPI)
4417 BPI->swapSuccEdgesProbabilities(BI.getParent());
4418 Worklist.push(Cmp);
4419 return &BI;
4420 }
4421
4422 if (isa<UndefValue>(Cond)) {
4423 handlePotentiallyDeadSuccessors(BI.getParent(), /*LiveSucc*/ nullptr);
4424 return nullptr;
4425 }
4426 if (auto *CI = dyn_cast<ConstantInt>(Cond)) {
4428 BI.getSuccessor(!CI->getZExtValue()));
4429 return nullptr;
4430 }
4431
4432 // Replace all dominated uses of the condition with true/false
4433 // Ignore constant expressions to avoid iterating over uses on other
4434 // functions.
4435 if (!isa<Constant>(Cond) && BI.getSuccessor(0) != BI.getSuccessor(1)) {
4436 for (auto &U : make_early_inc_range(Cond->uses())) {
4437 BasicBlockEdge Edge0(BI.getParent(), BI.getSuccessor(0));
4438 if (DT.dominates(Edge0, U)) {
4439 replaceUse(U, ConstantInt::getTrue(Cond->getType()));
4440 addToWorklist(cast<Instruction>(U.getUser()));
4441 continue;
4442 }
4443 BasicBlockEdge Edge1(BI.getParent(), BI.getSuccessor(1));
4444 if (DT.dominates(Edge1, U)) {
4445 replaceUse(U, ConstantInt::getFalse(Cond->getType()));
4446 addToWorklist(cast<Instruction>(U.getUser()));
4447 }
4448 }
4449 }
4450
4451 DC.registerBranch(&BI);
4452 return nullptr;
4453}
4454
4455// Replaces (switch (select cond, X, C)/(select cond, C, X)) with (switch X) if
4456// we can prove that both (switch C) and (switch X) go to the default when cond
4457// is false/true.
4460 bool IsTrueArm) {
4461 unsigned CstOpIdx = IsTrueArm ? 1 : 2;
4462 auto *C = dyn_cast<ConstantInt>(Select->getOperand(CstOpIdx));
4463 if (!C)
4464 return nullptr;
4465
4466 BasicBlock *CstBB = SI.findCaseValue(C)->getCaseSuccessor();
4467 if (CstBB != SI.getDefaultDest())
4468 return nullptr;
4469 Value *X = Select->getOperand(3 - CstOpIdx);
4471 const APInt *RHSC;
4472 if (!match(Select->getCondition(),
4473 m_ICmp(Pred, m_Specific(X), m_APInt(RHSC))))
4474 return nullptr;
4475 if (IsTrueArm)
4477
4478 // See whether we can replace the select with X
4480 for (auto Case : SI.cases())
4481 if (!CR.contains(Case.getCaseValue()->getValue()))
4482 return nullptr;
4483
4484 return X;
4485}
4486
4488 Value *Cond = SI.getCondition();
4489 Value *Op0;
4490 const APInt *CondOpC;
4491 using InvertFn = std::function<APInt(const APInt &Case, const APInt &C)>;
4492
4493 auto MaybeInvertible = [&](Value *Cond) -> InvertFn {
4494 if (match(Cond, m_Add(m_Value(Op0), m_APInt(CondOpC))))
4495 // Change 'switch (X+C) case Case:' into 'switch (X) case Case-C'.
4496 return [](const APInt &Case, const APInt &C) { return Case - C; };
4497
4498 if (match(Cond, m_Sub(m_APInt(CondOpC), m_Value(Op0))))
4499 // Change 'switch (C-X) case Case:' into 'switch (X) case C-Case'.
4500 return [](const APInt &Case, const APInt &C) { return C - Case; };
4501
4502 if (match(Cond, m_Xor(m_Value(Op0), m_APInt(CondOpC))) &&
4503 !CondOpC->isMinSignedValue() && !CondOpC->isMaxSignedValue())
4504 // Change 'switch (X^C) case Case:' into 'switch (X) case Case^C'.
4505 // Prevent creation of large case values by excluding extremes.
4506 return [](const APInt &Case, const APInt &C) { return Case ^ C; };
4507
4508 return nullptr;
4509 };
4510
4511 // Attempt to invert and simplify the switch condition, as long as the
4512 // condition is not used further, as it may not be profitable otherwise.
4513 if (auto InvertFn = MaybeInvertible(Cond); InvertFn && Cond->hasOneUse()) {
4514 for (auto &Case : SI.cases()) {
4515 const APInt &New = InvertFn(Case.getCaseValue()->getValue(), *CondOpC);
4516 Case.setValue(ConstantInt::get(SI.getContext(), New));
4517 }
4518 return replaceOperand(SI, 0, Op0);
4519 }
4520
4521 uint64_t ShiftAmt;
4522 if (match(Cond, m_Shl(m_Value(Op0), m_ConstantInt(ShiftAmt))) &&
4523 ShiftAmt < Op0->getType()->getScalarSizeInBits() &&
4524 all_of(SI.cases(), [&](const auto &Case) {
4525 return Case.getCaseValue()->getValue().countr_zero() >= ShiftAmt;
4526 })) {
4527 // Change 'switch (X << 2) case 4:' into 'switch (X) case 1:'.
4529 if (Shl->hasNoUnsignedWrap() || Shl->hasNoSignedWrap() ||
4530 Shl->hasOneUse()) {
4531 Value *NewCond = Op0;
4532 if (!Shl->hasNoUnsignedWrap() && !Shl->hasNoSignedWrap()) {
4533 // If the shift may wrap, we need to mask off the shifted bits.
4534 unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
4535 NewCond = Builder.CreateAnd(
4536 Op0, APInt::getLowBitsSet(BitWidth, BitWidth - ShiftAmt));
4537 }
4538 for (auto Case : SI.cases()) {
4539 const APInt &CaseVal = Case.getCaseValue()->getValue();
4540 APInt ShiftedCase = Shl->hasNoSignedWrap() ? CaseVal.ashr(ShiftAmt)
4541 : CaseVal.lshr(ShiftAmt);
4542 Case.setValue(ConstantInt::get(SI.getContext(), ShiftedCase));
4543 }
4544 return replaceOperand(SI, 0, NewCond);
4545 }
4546 }
4547
4548 // Fold switch(zext/sext(X)) into switch(X) if possible.
4549 if (match(Cond, m_ZExtOrSExt(m_Value(Op0)))) {
4550 bool IsZExt = isa<ZExtInst>(Cond);
4551 Type *SrcTy = Op0->getType();
4552 unsigned NewWidth = SrcTy->getScalarSizeInBits();
4553
4554 if (all_of(SI.cases(), [&](const auto &Case) {
4555 const APInt &CaseVal = Case.getCaseValue()->getValue();
4556 return IsZExt ? CaseVal.isIntN(NewWidth)
4557 : CaseVal.isSignedIntN(NewWidth);
4558 })) {
4559 for (auto &Case : SI.cases()) {
4560 APInt TruncatedCase = Case.getCaseValue()->getValue().trunc(NewWidth);
4561 Case.setValue(ConstantInt::get(SI.getContext(), TruncatedCase));
4562 }
4563 return replaceOperand(SI, 0, Op0);
4564 }
4565 }
4566
4567 // Fold switch(select cond, X, Y) into switch(X/Y) if possible
4568 if (auto *Select = dyn_cast<SelectInst>(Cond)) {
4569 if (Value *V =
4570 simplifySwitchOnSelectUsingRanges(SI, Select, /*IsTrueArm=*/true))
4571 return replaceOperand(SI, 0, V);
4572 if (Value *V =
4573 simplifySwitchOnSelectUsingRanges(SI, Select, /*IsTrueArm=*/false))
4574 return replaceOperand(SI, 0, V);
4575 }
4576
4578 unsigned LeadingKnownZeros = Known.countMinLeadingZeros();
4579 unsigned LeadingKnownOnes = Known.countMinLeadingOnes();
4580
4581 // Compute the number of leading bits we can ignore.
4582 // TODO: A better way to determine this would use ComputeNumSignBits().
4583 for (const auto &C : SI.cases()) {
4584 LeadingKnownZeros =
4585 std::min(LeadingKnownZeros, C.getCaseValue()->getValue().countl_zero());
4586 LeadingKnownOnes =
4587 std::min(LeadingKnownOnes, C.getCaseValue()->getValue().countl_one());
4588 }
4589
4590 unsigned NewWidth = Known.getBitWidth() - std::max(LeadingKnownZeros, LeadingKnownOnes);
4591
4592 // Shrink the condition operand if the new type is smaller than the old type.
4593 // But do not shrink to a non-standard type, because backend can't generate
4594 // good code for that yet.
4595 // TODO: We can make it aggressive again after fixing PR39569.
4596 if (NewWidth > 0 && NewWidth < Known.getBitWidth() &&
4597 shouldChangeType(Known.getBitWidth(), NewWidth)) {
4598 IntegerType *Ty = IntegerType::get(SI.getContext(), NewWidth);
4599 Builder.SetInsertPoint(&SI);
4600 Value *NewCond = Builder.CreateTrunc(Cond, Ty, "trunc");
4601
4602 for (auto Case : SI.cases()) {
4603 APInt TruncatedCase = Case.getCaseValue()->getValue().trunc(NewWidth);
4604 Case.setValue(ConstantInt::get(SI.getContext(), TruncatedCase));
4605 }
4606 return replaceOperand(SI, 0, NewCond);
4607 }
4608
4609 if (isa<UndefValue>(Cond)) {
4610 handlePotentiallyDeadSuccessors(SI.getParent(), /*LiveSucc*/ nullptr);
4611 return nullptr;
4612 }
4613 if (auto *CI = dyn_cast<ConstantInt>(Cond)) {
4615 SI.findCaseValue(CI)->getCaseSuccessor());
4616 return nullptr;
4617 }
4618
4619 return nullptr;
4620}
4621
4623InstCombinerImpl::foldExtractOfOverflowIntrinsic(ExtractValueInst &EV) {
4625 if (!WO)
4626 return nullptr;
4627
4628 Intrinsic::ID OvID = WO->getIntrinsicID();
4629 const APInt *C = nullptr;
4630 if (match(WO->getRHS(), m_APIntAllowPoison(C))) {
4631 if (*EV.idx_begin() == 0 && (OvID == Intrinsic::smul_with_overflow ||
4632 OvID == Intrinsic::umul_with_overflow)) {
4633 // extractvalue (any_mul_with_overflow X, -1), 0 --> -X
4634 if (C->isAllOnes())
4635 return BinaryOperator::CreateNeg(WO->getLHS());
4636 // extractvalue (any_mul_with_overflow X, 2^n), 0 --> X << n
4637 if (C->isPowerOf2()) {
4638 return BinaryOperator::CreateShl(
4639 WO->getLHS(),
4640 ConstantInt::get(WO->getLHS()->getType(), C->logBase2()));
4641 }
4642 }
4643 }
4644
4645 // We're extracting from an overflow intrinsic. See if we're the only user.
4646 // That allows us to simplify multiple result intrinsics to simpler things
4647 // that just get one value.
4648 if (!WO->hasOneUse())
4649 return nullptr;
4650
4651 // Check if we're grabbing only the result of a 'with overflow' intrinsic
4652 // and replace it with a traditional binary instruction.
4653 if (*EV.idx_begin() == 0) {
4654 Instruction::BinaryOps BinOp = WO->getBinaryOp();
4655 Value *LHS = WO->getLHS(), *RHS = WO->getRHS();
4656 // Replace the old instruction's uses with poison.
4657 replaceInstUsesWith(*WO, PoisonValue::get(WO->getType()));
4659 return BinaryOperator::Create(BinOp, LHS, RHS);
4660 }
4661
4662 assert(*EV.idx_begin() == 1 && "Unexpected extract index for overflow inst");
4663
4664 // (usub LHS, RHS) overflows when LHS is unsigned-less-than RHS.
4665 if (OvID == Intrinsic::usub_with_overflow)
4666 return new ICmpInst(ICmpInst::ICMP_ULT, WO->getLHS(), WO->getRHS());
4667
4668 // smul with i1 types overflows when both sides are set: -1 * -1 == +1, but
4669 // +1 is not possible because we assume signed values.
4670 if (OvID == Intrinsic::smul_with_overflow &&
4671 WO->getLHS()->getType()->isIntOrIntVectorTy(1))
4672 return BinaryOperator::CreateAnd(WO->getLHS(), WO->getRHS());
4673
4674 // extractvalue (umul_with_overflow X, X), 1 -> X u> 2^(N/2)-1
4675 if (OvID == Intrinsic::umul_with_overflow && WO->getLHS() == WO->getRHS()) {
4676 unsigned BitWidth = WO->getLHS()->getType()->getScalarSizeInBits();
4677 // Only handle even bitwidths for performance reasons.
4678 if (BitWidth % 2 == 0)
4679 return new ICmpInst(
4680 ICmpInst::ICMP_UGT, WO->getLHS(),
4681 ConstantInt::get(WO->getLHS()->getType(),
4683 }
4684
4685 // If only the overflow result is used, and the right hand side is a
4686 // constant (or constant splat), we can remove the intrinsic by directly
4687 // checking for overflow.
4688 if (C) {
4689 // Compute the no-wrap range for LHS given RHS=C, then construct an
4690 // equivalent icmp, potentially using an offset.
4691 ConstantRange NWR = ConstantRange::makeExactNoWrapRegion(
4692 WO->getBinaryOp(), *C, WO->getNoWrapKind());
4693
4695 APInt NewRHSC, Offset;
4696 NWR.getEquivalentICmp(Pred, NewRHSC, Offset);
4697 auto *OpTy = WO->getRHS()->getType();
4698 auto *NewLHS = WO->getLHS();
4699 if (Offset != 0)
4700 NewLHS = Builder.CreateAdd(NewLHS, ConstantInt::get(OpTy, Offset));
4701 return new ICmpInst(ICmpInst::getInversePredicate(Pred), NewLHS,
4702 ConstantInt::get(OpTy, NewRHSC));
4703 }
4704
4705 return nullptr;
4706}
4707
4710 InstCombiner::BuilderTy &Builder) {
4711 // Helper to fold frexp of select to select of frexp.
4712
4713 if (!SelectInst->hasOneUse() || !FrexpCall->hasOneUse())
4714 return nullptr;
4716 Value *TrueVal = SelectInst->getTrueValue();
4717 Value *FalseVal = SelectInst->getFalseValue();
4718
4719 const APFloat *ConstVal = nullptr;
4720 Value *VarOp = nullptr;
4721 bool ConstIsTrue = false;
4722
4723 if (match(TrueVal, m_APFloat(ConstVal))) {
4724 VarOp = FalseVal;
4725 ConstIsTrue = true;
4726 } else if (match(FalseVal, m_APFloat(ConstVal))) {
4727 VarOp = TrueVal;
4728 ConstIsTrue = false;
4729 } else {
4730 return nullptr;
4731 }
4732
4733 Builder.SetInsertPoint(&EV);
4734
4735 CallInst *NewFrexp =
4736 Builder.CreateCall(FrexpCall->getCalledFunction(), {VarOp}, "frexp");
4737 NewFrexp->copyIRFlags(FrexpCall);
4738
4739 Value *NewEV = Builder.CreateExtractValue(NewFrexp, 0, "mantissa");
4740
4741 int Exp;
4742 APFloat Mantissa = frexp(*ConstVal, Exp, APFloat::rmNearestTiesToEven);
4743
4744 Constant *ConstantMantissa = ConstantFP::get(TrueVal->getType(), Mantissa);
4745
4746 Value *NewSel = Builder.CreateSelectFMF(
4747 Cond, ConstIsTrue ? ConstantMantissa : NewEV,
4748 ConstIsTrue ? NewEV : ConstantMantissa, SelectInst, "select.frexp",
4750 return NewSel;
4751}
4753 Value *Agg = EV.getAggregateOperand();
4754
4755 if (!EV.hasIndices())
4756 return replaceInstUsesWith(EV, Agg);
4757
4758 if (Value *V = simplifyExtractValueInst(Agg, EV.getIndices(),
4759 SQ.getWithInstruction(&EV)))
4760 return replaceInstUsesWith(EV, V);
4761
4762 Value *Cond, *TrueVal, *FalseVal;
4764 m_Value(Cond), m_Value(TrueVal), m_Value(FalseVal)))))) {
4765 auto *SelInst =
4766 cast<SelectInst>(cast<IntrinsicInst>(Agg)->getArgOperand(0));
4767 if (Value *Result =
4768 foldFrexpOfSelect(EV, cast<IntrinsicInst>(Agg), SelInst, Builder))
4769 return replaceInstUsesWith(EV, Result);
4770 }
4772 // We're extracting from an insertvalue instruction, compare the indices
4773 const unsigned *exti, *exte, *insi, *inse;
4774 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
4775 exte = EV.idx_end(), inse = IV->idx_end();
4776 exti != exte && insi != inse;
4777 ++exti, ++insi) {
4778 if (*insi != *exti)
4779 // The insert and extract both reference distinctly different elements.
4780 // This means the extract is not influenced by the insert, and we can
4781 // replace the aggregate operand of the extract with the aggregate
4782 // operand of the insert. i.e., replace
4783 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
4784 // %E = extractvalue { i32, { i32 } } %I, 0
4785 // with
4786 // %E = extractvalue { i32, { i32 } } %A, 0
4787 return ExtractValueInst::Create(IV->getAggregateOperand(),
4788 EV.getIndices());
4789 }
4790 if (exti == exte && insi == inse)
4791 // Both iterators are at the end: Index lists are identical. Replace
4792 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
4793 // %C = extractvalue { i32, { i32 } } %B, 1, 0
4794 // with "i32 42"
4795 return replaceInstUsesWith(EV, IV->getInsertedValueOperand());
4796 if (exti == exte) {
4797 // The extract list is a prefix of the insert list. i.e. replace
4798 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
4799 // %E = extractvalue { i32, { i32 } } %I, 1
4800 // with
4801 // %X = extractvalue { i32, { i32 } } %A, 1
4802 // %E = insertvalue { i32 } %X, i32 42, 0
4803 // by switching the order of the insert and extract (though the
4804 // insertvalue should be left in, since it may have other uses).
4805 Value *NewEV = Builder.CreateExtractValue(IV->getAggregateOperand(),
4806 EV.getIndices());
4807 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
4808 ArrayRef(insi, inse));
4809 }
4810 if (insi == inse)
4811 // The insert list is a prefix of the extract list
4812 // We can simply remove the common indices from the extract and make it
4813 // operate on the inserted value instead of the insertvalue result.
4814 // i.e., replace
4815 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
4816 // %E = extractvalue { i32, { i32 } } %I, 1, 0
4817 // with
4818 // %E extractvalue { i32 } { i32 42 }, 0
4819 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
4820 ArrayRef(exti, exte));
4821 }
4822
4823 if (Instruction *R = foldExtractOfOverflowIntrinsic(EV))
4824 return R;
4825
4826 if (LoadInst *L = dyn_cast<LoadInst>(Agg)) {
4827 // Bail out if the aggregate contains scalable vector type
4828 if (auto *STy = dyn_cast<StructType>(Agg->getType());
4829 STy && STy->isScalableTy())
4830 return nullptr;
4831
4832 // If the (non-volatile) load only has one use, we can rewrite this to a
4833 // load from a GEP. This reduces the size of the load. If a load is used
4834 // only by extractvalue instructions then this either must have been
4835 // optimized before, or it is a struct with padding, in which case we
4836 // don't want to do the transformation as it loses padding knowledge.
4837 if (L->isSimple() && L->hasOneUse()) {
4838 // extractvalue has integer indices, getelementptr has Value*s. Convert.
4839 SmallVector<Value*, 4> Indices;
4840 // Prefix an i32 0 since we need the first element.
4841 Indices.push_back(Builder.getInt32(0));
4842 for (unsigned Idx : EV.indices())
4843 Indices.push_back(Builder.getInt32(Idx));
4844
4845 // We need to insert these at the location of the old load, not at that of
4846 // the extractvalue.
4847 Builder.SetInsertPoint(L);
4848 Value *GEP = Builder.CreateInBoundsGEP(L->getType(),
4849 L->getPointerOperand(), Indices);
4850 Instruction *NL = Builder.CreateLoad(EV.getType(), GEP);
4851 // Whatever aliasing information we had for the orignal load must also
4852 // hold for the smaller load, so propagate the annotations.
4853 NL->setAAMetadata(L->getAAMetadata());
4854 // Returning the load directly will cause the main loop to insert it in
4855 // the wrong spot, so use replaceInstUsesWith().
4856 return replaceInstUsesWith(EV, NL);
4857 }
4858 }
4859
4860 if (auto *PN = dyn_cast<PHINode>(Agg))
4861 if (Instruction *Res = foldOpIntoPhi(EV, PN))
4862 return Res;
4863
4864 // Canonicalize extract (select Cond, TV, FV)
4865 // -> select cond, (extract TV), (extract FV)
4866 if (auto *SI = dyn_cast<SelectInst>(Agg))
4867 if (Instruction *R = FoldOpIntoSelect(EV, SI, /*FoldWithMultiUse=*/true))
4868 return R;
4869
4870 // We could simplify extracts from other values. Note that nested extracts may
4871 // already be simplified implicitly by the above: extract (extract (insert) )
4872 // will be translated into extract ( insert ( extract ) ) first and then just
4873 // the value inserted, if appropriate. Similarly for extracts from single-use
4874 // loads: extract (extract (load)) will be translated to extract (load (gep))
4875 // and if again single-use then via load (gep (gep)) to load (gep).
4876 // However, double extracts from e.g. function arguments or return values
4877 // aren't handled yet.
4878 return nullptr;
4879}
4880
4882 Value *Base = BI.getOperand(0);
4883 Value *Val = BI.getOperand(1);
4884 Value *Offset = BI.getOperand(2);
4885 if (Value *V =
4886 simplifyBitInsertInst(Base, Val, Offset, SQ.getWithInstruction(&BI)))
4887 return replaceInstUsesWith(BI, V);
4888
4889 // bitinsert (bN x), (ty y), 0 -> bitcast y to bN, if ty is N bits wide
4890 if (match(Offset, m_Zero()) && DL.getTypeSizeInBits(Val->getType()) ==
4891 DL.getTypeSizeInBits(Base->getType()))
4892 return new BitCastInst(Val, Base->getType());
4893
4894 return nullptr;
4895}
4896
4898 Value *Src = BE.getOperand(0);
4899 Value *Offset = BE.getOperand(1);
4900 if (Value *V = simplifyBitExtractInst(BE.getType(), Src, Offset,
4901 SQ.getWithInstruction(&BE)))
4902 return replaceInstUsesWith(BE, V);
4903
4904 // bitextract ty, (bN x), 0 -> bitcast x to ty, if ty is N bits wide
4905 if (match(Offset, m_Zero()) && DL.getTypeSizeInBits(BE.getType()) ==
4906 DL.getTypeSizeInBits(Src->getType()))
4907 return new BitCastInst(Src, BE.getType());
4908
4909 return nullptr;
4910}
4911
4912/// Return 'true' if the given typeinfo will match anything.
4913static bool isCatchAll(EHPersonality Personality, Constant *TypeInfo) {
4914 switch (Personality) {
4918 // The GCC C EH and Rust personality only exists to support cleanups, so
4919 // it's not clear what the semantics of catch clauses are.
4920 return false;
4922 return false;
4924 // While __gnat_all_others_value will match any Ada exception, it doesn't
4925 // match foreign exceptions (or didn't, before gcc-4.7).
4926 return false;
4938 return isa<ConstantPointerNull>(TypeInfo);
4939 }
4940 llvm_unreachable("invalid enum");
4941}
4942
4943static bool shorter_filter(const Value *LHS, const Value *RHS) {
4944 return
4945 cast<ArrayType>(LHS->getType())->getNumElements()
4946 <
4947 cast<ArrayType>(RHS->getType())->getNumElements();
4948}
4949
4951 // The logic here should be correct for any real-world personality function.
4952 // However if that turns out not to be true, the offending logic can always
4953 // be conditioned on the personality function, like the catch-all logic is.
4954 EHPersonality Personality =
4955 classifyEHPersonality(LI.getParent()->getParent()->getPersonalityFn());
4956
4957 // Simplify the list of clauses, eg by removing repeated catch clauses
4958 // (these are often created by inlining).
4959 bool MakeNewInstruction = false; // If true, recreate using the following:
4960 SmallVector<Constant *, 16> NewClauses; // - Clauses for the new instruction;
4961 bool CleanupFlag = LI.isCleanup(); // - The new instruction is a cleanup.
4962
4963 SmallPtrSet<Value *, 16> AlreadyCaught; // Typeinfos known caught already.
4964 for (unsigned i = 0, e = LI.getNumClauses(); i != e; ++i) {
4965 bool isLastClause = i + 1 == e;
4966 if (LI.isCatch(i)) {
4967 // A catch clause.
4968 Constant *CatchClause = LI.getClause(i);
4969 Constant *TypeInfo = CatchClause->stripPointerCasts();
4970
4971 // If we already saw this clause, there is no point in having a second
4972 // copy of it.
4973 if (AlreadyCaught.insert(TypeInfo).second) {
4974 // This catch clause was not already seen.
4975 NewClauses.push_back(CatchClause);
4976 } else {
4977 // Repeated catch clause - drop the redundant copy.
4978 MakeNewInstruction = true;
4979 }
4980
4981 // If this is a catch-all then there is no point in keeping any following
4982 // clauses or marking the landingpad as having a cleanup.
4983 if (isCatchAll(Personality, TypeInfo)) {
4984 if (!isLastClause)
4985 MakeNewInstruction = true;
4986 CleanupFlag = false;
4987 break;
4988 }
4989 } else {
4990 // A filter clause. If any of the filter elements were already caught
4991 // then they can be dropped from the filter. It is tempting to try to
4992 // exploit the filter further by saying that any typeinfo that does not
4993 // occur in the filter can't be caught later (and thus can be dropped).
4994 // However this would be wrong, since typeinfos can match without being
4995 // equal (for example if one represents a C++ class, and the other some
4996 // class derived from it).
4997 assert(LI.isFilter(i) && "Unsupported landingpad clause!");
4998 Constant *FilterClause = LI.getClause(i);
4999 ArrayType *FilterType = cast<ArrayType>(FilterClause->getType());
5000 unsigned NumTypeInfos = FilterType->getNumElements();
5001
5002 // An empty filter catches everything, so there is no point in keeping any
5003 // following clauses or marking the landingpad as having a cleanup. By
5004 // dealing with this case here the following code is made a bit simpler.
5005 if (!NumTypeInfos) {
5006 NewClauses.push_back(FilterClause);
5007 if (!isLastClause)
5008 MakeNewInstruction = true;
5009 CleanupFlag = false;
5010 break;
5011 }
5012
5013 bool MakeNewFilter = false; // If true, make a new filter.
5014 SmallVector<Constant *, 16> NewFilterElts; // New elements.
5015 if (isa<ConstantAggregateZero>(FilterClause)) {
5016 // Not an empty filter - it contains at least one null typeinfo.
5017 assert(NumTypeInfos > 0 && "Should have handled empty filter already!");
5018 Constant *TypeInfo =
5020 // If this typeinfo is a catch-all then the filter can never match.
5021 if (isCatchAll(Personality, TypeInfo)) {
5022 // Throw the filter away.
5023 MakeNewInstruction = true;
5024 continue;
5025 }
5026
5027 // There is no point in having multiple copies of this typeinfo, so
5028 // discard all but the first copy if there is more than one.
5029 NewFilterElts.push_back(TypeInfo);
5030 if (NumTypeInfos > 1)
5031 MakeNewFilter = true;
5032 } else {
5033 ConstantArray *Filter = cast<ConstantArray>(FilterClause);
5034 SmallPtrSet<Value *, 16> SeenInFilter; // For uniquing the elements.
5035 NewFilterElts.reserve(NumTypeInfos);
5036
5037 // Remove any filter elements that were already caught or that already
5038 // occurred in the filter. While there, see if any of the elements are
5039 // catch-alls. If so, the filter can be discarded.
5040 bool SawCatchAll = false;
5041 for (unsigned j = 0; j != NumTypeInfos; ++j) {
5042 Constant *Elt = Filter->getOperand(j);
5043 Constant *TypeInfo = Elt->stripPointerCasts();
5044 if (isCatchAll(Personality, TypeInfo)) {
5045 // This element is a catch-all. Bail out, noting this fact.
5046 SawCatchAll = true;
5047 break;
5048 }
5049
5050 // Even if we've seen a type in a catch clause, we don't want to
5051 // remove it from the filter. An unexpected type handler may be
5052 // set up for a call site which throws an exception of the same
5053 // type caught. In order for the exception thrown by the unexpected
5054 // handler to propagate correctly, the filter must be correctly
5055 // described for the call site.
5056 //
5057 // Example:
5058 //
5059 // void unexpected() { throw 1;}
5060 // void foo() throw (int) {
5061 // std::set_unexpected(unexpected);
5062 // try {
5063 // throw 2.0;
5064 // } catch (int i) {}
5065 // }
5066
5067 // There is no point in having multiple copies of the same typeinfo in
5068 // a filter, so only add it if we didn't already.
5069 if (SeenInFilter.insert(TypeInfo).second)
5070 NewFilterElts.push_back(cast<Constant>(Elt));
5071 }
5072 // A filter containing a catch-all cannot match anything by definition.
5073 if (SawCatchAll) {
5074 // Throw the filter away.
5075 MakeNewInstruction = true;
5076 continue;
5077 }
5078
5079 // If we dropped something from the filter, make a new one.
5080 if (NewFilterElts.size() < NumTypeInfos)
5081 MakeNewFilter = true;
5082 }
5083 if (MakeNewFilter) {
5084 FilterType = ArrayType::get(FilterType->getElementType(),
5085 NewFilterElts.size());
5086 FilterClause = ConstantArray::get(FilterType, NewFilterElts);
5087 MakeNewInstruction = true;
5088 }
5089
5090 NewClauses.push_back(FilterClause);
5091
5092 // If the new filter is empty then it will catch everything so there is
5093 // no point in keeping any following clauses or marking the landingpad
5094 // as having a cleanup. The case of the original filter being empty was
5095 // already handled above.
5096 if (MakeNewFilter && !NewFilterElts.size()) {
5097 assert(MakeNewInstruction && "New filter but not a new instruction!");
5098 CleanupFlag = false;
5099 break;
5100 }
5101 }
5102 }
5103
5104 // If several filters occur in a row then reorder them so that the shortest
5105 // filters come first (those with the smallest number of elements). This is
5106 // advantageous because shorter filters are more likely to match, speeding up
5107 // unwinding, but mostly because it increases the effectiveness of the other
5108 // filter optimizations below.
5109 for (unsigned i = 0, e = NewClauses.size(); i + 1 < e; ) {
5110 unsigned j;
5111 // Find the maximal 'j' s.t. the range [i, j) consists entirely of filters.
5112 for (j = i; j != e; ++j)
5113 if (!isa<ArrayType>(NewClauses[j]->getType()))
5114 break;
5115
5116 // Check whether the filters are already sorted by length. We need to know
5117 // if sorting them is actually going to do anything so that we only make a
5118 // new landingpad instruction if it does.
5119 for (unsigned k = i; k + 1 < j; ++k)
5120 if (shorter_filter(NewClauses[k+1], NewClauses[k])) {
5121 // Not sorted, so sort the filters now. Doing an unstable sort would be
5122 // correct too but reordering filters pointlessly might confuse users.
5123 std::stable_sort(NewClauses.begin() + i, NewClauses.begin() + j,
5125 MakeNewInstruction = true;
5126 break;
5127 }
5128
5129 // Look for the next batch of filters.
5130 i = j + 1;
5131 }
5132
5133 // If typeinfos matched if and only if equal, then the elements of a filter L
5134 // that occurs later than a filter F could be replaced by the intersection of
5135 // the elements of F and L. In reality two typeinfos can match without being
5136 // equal (for example if one represents a C++ class, and the other some class
5137 // derived from it) so it would be wrong to perform this transform in general.
5138 // However the transform is correct and useful if F is a subset of L. In that
5139 // case L can be replaced by F, and thus removed altogether since repeating a
5140 // filter is pointless. So here we look at all pairs of filters F and L where
5141 // L follows F in the list of clauses, and remove L if every element of F is
5142 // an element of L. This can occur when inlining C++ functions with exception
5143 // specifications.
5144 for (unsigned i = 0; i + 1 < NewClauses.size(); ++i) {
5145 // Examine each filter in turn.
5146 Value *Filter = NewClauses[i];
5147 ArrayType *FTy = dyn_cast<ArrayType>(Filter->getType());
5148 if (!FTy)
5149 // Not a filter - skip it.
5150 continue;
5151 unsigned FElts = FTy->getNumElements();
5152 // Examine each filter following this one. Doing this backwards means that
5153 // we don't have to worry about filters disappearing under us when removed.
5154 for (unsigned j = NewClauses.size() - 1; j != i; --j) {
5155 Value *LFilter = NewClauses[j];
5156 ArrayType *LTy = dyn_cast<ArrayType>(LFilter->getType());
5157 if (!LTy)
5158 // Not a filter - skip it.
5159 continue;
5160 // If Filter is a subset of LFilter, i.e. every element of Filter is also
5161 // an element of LFilter, then discard LFilter.
5162 SmallVectorImpl<Constant *>::iterator J = NewClauses.begin() + j;
5163 // If Filter is empty then it is a subset of LFilter.
5164 if (!FElts) {
5165 // Discard LFilter.
5166 NewClauses.erase(J);
5167 MakeNewInstruction = true;
5168 // Move on to the next filter.
5169 continue;
5170 }
5171 unsigned LElts = LTy->getNumElements();
5172 // If Filter is longer than LFilter then it cannot be a subset of it.
5173 if (FElts > LElts)
5174 // Move on to the next filter.
5175 continue;
5176 // At this point we know that LFilter has at least one element.
5177 if (isa<ConstantAggregateZero>(LFilter)) { // LFilter only contains zeros.
5178 // Filter is a subset of LFilter iff Filter contains only zeros (as we
5179 // already know that Filter is not longer than LFilter).
5181 assert(FElts <= LElts && "Should have handled this case earlier!");
5182 // Discard LFilter.
5183 NewClauses.erase(J);
5184 MakeNewInstruction = true;
5185 }
5186 // Move on to the next filter.
5187 continue;
5188 }
5189 ConstantArray *LArray = cast<ConstantArray>(LFilter);
5190 if (isa<ConstantAggregateZero>(Filter)) { // Filter only contains zeros.
5191 // Since Filter is non-empty and contains only zeros, it is a subset of
5192 // LFilter iff LFilter contains a zero.
5193 assert(FElts > 0 && "Should have eliminated the empty filter earlier!");
5194 for (unsigned l = 0; l != LElts; ++l)
5195 if (isa<ConstantPointerNull>(LArray->getOperand(l))) {
5196 // LFilter contains a zero - discard it.
5197 NewClauses.erase(J);
5198 MakeNewInstruction = true;
5199 break;
5200 }
5201 // Move on to the next filter.
5202 continue;
5203 }
5204 // At this point we know that both filters are ConstantArrays. Loop over
5205 // operands to see whether every element of Filter is also an element of
5206 // LFilter. Since filters tend to be short this is probably faster than
5207 // using a method that scales nicely.
5209 bool AllFound = true;
5210 for (unsigned f = 0; f != FElts; ++f) {
5211 Value *FTypeInfo = FArray->getOperand(f)->stripPointerCasts();
5212 AllFound = false;
5213 for (unsigned l = 0; l != LElts; ++l) {
5214 Value *LTypeInfo = LArray->getOperand(l)->stripPointerCasts();
5215 if (LTypeInfo == FTypeInfo) {
5216 AllFound = true;
5217 break;
5218 }
5219 }
5220 if (!AllFound)
5221 break;
5222 }
5223 if (AllFound) {
5224 // Discard LFilter.
5225 NewClauses.erase(J);
5226 MakeNewInstruction = true;
5227 }
5228 // Move on to the next filter.
5229 }
5230 }
5231
5232 // If we changed any of the clauses, replace the old landingpad instruction
5233 // with a new one.
5234 if (MakeNewInstruction) {
5236 NewClauses.size());
5237 for (Constant *C : NewClauses)
5238 NLI->addClause(C);
5239 // A landing pad with no clauses must have the cleanup flag set. It is
5240 // theoretically possible, though highly unlikely, that we eliminated all
5241 // clauses. If so, force the cleanup flag to true.
5242 if (NewClauses.empty())
5243 CleanupFlag = true;
5244 NLI->setCleanup(CleanupFlag);
5245 return NLI;
5246 }
5247
5248 // Even if none of the clauses changed, we may nonetheless have understood
5249 // that the cleanup flag is pointless. Clear it if so.
5250 if (LI.isCleanup() != CleanupFlag) {
5251 assert(!CleanupFlag && "Adding a cleanup, not removing one?!");
5252 LI.setCleanup(CleanupFlag);
5253 return &LI;
5254 }
5255
5256 return nullptr;
5257}
5258
5259Value *
5261 // Try to push freeze through instructions that propagate but don't produce
5262 // poison as far as possible. If an operand of freeze follows three
5263 // conditions 1) one-use, 2) does not produce poison, and 3) has all but one
5264 // guaranteed-non-poison operands then push the freeze through to the one
5265 // operand that is not guaranteed non-poison. The actual transform is as
5266 // follows.
5267 // Op1 = ... ; Op1 can be posion
5268 // Op0 = Inst(Op1, NonPoisonOps...) ; Op0 has only one use and only have
5269 // ; single guaranteed-non-poison operands
5270 // ... = Freeze(Op0)
5271 // =>
5272 // Op1 = ...
5273 // Op1.fr = Freeze(Op1)
5274 // ... = Inst(Op1.fr, NonPoisonOps...)
5275 auto *OrigOp = OrigFI.getOperand(0);
5276 auto *OrigOpInst = dyn_cast<Instruction>(OrigOp);
5277
5278 // While we could change the other users of OrigOp to use freeze(OrigOp), that
5279 // potentially reduces their optimization potential, so let's only do this iff
5280 // the OrigOp is only used by the freeze.
5281 if (!OrigOpInst || !OrigOpInst->hasOneUse() || isa<PHINode>(OrigOp))
5282 return nullptr;
5283
5284 // We can't push the freeze through an instruction which can itself create
5285 // poison. If the only source of new poison is flags, we can simply
5286 // strip them (since we know the only use is the freeze and nothing can
5287 // benefit from them.)
5289 /*ConsiderFlagsAndMetadata*/ false))
5290 return nullptr;
5291
5292 // If operand is guaranteed not to be poison, there is no need to add freeze
5293 // to the operand. So we first find the operand that is not guaranteed to be
5294 // poison.
5295 Value *MaybePoisonOperand = nullptr;
5296 for (Value *V : OrigOpInst->operands()) {
5298 // Treat identical operands as a single operand.
5299 (MaybePoisonOperand && MaybePoisonOperand == V))
5300 continue;
5301 if (!MaybePoisonOperand)
5302 MaybePoisonOperand = V;
5303 else
5304 return nullptr;
5305 }
5306
5307 OrigOpInst->dropPoisonGeneratingAnnotations();
5308
5309 // If all operands are guaranteed to be non-poison, we can drop freeze.
5310 if (!MaybePoisonOperand)
5311 return OrigOp;
5312
5313 Builder.SetInsertPoint(OrigOpInst);
5314 Value *FrozenMaybePoisonOperand = Builder.CreateFreeze(
5315 MaybePoisonOperand, MaybePoisonOperand->getName() + ".fr");
5316
5317 OrigOpInst->replaceUsesOfWith(MaybePoisonOperand, FrozenMaybePoisonOperand);
5318 return OrigOp;
5319}
5320
5322 PHINode *PN) {
5323 // Detect whether this is a recurrence with a start value and some number of
5324 // backedge values. We'll check whether we can push the freeze through the
5325 // backedge values (possibly dropping poison flags along the way) until we
5326 // reach the phi again. In that case, we can move the freeze to the start
5327 // value.
5328 Use *StartU = nullptr;
5330 for (Use &U : PN->incoming_values()) {
5331 if (DT.dominates(PN->getParent(), PN->getIncomingBlock(U))) {
5332 // Add backedge value to worklist.
5333 Worklist.push_back(U.get());
5334 continue;
5335 }
5336
5337 // Don't bother handling multiple start values.
5338 if (StartU)
5339 return nullptr;
5340 StartU = &U;
5341 }
5342
5343 if (!StartU || Worklist.empty())
5344 return nullptr; // Not a recurrence.
5345
5346 Value *StartV = StartU->get();
5347 BasicBlock *StartBB = PN->getIncomingBlock(*StartU);
5348 bool StartNeedsFreeze = !isGuaranteedNotToBeUndefOrPoison(StartV);
5349 // We can't insert freeze if the start value is the result of the
5350 // terminator (e.g. an invoke).
5351 if (StartNeedsFreeze && StartBB->getTerminator() == StartV)
5352 return nullptr;
5353
5356 while (!Worklist.empty()) {
5357 Value *V = Worklist.pop_back_val();
5358 if (!Visited.insert(V).second)
5359 continue;
5360
5361 if (Visited.size() > 32)
5362 return nullptr; // Limit the total number of values we inspect.
5363
5364 // Assume that PN is non-poison, because it will be after the transform.
5365 if (V == PN || isGuaranteedNotToBeUndefOrPoison(V))
5366 continue;
5367
5370 /*ConsiderFlagsAndMetadata*/ false))
5371 return nullptr;
5372
5373 DropFlags.push_back(I);
5374 append_range(Worklist, I->operands());
5375 }
5376
5377 for (Instruction *I : DropFlags)
5378 I->dropPoisonGeneratingAnnotations();
5379
5380 if (StartNeedsFreeze) {
5381 Builder.SetInsertPoint(StartBB->getTerminator());
5382 Value *FrozenStartV = Builder.CreateFreeze(StartV,
5383 StartV->getName() + ".fr");
5384 replaceUse(*StartU, FrozenStartV);
5385 }
5386 return replaceInstUsesWith(FI, PN);
5387}
5388
5389// Check if any direct or bitcast user of this value is a shuffle instruction.
5391 for (auto *U : V->users()) {
5393 return true;
5395 return true;
5396 }
5397 return false;
5398}
5399
5401 Value *Op0 = I.getOperand(0);
5402
5403 if (Value *V = simplifyFreezeInst(Op0, SQ.getWithInstruction(&I)))
5404 return replaceInstUsesWith(I, V);
5405
5406 // freeze (phi const, x) --> phi const, (freeze x)
5407 if (auto *PN = dyn_cast<PHINode>(Op0)) {
5408 if (Instruction *NV = foldOpIntoPhi(I, PN))
5409 return NV;
5410 if (Instruction *NV = foldFreezeIntoRecurrence(I, PN))
5411 return NV;
5412 }
5413
5415 return replaceInstUsesWith(I, NI);
5416
5417 // If I is freeze(undef), check its uses and fold it to a fixed constant.
5418 // - or: pick -1
5419 // - select's condition: if the true value is constant, choose it by making
5420 // the condition true.
5421 // - phi: pick the common constant across operands
5422 // - default: pick 0
5423 //
5424 // Note that this transform is intentionally done here rather than
5425 // via an analysis in InstSimplify or at individual user sites. That is
5426 // because we must produce the same value for all uses of the freeze -
5427 // it's the reason "freeze" exists!
5428 //
5429 // TODO: This could use getBinopAbsorber() / getBinopIdentity() to avoid
5430 // duplicating logic for binops at least.
5431 auto getUndefReplacement = [&](Type *Ty) {
5432 auto pickCommonConstantFromPHI = [](PHINode &PN) -> Value * {
5433 // phi(freeze(undef), C, C). Choose C for freeze so the PHI can be
5434 // removed.
5435 Constant *BestValue = nullptr;
5436 for (Value *V : PN.incoming_values()) {
5437 if (match(V, m_Freeze(m_Undef())))
5438 continue;
5439
5441 if (!C)
5442 return nullptr;
5443
5445 return nullptr;
5446
5447 if (BestValue && BestValue != C)
5448 return nullptr;
5449
5450 BestValue = C;
5451 }
5452 return BestValue;
5453 };
5454
5455 Value *NullValue = Constant::getNullValue(Ty);
5456 Value *BestValue = nullptr;
5457 for (auto *U : I.users()) {
5458 Value *V = NullValue;
5459 if (match(U, m_Or(m_Value(), m_Value())))
5461 else if (match(U, m_Select(m_Specific(&I), m_Constant(), m_Value())))
5462 V = ConstantInt::getTrue(Ty);
5463 else if (match(U, m_c_Select(m_Specific(&I), m_Value(V)))) {
5464 if (V == &I || !isGuaranteedNotToBeUndefOrPoison(V, &AC, &I, &DT))
5465 V = NullValue;
5466 } else if (auto *PHI = dyn_cast<PHINode>(U)) {
5467 if (Value *MaybeV = pickCommonConstantFromPHI(*PHI))
5468 V = MaybeV;
5469 }
5470
5471 if (!BestValue)
5472 BestValue = V;
5473 else if (BestValue != V)
5474 BestValue = NullValue;
5475 }
5476 assert(BestValue && "Must have at least one use");
5477 assert(BestValue != &I && "Cannot replace with itself");
5478 return BestValue;
5479 };
5480
5481 if (match(Op0, m_Undef())) {
5482 // Don't fold freeze(undef/poison) if it's used as a vector operand in
5483 // a shuffle. This may improve codegen for shuffles that allow
5484 // unspecified inputs.
5486 return nullptr;
5487 return replaceInstUsesWith(I, getUndefReplacement(I.getType()));
5488 }
5489
5490 auto getFreezeVectorReplacement = [](Constant *C) -> Constant * {
5491 Type *Ty = C->getType();
5492 auto *VTy = dyn_cast<FixedVectorType>(Ty);
5493 if (!VTy)
5494 return nullptr;
5495 Constant *BestValue;
5497 m_Unless(m_Undef()), m_Constant(BestValue)))))
5498 BestValue = Constant::getNullValue(VTy->getScalarType());
5499 return Constant::replaceUndefsWith(C, BestValue);
5500 };
5501
5502 Constant *C;
5503 if (match(Op0, m_Constant(C)) && C->containsUndefOrPoisonElement() &&
5504 !C->containsConstantExpression()) {
5505 if (Constant *Repl = getFreezeVectorReplacement(C))
5506 return replaceInstUsesWith(I, Repl);
5507 }
5508
5509 // Replace uses of Op with freeze(Op).
5510 if (!isa<Constant>(Op0) && !Op0->hasOneUse()) {
5512 bool Changed = freezeUsesAfterDef(I, DT, &Users);
5513
5514 for (auto *U : Users) {
5515 // Re-queue U and its users: freezing U's operand can expose a fold on a
5516 // user of U (e.g. a freeze of U can now be pushed through it) that would
5517 // otherwise only fire on a later iteration, tripping the fixpoint
5518 // verifier.
5519 auto *UI = cast<Instruction>(U);
5520 Worklist.pushUsersToWorkList(*UI);
5521 Worklist.push(UI);
5522 }
5523
5524 if (Changed)
5525 return &I;
5526 }
5527
5528 return nullptr;
5529}
5530
5531/// Check for case where the call writes to an otherwise dead alloca. This
5532/// shows up for unused out-params in idiomatic C/C++ code. Note that this
5533/// helper *only* analyzes the write; doesn't check any other legality aspect.
5535 auto *CB = dyn_cast<CallBase>(I);
5536 if (!CB)
5537 // TODO: handle e.g. store to alloca here - only worth doing if we extend
5538 // to allow reload along used path as described below. Otherwise, this
5539 // is simply a store to a dead allocation which will be removed.
5540 return false;
5541 std::optional<MemoryLocation> Dest = MemoryLocation::getForDest(CB, TLI);
5542 if (!Dest)
5543 return false;
5544 auto *AI = dyn_cast<AllocaInst>(getUnderlyingObject(Dest->Ptr));
5545 if (!AI)
5546 // TODO: allow malloc?
5547 return false;
5548 // TODO: allow memory access dominated by move point? Note that since AI
5549 // could have a reference to itself captured by the call, we would need to
5550 // account for cycles in doing so.
5551 SmallVector<const User *> AllocaUsers;
5553 auto pushUsers = [&](const Instruction &I) {
5554 for (const User *U : I.users()) {
5555 if (Visited.insert(U).second)
5556 AllocaUsers.push_back(U);
5557 }
5558 };
5559 pushUsers(*AI);
5560 while (!AllocaUsers.empty()) {
5561 auto *UserI = cast<Instruction>(AllocaUsers.pop_back_val());
5562 if (isa<GetElementPtrInst>(UserI) || isa<AddrSpaceCastInst>(UserI)) {
5563 pushUsers(*UserI);
5564 continue;
5565 }
5566 if (UserI == CB)
5567 continue;
5568 // TODO: support lifetime.start/end here
5569 return false;
5570 }
5571 return true;
5572}
5573
5574/// Try to move the specified instruction from its current block into the
5575/// beginning of DestBlock, which can only happen if it's safe to move the
5576/// instruction past all of the instructions between it and the end of its
5577/// block.
5579 BasicBlock *DestBlock) {
5580 BasicBlock *SrcBlock = I->getParent();
5581
5582 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
5583 if (isa<PHINode>(I) || I->isEHPad() || I->mayThrow() || !I->willReturn() ||
5584 I->isTerminator())
5585 return false;
5586
5587 // Do not sink static or dynamic alloca instructions. Static allocas must
5588 // remain in the entry block, and dynamic allocas must not be sunk in between
5589 // a stacksave / stackrestore pair, which would incorrectly shorten its
5590 // lifetime.
5591 if (isa<AllocaInst>(I))
5592 return false;
5593
5594 // Do not sink into catchswitch blocks.
5595 if (isa<CatchSwitchInst>(DestBlock->getTerminator()))
5596 return false;
5597
5598 // Do not sink convergent call instructions.
5599 if (auto *CI = dyn_cast<CallInst>(I)) {
5600 if (CI->isConvergent())
5601 return false;
5602 }
5603
5604 // Unless we can prove that the memory write isn't visibile except on the
5605 // path we're sinking to, we must bail.
5606 if (I->mayWriteToMemory()) {
5607 if (!SoleWriteToDeadLocal(I, TLI))
5608 return false;
5609 }
5610
5611 // We can only sink load instructions if there is nothing between the load and
5612 // the end of block that could change the value.
5613 if (I->mayReadFromMemory() &&
5614 !I->hasMetadata(LLVMContext::MD_invariant_load)) {
5615 // We don't want to do any sophisticated alias analysis, so we only check
5616 // the instructions after I in I's parent block if we try to sink to its
5617 // successor block.
5618 if (DestBlock->getUniquePredecessor() != I->getParent())
5619 return false;
5620 for (BasicBlock::iterator Scan = std::next(I->getIterator()),
5621 E = I->getParent()->end();
5622 Scan != E; ++Scan)
5623 if (Scan->mayWriteToMemory() && !isa<AssumeInst>(Scan))
5624 return false;
5625 }
5626
5627 SmallVector<AssumeInst *, 2> AssumesToSink;
5628 I->dropDroppableUses([&](const Use *U) {
5629 auto *User = dyn_cast<Instruction>(U->getUser());
5630 if (User && User->getParent() != DestBlock) {
5631 if (auto *Assume = dyn_cast<AssumeInst>(User);
5632 Assume && Assume->getParent() == SrcBlock) {
5633 AssumesToSink.push_back(Assume);
5634 return false;
5635 }
5636 Worklist.add(User);
5637 return true;
5638 }
5639 return false;
5640 });
5641
5642 BasicBlock::iterator InsertPos = DestBlock->getFirstInsertionPt();
5643 I->moveBefore(*DestBlock, InsertPos);
5644 ++NumSunkInst;
5645
5646 // Sink the collected assumes right after I in DestBlock so that the
5647 // alignment/attribute guarantees they encode remain visible to later passes.
5648 for (AssumeInst *Assume : AssumesToSink)
5649 Assume->moveAfter(I);
5650
5651 // Also sink all related debug uses from the source basic block. Otherwise we
5652 // get debug use before the def. Attempt to salvage debug uses first, to
5653 // maximise the range variables have location for. If we cannot salvage, then
5654 // mark the location undef: we know it was supposed to receive a new location
5655 // here, but that computation has been sunk.
5656 SmallVector<DbgVariableRecord *, 2> DbgVariableRecords;
5657 findDbgUsers(I, DbgVariableRecords);
5658 if (!DbgVariableRecords.empty())
5659 tryToSinkInstructionDbgVariableRecords(I, InsertPos, SrcBlock, DestBlock,
5660 DbgVariableRecords);
5661
5662 // PS: there are numerous flaws with this behaviour, not least that right now
5663 // assignments can be re-ordered past other assignments to the same variable
5664 // if they use different Values. Creating more undef assignements can never be
5665 // undone. And salvaging all users outside of this block can un-necessarily
5666 // alter the lifetime of the live-value that the variable refers to.
5667 // Some of these things can be resolved by tolerating debug use-before-defs in
5668 // LLVM-IR, however it depends on the instruction-referencing CodeGen backend
5669 // being used for more architectures.
5670
5671 return true;
5672}
5673
5675 Instruction *I, BasicBlock::iterator InsertPos, BasicBlock *SrcBlock,
5676 BasicBlock *DestBlock,
5677 SmallVectorImpl<DbgVariableRecord *> &DbgVariableRecords) {
5678 // For all debug values in the destination block, the sunk instruction
5679 // will still be available, so they do not need to be dropped.
5680
5681 // Fetch all DbgVariableRecords not already in the destination.
5682 SmallVector<DbgVariableRecord *, 2> DbgVariableRecordsToSalvage;
5683 for (auto &DVR : DbgVariableRecords)
5684 if (DVR->getParent() != DestBlock)
5685 DbgVariableRecordsToSalvage.push_back(DVR);
5686
5687 // Fetch a second collection, of DbgVariableRecords in the source block that
5688 // we're going to sink.
5689 SmallVector<DbgVariableRecord *> DbgVariableRecordsToSink;
5690 for (DbgVariableRecord *DVR : DbgVariableRecordsToSalvage)
5691 if (DVR->getParent() == SrcBlock)
5692 DbgVariableRecordsToSink.push_back(DVR);
5693
5694 // Sort DbgVariableRecords according to their position in the block. This is a
5695 // partial order: DbgVariableRecords attached to different instructions will
5696 // be ordered by the instruction order, but DbgVariableRecords attached to the
5697 // same instruction won't have an order.
5698 auto Order = [](DbgVariableRecord *A, DbgVariableRecord *B) -> bool {
5699 return B->getInstruction()->comesBefore(A->getInstruction());
5700 };
5701 llvm::stable_sort(DbgVariableRecordsToSink, Order);
5702
5703 // If there are two assignments to the same variable attached to the same
5704 // instruction, the ordering between the two assignments is important. Scan
5705 // for this (rare) case and establish which is the last assignment.
5706 using InstVarPair = std::pair<const Instruction *, DebugVariable>;
5708 if (DbgVariableRecordsToSink.size() > 1) {
5710 // Count how many assignments to each variable there is per instruction.
5711 for (DbgVariableRecord *DVR : DbgVariableRecordsToSink) {
5712 DebugVariable DbgUserVariable =
5713 DebugVariable(DVR->getVariable(), DVR->getExpression(),
5714 DVR->getDebugLoc()->getInlinedAt());
5715 CountMap[std::make_pair(DVR->getInstruction(), DbgUserVariable)] += 1;
5716 }
5717
5718 // If there are any instructions with two assignments, add them to the
5719 // FilterOutMap to record that they need extra filtering.
5721 for (auto It : CountMap) {
5722 if (It.second > 1) {
5723 FilterOutMap[It.first] = nullptr;
5724 DupSet.insert(It.first.first);
5725 }
5726 }
5727
5728 // For all instruction/variable pairs needing extra filtering, find the
5729 // latest assignment.
5730 for (const Instruction *Inst : DupSet) {
5731 for (DbgVariableRecord &DVR :
5732 llvm::reverse(filterDbgVars(Inst->getDbgRecordRange()))) {
5733 DebugVariable DbgUserVariable =
5734 DebugVariable(DVR.getVariable(), DVR.getExpression(),
5735 DVR.getDebugLoc()->getInlinedAt());
5736 auto FilterIt =
5737 FilterOutMap.find(std::make_pair(Inst, DbgUserVariable));
5738 if (FilterIt == FilterOutMap.end())
5739 continue;
5740 if (FilterIt->second != nullptr)
5741 continue;
5742 FilterIt->second = &DVR;
5743 }
5744 }
5745 }
5746
5747 // Perform cloning of the DbgVariableRecords that we plan on sinking, filter
5748 // out any duplicate assignments identified above.
5750 SmallSet<DebugVariable, 4> SunkVariables;
5751 for (DbgVariableRecord *DVR : DbgVariableRecordsToSink) {
5753 continue;
5754
5755 DebugVariable DbgUserVariable =
5756 DebugVariable(DVR->getVariable(), DVR->getExpression(),
5757 DVR->getDebugLoc()->getInlinedAt());
5758
5759 // For any variable where there were multiple assignments in the same place,
5760 // ignore all but the last assignment.
5761 if (!FilterOutMap.empty()) {
5762 InstVarPair IVP = std::make_pair(DVR->getInstruction(), DbgUserVariable);
5763 auto It = FilterOutMap.find(IVP);
5764
5765 // Filter out.
5766 if (It != FilterOutMap.end() && It->second != DVR)
5767 continue;
5768 }
5769
5770 if (!SunkVariables.insert(DbgUserVariable).second)
5771 continue;
5772
5773 if (DVR->isDbgAssign())
5774 continue;
5775
5776 DVRClones.emplace_back(DVR->clone());
5777 LLVM_DEBUG(dbgs() << "CLONE: " << *DVRClones.back() << '\n');
5778 }
5779
5780 // Perform salvaging without the clones, then sink the clones.
5781 if (DVRClones.empty())
5782 return;
5783
5784 salvageDebugInfoForDbgValues(*I, DbgVariableRecordsToSalvage);
5785
5786 // The clones are in reverse order of original appearance. Assert that the
5787 // head bit is set on the iterator as we _should_ have received it via
5788 // getFirstInsertionPt. Inserting like this will reverse the clone order as
5789 // we'll repeatedly insert at the head, such as:
5790 // DVR-3 (third insertion goes here)
5791 // DVR-2 (second insertion goes here)
5792 // DVR-1 (first insertion goes here)
5793 // Any-Prior-DVRs
5794 // InsertPtInst
5795 assert(InsertPos.getHeadBit());
5796 for (DbgVariableRecord *DVRClone : DVRClones) {
5797 InsertPos->getParent()->insertDbgRecordBefore(DVRClone, InsertPos);
5798 LLVM_DEBUG(dbgs() << "SINK: " << *DVRClone << '\n');
5799 }
5800}
5801
5803 while (!Worklist.isEmpty()) {
5804 // Walk deferred instructions in reverse order, and push them to the
5805 // worklist, which means they'll end up popped from the worklist in-order.
5806 while (Instruction *I = Worklist.popDeferred()) {
5807 // Check to see if we can DCE the instruction. We do this already here to
5808 // reduce the number of uses and thus allow other folds to trigger.
5809 // Note that eraseInstFromFunction() may push additional instructions on
5810 // the deferred worklist, so this will DCE whole instruction chains.
5813 ++NumDeadInst;
5814 continue;
5815 }
5816
5817 Worklist.push(I);
5818 }
5819
5820 Instruction *I = Worklist.removeOne();
5821 if (I == nullptr) continue; // skip null values.
5822
5823 // Check to see if we can DCE the instruction.
5826 ++NumDeadInst;
5827 continue;
5828 }
5829
5830 if (!DebugCounter::shouldExecute(VisitCounter))
5831 continue;
5832
5833 // See if we can trivially sink this instruction to its user if we can
5834 // prove that the successor is not executed more frequently than our block.
5835 // Return the UserBlock if successful.
5836 auto getOptionalSinkBlockForInst =
5837 [this](Instruction *I) -> std::optional<BasicBlock *> {
5838 if (!CLOpts.code_sinking)
5839 return std::nullopt;
5840
5841 BasicBlock *BB = I->getParent();
5842 BasicBlock *UserParent = nullptr;
5843 unsigned NumUsers = 0;
5844
5845 for (Use &U : I->uses()) {
5846 User *User = U.getUser();
5847 if (User->isDroppable()) {
5848 // Do not sink if there are dereferenceable assumes that would be
5849 // removed.
5851 if (II->getIntrinsicID() != Intrinsic::assume ||
5852 !II->hasOperandBundle(LLVMContext::OB_Dereferenceable))
5853 continue;
5854 }
5855
5856 if (NumUsers > CLOpts.max_sink_users)
5857 return std::nullopt;
5858
5859 Instruction *UserInst = cast<Instruction>(User);
5860 // Special handling for Phi nodes - get the block the use occurs in.
5861 BasicBlock *UserBB = UserInst->getParent();
5862 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
5863 UserBB = PN->getIncomingBlock(U);
5864 // Bail out if we have uses in different blocks. We don't do any
5865 // sophisticated analysis (i.e finding NearestCommonDominator of these
5866 // use blocks).
5867 if (UserParent && UserParent != UserBB)
5868 return std::nullopt;
5869 UserParent = UserBB;
5870
5871 // Make sure these checks are done only once, naturally we do the checks
5872 // the first time we get the userparent, this will save compile time.
5873 if (NumUsers == 0) {
5874 // Try sinking to another block. If that block is unreachable, then do
5875 // not bother. SimplifyCFG should handle it.
5876 if (UserParent == BB || !DT.isReachableFromEntry(UserParent))
5877 return std::nullopt;
5878
5879 auto *Term = UserParent->getTerminator();
5880 // See if the user is one of our successors that has only one
5881 // predecessor, so that we don't have to split the critical edge.
5882 // Another option where we can sink is a block that ends with a
5883 // terminator that does not pass control to other block (such as
5884 // return or unreachable or resume). In this case:
5885 // - I dominates the User (by SSA form);
5886 // - the User will be executed at most once.
5887 // So sinking I down to User is always profitable or neutral.
5888 if (UserParent->getUniquePredecessor() != BB && !succ_empty(Term))
5889 return std::nullopt;
5890
5891 assert(DT.dominates(BB, UserParent) && "Dominance relation broken?");
5892 }
5893
5894 NumUsers++;
5895 }
5896
5897 // No user or only has droppable users.
5898 if (!UserParent)
5899 return std::nullopt;
5900
5901 return UserParent;
5902 };
5903
5904 auto OptBB = getOptionalSinkBlockForInst(I);
5905 if (OptBB) {
5906 auto *UserParent = *OptBB;
5907 // Okay, the CFG is simple enough, try to sink this instruction.
5908 if (tryToSinkInstruction(I, UserParent)) {
5909 LLVM_DEBUG(dbgs() << "IC: Sink: " << *I << '\n');
5910 MadeIRChange = true;
5911 // We'll add uses of the sunk instruction below, but since
5912 // sinking can expose opportunities for it's *operands* add
5913 // them to the worklist
5914 for (Use &U : I->operands())
5915 if (Instruction *OpI = dyn_cast<Instruction>(U.get()))
5916 Worklist.push(OpI);
5917 }
5918 }
5919
5920 // Now that we have an instruction, try combining it to simplify it.
5921 Builder.SetInsertPoint(I);
5922 Builder.SetCurrentDebugLocation(I->getDebugLoc());
5923 // Used by our IRBuilder inserter to copy annotation metadata.
5925
5926#ifndef NDEBUG
5927 std::string OrigI;
5928#endif
5929 LLVM_DEBUG(raw_string_ostream SS(OrigI); I->print(SS););
5930 LLVM_DEBUG(dbgs() << "IC: Visiting: " << OrigI << '\n');
5931
5932 if (Instruction *Result = visit(*I)) {
5933 ++NumCombined;
5934 // Should we replace the old instruction with a new one?
5935 if (Result != I) {
5936 LLVM_DEBUG(dbgs() << "IC: Old = " << *I << '\n'
5937 << " New = " << *Result << '\n');
5938
5939 // We copy the old instruction's DebugLoc to the new instruction, unless
5940 // InstCombine already assigned a DebugLoc to it, in which case we
5941 // should trust the more specifically selected DebugLoc.
5942 Result->setDebugLoc(Result->getDebugLoc().orElse(I->getDebugLoc()));
5943 // We also copy annotation metadata to the new instruction.
5944 Result->copyMetadata(*I, LLVMContext::MD_annotation);
5945 // Everything uses the new instruction now.
5946 I->replaceAllUsesWith(Result);
5947
5948 // Move the name to the new instruction first.
5949 Result->takeName(I);
5950
5951 // Insert the new instruction into the basic block...
5952 BasicBlock *InstParent = I->getParent();
5953 BasicBlock::iterator InsertPos = I->getIterator();
5954
5955 // Are we replace a PHI with something that isn't a PHI, or vice versa?
5956 if (isa<PHINode>(Result) != isa<PHINode>(I)) {
5957 // We need to fix up the insertion point.
5958 if (isa<PHINode>(I)) // PHI -> Non-PHI
5959 InsertPos = InstParent->getFirstInsertionPt();
5960 else // Non-PHI -> PHI
5961 InsertPos = InstParent->getFirstNonPHIIt();
5962 }
5963
5964 Result->insertInto(InstParent, InsertPos);
5965
5966 // Register newly created assumptions.
5967 if (auto *Assume = dyn_cast<AssumeInst>(Result))
5968 AC.registerAssumption(Assume);
5969
5970 // Push the new instruction and any users onto the worklist.
5971 Worklist.pushUsersToWorkList(*Result);
5972 Worklist.push(Result);
5973
5975 } else {
5976 LLVM_DEBUG(dbgs() << "IC: Mod = " << OrigI << '\n'
5977 << " New = " << *I << '\n');
5978
5979 // If the instruction was modified, it's possible that it is now dead.
5980 // if so, remove it.
5983 } else {
5984 Worklist.pushUsersToWorkList(*I);
5985 Worklist.push(I);
5986 }
5987 }
5988 MadeIRChange = true;
5989 }
5990 }
5991
5992 Worklist.zap();
5993 return MadeIRChange;
5994}
5995
5996// Track the scopes used by !alias.scope and !noalias. In a function, a
5997// @llvm.experimental.noalias.scope.decl is only useful if that scope is used
5998// by both sets. If not, the declaration of the scope can be safely omitted.
5999// The MDNode of the scope can be omitted as well for the instructions that are
6000// part of this function. We do not do that at this point, as this might become
6001// too time consuming to do.
6003 SmallPtrSet<const MDNode *, 8> UsedAliasScopesAndLists;
6004 SmallPtrSet<const MDNode *, 8> UsedNoAliasScopesAndLists;
6005 // Scopes used by every !alias.scope list that scopes from a disjoint-scope
6006 // domain appears in. This is used to catch scopes that don't actually make
6007 // anything noalias.
6009 CommonScopesOfDisjointDomain;
6010
6011 // Record, for each disjoint-scope domain \p ScopeList uses, which of its
6012 // scopes are used by \p ScopeList, adding to a running intersection.
6013 void recordDisjointDomainScopes(const MDNode *ScopeList) {
6015 for (const MDOperand &MDOperand : ScopeList->operands()) {
6016 const auto *MDScope = cast<MDNode>(MDOperand);
6017 const MDNode *Domain = AliasScopeNode(MDScope).getDomain();
6018 if (AliasScopeDomainNode(Domain).hasDisjointScopes())
6019 UsedScopes[Domain].insert(MDScope);
6020 }
6021
6022 for (auto &[Domain, Scopes] : UsedScopes) {
6023 auto [It, Inserted] =
6024 CommonScopesOfDisjointDomain.try_emplace(Domain, Scopes);
6025 if (!Inserted)
6026 llvm::set_intersect(It->second, Scopes);
6027 }
6028 }
6029
6030 // Return true if \p Scope is on the implicit !noalias list of one of the
6031 // analysed accesses, that is, if it belongs to a disjoint-scope domain and
6032 // some access uses that domain without using \p Scope.
6033 bool isImplicitlyNoAlias(const MDNode *Scope) const {
6034 auto It =
6035 CommonScopesOfDisjointDomain.find(AliasScopeNode(Scope).getDomain());
6036 return It != CommonScopesOfDisjointDomain.end() &&
6037 !It->second.contains(Scope);
6038 }
6039
6040public:
6042 // This seems to be faster than checking 'mayReadOrWriteMemory()'.
6043 if (!I->hasMetadataOtherThanDebugLoc())
6044 return;
6045
6046 auto Track = [](Metadata *ScopeList, auto &Container) -> const MDNode * {
6047 const auto *MDScopeList = dyn_cast_or_null<MDNode>(ScopeList);
6048 if (!MDScopeList || !Container.insert(MDScopeList).second)
6049 return nullptr;
6050 for (const auto &MDOperand : MDScopeList->operands())
6051 if (auto *MDScope = dyn_cast<MDNode>(MDOperand))
6052 Container.insert(MDScope);
6053 return MDScopeList;
6054 };
6055
6056 if (const MDNode *AliasScopeList =
6057 Track(I->getMetadata(LLVMContext::MD_alias_scope),
6058 UsedAliasScopesAndLists))
6059 recordDisjointDomainScopes(AliasScopeList);
6060 Track(I->getMetadata(LLVMContext::MD_noalias), UsedNoAliasScopesAndLists);
6061 }
6062
6065 if (!Decl)
6066 return false;
6067
6068 assert(Decl->use_empty() &&
6069 "llvm.experimental.noalias.scope.decl in use ?");
6070 const MDNode *MDSL = Decl->getScopeList();
6071 assert(MDSL->getNumOperands() == 1 &&
6072 "llvm.experimental.noalias.scope should refer to a single scope");
6073 auto &MDOperand = MDSL->getOperand(0);
6074 // A scope is relevant if it appears in an !alias.scope list, and either it
6075 // appears in a !noalias list, or it is on the implicit !noalias list of
6076 // some access using its disjoint-scope domain.
6077 if (auto *MD = dyn_cast<MDNode>(MDOperand))
6078 return !UsedAliasScopesAndLists.contains(MD) ||
6079 (!UsedNoAliasScopesAndLists.contains(MD) &&
6080 !isImplicitlyNoAlias(MD));
6081
6082 // Not an MDNode ? throw away.
6083 return true;
6084 }
6085};
6086
6087/// Populate the IC worklist from a function, by walking it in reverse
6088/// post-order and adding all reachable code to the worklist.
6089///
6090/// This has a couple of tricks to make the code faster and more powerful. In
6091/// particular, we constant fold and DCE instructions as we go, to avoid adding
6092/// them to the worklist (this significantly speeds up instcombine on code where
6093/// many instructions are dead or constant). Additionally, if we find a branch
6094/// whose condition is a known constant, we only visit the reachable successors.
6096 bool MadeIRChange = false;
6098 SmallVector<Instruction *, 128> InstrsForInstructionWorklist;
6099 DenseMap<Constant *, Constant *> FoldedConstants;
6100 AliasScopeTracker SeenAliasScopes;
6101
6102 auto HandleOnlyLiveSuccessor = [&](BasicBlock *BB, BasicBlock *LiveSucc) {
6103 for (BasicBlock *Succ : successors(BB))
6104 if (Succ != LiveSucc && DeadEdges.insert({BB, Succ}).second)
6105 for (PHINode &PN : Succ->phis())
6106 for (Use &U : PN.incoming_values())
6107 if (PN.getIncomingBlock(U) == BB && !isa<PoisonValue>(U)) {
6108 U.set(PoisonValue::get(PN.getType()));
6109 MadeIRChange = true;
6110 }
6111 };
6112
6113 for (BasicBlock *BB : RPOT) {
6114 if (!BB->isEntryBlock() && all_of(predecessors(BB), [&](BasicBlock *Pred) {
6115 return DeadEdges.contains({Pred, BB}) || DT.dominates(BB, Pred);
6116 })) {
6117 HandleOnlyLiveSuccessor(BB, nullptr);
6118 continue;
6119 }
6120 LiveBlocks.insert(BB);
6121
6122 for (Instruction &Inst : llvm::make_early_inc_range(*BB)) {
6123 // ConstantProp instruction if trivially constant.
6124 if (!Inst.use_empty() &&
6125 (Inst.getNumOperands() == 0 || isa<Constant>(Inst.getOperand(0))))
6126 if (Constant *C = ConstantFoldInstruction(&Inst, DL, &TLI)) {
6128 auto *CB = dyn_cast<CallBase>(&Inst);
6129 if (!CB || !CB->isMustTailCall() || IsDead) {
6130 LLVM_DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: " << Inst
6131 << '\n');
6132 Inst.replaceAllUsesWith(C);
6133 MadeIRChange = true;
6134 ++NumConstProp;
6135 if (IsDead) {
6136 // Omit the instruction from the worklist only if we deleted it.
6137 Inst.eraseFromParent();
6138 continue;
6139 }
6140 }
6141 }
6142
6143 // See if we can constant fold its operands.
6144 for (Use &U : Inst.operands()) {
6146 continue;
6147
6148 auto *C = cast<Constant>(U);
6149 Constant *&FoldRes = FoldedConstants[C];
6150 if (!FoldRes)
6151 FoldRes = ConstantFoldConstant(C, DL, &TLI);
6152
6153 if (FoldRes != C) {
6154 LLVM_DEBUG(dbgs() << "IC: ConstFold operand of: " << Inst
6155 << "\n Old = " << *C
6156 << "\n New = " << *FoldRes << '\n');
6157 U = FoldRes;
6158 MadeIRChange = true;
6159 }
6160 }
6161
6162 // Skip processing pseudo intrinsics in InstCombine. Processing
6163 // these call instructions consumes non-trivial amount of time and
6164 // provides no value for the optimization.
6165 if (!isa<PseudoProbeInst>(Inst)) {
6166 InstrsForInstructionWorklist.push_back(&Inst);
6167 SeenAliasScopes.analyse(&Inst);
6168 }
6169 }
6170
6171 // If this is a branch or switch on a constant, mark only the single
6172 // live successor. Otherwise assume all successors are live.
6173 Instruction *TI = BB->getTerminator();
6174 if (CondBrInst *BI = dyn_cast<CondBrInst>(TI)) {
6175 if (isa<UndefValue>(BI->getCondition())) {
6176 // Branch on undef is UB.
6177 HandleOnlyLiveSuccessor(BB, nullptr);
6178 continue;
6179 }
6180 if (auto *Cond = dyn_cast<ConstantInt>(BI->getCondition())) {
6181 bool CondVal = Cond->getZExtValue();
6182 HandleOnlyLiveSuccessor(BB, BI->getSuccessor(!CondVal));
6183 continue;
6184 }
6185 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
6186 if (isa<UndefValue>(SI->getCondition())) {
6187 // Switch on undef is UB.
6188 HandleOnlyLiveSuccessor(BB, nullptr);
6189 continue;
6190 }
6191 if (auto *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
6192 HandleOnlyLiveSuccessor(BB,
6193 SI->findCaseValue(Cond)->getCaseSuccessor());
6194 continue;
6195 }
6196 }
6197 }
6198
6199 // Remove instructions inside unreachable blocks. This prevents the
6200 // instcombine code from having to deal with some bad special cases, and
6201 // reduces use counts of instructions.
6202 for (BasicBlock &BB : F) {
6203 if (LiveBlocks.count(&BB))
6204 continue;
6205
6206 unsigned NumDeadInstInBB;
6207 NumDeadInstInBB = removeAllNonTerminatorAndEHPadInstructions(&BB);
6208
6209 MadeIRChange |= NumDeadInstInBB != 0;
6210 NumDeadInst += NumDeadInstInBB;
6211 }
6212
6213 // Once we've found all of the instructions to add to instcombine's worklist,
6214 // add them in reverse order. This way instcombine will visit from the top
6215 // of the function down. This jives well with the way that it adds all uses
6216 // of instructions to the worklist after doing a transformation, thus avoiding
6217 // some N^2 behavior in pathological cases.
6218 Worklist.reserve(InstrsForInstructionWorklist.size());
6219 for (Instruction *Inst : reverse(InstrsForInstructionWorklist)) {
6220 // DCE instruction if trivially dead. As we iterate in reverse program
6221 // order here, we will clean up whole chains of dead instructions.
6222 if (isInstructionTriviallyDead(Inst, &TLI) ||
6223 SeenAliasScopes.isNoAliasScopeDeclDead(Inst)) {
6224 ++NumDeadInst;
6225 LLVM_DEBUG(dbgs() << "IC: DCE: " << *Inst << '\n');
6226 salvageDebugInfo(*Inst);
6227 Inst->eraseFromParent();
6228 MadeIRChange = true;
6229 continue;
6230 }
6231
6232 Worklist.push(Inst);
6233 }
6234
6235 return MadeIRChange;
6236}
6237
6239 // Collect backedges.
6240 SmallVector<bool> Visited(F.getMaxBlockNumber());
6241 for (BasicBlock *BB : RPOT) {
6242 Visited[BB->getNumber()] = true;
6243 for (BasicBlock *Succ : successors(BB))
6244 if (Visited[Succ->getNumber()])
6245 BackEdges.insert({BB, Succ});
6246 }
6247 ComputedBackEdges = true;
6248}
6249
6255 const InstCombineOptions &Opts) {
6256 auto &DL = F.getDataLayout();
6257 bool VerifyFixpoint = Opts.VerifyFixpoint &&
6258 !F.hasFnAttribute("instcombine-no-verify-fixpoint");
6259
6261
6262 // Lower dbg.declare intrinsics otherwise their value may be clobbered
6263 // by instcombiner.
6264 const auto &CLOpts = getInstCombineCLOptions(F);
6265 bool MadeIRChange = false;
6266 if (CLOpts.lower_dbg_declare)
6267 MadeIRChange = LowerDbgDeclare(F);
6268
6269 // Iterate while there is work to do.
6270 unsigned Iteration = 0;
6271 while (true) {
6272 if (Iteration >= Opts.MaxIterations && !VerifyFixpoint) {
6273 LLVM_DEBUG(dbgs() << "\n\n[IC] Iteration limit #" << Opts.MaxIterations
6274 << " on " << F.getName()
6275 << " reached; stopping without verifying fixpoint\n");
6276 break;
6277 }
6278
6279 ++Iteration;
6280 ++NumWorklistIterations;
6281 LLVM_DEBUG(dbgs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
6282 << F.getName() << "\n");
6283
6284 InstCombinerImpl IC(Worklist, F, AA, AC, TLI, TTI, DT, ORE, BFI, BPI, PSI,
6285 DL, RPOT, CLOpts);
6286 bool MadeChangeInThisIteration = IC.prepareWorklist(F);
6287 MadeChangeInThisIteration |= IC.run();
6288 if (!MadeChangeInThisIteration)
6289 break;
6290
6291 MadeIRChange = true;
6292 if (Iteration > Opts.MaxIterations) {
6294 "Instruction Combining on " + Twine(F.getName()) +
6295 " did not reach a fixpoint after " + Twine(Opts.MaxIterations) +
6296 " iterations.\n\n"
6297 "If you encountered this error while working on InstCombine, "
6298 "determine the cause and either fix it, or add the "
6299 "\"instcombine-no-verify-fixpoint\" attribute to the test, with "
6300 "a comment explaining the reason for the convergence failure.\n\n"
6301 "If you encountered this error in any other situation, "
6302 "use 'instcombine<no-verify-fixpoint>' and "
6303 "do *not* file an issue.");
6304 }
6305 }
6306
6307 if (Iteration == 1)
6308 ++NumOneIteration;
6309 else if (Iteration == 2)
6310 ++NumTwoIterations;
6311 else if (Iteration == 3)
6312 ++NumThreeIterations;
6313 else
6314 ++NumFourOrMoreIterations;
6315
6316 return MadeIRChange;
6317}
6318
6320
6322 raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
6323 static_cast<PassInfoMixin<InstCombinePass> *>(this)->printPipeline(
6324 OS, MapClassName2PassName);
6325 OS << '<';
6326 OS << "max-iterations=" << Options.MaxIterations << ";";
6327 OS << (Options.VerifyFixpoint ? "" : "no-") << "verify-fixpoint";
6328 OS << '>';
6329}
6330
6331char InstCombinePass::ID = 0;
6332
6335 auto &LRT = AM.getResult<LastRunTrackingAnalysis>(F);
6336 // No changes since last InstCombine pass, exit early.
6337 if (LRT.shouldSkip(&ID))
6338 return PreservedAnalyses::all();
6339
6340 auto &AC = AM.getResult<AssumptionAnalysis>(F);
6341 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
6342 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
6344 auto &TTI = AM.getResult<TargetIRAnalysis>(F);
6345
6346 auto *AA = &AM.getResult<AAManager>(F);
6347 auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
6348 ProfileSummaryInfo *PSI =
6349 MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
6350 auto *BFI = (PSI && PSI->hasProfileSummary()) ?
6351 &AM.getResult<BlockFrequencyAnalysis>(F) : nullptr;
6353
6354 if (!combineInstructionsOverFunction(F, Worklist, AA, AC, TLI, TTI, DT, ORE,
6355 BFI, BPI, PSI, Options)) {
6356 // No changes, all analyses are preserved.
6357 LRT.update(&ID, /*Changed=*/false);
6358 return PreservedAnalyses::all();
6359 }
6360
6361 // Mark all the analyses that instcombine updates as preserved.
6363 LRT.update(&ID, /*Changed=*/true);
6366 return PA;
6367}
6368
6382
6384 if (skipFunction(F))
6385 return false;
6386
6387 // Required analyses.
6388 auto AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
6389 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
6392 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
6394
6395 // Optional analyses.
6396 ProfileSummaryInfo *PSI =
6398 BlockFrequencyInfo *BFI =
6399 (PSI && PSI->hasProfileSummary()) ?
6401 nullptr;
6402 BranchProbabilityInfo *BPI = nullptr;
6403 if (auto *WrapperPass =
6405 BPI = &WrapperPass->getBPI();
6406
6407 return combineInstructionsOverFunction(F, Worklist, AA, AC, TLI, TTI, DT, ORE,
6408 BFI, BPI, PSI, InstCombineOptions());
6409}
6410
6412
6414
6416 "Combine redundant instructions", false, false)
6427 "Combine redundant instructions", false, false)
6428
6429// Initialization Routines.
6433
const TargetLowering & TLI
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
AMDGPU Register Bank Select
Rewrite undef for PHI
This file declares a class to represent arbitrary precision floating point values and provide a varie...
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
This is the interface for LLVM's primary stateless and local alias analysis.
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static Domain getDomain(const ConstantRange &CR)
DXIL Resource Access
This file provides an implementation of debug counters.
#define DEBUG_COUNTER(VARNAME, COUNTERNAME, DESC)
This file defines the DenseMap class.
static bool isSigned(unsigned Opcode)
This is the interface for a simple mod/ref and alias analysis over globals.
Hexagon Common GEP
IRTranslator LLVM IR MI
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
This header defines various interfaces for pass management in LLVM.
This defines the Use class.
iv Induction Variable Users
Definition IVUsers.cpp:48
static bool rightDistributesOverLeft(Instruction::BinaryOps LOp, bool HasNUW, bool HasNSW, Intrinsic::ID ROp)
Return whether "(X ROp Y) LOp Z" is always equal to "(X LOp Z) ROp (Y LOp Z)".
static bool leftDistributesOverRight(Instruction::BinaryOps LOp, bool HasNUW, bool HasNSW, Intrinsic::ID ROp)
Return whether "X LOp (Y ROp Z)" is always equal to "(X LOp Y) ROp (X LOp Z)".
This file provides internal interfaces used to implement the InstCombine.
This file provides the primary interface to the instcombine pass.
static Value * simplifySwitchOnSelectUsingRanges(SwitchInst &SI, SelectInst *Select, bool IsTrueArm)
static bool isUsedWithinShuffleVector(Value *V)
static Constant * constantFoldBinOpWithSplat(unsigned Opcode, Constant *Vector, Constant *Splat, bool SplatLHS, const DataLayout &DL)
static bool shorter_filter(const Value *LHS, const Value *RHS)
static Instruction * combineConstantOffsets(GetElementPtrInst &GEP, InstCombinerImpl &IC)
Combine constant offsets separated by variable offsets.
static std::optional< ModRefInfo > isAllocSiteRemovable(Instruction *AI, SmallVectorImpl< Instruction * > &Users, const TargetLibraryInfo &TLI, bool KnowInit, unsigned MaxUsers)
static Instruction * foldSelectGEP(GetElementPtrInst &GEP, InstCombiner::BuilderTy &Builder)
Thread a GEP operation with constant indices through the constant true/false arms of a select.
static bool shouldMergeGEPs(GEPOperator &GEP, GEPOperator &Src)
static Instruction * foldSpliceBinOp(BinaryOperator &Inst, InstCombiner::BuilderTy &Builder)
static bool hasNoSignedWrap(BinaryOperator &I)
static bool isNeverEqualToUnescapedAlloc(Value *V, Instruction *AI)
static bool simplifyAssocCastAssoc(BinaryOperator *BinOp1, InstCombinerImpl &IC)
Combine constant operands of associative operations either before or after a cast to eliminate one of...
static bool combineInstructionsOverFunction(Function &F, InstructionWorklist &Worklist, AliasAnalysis *AA, AssumptionCache &AC, TargetLibraryInfo &TLI, TargetTransformInfo &TTI, DominatorTree &DT, OptimizationRemarkEmitter &ORE, BlockFrequencyInfo *BFI, BranchProbabilityInfo *BPI, ProfileSummaryInfo *PSI, const InstCombineOptions &Opts)
static Value * simplifyInstructionWithPHI(Instruction &I, PHINode *PN, Value *InValue, BasicBlock *InBB, const DataLayout &DL, const SimplifyQuery SQ)
static bool shouldCanonicalizeGEPToPtrAdd(GetElementPtrInst &GEP)
Return true if we should canonicalize the gep to an i8 ptradd.
static Value * getIdentityValue(Instruction::BinaryOps Opcode, Value *V)
This function returns identity value for given opcode, which can be used to factor patterns like (X *...
static Value * foldFrexpOfSelect(ExtractValueInst &EV, IntrinsicInst *FrexpCall, SelectInst *SelectInst, InstCombiner::BuilderTy &Builder)
static std::optional< std::pair< Value *, Value * > > matchSymmetricPhiNodesPair(PHINode *LHS, PHINode *RHS)
static Value * foldOperationIntoSelectOperand(Instruction &I, SelectInst *SI, Value *NewOp, InstCombiner &IC)
static void distributeBinOpOverSelect(InstCombinerImpl &IC, Instruction::BinaryOps Opcode, SelectInst *Sel, Value *Other, bool SelIsLHS, FastMathFlags FMF, const SimplifyQuery &SQ, Value *&True, Value *&False)
Distribute a binop over a select: (Cond ?
static Instruction * canonicalizeGEPOfConstGEPI8(GetElementPtrInst &GEP, GEPOperator *Src, InstCombinerImpl &IC)
static Instruction * tryToMoveFreeBeforeNullTest(CallInst &FI, const DataLayout &DL)
Move the call to free before a NULL test.
static Value * simplifyOperationIntoSelectOperand(Instruction &I, SelectInst *SI, bool IsTrueArm)
static Value * tryFactorization(BinaryOperator &I, const SimplifyQuery &SQ, InstCombiner::BuilderTy &Builder, Instruction::BinaryOps InnerOpcode, Value *A, Value *B, Value *C, Value *D)
This tries to simplify binary operations by factorizing out common terms (e.
static bool isRemovableWrite(CallBase &CB, Value *UsedV, const TargetLibraryInfo &TLI)
Given a call CB which uses an address UsedV, return true if we can prove the call's only possible eff...
static Instruction::BinaryOps getBinOpsForFactorization(Instruction::BinaryOps TopOpcode, BinaryOperator *Op, Value *&LHS, Value *&RHS, BinaryOperator *OtherOp)
This function predicates factorization using distributive laws.
static bool hasNoUnsignedWrap(BinaryOperator &I)
static bool SoleWriteToDeadLocal(Instruction *I, TargetLibraryInfo &TLI)
Check for case where the call writes to an otherwise dead alloca.
static Instruction * foldGEPOfPhi(GetElementPtrInst &GEP, PHINode *PN, IRBuilderBase &Builder)
static bool isCatchAll(EHPersonality Personality, Constant *TypeInfo)
Return 'true' if the given typeinfo will match anything.
static bool maintainNoSignedWrap(BinaryOperator &I, Value *B, Value *C)
static GEPNoWrapFlags getMergedGEPNoWrapFlags(GEPOperator &GEP1, GEPOperator &GEP2)
Determine nowrap flags for (gep (gep p, x), y) to (gep p, (x + y)) transform.
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
MachineBasicBlock * Folded
SmallVector< MachineOperand, 4 > Cond
unsigned Opc
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
This file contains the declarations for metadata subclasses.
#define T
uint64_t IntrinsicInst * II
static bool IsSelect(unsigned Opcode, bool CheckOnlyCC=false)
Check if the opcode is a SELECT or SELECT_CC variant.
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
This file contains the declarations for profiling metadata utility functions.
int64_t C1
int64_t C0
bool IsDead
BaseType
A given derived pointer can have multiple base pointers through phi/selects.
This file defines generic set operations that may be used on set's of different types,...
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:170
#define LLVM_DEBUG(...)
Definition Debug.h:119
static unsigned getScalarSizeInBits(Type *Ty)
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
This pass exposes codegen information to IR-level passes.
Value * RHS
Value * LHS
static const uint32_t IV[8]
Definition blake3_impl.h:83
bool isNoAliasScopeDeclDead(Instruction *Inst)
void analyse(Instruction *I)
The Input class is used to parse a yaml document into in-memory structs and vectors.
A manager for alias analyses.
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object.
static constexpr roundingMode rmNearestTiesToEven
Definition APFloat.h:379
static LLVM_ABI unsigned int semanticsPrecision(const fltSemantics &)
Definition APFloat.cpp:609
Class for arbitrary precision integers.
Definition APInt.h:78
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:230
static LLVM_ABI void udivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient, APInt &Remainder)
Dual division/remainder interface.
Definition APInt.cpp:1796
bool isMinSignedValue() const
Determine if this is the smallest signed value.
Definition APInt.h:419
static LLVM_ABI void sdivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient, APInt &Remainder)
Definition APInt.cpp:1928
LLVM_ABI APInt trunc(unsigned width) const
Truncate to new width.
Definition APInt.cpp:970
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition APInt.h:367
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:376
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
LLVM_ABI APInt sadd_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1966
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
Definition APInt.h:829
LLVM_ABI APInt smul_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1998
bool isMaxSignedValue() const
Determine if this is the largest signed value.
Definition APInt.h:401
bool isNonNegative() const
Determine if this APInt Value is non-negative (>= 0)
Definition APInt.h:330
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition APInt.h:1154
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:302
LLVM_ABI APInt ssub_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1979
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition APInt.h:853
Wrapper around alias scope domain metedata to allow accessing their fields, including surfacing the o...
Definition Metadata.h:1612
This is a simple wrapper around an MDNode which provides a higher-level interface by hiding the detai...
Definition Metadata.h:1642
const MDNode * getDomain() const
Get the MDNode for this AliasScopeNode's domain.
Definition Metadata.h:1653
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:280
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
Class to represent array types.
static LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
uint64_t getNumElements() const
Type * getElementType() const
This represents the llvm.assume intrinsic.
A function analysis which provides an AssumptionCache.
An immutable pass that tracks lazily created AssumptionCache objects.
A cache of @llvm.assume calls within a function.
Functions, function parameters, and return types can have attributes to indicate how they should be t...
Definition Attributes.h:106
LLVM_ABI uint64_t getDereferenceableBytes() const
Returns the number of dereferenceable bytes from the dereferenceable attribute.
bool isValid() const
Return true if the attribute is any kind of attribute.
Definition Attributes.h:260
LLVM Basic Block Representation.
Definition BasicBlock.h:61
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition BasicBlock.h:508
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
LLVM_ABI bool isEntryBlock() const
Return true if this is the entry block of the containing function.
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
const Instruction & front() const
Definition BasicBlock.h:462
LLVM_ABI const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:169
size_t size() const
Definition BasicBlock.h:460
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:236
static LLVM_ABI BinaryOperator * CreateNeg(Value *Op, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Helper functions to construct and inspect unary operations (NEG and NOT) via binary operators SUB and...
BinaryOps getOpcode() const
Definition InstrTypes.h:409
static LLVM_ABI BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
static BinaryOperator * CreateNUW(BinaryOps Opc, Value *V1, Value *V2, const Twine &Name="")
Definition InstrTypes.h:329
This class represents a no-op cast from one type to another.
Analysis pass which computes BlockFrequencyInfo.
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
Analysis pass which computes BranchProbabilityInfo.
Analysis providing branch probability information.
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
void setAttributes(AttributeList A)
Set the attributes for this call.
bool doesNotThrow() const
Determine if the call cannot unwind.
Value * getArgOperand(unsigned i) const
AttributeList getAttributes() const
Return the attributes for this call.
This class represents a function call, abstracting a target machine's calling convention.
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ ICMP_NE
not equal
Definition InstrTypes.h:762
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Definition InstrTypes.h:890
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Definition InstrTypes.h:852
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
Conditional Branch instruction.
LLVM_ABI void swapSuccessors()
Swap the successors of this branch instruction.
Value * getCondition() const
BasicBlock * getSuccessor(unsigned i) const
ConstantArray - Constant Array Declarations.
Definition Constants.h:590
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
A vector constant whose element type is a simple 1/2/4/8-byte integer or float/double,...
Definition Constants.h:951
static LLVM_ABI Constant * getSub(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
static LLVM_ABI Constant * getNot(Constant *C)
static LLVM_ABI Constant * getAdd(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
static LLVM_ABI Constant * getBinOpIdentity(unsigned Opcode, Type *Ty, bool AllowRHSConstant=false, bool NSZ=false)
Return the identity constant for a binary opcode.
static LLVM_ABI Constant * getNeg(Constant *C, bool HasNSW=false)
This is the shared class of boolean and integer constants.
Definition Constants.h:87
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
static LLVM_ABI ConstantInt * getBool(LLVMContext &Context, bool V)
This class represents a range of values.
LLVM_ABI bool getEquivalentICmp(CmpInst::Predicate &Pred, APInt &RHS) const
Set up Pred and RHS such that ConstantRange::makeExactICmpRegion(Pred, RHS) == *this.
static LLVM_ABI ConstantRange makeExactICmpRegion(CmpInst::Predicate Pred, const APInt &Other)
Produce the exact range such that all values in the returned range satisfy the given predicate with a...
LLVM_ABI bool contains(const APInt &Val) const
Return true if the specified value is in the set.
static LLVM_ABI ConstantRange makeExactNoWrapRegion(Instruction::BinaryOps BinOp, const APInt &Other, unsigned NoWrapKind)
Produce the range that contains X if and only if "X BinOp Other" does not wrap.
Constant Vector Declarations.
Definition Constants.h:674
static LLVM_ABI Constant * getSplat(ElementCount EC, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
static LLVM_ABI Constant * get(ArrayRef< Constant * > V)
This is an important base class in LLVM.
Definition Constant.h:44
static LLVM_ABI Constant * replaceUndefsWith(Constant *C, Constant *Replacement)
Try to replace undefined constant C or undefined elements in C with Replacement.
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
const Constant * stripPointerCasts() const
Definition Constant.h:243
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
LLVM_ABI Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
static LLVM_ABI DIExpression * appendOpsToArg(const DIExpression *Expr, ArrayRef< uint64_t > Ops, unsigned ArgNo, bool StackValue=false)
Create a copy of Expr by appending the given list of Ops to each instance of the operand DW_OP_LLVM_a...
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:63
Record of a variable value-assignment, aka a non instruction representation of the dbg....
static bool shouldExecute(CounterInfo &Counter)
Identifies a unique instance of a variable.
bool empty() const
Definition DenseMap.h:716
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:793
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:827
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
Legacy analysis pass which computes a DominatorTree.
Definition Dominators.h:277
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
This instruction extracts a struct member or array element value from an aggregate value.
ArrayRef< unsigned > getIndices() const
iterator_range< idx_iterator > indices() const
idx_iterator idx_end() const
static ExtractValueInst * Create(Value *Agg, ArrayRef< unsigned > Idxs, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
idx_iterator idx_begin() const
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:23
This class represents a freeze function that returns random concrete value if an operand is either a ...
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
FunctionPass(char &pid)
Definition Pass.h:314
bool skipFunction(const Function &F) const
Optional passes call this function to check whether the pass should be skipped.
Definition Pass.cpp:197
Represents flags for the getelementptr instruction/expression.
static GEPNoWrapFlags inBounds()
static GEPNoWrapFlags all()
static GEPNoWrapFlags noUnsignedWrap()
GEPNoWrapFlags intersectForReassociate(GEPNoWrapFlags Other) const
Given (gep (gep p, x), y), determine the nowrap flags for (gep (gep, p, y), x).
bool hasNoUnsignedWrap() const
bool isInBounds() const
GEPNoWrapFlags intersectForOffsetAdd(GEPNoWrapFlags Other) const
Given (gep (gep p, x), y), determine the nowrap flags for (gep p, x+y).
static GEPNoWrapFlags none()
GEPNoWrapFlags getNoWrapFlags() const
Definition Operator.h:385
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
static LLVM_ABI Type * getTypeAtIndex(Type *Ty, Value *Idx)
Return the type of the element at the given index of an indexable type.
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static GetElementPtrInst * CreateInBounds(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Create an "inbounds" getelementptr.
Legacy wrapper pass to provide the GlobalsAAResult object.
This instruction compares its operands according to the predicate given to the constructor.
CmpPredicate getCmpPredicate() const
static bool isEquality(Predicate P)
Return true if this predicate is either EQ or NE.
Common base class shared among various IRBuilders.
Definition IRBuilder.h:111
Value * CreatePtrAdd(Value *Ptr, Value *Offset, const Twine &Name="", GEPNoWrapFlags NW=GEPNoWrapFlags::none())
Definition IRBuilder.h:2094
Value * CreateBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:1733
ConstantInt * getInt(const APInt &AI)
Get a constant integer value.
Definition IRBuilder.h:486
void InsertHelper(Instruction *I, const Twine &Name, BasicBlock::iterator InsertPt) const
Definition IRBuilder.h:64
This instruction inserts a struct field of array element value into an aggregate value.
static InsertValueInst * Create(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
LLVM_ABI InstCombinePass(InstCombineOptions Opts={})
LLVM_ABI void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Instruction * visitBitExtractInst(BitExtractInst &BE)
Instruction * foldBinOpOfSelectAndCastOfSelectCondition(BinaryOperator &I)
Tries to simplify binops of select and cast of the select condition.
Instruction * visitCondBrInst(CondBrInst &BI)
Instruction * foldBinOpIntoSelectOrPhi(BinaryOperator &I)
This is a convenience wrapper function for the above two functions.
bool SimplifyAssociativeOrCommutative(BinaryOperator &I)
Performs a few simplifications for operators which are associative or commutative.
Instruction * visitGEPOfGEP(GetElementPtrInst &GEP, GEPOperator *Src)
Value * foldUsingDistributiveLaws(BinaryOperator &I)
Tries to simplify binary operations which some other binary operation distributes over.
Instruction * foldBinOpShiftWithShift(BinaryOperator &I)
Instruction * visitUnreachableInst(UnreachableInst &I)
Instruction * foldOpIntoPhi(Instruction &I, PHINode *PN, bool AllowMultipleUses=false)
Given a binary operator, cast instruction, or select which has a PHI node as operand #0,...
void handleUnreachableFrom(Instruction *I, SmallVectorImpl< BasicBlock * > &Worklist)
Value * SimplifyDemandedVectorElts(Value *V, APInt DemandedElts, APInt &PoisonElts, unsigned Depth=0, bool AllowMultipleUsers=false) override
The specified value produces a vector with any number of elements.
Instruction * visitFreeze(FreezeInst &I)
Instruction * foldBinOpSelectBinOp(BinaryOperator &Op)
In some cases it is beneficial to fold a select into a binary operator.
void handlePotentiallyDeadBlocks(SmallVectorImpl< BasicBlock * > &Worklist)
bool prepareWorklist(Function &F)
Perform early cleanup and prepare the InstCombine worklist.
Instruction * FoldOpIntoSelect(Instruction &Op, SelectInst *SI, bool FoldWithMultiUse=false, bool SimplifyBothArms=false)
Given an instruction with a select as one operand and a constant as the other operand,...
Instruction * visitFree(CallInst &FI, Value *FreedOp)
Instruction * visitExtractValueInst(ExtractValueInst &EV)
void handlePotentiallyDeadSuccessors(BasicBlock *BB, BasicBlock *LiveSucc)
Instruction * foldBinopWithRecurrence(BinaryOperator &BO)
Try to fold binary operators whose operands are simple interleaved recurrences to a single recurrence...
Instruction * eraseInstFromFunction(Instruction &I) override
Combiner aware instruction erasure.
Instruction * visitLandingPadInst(LandingPadInst &LI)
const InstCombineCLOptions & CLOpts
Value * simplifyNestedSelectsUsingImpliedCond(SelectInst &SI, Value *CondVal, bool CondIsTrue)
Given that CondVal is known to be CondIsTrue, try to simplify SI to one of its arms.
Instruction * visitReturnInst(ReturnInst &RI)
Instruction * visitSwitchInst(SwitchInst &SI)
Instruction * visitBitInsertInst(BitInsertInst &BI)
Instruction * foldBinopWithPhiOperands(BinaryOperator &BO)
For a binary operator with 2 phi operands, try to hoist the binary operation before the phi.
bool SimplifyDemandedFPClass(Instruction *I, unsigned Op, FPClassTest DemandedMask, KnownFPClass &Known, const SimplifyQuery &Q, unsigned Depth=0)
bool mergeStoreIntoSuccessor(StoreInst &SI)
Try to transform: if () { *P = v1; } else { *P = v2 } or: *P = v1; if () { *P = v2; }...
Instruction * tryFoldInstWithCtpopWithNot(Instruction *I)
Instruction * visitUncondBrInst(UncondBrInst &BI)
bool tryReassociateAndFoldSymmetricPair(BinaryOperator &OuterOp, BinaryOperator &InnerOp, Value *InnerVal0, Value *InnerVal1, Value *OuterVal)
If InnerVal1 and OuterVal form a symmetric pair, and "op" is commutative: "(InnerVal0 op InnerVal1) o...
void CreateNonTerminatorUnreachable(Instruction *InsertAt)
Create and insert the idiom we use to indicate a block is unreachable without having to rewrite the C...
Value * pushFreezeToPreventPoisonFromPropagating(FreezeInst &FI)
bool run()
Run the combiner over the entire worklist until it is empty.
Instruction * foldVectorBinop(BinaryOperator &Inst)
Canonicalize the position of binops relative to shufflevector.
bool removeInstructionsBeforeUnreachable(Instruction &I)
Value * SimplifySelectsFeedingBinaryOp(BinaryOperator &I, Value *LHS, Value *RHS)
void tryToSinkInstructionDbgVariableRecords(Instruction *I, BasicBlock::iterator InsertPos, BasicBlock *SrcBlock, BasicBlock *DestBlock, SmallVectorImpl< DbgVariableRecord * > &DPUsers)
void addDeadEdge(BasicBlock *From, BasicBlock *To, SmallVectorImpl< BasicBlock * > &Worklist)
Constant * unshuffleConstant(ArrayRef< int > ShMask, Constant *C, VectorType *NewCTy)
Find a constant NewC that has property: shuffle(NewC, poison, ShMask) = C for lanes that select NewC.
Instruction * visitAllocSite(Instruction &FI)
Instruction * visitGetElementPtrInst(GetElementPtrInst &GEP)
Value * tryFactorizationFolds(BinaryOperator &I)
This tries to simplify binary operations by factorizing out common terms (e.
Instruction * foldFreezeIntoRecurrence(FreezeInst &I, PHINode *PN)
bool tryToSinkInstruction(Instruction *I, BasicBlock *DestBlock)
Try to move the specified instruction from its current block into the beginning of DestBlock,...
void freelyInvertAllUsersOf(Value *V, Value *IgnoredUser=nullptr)
Freely adapt every user of V as-if V was changed to !V.
The core instruction combiner logic.
SimplifyQuery SQ
const DataLayout & getDataLayout() const
bool isFreeToInvert(Value *V, bool WillInvertAllUses, bool &DoesConsume)
Return true if the specified value is free to invert (apply ~ to).
static unsigned getComplexity(Value *V)
Assign a complexity or rank value to LLVM Values.
bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero=false, const Instruction *CtxI=nullptr, unsigned Depth=0)
TargetLibraryInfo & TLI
Instruction * InsertNewInstBefore(Instruction *New, BasicBlock::iterator Old)
Inserts an instruction New before instruction Old.
Instruction * replaceInstUsesWith(Instruction &I, Value *V)
A combiner-aware RAUW-like routine.
static bool shouldAvoidAbsorbingNotIntoSelect(const SelectInst &SI)
void replaceUse(Use &U, Value *NewValue)
Replace use and add the previously used value to the worklist.
static bool isCanonicalPredicate(CmpPredicate Pred)
Predicate canonicalization reduces the number of patterns that need to be matched by other transforms...
Instruction * AnnotationMetadataSource
Source for annotation metadata, used by the IRBuilder inserter.
InstructionWorklist & Worklist
A worklist of the instructions that need to be simplified.
Instruction * InsertNewInstWith(Instruction *New, BasicBlock::iterator Old)
Same as InsertNewInstBefore, but also sets the debug loc.
BranchProbabilityInfo * BPI
ReversePostOrderTraversal< BasicBlock * > & RPOT
const DataLayout & DL
DomConditionCache DC
unsigned ComputeNumSignBits(const Value *Op, const Instruction *CtxI=nullptr, unsigned Depth=0) const
const bool MinimizeSize
IRBuilder< TargetFolder, IRBuilderInstCombineInserter > BuilderTy
An IRBuilder that automatically inserts new instructions into the worklist.
LLVM_ABI std::optional< Instruction * > targetInstCombineIntrinsic(IntrinsicInst &II)
AssumptionCache & AC
void addToWorklist(Instruction *I)
LLVM_ABI Value * getFreelyInvertedImpl(Value *V, bool WillInvertAllUses, BuilderTy *Builder, bool &DoesConsume, unsigned Depth)
Return nonnull value if V is free to invert under the condition of WillInvertAllUses.
SmallDenseSet< std::pair< const BasicBlock *, const BasicBlock * >, 8 > BackEdges
Backedges, used to avoid pushing instructions across backedges in cases where this may result in infi...
LLVM_ABI std::optional< Value * > targetSimplifyDemandedVectorEltsIntrinsic(IntrinsicInst &II, APInt DemandedElts, APInt &UndefElts, APInt &UndefElts2, APInt &UndefElts3, std::function< void(Instruction *, unsigned, APInt, APInt &)> SimplifyAndSetOp)
Instruction * replaceOperand(Instruction &I, unsigned OpNum, Value *V)
Replace operand of instruction and add old operand to the worklist.
DominatorTree & DT
static Constant * getSafeVectorConstantForBinop(BinaryOperator::BinaryOps Opcode, Constant *In, bool IsRHSConstant)
Some binary operators require special handling to avoid poison and undefined behavior.
SmallDenseSet< std::pair< BasicBlock *, BasicBlock * >, 8 > DeadEdges
Edges that are known to never be taken.
LLVM_ABI std::optional< Value * > targetSimplifyDemandedUseBitsIntrinsic(IntrinsicInst &II, APInt DemandedMask, KnownBits &Known, bool &KnownBitsComputed)
LLVM_ABI bool isValidAddrSpaceCast(unsigned FromAS, unsigned ToAS) const
void computeKnownBits(const Value *V, KnownBits &Known, const Instruction *CtxI, unsigned Depth=0) const
Value * getFreelyInverted(Value *V, bool WillInvertAllUses, BuilderTy *Builder, bool &DoesConsume)
bool isBackEdge(const BasicBlock *From, const BasicBlock *To)
void visit(Iterator Start, Iterator End)
Definition InstVisitor.h:87
The legacy pass manager's instcombine pass.
Definition InstCombine.h:68
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
bool runOnFunction(Function &F) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass.
InstructionWorklist - This is the worklist management logic for InstCombine and other simplification ...
LLVM_ABI void dropUBImplyingAttrsAndMetadata(ArrayRef< unsigned > Keep={})
Drop any attributes or metadata that can cause immediate undefined behavior.
static bool isBitwiseLogicOp(unsigned Opcode)
Determine if the Opcode is and/or/xor.
LLVM_ABI void copyIRFlags(const Value *V, bool IncludeWrapFlags=true)
Convenience method to copy supported exact, fast-math, and (optionally) wrapping flags from V to this...
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
LLVM_ABI void setAAMetadata(const AAMDNodes &N)
Sets the AA metadata on this instruction from the AAMDNodes structure.
LLVM_ABI bool isAssociative() const LLVM_READONLY
Return true if the instruction is associative:
LLVM_ABI bool isCommutative() const LLVM_READONLY
Return true if the instruction is commutative:
LLVM_ABI void setFastMathFlags(FastMathFlags FMF)
Convenience function for setting multiple fast-math flags on this instruction, which must be an opera...
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
bool isTerminator() const
iterator_range< user_iterator > users()
void dropPoisonGeneratingAnnotations()
Drops flags, attributes and metadata that may generate poison.
LLVM_ABI FastMathFlags getFastMathFlags() const LLVM_READONLY
Convenience function for getting all the fast-math flags, which must be an operator which supports th...
LLVM_ABI bool willReturn() const LLVM_READONLY
Return true if the instruction will return (unwinding is considered as a form of returning control fl...
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
bool isBitwiseLogicOp() const
Return true if this is and/or/xor.
bool isShift() const
LLVM_ABI void dropPoisonGeneratingFlags()
Drops flags that may cause this instruction to evaluate to poison despite having non-poison inputs.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
LLVM_ABI void copyMetadata(const Instruction &SrcInst, ArrayRef< unsigned > WL=ArrayRef< unsigned >())
Copy metadata from SrcInst to this instruction.
bool isIntDivRem() const
Class to represent integer types.
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:333
A wrapper class for inspecting calls to intrinsic functions.
Invoke instruction.
static InvokeInst * Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, BasicBlock *IfException, ArrayRef< Value * > Args, const Twine &NameStr, InsertPosition InsertBefore=nullptr)
The landingpad instruction holds all of the information necessary to generate correct exception handl...
bool isCleanup() const
Return 'true' if this landingpad instruction is a cleanup.
unsigned getNumClauses() const
Get the number of clauses for this landing pad.
static LLVM_ABI LandingPadInst * Create(Type *RetTy, unsigned NumReservedClauses, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedClauses is a hint for the number of incoming clauses that this landingpad w...
LLVM_ABI void addClause(Constant *ClauseVal)
Add a catch or filter clause to the landing pad.
bool isCatch(unsigned Idx) const
Return 'true' if the clause and index Idx is a catch clause.
bool isFilter(unsigned Idx) const
Return 'true' if the clause and index Idx is a filter clause.
Constant * getClause(unsigned Idx) const
Get the value of the clause at index Idx.
void setCleanup(bool V)
Indicate that this landingpad instruction is a cleanup.
A function/module analysis which provides an empty LastRunTrackingInfo.
This is an alternative analysis pass to BlockFrequencyInfoWrapperPass.
static void getLazyBFIAnalysisUsage(AnalysisUsage &AU)
Helper for client passes to set up the analysis usage on behalf of this pass.
An instruction for reading from memory.
Value * getPointerOperand()
bool isVolatile() const
Return true if this is a load from a volatile memory location.
Metadata node.
Definition Metadata.h:1087
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1443
ArrayRef< MDOperand > operands() const
Definition Metadata.h:1441
unsigned getNumOperands() const
Return number of MDNode operands.
Definition Metadata.h:1449
Tracking metadata reference owned by Metadata.
Definition Metadata.h:908
This is the common base class for memset/memcpy/memmove.
static LLVM_ABI MemoryLocation getForDest(const MemIntrinsic *MI)
Return a location representing the destination of a memory set or transfer.
Root of the metadata hierarchy.
Definition Metadata.h:65
Value * getLHS() const
Value * getRHS() const
static ICmpInst::Predicate getPredicate(Intrinsic::ID ID)
Returns the comparison predicate underlying the intrinsic.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
MDNode * getScopeList() const
OptimizationRemarkEmitter legacy analysis pass.
The optimization diagnostic interface.
Utility class for integer operators which may exhibit overflow - Add, Sub, Mul, and Shl.
Definition Operator.h:78
bool hasNoSignedWrap() const
Test whether this operation is known to never undergo signed overflow, aka the nsw property.
Definition Operator.h:113
bool hasNoUnsignedWrap() const
Test whether this operation is known to never undergo unsigned overflow, aka the nuw property.
Definition Operator.h:107
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
op_range incoming_values()
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
PassRegistry - This class manages the registration and intitialization of the pass subsystem as appli...
AnalysisType & getAnalysis() const
getAnalysis<AnalysisType>() - This function is used by subclasses to get to the analysis information ...
AnalysisType * getAnalysisIfAvailable() const
getAnalysisIfAvailable<AnalysisType>() - Subclasses use this function to get analysis information tha...
In order to facilitate speculative execution, many instructions do not invoke immediate undefined beh...
Definition Constants.h:1705
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:151
PreservedAnalyses & preserve()
Mark an analysis as preserved.
Definition Analysis.h:132
An analysis pass based on the new PM to deliver ProfileSummaryInfo.
An analysis pass based on legacy pass manager to deliver ProfileSummaryInfo.
Analysis providing profile information.
bool hasProfileSummary() const
Returns true if profile summary is available.
A global registry used in conjunction with static constructors to make pluggable components (like tar...
Definition Registry.h:116
Return a value (possibly void), from a function.
Value * getReturnValue() const
Convenience accessor. Returns null if there is no return value.
This class represents the LLVM 'select' instruction.
const Value * getFalseValue() const
const Value * getCondition() const
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", InsertPosition InsertBefore=nullptr, const Instruction *MDFrom=nullptr)
const Value * getTrueValue() const
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
This instruction constructs a fixed permutation of two input vectors.
size_type size() const
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:346
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition SmallSet.h:134
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:184
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
iterator erase(const_iterator CI)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
typename SuperClass::iterator iterator
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Multiway switch.
Analysis pass providing the TargetTransformInfo.
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
Wrapper pass for TargetTransformInfo.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
bool isSized() const
Return true if it makes sense to take the size of this type.
Definition Type.h:321
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.h:354
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:292
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:370
bool isStructTy() const
True if this is an instance of StructType.
Definition Type.h:271
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:187
LLVM_ABI bool isScalableTy() const
Return true if this is a type whose size is a known multiple of vscale.
Definition Type.cpp:61
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
LLVM_ABI const fltSemantics & getFltSemantics() const
Definition Type.cpp:96
Unconditional Branch instruction.
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
This function has undefined behavior.
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
Use * op_iterator
Definition User.h:254
op_range operands()
Definition User.h:267
op_iterator op_begin()
Definition User.h:259
LLVM_ABI bool isDroppable() const
A droppable user is a user for which uses can be dropped without affecting correctness and should be ...
Definition User.cpp:109
LLVM_ABI bool replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
Definition User.cpp:21
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
op_iterator op_end()
Definition User.h:261
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
const Value * stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL, APInt &Offset) const
This is a wrapper around stripAndAccumulateConstantOffsets with the in-bounds requirement set to fals...
Definition Value.h:729
LLVM_ABI bool hasOneUser() const
Return true if there is exactly one user of this value.
Definition Value.cpp:158
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:441
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
bool hasUseList() const
Check if this Value has a use-list.
Definition Value.h:346
LLVM_ABI bool hasNUses(unsigned N) const
Return true if this Value has exactly N uses.
Definition Value.cpp:142
LLVM_ABI const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
Definition Value.cpp:707
bool use_empty() const
Definition Value.h:348
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:395
LLVM_ABI uint64_t getPointerDereferenceableBytes(const DataLayout &DL, bool &CanBeNull, bool *CanBeFreed) const
Returns the number of bytes known to be dereferenceable for the pointer value.
Definition Value.cpp:913
Base class of all SIMD vector types.
ElementCount getElementCount() const
Return an ElementCount instance to represent the (possibly scalable) number of elements in the vector...
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
Value handle that is nullable, but tries to track the Value.
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
Definition ilist_node.h:34
reverse_self_iterator getReverseIterator()
Definition ilist_node.h:126
self_iterator getIterator()
Definition ilist_node.h:123
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
A raw_ostream that writes to an std::string.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Abstract Attribute helper functions.
Definition Attributor.h:166
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
BinaryOp_match< SpecificConstantMatch, SrcTy, TargetOpcode::G_SUB > m_Neg(const SrcTy &&Src)
Matches a register negated by a G_SUB.
AllOnesConstantMatch m_AllOnes()
BinaryOp_match< SrcTy, SpecificConstantMatch, TargetOpcode::G_XOR, true > m_Not(const SrcTy &&Src)
Matches a register not-ed by a G_XOR.
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
match_unless< Pattern > m_Unless(const Pattern &P)
Match if the inner matcher does NOT match.
match_combine_or< Ty... > m_CombineOr(const Ty &...Ps)
Combine pattern matchers matching any of Ps patterns.
match_combine_and< Ty... > m_CombineAnd(const Ty &...Ps)
Combine pattern matchers matching all of Ps patterns.
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
CmpClass_match< LHS, RHS, FCmpInst > m_FCmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::AShr > m_AShr(const LHS &L, const RHS &R)
auto m_PtrToIntOrAddr(const OpTy &Op)
Matches PtrToInt or PtrToAddr.
OneOps_match< OpTy, Instruction::Freeze > m_Freeze(const OpTy &Op)
Matches FreezeInst.
auto m_Poison()
Match an arbitrary poison constant.
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
CastInst_match< OpTy, TruncInst > m_Trunc(const OpTy &Op)
Matches Trunc.
BinaryOp_match< LHS, RHS, Instruction::Xor > m_Xor(const LHS &L, const RHS &R)
br_match m_UnconditionalBr(BasicBlock *&Succ)
ap_match< APInt > m_APIntAllowPoison(const APInt *&Res)
Match APInt while allowing poison in splat vector constants.
auto m_ConstantExpr()
Match a constant expression or a constant that contains a constant expression.
specific_intval< false > m_SpecificInt(const APInt &V)
Match a specific integer value or vector with all elements equal to the value.
bool match(Val *V, const Pattern &P)
BinOpPred_match< LHS, RHS, is_idiv_op > m_IDiv(const LHS &L, const RHS &R)
Matches integer division operations.
match_bind< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
DisjointOr_match< LHS, RHS > m_DisjointOr(const LHS &L, const RHS &R)
BinOpPred_match< LHS, RHS, is_right_shift_op > m_Shr(const LHS &L, const RHS &R)
Matches logical shift operations.
ap_match< APFloat > m_APFloat(const APFloat *&Res)
Match a ConstantFP or splatted ConstantVector, binding the specified pointer to the contained APFloat...
cst_pred_ty< is_nonnegative > m_NonNegative()
Match an integer or vector of non-negative values.
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
auto m_BinOp()
Match an arbitrary binary operation and ignore it.
ExtractValue_match< Ind, Val_t > m_ExtractValue(const Val_t &V)
Match a single index ExtractValue instruction.
match_combine_or< CastInst_match< OpTy, UIToFPInst >, CastInst_match< OpTy, SIToFPInst > > m_IToFP(const OpTy &Op)
auto m_Value()
Match an arbitrary value and ignore it.
auto m_Ctpop(const Opnd0 &Op0)
BinaryOp_match< LHS, RHS, Instruction::Mul > m_Mul(const LHS &L, const RHS &R)
auto m_Constant()
Match an arbitrary Constant and ignore it.
ContainsMatchingVectorElement_match< SPTy > m_ContainsMatchingVectorElement(const SPTy &SubPattern)
Match a vector constant where at least one of its elements matches the subpattern.
NNegZExt_match< OpTy > m_NNegZExt(const OpTy &Op)
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
TwoOps_match< V1_t, V2_t, Instruction::ShuffleVector > m_Shuffle(const V1_t &v1, const V2_t &v2)
Matches ShuffleVectorInst independently of mask value.
ThreeOps_match< decltype(m_Value()), LHS, RHS, Instruction::Select, true > m_c_Select(const LHS &L, const RHS &R)
Match Select(C, LHS, RHS) or Select(C, RHS, LHS)
SpecificCmpClass_match< LHS, RHS, ICmpInst > m_SpecificICmp(CmpPredicate MatchPred, const LHS &L, const RHS &R)
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
Splat_match< T > m_Splat(const T &SubPattern)
Match a vector splat.
BinaryOp_match< LHS, RHS, Instruction::UDiv > m_UDiv(const LHS &L, const RHS &R)
is_zero< true > m_Zero()
Match any null constant or a vector with all elements equal to 0.
PtrAdd_match< PointerOpTy, OffsetOpTy > m_PtrAdd(const DataLayout &DL, const PointerOpTy &PointerOp, const OffsetOpTy &OffsetOp)
Matches GEP with i8 source element type and canonical index type.
match_immconstant_ty m_ImmConstant()
Match an arbitrary immediate Constant and ignore it.
SelectLike_match< CondTy, LTy, RTy > m_SelectLike(const CondTy &C, const LTy &TrueC, const RTy &FalseC)
Matches a value that behaves like a boolean-controlled select, i.e.
match_combine_or< BinaryOp_match< LHS, RHS, Instruction::Add >, DisjointOr_match< LHS, RHS > > m_AddLike(const LHS &L, const RHS &R)
Match either "add" or "or disjoint".
CastOperator_match< OpTy, Instruction::BitCast > m_BitCast(const OpTy &Op)
Matches BitCast.
match_combine_or< CastInst_match< OpTy, SExtInst >, NNegZExt_match< OpTy > > m_SExtLike(const OpTy &Op)
Match either "sext" or "zext nneg".
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
BinaryOp_match< LHS, RHS, Instruction::SDiv > m_SDiv(const LHS &L, const RHS &R)
auto m_VectorInsert(const Opnd0 &Op0, const Opnd1 &Op1, const Opnd2 &Op2)
match_combine_or< OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoSignedWrap >, DisjointOr_match< LHS, RHS > > m_NSWAddLike(const LHS &L, const RHS &R)
Match either "add nsw" or "or disjoint".
AnyBinaryOp_match< LHS, RHS, true > m_c_BinOp(const LHS &L, const RHS &R)
Matches a BinaryOperator with LHS and RHS in either order.
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
CmpClass_match< LHS, RHS, ICmpInst > m_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
match_combine_or< CastInst_match< OpTy, ZExtInst >, CastInst_match< OpTy, SExtInst > > m_ZExtOrSExt(const OpTy &Op)
BinOpPred_match< LHS, RHS, is_shift_op > m_Shift(const LHS &L, const RHS &R)
Matches shift operations.
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
cstfp_pred_ty< is_non_zero_fp > m_NonZeroFP()
Match a floating-point non-zero.
auto m_MaxOrMin(const Opnd0 &Op0, const Opnd1 &Op1)
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
brc_match< Cond_t, match_bind< BasicBlock >, match_bind< BasicBlock > > m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F)
BinaryOp_match< LHS, RHS, Instruction::SRem > m_SRem(const LHS &L, const RHS &R)
auto m_Undef()
Match an arbitrary undef constant.
auto m_VecReverse(const Opnd0 &Op0)
BinaryOp_match< LHS, RHS, Instruction::Or > m_Or(const LHS &L, const RHS &R)
CastInst_match< OpTy, SExtInst > m_SExt(const OpTy &Op)
Matches SExt.
match_combine_or< OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap >, DisjointOr_match< LHS, RHS > > m_NUWAddLike(const LHS &L, const RHS &R)
Match either "add nuw" or "or disjoint".
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI Intrinsic::ID getInverseMinMaxIntrinsic(Intrinsic::ID MinMaxID)
@ Offset
Definition DWP.cpp:577
detail::zippy< detail::zip_shortest, T, U, Args... > zip(T &&t, U &&u, Args &&...args)
zip iterator for two or more iteratable types.
Definition STLExtras.h:846
void stable_sort(R &&Range)
Definition STLExtras.h:2132
LLVM_ABI void initializeInstructionCombiningPassPass(PassRegistry &)
LLVM_ABI cl::opt< bool > ProfcheckDisableMetadataFixes
LLVM_ABI unsigned removeAllNonTerminatorAndEHPadInstructions(BasicBlock *BB)
Remove all instructions from a basic block other than its terminator and any present EH pad instructi...
Definition Local.cpp:2564
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
LLVM_ABI Value * simplifyBitInsertInst(Value *Base, Value *Val, Value *Offset, const SimplifyQuery &Q)
Given operands for a BitInsertInst, fold the result or return null.
LLVM_ABI Value * simplifyGEPInst(Type *SrcTy, Value *Ptr, ArrayRef< Value * > Indices, GEPNoWrapFlags NW, const SimplifyQuery &Q)
Given operands for a GetElementPtrInst, fold the result or return null.
bool succ_empty(const Instruction *I)
Definition CFG.h:141
LLVM_ABI Value * simplifyFreezeInst(Value *Op, const SimplifyQuery &Q)
Given an operand for a Freeze, see if we can fold the result.
LLVM_ABI std::optional< StringRef > getAllocationFamily(const Value *I)
If a function is part of an allocation family (e.g.
LLVM_ABI FunctionPass * createInstructionCombiningPass()
LLVM_ABI void findDbgValues(Value *V, SmallVectorImpl< DbgVariableRecord * > &DbgVariableRecords)
Finds the dbg.values describing a value.
@ Known
Known to have no common set bits.
LLVM_ABI bool freezeUsesAfterDef(FreezeInst &FI, DominatorTree &DT, SmallVectorImpl< User * > *Users=nullptr)
Move FI right after the definition of its operand, and replace the uses of the operand that it domina...
Definition Local.cpp:4095
void set_intersect(S1Ty &S1, const S2Ty &S2)
set_intersect(A, B) - Compute A := A ^ B Identical to set_intersection, except that it works on set<>...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI void salvageDebugInfo(const MachineRegisterInfo &MRI, MachineInstr &MI)
Assuming the instruction MI is going to be deleted, attempt to salvage debug users of MI by writing t...
Definition Utils.cpp:1833
auto successors(const MachineBasicBlock *BB)
LLVM_ABI Constant * ConstantFoldInstruction(const Instruction *I, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldInstruction - Try to constant fold the specified instruction.
OuterAnalysisManagerProxy< ModuleAnalysisManager, Function > ModuleAnalysisManagerFunctionProxy
Provide the ModuleAnalysisManager to Function proxy.
LLVM_ABI Value * lowerObjectSizeCall(IntrinsicInst *ObjectSize, const DataLayout &DL, const TargetLibraryInfo *TLI, bool MustSucceed)
Try to turn a call to @llvm.objectsize into an integer value of the given Type.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
LLVM_ABI Value * simplifyInstructionWithOperands(Instruction *I, ArrayRef< Value * > NewOps, const SimplifyQuery &Q)
Like simplifyInstruction but the operands of I are replaced with NewOps.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2229
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
gep_type_iterator gep_type_end(const User *GEP)
LLVM_ABI Value * getSplatValue(const Value *V)
Get splat value if the input is a splat vector or return nullptr.
LLVM_ABI Value * getReallocatedOperand(const CallBase *CB)
If this is a call to a realloc function, return the reallocated operand.
APFloat frexp(const APFloat &X, int &Exp, APFloat::roundingMode RM)
Equivalent of C standard library function.
Definition APFloat.h:1761
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
LLVM_ABI bool handleUnreachableTerminator(Instruction *I, SmallVectorImpl< Value * > &PoisonedValues)
If a terminator in an unreachable basic block has an operand of type Instruction, transform it into p...
Definition Local.cpp:2547
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition bit.h:204
LLVM_ABI void setBranchWeights(Instruction &I, ArrayRef< uint32_t > Weights, bool IsExpected, bool ElideAllZero=false)
Create a new branch_weights metadata node and add or overwrite a prof metadata reference to instructi...
const InstCombineCLOptions & getInstCombineCLOptions(const Function &F)
LLVM_ABI bool matchSimpleRecurrence(const PHINode *P, BinaryOperator *&BO, Value *&Start, Value *&Step)
Attempt to match a simple first order recurrence cycle of the form: iv = phi Ty [Start,...
LLVM_ABI Constant * ConstantFoldCompareInstOperands(unsigned Predicate, Constant *LHS, Constant *RHS, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, const Function *CtxF=nullptr)
Attempt to constant fold a compare instruction (icmp/fcmp) with the specified operands.
LLVM_ABI Value * simplifyAddInst(Value *LHS, Value *RHS, bool IsNSW, bool IsNUW, const SimplifyQuery &Q)
Given operands for an Add, fold the result or return null.
LLVM_ABI Constant * ConstantFoldConstant(const Constant *C, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldConstant - Fold the constant using the specified DataLayout.
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
constexpr bool has_single_bit(T Value) noexcept
Definition bit.h:149
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
LLVM_ABI bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction is not used, and the instruction will return.
Definition Local.cpp:408
LLVM_ABI bool isSplatValue(const Value *V, int Index=-1, unsigned Depth=0)
Return true if each element of the vector value V is poisoned or equal to every other non-poisoned el...
LLVM_ABI Value * emitGEPOffset(IRBuilderBase *Builder, const DataLayout &DL, User *GEP, bool NoAssumptions=false)
Given a getelementptr instruction/constantexpr, emit the code necessary to compute the offset from th...
Definition Local.cpp:22
constexpr unsigned MaxAnalysisRecursionDepth
LLVM_ABI bool isAllocLikeFn(const Value *V)
Tests if a value is a call or invoke to a library function that allocates memory (either malloc,...
FPOp
The floating-point operations supported by the folding helpers.
Definition FPFold.h:25
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
bool isModSet(const ModRefInfo MRI)
Definition ModRef.h:49
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
LLVM_ABI bool LowerDbgDeclare(Function &F)
Lowers dbg.declare records into appropriate set of dbg.value records.
Definition Local.cpp:1865
LLVM_ABI bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI void salvageDebugInfoForDbgValues(Instruction &I, ArrayRef< DbgVariableRecord * > DbgRecords)
Salvage only the records in DbgRecords instead of finding every debug user of I.
Definition Local.cpp:2170
generic_gep_type_iterator<> gep_type_iterator
LLVM_ABI void ConvertDebugDeclareToDebugValue(DbgVariableRecord *DVR, StoreInst *SI, DIBuilder &Builder)
Inserts a dbg.value record before a store to an alloca'd value that has an associated dbg....
Definition Local.cpp:1703
LLVM_ABI bool wouldInstructionBeTriviallyDead(const Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction would have no side effects if it was not used.
Definition Local.cpp:415
LLVM_ABI Constant * ConstantFoldCastOperand(unsigned Opcode, Constant *C, Type *DestTy, const DataLayout &DL)
Attempt to constant fold a cast with the specified operand.
LLVM_ABI bool canCreateUndefOrPoison(const Operator *Op, bool ConsiderFlagsAndMetadata=true)
canCreateUndefOrPoison returns true if Op can create undef or poison from non-undef & non-poison oper...
LLVM_ABI Constant * getInitialValueOfAllocation(const Value *V, Type *Ty)
If this is a call to an allocation function that initializes memory to a fixed value,...
LLVM_ABI EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth, bool MustPreserveProvenance=false)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI Value * simplifyExtractValueInst(Value *Agg, ArrayRef< unsigned > Idxs, const SimplifyQuery &Q)
Given operands for an ExtractValueInst, fold the result or return null.
LLVM_ABI Constant * ConstantFoldBinaryOpOperands(unsigned Opcode, Constant *LHS, Constant *RHS, const DataLayout &DL)
Attempt to constant fold a binary operation with the specified operands.
LLVM_ABI bool replaceAllDbgUsesWith(Instruction &From, Value &To, Instruction &DomPoint, DominatorTree &DT)
Point debug users of From to To or salvage them.
Definition Local.cpp:2493
LLVM_ABI bool isKnownNonZero(const Value *V, const SimplifyQuery &Q, unsigned Depth=0)
Return true if the given value is known to be non-zero when defined.
constexpr int PoisonMaskElem
ModRefInfo
Flags indicating whether a memory access modifies or references memory.
Definition ModRef.h:28
@ Ref
The access may reference the value stored in memory.
Definition ModRef.h:32
@ ModRef
The access may reference and may modify the value stored in memory.
Definition ModRef.h:36
@ Mod
The access may modify the value stored in memory.
Definition ModRef.h:34
@ NoModRef
The access neither references nor modifies the value stored in memory.
Definition ModRef.h:30
@ Other
Any other memory.
Definition ModRef.h:68
TargetTransformInfo TTI
LLVM_ABI Value * simplifyBitExtractInst(Type *Ty, Value *Src, Value *Offset, const SimplifyQuery &Q)
Given operands for a BitExtractInst, fold the result or return null.
LLVM_ABI Value * simplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for a BinaryOperator, fold the result or return null.
@ Sub
Subtraction of integers.
@ Add
Sum of integers.
DWARFExpression::Operation Op
bool isSafeToSpeculativelyExecuteWithVariableReplaced(const Instruction *I, bool IgnoreUBImplyingAttrs=true)
Don't use information from its non-constant operands.
LLVM_ABI bool isGuaranteedNotToBeUndefOrPoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Return true if this function can prove that V does not have undef bits and is never poison.
constexpr unsigned BitWidth
LLVM_ABI bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I)
Return true if this function can prove that the instruction I will always transfer execution to one o...
LLVM_ABI Constant * getLosslessInvCast(Constant *C, Type *InvCastTo, unsigned CastOp, const DataLayout &DL, PreservedCastFlags *Flags=nullptr)
Try to cast C to InvC losslessly, satisfying CastOp(InvC) equals C, or CastOp(InvC) is a refined valu...
LLVM_ABI bool extractBranchWeights(const MDNode *ProfileData, SmallVectorImpl< uint32_t > &Weights)
Extract branch weights from MD_prof metadata.
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
Definition STLExtras.h:2035
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
gep_type_iterator gep_type_begin(const User *GEP)
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
bool equal(L &&LRange, R &&RRange)
Wrapper function around std::equal to detect if pair-wise elements between two ranges are the same.
Definition STLExtras.h:2162
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
LLVM_ABI Constant * getElidedFreeResult(const Value *V)
If this is a call to a free function that returns a value, return the value that will be returned whe...
AAResults AliasAnalysis
Temporary typedef for legacy code that uses a generic AliasAnalysis pointer or reference.
static auto filterDbgVars(iterator_range< simple_ilist< DbgRecord >::iterator > R)
Filter the DbgRecord range to DbgVariableRecord types only and downcast.
LLVM_ABI Value * getFreedOperand(const CallBase *CB)
If this if a call to a free function, return the freed operand.
LLVM_ABI void initializeInstCombine(PassRegistry &)
Initialize all passes linked into the InstCombine library.
LLVM_ABI void findDbgUsers(Value *V, SmallVectorImpl< DbgVariableRecord * > &DbgVariableRecords)
Finds the debug info records describing a value.
LLVM_ABI Constant * ConstantFoldBinaryInstruction(unsigned Opcode, Constant *V1, Constant *V2)
bool isRefSet(const ModRefInfo MRI)
Definition ModRef.h:52
LLVM_ABI std::optional< bool > isImpliedCondition(const Value *LHS, const Value *RHS, const DataLayout &DL, bool LHSIsTrue=true, unsigned Depth=0)
Return true if RHS is known to be implied true by LHS.
LLVM_ABI bool isRemovableAlloc(const CallBase *V)
Return true if this is a call to an allocation function that does not have side effects that we are r...
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881
#define N
SimplifyQuery getWithInstruction(const Instruction *I) const