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