LLVM 19.0.0git
InstructionCombining.cpp
Go to the documentation of this file.
1//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// InstructionCombining - Combine instructions to form fewer, simple
10// instructions. This pass does not modify the CFG. This pass is where
11// algebraic simplification happens.
12//
13// This pass combines things like:
14// %Y = add i32 %X, 1
15// %Z = add i32 %Y, 1
16// into:
17// %Z = add i32 %X, 2
18//
19// This is a simple worklist driven algorithm.
20//
21// This pass guarantees that the following canonicalizations are performed on
22// the program:
23// 1. If a binary operator has a constant operand, it is moved to the RHS
24// 2. Bitwise operators with constant operands are always grouped so that
25// shifts are performed first, then or's, then and's, then xor's.
26// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
27// 4. All cmp instructions on boolean values are replaced with logical ops
28// 5. add X, X is represented as (X*2) => (X << 1)
29// 6. Multiplies with a power-of-two constant argument are transformed into
30// shifts.
31// ... etc.
32//
33//===----------------------------------------------------------------------===//
34
35#include "InstCombineInternal.h"
36#include "llvm/ADT/APInt.h"
37#include "llvm/ADT/ArrayRef.h"
38#include "llvm/ADT/DenseMap.h"
41#include "llvm/ADT/Statistic.h"
46#include "llvm/Analysis/CFG.h"
61#include "llvm/IR/BasicBlock.h"
62#include "llvm/IR/CFG.h"
63#include "llvm/IR/Constant.h"
64#include "llvm/IR/Constants.h"
65#include "llvm/IR/DIBuilder.h"
66#include "llvm/IR/DataLayout.h"
67#include "llvm/IR/DebugInfo.h"
69#include "llvm/IR/Dominators.h"
71#include "llvm/IR/Function.h"
73#include "llvm/IR/IRBuilder.h"
74#include "llvm/IR/InstrTypes.h"
75#include "llvm/IR/Instruction.h"
78#include "llvm/IR/Intrinsics.h"
79#include "llvm/IR/Metadata.h"
80#include "llvm/IR/Operator.h"
81#include "llvm/IR/PassManager.h"
83#include "llvm/IR/Type.h"
84#include "llvm/IR/Use.h"
85#include "llvm/IR/User.h"
86#include "llvm/IR/Value.h"
87#include "llvm/IR/ValueHandle.h"
92#include "llvm/Support/Debug.h"
100#include <algorithm>
101#include <cassert>
102#include <cstdint>
103#include <memory>
104#include <optional>
105#include <string>
106#include <utility>
107
108#define DEBUG_TYPE "instcombine"
110#include <optional>
111
112using namespace llvm;
113using namespace llvm::PatternMatch;
114
115STATISTIC(NumWorklistIterations,
116 "Number of instruction combining iterations performed");
117STATISTIC(NumOneIteration, "Number of functions with one iteration");
118STATISTIC(NumTwoIterations, "Number of functions with two iterations");
119STATISTIC(NumThreeIterations, "Number of functions with three iterations");
120STATISTIC(NumFourOrMoreIterations,
121 "Number of functions with four or more iterations");
122
123STATISTIC(NumCombined , "Number of insts combined");
124STATISTIC(NumConstProp, "Number of constant folds");
125STATISTIC(NumDeadInst , "Number of dead inst eliminated");
126STATISTIC(NumSunkInst , "Number of instructions sunk");
127STATISTIC(NumExpand, "Number of expansions");
128STATISTIC(NumFactor , "Number of factorizations");
129STATISTIC(NumReassoc , "Number of reassociations");
130DEBUG_COUNTER(VisitCounter, "instcombine-visit",
131 "Controls which instructions are visited");
132
133static cl::opt<bool>
134EnableCodeSinking("instcombine-code-sinking", cl::desc("Enable code sinking"),
135 cl::init(true));
136
138 "instcombine-max-sink-users", cl::init(32),
139 cl::desc("Maximum number of undroppable users for instruction sinking"));
140
142MaxArraySize("instcombine-maxarray-size", cl::init(1024),
143 cl::desc("Maximum array size considered when doing a combine"));
144
145// FIXME: Remove this flag when it is no longer necessary to convert
146// llvm.dbg.declare to avoid inaccurate debug info. Setting this to false
147// increases variable availability at the cost of accuracy. Variables that
148// cannot be promoted by mem2reg or SROA will be described as living in memory
149// for their entire lifetime. However, passes like DSE and instcombine can
150// delete stores to the alloca, leading to misleading and inaccurate debug
151// information. This flag can be removed when those passes are fixed.
152static cl::opt<unsigned> ShouldLowerDbgDeclare("instcombine-lower-dbg-declare",
153 cl::Hidden, cl::init(true));
154
155std::optional<Instruction *>
157 // Handle target specific intrinsics
159 return TTI.instCombineIntrinsic(*this, II);
160 }
161 return std::nullopt;
162}
163
165 IntrinsicInst &II, APInt DemandedMask, KnownBits &Known,
166 bool &KnownBitsComputed) {
167 // Handle target specific intrinsics
169 return TTI.simplifyDemandedUseBitsIntrinsic(*this, II, DemandedMask, Known,
170 KnownBitsComputed);
171 }
172 return std::nullopt;
173}
174
176 IntrinsicInst &II, APInt DemandedElts, APInt &PoisonElts,
177 APInt &PoisonElts2, APInt &PoisonElts3,
178 std::function<void(Instruction *, unsigned, APInt, APInt &)>
179 SimplifyAndSetOp) {
180 // Handle target specific intrinsics
183 *this, II, DemandedElts, PoisonElts, PoisonElts2, PoisonElts3,
184 SimplifyAndSetOp);
185 }
186 return std::nullopt;
187}
188
189bool InstCombiner::isValidAddrSpaceCast(unsigned FromAS, unsigned ToAS) const {
190 return TTI.isValidAddrSpaceCast(FromAS, ToAS);
191}
192
193Value *InstCombinerImpl::EmitGEPOffset(User *GEP) {
195}
196
197/// Legal integers and common types are considered desirable. This is used to
198/// avoid creating instructions with types that may not be supported well by the
199/// the backend.
200/// NOTE: This treats i8, i16 and i32 specially because they are common
201/// types in frontend languages.
202bool InstCombinerImpl::isDesirableIntType(unsigned BitWidth) const {
203 switch (BitWidth) {
204 case 8:
205 case 16:
206 case 32:
207 return true;
208 default:
209 return DL.isLegalInteger(BitWidth);
210 }
211}
212
213/// Return true if it is desirable to convert an integer computation from a
214/// given bit width to a new bit width.
215/// We don't want to convert from a legal or desirable type (like i8) to an
216/// illegal type or from a smaller to a larger illegal type. A width of '1'
217/// is always treated as a desirable type because i1 is a fundamental type in
218/// IR, and there are many specialized optimizations for i1 types.
219/// Common/desirable widths are equally treated as legal to convert to, in
220/// order to open up more combining opportunities.
221bool InstCombinerImpl::shouldChangeType(unsigned FromWidth,
222 unsigned ToWidth) const {
223 bool FromLegal = FromWidth == 1 || DL.isLegalInteger(FromWidth);
224 bool ToLegal = ToWidth == 1 || DL.isLegalInteger(ToWidth);
225
226 // Convert to desirable widths even if they are not legal types.
227 // Only shrink types, to prevent infinite loops.
228 if (ToWidth < FromWidth && isDesirableIntType(ToWidth))
229 return true;
230
231 // If this is a legal or desiable integer from type, and the result would be
232 // an illegal type, don't do the transformation.
233 if ((FromLegal || isDesirableIntType(FromWidth)) && !ToLegal)
234 return false;
235
236 // Otherwise, if both are illegal, do not increase the size of the result. We
237 // do allow things like i160 -> i64, but not i64 -> i160.
238 if (!FromLegal && !ToLegal && ToWidth > FromWidth)
239 return false;
240
241 return true;
242}
243
244/// Return true if it is desirable to convert a computation from 'From' to 'To'.
245/// We don't want to convert from a legal to an illegal type or from a smaller
246/// to a larger illegal type. i1 is always treated as a legal type because it is
247/// a fundamental type in IR, and there are many specialized optimizations for
248/// i1 types.
249bool InstCombinerImpl::shouldChangeType(Type *From, Type *To) const {
250 // TODO: This could be extended to allow vectors. Datalayout changes might be
251 // needed to properly support that.
252 if (!From->isIntegerTy() || !To->isIntegerTy())
253 return false;
254
255 unsigned FromWidth = From->getPrimitiveSizeInBits();
256 unsigned ToWidth = To->getPrimitiveSizeInBits();
257 return shouldChangeType(FromWidth, ToWidth);
258}
259
260// Return true, if No Signed Wrap should be maintained for I.
261// The No Signed Wrap flag can be kept if the operation "B (I.getOpcode) C",
262// where both B and C should be ConstantInts, results in a constant that does
263// not overflow. This function only handles the Add and Sub opcodes. For
264// all other opcodes, the function conservatively returns false.
266 auto *OBO = dyn_cast<OverflowingBinaryOperator>(&I);
267 if (!OBO || !OBO->hasNoSignedWrap())
268 return false;
269
270 // We reason about Add and Sub Only.
271 Instruction::BinaryOps Opcode = I.getOpcode();
272 if (Opcode != Instruction::Add && Opcode != Instruction::Sub)
273 return false;
274
275 const APInt *BVal, *CVal;
276 if (!match(B, m_APInt(BVal)) || !match(C, m_APInt(CVal)))
277 return false;
278
279 bool Overflow = false;
280 if (Opcode == Instruction::Add)
281 (void)BVal->sadd_ov(*CVal, Overflow);
282 else
283 (void)BVal->ssub_ov(*CVal, Overflow);
284
285 return !Overflow;
286}
287
289 auto *OBO = dyn_cast<OverflowingBinaryOperator>(&I);
290 return OBO && OBO->hasNoUnsignedWrap();
291}
292
294 auto *OBO = dyn_cast<OverflowingBinaryOperator>(&I);
295 return OBO && OBO->hasNoSignedWrap();
296}
297
298/// Conservatively clears subclassOptionalData after a reassociation or
299/// commutation. We preserve fast-math flags when applicable as they can be
300/// preserved.
302 FPMathOperator *FPMO = dyn_cast<FPMathOperator>(&I);
303 if (!FPMO) {
304 I.clearSubclassOptionalData();
305 return;
306 }
307
308 FastMathFlags FMF = I.getFastMathFlags();
309 I.clearSubclassOptionalData();
310 I.setFastMathFlags(FMF);
311}
312
313/// Combine constant operands of associative operations either before or after a
314/// cast to eliminate one of the associative operations:
315/// (op (cast (op X, C2)), C1) --> (cast (op X, op (C1, C2)))
316/// (op (cast (op X, C2)), C1) --> (op (cast X), op (C1, C2))
318 InstCombinerImpl &IC) {
319 auto *Cast = dyn_cast<CastInst>(BinOp1->getOperand(0));
320 if (!Cast || !Cast->hasOneUse())
321 return false;
322
323 // TODO: Enhance logic for other casts and remove this check.
324 auto CastOpcode = Cast->getOpcode();
325 if (CastOpcode != Instruction::ZExt)
326 return false;
327
328 // TODO: Enhance logic for other BinOps and remove this check.
329 if (!BinOp1->isBitwiseLogicOp())
330 return false;
331
332 auto AssocOpcode = BinOp1->getOpcode();
333 auto *BinOp2 = dyn_cast<BinaryOperator>(Cast->getOperand(0));
334 if (!BinOp2 || !BinOp2->hasOneUse() || BinOp2->getOpcode() != AssocOpcode)
335 return false;
336
337 Constant *C1, *C2;
338 if (!match(BinOp1->getOperand(1), m_Constant(C1)) ||
339 !match(BinOp2->getOperand(1), m_Constant(C2)))
340 return false;
341
342 // TODO: This assumes a zext cast.
343 // Eg, if it was a trunc, we'd cast C1 to the source type because casting C2
344 // to the destination type might lose bits.
345
346 // Fold the constants together in the destination type:
347 // (op (cast (op X, C2)), C1) --> (op (cast X), FoldedC)
348 const DataLayout &DL = IC.getDataLayout();
349 Type *DestTy = C1->getType();
350 Constant *CastC2 = ConstantFoldCastOperand(CastOpcode, C2, DestTy, DL);
351 if (!CastC2)
352 return false;
353 Constant *FoldedC = ConstantFoldBinaryOpOperands(AssocOpcode, C1, CastC2, DL);
354 if (!FoldedC)
355 return false;
356
357 IC.replaceOperand(*Cast, 0, BinOp2->getOperand(0));
358 IC.replaceOperand(*BinOp1, 1, FoldedC);
360 Cast->dropPoisonGeneratingFlags();
361 return true;
362}
363
364// Simplifies IntToPtr/PtrToInt RoundTrip Cast.
365// inttoptr ( ptrtoint (x) ) --> x
366Value *InstCombinerImpl::simplifyIntToPtrRoundTripCast(Value *Val) {
367 auto *IntToPtr = dyn_cast<IntToPtrInst>(Val);
368 if (IntToPtr && DL.getTypeSizeInBits(IntToPtr->getDestTy()) ==
369 DL.getTypeSizeInBits(IntToPtr->getSrcTy())) {
370 auto *PtrToInt = dyn_cast<PtrToIntInst>(IntToPtr->getOperand(0));
371 Type *CastTy = IntToPtr->getDestTy();
372 if (PtrToInt &&
373 CastTy->getPointerAddressSpace() ==
374 PtrToInt->getSrcTy()->getPointerAddressSpace() &&
375 DL.getTypeSizeInBits(PtrToInt->getSrcTy()) ==
376 DL.getTypeSizeInBits(PtrToInt->getDestTy()))
377 return PtrToInt->getOperand(0);
378 }
379 return nullptr;
380}
381
382/// This performs a few simplifications for operators that are associative or
383/// commutative:
384///
385/// Commutative operators:
386///
387/// 1. Order operands such that they are listed from right (least complex) to
388/// left (most complex). This puts constants before unary operators before
389/// binary operators.
390///
391/// Associative operators:
392///
393/// 2. Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
394/// 3. Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
395///
396/// Associative and commutative operators:
397///
398/// 4. Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
399/// 5. Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
400/// 6. Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
401/// if C1 and C2 are constants.
403 Instruction::BinaryOps Opcode = I.getOpcode();
404 bool Changed = false;
405
406 do {
407 // Order operands such that they are listed from right (least complex) to
408 // left (most complex). This puts constants before unary operators before
409 // binary operators.
410 if (I.isCommutative() && getComplexity(I.getOperand(0)) <
411 getComplexity(I.getOperand(1)))
412 Changed = !I.swapOperands();
413
414 if (I.isCommutative()) {
415 if (auto Pair = matchSymmetricPair(I.getOperand(0), I.getOperand(1))) {
416 replaceOperand(I, 0, Pair->first);
417 replaceOperand(I, 1, Pair->second);
418 Changed = true;
419 }
420 }
421
422 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(I.getOperand(0));
423 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1));
424
425 if (I.isAssociative()) {
426 // Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
427 if (Op0 && Op0->getOpcode() == Opcode) {
428 Value *A = Op0->getOperand(0);
429 Value *B = Op0->getOperand(1);
430 Value *C = I.getOperand(1);
431
432 // Does "B op C" simplify?
433 if (Value *V = simplifyBinOp(Opcode, B, C, SQ.getWithInstruction(&I))) {
434 // It simplifies to V. Form "A op V".
435 replaceOperand(I, 0, A);
436 replaceOperand(I, 1, V);
437 bool IsNUW = hasNoUnsignedWrap(I) && hasNoUnsignedWrap(*Op0);
438 bool IsNSW = maintainNoSignedWrap(I, B, C) && hasNoSignedWrap(*Op0);
439
440 // Conservatively clear all optional flags since they may not be
441 // preserved by the reassociation. Reset nsw/nuw based on the above
442 // analysis.
444
445 // Note: this is only valid because SimplifyBinOp doesn't look at
446 // the operands to Op0.
447 if (IsNUW)
448 I.setHasNoUnsignedWrap(true);
449
450 if (IsNSW)
451 I.setHasNoSignedWrap(true);
452
453 Changed = true;
454 ++NumReassoc;
455 continue;
456 }
457 }
458
459 // Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
460 if (Op1 && Op1->getOpcode() == Opcode) {
461 Value *A = I.getOperand(0);
462 Value *B = Op1->getOperand(0);
463 Value *C = Op1->getOperand(1);
464
465 // Does "A op B" simplify?
466 if (Value *V = simplifyBinOp(Opcode, A, B, SQ.getWithInstruction(&I))) {
467 // It simplifies to V. Form "V op C".
468 replaceOperand(I, 0, V);
469 replaceOperand(I, 1, C);
470 // Conservatively clear the optional flags, since they may not be
471 // preserved by the reassociation.
473 Changed = true;
474 ++NumReassoc;
475 continue;
476 }
477 }
478 }
479
480 if (I.isAssociative() && I.isCommutative()) {
481 if (simplifyAssocCastAssoc(&I, *this)) {
482 Changed = true;
483 ++NumReassoc;
484 continue;
485 }
486
487 // Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
488 if (Op0 && Op0->getOpcode() == Opcode) {
489 Value *A = Op0->getOperand(0);
490 Value *B = Op0->getOperand(1);
491 Value *C = I.getOperand(1);
492
493 // Does "C op A" simplify?
494 if (Value *V = simplifyBinOp(Opcode, C, A, SQ.getWithInstruction(&I))) {
495 // It simplifies to V. Form "V op B".
496 replaceOperand(I, 0, V);
497 replaceOperand(I, 1, B);
498 // Conservatively clear the optional flags, since they may not be
499 // preserved by the reassociation.
501 Changed = true;
502 ++NumReassoc;
503 continue;
504 }
505 }
506
507 // Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
508 if (Op1 && Op1->getOpcode() == Opcode) {
509 Value *A = I.getOperand(0);
510 Value *B = Op1->getOperand(0);
511 Value *C = Op1->getOperand(1);
512
513 // Does "C op A" simplify?
514 if (Value *V = simplifyBinOp(Opcode, C, A, SQ.getWithInstruction(&I))) {
515 // It simplifies to V. Form "B op V".
516 replaceOperand(I, 0, B);
517 replaceOperand(I, 1, V);
518 // Conservatively clear the optional flags, since they may not be
519 // preserved by the reassociation.
521 Changed = true;
522 ++NumReassoc;
523 continue;
524 }
525 }
526
527 // Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
528 // if C1 and C2 are constants.
529 Value *A, *B;
530 Constant *C1, *C2, *CRes;
531 if (Op0 && Op1 &&
532 Op0->getOpcode() == Opcode && Op1->getOpcode() == Opcode &&
533 match(Op0, m_OneUse(m_BinOp(m_Value(A), m_Constant(C1)))) &&
534 match(Op1, m_OneUse(m_BinOp(m_Value(B), m_Constant(C2)))) &&
535 (CRes = ConstantFoldBinaryOpOperands(Opcode, C1, C2, DL))) {
536 bool IsNUW = hasNoUnsignedWrap(I) &&
537 hasNoUnsignedWrap(*Op0) &&
538 hasNoUnsignedWrap(*Op1);
539 BinaryOperator *NewBO = (IsNUW && Opcode == Instruction::Add) ?
540 BinaryOperator::CreateNUW(Opcode, A, B) :
541 BinaryOperator::Create(Opcode, A, B);
542
543 if (isa<FPMathOperator>(NewBO)) {
544 FastMathFlags Flags = I.getFastMathFlags() &
545 Op0->getFastMathFlags() &
546 Op1->getFastMathFlags();
547 NewBO->setFastMathFlags(Flags);
548 }
549 InsertNewInstWith(NewBO, I.getIterator());
550 NewBO->takeName(Op1);
551 replaceOperand(I, 0, NewBO);
552 replaceOperand(I, 1, CRes);
553 // Conservatively clear the optional flags, since they may not be
554 // preserved by the reassociation.
556 if (IsNUW)
557 I.setHasNoUnsignedWrap(true);
558
559 Changed = true;
560 continue;
561 }
562 }
563
564 // No further simplifications.
565 return Changed;
566 } while (true);
567}
568
569/// Return whether "X LOp (Y ROp Z)" is always equal to
570/// "(X LOp Y) ROp (X LOp Z)".
573 // X & (Y | Z) <--> (X & Y) | (X & Z)
574 // X & (Y ^ Z) <--> (X & Y) ^ (X & Z)
575 if (LOp == Instruction::And)
576 return ROp == Instruction::Or || ROp == Instruction::Xor;
577
578 // X | (Y & Z) <--> (X | Y) & (X | Z)
579 if (LOp == Instruction::Or)
580 return ROp == Instruction::And;
581
582 // X * (Y + Z) <--> (X * Y) + (X * Z)
583 // X * (Y - Z) <--> (X * Y) - (X * Z)
584 if (LOp == Instruction::Mul)
585 return ROp == Instruction::Add || ROp == Instruction::Sub;
586
587 return false;
588}
589
590/// Return whether "(X LOp Y) ROp Z" is always equal to
591/// "(X ROp Z) LOp (Y ROp Z)".
595 return leftDistributesOverRight(ROp, LOp);
596
597 // (X {&|^} Y) >> Z <--> (X >> Z) {&|^} (Y >> Z) for all shifts.
599
600 // TODO: It would be nice to handle division, aka "(X + Y)/Z = X/Z + Y/Z",
601 // but this requires knowing that the addition does not overflow and other
602 // such subtleties.
603}
604
605/// This function returns identity value for given opcode, which can be used to
606/// factor patterns like (X * 2) + X ==> (X * 2) + (X * 1) ==> X * (2 + 1).
608 if (isa<Constant>(V))
609 return nullptr;
610
611 return ConstantExpr::getBinOpIdentity(Opcode, V->getType());
612}
613
614/// This function predicates factorization using distributive laws. By default,
615/// it just returns the 'Op' inputs. But for special-cases like
616/// 'add(shl(X, 5), ...)', this function will have TopOpcode == Instruction::Add
617/// and Op = shl(X, 5). The 'shl' is treated as the more general 'mul X, 32' to
618/// allow more factorization opportunities.
621 Value *&LHS, Value *&RHS, BinaryOperator *OtherOp) {
622 assert(Op && "Expected a binary operator");
623 LHS = Op->getOperand(0);
624 RHS = Op->getOperand(1);
625 if (TopOpcode == Instruction::Add || TopOpcode == Instruction::Sub) {
626 Constant *C;
627 if (match(Op, m_Shl(m_Value(), m_Constant(C)))) {
628 // X << C --> X * (1 << C)
629 RHS = ConstantExpr::getShl(ConstantInt::get(Op->getType(), 1), C);
630 return Instruction::Mul;
631 }
632 // TODO: We can add other conversions e.g. shr => div etc.
633 }
634 if (Instruction::isBitwiseLogicOp(TopOpcode)) {
635 if (OtherOp && OtherOp->getOpcode() == Instruction::AShr &&
637 // lshr nneg C, X --> ashr nneg C, X
638 return Instruction::AShr;
639 }
640 }
641 return Op->getOpcode();
642}
643
644/// This tries to simplify binary operations by factorizing out common terms
645/// (e. g. "(A*B)+(A*C)" -> "A*(B+C)").
648 Instruction::BinaryOps InnerOpcode, Value *A,
649 Value *B, Value *C, Value *D) {
650 assert(A && B && C && D && "All values must be provided");
651
652 Value *V = nullptr;
653 Value *RetVal = nullptr;
654 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
655 Instruction::BinaryOps TopLevelOpcode = I.getOpcode();
656
657 // Does "X op' Y" always equal "Y op' X"?
658 bool InnerCommutative = Instruction::isCommutative(InnerOpcode);
659
660 // Does "X op' (Y op Z)" always equal "(X op' Y) op (X op' Z)"?
661 if (leftDistributesOverRight(InnerOpcode, TopLevelOpcode)) {
662 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
663 // commutative case, "(A op' B) op (C op' A)"?
664 if (A == C || (InnerCommutative && A == D)) {
665 if (A != C)
666 std::swap(C, D);
667 // Consider forming "A op' (B op D)".
668 // If "B op D" simplifies then it can be formed with no cost.
669 V = simplifyBinOp(TopLevelOpcode, B, D, SQ.getWithInstruction(&I));
670
671 // If "B op D" doesn't simplify then only go on if one of the existing
672 // operations "A op' B" and "C op' D" will be zapped as no longer used.
673 if (!V && (LHS->hasOneUse() || RHS->hasOneUse()))
674 V = Builder.CreateBinOp(TopLevelOpcode, B, D, RHS->getName());
675 if (V)
676 RetVal = Builder.CreateBinOp(InnerOpcode, A, V);
677 }
678 }
679
680 // Does "(X op Y) op' Z" always equal "(X op' Z) op (Y op' Z)"?
681 if (!RetVal && rightDistributesOverLeft(TopLevelOpcode, InnerOpcode)) {
682 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
683 // commutative case, "(A op' B) op (B op' D)"?
684 if (B == D || (InnerCommutative && B == C)) {
685 if (B != D)
686 std::swap(C, D);
687 // Consider forming "(A op C) op' B".
688 // If "A op C" simplifies then it can be formed with no cost.
689 V = simplifyBinOp(TopLevelOpcode, A, C, SQ.getWithInstruction(&I));
690
691 // If "A op C" doesn't simplify then only go on if one of the existing
692 // operations "A op' B" and "C op' D" will be zapped as no longer used.
693 if (!V && (LHS->hasOneUse() || RHS->hasOneUse()))
694 V = Builder.CreateBinOp(TopLevelOpcode, A, C, LHS->getName());
695 if (V)
696 RetVal = Builder.CreateBinOp(InnerOpcode, V, B);
697 }
698 }
699
700 if (!RetVal)
701 return nullptr;
702
703 ++NumFactor;
704 RetVal->takeName(&I);
705
706 // Try to add no-overflow flags to the final value.
707 if (isa<OverflowingBinaryOperator>(RetVal)) {
708 bool HasNSW = false;
709 bool HasNUW = false;
710 if (isa<OverflowingBinaryOperator>(&I)) {
711 HasNSW = I.hasNoSignedWrap();
712 HasNUW = I.hasNoUnsignedWrap();
713 }
714 if (auto *LOBO = dyn_cast<OverflowingBinaryOperator>(LHS)) {
715 HasNSW &= LOBO->hasNoSignedWrap();
716 HasNUW &= LOBO->hasNoUnsignedWrap();
717 }
718
719 if (auto *ROBO = dyn_cast<OverflowingBinaryOperator>(RHS)) {
720 HasNSW &= ROBO->hasNoSignedWrap();
721 HasNUW &= ROBO->hasNoUnsignedWrap();
722 }
723
724 if (TopLevelOpcode == Instruction::Add && InnerOpcode == Instruction::Mul) {
725 // We can propagate 'nsw' if we know that
726 // %Y = mul nsw i16 %X, C
727 // %Z = add nsw i16 %Y, %X
728 // =>
729 // %Z = mul nsw i16 %X, C+1
730 //
731 // iff C+1 isn't INT_MIN
732 const APInt *CInt;
733 if (match(V, m_APInt(CInt)) && !CInt->isMinSignedValue())
734 cast<Instruction>(RetVal)->setHasNoSignedWrap(HasNSW);
735
736 // nuw can be propagated with any constant or nuw value.
737 cast<Instruction>(RetVal)->setHasNoUnsignedWrap(HasNUW);
738 }
739 }
740 return RetVal;
741}
742
743// If `I` has one Const operand and the other matches `(ctpop (not x))`,
744// replace `(ctpop (not x))` with `(sub nuw nsw BitWidth(x), (ctpop x))`.
745// This is only useful is the new subtract can fold so we only handle the
746// following cases:
747// 1) (add/sub/disjoint_or C, (ctpop (not x))
748// -> (add/sub/disjoint_or C', (ctpop x))
749// 1) (cmp pred C, (ctpop (not x))
750// -> (cmp pred C', (ctpop x))
752 unsigned Opc = I->getOpcode();
753 unsigned ConstIdx = 1;
754 switch (Opc) {
755 default:
756 return nullptr;
757 // (ctpop (not x)) <-> (sub nuw nsw BitWidth(x) - (ctpop x))
758 // We can fold the BitWidth(x) with add/sub/icmp as long the other operand
759 // is constant.
760 case Instruction::Sub:
761 ConstIdx = 0;
762 break;
763 case Instruction::ICmp:
764 // Signed predicates aren't correct in some edge cases like for i2 types, as
765 // well since (ctpop x) is known [0, log2(BitWidth(x))] almost all signed
766 // comparisons against it are simplfied to unsigned.
767 if (cast<ICmpInst>(I)->isSigned())
768 return nullptr;
769 break;
770 case Instruction::Or:
771 if (!match(I, m_DisjointOr(m_Value(), m_Value())))
772 return nullptr;
773 [[fallthrough]];
774 case Instruction::Add:
775 break;
776 }
777
778 Value *Op;
779 // Find ctpop.
780 if (!match(I->getOperand(1 - ConstIdx),
781 m_OneUse(m_Intrinsic<Intrinsic::ctpop>(m_Value(Op)))))
782 return nullptr;
783
784 Constant *C;
785 // Check other operand is ImmConstant.
786 if (!match(I->getOperand(ConstIdx), m_ImmConstant(C)))
787 return nullptr;
788
789 Type *Ty = Op->getType();
790 Constant *BitWidthC = ConstantInt::get(Ty, Ty->getScalarSizeInBits());
791 // Need extra check for icmp. Note if this check is true, it generally means
792 // the icmp will simplify to true/false.
793 if (Opc == Instruction::ICmp && !cast<ICmpInst>(I)->isEquality() &&
794 !ConstantExpr::getICmp(ICmpInst::ICMP_UGT, C, BitWidthC)->isZeroValue())
795 return nullptr;
796
797 // Check we can invert `(not x)` for free.
798 bool Consumes = false;
799 if (!isFreeToInvert(Op, Op->hasOneUse(), Consumes) || !Consumes)
800 return nullptr;
801 Value *NotOp = getFreelyInverted(Op, Op->hasOneUse(), &Builder);
802 assert(NotOp != nullptr &&
803 "Desync between isFreeToInvert and getFreelyInverted");
804
805 Value *CtpopOfNotOp = Builder.CreateIntrinsic(Ty, Intrinsic::ctpop, NotOp);
806
807 Value *R = nullptr;
808
809 // Do the transformation here to avoid potentially introducing an infinite
810 // loop.
811 switch (Opc) {
812 case Instruction::Sub:
813 R = Builder.CreateAdd(CtpopOfNotOp, ConstantExpr::getSub(C, BitWidthC));
814 break;
815 case Instruction::Or:
816 case Instruction::Add:
817 R = Builder.CreateSub(ConstantExpr::getAdd(C, BitWidthC), CtpopOfNotOp);
818 break;
819 case Instruction::ICmp:
820 R = Builder.CreateICmp(cast<ICmpInst>(I)->getSwappedPredicate(),
821 CtpopOfNotOp, ConstantExpr::getSub(BitWidthC, C));
822 break;
823 default:
824 llvm_unreachable("Unhandled Opcode");
825 }
826 assert(R != nullptr);
827 return replaceInstUsesWith(*I, R);
828}
829
830// (Binop1 (Binop2 (logic_shift X, C), C1), (logic_shift Y, C))
831// IFF
832// 1) the logic_shifts match
833// 2) either both binops are binops and one is `and` or
834// BinOp1 is `and`
835// (logic_shift (inv_logic_shift C1, C), C) == C1 or
836//
837// -> (logic_shift (Binop1 (Binop2 X, inv_logic_shift(C1, C)), Y), C)
838//
839// (Binop1 (Binop2 (logic_shift X, Amt), Mask), (logic_shift Y, Amt))
840// IFF
841// 1) the logic_shifts match
842// 2) BinOp1 == BinOp2 (if BinOp == `add`, then also requires `shl`).
843//
844// -> (BinOp (logic_shift (BinOp X, Y)), Mask)
845//
846// (Binop1 (Binop2 (arithmetic_shift X, Amt), Mask), (arithmetic_shift Y, Amt))
847// IFF
848// 1) Binop1 is bitwise logical operator `and`, `or` or `xor`
849// 2) Binop2 is `not`
850//
851// -> (arithmetic_shift Binop1((not X), Y), Amt)
852
854 const DataLayout &DL = I.getModule()->getDataLayout();
855 auto IsValidBinOpc = [](unsigned Opc) {
856 switch (Opc) {
857 default:
858 return false;
859 case Instruction::And:
860 case Instruction::Or:
861 case Instruction::Xor:
862 case Instruction::Add:
863 // Skip Sub as we only match constant masks which will canonicalize to use
864 // add.
865 return true;
866 }
867 };
868
869 // Check if we can distribute binop arbitrarily. `add` + `lshr` has extra
870 // constraints.
871 auto IsCompletelyDistributable = [](unsigned BinOpc1, unsigned BinOpc2,
872 unsigned ShOpc) {
873 assert(ShOpc != Instruction::AShr);
874 return (BinOpc1 != Instruction::Add && BinOpc2 != Instruction::Add) ||
875 ShOpc == Instruction::Shl;
876 };
877
878 auto GetInvShift = [](unsigned ShOpc) {
879 assert(ShOpc != Instruction::AShr);
880 return ShOpc == Instruction::LShr ? Instruction::Shl : Instruction::LShr;
881 };
882
883 auto CanDistributeBinops = [&](unsigned BinOpc1, unsigned BinOpc2,
884 unsigned ShOpc, Constant *CMask,
885 Constant *CShift) {
886 // If the BinOp1 is `and` we don't need to check the mask.
887 if (BinOpc1 == Instruction::And)
888 return true;
889
890 // For all other possible transfers we need complete distributable
891 // binop/shift (anything but `add` + `lshr`).
892 if (!IsCompletelyDistributable(BinOpc1, BinOpc2, ShOpc))
893 return false;
894
895 // If BinOp2 is `and`, any mask works (this only really helps for non-splat
896 // vecs, otherwise the mask will be simplified and the following check will
897 // handle it).
898 if (BinOpc2 == Instruction::And)
899 return true;
900
901 // Otherwise, need mask that meets the below requirement.
902 // (logic_shift (inv_logic_shift Mask, ShAmt), ShAmt) == Mask
903 Constant *MaskInvShift =
904 ConstantFoldBinaryOpOperands(GetInvShift(ShOpc), CMask, CShift, DL);
905 return ConstantFoldBinaryOpOperands(ShOpc, MaskInvShift, CShift, DL) ==
906 CMask;
907 };
908
909 auto MatchBinOp = [&](unsigned ShOpnum) -> Instruction * {
910 Constant *CMask, *CShift;
911 Value *X, *Y, *ShiftedX, *Mask, *Shift;
912 if (!match(I.getOperand(ShOpnum),
913 m_OneUse(m_Shift(m_Value(Y), m_Value(Shift)))))
914 return nullptr;
915 if (!match(I.getOperand(1 - ShOpnum),
916 m_BinOp(m_Value(ShiftedX), m_Value(Mask))))
917 return nullptr;
918
919 if (!match(ShiftedX, m_OneUse(m_Shift(m_Value(X), m_Specific(Shift)))))
920 return nullptr;
921
922 // Make sure we are matching instruction shifts and not ConstantExpr
923 auto *IY = dyn_cast<Instruction>(I.getOperand(ShOpnum));
924 auto *IX = dyn_cast<Instruction>(ShiftedX);
925 if (!IY || !IX)
926 return nullptr;
927
928 // LHS and RHS need same shift opcode
929 unsigned ShOpc = IY->getOpcode();
930 if (ShOpc != IX->getOpcode())
931 return nullptr;
932
933 // Make sure binop is real instruction and not ConstantExpr
934 auto *BO2 = dyn_cast<Instruction>(I.getOperand(1 - ShOpnum));
935 if (!BO2)
936 return nullptr;
937
938 unsigned BinOpc = BO2->getOpcode();
939 // Make sure we have valid binops.
940 if (!IsValidBinOpc(I.getOpcode()) || !IsValidBinOpc(BinOpc))
941 return nullptr;
942
943 if (ShOpc == Instruction::AShr) {
944 if (Instruction::isBitwiseLogicOp(I.getOpcode()) &&
945 BinOpc == Instruction::Xor && match(Mask, m_AllOnes())) {
946 Value *NotX = Builder.CreateNot(X);
947 Value *NewBinOp = Builder.CreateBinOp(I.getOpcode(), Y, NotX);
949 static_cast<Instruction::BinaryOps>(ShOpc), NewBinOp, Shift);
950 }
951
952 return nullptr;
953 }
954
955 // If BinOp1 == BinOp2 and it's bitwise or shl with add, then just
956 // distribute to drop the shift irrelevant of constants.
957 if (BinOpc == I.getOpcode() &&
958 IsCompletelyDistributable(I.getOpcode(), BinOpc, ShOpc)) {
959 Value *NewBinOp2 = Builder.CreateBinOp(I.getOpcode(), X, Y);
960 Value *NewBinOp1 = Builder.CreateBinOp(
961 static_cast<Instruction::BinaryOps>(ShOpc), NewBinOp2, Shift);
962 return BinaryOperator::Create(I.getOpcode(), NewBinOp1, Mask);
963 }
964
965 // Otherwise we can only distribute by constant shifting the mask, so
966 // ensure we have constants.
967 if (!match(Shift, m_ImmConstant(CShift)))
968 return nullptr;
969 if (!match(Mask, m_ImmConstant(CMask)))
970 return nullptr;
971
972 // Check if we can distribute the binops.
973 if (!CanDistributeBinops(I.getOpcode(), BinOpc, ShOpc, CMask, CShift))
974 return nullptr;
975
976 Constant *NewCMask =
977 ConstantFoldBinaryOpOperands(GetInvShift(ShOpc), CMask, CShift, DL);
978 Value *NewBinOp2 = Builder.CreateBinOp(
979 static_cast<Instruction::BinaryOps>(BinOpc), X, NewCMask);
980 Value *NewBinOp1 = Builder.CreateBinOp(I.getOpcode(), Y, NewBinOp2);
981 return BinaryOperator::Create(static_cast<Instruction::BinaryOps>(ShOpc),
982 NewBinOp1, CShift);
983 };
984
985 if (Instruction *R = MatchBinOp(0))
986 return R;
987 return MatchBinOp(1);
988}
989
990// (Binop (zext C), (select C, T, F))
991// -> (select C, (binop 1, T), (binop 0, F))
992//
993// (Binop (sext C), (select C, T, F))
994// -> (select C, (binop -1, T), (binop 0, F))
995//
996// Attempt to simplify binary operations into a select with folded args, when
997// one operand of the binop is a select instruction and the other operand is a
998// zext/sext extension, whose value is the select condition.
1001 // TODO: this simplification may be extended to any speculatable instruction,
1002 // not just binops, and would possibly be handled better in FoldOpIntoSelect.
1003 Instruction::BinaryOps Opc = I.getOpcode();
1004 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1005 Value *A, *CondVal, *TrueVal, *FalseVal;
1006 Value *CastOp;
1007
1008 auto MatchSelectAndCast = [&](Value *CastOp, Value *SelectOp) {
1009 return match(CastOp, m_ZExtOrSExt(m_Value(A))) &&
1010 A->getType()->getScalarSizeInBits() == 1 &&
1011 match(SelectOp, m_Select(m_Value(CondVal), m_Value(TrueVal),
1012 m_Value(FalseVal)));
1013 };
1014
1015 // Make sure one side of the binop is a select instruction, and the other is a
1016 // zero/sign extension operating on a i1.
1017 if (MatchSelectAndCast(LHS, RHS))
1018 CastOp = LHS;
1019 else if (MatchSelectAndCast(RHS, LHS))
1020 CastOp = RHS;
1021 else
1022 return nullptr;
1023
1024 auto NewFoldedConst = [&](bool IsTrueArm, Value *V) {
1025 bool IsCastOpRHS = (CastOp == RHS);
1026 bool IsZExt = isa<ZExtInst>(CastOp);
1027 Constant *C;
1028
1029 if (IsTrueArm) {
1030 C = Constant::getNullValue(V->getType());
1031 } else if (IsZExt) {
1032 unsigned BitWidth = V->getType()->getScalarSizeInBits();
1033 C = Constant::getIntegerValue(V->getType(), APInt(BitWidth, 1));
1034 } else {
1035 C = Constant::getAllOnesValue(V->getType());
1036 }
1037
1038 return IsCastOpRHS ? Builder.CreateBinOp(Opc, V, C)
1039 : Builder.CreateBinOp(Opc, C, V);
1040 };
1041
1042 // If the value used in the zext/sext is the select condition, or the negated
1043 // of the select condition, the binop can be simplified.
1044 if (CondVal == A) {
1045 Value *NewTrueVal = NewFoldedConst(false, TrueVal);
1046 return SelectInst::Create(CondVal, NewTrueVal,
1047 NewFoldedConst(true, FalseVal));
1048 }
1049
1050 if (match(A, m_Not(m_Specific(CondVal)))) {
1051 Value *NewTrueVal = NewFoldedConst(true, TrueVal);
1052 return SelectInst::Create(CondVal, NewTrueVal,
1053 NewFoldedConst(false, FalseVal));
1054 }
1055
1056 return nullptr;
1057}
1058
1060 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1061 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
1062 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
1063 Instruction::BinaryOps TopLevelOpcode = I.getOpcode();
1064 Value *A, *B, *C, *D;
1065 Instruction::BinaryOps LHSOpcode, RHSOpcode;
1066
1067 if (Op0)
1068 LHSOpcode = getBinOpsForFactorization(TopLevelOpcode, Op0, A, B, Op1);
1069 if (Op1)
1070 RHSOpcode = getBinOpsForFactorization(TopLevelOpcode, Op1, C, D, Op0);
1071
1072 // The instruction has the form "(A op' B) op (C op' D)". Try to factorize
1073 // a common term.
1074 if (Op0 && Op1 && LHSOpcode == RHSOpcode)
1075 if (Value *V = tryFactorization(I, SQ, Builder, LHSOpcode, A, B, C, D))
1076 return V;
1077
1078 // The instruction has the form "(A op' B) op (C)". Try to factorize common
1079 // term.
1080 if (Op0)
1081 if (Value *Ident = getIdentityValue(LHSOpcode, RHS))
1082 if (Value *V =
1083 tryFactorization(I, SQ, Builder, LHSOpcode, A, B, RHS, Ident))
1084 return V;
1085
1086 // The instruction has the form "(B) op (C op' D)". Try to factorize common
1087 // term.
1088 if (Op1)
1089 if (Value *Ident = getIdentityValue(RHSOpcode, LHS))
1090 if (Value *V =
1091 tryFactorization(I, SQ, Builder, RHSOpcode, LHS, Ident, C, D))
1092 return V;
1093
1094 return nullptr;
1095}
1096
1097/// This tries to simplify binary operations which some other binary operation
1098/// distributes over either by factorizing out common terms
1099/// (eg "(A*B)+(A*C)" -> "A*(B+C)") or expanding out if this results in
1100/// simplifications (eg: "A & (B | C) -> (A&B) | (A&C)" if this is a win).
1101/// Returns the simplified value, or null if it didn't simplify.
1103 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1104 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
1105 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
1106 Instruction::BinaryOps TopLevelOpcode = I.getOpcode();
1107
1108 // Factorization.
1109 if (Value *R = tryFactorizationFolds(I))
1110 return R;
1111
1112 // Expansion.
1113 if (Op0 && rightDistributesOverLeft(Op0->getOpcode(), TopLevelOpcode)) {
1114 // The instruction has the form "(A op' B) op C". See if expanding it out
1115 // to "(A op C) op' (B op C)" results in simplifications.
1116 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
1117 Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op'
1118
1119 // Disable the use of undef because it's not safe to distribute undef.
1120 auto SQDistributive = SQ.getWithInstruction(&I).getWithoutUndef();
1121 Value *L = simplifyBinOp(TopLevelOpcode, A, C, SQDistributive);
1122 Value *R = simplifyBinOp(TopLevelOpcode, B, C, SQDistributive);
1123
1124 // Do "A op C" and "B op C" both simplify?
1125 if (L && R) {
1126 // They do! Return "L op' R".
1127 ++NumExpand;
1128 C = Builder.CreateBinOp(InnerOpcode, L, R);
1129 C->takeName(&I);
1130 return C;
1131 }
1132
1133 // Does "A op C" simplify to the identity value for the inner opcode?
1134 if (L && L == ConstantExpr::getBinOpIdentity(InnerOpcode, L->getType())) {
1135 // They do! Return "B op C".
1136 ++NumExpand;
1137 C = Builder.CreateBinOp(TopLevelOpcode, B, C);
1138 C->takeName(&I);
1139 return C;
1140 }
1141
1142 // Does "B op C" simplify to the identity value for the inner opcode?
1143 if (R && R == ConstantExpr::getBinOpIdentity(InnerOpcode, R->getType())) {
1144 // They do! Return "A op C".
1145 ++NumExpand;
1146 C = Builder.CreateBinOp(TopLevelOpcode, A, C);
1147 C->takeName(&I);
1148 return C;
1149 }
1150 }
1151
1152 if (Op1 && leftDistributesOverRight(TopLevelOpcode, Op1->getOpcode())) {
1153 // The instruction has the form "A op (B op' C)". See if expanding it out
1154 // to "(A op B) op' (A op C)" results in simplifications.
1155 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
1156 Instruction::BinaryOps InnerOpcode = Op1->getOpcode(); // op'
1157
1158 // Disable the use of undef because it's not safe to distribute undef.
1159 auto SQDistributive = SQ.getWithInstruction(&I).getWithoutUndef();
1160 Value *L = simplifyBinOp(TopLevelOpcode, A, B, SQDistributive);
1161 Value *R = simplifyBinOp(TopLevelOpcode, A, C, SQDistributive);
1162
1163 // Do "A op B" and "A op C" both simplify?
1164 if (L && R) {
1165 // They do! Return "L op' R".
1166 ++NumExpand;
1167 A = Builder.CreateBinOp(InnerOpcode, L, R);
1168 A->takeName(&I);
1169 return A;
1170 }
1171
1172 // Does "A op B" simplify to the identity value for the inner opcode?
1173 if (L && L == ConstantExpr::getBinOpIdentity(InnerOpcode, L->getType())) {
1174 // They do! Return "A op C".
1175 ++NumExpand;
1176 A = Builder.CreateBinOp(TopLevelOpcode, A, C);
1177 A->takeName(&I);
1178 return A;
1179 }
1180
1181 // Does "A op C" simplify to the identity value for the inner opcode?
1182 if (R && R == ConstantExpr::getBinOpIdentity(InnerOpcode, R->getType())) {
1183 // They do! Return "A op B".
1184 ++NumExpand;
1185 A = Builder.CreateBinOp(TopLevelOpcode, A, B);
1186 A->takeName(&I);
1187 return A;
1188 }
1189 }
1190
1192}
1193
1194static std::optional<std::pair<Value *, Value *>>
1196 if (LHS->getParent() != RHS->getParent())
1197 return std::nullopt;
1198
1199 if (LHS->getNumIncomingValues() < 2)
1200 return std::nullopt;
1201
1202 if (!equal(LHS->blocks(), RHS->blocks()))
1203 return std::nullopt;
1204
1205 Value *L0 = LHS->getIncomingValue(0);
1206 Value *R0 = RHS->getIncomingValue(0);
1207
1208 for (unsigned I = 1, E = LHS->getNumIncomingValues(); I != E; ++I) {
1209 Value *L1 = LHS->getIncomingValue(I);
1210 Value *R1 = RHS->getIncomingValue(I);
1211
1212 if ((L0 == L1 && R0 == R1) || (L0 == R1 && R0 == L1))
1213 continue;
1214
1215 return std::nullopt;
1216 }
1217
1218 return std::optional(std::pair(L0, R0));
1219}
1220
1221std::optional<std::pair<Value *, Value *>>
1222InstCombinerImpl::matchSymmetricPair(Value *LHS, Value *RHS) {
1223 Instruction *LHSInst = dyn_cast<Instruction>(LHS);
1224 Instruction *RHSInst = dyn_cast<Instruction>(RHS);
1225 if (!LHSInst || !RHSInst || LHSInst->getOpcode() != RHSInst->getOpcode())
1226 return std::nullopt;
1227 switch (LHSInst->getOpcode()) {
1228 case Instruction::PHI:
1229 return matchSymmetricPhiNodesPair(cast<PHINode>(LHS), cast<PHINode>(RHS));
1230 case Instruction::Select: {
1231 Value *Cond = LHSInst->getOperand(0);
1232 Value *TrueVal = LHSInst->getOperand(1);
1233 Value *FalseVal = LHSInst->getOperand(2);
1234 if (Cond == RHSInst->getOperand(0) && TrueVal == RHSInst->getOperand(2) &&
1235 FalseVal == RHSInst->getOperand(1))
1236 return std::pair(TrueVal, FalseVal);
1237 return std::nullopt;
1238 }
1239 case Instruction::Call: {
1240 // Match min(a, b) and max(a, b)
1241 MinMaxIntrinsic *LHSMinMax = dyn_cast<MinMaxIntrinsic>(LHSInst);
1242 MinMaxIntrinsic *RHSMinMax = dyn_cast<MinMaxIntrinsic>(RHSInst);
1243 if (LHSMinMax && RHSMinMax &&
1244 LHSMinMax->getPredicate() ==
1246 ((LHSMinMax->getLHS() == RHSMinMax->getLHS() &&
1247 LHSMinMax->getRHS() == RHSMinMax->getRHS()) ||
1248 (LHSMinMax->getLHS() == RHSMinMax->getRHS() &&
1249 LHSMinMax->getRHS() == RHSMinMax->getLHS())))
1250 return std::pair(LHSMinMax->getLHS(), LHSMinMax->getRHS());
1251 return std::nullopt;
1252 }
1253 default:
1254 return std::nullopt;
1255 }
1256}
1257
1259 Value *LHS,
1260 Value *RHS) {
1261 Value *A, *B, *C, *D, *E, *F;
1262 bool LHSIsSelect = match(LHS, m_Select(m_Value(A), m_Value(B), m_Value(C)));
1263 bool RHSIsSelect = match(RHS, m_Select(m_Value(D), m_Value(E), m_Value(F)));
1264 if (!LHSIsSelect && !RHSIsSelect)
1265 return nullptr;
1266
1267 FastMathFlags FMF;
1269 if (isa<FPMathOperator>(&I)) {
1270 FMF = I.getFastMathFlags();
1272 }
1273
1274 Instruction::BinaryOps Opcode = I.getOpcode();
1276
1277 Value *Cond, *True = nullptr, *False = nullptr;
1278
1279 // Special-case for add/negate combination. Replace the zero in the negation
1280 // with the trailing add operand:
1281 // (Cond ? TVal : -N) + Z --> Cond ? True : (Z - N)
1282 // (Cond ? -N : FVal) + Z --> Cond ? (Z - N) : False
1283 auto foldAddNegate = [&](Value *TVal, Value *FVal, Value *Z) -> Value * {
1284 // We need an 'add' and exactly 1 arm of the select to have been simplified.
1285 if (Opcode != Instruction::Add || (!True && !False) || (True && False))
1286 return nullptr;
1287
1288 Value *N;
1289 if (True && match(FVal, m_Neg(m_Value(N)))) {
1290 Value *Sub = Builder.CreateSub(Z, N);
1291 return Builder.CreateSelect(Cond, True, Sub, I.getName());
1292 }
1293 if (False && match(TVal, m_Neg(m_Value(N)))) {
1294 Value *Sub = Builder.CreateSub(Z, N);
1295 return Builder.CreateSelect(Cond, Sub, False, I.getName());
1296 }
1297 return nullptr;
1298 };
1299
1300 if (LHSIsSelect && RHSIsSelect && A == D) {
1301 // (A ? B : C) op (A ? E : F) -> A ? (B op E) : (C op F)
1302 Cond = A;
1303 True = simplifyBinOp(Opcode, B, E, FMF, Q);
1304 False = simplifyBinOp(Opcode, C, F, FMF, Q);
1305
1306 if (LHS->hasOneUse() && RHS->hasOneUse()) {
1307 if (False && !True)
1308 True = Builder.CreateBinOp(Opcode, B, E);
1309 else if (True && !False)
1310 False = Builder.CreateBinOp(Opcode, C, F);
1311 }
1312 } else if (LHSIsSelect && LHS->hasOneUse()) {
1313 // (A ? B : C) op Y -> A ? (B op Y) : (C op Y)
1314 Cond = A;
1315 True = simplifyBinOp(Opcode, B, RHS, FMF, Q);
1316 False = simplifyBinOp(Opcode, C, RHS, FMF, Q);
1317 if (Value *NewSel = foldAddNegate(B, C, RHS))
1318 return NewSel;
1319 } else if (RHSIsSelect && RHS->hasOneUse()) {
1320 // X op (D ? E : F) -> D ? (X op E) : (X op F)
1321 Cond = D;
1322 True = simplifyBinOp(Opcode, LHS, E, FMF, Q);
1323 False = simplifyBinOp(Opcode, LHS, F, FMF, Q);
1324 if (Value *NewSel = foldAddNegate(E, F, LHS))
1325 return NewSel;
1326 }
1327
1328 if (!True || !False)
1329 return nullptr;
1330
1331 Value *SI = Builder.CreateSelect(Cond, True, False);
1332 SI->takeName(&I);
1333 return SI;
1334}
1335
1336/// Freely adapt every user of V as-if V was changed to !V.
1337/// WARNING: only if canFreelyInvertAllUsersOf() said this can be done.
1339 assert(!isa<Constant>(I) && "Shouldn't invert users of constant");
1340 for (User *U : make_early_inc_range(I->users())) {
1341 if (U == IgnoredUser)
1342 continue; // Don't consider this user.
1343 switch (cast<Instruction>(U)->getOpcode()) {
1344 case Instruction::Select: {
1345 auto *SI = cast<SelectInst>(U);
1346 SI->swapValues();
1347 SI->swapProfMetadata();
1348 break;
1349 }
1350 case Instruction::Br:
1351 cast<BranchInst>(U)->swapSuccessors(); // swaps prof metadata too
1352 break;
1353 case Instruction::Xor:
1354 replaceInstUsesWith(cast<Instruction>(*U), I);
1355 // Add to worklist for DCE.
1356 addToWorklist(cast<Instruction>(U));
1357 break;
1358 default:
1359 llvm_unreachable("Got unexpected user - out of sync with "
1360 "canFreelyInvertAllUsersOf() ?");
1361 }
1362 }
1363}
1364
1365/// Given a 'sub' instruction, return the RHS of the instruction if the LHS is a
1366/// constant zero (which is the 'negate' form).
1367Value *InstCombinerImpl::dyn_castNegVal(Value *V) const {
1368 Value *NegV;
1369 if (match(V, m_Neg(m_Value(NegV))))
1370 return NegV;
1371
1372 // Constants can be considered to be negated values if they can be folded.
1373 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
1374 return ConstantExpr::getNeg(C);
1375
1376 if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V))
1377 if (C->getType()->getElementType()->isIntegerTy())
1378 return ConstantExpr::getNeg(C);
1379
1380 if (ConstantVector *CV = dyn_cast<ConstantVector>(V)) {
1381 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
1382 Constant *Elt = CV->getAggregateElement(i);
1383 if (!Elt)
1384 return nullptr;
1385
1386 if (isa<UndefValue>(Elt))
1387 continue;
1388
1389 if (!isa<ConstantInt>(Elt))
1390 return nullptr;
1391 }
1392 return ConstantExpr::getNeg(CV);
1393 }
1394
1395 // Negate integer vector splats.
1396 if (auto *CV = dyn_cast<Constant>(V))
1397 if (CV->getType()->isVectorTy() &&
1398 CV->getType()->getScalarType()->isIntegerTy() && CV->getSplatValue())
1399 return ConstantExpr::getNeg(CV);
1400
1401 return nullptr;
1402}
1403
1404/// A binop with a constant operand and a sign-extended boolean operand may be
1405/// converted into a select of constants by applying the binary operation to
1406/// the constant with the two possible values of the extended boolean (0 or -1).
1407Instruction *InstCombinerImpl::foldBinopOfSextBoolToSelect(BinaryOperator &BO) {
1408 // TODO: Handle non-commutative binop (constant is operand 0).
1409 // TODO: Handle zext.
1410 // TODO: Peek through 'not' of cast.
1411 Value *BO0 = BO.getOperand(0);
1412 Value *BO1 = BO.getOperand(1);
1413 Value *X;
1414 Constant *C;
1415 if (!match(BO0, m_SExt(m_Value(X))) || !match(BO1, m_ImmConstant(C)) ||
1416 !X->getType()->isIntOrIntVectorTy(1))
1417 return nullptr;
1418
1419 // bo (sext i1 X), C --> select X, (bo -1, C), (bo 0, C)
1422 Value *TVal = Builder.CreateBinOp(BO.getOpcode(), Ones, C);
1423 Value *FVal = Builder.CreateBinOp(BO.getOpcode(), Zero, C);
1424 return SelectInst::Create(X, TVal, FVal);
1425}
1426
1428 SelectInst *SI,
1429 bool IsTrueArm) {
1430 SmallVector<Constant *> ConstOps;
1431 for (Value *Op : I.operands()) {
1432 CmpInst::Predicate Pred;
1433 Constant *C = nullptr;
1434 if (Op == SI) {
1435 C = dyn_cast<Constant>(IsTrueArm ? SI->getTrueValue()
1436 : SI->getFalseValue());
1437 } else if (match(SI->getCondition(),
1438 m_ICmp(Pred, m_Specific(Op), m_Constant(C))) &&
1439 Pred == (IsTrueArm ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE) &&
1441 // Pass
1442 } else {
1443 C = dyn_cast<Constant>(Op);
1444 }
1445 if (C == nullptr)
1446 return nullptr;
1447
1448 ConstOps.push_back(C);
1449 }
1450
1451 return ConstantFoldInstOperands(&I, ConstOps, I.getModule()->getDataLayout());
1452}
1453
1455 Value *NewOp, InstCombiner &IC) {
1456 Instruction *Clone = I.clone();
1457 Clone->replaceUsesOfWith(SI, NewOp);
1458 IC.InsertNewInstBefore(Clone, SI->getIterator());
1459 return Clone;
1460}
1461
1463 bool FoldWithMultiUse) {
1464 // Don't modify shared select instructions unless set FoldWithMultiUse
1465 if (!SI->hasOneUse() && !FoldWithMultiUse)
1466 return nullptr;
1467
1468 Value *TV = SI->getTrueValue();
1469 Value *FV = SI->getFalseValue();
1470 if (!(isa<Constant>(TV) || isa<Constant>(FV)))
1471 return nullptr;
1472
1473 // Bool selects with constant operands can be folded to logical ops.
1474 if (SI->getType()->isIntOrIntVectorTy(1))
1475 return nullptr;
1476
1477 // Test if a FCmpInst instruction is used exclusively by a select as
1478 // part of a minimum or maximum operation. If so, refrain from doing
1479 // any other folding. This helps out other analyses which understand
1480 // non-obfuscated minimum and maximum idioms. And in this case, at
1481 // least one of the comparison operands has at least one user besides
1482 // the compare (the select), which would often largely negate the
1483 // benefit of folding anyway.
1484 if (auto *CI = dyn_cast<FCmpInst>(SI->getCondition())) {
1485 if (CI->hasOneUse()) {
1486 Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
1487 if ((TV == Op0 && FV == Op1) || (FV == Op0 && TV == Op1))
1488 return nullptr;
1489 }
1490 }
1491
1492 // Make sure that one of the select arms constant folds successfully.
1493 Value *NewTV = constantFoldOperationIntoSelectOperand(Op, SI, /*IsTrueArm*/ true);
1494 Value *NewFV = constantFoldOperationIntoSelectOperand(Op, SI, /*IsTrueArm*/ false);
1495 if (!NewTV && !NewFV)
1496 return nullptr;
1497
1498 // Create an instruction for the arm that did not fold.
1499 if (!NewTV)
1500 NewTV = foldOperationIntoSelectOperand(Op, SI, TV, *this);
1501 if (!NewFV)
1502 NewFV = foldOperationIntoSelectOperand(Op, SI, FV, *this);
1503 return SelectInst::Create(SI->getCondition(), NewTV, NewFV, "", nullptr, SI);
1504}
1505
1507 Value *InValue, BasicBlock *InBB,
1508 const DataLayout &DL,
1509 const SimplifyQuery SQ) {
1510 // NB: It is a precondition of this transform that the operands be
1511 // phi translatable! This is usually trivially satisfied by limiting it
1512 // to constant ops, and for selects we do a more sophisticated check.
1514 for (Value *Op : I.operands()) {
1515 if (Op == PN)
1516 Ops.push_back(InValue);
1517 else
1518 Ops.push_back(Op->DoPHITranslation(PN->getParent(), InBB));
1519 }
1520
1521 // Don't consider the simplification successful if we get back a constant
1522 // expression. That's just an instruction in hiding.
1523 // Also reject the case where we simplify back to the phi node. We wouldn't
1524 // be able to remove it in that case.
1526 &I, Ops, SQ.getWithInstruction(InBB->getTerminator()));
1527 if (NewVal && NewVal != PN && !match(NewVal, m_ConstantExpr()))
1528 return NewVal;
1529
1530 // Check if incoming PHI value can be replaced with constant
1531 // based on implied condition.
1532 BranchInst *TerminatorBI = dyn_cast<BranchInst>(InBB->getTerminator());
1533 const ICmpInst *ICmp = dyn_cast<ICmpInst>(&I);
1534 if (TerminatorBI && TerminatorBI->isConditional() &&
1535 TerminatorBI->getSuccessor(0) != TerminatorBI->getSuccessor(1) && ICmp) {
1536 bool LHSIsTrue = TerminatorBI->getSuccessor(0) == PN->getParent();
1537 std::optional<bool> ImpliedCond =
1538 isImpliedCondition(TerminatorBI->getCondition(), ICmp->getPredicate(),
1539 Ops[0], Ops[1], DL, LHSIsTrue);
1540 if (ImpliedCond)
1541 return ConstantInt::getBool(I.getType(), ImpliedCond.value());
1542 }
1543
1544 return nullptr;
1545}
1546
1548 unsigned NumPHIValues = PN->getNumIncomingValues();
1549 if (NumPHIValues == 0)
1550 return nullptr;
1551
1552 // We normally only transform phis with a single use. However, if a PHI has
1553 // multiple uses and they are all the same operation, we can fold *all* of the
1554 // uses into the PHI.
1555 if (!PN->hasOneUse()) {
1556 // Walk the use list for the instruction, comparing them to I.
1557 for (User *U : PN->users()) {
1558 Instruction *UI = cast<Instruction>(U);
1559 if (UI != &I && !I.isIdenticalTo(UI))
1560 return nullptr;
1561 }
1562 // Otherwise, we can replace *all* users with the new PHI we form.
1563 }
1564
1565 // Check to see whether the instruction can be folded into each phi operand.
1566 // If there is one operand that does not fold, remember the BB it is in.
1567 // If there is more than one or if *it* is a PHI, bail out.
1568 SmallVector<Value *> NewPhiValues;
1569 BasicBlock *NonSimplifiedBB = nullptr;
1570 Value *NonSimplifiedInVal = nullptr;
1571 for (unsigned i = 0; i != NumPHIValues; ++i) {
1572 Value *InVal = PN->getIncomingValue(i);
1573 BasicBlock *InBB = PN->getIncomingBlock(i);
1574
1575 if (auto *NewVal = simplifyInstructionWithPHI(I, PN, InVal, InBB, DL, SQ)) {
1576 NewPhiValues.push_back(NewVal);
1577 continue;
1578 }
1579
1580 if (NonSimplifiedBB) return nullptr; // More than one non-simplified value.
1581
1582 NonSimplifiedBB = InBB;
1583 NonSimplifiedInVal = InVal;
1584 NewPhiValues.push_back(nullptr);
1585
1586 // If the InVal is an invoke at the end of the pred block, then we can't
1587 // insert a computation after it without breaking the edge.
1588 if (isa<InvokeInst>(InVal))
1589 if (cast<Instruction>(InVal)->getParent() == NonSimplifiedBB)
1590 return nullptr;
1591
1592 // If the incoming non-constant value is reachable from the phis block,
1593 // we'll push the operation across a loop backedge. This could result in
1594 // an infinite combine loop, and is generally non-profitable (especially
1595 // if the operation was originally outside the loop).
1596 if (isPotentiallyReachable(PN->getParent(), NonSimplifiedBB, nullptr, &DT,
1597 LI))
1598 return nullptr;
1599 }
1600
1601 // If there is exactly one non-simplified value, we can insert a copy of the
1602 // operation in that block. However, if this is a critical edge, we would be
1603 // inserting the computation on some other paths (e.g. inside a loop). Only
1604 // do this if the pred block is unconditionally branching into the phi block.
1605 // Also, make sure that the pred block is not dead code.
1606 if (NonSimplifiedBB != nullptr) {
1607 BranchInst *BI = dyn_cast<BranchInst>(NonSimplifiedBB->getTerminator());
1608 if (!BI || !BI->isUnconditional() ||
1609 !DT.isReachableFromEntry(NonSimplifiedBB))
1610 return nullptr;
1611 }
1612
1613 // Okay, we can do the transformation: create the new PHI node.
1614 PHINode *NewPN = PHINode::Create(I.getType(), PN->getNumIncomingValues());
1615 InsertNewInstBefore(NewPN, PN->getIterator());
1616 NewPN->takeName(PN);
1617 NewPN->setDebugLoc(PN->getDebugLoc());
1618
1619 // If we are going to have to insert a new computation, do so right before the
1620 // predecessor's terminator.
1621 Instruction *Clone = nullptr;
1622 if (NonSimplifiedBB) {
1623 Clone = I.clone();
1624 for (Use &U : Clone->operands()) {
1625 if (U == PN)
1626 U = NonSimplifiedInVal;
1627 else
1628 U = U->DoPHITranslation(PN->getParent(), NonSimplifiedBB);
1629 }
1630 InsertNewInstBefore(Clone, NonSimplifiedBB->getTerminator()->getIterator());
1631 }
1632
1633 for (unsigned i = 0; i != NumPHIValues; ++i) {
1634 if (NewPhiValues[i])
1635 NewPN->addIncoming(NewPhiValues[i], PN->getIncomingBlock(i));
1636 else
1637 NewPN->addIncoming(Clone, PN->getIncomingBlock(i));
1638 }
1639
1640 for (User *U : make_early_inc_range(PN->users())) {
1641 Instruction *User = cast<Instruction>(U);
1642 if (User == &I) continue;
1643 replaceInstUsesWith(*User, NewPN);
1645 }
1646
1647 replaceAllDbgUsesWith(const_cast<PHINode &>(*PN),
1648 const_cast<PHINode &>(*NewPN),
1649 const_cast<PHINode &>(*PN), DT);
1650 return replaceInstUsesWith(I, NewPN);
1651}
1652
1654 // TODO: This should be similar to the incoming values check in foldOpIntoPhi:
1655 // we are guarding against replicating the binop in >1 predecessor.
1656 // This could miss matching a phi with 2 constant incoming values.
1657 auto *Phi0 = dyn_cast<PHINode>(BO.getOperand(0));
1658 auto *Phi1 = dyn_cast<PHINode>(BO.getOperand(1));
1659 if (!Phi0 || !Phi1 || !Phi0->hasOneUse() || !Phi1->hasOneUse() ||
1660 Phi0->getNumOperands() != Phi1->getNumOperands())
1661 return nullptr;
1662
1663 // TODO: Remove the restriction for binop being in the same block as the phis.
1664 if (BO.getParent() != Phi0->getParent() ||
1665 BO.getParent() != Phi1->getParent())
1666 return nullptr;
1667
1668 // Fold if there is at least one specific constant value in phi0 or phi1's
1669 // incoming values that comes from the same block and this specific constant
1670 // value can be used to do optimization for specific binary operator.
1671 // For example:
1672 // %phi0 = phi i32 [0, %bb0], [%i, %bb1]
1673 // %phi1 = phi i32 [%j, %bb0], [0, %bb1]
1674 // %add = add i32 %phi0, %phi1
1675 // ==>
1676 // %add = phi i32 [%j, %bb0], [%i, %bb1]
1678 /*AllowRHSConstant*/ false);
1679 if (C) {
1680 SmallVector<Value *, 4> NewIncomingValues;
1681 auto CanFoldIncomingValuePair = [&](std::tuple<Use &, Use &> T) {
1682 auto &Phi0Use = std::get<0>(T);
1683 auto &Phi1Use = std::get<1>(T);
1684 if (Phi0->getIncomingBlock(Phi0Use) != Phi1->getIncomingBlock(Phi1Use))
1685 return false;
1686 Value *Phi0UseV = Phi0Use.get();
1687 Value *Phi1UseV = Phi1Use.get();
1688 if (Phi0UseV == C)
1689 NewIncomingValues.push_back(Phi1UseV);
1690 else if (Phi1UseV == C)
1691 NewIncomingValues.push_back(Phi0UseV);
1692 else
1693 return false;
1694 return true;
1695 };
1696
1697 if (all_of(zip(Phi0->operands(), Phi1->operands()),
1698 CanFoldIncomingValuePair)) {
1699 PHINode *NewPhi =
1700 PHINode::Create(Phi0->getType(), Phi0->getNumOperands());
1701 assert(NewIncomingValues.size() == Phi0->getNumOperands() &&
1702 "The number of collected incoming values should equal the number "
1703 "of the original PHINode operands!");
1704 for (unsigned I = 0; I < Phi0->getNumOperands(); I++)
1705 NewPhi->addIncoming(NewIncomingValues[I], Phi0->getIncomingBlock(I));
1706 return NewPhi;
1707 }
1708 }
1709
1710 if (Phi0->getNumOperands() != 2 || Phi1->getNumOperands() != 2)
1711 return nullptr;
1712
1713 // Match a pair of incoming constants for one of the predecessor blocks.
1714 BasicBlock *ConstBB, *OtherBB;
1715 Constant *C0, *C1;
1716 if (match(Phi0->getIncomingValue(0), m_ImmConstant(C0))) {
1717 ConstBB = Phi0->getIncomingBlock(0);
1718 OtherBB = Phi0->getIncomingBlock(1);
1719 } else if (match(Phi0->getIncomingValue(1), m_ImmConstant(C0))) {
1720 ConstBB = Phi0->getIncomingBlock(1);
1721 OtherBB = Phi0->getIncomingBlock(0);
1722 } else {
1723 return nullptr;
1724 }
1725 if (!match(Phi1->getIncomingValueForBlock(ConstBB), m_ImmConstant(C1)))
1726 return nullptr;
1727
1728 // The block that we are hoisting to must reach here unconditionally.
1729 // Otherwise, we could be speculatively executing an expensive or
1730 // non-speculative op.
1731 auto *PredBlockBranch = dyn_cast<BranchInst>(OtherBB->getTerminator());
1732 if (!PredBlockBranch || PredBlockBranch->isConditional() ||
1733 !DT.isReachableFromEntry(OtherBB))
1734 return nullptr;
1735
1736 // TODO: This check could be tightened to only apply to binops (div/rem) that
1737 // are not safe to speculatively execute. But that could allow hoisting
1738 // potentially expensive instructions (fdiv for example).
1739 for (auto BBIter = BO.getParent()->begin(); &*BBIter != &BO; ++BBIter)
1741 return nullptr;
1742
1743 // Fold constants for the predecessor block with constant incoming values.
1744 Constant *NewC = ConstantFoldBinaryOpOperands(BO.getOpcode(), C0, C1, DL);
1745 if (!NewC)
1746 return nullptr;
1747
1748 // Make a new binop in the predecessor block with the non-constant incoming
1749 // values.
1750 Builder.SetInsertPoint(PredBlockBranch);
1751 Value *NewBO = Builder.CreateBinOp(BO.getOpcode(),
1752 Phi0->getIncomingValueForBlock(OtherBB),
1753 Phi1->getIncomingValueForBlock(OtherBB));
1754 if (auto *NotFoldedNewBO = dyn_cast<BinaryOperator>(NewBO))
1755 NotFoldedNewBO->copyIRFlags(&BO);
1756
1757 // Replace the binop with a phi of the new values. The old phis are dead.
1758 PHINode *NewPhi = PHINode::Create(BO.getType(), 2);
1759 NewPhi->addIncoming(NewBO, OtherBB);
1760 NewPhi->addIncoming(NewC, ConstBB);
1761 return NewPhi;
1762}
1763
1765 if (!isa<Constant>(I.getOperand(1)))
1766 return nullptr;
1767
1768 if (auto *Sel = dyn_cast<SelectInst>(I.getOperand(0))) {
1769 if (Instruction *NewSel = FoldOpIntoSelect(I, Sel))
1770 return NewSel;
1771 } else if (auto *PN = dyn_cast<PHINode>(I.getOperand(0))) {
1772 if (Instruction *NewPhi = foldOpIntoPhi(I, PN))
1773 return NewPhi;
1774 }
1775 return nullptr;
1776}
1777
1779 // If this GEP has only 0 indices, it is the same pointer as
1780 // Src. If Src is not a trivial GEP too, don't combine
1781 // the indices.
1782 if (GEP.hasAllZeroIndices() && !Src.hasAllZeroIndices() &&
1783 !Src.hasOneUse())
1784 return false;
1785 return true;
1786}
1787
1789 if (!isa<VectorType>(Inst.getType()))
1790 return nullptr;
1791
1792 BinaryOperator::BinaryOps Opcode = Inst.getOpcode();
1793 Value *LHS = Inst.getOperand(0), *RHS = Inst.getOperand(1);
1794 assert(cast<VectorType>(LHS->getType())->getElementCount() ==
1795 cast<VectorType>(Inst.getType())->getElementCount());
1796 assert(cast<VectorType>(RHS->getType())->getElementCount() ==
1797 cast<VectorType>(Inst.getType())->getElementCount());
1798
1799 // If both operands of the binop are vector concatenations, then perform the
1800 // narrow binop on each pair of the source operands followed by concatenation
1801 // of the results.
1802 Value *L0, *L1, *R0, *R1;
1803 ArrayRef<int> Mask;
1804 if (match(LHS, m_Shuffle(m_Value(L0), m_Value(L1), m_Mask(Mask))) &&
1805 match(RHS, m_Shuffle(m_Value(R0), m_Value(R1), m_SpecificMask(Mask))) &&
1806 LHS->hasOneUse() && RHS->hasOneUse() &&
1807 cast<ShuffleVectorInst>(LHS)->isConcat() &&
1808 cast<ShuffleVectorInst>(RHS)->isConcat()) {
1809 // This transform does not have the speculative execution constraint as
1810 // below because the shuffle is a concatenation. The new binops are
1811 // operating on exactly the same elements as the existing binop.
1812 // TODO: We could ease the mask requirement to allow different undef lanes,
1813 // but that requires an analysis of the binop-with-undef output value.
1814 Value *NewBO0 = Builder.CreateBinOp(Opcode, L0, R0);
1815 if (auto *BO = dyn_cast<BinaryOperator>(NewBO0))
1816 BO->copyIRFlags(&Inst);
1817 Value *NewBO1 = Builder.CreateBinOp(Opcode, L1, R1);
1818 if (auto *BO = dyn_cast<BinaryOperator>(NewBO1))
1819 BO->copyIRFlags(&Inst);
1820 return new ShuffleVectorInst(NewBO0, NewBO1, Mask);
1821 }
1822
1823 auto createBinOpReverse = [&](Value *X, Value *Y) {
1824 Value *V = Builder.CreateBinOp(Opcode, X, Y, Inst.getName());
1825 if (auto *BO = dyn_cast<BinaryOperator>(V))
1826 BO->copyIRFlags(&Inst);
1827 Module *M = Inst.getModule();
1829 M, Intrinsic::experimental_vector_reverse, V->getType());
1830 return CallInst::Create(F, V);
1831 };
1832
1833 // NOTE: Reverse shuffles don't require the speculative execution protection
1834 // below because they don't affect which lanes take part in the computation.
1835
1836 Value *V1, *V2;
1837 if (match(LHS, m_VecReverse(m_Value(V1)))) {
1838 // Op(rev(V1), rev(V2)) -> rev(Op(V1, V2))
1839 if (match(RHS, m_VecReverse(m_Value(V2))) &&
1840 (LHS->hasOneUse() || RHS->hasOneUse() ||
1841 (LHS == RHS && LHS->hasNUses(2))))
1842 return createBinOpReverse(V1, V2);
1843
1844 // Op(rev(V1), RHSSplat)) -> rev(Op(V1, RHSSplat))
1845 if (LHS->hasOneUse() && isSplatValue(RHS))
1846 return createBinOpReverse(V1, RHS);
1847 }
1848 // Op(LHSSplat, rev(V2)) -> rev(Op(LHSSplat, V2))
1849 else if (isSplatValue(LHS) && match(RHS, m_OneUse(m_VecReverse(m_Value(V2)))))
1850 return createBinOpReverse(LHS, V2);
1851
1852 // It may not be safe to reorder shuffles and things like div, urem, etc.
1853 // because we may trap when executing those ops on unknown vector elements.
1854 // See PR20059.
1855 if (!isSafeToSpeculativelyExecute(&Inst))
1856 return nullptr;
1857
1858 auto createBinOpShuffle = [&](Value *X, Value *Y, ArrayRef<int> M) {
1859 Value *XY = Builder.CreateBinOp(Opcode, X, Y);
1860 if (auto *BO = dyn_cast<BinaryOperator>(XY))
1861 BO->copyIRFlags(&Inst);
1862 return new ShuffleVectorInst(XY, M);
1863 };
1864
1865 // If both arguments of the binary operation are shuffles that use the same
1866 // mask and shuffle within a single vector, move the shuffle after the binop.
1867 if (match(LHS, m_Shuffle(m_Value(V1), m_Poison(), m_Mask(Mask))) &&
1868 match(RHS, m_Shuffle(m_Value(V2), m_Poison(), m_SpecificMask(Mask))) &&
1869 V1->getType() == V2->getType() &&
1870 (LHS->hasOneUse() || RHS->hasOneUse() || LHS == RHS)) {
1871 // Op(shuffle(V1, Mask), shuffle(V2, Mask)) -> shuffle(Op(V1, V2), Mask)
1872 return createBinOpShuffle(V1, V2, Mask);
1873 }
1874
1875 // If both arguments of a commutative binop are select-shuffles that use the
1876 // same mask with commuted operands, the shuffles are unnecessary.
1877 if (Inst.isCommutative() &&
1878 match(LHS, m_Shuffle(m_Value(V1), m_Value(V2), m_Mask(Mask))) &&
1879 match(RHS,
1880 m_Shuffle(m_Specific(V2), m_Specific(V1), m_SpecificMask(Mask)))) {
1881 auto *LShuf = cast<ShuffleVectorInst>(LHS);
1882 auto *RShuf = cast<ShuffleVectorInst>(RHS);
1883 // TODO: Allow shuffles that contain undefs in the mask?
1884 // That is legal, but it reduces undef knowledge.
1885 // TODO: Allow arbitrary shuffles by shuffling after binop?
1886 // That might be legal, but we have to deal with poison.
1887 if (LShuf->isSelect() &&
1888 !is_contained(LShuf->getShuffleMask(), PoisonMaskElem) &&
1889 RShuf->isSelect() &&
1890 !is_contained(RShuf->getShuffleMask(), PoisonMaskElem)) {
1891 // Example:
1892 // LHS = shuffle V1, V2, <0, 5, 6, 3>
1893 // RHS = shuffle V2, V1, <0, 5, 6, 3>
1894 // LHS + RHS --> (V10+V20, V21+V11, V22+V12, V13+V23) --> V1 + V2
1895 Instruction *NewBO = BinaryOperator::Create(Opcode, V1, V2);
1896 NewBO->copyIRFlags(&Inst);
1897 return NewBO;
1898 }
1899 }
1900
1901 // If one argument is a shuffle within one vector and the other is a constant,
1902 // try moving the shuffle after the binary operation. This canonicalization
1903 // intends to move shuffles closer to other shuffles and binops closer to
1904 // other binops, so they can be folded. It may also enable demanded elements
1905 // transforms.
1906 Constant *C;
1907 auto *InstVTy = dyn_cast<FixedVectorType>(Inst.getType());
1908 if (InstVTy &&
1910 m_Mask(Mask))),
1911 m_ImmConstant(C))) &&
1912 cast<FixedVectorType>(V1->getType())->getNumElements() <=
1913 InstVTy->getNumElements()) {
1914 assert(InstVTy->getScalarType() == V1->getType()->getScalarType() &&
1915 "Shuffle should not change scalar type");
1916
1917 // Find constant NewC that has property:
1918 // shuffle(NewC, ShMask) = C
1919 // If such constant does not exist (example: ShMask=<0,0> and C=<1,2>)
1920 // reorder is not possible. A 1-to-1 mapping is not required. Example:
1921 // ShMask = <1,1,2,2> and C = <5,5,6,6> --> NewC = <undef,5,6,undef>
1922 bool ConstOp1 = isa<Constant>(RHS);
1923 ArrayRef<int> ShMask = Mask;
1924 unsigned SrcVecNumElts =
1925 cast<FixedVectorType>(V1->getType())->getNumElements();
1926 PoisonValue *PoisonScalar = PoisonValue::get(C->getType()->getScalarType());
1927 SmallVector<Constant *, 16> NewVecC(SrcVecNumElts, PoisonScalar);
1928 bool MayChange = true;
1929 unsigned NumElts = InstVTy->getNumElements();
1930 for (unsigned I = 0; I < NumElts; ++I) {
1931 Constant *CElt = C->getAggregateElement(I);
1932 if (ShMask[I] >= 0) {
1933 assert(ShMask[I] < (int)NumElts && "Not expecting narrowing shuffle");
1934 Constant *NewCElt = NewVecC[ShMask[I]];
1935 // Bail out if:
1936 // 1. The constant vector contains a constant expression.
1937 // 2. The shuffle needs an element of the constant vector that can't
1938 // be mapped to a new constant vector.
1939 // 3. This is a widening shuffle that copies elements of V1 into the
1940 // extended elements (extending with poison is allowed).
1941 if (!CElt || (!isa<PoisonValue>(NewCElt) && NewCElt != CElt) ||
1942 I >= SrcVecNumElts) {
1943 MayChange = false;
1944 break;
1945 }
1946 NewVecC[ShMask[I]] = CElt;
1947 }
1948 // If this is a widening shuffle, we must be able to extend with poison
1949 // elements. If the original binop does not produce a poison in the high
1950 // lanes, then this transform is not safe.
1951 // Similarly for poison lanes due to the shuffle mask, we can only
1952 // transform binops that preserve poison.
1953 // TODO: We could shuffle those non-poison constant values into the
1954 // result by using a constant vector (rather than an poison vector)
1955 // as operand 1 of the new binop, but that might be too aggressive
1956 // for target-independent shuffle creation.
1957 if (I >= SrcVecNumElts || ShMask[I] < 0) {
1958 Constant *MaybePoison =
1959 ConstOp1
1960 ? ConstantFoldBinaryOpOperands(Opcode, PoisonScalar, CElt, DL)
1961 : ConstantFoldBinaryOpOperands(Opcode, CElt, PoisonScalar, DL);
1962 if (!MaybePoison || !isa<PoisonValue>(MaybePoison)) {
1963 MayChange = false;
1964 break;
1965 }
1966 }
1967 }
1968 if (MayChange) {
1969 Constant *NewC = ConstantVector::get(NewVecC);
1970 // It may not be safe to execute a binop on a vector with poison elements
1971 // because the entire instruction can be folded to undef or create poison
1972 // that did not exist in the original code.
1973 // TODO: The shift case should not be necessary.
1974 if (Inst.isIntDivRem() || (Inst.isShift() && ConstOp1))
1975 NewC = getSafeVectorConstantForBinop(Opcode, NewC, ConstOp1);
1976
1977 // Op(shuffle(V1, Mask), C) -> shuffle(Op(V1, NewC), Mask)
1978 // Op(C, shuffle(V1, Mask)) -> shuffle(Op(NewC, V1), Mask)
1979 Value *NewLHS = ConstOp1 ? V1 : NewC;
1980 Value *NewRHS = ConstOp1 ? NewC : V1;
1981 return createBinOpShuffle(NewLHS, NewRHS, Mask);
1982 }
1983 }
1984
1985 // Try to reassociate to sink a splat shuffle after a binary operation.
1986 if (Inst.isAssociative() && Inst.isCommutative()) {
1987 // Canonicalize shuffle operand as LHS.
1988 if (isa<ShuffleVectorInst>(RHS))
1989 std::swap(LHS, RHS);
1990
1991 Value *X;
1992 ArrayRef<int> MaskC;
1993 int SplatIndex;
1994 Value *Y, *OtherOp;
1995 if (!match(LHS,
1996 m_OneUse(m_Shuffle(m_Value(X), m_Undef(), m_Mask(MaskC)))) ||
1997 !match(MaskC, m_SplatOrUndefMask(SplatIndex)) ||
1998 X->getType() != Inst.getType() ||
1999 !match(RHS, m_OneUse(m_BinOp(Opcode, m_Value(Y), m_Value(OtherOp)))))
2000 return nullptr;
2001
2002 // FIXME: This may not be safe if the analysis allows undef elements. By
2003 // moving 'Y' before the splat shuffle, we are implicitly assuming
2004 // that it is not undef/poison at the splat index.
2005 if (isSplatValue(OtherOp, SplatIndex)) {
2006 std::swap(Y, OtherOp);
2007 } else if (!isSplatValue(Y, SplatIndex)) {
2008 return nullptr;
2009 }
2010
2011 // X and Y are splatted values, so perform the binary operation on those
2012 // values followed by a splat followed by the 2nd binary operation:
2013 // bo (splat X), (bo Y, OtherOp) --> bo (splat (bo X, Y)), OtherOp
2014 Value *NewBO = Builder.CreateBinOp(Opcode, X, Y);
2015 SmallVector<int, 8> NewMask(MaskC.size(), SplatIndex);
2016 Value *NewSplat = Builder.CreateShuffleVector(NewBO, NewMask);
2017 Instruction *R = BinaryOperator::Create(Opcode, NewSplat, OtherOp);
2018
2019 // Intersect FMF on both new binops. Other (poison-generating) flags are
2020 // dropped to be safe.
2021 if (isa<FPMathOperator>(R)) {
2022 R->copyFastMathFlags(&Inst);
2023 R->andIRFlags(RHS);
2024 }
2025 if (auto *NewInstBO = dyn_cast<BinaryOperator>(NewBO))
2026 NewInstBO->copyIRFlags(R);
2027 return R;
2028 }
2029
2030 return nullptr;
2031}
2032
2033/// Try to narrow the width of a binop if at least 1 operand is an extend of
2034/// of a value. This requires a potentially expensive known bits check to make
2035/// sure the narrow op does not overflow.
2036Instruction *InstCombinerImpl::narrowMathIfNoOverflow(BinaryOperator &BO) {
2037 // We need at least one extended operand.
2038 Value *Op0 = BO.getOperand(0), *Op1 = BO.getOperand(1);
2039
2040 // If this is a sub, we swap the operands since we always want an extension
2041 // on the RHS. The LHS can be an extension or a constant.
2042 if (BO.getOpcode() == Instruction::Sub)
2043 std::swap(Op0, Op1);
2044
2045 Value *X;
2046 bool IsSext = match(Op0, m_SExt(m_Value(X)));
2047 if (!IsSext && !match(Op0, m_ZExt(m_Value(X))))
2048 return nullptr;
2049
2050 // If both operands are the same extension from the same source type and we
2051 // can eliminate at least one (hasOneUse), this might work.
2052 CastInst::CastOps CastOpc = IsSext ? Instruction::SExt : Instruction::ZExt;
2053 Value *Y;
2054 if (!(match(Op1, m_ZExtOrSExt(m_Value(Y))) && X->getType() == Y->getType() &&
2055 cast<Operator>(Op1)->getOpcode() == CastOpc &&
2056 (Op0->hasOneUse() || Op1->hasOneUse()))) {
2057 // If that did not match, see if we have a suitable constant operand.
2058 // Truncating and extending must produce the same constant.
2059 Constant *WideC;
2060 if (!Op0->hasOneUse() || !match(Op1, m_Constant(WideC)))
2061 return nullptr;
2062 Constant *NarrowC = getLosslessTrunc(WideC, X->getType(), CastOpc);
2063 if (!NarrowC)
2064 return nullptr;
2065 Y = NarrowC;
2066 }
2067
2068 // Swap back now that we found our operands.
2069 if (BO.getOpcode() == Instruction::Sub)
2070 std::swap(X, Y);
2071
2072 // Both operands have narrow versions. Last step: the math must not overflow
2073 // in the narrow width.
2074 if (!willNotOverflow(BO.getOpcode(), X, Y, BO, IsSext))
2075 return nullptr;
2076
2077 // bo (ext X), (ext Y) --> ext (bo X, Y)
2078 // bo (ext X), C --> ext (bo X, C')
2079 Value *NarrowBO = Builder.CreateBinOp(BO.getOpcode(), X, Y, "narrow");
2080 if (auto *NewBinOp = dyn_cast<BinaryOperator>(NarrowBO)) {
2081 if (IsSext)
2082 NewBinOp->setHasNoSignedWrap();
2083 else
2084 NewBinOp->setHasNoUnsignedWrap();
2085 }
2086 return CastInst::Create(CastOpc, NarrowBO, BO.getType());
2087}
2088
2090 // At least one GEP must be inbounds.
2091 if (!GEP1.isInBounds() && !GEP2.isInBounds())
2092 return false;
2093
2094 return (GEP1.isInBounds() || GEP1.hasAllZeroIndices()) &&
2095 (GEP2.isInBounds() || GEP2.hasAllZeroIndices());
2096}
2097
2098/// Thread a GEP operation with constant indices through the constant true/false
2099/// arms of a select.
2101 InstCombiner::BuilderTy &Builder) {
2102 if (!GEP.hasAllConstantIndices())
2103 return nullptr;
2104
2105 Instruction *Sel;
2106 Value *Cond;
2107 Constant *TrueC, *FalseC;
2108 if (!match(GEP.getPointerOperand(), m_Instruction(Sel)) ||
2109 !match(Sel,
2110 m_Select(m_Value(Cond), m_Constant(TrueC), m_Constant(FalseC))))
2111 return nullptr;
2112
2113 // gep (select Cond, TrueC, FalseC), IndexC --> select Cond, TrueC', FalseC'
2114 // Propagate 'inbounds' and metadata from existing instructions.
2115 // Note: using IRBuilder to create the constants for efficiency.
2116 SmallVector<Value *, 4> IndexC(GEP.indices());
2117 bool IsInBounds = GEP.isInBounds();
2118 Type *Ty = GEP.getSourceElementType();
2119 Value *NewTrueC = Builder.CreateGEP(Ty, TrueC, IndexC, "", IsInBounds);
2120 Value *NewFalseC = Builder.CreateGEP(Ty, FalseC, IndexC, "", IsInBounds);
2121 return SelectInst::Create(Cond, NewTrueC, NewFalseC, "", nullptr, Sel);
2122}
2123
2125 GEPOperator *Src) {
2126 // Combine Indices - If the source pointer to this getelementptr instruction
2127 // is a getelementptr instruction with matching element type, combine the
2128 // indices of the two getelementptr instructions into a single instruction.
2129 if (!shouldMergeGEPs(*cast<GEPOperator>(&GEP), *Src))
2130 return nullptr;
2131
2132 // For constant GEPs, use a more general offset-based folding approach.
2133 Type *PtrTy = Src->getType()->getScalarType();
2134 if (GEP.hasAllConstantIndices() &&
2135 (Src->hasOneUse() || Src->hasAllConstantIndices())) {
2136 // Split Src into a variable part and a constant suffix.
2138 Type *BaseType = GTI.getIndexedType();
2139 bool IsFirstType = true;
2140 unsigned NumVarIndices = 0;
2141 for (auto Pair : enumerate(Src->indices())) {
2142 if (!isa<ConstantInt>(Pair.value())) {
2143 BaseType = GTI.getIndexedType();
2144 IsFirstType = false;
2145 NumVarIndices = Pair.index() + 1;
2146 }
2147 ++GTI;
2148 }
2149
2150 // Determine the offset for the constant suffix of Src.
2152 if (NumVarIndices != Src->getNumIndices()) {
2153 // FIXME: getIndexedOffsetInType() does not handled scalable vectors.
2154 if (BaseType->isScalableTy())
2155 return nullptr;
2156
2157 SmallVector<Value *> ConstantIndices;
2158 if (!IsFirstType)
2159 ConstantIndices.push_back(
2161 append_range(ConstantIndices, drop_begin(Src->indices(), NumVarIndices));
2162 Offset += DL.getIndexedOffsetInType(BaseType, ConstantIndices);
2163 }
2164
2165 // Add the offset for GEP (which is fully constant).
2166 if (!GEP.accumulateConstantOffset(DL, Offset))
2167 return nullptr;
2168
2169 APInt OffsetOld = Offset;
2170 // Convert the total offset back into indices.
2171 SmallVector<APInt> ConstIndices =
2173 if (!Offset.isZero() || (!IsFirstType && !ConstIndices[0].isZero())) {
2174 // If both GEP are constant-indexed, and cannot be merged in either way,
2175 // convert them to a GEP of i8.
2176 if (Src->hasAllConstantIndices())
2177 return replaceInstUsesWith(
2179 Builder.getInt8Ty(), Src->getOperand(0),
2180 Builder.getInt(OffsetOld), "",
2181 isMergedGEPInBounds(*Src, *cast<GEPOperator>(&GEP))));
2182 return nullptr;
2183 }
2184
2185 bool IsInBounds = isMergedGEPInBounds(*Src, *cast<GEPOperator>(&GEP));
2186 SmallVector<Value *> Indices;
2187 append_range(Indices, drop_end(Src->indices(),
2188 Src->getNumIndices() - NumVarIndices));
2189 for (const APInt &Idx : drop_begin(ConstIndices, !IsFirstType)) {
2190 Indices.push_back(ConstantInt::get(GEP.getContext(), Idx));
2191 // Even if the total offset is inbounds, we may end up representing it
2192 // by first performing a larger negative offset, and then a smaller
2193 // positive one. The large negative offset might go out of bounds. Only
2194 // preserve inbounds if all signs are the same.
2195 IsInBounds &= Idx.isNonNegative() == ConstIndices[0].isNonNegative();
2196 }
2197
2198 return replaceInstUsesWith(
2199 GEP, Builder.CreateGEP(Src->getSourceElementType(), Src->getOperand(0),
2200 Indices, "", IsInBounds));
2201 }
2202
2203 if (Src->getResultElementType() != GEP.getSourceElementType())
2204 return nullptr;
2205
2206 SmallVector<Value*, 8> Indices;
2207
2208 // Find out whether the last index in the source GEP is a sequential idx.
2209 bool EndsWithSequential = false;
2210 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
2211 I != E; ++I)
2212 EndsWithSequential = I.isSequential();
2213
2214 // Can we combine the two pointer arithmetics offsets?
2215 if (EndsWithSequential) {
2216 // Replace: gep (gep %P, long B), long A, ...
2217 // With: T = long A+B; gep %P, T, ...
2218 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
2219 Value *GO1 = GEP.getOperand(1);
2220
2221 // If they aren't the same type, then the input hasn't been processed
2222 // by the loop above yet (which canonicalizes sequential index types to
2223 // intptr_t). Just avoid transforming this until the input has been
2224 // normalized.
2225 if (SO1->getType() != GO1->getType())
2226 return nullptr;
2227
2228 Value *Sum =
2229 simplifyAddInst(GO1, SO1, false, false, SQ.getWithInstruction(&GEP));
2230 // Only do the combine when we are sure the cost after the
2231 // merge is never more than that before the merge.
2232 if (Sum == nullptr)
2233 return nullptr;
2234
2235 // Update the GEP in place if possible.
2236 if (Src->getNumOperands() == 2) {
2237 GEP.setIsInBounds(isMergedGEPInBounds(*Src, *cast<GEPOperator>(&GEP)));
2238 replaceOperand(GEP, 0, Src->getOperand(0));
2239 replaceOperand(GEP, 1, Sum);
2240 return &GEP;
2241 }
2242 Indices.append(Src->op_begin()+1, Src->op_end()-1);
2243 Indices.push_back(Sum);
2244 Indices.append(GEP.op_begin()+2, GEP.op_end());
2245 } else if (isa<Constant>(*GEP.idx_begin()) &&
2246 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
2247 Src->getNumOperands() != 1) {
2248 // Otherwise we can do the fold if the first index of the GEP is a zero
2249 Indices.append(Src->op_begin()+1, Src->op_end());
2250 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
2251 }
2252
2253 if (!Indices.empty())
2254 return replaceInstUsesWith(
2256 Src->getSourceElementType(), Src->getOperand(0), Indices, "",
2257 isMergedGEPInBounds(*Src, *cast<GEPOperator>(&GEP))));
2258
2259 return nullptr;
2260}
2261
2263 BuilderTy *Builder,
2264 bool &DoesConsume, unsigned Depth) {
2265 static Value *const NonNull = reinterpret_cast<Value *>(uintptr_t(1));
2266 // ~(~(X)) -> X.
2267 Value *A, *B;
2268 if (match(V, m_Not(m_Value(A)))) {
2269 DoesConsume = true;
2270 return A;
2271 }
2272
2273 Constant *C;
2274 // Constants can be considered to be not'ed values.
2275 if (match(V, m_ImmConstant(C)))
2276 return ConstantExpr::getNot(C);
2277
2279 return nullptr;
2280
2281 // The rest of the cases require that we invert all uses so don't bother
2282 // doing the analysis if we know we can't use the result.
2283 if (!WillInvertAllUses)
2284 return nullptr;
2285
2286 // Compares can be inverted if all of their uses are being modified to use
2287 // the ~V.
2288 if (auto *I = dyn_cast<CmpInst>(V)) {
2289 if (Builder != nullptr)
2290 return Builder->CreateCmp(I->getInversePredicate(), I->getOperand(0),
2291 I->getOperand(1));
2292 return NonNull;
2293 }
2294
2295 // If `V` is of the form `A + B` then `-1 - V` can be folded into
2296 // `(-1 - B) - A` if we are willing to invert all of the uses.
2297 if (match(V, m_Add(m_Value(A), m_Value(B)))) {
2298 if (auto *BV = getFreelyInvertedImpl(B, B->hasOneUse(), Builder,
2299 DoesConsume, Depth))
2300 return Builder ? Builder->CreateSub(BV, A) : NonNull;
2301 if (auto *AV = getFreelyInvertedImpl(A, A->hasOneUse(), Builder,
2302 DoesConsume, Depth))
2303 return Builder ? Builder->CreateSub(AV, B) : NonNull;
2304 return nullptr;
2305 }
2306
2307 // If `V` is of the form `A ^ ~B` then `~(A ^ ~B)` can be folded
2308 // into `A ^ B` if we are willing to invert all of the uses.
2309 if (match(V, m_Xor(m_Value(A), m_Value(B)))) {
2310 if (auto *BV = getFreelyInvertedImpl(B, B->hasOneUse(), Builder,
2311 DoesConsume, Depth))
2312 return Builder ? Builder->CreateXor(A, BV) : NonNull;
2313 if (auto *AV = getFreelyInvertedImpl(A, A->hasOneUse(), Builder,
2314 DoesConsume, Depth))
2315 return Builder ? Builder->CreateXor(AV, B) : NonNull;
2316 return nullptr;
2317 }
2318
2319 // If `V` is of the form `B - A` then `-1 - V` can be folded into
2320 // `A + (-1 - B)` if we are willing to invert all of the uses.
2321 if (match(V, m_Sub(m_Value(A), m_Value(B)))) {
2322 if (auto *AV = getFreelyInvertedImpl(A, A->hasOneUse(), Builder,
2323 DoesConsume, Depth))
2324 return Builder ? Builder->CreateAdd(AV, B) : NonNull;
2325 return nullptr;
2326 }
2327
2328 // If `V` is of the form `(~A) s>> B` then `~((~A) s>> B)` can be folded
2329 // into `A s>> B` if we are willing to invert all of the uses.
2330 if (match(V, m_AShr(m_Value(A), m_Value(B)))) {
2331 if (auto *AV = getFreelyInvertedImpl(A, A->hasOneUse(), Builder,
2332 DoesConsume, Depth))
2333 return Builder ? Builder->CreateAShr(AV, B) : NonNull;
2334 return nullptr;
2335 }
2336
2337 Value *Cond;
2338 // LogicOps are special in that we canonicalize them at the cost of an
2339 // instruction.
2340 bool IsSelect = match(V, m_Select(m_Value(Cond), m_Value(A), m_Value(B))) &&
2341 !shouldAvoidAbsorbingNotIntoSelect(*cast<SelectInst>(V));
2342 // Selects/min/max with invertible operands are freely invertible
2343 if (IsSelect || match(V, m_MaxOrMin(m_Value(A), m_Value(B)))) {
2344 if (!getFreelyInvertedImpl(B, B->hasOneUse(), /*Builder*/ nullptr,
2345 DoesConsume, Depth))
2346 return nullptr;
2347 if (Value *NotA = getFreelyInvertedImpl(A, A->hasOneUse(), Builder,
2348 DoesConsume, Depth)) {
2349 if (Builder != nullptr) {
2350 Value *NotB = getFreelyInvertedImpl(B, B->hasOneUse(), Builder,
2351 DoesConsume, Depth);
2352 assert(NotB != nullptr &&
2353 "Unable to build inverted value for known freely invertable op");
2354 if (auto *II = dyn_cast<IntrinsicInst>(V))
2356 getInverseMinMaxIntrinsic(II->getIntrinsicID()), NotA, NotB);
2357 return Builder->CreateSelect(Cond, NotA, NotB);
2358 }
2359 return NonNull;
2360 }
2361 }
2362
2363 if (PHINode *PN = dyn_cast<PHINode>(V)) {
2365 for (Use &U : PN->operands()) {
2366 BasicBlock *IncomingBlock = PN->getIncomingBlock(U);
2367 Value *NewIncomingVal = getFreelyInvertedImpl(
2368 U.get(), /*WillInvertAllUses=*/false,
2369 /*Builder=*/nullptr, DoesConsume, MaxAnalysisRecursionDepth - 1);
2370 if (NewIncomingVal == nullptr)
2371 return nullptr;
2372 // Make sure that we can safely erase the original PHI node.
2373 if (NewIncomingVal == V)
2374 return nullptr;
2375 if (Builder != nullptr)
2376 IncomingValues.emplace_back(NewIncomingVal, IncomingBlock);
2377 }
2378 if (Builder != nullptr) {
2381 PHINode *NewPN =
2382 Builder->CreatePHI(PN->getType(), PN->getNumIncomingValues());
2383 for (auto [Val, Pred] : IncomingValues)
2384 NewPN->addIncoming(Val, Pred);
2385 return NewPN;
2386 }
2387 return NonNull;
2388 }
2389
2390 if (match(V, m_SExtLike(m_Value(A)))) {
2391 if (auto *AV = getFreelyInvertedImpl(A, A->hasOneUse(), Builder,
2392 DoesConsume, Depth))
2393 return Builder ? Builder->CreateSExt(AV, V->getType()) : NonNull;
2394 return nullptr;
2395 }
2396
2397 if (match(V, m_Trunc(m_Value(A)))) {
2398 if (auto *AV = getFreelyInvertedImpl(A, A->hasOneUse(), Builder,
2399 DoesConsume, Depth))
2400 return Builder ? Builder->CreateTrunc(AV, V->getType()) : NonNull;
2401 return nullptr;
2402 }
2403
2404 return nullptr;
2405}
2406
2408 Value *PtrOp = GEP.getOperand(0);
2409 SmallVector<Value *, 8> Indices(GEP.indices());
2410 Type *GEPType = GEP.getType();
2411 Type *GEPEltType = GEP.getSourceElementType();
2412 bool IsGEPSrcEleScalable = GEPEltType->isScalableTy();
2413 if (Value *V = simplifyGEPInst(GEPEltType, PtrOp, Indices, GEP.isInBounds(),
2415 return replaceInstUsesWith(GEP, V);
2416
2417 // For vector geps, use the generic demanded vector support.
2418 // Skip if GEP return type is scalable. The number of elements is unknown at
2419 // compile-time.
2420 if (auto *GEPFVTy = dyn_cast<FixedVectorType>(GEPType)) {
2421 auto VWidth = GEPFVTy->getNumElements();
2422 APInt PoisonElts(VWidth, 0);
2423 APInt AllOnesEltMask(APInt::getAllOnes(VWidth));
2424 if (Value *V = SimplifyDemandedVectorElts(&GEP, AllOnesEltMask,
2425 PoisonElts)) {
2426 if (V != &GEP)
2427 return replaceInstUsesWith(GEP, V);
2428 return &GEP;
2429 }
2430
2431 // TODO: 1) Scalarize splat operands, 2) scalarize entire instruction if
2432 // possible (decide on canonical form for pointer broadcast), 3) exploit
2433 // undef elements to decrease demanded bits
2434 }
2435
2436 // Eliminate unneeded casts for indices, and replace indices which displace
2437 // by multiples of a zero size type with zero.
2438 bool MadeChange = false;
2439
2440 // Index width may not be the same width as pointer width.
2441 // Data layout chooses the right type based on supported integer types.
2442 Type *NewScalarIndexTy =
2443 DL.getIndexType(GEP.getPointerOperandType()->getScalarType());
2444
2446 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end(); I != E;
2447 ++I, ++GTI) {
2448 // Skip indices into struct types.
2449 if (GTI.isStruct())
2450 continue;
2451
2452 Type *IndexTy = (*I)->getType();
2453 Type *NewIndexType =
2454 IndexTy->isVectorTy()
2455 ? VectorType::get(NewScalarIndexTy,
2456 cast<VectorType>(IndexTy)->getElementCount())
2457 : NewScalarIndexTy;
2458
2459 // If the element type has zero size then any index over it is equivalent
2460 // to an index of zero, so replace it with zero if it is not zero already.
2461 Type *EltTy = GTI.getIndexedType();
2462 if (EltTy->isSized() && DL.getTypeAllocSize(EltTy).isZero())
2463 if (!isa<Constant>(*I) || !match(I->get(), m_Zero())) {
2464 *I = Constant::getNullValue(NewIndexType);
2465 MadeChange = true;
2466 }
2467
2468 if (IndexTy != NewIndexType) {
2469 // If we are using a wider index than needed for this platform, shrink
2470 // it to what we need. If narrower, sign-extend it to what we need.
2471 // This explicit cast can make subsequent optimizations more obvious.
2472 *I = Builder.CreateIntCast(*I, NewIndexType, true);
2473 MadeChange = true;
2474 }
2475 }
2476 if (MadeChange)
2477 return &GEP;
2478
2479 // Canonicalize constant GEPs to i8 type.
2480 if (!GEPEltType->isIntegerTy(8) && GEP.hasAllConstantIndices()) {
2482 if (GEP.accumulateConstantOffset(DL, Offset))
2483 return replaceInstUsesWith(
2485 GEP.isInBounds()));
2486 }
2487
2488 // Check to see if the inputs to the PHI node are getelementptr instructions.
2489 if (auto *PN = dyn_cast<PHINode>(PtrOp)) {
2490 auto *Op1 = dyn_cast<GetElementPtrInst>(PN->getOperand(0));
2491 if (!Op1)
2492 return nullptr;
2493
2494 // Don't fold a GEP into itself through a PHI node. This can only happen
2495 // through the back-edge of a loop. Folding a GEP into itself means that
2496 // the value of the previous iteration needs to be stored in the meantime,
2497 // thus requiring an additional register variable to be live, but not
2498 // actually achieving anything (the GEP still needs to be executed once per
2499 // loop iteration).
2500 if (Op1 == &GEP)
2501 return nullptr;
2502
2503 int DI = -1;
2504
2505 for (auto I = PN->op_begin()+1, E = PN->op_end(); I !=E; ++I) {
2506 auto *Op2 = dyn_cast<GetElementPtrInst>(*I);
2507 if (!Op2 || Op1->getNumOperands() != Op2->getNumOperands() ||
2508 Op1->getSourceElementType() != Op2->getSourceElementType())
2509 return nullptr;
2510
2511 // As for Op1 above, don't try to fold a GEP into itself.
2512 if (Op2 == &GEP)
2513 return nullptr;
2514
2515 // Keep track of the type as we walk the GEP.
2516 Type *CurTy = nullptr;
2517
2518 for (unsigned J = 0, F = Op1->getNumOperands(); J != F; ++J) {
2519 if (Op1->getOperand(J)->getType() != Op2->getOperand(J)->getType())
2520 return nullptr;
2521
2522 if (Op1->getOperand(J) != Op2->getOperand(J)) {
2523 if (DI == -1) {
2524 // We have not seen any differences yet in the GEPs feeding the
2525 // PHI yet, so we record this one if it is allowed to be a
2526 // variable.
2527
2528 // The first two arguments can vary for any GEP, the rest have to be
2529 // static for struct slots
2530 if (J > 1) {
2531 assert(CurTy && "No current type?");
2532 if (CurTy->isStructTy())
2533 return nullptr;
2534 }
2535
2536 DI = J;
2537 } else {
2538 // The GEP is different by more than one input. While this could be
2539 // extended to support GEPs that vary by more than one variable it
2540 // doesn't make sense since it greatly increases the complexity and
2541 // would result in an R+R+R addressing mode which no backend
2542 // directly supports and would need to be broken into several
2543 // simpler instructions anyway.
2544 return nullptr;
2545 }
2546 }
2547
2548 // Sink down a layer of the type for the next iteration.
2549 if (J > 0) {
2550 if (J == 1) {
2551 CurTy = Op1->getSourceElementType();
2552 } else {
2553 CurTy =
2554 GetElementPtrInst::getTypeAtIndex(CurTy, Op1->getOperand(J));
2555 }
2556 }
2557 }
2558 }
2559
2560 // If not all GEPs are identical we'll have to create a new PHI node.
2561 // Check that the old PHI node has only one use so that it will get
2562 // removed.
2563 if (DI != -1 && !PN->hasOneUse())
2564 return nullptr;
2565
2566 auto *NewGEP = cast<GetElementPtrInst>(Op1->clone());
2567 if (DI == -1) {
2568 // All the GEPs feeding the PHI are identical. Clone one down into our
2569 // BB so that it can be merged with the current GEP.
2570 } else {
2571 // All the GEPs feeding the PHI differ at a single offset. Clone a GEP
2572 // into the current block so it can be merged, and create a new PHI to
2573 // set that index.
2574 PHINode *NewPN;
2575 {
2578 NewPN = Builder.CreatePHI(Op1->getOperand(DI)->getType(),
2579 PN->getNumOperands());
2580 }
2581
2582 for (auto &I : PN->operands())
2583 NewPN->addIncoming(cast<GEPOperator>(I)->getOperand(DI),
2584 PN->getIncomingBlock(I));
2585
2586 NewGEP->setOperand(DI, NewPN);
2587 }
2588
2589 NewGEP->insertBefore(*GEP.getParent(), GEP.getParent()->getFirstInsertionPt());
2590 return replaceOperand(GEP, 0, NewGEP);
2591 }
2592
2593 if (auto *Src = dyn_cast<GEPOperator>(PtrOp))
2594 if (Instruction *I = visitGEPOfGEP(GEP, Src))
2595 return I;
2596
2597 // Skip if GEP source element type is scalable. The type alloc size is unknown
2598 // at compile-time.
2599 if (GEP.getNumIndices() == 1 && !IsGEPSrcEleScalable) {
2600 unsigned AS = GEP.getPointerAddressSpace();
2601 if (GEP.getOperand(1)->getType()->getScalarSizeInBits() ==
2602 DL.getIndexSizeInBits(AS)) {
2603 uint64_t TyAllocSize = DL.getTypeAllocSize(GEPEltType).getFixedValue();
2604
2605 if (TyAllocSize == 1) {
2606 // Canonicalize (gep i8* X, (ptrtoint Y)-(ptrtoint X)) to (bitcast Y),
2607 // but only if the result pointer is only used as if it were an integer,
2608 // or both point to the same underlying object (otherwise provenance is
2609 // not necessarily retained).
2610 Value *X = GEP.getPointerOperand();
2611 Value *Y;
2612 if (match(GEP.getOperand(1),
2614 GEPType == Y->getType()) {
2615 bool HasSameUnderlyingObject =
2617 bool Changed = false;
2618 GEP.replaceUsesWithIf(Y, [&](Use &U) {
2619 bool ShouldReplace = HasSameUnderlyingObject ||
2620 isa<ICmpInst>(U.getUser()) ||
2621 isa<PtrToIntInst>(U.getUser());
2622 Changed |= ShouldReplace;
2623 return ShouldReplace;
2624 });
2625 return Changed ? &GEP : nullptr;
2626 }
2627 } else {
2628 // Canonicalize (gep T* X, V / sizeof(T)) to (gep i8* X, V)
2629 Value *V;
2630 if ((has_single_bit(TyAllocSize) &&
2631 match(GEP.getOperand(1),
2633 m_SpecificInt(countr_zero(TyAllocSize)))))) ||
2634 match(GEP.getOperand(1),
2635 m_Exact(m_IDiv(m_Value(V), m_SpecificInt(TyAllocSize))))) {
2637 Builder.getInt8Ty(), GEP.getPointerOperand(), V);
2638 NewGEP->setIsInBounds(GEP.isInBounds());
2639 return NewGEP;
2640 }
2641 }
2642 }
2643 }
2644 // We do not handle pointer-vector geps here.
2645 if (GEPType->isVectorTy())
2646 return nullptr;
2647
2648 if (GEP.getNumIndices() == 1) {
2649 // Try to replace ADD + GEP with GEP + GEP.
2650 Value *Idx1, *Idx2;
2651 if (match(GEP.getOperand(1),
2652 m_OneUse(m_Add(m_Value(Idx1), m_Value(Idx2))))) {
2653 // %idx = add i64 %idx1, %idx2
2654 // %gep = getelementptr i32, ptr %ptr, i64 %idx
2655 // as:
2656 // %newptr = getelementptr i32, ptr %ptr, i64 %idx1
2657 // %newgep = getelementptr i32, ptr %newptr, i64 %idx2
2658 auto *NewPtr = Builder.CreateGEP(GEP.getResultElementType(),
2659 GEP.getPointerOperand(), Idx1);
2660 return GetElementPtrInst::Create(GEP.getResultElementType(), NewPtr,
2661 Idx2);
2662 }
2663 ConstantInt *C;
2664 if (match(GEP.getOperand(1), m_OneUse(m_SExtLike(m_OneUse(m_NSWAdd(
2665 m_Value(Idx1), m_ConstantInt(C))))))) {
2666 // %add = add nsw i32 %idx1, idx2
2667 // %sidx = sext i32 %add to i64
2668 // %gep = getelementptr i32, ptr %ptr, i64 %sidx
2669 // as:
2670 // %newptr = getelementptr i32, ptr %ptr, i32 %idx1
2671 // %newgep = getelementptr i32, ptr %newptr, i32 idx2
2672 auto *NewPtr = Builder.CreateGEP(
2673 GEP.getResultElementType(), GEP.getPointerOperand(),
2674 Builder.CreateSExt(Idx1, GEP.getOperand(1)->getType()));
2676 GEP.getResultElementType(), NewPtr,
2677 Builder.CreateSExt(C, GEP.getOperand(1)->getType()));
2678 }
2679 }
2680
2681 if (!GEP.isInBounds()) {
2682 unsigned IdxWidth =
2684 APInt BasePtrOffset(IdxWidth, 0);
2685 Value *UnderlyingPtrOp =
2687 BasePtrOffset);
2688 bool CanBeNull, CanBeFreed;
2689 uint64_t DerefBytes = UnderlyingPtrOp->getPointerDereferenceableBytes(
2690 DL, CanBeNull, CanBeFreed);
2691 if (!CanBeNull && !CanBeFreed && DerefBytes != 0) {
2692 if (GEP.accumulateConstantOffset(DL, BasePtrOffset) &&
2693 BasePtrOffset.isNonNegative()) {
2694 APInt AllocSize(IdxWidth, DerefBytes);
2695 if (BasePtrOffset.ule(AllocSize)) {
2697 GEP.getSourceElementType(), PtrOp, Indices, GEP.getName());
2698 }
2699 }
2700 }
2701 }
2702
2704 return R;
2705
2706 return nullptr;
2707}
2708
2710 Instruction *AI) {
2711 if (isa<ConstantPointerNull>(V))
2712 return true;
2713 if (auto *LI = dyn_cast<LoadInst>(V))
2714 return isa<GlobalVariable>(LI->getPointerOperand());
2715 // Two distinct allocations will never be equal.
2716 return isAllocLikeFn(V, &TLI) && V != AI;
2717}
2718
2719/// Given a call CB which uses an address UsedV, return true if we can prove the
2720/// call's only possible effect is storing to V.
2721static bool isRemovableWrite(CallBase &CB, Value *UsedV,
2722 const TargetLibraryInfo &TLI) {
2723 if (!CB.use_empty())
2724 // TODO: add recursion if returned attribute is present
2725 return false;
2726
2727 if (CB.isTerminator())
2728 // TODO: remove implementation restriction
2729 return false;
2730
2731 if (!CB.willReturn() || !CB.doesNotThrow())
2732 return false;
2733
2734 // If the only possible side effect of the call is writing to the alloca,
2735 // and the result isn't used, we can safely remove any reads implied by the
2736 // call including those which might read the alloca itself.
2737 std::optional<MemoryLocation> Dest = MemoryLocation::getForDest(&CB, TLI);
2738 return Dest && Dest->Ptr == UsedV;
2739}
2740
2743 const TargetLibraryInfo &TLI) {
2745 const std::optional<StringRef> Family = getAllocationFamily(AI, &TLI);
2746 Worklist.push_back(AI);
2747
2748 do {
2749 Instruction *PI = Worklist.pop_back_val();
2750 for (User *U : PI->users()) {
2751 Instruction *I = cast<Instruction>(U);
2752 switch (I->getOpcode()) {
2753 default:
2754 // Give up the moment we see something we can't handle.
2755 return false;
2756
2757 case Instruction::AddrSpaceCast:
2758 case Instruction::BitCast:
2759 case Instruction::GetElementPtr:
2760 Users.emplace_back(I);
2761 Worklist.push_back(I);
2762 continue;
2763
2764 case Instruction::ICmp: {
2765 ICmpInst *ICI = cast<ICmpInst>(I);
2766 // We can fold eq/ne comparisons with null to false/true, respectively.
2767 // We also fold comparisons in some conditions provided the alloc has
2768 // not escaped (see isNeverEqualToUnescapedAlloc).
2769 if (!ICI->isEquality())
2770 return false;
2771 unsigned OtherIndex = (ICI->getOperand(0) == PI) ? 1 : 0;
2772 if (!isNeverEqualToUnescapedAlloc(ICI->getOperand(OtherIndex), TLI, AI))
2773 return false;
2774
2775 // Do not fold compares to aligned_alloc calls, as they may have to
2776 // return null in case the required alignment cannot be satisfied,
2777 // unless we can prove that both alignment and size are valid.
2778 auto AlignmentAndSizeKnownValid = [](CallBase *CB) {
2779 // Check if alignment and size of a call to aligned_alloc is valid,
2780 // that is alignment is a power-of-2 and the size is a multiple of the
2781 // alignment.
2782 const APInt *Alignment;
2783 const APInt *Size;
2784 return match(CB->getArgOperand(0), m_APInt(Alignment)) &&
2785 match(CB->getArgOperand(1), m_APInt(Size)) &&
2786 Alignment->isPowerOf2() && Size->urem(*Alignment).isZero();
2787 };
2788 auto *CB = dyn_cast<CallBase>(AI);
2789 LibFunc TheLibFunc;
2790 if (CB && TLI.getLibFunc(*CB->getCalledFunction(), TheLibFunc) &&
2791 TLI.has(TheLibFunc) && TheLibFunc == LibFunc_aligned_alloc &&
2792 !AlignmentAndSizeKnownValid(CB))
2793 return false;
2794 Users.emplace_back(I);
2795 continue;
2796 }
2797
2798 case Instruction::Call:
2799 // Ignore no-op and store intrinsics.
2800 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
2801 switch (II->getIntrinsicID()) {
2802 default:
2803 return false;
2804
2805 case Intrinsic::memmove:
2806 case Intrinsic::memcpy:
2807 case Intrinsic::memset: {
2808 MemIntrinsic *MI = cast<MemIntrinsic>(II);
2809 if (MI->isVolatile() || MI->getRawDest() != PI)
2810 return false;
2811 [[fallthrough]];
2812 }
2813 case Intrinsic::assume:
2814 case Intrinsic::invariant_start:
2815 case Intrinsic::invariant_end:
2816 case Intrinsic::lifetime_start:
2817 case Intrinsic::lifetime_end:
2818 case Intrinsic::objectsize:
2819 Users.emplace_back(I);
2820 continue;
2821 case Intrinsic::launder_invariant_group:
2822 case Intrinsic::strip_invariant_group:
2823 Users.emplace_back(I);
2824 Worklist.push_back(I);
2825 continue;
2826 }
2827 }
2828
2829 if (isRemovableWrite(*cast<CallBase>(I), PI, TLI)) {
2830 Users.emplace_back(I);
2831 continue;
2832 }
2833
2834 if (getFreedOperand(cast<CallBase>(I), &TLI) == PI &&
2835 getAllocationFamily(I, &TLI) == Family) {
2836 assert(Family);
2837 Users.emplace_back(I);
2838 continue;
2839 }
2840
2841 if (getReallocatedOperand(cast<CallBase>(I)) == PI &&
2842 getAllocationFamily(I, &TLI) == Family) {
2843 assert(Family);
2844 Users.emplace_back(I);
2845 Worklist.push_back(I);
2846 continue;
2847 }
2848
2849 return false;
2850
2851 case Instruction::Store: {
2852 StoreInst *SI = cast<StoreInst>(I);
2853 if (SI->isVolatile() || SI->getPointerOperand() != PI)
2854 return false;
2855 Users.emplace_back(I);
2856 continue;
2857 }
2858 }
2859 llvm_unreachable("missing a return?");
2860 }
2861 } while (!Worklist.empty());
2862 return true;
2863}
2864
2866 assert(isa<AllocaInst>(MI) || isRemovableAlloc(&cast<CallBase>(MI), &TLI));
2867
2868 // If we have a malloc call which is only used in any amount of comparisons to
2869 // null and free calls, delete the calls and replace the comparisons with true
2870 // or false as appropriate.
2871
2872 // This is based on the principle that we can substitute our own allocation
2873 // function (which will never return null) rather than knowledge of the
2874 // specific function being called. In some sense this can change the permitted
2875 // outputs of a program (when we convert a malloc to an alloca, the fact that
2876 // the allocation is now on the stack is potentially visible, for example),
2877 // but we believe in a permissible manner.
2879
2880 // If we are removing an alloca with a dbg.declare, insert dbg.value calls
2881 // before each store.
2884 std::unique_ptr<DIBuilder> DIB;
2885 if (isa<AllocaInst>(MI)) {
2886 findDbgUsers(DVIs, &MI, &DPVs);
2887 DIB.reset(new DIBuilder(*MI.getModule(), /*AllowUnresolved=*/false));
2888 }
2889
2890 if (isAllocSiteRemovable(&MI, Users, TLI)) {
2891 for (unsigned i = 0, e = Users.size(); i != e; ++i) {
2892 // Lowering all @llvm.objectsize calls first because they may
2893 // use a bitcast/GEP of the alloca we are removing.
2894 if (!Users[i])
2895 continue;
2896
2897 Instruction *I = cast<Instruction>(&*Users[i]);
2898
2899 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
2900 if (II->getIntrinsicID() == Intrinsic::objectsize) {
2901 SmallVector<Instruction *> InsertedInstructions;
2902 Value *Result = lowerObjectSizeCall(
2903 II, DL, &TLI, AA, /*MustSucceed=*/true, &InsertedInstructions);
2904 for (Instruction *Inserted : InsertedInstructions)
2905 Worklist.add(Inserted);
2906 replaceInstUsesWith(*I, Result);
2908 Users[i] = nullptr; // Skip examining in the next loop.
2909 }
2910 }
2911 }
2912 for (unsigned i = 0, e = Users.size(); i != e; ++i) {
2913 if (!Users[i])
2914 continue;
2915
2916 Instruction *I = cast<Instruction>(&*Users[i]);
2917
2918 if (ICmpInst *C = dyn_cast<ICmpInst>(I)) {
2920 ConstantInt::get(Type::getInt1Ty(C->getContext()),
2921 C->isFalseWhenEqual()));
2922 } else if (auto *SI = dyn_cast<StoreInst>(I)) {
2923 for (auto *DVI : DVIs)
2924 if (DVI->isAddressOfVariable())
2925 ConvertDebugDeclareToDebugValue(DVI, SI, *DIB);
2926 for (auto *DPV : DPVs)
2927 if (DPV->isAddressOfVariable())
2928 ConvertDebugDeclareToDebugValue(DPV, SI, *DIB);
2929 } else {
2930 // Casts, GEP, or anything else: we're about to delete this instruction,
2931 // so it can not have any valid uses.
2932 replaceInstUsesWith(*I, PoisonValue::get(I->getType()));
2933 }
2935 }
2936
2937 if (InvokeInst *II = dyn_cast<InvokeInst>(&MI)) {
2938 // Replace invoke with a NOP intrinsic to maintain the original CFG
2939 Module *M = II->getModule();
2940 Function *F = Intrinsic::getDeclaration(M, Intrinsic::donothing);
2941 InvokeInst::Create(F, II->getNormalDest(), II->getUnwindDest(),
2942 std::nullopt, "", II->getParent());
2943 }
2944
2945 // Remove debug intrinsics which describe the value contained within the
2946 // alloca. In addition to removing dbg.{declare,addr} which simply point to
2947 // the alloca, remove dbg.value(<alloca>, ..., DW_OP_deref)'s as well, e.g.:
2948 //
2949 // ```
2950 // define void @foo(i32 %0) {
2951 // %a = alloca i32 ; Deleted.
2952 // store i32 %0, i32* %a
2953 // dbg.value(i32 %0, "arg0") ; Not deleted.
2954 // dbg.value(i32* %a, "arg0", DW_OP_deref) ; Deleted.
2955 // call void @trivially_inlinable_no_op(i32* %a)
2956 // ret void
2957 // }
2958 // ```
2959 //
2960 // This may not be required if we stop describing the contents of allocas
2961 // using dbg.value(<alloca>, ..., DW_OP_deref), but we currently do this in
2962 // the LowerDbgDeclare utility.
2963 //
2964 // If there is a dead store to `%a` in @trivially_inlinable_no_op, the
2965 // "arg0" dbg.value may be stale after the call. However, failing to remove
2966 // the DW_OP_deref dbg.value causes large gaps in location coverage.
2967 //
2968 // FIXME: the Assignment Tracking project has now likely made this
2969 // redundant (and it's sometimes harmful).
2970 for (auto *DVI : DVIs)
2971 if (DVI->isAddressOfVariable() || DVI->getExpression()->startsWithDeref())
2972 DVI->eraseFromParent();
2973 for (auto *DPV : DPVs)
2974 if (DPV->isAddressOfVariable() || DPV->getExpression()->startsWithDeref())
2975 DPV->eraseFromParent();
2976
2977 return eraseInstFromFunction(MI);
2978 }
2979 return nullptr;
2980}
2981
2982/// Move the call to free before a NULL test.
2983///
2984/// Check if this free is accessed after its argument has been test
2985/// against NULL (property 0).
2986/// If yes, it is legal to move this call in its predecessor block.
2987///
2988/// The move is performed only if the block containing the call to free
2989/// will be removed, i.e.:
2990/// 1. it has only one predecessor P, and P has two successors
2991/// 2. it contains the call, noops, and an unconditional branch
2992/// 3. its successor is the same as its predecessor's successor
2993///
2994/// The profitability is out-of concern here and this function should
2995/// be called only if the caller knows this transformation would be
2996/// profitable (e.g., for code size).
2998 const DataLayout &DL) {
2999 Value *Op = FI.getArgOperand(0);
3000 BasicBlock *FreeInstrBB = FI.getParent();
3001 BasicBlock *PredBB = FreeInstrBB->getSinglePredecessor();
3002
3003 // Validate part of constraint #1: Only one predecessor
3004 // FIXME: We can extend the number of predecessor, but in that case, we
3005 // would duplicate the call to free in each predecessor and it may
3006 // not be profitable even for code size.
3007 if (!PredBB)
3008 return nullptr;
3009
3010 // Validate constraint #2: Does this block contains only the call to
3011 // free, noops, and an unconditional branch?
3012 BasicBlock *SuccBB;
3013 Instruction *FreeInstrBBTerminator = FreeInstrBB->getTerminator();
3014 if (!match(FreeInstrBBTerminator, m_UnconditionalBr(SuccBB)))
3015 return nullptr;
3016
3017 // If there are only 2 instructions in the block, at this point,
3018 // this is the call to free and unconditional.
3019 // If there are more than 2 instructions, check that they are noops
3020 // i.e., they won't hurt the performance of the generated code.
3021 if (FreeInstrBB->size() != 2) {
3022 for (const Instruction &Inst : FreeInstrBB->instructionsWithoutDebug()) {
3023 if (&Inst == &FI || &Inst == FreeInstrBBTerminator)
3024 continue;
3025 auto *Cast = dyn_cast<CastInst>(&Inst);
3026 if (!Cast || !Cast->isNoopCast(DL))
3027 return nullptr;
3028 }
3029 }
3030 // Validate the rest of constraint #1 by matching on the pred branch.
3031 Instruction *TI = PredBB->getTerminator();
3032 BasicBlock *TrueBB, *FalseBB;
3034 if (!match(TI, m_Br(m_ICmp(Pred,
3036 m_Specific(Op->stripPointerCasts())),
3037 m_Zero()),
3038 TrueBB, FalseBB)))
3039 return nullptr;
3040 if (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE)
3041 return nullptr;
3042
3043 // Validate constraint #3: Ensure the null case just falls through.
3044 if (SuccBB != (Pred == ICmpInst::ICMP_EQ ? TrueBB : FalseBB))
3045 return nullptr;
3046 assert(FreeInstrBB == (Pred == ICmpInst::ICMP_EQ ? FalseBB : TrueBB) &&
3047 "Broken CFG: missing edge from predecessor to successor");
3048
3049 // At this point, we know that everything in FreeInstrBB can be moved
3050 // before TI.
3051 for (Instruction &Instr : llvm::make_early_inc_range(*FreeInstrBB)) {
3052 if (&Instr == FreeInstrBBTerminator)
3053 break;
3054 Instr.moveBeforePreserving(TI);
3055 }
3056 assert(FreeInstrBB->size() == 1 &&
3057 "Only the branch instruction should remain");
3058
3059 // Now that we've moved the call to free before the NULL check, we have to
3060 // remove any attributes on its parameter that imply it's non-null, because
3061 // those attributes might have only been valid because of the NULL check, and
3062 // we can get miscompiles if we keep them. This is conservative if non-null is
3063 // also implied by something other than the NULL check, but it's guaranteed to
3064 // be correct, and the conservativeness won't matter in practice, since the
3065 // attributes are irrelevant for the call to free itself and the pointer
3066 // shouldn't be used after the call.
3067 AttributeList Attrs = FI.getAttributes();
3068 Attrs = Attrs.removeParamAttribute(FI.getContext(), 0, Attribute::NonNull);
3069 Attribute Dereferenceable = Attrs.getParamAttr(0, Attribute::Dereferenceable);
3070 if (Dereferenceable.isValid()) {
3071 uint64_t Bytes = Dereferenceable.getDereferenceableBytes();
3072 Attrs = Attrs.removeParamAttribute(FI.getContext(), 0,
3073 Attribute::Dereferenceable);
3074 Attrs = Attrs.addDereferenceableOrNullParamAttr(FI.getContext(), 0, Bytes);
3075 }
3076 FI.setAttributes(Attrs);
3077
3078 return &FI;
3079}
3080
3082 // free undef -> unreachable.
3083 if (isa<UndefValue>(Op)) {
3084 // Leave a marker since we can't modify the CFG here.
3086 return eraseInstFromFunction(FI);
3087 }
3088
3089 // If we have 'free null' delete the instruction. This can happen in stl code
3090 // when lots of inlining happens.
3091 if (isa<ConstantPointerNull>(Op))
3092 return eraseInstFromFunction(FI);
3093
3094 // If we had free(realloc(...)) with no intervening uses, then eliminate the
3095 // realloc() entirely.
3096 CallInst *CI = dyn_cast<CallInst>(Op);
3097 if (CI && CI->hasOneUse())
3098 if (Value *ReallocatedOp = getReallocatedOperand(CI))
3099 return eraseInstFromFunction(*replaceInstUsesWith(*CI, ReallocatedOp));
3100
3101 // If we optimize for code size, try to move the call to free before the null
3102 // test so that simplify cfg can remove the empty block and dead code
3103 // elimination the branch. I.e., helps to turn something like:
3104 // if (foo) free(foo);
3105 // into
3106 // free(foo);
3107 //
3108 // Note that we can only do this for 'free' and not for any flavor of
3109 // 'operator delete'; there is no 'operator delete' symbol for which we are
3110 // permitted to invent a call, even if we're passing in a null pointer.
3111 if (MinimizeSize) {
3112 LibFunc Func;
3113 if (TLI.getLibFunc(FI, Func) && TLI.has(Func) && Func == LibFunc_free)
3115 return I;
3116 }
3117
3118 return nullptr;
3119}
3120
3122 Value *RetVal = RI.getReturnValue();
3123 if (!RetVal || !AttributeFuncs::isNoFPClassCompatibleType(RetVal->getType()))
3124 return nullptr;
3125
3126 Function *F = RI.getFunction();
3127 FPClassTest ReturnClass = F->getAttributes().getRetNoFPClass();
3128 if (ReturnClass == fcNone)
3129 return nullptr;
3130
3131 KnownFPClass KnownClass;
3132 Value *Simplified =
3133 SimplifyDemandedUseFPClass(RetVal, ~ReturnClass, KnownClass, 0, &RI);
3134 if (!Simplified)
3135 return nullptr;
3136
3137 return ReturnInst::Create(RI.getContext(), Simplified);
3138}
3139
3140// WARNING: keep in sync with SimplifyCFGOpt::simplifyUnreachable()!
3142 // Try to remove the previous instruction if it must lead to unreachable.
3143 // This includes instructions like stores and "llvm.assume" that may not get
3144 // removed by simple dead code elimination.
3145 bool Changed = false;
3146 while (Instruction *Prev = I.getPrevNonDebugInstruction()) {
3147 // While we theoretically can erase EH, that would result in a block that
3148 // used to start with an EH no longer starting with EH, which is invalid.
3149 // To make it valid, we'd need to fixup predecessors to no longer refer to
3150 // this block, but that changes CFG, which is not allowed in InstCombine.
3151 if (Prev->isEHPad())
3152 break; // Can not drop any more instructions. We're done here.
3153
3155 break; // Can not drop any more instructions. We're done here.
3156 // Otherwise, this instruction can be freely erased,
3157 // even if it is not side-effect free.
3158
3159 // A value may still have uses before we process it here (for example, in
3160 // another unreachable block), so convert those to poison.
3161 replaceInstUsesWith(*Prev, PoisonValue::get(Prev->getType()));
3162 eraseInstFromFunction(*Prev);
3163 Changed = true;
3164 }
3165 return Changed;
3166}
3167
3170 return nullptr;
3171}
3172
3174 assert(BI.isUnconditional() && "Only for unconditional branches.");
3175
3176 // If this store is the second-to-last instruction in the basic block
3177 // (excluding debug info and bitcasts of pointers) and if the block ends with
3178 // an unconditional branch, try to move the store to the successor block.
3179
3180 auto GetLastSinkableStore = [](BasicBlock::iterator BBI) {
3181 auto IsNoopInstrForStoreMerging = [](BasicBlock::iterator BBI) {
3182 return BBI->isDebugOrPseudoInst() ||
3183 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy());
3184 };
3185
3186 BasicBlock::iterator FirstInstr = BBI->getParent()->begin();
3187 do {
3188 if (BBI != FirstInstr)
3189 --BBI;
3190 } while (BBI != FirstInstr && IsNoopInstrForStoreMerging(BBI));
3191
3192 return dyn_cast<StoreInst>(BBI);
3193 };
3194
3195 if (StoreInst *SI = GetLastSinkableStore(BasicBlock::iterator(BI)))
3196 if (mergeStoreIntoSuccessor(*SI))
3197 return &BI;
3198
3199 return nullptr;
3200}
3201
3204 if (!DeadEdges.insert({From, To}).second)
3205 return;
3206
3207 // Replace phi node operands in successor with poison.
3208 for (PHINode &PN : To->phis())
3209 for (Use &U : PN.incoming_values())
3210 if (PN.getIncomingBlock(U) == From && !isa<PoisonValue>(U)) {
3211 replaceUse(U, PoisonValue::get(PN.getType()));
3212 addToWorklist(&PN);
3213 MadeIRChange = true;
3214 }
3215
3216 Worklist.push_back(To);
3217}
3218
3219// Under the assumption that I is unreachable, remove it and following
3220// instructions. Changes are reported directly to MadeIRChange.
3223 BasicBlock *BB = I->getParent();
3224 for (Instruction &Inst : make_early_inc_range(
3225 make_range(std::next(BB->getTerminator()->getReverseIterator()),
3226 std::next(I->getReverseIterator())))) {
3227 if (!Inst.use_empty() && !Inst.getType()->isTokenTy()) {
3228 replaceInstUsesWith(Inst, PoisonValue::get(Inst.getType()));
3229 MadeIRChange = true;
3230 }
3231 if (Inst.isEHPad() || Inst.getType()->isTokenTy())
3232 continue;
3233 // RemoveDIs: erase debug-info on this instruction manually.
3234 Inst.dropDbgValues();
3236 MadeIRChange = true;
3237 }
3238
3239 // RemoveDIs: to match behaviour in dbg.value mode, drop debug-info on
3240 // terminator too.
3242
3243 // Handle potentially dead successors.
3244 for (BasicBlock *Succ : successors(BB))
3245 addDeadEdge(BB, Succ, Worklist);
3246}
3247
3250 while (!Worklist.empty()) {
3251 BasicBlock *BB = Worklist.pop_back_val();
3252 if (!all_of(predecessors(BB), [&](BasicBlock *Pred) {
3253 return DeadEdges.contains({Pred, BB}) || DT.dominates(BB, Pred);
3254 }))
3255 continue;
3256
3258 }
3259}
3260
3262 BasicBlock *LiveSucc) {
3264 for (BasicBlock *Succ : successors(BB)) {
3265 // The live successor isn't dead.
3266 if (Succ == LiveSucc)
3267 continue;
3268
3269 addDeadEdge(BB, Succ, Worklist);
3270 }
3271
3273}
3274
3276 if (BI.isUnconditional())
3278
3279 // Change br (not X), label True, label False to: br X, label False, True
3280 Value *Cond = BI.getCondition();
3281 Value *X;
3282 if (match(Cond, m_Not(m_Value(X))) && !isa<Constant>(X)) {
3283 // Swap Destinations and condition...
3284 BI.swapSuccessors();
3285 return replaceOperand(BI, 0, X);
3286 }
3287
3288 // Canonicalize logical-and-with-invert as logical-or-with-invert.
3289 // This is done by inverting the condition and swapping successors:
3290 // br (X && !Y), T, F --> br !(X && !Y), F, T --> br (!X || Y), F, T
3291 Value *Y;
3292 if (isa<SelectInst>(Cond) &&
3293 match(Cond,
3295 Value *NotX = Builder.CreateNot(X, "not." + X->getName());
3296 Value *Or = Builder.CreateLogicalOr(NotX, Y);
3297 BI.swapSuccessors();
3298 return replaceOperand(BI, 0, Or);
3299 }
3300
3301 // If the condition is irrelevant, remove the use so that other
3302 // transforms on the condition become more effective.
3303 if (!isa<ConstantInt>(Cond) && BI.getSuccessor(0) == BI.getSuccessor(1))
3304 return replaceOperand(BI, 0, ConstantInt::getFalse(Cond->getType()));
3305
3306 // Canonicalize, for example, fcmp_one -> fcmp_oeq.
3307 CmpInst::Predicate Pred;
3308 if (match(Cond, m_OneUse(m_FCmp(Pred, m_Value(), m_Value()))) &&
3309 !isCanonicalPredicate(Pred)) {
3310 // Swap destinations and condition.
3311 auto *Cmp = cast<CmpInst>(Cond);
3312 Cmp->setPredicate(CmpInst::getInversePredicate(Pred));
3313 BI.swapSuccessors();
3314 Worklist.push(Cmp);
3315 return &BI;
3316 }
3317
3318 if (isa<UndefValue>(Cond)) {
3319 handlePotentiallyDeadSuccessors(BI.getParent(), /*LiveSucc*/ nullptr);
3320 return nullptr;
3321 }
3322 if (auto *CI = dyn_cast<ConstantInt>(Cond)) {
3324 BI.getSuccessor(!CI->getZExtValue()));
3325 return nullptr;
3326 }
3327
3328 DC.registerBranch(&BI);
3329 return nullptr;
3330}
3331
3333 Value *Cond = SI.getCondition();
3334 Value *Op0;
3335 ConstantInt *AddRHS;
3336 if (match(Cond, m_Add(m_Value(Op0), m_ConstantInt(AddRHS)))) {
3337 // Change 'switch (X+4) case 1:' into 'switch (X) case -3'.
3338 for (auto Case : SI.cases()) {
3339 Constant *NewCase = ConstantExpr::getSub(Case.getCaseValue(), AddRHS);
3340 assert(isa<ConstantInt>(NewCase) &&
3341 "Result of expression should be constant");
3342 Case.setValue(cast<ConstantInt>(NewCase));
3343 }
3344 return replaceOperand(SI, 0, Op0);
3345 }
3346
3347 ConstantInt *SubLHS;
3348 if (match(Cond, m_Sub(m_ConstantInt(SubLHS), m_Value(Op0)))) {
3349 // Change 'switch (1-X) case 1:' into 'switch (X) case 0'.
3350 for (auto Case : SI.cases()) {
3351 Constant *NewCase = ConstantExpr::getSub(SubLHS, Case.getCaseValue());
3352 assert(isa<ConstantInt>(NewCase) &&
3353 "Result of expression should be constant");
3354 Case.setValue(cast<ConstantInt>(NewCase));
3355 }
3356 return replaceOperand(SI, 0, Op0);
3357 }
3358
3359 uint64_t ShiftAmt;
3360 if (match(Cond, m_Shl(m_Value(Op0), m_ConstantInt(ShiftAmt))) &&
3361 ShiftAmt < Op0->getType()->getScalarSizeInBits() &&
3362 all_of(SI.cases(), [&](const auto &Case) {
3363 return Case.getCaseValue()->getValue().countr_zero() >= ShiftAmt;
3364 })) {
3365 // Change 'switch (X << 2) case 4:' into 'switch (X) case 1:'.
3366 OverflowingBinaryOperator *Shl = cast<OverflowingBinaryOperator>(Cond);
3367 if (Shl->hasNoUnsignedWrap() || Shl->hasNoSignedWrap() ||
3368 Shl->hasOneUse()) {
3369 Value *NewCond = Op0;
3370 if (!Shl->hasNoUnsignedWrap() && !Shl->hasNoSignedWrap()) {
3371 // If the shift may wrap, we need to mask off the shifted bits.
3372 unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
3373 NewCond = Builder.CreateAnd(
3374 Op0, APInt::getLowBitsSet(BitWidth, BitWidth - ShiftAmt));
3375 }
3376 for (auto Case : SI.cases()) {
3377 const APInt &CaseVal = Case.getCaseValue()->getValue();
3378 APInt ShiftedCase = Shl->hasNoSignedWrap() ? CaseVal.ashr(ShiftAmt)
3379 : CaseVal.lshr(ShiftAmt);
3380 Case.setValue(ConstantInt::get(SI.getContext(), ShiftedCase));
3381 }
3382 return replaceOperand(SI, 0, NewCond);
3383 }
3384 }
3385
3386 // Fold switch(zext/sext(X)) into switch(X) if possible.
3387 if (match(Cond, m_ZExtOrSExt(m_Value(Op0)))) {
3388 bool IsZExt = isa<ZExtInst>(Cond);
3389 Type *SrcTy = Op0->getType();
3390 unsigned NewWidth = SrcTy->getScalarSizeInBits();
3391
3392 if (all_of(SI.cases(), [&](const auto &Case) {
3393 const APInt &CaseVal = Case.getCaseValue()->getValue();
3394 return IsZExt ? CaseVal.isIntN(NewWidth)
3395 : CaseVal.isSignedIntN(NewWidth);
3396 })) {
3397 for (auto &Case : SI.cases()) {
3398 APInt TruncatedCase = Case.getCaseValue()->getValue().trunc(NewWidth);
3399 Case.setValue(ConstantInt::get(SI.getContext(), TruncatedCase));
3400 }
3401 return replaceOperand(SI, 0, Op0);
3402 }
3403 }
3404
3405 KnownBits Known = computeKnownBits(Cond, 0, &SI);
3406 unsigned LeadingKnownZeros = Known.countMinLeadingZeros();
3407 unsigned LeadingKnownOnes = Known.countMinLeadingOnes();
3408
3409 // Compute the number of leading bits we can ignore.
3410 // TODO: A better way to determine this would use ComputeNumSignBits().
3411 for (const auto &C : SI.cases()) {
3412 LeadingKnownZeros =
3413 std::min(LeadingKnownZeros, C.getCaseValue()->getValue().countl_zero());
3414 LeadingKnownOnes =
3415 std::min(LeadingKnownOnes, C.getCaseValue()->getValue().countl_one());
3416 }
3417
3418 unsigned NewWidth = Known.getBitWidth() - std::max(LeadingKnownZeros, LeadingKnownOnes);
3419
3420 // Shrink the condition operand if the new type is smaller than the old type.
3421 // But do not shrink to a non-standard type, because backend can't generate
3422 // good code for that yet.
3423 // TODO: We can make it aggressive again after fixing PR39569.
3424 if (NewWidth > 0 && NewWidth < Known.getBitWidth() &&
3425 shouldChangeType(Known.getBitWidth(), NewWidth)) {
3426 IntegerType *Ty = IntegerType::get(SI.getContext(), NewWidth);
3428 Value *NewCond = Builder.CreateTrunc(Cond, Ty, "trunc");
3429
3430 for (auto Case : SI.cases()) {
3431 APInt TruncatedCase = Case.getCaseValue()->getValue().trunc(NewWidth);
3432 Case.setValue(ConstantInt::get(SI.getContext(), TruncatedCase));
3433 }
3434 return replaceOperand(SI, 0, NewCond);
3435 }
3436
3437 if (isa<UndefValue>(Cond)) {
3438 handlePotentiallyDeadSuccessors(SI.getParent(), /*LiveSucc*/ nullptr);
3439 return nullptr;
3440 }
3441 if (auto *CI = dyn_cast<ConstantInt>(Cond)) {
3442 handlePotentiallyDeadSuccessors(SI.getParent(),
3443 SI.findCaseValue(CI)->getCaseSuccessor());
3444 return nullptr;
3445 }
3446
3447 return nullptr;
3448}
3449
3451InstCombinerImpl::foldExtractOfOverflowIntrinsic(ExtractValueInst &EV) {
3452 auto *WO = dyn_cast<WithOverflowInst>(EV.getAggregateOperand());
3453 if (!WO)
3454 return nullptr;
3455
3456 Intrinsic::ID OvID = WO->getIntrinsicID();
3457 const APInt *C = nullptr;
3458 if (match(WO->getRHS(), m_APIntAllowUndef(C))) {
3459 if (*EV.idx_begin() == 0 && (OvID == Intrinsic::smul_with_overflow ||
3460 OvID == Intrinsic::umul_with_overflow)) {
3461 // extractvalue (any_mul_with_overflow X, -1), 0 --> -X
3462 if (C->isAllOnes())
3463 return BinaryOperator::CreateNeg(WO->getLHS());
3464 // extractvalue (any_mul_with_overflow X, 2^n), 0 --> X << n
3465 if (C->isPowerOf2()) {
3466 return BinaryOperator::CreateShl(
3467 WO->getLHS(),
3468 ConstantInt::get(WO->getLHS()->getType(), C->logBase2()));
3469 }
3470 }
3471 }
3472
3473 // We're extracting from an overflow intrinsic. See if we're the only user.
3474 // That allows us to simplify multiple result intrinsics to simpler things
3475 // that just get one value.
3476 if (!WO->hasOneUse())
3477 return nullptr;
3478
3479 // Check if we're grabbing only the result of a 'with overflow' intrinsic
3480 // and replace it with a traditional binary instruction.
3481 if (*EV.idx_begin() == 0) {
3482 Instruction::BinaryOps BinOp = WO->getBinaryOp();
3483 Value *LHS = WO->getLHS(), *RHS = WO->getRHS();
3484 // Replace the old instruction's uses with poison.
3485 replaceInstUsesWith(*WO, PoisonValue::get(WO->getType()));
3487 return BinaryOperator::Create(BinOp, LHS, RHS);
3488 }
3489
3490 assert(*EV.idx_begin() == 1 && "Unexpected extract index for overflow inst");
3491
3492 // (usub LHS, RHS) overflows when LHS is unsigned-less-than RHS.
3493 if (OvID == Intrinsic::usub_with_overflow)
3494 return new ICmpInst(ICmpInst::ICMP_ULT, WO->getLHS(), WO->getRHS());
3495
3496 // smul with i1 types overflows when both sides are set: -1 * -1 == +1, but
3497 // +1 is not possible because we assume signed values.
3498 if (OvID == Intrinsic::smul_with_overflow &&
3499 WO->getLHS()->getType()->isIntOrIntVectorTy(1))
3500 return BinaryOperator::CreateAnd(WO->getLHS(), WO->getRHS());
3501
3502 // extractvalue (umul_with_overflow X, X), 1 -> X u> 2^(N/2)-1
3503 if (OvID == Intrinsic::umul_with_overflow && WO->getLHS() == WO->getRHS()) {
3504 unsigned BitWidth = WO->getLHS()->getType()->getScalarSizeInBits();
3505 // Only handle even bitwidths for performance reasons.
3506 if (BitWidth % 2 == 0)
3507 return new ICmpInst(
3508 ICmpInst::ICMP_UGT, WO->getLHS(),
3509 ConstantInt::get(WO->getLHS()->getType(),
3511 }
3512
3513 // If only the overflow result is used, and the right hand side is a
3514 // constant (or constant splat), we can remove the intrinsic by directly
3515 // checking for overflow.
3516 if (C) {
3517 // Compute the no-wrap range for LHS given RHS=C, then construct an
3518 // equivalent icmp, potentially using an offset.
3520 WO->getBinaryOp(), *C, WO->getNoWrapKind());
3521
3522 CmpInst::Predicate Pred;
3523 APInt NewRHSC, Offset;
3524 NWR.getEquivalentICmp(Pred, NewRHSC, Offset);
3525 auto *OpTy = WO->getRHS()->getType();
3526 auto *NewLHS = WO->getLHS();
3527 if (Offset != 0)
3528 NewLHS = Builder.CreateAdd(NewLHS, ConstantInt::get(OpTy, Offset));
3529 return new ICmpInst(ICmpInst::getInversePredicate(Pred), NewLHS,
3530 ConstantInt::get(OpTy, NewRHSC));
3531 }
3532
3533 return nullptr;
3534}
3535
3537 Value *Agg = EV.getAggregateOperand();
3538
3539 if (!EV.hasIndices())
3540 return replaceInstUsesWith(EV, Agg);
3541
3542 if (Value *V = simplifyExtractValueInst(Agg, EV.getIndices(),
3543 SQ.getWithInstruction(&EV)))
3544 return replaceInstUsesWith(EV, V);
3545
3546 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
3547 // We're extracting from an insertvalue instruction, compare the indices
3548 const unsigned *exti, *exte, *insi, *inse;
3549 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
3550 exte = EV.idx_end(), inse = IV->idx_end();
3551 exti != exte && insi != inse;
3552 ++exti, ++insi) {
3553 if (*insi != *exti)
3554 // The insert and extract both reference distinctly different elements.
3555 // This means the extract is not influenced by the insert, and we can
3556 // replace the aggregate operand of the extract with the aggregate
3557 // operand of the insert. i.e., replace
3558 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
3559 // %E = extractvalue { i32, { i32 } } %I, 0
3560 // with
3561 // %E = extractvalue { i32, { i32 } } %A, 0
3562 return ExtractValueInst::Create(IV->getAggregateOperand(),
3563 EV.getIndices());
3564 }
3565 if (exti == exte && insi == inse)
3566 // Both iterators are at the end: Index lists are identical. Replace
3567 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
3568 // %C = extractvalue { i32, { i32 } } %B, 1, 0
3569 // with "i32 42"
3570 return replaceInstUsesWith(EV, IV->getInsertedValueOperand());
3571 if (exti == exte) {
3572 // The extract list is a prefix of the insert list. i.e. replace
3573 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
3574 // %E = extractvalue { i32, { i32 } } %I, 1
3575 // with
3576 // %X = extractvalue { i32, { i32 } } %A, 1
3577 // %E = insertvalue { i32 } %X, i32 42, 0
3578 // by switching the order of the insert and extract (though the
3579 // insertvalue should be left in, since it may have other uses).
3580 Value *NewEV = Builder.CreateExtractValue(IV->getAggregateOperand(),
3581 EV.getIndices());
3582 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
3583 ArrayRef(insi, inse));
3584 }
3585 if (insi == inse)
3586 // The insert list is a prefix of the extract list
3587 // We can simply remove the common indices from the extract and make it
3588 // operate on the inserted value instead of the insertvalue result.
3589 // i.e., replace
3590 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
3591 // %E = extractvalue { i32, { i32 } } %I, 1, 0
3592 // with
3593 // %E extractvalue { i32 } { i32 42 }, 0
3594 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
3595 ArrayRef(exti, exte));
3596 }
3597
3598 if (Instruction *R = foldExtractOfOverflowIntrinsic(EV))
3599 return R;
3600
3601 if (LoadInst *L = dyn_cast<LoadInst>(Agg)) {
3602 // Bail out if the aggregate contains scalable vector type
3603 if (auto *STy = dyn_cast<StructType>(Agg->getType());
3604 STy && STy->containsScalableVectorType())
3605 return nullptr;
3606
3607 // If the (non-volatile) load only has one use, we can rewrite this to a
3608 // load from a GEP. This reduces the size of the load. If a load is used
3609 // only by extractvalue instructions then this either must have been
3610 // optimized before, or it is a struct with padding, in which case we
3611 // don't want to do the transformation as it loses padding knowledge.
3612 if (L->isSimple() && L->hasOneUse()) {
3613 // extractvalue has integer indices, getelementptr has Value*s. Convert.
3614 SmallVector<Value*, 4> Indices;
3615 // Prefix an i32 0 since we need the first element.
3616 Indices.push_back(Builder.getInt32(0));
3617 for (unsigned Idx : EV.indices())
3618 Indices.push_back(Builder.getInt32(Idx));
3619
3620 // We need to insert these at the location of the old load, not at that of
3621 // the extractvalue.
3623 Value *GEP = Builder.CreateInBoundsGEP(L->getType(),
3624 L->getPointerOperand(), Indices);
3626 // Whatever aliasing information we had for the orignal load must also
3627 // hold for the smaller load, so propagate the annotations.
3628 NL->setAAMetadata(L->getAAMetadata());
3629 // Returning the load directly will cause the main loop to insert it in
3630 // the wrong spot, so use replaceInstUsesWith().
3631 return replaceInstUsesWith(EV, NL);
3632 }
3633 }
3634
3635 if (auto *PN = dyn_cast<PHINode>(Agg))
3636 if (Instruction *Res = foldOpIntoPhi(EV, PN))
3637 return Res;
3638
3639 // We could simplify extracts from other values. Note that nested extracts may
3640 // already be simplified implicitly by the above: extract (extract (insert) )
3641 // will be translated into extract ( insert ( extract ) ) first and then just
3642 // the value inserted, if appropriate. Similarly for extracts from single-use
3643 // loads: extract (extract (load)) will be translated to extract (load (gep))
3644 // and if again single-use then via load (gep (gep)) to load (gep).
3645 // However, double extracts from e.g. function arguments or return values
3646 // aren't handled yet.
3647 return nullptr;
3648}
3649
3650/// Return 'true' if the given typeinfo will match anything.
3651static bool isCatchAll(EHPersonality Personality, Constant *TypeInfo) {
3652 switch (Personality) {
3656 // The GCC C EH and Rust personality only exists to support cleanups, so
3657 // it's not clear what the semantics of catch clauses are.
3658 return false;
3660 return false;
3662 // While __gnat_all_others_value will match any Ada exception, it doesn't
3663 // match foreign exceptions (or didn't, before gcc-4.7).
3664 return false;
3674 return TypeInfo->isNullValue();
3675 }
3676 llvm_unreachable("invalid enum");
3677}
3678
3679static bool shorter_filter(const Value *LHS, const Value *RHS) {
3680 return
3681 cast<ArrayType>(LHS->getType())->getNumElements()
3682 <
3683 cast<ArrayType>(RHS->getType())->getNumElements();
3684}
3685
3687 // The logic here should be correct for any real-world personality function.
3688 // However if that turns out not to be true, the offending logic can always
3689 // be conditioned on the personality function, like the catch-all logic is.
3690 EHPersonality Personality =
3691 classifyEHPersonality(LI.getParent()->getParent()->getPersonalityFn());
3692
3693 // Simplify the list of clauses, eg by removing repeated catch clauses
3694 // (these are often created by inlining).
3695 bool MakeNewInstruction = false; // If true, recreate using the following:
3696 SmallVector<Constant *, 16> NewClauses; // - Clauses for the new instruction;
3697 bool CleanupFlag = LI.isCleanup(); // - The new instruction is a cleanup.
3698
3699 SmallPtrSet<Value *, 16> AlreadyCaught; // Typeinfos known caught already.
3700 for (unsigned i = 0, e = LI.getNumClauses(); i != e; ++i) {
3701 bool isLastClause = i + 1 == e;
3702 if (LI.isCatch(i)) {
3703 // A catch clause.
3704 Constant *CatchClause = LI.getClause(i);
3705 Constant *TypeInfo = CatchClause->stripPointerCasts();
3706
3707 // If we already saw this clause, there is no point in having a second
3708 // copy of it.
3709 if (AlreadyCaught.insert(TypeInfo).second) {
3710 // This catch clause was not already seen.
3711 NewClauses.push_back(CatchClause);
3712 } else {
3713 // Repeated catch clause - drop the redundant copy.
3714 MakeNewInstruction = true;
3715 }
3716
3717 // If this is a catch-all then there is no point in keeping any following
3718 // clauses or marking the landingpad as having a cleanup.
3719 if (isCatchAll(Personality, TypeInfo)) {
3720 if (!isLastClause)
3721 MakeNewInstruction = true;
3722 CleanupFlag = false;
3723 break;
3724 }
3725 } else {
3726 // A filter clause. If any of the filter elements were already caught
3727 // then they can be dropped from the filter. It is tempting to try to
3728 // exploit the filter further by saying that any typeinfo that does not
3729 // occur in the filter can't be caught later (and thus can be dropped).
3730 // However this would be wrong, since typeinfos can match without being
3731 // equal (for example if one represents a C++ class, and the other some
3732 // class derived from it).
3733 assert(LI.isFilter(i) && "Unsupported landingpad clause!");
3734 Constant *FilterClause = LI.getClause(i);
3735 ArrayType *FilterType = cast<ArrayType>(FilterClause->getType());
3736 unsigned NumTypeInfos = FilterType->getNumElements();
3737
3738 // An empty filter catches everything, so there is no point in keeping any
3739 // following clauses or marking the landingpad as having a cleanup. By
3740 // dealing with this case here the following code is made a bit simpler.
3741 if (!NumTypeInfos) {
3742 NewClauses.push_back(FilterClause);
3743 if (!isLastClause)
3744 MakeNewInstruction = true;
3745 CleanupFlag = false;
3746 break;
3747 }
3748
3749 bool MakeNewFilter = false; // If true, make a new filter.
3750 SmallVector<Constant *, 16> NewFilterElts; // New elements.
3751 if (isa<ConstantAggregateZero>(FilterClause)) {
3752 // Not an empty filter - it contains at least one null typeinfo.
3753 assert(NumTypeInfos > 0 && "Should have handled empty filter already!");
3754 Constant *TypeInfo =
3756 // If this typeinfo is a catch-all then the filter can never match.
3757 if (isCatchAll(Personality, TypeInfo)) {
3758 // Throw the filter away.
3759 MakeNewInstruction = true;
3760 continue;
3761 }
3762
3763 // There is no point in having multiple copies of this typeinfo, so
3764 // discard all but the first copy if there is more than one.
3765 NewFilterElts.push_back(TypeInfo);
3766 if (NumTypeInfos > 1)
3767 MakeNewFilter = true;
3768 } else {
3769 ConstantArray *Filter = cast<ConstantArray>(FilterClause);
3770 SmallPtrSet<Value *, 16> SeenInFilter; // For uniquing the elements.
3771 NewFilterElts.reserve(NumTypeInfos);
3772
3773 // Remove any filter elements that were already caught or that already
3774 // occurred in the filter. While there, see if any of the elements are
3775 // catch-alls. If so, the filter can be discarded.
3776 bool SawCatchAll = false;
3777 for (unsigned j = 0; j != NumTypeInfos; ++j) {
3778 Constant *Elt = Filter->getOperand(j);
3779 Constant *TypeInfo = Elt->stripPointerCasts();
3780 if (isCatchAll(Personality, TypeInfo)) {
3781 // This element is a catch-all. Bail out, noting this fact.
3782 SawCatchAll = true;
3783 break;
3784 }
3785
3786 // Even if we've seen a type in a catch clause, we don't want to
3787 // remove it from the filter. An unexpected type handler may be
3788 // set up for a call site which throws an exception of the same
3789 // type caught. In order for the exception thrown by the unexpected
3790 // handler to propagate correctly, the filter must be correctly
3791 // described for the call site.
3792 //
3793 // Example:
3794 //
3795 // void unexpected() { throw 1;}
3796 // void foo() throw (int) {
3797 // std::set_unexpected(unexpected);
3798 // try {
3799 // throw 2.0;
3800 // } catch (int i) {}
3801 // }
3802
3803 // There is no point in having multiple copies of the same typeinfo in
3804 // a filter, so only add it if we didn't already.
3805 if (SeenInFilter.insert(TypeInfo).second)
3806 NewFilterElts.push_back(cast<Constant>(Elt));
3807 }
3808 // A filter containing a catch-all cannot match anything by definition.
3809 if (SawCatchAll) {
3810 // Throw the filter away.
3811 MakeNewInstruction = true;
3812 continue;
3813 }
3814
3815 // If we dropped something from the filter, make a new one.
3816 if (NewFilterElts.size() < NumTypeInfos)
3817 MakeNewFilter = true;
3818 }
3819 if (MakeNewFilter) {
3820 FilterType = ArrayType::get(FilterType->getElementType(),
3821 NewFilterElts.size());
3822 FilterClause = ConstantArray::get(FilterType, NewFilterElts);
3823 MakeNewInstruction = true;
3824 }
3825
3826 NewClauses.push_back(FilterClause);
3827
3828 // If the new filter is empty then it will catch everything so there is
3829 // no point in keeping any following clauses or marking the landingpad
3830 // as having a cleanup. The case of the original filter being empty was
3831 // already handled above.
3832 if (MakeNewFilter && !NewFilterElts.size()) {
3833 assert(MakeNewInstruction && "New filter but not a new instruction!");
3834 CleanupFlag = false;
3835 break;
3836 }
3837 }
3838 }
3839
3840 // If several filters occur in a row then reorder them so that the shortest
3841 // filters come first (those with the smallest number of elements). This is
3842 // advantageous because shorter filters are more likely to match, speeding up
3843 // unwinding, but mostly because it increases the effectiveness of the other
3844 // filter optimizations below.
3845 for (unsigned i = 0, e = NewClauses.size(); i + 1 < e; ) {
3846 unsigned j;
3847 // Find the maximal 'j' s.t. the range [i, j) consists entirely of filters.
3848 for (j = i; j != e; ++j)
3849 if (!isa<ArrayType>(NewClauses[j]->getType()))
3850 break;
3851
3852 // Check whether the filters are already sorted by length. We need to know
3853 // if sorting them is actually going to do anything so that we only make a
3854 // new landingpad instruction if it does.
3855 for (unsigned k = i; k + 1 < j; ++k)
3856 if (shorter_filter(NewClauses[k+1], NewClauses[k])) {
3857 // Not sorted, so sort the filters now. Doing an unstable sort would be
3858 // correct too but reordering filters pointlessly might confuse users.
3859 std::stable_sort(NewClauses.begin() + i, NewClauses.begin() + j,
3861 MakeNewInstruction = true;
3862 break;
3863 }
3864
3865 // Look for the next batch of filters.
3866 i = j + 1;
3867 }
3868
3869 // If typeinfos matched if and only if equal, then the elements of a filter L
3870 // that occurs later than a filter F could be replaced by the intersection of
3871 // the elements of F and L. In reality two typeinfos can match without being
3872 // equal (for example if one represents a C++ class, and the other some class
3873 // derived from it) so it would be wrong to perform this transform in general.
3874 // However the transform is correct and useful if F is a subset of L. In that
3875 // case L can be replaced by F, and thus removed altogether since repeating a
3876 // filter is pointless. So here we look at all pairs of filters F and L where
3877 // L follows F in the list of clauses, and remove L if every element of F is
3878 // an element of L. This can occur when inlining C++ functions with exception
3879 // specifications.
3880 for (unsigned i = 0; i + 1 < NewClauses.size(); ++i) {
3881 // Examine each filter in turn.
3882 Value *Filter = NewClauses[i];
3883 ArrayType *FTy = dyn_cast<ArrayType>(Filter->getType());
3884 if (!FTy)
3885 // Not a filter - skip it.
3886 continue;
3887 unsigned FElts = FTy->getNumElements();
3888 // Examine each filter following this one. Doing this backwards means that
3889 // we don't have to worry about filters disappearing under us when removed.
3890 for (unsigned j = NewClauses.size() - 1; j != i; --j) {
3891 Value *LFilter = NewClauses[j];
3892 ArrayType *LTy = dyn_cast<ArrayType>(LFilter->getType());
3893 if (!LTy)
3894 // Not a filter - skip it.
3895 continue;
3896 // If Filter is a subset of LFilter, i.e. every element of Filter is also
3897 // an element of LFilter, then discard LFilter.
3898 SmallVectorImpl<Constant *>::iterator J = NewClauses.begin() + j;
3899 // If Filter is empty then it is a subset of LFilter.
3900 if (!FElts) {
3901 // Discard LFilter.
3902 NewClauses.erase(J);
3903 MakeNewInstruction = true;
3904 // Move on to the next filter.
3905 continue;
3906 }
3907 unsigned LElts = LTy->getNumElements();
3908 // If Filter is longer than LFilter then it cannot be a subset of it.
3909 if (FElts > LElts)
3910 // Move on to the next filter.
3911 continue;
3912 // At this point we know that LFilter has at least one element.
3913 if (isa<ConstantAggregateZero>(LFilter)) { // LFilter only contains zeros.
3914 // Filter is a subset of LFilter iff Filter contains only zeros (as we
3915 // already know that Filter is not longer than LFilter).
3916 if (isa<ConstantAggregateZero>(Filter)) {
3917 assert(FElts <= LElts && "Should have handled this case earlier!");
3918 // Discard LFilter.
3919 NewClauses.erase(J);
3920 MakeNewInstruction = true;
3921 }
3922 // Move on to the next filter.
3923 continue;
3924 }
3925 ConstantArray *LArray = cast<ConstantArray>(LFilter);
3926 if (isa<ConstantAggregateZero>(Filter)) { // Filter only contains zeros.
3927 // Since Filter is non-empty and contains only zeros, it is a subset of
3928 // LFilter iff LFilter contains a zero.
3929 assert(FElts > 0 && "Should have eliminated the empty filter earlier!");
3930 for (unsigned l = 0; l != LElts; ++l)
3931 if (LArray->getOperand(l)->isNullValue()) {
3932 // LFilter contains a zero - discard it.
3933 NewClauses.erase(J);
3934 MakeNewInstruction = true;
3935 break;
3936 }
3937 // Move on to the next filter.
3938 continue;
3939 }
3940 // At this point we know that both filters are ConstantArrays. Loop over
3941 // operands to see whether every element of Filter is also an element of
3942 // LFilter. Since filters tend to be short this is probably faster than
3943 // using a method that scales nicely.
3944 ConstantArray *FArray = cast<ConstantArray>(Filter);
3945 bool AllFound = true;
3946 for (unsigned f = 0; f != FElts; ++f) {
3947 Value *FTypeInfo = FArray->getOperand(f)->stripPointerCasts();
3948 AllFound = false;
3949 for (unsigned l = 0; l != LElts; ++l) {
3950 Value *LTypeInfo = LArray->getOperand(l)->stripPointerCasts();
3951 if (LTypeInfo == FTypeInfo) {
3952 AllFound = true;
3953 break;
3954 }
3955 }
3956 if (!AllFound)
3957 break;
3958 }
3959 if (AllFound) {
3960 // Discard LFilter.
3961 NewClauses.erase(J);
3962 MakeNewInstruction = true;
3963 }
3964 // Move on to the next filter.
3965 }
3966 }
3967
3968 // If we changed any of the clauses, replace the old landingpad instruction
3969 // with a new one.
3970 if (MakeNewInstruction) {
3971 LandingPadInst *NLI = LandingPadInst::Create(LI.getType(),
3972 NewClauses.size());
3973 for (unsigned i = 0, e = NewClauses.size(); i != e; ++i)
3974 NLI->addClause(NewClauses[i]);
3975 // A landing pad with no clauses must have the cleanup flag set. It is
3976 // theoretically possible, though highly unlikely, that we eliminated all
3977 // clauses. If so, force the cleanup flag to true.
3978 if (NewClauses.empty())
3979 CleanupFlag = true;
3980 NLI->setCleanup(CleanupFlag);
3981 return NLI;
3982 }
3983
3984 // Even if none of the clauses changed, we may nonetheless have understood
3985 // that the cleanup flag is pointless. Clear it if so.
3986 if (LI.isCleanup() != CleanupFlag) {
3987 assert(!CleanupFlag && "Adding a cleanup, not removing one?!");
3988 LI.setCleanup(CleanupFlag);
3989 return &LI;
3990 }
3991
3992 return nullptr;
3993}
3994
3995Value *
3997 // Try to push freeze through instructions that propagate but don't produce
3998 // poison as far as possible. If an operand of freeze follows three
3999 // conditions 1) one-use, 2) does not produce poison, and 3) has all but one
4000 // guaranteed-non-poison operands then push the freeze through to the one
4001 // operand that is not guaranteed non-poison. The actual transform is as
4002 // follows.
4003 // Op1 = ... ; Op1 can be posion
4004 // Op0 = Inst(Op1, NonPoisonOps...) ; Op0 has only one use and only have
4005 // ; single guaranteed-non-poison operands
4006 // ... = Freeze(Op0)
4007 // =>
4008 // Op1 = ...
4009 // Op1.fr = Freeze(Op1)
4010 // ... = Inst(Op1.fr, NonPoisonOps...)
4011 auto *OrigOp = OrigFI.getOperand(0);
4012 auto *OrigOpInst = dyn_cast<Instruction>(OrigOp);
4013
4014 // While we could change the other users of OrigOp to use freeze(OrigOp), that
4015 // potentially reduces their optimization potential, so let's only do this iff
4016 // the OrigOp is only used by the freeze.
4017 if (!OrigOpInst || !OrigOpInst->hasOneUse() || isa<PHINode>(OrigOp))
4018 return nullptr;
4019
4020 // We can't push the freeze through an instruction which can itself create
4021 // poison. If the only source of new poison is flags, we can simply
4022 // strip them (since we know the only use is the freeze and nothing can
4023 // benefit from them.)
4024 if (canCreateUndefOrPoison(cast<Operator>(OrigOp),
4025 /*ConsiderFlagsAndMetadata*/ false))
4026 return nullptr;
4027
4028 // If operand is guaranteed not to be poison, there is no need to add freeze
4029 // to the operand. So we first find the operand that is not guaranteed to be
4030 // poison.
4031 Use *MaybePoisonOperand = nullptr;
4032 for (Use &U : OrigOpInst->operands()) {
4033 if (isa<MetadataAsValue>(U.get()) ||
4035 continue;
4036 if (!MaybePoisonOperand)
4037 MaybePoisonOperand = &U;
4038 else
4039 return nullptr;
4040 }
4041
4042 OrigOpInst->dropPoisonGeneratingFlagsAndMetadata();
4043
4044 // If all operands are guaranteed to be non-poison, we can drop freeze.
4045 if (!MaybePoisonOperand)
4046 return OrigOp;
4047
4048 Builder.SetInsertPoint(OrigOpInst);
4049 auto *FrozenMaybePoisonOperand = Builder.CreateFreeze(
4050 MaybePoisonOperand->get(), MaybePoisonOperand->get()->getName() + ".fr");
4051
4052 replaceUse(*MaybePoisonOperand, FrozenMaybePoisonOperand);
4053 return OrigOp;
4054}
4055
4057 PHINode *PN) {
4058 // Detect whether this is a recurrence with a start value and some number of
4059 // backedge values. We'll check whether we can push the freeze through the
4060 // backedge values (possibly dropping poison flags along the way) until we
4061 // reach the phi again. In that case, we can move the freeze to the start
4062 // value.
4063 Use *StartU = nullptr;
4065 for (Use &U : PN->incoming_values()) {
4066 if (DT.dominates(PN->getParent(), PN->getIncomingBlock(U))) {
4067 // Add backedge value to worklist.
4068 Worklist.push_back(U.get());
4069 continue;
4070 }
4071
4072 // Don't bother handling multiple start values.
4073 if (StartU)
4074 return nullptr;
4075 StartU = &U;
4076 }
4077
4078 if (!StartU || Worklist.empty())
4079 return nullptr; // Not a recurrence.
4080
4081 Value *StartV = StartU->get();
4082 BasicBlock *StartBB = PN->getIncomingBlock(*StartU);
4083 bool StartNeedsFreeze = !isGuaranteedNotToBeUndefOrPoison(StartV);
4084 // We can't insert freeze if the start value is the result of the
4085 // terminator (e.g. an invoke).
4086 if (StartNeedsFreeze && StartBB->getTerminator() == StartV)
4087 return nullptr;
4088
4091 while (!Worklist.empty()) {
4092 Value *V = Worklist.pop_back_val();
4093 if (!Visited.insert(V).second)
4094 continue;
4095
4096 if (Visited.size() > 32)
4097 return nullptr; // Limit the total number of values we inspect.
4098
4099 // Assume that PN is non-poison, because it will be after the transform.
4100 if (V == PN || isGuaranteedNotToBeUndefOrPoison(V))
4101 continue;
4102
4103 Instruction *I = dyn_cast<Instruction>(V);
4104 if (!I || canCreateUndefOrPoison(cast<Operator>(I),
4105 /*ConsiderFlagsAndMetadata*/ false))
4106 return nullptr;
4107
4108 DropFlags.push_back(I);
4109 append_range(Worklist, I->operands());
4110 }
4111
4112 for (Instruction *I : DropFlags)
4113 I->dropPoisonGeneratingFlagsAndMetadata();
4114
4115 if (StartNeedsFreeze) {
4117 Value *FrozenStartV = Builder.CreateFreeze(StartV,
4118 StartV->getName() + ".fr");
4119 replaceUse(*StartU, FrozenStartV);
4120 }
4121 return replaceInstUsesWith(FI, PN);
4122}
4123
4125 Value *Op = FI.getOperand(0);
4126
4127 if (isa<Constant>(Op) || Op->hasOneUse())
4128 return false;
4129
4130 // Move the freeze directly after the definition of its operand, so that
4131 // it dominates the maximum number of uses. Note that it may not dominate
4132 // *all* uses if the operand is an invoke/callbr and the use is in a phi on
4133 // the normal/default destination. This is why the domination check in the
4134 // replacement below is still necessary.
4135 BasicBlock::iterator MoveBefore;
4136 if (isa<Argument>(Op)) {
4137 MoveBefore =
4139 } else {
4140 auto MoveBeforeOpt = cast<Instruction>(Op)->getInsertionPointAfterDef();
4141 if (!MoveBeforeOpt)
4142 return false;
4143 MoveBefore = *MoveBeforeOpt;
4144 }
4145
4146 // Don't move to the position of a debug intrinsic.
4147 if (isa<DbgInfoIntrinsic>(MoveBefore))
4148 MoveBefore = MoveBefore->getNextNonDebugInstruction()->getIterator();
4149 // Re-point iterator to come after any debug-info records, if we're
4150 // running in "RemoveDIs" mode
4151 MoveBefore.setHeadBit(false);
4152
4153 bool Changed = false;
4154 if (&FI != &*MoveBefore) {
4155 FI.moveBefore(*MoveBefore->getParent(), MoveBefore);
4156 Changed = true;
4157 }
4158
4159 Op->replaceUsesWithIf(&FI, [&](Use &U) -> bool {
4160 bool Dominates = DT.dominates(&FI, U);
4161 Changed |= Dominates;
4162 return Dominates;
4163 });
4164
4165 return Changed;
4166}
4167
4168// Check if any direct or bitcast user of this value is a shuffle instruction.
4170 for (auto *U : V->users()) {
4171 if (isa<ShuffleVectorInst>(U))
4172 return true;
4173 else if (match(U, m_BitCast(m_Specific(V))) && isUsedWithinShuffleVector(U))
4174 return true;
4175 }
4176 return false;
4177}
4178
4180 Value *Op0 = I.getOperand(0);
4181
4183 return replaceInstUsesWith(I, V);
4184
4185 // freeze (phi const, x) --> phi const, (freeze x)
4186 if (auto *PN = dyn_cast<PHINode>(Op0)) {
4187 if (Instruction *NV = foldOpIntoPhi(I, PN))
4188 return NV;
4189 if (Instruction *NV = foldFreezeIntoRecurrence(I, PN))
4190 return NV;
4191 }
4192
4194 return replaceInstUsesWith(I, NI);
4195
4196 // If I is freeze(undef), check its uses and fold it to a fixed constant.
4197 // - or: pick -1
4198 // - select's condition: if the true value is constant, choose it by making
4199 // the condition true.
4200 // - default: pick 0
4201 //
4202 // Note that this transform is intentionally done here rather than
4203 // via an analysis in InstSimplify or at individual user sites. That is
4204 // because we must produce the same value for all uses of the freeze -
4205 // it's the reason "freeze" exists!
4206 //
4207 // TODO: This could use getBinopAbsorber() / getBinopIdentity() to avoid
4208 // duplicating logic for binops at least.
4209 auto getUndefReplacement = [&I](Type *Ty) {
4210 Constant *BestValue = nullptr;
4211 Constant *NullValue = Constant::getNullValue(Ty);
4212 for (const auto *U : I.users()) {
4213 Constant *C = NullValue;
4214 if (match(U, m_Or(m_Value(), m_Value())))
4216 else if (match(U, m_Select(m_Specific(&I), m_Constant(), m_Value())))
4217 C = ConstantInt::getTrue(Ty);
4218
4219 if (!BestValue)
4220 BestValue = C;
4221 else if (BestValue != C)
4222 BestValue = NullValue;
4223 }
4224 assert(BestValue && "Must have at least one use");
4225 return BestValue;
4226 };
4227
4228 if (match(Op0, m_Undef())) {
4229 // Don't fold freeze(undef/poison) if it's used as a vector operand in
4230 // a shuffle. This may improve codegen for shuffles that allow
4231 // unspecified inputs.
4233 return nullptr;
4234 return replaceInstUsesWith(I, getUndefReplacement(I.getType()));
4235 }
4236
4237 Constant *C;
4238 if (match(Op0, m_Constant(C)) && C->containsUndefOrPoisonElement()) {
4239 Constant *ReplaceC = getUndefReplacement(I.getType()->getScalarType());
4241 }
4242
4243 // Replace uses of Op with freeze(Op).
4244 if (freezeOtherUses(I))
4245 return &I;
4246
4247 return nullptr;
4248}
4249
4250/// Check for case where the call writes to an otherwise dead alloca. This
4251/// shows up for unused out-params in idiomatic C/C++ code. Note that this
4252/// helper *only* analyzes the write; doesn't check any other legality aspect.
4254 auto *CB = dyn_cast<CallBase>(I);
4255 if (!CB)
4256 // TODO: handle e.g. store to alloca here - only worth doing if we extend
4257 // to allow reload along used path as described below. Otherwise, this
4258 // is simply a store to a dead allocation which will be removed.
4259 return false;
4260 std::optional<MemoryLocation> Dest = MemoryLocation::getForDest(CB, TLI);
4261 if (!Dest)
4262 return false;
4263 auto *AI = dyn_cast<AllocaInst>(getUnderlyingObject(Dest->Ptr));
4264 if (!AI)
4265 // TODO: allow malloc?
4266 return false;
4267 // TODO: allow memory access dominated by move point? Note that since AI
4268 // could have a reference to itself captured by the call, we would need to
4269 // account for cycles in doing so.
4270 SmallVector<const User *> AllocaUsers;
4272 auto pushUsers = [&](const Instruction &I) {
4273 for (const User *U : I.users()) {
4274 if (Visited.insert(U).second)
4275 AllocaUsers.push_back(U);
4276 }
4277 };
4278 pushUsers(*AI);
4279 while (!AllocaUsers.empty()) {
4280 auto *UserI = cast<Instruction>(AllocaUsers.pop_back_val());
4281 if (isa<BitCastInst>(UserI) || isa<GetElementPtrInst>(UserI) ||
4282 isa<AddrSpaceCastInst>(UserI)) {
4283 pushUsers(*UserI);
4284 continue;
4285 }
4286 if (UserI == CB)
4287 continue;
4288 // TODO: support lifetime.start/end here
4289 return false;
4290 }
4291 return true;
4292}
4293
4294/// Try to move the specified instruction from its current block into the
4295/// beginning of DestBlock, which can only happen if it's safe to move the
4296/// instruction past all of the instructions between it and the end of its
4297/// block.
4299 BasicBlock *DestBlock) {
4300 BasicBlock *SrcBlock = I->getParent();
4301
4302 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
4303 if (isa<PHINode>(I) || I->isEHPad() || I->mayThrow() || !I->willReturn() ||
4304 I->isTerminator())
4305 return false;
4306
4307 // Do not sink static or dynamic alloca instructions. Static allocas must
4308 // remain in the entry block, and dynamic allocas must not be sunk in between
4309 // a stacksave / stackrestore pair, which would incorrectly shorten its
4310 // lifetime.
4311 if (isa<AllocaInst>(I))
4312 return false;
4313
4314 // Do not sink into catchswitch blocks.
4315 if (isa<CatchSwitchInst>(DestBlock->getTerminator()))
4316 return false;
4317
4318 // Do not sink convergent call instructions.
4319 if (auto *CI = dyn_cast<CallInst>(I)) {
4320 if (CI->isConvergent())
4321 return false;
4322 }
4323
4324 // Unless we can prove that the memory write isn't visibile except on the
4325 // path we're sinking to, we must bail.
4326 if (I->mayWriteToMemory()) {
4327 if (!SoleWriteToDeadLocal(I, TLI))
4328 return false;
4329 }
4330
4331 // We can only sink load instructions if there is nothing between the load and
4332 // the end of block that could change the value.
4333 if (I->mayReadFromMemory()) {
4334 // We don't want to do any sophisticated alias analysis, so we only check
4335 // the instructions after I in I's parent block if we try to sink to its
4336 // successor block.
4337 if (DestBlock->getUniquePredecessor() != I->getParent())
4338 return false;
4339 for (BasicBlock::iterator Scan = std::next(I->getIterator()),
4340 E = I->getParent()->end();
4341 Scan != E; ++Scan)
4342 if (Scan->mayWriteToMemory())
4343 return false;
4344 }
4345
4346 I->dropDroppableUses([&](const Use *U) {
4347 auto *I = dyn_cast<Instruction>(U->getUser());
4348 if (I && I->getParent() != DestBlock) {
4349 Worklist.add(I);
4350 return true;
4351 }
4352 return false;
4353 });
4354 /// FIXME: We could remove droppable uses that are not dominated by
4355 /// the new position.
4356
4357 BasicBlock::iterator InsertPos = DestBlock->getFirstInsertionPt();
4358 I->moveBefore(*DestBlock, InsertPos);
4359 ++NumSunkInst;
4360
4361 // Also sink all related debug uses from the source basic block. Otherwise we
4362 // get debug use before the def. Attempt to salvage debug uses first, to
4363 // maximise the range variables have location for. If we cannot salvage, then
4364 // mark the location undef: we know it was supposed to receive a new location
4365 // here, but that computation has been sunk.
4368 findDbgUsers(DbgUsers, I, &DPValues);
4369 if (!DbgUsers.empty())
4370 tryToSinkInstructionDbgValues(I, InsertPos, SrcBlock, DestBlock, DbgUsers);
4371 if (!DPValues.empty())
4372 tryToSinkInstructionDPValues(I, InsertPos, SrcBlock, DestBlock, DPValues);
4373
4374 // PS: there are numerous flaws with this behaviour, not least that right now
4375 // assignments can be re-ordered past other assignments to the same variable
4376 // if they use different Values. Creating more undef assignements can never be
4377 // undone. And salvaging all users outside of this block can un-necessarily
4378 // alter the lifetime of the live-value that the variable refers to.
4379 // Some of these things can be resolved by tolerating debug use-before-defs in
4380 // LLVM-IR, however it depends on the instruction-referencing CodeGen backend
4381 // being used for more architectures.
4382
4383 return true;
4384}
4385
4387 Instruction *I, BasicBlock::iterator InsertPos, BasicBlock *SrcBlock,
4389 // For all debug values in the destination block, the sunk instruction
4390 // will still be available, so they do not need to be dropped.
4392 for (auto &DbgUser : DbgUsers)
4393 if (DbgUser->getParent() != DestBlock)
4394 DbgUsersToSalvage.push_back(DbgUser);
4395
4396 // Process the sinking DbgUsersToSalvage in reverse order, as we only want
4397 // to clone the last appearing debug intrinsic for each given variable.
4399 for (DbgVariableIntrinsic *DVI : DbgUsersToSalvage)
4400 if (DVI->getParent() == SrcBlock)
4401 DbgUsersToSink.push_back(DVI);
4402 llvm::sort(DbgUsersToSink,
4403 [](auto *A, auto *B) { return B->comesBefore(A); });
4404
4406 SmallSet<DebugVariable, 4> SunkVariables;
4407 for (auto *User : DbgUsersToSink) {
4408 // A dbg.declare instruction should not be cloned, since there can only be
4409 // one per variable fragment. It should be left in the original place
4410 // because the sunk instruction is not an alloca (otherwise we could not be
4411 // here).
4412 if (isa<DbgDeclareInst>(User))
4413 continue;
4414
4415 DebugVariable DbgUserVariable =
4416 DebugVariable(User->getVariable(), User->getExpression(),
4417 User->getDebugLoc()->getInlinedAt());
4418
4419 if (!SunkVariables.insert(DbgUserVariable).second)
4420 continue;
4421
4422 // Leave dbg.assign intrinsics in their original positions and there should
4423 // be no need to insert a clone.
4424 if (isa<DbgAssignIntrinsic>(User))
4425 continue;
4426
4427 DIIClones.emplace_back(cast<DbgVariableIntrinsic>(User->clone()));
4428 if (isa<DbgDeclareInst>(User) && isa<CastInst>(I))
4429 DIIClones.back()->replaceVariableLocationOp(I, I->getOperand(0));
4430 LLVM_DEBUG(dbgs() << "CLONE: " << *DIIClones.back() << '\n');
4431 }
4432
4433 // Perform salvaging without the clones, then sink the clones.
4434 if (!DIIClones.empty()) {
4435 salvageDebugInfoForDbgValues(*I, DbgUsersToSalvage, {});
4436 // The clones are in reverse order of original appearance, reverse again to
4437 // maintain the original order.
4438 for (auto &DIIClone : llvm::reverse(DIIClones)) {
4439 DIIClone->insertBefore(&*InsertPos);
4440 LLVM_DEBUG(dbgs() << "SINK: " << *DIIClone << '\n');
4441 }
4442 }
4443}
4444
4446 Instruction *I, BasicBlock::iterator InsertPos, BasicBlock *SrcBlock,
4447 BasicBlock *DestBlock, SmallVectorImpl<DPValue *> &DPValues) {
4448 // Implementation of tryToSinkInstructionDbgValues, but for the DPValue of
4449 // variable assignments rather than dbg.values.
4450
4451 // Fetch all DPValues not already in the destination.
4452 SmallVector<DPValue *, 2> DPValuesToSalvage;
4453 for (auto &DPV : DPValues)
4454 if (DPV->getParent() != DestBlock)
4455 DPValuesToSalvage.push_back(DPV);
4456
4457 // Fetch a second collection, of DPValues in the source block that we're going
4458 // to sink.
4459 SmallVector<DPValue *> DPValuesToSink;
4460 for (DPValue *DPV : DPValuesToSalvage)
4461 if (DPV->getParent() == SrcBlock)
4462 DPValuesToSink.push_back(DPV);
4463
4464 // Sort DPValues according to their position in the block. This is a partial
4465 // order: DPValues attached to different instructions will be ordered by the
4466 // instruction order, but DPValues attached to the same instruction won't
4467 // have an order.
4468 auto Order = [](DPValue *A, DPValue *B) -> bool {
4469 return B->getInstruction()->comesBefore(A->getInstruction());
4470 };
4471 llvm::stable_sort(DPValuesToSink, Order);
4472
4473 // If there are two assignments to the same variable attached to the same
4474 // instruction, the ordering between the two assignments is important. Scan
4475 // for this (rare) case and establish which is the last assignment.
4476 using InstVarPair = std::pair<const Instruction *, DebugVariable>;
4478 if (DPValuesToSink.size() > 1) {
4480 // Count how many assignments to each variable there is per instruction.
4481 for (DPValue *DPV : DPValuesToSink) {
4482 DebugVariable DbgUserVariable =
4483 DebugVariable(DPV->getVariable(), DPV->getExpression(),
4484 DPV->getDebugLoc()->getInlinedAt());
4485 CountMap[std::make_pair(DPV->getInstruction(), DbgUserVariable)] += 1;
4486 }
4487
4488 // If there are any instructions with two assignments, add them to the
4489 // FilterOutMap to record that they need extra filtering.
4491 for (auto It : CountMap) {
4492 if (It.second > 1) {
4493 FilterOutMap[It.first] = nullptr;
4494 DupSet.insert(It.first.first);
4495 }
4496 }
4497
4498 // For all instruction/variable pairs needing extra filtering, find the
4499 // latest assignment.
4500 for (const Instruction *Inst : DupSet) {
4501 for (DPValue &DPV :
4502 llvm::reverse(DPValue::filter(Inst->getDbgValueRange()))) {
4503 DebugVariable DbgUserVariable =
4504 DebugVariable(DPV.getVariable(), DPV.getExpression(),
4505 DPV.getDebugLoc()->getInlinedAt());
4506 auto FilterIt =
4507 FilterOutMap.find(std::make_pair(Inst, DbgUserVariable));
4508 if (FilterIt == FilterOutMap.end())
4509 continue;
4510 if (FilterIt->second != nullptr)
4511 continue;
4512 FilterIt->second = &DPV;
4513 }
4514 }
4515 }
4516
4517 // Perform cloning of the DPValues that we plan on sinking, filter out any
4518 // duplicate assignments identified above.
4519 SmallVector<DPValue *, 2> DPVClones;
4520 SmallSet<DebugVariable, 4> SunkVariables;
4521 for (DPValue *DPV : DPValuesToSink) {
4522 if (DPV->Type == DPValue::LocationType::Declare)
4523 continue;
4524
4525 DebugVariable DbgUserVariable =
4526 DebugVariable(DPV->getVariable(), DPV->getExpression(),
4527 DPV->getDebugLoc()->getInlinedAt());
4528
4529 // For any variable where there were multiple assignments in the same place,
4530 // ignore all but the last assignment.
4531 if (!FilterOutMap.empty()) {
4532 InstVarPair IVP = std::make_pair(DPV->getInstruction(), DbgUserVariable);
4533 auto It = FilterOutMap.find(IVP);
4534
4535 // Filter out.
4536 if (It != FilterOutMap.end() && It->second != DPV)
4537 continue;
4538 }
4539
4540 if (!SunkVariables.insert(DbgUserVariable).second)
4541 continue;
4542
4543 if (DPV->isDbgAssign())
4544 continue;
4545
4546 DPVClones.emplace_back(DPV->clone());
4547 LLVM_DEBUG(dbgs() << "CLONE: " << *DPVClones.back() << '\n');
4548 }
4549
4550 // Perform salvaging without the clones, then sink the clones.
4551 if (DPVClones.empty())
4552 return;
4553
4554 salvageDebugInfoForDbgValues(*I, {}, DPValuesToSalvage);
4555
4556 // The clones are in reverse order of original appearance. Assert that the
4557 // head bit is set on the iterator as we _should_ have received it via
4558 // getFirstInsertionPt. Inserting like this will reverse the clone order as
4559 // we'll repeatedly insert at the head, such as:
4560 // DPV-3 (third insertion goes here)
4561 // DPV-2 (second insertion goes here)
4562 // DPV-1 (first insertion goes here)
4563 // Any-Prior-DPVs
4564 // InsertPtInst
4565 assert(InsertPos.getHeadBit());
4566 for (DPValue *DPVClone : DPVClones) {
4567 InsertPos->getParent()->insertDPValueBefore(DPVClone, InsertPos);
4568 LLVM_DEBUG(dbgs() << "SINK: " << *DPVClone << '\n');
4569 }
4570}
4571
4573 while (!Worklist.isEmpty()) {
4574 // Walk deferred instructions in reverse order, and push them to the
4575 // worklist, which means they'll end up popped from the worklist in-order.
4576 while (Instruction *I = Worklist.popDeferred()) {
4577 // Check to see if we can DCE the instruction. We do this already here to
4578 // reduce the number of uses and thus allow other folds to trigger.
4579 // Note that eraseInstFromFunction() may push additional instructions on
4580 // the deferred worklist, so this will DCE whole instruction chains.
4583 ++NumDeadInst;
4584 continue;
4585 }
4586
4587 Worklist.push(I);
4588 }
4589
4591 if (I == nullptr) continue; // skip null values.
4592
4593 // Check to see if we can DCE the instruction.
4596 ++NumDeadInst;
4597 continue;
4598 }
4599
4600 if (!DebugCounter::shouldExecute(VisitCounter))
4601 continue;
4602
4603 // See if we can trivially sink this instruction to its user if we can
4604 // prove that the successor is not executed more frequently than our block.
4605 // Return the UserBlock if successful.
4606 auto getOptionalSinkBlockForInst =
4607 [this](Instruction *I) -> std::optional<BasicBlock *> {
4608 if (!EnableCodeSinking)
4609 return std::nullopt;
4610
4611 BasicBlock *BB = I->getParent();
4612 BasicBlock *UserParent = nullptr;
4613 unsigned NumUsers = 0;
4614
4615 for (auto *U : I->users()) {
4616 if (U->isDroppable())
4617 continue;
4618 if (NumUsers > MaxSinkNumUsers)
4619 return std::nullopt;
4620
4621 Instruction *UserInst = cast<Instruction>(U);
4622 // Special handling for Phi nodes - get the block the use occurs in.
4623 if (PHINode *PN = dyn_cast<PHINode>(UserInst)) {
4624 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
4625 if (PN->getIncomingValue(i) == I) {
4626 // Bail out if we have uses in different blocks. We don't do any
4627 // sophisticated analysis (i.e finding NearestCommonDominator of
4628 // these use blocks).
4629 if (UserParent && UserParent != PN->getIncomingBlock(i))
4630 return std::nullopt;
4631 UserParent = PN->getIncomingBlock(i);
4632 }
4633 }
4634 assert(UserParent && "expected to find user block!");
4635 } else {
4636 if (UserParent && UserParent != UserInst->getParent())
4637 return std::nullopt;
4638 UserParent = UserInst->getParent();
4639 }
4640
4641 // Make sure these checks are done only once, naturally we do the checks
4642 // the first time we get the userparent, this will save compile time.
4643 if (NumUsers == 0) {
4644 // Try sinking to another block. If that block is unreachable, then do
4645 // not bother. SimplifyCFG should handle it.
4646 if (UserParent == BB || !DT.isReachableFromEntry(UserParent))
4647 return std::nullopt;
4648
4649 auto *Term = UserParent->getTerminator();
4650 // See if the user is one of our successors that has only one
4651 // predecessor, so that we don't have to split the critical edge.
4652 // Another option where we can sink is a block that ends with a
4653 // terminator that does not pass control to other block (such as
4654 // return or unreachable or resume). In this case:</