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