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