xref: /freebsd-src/contrib/llvm-project/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
10b57cec5SDimitry Andric //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // InstructionCombining - Combine instructions to form fewer, simple
100b57cec5SDimitry Andric // instructions.  This pass does not modify the CFG.  This pass is where
110b57cec5SDimitry Andric // algebraic simplification happens.
120b57cec5SDimitry Andric //
130b57cec5SDimitry Andric // This pass combines things like:
140b57cec5SDimitry Andric //    %Y = add i32 %X, 1
150b57cec5SDimitry Andric //    %Z = add i32 %Y, 1
160b57cec5SDimitry Andric // into:
170b57cec5SDimitry Andric //    %Z = add i32 %X, 2
180b57cec5SDimitry Andric //
190b57cec5SDimitry Andric // This is a simple worklist driven algorithm.
200b57cec5SDimitry Andric //
210b57cec5SDimitry Andric // This pass guarantees that the following canonicalizations are performed on
220b57cec5SDimitry Andric // the program:
230b57cec5SDimitry Andric //    1. If a binary operator has a constant operand, it is moved to the RHS
240b57cec5SDimitry Andric //    2. Bitwise operators with constant operands are always grouped so that
250b57cec5SDimitry Andric //       shifts are performed first, then or's, then and's, then xor's.
260b57cec5SDimitry Andric //    3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
270b57cec5SDimitry Andric //    4. All cmp instructions on boolean values are replaced with logical ops
280b57cec5SDimitry Andric //    5. add X, X is represented as (X*2) => (X << 1)
290b57cec5SDimitry Andric //    6. Multiplies with a power-of-two constant argument are transformed into
300b57cec5SDimitry Andric //       shifts.
310b57cec5SDimitry Andric //   ... etc.
320b57cec5SDimitry Andric //
330b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
340b57cec5SDimitry Andric 
350b57cec5SDimitry Andric #include "InstCombineInternal.h"
360b57cec5SDimitry Andric #include "llvm/ADT/APInt.h"
370b57cec5SDimitry Andric #include "llvm/ADT/ArrayRef.h"
380b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h"
390b57cec5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
400b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
410b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h"
420b57cec5SDimitry Andric #include "llvm/Analysis/AliasAnalysis.h"
430b57cec5SDimitry Andric #include "llvm/Analysis/AssumptionCache.h"
440b57cec5SDimitry Andric #include "llvm/Analysis/BasicAliasAnalysis.h"
450b57cec5SDimitry Andric #include "llvm/Analysis/BlockFrequencyInfo.h"
460b57cec5SDimitry Andric #include "llvm/Analysis/CFG.h"
470b57cec5SDimitry Andric #include "llvm/Analysis/ConstantFolding.h"
480b57cec5SDimitry Andric #include "llvm/Analysis/GlobalsModRef.h"
490b57cec5SDimitry Andric #include "llvm/Analysis/InstructionSimplify.h"
500b57cec5SDimitry Andric #include "llvm/Analysis/LazyBlockFrequencyInfo.h"
510b57cec5SDimitry Andric #include "llvm/Analysis/LoopInfo.h"
520b57cec5SDimitry Andric #include "llvm/Analysis/MemoryBuiltins.h"
530b57cec5SDimitry Andric #include "llvm/Analysis/OptimizationRemarkEmitter.h"
540b57cec5SDimitry Andric #include "llvm/Analysis/ProfileSummaryInfo.h"
550b57cec5SDimitry Andric #include "llvm/Analysis/TargetFolder.h"
560b57cec5SDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h"
57e8d8bef9SDimitry Andric #include "llvm/Analysis/TargetTransformInfo.h"
5881ad6265SDimitry Andric #include "llvm/Analysis/Utils/Local.h"
590b57cec5SDimitry Andric #include "llvm/Analysis/ValueTracking.h"
605ffd83dbSDimitry Andric #include "llvm/Analysis/VectorUtils.h"
610b57cec5SDimitry Andric #include "llvm/IR/BasicBlock.h"
620b57cec5SDimitry Andric #include "llvm/IR/CFG.h"
630b57cec5SDimitry Andric #include "llvm/IR/Constant.h"
640b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
650b57cec5SDimitry Andric #include "llvm/IR/DIBuilder.h"
660b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
671fd87a68SDimitry Andric #include "llvm/IR/DebugInfo.h"
680b57cec5SDimitry Andric #include "llvm/IR/DerivedTypes.h"
690b57cec5SDimitry Andric #include "llvm/IR/Dominators.h"
7006c3fb27SDimitry Andric #include "llvm/IR/EHPersonalities.h"
710b57cec5SDimitry Andric #include "llvm/IR/Function.h"
720b57cec5SDimitry Andric #include "llvm/IR/GetElementPtrTypeIterator.h"
730b57cec5SDimitry Andric #include "llvm/IR/IRBuilder.h"
740b57cec5SDimitry Andric #include "llvm/IR/InstrTypes.h"
750b57cec5SDimitry Andric #include "llvm/IR/Instruction.h"
760b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
770b57cec5SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
780b57cec5SDimitry Andric #include "llvm/IR/Intrinsics.h"
790b57cec5SDimitry Andric #include "llvm/IR/Metadata.h"
800b57cec5SDimitry Andric #include "llvm/IR/Operator.h"
810b57cec5SDimitry Andric #include "llvm/IR/PassManager.h"
820b57cec5SDimitry Andric #include "llvm/IR/PatternMatch.h"
830b57cec5SDimitry Andric #include "llvm/IR/Type.h"
840b57cec5SDimitry Andric #include "llvm/IR/Use.h"
850b57cec5SDimitry Andric #include "llvm/IR/User.h"
860b57cec5SDimitry Andric #include "llvm/IR/Value.h"
870b57cec5SDimitry Andric #include "llvm/IR/ValueHandle.h"
88480093f4SDimitry Andric #include "llvm/InitializePasses.h"
890b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
900b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
910b57cec5SDimitry Andric #include "llvm/Support/Compiler.h"
920b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
930b57cec5SDimitry Andric #include "llvm/Support/DebugCounter.h"
940b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
950b57cec5SDimitry Andric #include "llvm/Support/KnownBits.h"
960b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
970b57cec5SDimitry Andric #include "llvm/Transforms/InstCombine/InstCombine.h"
98bdd1243dSDimitry Andric #include "llvm/Transforms/Utils/BasicBlockUtils.h"
990b57cec5SDimitry Andric #include "llvm/Transforms/Utils/Local.h"
1000b57cec5SDimitry Andric #include <algorithm>
1010b57cec5SDimitry Andric #include <cassert>
1020b57cec5SDimitry Andric #include <cstdint>
1030b57cec5SDimitry Andric #include <memory>
104bdd1243dSDimitry Andric #include <optional>
1050b57cec5SDimitry Andric #include <string>
1060b57cec5SDimitry Andric #include <utility>
1070b57cec5SDimitry Andric 
108349cc55cSDimitry Andric #define DEBUG_TYPE "instcombine"
109349cc55cSDimitry Andric #include "llvm/Transforms/Utils/InstructionWorklist.h"
110bdd1243dSDimitry Andric #include <optional>
111349cc55cSDimitry Andric 
1120b57cec5SDimitry Andric using namespace llvm;
1130b57cec5SDimitry Andric using namespace llvm::PatternMatch;
1140b57cec5SDimitry Andric 
115e8d8bef9SDimitry Andric STATISTIC(NumWorklistIterations,
116e8d8bef9SDimitry Andric           "Number of instruction combining iterations performed");
11706c3fb27SDimitry Andric STATISTIC(NumOneIteration, "Number of functions with one iteration");
11806c3fb27SDimitry Andric STATISTIC(NumTwoIterations, "Number of functions with two iterations");
11906c3fb27SDimitry Andric STATISTIC(NumThreeIterations, "Number of functions with three iterations");
12006c3fb27SDimitry Andric STATISTIC(NumFourOrMoreIterations,
12106c3fb27SDimitry Andric           "Number of functions with four or more iterations");
122e8d8bef9SDimitry Andric 
1230b57cec5SDimitry Andric STATISTIC(NumCombined , "Number of insts combined");
1240b57cec5SDimitry Andric STATISTIC(NumConstProp, "Number of constant folds");
1250b57cec5SDimitry Andric STATISTIC(NumDeadInst , "Number of dead inst eliminated");
1260b57cec5SDimitry Andric STATISTIC(NumSunkInst , "Number of instructions sunk");
1270b57cec5SDimitry Andric STATISTIC(NumExpand,    "Number of expansions");
1280b57cec5SDimitry Andric STATISTIC(NumFactor   , "Number of factorizations");
1290b57cec5SDimitry Andric STATISTIC(NumReassoc  , "Number of reassociations");
1300b57cec5SDimitry Andric DEBUG_COUNTER(VisitCounter, "instcombine-visit",
1310b57cec5SDimitry Andric               "Controls which instructions are visited");
1320b57cec5SDimitry Andric 
1330b57cec5SDimitry Andric static cl::opt<bool>
1340b57cec5SDimitry Andric EnableCodeSinking("instcombine-code-sinking", cl::desc("Enable code sinking"),
1350b57cec5SDimitry Andric                                               cl::init(true));
1360b57cec5SDimitry Andric 
13781ad6265SDimitry Andric static cl::opt<unsigned> MaxSinkNumUsers(
13881ad6265SDimitry Andric     "instcombine-max-sink-users", cl::init(32),
13981ad6265SDimitry Andric     cl::desc("Maximum number of undroppable users for instruction sinking"));
14081ad6265SDimitry Andric 
1410b57cec5SDimitry Andric static cl::opt<unsigned>
1420b57cec5SDimitry Andric MaxArraySize("instcombine-maxarray-size", cl::init(1024),
1430b57cec5SDimitry Andric              cl::desc("Maximum array size considered when doing a combine"));
1440b57cec5SDimitry Andric 
1450b57cec5SDimitry Andric // FIXME: Remove this flag when it is no longer necessary to convert
1460b57cec5SDimitry Andric // llvm.dbg.declare to avoid inaccurate debug info. Setting this to false
1470b57cec5SDimitry Andric // increases variable availability at the cost of accuracy. Variables that
1480b57cec5SDimitry Andric // cannot be promoted by mem2reg or SROA will be described as living in memory
1490b57cec5SDimitry Andric // for their entire lifetime. However, passes like DSE and instcombine can
1500b57cec5SDimitry Andric // delete stores to the alloca, leading to misleading and inaccurate debug
1510b57cec5SDimitry Andric // information. This flag can be removed when those passes are fixed.
1520b57cec5SDimitry Andric static cl::opt<unsigned> ShouldLowerDbgDeclare("instcombine-lower-dbg-declare",
1530b57cec5SDimitry Andric                                                cl::Hidden, cl::init(true));
1540b57cec5SDimitry Andric 
155bdd1243dSDimitry Andric std::optional<Instruction *>
156e8d8bef9SDimitry Andric InstCombiner::targetInstCombineIntrinsic(IntrinsicInst &II) {
157e8d8bef9SDimitry Andric   // Handle target specific intrinsics
158e8d8bef9SDimitry Andric   if (II.getCalledFunction()->isTargetIntrinsic()) {
159e8d8bef9SDimitry Andric     return TTI.instCombineIntrinsic(*this, II);
160e8d8bef9SDimitry Andric   }
161bdd1243dSDimitry Andric   return std::nullopt;
162e8d8bef9SDimitry Andric }
163e8d8bef9SDimitry Andric 
164bdd1243dSDimitry Andric std::optional<Value *> InstCombiner::targetSimplifyDemandedUseBitsIntrinsic(
165e8d8bef9SDimitry Andric     IntrinsicInst &II, APInt DemandedMask, KnownBits &Known,
166e8d8bef9SDimitry Andric     bool &KnownBitsComputed) {
167e8d8bef9SDimitry Andric   // Handle target specific intrinsics
168e8d8bef9SDimitry Andric   if (II.getCalledFunction()->isTargetIntrinsic()) {
169e8d8bef9SDimitry Andric     return TTI.simplifyDemandedUseBitsIntrinsic(*this, II, DemandedMask, Known,
170e8d8bef9SDimitry Andric                                                 KnownBitsComputed);
171e8d8bef9SDimitry Andric   }
172bdd1243dSDimitry Andric   return std::nullopt;
173e8d8bef9SDimitry Andric }
174e8d8bef9SDimitry Andric 
175bdd1243dSDimitry Andric std::optional<Value *> InstCombiner::targetSimplifyDemandedVectorEltsIntrinsic(
176cb14a3feSDimitry Andric     IntrinsicInst &II, APInt DemandedElts, APInt &PoisonElts,
177cb14a3feSDimitry Andric     APInt &PoisonElts2, APInt &PoisonElts3,
178e8d8bef9SDimitry Andric     std::function<void(Instruction *, unsigned, APInt, APInt &)>
179e8d8bef9SDimitry Andric         SimplifyAndSetOp) {
180e8d8bef9SDimitry Andric   // Handle target specific intrinsics
181e8d8bef9SDimitry Andric   if (II.getCalledFunction()->isTargetIntrinsic()) {
182e8d8bef9SDimitry Andric     return TTI.simplifyDemandedVectorEltsIntrinsic(
183cb14a3feSDimitry Andric         *this, II, DemandedElts, PoisonElts, PoisonElts2, PoisonElts3,
184e8d8bef9SDimitry Andric         SimplifyAndSetOp);
185e8d8bef9SDimitry Andric   }
186bdd1243dSDimitry Andric   return std::nullopt;
187e8d8bef9SDimitry Andric }
188e8d8bef9SDimitry Andric 
18906c3fb27SDimitry Andric bool InstCombiner::isValidAddrSpaceCast(unsigned FromAS, unsigned ToAS) const {
19006c3fb27SDimitry Andric   return TTI.isValidAddrSpaceCast(FromAS, ToAS);
19106c3fb27SDimitry Andric }
19206c3fb27SDimitry Andric 
193*0fca6ea1SDimitry Andric Value *InstCombinerImpl::EmitGEPOffset(GEPOperator *GEP, bool RewriteGEP) {
194*0fca6ea1SDimitry Andric   if (!RewriteGEP)
195bdd1243dSDimitry Andric     return llvm::emitGEPOffset(&Builder, DL, GEP);
196*0fca6ea1SDimitry Andric 
197*0fca6ea1SDimitry Andric   IRBuilderBase::InsertPointGuard Guard(Builder);
198*0fca6ea1SDimitry Andric   auto *Inst = dyn_cast<Instruction>(GEP);
199*0fca6ea1SDimitry Andric   if (Inst)
200*0fca6ea1SDimitry Andric     Builder.SetInsertPoint(Inst);
201*0fca6ea1SDimitry Andric 
202*0fca6ea1SDimitry Andric   Value *Offset = EmitGEPOffset(GEP);
203*0fca6ea1SDimitry Andric   // If a non-trivial GEP has other uses, rewrite it to avoid duplicating
204*0fca6ea1SDimitry Andric   // the offset arithmetic.
205*0fca6ea1SDimitry Andric   if (Inst && !GEP->hasOneUse() && !GEP->hasAllConstantIndices() &&
206*0fca6ea1SDimitry Andric       !GEP->getSourceElementType()->isIntegerTy(8)) {
207*0fca6ea1SDimitry Andric     replaceInstUsesWith(
208*0fca6ea1SDimitry Andric         *Inst, Builder.CreateGEP(Builder.getInt8Ty(), GEP->getPointerOperand(),
209*0fca6ea1SDimitry Andric                                  Offset, "", GEP->getNoWrapFlags()));
210*0fca6ea1SDimitry Andric     eraseInstFromFunction(*Inst);
211*0fca6ea1SDimitry Andric   }
212*0fca6ea1SDimitry Andric   return Offset;
2130b57cec5SDimitry Andric }
2140b57cec5SDimitry Andric 
215349cc55cSDimitry Andric /// Legal integers and common types are considered desirable. This is used to
216349cc55cSDimitry Andric /// avoid creating instructions with types that may not be supported well by the
217349cc55cSDimitry Andric /// the backend.
218349cc55cSDimitry Andric /// NOTE: This treats i8, i16 and i32 specially because they are common
219349cc55cSDimitry Andric ///       types in frontend languages.
220349cc55cSDimitry Andric bool InstCombinerImpl::isDesirableIntType(unsigned BitWidth) const {
221349cc55cSDimitry Andric   switch (BitWidth) {
222349cc55cSDimitry Andric   case 8:
223349cc55cSDimitry Andric   case 16:
224349cc55cSDimitry Andric   case 32:
225349cc55cSDimitry Andric     return true;
226349cc55cSDimitry Andric   default:
227349cc55cSDimitry Andric     return DL.isLegalInteger(BitWidth);
228349cc55cSDimitry Andric   }
229349cc55cSDimitry Andric }
230349cc55cSDimitry Andric 
2310b57cec5SDimitry Andric /// Return true if it is desirable to convert an integer computation from a
2320b57cec5SDimitry Andric /// given bit width to a new bit width.
233bdd1243dSDimitry Andric /// We don't want to convert from a legal or desirable type (like i8) to an
234bdd1243dSDimitry Andric /// illegal type or from a smaller to a larger illegal type. A width of '1'
235bdd1243dSDimitry Andric /// is always treated as a desirable type because i1 is a fundamental type in
236bdd1243dSDimitry Andric /// IR, and there are many specialized optimizations for i1 types.
237bdd1243dSDimitry Andric /// Common/desirable widths are equally treated as legal to convert to, in
238bdd1243dSDimitry Andric /// order to open up more combining opportunities.
239e8d8bef9SDimitry Andric bool InstCombinerImpl::shouldChangeType(unsigned FromWidth,
2400b57cec5SDimitry Andric                                         unsigned ToWidth) const {
2410b57cec5SDimitry Andric   bool FromLegal = FromWidth == 1 || DL.isLegalInteger(FromWidth);
2420b57cec5SDimitry Andric   bool ToLegal = ToWidth == 1 || DL.isLegalInteger(ToWidth);
2430b57cec5SDimitry Andric 
244349cc55cSDimitry Andric   // Convert to desirable widths even if they are not legal types.
245349cc55cSDimitry Andric   // Only shrink types, to prevent infinite loops.
246349cc55cSDimitry Andric   if (ToWidth < FromWidth && isDesirableIntType(ToWidth))
2470b57cec5SDimitry Andric     return true;
2480b57cec5SDimitry Andric 
249bdd1243dSDimitry Andric   // If this is a legal or desiable integer from type, and the result would be
250bdd1243dSDimitry Andric   // an illegal type, don't do the transformation.
251bdd1243dSDimitry Andric   if ((FromLegal || isDesirableIntType(FromWidth)) && !ToLegal)
2520b57cec5SDimitry Andric     return false;
2530b57cec5SDimitry Andric 
2540b57cec5SDimitry Andric   // Otherwise, if both are illegal, do not increase the size of the result. We
2550b57cec5SDimitry Andric   // do allow things like i160 -> i64, but not i64 -> i160.
2560b57cec5SDimitry Andric   if (!FromLegal && !ToLegal && ToWidth > FromWidth)
2570b57cec5SDimitry Andric     return false;
2580b57cec5SDimitry Andric 
2590b57cec5SDimitry Andric   return true;
2600b57cec5SDimitry Andric }
2610b57cec5SDimitry Andric 
2620b57cec5SDimitry Andric /// Return true if it is desirable to convert a computation from 'From' to 'To'.
2630b57cec5SDimitry Andric /// We don't want to convert from a legal to an illegal type or from a smaller
2640b57cec5SDimitry Andric /// to a larger illegal type. i1 is always treated as a legal type because it is
2650b57cec5SDimitry Andric /// a fundamental type in IR, and there are many specialized optimizations for
2660b57cec5SDimitry Andric /// i1 types.
267e8d8bef9SDimitry Andric bool InstCombinerImpl::shouldChangeType(Type *From, Type *To) const {
2680b57cec5SDimitry Andric   // TODO: This could be extended to allow vectors. Datalayout changes might be
2690b57cec5SDimitry Andric   // needed to properly support that.
2700b57cec5SDimitry Andric   if (!From->isIntegerTy() || !To->isIntegerTy())
2710b57cec5SDimitry Andric     return false;
2720b57cec5SDimitry Andric 
2730b57cec5SDimitry Andric   unsigned FromWidth = From->getPrimitiveSizeInBits();
2740b57cec5SDimitry Andric   unsigned ToWidth = To->getPrimitiveSizeInBits();
2750b57cec5SDimitry Andric   return shouldChangeType(FromWidth, ToWidth);
2760b57cec5SDimitry Andric }
2770b57cec5SDimitry Andric 
2780b57cec5SDimitry Andric // Return true, if No Signed Wrap should be maintained for I.
2790b57cec5SDimitry Andric // The No Signed Wrap flag can be kept if the operation "B (I.getOpcode) C",
2800b57cec5SDimitry Andric // where both B and C should be ConstantInts, results in a constant that does
2810b57cec5SDimitry Andric // not overflow. This function only handles the Add and Sub opcodes. For
2820b57cec5SDimitry Andric // all other opcodes, the function conservatively returns false.
2838bcb0991SDimitry Andric static bool maintainNoSignedWrap(BinaryOperator &I, Value *B, Value *C) {
2848bcb0991SDimitry Andric   auto *OBO = dyn_cast<OverflowingBinaryOperator>(&I);
2850b57cec5SDimitry Andric   if (!OBO || !OBO->hasNoSignedWrap())
2860b57cec5SDimitry Andric     return false;
2870b57cec5SDimitry Andric 
2880b57cec5SDimitry Andric   // We reason about Add and Sub Only.
2890b57cec5SDimitry Andric   Instruction::BinaryOps Opcode = I.getOpcode();
2900b57cec5SDimitry Andric   if (Opcode != Instruction::Add && Opcode != Instruction::Sub)
2910b57cec5SDimitry Andric     return false;
2920b57cec5SDimitry Andric 
2930b57cec5SDimitry Andric   const APInt *BVal, *CVal;
2940b57cec5SDimitry Andric   if (!match(B, m_APInt(BVal)) || !match(C, m_APInt(CVal)))
2950b57cec5SDimitry Andric     return false;
2960b57cec5SDimitry Andric 
2970b57cec5SDimitry Andric   bool Overflow = false;
2980b57cec5SDimitry Andric   if (Opcode == Instruction::Add)
2990b57cec5SDimitry Andric     (void)BVal->sadd_ov(*CVal, Overflow);
3000b57cec5SDimitry Andric   else
3010b57cec5SDimitry Andric     (void)BVal->ssub_ov(*CVal, Overflow);
3020b57cec5SDimitry Andric 
3030b57cec5SDimitry Andric   return !Overflow;
3040b57cec5SDimitry Andric }
3050b57cec5SDimitry Andric 
3060b57cec5SDimitry Andric static bool hasNoUnsignedWrap(BinaryOperator &I) {
3078bcb0991SDimitry Andric   auto *OBO = dyn_cast<OverflowingBinaryOperator>(&I);
3080b57cec5SDimitry Andric   return OBO && OBO->hasNoUnsignedWrap();
3090b57cec5SDimitry Andric }
3100b57cec5SDimitry Andric 
3118bcb0991SDimitry Andric static bool hasNoSignedWrap(BinaryOperator &I) {
3128bcb0991SDimitry Andric   auto *OBO = dyn_cast<OverflowingBinaryOperator>(&I);
3138bcb0991SDimitry Andric   return OBO && OBO->hasNoSignedWrap();
3148bcb0991SDimitry Andric }
3158bcb0991SDimitry Andric 
3160b57cec5SDimitry Andric /// Conservatively clears subclassOptionalData after a reassociation or
3170b57cec5SDimitry Andric /// commutation. We preserve fast-math flags when applicable as they can be
3180b57cec5SDimitry Andric /// preserved.
3190b57cec5SDimitry Andric static void ClearSubclassDataAfterReassociation(BinaryOperator &I) {
3200b57cec5SDimitry Andric   FPMathOperator *FPMO = dyn_cast<FPMathOperator>(&I);
3210b57cec5SDimitry Andric   if (!FPMO) {
3220b57cec5SDimitry Andric     I.clearSubclassOptionalData();
3230b57cec5SDimitry Andric     return;
3240b57cec5SDimitry Andric   }
3250b57cec5SDimitry Andric 
3260b57cec5SDimitry Andric   FastMathFlags FMF = I.getFastMathFlags();
3270b57cec5SDimitry Andric   I.clearSubclassOptionalData();
3280b57cec5SDimitry Andric   I.setFastMathFlags(FMF);
3290b57cec5SDimitry Andric }
3300b57cec5SDimitry Andric 
3310b57cec5SDimitry Andric /// Combine constant operands of associative operations either before or after a
3320b57cec5SDimitry Andric /// cast to eliminate one of the associative operations:
3330b57cec5SDimitry Andric /// (op (cast (op X, C2)), C1) --> (cast (op X, op (C1, C2)))
3340b57cec5SDimitry Andric /// (op (cast (op X, C2)), C1) --> (op (cast X), op (C1, C2))
335e8d8bef9SDimitry Andric static bool simplifyAssocCastAssoc(BinaryOperator *BinOp1,
336e8d8bef9SDimitry Andric                                    InstCombinerImpl &IC) {
3370b57cec5SDimitry Andric   auto *Cast = dyn_cast<CastInst>(BinOp1->getOperand(0));
3380b57cec5SDimitry Andric   if (!Cast || !Cast->hasOneUse())
3390b57cec5SDimitry Andric     return false;
3400b57cec5SDimitry Andric 
3410b57cec5SDimitry Andric   // TODO: Enhance logic for other casts and remove this check.
3420b57cec5SDimitry Andric   auto CastOpcode = Cast->getOpcode();
3430b57cec5SDimitry Andric   if (CastOpcode != Instruction::ZExt)
3440b57cec5SDimitry Andric     return false;
3450b57cec5SDimitry Andric 
3460b57cec5SDimitry Andric   // TODO: Enhance logic for other BinOps and remove this check.
3470b57cec5SDimitry Andric   if (!BinOp1->isBitwiseLogicOp())
3480b57cec5SDimitry Andric     return false;
3490b57cec5SDimitry Andric 
3500b57cec5SDimitry Andric   auto AssocOpcode = BinOp1->getOpcode();
3510b57cec5SDimitry Andric   auto *BinOp2 = dyn_cast<BinaryOperator>(Cast->getOperand(0));
3520b57cec5SDimitry Andric   if (!BinOp2 || !BinOp2->hasOneUse() || BinOp2->getOpcode() != AssocOpcode)
3530b57cec5SDimitry Andric     return false;
3540b57cec5SDimitry Andric 
3550b57cec5SDimitry Andric   Constant *C1, *C2;
3560b57cec5SDimitry Andric   if (!match(BinOp1->getOperand(1), m_Constant(C1)) ||
3570b57cec5SDimitry Andric       !match(BinOp2->getOperand(1), m_Constant(C2)))
3580b57cec5SDimitry Andric     return false;
3590b57cec5SDimitry Andric 
3600b57cec5SDimitry Andric   // TODO: This assumes a zext cast.
3610b57cec5SDimitry Andric   // Eg, if it was a trunc, we'd cast C1 to the source type because casting C2
3620b57cec5SDimitry Andric   // to the destination type might lose bits.
3630b57cec5SDimitry Andric 
3640b57cec5SDimitry Andric   // Fold the constants together in the destination type:
3650b57cec5SDimitry Andric   // (op (cast (op X, C2)), C1) --> (op (cast X), FoldedC)
3665f757f3fSDimitry Andric   const DataLayout &DL = IC.getDataLayout();
3670b57cec5SDimitry Andric   Type *DestTy = C1->getType();
3685f757f3fSDimitry Andric   Constant *CastC2 = ConstantFoldCastOperand(CastOpcode, C2, DestTy, DL);
3695f757f3fSDimitry Andric   if (!CastC2)
3705f757f3fSDimitry Andric     return false;
3715f757f3fSDimitry Andric   Constant *FoldedC = ConstantFoldBinaryOpOperands(AssocOpcode, C1, CastC2, DL);
37206c3fb27SDimitry Andric   if (!FoldedC)
37306c3fb27SDimitry Andric     return false;
37406c3fb27SDimitry Andric 
3755ffd83dbSDimitry Andric   IC.replaceOperand(*Cast, 0, BinOp2->getOperand(0));
3765ffd83dbSDimitry Andric   IC.replaceOperand(*BinOp1, 1, FoldedC);
3775f757f3fSDimitry Andric   BinOp1->dropPoisonGeneratingFlags();
3785f757f3fSDimitry Andric   Cast->dropPoisonGeneratingFlags();
3790b57cec5SDimitry Andric   return true;
3800b57cec5SDimitry Andric }
3810b57cec5SDimitry Andric 
38206c3fb27SDimitry Andric // Simplifies IntToPtr/PtrToInt RoundTrip Cast.
383fe6060f1SDimitry Andric // inttoptr ( ptrtoint (x) ) --> x
384fe6060f1SDimitry Andric Value *InstCombinerImpl::simplifyIntToPtrRoundTripCast(Value *Val) {
385fe6060f1SDimitry Andric   auto *IntToPtr = dyn_cast<IntToPtrInst>(Val);
386bdd1243dSDimitry Andric   if (IntToPtr && DL.getTypeSizeInBits(IntToPtr->getDestTy()) ==
387fe6060f1SDimitry Andric                       DL.getTypeSizeInBits(IntToPtr->getSrcTy())) {
388fe6060f1SDimitry Andric     auto *PtrToInt = dyn_cast<PtrToIntInst>(IntToPtr->getOperand(0));
389fe6060f1SDimitry Andric     Type *CastTy = IntToPtr->getDestTy();
390fe6060f1SDimitry Andric     if (PtrToInt &&
391fe6060f1SDimitry Andric         CastTy->getPointerAddressSpace() ==
392fe6060f1SDimitry Andric             PtrToInt->getSrcTy()->getPointerAddressSpace() &&
393bdd1243dSDimitry Andric         DL.getTypeSizeInBits(PtrToInt->getSrcTy()) ==
39406c3fb27SDimitry Andric             DL.getTypeSizeInBits(PtrToInt->getDestTy()))
39506c3fb27SDimitry Andric       return PtrToInt->getOperand(0);
396fe6060f1SDimitry Andric   }
397fe6060f1SDimitry Andric   return nullptr;
398fe6060f1SDimitry Andric }
399fe6060f1SDimitry Andric 
4000b57cec5SDimitry Andric /// This performs a few simplifications for operators that are associative or
4010b57cec5SDimitry Andric /// commutative:
4020b57cec5SDimitry Andric ///
4030b57cec5SDimitry Andric ///  Commutative operators:
4040b57cec5SDimitry Andric ///
4050b57cec5SDimitry Andric ///  1. Order operands such that they are listed from right (least complex) to
4060b57cec5SDimitry Andric ///     left (most complex).  This puts constants before unary operators before
4070b57cec5SDimitry Andric ///     binary operators.
4080b57cec5SDimitry Andric ///
4090b57cec5SDimitry Andric ///  Associative operators:
4100b57cec5SDimitry Andric ///
4110b57cec5SDimitry Andric ///  2. Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
4120b57cec5SDimitry Andric ///  3. Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
4130b57cec5SDimitry Andric ///
4140b57cec5SDimitry Andric ///  Associative and commutative operators:
4150b57cec5SDimitry Andric ///
4160b57cec5SDimitry Andric ///  4. Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
4170b57cec5SDimitry Andric ///  5. Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
4180b57cec5SDimitry Andric ///  6. Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
4190b57cec5SDimitry Andric ///     if C1 and C2 are constants.
420e8d8bef9SDimitry Andric bool InstCombinerImpl::SimplifyAssociativeOrCommutative(BinaryOperator &I) {
4210b57cec5SDimitry Andric   Instruction::BinaryOps Opcode = I.getOpcode();
4220b57cec5SDimitry Andric   bool Changed = false;
4230b57cec5SDimitry Andric 
4240b57cec5SDimitry Andric   do {
4250b57cec5SDimitry Andric     // Order operands such that they are listed from right (least complex) to
4260b57cec5SDimitry Andric     // left (most complex).  This puts constants before unary operators before
4270b57cec5SDimitry Andric     // binary operators.
4280b57cec5SDimitry Andric     if (I.isCommutative() && getComplexity(I.getOperand(0)) <
4290b57cec5SDimitry Andric         getComplexity(I.getOperand(1)))
4300b57cec5SDimitry Andric       Changed = !I.swapOperands();
4310b57cec5SDimitry Andric 
4321db9f3b2SDimitry Andric     if (I.isCommutative()) {
4331db9f3b2SDimitry Andric       if (auto Pair = matchSymmetricPair(I.getOperand(0), I.getOperand(1))) {
4341db9f3b2SDimitry Andric         replaceOperand(I, 0, Pair->first);
4351db9f3b2SDimitry Andric         replaceOperand(I, 1, Pair->second);
4361db9f3b2SDimitry Andric         Changed = true;
4371db9f3b2SDimitry Andric       }
4381db9f3b2SDimitry Andric     }
4391db9f3b2SDimitry Andric 
4400b57cec5SDimitry Andric     BinaryOperator *Op0 = dyn_cast<BinaryOperator>(I.getOperand(0));
4410b57cec5SDimitry Andric     BinaryOperator *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1));
4420b57cec5SDimitry Andric 
4430b57cec5SDimitry Andric     if (I.isAssociative()) {
4440b57cec5SDimitry Andric       // Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
4450b57cec5SDimitry Andric       if (Op0 && Op0->getOpcode() == Opcode) {
4460b57cec5SDimitry Andric         Value *A = Op0->getOperand(0);
4470b57cec5SDimitry Andric         Value *B = Op0->getOperand(1);
4480b57cec5SDimitry Andric         Value *C = I.getOperand(1);
4490b57cec5SDimitry Andric 
4500b57cec5SDimitry Andric         // Does "B op C" simplify?
45181ad6265SDimitry Andric         if (Value *V = simplifyBinOp(Opcode, B, C, SQ.getWithInstruction(&I))) {
4520b57cec5SDimitry Andric           // It simplifies to V.  Form "A op V".
4535ffd83dbSDimitry Andric           replaceOperand(I, 0, A);
4545ffd83dbSDimitry Andric           replaceOperand(I, 1, V);
4550b57cec5SDimitry Andric           bool IsNUW = hasNoUnsignedWrap(I) && hasNoUnsignedWrap(*Op0);
4568bcb0991SDimitry Andric           bool IsNSW = maintainNoSignedWrap(I, B, C) && hasNoSignedWrap(*Op0);
4570b57cec5SDimitry Andric 
4588bcb0991SDimitry Andric           // Conservatively clear all optional flags since they may not be
4598bcb0991SDimitry Andric           // preserved by the reassociation. Reset nsw/nuw based on the above
4608bcb0991SDimitry Andric           // analysis.
4610b57cec5SDimitry Andric           ClearSubclassDataAfterReassociation(I);
4620b57cec5SDimitry Andric 
4638bcb0991SDimitry Andric           // Note: this is only valid because SimplifyBinOp doesn't look at
4648bcb0991SDimitry Andric           // the operands to Op0.
4650b57cec5SDimitry Andric           if (IsNUW)
4660b57cec5SDimitry Andric             I.setHasNoUnsignedWrap(true);
4670b57cec5SDimitry Andric 
4688bcb0991SDimitry Andric           if (IsNSW)
4690b57cec5SDimitry Andric             I.setHasNoSignedWrap(true);
4700b57cec5SDimitry Andric 
4710b57cec5SDimitry Andric           Changed = true;
4720b57cec5SDimitry Andric           ++NumReassoc;
4730b57cec5SDimitry Andric           continue;
4740b57cec5SDimitry Andric         }
4750b57cec5SDimitry Andric       }
4760b57cec5SDimitry Andric 
4770b57cec5SDimitry Andric       // Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
4780b57cec5SDimitry Andric       if (Op1 && Op1->getOpcode() == Opcode) {
4790b57cec5SDimitry Andric         Value *A = I.getOperand(0);
4800b57cec5SDimitry Andric         Value *B = Op1->getOperand(0);
4810b57cec5SDimitry Andric         Value *C = Op1->getOperand(1);
4820b57cec5SDimitry Andric 
4830b57cec5SDimitry Andric         // Does "A op B" simplify?
48481ad6265SDimitry Andric         if (Value *V = simplifyBinOp(Opcode, A, B, SQ.getWithInstruction(&I))) {
4850b57cec5SDimitry Andric           // It simplifies to V.  Form "V op C".
4865ffd83dbSDimitry Andric           replaceOperand(I, 0, V);
4875ffd83dbSDimitry Andric           replaceOperand(I, 1, C);
4880b57cec5SDimitry Andric           // Conservatively clear the optional flags, since they may not be
4890b57cec5SDimitry Andric           // preserved by the reassociation.
4900b57cec5SDimitry Andric           ClearSubclassDataAfterReassociation(I);
4910b57cec5SDimitry Andric           Changed = true;
4920b57cec5SDimitry Andric           ++NumReassoc;
4930b57cec5SDimitry Andric           continue;
4940b57cec5SDimitry Andric         }
4950b57cec5SDimitry Andric       }
4960b57cec5SDimitry Andric     }
4970b57cec5SDimitry Andric 
4980b57cec5SDimitry Andric     if (I.isAssociative() && I.isCommutative()) {
4995ffd83dbSDimitry Andric       if (simplifyAssocCastAssoc(&I, *this)) {
5000b57cec5SDimitry Andric         Changed = true;
5010b57cec5SDimitry Andric         ++NumReassoc;
5020b57cec5SDimitry Andric         continue;
5030b57cec5SDimitry Andric       }
5040b57cec5SDimitry Andric 
5050b57cec5SDimitry Andric       // Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
5060b57cec5SDimitry Andric       if (Op0 && Op0->getOpcode() == Opcode) {
5070b57cec5SDimitry Andric         Value *A = Op0->getOperand(0);
5080b57cec5SDimitry Andric         Value *B = Op0->getOperand(1);
5090b57cec5SDimitry Andric         Value *C = I.getOperand(1);
5100b57cec5SDimitry Andric 
5110b57cec5SDimitry Andric         // Does "C op A" simplify?
51281ad6265SDimitry Andric         if (Value *V = simplifyBinOp(Opcode, C, A, SQ.getWithInstruction(&I))) {
5130b57cec5SDimitry Andric           // It simplifies to V.  Form "V op B".
5145ffd83dbSDimitry Andric           replaceOperand(I, 0, V);
5155ffd83dbSDimitry Andric           replaceOperand(I, 1, B);
5160b57cec5SDimitry Andric           // Conservatively clear the optional flags, since they may not be
5170b57cec5SDimitry Andric           // preserved by the reassociation.
5180b57cec5SDimitry Andric           ClearSubclassDataAfterReassociation(I);
5190b57cec5SDimitry Andric           Changed = true;
5200b57cec5SDimitry Andric           ++NumReassoc;
5210b57cec5SDimitry Andric           continue;
5220b57cec5SDimitry Andric         }
5230b57cec5SDimitry Andric       }
5240b57cec5SDimitry Andric 
5250b57cec5SDimitry Andric       // Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
5260b57cec5SDimitry Andric       if (Op1 && Op1->getOpcode() == Opcode) {
5270b57cec5SDimitry Andric         Value *A = I.getOperand(0);
5280b57cec5SDimitry Andric         Value *B = Op1->getOperand(0);
5290b57cec5SDimitry Andric         Value *C = Op1->getOperand(1);
5300b57cec5SDimitry Andric 
5310b57cec5SDimitry Andric         // Does "C op A" simplify?
53281ad6265SDimitry Andric         if (Value *V = simplifyBinOp(Opcode, C, A, SQ.getWithInstruction(&I))) {
5330b57cec5SDimitry Andric           // It simplifies to V.  Form "B op V".
5345ffd83dbSDimitry Andric           replaceOperand(I, 0, B);
5355ffd83dbSDimitry Andric           replaceOperand(I, 1, V);
5360b57cec5SDimitry Andric           // Conservatively clear the optional flags, since they may not be
5370b57cec5SDimitry Andric           // preserved by the reassociation.
5380b57cec5SDimitry Andric           ClearSubclassDataAfterReassociation(I);
5390b57cec5SDimitry Andric           Changed = true;
5400b57cec5SDimitry Andric           ++NumReassoc;
5410b57cec5SDimitry Andric           continue;
5420b57cec5SDimitry Andric         }
5430b57cec5SDimitry Andric       }
5440b57cec5SDimitry Andric 
5450b57cec5SDimitry Andric       // Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
5460b57cec5SDimitry Andric       // if C1 and C2 are constants.
5470b57cec5SDimitry Andric       Value *A, *B;
548753f127fSDimitry Andric       Constant *C1, *C2, *CRes;
5490b57cec5SDimitry Andric       if (Op0 && Op1 &&
5500b57cec5SDimitry Andric           Op0->getOpcode() == Opcode && Op1->getOpcode() == Opcode &&
5510b57cec5SDimitry Andric           match(Op0, m_OneUse(m_BinOp(m_Value(A), m_Constant(C1)))) &&
552753f127fSDimitry Andric           match(Op1, m_OneUse(m_BinOp(m_Value(B), m_Constant(C2)))) &&
553753f127fSDimitry Andric           (CRes = ConstantFoldBinaryOpOperands(Opcode, C1, C2, DL))) {
5540b57cec5SDimitry Andric         bool IsNUW = hasNoUnsignedWrap(I) &&
5550b57cec5SDimitry Andric            hasNoUnsignedWrap(*Op0) &&
5560b57cec5SDimitry Andric            hasNoUnsignedWrap(*Op1);
5570b57cec5SDimitry Andric          BinaryOperator *NewBO = (IsNUW && Opcode == Instruction::Add) ?
5580b57cec5SDimitry Andric            BinaryOperator::CreateNUW(Opcode, A, B) :
5590b57cec5SDimitry Andric            BinaryOperator::Create(Opcode, A, B);
5600b57cec5SDimitry Andric 
5610b57cec5SDimitry Andric          if (isa<FPMathOperator>(NewBO)) {
5625f757f3fSDimitry Andric            FastMathFlags Flags = I.getFastMathFlags() &
5635f757f3fSDimitry Andric                                  Op0->getFastMathFlags() &
5645f757f3fSDimitry Andric                                  Op1->getFastMathFlags();
5650b57cec5SDimitry Andric            NewBO->setFastMathFlags(Flags);
5660b57cec5SDimitry Andric         }
5675f757f3fSDimitry Andric         InsertNewInstWith(NewBO, I.getIterator());
5680b57cec5SDimitry Andric         NewBO->takeName(Op1);
5695ffd83dbSDimitry Andric         replaceOperand(I, 0, NewBO);
570753f127fSDimitry Andric         replaceOperand(I, 1, CRes);
5710b57cec5SDimitry Andric         // Conservatively clear the optional flags, since they may not be
5720b57cec5SDimitry Andric         // preserved by the reassociation.
5730b57cec5SDimitry Andric         ClearSubclassDataAfterReassociation(I);
5740b57cec5SDimitry Andric         if (IsNUW)
5750b57cec5SDimitry Andric           I.setHasNoUnsignedWrap(true);
5760b57cec5SDimitry Andric 
5770b57cec5SDimitry Andric         Changed = true;
5780b57cec5SDimitry Andric         continue;
5790b57cec5SDimitry Andric       }
5800b57cec5SDimitry Andric     }
5810b57cec5SDimitry Andric 
5820b57cec5SDimitry Andric     // No further simplifications.
5830b57cec5SDimitry Andric     return Changed;
5840b57cec5SDimitry Andric   } while (true);
5850b57cec5SDimitry Andric }
5860b57cec5SDimitry Andric 
5870b57cec5SDimitry Andric /// Return whether "X LOp (Y ROp Z)" is always equal to
5880b57cec5SDimitry Andric /// "(X LOp Y) ROp (X LOp Z)".
5890b57cec5SDimitry Andric static bool leftDistributesOverRight(Instruction::BinaryOps LOp,
5900b57cec5SDimitry Andric                                      Instruction::BinaryOps ROp) {
5910b57cec5SDimitry Andric   // X & (Y | Z) <--> (X & Y) | (X & Z)
5920b57cec5SDimitry Andric   // X & (Y ^ Z) <--> (X & Y) ^ (X & Z)
5930b57cec5SDimitry Andric   if (LOp == Instruction::And)
5940b57cec5SDimitry Andric     return ROp == Instruction::Or || ROp == Instruction::Xor;
5950b57cec5SDimitry Andric 
5960b57cec5SDimitry Andric   // X | (Y & Z) <--> (X | Y) & (X | Z)
5970b57cec5SDimitry Andric   if (LOp == Instruction::Or)
5980b57cec5SDimitry Andric     return ROp == Instruction::And;
5990b57cec5SDimitry Andric 
6000b57cec5SDimitry Andric   // X * (Y + Z) <--> (X * Y) + (X * Z)
6010b57cec5SDimitry Andric   // X * (Y - Z) <--> (X * Y) - (X * Z)
6020b57cec5SDimitry Andric   if (LOp == Instruction::Mul)
6030b57cec5SDimitry Andric     return ROp == Instruction::Add || ROp == Instruction::Sub;
6040b57cec5SDimitry Andric 
6050b57cec5SDimitry Andric   return false;
6060b57cec5SDimitry Andric }
6070b57cec5SDimitry Andric 
6080b57cec5SDimitry Andric /// Return whether "(X LOp Y) ROp Z" is always equal to
6090b57cec5SDimitry Andric /// "(X ROp Z) LOp (Y ROp Z)".
6100b57cec5SDimitry Andric static bool rightDistributesOverLeft(Instruction::BinaryOps LOp,
6110b57cec5SDimitry Andric                                      Instruction::BinaryOps ROp) {
6120b57cec5SDimitry Andric   if (Instruction::isCommutative(ROp))
6130b57cec5SDimitry Andric     return leftDistributesOverRight(ROp, LOp);
6140b57cec5SDimitry Andric 
6150b57cec5SDimitry Andric   // (X {&|^} Y) >> Z <--> (X >> Z) {&|^} (Y >> Z) for all shifts.
6160b57cec5SDimitry Andric   return Instruction::isBitwiseLogicOp(LOp) && Instruction::isShift(ROp);
6170b57cec5SDimitry Andric 
6180b57cec5SDimitry Andric   // TODO: It would be nice to handle division, aka "(X + Y)/Z = X/Z + Y/Z",
6190b57cec5SDimitry Andric   // but this requires knowing that the addition does not overflow and other
6200b57cec5SDimitry Andric   // such subtleties.
6210b57cec5SDimitry Andric }
6220b57cec5SDimitry Andric 
6230b57cec5SDimitry Andric /// This function returns identity value for given opcode, which can be used to
6240b57cec5SDimitry Andric /// factor patterns like (X * 2) + X ==> (X * 2) + (X * 1) ==> X * (2 + 1).
6250b57cec5SDimitry Andric static Value *getIdentityValue(Instruction::BinaryOps Opcode, Value *V) {
6260b57cec5SDimitry Andric   if (isa<Constant>(V))
6270b57cec5SDimitry Andric     return nullptr;
6280b57cec5SDimitry Andric 
6290b57cec5SDimitry Andric   return ConstantExpr::getBinOpIdentity(Opcode, V->getType());
6300b57cec5SDimitry Andric }
6310b57cec5SDimitry Andric 
6320b57cec5SDimitry Andric /// This function predicates factorization using distributive laws. By default,
6330b57cec5SDimitry Andric /// it just returns the 'Op' inputs. But for special-cases like
6340b57cec5SDimitry Andric /// 'add(shl(X, 5), ...)', this function will have TopOpcode == Instruction::Add
6350b57cec5SDimitry Andric /// and Op = shl(X, 5). The 'shl' is treated as the more general 'mul X, 32' to
6360b57cec5SDimitry Andric /// allow more factorization opportunities.
6370b57cec5SDimitry Andric static Instruction::BinaryOps
6380b57cec5SDimitry Andric getBinOpsForFactorization(Instruction::BinaryOps TopOpcode, BinaryOperator *Op,
6395f757f3fSDimitry Andric                           Value *&LHS, Value *&RHS, BinaryOperator *OtherOp) {
6400b57cec5SDimitry Andric   assert(Op && "Expected a binary operator");
6410b57cec5SDimitry Andric   LHS = Op->getOperand(0);
6420b57cec5SDimitry Andric   RHS = Op->getOperand(1);
6430b57cec5SDimitry Andric   if (TopOpcode == Instruction::Add || TopOpcode == Instruction::Sub) {
6440b57cec5SDimitry Andric     Constant *C;
645*0fca6ea1SDimitry Andric     if (match(Op, m_Shl(m_Value(), m_ImmConstant(C)))) {
6460b57cec5SDimitry Andric       // X << C --> X * (1 << C)
647*0fca6ea1SDimitry Andric       RHS = ConstantFoldBinaryInstruction(
648*0fca6ea1SDimitry Andric           Instruction::Shl, ConstantInt::get(Op->getType(), 1), C);
649*0fca6ea1SDimitry Andric       assert(RHS && "Constant folding of immediate constants failed");
6500b57cec5SDimitry Andric       return Instruction::Mul;
6510b57cec5SDimitry Andric     }
6520b57cec5SDimitry Andric     // TODO: We can add other conversions e.g. shr => div etc.
6530b57cec5SDimitry Andric   }
6545f757f3fSDimitry Andric   if (Instruction::isBitwiseLogicOp(TopOpcode)) {
6555f757f3fSDimitry Andric     if (OtherOp && OtherOp->getOpcode() == Instruction::AShr &&
6565f757f3fSDimitry Andric         match(Op, m_LShr(m_NonNegative(), m_Value()))) {
6575f757f3fSDimitry Andric       // lshr nneg C, X --> ashr nneg C, X
6585f757f3fSDimitry Andric       return Instruction::AShr;
6595f757f3fSDimitry Andric     }
6605f757f3fSDimitry Andric   }
6610b57cec5SDimitry Andric   return Op->getOpcode();
6620b57cec5SDimitry Andric }
6630b57cec5SDimitry Andric 
6640b57cec5SDimitry Andric /// This tries to simplify binary operations by factorizing out common terms
6650b57cec5SDimitry Andric /// (e. g. "(A*B)+(A*C)" -> "A*(B+C)").
666bdd1243dSDimitry Andric static Value *tryFactorization(BinaryOperator &I, const SimplifyQuery &SQ,
667bdd1243dSDimitry Andric                                InstCombiner::BuilderTy &Builder,
668bdd1243dSDimitry Andric                                Instruction::BinaryOps InnerOpcode, Value *A,
669bdd1243dSDimitry Andric                                Value *B, Value *C, Value *D) {
6700b57cec5SDimitry Andric   assert(A && B && C && D && "All values must be provided");
6710b57cec5SDimitry Andric 
6720b57cec5SDimitry Andric   Value *V = nullptr;
673bdd1243dSDimitry Andric   Value *RetVal = nullptr;
6740b57cec5SDimitry Andric   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
6750b57cec5SDimitry Andric   Instruction::BinaryOps TopLevelOpcode = I.getOpcode();
6760b57cec5SDimitry Andric 
6770b57cec5SDimitry Andric   // Does "X op' Y" always equal "Y op' X"?
6780b57cec5SDimitry Andric   bool InnerCommutative = Instruction::isCommutative(InnerOpcode);
6790b57cec5SDimitry Andric 
6800b57cec5SDimitry Andric   // Does "X op' (Y op Z)" always equal "(X op' Y) op (X op' Z)"?
681bdd1243dSDimitry Andric   if (leftDistributesOverRight(InnerOpcode, TopLevelOpcode)) {
6820b57cec5SDimitry Andric     // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
6830b57cec5SDimitry Andric     // commutative case, "(A op' B) op (C op' A)"?
6840b57cec5SDimitry Andric     if (A == C || (InnerCommutative && A == D)) {
6850b57cec5SDimitry Andric       if (A != C)
6860b57cec5SDimitry Andric         std::swap(C, D);
6870b57cec5SDimitry Andric       // Consider forming "A op' (B op D)".
6880b57cec5SDimitry Andric       // If "B op D" simplifies then it can be formed with no cost.
68981ad6265SDimitry Andric       V = simplifyBinOp(TopLevelOpcode, B, D, SQ.getWithInstruction(&I));
690bdd1243dSDimitry Andric 
691bdd1243dSDimitry Andric       // If "B op D" doesn't simplify then only go on if one of the existing
6920b57cec5SDimitry Andric       // operations "A op' B" and "C op' D" will be zapped as no longer used.
693bdd1243dSDimitry Andric       if (!V && (LHS->hasOneUse() || RHS->hasOneUse()))
6940b57cec5SDimitry Andric         V = Builder.CreateBinOp(TopLevelOpcode, B, D, RHS->getName());
695bdd1243dSDimitry Andric       if (V)
696bdd1243dSDimitry Andric         RetVal = Builder.CreateBinOp(InnerOpcode, A, V);
6970b57cec5SDimitry Andric     }
6980b57cec5SDimitry Andric   }
6990b57cec5SDimitry Andric 
7000b57cec5SDimitry Andric   // Does "(X op Y) op' Z" always equal "(X op' Z) op (Y op' Z)"?
701bdd1243dSDimitry Andric   if (!RetVal && rightDistributesOverLeft(TopLevelOpcode, InnerOpcode)) {
7020b57cec5SDimitry Andric     // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
7030b57cec5SDimitry Andric     // commutative case, "(A op' B) op (B op' D)"?
7040b57cec5SDimitry Andric     if (B == D || (InnerCommutative && B == C)) {
7050b57cec5SDimitry Andric       if (B != D)
7060b57cec5SDimitry Andric         std::swap(C, D);
7070b57cec5SDimitry Andric       // Consider forming "(A op C) op' B".
7080b57cec5SDimitry Andric       // If "A op C" simplifies then it can be formed with no cost.
70981ad6265SDimitry Andric       V = simplifyBinOp(TopLevelOpcode, A, C, SQ.getWithInstruction(&I));
7100b57cec5SDimitry Andric 
711bdd1243dSDimitry Andric       // If "A op C" doesn't simplify then only go on if one of the existing
7120b57cec5SDimitry Andric       // operations "A op' B" and "C op' D" will be zapped as no longer used.
713bdd1243dSDimitry Andric       if (!V && (LHS->hasOneUse() || RHS->hasOneUse()))
7140b57cec5SDimitry Andric         V = Builder.CreateBinOp(TopLevelOpcode, A, C, LHS->getName());
715bdd1243dSDimitry Andric       if (V)
716bdd1243dSDimitry Andric         RetVal = Builder.CreateBinOp(InnerOpcode, V, B);
7170b57cec5SDimitry Andric     }
7180b57cec5SDimitry Andric   }
7190b57cec5SDimitry Andric 
720bdd1243dSDimitry Andric   if (!RetVal)
721bdd1243dSDimitry Andric     return nullptr;
722bdd1243dSDimitry Andric 
7230b57cec5SDimitry Andric   ++NumFactor;
724bdd1243dSDimitry Andric   RetVal->takeName(&I);
7250b57cec5SDimitry Andric 
726bdd1243dSDimitry Andric   // Try to add no-overflow flags to the final value.
727bdd1243dSDimitry Andric   if (isa<OverflowingBinaryOperator>(RetVal)) {
7280b57cec5SDimitry Andric     bool HasNSW = false;
7290b57cec5SDimitry Andric     bool HasNUW = false;
7300b57cec5SDimitry Andric     if (isa<OverflowingBinaryOperator>(&I)) {
7310b57cec5SDimitry Andric       HasNSW = I.hasNoSignedWrap();
7320b57cec5SDimitry Andric       HasNUW = I.hasNoUnsignedWrap();
7330b57cec5SDimitry Andric     }
7340b57cec5SDimitry Andric     if (auto *LOBO = dyn_cast<OverflowingBinaryOperator>(LHS)) {
7350b57cec5SDimitry Andric       HasNSW &= LOBO->hasNoSignedWrap();
7360b57cec5SDimitry Andric       HasNUW &= LOBO->hasNoUnsignedWrap();
7370b57cec5SDimitry Andric     }
7380b57cec5SDimitry Andric 
7390b57cec5SDimitry Andric     if (auto *ROBO = dyn_cast<OverflowingBinaryOperator>(RHS)) {
7400b57cec5SDimitry Andric       HasNSW &= ROBO->hasNoSignedWrap();
7410b57cec5SDimitry Andric       HasNUW &= ROBO->hasNoUnsignedWrap();
7420b57cec5SDimitry Andric     }
7430b57cec5SDimitry Andric 
744bdd1243dSDimitry Andric     if (TopLevelOpcode == Instruction::Add && InnerOpcode == Instruction::Mul) {
7450b57cec5SDimitry Andric       // We can propagate 'nsw' if we know that
7460b57cec5SDimitry Andric       //  %Y = mul nsw i16 %X, C
7470b57cec5SDimitry Andric       //  %Z = add nsw i16 %Y, %X
7480b57cec5SDimitry Andric       // =>
7490b57cec5SDimitry Andric       //  %Z = mul nsw i16 %X, C+1
7500b57cec5SDimitry Andric       //
7510b57cec5SDimitry Andric       // iff C+1 isn't INT_MIN
7528bcb0991SDimitry Andric       const APInt *CInt;
753bdd1243dSDimitry Andric       if (match(V, m_APInt(CInt)) && !CInt->isMinSignedValue())
754bdd1243dSDimitry Andric         cast<Instruction>(RetVal)->setHasNoSignedWrap(HasNSW);
7550b57cec5SDimitry Andric 
7560b57cec5SDimitry Andric       // nuw can be propagated with any constant or nuw value.
757bdd1243dSDimitry Andric       cast<Instruction>(RetVal)->setHasNoUnsignedWrap(HasNUW);
7580b57cec5SDimitry Andric     }
7590b57cec5SDimitry Andric   }
760bdd1243dSDimitry Andric   return RetVal;
7610b57cec5SDimitry Andric }
7620b57cec5SDimitry Andric 
7637a6dacacSDimitry Andric // If `I` has one Const operand and the other matches `(ctpop (not x))`,
7647a6dacacSDimitry Andric // replace `(ctpop (not x))` with `(sub nuw nsw BitWidth(x), (ctpop x))`.
7657a6dacacSDimitry Andric // This is only useful is the new subtract can fold so we only handle the
7667a6dacacSDimitry Andric // following cases:
7677a6dacacSDimitry Andric //    1) (add/sub/disjoint_or C, (ctpop (not x))
7687a6dacacSDimitry Andric //        -> (add/sub/disjoint_or C', (ctpop x))
7697a6dacacSDimitry Andric //    1) (cmp pred C, (ctpop (not x))
7707a6dacacSDimitry Andric //        -> (cmp pred C', (ctpop x))
7717a6dacacSDimitry Andric Instruction *InstCombinerImpl::tryFoldInstWithCtpopWithNot(Instruction *I) {
7727a6dacacSDimitry Andric   unsigned Opc = I->getOpcode();
7737a6dacacSDimitry Andric   unsigned ConstIdx = 1;
7747a6dacacSDimitry Andric   switch (Opc) {
7757a6dacacSDimitry Andric   default:
7767a6dacacSDimitry Andric     return nullptr;
7777a6dacacSDimitry Andric     // (ctpop (not x)) <-> (sub nuw nsw BitWidth(x) - (ctpop x))
7787a6dacacSDimitry Andric     // We can fold the BitWidth(x) with add/sub/icmp as long the other operand
7797a6dacacSDimitry Andric     // is constant.
7807a6dacacSDimitry Andric   case Instruction::Sub:
7817a6dacacSDimitry Andric     ConstIdx = 0;
7827a6dacacSDimitry Andric     break;
7837a6dacacSDimitry Andric   case Instruction::ICmp:
7847a6dacacSDimitry Andric     // Signed predicates aren't correct in some edge cases like for i2 types, as
7857a6dacacSDimitry Andric     // well since (ctpop x) is known [0, log2(BitWidth(x))] almost all signed
7867a6dacacSDimitry Andric     // comparisons against it are simplfied to unsigned.
7877a6dacacSDimitry Andric     if (cast<ICmpInst>(I)->isSigned())
7887a6dacacSDimitry Andric       return nullptr;
7897a6dacacSDimitry Andric     break;
7907a6dacacSDimitry Andric   case Instruction::Or:
7917a6dacacSDimitry Andric     if (!match(I, m_DisjointOr(m_Value(), m_Value())))
7927a6dacacSDimitry Andric       return nullptr;
7937a6dacacSDimitry Andric     [[fallthrough]];
7947a6dacacSDimitry Andric   case Instruction::Add:
7957a6dacacSDimitry Andric     break;
7967a6dacacSDimitry Andric   }
7977a6dacacSDimitry Andric 
7987a6dacacSDimitry Andric   Value *Op;
7997a6dacacSDimitry Andric   // Find ctpop.
8007a6dacacSDimitry Andric   if (!match(I->getOperand(1 - ConstIdx),
8017a6dacacSDimitry Andric              m_OneUse(m_Intrinsic<Intrinsic::ctpop>(m_Value(Op)))))
8027a6dacacSDimitry Andric     return nullptr;
8037a6dacacSDimitry Andric 
8047a6dacacSDimitry Andric   Constant *C;
8057a6dacacSDimitry Andric   // Check other operand is ImmConstant.
8067a6dacacSDimitry Andric   if (!match(I->getOperand(ConstIdx), m_ImmConstant(C)))
8077a6dacacSDimitry Andric     return nullptr;
8087a6dacacSDimitry Andric 
8097a6dacacSDimitry Andric   Type *Ty = Op->getType();
8107a6dacacSDimitry Andric   Constant *BitWidthC = ConstantInt::get(Ty, Ty->getScalarSizeInBits());
8117a6dacacSDimitry Andric   // Need extra check for icmp. Note if this check is true, it generally means
8127a6dacacSDimitry Andric   // the icmp will simplify to true/false.
813*0fca6ea1SDimitry Andric   if (Opc == Instruction::ICmp && !cast<ICmpInst>(I)->isEquality()) {
814*0fca6ea1SDimitry Andric     Constant *Cmp =
815*0fca6ea1SDimitry Andric         ConstantFoldCompareInstOperands(ICmpInst::ICMP_UGT, C, BitWidthC, DL);
816*0fca6ea1SDimitry Andric     if (!Cmp || !Cmp->isZeroValue())
8177a6dacacSDimitry Andric       return nullptr;
818*0fca6ea1SDimitry Andric   }
8197a6dacacSDimitry Andric 
8207a6dacacSDimitry Andric   // Check we can invert `(not x)` for free.
8217a6dacacSDimitry Andric   bool Consumes = false;
8227a6dacacSDimitry Andric   if (!isFreeToInvert(Op, Op->hasOneUse(), Consumes) || !Consumes)
8237a6dacacSDimitry Andric     return nullptr;
8247a6dacacSDimitry Andric   Value *NotOp = getFreelyInverted(Op, Op->hasOneUse(), &Builder);
8257a6dacacSDimitry Andric   assert(NotOp != nullptr &&
8267a6dacacSDimitry Andric          "Desync between isFreeToInvert and getFreelyInverted");
8277a6dacacSDimitry Andric 
8287a6dacacSDimitry Andric   Value *CtpopOfNotOp = Builder.CreateIntrinsic(Ty, Intrinsic::ctpop, NotOp);
8297a6dacacSDimitry Andric 
8307a6dacacSDimitry Andric   Value *R = nullptr;
8317a6dacacSDimitry Andric 
8327a6dacacSDimitry Andric   // Do the transformation here to avoid potentially introducing an infinite
8337a6dacacSDimitry Andric   // loop.
8347a6dacacSDimitry Andric   switch (Opc) {
8357a6dacacSDimitry Andric   case Instruction::Sub:
8367a6dacacSDimitry Andric     R = Builder.CreateAdd(CtpopOfNotOp, ConstantExpr::getSub(C, BitWidthC));
8377a6dacacSDimitry Andric     break;
8387a6dacacSDimitry Andric   case Instruction::Or:
8397a6dacacSDimitry Andric   case Instruction::Add:
8407a6dacacSDimitry Andric     R = Builder.CreateSub(ConstantExpr::getAdd(C, BitWidthC), CtpopOfNotOp);
8417a6dacacSDimitry Andric     break;
8427a6dacacSDimitry Andric   case Instruction::ICmp:
8437a6dacacSDimitry Andric     R = Builder.CreateICmp(cast<ICmpInst>(I)->getSwappedPredicate(),
8447a6dacacSDimitry Andric                            CtpopOfNotOp, ConstantExpr::getSub(BitWidthC, C));
8457a6dacacSDimitry Andric     break;
8467a6dacacSDimitry Andric   default:
8477a6dacacSDimitry Andric     llvm_unreachable("Unhandled Opcode");
8487a6dacacSDimitry Andric   }
8497a6dacacSDimitry Andric   assert(R != nullptr);
8507a6dacacSDimitry Andric   return replaceInstUsesWith(*I, R);
8517a6dacacSDimitry Andric }
8527a6dacacSDimitry Andric 
85306c3fb27SDimitry Andric // (Binop1 (Binop2 (logic_shift X, C), C1), (logic_shift Y, C))
85406c3fb27SDimitry Andric //   IFF
85506c3fb27SDimitry Andric //    1) the logic_shifts match
85606c3fb27SDimitry Andric //    2) either both binops are binops and one is `and` or
85706c3fb27SDimitry Andric //       BinOp1 is `and`
85806c3fb27SDimitry Andric //       (logic_shift (inv_logic_shift C1, C), C) == C1 or
85906c3fb27SDimitry Andric //
86006c3fb27SDimitry Andric //    -> (logic_shift (Binop1 (Binop2 X, inv_logic_shift(C1, C)), Y), C)
86106c3fb27SDimitry Andric //
86206c3fb27SDimitry Andric // (Binop1 (Binop2 (logic_shift X, Amt), Mask), (logic_shift Y, Amt))
86306c3fb27SDimitry Andric //   IFF
86406c3fb27SDimitry Andric //    1) the logic_shifts match
86506c3fb27SDimitry Andric //    2) BinOp1 == BinOp2 (if BinOp ==  `add`, then also requires `shl`).
86606c3fb27SDimitry Andric //
86706c3fb27SDimitry Andric //    -> (BinOp (logic_shift (BinOp X, Y)), Mask)
8685f757f3fSDimitry Andric //
8695f757f3fSDimitry Andric // (Binop1 (Binop2 (arithmetic_shift X, Amt), Mask), (arithmetic_shift Y, Amt))
8705f757f3fSDimitry Andric //   IFF
8715f757f3fSDimitry Andric //   1) Binop1 is bitwise logical operator `and`, `or` or `xor`
8725f757f3fSDimitry Andric //   2) Binop2 is `not`
8735f757f3fSDimitry Andric //
8745f757f3fSDimitry Andric //   -> (arithmetic_shift Binop1((not X), Y), Amt)
8755f757f3fSDimitry Andric 
87606c3fb27SDimitry Andric Instruction *InstCombinerImpl::foldBinOpShiftWithShift(BinaryOperator &I) {
877*0fca6ea1SDimitry Andric   const DataLayout &DL = I.getDataLayout();
87806c3fb27SDimitry Andric   auto IsValidBinOpc = [](unsigned Opc) {
87906c3fb27SDimitry Andric     switch (Opc) {
88006c3fb27SDimitry Andric     default:
88106c3fb27SDimitry Andric       return false;
88206c3fb27SDimitry Andric     case Instruction::And:
88306c3fb27SDimitry Andric     case Instruction::Or:
88406c3fb27SDimitry Andric     case Instruction::Xor:
88506c3fb27SDimitry Andric     case Instruction::Add:
88606c3fb27SDimitry Andric       // Skip Sub as we only match constant masks which will canonicalize to use
88706c3fb27SDimitry Andric       // add.
88806c3fb27SDimitry Andric       return true;
88906c3fb27SDimitry Andric     }
89006c3fb27SDimitry Andric   };
89106c3fb27SDimitry Andric 
89206c3fb27SDimitry Andric   // Check if we can distribute binop arbitrarily. `add` + `lshr` has extra
89306c3fb27SDimitry Andric   // constraints.
89406c3fb27SDimitry Andric   auto IsCompletelyDistributable = [](unsigned BinOpc1, unsigned BinOpc2,
89506c3fb27SDimitry Andric                                       unsigned ShOpc) {
8965f757f3fSDimitry Andric     assert(ShOpc != Instruction::AShr);
89706c3fb27SDimitry Andric     return (BinOpc1 != Instruction::Add && BinOpc2 != Instruction::Add) ||
89806c3fb27SDimitry Andric            ShOpc == Instruction::Shl;
89906c3fb27SDimitry Andric   };
90006c3fb27SDimitry Andric 
90106c3fb27SDimitry Andric   auto GetInvShift = [](unsigned ShOpc) {
9025f757f3fSDimitry Andric     assert(ShOpc != Instruction::AShr);
90306c3fb27SDimitry Andric     return ShOpc == Instruction::LShr ? Instruction::Shl : Instruction::LShr;
90406c3fb27SDimitry Andric   };
90506c3fb27SDimitry Andric 
90606c3fb27SDimitry Andric   auto CanDistributeBinops = [&](unsigned BinOpc1, unsigned BinOpc2,
90706c3fb27SDimitry Andric                                  unsigned ShOpc, Constant *CMask,
90806c3fb27SDimitry Andric                                  Constant *CShift) {
90906c3fb27SDimitry Andric     // If the BinOp1 is `and` we don't need to check the mask.
91006c3fb27SDimitry Andric     if (BinOpc1 == Instruction::And)
91106c3fb27SDimitry Andric       return true;
91206c3fb27SDimitry Andric 
91306c3fb27SDimitry Andric     // For all other possible transfers we need complete distributable
91406c3fb27SDimitry Andric     // binop/shift (anything but `add` + `lshr`).
91506c3fb27SDimitry Andric     if (!IsCompletelyDistributable(BinOpc1, BinOpc2, ShOpc))
91606c3fb27SDimitry Andric       return false;
91706c3fb27SDimitry Andric 
91806c3fb27SDimitry Andric     // If BinOp2 is `and`, any mask works (this only really helps for non-splat
91906c3fb27SDimitry Andric     // vecs, otherwise the mask will be simplified and the following check will
92006c3fb27SDimitry Andric     // handle it).
92106c3fb27SDimitry Andric     if (BinOpc2 == Instruction::And)
92206c3fb27SDimitry Andric       return true;
92306c3fb27SDimitry Andric 
92406c3fb27SDimitry Andric     // Otherwise, need mask that meets the below requirement.
92506c3fb27SDimitry Andric     // (logic_shift (inv_logic_shift Mask, ShAmt), ShAmt) == Mask
9265f757f3fSDimitry Andric     Constant *MaskInvShift =
9275f757f3fSDimitry Andric         ConstantFoldBinaryOpOperands(GetInvShift(ShOpc), CMask, CShift, DL);
9285f757f3fSDimitry Andric     return ConstantFoldBinaryOpOperands(ShOpc, MaskInvShift, CShift, DL) ==
9295f757f3fSDimitry Andric            CMask;
93006c3fb27SDimitry Andric   };
93106c3fb27SDimitry Andric 
93206c3fb27SDimitry Andric   auto MatchBinOp = [&](unsigned ShOpnum) -> Instruction * {
93306c3fb27SDimitry Andric     Constant *CMask, *CShift;
93406c3fb27SDimitry Andric     Value *X, *Y, *ShiftedX, *Mask, *Shift;
93506c3fb27SDimitry Andric     if (!match(I.getOperand(ShOpnum),
9365f757f3fSDimitry Andric                m_OneUse(m_Shift(m_Value(Y), m_Value(Shift)))))
93706c3fb27SDimitry Andric       return nullptr;
93806c3fb27SDimitry Andric     if (!match(I.getOperand(1 - ShOpnum),
93906c3fb27SDimitry Andric                m_BinOp(m_Value(ShiftedX), m_Value(Mask))))
94006c3fb27SDimitry Andric       return nullptr;
94106c3fb27SDimitry Andric 
9425f757f3fSDimitry Andric     if (!match(ShiftedX, m_OneUse(m_Shift(m_Value(X), m_Specific(Shift)))))
94306c3fb27SDimitry Andric       return nullptr;
94406c3fb27SDimitry Andric 
94506c3fb27SDimitry Andric     // Make sure we are matching instruction shifts and not ConstantExpr
94606c3fb27SDimitry Andric     auto *IY = dyn_cast<Instruction>(I.getOperand(ShOpnum));
94706c3fb27SDimitry Andric     auto *IX = dyn_cast<Instruction>(ShiftedX);
94806c3fb27SDimitry Andric     if (!IY || !IX)
94906c3fb27SDimitry Andric       return nullptr;
95006c3fb27SDimitry Andric 
95106c3fb27SDimitry Andric     // LHS and RHS need same shift opcode
95206c3fb27SDimitry Andric     unsigned ShOpc = IY->getOpcode();
95306c3fb27SDimitry Andric     if (ShOpc != IX->getOpcode())
95406c3fb27SDimitry Andric       return nullptr;
95506c3fb27SDimitry Andric 
95606c3fb27SDimitry Andric     // Make sure binop is real instruction and not ConstantExpr
95706c3fb27SDimitry Andric     auto *BO2 = dyn_cast<Instruction>(I.getOperand(1 - ShOpnum));
95806c3fb27SDimitry Andric     if (!BO2)
95906c3fb27SDimitry Andric       return nullptr;
96006c3fb27SDimitry Andric 
96106c3fb27SDimitry Andric     unsigned BinOpc = BO2->getOpcode();
96206c3fb27SDimitry Andric     // Make sure we have valid binops.
96306c3fb27SDimitry Andric     if (!IsValidBinOpc(I.getOpcode()) || !IsValidBinOpc(BinOpc))
96406c3fb27SDimitry Andric       return nullptr;
96506c3fb27SDimitry Andric 
9665f757f3fSDimitry Andric     if (ShOpc == Instruction::AShr) {
9675f757f3fSDimitry Andric       if (Instruction::isBitwiseLogicOp(I.getOpcode()) &&
9685f757f3fSDimitry Andric           BinOpc == Instruction::Xor && match(Mask, m_AllOnes())) {
9695f757f3fSDimitry Andric         Value *NotX = Builder.CreateNot(X);
9705f757f3fSDimitry Andric         Value *NewBinOp = Builder.CreateBinOp(I.getOpcode(), Y, NotX);
9715f757f3fSDimitry Andric         return BinaryOperator::Create(
9725f757f3fSDimitry Andric             static_cast<Instruction::BinaryOps>(ShOpc), NewBinOp, Shift);
9735f757f3fSDimitry Andric       }
9745f757f3fSDimitry Andric 
9755f757f3fSDimitry Andric       return nullptr;
9765f757f3fSDimitry Andric     }
9775f757f3fSDimitry Andric 
97806c3fb27SDimitry Andric     // If BinOp1 == BinOp2 and it's bitwise or shl with add, then just
97906c3fb27SDimitry Andric     // distribute to drop the shift irrelevant of constants.
98006c3fb27SDimitry Andric     if (BinOpc == I.getOpcode() &&
98106c3fb27SDimitry Andric         IsCompletelyDistributable(I.getOpcode(), BinOpc, ShOpc)) {
98206c3fb27SDimitry Andric       Value *NewBinOp2 = Builder.CreateBinOp(I.getOpcode(), X, Y);
98306c3fb27SDimitry Andric       Value *NewBinOp1 = Builder.CreateBinOp(
98406c3fb27SDimitry Andric           static_cast<Instruction::BinaryOps>(ShOpc), NewBinOp2, Shift);
98506c3fb27SDimitry Andric       return BinaryOperator::Create(I.getOpcode(), NewBinOp1, Mask);
98606c3fb27SDimitry Andric     }
98706c3fb27SDimitry Andric 
98806c3fb27SDimitry Andric     // Otherwise we can only distribute by constant shifting the mask, so
98906c3fb27SDimitry Andric     // ensure we have constants.
99006c3fb27SDimitry Andric     if (!match(Shift, m_ImmConstant(CShift)))
99106c3fb27SDimitry Andric       return nullptr;
99206c3fb27SDimitry Andric     if (!match(Mask, m_ImmConstant(CMask)))
99306c3fb27SDimitry Andric       return nullptr;
99406c3fb27SDimitry Andric 
99506c3fb27SDimitry Andric     // Check if we can distribute the binops.
99606c3fb27SDimitry Andric     if (!CanDistributeBinops(I.getOpcode(), BinOpc, ShOpc, CMask, CShift))
99706c3fb27SDimitry Andric       return nullptr;
99806c3fb27SDimitry Andric 
9995f757f3fSDimitry Andric     Constant *NewCMask =
10005f757f3fSDimitry Andric         ConstantFoldBinaryOpOperands(GetInvShift(ShOpc), CMask, CShift, DL);
100106c3fb27SDimitry Andric     Value *NewBinOp2 = Builder.CreateBinOp(
100206c3fb27SDimitry Andric         static_cast<Instruction::BinaryOps>(BinOpc), X, NewCMask);
100306c3fb27SDimitry Andric     Value *NewBinOp1 = Builder.CreateBinOp(I.getOpcode(), Y, NewBinOp2);
100406c3fb27SDimitry Andric     return BinaryOperator::Create(static_cast<Instruction::BinaryOps>(ShOpc),
100506c3fb27SDimitry Andric                                   NewBinOp1, CShift);
100606c3fb27SDimitry Andric   };
100706c3fb27SDimitry Andric 
100806c3fb27SDimitry Andric   if (Instruction *R = MatchBinOp(0))
100906c3fb27SDimitry Andric     return R;
101006c3fb27SDimitry Andric   return MatchBinOp(1);
101106c3fb27SDimitry Andric }
101206c3fb27SDimitry Andric 
101306c3fb27SDimitry Andric // (Binop (zext C), (select C, T, F))
101406c3fb27SDimitry Andric //    -> (select C, (binop 1, T), (binop 0, F))
101506c3fb27SDimitry Andric //
101606c3fb27SDimitry Andric // (Binop (sext C), (select C, T, F))
101706c3fb27SDimitry Andric //    -> (select C, (binop -1, T), (binop 0, F))
101806c3fb27SDimitry Andric //
101906c3fb27SDimitry Andric // Attempt to simplify binary operations into a select with folded args, when
102006c3fb27SDimitry Andric // one operand of the binop is a select instruction and the other operand is a
102106c3fb27SDimitry Andric // zext/sext extension, whose value is the select condition.
102206c3fb27SDimitry Andric Instruction *
102306c3fb27SDimitry Andric InstCombinerImpl::foldBinOpOfSelectAndCastOfSelectCondition(BinaryOperator &I) {
102406c3fb27SDimitry Andric   // TODO: this simplification may be extended to any speculatable instruction,
102506c3fb27SDimitry Andric   // not just binops, and would possibly be handled better in FoldOpIntoSelect.
102606c3fb27SDimitry Andric   Instruction::BinaryOps Opc = I.getOpcode();
102706c3fb27SDimitry Andric   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
102806c3fb27SDimitry Andric   Value *A, *CondVal, *TrueVal, *FalseVal;
102906c3fb27SDimitry Andric   Value *CastOp;
103006c3fb27SDimitry Andric 
103106c3fb27SDimitry Andric   auto MatchSelectAndCast = [&](Value *CastOp, Value *SelectOp) {
103206c3fb27SDimitry Andric     return match(CastOp, m_ZExtOrSExt(m_Value(A))) &&
103306c3fb27SDimitry Andric            A->getType()->getScalarSizeInBits() == 1 &&
103406c3fb27SDimitry Andric            match(SelectOp, m_Select(m_Value(CondVal), m_Value(TrueVal),
103506c3fb27SDimitry Andric                                     m_Value(FalseVal)));
103606c3fb27SDimitry Andric   };
103706c3fb27SDimitry Andric 
103806c3fb27SDimitry Andric   // Make sure one side of the binop is a select instruction, and the other is a
103906c3fb27SDimitry Andric   // zero/sign extension operating on a i1.
104006c3fb27SDimitry Andric   if (MatchSelectAndCast(LHS, RHS))
104106c3fb27SDimitry Andric     CastOp = LHS;
104206c3fb27SDimitry Andric   else if (MatchSelectAndCast(RHS, LHS))
104306c3fb27SDimitry Andric     CastOp = RHS;
104406c3fb27SDimitry Andric   else
104506c3fb27SDimitry Andric     return nullptr;
104606c3fb27SDimitry Andric 
104706c3fb27SDimitry Andric   auto NewFoldedConst = [&](bool IsTrueArm, Value *V) {
104806c3fb27SDimitry Andric     bool IsCastOpRHS = (CastOp == RHS);
10495f757f3fSDimitry Andric     bool IsZExt = isa<ZExtInst>(CastOp);
105006c3fb27SDimitry Andric     Constant *C;
105106c3fb27SDimitry Andric 
105206c3fb27SDimitry Andric     if (IsTrueArm) {
105306c3fb27SDimitry Andric       C = Constant::getNullValue(V->getType());
105406c3fb27SDimitry Andric     } else if (IsZExt) {
105506c3fb27SDimitry Andric       unsigned BitWidth = V->getType()->getScalarSizeInBits();
105606c3fb27SDimitry Andric       C = Constant::getIntegerValue(V->getType(), APInt(BitWidth, 1));
105706c3fb27SDimitry Andric     } else {
105806c3fb27SDimitry Andric       C = Constant::getAllOnesValue(V->getType());
105906c3fb27SDimitry Andric     }
106006c3fb27SDimitry Andric 
106106c3fb27SDimitry Andric     return IsCastOpRHS ? Builder.CreateBinOp(Opc, V, C)
106206c3fb27SDimitry Andric                        : Builder.CreateBinOp(Opc, C, V);
106306c3fb27SDimitry Andric   };
106406c3fb27SDimitry Andric 
106506c3fb27SDimitry Andric   // If the value used in the zext/sext is the select condition, or the negated
106606c3fb27SDimitry Andric   // of the select condition, the binop can be simplified.
10675f757f3fSDimitry Andric   if (CondVal == A) {
10685f757f3fSDimitry Andric     Value *NewTrueVal = NewFoldedConst(false, TrueVal);
10695f757f3fSDimitry Andric     return SelectInst::Create(CondVal, NewTrueVal,
107006c3fb27SDimitry Andric                               NewFoldedConst(true, FalseVal));
10715f757f3fSDimitry Andric   }
107206c3fb27SDimitry Andric 
10735f757f3fSDimitry Andric   if (match(A, m_Not(m_Specific(CondVal)))) {
10745f757f3fSDimitry Andric     Value *NewTrueVal = NewFoldedConst(true, TrueVal);
10755f757f3fSDimitry Andric     return SelectInst::Create(CondVal, NewTrueVal,
107606c3fb27SDimitry Andric                               NewFoldedConst(false, FalseVal));
10775f757f3fSDimitry Andric   }
107806c3fb27SDimitry Andric 
107906c3fb27SDimitry Andric   return nullptr;
108006c3fb27SDimitry Andric }
108106c3fb27SDimitry Andric 
1082bdd1243dSDimitry Andric Value *InstCombinerImpl::tryFactorizationFolds(BinaryOperator &I) {
10830b57cec5SDimitry Andric   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
10840b57cec5SDimitry Andric   BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
10850b57cec5SDimitry Andric   BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
10860b57cec5SDimitry Andric   Instruction::BinaryOps TopLevelOpcode = I.getOpcode();
10870b57cec5SDimitry Andric   Value *A, *B, *C, *D;
10880b57cec5SDimitry Andric   Instruction::BinaryOps LHSOpcode, RHSOpcode;
1089bdd1243dSDimitry Andric 
10900b57cec5SDimitry Andric   if (Op0)
10915f757f3fSDimitry Andric     LHSOpcode = getBinOpsForFactorization(TopLevelOpcode, Op0, A, B, Op1);
10920b57cec5SDimitry Andric   if (Op1)
10935f757f3fSDimitry Andric     RHSOpcode = getBinOpsForFactorization(TopLevelOpcode, Op1, C, D, Op0);
10940b57cec5SDimitry Andric 
10950b57cec5SDimitry Andric   // The instruction has the form "(A op' B) op (C op' D)".  Try to factorize
10960b57cec5SDimitry Andric   // a common term.
10970b57cec5SDimitry Andric   if (Op0 && Op1 && LHSOpcode == RHSOpcode)
1098bdd1243dSDimitry Andric     if (Value *V = tryFactorization(I, SQ, Builder, LHSOpcode, A, B, C, D))
10990b57cec5SDimitry Andric       return V;
11000b57cec5SDimitry Andric 
11010b57cec5SDimitry Andric   // The instruction has the form "(A op' B) op (C)".  Try to factorize common
11020b57cec5SDimitry Andric   // term.
11030b57cec5SDimitry Andric   if (Op0)
11040b57cec5SDimitry Andric     if (Value *Ident = getIdentityValue(LHSOpcode, RHS))
1105bdd1243dSDimitry Andric       if (Value *V =
1106bdd1243dSDimitry Andric               tryFactorization(I, SQ, Builder, LHSOpcode, A, B, RHS, Ident))
11070b57cec5SDimitry Andric         return V;
11080b57cec5SDimitry Andric 
11090b57cec5SDimitry Andric   // The instruction has the form "(B) op (C op' D)".  Try to factorize common
11100b57cec5SDimitry Andric   // term.
11110b57cec5SDimitry Andric   if (Op1)
11120b57cec5SDimitry Andric     if (Value *Ident = getIdentityValue(RHSOpcode, LHS))
1113bdd1243dSDimitry Andric       if (Value *V =
1114bdd1243dSDimitry Andric               tryFactorization(I, SQ, Builder, RHSOpcode, LHS, Ident, C, D))
11150b57cec5SDimitry Andric         return V;
1116bdd1243dSDimitry Andric 
1117bdd1243dSDimitry Andric   return nullptr;
11180b57cec5SDimitry Andric }
11190b57cec5SDimitry Andric 
1120bdd1243dSDimitry Andric /// This tries to simplify binary operations which some other binary operation
1121bdd1243dSDimitry Andric /// distributes over either by factorizing out common terms
1122bdd1243dSDimitry Andric /// (eg "(A*B)+(A*C)" -> "A*(B+C)") or expanding out if this results in
1123bdd1243dSDimitry Andric /// simplifications (eg: "A & (B | C) -> (A&B) | (A&C)" if this is a win).
1124bdd1243dSDimitry Andric /// Returns the simplified value, or null if it didn't simplify.
1125bdd1243dSDimitry Andric Value *InstCombinerImpl::foldUsingDistributiveLaws(BinaryOperator &I) {
1126bdd1243dSDimitry Andric   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1127bdd1243dSDimitry Andric   BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
1128bdd1243dSDimitry Andric   BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
1129bdd1243dSDimitry Andric   Instruction::BinaryOps TopLevelOpcode = I.getOpcode();
1130bdd1243dSDimitry Andric 
1131bdd1243dSDimitry Andric   // Factorization.
1132bdd1243dSDimitry Andric   if (Value *R = tryFactorizationFolds(I))
1133bdd1243dSDimitry Andric     return R;
1134bdd1243dSDimitry Andric 
11350b57cec5SDimitry Andric   // Expansion.
11360b57cec5SDimitry Andric   if (Op0 && rightDistributesOverLeft(Op0->getOpcode(), TopLevelOpcode)) {
11370b57cec5SDimitry Andric     // The instruction has the form "(A op' B) op C".  See if expanding it out
11380b57cec5SDimitry Andric     // to "(A op C) op' (B op C)" results in simplifications.
11390b57cec5SDimitry Andric     Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
11400b57cec5SDimitry Andric     Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op'
11410b57cec5SDimitry Andric 
1142e8d8bef9SDimitry Andric     // Disable the use of undef because it's not safe to distribute undef.
1143e8d8bef9SDimitry Andric     auto SQDistributive = SQ.getWithInstruction(&I).getWithoutUndef();
114481ad6265SDimitry Andric     Value *L = simplifyBinOp(TopLevelOpcode, A, C, SQDistributive);
114581ad6265SDimitry Andric     Value *R = simplifyBinOp(TopLevelOpcode, B, C, SQDistributive);
11460b57cec5SDimitry Andric 
11470b57cec5SDimitry Andric     // Do "A op C" and "B op C" both simplify?
11480b57cec5SDimitry Andric     if (L && R) {
11490b57cec5SDimitry Andric       // They do! Return "L op' R".
11500b57cec5SDimitry Andric       ++NumExpand;
11510b57cec5SDimitry Andric       C = Builder.CreateBinOp(InnerOpcode, L, R);
11520b57cec5SDimitry Andric       C->takeName(&I);
11530b57cec5SDimitry Andric       return C;
11540b57cec5SDimitry Andric     }
11550b57cec5SDimitry Andric 
11560b57cec5SDimitry Andric     // Does "A op C" simplify to the identity value for the inner opcode?
11570b57cec5SDimitry Andric     if (L && L == ConstantExpr::getBinOpIdentity(InnerOpcode, L->getType())) {
11580b57cec5SDimitry Andric       // They do! Return "B op C".
11590b57cec5SDimitry Andric       ++NumExpand;
11600b57cec5SDimitry Andric       C = Builder.CreateBinOp(TopLevelOpcode, B, C);
11610b57cec5SDimitry Andric       C->takeName(&I);
11620b57cec5SDimitry Andric       return C;
11630b57cec5SDimitry Andric     }
11640b57cec5SDimitry Andric 
11650b57cec5SDimitry Andric     // Does "B op C" simplify to the identity value for the inner opcode?
11660b57cec5SDimitry Andric     if (R && R == ConstantExpr::getBinOpIdentity(InnerOpcode, R->getType())) {
11670b57cec5SDimitry Andric       // They do! Return "A op C".
11680b57cec5SDimitry Andric       ++NumExpand;
11690b57cec5SDimitry Andric       C = Builder.CreateBinOp(TopLevelOpcode, A, C);
11700b57cec5SDimitry Andric       C->takeName(&I);
11710b57cec5SDimitry Andric       return C;
11720b57cec5SDimitry Andric     }
11730b57cec5SDimitry Andric   }
11740b57cec5SDimitry Andric 
11750b57cec5SDimitry Andric   if (Op1 && leftDistributesOverRight(TopLevelOpcode, Op1->getOpcode())) {
11760b57cec5SDimitry Andric     // The instruction has the form "A op (B op' C)".  See if expanding it out
11770b57cec5SDimitry Andric     // to "(A op B) op' (A op C)" results in simplifications.
11780b57cec5SDimitry Andric     Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
11790b57cec5SDimitry Andric     Instruction::BinaryOps InnerOpcode = Op1->getOpcode(); // op'
11800b57cec5SDimitry Andric 
1181e8d8bef9SDimitry Andric     // Disable the use of undef because it's not safe to distribute undef.
1182e8d8bef9SDimitry Andric     auto SQDistributive = SQ.getWithInstruction(&I).getWithoutUndef();
118381ad6265SDimitry Andric     Value *L = simplifyBinOp(TopLevelOpcode, A, B, SQDistributive);
118481ad6265SDimitry Andric     Value *R = simplifyBinOp(TopLevelOpcode, A, C, SQDistributive);
11850b57cec5SDimitry Andric 
11860b57cec5SDimitry Andric     // Do "A op B" and "A op C" both simplify?
11870b57cec5SDimitry Andric     if (L && R) {
11880b57cec5SDimitry Andric       // They do! Return "L op' R".
11890b57cec5SDimitry Andric       ++NumExpand;
11900b57cec5SDimitry Andric       A = Builder.CreateBinOp(InnerOpcode, L, R);
11910b57cec5SDimitry Andric       A->takeName(&I);
11920b57cec5SDimitry Andric       return A;
11930b57cec5SDimitry Andric     }
11940b57cec5SDimitry Andric 
11950b57cec5SDimitry Andric     // Does "A op B" simplify to the identity value for the inner opcode?
11960b57cec5SDimitry Andric     if (L && L == ConstantExpr::getBinOpIdentity(InnerOpcode, L->getType())) {
11970b57cec5SDimitry Andric       // They do! Return "A op C".
11980b57cec5SDimitry Andric       ++NumExpand;
11990b57cec5SDimitry Andric       A = Builder.CreateBinOp(TopLevelOpcode, A, C);
12000b57cec5SDimitry Andric       A->takeName(&I);
12010b57cec5SDimitry Andric       return A;
12020b57cec5SDimitry Andric     }
12030b57cec5SDimitry Andric 
12040b57cec5SDimitry Andric     // Does "A op C" simplify to the identity value for the inner opcode?
12050b57cec5SDimitry Andric     if (R && R == ConstantExpr::getBinOpIdentity(InnerOpcode, R->getType())) {
12060b57cec5SDimitry Andric       // They do! Return "A op B".
12070b57cec5SDimitry Andric       ++NumExpand;
12080b57cec5SDimitry Andric       A = Builder.CreateBinOp(TopLevelOpcode, A, B);
12090b57cec5SDimitry Andric       A->takeName(&I);
12100b57cec5SDimitry Andric       return A;
12110b57cec5SDimitry Andric     }
12120b57cec5SDimitry Andric   }
12130b57cec5SDimitry Andric 
12140b57cec5SDimitry Andric   return SimplifySelectsFeedingBinaryOp(I, LHS, RHS);
12150b57cec5SDimitry Andric }
12160b57cec5SDimitry Andric 
12171db9f3b2SDimitry Andric static std::optional<std::pair<Value *, Value *>>
12181db9f3b2SDimitry Andric matchSymmetricPhiNodesPair(PHINode *LHS, PHINode *RHS) {
1219cb14a3feSDimitry Andric   if (LHS->getParent() != RHS->getParent())
1220cb14a3feSDimitry Andric     return std::nullopt;
1221cb14a3feSDimitry Andric 
1222cb14a3feSDimitry Andric   if (LHS->getNumIncomingValues() < 2)
1223cb14a3feSDimitry Andric     return std::nullopt;
1224cb14a3feSDimitry Andric 
1225cb14a3feSDimitry Andric   if (!equal(LHS->blocks(), RHS->blocks()))
1226cb14a3feSDimitry Andric     return std::nullopt;
1227cb14a3feSDimitry Andric 
1228cb14a3feSDimitry Andric   Value *L0 = LHS->getIncomingValue(0);
1229cb14a3feSDimitry Andric   Value *R0 = RHS->getIncomingValue(0);
1230cb14a3feSDimitry Andric 
1231cb14a3feSDimitry Andric   for (unsigned I = 1, E = LHS->getNumIncomingValues(); I != E; ++I) {
1232cb14a3feSDimitry Andric     Value *L1 = LHS->getIncomingValue(I);
1233cb14a3feSDimitry Andric     Value *R1 = RHS->getIncomingValue(I);
1234cb14a3feSDimitry Andric 
1235cb14a3feSDimitry Andric     if ((L0 == L1 && R0 == R1) || (L0 == R1 && R0 == L1))
1236cb14a3feSDimitry Andric       continue;
1237cb14a3feSDimitry Andric 
1238cb14a3feSDimitry Andric     return std::nullopt;
1239cb14a3feSDimitry Andric   }
1240cb14a3feSDimitry Andric 
1241cb14a3feSDimitry Andric   return std::optional(std::pair(L0, R0));
1242cb14a3feSDimitry Andric }
1243cb14a3feSDimitry Andric 
12441db9f3b2SDimitry Andric std::optional<std::pair<Value *, Value *>>
12451db9f3b2SDimitry Andric InstCombinerImpl::matchSymmetricPair(Value *LHS, Value *RHS) {
12461db9f3b2SDimitry Andric   Instruction *LHSInst = dyn_cast<Instruction>(LHS);
12471db9f3b2SDimitry Andric   Instruction *RHSInst = dyn_cast<Instruction>(RHS);
12481db9f3b2SDimitry Andric   if (!LHSInst || !RHSInst || LHSInst->getOpcode() != RHSInst->getOpcode())
12491db9f3b2SDimitry Andric     return std::nullopt;
12501db9f3b2SDimitry Andric   switch (LHSInst->getOpcode()) {
12511db9f3b2SDimitry Andric   case Instruction::PHI:
12521db9f3b2SDimitry Andric     return matchSymmetricPhiNodesPair(cast<PHINode>(LHS), cast<PHINode>(RHS));
12531db9f3b2SDimitry Andric   case Instruction::Select: {
12541db9f3b2SDimitry Andric     Value *Cond = LHSInst->getOperand(0);
12551db9f3b2SDimitry Andric     Value *TrueVal = LHSInst->getOperand(1);
12561db9f3b2SDimitry Andric     Value *FalseVal = LHSInst->getOperand(2);
12571db9f3b2SDimitry Andric     if (Cond == RHSInst->getOperand(0) && TrueVal == RHSInst->getOperand(2) &&
12581db9f3b2SDimitry Andric         FalseVal == RHSInst->getOperand(1))
12591db9f3b2SDimitry Andric       return std::pair(TrueVal, FalseVal);
12601db9f3b2SDimitry Andric     return std::nullopt;
1261cb14a3feSDimitry Andric   }
12621db9f3b2SDimitry Andric   case Instruction::Call: {
12631db9f3b2SDimitry Andric     // Match min(a, b) and max(a, b)
12641db9f3b2SDimitry Andric     MinMaxIntrinsic *LHSMinMax = dyn_cast<MinMaxIntrinsic>(LHSInst);
12651db9f3b2SDimitry Andric     MinMaxIntrinsic *RHSMinMax = dyn_cast<MinMaxIntrinsic>(RHSInst);
12661db9f3b2SDimitry Andric     if (LHSMinMax && RHSMinMax &&
12671db9f3b2SDimitry Andric         LHSMinMax->getPredicate() ==
12681db9f3b2SDimitry Andric             ICmpInst::getSwappedPredicate(RHSMinMax->getPredicate()) &&
12691db9f3b2SDimitry Andric         ((LHSMinMax->getLHS() == RHSMinMax->getLHS() &&
12701db9f3b2SDimitry Andric           LHSMinMax->getRHS() == RHSMinMax->getRHS()) ||
12711db9f3b2SDimitry Andric          (LHSMinMax->getLHS() == RHSMinMax->getRHS() &&
12721db9f3b2SDimitry Andric           LHSMinMax->getRHS() == RHSMinMax->getLHS())))
12731db9f3b2SDimitry Andric       return std::pair(LHSMinMax->getLHS(), LHSMinMax->getRHS());
12741db9f3b2SDimitry Andric     return std::nullopt;
12751db9f3b2SDimitry Andric   }
12761db9f3b2SDimitry Andric   default:
12771db9f3b2SDimitry Andric     return std::nullopt;
12781db9f3b2SDimitry Andric   }
1279cb14a3feSDimitry Andric }
1280cb14a3feSDimitry Andric 
1281e8d8bef9SDimitry Andric Value *InstCombinerImpl::SimplifySelectsFeedingBinaryOp(BinaryOperator &I,
1282e8d8bef9SDimitry Andric                                                         Value *LHS,
1283e8d8bef9SDimitry Andric                                                         Value *RHS) {
1284480093f4SDimitry Andric   Value *A, *B, *C, *D, *E, *F;
1285480093f4SDimitry Andric   bool LHSIsSelect = match(LHS, m_Select(m_Value(A), m_Value(B), m_Value(C)));
1286480093f4SDimitry Andric   bool RHSIsSelect = match(RHS, m_Select(m_Value(D), m_Value(E), m_Value(F)));
1287480093f4SDimitry Andric   if (!LHSIsSelect && !RHSIsSelect)
1288480093f4SDimitry Andric     return nullptr;
12890b57cec5SDimitry Andric 
12908bcb0991SDimitry Andric   FastMathFlags FMF;
12918bcb0991SDimitry Andric   BuilderTy::FastMathFlagGuard Guard(Builder);
12928bcb0991SDimitry Andric   if (isa<FPMathOperator>(&I)) {
12938bcb0991SDimitry Andric     FMF = I.getFastMathFlags();
12948bcb0991SDimitry Andric     Builder.setFastMathFlags(FMF);
12958bcb0991SDimitry Andric   }
12968bcb0991SDimitry Andric 
1297480093f4SDimitry Andric   Instruction::BinaryOps Opcode = I.getOpcode();
1298480093f4SDimitry Andric   SimplifyQuery Q = SQ.getWithInstruction(&I);
12990b57cec5SDimitry Andric 
1300480093f4SDimitry Andric   Value *Cond, *True = nullptr, *False = nullptr;
1301bdd1243dSDimitry Andric 
1302bdd1243dSDimitry Andric   // Special-case for add/negate combination. Replace the zero in the negation
1303bdd1243dSDimitry Andric   // with the trailing add operand:
1304bdd1243dSDimitry Andric   // (Cond ? TVal : -N) + Z --> Cond ? True : (Z - N)
1305bdd1243dSDimitry Andric   // (Cond ? -N : FVal) + Z --> Cond ? (Z - N) : False
1306bdd1243dSDimitry Andric   auto foldAddNegate = [&](Value *TVal, Value *FVal, Value *Z) -> Value * {
1307bdd1243dSDimitry Andric     // We need an 'add' and exactly 1 arm of the select to have been simplified.
1308bdd1243dSDimitry Andric     if (Opcode != Instruction::Add || (!True && !False) || (True && False))
1309bdd1243dSDimitry Andric       return nullptr;
1310bdd1243dSDimitry Andric 
1311bdd1243dSDimitry Andric     Value *N;
1312bdd1243dSDimitry Andric     if (True && match(FVal, m_Neg(m_Value(N)))) {
1313bdd1243dSDimitry Andric       Value *Sub = Builder.CreateSub(Z, N);
1314bdd1243dSDimitry Andric       return Builder.CreateSelect(Cond, True, Sub, I.getName());
1315bdd1243dSDimitry Andric     }
1316bdd1243dSDimitry Andric     if (False && match(TVal, m_Neg(m_Value(N)))) {
1317bdd1243dSDimitry Andric       Value *Sub = Builder.CreateSub(Z, N);
1318bdd1243dSDimitry Andric       return Builder.CreateSelect(Cond, Sub, False, I.getName());
1319bdd1243dSDimitry Andric     }
1320bdd1243dSDimitry Andric     return nullptr;
1321bdd1243dSDimitry Andric   };
1322bdd1243dSDimitry Andric 
1323480093f4SDimitry Andric   if (LHSIsSelect && RHSIsSelect && A == D) {
1324480093f4SDimitry Andric     // (A ? B : C) op (A ? E : F) -> A ? (B op E) : (C op F)
1325480093f4SDimitry Andric     Cond = A;
132681ad6265SDimitry Andric     True = simplifyBinOp(Opcode, B, E, FMF, Q);
132781ad6265SDimitry Andric     False = simplifyBinOp(Opcode, C, F, FMF, Q);
1328480093f4SDimitry Andric 
1329480093f4SDimitry Andric     if (LHS->hasOneUse() && RHS->hasOneUse()) {
1330480093f4SDimitry Andric       if (False && !True)
1331480093f4SDimitry Andric         True = Builder.CreateBinOp(Opcode, B, E);
1332480093f4SDimitry Andric       else if (True && !False)
1333480093f4SDimitry Andric         False = Builder.CreateBinOp(Opcode, C, F);
1334480093f4SDimitry Andric     }
1335480093f4SDimitry Andric   } else if (LHSIsSelect && LHS->hasOneUse()) {
1336480093f4SDimitry Andric     // (A ? B : C) op Y -> A ? (B op Y) : (C op Y)
1337480093f4SDimitry Andric     Cond = A;
133881ad6265SDimitry Andric     True = simplifyBinOp(Opcode, B, RHS, FMF, Q);
133981ad6265SDimitry Andric     False = simplifyBinOp(Opcode, C, RHS, FMF, Q);
1340bdd1243dSDimitry Andric     if (Value *NewSel = foldAddNegate(B, C, RHS))
1341bdd1243dSDimitry Andric       return NewSel;
1342480093f4SDimitry Andric   } else if (RHSIsSelect && RHS->hasOneUse()) {
1343480093f4SDimitry Andric     // X op (D ? E : F) -> D ? (X op E) : (X op F)
1344480093f4SDimitry Andric     Cond = D;
134581ad6265SDimitry Andric     True = simplifyBinOp(Opcode, LHS, E, FMF, Q);
134681ad6265SDimitry Andric     False = simplifyBinOp(Opcode, LHS, F, FMF, Q);
1347bdd1243dSDimitry Andric     if (Value *NewSel = foldAddNegate(E, F, LHS))
1348bdd1243dSDimitry Andric       return NewSel;
13490b57cec5SDimitry Andric   }
13500b57cec5SDimitry Andric 
1351480093f4SDimitry Andric   if (!True || !False)
1352480093f4SDimitry Andric     return nullptr;
1353480093f4SDimitry Andric 
1354480093f4SDimitry Andric   Value *SI = Builder.CreateSelect(Cond, True, False);
1355480093f4SDimitry Andric   SI->takeName(&I);
13560b57cec5SDimitry Andric   return SI;
13570b57cec5SDimitry Andric }
13580b57cec5SDimitry Andric 
1359e8d8bef9SDimitry Andric /// Freely adapt every user of V as-if V was changed to !V.
1360e8d8bef9SDimitry Andric /// WARNING: only if canFreelyInvertAllUsersOf() said this can be done.
1361bdd1243dSDimitry Andric void InstCombinerImpl::freelyInvertAllUsersOf(Value *I, Value *IgnoredUser) {
136206c3fb27SDimitry Andric   assert(!isa<Constant>(I) && "Shouldn't invert users of constant");
1363bdd1243dSDimitry Andric   for (User *U : make_early_inc_range(I->users())) {
1364bdd1243dSDimitry Andric     if (U == IgnoredUser)
1365bdd1243dSDimitry Andric       continue; // Don't consider this user.
1366e8d8bef9SDimitry Andric     switch (cast<Instruction>(U)->getOpcode()) {
1367e8d8bef9SDimitry Andric     case Instruction::Select: {
1368e8d8bef9SDimitry Andric       auto *SI = cast<SelectInst>(U);
1369e8d8bef9SDimitry Andric       SI->swapValues();
1370e8d8bef9SDimitry Andric       SI->swapProfMetadata();
1371e8d8bef9SDimitry Andric       break;
1372e8d8bef9SDimitry Andric     }
1373*0fca6ea1SDimitry Andric     case Instruction::Br: {
1374*0fca6ea1SDimitry Andric       BranchInst *BI = cast<BranchInst>(U);
1375*0fca6ea1SDimitry Andric       BI->swapSuccessors(); // swaps prof metadata too
1376*0fca6ea1SDimitry Andric       if (BPI)
1377*0fca6ea1SDimitry Andric         BPI->swapSuccEdgesProbabilities(BI->getParent());
1378e8d8bef9SDimitry Andric       break;
1379*0fca6ea1SDimitry Andric     }
1380e8d8bef9SDimitry Andric     case Instruction::Xor:
1381e8d8bef9SDimitry Andric       replaceInstUsesWith(cast<Instruction>(*U), I);
13825f757f3fSDimitry Andric       // Add to worklist for DCE.
13835f757f3fSDimitry Andric       addToWorklist(cast<Instruction>(U));
1384e8d8bef9SDimitry Andric       break;
1385e8d8bef9SDimitry Andric     default:
1386e8d8bef9SDimitry Andric       llvm_unreachable("Got unexpected user - out of sync with "
1387e8d8bef9SDimitry Andric                        "canFreelyInvertAllUsersOf() ?");
1388e8d8bef9SDimitry Andric     }
1389e8d8bef9SDimitry Andric   }
1390e8d8bef9SDimitry Andric }
1391e8d8bef9SDimitry Andric 
13920b57cec5SDimitry Andric /// Given a 'sub' instruction, return the RHS of the instruction if the LHS is a
13930b57cec5SDimitry Andric /// constant zero (which is the 'negate' form).
1394e8d8bef9SDimitry Andric Value *InstCombinerImpl::dyn_castNegVal(Value *V) const {
13950b57cec5SDimitry Andric   Value *NegV;
13960b57cec5SDimitry Andric   if (match(V, m_Neg(m_Value(NegV))))
13970b57cec5SDimitry Andric     return NegV;
13980b57cec5SDimitry Andric 
13990b57cec5SDimitry Andric   // Constants can be considered to be negated values if they can be folded.
14000b57cec5SDimitry Andric   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
14010b57cec5SDimitry Andric     return ConstantExpr::getNeg(C);
14020b57cec5SDimitry Andric 
14030b57cec5SDimitry Andric   if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V))
14040b57cec5SDimitry Andric     if (C->getType()->getElementType()->isIntegerTy())
14050b57cec5SDimitry Andric       return ConstantExpr::getNeg(C);
14060b57cec5SDimitry Andric 
14070b57cec5SDimitry Andric   if (ConstantVector *CV = dyn_cast<ConstantVector>(V)) {
14080b57cec5SDimitry Andric     for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
14090b57cec5SDimitry Andric       Constant *Elt = CV->getAggregateElement(i);
14100b57cec5SDimitry Andric       if (!Elt)
14110b57cec5SDimitry Andric         return nullptr;
14120b57cec5SDimitry Andric 
14130b57cec5SDimitry Andric       if (isa<UndefValue>(Elt))
14140b57cec5SDimitry Andric         continue;
14150b57cec5SDimitry Andric 
14160b57cec5SDimitry Andric       if (!isa<ConstantInt>(Elt))
14170b57cec5SDimitry Andric         return nullptr;
14180b57cec5SDimitry Andric     }
14190b57cec5SDimitry Andric     return ConstantExpr::getNeg(CV);
14200b57cec5SDimitry Andric   }
14210b57cec5SDimitry Andric 
1422fe6060f1SDimitry Andric   // Negate integer vector splats.
1423fe6060f1SDimitry Andric   if (auto *CV = dyn_cast<Constant>(V))
1424fe6060f1SDimitry Andric     if (CV->getType()->isVectorTy() &&
1425fe6060f1SDimitry Andric         CV->getType()->getScalarType()->isIntegerTy() && CV->getSplatValue())
1426fe6060f1SDimitry Andric       return ConstantExpr::getNeg(CV);
1427fe6060f1SDimitry Andric 
14280b57cec5SDimitry Andric   return nullptr;
14290b57cec5SDimitry Andric }
14300b57cec5SDimitry Andric 
1431*0fca6ea1SDimitry Andric // Try to fold:
1432*0fca6ea1SDimitry Andric //    1) (fp_binop ({s|u}itofp x), ({s|u}itofp y))
1433*0fca6ea1SDimitry Andric //        -> ({s|u}itofp (int_binop x, y))
1434*0fca6ea1SDimitry Andric //    2) (fp_binop ({s|u}itofp x), FpC)
1435*0fca6ea1SDimitry Andric //        -> ({s|u}itofp (int_binop x, (fpto{s|u}i FpC)))
1436*0fca6ea1SDimitry Andric //
1437*0fca6ea1SDimitry Andric // Assuming the sign of the cast for x/y is `OpsFromSigned`.
1438*0fca6ea1SDimitry Andric Instruction *InstCombinerImpl::foldFBinOpOfIntCastsFromSign(
1439*0fca6ea1SDimitry Andric     BinaryOperator &BO, bool OpsFromSigned, std::array<Value *, 2> IntOps,
1440*0fca6ea1SDimitry Andric     Constant *Op1FpC, SmallVectorImpl<WithCache<const Value *>> &OpsKnown) {
1441*0fca6ea1SDimitry Andric 
1442*0fca6ea1SDimitry Andric   Type *FPTy = BO.getType();
1443*0fca6ea1SDimitry Andric   Type *IntTy = IntOps[0]->getType();
1444*0fca6ea1SDimitry Andric 
1445*0fca6ea1SDimitry Andric   unsigned IntSz = IntTy->getScalarSizeInBits();
1446*0fca6ea1SDimitry Andric   // This is the maximum number of inuse bits by the integer where the int -> fp
1447*0fca6ea1SDimitry Andric   // casts are exact.
1448*0fca6ea1SDimitry Andric   unsigned MaxRepresentableBits =
1449*0fca6ea1SDimitry Andric       APFloat::semanticsPrecision(FPTy->getScalarType()->getFltSemantics());
1450*0fca6ea1SDimitry Andric 
1451*0fca6ea1SDimitry Andric   // Preserve known number of leading bits. This can allow us to trivial nsw/nuw
1452*0fca6ea1SDimitry Andric   // checks later on.
1453*0fca6ea1SDimitry Andric   unsigned NumUsedLeadingBits[2] = {IntSz, IntSz};
1454*0fca6ea1SDimitry Andric 
1455*0fca6ea1SDimitry Andric   // NB: This only comes up if OpsFromSigned is true, so there is no need to
1456*0fca6ea1SDimitry Andric   // cache if between calls to `foldFBinOpOfIntCastsFromSign`.
1457*0fca6ea1SDimitry Andric   auto IsNonZero = [&](unsigned OpNo) -> bool {
1458*0fca6ea1SDimitry Andric     if (OpsKnown[OpNo].hasKnownBits() &&
1459*0fca6ea1SDimitry Andric         OpsKnown[OpNo].getKnownBits(SQ).isNonZero())
1460*0fca6ea1SDimitry Andric       return true;
1461*0fca6ea1SDimitry Andric     return isKnownNonZero(IntOps[OpNo], SQ);
1462*0fca6ea1SDimitry Andric   };
1463*0fca6ea1SDimitry Andric 
1464*0fca6ea1SDimitry Andric   auto IsNonNeg = [&](unsigned OpNo) -> bool {
1465*0fca6ea1SDimitry Andric     // NB: This matches the impl in ValueTracking, we just try to use cached
1466*0fca6ea1SDimitry Andric     // knownbits here. If we ever start supporting WithCache for
1467*0fca6ea1SDimitry Andric     // `isKnownNonNegative`, change this to an explicit call.
1468*0fca6ea1SDimitry Andric     return OpsKnown[OpNo].getKnownBits(SQ).isNonNegative();
1469*0fca6ea1SDimitry Andric   };
1470*0fca6ea1SDimitry Andric 
1471*0fca6ea1SDimitry Andric   // Check if we know for certain that ({s|u}itofp op) is exact.
1472*0fca6ea1SDimitry Andric   auto IsValidPromotion = [&](unsigned OpNo) -> bool {
1473*0fca6ea1SDimitry Andric     // Can we treat this operand as the desired sign?
1474*0fca6ea1SDimitry Andric     if (OpsFromSigned != isa<SIToFPInst>(BO.getOperand(OpNo)) &&
1475*0fca6ea1SDimitry Andric         !IsNonNeg(OpNo))
1476*0fca6ea1SDimitry Andric       return false;
1477*0fca6ea1SDimitry Andric 
1478*0fca6ea1SDimitry Andric     // If fp precision >= bitwidth(op) then its exact.
1479*0fca6ea1SDimitry Andric     // NB: This is slightly conservative for `sitofp`. For signed conversion, we
1480*0fca6ea1SDimitry Andric     // can handle `MaxRepresentableBits == IntSz - 1` as the sign bit will be
1481*0fca6ea1SDimitry Andric     // handled specially. We can't, however, increase the bound arbitrarily for
1482*0fca6ea1SDimitry Andric     // `sitofp` as for larger sizes, it won't sign extend.
1483*0fca6ea1SDimitry Andric     if (MaxRepresentableBits < IntSz) {
1484*0fca6ea1SDimitry Andric       // Otherwise if its signed cast check that fp precisions >= bitwidth(op) -
1485*0fca6ea1SDimitry Andric       // numSignBits(op).
1486*0fca6ea1SDimitry Andric       // TODO: If we add support for `WithCache` in `ComputeNumSignBits`, change
1487*0fca6ea1SDimitry Andric       // `IntOps[OpNo]` arguments to `KnownOps[OpNo]`.
1488*0fca6ea1SDimitry Andric       if (OpsFromSigned)
1489*0fca6ea1SDimitry Andric         NumUsedLeadingBits[OpNo] = IntSz - ComputeNumSignBits(IntOps[OpNo]);
1490*0fca6ea1SDimitry Andric       // Finally for unsigned check that fp precision >= bitwidth(op) -
1491*0fca6ea1SDimitry Andric       // numLeadingZeros(op).
1492*0fca6ea1SDimitry Andric       else {
1493*0fca6ea1SDimitry Andric         NumUsedLeadingBits[OpNo] =
1494*0fca6ea1SDimitry Andric             IntSz - OpsKnown[OpNo].getKnownBits(SQ).countMinLeadingZeros();
1495*0fca6ea1SDimitry Andric       }
1496*0fca6ea1SDimitry Andric     }
1497*0fca6ea1SDimitry Andric     // NB: We could also check if op is known to be a power of 2 or zero (which
1498*0fca6ea1SDimitry Andric     // will always be representable). Its unlikely, however, that is we are
1499*0fca6ea1SDimitry Andric     // unable to bound op in any way we will be able to pass the overflow checks
1500*0fca6ea1SDimitry Andric     // later on.
1501*0fca6ea1SDimitry Andric 
1502*0fca6ea1SDimitry Andric     if (MaxRepresentableBits < NumUsedLeadingBits[OpNo])
1503*0fca6ea1SDimitry Andric       return false;
1504*0fca6ea1SDimitry Andric     // Signed + Mul also requires that op is non-zero to avoid -0 cases.
1505*0fca6ea1SDimitry Andric     return !OpsFromSigned || BO.getOpcode() != Instruction::FMul ||
1506*0fca6ea1SDimitry Andric            IsNonZero(OpNo);
1507*0fca6ea1SDimitry Andric   };
1508*0fca6ea1SDimitry Andric 
1509*0fca6ea1SDimitry Andric   // If we have a constant rhs, see if we can losslessly convert it to an int.
1510*0fca6ea1SDimitry Andric   if (Op1FpC != nullptr) {
1511*0fca6ea1SDimitry Andric     // Signed + Mul req non-zero
1512*0fca6ea1SDimitry Andric     if (OpsFromSigned && BO.getOpcode() == Instruction::FMul &&
1513*0fca6ea1SDimitry Andric         !match(Op1FpC, m_NonZeroFP()))
1514*0fca6ea1SDimitry Andric       return nullptr;
1515*0fca6ea1SDimitry Andric 
1516*0fca6ea1SDimitry Andric     Constant *Op1IntC = ConstantFoldCastOperand(
1517*0fca6ea1SDimitry Andric         OpsFromSigned ? Instruction::FPToSI : Instruction::FPToUI, Op1FpC,
1518*0fca6ea1SDimitry Andric         IntTy, DL);
1519*0fca6ea1SDimitry Andric     if (Op1IntC == nullptr)
1520*0fca6ea1SDimitry Andric       return nullptr;
1521*0fca6ea1SDimitry Andric     if (ConstantFoldCastOperand(OpsFromSigned ? Instruction::SIToFP
1522*0fca6ea1SDimitry Andric                                               : Instruction::UIToFP,
1523*0fca6ea1SDimitry Andric                                 Op1IntC, FPTy, DL) != Op1FpC)
1524*0fca6ea1SDimitry Andric       return nullptr;
1525*0fca6ea1SDimitry Andric 
1526*0fca6ea1SDimitry Andric     // First try to keep sign of cast the same.
1527*0fca6ea1SDimitry Andric     IntOps[1] = Op1IntC;
1528*0fca6ea1SDimitry Andric   }
1529*0fca6ea1SDimitry Andric 
1530*0fca6ea1SDimitry Andric   // Ensure lhs/rhs integer types match.
1531*0fca6ea1SDimitry Andric   if (IntTy != IntOps[1]->getType())
1532*0fca6ea1SDimitry Andric     return nullptr;
1533*0fca6ea1SDimitry Andric 
1534*0fca6ea1SDimitry Andric   if (Op1FpC == nullptr) {
1535*0fca6ea1SDimitry Andric     if (!IsValidPromotion(1))
1536*0fca6ea1SDimitry Andric       return nullptr;
1537*0fca6ea1SDimitry Andric   }
1538*0fca6ea1SDimitry Andric   if (!IsValidPromotion(0))
1539*0fca6ea1SDimitry Andric     return nullptr;
1540*0fca6ea1SDimitry Andric 
1541*0fca6ea1SDimitry Andric   // Final we check if the integer version of the binop will not overflow.
1542*0fca6ea1SDimitry Andric   BinaryOperator::BinaryOps IntOpc;
1543*0fca6ea1SDimitry Andric   // Because of the precision check, we can often rule out overflows.
1544*0fca6ea1SDimitry Andric   bool NeedsOverflowCheck = true;
1545*0fca6ea1SDimitry Andric   // Try to conservatively rule out overflow based on the already done precision
1546*0fca6ea1SDimitry Andric   // checks.
1547*0fca6ea1SDimitry Andric   unsigned OverflowMaxOutputBits = OpsFromSigned ? 2 : 1;
1548*0fca6ea1SDimitry Andric   unsigned OverflowMaxCurBits =
1549*0fca6ea1SDimitry Andric       std::max(NumUsedLeadingBits[0], NumUsedLeadingBits[1]);
1550*0fca6ea1SDimitry Andric   bool OutputSigned = OpsFromSigned;
1551*0fca6ea1SDimitry Andric   switch (BO.getOpcode()) {
1552*0fca6ea1SDimitry Andric   case Instruction::FAdd:
1553*0fca6ea1SDimitry Andric     IntOpc = Instruction::Add;
1554*0fca6ea1SDimitry Andric     OverflowMaxOutputBits += OverflowMaxCurBits;
1555*0fca6ea1SDimitry Andric     break;
1556*0fca6ea1SDimitry Andric   case Instruction::FSub:
1557*0fca6ea1SDimitry Andric     IntOpc = Instruction::Sub;
1558*0fca6ea1SDimitry Andric     OverflowMaxOutputBits += OverflowMaxCurBits;
1559*0fca6ea1SDimitry Andric     break;
1560*0fca6ea1SDimitry Andric   case Instruction::FMul:
1561*0fca6ea1SDimitry Andric     IntOpc = Instruction::Mul;
1562*0fca6ea1SDimitry Andric     OverflowMaxOutputBits += OverflowMaxCurBits * 2;
1563*0fca6ea1SDimitry Andric     break;
1564*0fca6ea1SDimitry Andric   default:
1565*0fca6ea1SDimitry Andric     llvm_unreachable("Unsupported binop");
1566*0fca6ea1SDimitry Andric   }
1567*0fca6ea1SDimitry Andric   // The precision check may have already ruled out overflow.
1568*0fca6ea1SDimitry Andric   if (OverflowMaxOutputBits < IntSz) {
1569*0fca6ea1SDimitry Andric     NeedsOverflowCheck = false;
1570*0fca6ea1SDimitry Andric     // We can bound unsigned overflow from sub to in range signed value (this is
1571*0fca6ea1SDimitry Andric     // what allows us to avoid the overflow check for sub).
1572*0fca6ea1SDimitry Andric     if (IntOpc == Instruction::Sub)
1573*0fca6ea1SDimitry Andric       OutputSigned = true;
1574*0fca6ea1SDimitry Andric   }
1575*0fca6ea1SDimitry Andric 
1576*0fca6ea1SDimitry Andric   // Precision check did not rule out overflow, so need to check.
1577*0fca6ea1SDimitry Andric   // TODO: If we add support for `WithCache` in `willNotOverflow`, change
1578*0fca6ea1SDimitry Andric   // `IntOps[...]` arguments to `KnownOps[...]`.
1579*0fca6ea1SDimitry Andric   if (NeedsOverflowCheck &&
1580*0fca6ea1SDimitry Andric       !willNotOverflow(IntOpc, IntOps[0], IntOps[1], BO, OutputSigned))
1581*0fca6ea1SDimitry Andric     return nullptr;
1582*0fca6ea1SDimitry Andric 
1583*0fca6ea1SDimitry Andric   Value *IntBinOp = Builder.CreateBinOp(IntOpc, IntOps[0], IntOps[1]);
1584*0fca6ea1SDimitry Andric   if (auto *IntBO = dyn_cast<BinaryOperator>(IntBinOp)) {
1585*0fca6ea1SDimitry Andric     IntBO->setHasNoSignedWrap(OutputSigned);
1586*0fca6ea1SDimitry Andric     IntBO->setHasNoUnsignedWrap(!OutputSigned);
1587*0fca6ea1SDimitry Andric   }
1588*0fca6ea1SDimitry Andric   if (OutputSigned)
1589*0fca6ea1SDimitry Andric     return new SIToFPInst(IntBinOp, FPTy);
1590*0fca6ea1SDimitry Andric   return new UIToFPInst(IntBinOp, FPTy);
1591*0fca6ea1SDimitry Andric }
1592*0fca6ea1SDimitry Andric 
1593*0fca6ea1SDimitry Andric // Try to fold:
1594*0fca6ea1SDimitry Andric //    1) (fp_binop ({s|u}itofp x), ({s|u}itofp y))
1595*0fca6ea1SDimitry Andric //        -> ({s|u}itofp (int_binop x, y))
1596*0fca6ea1SDimitry Andric //    2) (fp_binop ({s|u}itofp x), FpC)
1597*0fca6ea1SDimitry Andric //        -> ({s|u}itofp (int_binop x, (fpto{s|u}i FpC)))
1598*0fca6ea1SDimitry Andric Instruction *InstCombinerImpl::foldFBinOpOfIntCasts(BinaryOperator &BO) {
1599*0fca6ea1SDimitry Andric   std::array<Value *, 2> IntOps = {nullptr, nullptr};
1600*0fca6ea1SDimitry Andric   Constant *Op1FpC = nullptr;
1601*0fca6ea1SDimitry Andric   // Check for:
1602*0fca6ea1SDimitry Andric   //    1) (binop ({s|u}itofp x), ({s|u}itofp y))
1603*0fca6ea1SDimitry Andric   //    2) (binop ({s|u}itofp x), FpC)
1604*0fca6ea1SDimitry Andric   if (!match(BO.getOperand(0), m_SIToFP(m_Value(IntOps[0]))) &&
1605*0fca6ea1SDimitry Andric       !match(BO.getOperand(0), m_UIToFP(m_Value(IntOps[0]))))
1606*0fca6ea1SDimitry Andric     return nullptr;
1607*0fca6ea1SDimitry Andric 
1608*0fca6ea1SDimitry Andric   if (!match(BO.getOperand(1), m_Constant(Op1FpC)) &&
1609*0fca6ea1SDimitry Andric       !match(BO.getOperand(1), m_SIToFP(m_Value(IntOps[1]))) &&
1610*0fca6ea1SDimitry Andric       !match(BO.getOperand(1), m_UIToFP(m_Value(IntOps[1]))))
1611*0fca6ea1SDimitry Andric     return nullptr;
1612*0fca6ea1SDimitry Andric 
1613*0fca6ea1SDimitry Andric   // Cache KnownBits a bit to potentially save some analysis.
1614*0fca6ea1SDimitry Andric   SmallVector<WithCache<const Value *>, 2> OpsKnown = {IntOps[0], IntOps[1]};
1615*0fca6ea1SDimitry Andric 
1616*0fca6ea1SDimitry Andric   // Try treating x/y as coming from both `uitofp` and `sitofp`. There are
1617*0fca6ea1SDimitry Andric   // different constraints depending on the sign of the cast.
1618*0fca6ea1SDimitry Andric   // NB: `(uitofp nneg X)` == `(sitofp nneg X)`.
1619*0fca6ea1SDimitry Andric   if (Instruction *R = foldFBinOpOfIntCastsFromSign(BO, /*OpsFromSigned=*/false,
1620*0fca6ea1SDimitry Andric                                                     IntOps, Op1FpC, OpsKnown))
1621*0fca6ea1SDimitry Andric     return R;
1622*0fca6ea1SDimitry Andric   return foldFBinOpOfIntCastsFromSign(BO, /*OpsFromSigned=*/true, IntOps,
1623*0fca6ea1SDimitry Andric                                       Op1FpC, OpsKnown);
1624*0fca6ea1SDimitry Andric }
1625*0fca6ea1SDimitry Andric 
16264824e7fdSDimitry Andric /// A binop with a constant operand and a sign-extended boolean operand may be
16274824e7fdSDimitry Andric /// converted into a select of constants by applying the binary operation to
16284824e7fdSDimitry Andric /// the constant with the two possible values of the extended boolean (0 or -1).
16294824e7fdSDimitry Andric Instruction *InstCombinerImpl::foldBinopOfSextBoolToSelect(BinaryOperator &BO) {
16304824e7fdSDimitry Andric   // TODO: Handle non-commutative binop (constant is operand 0).
16314824e7fdSDimitry Andric   // TODO: Handle zext.
16324824e7fdSDimitry Andric   // TODO: Peek through 'not' of cast.
16334824e7fdSDimitry Andric   Value *BO0 = BO.getOperand(0);
16344824e7fdSDimitry Andric   Value *BO1 = BO.getOperand(1);
16354824e7fdSDimitry Andric   Value *X;
16364824e7fdSDimitry Andric   Constant *C;
16374824e7fdSDimitry Andric   if (!match(BO0, m_SExt(m_Value(X))) || !match(BO1, m_ImmConstant(C)) ||
16384824e7fdSDimitry Andric       !X->getType()->isIntOrIntVectorTy(1))
16394824e7fdSDimitry Andric     return nullptr;
16404824e7fdSDimitry Andric 
16414824e7fdSDimitry Andric   // bo (sext i1 X), C --> select X, (bo -1, C), (bo 0, C)
16424824e7fdSDimitry Andric   Constant *Ones = ConstantInt::getAllOnesValue(BO.getType());
16434824e7fdSDimitry Andric   Constant *Zero = ConstantInt::getNullValue(BO.getType());
164481ad6265SDimitry Andric   Value *TVal = Builder.CreateBinOp(BO.getOpcode(), Ones, C);
164581ad6265SDimitry Andric   Value *FVal = Builder.CreateBinOp(BO.getOpcode(), Zero, C);
16464824e7fdSDimitry Andric   return SelectInst::Create(X, TVal, FVal);
16474824e7fdSDimitry Andric }
16484824e7fdSDimitry Andric 
164906c3fb27SDimitry Andric static Constant *constantFoldOperationIntoSelectOperand(Instruction &I,
165006c3fb27SDimitry Andric                                                         SelectInst *SI,
165106c3fb27SDimitry Andric                                                         bool IsTrueArm) {
1652fcaf7f86SDimitry Andric   SmallVector<Constant *> ConstOps;
1653fcaf7f86SDimitry Andric   for (Value *Op : I.operands()) {
165406c3fb27SDimitry Andric     CmpInst::Predicate Pred;
165506c3fb27SDimitry Andric     Constant *C = nullptr;
165606c3fb27SDimitry Andric     if (Op == SI) {
165706c3fb27SDimitry Andric       C = dyn_cast<Constant>(IsTrueArm ? SI->getTrueValue()
165806c3fb27SDimitry Andric                                        : SI->getFalseValue());
165906c3fb27SDimitry Andric     } else if (match(SI->getCondition(),
166006c3fb27SDimitry Andric                      m_ICmp(Pred, m_Specific(Op), m_Constant(C))) &&
166106c3fb27SDimitry Andric                Pred == (IsTrueArm ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE) &&
166206c3fb27SDimitry Andric                isGuaranteedNotToBeUndefOrPoison(C)) {
166306c3fb27SDimitry Andric       // Pass
166406c3fb27SDimitry Andric     } else {
166506c3fb27SDimitry Andric       C = dyn_cast<Constant>(Op);
1666fcaf7f86SDimitry Andric     }
166706c3fb27SDimitry Andric     if (C == nullptr)
166806c3fb27SDimitry Andric       return nullptr;
166906c3fb27SDimitry Andric 
167006c3fb27SDimitry Andric     ConstOps.push_back(C);
167106c3fb27SDimitry Andric   }
167206c3fb27SDimitry Andric 
1673*0fca6ea1SDimitry Andric   return ConstantFoldInstOperands(&I, ConstOps, I.getDataLayout());
1674fcaf7f86SDimitry Andric }
1675fcaf7f86SDimitry Andric 
167606c3fb27SDimitry Andric static Value *foldOperationIntoSelectOperand(Instruction &I, SelectInst *SI,
167706c3fb27SDimitry Andric                                              Value *NewOp, InstCombiner &IC) {
167806c3fb27SDimitry Andric   Instruction *Clone = I.clone();
167906c3fb27SDimitry Andric   Clone->replaceUsesOfWith(SI, NewOp);
1680439352acSDimitry Andric   Clone->dropUBImplyingAttrsAndMetadata();
16815f757f3fSDimitry Andric   IC.InsertNewInstBefore(Clone, SI->getIterator());
168206c3fb27SDimitry Andric   return Clone;
16830b57cec5SDimitry Andric }
16840b57cec5SDimitry Andric 
168581ad6265SDimitry Andric Instruction *InstCombinerImpl::FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
168681ad6265SDimitry Andric                                                 bool FoldWithMultiUse) {
168781ad6265SDimitry Andric   // Don't modify shared select instructions unless set FoldWithMultiUse
168881ad6265SDimitry Andric   if (!SI->hasOneUse() && !FoldWithMultiUse)
16890b57cec5SDimitry Andric     return nullptr;
16900b57cec5SDimitry Andric 
16910b57cec5SDimitry Andric   Value *TV = SI->getTrueValue();
16920b57cec5SDimitry Andric   Value *FV = SI->getFalseValue();
16930b57cec5SDimitry Andric   if (!(isa<Constant>(TV) || isa<Constant>(FV)))
16940b57cec5SDimitry Andric     return nullptr;
16950b57cec5SDimitry Andric 
16960b57cec5SDimitry Andric   // Bool selects with constant operands can be folded to logical ops.
16970b57cec5SDimitry Andric   if (SI->getType()->isIntOrIntVectorTy(1))
16980b57cec5SDimitry Andric     return nullptr;
16990b57cec5SDimitry Andric 
17005f757f3fSDimitry Andric   // Test if a FCmpInst instruction is used exclusively by a select as
17015f757f3fSDimitry Andric   // part of a minimum or maximum operation. If so, refrain from doing
17025f757f3fSDimitry Andric   // any other folding. This helps out other analyses which understand
17035f757f3fSDimitry Andric   // non-obfuscated minimum and maximum idioms. And in this case, at
17045f757f3fSDimitry Andric   // least one of the comparison operands has at least one user besides
17055f757f3fSDimitry Andric   // the compare (the select), which would often largely negate the
17065f757f3fSDimitry Andric   // benefit of folding anyway.
17075f757f3fSDimitry Andric   if (auto *CI = dyn_cast<FCmpInst>(SI->getCondition())) {
17085f757f3fSDimitry Andric     if (CI->hasOneUse()) {
17095f757f3fSDimitry Andric       Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
17105f757f3fSDimitry Andric       if ((TV == Op0 && FV == Op1) || (FV == Op0 && TV == Op1))
17115f757f3fSDimitry Andric         return nullptr;
17125f757f3fSDimitry Andric     }
17135f757f3fSDimitry Andric   }
17145f757f3fSDimitry Andric 
1715fcaf7f86SDimitry Andric   // Make sure that one of the select arms constant folds successfully.
171606c3fb27SDimitry Andric   Value *NewTV = constantFoldOperationIntoSelectOperand(Op, SI, /*IsTrueArm*/ true);
171706c3fb27SDimitry Andric   Value *NewFV = constantFoldOperationIntoSelectOperand(Op, SI, /*IsTrueArm*/ false);
1718fcaf7f86SDimitry Andric   if (!NewTV && !NewFV)
1719fcaf7f86SDimitry Andric     return nullptr;
1720fcaf7f86SDimitry Andric 
1721fcaf7f86SDimitry Andric   // Create an instruction for the arm that did not fold.
1722fcaf7f86SDimitry Andric   if (!NewTV)
172306c3fb27SDimitry Andric     NewTV = foldOperationIntoSelectOperand(Op, SI, TV, *this);
1724fcaf7f86SDimitry Andric   if (!NewFV)
172506c3fb27SDimitry Andric     NewFV = foldOperationIntoSelectOperand(Op, SI, FV, *this);
17260b57cec5SDimitry Andric   return SelectInst::Create(SI->getCondition(), NewTV, NewFV, "", nullptr, SI);
17270b57cec5SDimitry Andric }
17280b57cec5SDimitry Andric 
17295f757f3fSDimitry Andric static Value *simplifyInstructionWithPHI(Instruction &I, PHINode *PN,
17305f757f3fSDimitry Andric                                          Value *InValue, BasicBlock *InBB,
17315f757f3fSDimitry Andric                                          const DataLayout &DL,
17325f757f3fSDimitry Andric                                          const SimplifyQuery SQ) {
17335f757f3fSDimitry Andric   // NB: It is a precondition of this transform that the operands be
17345f757f3fSDimitry Andric   // phi translatable! This is usually trivially satisfied by limiting it
17355f757f3fSDimitry Andric   // to constant ops, and for selects we do a more sophisticated check.
17365f757f3fSDimitry Andric   SmallVector<Value *> Ops;
17375f757f3fSDimitry Andric   for (Value *Op : I.operands()) {
17385f757f3fSDimitry Andric     if (Op == PN)
17395f757f3fSDimitry Andric       Ops.push_back(InValue);
17405f757f3fSDimitry Andric     else
17415f757f3fSDimitry Andric       Ops.push_back(Op->DoPHITranslation(PN->getParent(), InBB));
17425f757f3fSDimitry Andric   }
17435f757f3fSDimitry Andric 
17445f757f3fSDimitry Andric   // Don't consider the simplification successful if we get back a constant
17455f757f3fSDimitry Andric   // expression. That's just an instruction in hiding.
17465f757f3fSDimitry Andric   // Also reject the case where we simplify back to the phi node. We wouldn't
17475f757f3fSDimitry Andric   // be able to remove it in that case.
17485f757f3fSDimitry Andric   Value *NewVal = simplifyInstructionWithOperands(
17495f757f3fSDimitry Andric       &I, Ops, SQ.getWithInstruction(InBB->getTerminator()));
17505f757f3fSDimitry Andric   if (NewVal && NewVal != PN && !match(NewVal, m_ConstantExpr()))
17515f757f3fSDimitry Andric     return NewVal;
17525f757f3fSDimitry Andric 
17535f757f3fSDimitry Andric   // Check if incoming PHI value can be replaced with constant
17545f757f3fSDimitry Andric   // based on implied condition.
17555f757f3fSDimitry Andric   BranchInst *TerminatorBI = dyn_cast<BranchInst>(InBB->getTerminator());
17565f757f3fSDimitry Andric   const ICmpInst *ICmp = dyn_cast<ICmpInst>(&I);
17575f757f3fSDimitry Andric   if (TerminatorBI && TerminatorBI->isConditional() &&
17585f757f3fSDimitry Andric       TerminatorBI->getSuccessor(0) != TerminatorBI->getSuccessor(1) && ICmp) {
17595f757f3fSDimitry Andric     bool LHSIsTrue = TerminatorBI->getSuccessor(0) == PN->getParent();
17605f757f3fSDimitry Andric     std::optional<bool> ImpliedCond =
17615f757f3fSDimitry Andric         isImpliedCondition(TerminatorBI->getCondition(), ICmp->getPredicate(),
17625f757f3fSDimitry Andric                            Ops[0], Ops[1], DL, LHSIsTrue);
17635f757f3fSDimitry Andric     if (ImpliedCond)
17645f757f3fSDimitry Andric       return ConstantInt::getBool(I.getType(), ImpliedCond.value());
17655f757f3fSDimitry Andric   }
17665f757f3fSDimitry Andric 
17675f757f3fSDimitry Andric   return nullptr;
17685f757f3fSDimitry Andric }
17695f757f3fSDimitry Andric 
1770e8d8bef9SDimitry Andric Instruction *InstCombinerImpl::foldOpIntoPhi(Instruction &I, PHINode *PN) {
17710b57cec5SDimitry Andric   unsigned NumPHIValues = PN->getNumIncomingValues();
17720b57cec5SDimitry Andric   if (NumPHIValues == 0)
17730b57cec5SDimitry Andric     return nullptr;
17740b57cec5SDimitry Andric 
17750b57cec5SDimitry Andric   // We normally only transform phis with a single use.  However, if a PHI has
17760b57cec5SDimitry Andric   // multiple uses and they are all the same operation, we can fold *all* of the
17770b57cec5SDimitry Andric   // uses into the PHI.
17780b57cec5SDimitry Andric   if (!PN->hasOneUse()) {
17790b57cec5SDimitry Andric     // Walk the use list for the instruction, comparing them to I.
17800b57cec5SDimitry Andric     for (User *U : PN->users()) {
17810b57cec5SDimitry Andric       Instruction *UI = cast<Instruction>(U);
17820b57cec5SDimitry Andric       if (UI != &I && !I.isIdenticalTo(UI))
17830b57cec5SDimitry Andric         return nullptr;
17840b57cec5SDimitry Andric     }
17850b57cec5SDimitry Andric     // Otherwise, we can replace *all* users with the new PHI we form.
17860b57cec5SDimitry Andric   }
17870b57cec5SDimitry Andric 
1788bdd1243dSDimitry Andric   // Check to see whether the instruction can be folded into each phi operand.
1789bdd1243dSDimitry Andric   // If there is one operand that does not fold, remember the BB it is in.
1790bdd1243dSDimitry Andric   // If there is more than one or if *it* is a PHI, bail out.
1791bdd1243dSDimitry Andric   SmallVector<Value *> NewPhiValues;
1792bdd1243dSDimitry Andric   BasicBlock *NonSimplifiedBB = nullptr;
1793bdd1243dSDimitry Andric   Value *NonSimplifiedInVal = nullptr;
17940b57cec5SDimitry Andric   for (unsigned i = 0; i != NumPHIValues; ++i) {
17950b57cec5SDimitry Andric     Value *InVal = PN->getIncomingValue(i);
1796bdd1243dSDimitry Andric     BasicBlock *InBB = PN->getIncomingBlock(i);
1797bdd1243dSDimitry Andric 
17985f757f3fSDimitry Andric     if (auto *NewVal = simplifyInstructionWithPHI(I, PN, InVal, InBB, DL, SQ)) {
1799bdd1243dSDimitry Andric       NewPhiValues.push_back(NewVal);
1800349cc55cSDimitry Andric       continue;
1801bdd1243dSDimitry Andric     }
18020b57cec5SDimitry Andric 
1803bdd1243dSDimitry Andric     if (NonSimplifiedBB) return nullptr;  // More than one non-simplified value.
18040b57cec5SDimitry Andric 
1805bdd1243dSDimitry Andric     NonSimplifiedBB = InBB;
1806bdd1243dSDimitry Andric     NonSimplifiedInVal = InVal;
1807bdd1243dSDimitry Andric     NewPhiValues.push_back(nullptr);
18080b57cec5SDimitry Andric 
18090b57cec5SDimitry Andric     // If the InVal is an invoke at the end of the pred block, then we can't
18100b57cec5SDimitry Andric     // insert a computation after it without breaking the edge.
18110b57cec5SDimitry Andric     if (isa<InvokeInst>(InVal))
1812bdd1243dSDimitry Andric       if (cast<Instruction>(InVal)->getParent() == NonSimplifiedBB)
18130b57cec5SDimitry Andric         return nullptr;
18140b57cec5SDimitry Andric 
181581ad6265SDimitry Andric     // If the incoming non-constant value is reachable from the phis block,
181681ad6265SDimitry Andric     // we'll push the operation across a loop backedge. This could result in
181781ad6265SDimitry Andric     // an infinite combine loop, and is generally non-profitable (especially
181881ad6265SDimitry Andric     // if the operation was originally outside the loop).
1819bdd1243dSDimitry Andric     if (isPotentiallyReachable(PN->getParent(), NonSimplifiedBB, nullptr, &DT,
1820bdd1243dSDimitry Andric                                LI))
18210b57cec5SDimitry Andric       return nullptr;
18220b57cec5SDimitry Andric   }
18230b57cec5SDimitry Andric 
1824bdd1243dSDimitry Andric   // If there is exactly one non-simplified value, we can insert a copy of the
18250b57cec5SDimitry Andric   // operation in that block.  However, if this is a critical edge, we would be
18260b57cec5SDimitry Andric   // inserting the computation on some other paths (e.g. inside a loop).  Only
18270b57cec5SDimitry Andric   // do this if the pred block is unconditionally branching into the phi block.
1828e8d8bef9SDimitry Andric   // Also, make sure that the pred block is not dead code.
1829bdd1243dSDimitry Andric   if (NonSimplifiedBB != nullptr) {
1830bdd1243dSDimitry Andric     BranchInst *BI = dyn_cast<BranchInst>(NonSimplifiedBB->getTerminator());
1831bdd1243dSDimitry Andric     if (!BI || !BI->isUnconditional() ||
1832bdd1243dSDimitry Andric         !DT.isReachableFromEntry(NonSimplifiedBB))
1833e8d8bef9SDimitry Andric       return nullptr;
18340b57cec5SDimitry Andric   }
18350b57cec5SDimitry Andric 
18360b57cec5SDimitry Andric   // Okay, we can do the transformation: create the new PHI node.
18370b57cec5SDimitry Andric   PHINode *NewPN = PHINode::Create(I.getType(), PN->getNumIncomingValues());
18385f757f3fSDimitry Andric   InsertNewInstBefore(NewPN, PN->getIterator());
18390b57cec5SDimitry Andric   NewPN->takeName(PN);
184006c3fb27SDimitry Andric   NewPN->setDebugLoc(PN->getDebugLoc());
18410b57cec5SDimitry Andric 
18420b57cec5SDimitry Andric   // If we are going to have to insert a new computation, do so right before the
18430b57cec5SDimitry Andric   // predecessor's terminator.
1844bdd1243dSDimitry Andric   Instruction *Clone = nullptr;
1845bdd1243dSDimitry Andric   if (NonSimplifiedBB) {
1846bdd1243dSDimitry Andric     Clone = I.clone();
1847bdd1243dSDimitry Andric     for (Use &U : Clone->operands()) {
1848bdd1243dSDimitry Andric       if (U == PN)
1849bdd1243dSDimitry Andric         U = NonSimplifiedInVal;
1850bdd1243dSDimitry Andric       else
1851bdd1243dSDimitry Andric         U = U->DoPHITranslation(PN->getParent(), NonSimplifiedBB);
1852bdd1243dSDimitry Andric     }
18535f757f3fSDimitry Andric     InsertNewInstBefore(Clone, NonSimplifiedBB->getTerminator()->getIterator());
1854bdd1243dSDimitry Andric   }
18550b57cec5SDimitry Andric 
18560b57cec5SDimitry Andric   for (unsigned i = 0; i != NumPHIValues; ++i) {
1857bdd1243dSDimitry Andric     if (NewPhiValues[i])
1858bdd1243dSDimitry Andric       NewPN->addIncoming(NewPhiValues[i], PN->getIncomingBlock(i));
18590b57cec5SDimitry Andric     else
1860bdd1243dSDimitry Andric       NewPN->addIncoming(Clone, PN->getIncomingBlock(i));
18610b57cec5SDimitry Andric   }
18620b57cec5SDimitry Andric 
1863e8d8bef9SDimitry Andric   for (User *U : make_early_inc_range(PN->users())) {
1864e8d8bef9SDimitry Andric     Instruction *User = cast<Instruction>(U);
18650b57cec5SDimitry Andric     if (User == &I) continue;
18660b57cec5SDimitry Andric     replaceInstUsesWith(*User, NewPN);
18670b57cec5SDimitry Andric     eraseInstFromFunction(*User);
18680b57cec5SDimitry Andric   }
186906c3fb27SDimitry Andric 
187006c3fb27SDimitry Andric   replaceAllDbgUsesWith(const_cast<PHINode &>(*PN),
187106c3fb27SDimitry Andric                         const_cast<PHINode &>(*NewPN),
187206c3fb27SDimitry Andric                         const_cast<PHINode &>(*PN), DT);
18730b57cec5SDimitry Andric   return replaceInstUsesWith(I, NewPN);
18740b57cec5SDimitry Andric }
18750b57cec5SDimitry Andric 
187604eeddc0SDimitry Andric Instruction *InstCombinerImpl::foldBinopWithPhiOperands(BinaryOperator &BO) {
187704eeddc0SDimitry Andric   // TODO: This should be similar to the incoming values check in foldOpIntoPhi:
187804eeddc0SDimitry Andric   //       we are guarding against replicating the binop in >1 predecessor.
187904eeddc0SDimitry Andric   //       This could miss matching a phi with 2 constant incoming values.
188004eeddc0SDimitry Andric   auto *Phi0 = dyn_cast<PHINode>(BO.getOperand(0));
188104eeddc0SDimitry Andric   auto *Phi1 = dyn_cast<PHINode>(BO.getOperand(1));
188204eeddc0SDimitry Andric   if (!Phi0 || !Phi1 || !Phi0->hasOneUse() || !Phi1->hasOneUse() ||
188306c3fb27SDimitry Andric       Phi0->getNumOperands() != Phi1->getNumOperands())
188404eeddc0SDimitry Andric     return nullptr;
188504eeddc0SDimitry Andric 
188604eeddc0SDimitry Andric   // TODO: Remove the restriction for binop being in the same block as the phis.
188704eeddc0SDimitry Andric   if (BO.getParent() != Phi0->getParent() ||
188804eeddc0SDimitry Andric       BO.getParent() != Phi1->getParent())
188904eeddc0SDimitry Andric     return nullptr;
189004eeddc0SDimitry Andric 
189106c3fb27SDimitry Andric   // Fold if there is at least one specific constant value in phi0 or phi1's
189206c3fb27SDimitry Andric   // incoming values that comes from the same block and this specific constant
189306c3fb27SDimitry Andric   // value can be used to do optimization for specific binary operator.
189406c3fb27SDimitry Andric   // For example:
189506c3fb27SDimitry Andric   // %phi0 = phi i32 [0, %bb0], [%i, %bb1]
189606c3fb27SDimitry Andric   // %phi1 = phi i32 [%j, %bb0], [0, %bb1]
189706c3fb27SDimitry Andric   // %add = add i32 %phi0, %phi1
189806c3fb27SDimitry Andric   // ==>
189906c3fb27SDimitry Andric   // %add = phi i32 [%j, %bb0], [%i, %bb1]
190006c3fb27SDimitry Andric   Constant *C = ConstantExpr::getBinOpIdentity(BO.getOpcode(), BO.getType(),
190106c3fb27SDimitry Andric                                                /*AllowRHSConstant*/ false);
190206c3fb27SDimitry Andric   if (C) {
190306c3fb27SDimitry Andric     SmallVector<Value *, 4> NewIncomingValues;
190406c3fb27SDimitry Andric     auto CanFoldIncomingValuePair = [&](std::tuple<Use &, Use &> T) {
190506c3fb27SDimitry Andric       auto &Phi0Use = std::get<0>(T);
190606c3fb27SDimitry Andric       auto &Phi1Use = std::get<1>(T);
190706c3fb27SDimitry Andric       if (Phi0->getIncomingBlock(Phi0Use) != Phi1->getIncomingBlock(Phi1Use))
190806c3fb27SDimitry Andric         return false;
190906c3fb27SDimitry Andric       Value *Phi0UseV = Phi0Use.get();
191006c3fb27SDimitry Andric       Value *Phi1UseV = Phi1Use.get();
191106c3fb27SDimitry Andric       if (Phi0UseV == C)
191206c3fb27SDimitry Andric         NewIncomingValues.push_back(Phi1UseV);
191306c3fb27SDimitry Andric       else if (Phi1UseV == C)
191406c3fb27SDimitry Andric         NewIncomingValues.push_back(Phi0UseV);
191506c3fb27SDimitry Andric       else
191606c3fb27SDimitry Andric         return false;
191706c3fb27SDimitry Andric       return true;
191806c3fb27SDimitry Andric     };
191906c3fb27SDimitry Andric 
192006c3fb27SDimitry Andric     if (all_of(zip(Phi0->operands(), Phi1->operands()),
192106c3fb27SDimitry Andric                CanFoldIncomingValuePair)) {
192206c3fb27SDimitry Andric       PHINode *NewPhi =
192306c3fb27SDimitry Andric           PHINode::Create(Phi0->getType(), Phi0->getNumOperands());
192406c3fb27SDimitry Andric       assert(NewIncomingValues.size() == Phi0->getNumOperands() &&
192506c3fb27SDimitry Andric              "The number of collected incoming values should equal the number "
192606c3fb27SDimitry Andric              "of the original PHINode operands!");
192706c3fb27SDimitry Andric       for (unsigned I = 0; I < Phi0->getNumOperands(); I++)
192806c3fb27SDimitry Andric         NewPhi->addIncoming(NewIncomingValues[I], Phi0->getIncomingBlock(I));
192906c3fb27SDimitry Andric       return NewPhi;
193006c3fb27SDimitry Andric     }
193106c3fb27SDimitry Andric   }
193206c3fb27SDimitry Andric 
193306c3fb27SDimitry Andric   if (Phi0->getNumOperands() != 2 || Phi1->getNumOperands() != 2)
193406c3fb27SDimitry Andric     return nullptr;
193506c3fb27SDimitry Andric 
193604eeddc0SDimitry Andric   // Match a pair of incoming constants for one of the predecessor blocks.
193704eeddc0SDimitry Andric   BasicBlock *ConstBB, *OtherBB;
193804eeddc0SDimitry Andric   Constant *C0, *C1;
193904eeddc0SDimitry Andric   if (match(Phi0->getIncomingValue(0), m_ImmConstant(C0))) {
194004eeddc0SDimitry Andric     ConstBB = Phi0->getIncomingBlock(0);
194104eeddc0SDimitry Andric     OtherBB = Phi0->getIncomingBlock(1);
194204eeddc0SDimitry Andric   } else if (match(Phi0->getIncomingValue(1), m_ImmConstant(C0))) {
194304eeddc0SDimitry Andric     ConstBB = Phi0->getIncomingBlock(1);
194404eeddc0SDimitry Andric     OtherBB = Phi0->getIncomingBlock(0);
194504eeddc0SDimitry Andric   } else {
194604eeddc0SDimitry Andric     return nullptr;
194704eeddc0SDimitry Andric   }
194804eeddc0SDimitry Andric   if (!match(Phi1->getIncomingValueForBlock(ConstBB), m_ImmConstant(C1)))
194904eeddc0SDimitry Andric     return nullptr;
195004eeddc0SDimitry Andric 
195104eeddc0SDimitry Andric   // The block that we are hoisting to must reach here unconditionally.
195204eeddc0SDimitry Andric   // Otherwise, we could be speculatively executing an expensive or
195304eeddc0SDimitry Andric   // non-speculative op.
195404eeddc0SDimitry Andric   auto *PredBlockBranch = dyn_cast<BranchInst>(OtherBB->getTerminator());
195504eeddc0SDimitry Andric   if (!PredBlockBranch || PredBlockBranch->isConditional() ||
195604eeddc0SDimitry Andric       !DT.isReachableFromEntry(OtherBB))
195704eeddc0SDimitry Andric     return nullptr;
195804eeddc0SDimitry Andric 
195904eeddc0SDimitry Andric   // TODO: This check could be tightened to only apply to binops (div/rem) that
196004eeddc0SDimitry Andric   //       are not safe to speculatively execute. But that could allow hoisting
196104eeddc0SDimitry Andric   //       potentially expensive instructions (fdiv for example).
196204eeddc0SDimitry Andric   for (auto BBIter = BO.getParent()->begin(); &*BBIter != &BO; ++BBIter)
196304eeddc0SDimitry Andric     if (!isGuaranteedToTransferExecutionToSuccessor(&*BBIter))
196404eeddc0SDimitry Andric       return nullptr;
196504eeddc0SDimitry Andric 
1966753f127fSDimitry Andric   // Fold constants for the predecessor block with constant incoming values.
1967753f127fSDimitry Andric   Constant *NewC = ConstantFoldBinaryOpOperands(BO.getOpcode(), C0, C1, DL);
1968753f127fSDimitry Andric   if (!NewC)
1969753f127fSDimitry Andric     return nullptr;
1970753f127fSDimitry Andric 
197104eeddc0SDimitry Andric   // Make a new binop in the predecessor block with the non-constant incoming
197204eeddc0SDimitry Andric   // values.
197304eeddc0SDimitry Andric   Builder.SetInsertPoint(PredBlockBranch);
197404eeddc0SDimitry Andric   Value *NewBO = Builder.CreateBinOp(BO.getOpcode(),
197504eeddc0SDimitry Andric                                      Phi0->getIncomingValueForBlock(OtherBB),
197604eeddc0SDimitry Andric                                      Phi1->getIncomingValueForBlock(OtherBB));
197704eeddc0SDimitry Andric   if (auto *NotFoldedNewBO = dyn_cast<BinaryOperator>(NewBO))
197804eeddc0SDimitry Andric     NotFoldedNewBO->copyIRFlags(&BO);
197904eeddc0SDimitry Andric 
198004eeddc0SDimitry Andric   // Replace the binop with a phi of the new values. The old phis are dead.
198104eeddc0SDimitry Andric   PHINode *NewPhi = PHINode::Create(BO.getType(), 2);
198204eeddc0SDimitry Andric   NewPhi->addIncoming(NewBO, OtherBB);
198304eeddc0SDimitry Andric   NewPhi->addIncoming(NewC, ConstBB);
198404eeddc0SDimitry Andric   return NewPhi;
198504eeddc0SDimitry Andric }
198604eeddc0SDimitry Andric 
1987e8d8bef9SDimitry Andric Instruction *InstCombinerImpl::foldBinOpIntoSelectOrPhi(BinaryOperator &I) {
19880b57cec5SDimitry Andric   if (!isa<Constant>(I.getOperand(1)))
19890b57cec5SDimitry Andric     return nullptr;
19900b57cec5SDimitry Andric 
19910b57cec5SDimitry Andric   if (auto *Sel = dyn_cast<SelectInst>(I.getOperand(0))) {
19920b57cec5SDimitry Andric     if (Instruction *NewSel = FoldOpIntoSelect(I, Sel))
19930b57cec5SDimitry Andric       return NewSel;
19940b57cec5SDimitry Andric   } else if (auto *PN = dyn_cast<PHINode>(I.getOperand(0))) {
19950b57cec5SDimitry Andric     if (Instruction *NewPhi = foldOpIntoPhi(I, PN))
19960b57cec5SDimitry Andric       return NewPhi;
19970b57cec5SDimitry Andric   }
19980b57cec5SDimitry Andric   return nullptr;
19990b57cec5SDimitry Andric }
20000b57cec5SDimitry Andric 
20010b57cec5SDimitry Andric static bool shouldMergeGEPs(GEPOperator &GEP, GEPOperator &Src) {
20020b57cec5SDimitry Andric   // If this GEP has only 0 indices, it is the same pointer as
20030b57cec5SDimitry Andric   // Src. If Src is not a trivial GEP too, don't combine
20040b57cec5SDimitry Andric   // the indices.
20050b57cec5SDimitry Andric   if (GEP.hasAllZeroIndices() && !Src.hasAllZeroIndices() &&
20060b57cec5SDimitry Andric       !Src.hasOneUse())
20070b57cec5SDimitry Andric     return false;
20080b57cec5SDimitry Andric   return true;
20090b57cec5SDimitry Andric }
20100b57cec5SDimitry Andric 
2011e8d8bef9SDimitry Andric Instruction *InstCombinerImpl::foldVectorBinop(BinaryOperator &Inst) {
2012e8d8bef9SDimitry Andric   if (!isa<VectorType>(Inst.getType()))
20135ffd83dbSDimitry Andric     return nullptr;
20140b57cec5SDimitry Andric 
20150b57cec5SDimitry Andric   BinaryOperator::BinaryOps Opcode = Inst.getOpcode();
20160b57cec5SDimitry Andric   Value *LHS = Inst.getOperand(0), *RHS = Inst.getOperand(1);
20175ffd83dbSDimitry Andric   assert(cast<VectorType>(LHS->getType())->getElementCount() ==
20185ffd83dbSDimitry Andric          cast<VectorType>(Inst.getType())->getElementCount());
20195ffd83dbSDimitry Andric   assert(cast<VectorType>(RHS->getType())->getElementCount() ==
20205ffd83dbSDimitry Andric          cast<VectorType>(Inst.getType())->getElementCount());
20210b57cec5SDimitry Andric 
20220b57cec5SDimitry Andric   // If both operands of the binop are vector concatenations, then perform the
20230b57cec5SDimitry Andric   // narrow binop on each pair of the source operands followed by concatenation
20240b57cec5SDimitry Andric   // of the results.
20250b57cec5SDimitry Andric   Value *L0, *L1, *R0, *R1;
20265ffd83dbSDimitry Andric   ArrayRef<int> Mask;
20275ffd83dbSDimitry Andric   if (match(LHS, m_Shuffle(m_Value(L0), m_Value(L1), m_Mask(Mask))) &&
20285ffd83dbSDimitry Andric       match(RHS, m_Shuffle(m_Value(R0), m_Value(R1), m_SpecificMask(Mask))) &&
20290b57cec5SDimitry Andric       LHS->hasOneUse() && RHS->hasOneUse() &&
20300b57cec5SDimitry Andric       cast<ShuffleVectorInst>(LHS)->isConcat() &&
20310b57cec5SDimitry Andric       cast<ShuffleVectorInst>(RHS)->isConcat()) {
20320b57cec5SDimitry Andric     // This transform does not have the speculative execution constraint as
20330b57cec5SDimitry Andric     // below because the shuffle is a concatenation. The new binops are
20340b57cec5SDimitry Andric     // operating on exactly the same elements as the existing binop.
20350b57cec5SDimitry Andric     // TODO: We could ease the mask requirement to allow different undef lanes,
20360b57cec5SDimitry Andric     //       but that requires an analysis of the binop-with-undef output value.
20370b57cec5SDimitry Andric     Value *NewBO0 = Builder.CreateBinOp(Opcode, L0, R0);
20380b57cec5SDimitry Andric     if (auto *BO = dyn_cast<BinaryOperator>(NewBO0))
20390b57cec5SDimitry Andric       BO->copyIRFlags(&Inst);
20400b57cec5SDimitry Andric     Value *NewBO1 = Builder.CreateBinOp(Opcode, L1, R1);
20410b57cec5SDimitry Andric     if (auto *BO = dyn_cast<BinaryOperator>(NewBO1))
20420b57cec5SDimitry Andric       BO->copyIRFlags(&Inst);
20430b57cec5SDimitry Andric     return new ShuffleVectorInst(NewBO0, NewBO1, Mask);
20440b57cec5SDimitry Andric   }
20450b57cec5SDimitry Andric 
2046bdd1243dSDimitry Andric   auto createBinOpReverse = [&](Value *X, Value *Y) {
2047bdd1243dSDimitry Andric     Value *V = Builder.CreateBinOp(Opcode, X, Y, Inst.getName());
2048bdd1243dSDimitry Andric     if (auto *BO = dyn_cast<BinaryOperator>(V))
2049bdd1243dSDimitry Andric       BO->copyIRFlags(&Inst);
2050bdd1243dSDimitry Andric     Module *M = Inst.getModule();
2051*0fca6ea1SDimitry Andric     Function *F =
2052*0fca6ea1SDimitry Andric         Intrinsic::getDeclaration(M, Intrinsic::vector_reverse, V->getType());
2053bdd1243dSDimitry Andric     return CallInst::Create(F, V);
2054bdd1243dSDimitry Andric   };
2055bdd1243dSDimitry Andric 
2056bdd1243dSDimitry Andric   // NOTE: Reverse shuffles don't require the speculative execution protection
2057bdd1243dSDimitry Andric   // below because they don't affect which lanes take part in the computation.
2058bdd1243dSDimitry Andric 
2059bdd1243dSDimitry Andric   Value *V1, *V2;
2060bdd1243dSDimitry Andric   if (match(LHS, m_VecReverse(m_Value(V1)))) {
2061bdd1243dSDimitry Andric     // Op(rev(V1), rev(V2)) -> rev(Op(V1, V2))
2062bdd1243dSDimitry Andric     if (match(RHS, m_VecReverse(m_Value(V2))) &&
2063bdd1243dSDimitry Andric         (LHS->hasOneUse() || RHS->hasOneUse() ||
2064bdd1243dSDimitry Andric          (LHS == RHS && LHS->hasNUses(2))))
2065bdd1243dSDimitry Andric       return createBinOpReverse(V1, V2);
2066bdd1243dSDimitry Andric 
2067bdd1243dSDimitry Andric     // Op(rev(V1), RHSSplat)) -> rev(Op(V1, RHSSplat))
2068bdd1243dSDimitry Andric     if (LHS->hasOneUse() && isSplatValue(RHS))
2069bdd1243dSDimitry Andric       return createBinOpReverse(V1, RHS);
2070bdd1243dSDimitry Andric   }
2071bdd1243dSDimitry Andric   // Op(LHSSplat, rev(V2)) -> rev(Op(LHSSplat, V2))
2072bdd1243dSDimitry Andric   else if (isSplatValue(LHS) && match(RHS, m_OneUse(m_VecReverse(m_Value(V2)))))
2073bdd1243dSDimitry Andric     return createBinOpReverse(LHS, V2);
2074bdd1243dSDimitry Andric 
20750b57cec5SDimitry Andric   // It may not be safe to reorder shuffles and things like div, urem, etc.
20760b57cec5SDimitry Andric   // because we may trap when executing those ops on unknown vector elements.
20770b57cec5SDimitry Andric   // See PR20059.
20780b57cec5SDimitry Andric   if (!isSafeToSpeculativelyExecute(&Inst))
20790b57cec5SDimitry Andric     return nullptr;
20800b57cec5SDimitry Andric 
20815ffd83dbSDimitry Andric   auto createBinOpShuffle = [&](Value *X, Value *Y, ArrayRef<int> M) {
20820b57cec5SDimitry Andric     Value *XY = Builder.CreateBinOp(Opcode, X, Y);
20830b57cec5SDimitry Andric     if (auto *BO = dyn_cast<BinaryOperator>(XY))
20840b57cec5SDimitry Andric       BO->copyIRFlags(&Inst);
2085349cc55cSDimitry Andric     return new ShuffleVectorInst(XY, M);
20860b57cec5SDimitry Andric   };
20870b57cec5SDimitry Andric 
20880b57cec5SDimitry Andric   // If both arguments of the binary operation are shuffles that use the same
20890b57cec5SDimitry Andric   // mask and shuffle within a single vector, move the shuffle after the binop.
2090cb14a3feSDimitry Andric   if (match(LHS, m_Shuffle(m_Value(V1), m_Poison(), m_Mask(Mask))) &&
2091cb14a3feSDimitry Andric       match(RHS, m_Shuffle(m_Value(V2), m_Poison(), m_SpecificMask(Mask))) &&
20920b57cec5SDimitry Andric       V1->getType() == V2->getType() &&
20930b57cec5SDimitry Andric       (LHS->hasOneUse() || RHS->hasOneUse() || LHS == RHS)) {
20940b57cec5SDimitry Andric     // Op(shuffle(V1, Mask), shuffle(V2, Mask)) -> shuffle(Op(V1, V2), Mask)
20950b57cec5SDimitry Andric     return createBinOpShuffle(V1, V2, Mask);
20960b57cec5SDimitry Andric   }
20970b57cec5SDimitry Andric 
20980b57cec5SDimitry Andric   // If both arguments of a commutative binop are select-shuffles that use the
20990b57cec5SDimitry Andric   // same mask with commuted operands, the shuffles are unnecessary.
21000b57cec5SDimitry Andric   if (Inst.isCommutative() &&
21015ffd83dbSDimitry Andric       match(LHS, m_Shuffle(m_Value(V1), m_Value(V2), m_Mask(Mask))) &&
21025ffd83dbSDimitry Andric       match(RHS,
21035ffd83dbSDimitry Andric             m_Shuffle(m_Specific(V2), m_Specific(V1), m_SpecificMask(Mask)))) {
21040b57cec5SDimitry Andric     auto *LShuf = cast<ShuffleVectorInst>(LHS);
21050b57cec5SDimitry Andric     auto *RShuf = cast<ShuffleVectorInst>(RHS);
21060b57cec5SDimitry Andric     // TODO: Allow shuffles that contain undefs in the mask?
21070b57cec5SDimitry Andric     //       That is legal, but it reduces undef knowledge.
21080b57cec5SDimitry Andric     // TODO: Allow arbitrary shuffles by shuffling after binop?
21090b57cec5SDimitry Andric     //       That might be legal, but we have to deal with poison.
21105ffd83dbSDimitry Andric     if (LShuf->isSelect() &&
211106c3fb27SDimitry Andric         !is_contained(LShuf->getShuffleMask(), PoisonMaskElem) &&
21125ffd83dbSDimitry Andric         RShuf->isSelect() &&
211306c3fb27SDimitry Andric         !is_contained(RShuf->getShuffleMask(), PoisonMaskElem)) {
21140b57cec5SDimitry Andric       // Example:
21150b57cec5SDimitry Andric       // LHS = shuffle V1, V2, <0, 5, 6, 3>
21160b57cec5SDimitry Andric       // RHS = shuffle V2, V1, <0, 5, 6, 3>
21170b57cec5SDimitry Andric       // LHS + RHS --> (V10+V20, V21+V11, V22+V12, V13+V23) --> V1 + V2
21180b57cec5SDimitry Andric       Instruction *NewBO = BinaryOperator::Create(Opcode, V1, V2);
21190b57cec5SDimitry Andric       NewBO->copyIRFlags(&Inst);
21200b57cec5SDimitry Andric       return NewBO;
21210b57cec5SDimitry Andric     }
21220b57cec5SDimitry Andric   }
21230b57cec5SDimitry Andric 
21240b57cec5SDimitry Andric   // If one argument is a shuffle within one vector and the other is a constant,
21250b57cec5SDimitry Andric   // try moving the shuffle after the binary operation. This canonicalization
21260b57cec5SDimitry Andric   // intends to move shuffles closer to other shuffles and binops closer to
21270b57cec5SDimitry Andric   // other binops, so they can be folded. It may also enable demanded elements
21280b57cec5SDimitry Andric   // transforms.
21290b57cec5SDimitry Andric   Constant *C;
2130e8d8bef9SDimitry Andric   auto *InstVTy = dyn_cast<FixedVectorType>(Inst.getType());
2131e8d8bef9SDimitry Andric   if (InstVTy &&
2132cb14a3feSDimitry Andric       match(&Inst, m_c_BinOp(m_OneUse(m_Shuffle(m_Value(V1), m_Poison(),
2133cb14a3feSDimitry Andric                                                 m_Mask(Mask))),
2134e8d8bef9SDimitry Andric                              m_ImmConstant(C))) &&
2135e8d8bef9SDimitry Andric       cast<FixedVectorType>(V1->getType())->getNumElements() <=
2136e8d8bef9SDimitry Andric           InstVTy->getNumElements()) {
2137e8d8bef9SDimitry Andric     assert(InstVTy->getScalarType() == V1->getType()->getScalarType() &&
21380b57cec5SDimitry Andric            "Shuffle should not change scalar type");
21390b57cec5SDimitry Andric 
21400b57cec5SDimitry Andric     // Find constant NewC that has property:
21410b57cec5SDimitry Andric     //   shuffle(NewC, ShMask) = C
21420b57cec5SDimitry Andric     // If such constant does not exist (example: ShMask=<0,0> and C=<1,2>)
21430b57cec5SDimitry Andric     // reorder is not possible. A 1-to-1 mapping is not required. Example:
21440b57cec5SDimitry Andric     // ShMask = <1,1,2,2> and C = <5,5,6,6> --> NewC = <undef,5,6,undef>
21450b57cec5SDimitry Andric     bool ConstOp1 = isa<Constant>(RHS);
21465ffd83dbSDimitry Andric     ArrayRef<int> ShMask = Mask;
21475ffd83dbSDimitry Andric     unsigned SrcVecNumElts =
21485ffd83dbSDimitry Andric         cast<FixedVectorType>(V1->getType())->getNumElements();
2149cb14a3feSDimitry Andric     PoisonValue *PoisonScalar = PoisonValue::get(C->getType()->getScalarType());
2150cb14a3feSDimitry Andric     SmallVector<Constant *, 16> NewVecC(SrcVecNumElts, PoisonScalar);
21510b57cec5SDimitry Andric     bool MayChange = true;
2152e8d8bef9SDimitry Andric     unsigned NumElts = InstVTy->getNumElements();
21530b57cec5SDimitry Andric     for (unsigned I = 0; I < NumElts; ++I) {
21540b57cec5SDimitry Andric       Constant *CElt = C->getAggregateElement(I);
21550b57cec5SDimitry Andric       if (ShMask[I] >= 0) {
21560b57cec5SDimitry Andric         assert(ShMask[I] < (int)NumElts && "Not expecting narrowing shuffle");
21570b57cec5SDimitry Andric         Constant *NewCElt = NewVecC[ShMask[I]];
21580b57cec5SDimitry Andric         // Bail out if:
21590b57cec5SDimitry Andric         // 1. The constant vector contains a constant expression.
21600b57cec5SDimitry Andric         // 2. The shuffle needs an element of the constant vector that can't
21610b57cec5SDimitry Andric         //    be mapped to a new constant vector.
21620b57cec5SDimitry Andric         // 3. This is a widening shuffle that copies elements of V1 into the
2163cb14a3feSDimitry Andric         //    extended elements (extending with poison is allowed).
2164cb14a3feSDimitry Andric         if (!CElt || (!isa<PoisonValue>(NewCElt) && NewCElt != CElt) ||
21650b57cec5SDimitry Andric             I >= SrcVecNumElts) {
21660b57cec5SDimitry Andric           MayChange = false;
21670b57cec5SDimitry Andric           break;
21680b57cec5SDimitry Andric         }
21690b57cec5SDimitry Andric         NewVecC[ShMask[I]] = CElt;
21700b57cec5SDimitry Andric       }
2171cb14a3feSDimitry Andric       // If this is a widening shuffle, we must be able to extend with poison
2172cb14a3feSDimitry Andric       // elements. If the original binop does not produce a poison in the high
21730b57cec5SDimitry Andric       // lanes, then this transform is not safe.
2174cb14a3feSDimitry Andric       // Similarly for poison lanes due to the shuffle mask, we can only
2175cb14a3feSDimitry Andric       // transform binops that preserve poison.
2176cb14a3feSDimitry Andric       // TODO: We could shuffle those non-poison constant values into the
2177cb14a3feSDimitry Andric       //       result by using a constant vector (rather than an poison vector)
21780b57cec5SDimitry Andric       //       as operand 1 of the new binop, but that might be too aggressive
21790b57cec5SDimitry Andric       //       for target-independent shuffle creation.
2180480093f4SDimitry Andric       if (I >= SrcVecNumElts || ShMask[I] < 0) {
2181cb14a3feSDimitry Andric         Constant *MaybePoison =
2182753f127fSDimitry Andric             ConstOp1
2183cb14a3feSDimitry Andric                 ? ConstantFoldBinaryOpOperands(Opcode, PoisonScalar, CElt, DL)
2184cb14a3feSDimitry Andric                 : ConstantFoldBinaryOpOperands(Opcode, CElt, PoisonScalar, DL);
2185cb14a3feSDimitry Andric         if (!MaybePoison || !isa<PoisonValue>(MaybePoison)) {
21860b57cec5SDimitry Andric           MayChange = false;
21870b57cec5SDimitry Andric           break;
21880b57cec5SDimitry Andric         }
21890b57cec5SDimitry Andric       }
21900b57cec5SDimitry Andric     }
21910b57cec5SDimitry Andric     if (MayChange) {
21920b57cec5SDimitry Andric       Constant *NewC = ConstantVector::get(NewVecC);
2193cb14a3feSDimitry Andric       // It may not be safe to execute a binop on a vector with poison elements
21940b57cec5SDimitry Andric       // because the entire instruction can be folded to undef or create poison
21950b57cec5SDimitry Andric       // that did not exist in the original code.
2196cb14a3feSDimitry Andric       // TODO: The shift case should not be necessary.
21970b57cec5SDimitry Andric       if (Inst.isIntDivRem() || (Inst.isShift() && ConstOp1))
21980b57cec5SDimitry Andric         NewC = getSafeVectorConstantForBinop(Opcode, NewC, ConstOp1);
21990b57cec5SDimitry Andric 
22000b57cec5SDimitry Andric       // Op(shuffle(V1, Mask), C) -> shuffle(Op(V1, NewC), Mask)
22010b57cec5SDimitry Andric       // Op(C, shuffle(V1, Mask)) -> shuffle(Op(NewC, V1), Mask)
22020b57cec5SDimitry Andric       Value *NewLHS = ConstOp1 ? V1 : NewC;
22030b57cec5SDimitry Andric       Value *NewRHS = ConstOp1 ? NewC : V1;
22040b57cec5SDimitry Andric       return createBinOpShuffle(NewLHS, NewRHS, Mask);
22050b57cec5SDimitry Andric     }
22060b57cec5SDimitry Andric   }
22070b57cec5SDimitry Andric 
22085ffd83dbSDimitry Andric   // Try to reassociate to sink a splat shuffle after a binary operation.
22095ffd83dbSDimitry Andric   if (Inst.isAssociative() && Inst.isCommutative()) {
22105ffd83dbSDimitry Andric     // Canonicalize shuffle operand as LHS.
22115ffd83dbSDimitry Andric     if (isa<ShuffleVectorInst>(RHS))
22125ffd83dbSDimitry Andric       std::swap(LHS, RHS);
22135ffd83dbSDimitry Andric 
22145ffd83dbSDimitry Andric     Value *X;
22155ffd83dbSDimitry Andric     ArrayRef<int> MaskC;
22165ffd83dbSDimitry Andric     int SplatIndex;
2217349cc55cSDimitry Andric     Value *Y, *OtherOp;
22185ffd83dbSDimitry Andric     if (!match(LHS,
22195ffd83dbSDimitry Andric                m_OneUse(m_Shuffle(m_Value(X), m_Undef(), m_Mask(MaskC)))) ||
2220*0fca6ea1SDimitry Andric         !match(MaskC, m_SplatOrPoisonMask(SplatIndex)) ||
2221349cc55cSDimitry Andric         X->getType() != Inst.getType() ||
2222349cc55cSDimitry Andric         !match(RHS, m_OneUse(m_BinOp(Opcode, m_Value(Y), m_Value(OtherOp)))))
22235ffd83dbSDimitry Andric       return nullptr;
22245ffd83dbSDimitry Andric 
22255ffd83dbSDimitry Andric     // FIXME: This may not be safe if the analysis allows undef elements. By
22265ffd83dbSDimitry Andric     //        moving 'Y' before the splat shuffle, we are implicitly assuming
22275ffd83dbSDimitry Andric     //        that it is not undef/poison at the splat index.
2228349cc55cSDimitry Andric     if (isSplatValue(OtherOp, SplatIndex)) {
2229349cc55cSDimitry Andric       std::swap(Y, OtherOp);
2230349cc55cSDimitry Andric     } else if (!isSplatValue(Y, SplatIndex)) {
22315ffd83dbSDimitry Andric       return nullptr;
22325ffd83dbSDimitry Andric     }
22335ffd83dbSDimitry Andric 
22345ffd83dbSDimitry Andric     // X and Y are splatted values, so perform the binary operation on those
22355ffd83dbSDimitry Andric     // values followed by a splat followed by the 2nd binary operation:
22365ffd83dbSDimitry Andric     // bo (splat X), (bo Y, OtherOp) --> bo (splat (bo X, Y)), OtherOp
22375ffd83dbSDimitry Andric     Value *NewBO = Builder.CreateBinOp(Opcode, X, Y);
22385ffd83dbSDimitry Andric     SmallVector<int, 8> NewMask(MaskC.size(), SplatIndex);
2239e8d8bef9SDimitry Andric     Value *NewSplat = Builder.CreateShuffleVector(NewBO, NewMask);
22405ffd83dbSDimitry Andric     Instruction *R = BinaryOperator::Create(Opcode, NewSplat, OtherOp);
22415ffd83dbSDimitry Andric 
22425ffd83dbSDimitry Andric     // Intersect FMF on both new binops. Other (poison-generating) flags are
22435ffd83dbSDimitry Andric     // dropped to be safe.
22445ffd83dbSDimitry Andric     if (isa<FPMathOperator>(R)) {
22455ffd83dbSDimitry Andric       R->copyFastMathFlags(&Inst);
2246349cc55cSDimitry Andric       R->andIRFlags(RHS);
22475ffd83dbSDimitry Andric     }
22485ffd83dbSDimitry Andric     if (auto *NewInstBO = dyn_cast<BinaryOperator>(NewBO))
22495ffd83dbSDimitry Andric       NewInstBO->copyIRFlags(R);
22505ffd83dbSDimitry Andric     return R;
22515ffd83dbSDimitry Andric   }
22525ffd83dbSDimitry Andric 
22530b57cec5SDimitry Andric   return nullptr;
22540b57cec5SDimitry Andric }
22550b57cec5SDimitry Andric 
22560b57cec5SDimitry Andric /// Try to narrow the width of a binop if at least 1 operand is an extend of
22570b57cec5SDimitry Andric /// of a value. This requires a potentially expensive known bits check to make
22580b57cec5SDimitry Andric /// sure the narrow op does not overflow.
2259e8d8bef9SDimitry Andric Instruction *InstCombinerImpl::narrowMathIfNoOverflow(BinaryOperator &BO) {
22600b57cec5SDimitry Andric   // We need at least one extended operand.
22610b57cec5SDimitry Andric   Value *Op0 = BO.getOperand(0), *Op1 = BO.getOperand(1);
22620b57cec5SDimitry Andric 
22630b57cec5SDimitry Andric   // If this is a sub, we swap the operands since we always want an extension
22640b57cec5SDimitry Andric   // on the RHS. The LHS can be an extension or a constant.
22650b57cec5SDimitry Andric   if (BO.getOpcode() == Instruction::Sub)
22660b57cec5SDimitry Andric     std::swap(Op0, Op1);
22670b57cec5SDimitry Andric 
22680b57cec5SDimitry Andric   Value *X;
22690b57cec5SDimitry Andric   bool IsSext = match(Op0, m_SExt(m_Value(X)));
22700b57cec5SDimitry Andric   if (!IsSext && !match(Op0, m_ZExt(m_Value(X))))
22710b57cec5SDimitry Andric     return nullptr;
22720b57cec5SDimitry Andric 
22730b57cec5SDimitry Andric   // If both operands are the same extension from the same source type and we
22740b57cec5SDimitry Andric   // can eliminate at least one (hasOneUse), this might work.
22750b57cec5SDimitry Andric   CastInst::CastOps CastOpc = IsSext ? Instruction::SExt : Instruction::ZExt;
22760b57cec5SDimitry Andric   Value *Y;
22770b57cec5SDimitry Andric   if (!(match(Op1, m_ZExtOrSExt(m_Value(Y))) && X->getType() == Y->getType() &&
22780b57cec5SDimitry Andric         cast<Operator>(Op1)->getOpcode() == CastOpc &&
22790b57cec5SDimitry Andric         (Op0->hasOneUse() || Op1->hasOneUse()))) {
22800b57cec5SDimitry Andric     // If that did not match, see if we have a suitable constant operand.
22810b57cec5SDimitry Andric     // Truncating and extending must produce the same constant.
22820b57cec5SDimitry Andric     Constant *WideC;
22830b57cec5SDimitry Andric     if (!Op0->hasOneUse() || !match(Op1, m_Constant(WideC)))
22840b57cec5SDimitry Andric       return nullptr;
22855f757f3fSDimitry Andric     Constant *NarrowC = getLosslessTrunc(WideC, X->getType(), CastOpc);
22865f757f3fSDimitry Andric     if (!NarrowC)
22870b57cec5SDimitry Andric       return nullptr;
22880b57cec5SDimitry Andric     Y = NarrowC;
22890b57cec5SDimitry Andric   }
22900b57cec5SDimitry Andric 
22910b57cec5SDimitry Andric   // Swap back now that we found our operands.
22920b57cec5SDimitry Andric   if (BO.getOpcode() == Instruction::Sub)
22930b57cec5SDimitry Andric     std::swap(X, Y);
22940b57cec5SDimitry Andric 
22950b57cec5SDimitry Andric   // Both operands have narrow versions. Last step: the math must not overflow
22960b57cec5SDimitry Andric   // in the narrow width.
22970b57cec5SDimitry Andric   if (!willNotOverflow(BO.getOpcode(), X, Y, BO, IsSext))
22980b57cec5SDimitry Andric     return nullptr;
22990b57cec5SDimitry Andric 
23000b57cec5SDimitry Andric   // bo (ext X), (ext Y) --> ext (bo X, Y)
23010b57cec5SDimitry Andric   // bo (ext X), C       --> ext (bo X, C')
23020b57cec5SDimitry Andric   Value *NarrowBO = Builder.CreateBinOp(BO.getOpcode(), X, Y, "narrow");
23030b57cec5SDimitry Andric   if (auto *NewBinOp = dyn_cast<BinaryOperator>(NarrowBO)) {
23040b57cec5SDimitry Andric     if (IsSext)
23050b57cec5SDimitry Andric       NewBinOp->setHasNoSignedWrap();
23060b57cec5SDimitry Andric     else
23070b57cec5SDimitry Andric       NewBinOp->setHasNoUnsignedWrap();
23080b57cec5SDimitry Andric   }
23090b57cec5SDimitry Andric   return CastInst::Create(CastOpc, NarrowBO, BO.getType());
23100b57cec5SDimitry Andric }
23110b57cec5SDimitry Andric 
2312480093f4SDimitry Andric static bool isMergedGEPInBounds(GEPOperator &GEP1, GEPOperator &GEP2) {
2313*0fca6ea1SDimitry Andric   return GEP1.isInBounds() && GEP2.isInBounds();
2314480093f4SDimitry Andric }
2315480093f4SDimitry Andric 
23165ffd83dbSDimitry Andric /// Thread a GEP operation with constant indices through the constant true/false
23175ffd83dbSDimitry Andric /// arms of a select.
23185ffd83dbSDimitry Andric static Instruction *foldSelectGEP(GetElementPtrInst &GEP,
23195ffd83dbSDimitry Andric                                   InstCombiner::BuilderTy &Builder) {
23205ffd83dbSDimitry Andric   if (!GEP.hasAllConstantIndices())
23215ffd83dbSDimitry Andric     return nullptr;
23225ffd83dbSDimitry Andric 
23235ffd83dbSDimitry Andric   Instruction *Sel;
23245ffd83dbSDimitry Andric   Value *Cond;
23255ffd83dbSDimitry Andric   Constant *TrueC, *FalseC;
23265ffd83dbSDimitry Andric   if (!match(GEP.getPointerOperand(), m_Instruction(Sel)) ||
23275ffd83dbSDimitry Andric       !match(Sel,
23285ffd83dbSDimitry Andric              m_Select(m_Value(Cond), m_Constant(TrueC), m_Constant(FalseC))))
23295ffd83dbSDimitry Andric     return nullptr;
23305ffd83dbSDimitry Andric 
23315ffd83dbSDimitry Andric   // gep (select Cond, TrueC, FalseC), IndexC --> select Cond, TrueC', FalseC'
23325ffd83dbSDimitry Andric   // Propagate 'inbounds' and metadata from existing instructions.
23335ffd83dbSDimitry Andric   // Note: using IRBuilder to create the constants for efficiency.
2334e8d8bef9SDimitry Andric   SmallVector<Value *, 4> IndexC(GEP.indices());
2335*0fca6ea1SDimitry Andric   GEPNoWrapFlags NW = GEP.getNoWrapFlags();
2336fe6060f1SDimitry Andric   Type *Ty = GEP.getSourceElementType();
2337*0fca6ea1SDimitry Andric   Value *NewTrueC = Builder.CreateGEP(Ty, TrueC, IndexC, "", NW);
2338*0fca6ea1SDimitry Andric   Value *NewFalseC = Builder.CreateGEP(Ty, FalseC, IndexC, "", NW);
23395ffd83dbSDimitry Andric   return SelectInst::Create(Cond, NewTrueC, NewFalseC, "", nullptr, Sel);
23405ffd83dbSDimitry Andric }
23415ffd83dbSDimitry Andric 
2342*0fca6ea1SDimitry Andric // Canonicalization:
2343*0fca6ea1SDimitry Andric // gep T, (gep i8, base, C1), (Index + C2) into
2344*0fca6ea1SDimitry Andric // gep T, (gep i8, base, C1 + C2 * sizeof(T)), Index
2345*0fca6ea1SDimitry Andric static Instruction *canonicalizeGEPOfConstGEPI8(GetElementPtrInst &GEP,
2346*0fca6ea1SDimitry Andric                                                 GEPOperator *Src,
2347*0fca6ea1SDimitry Andric                                                 InstCombinerImpl &IC) {
2348*0fca6ea1SDimitry Andric   if (GEP.getNumIndices() != 1)
2349*0fca6ea1SDimitry Andric     return nullptr;
2350*0fca6ea1SDimitry Andric   auto &DL = IC.getDataLayout();
2351*0fca6ea1SDimitry Andric   Value *Base;
2352*0fca6ea1SDimitry Andric   const APInt *C1;
2353*0fca6ea1SDimitry Andric   if (!match(Src, m_PtrAdd(m_Value(Base), m_APInt(C1))))
2354*0fca6ea1SDimitry Andric     return nullptr;
2355*0fca6ea1SDimitry Andric   Value *VarIndex;
2356*0fca6ea1SDimitry Andric   const APInt *C2;
2357*0fca6ea1SDimitry Andric   Type *PtrTy = Src->getType()->getScalarType();
2358*0fca6ea1SDimitry Andric   unsigned IndexSizeInBits = DL.getIndexTypeSizeInBits(PtrTy);
2359*0fca6ea1SDimitry Andric   if (!match(GEP.getOperand(1), m_AddLike(m_Value(VarIndex), m_APInt(C2))))
2360*0fca6ea1SDimitry Andric     return nullptr;
2361*0fca6ea1SDimitry Andric   if (C1->getBitWidth() != IndexSizeInBits ||
2362*0fca6ea1SDimitry Andric       C2->getBitWidth() != IndexSizeInBits)
2363*0fca6ea1SDimitry Andric     return nullptr;
2364*0fca6ea1SDimitry Andric   Type *BaseType = GEP.getSourceElementType();
2365*0fca6ea1SDimitry Andric   if (isa<ScalableVectorType>(BaseType))
2366*0fca6ea1SDimitry Andric     return nullptr;
2367*0fca6ea1SDimitry Andric   APInt TypeSize(IndexSizeInBits, DL.getTypeAllocSize(BaseType));
2368*0fca6ea1SDimitry Andric   APInt NewOffset = TypeSize * *C2 + *C1;
2369*0fca6ea1SDimitry Andric   if (NewOffset.isZero() ||
2370*0fca6ea1SDimitry Andric       (Src->hasOneUse() && GEP.getOperand(1)->hasOneUse())) {
2371*0fca6ea1SDimitry Andric     Value *GEPConst =
2372*0fca6ea1SDimitry Andric         IC.Builder.CreatePtrAdd(Base, IC.Builder.getInt(NewOffset));
2373*0fca6ea1SDimitry Andric     return GetElementPtrInst::Create(BaseType, GEPConst, VarIndex);
2374*0fca6ea1SDimitry Andric   }
2375*0fca6ea1SDimitry Andric 
2376*0fca6ea1SDimitry Andric   return nullptr;
2377*0fca6ea1SDimitry Andric }
2378*0fca6ea1SDimitry Andric 
237904eeddc0SDimitry Andric Instruction *InstCombinerImpl::visitGEPOfGEP(GetElementPtrInst &GEP,
238004eeddc0SDimitry Andric                                              GEPOperator *Src) {
238104eeddc0SDimitry Andric   // Combine Indices - If the source pointer to this getelementptr instruction
238204eeddc0SDimitry Andric   // is a getelementptr instruction with matching element type, combine the
238304eeddc0SDimitry Andric   // indices of the two getelementptr instructions into a single instruction.
238404eeddc0SDimitry Andric   if (!shouldMergeGEPs(*cast<GEPOperator>(&GEP), *Src))
238504eeddc0SDimitry Andric     return nullptr;
238604eeddc0SDimitry Andric 
2387*0fca6ea1SDimitry Andric   if (auto *I = canonicalizeGEPOfConstGEPI8(GEP, Src, *this))
2388*0fca6ea1SDimitry Andric     return I;
2389*0fca6ea1SDimitry Andric 
239081ad6265SDimitry Andric   // For constant GEPs, use a more general offset-based folding approach.
239181ad6265SDimitry Andric   Type *PtrTy = Src->getType()->getScalarType();
239206c3fb27SDimitry Andric   if (GEP.hasAllConstantIndices() &&
239381ad6265SDimitry Andric       (Src->hasOneUse() || Src->hasAllConstantIndices())) {
239481ad6265SDimitry Andric     // Split Src into a variable part and a constant suffix.
239581ad6265SDimitry Andric     gep_type_iterator GTI = gep_type_begin(*Src);
239681ad6265SDimitry Andric     Type *BaseType = GTI.getIndexedType();
239781ad6265SDimitry Andric     bool IsFirstType = true;
239881ad6265SDimitry Andric     unsigned NumVarIndices = 0;
239981ad6265SDimitry Andric     for (auto Pair : enumerate(Src->indices())) {
240081ad6265SDimitry Andric       if (!isa<ConstantInt>(Pair.value())) {
240181ad6265SDimitry Andric         BaseType = GTI.getIndexedType();
240281ad6265SDimitry Andric         IsFirstType = false;
240381ad6265SDimitry Andric         NumVarIndices = Pair.index() + 1;
240481ad6265SDimitry Andric       }
240581ad6265SDimitry Andric       ++GTI;
240681ad6265SDimitry Andric     }
240781ad6265SDimitry Andric 
240881ad6265SDimitry Andric     // Determine the offset for the constant suffix of Src.
240981ad6265SDimitry Andric     APInt Offset(DL.getIndexTypeSizeInBits(PtrTy), 0);
241081ad6265SDimitry Andric     if (NumVarIndices != Src->getNumIndices()) {
241181ad6265SDimitry Andric       // FIXME: getIndexedOffsetInType() does not handled scalable vectors.
24125f757f3fSDimitry Andric       if (BaseType->isScalableTy())
241381ad6265SDimitry Andric         return nullptr;
241481ad6265SDimitry Andric 
241581ad6265SDimitry Andric       SmallVector<Value *> ConstantIndices;
241681ad6265SDimitry Andric       if (!IsFirstType)
241781ad6265SDimitry Andric         ConstantIndices.push_back(
241881ad6265SDimitry Andric             Constant::getNullValue(Type::getInt32Ty(GEP.getContext())));
241981ad6265SDimitry Andric       append_range(ConstantIndices, drop_begin(Src->indices(), NumVarIndices));
242081ad6265SDimitry Andric       Offset += DL.getIndexedOffsetInType(BaseType, ConstantIndices);
242181ad6265SDimitry Andric     }
242281ad6265SDimitry Andric 
242381ad6265SDimitry Andric     // Add the offset for GEP (which is fully constant).
242481ad6265SDimitry Andric     if (!GEP.accumulateConstantOffset(DL, Offset))
242581ad6265SDimitry Andric       return nullptr;
242681ad6265SDimitry Andric 
242781ad6265SDimitry Andric     APInt OffsetOld = Offset;
242881ad6265SDimitry Andric     // Convert the total offset back into indices.
242981ad6265SDimitry Andric     SmallVector<APInt> ConstIndices =
243081ad6265SDimitry Andric         DL.getGEPIndicesForOffset(BaseType, Offset);
243181ad6265SDimitry Andric     if (!Offset.isZero() || (!IsFirstType && !ConstIndices[0].isZero())) {
243281ad6265SDimitry Andric       // If both GEP are constant-indexed, and cannot be merged in either way,
243381ad6265SDimitry Andric       // convert them to a GEP of i8.
243481ad6265SDimitry Andric       if (Src->hasAllConstantIndices())
243506c3fb27SDimitry Andric         return replaceInstUsesWith(
243606c3fb27SDimitry Andric             GEP, Builder.CreateGEP(
243781ad6265SDimitry Andric                      Builder.getInt8Ty(), Src->getOperand(0),
243806c3fb27SDimitry Andric                      Builder.getInt(OffsetOld), "",
243906c3fb27SDimitry Andric                      isMergedGEPInBounds(*Src, *cast<GEPOperator>(&GEP))));
244081ad6265SDimitry Andric       return nullptr;
244181ad6265SDimitry Andric     }
244281ad6265SDimitry Andric 
244381ad6265SDimitry Andric     bool IsInBounds = isMergedGEPInBounds(*Src, *cast<GEPOperator>(&GEP));
244481ad6265SDimitry Andric     SmallVector<Value *> Indices;
244581ad6265SDimitry Andric     append_range(Indices, drop_end(Src->indices(),
244681ad6265SDimitry Andric                                    Src->getNumIndices() - NumVarIndices));
244781ad6265SDimitry Andric     for (const APInt &Idx : drop_begin(ConstIndices, !IsFirstType)) {
244881ad6265SDimitry Andric       Indices.push_back(ConstantInt::get(GEP.getContext(), Idx));
244981ad6265SDimitry Andric       // Even if the total offset is inbounds, we may end up representing it
245081ad6265SDimitry Andric       // by first performing a larger negative offset, and then a smaller
245181ad6265SDimitry Andric       // positive one. The large negative offset might go out of bounds. Only
245281ad6265SDimitry Andric       // preserve inbounds if all signs are the same.
245381ad6265SDimitry Andric       IsInBounds &= Idx.isNonNegative() == ConstIndices[0].isNonNegative();
245481ad6265SDimitry Andric     }
245581ad6265SDimitry Andric 
245606c3fb27SDimitry Andric     return replaceInstUsesWith(
245706c3fb27SDimitry Andric         GEP, Builder.CreateGEP(Src->getSourceElementType(), Src->getOperand(0),
245806c3fb27SDimitry Andric                                Indices, "", IsInBounds));
245981ad6265SDimitry Andric   }
246081ad6265SDimitry Andric 
246181ad6265SDimitry Andric   if (Src->getResultElementType() != GEP.getSourceElementType())
246281ad6265SDimitry Andric     return nullptr;
246381ad6265SDimitry Andric 
246404eeddc0SDimitry Andric   SmallVector<Value*, 8> Indices;
246504eeddc0SDimitry Andric 
246604eeddc0SDimitry Andric   // Find out whether the last index in the source GEP is a sequential idx.
246704eeddc0SDimitry Andric   bool EndsWithSequential = false;
246804eeddc0SDimitry Andric   for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
246904eeddc0SDimitry Andric        I != E; ++I)
247004eeddc0SDimitry Andric     EndsWithSequential = I.isSequential();
247104eeddc0SDimitry Andric 
247204eeddc0SDimitry Andric   // Can we combine the two pointer arithmetics offsets?
247304eeddc0SDimitry Andric   if (EndsWithSequential) {
247404eeddc0SDimitry Andric     // Replace: gep (gep %P, long B), long A, ...
247504eeddc0SDimitry Andric     // With:    T = long A+B; gep %P, T, ...
247604eeddc0SDimitry Andric     Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
247704eeddc0SDimitry Andric     Value *GO1 = GEP.getOperand(1);
247804eeddc0SDimitry Andric 
247904eeddc0SDimitry Andric     // If they aren't the same type, then the input hasn't been processed
248004eeddc0SDimitry Andric     // by the loop above yet (which canonicalizes sequential index types to
248104eeddc0SDimitry Andric     // intptr_t).  Just avoid transforming this until the input has been
248204eeddc0SDimitry Andric     // normalized.
248304eeddc0SDimitry Andric     if (SO1->getType() != GO1->getType())
248404eeddc0SDimitry Andric       return nullptr;
248504eeddc0SDimitry Andric 
248604eeddc0SDimitry Andric     Value *Sum =
248781ad6265SDimitry Andric         simplifyAddInst(GO1, SO1, false, false, SQ.getWithInstruction(&GEP));
248804eeddc0SDimitry Andric     // Only do the combine when we are sure the cost after the
248904eeddc0SDimitry Andric     // merge is never more than that before the merge.
249004eeddc0SDimitry Andric     if (Sum == nullptr)
249104eeddc0SDimitry Andric       return nullptr;
249204eeddc0SDimitry Andric 
249304eeddc0SDimitry Andric     // Update the GEP in place if possible.
249404eeddc0SDimitry Andric     if (Src->getNumOperands() == 2) {
249504eeddc0SDimitry Andric       GEP.setIsInBounds(isMergedGEPInBounds(*Src, *cast<GEPOperator>(&GEP)));
249604eeddc0SDimitry Andric       replaceOperand(GEP, 0, Src->getOperand(0));
249704eeddc0SDimitry Andric       replaceOperand(GEP, 1, Sum);
249804eeddc0SDimitry Andric       return &GEP;
249904eeddc0SDimitry Andric     }
250004eeddc0SDimitry Andric     Indices.append(Src->op_begin()+1, Src->op_end()-1);
250104eeddc0SDimitry Andric     Indices.push_back(Sum);
250204eeddc0SDimitry Andric     Indices.append(GEP.op_begin()+2, GEP.op_end());
250304eeddc0SDimitry Andric   } else if (isa<Constant>(*GEP.idx_begin()) &&
250404eeddc0SDimitry Andric              cast<Constant>(*GEP.idx_begin())->isNullValue() &&
250504eeddc0SDimitry Andric              Src->getNumOperands() != 1) {
250604eeddc0SDimitry Andric     // Otherwise we can do the fold if the first index of the GEP is a zero
250704eeddc0SDimitry Andric     Indices.append(Src->op_begin()+1, Src->op_end());
250804eeddc0SDimitry Andric     Indices.append(GEP.idx_begin()+1, GEP.idx_end());
250904eeddc0SDimitry Andric   }
251004eeddc0SDimitry Andric 
251104eeddc0SDimitry Andric   if (!Indices.empty())
251206c3fb27SDimitry Andric     return replaceInstUsesWith(
251306c3fb27SDimitry Andric         GEP, Builder.CreateGEP(
251406c3fb27SDimitry Andric                  Src->getSourceElementType(), Src->getOperand(0), Indices, "",
251506c3fb27SDimitry Andric                  isMergedGEPInBounds(*Src, *cast<GEPOperator>(&GEP))));
251604eeddc0SDimitry Andric 
251704eeddc0SDimitry Andric   return nullptr;
251804eeddc0SDimitry Andric }
251904eeddc0SDimitry Andric 
25205f757f3fSDimitry Andric Value *InstCombiner::getFreelyInvertedImpl(Value *V, bool WillInvertAllUses,
25215f757f3fSDimitry Andric                                            BuilderTy *Builder,
25225f757f3fSDimitry Andric                                            bool &DoesConsume, unsigned Depth) {
25235f757f3fSDimitry Andric   static Value *const NonNull = reinterpret_cast<Value *>(uintptr_t(1));
25245f757f3fSDimitry Andric   // ~(~(X)) -> X.
25255f757f3fSDimitry Andric   Value *A, *B;
25265f757f3fSDimitry Andric   if (match(V, m_Not(m_Value(A)))) {
25275f757f3fSDimitry Andric     DoesConsume = true;
25285f757f3fSDimitry Andric     return A;
25295f757f3fSDimitry Andric   }
25305f757f3fSDimitry Andric 
25315f757f3fSDimitry Andric   Constant *C;
25325f757f3fSDimitry Andric   // Constants can be considered to be not'ed values.
25335f757f3fSDimitry Andric   if (match(V, m_ImmConstant(C)))
25345f757f3fSDimitry Andric     return ConstantExpr::getNot(C);
25355f757f3fSDimitry Andric 
25365f757f3fSDimitry Andric   if (Depth++ >= MaxAnalysisRecursionDepth)
25375f757f3fSDimitry Andric     return nullptr;
25385f757f3fSDimitry Andric 
25395f757f3fSDimitry Andric   // The rest of the cases require that we invert all uses so don't bother
25405f757f3fSDimitry Andric   // doing the analysis if we know we can't use the result.
25415f757f3fSDimitry Andric   if (!WillInvertAllUses)
25425f757f3fSDimitry Andric     return nullptr;
25435f757f3fSDimitry Andric 
25445f757f3fSDimitry Andric   // Compares can be inverted if all of their uses are being modified to use
25455f757f3fSDimitry Andric   // the ~V.
25465f757f3fSDimitry Andric   if (auto *I = dyn_cast<CmpInst>(V)) {
25475f757f3fSDimitry Andric     if (Builder != nullptr)
25485f757f3fSDimitry Andric       return Builder->CreateCmp(I->getInversePredicate(), I->getOperand(0),
25495f757f3fSDimitry Andric                                 I->getOperand(1));
25505f757f3fSDimitry Andric     return NonNull;
25515f757f3fSDimitry Andric   }
25525f757f3fSDimitry Andric 
25535f757f3fSDimitry Andric   // If `V` is of the form `A + B` then `-1 - V` can be folded into
25545f757f3fSDimitry Andric   // `(-1 - B) - A` if we are willing to invert all of the uses.
25555f757f3fSDimitry Andric   if (match(V, m_Add(m_Value(A), m_Value(B)))) {
25565f757f3fSDimitry Andric     if (auto *BV = getFreelyInvertedImpl(B, B->hasOneUse(), Builder,
25575f757f3fSDimitry Andric                                          DoesConsume, Depth))
25585f757f3fSDimitry Andric       return Builder ? Builder->CreateSub(BV, A) : NonNull;
25595f757f3fSDimitry Andric     if (auto *AV = getFreelyInvertedImpl(A, A->hasOneUse(), Builder,
25605f757f3fSDimitry Andric                                          DoesConsume, Depth))
25615f757f3fSDimitry Andric       return Builder ? Builder->CreateSub(AV, B) : NonNull;
25625f757f3fSDimitry Andric     return nullptr;
25635f757f3fSDimitry Andric   }
25645f757f3fSDimitry Andric 
25655f757f3fSDimitry Andric   // If `V` is of the form `A ^ ~B` then `~(A ^ ~B)` can be folded
25665f757f3fSDimitry Andric   // into `A ^ B` if we are willing to invert all of the uses.
25675f757f3fSDimitry Andric   if (match(V, m_Xor(m_Value(A), m_Value(B)))) {
25685f757f3fSDimitry Andric     if (auto *BV = getFreelyInvertedImpl(B, B->hasOneUse(), Builder,
25695f757f3fSDimitry Andric                                          DoesConsume, Depth))
25705f757f3fSDimitry Andric       return Builder ? Builder->CreateXor(A, BV) : NonNull;
25715f757f3fSDimitry Andric     if (auto *AV = getFreelyInvertedImpl(A, A->hasOneUse(), Builder,
25725f757f3fSDimitry Andric                                          DoesConsume, Depth))
25735f757f3fSDimitry Andric       return Builder ? Builder->CreateXor(AV, B) : NonNull;
25745f757f3fSDimitry Andric     return nullptr;
25755f757f3fSDimitry Andric   }
25765f757f3fSDimitry Andric 
25775f757f3fSDimitry Andric   // If `V` is of the form `B - A` then `-1 - V` can be folded into
25785f757f3fSDimitry Andric   // `A + (-1 - B)` if we are willing to invert all of the uses.
25795f757f3fSDimitry Andric   if (match(V, m_Sub(m_Value(A), m_Value(B)))) {
25805f757f3fSDimitry Andric     if (auto *AV = getFreelyInvertedImpl(A, A->hasOneUse(), Builder,
25815f757f3fSDimitry Andric                                          DoesConsume, Depth))
25825f757f3fSDimitry Andric       return Builder ? Builder->CreateAdd(AV, B) : NonNull;
25835f757f3fSDimitry Andric     return nullptr;
25845f757f3fSDimitry Andric   }
25855f757f3fSDimitry Andric 
25865f757f3fSDimitry Andric   // If `V` is of the form `(~A) s>> B` then `~((~A) s>> B)` can be folded
25875f757f3fSDimitry Andric   // into `A s>> B` if we are willing to invert all of the uses.
25885f757f3fSDimitry Andric   if (match(V, m_AShr(m_Value(A), m_Value(B)))) {
25895f757f3fSDimitry Andric     if (auto *AV = getFreelyInvertedImpl(A, A->hasOneUse(), Builder,
25905f757f3fSDimitry Andric                                          DoesConsume, Depth))
25915f757f3fSDimitry Andric       return Builder ? Builder->CreateAShr(AV, B) : NonNull;
25925f757f3fSDimitry Andric     return nullptr;
25935f757f3fSDimitry Andric   }
25945f757f3fSDimitry Andric 
25955f757f3fSDimitry Andric   Value *Cond;
25965f757f3fSDimitry Andric   // LogicOps are special in that we canonicalize them at the cost of an
25975f757f3fSDimitry Andric   // instruction.
25985f757f3fSDimitry Andric   bool IsSelect = match(V, m_Select(m_Value(Cond), m_Value(A), m_Value(B))) &&
25995f757f3fSDimitry Andric                   !shouldAvoidAbsorbingNotIntoSelect(*cast<SelectInst>(V));
26005f757f3fSDimitry Andric   // Selects/min/max with invertible operands are freely invertible
26015f757f3fSDimitry Andric   if (IsSelect || match(V, m_MaxOrMin(m_Value(A), m_Value(B)))) {
2602*0fca6ea1SDimitry Andric     bool LocalDoesConsume = DoesConsume;
26035f757f3fSDimitry Andric     if (!getFreelyInvertedImpl(B, B->hasOneUse(), /*Builder*/ nullptr,
2604*0fca6ea1SDimitry Andric                                LocalDoesConsume, Depth))
26055f757f3fSDimitry Andric       return nullptr;
26065f757f3fSDimitry Andric     if (Value *NotA = getFreelyInvertedImpl(A, A->hasOneUse(), Builder,
2607*0fca6ea1SDimitry Andric                                             LocalDoesConsume, Depth)) {
2608*0fca6ea1SDimitry Andric       DoesConsume = LocalDoesConsume;
26095f757f3fSDimitry Andric       if (Builder != nullptr) {
26105f757f3fSDimitry Andric         Value *NotB = getFreelyInvertedImpl(B, B->hasOneUse(), Builder,
26115f757f3fSDimitry Andric                                             DoesConsume, Depth);
26125f757f3fSDimitry Andric         assert(NotB != nullptr &&
26135f757f3fSDimitry Andric                "Unable to build inverted value for known freely invertable op");
26145f757f3fSDimitry Andric         if (auto *II = dyn_cast<IntrinsicInst>(V))
26155f757f3fSDimitry Andric           return Builder->CreateBinaryIntrinsic(
26165f757f3fSDimitry Andric               getInverseMinMaxIntrinsic(II->getIntrinsicID()), NotA, NotB);
26175f757f3fSDimitry Andric         return Builder->CreateSelect(Cond, NotA, NotB);
26185f757f3fSDimitry Andric       }
26195f757f3fSDimitry Andric       return NonNull;
26205f757f3fSDimitry Andric     }
26215f757f3fSDimitry Andric   }
26225f757f3fSDimitry Andric 
2623*0fca6ea1SDimitry Andric   if (PHINode *PN = dyn_cast<PHINode>(V)) {
2624*0fca6ea1SDimitry Andric     bool LocalDoesConsume = DoesConsume;
2625*0fca6ea1SDimitry Andric     SmallVector<std::pair<Value *, BasicBlock *>, 8> IncomingValues;
2626*0fca6ea1SDimitry Andric     for (Use &U : PN->operands()) {
2627*0fca6ea1SDimitry Andric       BasicBlock *IncomingBlock = PN->getIncomingBlock(U);
2628*0fca6ea1SDimitry Andric       Value *NewIncomingVal = getFreelyInvertedImpl(
2629*0fca6ea1SDimitry Andric           U.get(), /*WillInvertAllUses=*/false,
2630*0fca6ea1SDimitry Andric           /*Builder=*/nullptr, LocalDoesConsume, MaxAnalysisRecursionDepth - 1);
2631*0fca6ea1SDimitry Andric       if (NewIncomingVal == nullptr)
2632*0fca6ea1SDimitry Andric         return nullptr;
2633*0fca6ea1SDimitry Andric       // Make sure that we can safely erase the original PHI node.
2634*0fca6ea1SDimitry Andric       if (NewIncomingVal == V)
2635*0fca6ea1SDimitry Andric         return nullptr;
2636*0fca6ea1SDimitry Andric       if (Builder != nullptr)
2637*0fca6ea1SDimitry Andric         IncomingValues.emplace_back(NewIncomingVal, IncomingBlock);
2638*0fca6ea1SDimitry Andric     }
2639*0fca6ea1SDimitry Andric 
2640*0fca6ea1SDimitry Andric     DoesConsume = LocalDoesConsume;
2641*0fca6ea1SDimitry Andric     if (Builder != nullptr) {
2642*0fca6ea1SDimitry Andric       IRBuilderBase::InsertPointGuard Guard(*Builder);
2643*0fca6ea1SDimitry Andric       Builder->SetInsertPoint(PN);
2644*0fca6ea1SDimitry Andric       PHINode *NewPN =
2645*0fca6ea1SDimitry Andric           Builder->CreatePHI(PN->getType(), PN->getNumIncomingValues());
2646*0fca6ea1SDimitry Andric       for (auto [Val, Pred] : IncomingValues)
2647*0fca6ea1SDimitry Andric         NewPN->addIncoming(Val, Pred);
2648*0fca6ea1SDimitry Andric       return NewPN;
2649*0fca6ea1SDimitry Andric     }
2650*0fca6ea1SDimitry Andric     return NonNull;
2651*0fca6ea1SDimitry Andric   }
2652*0fca6ea1SDimitry Andric 
2653*0fca6ea1SDimitry Andric   if (match(V, m_SExtLike(m_Value(A)))) {
2654*0fca6ea1SDimitry Andric     if (auto *AV = getFreelyInvertedImpl(A, A->hasOneUse(), Builder,
2655*0fca6ea1SDimitry Andric                                          DoesConsume, Depth))
2656*0fca6ea1SDimitry Andric       return Builder ? Builder->CreateSExt(AV, V->getType()) : NonNull;
2657*0fca6ea1SDimitry Andric     return nullptr;
2658*0fca6ea1SDimitry Andric   }
2659*0fca6ea1SDimitry Andric 
2660*0fca6ea1SDimitry Andric   if (match(V, m_Trunc(m_Value(A)))) {
2661*0fca6ea1SDimitry Andric     if (auto *AV = getFreelyInvertedImpl(A, A->hasOneUse(), Builder,
2662*0fca6ea1SDimitry Andric                                          DoesConsume, Depth))
2663*0fca6ea1SDimitry Andric       return Builder ? Builder->CreateTrunc(AV, V->getType()) : NonNull;
2664*0fca6ea1SDimitry Andric     return nullptr;
2665*0fca6ea1SDimitry Andric   }
2666*0fca6ea1SDimitry Andric 
2667*0fca6ea1SDimitry Andric   // De Morgan's Laws:
2668*0fca6ea1SDimitry Andric   // (~(A | B)) -> (~A & ~B)
2669*0fca6ea1SDimitry Andric   // (~(A & B)) -> (~A | ~B)
2670*0fca6ea1SDimitry Andric   auto TryInvertAndOrUsingDeMorgan = [&](Instruction::BinaryOps Opcode,
2671*0fca6ea1SDimitry Andric                                          bool IsLogical, Value *A,
2672*0fca6ea1SDimitry Andric                                          Value *B) -> Value * {
2673*0fca6ea1SDimitry Andric     bool LocalDoesConsume = DoesConsume;
2674*0fca6ea1SDimitry Andric     if (!getFreelyInvertedImpl(B, B->hasOneUse(), /*Builder=*/nullptr,
2675*0fca6ea1SDimitry Andric                                LocalDoesConsume, Depth))
2676*0fca6ea1SDimitry Andric       return nullptr;
2677*0fca6ea1SDimitry Andric     if (auto *NotA = getFreelyInvertedImpl(A, A->hasOneUse(), Builder,
2678*0fca6ea1SDimitry Andric                                            LocalDoesConsume, Depth)) {
2679*0fca6ea1SDimitry Andric       auto *NotB = getFreelyInvertedImpl(B, B->hasOneUse(), Builder,
2680*0fca6ea1SDimitry Andric                                          LocalDoesConsume, Depth);
2681*0fca6ea1SDimitry Andric       DoesConsume = LocalDoesConsume;
2682*0fca6ea1SDimitry Andric       if (IsLogical)
2683*0fca6ea1SDimitry Andric         return Builder ? Builder->CreateLogicalOp(Opcode, NotA, NotB) : NonNull;
2684*0fca6ea1SDimitry Andric       return Builder ? Builder->CreateBinOp(Opcode, NotA, NotB) : NonNull;
2685*0fca6ea1SDimitry Andric     }
2686*0fca6ea1SDimitry Andric 
2687*0fca6ea1SDimitry Andric     return nullptr;
2688*0fca6ea1SDimitry Andric   };
2689*0fca6ea1SDimitry Andric 
2690*0fca6ea1SDimitry Andric   if (match(V, m_Or(m_Value(A), m_Value(B))))
2691*0fca6ea1SDimitry Andric     return TryInvertAndOrUsingDeMorgan(Instruction::And, /*IsLogical=*/false, A,
2692*0fca6ea1SDimitry Andric                                        B);
2693*0fca6ea1SDimitry Andric 
2694*0fca6ea1SDimitry Andric   if (match(V, m_And(m_Value(A), m_Value(B))))
2695*0fca6ea1SDimitry Andric     return TryInvertAndOrUsingDeMorgan(Instruction::Or, /*IsLogical=*/false, A,
2696*0fca6ea1SDimitry Andric                                        B);
2697*0fca6ea1SDimitry Andric 
2698*0fca6ea1SDimitry Andric   if (match(V, m_LogicalOr(m_Value(A), m_Value(B))))
2699*0fca6ea1SDimitry Andric     return TryInvertAndOrUsingDeMorgan(Instruction::And, /*IsLogical=*/true, A,
2700*0fca6ea1SDimitry Andric                                        B);
2701*0fca6ea1SDimitry Andric 
2702*0fca6ea1SDimitry Andric   if (match(V, m_LogicalAnd(m_Value(A), m_Value(B))))
2703*0fca6ea1SDimitry Andric     return TryInvertAndOrUsingDeMorgan(Instruction::Or, /*IsLogical=*/true, A,
2704*0fca6ea1SDimitry Andric                                        B);
2705*0fca6ea1SDimitry Andric 
27065f757f3fSDimitry Andric   return nullptr;
27075f757f3fSDimitry Andric }
27085f757f3fSDimitry Andric 
2709e8d8bef9SDimitry Andric Instruction *InstCombinerImpl::visitGetElementPtrInst(GetElementPtrInst &GEP) {
271004eeddc0SDimitry Andric   Value *PtrOp = GEP.getOperand(0);
271104eeddc0SDimitry Andric   SmallVector<Value *, 8> Indices(GEP.indices());
27120b57cec5SDimitry Andric   Type *GEPType = GEP.getType();
27130b57cec5SDimitry Andric   Type *GEPEltType = GEP.getSourceElementType();
2714*0fca6ea1SDimitry Andric   if (Value *V =
2715*0fca6ea1SDimitry Andric           simplifyGEPInst(GEPEltType, PtrOp, Indices, GEP.getNoWrapFlags(),
2716349cc55cSDimitry Andric                           SQ.getWithInstruction(&GEP)))
27170b57cec5SDimitry Andric     return replaceInstUsesWith(GEP, V);
27180b57cec5SDimitry Andric 
27190b57cec5SDimitry Andric   // For vector geps, use the generic demanded vector support.
27205ffd83dbSDimitry Andric   // Skip if GEP return type is scalable. The number of elements is unknown at
27215ffd83dbSDimitry Andric   // compile-time.
27225ffd83dbSDimitry Andric   if (auto *GEPFVTy = dyn_cast<FixedVectorType>(GEPType)) {
27235ffd83dbSDimitry Andric     auto VWidth = GEPFVTy->getNumElements();
2724cb14a3feSDimitry Andric     APInt PoisonElts(VWidth, 0);
2725349cc55cSDimitry Andric     APInt AllOnesEltMask(APInt::getAllOnes(VWidth));
27260b57cec5SDimitry Andric     if (Value *V = SimplifyDemandedVectorElts(&GEP, AllOnesEltMask,
2727cb14a3feSDimitry Andric                                               PoisonElts)) {
27280b57cec5SDimitry Andric       if (V != &GEP)
27290b57cec5SDimitry Andric         return replaceInstUsesWith(GEP, V);
27300b57cec5SDimitry Andric       return &GEP;
27310b57cec5SDimitry Andric     }
27320b57cec5SDimitry Andric 
27330b57cec5SDimitry Andric     // TODO: 1) Scalarize splat operands, 2) scalarize entire instruction if
27340b57cec5SDimitry Andric     // possible (decide on canonical form for pointer broadcast), 3) exploit
27350b57cec5SDimitry Andric     // undef elements to decrease demanded bits
27360b57cec5SDimitry Andric   }
27370b57cec5SDimitry Andric 
27380b57cec5SDimitry Andric   // Eliminate unneeded casts for indices, and replace indices which displace
27390b57cec5SDimitry Andric   // by multiples of a zero size type with zero.
27400b57cec5SDimitry Andric   bool MadeChange = false;
27410b57cec5SDimitry Andric 
27420b57cec5SDimitry Andric   // Index width may not be the same width as pointer width.
27430b57cec5SDimitry Andric   // Data layout chooses the right type based on supported integer types.
27440b57cec5SDimitry Andric   Type *NewScalarIndexTy =
27450b57cec5SDimitry Andric       DL.getIndexType(GEP.getPointerOperandType()->getScalarType());
27460b57cec5SDimitry Andric 
27470b57cec5SDimitry Andric   gep_type_iterator GTI = gep_type_begin(GEP);
27480b57cec5SDimitry Andric   for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end(); I != E;
27490b57cec5SDimitry Andric        ++I, ++GTI) {
27500b57cec5SDimitry Andric     // Skip indices into struct types.
27510b57cec5SDimitry Andric     if (GTI.isStruct())
27520b57cec5SDimitry Andric       continue;
27530b57cec5SDimitry Andric 
27540b57cec5SDimitry Andric     Type *IndexTy = (*I)->getType();
27550b57cec5SDimitry Andric     Type *NewIndexType =
27560b57cec5SDimitry Andric         IndexTy->isVectorTy()
27575ffd83dbSDimitry Andric             ? VectorType::get(NewScalarIndexTy,
27585ffd83dbSDimitry Andric                               cast<VectorType>(IndexTy)->getElementCount())
27590b57cec5SDimitry Andric             : NewScalarIndexTy;
27600b57cec5SDimitry Andric 
27610b57cec5SDimitry Andric     // If the element type has zero size then any index over it is equivalent
27620b57cec5SDimitry Andric     // to an index of zero, so replace it with zero if it is not zero already.
27630b57cec5SDimitry Andric     Type *EltTy = GTI.getIndexedType();
27645ffd83dbSDimitry Andric     if (EltTy->isSized() && DL.getTypeAllocSize(EltTy).isZero())
27658bcb0991SDimitry Andric       if (!isa<Constant>(*I) || !match(I->get(), m_Zero())) {
27660b57cec5SDimitry Andric         *I = Constant::getNullValue(NewIndexType);
27670b57cec5SDimitry Andric         MadeChange = true;
27680b57cec5SDimitry Andric       }
27690b57cec5SDimitry Andric 
27700b57cec5SDimitry Andric     if (IndexTy != NewIndexType) {
27710b57cec5SDimitry Andric       // If we are using a wider index than needed for this platform, shrink
27720b57cec5SDimitry Andric       // it to what we need.  If narrower, sign-extend it to what we need.
27730b57cec5SDimitry Andric       // This explicit cast can make subsequent optimizations more obvious.
27740b57cec5SDimitry Andric       *I = Builder.CreateIntCast(*I, NewIndexType, true);
27750b57cec5SDimitry Andric       MadeChange = true;
27760b57cec5SDimitry Andric     }
27770b57cec5SDimitry Andric   }
27780b57cec5SDimitry Andric   if (MadeChange)
27790b57cec5SDimitry Andric     return &GEP;
27800b57cec5SDimitry Andric 
2781*0fca6ea1SDimitry Andric   // Canonicalize constant GEPs to i8 type.
2782*0fca6ea1SDimitry Andric   if (!GEPEltType->isIntegerTy(8) && GEP.hasAllConstantIndices()) {
2783*0fca6ea1SDimitry Andric     APInt Offset(DL.getIndexTypeSizeInBits(GEPType), 0);
2784*0fca6ea1SDimitry Andric     if (GEP.accumulateConstantOffset(DL, Offset))
2785*0fca6ea1SDimitry Andric       return replaceInstUsesWith(
2786*0fca6ea1SDimitry Andric           GEP, Builder.CreatePtrAdd(PtrOp, Builder.getInt(Offset), "",
2787*0fca6ea1SDimitry Andric                                     GEP.getNoWrapFlags()));
2788*0fca6ea1SDimitry Andric   }
2789*0fca6ea1SDimitry Andric 
2790*0fca6ea1SDimitry Andric   // Canonicalize
2791*0fca6ea1SDimitry Andric   //  - scalable GEPs to an explicit offset using the llvm.vscale intrinsic.
2792*0fca6ea1SDimitry Andric   //    This has better support in BasicAA.
2793*0fca6ea1SDimitry Andric   //  - gep i32 p, mul(O, C) -> gep i8, p, mul(O, C*4) to fold the two
2794*0fca6ea1SDimitry Andric   //    multiplies together.
2795*0fca6ea1SDimitry Andric   if (GEPEltType->isScalableTy() ||
2796*0fca6ea1SDimitry Andric       (!GEPEltType->isIntegerTy(8) && GEP.getNumIndices() == 1 &&
2797*0fca6ea1SDimitry Andric        match(GEP.getOperand(1),
2798*0fca6ea1SDimitry Andric              m_OneUse(m_CombineOr(m_Mul(m_Value(), m_ConstantInt()),
2799*0fca6ea1SDimitry Andric                                   m_Shl(m_Value(), m_ConstantInt())))))) {
2800*0fca6ea1SDimitry Andric     Value *Offset = EmitGEPOffset(cast<GEPOperator>(&GEP));
2801*0fca6ea1SDimitry Andric     return replaceInstUsesWith(
2802*0fca6ea1SDimitry Andric         GEP, Builder.CreatePtrAdd(PtrOp, Offset, "", GEP.getNoWrapFlags()));
2803*0fca6ea1SDimitry Andric   }
2804*0fca6ea1SDimitry Andric 
28050b57cec5SDimitry Andric   // Check to see if the inputs to the PHI node are getelementptr instructions.
28060b57cec5SDimitry Andric   if (auto *PN = dyn_cast<PHINode>(PtrOp)) {
28070b57cec5SDimitry Andric     auto *Op1 = dyn_cast<GetElementPtrInst>(PN->getOperand(0));
28080b57cec5SDimitry Andric     if (!Op1)
28090b57cec5SDimitry Andric       return nullptr;
28100b57cec5SDimitry Andric 
28110b57cec5SDimitry Andric     // Don't fold a GEP into itself through a PHI node. This can only happen
28120b57cec5SDimitry Andric     // through the back-edge of a loop. Folding a GEP into itself means that
28130b57cec5SDimitry Andric     // the value of the previous iteration needs to be stored in the meantime,
28140b57cec5SDimitry Andric     // thus requiring an additional register variable to be live, but not
28150b57cec5SDimitry Andric     // actually achieving anything (the GEP still needs to be executed once per
28160b57cec5SDimitry Andric     // loop iteration).
28170b57cec5SDimitry Andric     if (Op1 == &GEP)
28180b57cec5SDimitry Andric       return nullptr;
28190b57cec5SDimitry Andric 
28200b57cec5SDimitry Andric     int DI = -1;
28210b57cec5SDimitry Andric 
28220b57cec5SDimitry Andric     for (auto I = PN->op_begin()+1, E = PN->op_end(); I !=E; ++I) {
28230b57cec5SDimitry Andric       auto *Op2 = dyn_cast<GetElementPtrInst>(*I);
282481ad6265SDimitry Andric       if (!Op2 || Op1->getNumOperands() != Op2->getNumOperands() ||
282581ad6265SDimitry Andric           Op1->getSourceElementType() != Op2->getSourceElementType())
28260b57cec5SDimitry Andric         return nullptr;
28270b57cec5SDimitry Andric 
28280b57cec5SDimitry Andric       // As for Op1 above, don't try to fold a GEP into itself.
28290b57cec5SDimitry Andric       if (Op2 == &GEP)
28300b57cec5SDimitry Andric         return nullptr;
28310b57cec5SDimitry Andric 
28320b57cec5SDimitry Andric       // Keep track of the type as we walk the GEP.
28330b57cec5SDimitry Andric       Type *CurTy = nullptr;
28340b57cec5SDimitry Andric 
28350b57cec5SDimitry Andric       for (unsigned J = 0, F = Op1->getNumOperands(); J != F; ++J) {
28360b57cec5SDimitry Andric         if (Op1->getOperand(J)->getType() != Op2->getOperand(J)->getType())
28370b57cec5SDimitry Andric           return nullptr;
28380b57cec5SDimitry Andric 
28390b57cec5SDimitry Andric         if (Op1->getOperand(J) != Op2->getOperand(J)) {
28400b57cec5SDimitry Andric           if (DI == -1) {
28410b57cec5SDimitry Andric             // We have not seen any differences yet in the GEPs feeding the
28420b57cec5SDimitry Andric             // PHI yet, so we record this one if it is allowed to be a
28430b57cec5SDimitry Andric             // variable.
28440b57cec5SDimitry Andric 
28450b57cec5SDimitry Andric             // The first two arguments can vary for any GEP, the rest have to be
28460b57cec5SDimitry Andric             // static for struct slots
2847480093f4SDimitry Andric             if (J > 1) {
2848480093f4SDimitry Andric               assert(CurTy && "No current type?");
2849480093f4SDimitry Andric               if (CurTy->isStructTy())
28500b57cec5SDimitry Andric                 return nullptr;
2851480093f4SDimitry Andric             }
28520b57cec5SDimitry Andric 
28530b57cec5SDimitry Andric             DI = J;
28540b57cec5SDimitry Andric           } else {
28550b57cec5SDimitry Andric             // The GEP is different by more than one input. While this could be
28560b57cec5SDimitry Andric             // extended to support GEPs that vary by more than one variable it
28570b57cec5SDimitry Andric             // doesn't make sense since it greatly increases the complexity and
28580b57cec5SDimitry Andric             // would result in an R+R+R addressing mode which no backend
28590b57cec5SDimitry Andric             // directly supports and would need to be broken into several
28600b57cec5SDimitry Andric             // simpler instructions anyway.
28610b57cec5SDimitry Andric             return nullptr;
28620b57cec5SDimitry Andric           }
28630b57cec5SDimitry Andric         }
28640b57cec5SDimitry Andric 
28650b57cec5SDimitry Andric         // Sink down a layer of the type for the next iteration.
28660b57cec5SDimitry Andric         if (J > 0) {
28670b57cec5SDimitry Andric           if (J == 1) {
28680b57cec5SDimitry Andric             CurTy = Op1->getSourceElementType();
28690b57cec5SDimitry Andric           } else {
28705ffd83dbSDimitry Andric             CurTy =
28715ffd83dbSDimitry Andric                 GetElementPtrInst::getTypeAtIndex(CurTy, Op1->getOperand(J));
28720b57cec5SDimitry Andric           }
28730b57cec5SDimitry Andric         }
28740b57cec5SDimitry Andric       }
28750b57cec5SDimitry Andric     }
28760b57cec5SDimitry Andric 
28770b57cec5SDimitry Andric     // If not all GEPs are identical we'll have to create a new PHI node.
28780b57cec5SDimitry Andric     // Check that the old PHI node has only one use so that it will get
28790b57cec5SDimitry Andric     // removed.
28800b57cec5SDimitry Andric     if (DI != -1 && !PN->hasOneUse())
28810b57cec5SDimitry Andric       return nullptr;
28820b57cec5SDimitry Andric 
28830b57cec5SDimitry Andric     auto *NewGEP = cast<GetElementPtrInst>(Op1->clone());
28840b57cec5SDimitry Andric     if (DI == -1) {
28850b57cec5SDimitry Andric       // All the GEPs feeding the PHI are identical. Clone one down into our
28860b57cec5SDimitry Andric       // BB so that it can be merged with the current GEP.
28870b57cec5SDimitry Andric     } else {
28880b57cec5SDimitry Andric       // All the GEPs feeding the PHI differ at a single offset. Clone a GEP
28890b57cec5SDimitry Andric       // into the current block so it can be merged, and create a new PHI to
28900b57cec5SDimitry Andric       // set that index.
28910b57cec5SDimitry Andric       PHINode *NewPN;
28920b57cec5SDimitry Andric       {
28930b57cec5SDimitry Andric         IRBuilderBase::InsertPointGuard Guard(Builder);
28940b57cec5SDimitry Andric         Builder.SetInsertPoint(PN);
28950b57cec5SDimitry Andric         NewPN = Builder.CreatePHI(Op1->getOperand(DI)->getType(),
28960b57cec5SDimitry Andric                                   PN->getNumOperands());
28970b57cec5SDimitry Andric       }
28980b57cec5SDimitry Andric 
28990b57cec5SDimitry Andric       for (auto &I : PN->operands())
29000b57cec5SDimitry Andric         NewPN->addIncoming(cast<GEPOperator>(I)->getOperand(DI),
29010b57cec5SDimitry Andric                            PN->getIncomingBlock(I));
29020b57cec5SDimitry Andric 
29030b57cec5SDimitry Andric       NewGEP->setOperand(DI, NewPN);
29040b57cec5SDimitry Andric     }
29050b57cec5SDimitry Andric 
29065f757f3fSDimitry Andric     NewGEP->insertBefore(*GEP.getParent(), GEP.getParent()->getFirstInsertionPt());
2907bdd1243dSDimitry Andric     return replaceOperand(GEP, 0, NewGEP);
29080b57cec5SDimitry Andric   }
29090b57cec5SDimitry Andric 
291004eeddc0SDimitry Andric   if (auto *Src = dyn_cast<GEPOperator>(PtrOp))
291104eeddc0SDimitry Andric     if (Instruction *I = visitGEPOfGEP(GEP, Src))
291204eeddc0SDimitry Andric       return I;
29130b57cec5SDimitry Andric 
2914*0fca6ea1SDimitry Andric   if (GEP.getNumIndices() == 1) {
29150b57cec5SDimitry Andric     unsigned AS = GEP.getPointerAddressSpace();
29160b57cec5SDimitry Andric     if (GEP.getOperand(1)->getType()->getScalarSizeInBits() ==
29170b57cec5SDimitry Andric         DL.getIndexSizeInBits(AS)) {
2918bdd1243dSDimitry Andric       uint64_t TyAllocSize = DL.getTypeAllocSize(GEPEltType).getFixedValue();
29190b57cec5SDimitry Andric 
29200b57cec5SDimitry Andric       if (TyAllocSize == 1) {
2921647cbc5dSDimitry Andric         // Canonicalize (gep i8* X, (ptrtoint Y)-(ptrtoint X)) to (bitcast Y),
2922647cbc5dSDimitry Andric         // but only if the result pointer is only used as if it were an integer,
2923647cbc5dSDimitry Andric         // or both point to the same underlying object (otherwise provenance is
2924647cbc5dSDimitry Andric         // not necessarily retained).
2925647cbc5dSDimitry Andric         Value *X = GEP.getPointerOperand();
29260b57cec5SDimitry Andric         Value *Y;
2927647cbc5dSDimitry Andric         if (match(GEP.getOperand(1),
2928647cbc5dSDimitry Andric                   m_Sub(m_PtrToInt(m_Value(Y)), m_PtrToInt(m_Specific(X)))) &&
2929647cbc5dSDimitry Andric             GEPType == Y->getType()) {
2930647cbc5dSDimitry Andric           bool HasSameUnderlyingObject =
2931647cbc5dSDimitry Andric               getUnderlyingObject(X) == getUnderlyingObject(Y);
2932647cbc5dSDimitry Andric           bool Changed = false;
2933647cbc5dSDimitry Andric           GEP.replaceUsesWithIf(Y, [&](Use &U) {
2934647cbc5dSDimitry Andric             bool ShouldReplace = HasSameUnderlyingObject ||
2935647cbc5dSDimitry Andric                                  isa<ICmpInst>(U.getUser()) ||
2936647cbc5dSDimitry Andric                                  isa<PtrToIntInst>(U.getUser());
2937647cbc5dSDimitry Andric             Changed |= ShouldReplace;
2938647cbc5dSDimitry Andric             return ShouldReplace;
2939647cbc5dSDimitry Andric           });
2940647cbc5dSDimitry Andric           return Changed ? &GEP : nullptr;
2941647cbc5dSDimitry Andric         }
2942*0fca6ea1SDimitry Andric       } else if (auto *ExactIns =
2943*0fca6ea1SDimitry Andric                      dyn_cast<PossiblyExactOperator>(GEP.getOperand(1))) {
2944647cbc5dSDimitry Andric         // Canonicalize (gep T* X, V / sizeof(T)) to (gep i8* X, V)
2945647cbc5dSDimitry Andric         Value *V;
2946*0fca6ea1SDimitry Andric         if (ExactIns->isExact()) {
2947647cbc5dSDimitry Andric           if ((has_single_bit(TyAllocSize) &&
2948647cbc5dSDimitry Andric                match(GEP.getOperand(1),
2949*0fca6ea1SDimitry Andric                      m_Shr(m_Value(V),
2950*0fca6ea1SDimitry Andric                            m_SpecificInt(countr_zero(TyAllocSize))))) ||
2951647cbc5dSDimitry Andric               match(GEP.getOperand(1),
2952*0fca6ea1SDimitry Andric                     m_IDiv(m_Value(V), m_SpecificInt(TyAllocSize)))) {
2953*0fca6ea1SDimitry Andric             return GetElementPtrInst::Create(Builder.getInt8Ty(),
2954*0fca6ea1SDimitry Andric                                              GEP.getPointerOperand(), V,
2955*0fca6ea1SDimitry Andric                                              GEP.getNoWrapFlags());
2956*0fca6ea1SDimitry Andric           }
2957*0fca6ea1SDimitry Andric         }
2958*0fca6ea1SDimitry Andric         if (ExactIns->isExact() && ExactIns->hasOneUse()) {
2959*0fca6ea1SDimitry Andric           // Try to canonicalize non-i8 element type to i8 if the index is an
2960*0fca6ea1SDimitry Andric           // exact instruction. If the index is an exact instruction (div/shr)
2961*0fca6ea1SDimitry Andric           // with a constant RHS, we can fold the non-i8 element scale into the
2962*0fca6ea1SDimitry Andric           // div/shr (similiar to the mul case, just inverted).
2963*0fca6ea1SDimitry Andric           const APInt *C;
2964*0fca6ea1SDimitry Andric           std::optional<APInt> NewC;
2965*0fca6ea1SDimitry Andric           if (has_single_bit(TyAllocSize) &&
2966*0fca6ea1SDimitry Andric               match(ExactIns, m_Shr(m_Value(V), m_APInt(C))) &&
2967*0fca6ea1SDimitry Andric               C->uge(countr_zero(TyAllocSize)))
2968*0fca6ea1SDimitry Andric             NewC = *C - countr_zero(TyAllocSize);
2969*0fca6ea1SDimitry Andric           else if (match(ExactIns, m_UDiv(m_Value(V), m_APInt(C)))) {
2970*0fca6ea1SDimitry Andric             APInt Quot;
2971*0fca6ea1SDimitry Andric             uint64_t Rem;
2972*0fca6ea1SDimitry Andric             APInt::udivrem(*C, TyAllocSize, Quot, Rem);
2973*0fca6ea1SDimitry Andric             if (Rem == 0)
2974*0fca6ea1SDimitry Andric               NewC = Quot;
2975*0fca6ea1SDimitry Andric           } else if (match(ExactIns, m_SDiv(m_Value(V), m_APInt(C)))) {
2976*0fca6ea1SDimitry Andric             APInt Quot;
2977*0fca6ea1SDimitry Andric             int64_t Rem;
2978*0fca6ea1SDimitry Andric             APInt::sdivrem(*C, TyAllocSize, Quot, Rem);
2979*0fca6ea1SDimitry Andric             // For sdiv we need to make sure we arent creating INT_MIN / -1.
2980*0fca6ea1SDimitry Andric             if (!Quot.isAllOnes() && Rem == 0)
2981*0fca6ea1SDimitry Andric               NewC = Quot;
2982*0fca6ea1SDimitry Andric           }
2983*0fca6ea1SDimitry Andric 
2984*0fca6ea1SDimitry Andric           if (NewC.has_value()) {
2985*0fca6ea1SDimitry Andric             Value *NewOp = Builder.CreateBinOp(
2986*0fca6ea1SDimitry Andric                 static_cast<Instruction::BinaryOps>(ExactIns->getOpcode()), V,
2987*0fca6ea1SDimitry Andric                 ConstantInt::get(V->getType(), *NewC));
2988*0fca6ea1SDimitry Andric             cast<BinaryOperator>(NewOp)->setIsExact();
2989*0fca6ea1SDimitry Andric             return GetElementPtrInst::Create(Builder.getInt8Ty(),
2990*0fca6ea1SDimitry Andric                                              GEP.getPointerOperand(), NewOp,
2991*0fca6ea1SDimitry Andric                                              GEP.getNoWrapFlags());
2992*0fca6ea1SDimitry Andric           }
2993647cbc5dSDimitry Andric         }
2994647cbc5dSDimitry Andric       }
29950b57cec5SDimitry Andric     }
29960b57cec5SDimitry Andric   }
29970b57cec5SDimitry Andric   // We do not handle pointer-vector geps here.
29980b57cec5SDimitry Andric   if (GEPType->isVectorTy())
29990b57cec5SDimitry Andric     return nullptr;
30000b57cec5SDimitry Andric 
30015f757f3fSDimitry Andric   if (GEP.getNumIndices() == 1) {
3002*0fca6ea1SDimitry Andric     // We can only preserve inbounds if the original gep is inbounds, the add
3003*0fca6ea1SDimitry Andric     // is nsw, and the add operands are non-negative.
3004*0fca6ea1SDimitry Andric     auto CanPreserveInBounds = [&](bool AddIsNSW, Value *Idx1, Value *Idx2) {
3005*0fca6ea1SDimitry Andric       SimplifyQuery Q = SQ.getWithInstruction(&GEP);
3006*0fca6ea1SDimitry Andric       return GEP.isInBounds() && AddIsNSW && isKnownNonNegative(Idx1, Q) &&
3007*0fca6ea1SDimitry Andric              isKnownNonNegative(Idx2, Q);
3008*0fca6ea1SDimitry Andric     };
3009*0fca6ea1SDimitry Andric 
30105f757f3fSDimitry Andric     // Try to replace ADD + GEP with GEP + GEP.
30115f757f3fSDimitry Andric     Value *Idx1, *Idx2;
30125f757f3fSDimitry Andric     if (match(GEP.getOperand(1),
30135f757f3fSDimitry Andric               m_OneUse(m_Add(m_Value(Idx1), m_Value(Idx2))))) {
30145f757f3fSDimitry Andric       //   %idx = add i64 %idx1, %idx2
30155f757f3fSDimitry Andric       //   %gep = getelementptr i32, ptr %ptr, i64 %idx
30165f757f3fSDimitry Andric       // as:
30175f757f3fSDimitry Andric       //   %newptr = getelementptr i32, ptr %ptr, i64 %idx1
30185f757f3fSDimitry Andric       //   %newgep = getelementptr i32, ptr %newptr, i64 %idx2
3019*0fca6ea1SDimitry Andric       bool IsInBounds = CanPreserveInBounds(
3020*0fca6ea1SDimitry Andric           cast<OverflowingBinaryOperator>(GEP.getOperand(1))->hasNoSignedWrap(),
3021*0fca6ea1SDimitry Andric           Idx1, Idx2);
3022*0fca6ea1SDimitry Andric       auto *NewPtr =
3023*0fca6ea1SDimitry Andric           Builder.CreateGEP(GEP.getSourceElementType(), GEP.getPointerOperand(),
3024*0fca6ea1SDimitry Andric                             Idx1, "", IsInBounds);
3025*0fca6ea1SDimitry Andric       return replaceInstUsesWith(
3026*0fca6ea1SDimitry Andric           GEP, Builder.CreateGEP(GEP.getSourceElementType(), NewPtr, Idx2, "",
3027*0fca6ea1SDimitry Andric                                  IsInBounds));
30285f757f3fSDimitry Andric     }
30295f757f3fSDimitry Andric     ConstantInt *C;
3030cb14a3feSDimitry Andric     if (match(GEP.getOperand(1), m_OneUse(m_SExtLike(m_OneUse(m_NSWAdd(
30315f757f3fSDimitry Andric                                      m_Value(Idx1), m_ConstantInt(C))))))) {
30325f757f3fSDimitry Andric       // %add = add nsw i32 %idx1, idx2
30335f757f3fSDimitry Andric       // %sidx = sext i32 %add to i64
30345f757f3fSDimitry Andric       // %gep = getelementptr i32, ptr %ptr, i64 %sidx
30355f757f3fSDimitry Andric       // as:
30365f757f3fSDimitry Andric       // %newptr = getelementptr i32, ptr %ptr, i32 %idx1
30375f757f3fSDimitry Andric       // %newgep = getelementptr i32, ptr %newptr, i32 idx2
3038*0fca6ea1SDimitry Andric       bool IsInBounds = CanPreserveInBounds(
3039*0fca6ea1SDimitry Andric           /*IsNSW=*/true, Idx1, C);
30405f757f3fSDimitry Andric       auto *NewPtr = Builder.CreateGEP(
3041*0fca6ea1SDimitry Andric           GEP.getSourceElementType(), GEP.getPointerOperand(),
3042*0fca6ea1SDimitry Andric           Builder.CreateSExt(Idx1, GEP.getOperand(1)->getType()), "",
3043*0fca6ea1SDimitry Andric           IsInBounds);
3044*0fca6ea1SDimitry Andric       return replaceInstUsesWith(
3045*0fca6ea1SDimitry Andric           GEP,
3046*0fca6ea1SDimitry Andric           Builder.CreateGEP(GEP.getSourceElementType(), NewPtr,
3047*0fca6ea1SDimitry Andric                             Builder.CreateSExt(C, GEP.getOperand(1)->getType()),
3048*0fca6ea1SDimitry Andric                             "", IsInBounds));
30495f757f3fSDimitry Andric     }
30505f757f3fSDimitry Andric   }
30515f757f3fSDimitry Andric 
30520b57cec5SDimitry Andric   if (!GEP.isInBounds()) {
30530b57cec5SDimitry Andric     unsigned IdxWidth =
30540b57cec5SDimitry Andric         DL.getIndexSizeInBits(PtrOp->getType()->getPointerAddressSpace());
30550b57cec5SDimitry Andric     APInt BasePtrOffset(IdxWidth, 0);
30560b57cec5SDimitry Andric     Value *UnderlyingPtrOp =
30570b57cec5SDimitry Andric             PtrOp->stripAndAccumulateInBoundsConstantOffsets(DL,
30580b57cec5SDimitry Andric                                                              BasePtrOffset);
305906c3fb27SDimitry Andric     bool CanBeNull, CanBeFreed;
306006c3fb27SDimitry Andric     uint64_t DerefBytes = UnderlyingPtrOp->getPointerDereferenceableBytes(
306106c3fb27SDimitry Andric         DL, CanBeNull, CanBeFreed);
306206c3fb27SDimitry Andric     if (!CanBeNull && !CanBeFreed && DerefBytes != 0) {
30630b57cec5SDimitry Andric       if (GEP.accumulateConstantOffset(DL, BasePtrOffset) &&
30640b57cec5SDimitry Andric           BasePtrOffset.isNonNegative()) {
306506c3fb27SDimitry Andric         APInt AllocSize(IdxWidth, DerefBytes);
30660b57cec5SDimitry Andric         if (BasePtrOffset.ule(AllocSize)) {
30670b57cec5SDimitry Andric           return GetElementPtrInst::CreateInBounds(
306804eeddc0SDimitry Andric               GEP.getSourceElementType(), PtrOp, Indices, GEP.getName());
30690b57cec5SDimitry Andric         }
30700b57cec5SDimitry Andric       }
30710b57cec5SDimitry Andric     }
30720b57cec5SDimitry Andric   }
30730b57cec5SDimitry Andric 
30745ffd83dbSDimitry Andric   if (Instruction *R = foldSelectGEP(GEP, Builder))
30755ffd83dbSDimitry Andric     return R;
30765ffd83dbSDimitry Andric 
30770b57cec5SDimitry Andric   return nullptr;
30780b57cec5SDimitry Andric }
30790b57cec5SDimitry Andric 
30800eae32dcSDimitry Andric static bool isNeverEqualToUnescapedAlloc(Value *V, const TargetLibraryInfo &TLI,
30810b57cec5SDimitry Andric                                          Instruction *AI) {
30820b57cec5SDimitry Andric   if (isa<ConstantPointerNull>(V))
30830b57cec5SDimitry Andric     return true;
30840b57cec5SDimitry Andric   if (auto *LI = dyn_cast<LoadInst>(V))
30850b57cec5SDimitry Andric     return isa<GlobalVariable>(LI->getPointerOperand());
30860b57cec5SDimitry Andric   // Two distinct allocations will never be equal.
30870eae32dcSDimitry Andric   return isAllocLikeFn(V, &TLI) && V != AI;
30880eae32dcSDimitry Andric }
30890eae32dcSDimitry Andric 
30900eae32dcSDimitry Andric /// Given a call CB which uses an address UsedV, return true if we can prove the
30910eae32dcSDimitry Andric /// call's only possible effect is storing to V.
30920eae32dcSDimitry Andric static bool isRemovableWrite(CallBase &CB, Value *UsedV,
30930eae32dcSDimitry Andric                              const TargetLibraryInfo &TLI) {
30940eae32dcSDimitry Andric   if (!CB.use_empty())
30950eae32dcSDimitry Andric     // TODO: add recursion if returned attribute is present
30960eae32dcSDimitry Andric     return false;
30970eae32dcSDimitry Andric 
30980eae32dcSDimitry Andric   if (CB.isTerminator())
30990eae32dcSDimitry Andric     // TODO: remove implementation restriction
31000eae32dcSDimitry Andric     return false;
31010eae32dcSDimitry Andric 
31020eae32dcSDimitry Andric   if (!CB.willReturn() || !CB.doesNotThrow())
31030eae32dcSDimitry Andric     return false;
31040eae32dcSDimitry Andric 
31050eae32dcSDimitry Andric   // If the only possible side effect of the call is writing to the alloca,
31060eae32dcSDimitry Andric   // and the result isn't used, we can safely remove any reads implied by the
31070eae32dcSDimitry Andric   // call including those which might read the alloca itself.
3108bdd1243dSDimitry Andric   std::optional<MemoryLocation> Dest = MemoryLocation::getForDest(&CB, TLI);
31090eae32dcSDimitry Andric   return Dest && Dest->Ptr == UsedV;
31100b57cec5SDimitry Andric }
31110b57cec5SDimitry Andric 
31120b57cec5SDimitry Andric static bool isAllocSiteRemovable(Instruction *AI,
31130b57cec5SDimitry Andric                                  SmallVectorImpl<WeakTrackingVH> &Users,
31140eae32dcSDimitry Andric                                  const TargetLibraryInfo &TLI) {
31150b57cec5SDimitry Andric   SmallVector<Instruction*, 4> Worklist;
3116bdd1243dSDimitry Andric   const std::optional<StringRef> Family = getAllocationFamily(AI, &TLI);
31170b57cec5SDimitry Andric   Worklist.push_back(AI);
31180b57cec5SDimitry Andric 
31190b57cec5SDimitry Andric   do {
31200b57cec5SDimitry Andric     Instruction *PI = Worklist.pop_back_val();
31210b57cec5SDimitry Andric     for (User *U : PI->users()) {
31220b57cec5SDimitry Andric       Instruction *I = cast<Instruction>(U);
31230b57cec5SDimitry Andric       switch (I->getOpcode()) {
31240b57cec5SDimitry Andric       default:
31250b57cec5SDimitry Andric         // Give up the moment we see something we can't handle.
31260b57cec5SDimitry Andric         return false;
31270b57cec5SDimitry Andric 
31280b57cec5SDimitry Andric       case Instruction::AddrSpaceCast:
31290b57cec5SDimitry Andric       case Instruction::BitCast:
31300b57cec5SDimitry Andric       case Instruction::GetElementPtr:
31310b57cec5SDimitry Andric         Users.emplace_back(I);
31320b57cec5SDimitry Andric         Worklist.push_back(I);
31330b57cec5SDimitry Andric         continue;
31340b57cec5SDimitry Andric 
31350b57cec5SDimitry Andric       case Instruction::ICmp: {
31360b57cec5SDimitry Andric         ICmpInst *ICI = cast<ICmpInst>(I);
31370b57cec5SDimitry Andric         // We can fold eq/ne comparisons with null to false/true, respectively.
31380b57cec5SDimitry Andric         // We also fold comparisons in some conditions provided the alloc has
31390b57cec5SDimitry Andric         // not escaped (see isNeverEqualToUnescapedAlloc).
31400b57cec5SDimitry Andric         if (!ICI->isEquality())
31410b57cec5SDimitry Andric           return false;
31420b57cec5SDimitry Andric         unsigned OtherIndex = (ICI->getOperand(0) == PI) ? 1 : 0;
31430b57cec5SDimitry Andric         if (!isNeverEqualToUnescapedAlloc(ICI->getOperand(OtherIndex), TLI, AI))
31440b57cec5SDimitry Andric           return false;
31455f757f3fSDimitry Andric 
31465f757f3fSDimitry Andric         // Do not fold compares to aligned_alloc calls, as they may have to
31475f757f3fSDimitry Andric         // return null in case the required alignment cannot be satisfied,
31485f757f3fSDimitry Andric         // unless we can prove that both alignment and size are valid.
31495f757f3fSDimitry Andric         auto AlignmentAndSizeKnownValid = [](CallBase *CB) {
31505f757f3fSDimitry Andric           // Check if alignment and size of a call to aligned_alloc is valid,
31515f757f3fSDimitry Andric           // that is alignment is a power-of-2 and the size is a multiple of the
31525f757f3fSDimitry Andric           // alignment.
31535f757f3fSDimitry Andric           const APInt *Alignment;
31545f757f3fSDimitry Andric           const APInt *Size;
31555f757f3fSDimitry Andric           return match(CB->getArgOperand(0), m_APInt(Alignment)) &&
31565f757f3fSDimitry Andric                  match(CB->getArgOperand(1), m_APInt(Size)) &&
31575f757f3fSDimitry Andric                  Alignment->isPowerOf2() && Size->urem(*Alignment).isZero();
31585f757f3fSDimitry Andric         };
31595f757f3fSDimitry Andric         auto *CB = dyn_cast<CallBase>(AI);
31605f757f3fSDimitry Andric         LibFunc TheLibFunc;
31615f757f3fSDimitry Andric         if (CB && TLI.getLibFunc(*CB->getCalledFunction(), TheLibFunc) &&
31625f757f3fSDimitry Andric             TLI.has(TheLibFunc) && TheLibFunc == LibFunc_aligned_alloc &&
31635f757f3fSDimitry Andric             !AlignmentAndSizeKnownValid(CB))
31645f757f3fSDimitry Andric           return false;
31650b57cec5SDimitry Andric         Users.emplace_back(I);
31660b57cec5SDimitry Andric         continue;
31670b57cec5SDimitry Andric       }
31680b57cec5SDimitry Andric 
31690b57cec5SDimitry Andric       case Instruction::Call:
31700b57cec5SDimitry Andric         // Ignore no-op and store intrinsics.
31710b57cec5SDimitry Andric         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
31720b57cec5SDimitry Andric           switch (II->getIntrinsicID()) {
31730b57cec5SDimitry Andric           default:
31740b57cec5SDimitry Andric             return false;
31750b57cec5SDimitry Andric 
31760b57cec5SDimitry Andric           case Intrinsic::memmove:
31770b57cec5SDimitry Andric           case Intrinsic::memcpy:
31780b57cec5SDimitry Andric           case Intrinsic::memset: {
31790b57cec5SDimitry Andric             MemIntrinsic *MI = cast<MemIntrinsic>(II);
31800b57cec5SDimitry Andric             if (MI->isVolatile() || MI->getRawDest() != PI)
31810b57cec5SDimitry Andric               return false;
3182bdd1243dSDimitry Andric             [[fallthrough]];
31830b57cec5SDimitry Andric           }
31845ffd83dbSDimitry Andric           case Intrinsic::assume:
31850b57cec5SDimitry Andric           case Intrinsic::invariant_start:
31860b57cec5SDimitry Andric           case Intrinsic::invariant_end:
31870b57cec5SDimitry Andric           case Intrinsic::lifetime_start:
31880b57cec5SDimitry Andric           case Intrinsic::lifetime_end:
31890b57cec5SDimitry Andric           case Intrinsic::objectsize:
31900b57cec5SDimitry Andric             Users.emplace_back(I);
31910b57cec5SDimitry Andric             continue;
3192fe6060f1SDimitry Andric           case Intrinsic::launder_invariant_group:
3193fe6060f1SDimitry Andric           case Intrinsic::strip_invariant_group:
3194fe6060f1SDimitry Andric             Users.emplace_back(I);
3195fe6060f1SDimitry Andric             Worklist.push_back(I);
3196fe6060f1SDimitry Andric             continue;
31970b57cec5SDimitry Andric           }
31980b57cec5SDimitry Andric         }
31990b57cec5SDimitry Andric 
32000eae32dcSDimitry Andric         if (isRemovableWrite(*cast<CallBase>(I), PI, TLI)) {
32010b57cec5SDimitry Andric           Users.emplace_back(I);
32020b57cec5SDimitry Andric           continue;
32030b57cec5SDimitry Andric         }
3204349cc55cSDimitry Andric 
3205fcaf7f86SDimitry Andric         if (getFreedOperand(cast<CallBase>(I), &TLI) == PI &&
3206fcaf7f86SDimitry Andric             getAllocationFamily(I, &TLI) == Family) {
320781ad6265SDimitry Andric           assert(Family);
32080eae32dcSDimitry Andric           Users.emplace_back(I);
32090eae32dcSDimitry Andric           continue;
32100eae32dcSDimitry Andric         }
32110eae32dcSDimitry Andric 
3212bdd1243dSDimitry Andric         if (getReallocatedOperand(cast<CallBase>(I)) == PI &&
321381ad6265SDimitry Andric             getAllocationFamily(I, &TLI) == Family) {
321481ad6265SDimitry Andric           assert(Family);
3215349cc55cSDimitry Andric           Users.emplace_back(I);
3216349cc55cSDimitry Andric           Worklist.push_back(I);
3217349cc55cSDimitry Andric           continue;
3218349cc55cSDimitry Andric         }
3219349cc55cSDimitry Andric 
32200b57cec5SDimitry Andric         return false;
32210b57cec5SDimitry Andric 
32220b57cec5SDimitry Andric       case Instruction::Store: {
32230b57cec5SDimitry Andric         StoreInst *SI = cast<StoreInst>(I);
32240b57cec5SDimitry Andric         if (SI->isVolatile() || SI->getPointerOperand() != PI)
32250b57cec5SDimitry Andric           return false;
32260b57cec5SDimitry Andric         Users.emplace_back(I);
32270b57cec5SDimitry Andric         continue;
32280b57cec5SDimitry Andric       }
32290b57cec5SDimitry Andric       }
32300b57cec5SDimitry Andric       llvm_unreachable("missing a return?");
32310b57cec5SDimitry Andric     }
32320b57cec5SDimitry Andric   } while (!Worklist.empty());
32330b57cec5SDimitry Andric   return true;
32340b57cec5SDimitry Andric }
32350b57cec5SDimitry Andric 
3236e8d8bef9SDimitry Andric Instruction *InstCombinerImpl::visitAllocSite(Instruction &MI) {
3237fcaf7f86SDimitry Andric   assert(isa<AllocaInst>(MI) || isRemovableAlloc(&cast<CallBase>(MI), &TLI));
323804eeddc0SDimitry Andric 
32390b57cec5SDimitry Andric   // If we have a malloc call which is only used in any amount of comparisons to
32400b57cec5SDimitry Andric   // null and free calls, delete the calls and replace the comparisons with true
32410b57cec5SDimitry Andric   // or false as appropriate.
32420b57cec5SDimitry Andric 
32430b57cec5SDimitry Andric   // This is based on the principle that we can substitute our own allocation
32440b57cec5SDimitry Andric   // function (which will never return null) rather than knowledge of the
32450b57cec5SDimitry Andric   // specific function being called. In some sense this can change the permitted
32460b57cec5SDimitry Andric   // outputs of a program (when we convert a malloc to an alloca, the fact that
32470b57cec5SDimitry Andric   // the allocation is now on the stack is potentially visible, for example),
32480b57cec5SDimitry Andric   // but we believe in a permissible manner.
32490b57cec5SDimitry Andric   SmallVector<WeakTrackingVH, 64> Users;
32500b57cec5SDimitry Andric 
32510b57cec5SDimitry Andric   // If we are removing an alloca with a dbg.declare, insert dbg.value calls
32520b57cec5SDimitry Andric   // before each store.
3253e8d8bef9SDimitry Andric   SmallVector<DbgVariableIntrinsic *, 8> DVIs;
3254*0fca6ea1SDimitry Andric   SmallVector<DbgVariableRecord *, 8> DVRs;
32550b57cec5SDimitry Andric   std::unique_ptr<DIBuilder> DIB;
32560b57cec5SDimitry Andric   if (isa<AllocaInst>(MI)) {
3257*0fca6ea1SDimitry Andric     findDbgUsers(DVIs, &MI, &DVRs);
32580b57cec5SDimitry Andric     DIB.reset(new DIBuilder(*MI.getModule(), /*AllowUnresolved=*/false));
32590b57cec5SDimitry Andric   }
32600b57cec5SDimitry Andric 
32610eae32dcSDimitry Andric   if (isAllocSiteRemovable(&MI, Users, TLI)) {
32620b57cec5SDimitry Andric     for (unsigned i = 0, e = Users.size(); i != e; ++i) {
32630b57cec5SDimitry Andric       // Lowering all @llvm.objectsize calls first because they may
32640b57cec5SDimitry Andric       // use a bitcast/GEP of the alloca we are removing.
32650b57cec5SDimitry Andric       if (!Users[i])
32660b57cec5SDimitry Andric        continue;
32670b57cec5SDimitry Andric 
32680b57cec5SDimitry Andric       Instruction *I = cast<Instruction>(&*Users[i]);
32690b57cec5SDimitry Andric 
32700b57cec5SDimitry Andric       if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
32710b57cec5SDimitry Andric         if (II->getIntrinsicID() == Intrinsic::objectsize) {
327206c3fb27SDimitry Andric           SmallVector<Instruction *> InsertedInstructions;
327306c3fb27SDimitry Andric           Value *Result = lowerObjectSizeCall(
327406c3fb27SDimitry Andric               II, DL, &TLI, AA, /*MustSucceed=*/true, &InsertedInstructions);
327506c3fb27SDimitry Andric           for (Instruction *Inserted : InsertedInstructions)
327606c3fb27SDimitry Andric             Worklist.add(Inserted);
32770b57cec5SDimitry Andric           replaceInstUsesWith(*I, Result);
32780b57cec5SDimitry Andric           eraseInstFromFunction(*I);
32790b57cec5SDimitry Andric           Users[i] = nullptr; // Skip examining in the next loop.
32800b57cec5SDimitry Andric         }
32810b57cec5SDimitry Andric       }
32820b57cec5SDimitry Andric     }
32830b57cec5SDimitry Andric     for (unsigned i = 0, e = Users.size(); i != e; ++i) {
32840b57cec5SDimitry Andric       if (!Users[i])
32850b57cec5SDimitry Andric         continue;
32860b57cec5SDimitry Andric 
32870b57cec5SDimitry Andric       Instruction *I = cast<Instruction>(&*Users[i]);
32880b57cec5SDimitry Andric 
32890b57cec5SDimitry Andric       if (ICmpInst *C = dyn_cast<ICmpInst>(I)) {
32900b57cec5SDimitry Andric         replaceInstUsesWith(*C,
32910b57cec5SDimitry Andric                             ConstantInt::get(Type::getInt1Ty(C->getContext()),
32920b57cec5SDimitry Andric                                              C->isFalseWhenEqual()));
32930b57cec5SDimitry Andric       } else if (auto *SI = dyn_cast<StoreInst>(I)) {
3294e8d8bef9SDimitry Andric         for (auto *DVI : DVIs)
3295e8d8bef9SDimitry Andric           if (DVI->isAddressOfVariable())
3296e8d8bef9SDimitry Andric             ConvertDebugDeclareToDebugValue(DVI, SI, *DIB);
3297*0fca6ea1SDimitry Andric         for (auto *DVR : DVRs)
3298*0fca6ea1SDimitry Andric           if (DVR->isAddressOfVariable())
3299*0fca6ea1SDimitry Andric             ConvertDebugDeclareToDebugValue(DVR, SI, *DIB);
3300480093f4SDimitry Andric       } else {
3301480093f4SDimitry Andric         // Casts, GEP, or anything else: we're about to delete this instruction,
3302480093f4SDimitry Andric         // so it can not have any valid uses.
3303fe6060f1SDimitry Andric         replaceInstUsesWith(*I, PoisonValue::get(I->getType()));
33040b57cec5SDimitry Andric       }
33050b57cec5SDimitry Andric       eraseInstFromFunction(*I);
33060b57cec5SDimitry Andric     }
33070b57cec5SDimitry Andric 
33080b57cec5SDimitry Andric     if (InvokeInst *II = dyn_cast<InvokeInst>(&MI)) {
33090b57cec5SDimitry Andric       // Replace invoke with a NOP intrinsic to maintain the original CFG
33100b57cec5SDimitry Andric       Module *M = II->getModule();
33110b57cec5SDimitry Andric       Function *F = Intrinsic::getDeclaration(M, Intrinsic::donothing);
33120b57cec5SDimitry Andric       InvokeInst::Create(F, II->getNormalDest(), II->getUnwindDest(),
3313bdd1243dSDimitry Andric                          std::nullopt, "", II->getParent());
33140b57cec5SDimitry Andric     }
33150b57cec5SDimitry Andric 
3316e8d8bef9SDimitry Andric     // Remove debug intrinsics which describe the value contained within the
3317e8d8bef9SDimitry Andric     // alloca. In addition to removing dbg.{declare,addr} which simply point to
3318e8d8bef9SDimitry Andric     // the alloca, remove dbg.value(<alloca>, ..., DW_OP_deref)'s as well, e.g.:
3319e8d8bef9SDimitry Andric     //
3320e8d8bef9SDimitry Andric     // ```
3321e8d8bef9SDimitry Andric     //   define void @foo(i32 %0) {
3322e8d8bef9SDimitry Andric     //     %a = alloca i32                              ; Deleted.
3323e8d8bef9SDimitry Andric     //     store i32 %0, i32* %a
3324e8d8bef9SDimitry Andric     //     dbg.value(i32 %0, "arg0")                    ; Not deleted.
3325e8d8bef9SDimitry Andric     //     dbg.value(i32* %a, "arg0", DW_OP_deref)      ; Deleted.
3326e8d8bef9SDimitry Andric     //     call void @trivially_inlinable_no_op(i32* %a)
3327e8d8bef9SDimitry Andric     //     ret void
3328e8d8bef9SDimitry Andric     //  }
3329e8d8bef9SDimitry Andric     // ```
3330e8d8bef9SDimitry Andric     //
3331e8d8bef9SDimitry Andric     // This may not be required if we stop describing the contents of allocas
3332e8d8bef9SDimitry Andric     // using dbg.value(<alloca>, ..., DW_OP_deref), but we currently do this in
3333e8d8bef9SDimitry Andric     // the LowerDbgDeclare utility.
3334e8d8bef9SDimitry Andric     //
3335e8d8bef9SDimitry Andric     // If there is a dead store to `%a` in @trivially_inlinable_no_op, the
3336e8d8bef9SDimitry Andric     // "arg0" dbg.value may be stale after the call. However, failing to remove
3337e8d8bef9SDimitry Andric     // the DW_OP_deref dbg.value causes large gaps in location coverage.
33385f757f3fSDimitry Andric     //
33395f757f3fSDimitry Andric     // FIXME: the Assignment Tracking project has now likely made this
33405f757f3fSDimitry Andric     // redundant (and it's sometimes harmful).
3341e8d8bef9SDimitry Andric     for (auto *DVI : DVIs)
3342e8d8bef9SDimitry Andric       if (DVI->isAddressOfVariable() || DVI->getExpression()->startsWithDeref())
3343e8d8bef9SDimitry Andric         DVI->eraseFromParent();
3344*0fca6ea1SDimitry Andric     for (auto *DVR : DVRs)
3345*0fca6ea1SDimitry Andric       if (DVR->isAddressOfVariable() || DVR->getExpression()->startsWithDeref())
3346*0fca6ea1SDimitry Andric         DVR->eraseFromParent();
33470b57cec5SDimitry Andric 
33480b57cec5SDimitry Andric     return eraseInstFromFunction(MI);
33490b57cec5SDimitry Andric   }
33500b57cec5SDimitry Andric   return nullptr;
33510b57cec5SDimitry Andric }
33520b57cec5SDimitry Andric 
33530b57cec5SDimitry Andric /// Move the call to free before a NULL test.
33540b57cec5SDimitry Andric ///
33550b57cec5SDimitry Andric /// Check if this free is accessed after its argument has been test
33560b57cec5SDimitry Andric /// against NULL (property 0).
33570b57cec5SDimitry Andric /// If yes, it is legal to move this call in its predecessor block.
33580b57cec5SDimitry Andric ///
33590b57cec5SDimitry Andric /// The move is performed only if the block containing the call to free
33600b57cec5SDimitry Andric /// will be removed, i.e.:
33610b57cec5SDimitry Andric /// 1. it has only one predecessor P, and P has two successors
33620b57cec5SDimitry Andric /// 2. it contains the call, noops, and an unconditional branch
33630b57cec5SDimitry Andric /// 3. its successor is the same as its predecessor's successor
33640b57cec5SDimitry Andric ///
33650b57cec5SDimitry Andric /// The profitability is out-of concern here and this function should
33660b57cec5SDimitry Andric /// be called only if the caller knows this transformation would be
33670b57cec5SDimitry Andric /// profitable (e.g., for code size).
33680b57cec5SDimitry Andric static Instruction *tryToMoveFreeBeforeNullTest(CallInst &FI,
33690b57cec5SDimitry Andric                                                 const DataLayout &DL) {
33700b57cec5SDimitry Andric   Value *Op = FI.getArgOperand(0);
33710b57cec5SDimitry Andric   BasicBlock *FreeInstrBB = FI.getParent();
33720b57cec5SDimitry Andric   BasicBlock *PredBB = FreeInstrBB->getSinglePredecessor();
33730b57cec5SDimitry Andric 
33740b57cec5SDimitry Andric   // Validate part of constraint #1: Only one predecessor
33750b57cec5SDimitry Andric   // FIXME: We can extend the number of predecessor, but in that case, we
33760b57cec5SDimitry Andric   //        would duplicate the call to free in each predecessor and it may
33770b57cec5SDimitry Andric   //        not be profitable even for code size.
33780b57cec5SDimitry Andric   if (!PredBB)
33790b57cec5SDimitry Andric     return nullptr;
33800b57cec5SDimitry Andric 
33810b57cec5SDimitry Andric   // Validate constraint #2: Does this block contains only the call to
33820b57cec5SDimitry Andric   //                         free, noops, and an unconditional branch?
33830b57cec5SDimitry Andric   BasicBlock *SuccBB;
33840b57cec5SDimitry Andric   Instruction *FreeInstrBBTerminator = FreeInstrBB->getTerminator();
33850b57cec5SDimitry Andric   if (!match(FreeInstrBBTerminator, m_UnconditionalBr(SuccBB)))
33860b57cec5SDimitry Andric     return nullptr;
33870b57cec5SDimitry Andric 
33880b57cec5SDimitry Andric   // If there are only 2 instructions in the block, at this point,
33890b57cec5SDimitry Andric   // this is the call to free and unconditional.
33900b57cec5SDimitry Andric   // If there are more than 2 instructions, check that they are noops
33910b57cec5SDimitry Andric   // i.e., they won't hurt the performance of the generated code.
33920b57cec5SDimitry Andric   if (FreeInstrBB->size() != 2) {
33935ffd83dbSDimitry Andric     for (const Instruction &Inst : FreeInstrBB->instructionsWithoutDebug()) {
33940b57cec5SDimitry Andric       if (&Inst == &FI || &Inst == FreeInstrBBTerminator)
33950b57cec5SDimitry Andric         continue;
33960b57cec5SDimitry Andric       auto *Cast = dyn_cast<CastInst>(&Inst);
33970b57cec5SDimitry Andric       if (!Cast || !Cast->isNoopCast(DL))
33980b57cec5SDimitry Andric         return nullptr;
33990b57cec5SDimitry Andric     }
34000b57cec5SDimitry Andric   }
34010b57cec5SDimitry Andric   // Validate the rest of constraint #1 by matching on the pred branch.
34020b57cec5SDimitry Andric   Instruction *TI = PredBB->getTerminator();
34030b57cec5SDimitry Andric   BasicBlock *TrueBB, *FalseBB;
34040b57cec5SDimitry Andric   ICmpInst::Predicate Pred;
34050b57cec5SDimitry Andric   if (!match(TI, m_Br(m_ICmp(Pred,
34060b57cec5SDimitry Andric                              m_CombineOr(m_Specific(Op),
34070b57cec5SDimitry Andric                                          m_Specific(Op->stripPointerCasts())),
34080b57cec5SDimitry Andric                              m_Zero()),
34090b57cec5SDimitry Andric                       TrueBB, FalseBB)))
34100b57cec5SDimitry Andric     return nullptr;
34110b57cec5SDimitry Andric   if (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE)
34120b57cec5SDimitry Andric     return nullptr;
34130b57cec5SDimitry Andric 
34140b57cec5SDimitry Andric   // Validate constraint #3: Ensure the null case just falls through.
34150b57cec5SDimitry Andric   if (SuccBB != (Pred == ICmpInst::ICMP_EQ ? TrueBB : FalseBB))
34160b57cec5SDimitry Andric     return nullptr;
34170b57cec5SDimitry Andric   assert(FreeInstrBB == (Pred == ICmpInst::ICMP_EQ ? FalseBB : TrueBB) &&
34180b57cec5SDimitry Andric          "Broken CFG: missing edge from predecessor to successor");
34190b57cec5SDimitry Andric 
34200b57cec5SDimitry Andric   // At this point, we know that everything in FreeInstrBB can be moved
34210b57cec5SDimitry Andric   // before TI.
3422349cc55cSDimitry Andric   for (Instruction &Instr : llvm::make_early_inc_range(*FreeInstrBB)) {
34230b57cec5SDimitry Andric     if (&Instr == FreeInstrBBTerminator)
34240b57cec5SDimitry Andric       break;
34255f757f3fSDimitry Andric     Instr.moveBeforePreserving(TI);
34260b57cec5SDimitry Andric   }
34270b57cec5SDimitry Andric   assert(FreeInstrBB->size() == 1 &&
34280b57cec5SDimitry Andric          "Only the branch instruction should remain");
3429349cc55cSDimitry Andric 
3430349cc55cSDimitry Andric   // Now that we've moved the call to free before the NULL check, we have to
3431349cc55cSDimitry Andric   // remove any attributes on its parameter that imply it's non-null, because
3432349cc55cSDimitry Andric   // those attributes might have only been valid because of the NULL check, and
3433349cc55cSDimitry Andric   // we can get miscompiles if we keep them. This is conservative if non-null is
3434349cc55cSDimitry Andric   // also implied by something other than the NULL check, but it's guaranteed to
3435349cc55cSDimitry Andric   // be correct, and the conservativeness won't matter in practice, since the
3436349cc55cSDimitry Andric   // attributes are irrelevant for the call to free itself and the pointer
3437349cc55cSDimitry Andric   // shouldn't be used after the call.
3438349cc55cSDimitry Andric   AttributeList Attrs = FI.getAttributes();
3439349cc55cSDimitry Andric   Attrs = Attrs.removeParamAttribute(FI.getContext(), 0, Attribute::NonNull);
3440349cc55cSDimitry Andric   Attribute Dereferenceable = Attrs.getParamAttr(0, Attribute::Dereferenceable);
3441349cc55cSDimitry Andric   if (Dereferenceable.isValid()) {
3442349cc55cSDimitry Andric     uint64_t Bytes = Dereferenceable.getDereferenceableBytes();
3443349cc55cSDimitry Andric     Attrs = Attrs.removeParamAttribute(FI.getContext(), 0,
3444349cc55cSDimitry Andric                                        Attribute::Dereferenceable);
3445349cc55cSDimitry Andric     Attrs = Attrs.addDereferenceableOrNullParamAttr(FI.getContext(), 0, Bytes);
3446349cc55cSDimitry Andric   }
3447349cc55cSDimitry Andric   FI.setAttributes(Attrs);
3448349cc55cSDimitry Andric 
34490b57cec5SDimitry Andric   return &FI;
34500b57cec5SDimitry Andric }
34510b57cec5SDimitry Andric 
3452fcaf7f86SDimitry Andric Instruction *InstCombinerImpl::visitFree(CallInst &FI, Value *Op) {
34530b57cec5SDimitry Andric   // free undef -> unreachable.
34540b57cec5SDimitry Andric   if (isa<UndefValue>(Op)) {
34550b57cec5SDimitry Andric     // Leave a marker since we can't modify the CFG here.
34560b57cec5SDimitry Andric     CreateNonTerminatorUnreachable(&FI);
34570b57cec5SDimitry Andric     return eraseInstFromFunction(FI);
34580b57cec5SDimitry Andric   }
34590b57cec5SDimitry Andric 
34600b57cec5SDimitry Andric   // If we have 'free null' delete the instruction.  This can happen in stl code
34610b57cec5SDimitry Andric   // when lots of inlining happens.
34620b57cec5SDimitry Andric   if (isa<ConstantPointerNull>(Op))
34630b57cec5SDimitry Andric     return eraseInstFromFunction(FI);
34640b57cec5SDimitry Andric 
3465349cc55cSDimitry Andric   // If we had free(realloc(...)) with no intervening uses, then eliminate the
3466349cc55cSDimitry Andric   // realloc() entirely.
3467fcaf7f86SDimitry Andric   CallInst *CI = dyn_cast<CallInst>(Op);
3468fcaf7f86SDimitry Andric   if (CI && CI->hasOneUse())
3469bdd1243dSDimitry Andric     if (Value *ReallocatedOp = getReallocatedOperand(CI))
3470fcaf7f86SDimitry Andric       return eraseInstFromFunction(*replaceInstUsesWith(*CI, ReallocatedOp));
3471349cc55cSDimitry Andric 
34720b57cec5SDimitry Andric   // If we optimize for code size, try to move the call to free before the null
34730b57cec5SDimitry Andric   // test so that simplify cfg can remove the empty block and dead code
34740b57cec5SDimitry Andric   // elimination the branch. I.e., helps to turn something like:
34750b57cec5SDimitry Andric   // if (foo) free(foo);
34760b57cec5SDimitry Andric   // into
34770b57cec5SDimitry Andric   // free(foo);
34785ffd83dbSDimitry Andric   //
34795ffd83dbSDimitry Andric   // Note that we can only do this for 'free' and not for any flavor of
34805ffd83dbSDimitry Andric   // 'operator delete'; there is no 'operator delete' symbol for which we are
34815ffd83dbSDimitry Andric   // permitted to invent a call, even if we're passing in a null pointer.
34825ffd83dbSDimitry Andric   if (MinimizeSize) {
34835ffd83dbSDimitry Andric     LibFunc Func;
34845ffd83dbSDimitry Andric     if (TLI.getLibFunc(FI, Func) && TLI.has(Func) && Func == LibFunc_free)
34850b57cec5SDimitry Andric       if (Instruction *I = tryToMoveFreeBeforeNullTest(FI, DL))
34860b57cec5SDimitry Andric         return I;
34875ffd83dbSDimitry Andric   }
34880b57cec5SDimitry Andric 
34890b57cec5SDimitry Andric   return nullptr;
34900b57cec5SDimitry Andric }
34910b57cec5SDimitry Andric 
3492e8d8bef9SDimitry Andric Instruction *InstCombinerImpl::visitReturnInst(ReturnInst &RI) {
3493*0fca6ea1SDimitry Andric   Value *RetVal = RI.getReturnValue();
3494*0fca6ea1SDimitry Andric   if (!RetVal || !AttributeFuncs::isNoFPClassCompatibleType(RetVal->getType()))
34955ffd83dbSDimitry Andric     return nullptr;
3496*0fca6ea1SDimitry Andric 
3497*0fca6ea1SDimitry Andric   Function *F = RI.getFunction();
3498*0fca6ea1SDimitry Andric   FPClassTest ReturnClass = F->getAttributes().getRetNoFPClass();
3499*0fca6ea1SDimitry Andric   if (ReturnClass == fcNone)
3500*0fca6ea1SDimitry Andric     return nullptr;
3501*0fca6ea1SDimitry Andric 
3502*0fca6ea1SDimitry Andric   KnownFPClass KnownClass;
3503*0fca6ea1SDimitry Andric   Value *Simplified =
3504*0fca6ea1SDimitry Andric       SimplifyDemandedUseFPClass(RetVal, ~ReturnClass, KnownClass, 0, &RI);
3505*0fca6ea1SDimitry Andric   if (!Simplified)
3506*0fca6ea1SDimitry Andric     return nullptr;
3507*0fca6ea1SDimitry Andric 
3508*0fca6ea1SDimitry Andric   return ReturnInst::Create(RI.getContext(), Simplified);
35095ffd83dbSDimitry Andric }
35105ffd83dbSDimitry Andric 
3511fe6060f1SDimitry Andric // WARNING: keep in sync with SimplifyCFGOpt::simplifyUnreachable()!
351206c3fb27SDimitry Andric bool InstCombinerImpl::removeInstructionsBeforeUnreachable(Instruction &I) {
3513e8d8bef9SDimitry Andric   // Try to remove the previous instruction if it must lead to unreachable.
3514e8d8bef9SDimitry Andric   // This includes instructions like stores and "llvm.assume" that may not get
3515e8d8bef9SDimitry Andric   // removed by simple dead code elimination.
351606c3fb27SDimitry Andric   bool Changed = false;
3517fe6060f1SDimitry Andric   while (Instruction *Prev = I.getPrevNonDebugInstruction()) {
3518fe6060f1SDimitry Andric     // While we theoretically can erase EH, that would result in a block that
3519fe6060f1SDimitry Andric     // used to start with an EH no longer starting with EH, which is invalid.
3520fe6060f1SDimitry Andric     // To make it valid, we'd need to fixup predecessors to no longer refer to
3521fe6060f1SDimitry Andric     // this block, but that changes CFG, which is not allowed in InstCombine.
3522fe6060f1SDimitry Andric     if (Prev->isEHPad())
352306c3fb27SDimitry Andric       break; // Can not drop any more instructions. We're done here.
3524fe6060f1SDimitry Andric 
3525fe6060f1SDimitry Andric     if (!isGuaranteedToTransferExecutionToSuccessor(Prev))
352606c3fb27SDimitry Andric       break; // Can not drop any more instructions. We're done here.
3527fe6060f1SDimitry Andric     // Otherwise, this instruction can be freely erased,
3528fe6060f1SDimitry Andric     // even if it is not side-effect free.
3529e8d8bef9SDimitry Andric 
3530e8d8bef9SDimitry Andric     // A value may still have uses before we process it here (for example, in
3531fe6060f1SDimitry Andric     // another unreachable block), so convert those to poison.
3532fe6060f1SDimitry Andric     replaceInstUsesWith(*Prev, PoisonValue::get(Prev->getType()));
3533e8d8bef9SDimitry Andric     eraseInstFromFunction(*Prev);
353406c3fb27SDimitry Andric     Changed = true;
3535e8d8bef9SDimitry Andric   }
353606c3fb27SDimitry Andric   return Changed;
353706c3fb27SDimitry Andric }
353806c3fb27SDimitry Andric 
353906c3fb27SDimitry Andric Instruction *InstCombinerImpl::visitUnreachableInst(UnreachableInst &I) {
354006c3fb27SDimitry Andric   removeInstructionsBeforeUnreachable(I);
3541e8d8bef9SDimitry Andric   return nullptr;
3542e8d8bef9SDimitry Andric }
3543e8d8bef9SDimitry Andric 
3544e8d8bef9SDimitry Andric Instruction *InstCombinerImpl::visitUnconditionalBranchInst(BranchInst &BI) {
35455ffd83dbSDimitry Andric   assert(BI.isUnconditional() && "Only for unconditional branches.");
35465ffd83dbSDimitry Andric 
35475ffd83dbSDimitry Andric   // If this store is the second-to-last instruction in the basic block
35485ffd83dbSDimitry Andric   // (excluding debug info and bitcasts of pointers) and if the block ends with
35495ffd83dbSDimitry Andric   // an unconditional branch, try to move the store to the successor block.
35505ffd83dbSDimitry Andric 
35515ffd83dbSDimitry Andric   auto GetLastSinkableStore = [](BasicBlock::iterator BBI) {
35525ffd83dbSDimitry Andric     auto IsNoopInstrForStoreMerging = [](BasicBlock::iterator BBI) {
3553349cc55cSDimitry Andric       return BBI->isDebugOrPseudoInst() ||
35545ffd83dbSDimitry Andric              (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy());
35555ffd83dbSDimitry Andric     };
35565ffd83dbSDimitry Andric 
35575ffd83dbSDimitry Andric     BasicBlock::iterator FirstInstr = BBI->getParent()->begin();
35585ffd83dbSDimitry Andric     do {
35595ffd83dbSDimitry Andric       if (BBI != FirstInstr)
35605ffd83dbSDimitry Andric         --BBI;
35615ffd83dbSDimitry Andric     } while (BBI != FirstInstr && IsNoopInstrForStoreMerging(BBI));
35625ffd83dbSDimitry Andric 
35635ffd83dbSDimitry Andric     return dyn_cast<StoreInst>(BBI);
35645ffd83dbSDimitry Andric   };
35655ffd83dbSDimitry Andric 
35665ffd83dbSDimitry Andric   if (StoreInst *SI = GetLastSinkableStore(BasicBlock::iterator(BI)))
35675ffd83dbSDimitry Andric     if (mergeStoreIntoSuccessor(*SI))
35685ffd83dbSDimitry Andric       return &BI;
35690b57cec5SDimitry Andric 
35700b57cec5SDimitry Andric   return nullptr;
35710b57cec5SDimitry Andric }
35720b57cec5SDimitry Andric 
35735f757f3fSDimitry Andric void InstCombinerImpl::addDeadEdge(BasicBlock *From, BasicBlock *To,
35745f757f3fSDimitry Andric                                    SmallVectorImpl<BasicBlock *> &Worklist) {
35755f757f3fSDimitry Andric   if (!DeadEdges.insert({From, To}).second)
35765f757f3fSDimitry Andric     return;
35775f757f3fSDimitry Andric 
35785f757f3fSDimitry Andric   // Replace phi node operands in successor with poison.
35795f757f3fSDimitry Andric   for (PHINode &PN : To->phis())
35805f757f3fSDimitry Andric     for (Use &U : PN.incoming_values())
35815f757f3fSDimitry Andric       if (PN.getIncomingBlock(U) == From && !isa<PoisonValue>(U)) {
35825f757f3fSDimitry Andric         replaceUse(U, PoisonValue::get(PN.getType()));
35835f757f3fSDimitry Andric         addToWorklist(&PN);
35845f757f3fSDimitry Andric         MadeIRChange = true;
35855f757f3fSDimitry Andric       }
35865f757f3fSDimitry Andric 
35875f757f3fSDimitry Andric   Worklist.push_back(To);
35885f757f3fSDimitry Andric }
35895f757f3fSDimitry Andric 
359006c3fb27SDimitry Andric // Under the assumption that I is unreachable, remove it and following
35915f757f3fSDimitry Andric // instructions. Changes are reported directly to MadeIRChange.
35925f757f3fSDimitry Andric void InstCombinerImpl::handleUnreachableFrom(
35935f757f3fSDimitry Andric     Instruction *I, SmallVectorImpl<BasicBlock *> &Worklist) {
359406c3fb27SDimitry Andric   BasicBlock *BB = I->getParent();
359506c3fb27SDimitry Andric   for (Instruction &Inst : make_early_inc_range(
359606c3fb27SDimitry Andric            make_range(std::next(BB->getTerminator()->getReverseIterator()),
359706c3fb27SDimitry Andric                       std::next(I->getReverseIterator())))) {
359806c3fb27SDimitry Andric     if (!Inst.use_empty() && !Inst.getType()->isTokenTy()) {
359906c3fb27SDimitry Andric       replaceInstUsesWith(Inst, PoisonValue::get(Inst.getType()));
36005f757f3fSDimitry Andric       MadeIRChange = true;
360106c3fb27SDimitry Andric     }
360206c3fb27SDimitry Andric     if (Inst.isEHPad() || Inst.getType()->isTokenTy())
360306c3fb27SDimitry Andric       continue;
36045f757f3fSDimitry Andric     // RemoveDIs: erase debug-info on this instruction manually.
3605*0fca6ea1SDimitry Andric     Inst.dropDbgRecords();
360606c3fb27SDimitry Andric     eraseInstFromFunction(Inst);
36075f757f3fSDimitry Andric     MadeIRChange = true;
360806c3fb27SDimitry Andric   }
360906c3fb27SDimitry Andric 
3610*0fca6ea1SDimitry Andric   SmallVector<Value *> Changed;
3611*0fca6ea1SDimitry Andric   if (handleUnreachableTerminator(BB->getTerminator(), Changed)) {
3612*0fca6ea1SDimitry Andric     MadeIRChange = true;
3613*0fca6ea1SDimitry Andric     for (Value *V : Changed)
3614*0fca6ea1SDimitry Andric       addToWorklist(cast<Instruction>(V));
3615*0fca6ea1SDimitry Andric   }
36165f757f3fSDimitry Andric 
36175f757f3fSDimitry Andric   // Handle potentially dead successors.
361806c3fb27SDimitry Andric   for (BasicBlock *Succ : successors(BB))
36195f757f3fSDimitry Andric     addDeadEdge(BB, Succ, Worklist);
362006c3fb27SDimitry Andric }
362106c3fb27SDimitry Andric 
36225f757f3fSDimitry Andric void InstCombinerImpl::handlePotentiallyDeadBlocks(
36235f757f3fSDimitry Andric     SmallVectorImpl<BasicBlock *> &Worklist) {
36245f757f3fSDimitry Andric   while (!Worklist.empty()) {
36255f757f3fSDimitry Andric     BasicBlock *BB = Worklist.pop_back_val();
36265f757f3fSDimitry Andric     if (!all_of(predecessors(BB), [&](BasicBlock *Pred) {
36275f757f3fSDimitry Andric           return DeadEdges.contains({Pred, BB}) || DT.dominates(BB, Pred);
36285f757f3fSDimitry Andric         }))
36295f757f3fSDimitry Andric       continue;
36305f757f3fSDimitry Andric 
36315f757f3fSDimitry Andric     handleUnreachableFrom(&BB->front(), Worklist);
36325f757f3fSDimitry Andric   }
363306c3fb27SDimitry Andric }
363406c3fb27SDimitry Andric 
36355f757f3fSDimitry Andric void InstCombinerImpl::handlePotentiallyDeadSuccessors(BasicBlock *BB,
363606c3fb27SDimitry Andric                                                        BasicBlock *LiveSucc) {
36375f757f3fSDimitry Andric   SmallVector<BasicBlock *> Worklist;
363806c3fb27SDimitry Andric   for (BasicBlock *Succ : successors(BB)) {
363906c3fb27SDimitry Andric     // The live successor isn't dead.
364006c3fb27SDimitry Andric     if (Succ == LiveSucc)
364106c3fb27SDimitry Andric       continue;
364206c3fb27SDimitry Andric 
36435f757f3fSDimitry Andric     addDeadEdge(BB, Succ, Worklist);
364406c3fb27SDimitry Andric   }
36455f757f3fSDimitry Andric 
36465f757f3fSDimitry Andric   handlePotentiallyDeadBlocks(Worklist);
364706c3fb27SDimitry Andric }
364806c3fb27SDimitry Andric 
3649e8d8bef9SDimitry Andric Instruction *InstCombinerImpl::visitBranchInst(BranchInst &BI) {
36505ffd83dbSDimitry Andric   if (BI.isUnconditional())
36515ffd83dbSDimitry Andric     return visitUnconditionalBranchInst(BI);
36525ffd83dbSDimitry Andric 
36530b57cec5SDimitry Andric   // Change br (not X), label True, label False to: br X, label False, True
3654bdd1243dSDimitry Andric   Value *Cond = BI.getCondition();
3655bdd1243dSDimitry Andric   Value *X;
3656bdd1243dSDimitry Andric   if (match(Cond, m_Not(m_Value(X))) && !isa<Constant>(X)) {
36570b57cec5SDimitry Andric     // Swap Destinations and condition...
36580b57cec5SDimitry Andric     BI.swapSuccessors();
3659*0fca6ea1SDimitry Andric     if (BPI)
3660*0fca6ea1SDimitry Andric       BPI->swapSuccEdgesProbabilities(BI.getParent());
36615ffd83dbSDimitry Andric     return replaceOperand(BI, 0, X);
36620b57cec5SDimitry Andric   }
36630b57cec5SDimitry Andric 
3664bdd1243dSDimitry Andric   // Canonicalize logical-and-with-invert as logical-or-with-invert.
3665bdd1243dSDimitry Andric   // This is done by inverting the condition and swapping successors:
3666bdd1243dSDimitry Andric   // br (X && !Y), T, F --> br !(X && !Y), F, T --> br (!X || Y), F, T
3667bdd1243dSDimitry Andric   Value *Y;
3668bdd1243dSDimitry Andric   if (isa<SelectInst>(Cond) &&
3669bdd1243dSDimitry Andric       match(Cond,
3670bdd1243dSDimitry Andric             m_OneUse(m_LogicalAnd(m_Value(X), m_OneUse(m_Not(m_Value(Y))))))) {
3671bdd1243dSDimitry Andric     Value *NotX = Builder.CreateNot(X, "not." + X->getName());
3672bdd1243dSDimitry Andric     Value *Or = Builder.CreateLogicalOr(NotX, Y);
3673bdd1243dSDimitry Andric     BI.swapSuccessors();
3674*0fca6ea1SDimitry Andric     if (BPI)
3675*0fca6ea1SDimitry Andric       BPI->swapSuccEdgesProbabilities(BI.getParent());
3676bdd1243dSDimitry Andric     return replaceOperand(BI, 0, Or);
3677bdd1243dSDimitry Andric   }
3678bdd1243dSDimitry Andric 
36790b57cec5SDimitry Andric   // If the condition is irrelevant, remove the use so that other
36800b57cec5SDimitry Andric   // transforms on the condition become more effective.
3681bdd1243dSDimitry Andric   if (!isa<ConstantInt>(Cond) && BI.getSuccessor(0) == BI.getSuccessor(1))
3682bdd1243dSDimitry Andric     return replaceOperand(BI, 0, ConstantInt::getFalse(Cond->getType()));
36830b57cec5SDimitry Andric 
36845ffd83dbSDimitry Andric   // Canonicalize, for example, fcmp_one -> fcmp_oeq.
36850b57cec5SDimitry Andric   CmpInst::Predicate Pred;
3686bdd1243dSDimitry Andric   if (match(Cond, m_OneUse(m_FCmp(Pred, m_Value(), m_Value()))) &&
36870b57cec5SDimitry Andric       !isCanonicalPredicate(Pred)) {
36880b57cec5SDimitry Andric     // Swap destinations and condition.
3689bdd1243dSDimitry Andric     auto *Cmp = cast<CmpInst>(Cond);
3690bdd1243dSDimitry Andric     Cmp->setPredicate(CmpInst::getInversePredicate(Pred));
36910b57cec5SDimitry Andric     BI.swapSuccessors();
3692*0fca6ea1SDimitry Andric     if (BPI)
3693*0fca6ea1SDimitry Andric       BPI->swapSuccEdgesProbabilities(BI.getParent());
3694bdd1243dSDimitry Andric     Worklist.push(Cmp);
36950b57cec5SDimitry Andric     return &BI;
36960b57cec5SDimitry Andric   }
36970b57cec5SDimitry Andric 
36985f757f3fSDimitry Andric   if (isa<UndefValue>(Cond)) {
36995f757f3fSDimitry Andric     handlePotentiallyDeadSuccessors(BI.getParent(), /*LiveSucc*/ nullptr);
37005f757f3fSDimitry Andric     return nullptr;
37015f757f3fSDimitry Andric   }
37025f757f3fSDimitry Andric   if (auto *CI = dyn_cast<ConstantInt>(Cond)) {
37035f757f3fSDimitry Andric     handlePotentiallyDeadSuccessors(BI.getParent(),
37045f757f3fSDimitry Andric                                     BI.getSuccessor(!CI->getZExtValue()));
37055f757f3fSDimitry Andric     return nullptr;
37065f757f3fSDimitry Andric   }
370706c3fb27SDimitry Andric 
37085f757f3fSDimitry Andric   DC.registerBranch(&BI);
37090b57cec5SDimitry Andric   return nullptr;
37100b57cec5SDimitry Andric }
37110b57cec5SDimitry Andric 
3712*0fca6ea1SDimitry Andric // Replaces (switch (select cond, X, C)/(select cond, C, X)) with (switch X) if
3713*0fca6ea1SDimitry Andric // we can prove that both (switch C) and (switch X) go to the default when cond
3714*0fca6ea1SDimitry Andric // is false/true.
3715*0fca6ea1SDimitry Andric static Value *simplifySwitchOnSelectUsingRanges(SwitchInst &SI,
3716*0fca6ea1SDimitry Andric                                                 SelectInst *Select,
3717*0fca6ea1SDimitry Andric                                                 bool IsTrueArm) {
3718*0fca6ea1SDimitry Andric   unsigned CstOpIdx = IsTrueArm ? 1 : 2;
3719*0fca6ea1SDimitry Andric   auto *C = dyn_cast<ConstantInt>(Select->getOperand(CstOpIdx));
3720*0fca6ea1SDimitry Andric   if (!C)
3721*0fca6ea1SDimitry Andric     return nullptr;
3722*0fca6ea1SDimitry Andric 
3723*0fca6ea1SDimitry Andric   BasicBlock *CstBB = SI.findCaseValue(C)->getCaseSuccessor();
3724*0fca6ea1SDimitry Andric   if (CstBB != SI.getDefaultDest())
3725*0fca6ea1SDimitry Andric     return nullptr;
3726*0fca6ea1SDimitry Andric   Value *X = Select->getOperand(3 - CstOpIdx);
3727*0fca6ea1SDimitry Andric   ICmpInst::Predicate Pred;
3728*0fca6ea1SDimitry Andric   const APInt *RHSC;
3729*0fca6ea1SDimitry Andric   if (!match(Select->getCondition(),
3730*0fca6ea1SDimitry Andric              m_ICmp(Pred, m_Specific(X), m_APInt(RHSC))))
3731*0fca6ea1SDimitry Andric     return nullptr;
3732*0fca6ea1SDimitry Andric   if (IsTrueArm)
3733*0fca6ea1SDimitry Andric     Pred = ICmpInst::getInversePredicate(Pred);
3734*0fca6ea1SDimitry Andric 
3735*0fca6ea1SDimitry Andric   // See whether we can replace the select with X
3736*0fca6ea1SDimitry Andric   ConstantRange CR = ConstantRange::makeExactICmpRegion(Pred, *RHSC);
3737*0fca6ea1SDimitry Andric   for (auto Case : SI.cases())
3738*0fca6ea1SDimitry Andric     if (!CR.contains(Case.getCaseValue()->getValue()))
3739*0fca6ea1SDimitry Andric       return nullptr;
3740*0fca6ea1SDimitry Andric 
3741*0fca6ea1SDimitry Andric   return X;
3742*0fca6ea1SDimitry Andric }
3743*0fca6ea1SDimitry Andric 
3744e8d8bef9SDimitry Andric Instruction *InstCombinerImpl::visitSwitchInst(SwitchInst &SI) {
37450b57cec5SDimitry Andric   Value *Cond = SI.getCondition();
37460b57cec5SDimitry Andric   Value *Op0;
37470b57cec5SDimitry Andric   ConstantInt *AddRHS;
37480b57cec5SDimitry Andric   if (match(Cond, m_Add(m_Value(Op0), m_ConstantInt(AddRHS)))) {
37490b57cec5SDimitry Andric     // Change 'switch (X+4) case 1:' into 'switch (X) case -3'.
37500b57cec5SDimitry Andric     for (auto Case : SI.cases()) {
37510b57cec5SDimitry Andric       Constant *NewCase = ConstantExpr::getSub(Case.getCaseValue(), AddRHS);
37520b57cec5SDimitry Andric       assert(isa<ConstantInt>(NewCase) &&
37530b57cec5SDimitry Andric              "Result of expression should be constant");
37540b57cec5SDimitry Andric       Case.setValue(cast<ConstantInt>(NewCase));
37550b57cec5SDimitry Andric     }
37565ffd83dbSDimitry Andric     return replaceOperand(SI, 0, Op0);
37570b57cec5SDimitry Andric   }
37580b57cec5SDimitry Andric 
37591db9f3b2SDimitry Andric   ConstantInt *SubLHS;
37601db9f3b2SDimitry Andric   if (match(Cond, m_Sub(m_ConstantInt(SubLHS), m_Value(Op0)))) {
37611db9f3b2SDimitry Andric     // Change 'switch (1-X) case 1:' into 'switch (X) case 0'.
37621db9f3b2SDimitry Andric     for (auto Case : SI.cases()) {
37631db9f3b2SDimitry Andric       Constant *NewCase = ConstantExpr::getSub(SubLHS, Case.getCaseValue());
37641db9f3b2SDimitry Andric       assert(isa<ConstantInt>(NewCase) &&
37651db9f3b2SDimitry Andric              "Result of expression should be constant");
37661db9f3b2SDimitry Andric       Case.setValue(cast<ConstantInt>(NewCase));
37671db9f3b2SDimitry Andric     }
37681db9f3b2SDimitry Andric     return replaceOperand(SI, 0, Op0);
37691db9f3b2SDimitry Andric   }
37701db9f3b2SDimitry Andric 
37711db9f3b2SDimitry Andric   uint64_t ShiftAmt;
37721db9f3b2SDimitry Andric   if (match(Cond, m_Shl(m_Value(Op0), m_ConstantInt(ShiftAmt))) &&
37731db9f3b2SDimitry Andric       ShiftAmt < Op0->getType()->getScalarSizeInBits() &&
37741db9f3b2SDimitry Andric       all_of(SI.cases(), [&](const auto &Case) {
37751db9f3b2SDimitry Andric         return Case.getCaseValue()->getValue().countr_zero() >= ShiftAmt;
37761db9f3b2SDimitry Andric       })) {
37771db9f3b2SDimitry Andric     // Change 'switch (X << 2) case 4:' into 'switch (X) case 1:'.
37781db9f3b2SDimitry Andric     OverflowingBinaryOperator *Shl = cast<OverflowingBinaryOperator>(Cond);
37791db9f3b2SDimitry Andric     if (Shl->hasNoUnsignedWrap() || Shl->hasNoSignedWrap() ||
37801db9f3b2SDimitry Andric         Shl->hasOneUse()) {
37811db9f3b2SDimitry Andric       Value *NewCond = Op0;
37821db9f3b2SDimitry Andric       if (!Shl->hasNoUnsignedWrap() && !Shl->hasNoSignedWrap()) {
37831db9f3b2SDimitry Andric         // If the shift may wrap, we need to mask off the shifted bits.
37841db9f3b2SDimitry Andric         unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
37851db9f3b2SDimitry Andric         NewCond = Builder.CreateAnd(
37861db9f3b2SDimitry Andric             Op0, APInt::getLowBitsSet(BitWidth, BitWidth - ShiftAmt));
37871db9f3b2SDimitry Andric       }
37881db9f3b2SDimitry Andric       for (auto Case : SI.cases()) {
37891db9f3b2SDimitry Andric         const APInt &CaseVal = Case.getCaseValue()->getValue();
37901db9f3b2SDimitry Andric         APInt ShiftedCase = Shl->hasNoSignedWrap() ? CaseVal.ashr(ShiftAmt)
37911db9f3b2SDimitry Andric                                                    : CaseVal.lshr(ShiftAmt);
37921db9f3b2SDimitry Andric         Case.setValue(ConstantInt::get(SI.getContext(), ShiftedCase));
37931db9f3b2SDimitry Andric       }
37941db9f3b2SDimitry Andric       return replaceOperand(SI, 0, NewCond);
37951db9f3b2SDimitry Andric     }
37961db9f3b2SDimitry Andric   }
37971db9f3b2SDimitry Andric 
37981db9f3b2SDimitry Andric   // Fold switch(zext/sext(X)) into switch(X) if possible.
37991db9f3b2SDimitry Andric   if (match(Cond, m_ZExtOrSExt(m_Value(Op0)))) {
38001db9f3b2SDimitry Andric     bool IsZExt = isa<ZExtInst>(Cond);
38011db9f3b2SDimitry Andric     Type *SrcTy = Op0->getType();
38021db9f3b2SDimitry Andric     unsigned NewWidth = SrcTy->getScalarSizeInBits();
38031db9f3b2SDimitry Andric 
38041db9f3b2SDimitry Andric     if (all_of(SI.cases(), [&](const auto &Case) {
38051db9f3b2SDimitry Andric           const APInt &CaseVal = Case.getCaseValue()->getValue();
38061db9f3b2SDimitry Andric           return IsZExt ? CaseVal.isIntN(NewWidth)
38071db9f3b2SDimitry Andric                         : CaseVal.isSignedIntN(NewWidth);
38081db9f3b2SDimitry Andric         })) {
38091db9f3b2SDimitry Andric       for (auto &Case : SI.cases()) {
38101db9f3b2SDimitry Andric         APInt TruncatedCase = Case.getCaseValue()->getValue().trunc(NewWidth);
38111db9f3b2SDimitry Andric         Case.setValue(ConstantInt::get(SI.getContext(), TruncatedCase));
38121db9f3b2SDimitry Andric       }
38131db9f3b2SDimitry Andric       return replaceOperand(SI, 0, Op0);
38141db9f3b2SDimitry Andric     }
38151db9f3b2SDimitry Andric   }
38161db9f3b2SDimitry Andric 
3817*0fca6ea1SDimitry Andric   // Fold switch(select cond, X, Y) into switch(X/Y) if possible
3818*0fca6ea1SDimitry Andric   if (auto *Select = dyn_cast<SelectInst>(Cond)) {
3819*0fca6ea1SDimitry Andric     if (Value *V =
3820*0fca6ea1SDimitry Andric             simplifySwitchOnSelectUsingRanges(SI, Select, /*IsTrueArm=*/true))
3821*0fca6ea1SDimitry Andric       return replaceOperand(SI, 0, V);
3822*0fca6ea1SDimitry Andric     if (Value *V =
3823*0fca6ea1SDimitry Andric             simplifySwitchOnSelectUsingRanges(SI, Select, /*IsTrueArm=*/false))
3824*0fca6ea1SDimitry Andric       return replaceOperand(SI, 0, V);
3825*0fca6ea1SDimitry Andric   }
3826*0fca6ea1SDimitry Andric 
38270b57cec5SDimitry Andric   KnownBits Known = computeKnownBits(Cond, 0, &SI);
38280b57cec5SDimitry Andric   unsigned LeadingKnownZeros = Known.countMinLeadingZeros();
38290b57cec5SDimitry Andric   unsigned LeadingKnownOnes = Known.countMinLeadingOnes();
38300b57cec5SDimitry Andric 
38310b57cec5SDimitry Andric   // Compute the number of leading bits we can ignore.
38320b57cec5SDimitry Andric   // TODO: A better way to determine this would use ComputeNumSignBits().
3833bdd1243dSDimitry Andric   for (const auto &C : SI.cases()) {
383406c3fb27SDimitry Andric     LeadingKnownZeros =
383506c3fb27SDimitry Andric         std::min(LeadingKnownZeros, C.getCaseValue()->getValue().countl_zero());
383606c3fb27SDimitry Andric     LeadingKnownOnes =
383706c3fb27SDimitry Andric         std::min(LeadingKnownOnes, C.getCaseValue()->getValue().countl_one());
38380b57cec5SDimitry Andric   }
38390b57cec5SDimitry Andric 
38400b57cec5SDimitry Andric   unsigned NewWidth = Known.getBitWidth() - std::max(LeadingKnownZeros, LeadingKnownOnes);
38410b57cec5SDimitry Andric 
38420b57cec5SDimitry Andric   // Shrink the condition operand if the new type is smaller than the old type.
38430b57cec5SDimitry Andric   // But do not shrink to a non-standard type, because backend can't generate
38440b57cec5SDimitry Andric   // good code for that yet.
38450b57cec5SDimitry Andric   // TODO: We can make it aggressive again after fixing PR39569.
38460b57cec5SDimitry Andric   if (NewWidth > 0 && NewWidth < Known.getBitWidth() &&
38470b57cec5SDimitry Andric       shouldChangeType(Known.getBitWidth(), NewWidth)) {
38480b57cec5SDimitry Andric     IntegerType *Ty = IntegerType::get(SI.getContext(), NewWidth);
38490b57cec5SDimitry Andric     Builder.SetInsertPoint(&SI);
38500b57cec5SDimitry Andric     Value *NewCond = Builder.CreateTrunc(Cond, Ty, "trunc");
38510b57cec5SDimitry Andric 
38520b57cec5SDimitry Andric     for (auto Case : SI.cases()) {
38530b57cec5SDimitry Andric       APInt TruncatedCase = Case.getCaseValue()->getValue().trunc(NewWidth);
38540b57cec5SDimitry Andric       Case.setValue(ConstantInt::get(SI.getContext(), TruncatedCase));
38550b57cec5SDimitry Andric     }
38565ffd83dbSDimitry Andric     return replaceOperand(SI, 0, NewCond);
38570b57cec5SDimitry Andric   }
38580b57cec5SDimitry Andric 
38595f757f3fSDimitry Andric   if (isa<UndefValue>(Cond)) {
38605f757f3fSDimitry Andric     handlePotentiallyDeadSuccessors(SI.getParent(), /*LiveSucc*/ nullptr);
38615f757f3fSDimitry Andric     return nullptr;
38625f757f3fSDimitry Andric   }
38635f757f3fSDimitry Andric   if (auto *CI = dyn_cast<ConstantInt>(Cond)) {
38645f757f3fSDimitry Andric     handlePotentiallyDeadSuccessors(SI.getParent(),
38655f757f3fSDimitry Andric                                     SI.findCaseValue(CI)->getCaseSuccessor());
38665f757f3fSDimitry Andric     return nullptr;
38675f757f3fSDimitry Andric   }
38685f757f3fSDimitry Andric 
38690b57cec5SDimitry Andric   return nullptr;
38700b57cec5SDimitry Andric }
38710b57cec5SDimitry Andric 
3872bdd1243dSDimitry Andric Instruction *
3873bdd1243dSDimitry Andric InstCombinerImpl::foldExtractOfOverflowIntrinsic(ExtractValueInst &EV) {
3874bdd1243dSDimitry Andric   auto *WO = dyn_cast<WithOverflowInst>(EV.getAggregateOperand());
3875bdd1243dSDimitry Andric   if (!WO)
3876bdd1243dSDimitry Andric     return nullptr;
3877bdd1243dSDimitry Andric 
3878bdd1243dSDimitry Andric   Intrinsic::ID OvID = WO->getIntrinsicID();
3879bdd1243dSDimitry Andric   const APInt *C = nullptr;
3880*0fca6ea1SDimitry Andric   if (match(WO->getRHS(), m_APIntAllowPoison(C))) {
3881bdd1243dSDimitry Andric     if (*EV.idx_begin() == 0 && (OvID == Intrinsic::smul_with_overflow ||
3882bdd1243dSDimitry Andric                                  OvID == Intrinsic::umul_with_overflow)) {
3883bdd1243dSDimitry Andric       // extractvalue (any_mul_with_overflow X, -1), 0 --> -X
3884bdd1243dSDimitry Andric       if (C->isAllOnes())
3885bdd1243dSDimitry Andric         return BinaryOperator::CreateNeg(WO->getLHS());
3886bdd1243dSDimitry Andric       // extractvalue (any_mul_with_overflow X, 2^n), 0 --> X << n
3887bdd1243dSDimitry Andric       if (C->isPowerOf2()) {
3888bdd1243dSDimitry Andric         return BinaryOperator::CreateShl(
3889bdd1243dSDimitry Andric             WO->getLHS(),
3890bdd1243dSDimitry Andric             ConstantInt::get(WO->getLHS()->getType(), C->logBase2()));
3891bdd1243dSDimitry Andric       }
3892bdd1243dSDimitry Andric     }
3893bdd1243dSDimitry Andric   }
3894bdd1243dSDimitry Andric 
3895bdd1243dSDimitry Andric   // We're extracting from an overflow intrinsic. See if we're the only user.
3896bdd1243dSDimitry Andric   // That allows us to simplify multiple result intrinsics to simpler things
3897bdd1243dSDimitry Andric   // that just get one value.
3898bdd1243dSDimitry Andric   if (!WO->hasOneUse())
3899bdd1243dSDimitry Andric     return nullptr;
3900bdd1243dSDimitry Andric 
3901bdd1243dSDimitry Andric   // Check if we're grabbing only the result of a 'with overflow' intrinsic
3902bdd1243dSDimitry Andric   // and replace it with a traditional binary instruction.
3903bdd1243dSDimitry Andric   if (*EV.idx_begin() == 0) {
3904bdd1243dSDimitry Andric     Instruction::BinaryOps BinOp = WO->getBinaryOp();
3905bdd1243dSDimitry Andric     Value *LHS = WO->getLHS(), *RHS = WO->getRHS();
3906bdd1243dSDimitry Andric     // Replace the old instruction's uses with poison.
3907bdd1243dSDimitry Andric     replaceInstUsesWith(*WO, PoisonValue::get(WO->getType()));
3908bdd1243dSDimitry Andric     eraseInstFromFunction(*WO);
3909bdd1243dSDimitry Andric     return BinaryOperator::Create(BinOp, LHS, RHS);
3910bdd1243dSDimitry Andric   }
3911bdd1243dSDimitry Andric 
3912bdd1243dSDimitry Andric   assert(*EV.idx_begin() == 1 && "Unexpected extract index for overflow inst");
3913bdd1243dSDimitry Andric 
3914bdd1243dSDimitry Andric   // (usub LHS, RHS) overflows when LHS is unsigned-less-than RHS.
3915bdd1243dSDimitry Andric   if (OvID == Intrinsic::usub_with_overflow)
3916bdd1243dSDimitry Andric     return new ICmpInst(ICmpInst::ICMP_ULT, WO->getLHS(), WO->getRHS());
3917bdd1243dSDimitry Andric 
3918bdd1243dSDimitry Andric   // smul with i1 types overflows when both sides are set: -1 * -1 == +1, but
3919bdd1243dSDimitry Andric   // +1 is not possible because we assume signed values.
3920bdd1243dSDimitry Andric   if (OvID == Intrinsic::smul_with_overflow &&
3921bdd1243dSDimitry Andric       WO->getLHS()->getType()->isIntOrIntVectorTy(1))
3922bdd1243dSDimitry Andric     return BinaryOperator::CreateAnd(WO->getLHS(), WO->getRHS());
3923bdd1243dSDimitry Andric 
3924*0fca6ea1SDimitry Andric   // extractvalue (umul_with_overflow X, X), 1 -> X u> 2^(N/2)-1
3925*0fca6ea1SDimitry Andric   if (OvID == Intrinsic::umul_with_overflow && WO->getLHS() == WO->getRHS()) {
3926*0fca6ea1SDimitry Andric     unsigned BitWidth = WO->getLHS()->getType()->getScalarSizeInBits();
3927*0fca6ea1SDimitry Andric     // Only handle even bitwidths for performance reasons.
3928*0fca6ea1SDimitry Andric     if (BitWidth % 2 == 0)
3929*0fca6ea1SDimitry Andric       return new ICmpInst(
3930*0fca6ea1SDimitry Andric           ICmpInst::ICMP_UGT, WO->getLHS(),
3931*0fca6ea1SDimitry Andric           ConstantInt::get(WO->getLHS()->getType(),
3932*0fca6ea1SDimitry Andric                            APInt::getLowBitsSet(BitWidth, BitWidth / 2)));
3933*0fca6ea1SDimitry Andric   }
3934*0fca6ea1SDimitry Andric 
3935bdd1243dSDimitry Andric   // If only the overflow result is used, and the right hand side is a
3936bdd1243dSDimitry Andric   // constant (or constant splat), we can remove the intrinsic by directly
3937bdd1243dSDimitry Andric   // checking for overflow.
3938bdd1243dSDimitry Andric   if (C) {
3939bdd1243dSDimitry Andric     // Compute the no-wrap range for LHS given RHS=C, then construct an
3940bdd1243dSDimitry Andric     // equivalent icmp, potentially using an offset.
3941bdd1243dSDimitry Andric     ConstantRange NWR = ConstantRange::makeExactNoWrapRegion(
3942bdd1243dSDimitry Andric         WO->getBinaryOp(), *C, WO->getNoWrapKind());
3943bdd1243dSDimitry Andric 
3944bdd1243dSDimitry Andric     CmpInst::Predicate Pred;
3945bdd1243dSDimitry Andric     APInt NewRHSC, Offset;
3946bdd1243dSDimitry Andric     NWR.getEquivalentICmp(Pred, NewRHSC, Offset);
3947bdd1243dSDimitry Andric     auto *OpTy = WO->getRHS()->getType();
3948bdd1243dSDimitry Andric     auto *NewLHS = WO->getLHS();
3949bdd1243dSDimitry Andric     if (Offset != 0)
3950bdd1243dSDimitry Andric       NewLHS = Builder.CreateAdd(NewLHS, ConstantInt::get(OpTy, Offset));
3951bdd1243dSDimitry Andric     return new ICmpInst(ICmpInst::getInversePredicate(Pred), NewLHS,
3952bdd1243dSDimitry Andric                         ConstantInt::get(OpTy, NewRHSC));
3953bdd1243dSDimitry Andric   }
3954bdd1243dSDimitry Andric 
3955bdd1243dSDimitry Andric   return nullptr;
3956bdd1243dSDimitry Andric }
3957bdd1243dSDimitry Andric 
3958e8d8bef9SDimitry Andric Instruction *InstCombinerImpl::visitExtractValueInst(ExtractValueInst &EV) {
39590b57cec5SDimitry Andric   Value *Agg = EV.getAggregateOperand();
39600b57cec5SDimitry Andric 
39610b57cec5SDimitry Andric   if (!EV.hasIndices())
39620b57cec5SDimitry Andric     return replaceInstUsesWith(EV, Agg);
39630b57cec5SDimitry Andric 
396481ad6265SDimitry Andric   if (Value *V = simplifyExtractValueInst(Agg, EV.getIndices(),
39650b57cec5SDimitry Andric                                           SQ.getWithInstruction(&EV)))
39660b57cec5SDimitry Andric     return replaceInstUsesWith(EV, V);
39670b57cec5SDimitry Andric 
39680b57cec5SDimitry Andric   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
39690b57cec5SDimitry Andric     // We're extracting from an insertvalue instruction, compare the indices
39700b57cec5SDimitry Andric     const unsigned *exti, *exte, *insi, *inse;
39710b57cec5SDimitry Andric     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
39720b57cec5SDimitry Andric          exte = EV.idx_end(), inse = IV->idx_end();
39730b57cec5SDimitry Andric          exti != exte && insi != inse;
39740b57cec5SDimitry Andric          ++exti, ++insi) {
39750b57cec5SDimitry Andric       if (*insi != *exti)
39760b57cec5SDimitry Andric         // The insert and extract both reference distinctly different elements.
39770b57cec5SDimitry Andric         // This means the extract is not influenced by the insert, and we can
39780b57cec5SDimitry Andric         // replace the aggregate operand of the extract with the aggregate
39790b57cec5SDimitry Andric         // operand of the insert. i.e., replace
39800b57cec5SDimitry Andric         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
39810b57cec5SDimitry Andric         // %E = extractvalue { i32, { i32 } } %I, 0
39820b57cec5SDimitry Andric         // with
39830b57cec5SDimitry Andric         // %E = extractvalue { i32, { i32 } } %A, 0
39840b57cec5SDimitry Andric         return ExtractValueInst::Create(IV->getAggregateOperand(),
39850b57cec5SDimitry Andric                                         EV.getIndices());
39860b57cec5SDimitry Andric     }
39870b57cec5SDimitry Andric     if (exti == exte && insi == inse)
39880b57cec5SDimitry Andric       // Both iterators are at the end: Index lists are identical. Replace
39890b57cec5SDimitry Andric       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
39900b57cec5SDimitry Andric       // %C = extractvalue { i32, { i32 } } %B, 1, 0
39910b57cec5SDimitry Andric       // with "i32 42"
39920b57cec5SDimitry Andric       return replaceInstUsesWith(EV, IV->getInsertedValueOperand());
39930b57cec5SDimitry Andric     if (exti == exte) {
39940b57cec5SDimitry Andric       // The extract list is a prefix of the insert list. i.e. replace
39950b57cec5SDimitry Andric       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
39960b57cec5SDimitry Andric       // %E = extractvalue { i32, { i32 } } %I, 1
39970b57cec5SDimitry Andric       // with
39980b57cec5SDimitry Andric       // %X = extractvalue { i32, { i32 } } %A, 1
39990b57cec5SDimitry Andric       // %E = insertvalue { i32 } %X, i32 42, 0
40000b57cec5SDimitry Andric       // by switching the order of the insert and extract (though the
40010b57cec5SDimitry Andric       // insertvalue should be left in, since it may have other uses).
40020b57cec5SDimitry Andric       Value *NewEV = Builder.CreateExtractValue(IV->getAggregateOperand(),
40030b57cec5SDimitry Andric                                                 EV.getIndices());
40040b57cec5SDimitry Andric       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
4005bdd1243dSDimitry Andric                                      ArrayRef(insi, inse));
40060b57cec5SDimitry Andric     }
40070b57cec5SDimitry Andric     if (insi == inse)
40080b57cec5SDimitry Andric       // The insert list is a prefix of the extract list
40090b57cec5SDimitry Andric       // We can simply remove the common indices from the extract and make it
40100b57cec5SDimitry Andric       // operate on the inserted value instead of the insertvalue result.
40110b57cec5SDimitry Andric       // i.e., replace
40120b57cec5SDimitry Andric       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
40130b57cec5SDimitry Andric       // %E = extractvalue { i32, { i32 } } %I, 1, 0
40140b57cec5SDimitry Andric       // with
40150b57cec5SDimitry Andric       // %E extractvalue { i32 } { i32 42 }, 0
40160b57cec5SDimitry Andric       return ExtractValueInst::Create(IV->getInsertedValueOperand(),
4017bdd1243dSDimitry Andric                                       ArrayRef(exti, exte));
401881ad6265SDimitry Andric   }
401981ad6265SDimitry Andric 
4020bdd1243dSDimitry Andric   if (Instruction *R = foldExtractOfOverflowIntrinsic(EV))
4021bdd1243dSDimitry Andric     return R;
40220b57cec5SDimitry Andric 
4023bdd1243dSDimitry Andric   if (LoadInst *L = dyn_cast<LoadInst>(Agg)) {
402406c3fb27SDimitry Andric     // Bail out if the aggregate contains scalable vector type
402506c3fb27SDimitry Andric     if (auto *STy = dyn_cast<StructType>(Agg->getType());
402606c3fb27SDimitry Andric         STy && STy->containsScalableVectorType())
402706c3fb27SDimitry Andric       return nullptr;
402806c3fb27SDimitry Andric 
40290b57cec5SDimitry Andric     // If the (non-volatile) load only has one use, we can rewrite this to a
40300b57cec5SDimitry Andric     // load from a GEP. This reduces the size of the load. If a load is used
40310b57cec5SDimitry Andric     // only by extractvalue instructions then this either must have been
40320b57cec5SDimitry Andric     // optimized before, or it is a struct with padding, in which case we
40330b57cec5SDimitry Andric     // don't want to do the transformation as it loses padding knowledge.
40340b57cec5SDimitry Andric     if (L->isSimple() && L->hasOneUse()) {
40350b57cec5SDimitry Andric       // extractvalue has integer indices, getelementptr has Value*s. Convert.
40360b57cec5SDimitry Andric       SmallVector<Value*, 4> Indices;
40370b57cec5SDimitry Andric       // Prefix an i32 0 since we need the first element.
40380b57cec5SDimitry Andric       Indices.push_back(Builder.getInt32(0));
4039fe6060f1SDimitry Andric       for (unsigned Idx : EV.indices())
4040fe6060f1SDimitry Andric         Indices.push_back(Builder.getInt32(Idx));
40410b57cec5SDimitry Andric 
40420b57cec5SDimitry Andric       // We need to insert these at the location of the old load, not at that of
40430b57cec5SDimitry Andric       // the extractvalue.
40440b57cec5SDimitry Andric       Builder.SetInsertPoint(L);
40450b57cec5SDimitry Andric       Value *GEP = Builder.CreateInBoundsGEP(L->getType(),
40460b57cec5SDimitry Andric                                              L->getPointerOperand(), Indices);
40470b57cec5SDimitry Andric       Instruction *NL = Builder.CreateLoad(EV.getType(), GEP);
40480b57cec5SDimitry Andric       // Whatever aliasing information we had for the orignal load must also
40490b57cec5SDimitry Andric       // hold for the smaller load, so propagate the annotations.
4050349cc55cSDimitry Andric       NL->setAAMetadata(L->getAAMetadata());
40510b57cec5SDimitry Andric       // Returning the load directly will cause the main loop to insert it in
40520b57cec5SDimitry Andric       // the wrong spot, so use replaceInstUsesWith().
40530b57cec5SDimitry Andric       return replaceInstUsesWith(EV, NL);
40540b57cec5SDimitry Andric     }
4055bdd1243dSDimitry Andric   }
4056bdd1243dSDimitry Andric 
4057bdd1243dSDimitry Andric   if (auto *PN = dyn_cast<PHINode>(Agg))
4058bdd1243dSDimitry Andric     if (Instruction *Res = foldOpIntoPhi(EV, PN))
4059bdd1243dSDimitry Andric       return Res;
4060bdd1243dSDimitry Andric 
4061*0fca6ea1SDimitry Andric   // Canonicalize extract (select Cond, TV, FV)
4062*0fca6ea1SDimitry Andric   // -> select cond, (extract TV), (extract FV)
4063*0fca6ea1SDimitry Andric   if (auto *SI = dyn_cast<SelectInst>(Agg))
4064*0fca6ea1SDimitry Andric     if (Instruction *R = FoldOpIntoSelect(EV, SI, /*FoldWithMultiUse=*/true))
4065*0fca6ea1SDimitry Andric       return R;
4066*0fca6ea1SDimitry Andric 
40670b57cec5SDimitry Andric   // We could simplify extracts from other values. Note that nested extracts may
40680b57cec5SDimitry Andric   // already be simplified implicitly by the above: extract (extract (insert) )
40690b57cec5SDimitry Andric   // will be translated into extract ( insert ( extract ) ) first and then just
40700b57cec5SDimitry Andric   // the value inserted, if appropriate. Similarly for extracts from single-use
40710b57cec5SDimitry Andric   // loads: extract (extract (load)) will be translated to extract (load (gep))
40720b57cec5SDimitry Andric   // and if again single-use then via load (gep (gep)) to load (gep).
40730b57cec5SDimitry Andric   // However, double extracts from e.g. function arguments or return values
40740b57cec5SDimitry Andric   // aren't handled yet.
40750b57cec5SDimitry Andric   return nullptr;
40760b57cec5SDimitry Andric }
40770b57cec5SDimitry Andric 
40780b57cec5SDimitry Andric /// Return 'true' if the given typeinfo will match anything.
40790b57cec5SDimitry Andric static bool isCatchAll(EHPersonality Personality, Constant *TypeInfo) {
40800b57cec5SDimitry Andric   switch (Personality) {
40810b57cec5SDimitry Andric   case EHPersonality::GNU_C:
40820b57cec5SDimitry Andric   case EHPersonality::GNU_C_SjLj:
40830b57cec5SDimitry Andric   case EHPersonality::Rust:
40840b57cec5SDimitry Andric     // The GCC C EH and Rust personality only exists to support cleanups, so
40850b57cec5SDimitry Andric     // it's not clear what the semantics of catch clauses are.
40860b57cec5SDimitry Andric     return false;
40870b57cec5SDimitry Andric   case EHPersonality::Unknown:
40880b57cec5SDimitry Andric     return false;
40890b57cec5SDimitry Andric   case EHPersonality::GNU_Ada:
40900b57cec5SDimitry Andric     // While __gnat_all_others_value will match any Ada exception, it doesn't
40910b57cec5SDimitry Andric     // match foreign exceptions (or didn't, before gcc-4.7).
40920b57cec5SDimitry Andric     return false;
40930b57cec5SDimitry Andric   case EHPersonality::GNU_CXX:
40940b57cec5SDimitry Andric   case EHPersonality::GNU_CXX_SjLj:
40950b57cec5SDimitry Andric   case EHPersonality::GNU_ObjC:
40960b57cec5SDimitry Andric   case EHPersonality::MSVC_X86SEH:
4097e8d8bef9SDimitry Andric   case EHPersonality::MSVC_TableSEH:
40980b57cec5SDimitry Andric   case EHPersonality::MSVC_CXX:
40990b57cec5SDimitry Andric   case EHPersonality::CoreCLR:
41000b57cec5SDimitry Andric   case EHPersonality::Wasm_CXX:
4101e8d8bef9SDimitry Andric   case EHPersonality::XL_CXX:
4102*0fca6ea1SDimitry Andric   case EHPersonality::ZOS_CXX:
41030b57cec5SDimitry Andric     return TypeInfo->isNullValue();
41040b57cec5SDimitry Andric   }
41050b57cec5SDimitry Andric   llvm_unreachable("invalid enum");
41060b57cec5SDimitry Andric }
41070b57cec5SDimitry Andric 
41080b57cec5SDimitry Andric static bool shorter_filter(const Value *LHS, const Value *RHS) {
41090b57cec5SDimitry Andric   return
41100b57cec5SDimitry Andric     cast<ArrayType>(LHS->getType())->getNumElements()
41110b57cec5SDimitry Andric   <
41120b57cec5SDimitry Andric     cast<ArrayType>(RHS->getType())->getNumElements();
41130b57cec5SDimitry Andric }
41140b57cec5SDimitry Andric 
4115e8d8bef9SDimitry Andric Instruction *InstCombinerImpl::visitLandingPadInst(LandingPadInst &LI) {
41160b57cec5SDimitry Andric   // The logic here should be correct for any real-world personality function.
41170b57cec5SDimitry Andric   // However if that turns out not to be true, the offending logic can always
41180b57cec5SDimitry Andric   // be conditioned on the personality function, like the catch-all logic is.
41190b57cec5SDimitry Andric   EHPersonality Personality =
41200b57cec5SDimitry Andric       classifyEHPersonality(LI.getParent()->getParent()->getPersonalityFn());
41210b57cec5SDimitry Andric 
41220b57cec5SDimitry Andric   // Simplify the list of clauses, eg by removing repeated catch clauses
41230b57cec5SDimitry Andric   // (these are often created by inlining).
41240b57cec5SDimitry Andric   bool MakeNewInstruction = false; // If true, recreate using the following:
41250b57cec5SDimitry Andric   SmallVector<Constant *, 16> NewClauses; // - Clauses for the new instruction;
41260b57cec5SDimitry Andric   bool CleanupFlag = LI.isCleanup();   // - The new instruction is a cleanup.
41270b57cec5SDimitry Andric 
41280b57cec5SDimitry Andric   SmallPtrSet<Value *, 16> AlreadyCaught; // Typeinfos known caught already.
41290b57cec5SDimitry Andric   for (unsigned i = 0, e = LI.getNumClauses(); i != e; ++i) {
41300b57cec5SDimitry Andric     bool isLastClause = i + 1 == e;
41310b57cec5SDimitry Andric     if (LI.isCatch(i)) {
41320b57cec5SDimitry Andric       // A catch clause.
41330b57cec5SDimitry Andric       Constant *CatchClause = LI.getClause(i);
41340b57cec5SDimitry Andric       Constant *TypeInfo = CatchClause->stripPointerCasts();
41350b57cec5SDimitry Andric 
41360b57cec5SDimitry Andric       // If we already saw this clause, there is no point in having a second
41370b57cec5SDimitry Andric       // copy of it.
41380b57cec5SDimitry Andric       if (AlreadyCaught.insert(TypeInfo).second) {
41390b57cec5SDimitry Andric         // This catch clause was not already seen.
41400b57cec5SDimitry Andric         NewClauses.push_back(CatchClause);
41410b57cec5SDimitry Andric       } else {
41420b57cec5SDimitry Andric         // Repeated catch clause - drop the redundant copy.
41430b57cec5SDimitry Andric         MakeNewInstruction = true;
41440b57cec5SDimitry Andric       }
41450b57cec5SDimitry Andric 
41460b57cec5SDimitry Andric       // If this is a catch-all then there is no point in keeping any following
41470b57cec5SDimitry Andric       // clauses or marking the landingpad as having a cleanup.
41480b57cec5SDimitry Andric       if (isCatchAll(Personality, TypeInfo)) {
41490b57cec5SDimitry Andric         if (!isLastClause)
41500b57cec5SDimitry Andric           MakeNewInstruction = true;
41510b57cec5SDimitry Andric         CleanupFlag = false;
41520b57cec5SDimitry Andric         break;
41530b57cec5SDimitry Andric       }
41540b57cec5SDimitry Andric     } else {
41550b57cec5SDimitry Andric       // A filter clause.  If any of the filter elements were already caught
41560b57cec5SDimitry Andric       // then they can be dropped from the filter.  It is tempting to try to
41570b57cec5SDimitry Andric       // exploit the filter further by saying that any typeinfo that does not
41580b57cec5SDimitry Andric       // occur in the filter can't be caught later (and thus can be dropped).
41590b57cec5SDimitry Andric       // However this would be wrong, since typeinfos can match without being
41600b57cec5SDimitry Andric       // equal (for example if one represents a C++ class, and the other some
41610b57cec5SDimitry Andric       // class derived from it).
41620b57cec5SDimitry Andric       assert(LI.isFilter(i) && "Unsupported landingpad clause!");
41630b57cec5SDimitry Andric       Constant *FilterClause = LI.getClause(i);
41640b57cec5SDimitry Andric       ArrayType *FilterType = cast<ArrayType>(FilterClause->getType());
41650b57cec5SDimitry Andric       unsigned NumTypeInfos = FilterType->getNumElements();
41660b57cec5SDimitry Andric 
41670b57cec5SDimitry Andric       // An empty filter catches everything, so there is no point in keeping any
41680b57cec5SDimitry Andric       // following clauses or marking the landingpad as having a cleanup.  By
41690b57cec5SDimitry Andric       // dealing with this case here the following code is made a bit simpler.
41700b57cec5SDimitry Andric       if (!NumTypeInfos) {
41710b57cec5SDimitry Andric         NewClauses.push_back(FilterClause);
41720b57cec5SDimitry Andric         if (!isLastClause)
41730b57cec5SDimitry Andric           MakeNewInstruction = true;
41740b57cec5SDimitry Andric         CleanupFlag = false;
41750b57cec5SDimitry Andric         break;
41760b57cec5SDimitry Andric       }
41770b57cec5SDimitry Andric 
41780b57cec5SDimitry Andric       bool MakeNewFilter = false; // If true, make a new filter.
41790b57cec5SDimitry Andric       SmallVector<Constant *, 16> NewFilterElts; // New elements.
41800b57cec5SDimitry Andric       if (isa<ConstantAggregateZero>(FilterClause)) {
41810b57cec5SDimitry Andric         // Not an empty filter - it contains at least one null typeinfo.
41820b57cec5SDimitry Andric         assert(NumTypeInfos > 0 && "Should have handled empty filter already!");
41830b57cec5SDimitry Andric         Constant *TypeInfo =
41840b57cec5SDimitry Andric           Constant::getNullValue(FilterType->getElementType());
41850b57cec5SDimitry Andric         // If this typeinfo is a catch-all then the filter can never match.
41860b57cec5SDimitry Andric         if (isCatchAll(Personality, TypeInfo)) {
41870b57cec5SDimitry Andric           // Throw the filter away.
41880b57cec5SDimitry Andric           MakeNewInstruction = true;
41890b57cec5SDimitry Andric           continue;
41900b57cec5SDimitry Andric         }
41910b57cec5SDimitry Andric 
41920b57cec5SDimitry Andric         // There is no point in having multiple copies of this typeinfo, so
41930b57cec5SDimitry Andric         // discard all but the first copy if there is more than one.
41940b57cec5SDimitry Andric         NewFilterElts.push_back(TypeInfo);
41950b57cec5SDimitry Andric         if (NumTypeInfos > 1)
41960b57cec5SDimitry Andric           MakeNewFilter = true;
41970b57cec5SDimitry Andric       } else {
41980b57cec5SDimitry Andric         ConstantArray *Filter = cast<ConstantArray>(FilterClause);
41990b57cec5SDimitry Andric         SmallPtrSet<Value *, 16> SeenInFilter; // For uniquing the elements.
42000b57cec5SDimitry Andric         NewFilterElts.reserve(NumTypeInfos);
42010b57cec5SDimitry Andric 
42020b57cec5SDimitry Andric         // Remove any filter elements that were already caught or that already
42030b57cec5SDimitry Andric         // occurred in the filter.  While there, see if any of the elements are
42040b57cec5SDimitry Andric         // catch-alls.  If so, the filter can be discarded.
42050b57cec5SDimitry Andric         bool SawCatchAll = false;
42060b57cec5SDimitry Andric         for (unsigned j = 0; j != NumTypeInfos; ++j) {
42070b57cec5SDimitry Andric           Constant *Elt = Filter->getOperand(j);
42080b57cec5SDimitry Andric           Constant *TypeInfo = Elt->stripPointerCasts();
42090b57cec5SDimitry Andric           if (isCatchAll(Personality, TypeInfo)) {
42100b57cec5SDimitry Andric             // This element is a catch-all.  Bail out, noting this fact.
42110b57cec5SDimitry Andric             SawCatchAll = true;
42120b57cec5SDimitry Andric             break;
42130b57cec5SDimitry Andric           }
42140b57cec5SDimitry Andric 
42150b57cec5SDimitry Andric           // Even if we've seen a type in a catch clause, we don't want to
42160b57cec5SDimitry Andric           // remove it from the filter.  An unexpected type handler may be
42170b57cec5SDimitry Andric           // set up for a call site which throws an exception of the same
42180b57cec5SDimitry Andric           // type caught.  In order for the exception thrown by the unexpected
42190b57cec5SDimitry Andric           // handler to propagate correctly, the filter must be correctly
42200b57cec5SDimitry Andric           // described for the call site.
42210b57cec5SDimitry Andric           //
42220b57cec5SDimitry Andric           // Example:
42230b57cec5SDimitry Andric           //
42240b57cec5SDimitry Andric           // void unexpected() { throw 1;}
42250b57cec5SDimitry Andric           // void foo() throw (int) {
42260b57cec5SDimitry Andric           //   std::set_unexpected(unexpected);
42270b57cec5SDimitry Andric           //   try {
42280b57cec5SDimitry Andric           //     throw 2.0;
42290b57cec5SDimitry Andric           //   } catch (int i) {}
42300b57cec5SDimitry Andric           // }
42310b57cec5SDimitry Andric 
42320b57cec5SDimitry Andric           // There is no point in having multiple copies of the same typeinfo in
42330b57cec5SDimitry Andric           // a filter, so only add it if we didn't already.
42340b57cec5SDimitry Andric           if (SeenInFilter.insert(TypeInfo).second)
42350b57cec5SDimitry Andric             NewFilterElts.push_back(cast<Constant>(Elt));
42360b57cec5SDimitry Andric         }
42370b57cec5SDimitry Andric         // A filter containing a catch-all cannot match anything by definition.
42380b57cec5SDimitry Andric         if (SawCatchAll) {
42390b57cec5SDimitry Andric           // Throw the filter away.
42400b57cec5SDimitry Andric           MakeNewInstruction = true;
42410b57cec5SDimitry Andric           continue;
42420b57cec5SDimitry Andric         }
42430b57cec5SDimitry Andric 
42440b57cec5SDimitry Andric         // If we dropped something from the filter, make a new one.
42450b57cec5SDimitry Andric         if (NewFilterElts.size() < NumTypeInfos)
42460b57cec5SDimitry Andric           MakeNewFilter = true;
42470b57cec5SDimitry Andric       }
42480b57cec5SDimitry Andric       if (MakeNewFilter) {
42490b57cec5SDimitry Andric         FilterType = ArrayType::get(FilterType->getElementType(),
42500b57cec5SDimitry Andric                                     NewFilterElts.size());
42510b57cec5SDimitry Andric         FilterClause = ConstantArray::get(FilterType, NewFilterElts);
42520b57cec5SDimitry Andric         MakeNewInstruction = true;
42530b57cec5SDimitry Andric       }
42540b57cec5SDimitry Andric 
42550b57cec5SDimitry Andric       NewClauses.push_back(FilterClause);
42560b57cec5SDimitry Andric 
42570b57cec5SDimitry Andric       // If the new filter is empty then it will catch everything so there is
42580b57cec5SDimitry Andric       // no point in keeping any following clauses or marking the landingpad
42590b57cec5SDimitry Andric       // as having a cleanup.  The case of the original filter being empty was
42600b57cec5SDimitry Andric       // already handled above.
42610b57cec5SDimitry Andric       if (MakeNewFilter && !NewFilterElts.size()) {
42620b57cec5SDimitry Andric         assert(MakeNewInstruction && "New filter but not a new instruction!");
42630b57cec5SDimitry Andric         CleanupFlag = false;
42640b57cec5SDimitry Andric         break;
42650b57cec5SDimitry Andric       }
42660b57cec5SDimitry Andric     }
42670b57cec5SDimitry Andric   }
42680b57cec5SDimitry Andric 
42690b57cec5SDimitry Andric   // If several filters occur in a row then reorder them so that the shortest
42700b57cec5SDimitry Andric   // filters come first (those with the smallest number of elements).  This is
42710b57cec5SDimitry Andric   // advantageous because shorter filters are more likely to match, speeding up
42720b57cec5SDimitry Andric   // unwinding, but mostly because it increases the effectiveness of the other
42730b57cec5SDimitry Andric   // filter optimizations below.
42740b57cec5SDimitry Andric   for (unsigned i = 0, e = NewClauses.size(); i + 1 < e; ) {
42750b57cec5SDimitry Andric     unsigned j;
42760b57cec5SDimitry Andric     // Find the maximal 'j' s.t. the range [i, j) consists entirely of filters.
42770b57cec5SDimitry Andric     for (j = i; j != e; ++j)
42780b57cec5SDimitry Andric       if (!isa<ArrayType>(NewClauses[j]->getType()))
42790b57cec5SDimitry Andric         break;
42800b57cec5SDimitry Andric 
42810b57cec5SDimitry Andric     // Check whether the filters are already sorted by length.  We need to know
42820b57cec5SDimitry Andric     // if sorting them is actually going to do anything so that we only make a
42830b57cec5SDimitry Andric     // new landingpad instruction if it does.
42840b57cec5SDimitry Andric     for (unsigned k = i; k + 1 < j; ++k)
42850b57cec5SDimitry Andric       if (shorter_filter(NewClauses[k+1], NewClauses[k])) {
42860b57cec5SDimitry Andric         // Not sorted, so sort the filters now.  Doing an unstable sort would be
42870b57cec5SDimitry Andric         // correct too but reordering filters pointlessly might confuse users.
42880b57cec5SDimitry Andric         std::stable_sort(NewClauses.begin() + i, NewClauses.begin() + j,
42890b57cec5SDimitry Andric                          shorter_filter);
42900b57cec5SDimitry Andric         MakeNewInstruction = true;
42910b57cec5SDimitry Andric         break;
42920b57cec5SDimitry Andric       }
42930b57cec5SDimitry Andric 
42940b57cec5SDimitry Andric     // Look for the next batch of filters.
42950b57cec5SDimitry Andric     i = j + 1;
42960b57cec5SDimitry Andric   }
42970b57cec5SDimitry Andric 
42980b57cec5SDimitry Andric   // If typeinfos matched if and only if equal, then the elements of a filter L
42990b57cec5SDimitry Andric   // that occurs later than a filter F could be replaced by the intersection of
43000b57cec5SDimitry Andric   // the elements of F and L.  In reality two typeinfos can match without being
43010b57cec5SDimitry Andric   // equal (for example if one represents a C++ class, and the other some class
43020b57cec5SDimitry Andric   // derived from it) so it would be wrong to perform this transform in general.
43030b57cec5SDimitry Andric   // However the transform is correct and useful if F is a subset of L.  In that
43040b57cec5SDimitry Andric   // case L can be replaced by F, and thus removed altogether since repeating a
43050b57cec5SDimitry Andric   // filter is pointless.  So here we look at all pairs of filters F and L where
43060b57cec5SDimitry Andric   // L follows F in the list of clauses, and remove L if every element of F is
43070b57cec5SDimitry Andric   // an element of L.  This can occur when inlining C++ functions with exception
43080b57cec5SDimitry Andric   // specifications.
43090b57cec5SDimitry Andric   for (unsigned i = 0; i + 1 < NewClauses.size(); ++i) {
43100b57cec5SDimitry Andric     // Examine each filter in turn.
43110b57cec5SDimitry Andric     Value *Filter = NewClauses[i];
43120b57cec5SDimitry Andric     ArrayType *FTy = dyn_cast<ArrayType>(Filter->getType());
43130b57cec5SDimitry Andric     if (!FTy)
43140b57cec5SDimitry Andric       // Not a filter - skip it.
43150b57cec5SDimitry Andric       continue;
43160b57cec5SDimitry Andric     unsigned FElts = FTy->getNumElements();
43170b57cec5SDimitry Andric     // Examine each filter following this one.  Doing this backwards means that
43180b57cec5SDimitry Andric     // we don't have to worry about filters disappearing under us when removed.
43190b57cec5SDimitry Andric     for (unsigned j = NewClauses.size() - 1; j != i; --j) {
43200b57cec5SDimitry Andric       Value *LFilter = NewClauses[j];
43210b57cec5SDimitry Andric       ArrayType *LTy = dyn_cast<ArrayType>(LFilter->getType());
43220b57cec5SDimitry Andric       if (!LTy)
43230b57cec5SDimitry Andric         // Not a filter - skip it.
43240b57cec5SDimitry Andric         continue;
43250b57cec5SDimitry Andric       // If Filter is a subset of LFilter, i.e. every element of Filter is also
43260b57cec5SDimitry Andric       // an element of LFilter, then discard LFilter.
43270b57cec5SDimitry Andric       SmallVectorImpl<Constant *>::iterator J = NewClauses.begin() + j;
43280b57cec5SDimitry Andric       // If Filter is empty then it is a subset of LFilter.
43290b57cec5SDimitry Andric       if (!FElts) {
43300b57cec5SDimitry Andric         // Discard LFilter.
43310b57cec5SDimitry Andric         NewClauses.erase(J);
43320b57cec5SDimitry Andric         MakeNewInstruction = true;
43330b57cec5SDimitry Andric         // Move on to the next filter.
43340b57cec5SDimitry Andric         continue;
43350b57cec5SDimitry Andric       }
43360b57cec5SDimitry Andric       unsigned LElts = LTy->getNumElements();
43370b57cec5SDimitry Andric       // If Filter is longer than LFilter then it cannot be a subset of it.
43380b57cec5SDimitry Andric       if (FElts > LElts)
43390b57cec5SDimitry Andric         // Move on to the next filter.
43400b57cec5SDimitry Andric         continue;
43410b57cec5SDimitry Andric       // At this point we know that LFilter has at least one element.
43420b57cec5SDimitry Andric       if (isa<ConstantAggregateZero>(LFilter)) { // LFilter only contains zeros.
43430b57cec5SDimitry Andric         // Filter is a subset of LFilter iff Filter contains only zeros (as we
43440b57cec5SDimitry Andric         // already know that Filter is not longer than LFilter).
43450b57cec5SDimitry Andric         if (isa<ConstantAggregateZero>(Filter)) {
43460b57cec5SDimitry Andric           assert(FElts <= LElts && "Should have handled this case earlier!");
43470b57cec5SDimitry Andric           // Discard LFilter.
43480b57cec5SDimitry Andric           NewClauses.erase(J);
43490b57cec5SDimitry Andric           MakeNewInstruction = true;
43500b57cec5SDimitry Andric         }
43510b57cec5SDimitry Andric         // Move on to the next filter.
43520b57cec5SDimitry Andric         continue;
43530b57cec5SDimitry Andric       }
43540b57cec5SDimitry Andric       ConstantArray *LArray = cast<ConstantArray>(LFilter);
43550b57cec5SDimitry Andric       if (isa<ConstantAggregateZero>(Filter)) { // Filter only contains zeros.
43560b57cec5SDimitry Andric         // Since Filter is non-empty and contains only zeros, it is a subset of
43570b57cec5SDimitry Andric         // LFilter iff LFilter contains a zero.
43580b57cec5SDimitry Andric         assert(FElts > 0 && "Should have eliminated the empty filter earlier!");
43590b57cec5SDimitry Andric         for (unsigned l = 0; l != LElts; ++l)
43600b57cec5SDimitry Andric           if (LArray->getOperand(l)->isNullValue()) {
43610b57cec5SDimitry Andric             // LFilter contains a zero - discard it.
43620b57cec5SDimitry Andric             NewClauses.erase(J);
43630b57cec5SDimitry Andric             MakeNewInstruction = true;
43640b57cec5SDimitry Andric             break;
43650b57cec5SDimitry Andric           }
43660b57cec5SDimitry Andric         // Move on to the next filter.
43670b57cec5SDimitry Andric         continue;
43680b57cec5SDimitry Andric       }
43690b57cec5SDimitry Andric       // At this point we know that both filters are ConstantArrays.  Loop over
43700b57cec5SDimitry Andric       // operands to see whether every element of Filter is also an element of
43710b57cec5SDimitry Andric       // LFilter.  Since filters tend to be short this is probably faster than
43720b57cec5SDimitry Andric       // using a method that scales nicely.
43730b57cec5SDimitry Andric       ConstantArray *FArray = cast<ConstantArray>(Filter);
43740b57cec5SDimitry Andric       bool AllFound = true;
43750b57cec5SDimitry Andric       for (unsigned f = 0; f != FElts; ++f) {
43760b57cec5SDimitry Andric         Value *FTypeInfo = FArray->getOperand(f)->stripPointerCasts();
43770b57cec5SDimitry Andric         AllFound = false;
43780b57cec5SDimitry Andric         for (unsigned l = 0; l != LElts; ++l) {
43790b57cec5SDimitry Andric           Value *LTypeInfo = LArray->getOperand(l)->stripPointerCasts();
43800b57cec5SDimitry Andric           if (LTypeInfo == FTypeInfo) {
43810b57cec5SDimitry Andric             AllFound = true;
43820b57cec5SDimitry Andric             break;
43830b57cec5SDimitry Andric           }
43840b57cec5SDimitry Andric         }
43850b57cec5SDimitry Andric         if (!AllFound)
43860b57cec5SDimitry Andric           break;
43870b57cec5SDimitry Andric       }
43880b57cec5SDimitry Andric       if (AllFound) {
43890b57cec5SDimitry Andric         // Discard LFilter.
43900b57cec5SDimitry Andric         NewClauses.erase(J);
43910b57cec5SDimitry Andric         MakeNewInstruction = true;
43920b57cec5SDimitry Andric       }
43930b57cec5SDimitry Andric       // Move on to the next filter.
43940b57cec5SDimitry Andric     }
43950b57cec5SDimitry Andric   }
43960b57cec5SDimitry Andric 
43970b57cec5SDimitry Andric   // If we changed any of the clauses, replace the old landingpad instruction
43980b57cec5SDimitry Andric   // with a new one.
43990b57cec5SDimitry Andric   if (MakeNewInstruction) {
44000b57cec5SDimitry Andric     LandingPadInst *NLI = LandingPadInst::Create(LI.getType(),
44010b57cec5SDimitry Andric                                                  NewClauses.size());
4402*0fca6ea1SDimitry Andric     for (Constant *C : NewClauses)
4403*0fca6ea1SDimitry Andric       NLI->addClause(C);
44040b57cec5SDimitry Andric     // A landing pad with no clauses must have the cleanup flag set.  It is
44050b57cec5SDimitry Andric     // theoretically possible, though highly unlikely, that we eliminated all
44060b57cec5SDimitry Andric     // clauses.  If so, force the cleanup flag to true.
44070b57cec5SDimitry Andric     if (NewClauses.empty())
44080b57cec5SDimitry Andric       CleanupFlag = true;
44090b57cec5SDimitry Andric     NLI->setCleanup(CleanupFlag);
44100b57cec5SDimitry Andric     return NLI;
44110b57cec5SDimitry Andric   }
44120b57cec5SDimitry Andric 
44130b57cec5SDimitry Andric   // Even if none of the clauses changed, we may nonetheless have understood
44140b57cec5SDimitry Andric   // that the cleanup flag is pointless.  Clear it if so.
44150b57cec5SDimitry Andric   if (LI.isCleanup() != CleanupFlag) {
44160b57cec5SDimitry Andric     assert(!CleanupFlag && "Adding a cleanup, not removing one?!");
44170b57cec5SDimitry Andric     LI.setCleanup(CleanupFlag);
44180b57cec5SDimitry Andric     return &LI;
44190b57cec5SDimitry Andric   }
44200b57cec5SDimitry Andric 
44210b57cec5SDimitry Andric   return nullptr;
44220b57cec5SDimitry Andric }
44230b57cec5SDimitry Andric 
4424fe6060f1SDimitry Andric Value *
4425fe6060f1SDimitry Andric InstCombinerImpl::pushFreezeToPreventPoisonFromPropagating(FreezeInst &OrigFI) {
4426fe6060f1SDimitry Andric   // Try to push freeze through instructions that propagate but don't produce
4427fe6060f1SDimitry Andric   // poison as far as possible.  If an operand of freeze follows three
4428fe6060f1SDimitry Andric   // conditions 1) one-use, 2) does not produce poison, and 3) has all but one
4429fe6060f1SDimitry Andric   // guaranteed-non-poison operands then push the freeze through to the one
4430fe6060f1SDimitry Andric   // operand that is not guaranteed non-poison.  The actual transform is as
4431fe6060f1SDimitry Andric   // follows.
4432fe6060f1SDimitry Andric   //   Op1 = ...                        ; Op1 can be posion
4433fe6060f1SDimitry Andric   //   Op0 = Inst(Op1, NonPoisonOps...) ; Op0 has only one use and only have
4434fe6060f1SDimitry Andric   //                                    ; single guaranteed-non-poison operands
4435fe6060f1SDimitry Andric   //   ... = Freeze(Op0)
4436fe6060f1SDimitry Andric   // =>
4437fe6060f1SDimitry Andric   //   Op1 = ...
4438fe6060f1SDimitry Andric   //   Op1.fr = Freeze(Op1)
4439fe6060f1SDimitry Andric   //   ... = Inst(Op1.fr, NonPoisonOps...)
4440fe6060f1SDimitry Andric   auto *OrigOp = OrigFI.getOperand(0);
4441fe6060f1SDimitry Andric   auto *OrigOpInst = dyn_cast<Instruction>(OrigOp);
4442fe6060f1SDimitry Andric 
4443fe6060f1SDimitry Andric   // While we could change the other users of OrigOp to use freeze(OrigOp), that
4444fe6060f1SDimitry Andric   // potentially reduces their optimization potential, so let's only do this iff
4445fe6060f1SDimitry Andric   // the OrigOp is only used by the freeze.
4446349cc55cSDimitry Andric   if (!OrigOpInst || !OrigOpInst->hasOneUse() || isa<PHINode>(OrigOp))
4447349cc55cSDimitry Andric     return nullptr;
4448349cc55cSDimitry Andric 
4449349cc55cSDimitry Andric   // We can't push the freeze through an instruction which can itself create
4450349cc55cSDimitry Andric   // poison.  If the only source of new poison is flags, we can simply
4451349cc55cSDimitry Andric   // strip them (since we know the only use is the freeze and nothing can
4452349cc55cSDimitry Andric   // benefit from them.)
4453bdd1243dSDimitry Andric   if (canCreateUndefOrPoison(cast<Operator>(OrigOp),
4454bdd1243dSDimitry Andric                              /*ConsiderFlagsAndMetadata*/ false))
4455fe6060f1SDimitry Andric     return nullptr;
4456fe6060f1SDimitry Andric 
4457fe6060f1SDimitry Andric   // If operand is guaranteed not to be poison, there is no need to add freeze
4458fe6060f1SDimitry Andric   // to the operand. So we first find the operand that is not guaranteed to be
4459fe6060f1SDimitry Andric   // poison.
4460fe6060f1SDimitry Andric   Use *MaybePoisonOperand = nullptr;
4461fe6060f1SDimitry Andric   for (Use &U : OrigOpInst->operands()) {
4462bdd1243dSDimitry Andric     if (isa<MetadataAsValue>(U.get()) ||
4463bdd1243dSDimitry Andric         isGuaranteedNotToBeUndefOrPoison(U.get()))
4464fe6060f1SDimitry Andric       continue;
4465fe6060f1SDimitry Andric     if (!MaybePoisonOperand)
4466fe6060f1SDimitry Andric       MaybePoisonOperand = &U;
4467fe6060f1SDimitry Andric     else
4468fe6060f1SDimitry Andric       return nullptr;
4469fe6060f1SDimitry Andric   }
4470fe6060f1SDimitry Andric 
4471*0fca6ea1SDimitry Andric   OrigOpInst->dropPoisonGeneratingAnnotations();
4472349cc55cSDimitry Andric 
4473fe6060f1SDimitry Andric   // If all operands are guaranteed to be non-poison, we can drop freeze.
4474fe6060f1SDimitry Andric   if (!MaybePoisonOperand)
4475fe6060f1SDimitry Andric     return OrigOp;
4476fe6060f1SDimitry Andric 
447781ad6265SDimitry Andric   Builder.SetInsertPoint(OrigOpInst);
447881ad6265SDimitry Andric   auto *FrozenMaybePoisonOperand = Builder.CreateFreeze(
4479fe6060f1SDimitry Andric       MaybePoisonOperand->get(), MaybePoisonOperand->get()->getName() + ".fr");
4480fe6060f1SDimitry Andric 
4481fe6060f1SDimitry Andric   replaceUse(*MaybePoisonOperand, FrozenMaybePoisonOperand);
4482fe6060f1SDimitry Andric   return OrigOp;
4483fe6060f1SDimitry Andric }
4484fe6060f1SDimitry Andric 
448581ad6265SDimitry Andric Instruction *InstCombinerImpl::foldFreezeIntoRecurrence(FreezeInst &FI,
448681ad6265SDimitry Andric                                                         PHINode *PN) {
448781ad6265SDimitry Andric   // Detect whether this is a recurrence with a start value and some number of
448881ad6265SDimitry Andric   // backedge values. We'll check whether we can push the freeze through the
448981ad6265SDimitry Andric   // backedge values (possibly dropping poison flags along the way) until we
449081ad6265SDimitry Andric   // reach the phi again. In that case, we can move the freeze to the start
449181ad6265SDimitry Andric   // value.
449281ad6265SDimitry Andric   Use *StartU = nullptr;
449381ad6265SDimitry Andric   SmallVector<Value *> Worklist;
449481ad6265SDimitry Andric   for (Use &U : PN->incoming_values()) {
449581ad6265SDimitry Andric     if (DT.dominates(PN->getParent(), PN->getIncomingBlock(U))) {
449681ad6265SDimitry Andric       // Add backedge value to worklist.
449781ad6265SDimitry Andric       Worklist.push_back(U.get());
449881ad6265SDimitry Andric       continue;
449981ad6265SDimitry Andric     }
450081ad6265SDimitry Andric 
450181ad6265SDimitry Andric     // Don't bother handling multiple start values.
450281ad6265SDimitry Andric     if (StartU)
450381ad6265SDimitry Andric       return nullptr;
450481ad6265SDimitry Andric     StartU = &U;
450581ad6265SDimitry Andric   }
450681ad6265SDimitry Andric 
450781ad6265SDimitry Andric   if (!StartU || Worklist.empty())
450881ad6265SDimitry Andric     return nullptr; // Not a recurrence.
450981ad6265SDimitry Andric 
451081ad6265SDimitry Andric   Value *StartV = StartU->get();
451181ad6265SDimitry Andric   BasicBlock *StartBB = PN->getIncomingBlock(*StartU);
451281ad6265SDimitry Andric   bool StartNeedsFreeze = !isGuaranteedNotToBeUndefOrPoison(StartV);
45135f757f3fSDimitry Andric   // We can't insert freeze if the start value is the result of the
451481ad6265SDimitry Andric   // terminator (e.g. an invoke).
451581ad6265SDimitry Andric   if (StartNeedsFreeze && StartBB->getTerminator() == StartV)
451681ad6265SDimitry Andric     return nullptr;
451781ad6265SDimitry Andric 
451881ad6265SDimitry Andric   SmallPtrSet<Value *, 32> Visited;
451981ad6265SDimitry Andric   SmallVector<Instruction *> DropFlags;
452081ad6265SDimitry Andric   while (!Worklist.empty()) {
452181ad6265SDimitry Andric     Value *V = Worklist.pop_back_val();
452281ad6265SDimitry Andric     if (!Visited.insert(V).second)
452381ad6265SDimitry Andric       continue;
452481ad6265SDimitry Andric 
452581ad6265SDimitry Andric     if (Visited.size() > 32)
452681ad6265SDimitry Andric       return nullptr; // Limit the total number of values we inspect.
452781ad6265SDimitry Andric 
452881ad6265SDimitry Andric     // Assume that PN is non-poison, because it will be after the transform.
452981ad6265SDimitry Andric     if (V == PN || isGuaranteedNotToBeUndefOrPoison(V))
453081ad6265SDimitry Andric       continue;
453181ad6265SDimitry Andric 
453281ad6265SDimitry Andric     Instruction *I = dyn_cast<Instruction>(V);
453381ad6265SDimitry Andric     if (!I || canCreateUndefOrPoison(cast<Operator>(I),
4534bdd1243dSDimitry Andric                                      /*ConsiderFlagsAndMetadata*/ false))
453581ad6265SDimitry Andric       return nullptr;
453681ad6265SDimitry Andric 
453781ad6265SDimitry Andric     DropFlags.push_back(I);
453881ad6265SDimitry Andric     append_range(Worklist, I->operands());
453981ad6265SDimitry Andric   }
454081ad6265SDimitry Andric 
454181ad6265SDimitry Andric   for (Instruction *I : DropFlags)
4542*0fca6ea1SDimitry Andric     I->dropPoisonGeneratingAnnotations();
454381ad6265SDimitry Andric 
454481ad6265SDimitry Andric   if (StartNeedsFreeze) {
454581ad6265SDimitry Andric     Builder.SetInsertPoint(StartBB->getTerminator());
454681ad6265SDimitry Andric     Value *FrozenStartV = Builder.CreateFreeze(StartV,
454781ad6265SDimitry Andric                                                StartV->getName() + ".fr");
454881ad6265SDimitry Andric     replaceUse(*StartU, FrozenStartV);
454981ad6265SDimitry Andric   }
455081ad6265SDimitry Andric   return replaceInstUsesWith(FI, PN);
455181ad6265SDimitry Andric }
455281ad6265SDimitry Andric 
455381ad6265SDimitry Andric bool InstCombinerImpl::freezeOtherUses(FreezeInst &FI) {
4554fe6060f1SDimitry Andric   Value *Op = FI.getOperand(0);
4555fe6060f1SDimitry Andric 
455681ad6265SDimitry Andric   if (isa<Constant>(Op) || Op->hasOneUse())
4557fe6060f1SDimitry Andric     return false;
4558fe6060f1SDimitry Andric 
455981ad6265SDimitry Andric   // Move the freeze directly after the definition of its operand, so that
456081ad6265SDimitry Andric   // it dominates the maximum number of uses. Note that it may not dominate
456181ad6265SDimitry Andric   // *all* uses if the operand is an invoke/callbr and the use is in a phi on
456281ad6265SDimitry Andric   // the normal/default destination. This is why the domination check in the
456381ad6265SDimitry Andric   // replacement below is still necessary.
45645f757f3fSDimitry Andric   BasicBlock::iterator MoveBefore;
456581ad6265SDimitry Andric   if (isa<Argument>(Op)) {
4566bdd1243dSDimitry Andric     MoveBefore =
45675f757f3fSDimitry Andric         FI.getFunction()->getEntryBlock().getFirstNonPHIOrDbgOrAlloca();
456881ad6265SDimitry Andric   } else {
45695f757f3fSDimitry Andric     auto MoveBeforeOpt = cast<Instruction>(Op)->getInsertionPointAfterDef();
45705f757f3fSDimitry Andric     if (!MoveBeforeOpt)
4571bdd1243dSDimitry Andric       return false;
45725f757f3fSDimitry Andric     MoveBefore = *MoveBeforeOpt;
457381ad6265SDimitry Andric   }
457481ad6265SDimitry Andric 
45755f757f3fSDimitry Andric   // Don't move to the position of a debug intrinsic.
45765f757f3fSDimitry Andric   if (isa<DbgInfoIntrinsic>(MoveBefore))
45775f757f3fSDimitry Andric     MoveBefore = MoveBefore->getNextNonDebugInstruction()->getIterator();
45785f757f3fSDimitry Andric   // Re-point iterator to come after any debug-info records, if we're
45795f757f3fSDimitry Andric   // running in "RemoveDIs" mode
45805f757f3fSDimitry Andric   MoveBefore.setHeadBit(false);
45815f757f3fSDimitry Andric 
4582fe6060f1SDimitry Andric   bool Changed = false;
45835f757f3fSDimitry Andric   if (&FI != &*MoveBefore) {
45845f757f3fSDimitry Andric     FI.moveBefore(*MoveBefore->getParent(), MoveBefore);
458581ad6265SDimitry Andric     Changed = true;
458681ad6265SDimitry Andric   }
458781ad6265SDimitry Andric 
4588fe6060f1SDimitry Andric   Op->replaceUsesWithIf(&FI, [&](Use &U) -> bool {
4589fe6060f1SDimitry Andric     bool Dominates = DT.dominates(&FI, U);
4590fe6060f1SDimitry Andric     Changed |= Dominates;
4591fe6060f1SDimitry Andric     return Dominates;
4592fe6060f1SDimitry Andric   });
4593fe6060f1SDimitry Andric 
4594fe6060f1SDimitry Andric   return Changed;
4595fe6060f1SDimitry Andric }
4596fe6060f1SDimitry Andric 
459706c3fb27SDimitry Andric // Check if any direct or bitcast user of this value is a shuffle instruction.
459806c3fb27SDimitry Andric static bool isUsedWithinShuffleVector(Value *V) {
459906c3fb27SDimitry Andric   for (auto *U : V->users()) {
460006c3fb27SDimitry Andric     if (isa<ShuffleVectorInst>(U))
460106c3fb27SDimitry Andric       return true;
460206c3fb27SDimitry Andric     else if (match(U, m_BitCast(m_Specific(V))) && isUsedWithinShuffleVector(U))
460306c3fb27SDimitry Andric       return true;
460406c3fb27SDimitry Andric   }
460506c3fb27SDimitry Andric   return false;
460606c3fb27SDimitry Andric }
460706c3fb27SDimitry Andric 
4608e8d8bef9SDimitry Andric Instruction *InstCombinerImpl::visitFreeze(FreezeInst &I) {
4609480093f4SDimitry Andric   Value *Op0 = I.getOperand(0);
4610480093f4SDimitry Andric 
461181ad6265SDimitry Andric   if (Value *V = simplifyFreezeInst(Op0, SQ.getWithInstruction(&I)))
4612480093f4SDimitry Andric     return replaceInstUsesWith(I, V);
4613480093f4SDimitry Andric 
4614e8d8bef9SDimitry Andric   // freeze (phi const, x) --> phi const, (freeze x)
4615e8d8bef9SDimitry Andric   if (auto *PN = dyn_cast<PHINode>(Op0)) {
4616e8d8bef9SDimitry Andric     if (Instruction *NV = foldOpIntoPhi(I, PN))
4617e8d8bef9SDimitry Andric       return NV;
461881ad6265SDimitry Andric     if (Instruction *NV = foldFreezeIntoRecurrence(I, PN))
461981ad6265SDimitry Andric       return NV;
4620e8d8bef9SDimitry Andric   }
4621e8d8bef9SDimitry Andric 
4622fe6060f1SDimitry Andric   if (Value *NI = pushFreezeToPreventPoisonFromPropagating(I))
4623fe6060f1SDimitry Andric     return replaceInstUsesWith(I, NI);
4624fe6060f1SDimitry Andric 
462581ad6265SDimitry Andric   // If I is freeze(undef), check its uses and fold it to a fixed constant.
4626e8d8bef9SDimitry Andric   // - or: pick -1
462781ad6265SDimitry Andric   // - select's condition: if the true value is constant, choose it by making
462881ad6265SDimitry Andric   //                       the condition true.
462981ad6265SDimitry Andric   // - default: pick 0
463081ad6265SDimitry Andric   //
463181ad6265SDimitry Andric   // Note that this transform is intentionally done here rather than
463281ad6265SDimitry Andric   // via an analysis in InstSimplify or at individual user sites. That is
463381ad6265SDimitry Andric   // because we must produce the same value for all uses of the freeze -
463481ad6265SDimitry Andric   // it's the reason "freeze" exists!
463581ad6265SDimitry Andric   //
463681ad6265SDimitry Andric   // TODO: This could use getBinopAbsorber() / getBinopIdentity() to avoid
463781ad6265SDimitry Andric   //       duplicating logic for binops at least.
463881ad6265SDimitry Andric   auto getUndefReplacement = [&I](Type *Ty) {
4639e8d8bef9SDimitry Andric     Constant *BestValue = nullptr;
464081ad6265SDimitry Andric     Constant *NullValue = Constant::getNullValue(Ty);
4641e8d8bef9SDimitry Andric     for (const auto *U : I.users()) {
4642e8d8bef9SDimitry Andric       Constant *C = NullValue;
4643e8d8bef9SDimitry Andric       if (match(U, m_Or(m_Value(), m_Value())))
464481ad6265SDimitry Andric         C = ConstantInt::getAllOnesValue(Ty);
464581ad6265SDimitry Andric       else if (match(U, m_Select(m_Specific(&I), m_Constant(), m_Value())))
464681ad6265SDimitry Andric         C = ConstantInt::getTrue(Ty);
4647e8d8bef9SDimitry Andric 
4648e8d8bef9SDimitry Andric       if (!BestValue)
4649e8d8bef9SDimitry Andric         BestValue = C;
4650e8d8bef9SDimitry Andric       else if (BestValue != C)
4651e8d8bef9SDimitry Andric         BestValue = NullValue;
4652e8d8bef9SDimitry Andric     }
465381ad6265SDimitry Andric     assert(BestValue && "Must have at least one use");
465481ad6265SDimitry Andric     return BestValue;
465581ad6265SDimitry Andric   };
4656e8d8bef9SDimitry Andric 
465706c3fb27SDimitry Andric   if (match(Op0, m_Undef())) {
465806c3fb27SDimitry Andric     // Don't fold freeze(undef/poison) if it's used as a vector operand in
465906c3fb27SDimitry Andric     // a shuffle. This may improve codegen for shuffles that allow
466006c3fb27SDimitry Andric     // unspecified inputs.
466106c3fb27SDimitry Andric     if (isUsedWithinShuffleVector(&I))
466206c3fb27SDimitry Andric       return nullptr;
466381ad6265SDimitry Andric     return replaceInstUsesWith(I, getUndefReplacement(I.getType()));
466406c3fb27SDimitry Andric   }
466581ad6265SDimitry Andric 
466681ad6265SDimitry Andric   Constant *C;
466781ad6265SDimitry Andric   if (match(Op0, m_Constant(C)) && C->containsUndefOrPoisonElement()) {
466881ad6265SDimitry Andric     Constant *ReplaceC = getUndefReplacement(I.getType()->getScalarType());
466981ad6265SDimitry Andric     return replaceInstUsesWith(I, Constant::replaceUndefsWith(C, ReplaceC));
4670e8d8bef9SDimitry Andric   }
4671e8d8bef9SDimitry Andric 
467281ad6265SDimitry Andric   // Replace uses of Op with freeze(Op).
467381ad6265SDimitry Andric   if (freezeOtherUses(I))
4674fe6060f1SDimitry Andric     return &I;
4675fe6060f1SDimitry Andric 
4676480093f4SDimitry Andric   return nullptr;
4677480093f4SDimitry Andric }
4678480093f4SDimitry Andric 
467904eeddc0SDimitry Andric /// Check for case where the call writes to an otherwise dead alloca.  This
468004eeddc0SDimitry Andric /// shows up for unused out-params in idiomatic C/C++ code.   Note that this
468104eeddc0SDimitry Andric /// helper *only* analyzes the write; doesn't check any other legality aspect.
468204eeddc0SDimitry Andric static bool SoleWriteToDeadLocal(Instruction *I, TargetLibraryInfo &TLI) {
468304eeddc0SDimitry Andric   auto *CB = dyn_cast<CallBase>(I);
468404eeddc0SDimitry Andric   if (!CB)
468504eeddc0SDimitry Andric     // TODO: handle e.g. store to alloca here - only worth doing if we extend
468604eeddc0SDimitry Andric     // to allow reload along used path as described below.  Otherwise, this
468704eeddc0SDimitry Andric     // is simply a store to a dead allocation which will be removed.
468804eeddc0SDimitry Andric     return false;
4689bdd1243dSDimitry Andric   std::optional<MemoryLocation> Dest = MemoryLocation::getForDest(CB, TLI);
469004eeddc0SDimitry Andric   if (!Dest)
469104eeddc0SDimitry Andric     return false;
469204eeddc0SDimitry Andric   auto *AI = dyn_cast<AllocaInst>(getUnderlyingObject(Dest->Ptr));
469304eeddc0SDimitry Andric   if (!AI)
469404eeddc0SDimitry Andric     // TODO: allow malloc?
469504eeddc0SDimitry Andric     return false;
469604eeddc0SDimitry Andric   // TODO: allow memory access dominated by move point?  Note that since AI
469704eeddc0SDimitry Andric   // could have a reference to itself captured by the call, we would need to
469804eeddc0SDimitry Andric   // account for cycles in doing so.
469904eeddc0SDimitry Andric   SmallVector<const User *> AllocaUsers;
470004eeddc0SDimitry Andric   SmallPtrSet<const User *, 4> Visited;
470104eeddc0SDimitry Andric   auto pushUsers = [&](const Instruction &I) {
470204eeddc0SDimitry Andric     for (const User *U : I.users()) {
470304eeddc0SDimitry Andric       if (Visited.insert(U).second)
470404eeddc0SDimitry Andric         AllocaUsers.push_back(U);
470504eeddc0SDimitry Andric     }
470604eeddc0SDimitry Andric   };
470704eeddc0SDimitry Andric   pushUsers(*AI);
470804eeddc0SDimitry Andric   while (!AllocaUsers.empty()) {
470904eeddc0SDimitry Andric     auto *UserI = cast<Instruction>(AllocaUsers.pop_back_val());
471004eeddc0SDimitry Andric     if (isa<BitCastInst>(UserI) || isa<GetElementPtrInst>(UserI) ||
471104eeddc0SDimitry Andric         isa<AddrSpaceCastInst>(UserI)) {
471204eeddc0SDimitry Andric       pushUsers(*UserI);
471304eeddc0SDimitry Andric       continue;
471404eeddc0SDimitry Andric     }
471504eeddc0SDimitry Andric     if (UserI == CB)
471604eeddc0SDimitry Andric       continue;
471704eeddc0SDimitry Andric     // TODO: support lifetime.start/end here
471804eeddc0SDimitry Andric     return false;
471904eeddc0SDimitry Andric   }
472004eeddc0SDimitry Andric   return true;
472104eeddc0SDimitry Andric }
472204eeddc0SDimitry Andric 
47230b57cec5SDimitry Andric /// Try to move the specified instruction from its current block into the
47240b57cec5SDimitry Andric /// beginning of DestBlock, which can only happen if it's safe to move the
47250b57cec5SDimitry Andric /// instruction past all of the instructions between it and the end of its
47260b57cec5SDimitry Andric /// block.
472706c3fb27SDimitry Andric bool InstCombinerImpl::tryToSinkInstruction(Instruction *I,
472806c3fb27SDimitry Andric                                             BasicBlock *DestBlock) {
47290b57cec5SDimitry Andric   BasicBlock *SrcBlock = I->getParent();
47300b57cec5SDimitry Andric 
47310b57cec5SDimitry Andric   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
473204eeddc0SDimitry Andric   if (isa<PHINode>(I) || I->isEHPad() || I->mayThrow() || !I->willReturn() ||
47330b57cec5SDimitry Andric       I->isTerminator())
47340b57cec5SDimitry Andric     return false;
47350b57cec5SDimitry Andric 
47360b57cec5SDimitry Andric   // Do not sink static or dynamic alloca instructions. Static allocas must
47370b57cec5SDimitry Andric   // remain in the entry block, and dynamic allocas must not be sunk in between
47380b57cec5SDimitry Andric   // a stacksave / stackrestore pair, which would incorrectly shorten its
47390b57cec5SDimitry Andric   // lifetime.
47400b57cec5SDimitry Andric   if (isa<AllocaInst>(I))
47410b57cec5SDimitry Andric     return false;
47420b57cec5SDimitry Andric 
47430b57cec5SDimitry Andric   // Do not sink into catchswitch blocks.
47440b57cec5SDimitry Andric   if (isa<CatchSwitchInst>(DestBlock->getTerminator()))
47450b57cec5SDimitry Andric     return false;
47460b57cec5SDimitry Andric 
47470b57cec5SDimitry Andric   // Do not sink convergent call instructions.
47480b57cec5SDimitry Andric   if (auto *CI = dyn_cast<CallInst>(I)) {
47490b57cec5SDimitry Andric     if (CI->isConvergent())
47500b57cec5SDimitry Andric       return false;
47510b57cec5SDimitry Andric   }
475204eeddc0SDimitry Andric 
475304eeddc0SDimitry Andric   // Unless we can prove that the memory write isn't visibile except on the
475404eeddc0SDimitry Andric   // path we're sinking to, we must bail.
475504eeddc0SDimitry Andric   if (I->mayWriteToMemory()) {
475604eeddc0SDimitry Andric     if (!SoleWriteToDeadLocal(I, TLI))
475704eeddc0SDimitry Andric       return false;
475804eeddc0SDimitry Andric   }
475904eeddc0SDimitry Andric 
47600b57cec5SDimitry Andric   // We can only sink load instructions if there is nothing between the load and
47610b57cec5SDimitry Andric   // the end of block that could change the value.
47620b57cec5SDimitry Andric   if (I->mayReadFromMemory()) {
47635ffd83dbSDimitry Andric     // We don't want to do any sophisticated alias analysis, so we only check
47645ffd83dbSDimitry Andric     // the instructions after I in I's parent block if we try to sink to its
47655ffd83dbSDimitry Andric     // successor block.
47665ffd83dbSDimitry Andric     if (DestBlock->getUniquePredecessor() != I->getParent())
47675ffd83dbSDimitry Andric       return false;
476804eeddc0SDimitry Andric     for (BasicBlock::iterator Scan = std::next(I->getIterator()),
47690b57cec5SDimitry Andric                               E = I->getParent()->end();
47700b57cec5SDimitry Andric          Scan != E; ++Scan)
47710b57cec5SDimitry Andric       if (Scan->mayWriteToMemory())
47720b57cec5SDimitry Andric         return false;
47730b57cec5SDimitry Andric   }
47745ffd83dbSDimitry Andric 
477506c3fb27SDimitry Andric   I->dropDroppableUses([&](const Use *U) {
477606c3fb27SDimitry Andric     auto *I = dyn_cast<Instruction>(U->getUser());
477706c3fb27SDimitry Andric     if (I && I->getParent() != DestBlock) {
477806c3fb27SDimitry Andric       Worklist.add(I);
47795ffd83dbSDimitry Andric       return true;
478006c3fb27SDimitry Andric     }
478106c3fb27SDimitry Andric     return false;
47825ffd83dbSDimitry Andric   });
47835ffd83dbSDimitry Andric   /// FIXME: We could remove droppable uses that are not dominated by
47845ffd83dbSDimitry Andric   /// the new position.
47855ffd83dbSDimitry Andric 
47860b57cec5SDimitry Andric   BasicBlock::iterator InsertPos = DestBlock->getFirstInsertionPt();
47875f757f3fSDimitry Andric   I->moveBefore(*DestBlock, InsertPos);
47880b57cec5SDimitry Andric   ++NumSunkInst;
47890b57cec5SDimitry Andric 
47900b57cec5SDimitry Andric   // Also sink all related debug uses from the source basic block. Otherwise we
47910b57cec5SDimitry Andric   // get debug use before the def. Attempt to salvage debug uses first, to
47920b57cec5SDimitry Andric   // maximise the range variables have location for. If we cannot salvage, then
47930b57cec5SDimitry Andric   // mark the location undef: we know it was supposed to receive a new location
47940b57cec5SDimitry Andric   // here, but that computation has been sunk.
47950b57cec5SDimitry Andric   SmallVector<DbgVariableIntrinsic *, 2> DbgUsers;
4796*0fca6ea1SDimitry Andric   SmallVector<DbgVariableRecord *, 2> DbgVariableRecords;
4797*0fca6ea1SDimitry Andric   findDbgUsers(DbgUsers, I, &DbgVariableRecords);
4798*0fca6ea1SDimitry Andric   if (!DbgUsers.empty())
4799*0fca6ea1SDimitry Andric     tryToSinkInstructionDbgValues(I, InsertPos, SrcBlock, DestBlock, DbgUsers);
4800*0fca6ea1SDimitry Andric   if (!DbgVariableRecords.empty())
4801*0fca6ea1SDimitry Andric     tryToSinkInstructionDbgVariableRecords(I, InsertPos, SrcBlock, DestBlock,
4802*0fca6ea1SDimitry Andric                                            DbgVariableRecords);
48035f757f3fSDimitry Andric 
4804*0fca6ea1SDimitry Andric   // PS: there are numerous flaws with this behaviour, not least that right now
4805*0fca6ea1SDimitry Andric   // assignments can be re-ordered past other assignments to the same variable
4806*0fca6ea1SDimitry Andric   // if they use different Values. Creating more undef assignements can never be
4807*0fca6ea1SDimitry Andric   // undone. And salvaging all users outside of this block can un-necessarily
4808*0fca6ea1SDimitry Andric   // alter the lifetime of the live-value that the variable refers to.
4809*0fca6ea1SDimitry Andric   // Some of these things can be resolved by tolerating debug use-before-defs in
4810*0fca6ea1SDimitry Andric   // LLVM-IR, however it depends on the instruction-referencing CodeGen backend
4811*0fca6ea1SDimitry Andric   // being used for more architectures.
4812*0fca6ea1SDimitry Andric 
4813*0fca6ea1SDimitry Andric   return true;
4814*0fca6ea1SDimitry Andric }
4815*0fca6ea1SDimitry Andric 
4816*0fca6ea1SDimitry Andric void InstCombinerImpl::tryToSinkInstructionDbgValues(
4817*0fca6ea1SDimitry Andric     Instruction *I, BasicBlock::iterator InsertPos, BasicBlock *SrcBlock,
4818*0fca6ea1SDimitry Andric     BasicBlock *DestBlock, SmallVectorImpl<DbgVariableIntrinsic *> &DbgUsers) {
48195f757f3fSDimitry Andric   // For all debug values in the destination block, the sunk instruction
48205f757f3fSDimitry Andric   // will still be available, so they do not need to be dropped.
48215f757f3fSDimitry Andric   SmallVector<DbgVariableIntrinsic *, 2> DbgUsersToSalvage;
48225f757f3fSDimitry Andric   for (auto &DbgUser : DbgUsers)
48235f757f3fSDimitry Andric     if (DbgUser->getParent() != DestBlock)
48245f757f3fSDimitry Andric       DbgUsersToSalvage.push_back(DbgUser);
48255f757f3fSDimitry Andric 
48265f757f3fSDimitry Andric   // Process the sinking DbgUsersToSalvage in reverse order, as we only want
48275f757f3fSDimitry Andric   // to clone the last appearing debug intrinsic for each given variable.
4828fe6060f1SDimitry Andric   SmallVector<DbgVariableIntrinsic *, 2> DbgUsersToSink;
48295f757f3fSDimitry Andric   for (DbgVariableIntrinsic *DVI : DbgUsersToSalvage)
4830fe6060f1SDimitry Andric     if (DVI->getParent() == SrcBlock)
4831fe6060f1SDimitry Andric       DbgUsersToSink.push_back(DVI);
4832fe6060f1SDimitry Andric   llvm::sort(DbgUsersToSink,
4833fe6060f1SDimitry Andric              [](auto *A, auto *B) { return B->comesBefore(A); });
48345ffd83dbSDimitry Andric 
48355ffd83dbSDimitry Andric   SmallVector<DbgVariableIntrinsic *, 2> DIIClones;
4836fe6060f1SDimitry Andric   SmallSet<DebugVariable, 4> SunkVariables;
4837bdd1243dSDimitry Andric   for (auto *User : DbgUsersToSink) {
48385ffd83dbSDimitry Andric     // A dbg.declare instruction should not be cloned, since there can only be
48395ffd83dbSDimitry Andric     // one per variable fragment. It should be left in the original place
48405ffd83dbSDimitry Andric     // because the sunk instruction is not an alloca (otherwise we could not be
48415ffd83dbSDimitry Andric     // here).
4842fe6060f1SDimitry Andric     if (isa<DbgDeclareInst>(User))
4843fe6060f1SDimitry Andric       continue;
4844fe6060f1SDimitry Andric 
4845fe6060f1SDimitry Andric     DebugVariable DbgUserVariable =
4846fe6060f1SDimitry Andric         DebugVariable(User->getVariable(), User->getExpression(),
4847fe6060f1SDimitry Andric                       User->getDebugLoc()->getInlinedAt());
4848fe6060f1SDimitry Andric 
4849fe6060f1SDimitry Andric     if (!SunkVariables.insert(DbgUserVariable).second)
48508bcb0991SDimitry Andric       continue;
48515ffd83dbSDimitry Andric 
4852bdd1243dSDimitry Andric     // Leave dbg.assign intrinsics in their original positions and there should
4853bdd1243dSDimitry Andric     // be no need to insert a clone.
4854bdd1243dSDimitry Andric     if (isa<DbgAssignIntrinsic>(User))
4855bdd1243dSDimitry Andric       continue;
4856bdd1243dSDimitry Andric 
48575ffd83dbSDimitry Andric     DIIClones.emplace_back(cast<DbgVariableIntrinsic>(User->clone()));
4858fe6060f1SDimitry Andric     if (isa<DbgDeclareInst>(User) && isa<CastInst>(I))
4859fe6060f1SDimitry Andric       DIIClones.back()->replaceVariableLocationOp(I, I->getOperand(0));
48605ffd83dbSDimitry Andric     LLVM_DEBUG(dbgs() << "CLONE: " << *DIIClones.back() << '\n');
48618bcb0991SDimitry Andric   }
48628bcb0991SDimitry Andric 
48635ffd83dbSDimitry Andric   // Perform salvaging without the clones, then sink the clones.
48645ffd83dbSDimitry Andric   if (!DIIClones.empty()) {
4865*0fca6ea1SDimitry Andric     salvageDebugInfoForDbgValues(*I, DbgUsersToSalvage, {});
4866fe6060f1SDimitry Andric     // The clones are in reverse order of original appearance, reverse again to
4867fe6060f1SDimitry Andric     // maintain the original order.
4868fe6060f1SDimitry Andric     for (auto &DIIClone : llvm::reverse(DIIClones)) {
48695ffd83dbSDimitry Andric       DIIClone->insertBefore(&*InsertPos);
48705ffd83dbSDimitry Andric       LLVM_DEBUG(dbgs() << "SINK: " << *DIIClone << '\n');
48715ffd83dbSDimitry Andric     }
48725ffd83dbSDimitry Andric   }
4873*0fca6ea1SDimitry Andric }
48740b57cec5SDimitry Andric 
4875*0fca6ea1SDimitry Andric void InstCombinerImpl::tryToSinkInstructionDbgVariableRecords(
4876*0fca6ea1SDimitry Andric     Instruction *I, BasicBlock::iterator InsertPos, BasicBlock *SrcBlock,
4877*0fca6ea1SDimitry Andric     BasicBlock *DestBlock,
4878*0fca6ea1SDimitry Andric     SmallVectorImpl<DbgVariableRecord *> &DbgVariableRecords) {
4879*0fca6ea1SDimitry Andric   // Implementation of tryToSinkInstructionDbgValues, but for the
4880*0fca6ea1SDimitry Andric   // DbgVariableRecord of variable assignments rather than dbg.values.
4881*0fca6ea1SDimitry Andric 
4882*0fca6ea1SDimitry Andric   // Fetch all DbgVariableRecords not already in the destination.
4883*0fca6ea1SDimitry Andric   SmallVector<DbgVariableRecord *, 2> DbgVariableRecordsToSalvage;
4884*0fca6ea1SDimitry Andric   for (auto &DVR : DbgVariableRecords)
4885*0fca6ea1SDimitry Andric     if (DVR->getParent() != DestBlock)
4886*0fca6ea1SDimitry Andric       DbgVariableRecordsToSalvage.push_back(DVR);
4887*0fca6ea1SDimitry Andric 
4888*0fca6ea1SDimitry Andric   // Fetch a second collection, of DbgVariableRecords in the source block that
4889*0fca6ea1SDimitry Andric   // we're going to sink.
4890*0fca6ea1SDimitry Andric   SmallVector<DbgVariableRecord *> DbgVariableRecordsToSink;
4891*0fca6ea1SDimitry Andric   for (DbgVariableRecord *DVR : DbgVariableRecordsToSalvage)
4892*0fca6ea1SDimitry Andric     if (DVR->getParent() == SrcBlock)
4893*0fca6ea1SDimitry Andric       DbgVariableRecordsToSink.push_back(DVR);
4894*0fca6ea1SDimitry Andric 
4895*0fca6ea1SDimitry Andric   // Sort DbgVariableRecords according to their position in the block. This is a
4896*0fca6ea1SDimitry Andric   // partial order: DbgVariableRecords attached to different instructions will
4897*0fca6ea1SDimitry Andric   // be ordered by the instruction order, but DbgVariableRecords attached to the
4898*0fca6ea1SDimitry Andric   // same instruction won't have an order.
4899*0fca6ea1SDimitry Andric   auto Order = [](DbgVariableRecord *A, DbgVariableRecord *B) -> bool {
4900*0fca6ea1SDimitry Andric     return B->getInstruction()->comesBefore(A->getInstruction());
4901*0fca6ea1SDimitry Andric   };
4902*0fca6ea1SDimitry Andric   llvm::stable_sort(DbgVariableRecordsToSink, Order);
4903*0fca6ea1SDimitry Andric 
4904*0fca6ea1SDimitry Andric   // If there are two assignments to the same variable attached to the same
4905*0fca6ea1SDimitry Andric   // instruction, the ordering between the two assignments is important. Scan
4906*0fca6ea1SDimitry Andric   // for this (rare) case and establish which is the last assignment.
4907*0fca6ea1SDimitry Andric   using InstVarPair = std::pair<const Instruction *, DebugVariable>;
4908*0fca6ea1SDimitry Andric   SmallDenseMap<InstVarPair, DbgVariableRecord *> FilterOutMap;
4909*0fca6ea1SDimitry Andric   if (DbgVariableRecordsToSink.size() > 1) {
4910*0fca6ea1SDimitry Andric     SmallDenseMap<InstVarPair, unsigned> CountMap;
4911*0fca6ea1SDimitry Andric     // Count how many assignments to each variable there is per instruction.
4912*0fca6ea1SDimitry Andric     for (DbgVariableRecord *DVR : DbgVariableRecordsToSink) {
4913*0fca6ea1SDimitry Andric       DebugVariable DbgUserVariable =
4914*0fca6ea1SDimitry Andric           DebugVariable(DVR->getVariable(), DVR->getExpression(),
4915*0fca6ea1SDimitry Andric                         DVR->getDebugLoc()->getInlinedAt());
4916*0fca6ea1SDimitry Andric       CountMap[std::make_pair(DVR->getInstruction(), DbgUserVariable)] += 1;
4917*0fca6ea1SDimitry Andric     }
4918*0fca6ea1SDimitry Andric 
4919*0fca6ea1SDimitry Andric     // If there are any instructions with two assignments, add them to the
4920*0fca6ea1SDimitry Andric     // FilterOutMap to record that they need extra filtering.
4921*0fca6ea1SDimitry Andric     SmallPtrSet<const Instruction *, 4> DupSet;
4922*0fca6ea1SDimitry Andric     for (auto It : CountMap) {
4923*0fca6ea1SDimitry Andric       if (It.second > 1) {
4924*0fca6ea1SDimitry Andric         FilterOutMap[It.first] = nullptr;
4925*0fca6ea1SDimitry Andric         DupSet.insert(It.first.first);
4926*0fca6ea1SDimitry Andric       }
4927*0fca6ea1SDimitry Andric     }
4928*0fca6ea1SDimitry Andric 
4929*0fca6ea1SDimitry Andric     // For all instruction/variable pairs needing extra filtering, find the
4930*0fca6ea1SDimitry Andric     // latest assignment.
4931*0fca6ea1SDimitry Andric     for (const Instruction *Inst : DupSet) {
4932*0fca6ea1SDimitry Andric       for (DbgVariableRecord &DVR :
4933*0fca6ea1SDimitry Andric            llvm::reverse(filterDbgVars(Inst->getDbgRecordRange()))) {
4934*0fca6ea1SDimitry Andric         DebugVariable DbgUserVariable =
4935*0fca6ea1SDimitry Andric             DebugVariable(DVR.getVariable(), DVR.getExpression(),
4936*0fca6ea1SDimitry Andric                           DVR.getDebugLoc()->getInlinedAt());
4937*0fca6ea1SDimitry Andric         auto FilterIt =
4938*0fca6ea1SDimitry Andric             FilterOutMap.find(std::make_pair(Inst, DbgUserVariable));
4939*0fca6ea1SDimitry Andric         if (FilterIt == FilterOutMap.end())
4940*0fca6ea1SDimitry Andric           continue;
4941*0fca6ea1SDimitry Andric         if (FilterIt->second != nullptr)
4942*0fca6ea1SDimitry Andric           continue;
4943*0fca6ea1SDimitry Andric         FilterIt->second = &DVR;
4944*0fca6ea1SDimitry Andric       }
4945*0fca6ea1SDimitry Andric     }
4946*0fca6ea1SDimitry Andric   }
4947*0fca6ea1SDimitry Andric 
4948*0fca6ea1SDimitry Andric   // Perform cloning of the DbgVariableRecords that we plan on sinking, filter
4949*0fca6ea1SDimitry Andric   // out any duplicate assignments identified above.
4950*0fca6ea1SDimitry Andric   SmallVector<DbgVariableRecord *, 2> DVRClones;
4951*0fca6ea1SDimitry Andric   SmallSet<DebugVariable, 4> SunkVariables;
4952*0fca6ea1SDimitry Andric   for (DbgVariableRecord *DVR : DbgVariableRecordsToSink) {
4953*0fca6ea1SDimitry Andric     if (DVR->Type == DbgVariableRecord::LocationType::Declare)
4954*0fca6ea1SDimitry Andric       continue;
4955*0fca6ea1SDimitry Andric 
4956*0fca6ea1SDimitry Andric     DebugVariable DbgUserVariable =
4957*0fca6ea1SDimitry Andric         DebugVariable(DVR->getVariable(), DVR->getExpression(),
4958*0fca6ea1SDimitry Andric                       DVR->getDebugLoc()->getInlinedAt());
4959*0fca6ea1SDimitry Andric 
4960*0fca6ea1SDimitry Andric     // For any variable where there were multiple assignments in the same place,
4961*0fca6ea1SDimitry Andric     // ignore all but the last assignment.
4962*0fca6ea1SDimitry Andric     if (!FilterOutMap.empty()) {
4963*0fca6ea1SDimitry Andric       InstVarPair IVP = std::make_pair(DVR->getInstruction(), DbgUserVariable);
4964*0fca6ea1SDimitry Andric       auto It = FilterOutMap.find(IVP);
4965*0fca6ea1SDimitry Andric 
4966*0fca6ea1SDimitry Andric       // Filter out.
4967*0fca6ea1SDimitry Andric       if (It != FilterOutMap.end() && It->second != DVR)
4968*0fca6ea1SDimitry Andric         continue;
4969*0fca6ea1SDimitry Andric     }
4970*0fca6ea1SDimitry Andric 
4971*0fca6ea1SDimitry Andric     if (!SunkVariables.insert(DbgUserVariable).second)
4972*0fca6ea1SDimitry Andric       continue;
4973*0fca6ea1SDimitry Andric 
4974*0fca6ea1SDimitry Andric     if (DVR->isDbgAssign())
4975*0fca6ea1SDimitry Andric       continue;
4976*0fca6ea1SDimitry Andric 
4977*0fca6ea1SDimitry Andric     DVRClones.emplace_back(DVR->clone());
4978*0fca6ea1SDimitry Andric     LLVM_DEBUG(dbgs() << "CLONE: " << *DVRClones.back() << '\n');
4979*0fca6ea1SDimitry Andric   }
4980*0fca6ea1SDimitry Andric 
4981*0fca6ea1SDimitry Andric   // Perform salvaging without the clones, then sink the clones.
4982*0fca6ea1SDimitry Andric   if (DVRClones.empty())
4983*0fca6ea1SDimitry Andric     return;
4984*0fca6ea1SDimitry Andric 
4985*0fca6ea1SDimitry Andric   salvageDebugInfoForDbgValues(*I, {}, DbgVariableRecordsToSalvage);
4986*0fca6ea1SDimitry Andric 
4987*0fca6ea1SDimitry Andric   // The clones are in reverse order of original appearance. Assert that the
4988*0fca6ea1SDimitry Andric   // head bit is set on the iterator as we _should_ have received it via
4989*0fca6ea1SDimitry Andric   // getFirstInsertionPt. Inserting like this will reverse the clone order as
4990*0fca6ea1SDimitry Andric   // we'll repeatedly insert at the head, such as:
4991*0fca6ea1SDimitry Andric   //   DVR-3 (third insertion goes here)
4992*0fca6ea1SDimitry Andric   //   DVR-2 (second insertion goes here)
4993*0fca6ea1SDimitry Andric   //   DVR-1 (first insertion goes here)
4994*0fca6ea1SDimitry Andric   //   Any-Prior-DVRs
4995*0fca6ea1SDimitry Andric   //   InsertPtInst
4996*0fca6ea1SDimitry Andric   assert(InsertPos.getHeadBit());
4997*0fca6ea1SDimitry Andric   for (DbgVariableRecord *DVRClone : DVRClones) {
4998*0fca6ea1SDimitry Andric     InsertPos->getParent()->insertDbgRecordBefore(DVRClone, InsertPos);
4999*0fca6ea1SDimitry Andric     LLVM_DEBUG(dbgs() << "SINK: " << *DVRClone << '\n');
5000*0fca6ea1SDimitry Andric   }
50010b57cec5SDimitry Andric }
50020b57cec5SDimitry Andric 
5003e8d8bef9SDimitry Andric bool InstCombinerImpl::run() {
50040b57cec5SDimitry Andric   while (!Worklist.isEmpty()) {
50055ffd83dbSDimitry Andric     // Walk deferred instructions in reverse order, and push them to the
50065ffd83dbSDimitry Andric     // worklist, which means they'll end up popped from the worklist in-order.
50075ffd83dbSDimitry Andric     while (Instruction *I = Worklist.popDeferred()) {
50085ffd83dbSDimitry Andric       // Check to see if we can DCE the instruction. We do this already here to
50095ffd83dbSDimitry Andric       // reduce the number of uses and thus allow other folds to trigger.
50105ffd83dbSDimitry Andric       // Note that eraseInstFromFunction() may push additional instructions on
50115ffd83dbSDimitry Andric       // the deferred worklist, so this will DCE whole instruction chains.
50125ffd83dbSDimitry Andric       if (isInstructionTriviallyDead(I, &TLI)) {
50135ffd83dbSDimitry Andric         eraseInstFromFunction(*I);
50145ffd83dbSDimitry Andric         ++NumDeadInst;
50155ffd83dbSDimitry Andric         continue;
50165ffd83dbSDimitry Andric       }
50175ffd83dbSDimitry Andric 
50185ffd83dbSDimitry Andric       Worklist.push(I);
50195ffd83dbSDimitry Andric     }
50205ffd83dbSDimitry Andric 
50215ffd83dbSDimitry Andric     Instruction *I = Worklist.removeOne();
50220b57cec5SDimitry Andric     if (I == nullptr) continue;  // skip null values.
50230b57cec5SDimitry Andric 
50240b57cec5SDimitry Andric     // Check to see if we can DCE the instruction.
50250b57cec5SDimitry Andric     if (isInstructionTriviallyDead(I, &TLI)) {
50260b57cec5SDimitry Andric       eraseInstFromFunction(*I);
50270b57cec5SDimitry Andric       ++NumDeadInst;
50280b57cec5SDimitry Andric       continue;
50290b57cec5SDimitry Andric     }
50300b57cec5SDimitry Andric 
50310b57cec5SDimitry Andric     if (!DebugCounter::shouldExecute(VisitCounter))
50320b57cec5SDimitry Andric       continue;
50330b57cec5SDimitry Andric 
50345ffd83dbSDimitry Andric     // See if we can trivially sink this instruction to its user if we can
50355ffd83dbSDimitry Andric     // prove that the successor is not executed more frequently than our block.
5036349cc55cSDimitry Andric     // Return the UserBlock if successful.
5037349cc55cSDimitry Andric     auto getOptionalSinkBlockForInst =
5038bdd1243dSDimitry Andric         [this](Instruction *I) -> std::optional<BasicBlock *> {
5039349cc55cSDimitry Andric       if (!EnableCodeSinking)
5040bdd1243dSDimitry Andric         return std::nullopt;
50410b57cec5SDimitry Andric 
5042349cc55cSDimitry Andric       BasicBlock *BB = I->getParent();
5043349cc55cSDimitry Andric       BasicBlock *UserParent = nullptr;
504481ad6265SDimitry Andric       unsigned NumUsers = 0;
5045349cc55cSDimitry Andric 
5046*0fca6ea1SDimitry Andric       for (Use &U : I->uses()) {
5047*0fca6ea1SDimitry Andric         User *User = U.getUser();
5048*0fca6ea1SDimitry Andric         if (User->isDroppable())
504981ad6265SDimitry Andric           continue;
505081ad6265SDimitry Andric         if (NumUsers > MaxSinkNumUsers)
5051bdd1243dSDimitry Andric           return std::nullopt;
505281ad6265SDimitry Andric 
5053*0fca6ea1SDimitry Andric         Instruction *UserInst = cast<Instruction>(User);
5054349cc55cSDimitry Andric         // Special handling for Phi nodes - get the block the use occurs in.
5055*0fca6ea1SDimitry Andric         BasicBlock *UserBB = UserInst->getParent();
5056*0fca6ea1SDimitry Andric         if (PHINode *PN = dyn_cast<PHINode>(UserInst))
5057*0fca6ea1SDimitry Andric           UserBB = PN->getIncomingBlock(U);
5058349cc55cSDimitry Andric         // Bail out if we have uses in different blocks. We don't do any
5059*0fca6ea1SDimitry Andric         // sophisticated analysis (i.e finding NearestCommonDominator of these
5060*0fca6ea1SDimitry Andric         // use blocks).
5061*0fca6ea1SDimitry Andric         if (UserParent && UserParent != UserBB)
5062bdd1243dSDimitry Andric           return std::nullopt;
5063*0fca6ea1SDimitry Andric         UserParent = UserBB;
50640b57cec5SDimitry Andric 
506581ad6265SDimitry Andric         // Make sure these checks are done only once, naturally we do the checks
506681ad6265SDimitry Andric         // the first time we get the userparent, this will save compile time.
506781ad6265SDimitry Andric         if (NumUsers == 0) {
5068e8d8bef9SDimitry Andric           // Try sinking to another block. If that block is unreachable, then do
5069e8d8bef9SDimitry Andric           // not bother. SimplifyCFG should handle it.
5070349cc55cSDimitry Andric           if (UserParent == BB || !DT.isReachableFromEntry(UserParent))
5071bdd1243dSDimitry Andric             return std::nullopt;
5072349cc55cSDimitry Andric 
5073349cc55cSDimitry Andric           auto *Term = UserParent->getTerminator();
50745ffd83dbSDimitry Andric           // See if the user is one of our successors that has only one
50755ffd83dbSDimitry Andric           // predecessor, so that we don't have to split the critical edge.
50765ffd83dbSDimitry Andric           // Another option where we can sink is a block that ends with a
50775ffd83dbSDimitry Andric           // terminator that does not pass control to other block (such as
507804eeddc0SDimitry Andric           // return or unreachable or resume). In this case:
50795ffd83dbSDimitry Andric           //   - I dominates the User (by SSA form);
50805ffd83dbSDimitry Andric           //   - the User will be executed at most once.
50815ffd83dbSDimitry Andric           // So sinking I down to User is always profitable or neutral.
508281ad6265SDimitry Andric           if (UserParent->getUniquePredecessor() != BB && !succ_empty(Term))
5083bdd1243dSDimitry Andric             return std::nullopt;
508481ad6265SDimitry Andric 
508581ad6265SDimitry Andric           assert(DT.dominates(BB, UserParent) && "Dominance relation broken?");
508681ad6265SDimitry Andric         }
508781ad6265SDimitry Andric 
508881ad6265SDimitry Andric         NumUsers++;
508981ad6265SDimitry Andric       }
509081ad6265SDimitry Andric 
509181ad6265SDimitry Andric       // No user or only has droppable users.
509281ad6265SDimitry Andric       if (!UserParent)
5093bdd1243dSDimitry Andric         return std::nullopt;
509481ad6265SDimitry Andric 
509581ad6265SDimitry Andric       return UserParent;
5096349cc55cSDimitry Andric     };
5097349cc55cSDimitry Andric 
5098349cc55cSDimitry Andric     auto OptBB = getOptionalSinkBlockForInst(I);
5099349cc55cSDimitry Andric     if (OptBB) {
5100349cc55cSDimitry Andric       auto *UserParent = *OptBB;
51010b57cec5SDimitry Andric       // Okay, the CFG is simple enough, try to sink this instruction.
510206c3fb27SDimitry Andric       if (tryToSinkInstruction(I, UserParent)) {
51030b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "IC: Sink: " << *I << '\n');
51040b57cec5SDimitry Andric         MadeIRChange = true;
5105349cc55cSDimitry Andric         // We'll add uses of the sunk instruction below, but since
5106349cc55cSDimitry Andric         // sinking can expose opportunities for it's *operands* add
5107349cc55cSDimitry Andric         // them to the worklist
51080b57cec5SDimitry Andric         for (Use &U : I->operands())
51090b57cec5SDimitry Andric           if (Instruction *OpI = dyn_cast<Instruction>(U.get()))
51105ffd83dbSDimitry Andric             Worklist.push(OpI);
51110b57cec5SDimitry Andric       }
51120b57cec5SDimitry Andric     }
51130b57cec5SDimitry Andric 
51140b57cec5SDimitry Andric     // Now that we have an instruction, try combining it to simplify it.
51150b57cec5SDimitry Andric     Builder.SetInsertPoint(I);
5116e8d8bef9SDimitry Andric     Builder.CollectMetadataToCopy(
5117e8d8bef9SDimitry Andric         I, {LLVMContext::MD_dbg, LLVMContext::MD_annotation});
51180b57cec5SDimitry Andric 
51190b57cec5SDimitry Andric #ifndef NDEBUG
51200b57cec5SDimitry Andric     std::string OrigI;
51210b57cec5SDimitry Andric #endif
5122*0fca6ea1SDimitry Andric     LLVM_DEBUG(raw_string_ostream SS(OrigI); I->print(SS););
51230b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "IC: Visiting: " << OrigI << '\n');
51240b57cec5SDimitry Andric 
51250b57cec5SDimitry Andric     if (Instruction *Result = visit(*I)) {
51260b57cec5SDimitry Andric       ++NumCombined;
51270b57cec5SDimitry Andric       // Should we replace the old instruction with a new one?
51280b57cec5SDimitry Andric       if (Result != I) {
51290b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "IC: Old = " << *I << '\n'
51300b57cec5SDimitry Andric                           << "    New = " << *Result << '\n');
51310b57cec5SDimitry Andric 
5132e8d8bef9SDimitry Andric         Result->copyMetadata(*I,
5133e8d8bef9SDimitry Andric                              {LLVMContext::MD_dbg, LLVMContext::MD_annotation});
51340b57cec5SDimitry Andric         // Everything uses the new instruction now.
51350b57cec5SDimitry Andric         I->replaceAllUsesWith(Result);
51360b57cec5SDimitry Andric 
51370b57cec5SDimitry Andric         // Move the name to the new instruction first.
51380b57cec5SDimitry Andric         Result->takeName(I);
51390b57cec5SDimitry Andric 
51400b57cec5SDimitry Andric         // Insert the new instruction into the basic block...
51410b57cec5SDimitry Andric         BasicBlock *InstParent = I->getParent();
51420b57cec5SDimitry Andric         BasicBlock::iterator InsertPos = I->getIterator();
51430b57cec5SDimitry Andric 
5144e8d8bef9SDimitry Andric         // Are we replace a PHI with something that isn't a PHI, or vice versa?
5145e8d8bef9SDimitry Andric         if (isa<PHINode>(Result) != isa<PHINode>(I)) {
5146e8d8bef9SDimitry Andric           // We need to fix up the insertion point.
5147e8d8bef9SDimitry Andric           if (isa<PHINode>(I)) // PHI -> Non-PHI
51480b57cec5SDimitry Andric             InsertPos = InstParent->getFirstInsertionPt();
5149e8d8bef9SDimitry Andric           else // Non-PHI -> PHI
51507a6dacacSDimitry Andric             InsertPos = InstParent->getFirstNonPHIIt();
5151e8d8bef9SDimitry Andric         }
51520b57cec5SDimitry Andric 
5153bdd1243dSDimitry Andric         Result->insertInto(InstParent, InsertPos);
51540b57cec5SDimitry Andric 
5155480093f4SDimitry Andric         // Push the new instruction and any users onto the worklist.
51565ffd83dbSDimitry Andric         Worklist.pushUsersToWorkList(*Result);
51575ffd83dbSDimitry Andric         Worklist.push(Result);
5158480093f4SDimitry Andric 
51590b57cec5SDimitry Andric         eraseInstFromFunction(*I);
51600b57cec5SDimitry Andric       } else {
51610b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "IC: Mod = " << OrigI << '\n'
51620b57cec5SDimitry Andric                           << "    New = " << *I << '\n');
51630b57cec5SDimitry Andric 
51640b57cec5SDimitry Andric         // If the instruction was modified, it's possible that it is now dead.
51650b57cec5SDimitry Andric         // if so, remove it.
51660b57cec5SDimitry Andric         if (isInstructionTriviallyDead(I, &TLI)) {
51670b57cec5SDimitry Andric           eraseInstFromFunction(*I);
51680b57cec5SDimitry Andric         } else {
51695ffd83dbSDimitry Andric           Worklist.pushUsersToWorkList(*I);
51705ffd83dbSDimitry Andric           Worklist.push(I);
51710b57cec5SDimitry Andric         }
51720b57cec5SDimitry Andric       }
51730b57cec5SDimitry Andric       MadeIRChange = true;
51740b57cec5SDimitry Andric     }
51750b57cec5SDimitry Andric   }
51760b57cec5SDimitry Andric 
51775ffd83dbSDimitry Andric   Worklist.zap();
51780b57cec5SDimitry Andric   return MadeIRChange;
51790b57cec5SDimitry Andric }
51800b57cec5SDimitry Andric 
5181e8d8bef9SDimitry Andric // Track the scopes used by !alias.scope and !noalias. In a function, a
5182e8d8bef9SDimitry Andric // @llvm.experimental.noalias.scope.decl is only useful if that scope is used
5183e8d8bef9SDimitry Andric // by both sets. If not, the declaration of the scope can be safely omitted.
5184e8d8bef9SDimitry Andric // The MDNode of the scope can be omitted as well for the instructions that are
5185e8d8bef9SDimitry Andric // part of this function. We do not do that at this point, as this might become
5186e8d8bef9SDimitry Andric // too time consuming to do.
5187e8d8bef9SDimitry Andric class AliasScopeTracker {
5188e8d8bef9SDimitry Andric   SmallPtrSet<const MDNode *, 8> UsedAliasScopesAndLists;
5189e8d8bef9SDimitry Andric   SmallPtrSet<const MDNode *, 8> UsedNoAliasScopesAndLists;
5190e8d8bef9SDimitry Andric 
5191e8d8bef9SDimitry Andric public:
5192e8d8bef9SDimitry Andric   void analyse(Instruction *I) {
5193e8d8bef9SDimitry Andric     // This seems to be faster than checking 'mayReadOrWriteMemory()'.
5194e8d8bef9SDimitry Andric     if (!I->hasMetadataOtherThanDebugLoc())
5195e8d8bef9SDimitry Andric       return;
5196e8d8bef9SDimitry Andric 
5197e8d8bef9SDimitry Andric     auto Track = [](Metadata *ScopeList, auto &Container) {
5198e8d8bef9SDimitry Andric       const auto *MDScopeList = dyn_cast_or_null<MDNode>(ScopeList);
5199e8d8bef9SDimitry Andric       if (!MDScopeList || !Container.insert(MDScopeList).second)
5200e8d8bef9SDimitry Andric         return;
5201bdd1243dSDimitry Andric       for (const auto &MDOperand : MDScopeList->operands())
5202e8d8bef9SDimitry Andric         if (auto *MDScope = dyn_cast<MDNode>(MDOperand))
5203e8d8bef9SDimitry Andric           Container.insert(MDScope);
5204e8d8bef9SDimitry Andric     };
5205e8d8bef9SDimitry Andric 
5206e8d8bef9SDimitry Andric     Track(I->getMetadata(LLVMContext::MD_alias_scope), UsedAliasScopesAndLists);
5207e8d8bef9SDimitry Andric     Track(I->getMetadata(LLVMContext::MD_noalias), UsedNoAliasScopesAndLists);
5208e8d8bef9SDimitry Andric   }
5209e8d8bef9SDimitry Andric 
5210e8d8bef9SDimitry Andric   bool isNoAliasScopeDeclDead(Instruction *Inst) {
5211e8d8bef9SDimitry Andric     NoAliasScopeDeclInst *Decl = dyn_cast<NoAliasScopeDeclInst>(Inst);
5212e8d8bef9SDimitry Andric     if (!Decl)
5213e8d8bef9SDimitry Andric       return false;
5214e8d8bef9SDimitry Andric 
5215e8d8bef9SDimitry Andric     assert(Decl->use_empty() &&
5216e8d8bef9SDimitry Andric            "llvm.experimental.noalias.scope.decl in use ?");
5217e8d8bef9SDimitry Andric     const MDNode *MDSL = Decl->getScopeList();
5218e8d8bef9SDimitry Andric     assert(MDSL->getNumOperands() == 1 &&
5219e8d8bef9SDimitry Andric            "llvm.experimental.noalias.scope should refer to a single scope");
5220e8d8bef9SDimitry Andric     auto &MDOperand = MDSL->getOperand(0);
5221e8d8bef9SDimitry Andric     if (auto *MD = dyn_cast<MDNode>(MDOperand))
5222e8d8bef9SDimitry Andric       return !UsedAliasScopesAndLists.contains(MD) ||
5223e8d8bef9SDimitry Andric              !UsedNoAliasScopesAndLists.contains(MD);
5224e8d8bef9SDimitry Andric 
5225e8d8bef9SDimitry Andric     // Not an MDNode ? throw away.
5226e8d8bef9SDimitry Andric     return true;
5227e8d8bef9SDimitry Andric   }
5228e8d8bef9SDimitry Andric };
5229e8d8bef9SDimitry Andric 
52305f757f3fSDimitry Andric /// Populate the IC worklist from a function, by walking it in reverse
52315f757f3fSDimitry Andric /// post-order and adding all reachable code to the worklist.
52320b57cec5SDimitry Andric ///
52330b57cec5SDimitry Andric /// This has a couple of tricks to make the code faster and more powerful.  In
52340b57cec5SDimitry Andric /// particular, we constant fold and DCE instructions as we go, to avoid adding
52350b57cec5SDimitry Andric /// them to the worklist (this significantly speeds up instcombine on code where
52360b57cec5SDimitry Andric /// many instructions are dead or constant).  Additionally, if we find a branch
52370b57cec5SDimitry Andric /// whose condition is a known constant, we only visit the reachable successors.
52385f757f3fSDimitry Andric bool InstCombinerImpl::prepareWorklist(
52395f757f3fSDimitry Andric     Function &F, ReversePostOrderTraversal<BasicBlock *> &RPOT) {
52400b57cec5SDimitry Andric   bool MadeIRChange = false;
52415f757f3fSDimitry Andric   SmallPtrSet<BasicBlock *, 32> LiveBlocks;
5242349cc55cSDimitry Andric   SmallVector<Instruction *, 128> InstrsForInstructionWorklist;
52430b57cec5SDimitry Andric   DenseMap<Constant *, Constant *> FoldedConstants;
5244e8d8bef9SDimitry Andric   AliasScopeTracker SeenAliasScopes;
52450b57cec5SDimitry Andric 
52465f757f3fSDimitry Andric   auto HandleOnlyLiveSuccessor = [&](BasicBlock *BB, BasicBlock *LiveSucc) {
52475f757f3fSDimitry Andric     for (BasicBlock *Succ : successors(BB))
52485f757f3fSDimitry Andric       if (Succ != LiveSucc && DeadEdges.insert({BB, Succ}).second)
52495f757f3fSDimitry Andric         for (PHINode &PN : Succ->phis())
52505f757f3fSDimitry Andric           for (Use &U : PN.incoming_values())
52515f757f3fSDimitry Andric             if (PN.getIncomingBlock(U) == BB && !isa<PoisonValue>(U)) {
52525f757f3fSDimitry Andric               U.set(PoisonValue::get(PN.getType()));
52535f757f3fSDimitry Andric               MadeIRChange = true;
52545f757f3fSDimitry Andric             }
52555f757f3fSDimitry Andric   };
52560b57cec5SDimitry Andric 
52575f757f3fSDimitry Andric   for (BasicBlock *BB : RPOT) {
52585f757f3fSDimitry Andric     if (!BB->isEntryBlock() && all_of(predecessors(BB), [&](BasicBlock *Pred) {
52595f757f3fSDimitry Andric           return DeadEdges.contains({Pred, BB}) || DT.dominates(BB, Pred);
52605f757f3fSDimitry Andric         })) {
52615f757f3fSDimitry Andric       HandleOnlyLiveSuccessor(BB, nullptr);
52620b57cec5SDimitry Andric       continue;
52635f757f3fSDimitry Andric     }
52645f757f3fSDimitry Andric     LiveBlocks.insert(BB);
52650b57cec5SDimitry Andric 
5266349cc55cSDimitry Andric     for (Instruction &Inst : llvm::make_early_inc_range(*BB)) {
52670b57cec5SDimitry Andric       // ConstantProp instruction if trivially constant.
5268349cc55cSDimitry Andric       if (!Inst.use_empty() &&
5269349cc55cSDimitry Andric           (Inst.getNumOperands() == 0 || isa<Constant>(Inst.getOperand(0))))
52705f757f3fSDimitry Andric         if (Constant *C = ConstantFoldInstruction(&Inst, DL, &TLI)) {
5271349cc55cSDimitry Andric           LLVM_DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: " << Inst
52720b57cec5SDimitry Andric                             << '\n');
5273349cc55cSDimitry Andric           Inst.replaceAllUsesWith(C);
52740b57cec5SDimitry Andric           ++NumConstProp;
52755f757f3fSDimitry Andric           if (isInstructionTriviallyDead(&Inst, &TLI))
5276349cc55cSDimitry Andric             Inst.eraseFromParent();
52770b57cec5SDimitry Andric           MadeIRChange = true;
52780b57cec5SDimitry Andric           continue;
52790b57cec5SDimitry Andric         }
52800b57cec5SDimitry Andric 
52810b57cec5SDimitry Andric       // See if we can constant fold its operands.
5282349cc55cSDimitry Andric       for (Use &U : Inst.operands()) {
52830b57cec5SDimitry Andric         if (!isa<ConstantVector>(U) && !isa<ConstantExpr>(U))
52840b57cec5SDimitry Andric           continue;
52850b57cec5SDimitry Andric 
52860b57cec5SDimitry Andric         auto *C = cast<Constant>(U);
52870b57cec5SDimitry Andric         Constant *&FoldRes = FoldedConstants[C];
52880b57cec5SDimitry Andric         if (!FoldRes)
52895f757f3fSDimitry Andric           FoldRes = ConstantFoldConstant(C, DL, &TLI);
52900b57cec5SDimitry Andric 
52910b57cec5SDimitry Andric         if (FoldRes != C) {
5292349cc55cSDimitry Andric           LLVM_DEBUG(dbgs() << "IC: ConstFold operand of: " << Inst
52930b57cec5SDimitry Andric                             << "\n    Old = " << *C
52940b57cec5SDimitry Andric                             << "\n    New = " << *FoldRes << '\n');
52950b57cec5SDimitry Andric           U = FoldRes;
52960b57cec5SDimitry Andric           MadeIRChange = true;
52970b57cec5SDimitry Andric         }
52980b57cec5SDimitry Andric       }
52990b57cec5SDimitry Andric 
5300d409305fSDimitry Andric       // Skip processing debug and pseudo intrinsics in InstCombine. Processing
5301d409305fSDimitry Andric       // these call instructions consumes non-trivial amount of time and
5302d409305fSDimitry Andric       // provides no value for the optimization.
5303349cc55cSDimitry Andric       if (!Inst.isDebugOrPseudoInst()) {
5304349cc55cSDimitry Andric         InstrsForInstructionWorklist.push_back(&Inst);
5305349cc55cSDimitry Andric         SeenAliasScopes.analyse(&Inst);
5306e8d8bef9SDimitry Andric       }
53070b57cec5SDimitry Andric     }
53080b57cec5SDimitry Andric 
53095f757f3fSDimitry Andric     // If this is a branch or switch on a constant, mark only the single
53105f757f3fSDimitry Andric     // live successor. Otherwise assume all successors are live.
53110b57cec5SDimitry Andric     Instruction *TI = BB->getTerminator();
531206c3fb27SDimitry Andric     if (BranchInst *BI = dyn_cast<BranchInst>(TI); BI && BI->isConditional()) {
53135f757f3fSDimitry Andric       if (isa<UndefValue>(BI->getCondition())) {
531406c3fb27SDimitry Andric         // Branch on undef is UB.
53155f757f3fSDimitry Andric         HandleOnlyLiveSuccessor(BB, nullptr);
531606c3fb27SDimitry Andric         continue;
53175f757f3fSDimitry Andric       }
531806c3fb27SDimitry Andric       if (auto *Cond = dyn_cast<ConstantInt>(BI->getCondition())) {
531906c3fb27SDimitry Andric         bool CondVal = Cond->getZExtValue();
53205f757f3fSDimitry Andric         HandleOnlyLiveSuccessor(BB, BI->getSuccessor(!CondVal));
53210b57cec5SDimitry Andric         continue;
53220b57cec5SDimitry Andric       }
53230b57cec5SDimitry Andric     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
53245f757f3fSDimitry Andric       if (isa<UndefValue>(SI->getCondition())) {
532506c3fb27SDimitry Andric         // Switch on undef is UB.
53265f757f3fSDimitry Andric         HandleOnlyLiveSuccessor(BB, nullptr);
532706c3fb27SDimitry Andric         continue;
53285f757f3fSDimitry Andric       }
532906c3fb27SDimitry Andric       if (auto *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
53305f757f3fSDimitry Andric         HandleOnlyLiveSuccessor(BB,
53315f757f3fSDimitry Andric                                 SI->findCaseValue(Cond)->getCaseSuccessor());
53320b57cec5SDimitry Andric         continue;
53330b57cec5SDimitry Andric       }
53340b57cec5SDimitry Andric     }
53355f757f3fSDimitry Andric   }
53360b57cec5SDimitry Andric 
53375ffd83dbSDimitry Andric   // Remove instructions inside unreachable blocks. This prevents the
53385ffd83dbSDimitry Andric   // instcombine code from having to deal with some bad special cases, and
53395ffd83dbSDimitry Andric   // reduces use counts of instructions.
53400b57cec5SDimitry Andric   for (BasicBlock &BB : F) {
53415f757f3fSDimitry Andric     if (LiveBlocks.count(&BB))
53420b57cec5SDimitry Andric       continue;
53430b57cec5SDimitry Andric 
5344e8d8bef9SDimitry Andric     unsigned NumDeadInstInBB;
5345e8d8bef9SDimitry Andric     unsigned NumDeadDbgInstInBB;
5346e8d8bef9SDimitry Andric     std::tie(NumDeadInstInBB, NumDeadDbgInstInBB) =
5347e8d8bef9SDimitry Andric         removeAllNonTerminatorAndEHPadInstructions(&BB);
5348e8d8bef9SDimitry Andric 
5349e8d8bef9SDimitry Andric     MadeIRChange |= NumDeadInstInBB + NumDeadDbgInstInBB > 0;
53500b57cec5SDimitry Andric     NumDeadInst += NumDeadInstInBB;
53510b57cec5SDimitry Andric   }
53520b57cec5SDimitry Andric 
53535ffd83dbSDimitry Andric   // Once we've found all of the instructions to add to instcombine's worklist,
53545ffd83dbSDimitry Andric   // add them in reverse order.  This way instcombine will visit from the top
53555ffd83dbSDimitry Andric   // of the function down.  This jives well with the way that it adds all uses
53565ffd83dbSDimitry Andric   // of instructions to the worklist after doing a transformation, thus avoiding
53575ffd83dbSDimitry Andric   // some N^2 behavior in pathological cases.
53585f757f3fSDimitry Andric   Worklist.reserve(InstrsForInstructionWorklist.size());
5359349cc55cSDimitry Andric   for (Instruction *Inst : reverse(InstrsForInstructionWorklist)) {
53605ffd83dbSDimitry Andric     // DCE instruction if trivially dead. As we iterate in reverse program
53615ffd83dbSDimitry Andric     // order here, we will clean up whole chains of dead instructions.
53625f757f3fSDimitry Andric     if (isInstructionTriviallyDead(Inst, &TLI) ||
5363e8d8bef9SDimitry Andric         SeenAliasScopes.isNoAliasScopeDeclDead(Inst)) {
53645ffd83dbSDimitry Andric       ++NumDeadInst;
53655ffd83dbSDimitry Andric       LLVM_DEBUG(dbgs() << "IC: DCE: " << *Inst << '\n');
53665ffd83dbSDimitry Andric       salvageDebugInfo(*Inst);
53675ffd83dbSDimitry Andric       Inst->eraseFromParent();
53685ffd83dbSDimitry Andric       MadeIRChange = true;
53695ffd83dbSDimitry Andric       continue;
53705ffd83dbSDimitry Andric     }
53715ffd83dbSDimitry Andric 
53725f757f3fSDimitry Andric     Worklist.push(Inst);
53735ffd83dbSDimitry Andric   }
53745ffd83dbSDimitry Andric 
53750b57cec5SDimitry Andric   return MadeIRChange;
53760b57cec5SDimitry Andric }
53770b57cec5SDimitry Andric 
53780b57cec5SDimitry Andric static bool combineInstructionsOverFunction(
5379349cc55cSDimitry Andric     Function &F, InstructionWorklist &Worklist, AliasAnalysis *AA,
5380e8d8bef9SDimitry Andric     AssumptionCache &AC, TargetLibraryInfo &TLI, TargetTransformInfo &TTI,
5381e8d8bef9SDimitry Andric     DominatorTree &DT, OptimizationRemarkEmitter &ORE, BlockFrequencyInfo *BFI,
5382*0fca6ea1SDimitry Andric     BranchProbabilityInfo *BPI, ProfileSummaryInfo *PSI, LoopInfo *LI,
5383*0fca6ea1SDimitry Andric     const InstCombineOptions &Opts) {
5384*0fca6ea1SDimitry Andric   auto &DL = F.getDataLayout();
53850b57cec5SDimitry Andric 
53860b57cec5SDimitry Andric   /// Builder - This is an IRBuilder that automatically inserts new
53870b57cec5SDimitry Andric   /// instructions into the worklist when they are created.
53880b57cec5SDimitry Andric   IRBuilder<TargetFolder, IRBuilderCallbackInserter> Builder(
53890b57cec5SDimitry Andric       F.getContext(), TargetFolder(DL),
53900b57cec5SDimitry Andric       IRBuilderCallbackInserter([&Worklist, &AC](Instruction *I) {
53915ffd83dbSDimitry Andric         Worklist.add(I);
5392fe6060f1SDimitry Andric         if (auto *Assume = dyn_cast<AssumeInst>(I))
5393fe6060f1SDimitry Andric           AC.registerAssumption(Assume);
53940b57cec5SDimitry Andric       }));
53950b57cec5SDimitry Andric 
53965f757f3fSDimitry Andric   ReversePostOrderTraversal<BasicBlock *> RPOT(&F.front());
53975f757f3fSDimitry Andric 
53980b57cec5SDimitry Andric   // Lower dbg.declare intrinsics otherwise their value may be clobbered
53990b57cec5SDimitry Andric   // by instcombiner.
54000b57cec5SDimitry Andric   bool MadeIRChange = false;
54010b57cec5SDimitry Andric   if (ShouldLowerDbgDeclare)
54020b57cec5SDimitry Andric     MadeIRChange = LowerDbgDeclare(F);
54030b57cec5SDimitry Andric 
54040b57cec5SDimitry Andric   // Iterate while there is work to do.
5405480093f4SDimitry Andric   unsigned Iteration = 0;
54060b57cec5SDimitry Andric   while (true) {
54070b57cec5SDimitry Andric     ++Iteration;
5408480093f4SDimitry Andric 
54095f757f3fSDimitry Andric     if (Iteration > Opts.MaxIterations && !Opts.VerifyFixpoint) {
54105f757f3fSDimitry Andric       LLVM_DEBUG(dbgs() << "\n\n[IC] Iteration limit #" << Opts.MaxIterations
5411480093f4SDimitry Andric                         << " on " << F.getName()
54125f757f3fSDimitry Andric                         << " reached; stopping without verifying fixpoint\n");
5413480093f4SDimitry Andric       break;
5414480093f4SDimitry Andric     }
5415480093f4SDimitry Andric 
54165f757f3fSDimitry Andric     ++NumWorklistIterations;
54170b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
54180b57cec5SDimitry Andric                       << F.getName() << "\n");
54190b57cec5SDimitry Andric 
5420e8d8bef9SDimitry Andric     InstCombinerImpl IC(Worklist, Builder, F.hasMinSize(), AA, AC, TLI, TTI, DT,
5421*0fca6ea1SDimitry Andric                         ORE, BFI, BPI, PSI, DL, LI);
54220b57cec5SDimitry Andric     IC.MaxArraySizeForCombine = MaxArraySize;
54235f757f3fSDimitry Andric     bool MadeChangeInThisIteration = IC.prepareWorklist(F, RPOT);
54245f757f3fSDimitry Andric     MadeChangeInThisIteration |= IC.run();
54255f757f3fSDimitry Andric     if (!MadeChangeInThisIteration)
54260b57cec5SDimitry Andric       break;
5427480093f4SDimitry Andric 
5428480093f4SDimitry Andric     MadeIRChange = true;
54295f757f3fSDimitry Andric     if (Iteration > Opts.MaxIterations) {
54305f757f3fSDimitry Andric       report_fatal_error(
54315f757f3fSDimitry Andric           "Instruction Combining did not reach a fixpoint after " +
5432*0fca6ea1SDimitry Andric               Twine(Opts.MaxIterations) + " iterations",
5433*0fca6ea1SDimitry Andric           /*GenCrashDiag=*/false);
54345f757f3fSDimitry Andric     }
54350b57cec5SDimitry Andric   }
54360b57cec5SDimitry Andric 
543706c3fb27SDimitry Andric   if (Iteration == 1)
543806c3fb27SDimitry Andric     ++NumOneIteration;
543906c3fb27SDimitry Andric   else if (Iteration == 2)
544006c3fb27SDimitry Andric     ++NumTwoIterations;
544106c3fb27SDimitry Andric   else if (Iteration == 3)
544206c3fb27SDimitry Andric     ++NumThreeIterations;
544306c3fb27SDimitry Andric   else
544406c3fb27SDimitry Andric     ++NumFourOrMoreIterations;
544506c3fb27SDimitry Andric 
5446480093f4SDimitry Andric   return MadeIRChange;
54470b57cec5SDimitry Andric }
54480b57cec5SDimitry Andric 
544906c3fb27SDimitry Andric InstCombinePass::InstCombinePass(InstCombineOptions Opts) : Options(Opts) {}
5450480093f4SDimitry Andric 
545106c3fb27SDimitry Andric void InstCombinePass::printPipeline(
545206c3fb27SDimitry Andric     raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
545306c3fb27SDimitry Andric   static_cast<PassInfoMixin<InstCombinePass> *>(this)->printPipeline(
545406c3fb27SDimitry Andric       OS, MapClassName2PassName);
545506c3fb27SDimitry Andric   OS << '<';
545606c3fb27SDimitry Andric   OS << "max-iterations=" << Options.MaxIterations << ";";
54575f757f3fSDimitry Andric   OS << (Options.UseLoopInfo ? "" : "no-") << "use-loop-info;";
54585f757f3fSDimitry Andric   OS << (Options.VerifyFixpoint ? "" : "no-") << "verify-fixpoint";
545906c3fb27SDimitry Andric   OS << '>';
546006c3fb27SDimitry Andric }
5461480093f4SDimitry Andric 
54620b57cec5SDimitry Andric PreservedAnalyses InstCombinePass::run(Function &F,
54630b57cec5SDimitry Andric                                        FunctionAnalysisManager &AM) {
54640b57cec5SDimitry Andric   auto &AC = AM.getResult<AssumptionAnalysis>(F);
54650b57cec5SDimitry Andric   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
54660b57cec5SDimitry Andric   auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
54670b57cec5SDimitry Andric   auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
5468e8d8bef9SDimitry Andric   auto &TTI = AM.getResult<TargetIRAnalysis>(F);
54690b57cec5SDimitry Andric 
547006c3fb27SDimitry Andric   // TODO: Only use LoopInfo when the option is set. This requires that the
547106c3fb27SDimitry Andric   //       callers in the pass pipeline explicitly set the option.
54720b57cec5SDimitry Andric   auto *LI = AM.getCachedResult<LoopAnalysis>(F);
547306c3fb27SDimitry Andric   if (!LI && Options.UseLoopInfo)
547406c3fb27SDimitry Andric     LI = &AM.getResult<LoopAnalysis>(F);
54750b57cec5SDimitry Andric 
54760b57cec5SDimitry Andric   auto *AA = &AM.getResult<AAManager>(F);
54775ffd83dbSDimitry Andric   auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
54780b57cec5SDimitry Andric   ProfileSummaryInfo *PSI =
54795ffd83dbSDimitry Andric       MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
54800b57cec5SDimitry Andric   auto *BFI = (PSI && PSI->hasProfileSummary()) ?
54810b57cec5SDimitry Andric       &AM.getResult<BlockFrequencyAnalysis>(F) : nullptr;
5482*0fca6ea1SDimitry Andric   auto *BPI = AM.getCachedResult<BranchProbabilityAnalysis>(F);
54830b57cec5SDimitry Andric 
5484e8d8bef9SDimitry Andric   if (!combineInstructionsOverFunction(F, Worklist, AA, AC, TLI, TTI, DT, ORE,
5485*0fca6ea1SDimitry Andric                                        BFI, BPI, PSI, LI, Options))
54860b57cec5SDimitry Andric     // No changes, all analyses are preserved.
54870b57cec5SDimitry Andric     return PreservedAnalyses::all();
54880b57cec5SDimitry Andric 
54890b57cec5SDimitry Andric   // Mark all the analyses that instcombine updates as preserved.
54900b57cec5SDimitry Andric   PreservedAnalyses PA;
54910b57cec5SDimitry Andric   PA.preserveSet<CFGAnalyses>();
54920b57cec5SDimitry Andric   return PA;
54930b57cec5SDimitry Andric }
54940b57cec5SDimitry Andric 
54950b57cec5SDimitry Andric void InstructionCombiningPass::getAnalysisUsage(AnalysisUsage &AU) const {
54960b57cec5SDimitry Andric   AU.setPreservesCFG();
54970b57cec5SDimitry Andric   AU.addRequired<AAResultsWrapperPass>();
54980b57cec5SDimitry Andric   AU.addRequired<AssumptionCacheTracker>();
54990b57cec5SDimitry Andric   AU.addRequired<TargetLibraryInfoWrapperPass>();
5500e8d8bef9SDimitry Andric   AU.addRequired<TargetTransformInfoWrapperPass>();
55010b57cec5SDimitry Andric   AU.addRequired<DominatorTreeWrapperPass>();
55020b57cec5SDimitry Andric   AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
55030b57cec5SDimitry Andric   AU.addPreserved<DominatorTreeWrapperPass>();
55040b57cec5SDimitry Andric   AU.addPreserved<AAResultsWrapperPass>();
55050b57cec5SDimitry Andric   AU.addPreserved<BasicAAWrapperPass>();
55060b57cec5SDimitry Andric   AU.addPreserved<GlobalsAAWrapperPass>();
55070b57cec5SDimitry Andric   AU.addRequired<ProfileSummaryInfoWrapperPass>();
55080b57cec5SDimitry Andric   LazyBlockFrequencyInfoPass::getLazyBFIAnalysisUsage(AU);
55090b57cec5SDimitry Andric }
55100b57cec5SDimitry Andric 
55110b57cec5SDimitry Andric bool InstructionCombiningPass::runOnFunction(Function &F) {
55120b57cec5SDimitry Andric   if (skipFunction(F))
55130b57cec5SDimitry Andric     return false;
55140b57cec5SDimitry Andric 
55150b57cec5SDimitry Andric   // Required analyses.
55160b57cec5SDimitry Andric   auto AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
55170b57cec5SDimitry Andric   auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
55188bcb0991SDimitry Andric   auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
5519e8d8bef9SDimitry Andric   auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
55200b57cec5SDimitry Andric   auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
55210b57cec5SDimitry Andric   auto &ORE = getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
55220b57cec5SDimitry Andric 
55230b57cec5SDimitry Andric   // Optional analyses.
55240b57cec5SDimitry Andric   auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
55250b57cec5SDimitry Andric   auto *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
55260b57cec5SDimitry Andric   ProfileSummaryInfo *PSI =
55270b57cec5SDimitry Andric       &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
55280b57cec5SDimitry Andric   BlockFrequencyInfo *BFI =
55290b57cec5SDimitry Andric       (PSI && PSI->hasProfileSummary()) ?
55300b57cec5SDimitry Andric       &getAnalysis<LazyBlockFrequencyInfoPass>().getBFI() :
55310b57cec5SDimitry Andric       nullptr;
5532*0fca6ea1SDimitry Andric   BranchProbabilityInfo *BPI = nullptr;
5533*0fca6ea1SDimitry Andric   if (auto *WrapperPass =
5534*0fca6ea1SDimitry Andric           getAnalysisIfAvailable<BranchProbabilityInfoWrapperPass>())
5535*0fca6ea1SDimitry Andric     BPI = &WrapperPass->getBPI();
55360b57cec5SDimitry Andric 
5537e8d8bef9SDimitry Andric   return combineInstructionsOverFunction(F, Worklist, AA, AC, TLI, TTI, DT, ORE,
5538*0fca6ea1SDimitry Andric                                          BFI, BPI, PSI, LI,
5539*0fca6ea1SDimitry Andric                                          InstCombineOptions());
55400b57cec5SDimitry Andric }
55410b57cec5SDimitry Andric 
55420b57cec5SDimitry Andric char InstructionCombiningPass::ID = 0;
55430b57cec5SDimitry Andric 
554406c3fb27SDimitry Andric InstructionCombiningPass::InstructionCombiningPass() : FunctionPass(ID) {
5545480093f4SDimitry Andric   initializeInstructionCombiningPassPass(*PassRegistry::getPassRegistry());
5546480093f4SDimitry Andric }
5547480093f4SDimitry Andric 
55480b57cec5SDimitry Andric INITIALIZE_PASS_BEGIN(InstructionCombiningPass, "instcombine",
55490b57cec5SDimitry Andric                       "Combine redundant instructions", false, false)
55500b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
55510b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
5552e8d8bef9SDimitry Andric INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
55530b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
55540b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
55550b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
55560b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
55570b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(LazyBlockFrequencyInfoPass)
55580b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
55590b57cec5SDimitry Andric INITIALIZE_PASS_END(InstructionCombiningPass, "instcombine",
55600b57cec5SDimitry Andric                     "Combine redundant instructions", false, false)
55610b57cec5SDimitry Andric 
55620b57cec5SDimitry Andric // Initialization Routines
55630b57cec5SDimitry Andric void llvm::initializeInstCombine(PassRegistry &Registry) {
55640b57cec5SDimitry Andric   initializeInstructionCombiningPassPass(Registry);
55650b57cec5SDimitry Andric }
55660b57cec5SDimitry Andric 
55675ffd83dbSDimitry Andric FunctionPass *llvm::createInstructionCombiningPass() {
55685ffd83dbSDimitry Andric   return new InstructionCombiningPass();
55690b57cec5SDimitry Andric }
5570