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