LLVM 20.0.0git
SimplifyCFG.cpp
Go to the documentation of this file.
1//===- SimplifyCFG.cpp - Code to perform CFG simplification ---------------===//
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// Peephole optimize the CFG.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/ADT/APInt.h"
14#include "llvm/ADT/ArrayRef.h"
15#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/MapVector.h"
17#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/Sequence.h"
20#include "llvm/ADT/SetVector.h"
23#include "llvm/ADT/Statistic.h"
24#include "llvm/ADT/StringRef.h"
35#include "llvm/IR/Attributes.h"
36#include "llvm/IR/BasicBlock.h"
37#include "llvm/IR/CFG.h"
38#include "llvm/IR/Constant.h"
40#include "llvm/IR/Constants.h"
41#include "llvm/IR/DataLayout.h"
42#include "llvm/IR/DebugInfo.h"
44#include "llvm/IR/Function.h"
45#include "llvm/IR/GlobalValue.h"
47#include "llvm/IR/IRBuilder.h"
48#include "llvm/IR/InstrTypes.h"
49#include "llvm/IR/Instruction.h"
52#include "llvm/IR/LLVMContext.h"
53#include "llvm/IR/MDBuilder.h"
55#include "llvm/IR/Metadata.h"
56#include "llvm/IR/Module.h"
57#include "llvm/IR/NoFolder.h"
58#include "llvm/IR/Operator.h"
61#include "llvm/IR/Type.h"
62#include "llvm/IR/Use.h"
63#include "llvm/IR/User.h"
64#include "llvm/IR/Value.h"
65#include "llvm/IR/ValueHandle.h"
69#include "llvm/Support/Debug.h"
77#include <algorithm>
78#include <cassert>
79#include <climits>
80#include <cstddef>
81#include <cstdint>
82#include <iterator>
83#include <map>
84#include <optional>
85#include <set>
86#include <tuple>
87#include <utility>
88#include <vector>
89
90using namespace llvm;
91using namespace PatternMatch;
92
93#define DEBUG_TYPE "simplifycfg"
94
96 "simplifycfg-require-and-preserve-domtree", cl::Hidden,
97
98 cl::desc("Temorary development switch used to gradually uplift SimplifyCFG "
99 "into preserving DomTree,"));
100
101// Chosen as 2 so as to be cheap, but still to have enough power to fold
102// a select, so the "clamp" idiom (of a min followed by a max) will be caught.
103// To catch this, we need to fold a compare and a select, hence '2' being the
104// minimum reasonable default.
106 "phi-node-folding-threshold", cl::Hidden, cl::init(2),
107 cl::desc(
108 "Control the amount of phi node folding to perform (default = 2)"));
109
111 "two-entry-phi-node-folding-threshold", cl::Hidden, cl::init(4),
112 cl::desc("Control the maximal total instruction cost that we are willing "
113 "to speculatively execute to fold a 2-entry PHI node into a "
114 "select (default = 4)"));
115
116static cl::opt<bool>
117 HoistCommon("simplifycfg-hoist-common", cl::Hidden, cl::init(true),
118 cl::desc("Hoist common instructions up to the parent block"));
119
121 HoistCommonSkipLimit("simplifycfg-hoist-common-skip-limit", cl::Hidden,
122 cl::init(20),
123 cl::desc("Allow reordering across at most this many "
124 "instructions when hoisting"));
125
126static cl::opt<bool>
127 SinkCommon("simplifycfg-sink-common", cl::Hidden, cl::init(true),
128 cl::desc("Sink common instructions down to the end block"));
129
131 "simplifycfg-hoist-cond-stores", cl::Hidden, cl::init(true),
132 cl::desc("Hoist conditional stores if an unconditional store precedes"));
133
135 "simplifycfg-merge-cond-stores", cl::Hidden, cl::init(true),
136 cl::desc("Hoist conditional stores even if an unconditional store does not "
137 "precede - hoist multiple conditional stores into a single "
138 "predicated store"));
139
141 "simplifycfg-merge-cond-stores-aggressively", cl::Hidden, cl::init(false),
142 cl::desc("When merging conditional stores, do so even if the resultant "
143 "basic blocks are unlikely to be if-converted as a result"));
144
146 "speculate-one-expensive-inst", cl::Hidden, cl::init(true),
147 cl::desc("Allow exactly one expensive instruction to be speculatively "
148 "executed"));
149
151 "max-speculation-depth", cl::Hidden, cl::init(10),
152 cl::desc("Limit maximum recursion depth when calculating costs of "
153 "speculatively executed instructions"));
154
155static cl::opt<int>
156 MaxSmallBlockSize("simplifycfg-max-small-block-size", cl::Hidden,
157 cl::init(10),
158 cl::desc("Max size of a block which is still considered "
159 "small enough to thread through"));
160
161// Two is chosen to allow one negation and a logical combine.
163 BranchFoldThreshold("simplifycfg-branch-fold-threshold", cl::Hidden,
164 cl::init(2),
165 cl::desc("Maximum cost of combining conditions when "
166 "folding branches"));
167
169 "simplifycfg-branch-fold-common-dest-vector-multiplier", cl::Hidden,
170 cl::init(2),
171 cl::desc("Multiplier to apply to threshold when determining whether or not "
172 "to fold branch to common destination when vector operations are "
173 "present"));
174
176 "simplifycfg-merge-compatible-invokes", cl::Hidden, cl::init(true),
177 cl::desc("Allow SimplifyCFG to merge invokes together when appropriate"));
178
180 "max-switch-cases-per-result", cl::Hidden, cl::init(16),
181 cl::desc("Limit cases to analyze when converting a switch to select"));
182
183STATISTIC(NumBitMaps, "Number of switch instructions turned into bitmaps");
184STATISTIC(NumLinearMaps,
185 "Number of switch instructions turned into linear mapping");
186STATISTIC(NumLookupTables,
187 "Number of switch instructions turned into lookup tables");
189 NumLookupTablesHoles,
190 "Number of switch instructions turned into lookup tables (holes checked)");
191STATISTIC(NumTableCmpReuses, "Number of reused switch table lookup compares");
192STATISTIC(NumFoldValueComparisonIntoPredecessors,
193 "Number of value comparisons folded into predecessor basic blocks");
194STATISTIC(NumFoldBranchToCommonDest,
195 "Number of branches folded into predecessor basic block");
197 NumHoistCommonCode,
198 "Number of common instruction 'blocks' hoisted up to the begin block");
199STATISTIC(NumHoistCommonInstrs,
200 "Number of common instructions hoisted up to the begin block");
201STATISTIC(NumSinkCommonCode,
202 "Number of common instruction 'blocks' sunk down to the end block");
203STATISTIC(NumSinkCommonInstrs,
204 "Number of common instructions sunk down to the end block");
205STATISTIC(NumSpeculations, "Number of speculative executed instructions");
206STATISTIC(NumInvokes,
207 "Number of invokes with empty resume blocks simplified into calls");
208STATISTIC(NumInvokesMerged, "Number of invokes that were merged together");
209STATISTIC(NumInvokeSetsFormed, "Number of invoke sets that were formed");
210
211namespace {
212
213// The first field contains the value that the switch produces when a certain
214// case group is selected, and the second field is a vector containing the
215// cases composing the case group.
216using SwitchCaseResultVectorTy =
218
219// The first field contains the phi node that generates a result of the switch
220// and the second field contains the value generated for a certain case in the
221// switch for that PHI.
222using SwitchCaseResultsTy = SmallVector<std::pair<PHINode *, Constant *>, 4>;
223
224/// ValueEqualityComparisonCase - Represents a case of a switch.
225struct ValueEqualityComparisonCase {
227 BasicBlock *Dest;
228
229 ValueEqualityComparisonCase(ConstantInt *Value, BasicBlock *Dest)
230 : Value(Value), Dest(Dest) {}
231
232 bool operator<(ValueEqualityComparisonCase RHS) const {
233 // Comparing pointers is ok as we only rely on the order for uniquing.
234 return Value < RHS.Value;
235 }
236
237 bool operator==(BasicBlock *RHSDest) const { return Dest == RHSDest; }
238};
239
240class SimplifyCFGOpt {
242 DomTreeUpdater *DTU;
243 const DataLayout &DL;
244 ArrayRef<WeakVH> LoopHeaders;
246 bool Resimplify;
247
248 Value *isValueEqualityComparison(Instruction *TI);
249 BasicBlock *getValueEqualityComparisonCases(
250 Instruction *TI, std::vector<ValueEqualityComparisonCase> &Cases);
251 bool simplifyEqualityComparisonWithOnlyPredecessor(Instruction *TI,
252 BasicBlock *Pred,
253 IRBuilder<> &Builder);
254 bool performValueComparisonIntoPredecessorFolding(Instruction *TI, Value *&CV,
255 Instruction *PTI,
256 IRBuilder<> &Builder);
257 bool foldValueComparisonIntoPredecessors(Instruction *TI,
258 IRBuilder<> &Builder);
259
260 bool simplifyResume(ResumeInst *RI, IRBuilder<> &Builder);
261 bool simplifySingleResume(ResumeInst *RI);
262 bool simplifyCommonResume(ResumeInst *RI);
263 bool simplifyCleanupReturn(CleanupReturnInst *RI);
264 bool simplifyUnreachable(UnreachableInst *UI);
265 bool simplifySwitch(SwitchInst *SI, IRBuilder<> &Builder);
266 bool simplifyIndirectBr(IndirectBrInst *IBI);
267 bool simplifyBranch(BranchInst *Branch, IRBuilder<> &Builder);
268 bool simplifyUncondBranch(BranchInst *BI, IRBuilder<> &Builder);
269 bool simplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder);
270
271 bool tryToSimplifyUncondBranchWithICmpInIt(ICmpInst *ICI,
272 IRBuilder<> &Builder);
273
274 bool hoistCommonCodeFromSuccessors(BasicBlock *BB, bool EqTermsOnly);
275 bool hoistSuccIdenticalTerminatorToSwitchOrIf(
276 Instruction *TI, Instruction *I1,
277 SmallVectorImpl<Instruction *> &OtherSuccTIs);
278 bool speculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB);
279 bool simplifyTerminatorOnSelect(Instruction *OldTerm, Value *Cond,
280 BasicBlock *TrueBB, BasicBlock *FalseBB,
281 uint32_t TrueWeight, uint32_t FalseWeight);
282 bool simplifyBranchOnICmpChain(BranchInst *BI, IRBuilder<> &Builder,
283 const DataLayout &DL);
284 bool simplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select);
285 bool simplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI);
286 bool turnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder);
287
288public:
289 SimplifyCFGOpt(const TargetTransformInfo &TTI, DomTreeUpdater *DTU,
290 const DataLayout &DL, ArrayRef<WeakVH> LoopHeaders,
291 const SimplifyCFGOptions &Opts)
292 : TTI(TTI), DTU(DTU), DL(DL), LoopHeaders(LoopHeaders), Options(Opts) {
293 assert((!DTU || !DTU->hasPostDomTree()) &&
294 "SimplifyCFG is not yet capable of maintaining validity of a "
295 "PostDomTree, so don't ask for it.");
296 }
297
298 bool simplifyOnce(BasicBlock *BB);
299 bool run(BasicBlock *BB);
300
301 // Helper to set Resimplify and return change indication.
302 bool requestResimplify() {
303 Resimplify = true;
304 return true;
305 }
306};
307
308} // end anonymous namespace
309
310/// Return true if all the PHI nodes in the basic block \p BB
311/// receive compatible (identical) incoming values when coming from
312/// all of the predecessor blocks that are specified in \p IncomingBlocks.
313///
314/// Note that if the values aren't exactly identical, but \p EquivalenceSet
315/// is provided, and *both* of the values are present in the set,
316/// then they are considered equal.
318 BasicBlock *BB, ArrayRef<BasicBlock *> IncomingBlocks,
319 SmallPtrSetImpl<Value *> *EquivalenceSet = nullptr) {
320 assert(IncomingBlocks.size() == 2 &&
321 "Only for a pair of incoming blocks at the time!");
322
323 // FIXME: it is okay if one of the incoming values is an `undef` value,
324 // iff the other incoming value is guaranteed to be a non-poison value.
325 // FIXME: it is okay if one of the incoming values is a `poison` value.
326 return all_of(BB->phis(), [IncomingBlocks, EquivalenceSet](PHINode &PN) {
327 Value *IV0 = PN.getIncomingValueForBlock(IncomingBlocks[0]);
328 Value *IV1 = PN.getIncomingValueForBlock(IncomingBlocks[1]);
329 if (IV0 == IV1)
330 return true;
331 if (EquivalenceSet && EquivalenceSet->contains(IV0) &&
332 EquivalenceSet->contains(IV1))
333 return true;
334 return false;
335 });
336}
337
338/// Return true if it is safe to merge these two
339/// terminator instructions together.
340static bool
342 SmallSetVector<BasicBlock *, 4> *FailBlocks = nullptr) {
343 if (SI1 == SI2)
344 return false; // Can't merge with self!
345
346 // It is not safe to merge these two switch instructions if they have a common
347 // successor, and if that successor has a PHI node, and if *that* PHI node has
348 // conflicting incoming values from the two switch blocks.
349 BasicBlock *SI1BB = SI1->getParent();
350 BasicBlock *SI2BB = SI2->getParent();
351
352 SmallPtrSet<BasicBlock *, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
353 bool Fail = false;
354 for (BasicBlock *Succ : successors(SI2BB)) {
355 if (!SI1Succs.count(Succ))
356 continue;
357 if (incomingValuesAreCompatible(Succ, {SI1BB, SI2BB}))
358 continue;
359 Fail = true;
360 if (FailBlocks)
361 FailBlocks->insert(Succ);
362 else
363 break;
364 }
365
366 return !Fail;
367}
368
369/// Update PHI nodes in Succ to indicate that there will now be entries in it
370/// from the 'NewPred' block. The values that will be flowing into the PHI nodes
371/// will be the same as those coming in from ExistPred, an existing predecessor
372/// of Succ.
373static void addPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
374 BasicBlock *ExistPred,
375 MemorySSAUpdater *MSSAU = nullptr) {
376 for (PHINode &PN : Succ->phis())
377 PN.addIncoming(PN.getIncomingValueForBlock(ExistPred), NewPred);
378 if (MSSAU)
379 if (auto *MPhi = MSSAU->getMemorySSA()->getMemoryAccess(Succ))
380 MPhi->addIncoming(MPhi->getIncomingValueForBlock(ExistPred), NewPred);
381}
382
383/// Compute an abstract "cost" of speculating the given instruction,
384/// which is assumed to be safe to speculate. TCC_Free means cheap,
385/// TCC_Basic means less cheap, and TCC_Expensive means prohibitively
386/// expensive.
388 const TargetTransformInfo &TTI) {
389 assert((!isa<Instruction>(I) ||
390 isSafeToSpeculativelyExecute(cast<Instruction>(I))) &&
391 "Instruction is not safe to speculatively execute!");
393}
394
395/// If we have a merge point of an "if condition" as accepted above,
396/// return true if the specified value dominates the block. We
397/// don't handle the true generality of domination here, just a special case
398/// which works well enough for us.
399///
400/// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
401/// see if V (which must be an instruction) and its recursive operands
402/// that do not dominate BB have a combined cost lower than Budget and
403/// are non-trapping. If both are true, the instruction is inserted into the
404/// set and true is returned.
405///
406/// The cost for most non-trapping instructions is defined as 1 except for
407/// Select whose cost is 2.
408///
409/// After this function returns, Cost is increased by the cost of
410/// V plus its non-dominating operands. If that cost is greater than
411/// Budget, false is returned and Cost is undefined.
413 SmallPtrSetImpl<Instruction *> &AggressiveInsts,
415 InstructionCost Budget,
417 unsigned Depth = 0) {
418 // It is possible to hit a zero-cost cycle (phi/gep instructions for example),
419 // so limit the recursion depth.
420 // TODO: While this recursion limit does prevent pathological behavior, it
421 // would be better to track visited instructions to avoid cycles.
423 return false;
424
425 Instruction *I = dyn_cast<Instruction>(V);
426 if (!I) {
427 // Non-instructions dominate all instructions and can be executed
428 // unconditionally.
429 return true;
430 }
431 BasicBlock *PBB = I->getParent();
432
433 // We don't want to allow weird loops that might have the "if condition" in
434 // the bottom of this block.
435 if (PBB == BB)
436 return false;
437
438 // If this instruction is defined in a block that contains an unconditional
439 // branch to BB, then it must be in the 'conditional' part of the "if
440 // statement". If not, it definitely dominates the region.
441 BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator());
442 if (!BI || BI->isConditional() || BI->getSuccessor(0) != BB)
443 return true;
444
445 // If we have seen this instruction before, don't count it again.
446 if (AggressiveInsts.count(I))
447 return true;
448
449 // Okay, it looks like the instruction IS in the "condition". Check to
450 // see if it's a cheap instruction to unconditionally compute, and if it
451 // only uses stuff defined outside of the condition. If so, hoist it out.
453 return false;
454
456
457 // Allow exactly one instruction to be speculated regardless of its cost
458 // (as long as it is safe to do so).
459 // This is intended to flatten the CFG even if the instruction is a division
460 // or other expensive operation. The speculation of an expensive instruction
461 // is expected to be undone in CodeGenPrepare if the speculation has not
462 // enabled further IR optimizations.
463 if (Cost > Budget &&
464 (!SpeculateOneExpensiveInst || !AggressiveInsts.empty() || Depth > 0 ||
465 !Cost.isValid()))
466 return false;
467
468 // Okay, we can only really hoist these out if their operands do
469 // not take us over the cost threshold.
470 for (Use &Op : I->operands())
471 if (!dominatesMergePoint(Op, BB, AggressiveInsts, Cost, Budget, TTI,
472 Depth + 1))
473 return false;
474 // Okay, it's safe to do this! Remember this instruction.
475 AggressiveInsts.insert(I);
476 return true;
477}
478
479/// Extract ConstantInt from value, looking through IntToPtr
480/// and PointerNullValue. Return NULL if value is not a constant int.
482 // Normal constant int.
483 ConstantInt *CI = dyn_cast<ConstantInt>(V);
484 if (CI || !isa<Constant>(V) || !V->getType()->isPointerTy() ||
485 DL.isNonIntegralPointerType(V->getType()))
486 return CI;
487
488 // This is some kind of pointer constant. Turn it into a pointer-sized
489 // ConstantInt if possible.
490 IntegerType *PtrTy = cast<IntegerType>(DL.getIntPtrType(V->getType()));
491
492 // Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*).
493 if (isa<ConstantPointerNull>(V))
494 return ConstantInt::get(PtrTy, 0);
495
496 // IntToPtr const int.
497 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
498 if (CE->getOpcode() == Instruction::IntToPtr)
499 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) {
500 // The constant is very likely to have the right type already.
501 if (CI->getType() == PtrTy)
502 return CI;
503 else
504 return cast<ConstantInt>(
505 ConstantFoldIntegerCast(CI, PtrTy, /*isSigned=*/false, DL));
506 }
507 return nullptr;
508}
509
510namespace {
511
512/// Given a chain of or (||) or and (&&) comparison of a value against a
513/// constant, this will try to recover the information required for a switch
514/// structure.
515/// It will depth-first traverse the chain of comparison, seeking for patterns
516/// like %a == 12 or %a < 4 and combine them to produce a set of integer
517/// representing the different cases for the switch.
518/// Note that if the chain is composed of '||' it will build the set of elements
519/// that matches the comparisons (i.e. any of this value validate the chain)
520/// while for a chain of '&&' it will build the set elements that make the test
521/// fail.
522struct ConstantComparesGatherer {
523 const DataLayout &DL;
524
525 /// Value found for the switch comparison
526 Value *CompValue = nullptr;
527
528 /// Extra clause to be checked before the switch
529 Value *Extra = nullptr;
530
531 /// Set of integers to match in switch
533
534 /// Number of comparisons matched in the and/or chain
535 unsigned UsedICmps = 0;
536
537 /// Construct and compute the result for the comparison instruction Cond
538 ConstantComparesGatherer(Instruction *Cond, const DataLayout &DL) : DL(DL) {
539 gather(Cond);
540 }
541
542 ConstantComparesGatherer(const ConstantComparesGatherer &) = delete;
543 ConstantComparesGatherer &
544 operator=(const ConstantComparesGatherer &) = delete;
545
546private:
547 /// Try to set the current value used for the comparison, it succeeds only if
548 /// it wasn't set before or if the new value is the same as the old one
549 bool setValueOnce(Value *NewVal) {
550 if (CompValue && CompValue != NewVal)
551 return false;
552 CompValue = NewVal;
553 return (CompValue != nullptr);
554 }
555
556 /// Try to match Instruction "I" as a comparison against a constant and
557 /// populates the array Vals with the set of values that match (or do not
558 /// match depending on isEQ).
559 /// Return false on failure. On success, the Value the comparison matched
560 /// against is placed in CompValue.
561 /// If CompValue is already set, the function is expected to fail if a match
562 /// is found but the value compared to is different.
563 bool matchInstruction(Instruction *I, bool isEQ) {
564 // If this is an icmp against a constant, handle this as one of the cases.
565 ICmpInst *ICI;
566 ConstantInt *C;
567 if (!((ICI = dyn_cast<ICmpInst>(I)) &&
568 (C = getConstantInt(I->getOperand(1), DL)))) {
569 return false;
570 }
571
572 Value *RHSVal;
573 const APInt *RHSC;
574
575 // Pattern match a special case
576 // (x & ~2^z) == y --> x == y || x == y|2^z
577 // This undoes a transformation done by instcombine to fuse 2 compares.
578 if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE)) {
579 // It's a little bit hard to see why the following transformations are
580 // correct. Here is a CVC3 program to verify them for 64-bit values:
581
582 /*
583 ONE : BITVECTOR(64) = BVZEROEXTEND(0bin1, 63);
584 x : BITVECTOR(64);
585 y : BITVECTOR(64);
586 z : BITVECTOR(64);
587 mask : BITVECTOR(64) = BVSHL(ONE, z);
588 QUERY( (y & ~mask = y) =>
589 ((x & ~mask = y) <=> (x = y OR x = (y | mask)))
590 );
591 QUERY( (y | mask = y) =>
592 ((x | mask = y) <=> (x = y OR x = (y & ~mask)))
593 );
594 */
595
596 // Please note that each pattern must be a dual implication (<--> or
597 // iff). One directional implication can create spurious matches. If the
598 // implication is only one-way, an unsatisfiable condition on the left
599 // side can imply a satisfiable condition on the right side. Dual
600 // implication ensures that satisfiable conditions are transformed to
601 // other satisfiable conditions and unsatisfiable conditions are
602 // transformed to other unsatisfiable conditions.
603
604 // Here is a concrete example of a unsatisfiable condition on the left
605 // implying a satisfiable condition on the right:
606 //
607 // mask = (1 << z)
608 // (x & ~mask) == y --> (x == y || x == (y | mask))
609 //
610 // Substituting y = 3, z = 0 yields:
611 // (x & -2) == 3 --> (x == 3 || x == 2)
612
613 // Pattern match a special case:
614 /*
615 QUERY( (y & ~mask = y) =>
616 ((x & ~mask = y) <=> (x = y OR x = (y | mask)))
617 );
618 */
619 if (match(ICI->getOperand(0),
620 m_And(m_Value(RHSVal), m_APInt(RHSC)))) {
621 APInt Mask = ~*RHSC;
622 if (Mask.isPowerOf2() && (C->getValue() & ~Mask) == C->getValue()) {
623 // If we already have a value for the switch, it has to match!
624 if (!setValueOnce(RHSVal))
625 return false;
626
627 Vals.push_back(C);
628 Vals.push_back(
629 ConstantInt::get(C->getContext(),
630 C->getValue() | Mask));
631 UsedICmps++;
632 return true;
633 }
634 }
635
636 // Pattern match a special case:
637 /*
638 QUERY( (y | mask = y) =>
639 ((x | mask = y) <=> (x = y OR x = (y & ~mask)))
640 );
641 */
642 if (match(ICI->getOperand(0),
643 m_Or(m_Value(RHSVal), m_APInt(RHSC)))) {
644 APInt Mask = *RHSC;
645 if (Mask.isPowerOf2() && (C->getValue() | Mask) == C->getValue()) {
646 // If we already have a value for the switch, it has to match!
647 if (!setValueOnce(RHSVal))
648 return false;
649
650 Vals.push_back(C);
651 Vals.push_back(ConstantInt::get(C->getContext(),
652 C->getValue() & ~Mask));
653 UsedICmps++;
654 return true;
655 }
656 }
657
658 // If we already have a value for the switch, it has to match!
659 if (!setValueOnce(ICI->getOperand(0)))
660 return false;
661
662 UsedICmps++;
663 Vals.push_back(C);
664 return ICI->getOperand(0);
665 }
666
667 // If we have "x ult 3", for example, then we can add 0,1,2 to the set.
668 ConstantRange Span =
670
671 // Shift the range if the compare is fed by an add. This is the range
672 // compare idiom as emitted by instcombine.
673 Value *CandidateVal = I->getOperand(0);
674 if (match(I->getOperand(0), m_Add(m_Value(RHSVal), m_APInt(RHSC)))) {
675 Span = Span.subtract(*RHSC);
676 CandidateVal = RHSVal;
677 }
678
679 // If this is an and/!= check, then we are looking to build the set of
680 // value that *don't* pass the and chain. I.e. to turn "x ugt 2" into
681 // x != 0 && x != 1.
682 if (!isEQ)
683 Span = Span.inverse();
684
685 // If there are a ton of values, we don't want to make a ginormous switch.
686 if (Span.isSizeLargerThan(8) || Span.isEmptySet()) {
687 return false;
688 }
689
690 // If we already have a value for the switch, it has to match!
691 if (!setValueOnce(CandidateVal))
692 return false;
693
694 // Add all values from the range to the set
695 for (APInt Tmp = Span.getLower(); Tmp != Span.getUpper(); ++Tmp)
696 Vals.push_back(ConstantInt::get(I->getContext(), Tmp));
697
698 UsedICmps++;
699 return true;
700 }
701
702 /// Given a potentially 'or'd or 'and'd together collection of icmp
703 /// eq/ne/lt/gt instructions that compare a value against a constant, extract
704 /// the value being compared, and stick the list constants into the Vals
705 /// vector.
706 /// One "Extra" case is allowed to differ from the other.
707 void gather(Value *V) {
708 bool isEQ = match(V, m_LogicalOr(m_Value(), m_Value()));
709
710 // Keep a stack (SmallVector for efficiency) for depth-first traversal
713
714 // Initialize
715 Visited.insert(V);
716 DFT.push_back(V);
717
718 while (!DFT.empty()) {
719 V = DFT.pop_back_val();
720
721 if (Instruction *I = dyn_cast<Instruction>(V)) {
722 // If it is a || (or && depending on isEQ), process the operands.
723 Value *Op0, *Op1;
724 if (isEQ ? match(I, m_LogicalOr(m_Value(Op0), m_Value(Op1)))
725 : match(I, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
726 if (Visited.insert(Op1).second)
727 DFT.push_back(Op1);
728 if (Visited.insert(Op0).second)
729 DFT.push_back(Op0);
730
731 continue;
732 }
733
734 // Try to match the current instruction
735 if (matchInstruction(I, isEQ))
736 // Match succeed, continue the loop
737 continue;
738 }
739
740 // One element of the sequence of || (or &&) could not be match as a
741 // comparison against the same value as the others.
742 // We allow only one "Extra" case to be checked before the switch
743 if (!Extra) {
744 Extra = V;
745 continue;
746 }
747 // Failed to parse a proper sequence, abort now
748 CompValue = nullptr;
749 break;
750 }
751 }
752};
753
754} // end anonymous namespace
755
757 MemorySSAUpdater *MSSAU = nullptr) {
758 Instruction *Cond = nullptr;
759 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
760 Cond = dyn_cast<Instruction>(SI->getCondition());
761 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
762 if (BI->isConditional())
763 Cond = dyn_cast<Instruction>(BI->getCondition());
764 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) {
765 Cond = dyn_cast<Instruction>(IBI->getAddress());
766 }
767
768 TI->eraseFromParent();
769 if (Cond)
771}
772
773/// Return true if the specified terminator checks
774/// to see if a value is equal to constant integer value.
775Value *SimplifyCFGOpt::isValueEqualityComparison(Instruction *TI) {
776 Value *CV = nullptr;
777 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
778 // Do not permit merging of large switch instructions into their
779 // predecessors unless there is only one predecessor.
780 if (!SI->getParent()->hasNPredecessorsOrMore(128 / SI->getNumSuccessors()))
781 CV = SI->getCondition();
782 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI))
783 if (BI->isConditional() && BI->getCondition()->hasOneUse())
784 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition())) {
785 if (ICI->isEquality() && getConstantInt(ICI->getOperand(1), DL))
786 CV = ICI->getOperand(0);
787 }
788
789 // Unwrap any lossless ptrtoint cast.
790 if (CV) {
791 if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV)) {
792 Value *Ptr = PTII->getPointerOperand();
793 if (PTII->getType() == DL.getIntPtrType(Ptr->getType()))
794 CV = Ptr;
795 }
796 }
797 return CV;
798}
799
800/// Given a value comparison instruction,
801/// decode all of the 'cases' that it represents and return the 'default' block.
802BasicBlock *SimplifyCFGOpt::getValueEqualityComparisonCases(
803 Instruction *TI, std::vector<ValueEqualityComparisonCase> &Cases) {
804 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
805 Cases.reserve(SI->getNumCases());
806 for (auto Case : SI->cases())
807 Cases.push_back(ValueEqualityComparisonCase(Case.getCaseValue(),
808 Case.getCaseSuccessor()));
809 return SI->getDefaultDest();
810 }
811
812 BranchInst *BI = cast<BranchInst>(TI);
813 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
814 BasicBlock *Succ = BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_NE);
815 Cases.push_back(ValueEqualityComparisonCase(
816 getConstantInt(ICI->getOperand(1), DL), Succ));
817 return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ);
818}
819
820/// Given a vector of bb/value pairs, remove any entries
821/// in the list that match the specified block.
822static void
824 std::vector<ValueEqualityComparisonCase> &Cases) {
825 llvm::erase(Cases, BB);
826}
827
828/// Return true if there are any keys in C1 that exist in C2 as well.
829static bool valuesOverlap(std::vector<ValueEqualityComparisonCase> &C1,
830 std::vector<ValueEqualityComparisonCase> &C2) {
831 std::vector<ValueEqualityComparisonCase> *V1 = &C1, *V2 = &C2;
832
833 // Make V1 be smaller than V2.
834 if (V1->size() > V2->size())
835 std::swap(V1, V2);
836
837 if (V1->empty())
838 return false;
839 if (V1->size() == 1) {
840 // Just scan V2.
841 ConstantInt *TheVal = (*V1)[0].Value;
842 for (const ValueEqualityComparisonCase &VECC : *V2)
843 if (TheVal == VECC.Value)
844 return true;
845 }
846
847 // Otherwise, just sort both lists and compare element by element.
848 array_pod_sort(V1->begin(), V1->end());
849 array_pod_sort(V2->begin(), V2->end());
850 unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
851 while (i1 != e1 && i2 != e2) {
852 if ((*V1)[i1].Value == (*V2)[i2].Value)
853 return true;
854 if ((*V1)[i1].Value < (*V2)[i2].Value)
855 ++i1;
856 else
857 ++i2;
858 }
859 return false;
860}
861
862// Set branch weights on SwitchInst. This sets the metadata if there is at
863// least one non-zero weight.
865 bool IsExpected) {
866 // Check that there is at least one non-zero weight. Otherwise, pass
867 // nullptr to setMetadata which will erase the existing metadata.
868 MDNode *N = nullptr;
869 if (llvm::any_of(Weights, [](uint32_t W) { return W != 0; }))
870 N = MDBuilder(SI->getParent()->getContext())
871 .createBranchWeights(Weights, IsExpected);
872 SI->setMetadata(LLVMContext::MD_prof, N);
873}
874
875// Similar to the above, but for branch and select instructions that take
876// exactly 2 weights.
877static void setBranchWeights(Instruction *I, uint32_t TrueWeight,
878 uint32_t FalseWeight, bool IsExpected) {
879 assert(isa<BranchInst>(I) || isa<SelectInst>(I));
880 // Check that there is at least one non-zero weight. Otherwise, pass
881 // nullptr to setMetadata which will erase the existing metadata.
882 MDNode *N = nullptr;
883 if (TrueWeight || FalseWeight)
884 N = MDBuilder(I->getParent()->getContext())
885 .createBranchWeights(TrueWeight, FalseWeight, IsExpected);
886 I->setMetadata(LLVMContext::MD_prof, N);
887}
888
889/// If TI is known to be a terminator instruction and its block is known to
890/// only have a single predecessor block, check to see if that predecessor is
891/// also a value comparison with the same value, and if that comparison
892/// determines the outcome of this comparison. If so, simplify TI. This does a
893/// very limited form of jump threading.
894bool SimplifyCFGOpt::simplifyEqualityComparisonWithOnlyPredecessor(
895 Instruction *TI, BasicBlock *Pred, IRBuilder<> &Builder) {
896 Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
897 if (!PredVal)
898 return false; // Not a value comparison in predecessor.
899
900 Value *ThisVal = isValueEqualityComparison(TI);
901 assert(ThisVal && "This isn't a value comparison!!");
902 if (ThisVal != PredVal)
903 return false; // Different predicates.
904
905 // TODO: Preserve branch weight metadata, similarly to how
906 // foldValueComparisonIntoPredecessors preserves it.
907
908 // Find out information about when control will move from Pred to TI's block.
909 std::vector<ValueEqualityComparisonCase> PredCases;
910 BasicBlock *PredDef =
911 getValueEqualityComparisonCases(Pred->getTerminator(), PredCases);
912 eliminateBlockCases(PredDef, PredCases); // Remove default from cases.
913
914 // Find information about how control leaves this block.
915 std::vector<ValueEqualityComparisonCase> ThisCases;
916 BasicBlock *ThisDef = getValueEqualityComparisonCases(TI, ThisCases);
917 eliminateBlockCases(ThisDef, ThisCases); // Remove default from cases.
918
919 // If TI's block is the default block from Pred's comparison, potentially
920 // simplify TI based on this knowledge.
921 if (PredDef == TI->getParent()) {
922 // If we are here, we know that the value is none of those cases listed in
923 // PredCases. If there are any cases in ThisCases that are in PredCases, we
924 // can simplify TI.
925 if (!valuesOverlap(PredCases, ThisCases))
926 return false;
927
928 if (isa<BranchInst>(TI)) {
929 // Okay, one of the successors of this condbr is dead. Convert it to a
930 // uncond br.
931 assert(ThisCases.size() == 1 && "Branch can only have one case!");
932 // Insert the new branch.
933 Instruction *NI = Builder.CreateBr(ThisDef);
934 (void)NI;
935
936 // Remove PHI node entries for the dead edge.
937 ThisCases[0].Dest->removePredecessor(PredDef);
938
939 LLVM_DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
940 << "Through successor TI: " << *TI << "Leaving: " << *NI
941 << "\n");
942
944
945 if (DTU)
946 DTU->applyUpdates(
947 {{DominatorTree::Delete, PredDef, ThisCases[0].Dest}});
948
949 return true;
950 }
951
952 SwitchInstProfUpdateWrapper SI = *cast<SwitchInst>(TI);
953 // Okay, TI has cases that are statically dead, prune them away.
955 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
956 DeadCases.insert(PredCases[i].Value);
957
958 LLVM_DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
959 << "Through successor TI: " << *TI);
960
961 SmallDenseMap<BasicBlock *, int, 8> NumPerSuccessorCases;
962 for (SwitchInst::CaseIt i = SI->case_end(), e = SI->case_begin(); i != e;) {
963 --i;
964 auto *Successor = i->getCaseSuccessor();
965 if (DTU)
966 ++NumPerSuccessorCases[Successor];
967 if (DeadCases.count(i->getCaseValue())) {
968 Successor->removePredecessor(PredDef);
969 SI.removeCase(i);
970 if (DTU)
971 --NumPerSuccessorCases[Successor];
972 }
973 }
974
975 if (DTU) {
976 std::vector<DominatorTree::UpdateType> Updates;
977 for (const std::pair<BasicBlock *, int> &I : NumPerSuccessorCases)
978 if (I.second == 0)
979 Updates.push_back({DominatorTree::Delete, PredDef, I.first});
980 DTU->applyUpdates(Updates);
981 }
982
983 LLVM_DEBUG(dbgs() << "Leaving: " << *TI << "\n");
984 return true;
985 }
986
987 // Otherwise, TI's block must correspond to some matched value. Find out
988 // which value (or set of values) this is.
989 ConstantInt *TIV = nullptr;
990 BasicBlock *TIBB = TI->getParent();
991 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
992 if (PredCases[i].Dest == TIBB) {
993 if (TIV)
994 return false; // Cannot handle multiple values coming to this block.
995 TIV = PredCases[i].Value;
996 }
997 assert(TIV && "No edge from pred to succ?");
998
999 // Okay, we found the one constant that our value can be if we get into TI's
1000 // BB. Find out which successor will unconditionally be branched to.
1001 BasicBlock *TheRealDest = nullptr;
1002 for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
1003 if (ThisCases[i].Value == TIV) {
1004 TheRealDest = ThisCases[i].Dest;
1005 break;
1006 }
1007
1008 // If not handled by any explicit cases, it is handled by the default case.
1009 if (!TheRealDest)
1010 TheRealDest = ThisDef;
1011
1012 SmallPtrSet<BasicBlock *, 2> RemovedSuccs;
1013
1014 // Remove PHI node entries for dead edges.
1015 BasicBlock *CheckEdge = TheRealDest;
1016 for (BasicBlock *Succ : successors(TIBB))
1017 if (Succ != CheckEdge) {
1018 if (Succ != TheRealDest)
1019 RemovedSuccs.insert(Succ);
1020 Succ->removePredecessor(TIBB);
1021 } else
1022 CheckEdge = nullptr;
1023
1024 // Insert the new branch.
1025 Instruction *NI = Builder.CreateBr(TheRealDest);
1026 (void)NI;
1027
1028 LLVM_DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
1029 << "Through successor TI: " << *TI << "Leaving: " << *NI
1030 << "\n");
1031
1033 if (DTU) {
1035 Updates.reserve(RemovedSuccs.size());
1036 for (auto *RemovedSucc : RemovedSuccs)
1037 Updates.push_back({DominatorTree::Delete, TIBB, RemovedSucc});
1038 DTU->applyUpdates(Updates);
1039 }
1040 return true;
1041}
1042
1043namespace {
1044
1045/// This class implements a stable ordering of constant
1046/// integers that does not depend on their address. This is important for
1047/// applications that sort ConstantInt's to ensure uniqueness.
1048struct ConstantIntOrdering {
1049 bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
1050 return LHS->getValue().ult(RHS->getValue());
1051 }
1052};
1053
1054} // end anonymous namespace
1055
1057 ConstantInt *const *P2) {
1058 const ConstantInt *LHS = *P1;
1059 const ConstantInt *RHS = *P2;
1060 if (LHS == RHS)
1061 return 0;
1062 return LHS->getValue().ult(RHS->getValue()) ? 1 : -1;
1063}
1064
1065/// Get Weights of a given terminator, the default weight is at the front
1066/// of the vector. If TI is a conditional eq, we need to swap the branch-weight
1067/// metadata.
1069 SmallVectorImpl<uint64_t> &Weights) {
1070 MDNode *MD = TI->getMetadata(LLVMContext::MD_prof);
1071 assert(MD && "Invalid branch-weight metadata");
1072 extractFromBranchWeightMD64(MD, Weights);
1073
1074 // If TI is a conditional eq, the default case is the false case,
1075 // and the corresponding branch-weight data is at index 2. We swap the
1076 // default weight to be the first entry.
1077 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1078 assert(Weights.size() == 2);
1079 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
1080 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
1081 std::swap(Weights.front(), Weights.back());
1082 }
1083}
1084
1085/// Keep halving the weights until all can fit in uint32_t.
1087 uint64_t Max = *llvm::max_element(Weights);
1088 if (Max > UINT_MAX) {
1089 unsigned Offset = 32 - llvm::countl_zero(Max);
1090 for (uint64_t &I : Weights)
1091 I >>= Offset;
1092 }
1093}
1094
1096 BasicBlock *BB, BasicBlock *PredBlock, ValueToValueMapTy &VMap) {
1097 Instruction *PTI = PredBlock->getTerminator();
1098
1099 // If we have bonus instructions, clone them into the predecessor block.
1100 // Note that there may be multiple predecessor blocks, so we cannot move
1101 // bonus instructions to a predecessor block.
1102 for (Instruction &BonusInst : *BB) {
1103 if (BonusInst.isTerminator())
1104 continue;
1105
1106 Instruction *NewBonusInst = BonusInst.clone();
1107
1108 if (!isa<DbgInfoIntrinsic>(BonusInst) &&
1109 PTI->getDebugLoc() != NewBonusInst->getDebugLoc()) {
1110 // Unless the instruction has the same !dbg location as the original
1111 // branch, drop it. When we fold the bonus instructions we want to make
1112 // sure we reset their debug locations in order to avoid stepping on
1113 // dead code caused by folding dead branches.
1114 NewBonusInst->setDebugLoc(DebugLoc());
1115 }
1116
1117 RemapInstruction(NewBonusInst, VMap,
1119
1120 // If we speculated an instruction, we need to drop any metadata that may
1121 // result in undefined behavior, as the metadata might have been valid
1122 // only given the branch precondition.
1123 // Similarly strip attributes on call parameters that may cause UB in
1124 // location the call is moved to.
1125 NewBonusInst->dropUBImplyingAttrsAndMetadata();
1126
1127 NewBonusInst->insertInto(PredBlock, PTI->getIterator());
1128 auto Range = NewBonusInst->cloneDebugInfoFrom(&BonusInst);
1129 RemapDbgRecordRange(NewBonusInst->getModule(), Range, VMap,
1131
1132 if (isa<DbgInfoIntrinsic>(BonusInst))
1133 continue;
1134
1135 NewBonusInst->takeName(&BonusInst);
1136 BonusInst.setName(NewBonusInst->getName() + ".old");
1137 VMap[&BonusInst] = NewBonusInst;
1138
1139 // Update (liveout) uses of bonus instructions,
1140 // now that the bonus instruction has been cloned into predecessor.
1141 // Note that we expect to be in a block-closed SSA form for this to work!
1142 for (Use &U : make_early_inc_range(BonusInst.uses())) {
1143 auto *UI = cast<Instruction>(U.getUser());
1144 auto *PN = dyn_cast<PHINode>(UI);
1145 if (!PN) {
1146 assert(UI->getParent() == BB && BonusInst.comesBefore(UI) &&
1147 "If the user is not a PHI node, then it should be in the same "
1148 "block as, and come after, the original bonus instruction.");
1149 continue; // Keep using the original bonus instruction.
1150 }
1151 // Is this the block-closed SSA form PHI node?
1152 if (PN->getIncomingBlock(U) == BB)
1153 continue; // Great, keep using the original bonus instruction.
1154 // The only other alternative is an "use" when coming from
1155 // the predecessor block - here we should refer to the cloned bonus instr.
1156 assert(PN->getIncomingBlock(U) == PredBlock &&
1157 "Not in block-closed SSA form?");
1158 U.set(NewBonusInst);
1159 }
1160 }
1161}
1162
1163bool SimplifyCFGOpt::performValueComparisonIntoPredecessorFolding(
1164 Instruction *TI, Value *&CV, Instruction *PTI, IRBuilder<> &Builder) {
1165 BasicBlock *BB = TI->getParent();
1166 BasicBlock *Pred = PTI->getParent();
1167
1169
1170 // Figure out which 'cases' to copy from SI to PSI.
1171 std::vector<ValueEqualityComparisonCase> BBCases;
1172 BasicBlock *BBDefault = getValueEqualityComparisonCases(TI, BBCases);
1173
1174 std::vector<ValueEqualityComparisonCase> PredCases;
1175 BasicBlock *PredDefault = getValueEqualityComparisonCases(PTI, PredCases);
1176
1177 // Based on whether the default edge from PTI goes to BB or not, fill in
1178 // PredCases and PredDefault with the new switch cases we would like to
1179 // build.
1181
1182 // Update the branch weight metadata along the way
1184 bool PredHasWeights = hasBranchWeightMD(*PTI);
1185 bool SuccHasWeights = hasBranchWeightMD(*TI);
1186
1187 if (PredHasWeights) {
1188 getBranchWeights(PTI, Weights);
1189 // branch-weight metadata is inconsistent here.
1190 if (Weights.size() != 1 + PredCases.size())
1191 PredHasWeights = SuccHasWeights = false;
1192 } else if (SuccHasWeights)
1193 // If there are no predecessor weights but there are successor weights,
1194 // populate Weights with 1, which will later be scaled to the sum of
1195 // successor's weights
1196 Weights.assign(1 + PredCases.size(), 1);
1197
1198 SmallVector<uint64_t, 8> SuccWeights;
1199 if (SuccHasWeights) {
1200 getBranchWeights(TI, SuccWeights);
1201 // branch-weight metadata is inconsistent here.
1202 if (SuccWeights.size() != 1 + BBCases.size())
1203 PredHasWeights = SuccHasWeights = false;
1204 } else if (PredHasWeights)
1205 SuccWeights.assign(1 + BBCases.size(), 1);
1206
1207 if (PredDefault == BB) {
1208 // If this is the default destination from PTI, only the edges in TI
1209 // that don't occur in PTI, or that branch to BB will be activated.
1210 std::set<ConstantInt *, ConstantIntOrdering> PTIHandled;
1211 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
1212 if (PredCases[i].Dest != BB)
1213 PTIHandled.insert(PredCases[i].Value);
1214 else {
1215 // The default destination is BB, we don't need explicit targets.
1216 std::swap(PredCases[i], PredCases.back());
1217
1218 if (PredHasWeights || SuccHasWeights) {
1219 // Increase weight for the default case.
1220 Weights[0] += Weights[i + 1];
1221 std::swap(Weights[i + 1], Weights.back());
1222 Weights.pop_back();
1223 }
1224
1225 PredCases.pop_back();
1226 --i;
1227 --e;
1228 }
1229
1230 // Reconstruct the new switch statement we will be building.
1231 if (PredDefault != BBDefault) {
1232 PredDefault->removePredecessor(Pred);
1233 if (DTU && PredDefault != BB)
1234 Updates.push_back({DominatorTree::Delete, Pred, PredDefault});
1235 PredDefault = BBDefault;
1236 ++NewSuccessors[BBDefault];
1237 }
1238
1239 unsigned CasesFromPred = Weights.size();
1240 uint64_t ValidTotalSuccWeight = 0;
1241 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
1242 if (!PTIHandled.count(BBCases[i].Value) && BBCases[i].Dest != BBDefault) {
1243 PredCases.push_back(BBCases[i]);
1244 ++NewSuccessors[BBCases[i].Dest];
1245 if (SuccHasWeights || PredHasWeights) {
1246 // The default weight is at index 0, so weight for the ith case
1247 // should be at index i+1. Scale the cases from successor by
1248 // PredDefaultWeight (Weights[0]).
1249 Weights.push_back(Weights[0] * SuccWeights[i + 1]);
1250 ValidTotalSuccWeight += SuccWeights[i + 1];
1251 }
1252 }
1253
1254 if (SuccHasWeights || PredHasWeights) {
1255 ValidTotalSuccWeight += SuccWeights[0];
1256 // Scale the cases from predecessor by ValidTotalSuccWeight.
1257 for (unsigned i = 1; i < CasesFromPred; ++i)
1258 Weights[i] *= ValidTotalSuccWeight;
1259 // Scale the default weight by SuccDefaultWeight (SuccWeights[0]).
1260 Weights[0] *= SuccWeights[0];
1261 }
1262 } else {
1263 // If this is not the default destination from PSI, only the edges
1264 // in SI that occur in PSI with a destination of BB will be
1265 // activated.
1266 std::set<ConstantInt *, ConstantIntOrdering> PTIHandled;
1267 std::map<ConstantInt *, uint64_t> WeightsForHandled;
1268 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
1269 if (PredCases[i].Dest == BB) {
1270 PTIHandled.insert(PredCases[i].Value);
1271
1272 if (PredHasWeights || SuccHasWeights) {
1273 WeightsForHandled[PredCases[i].Value] = Weights[i + 1];
1274 std::swap(Weights[i + 1], Weights.back());
1275 Weights.pop_back();
1276 }
1277
1278 std::swap(PredCases[i], PredCases.back());
1279 PredCases.pop_back();
1280 --i;
1281 --e;
1282 }
1283
1284 // Okay, now we know which constants were sent to BB from the
1285 // predecessor. Figure out where they will all go now.
1286 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
1287 if (PTIHandled.count(BBCases[i].Value)) {
1288 // If this is one we are capable of getting...
1289 if (PredHasWeights || SuccHasWeights)
1290 Weights.push_back(WeightsForHandled[BBCases[i].Value]);
1291 PredCases.push_back(BBCases[i]);
1292 ++NewSuccessors[BBCases[i].Dest];
1293 PTIHandled.erase(BBCases[i].Value); // This constant is taken care of
1294 }
1295
1296 // If there are any constants vectored to BB that TI doesn't handle,
1297 // they must go to the default destination of TI.
1298 for (ConstantInt *I : PTIHandled) {
1299 if (PredHasWeights || SuccHasWeights)
1300 Weights.push_back(WeightsForHandled[I]);
1301 PredCases.push_back(ValueEqualityComparisonCase(I, BBDefault));
1302 ++NewSuccessors[BBDefault];
1303 }
1304 }
1305
1306 // Okay, at this point, we know which new successor Pred will get. Make
1307 // sure we update the number of entries in the PHI nodes for these
1308 // successors.
1309 SmallPtrSet<BasicBlock *, 2> SuccsOfPred;
1310 if (DTU) {
1311 SuccsOfPred = {succ_begin(Pred), succ_end(Pred)};
1312 Updates.reserve(Updates.size() + NewSuccessors.size());
1313 }
1314 for (const std::pair<BasicBlock *, int /*Num*/> &NewSuccessor :
1315 NewSuccessors) {
1316 for (auto I : seq(NewSuccessor.second)) {
1317 (void)I;
1318 addPredecessorToBlock(NewSuccessor.first, Pred, BB);
1319 }
1320 if (DTU && !SuccsOfPred.contains(NewSuccessor.first))
1321 Updates.push_back({DominatorTree::Insert, Pred, NewSuccessor.first});
1322 }
1323
1324 Builder.SetInsertPoint(PTI);
1325 // Convert pointer to int before we switch.
1326 if (CV->getType()->isPointerTy()) {
1327 CV =
1328 Builder.CreatePtrToInt(CV, DL.getIntPtrType(CV->getType()), "magicptr");
1329 }
1330
1331 // Now that the successors are updated, create the new Switch instruction.
1332 SwitchInst *NewSI = Builder.CreateSwitch(CV, PredDefault, PredCases.size());
1333 NewSI->setDebugLoc(PTI->getDebugLoc());
1334 for (ValueEqualityComparisonCase &V : PredCases)
1335 NewSI->addCase(V.Value, V.Dest);
1336
1337 if (PredHasWeights || SuccHasWeights) {
1338 // Halve the weights if any of them cannot fit in an uint32_t
1339 fitWeights(Weights);
1340
1341 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
1342
1343 setBranchWeights(NewSI, MDWeights, /*IsExpected=*/false);
1344 }
1345
1347
1348 // Okay, last check. If BB is still a successor of PSI, then we must
1349 // have an infinite loop case. If so, add an infinitely looping block
1350 // to handle the case to preserve the behavior of the code.
1351 BasicBlock *InfLoopBlock = nullptr;
1352 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
1353 if (NewSI->getSuccessor(i) == BB) {
1354 if (!InfLoopBlock) {
1355 // Insert it at the end of the function, because it's either code,
1356 // or it won't matter if it's hot. :)
1357 InfLoopBlock =
1358 BasicBlock::Create(BB->getContext(), "infloop", BB->getParent());
1359 BranchInst::Create(InfLoopBlock, InfLoopBlock);
1360 if (DTU)
1361 Updates.push_back(
1362 {DominatorTree::Insert, InfLoopBlock, InfLoopBlock});
1363 }
1364 NewSI->setSuccessor(i, InfLoopBlock);
1365 }
1366
1367 if (DTU) {
1368 if (InfLoopBlock)
1369 Updates.push_back({DominatorTree::Insert, Pred, InfLoopBlock});
1370
1371 Updates.push_back({DominatorTree::Delete, Pred, BB});
1372
1373 DTU->applyUpdates(Updates);
1374 }
1375
1376 ++NumFoldValueComparisonIntoPredecessors;
1377 return true;
1378}
1379
1380/// The specified terminator is a value equality comparison instruction
1381/// (either a switch or a branch on "X == c").
1382/// See if any of the predecessors of the terminator block are value comparisons
1383/// on the same value. If so, and if safe to do so, fold them together.
1384bool SimplifyCFGOpt::foldValueComparisonIntoPredecessors(Instruction *TI,
1385 IRBuilder<> &Builder) {
1386 BasicBlock *BB = TI->getParent();
1387 Value *CV = isValueEqualityComparison(TI); // CondVal
1388 assert(CV && "Not a comparison?");
1389
1390 bool Changed = false;
1391
1393 while (!Preds.empty()) {
1394 BasicBlock *Pred = Preds.pop_back_val();
1395 Instruction *PTI = Pred->getTerminator();
1396
1397 // Don't try to fold into itself.
1398 if (Pred == BB)
1399 continue;
1400
1401 // See if the predecessor is a comparison with the same value.
1402 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
1403 if (PCV != CV)
1404 continue;
1405
1407 if (!safeToMergeTerminators(TI, PTI, &FailBlocks)) {
1408 for (auto *Succ : FailBlocks) {
1409 if (!SplitBlockPredecessors(Succ, TI->getParent(), ".fold.split", DTU))
1410 return false;
1411 }
1412 }
1413
1414 performValueComparisonIntoPredecessorFolding(TI, CV, PTI, Builder);
1415 Changed = true;
1416 }
1417 return Changed;
1418}
1419
1420// If we would need to insert a select that uses the value of this invoke
1421// (comments in hoistSuccIdenticalTerminatorToSwitchOrIf explain why we would
1422// need to do this), we can't hoist the invoke, as there is nowhere to put the
1423// select in this case.
1425 Instruction *I1, Instruction *I2) {
1426 for (BasicBlock *Succ : successors(BB1)) {
1427 for (const PHINode &PN : Succ->phis()) {
1428 Value *BB1V = PN.getIncomingValueForBlock(BB1);
1429 Value *BB2V = PN.getIncomingValueForBlock(BB2);
1430 if (BB1V != BB2V && (BB1V == I1 || BB2V == I2)) {
1431 return false;
1432 }
1433 }
1434 }
1435 return true;
1436}
1437
1438// Get interesting characteristics of instructions that
1439// `hoistCommonCodeFromSuccessors` didn't hoist. They restrict what kind of
1440// instructions can be reordered across.
1446
1448 unsigned Flags = 0;
1449 if (I->mayReadFromMemory())
1450 Flags |= SkipReadMem;
1451 // We can't arbitrarily move around allocas, e.g. moving allocas (especially
1452 // inalloca) across stacksave/stackrestore boundaries.
1453 if (I->mayHaveSideEffects() || isa<AllocaInst>(I))
1454 Flags |= SkipSideEffect;
1456 Flags |= SkipImplicitControlFlow;
1457 return Flags;
1458}
1459
1460// Returns true if it is safe to reorder an instruction across preceding
1461// instructions in a basic block.
1462static bool isSafeToHoistInstr(Instruction *I, unsigned Flags) {
1463 // Don't reorder a store over a load.
1464 if ((Flags & SkipReadMem) && I->mayWriteToMemory())
1465 return false;
1466
1467 // If we have seen an instruction with side effects, it's unsafe to reorder an
1468 // instruction which reads memory or itself has side effects.
1469 if ((Flags & SkipSideEffect) &&
1470 (I->mayReadFromMemory() || I->mayHaveSideEffects() || isa<AllocaInst>(I)))
1471 return false;
1472
1473 // Reordering across an instruction which does not necessarily transfer
1474 // control to the next instruction is speculation.
1476 return false;
1477
1478 // Hoisting of llvm.deoptimize is only legal together with the next return
1479 // instruction, which this pass is not always able to do.
1480 if (auto *CB = dyn_cast<CallBase>(I))
1481 if (CB->getIntrinsicID() == Intrinsic::experimental_deoptimize)
1482 return false;
1483
1484 // It's also unsafe/illegal to hoist an instruction above its instruction
1485 // operands
1486 BasicBlock *BB = I->getParent();
1487 for (Value *Op : I->operands()) {
1488 if (auto *J = dyn_cast<Instruction>(Op))
1489 if (J->getParent() == BB)
1490 return false;
1491 }
1492
1493 return true;
1494}
1495
1496static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I, bool PtrValueMayBeModified = false);
1497
1498/// Helper function for hoistCommonCodeFromSuccessors. Return true if identical
1499/// instructions \p I1 and \p I2 can and should be hoisted.
1501 const TargetTransformInfo &TTI) {
1502 // If we're going to hoist a call, make sure that the two instructions
1503 // we're commoning/hoisting are both marked with musttail, or neither of
1504 // them is marked as such. Otherwise, we might end up in a situation where
1505 // we hoist from a block where the terminator is a `ret` to a block where
1506 // the terminator is a `br`, and `musttail` calls expect to be followed by
1507 // a return.
1508 auto *C1 = dyn_cast<CallInst>(I1);
1509 auto *C2 = dyn_cast<CallInst>(I2);
1510 if (C1 && C2)
1511 if (C1->isMustTailCall() != C2->isMustTailCall())
1512 return false;
1513
1515 return false;
1516
1517 // If any of the two call sites has nomerge or convergent attribute, stop
1518 // hoisting.
1519 if (const auto *CB1 = dyn_cast<CallBase>(I1))
1520 if (CB1->cannotMerge() || CB1->isConvergent())
1521 return false;
1522 if (const auto *CB2 = dyn_cast<CallBase>(I2))
1523 if (CB2->cannotMerge() || CB2->isConvergent())
1524 return false;
1525
1526 return true;
1527}
1528
1529/// Hoists DbgVariableRecords from \p I1 and \p OtherInstrs that are identical
1530/// in lock-step to \p TI. This matches how dbg.* intrinsics are hoisting in
1531/// hoistCommonCodeFromSuccessors. e.g. The input:
1532/// I1 DVRs: { x, z },
1533/// OtherInsts: { I2 DVRs: { x, y, z } }
1534/// would result in hoisting only DbgVariableRecord x.
1536 Instruction *TI, Instruction *I1,
1537 SmallVectorImpl<Instruction *> &OtherInsts) {
1538 if (!I1->hasDbgRecords())
1539 return;
1540 using CurrentAndEndIt =
1541 std::pair<DbgRecord::self_iterator, DbgRecord::self_iterator>;
1542 // Vector of {Current, End} iterators.
1544 Itrs.reserve(OtherInsts.size() + 1);
1545 // Helper lambdas for lock-step checks:
1546 // Return true if this Current == End.
1547 auto atEnd = [](const CurrentAndEndIt &Pair) {
1548 return Pair.first == Pair.second;
1549 };
1550 // Return true if all Current are identical.
1551 auto allIdentical = [](const SmallVector<CurrentAndEndIt> &Itrs) {
1552 return all_of(make_first_range(ArrayRef(Itrs).drop_front()),
1554 return Itrs[0].first->isIdenticalToWhenDefined(*I);
1555 });
1556 };
1557
1558 // Collect the iterators.
1559 Itrs.push_back(
1560 {I1->getDbgRecordRange().begin(), I1->getDbgRecordRange().end()});
1561 for (Instruction *Other : OtherInsts) {
1562 if (!Other->hasDbgRecords())
1563 return;
1564 Itrs.push_back(
1565 {Other->getDbgRecordRange().begin(), Other->getDbgRecordRange().end()});
1566 }
1567
1568 // Iterate in lock-step until any of the DbgRecord lists are exausted. If
1569 // the lock-step DbgRecord are identical, hoist all of them to TI.
1570 // This replicates the dbg.* intrinsic behaviour in
1571 // hoistCommonCodeFromSuccessors.
1572 while (none_of(Itrs, atEnd)) {
1573 bool HoistDVRs = allIdentical(Itrs);
1574 for (CurrentAndEndIt &Pair : Itrs) {
1575 // Increment Current iterator now as we may be about to move the
1576 // DbgRecord.
1577 DbgRecord &DR = *Pair.first++;
1578 if (HoistDVRs) {
1579 DR.removeFromParent();
1580 TI->getParent()->insertDbgRecordBefore(&DR, TI->getIterator());
1581 }
1582 }
1583 }
1584}
1585
1586/// Hoist any common code in the successor blocks up into the block. This
1587/// function guarantees that BB dominates all successors. If EqTermsOnly is
1588/// given, only perform hoisting in case both blocks only contain a terminator.
1589/// In that case, only the original BI will be replaced and selects for PHIs are
1590/// added.
1591bool SimplifyCFGOpt::hoistCommonCodeFromSuccessors(BasicBlock *BB,
1592 bool EqTermsOnly) {
1593 // This does very trivial matching, with limited scanning, to find identical
1594 // instructions in the two blocks. In particular, we don't want to get into
1595 // O(N1*N2*...) situations here where Ni are the sizes of these successors. As
1596 // such, we currently just scan for obviously identical instructions in an
1597 // identical order, possibly separated by the same number of non-identical
1598 // instructions.
1599 unsigned int SuccSize = succ_size(BB);
1600 if (SuccSize < 2)
1601 return false;
1602
1603 // If either of the blocks has it's address taken, then we can't do this fold,
1604 // because the code we'd hoist would no longer run when we jump into the block
1605 // by it's address.
1606 for (auto *Succ : successors(BB))
1607 if (Succ->hasAddressTaken() || !Succ->getSinglePredecessor())
1608 return false;
1609
1610 auto *TI = BB->getTerminator();
1611
1612 // The second of pair is a SkipFlags bitmask.
1613 using SuccIterPair = std::pair<BasicBlock::iterator, unsigned>;
1614 SmallVector<SuccIterPair, 8> SuccIterPairs;
1615 for (auto *Succ : successors(BB)) {
1616 BasicBlock::iterator SuccItr = Succ->begin();
1617 if (isa<PHINode>(*SuccItr))
1618 return false;
1619 SuccIterPairs.push_back(SuccIterPair(SuccItr, 0));
1620 }
1621
1622 // Check if only hoisting terminators is allowed. This does not add new
1623 // instructions to the hoist location.
1624 if (EqTermsOnly) {
1625 // Skip any debug intrinsics, as they are free to hoist.
1626 for (auto &SuccIter : make_first_range(SuccIterPairs)) {
1627 auto *INonDbg = &*skipDebugIntrinsics(SuccIter);
1628 if (!INonDbg->isTerminator())
1629 return false;
1630 }
1631 // Now we know that we only need to hoist debug intrinsics and the
1632 // terminator. Let the loop below handle those 2 cases.
1633 }
1634
1635 // Count how many instructions were not hoisted so far. There's a limit on how
1636 // many instructions we skip, serving as a compilation time control as well as
1637 // preventing excessive increase of life ranges.
1638 unsigned NumSkipped = 0;
1639 // If we find an unreachable instruction at the beginning of a basic block, we
1640 // can still hoist instructions from the rest of the basic blocks.
1641 if (SuccIterPairs.size() > 2) {
1642 erase_if(SuccIterPairs,
1643 [](const auto &Pair) { return isa<UnreachableInst>(Pair.first); });
1644 if (SuccIterPairs.size() < 2)
1645 return false;
1646 }
1647
1648 bool Changed = false;
1649
1650 for (;;) {
1651 auto *SuccIterPairBegin = SuccIterPairs.begin();
1652 auto &BB1ItrPair = *SuccIterPairBegin++;
1653 auto OtherSuccIterPairRange =
1654 iterator_range(SuccIterPairBegin, SuccIterPairs.end());
1655 auto OtherSuccIterRange = make_first_range(OtherSuccIterPairRange);
1656
1657 Instruction *I1 = &*BB1ItrPair.first;
1658
1659 // Skip debug info if it is not identical.
1660 bool AllDbgInstsAreIdentical = all_of(OtherSuccIterRange, [I1](auto &Iter) {
1661 Instruction *I2 = &*Iter;
1662 return I1->isIdenticalToWhenDefined(I2);
1663 });
1664 if (!AllDbgInstsAreIdentical) {
1665 while (isa<DbgInfoIntrinsic>(I1))
1666 I1 = &*++BB1ItrPair.first;
1667 for (auto &SuccIter : OtherSuccIterRange) {
1668 Instruction *I2 = &*SuccIter;
1669 while (isa<DbgInfoIntrinsic>(I2))
1670 I2 = &*++SuccIter;
1671 }
1672 }
1673
1674 bool AllInstsAreIdentical = true;
1675 bool HasTerminator = I1->isTerminator();
1676 for (auto &SuccIter : OtherSuccIterRange) {
1677 Instruction *I2 = &*SuccIter;
1678 HasTerminator |= I2->isTerminator();
1679 if (AllInstsAreIdentical && (!I1->isIdenticalToWhenDefined(I2) ||
1680 MMRAMetadata(*I1) != MMRAMetadata(*I2)))
1681 AllInstsAreIdentical = false;
1682 }
1683
1685 for (auto &SuccIter : OtherSuccIterRange)
1686 OtherInsts.push_back(&*SuccIter);
1687
1688 // If we are hoisting the terminator instruction, don't move one (making a
1689 // broken BB), instead clone it, and remove BI.
1690 if (HasTerminator) {
1691 // Even if BB, which contains only one unreachable instruction, is ignored
1692 // at the beginning of the loop, we can hoist the terminator instruction.
1693 // If any instructions remain in the block, we cannot hoist terminators.
1694 if (NumSkipped || !AllInstsAreIdentical) {
1695 hoistLockstepIdenticalDbgVariableRecords(TI, I1, OtherInsts);
1696 return Changed;
1697 }
1698
1699 return hoistSuccIdenticalTerminatorToSwitchOrIf(TI, I1, OtherInsts) ||
1700 Changed;
1701 }
1702
1703 if (AllInstsAreIdentical) {
1704 unsigned SkipFlagsBB1 = BB1ItrPair.second;
1705 AllInstsAreIdentical =
1706 isSafeToHoistInstr(I1, SkipFlagsBB1) &&
1707 all_of(OtherSuccIterPairRange, [=](const auto &Pair) {
1708 Instruction *I2 = &*Pair.first;
1709 unsigned SkipFlagsBB2 = Pair.second;
1710 // Even if the instructions are identical, it may not
1711 // be safe to hoist them if we have skipped over
1712 // instructions with side effects or their operands
1713 // weren't hoisted.
1714 return isSafeToHoistInstr(I2, SkipFlagsBB2) &&
1716 });
1717 }
1718
1719 if (AllInstsAreIdentical) {
1720 BB1ItrPair.first++;
1721 if (isa<DbgInfoIntrinsic>(I1)) {
1722 // The debug location is an integral part of a debug info intrinsic
1723 // and can't be separated from it or replaced. Instead of attempting
1724 // to merge locations, simply hoist both copies of the intrinsic.
1725 hoistLockstepIdenticalDbgVariableRecords(TI, I1, OtherInsts);
1726 // We've just hoisted DbgVariableRecords; move I1 after them (before TI)
1727 // and leave any that were not hoisted behind (by calling moveBefore
1728 // rather than moveBeforePreserving).
1729 I1->moveBefore(TI);
1730 for (auto &SuccIter : OtherSuccIterRange) {
1731 auto *I2 = &*SuccIter++;
1732 assert(isa<DbgInfoIntrinsic>(I2));
1733 I2->moveBefore(TI);
1734 }
1735 } else {
1736 // For a normal instruction, we just move one to right before the
1737 // branch, then replace all uses of the other with the first. Finally,
1738 // we remove the now redundant second instruction.
1739 hoistLockstepIdenticalDbgVariableRecords(TI, I1, OtherInsts);
1740 // We've just hoisted DbgVariableRecords; move I1 after them (before TI)
1741 // and leave any that were not hoisted behind (by calling moveBefore
1742 // rather than moveBeforePreserving).
1743 I1->moveBefore(TI);
1744 for (auto &SuccIter : OtherSuccIterRange) {
1745 Instruction *I2 = &*SuccIter++;
1746 assert(I2 != I1);
1747 if (!I2->use_empty())
1748 I2->replaceAllUsesWith(I1);
1749 I1->andIRFlags(I2);
1750 combineMetadataForCSE(I1, I2, true);
1751 // I1 and I2 are being combined into a single instruction. Its debug
1752 // location is the merged locations of the original instructions.
1753 I1->applyMergedLocation(I1->getDebugLoc(), I2->getDebugLoc());
1754 I2->eraseFromParent();
1755 }
1756 }
1757 if (!Changed)
1758 NumHoistCommonCode += SuccIterPairs.size();
1759 Changed = true;
1760 NumHoistCommonInstrs += SuccIterPairs.size();
1761 } else {
1762 if (NumSkipped >= HoistCommonSkipLimit) {
1763 hoistLockstepIdenticalDbgVariableRecords(TI, I1, OtherInsts);
1764 return Changed;
1765 }
1766 // We are about to skip over a pair of non-identical instructions. Record
1767 // if any have characteristics that would prevent reordering instructions
1768 // across them.
1769 for (auto &SuccIterPair : SuccIterPairs) {
1770 Instruction *I = &*SuccIterPair.first++;
1771 SuccIterPair.second |= skippedInstrFlags(I);
1772 }
1773 ++NumSkipped;
1774 }
1775 }
1776}
1777
1778bool SimplifyCFGOpt::hoistSuccIdenticalTerminatorToSwitchOrIf(
1779 Instruction *TI, Instruction *I1,
1780 SmallVectorImpl<Instruction *> &OtherSuccTIs) {
1781
1782 auto *BI = dyn_cast<BranchInst>(TI);
1783
1784 bool Changed = false;
1785 BasicBlock *TIParent = TI->getParent();
1786 BasicBlock *BB1 = I1->getParent();
1787
1788 // Use only for an if statement.
1789 auto *I2 = *OtherSuccTIs.begin();
1790 auto *BB2 = I2->getParent();
1791 if (BI) {
1792 assert(OtherSuccTIs.size() == 1);
1793 assert(BI->getSuccessor(0) == I1->getParent());
1794 assert(BI->getSuccessor(1) == I2->getParent());
1795 }
1796
1797 // In the case of an if statement, we try to hoist an invoke.
1798 // FIXME: Can we define a safety predicate for CallBr?
1799 // FIXME: Test case llvm/test/Transforms/SimplifyCFG/2009-06-15-InvokeCrash.ll
1800 // removed in 4c923b3b3fd0ac1edebf0603265ca3ba51724937 commit?
1801 if (isa<InvokeInst>(I1) && (!BI || !isSafeToHoistInvoke(BB1, BB2, I1, I2)))
1802 return false;
1803
1804 // TODO: callbr hoisting currently disabled pending further study.
1805 if (isa<CallBrInst>(I1))
1806 return false;
1807
1808 for (BasicBlock *Succ : successors(BB1)) {
1809 for (PHINode &PN : Succ->phis()) {
1810 Value *BB1V = PN.getIncomingValueForBlock(BB1);
1811 for (Instruction *OtherSuccTI : OtherSuccTIs) {
1812 Value *BB2V = PN.getIncomingValueForBlock(OtherSuccTI->getParent());
1813 if (BB1V == BB2V)
1814 continue;
1815
1816 // In the case of an if statement, check for
1817 // passingValueIsAlwaysUndefined here because we would rather eliminate
1818 // undefined control flow then converting it to a select.
1819 if (!BI || passingValueIsAlwaysUndefined(BB1V, &PN) ||
1821 return false;
1822 }
1823 }
1824 }
1825
1826 // Hoist DbgVariableRecords attached to the terminator to match dbg.*
1827 // intrinsic hoisting behaviour in hoistCommonCodeFromSuccessors.
1828 hoistLockstepIdenticalDbgVariableRecords(TI, I1, OtherSuccTIs);
1829 // Clone the terminator and hoist it into the pred, without any debug info.
1830 Instruction *NT = I1->clone();
1831 NT->insertInto(TIParent, TI->getIterator());
1832 if (!NT->getType()->isVoidTy()) {
1833 I1->replaceAllUsesWith(NT);
1834 for (Instruction *OtherSuccTI : OtherSuccTIs)
1835 OtherSuccTI->replaceAllUsesWith(NT);
1836 NT->takeName(I1);
1837 }
1838 Changed = true;
1839 NumHoistCommonInstrs += OtherSuccTIs.size() + 1;
1840
1841 // Ensure terminator gets a debug location, even an unknown one, in case
1842 // it involves inlinable calls.
1844 Locs.push_back(I1->getDebugLoc());
1845 for (auto *OtherSuccTI : OtherSuccTIs)
1846 Locs.push_back(OtherSuccTI->getDebugLoc());
1847 NT->setDebugLoc(DILocation::getMergedLocations(Locs));
1848
1849 // PHIs created below will adopt NT's merged DebugLoc.
1850 IRBuilder<NoFolder> Builder(NT);
1851
1852 // In the case of an if statement, hoisting one of the terminators from our
1853 // successor is a great thing. Unfortunately, the successors of the if/else
1854 // blocks may have PHI nodes in them. If they do, all PHI entries for BB1/BB2
1855 // must agree for all PHI nodes, so we insert select instruction to compute
1856 // the final result.
1857 if (BI) {
1858 std::map<std::pair<Value *, Value *>, SelectInst *> InsertedSelects;
1859 for (BasicBlock *Succ : successors(BB1)) {
1860 for (PHINode &PN : Succ->phis()) {
1861 Value *BB1V = PN.getIncomingValueForBlock(BB1);
1862 Value *BB2V = PN.getIncomingValueForBlock(BB2);
1863 if (BB1V == BB2V)
1864 continue;
1865
1866 // These values do not agree. Insert a select instruction before NT
1867 // that determines the right value.
1868 SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
1869 if (!SI) {
1870 // Propagate fast-math-flags from phi node to its replacement select.
1871 IRBuilder<>::FastMathFlagGuard FMFGuard(Builder);
1872 if (isa<FPMathOperator>(PN))
1873 Builder.setFastMathFlags(PN.getFastMathFlags());
1874
1875 SI = cast<SelectInst>(Builder.CreateSelect(
1876 BI->getCondition(), BB1V, BB2V,
1877 BB1V->getName() + "." + BB2V->getName(), BI));
1878 }
1879
1880 // Make the PHI node use the select for all incoming values for BB1/BB2
1881 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
1882 if (PN.getIncomingBlock(i) == BB1 || PN.getIncomingBlock(i) == BB2)
1883 PN.setIncomingValue(i, SI);
1884 }
1885 }
1886 }
1887
1889
1890 // Update any PHI nodes in our new successors.
1891 for (BasicBlock *Succ : successors(BB1)) {
1892 addPredecessorToBlock(Succ, TIParent, BB1);
1893 if (DTU)
1894 Updates.push_back({DominatorTree::Insert, TIParent, Succ});
1895 }
1896
1897 if (DTU)
1898 for (BasicBlock *Succ : successors(TI))
1899 Updates.push_back({DominatorTree::Delete, TIParent, Succ});
1900
1902 if (DTU)
1903 DTU->applyUpdates(Updates);
1904 return Changed;
1905}
1906
1907// Check lifetime markers.
1908static bool isLifeTimeMarker(const Instruction *I) {
1909 if (auto II = dyn_cast<IntrinsicInst>(I)) {
1910 switch (II->getIntrinsicID()) {
1911 default:
1912 break;
1913 case Intrinsic::lifetime_start:
1914 case Intrinsic::lifetime_end:
1915 return true;
1916 }
1917 }
1918 return false;
1919}
1920
1921// TODO: Refine this. This should avoid cases like turning constant memcpy sizes
1922// into variables.
1924 int OpIdx) {
1925 return !isa<IntrinsicInst>(I);
1926}
1927
1928// All instructions in Insts belong to different blocks that all unconditionally
1929// branch to a common successor. Analyze each instruction and return true if it
1930// would be possible to sink them into their successor, creating one common
1931// instruction instead. For every value that would be required to be provided by
1932// PHI node (because an operand varies in each input block), add to PHIOperands.
1935 DenseMap<const Use *, SmallVector<Value *, 4>> &PHIOperands) {
1936 // Prune out obviously bad instructions to move. Each instruction must have
1937 // the same number of uses, and we check later that the uses are consistent.
1938 std::optional<unsigned> NumUses;
1939 for (auto *I : Insts) {
1940 // These instructions may change or break semantics if moved.
1941 if (isa<PHINode>(I) || I->isEHPad() || isa<AllocaInst>(I) ||
1942 I->getType()->isTokenTy())
1943 return false;
1944
1945 // Do not try to sink an instruction in an infinite loop - it can cause
1946 // this algorithm to infinite loop.
1947 if (I->getParent()->getSingleSuccessor() == I->getParent())
1948 return false;
1949
1950 // Conservatively return false if I is an inline-asm instruction. Sinking
1951 // and merging inline-asm instructions can potentially create arguments
1952 // that cannot satisfy the inline-asm constraints.
1953 // If the instruction has nomerge or convergent attribute, return false.
1954 if (const auto *C = dyn_cast<CallBase>(I))
1955 if (C->isInlineAsm() || C->cannotMerge() || C->isConvergent())
1956 return false;
1957
1958 if (!NumUses)
1959 NumUses = I->getNumUses();
1960 else if (NumUses != I->getNumUses())
1961 return false;
1962 }
1963
1964 const Instruction *I0 = Insts.front();
1965 const auto I0MMRA = MMRAMetadata(*I0);
1966 for (auto *I : Insts) {
1967 if (!I->isSameOperationAs(I0))
1968 return false;
1969
1970 // swifterror pointers can only be used by a load or store; sinking a load
1971 // or store would require introducing a select for the pointer operand,
1972 // which isn't allowed for swifterror pointers.
1973 if (isa<StoreInst>(I) && I->getOperand(1)->isSwiftError())
1974 return false;
1975 if (isa<LoadInst>(I) && I->getOperand(0)->isSwiftError())
1976 return false;
1977
1978 // Treat MMRAs conservatively. This pass can be quite aggressive and
1979 // could drop a lot of MMRAs otherwise.
1980 if (MMRAMetadata(*I) != I0MMRA)
1981 return false;
1982 }
1983
1984 // Uses must be consistent: If I0 is used in a phi node in the sink target,
1985 // then the other phi operands must match the instructions from Insts. This
1986 // also has to hold true for any phi nodes that would be created as a result
1987 // of sinking. Both of these cases are represented by PhiOperands.
1988 for (const Use &U : I0->uses()) {
1989 auto It = PHIOperands.find(&U);
1990 if (It == PHIOperands.end())
1991 // There may be uses in other blocks when sinking into a loop header.
1992 return false;
1993 if (!equal(Insts, It->second))
1994 return false;
1995 }
1996
1997 // Because SROA can't handle speculating stores of selects, try not to sink
1998 // loads, stores or lifetime markers of allocas when we'd have to create a
1999 // PHI for the address operand. Also, because it is likely that loads or
2000 // stores of allocas will disappear when Mem2Reg/SROA is run, don't sink
2001 // them.
2002 // This can cause code churn which can have unintended consequences down
2003 // the line - see https://llvm.org/bugs/show_bug.cgi?id=30244.
2004 // FIXME: This is a workaround for a deficiency in SROA - see
2005 // https://llvm.org/bugs/show_bug.cgi?id=30188
2006 if (isa<StoreInst>(I0) && any_of(Insts, [](const Instruction *I) {
2007 return isa<AllocaInst>(I->getOperand(1)->stripPointerCasts());
2008 }))
2009 return false;
2010 if (isa<LoadInst>(I0) && any_of(Insts, [](const Instruction *I) {
2011 return isa<AllocaInst>(I->getOperand(0)->stripPointerCasts());
2012 }))
2013 return false;
2014 if (isLifeTimeMarker(I0) && any_of(Insts, [](const Instruction *I) {
2015 return isa<AllocaInst>(I->getOperand(1)->stripPointerCasts());
2016 }))
2017 return false;
2018
2019 // For calls to be sinkable, they must all be indirect, or have same callee.
2020 // I.e. if we have two direct calls to different callees, we don't want to
2021 // turn that into an indirect call. Likewise, if we have an indirect call,
2022 // and a direct call, we don't actually want to have a single indirect call.
2023 if (isa<CallBase>(I0)) {
2024 auto IsIndirectCall = [](const Instruction *I) {
2025 return cast<CallBase>(I)->isIndirectCall();
2026 };
2027 bool HaveIndirectCalls = any_of(Insts, IsIndirectCall);
2028 bool AllCallsAreIndirect = all_of(Insts, IsIndirectCall);
2029 if (HaveIndirectCalls) {
2030 if (!AllCallsAreIndirect)
2031 return false;
2032 } else {
2033 // All callees must be identical.
2034 Value *Callee = nullptr;
2035 for (const Instruction *I : Insts) {
2036 Value *CurrCallee = cast<CallBase>(I)->getCalledOperand();
2037 if (!Callee)
2038 Callee = CurrCallee;
2039 else if (Callee != CurrCallee)
2040 return false;
2041 }
2042 }
2043 }
2044
2045 for (unsigned OI = 0, OE = I0->getNumOperands(); OI != OE; ++OI) {
2046 Value *Op = I0->getOperand(OI);
2047 if (Op->getType()->isTokenTy())
2048 // Don't touch any operand of token type.
2049 return false;
2050
2051 auto SameAsI0 = [&I0, OI](const Instruction *I) {
2052 assert(I->getNumOperands() == I0->getNumOperands());
2053 return I->getOperand(OI) == I0->getOperand(OI);
2054 };
2055 if (!all_of(Insts, SameAsI0)) {
2056 if ((isa<Constant>(Op) && !replacingOperandWithVariableIsCheap(I0, OI)) ||
2058 // We can't create a PHI from this GEP.
2059 return false;
2060 auto &Ops = PHIOperands[&I0->getOperandUse(OI)];
2061 for (auto *I : Insts)
2062 Ops.push_back(I->getOperand(OI));
2063 }
2064 }
2065 return true;
2066}
2067
2068// Assuming canSinkInstructions(Blocks) has returned true, sink the last
2069// instruction of every block in Blocks to their common successor, commoning
2070// into one instruction.
2072 auto *BBEnd = Blocks[0]->getTerminator()->getSuccessor(0);
2073
2074 // canSinkInstructions returning true guarantees that every block has at
2075 // least one non-terminator instruction.
2077 for (auto *BB : Blocks) {
2078 Instruction *I = BB->getTerminator();
2079 do {
2080 I = I->getPrevNode();
2081 } while (isa<DbgInfoIntrinsic>(I) && I != &BB->front());
2082 if (!isa<DbgInfoIntrinsic>(I))
2083 Insts.push_back(I);
2084 }
2085
2086 // We don't need to do any more checking here; canSinkInstructions should
2087 // have done it all for us.
2088 SmallVector<Value*, 4> NewOperands;
2089 Instruction *I0 = Insts.front();
2090 for (unsigned O = 0, E = I0->getNumOperands(); O != E; ++O) {
2091 // This check is different to that in canSinkInstructions. There, we
2092 // cared about the global view once simplifycfg (and instcombine) have
2093 // completed - it takes into account PHIs that become trivially
2094 // simplifiable. However here we need a more local view; if an operand
2095 // differs we create a PHI and rely on instcombine to clean up the very
2096 // small mess we may make.
2097 bool NeedPHI = any_of(Insts, [&I0, O](const Instruction *I) {
2098 return I->getOperand(O) != I0->getOperand(O);
2099 });
2100 if (!NeedPHI) {
2101 NewOperands.push_back(I0->getOperand(O));
2102 continue;
2103 }
2104
2105 // Create a new PHI in the successor block and populate it.
2106 auto *Op = I0->getOperand(O);
2107 assert(!Op->getType()->isTokenTy() && "Can't PHI tokens!");
2108 auto *PN =
2109 PHINode::Create(Op->getType(), Insts.size(), Op->getName() + ".sink");
2110 PN->insertBefore(BBEnd->begin());
2111 for (auto *I : Insts)
2112 PN->addIncoming(I->getOperand(O), I->getParent());
2113 NewOperands.push_back(PN);
2114 }
2115
2116 // Arbitrarily use I0 as the new "common" instruction; remap its operands
2117 // and move it to the start of the successor block.
2118 for (unsigned O = 0, E = I0->getNumOperands(); O != E; ++O)
2119 I0->getOperandUse(O).set(NewOperands[O]);
2120
2121 I0->moveBefore(*BBEnd, BBEnd->getFirstInsertionPt());
2122
2123 // Update metadata and IR flags, and merge debug locations.
2124 for (auto *I : Insts)
2125 if (I != I0) {
2126 // The debug location for the "common" instruction is the merged locations
2127 // of all the commoned instructions. We start with the original location
2128 // of the "common" instruction and iteratively merge each location in the
2129 // loop below.
2130 // This is an N-way merge, which will be inefficient if I0 is a CallInst.
2131 // However, as N-way merge for CallInst is rare, so we use simplified API
2132 // instead of using complex API for N-way merge.
2133 I0->applyMergedLocation(I0->getDebugLoc(), I->getDebugLoc());
2134 combineMetadataForCSE(I0, I, true);
2135 I0->andIRFlags(I);
2136 }
2137
2138 for (User *U : make_early_inc_range(I0->users())) {
2139 // canSinkLastInstruction checked that all instructions are only used by
2140 // phi nodes in a way that allows replacing the phi node with the common
2141 // instruction.
2142 auto *PN = cast<PHINode>(U);
2143 PN->replaceAllUsesWith(I0);
2144 PN->eraseFromParent();
2145 }
2146
2147 // Finally nuke all instructions apart from the common instruction.
2148 for (auto *I : Insts) {
2149 if (I == I0)
2150 continue;
2151 // The remaining uses are debug users, replace those with the common inst.
2152 // In most (all?) cases this just introduces a use-before-def.
2153 assert(I->user_empty() && "Inst unexpectedly still has non-dbg users");
2154 I->replaceAllUsesWith(I0);
2155 I->eraseFromParent();
2156 }
2157}
2158
2159namespace {
2160
2161 // LockstepReverseIterator - Iterates through instructions
2162 // in a set of blocks in reverse order from the first non-terminator.
2163 // For example (assume all blocks have size n):
2164 // LockstepReverseIterator I([B1, B2, B3]);
2165 // *I-- = [B1[n], B2[n], B3[n]];
2166 // *I-- = [B1[n-1], B2[n-1], B3[n-1]];
2167 // *I-- = [B1[n-2], B2[n-2], B3[n-2]];
2168 // ...
2169 class LockstepReverseIterator {
2172 bool Fail;
2173
2174 public:
2175 LockstepReverseIterator(ArrayRef<BasicBlock*> Blocks) : Blocks(Blocks) {
2176 reset();
2177 }
2178
2179 void reset() {
2180 Fail = false;
2181 Insts.clear();
2182 for (auto *BB : Blocks) {
2183 Instruction *Inst = BB->getTerminator();
2184 for (Inst = Inst->getPrevNode(); Inst && isa<DbgInfoIntrinsic>(Inst);)
2185 Inst = Inst->getPrevNode();
2186 if (!Inst) {
2187 // Block wasn't big enough.
2188 Fail = true;
2189 return;
2190 }
2191 Insts.push_back(Inst);
2192 }
2193 }
2194
2195 bool isValid() const {
2196 return !Fail;
2197 }
2198
2199 void operator--() {
2200 if (Fail)
2201 return;
2202 for (auto *&Inst : Insts) {
2203 for (Inst = Inst->getPrevNode(); Inst && isa<DbgInfoIntrinsic>(Inst);)
2204 Inst = Inst->getPrevNode();
2205 // Already at beginning of block.
2206 if (!Inst) {
2207 Fail = true;
2208 return;
2209 }
2210 }
2211 }
2212
2213 void operator++() {
2214 if (Fail)
2215 return;
2216 for (auto *&Inst : Insts) {
2217 for (Inst = Inst->getNextNode(); Inst && isa<DbgInfoIntrinsic>(Inst);)
2218 Inst = Inst->getNextNode();
2219 // Already at end of block.
2220 if (!Inst) {
2221 Fail = true;
2222 return;
2223 }
2224 }
2225 }
2226
2228 return Insts;
2229 }
2230 };
2231
2232} // end anonymous namespace
2233
2234/// Check whether BB's predecessors end with unconditional branches. If it is
2235/// true, sink any common code from the predecessors to BB.
2237 DomTreeUpdater *DTU) {
2238 // We support two situations:
2239 // (1) all incoming arcs are unconditional
2240 // (2) there are non-unconditional incoming arcs
2241 //
2242 // (2) is very common in switch defaults and
2243 // else-if patterns;
2244 //
2245 // if (a) f(1);
2246 // else if (b) f(2);
2247 //
2248 // produces:
2249 //
2250 // [if]
2251 // / \
2252 // [f(1)] [if]
2253 // | | \
2254 // | | |
2255 // | [f(2)]|
2256 // \ | /
2257 // [ end ]
2258 //
2259 // [end] has two unconditional predecessor arcs and one conditional. The
2260 // conditional refers to the implicit empty 'else' arc. This conditional
2261 // arc can also be caused by an empty default block in a switch.
2262 //
2263 // In this case, we attempt to sink code from all *unconditional* arcs.
2264 // If we can sink instructions from these arcs (determined during the scan
2265 // phase below) we insert a common successor for all unconditional arcs and
2266 // connect that to [end], to enable sinking:
2267 //
2268 // [if]
2269 // / \
2270 // [x(1)] [if]
2271 // | | \
2272 // | | \
2273 // | [x(2)] |
2274 // \ / |
2275 // [sink.split] |
2276 // \ /
2277 // [ end ]
2278 //
2279 SmallVector<BasicBlock*,4> UnconditionalPreds;
2280 bool HaveNonUnconditionalPredecessors = false;
2281 for (auto *PredBB : predecessors(BB)) {
2282 auto *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator());
2283 if (PredBr && PredBr->isUnconditional())
2284 UnconditionalPreds.push_back(PredBB);
2285 else
2286 HaveNonUnconditionalPredecessors = true;
2287 }
2288 if (UnconditionalPreds.size() < 2)
2289 return false;
2290
2291 // We take a two-step approach to tail sinking. First we scan from the end of
2292 // each block upwards in lockstep. If the n'th instruction from the end of each
2293 // block can be sunk, those instructions are added to ValuesToSink and we
2294 // carry on. If we can sink an instruction but need to PHI-merge some operands
2295 // (because they're not identical in each instruction) we add these to
2296 // PHIOperands.
2297 // We prepopulate PHIOperands with the phis that already exist in BB.
2299 for (PHINode &PN : BB->phis()) {
2301 for (const Use &U : PN.incoming_values())
2302 IncomingVals.insert({PN.getIncomingBlock(U), &U});
2303 auto &Ops = PHIOperands[IncomingVals[UnconditionalPreds[0]]];
2304 for (BasicBlock *Pred : UnconditionalPreds)
2305 Ops.push_back(*IncomingVals[Pred]);
2306 }
2307
2308 int ScanIdx = 0;
2309 SmallPtrSet<Value*,4> InstructionsToSink;
2310 LockstepReverseIterator LRI(UnconditionalPreds);
2311 while (LRI.isValid() &&
2312 canSinkInstructions(*LRI, PHIOperands)) {
2313 LLVM_DEBUG(dbgs() << "SINK: instruction can be sunk: " << *(*LRI)[0]
2314 << "\n");
2315 InstructionsToSink.insert((*LRI).begin(), (*LRI).end());
2316 ++ScanIdx;
2317 --LRI;
2318 }
2319
2320 // If no instructions can be sunk, early-return.
2321 if (ScanIdx == 0)
2322 return false;
2323
2324 bool followedByDeoptOrUnreachable = IsBlockFollowedByDeoptOrUnreachable(BB);
2325
2326 if (!followedByDeoptOrUnreachable) {
2327 // Okay, we *could* sink last ScanIdx instructions. But how many can we
2328 // actually sink before encountering instruction that is unprofitable to
2329 // sink?
2330 auto ProfitableToSinkInstruction = [&](LockstepReverseIterator &LRI) {
2331 unsigned NumPHIInsts = 0;
2332 for (Use &U : (*LRI)[0]->operands()) {
2333 auto It = PHIOperands.find(&U);
2334 if (It != PHIOperands.end() && !all_of(It->second, [&](Value *V) {
2335 return InstructionsToSink.contains(V);
2336 })) {
2337 ++NumPHIInsts;
2338 // FIXME: this check is overly optimistic. We may end up not sinking
2339 // said instruction, due to the very same profitability check.
2340 // See @creating_too_many_phis in sink-common-code.ll.
2341 }
2342 }
2343 LLVM_DEBUG(dbgs() << "SINK: #phi insts: " << NumPHIInsts << "\n");
2344 return NumPHIInsts <= 1;
2345 };
2346
2347 // We've determined that we are going to sink last ScanIdx instructions,
2348 // and recorded them in InstructionsToSink. Now, some instructions may be
2349 // unprofitable to sink. But that determination depends on the instructions
2350 // that we are going to sink.
2351
2352 // First, forward scan: find the first instruction unprofitable to sink,
2353 // recording all the ones that are profitable to sink.
2354 // FIXME: would it be better, after we detect that not all are profitable.
2355 // to either record the profitable ones, or erase the unprofitable ones?
2356 // Maybe we need to choose (at runtime) the one that will touch least
2357 // instrs?
2358 LRI.reset();
2359 int Idx = 0;
2360 SmallPtrSet<Value *, 4> InstructionsProfitableToSink;
2361 while (Idx < ScanIdx) {
2362 if (!ProfitableToSinkInstruction(LRI)) {
2363 // Too many PHIs would be created.
2364 LLVM_DEBUG(
2365 dbgs() << "SINK: stopping here, too many PHIs would be created!\n");
2366 break;
2367 }
2368 InstructionsProfitableToSink.insert((*LRI).begin(), (*LRI).end());
2369 --LRI;
2370 ++Idx;
2371 }
2372
2373 // If no instructions can be sunk, early-return.
2374 if (Idx == 0)
2375 return false;
2376
2377 // Did we determine that (only) some instructions are unprofitable to sink?
2378 if (Idx < ScanIdx) {
2379 // Okay, some instructions are unprofitable.
2380 ScanIdx = Idx;
2381 InstructionsToSink = InstructionsProfitableToSink;
2382
2383 // But, that may make other instructions unprofitable, too.
2384 // So, do a backward scan, do any earlier instructions become
2385 // unprofitable?
2386 assert(
2387 !ProfitableToSinkInstruction(LRI) &&
2388 "We already know that the last instruction is unprofitable to sink");
2389 ++LRI;
2390 --Idx;
2391 while (Idx >= 0) {
2392 // If we detect that an instruction becomes unprofitable to sink,
2393 // all earlier instructions won't be sunk either,
2394 // so preemptively keep InstructionsProfitableToSink in sync.
2395 // FIXME: is this the most performant approach?
2396 for (auto *I : *LRI)
2397 InstructionsProfitableToSink.erase(I);
2398 if (!ProfitableToSinkInstruction(LRI)) {
2399 // Everything starting with this instruction won't be sunk.
2400 ScanIdx = Idx;
2401 InstructionsToSink = InstructionsProfitableToSink;
2402 }
2403 ++LRI;
2404 --Idx;
2405 }
2406 }
2407
2408 // If no instructions can be sunk, early-return.
2409 if (ScanIdx == 0)
2410 return false;
2411 }
2412
2413 bool Changed = false;
2414
2415 if (HaveNonUnconditionalPredecessors) {
2416 if (!followedByDeoptOrUnreachable) {
2417 // It is always legal to sink common instructions from unconditional
2418 // predecessors. However, if not all predecessors are unconditional,
2419 // this transformation might be pessimizing. So as a rule of thumb,
2420 // don't do it unless we'd sink at least one non-speculatable instruction.
2421 // See https://bugs.llvm.org/show_bug.cgi?id=30244
2422 LRI.reset();
2423 int Idx = 0;
2424 bool Profitable = false;
2425 while (Idx < ScanIdx) {
2426 if (!isSafeToSpeculativelyExecute((*LRI)[0])) {
2427 Profitable = true;
2428 break;
2429 }
2430 --LRI;
2431 ++Idx;
2432 }
2433 if (!Profitable)
2434 return false;
2435 }
2436
2437 LLVM_DEBUG(dbgs() << "SINK: Splitting edge\n");
2438 // We have a conditional edge and we're going to sink some instructions.
2439 // Insert a new block postdominating all blocks we're going to sink from.
2440 if (!SplitBlockPredecessors(BB, UnconditionalPreds, ".sink.split", DTU))
2441 // Edges couldn't be split.
2442 return false;
2443 Changed = true;
2444 }
2445
2446 // Now that we've analyzed all potential sinking candidates, perform the
2447 // actual sink. We iteratively sink the last non-terminator of the source
2448 // blocks into their common successor unless doing so would require too
2449 // many PHI instructions to be generated (currently only one PHI is allowed
2450 // per sunk instruction).
2451 //
2452 // We can use InstructionsToSink to discount values needing PHI-merging that will
2453 // actually be sunk in a later iteration. This allows us to be more
2454 // aggressive in what we sink. This does allow a false positive where we
2455 // sink presuming a later value will also be sunk, but stop half way through
2456 // and never actually sink it which means we produce more PHIs than intended.
2457 // This is unlikely in practice though.
2458 int SinkIdx = 0;
2459 for (; SinkIdx != ScanIdx; ++SinkIdx) {
2460 LLVM_DEBUG(dbgs() << "SINK: Sink: "
2461 << *UnconditionalPreds[0]->getTerminator()->getPrevNode()
2462 << "\n");
2463
2464 // Because we've sunk every instruction in turn, the current instruction to
2465 // sink is always at index 0.
2466 LRI.reset();
2467
2468 sinkLastInstruction(UnconditionalPreds);
2469 NumSinkCommonInstrs++;
2470 Changed = true;
2471 }
2472 if (SinkIdx != 0)
2473 ++NumSinkCommonCode;
2474 return Changed;
2475}
2476
2477namespace {
2478
2479struct CompatibleSets {
2480 using SetTy = SmallVector<InvokeInst *, 2>;
2481
2483
2484 static bool shouldBelongToSameSet(ArrayRef<InvokeInst *> Invokes);
2485
2486 SetTy &getCompatibleSet(InvokeInst *II);
2487
2488 void insert(InvokeInst *II);
2489};
2490
2491CompatibleSets::SetTy &CompatibleSets::getCompatibleSet(InvokeInst *II) {
2492 // Perform a linear scan over all the existing sets, see if the new `invoke`
2493 // is compatible with any particular set. Since we know that all the `invokes`
2494 // within a set are compatible, only check the first `invoke` in each set.
2495 // WARNING: at worst, this has quadratic complexity.
2496 for (CompatibleSets::SetTy &Set : Sets) {
2497 if (CompatibleSets::shouldBelongToSameSet({Set.front(), II}))
2498 return Set;
2499 }
2500
2501 // Otherwise, we either had no sets yet, or this invoke forms a new set.
2502 return Sets.emplace_back();
2503}
2504
2505void CompatibleSets::insert(InvokeInst *II) {
2506 getCompatibleSet(II).emplace_back(II);
2507}
2508
2509bool CompatibleSets::shouldBelongToSameSet(ArrayRef<InvokeInst *> Invokes) {
2510 assert(Invokes.size() == 2 && "Always called with exactly two candidates.");
2511
2512 // Can we theoretically merge these `invoke`s?
2513 auto IsIllegalToMerge = [](InvokeInst *II) {
2514 return II->cannotMerge() || II->isInlineAsm();
2515 };
2516 if (any_of(Invokes, IsIllegalToMerge))
2517 return false;
2518
2519 // Either both `invoke`s must be direct,
2520 // or both `invoke`s must be indirect.
2521 auto IsIndirectCall = [](InvokeInst *II) { return II->isIndirectCall(); };
2522 bool HaveIndirectCalls = any_of(Invokes, IsIndirectCall);
2523 bool AllCallsAreIndirect = all_of(Invokes, IsIndirectCall);
2524 if (HaveIndirectCalls) {
2525 if (!AllCallsAreIndirect)
2526 return false;
2527 } else {
2528 // All callees must be identical.
2529 Value *Callee = nullptr;
2530 for (InvokeInst *II : Invokes) {
2531 Value *CurrCallee = II->getCalledOperand();
2532 assert(CurrCallee && "There is always a called operand.");
2533 if (!Callee)
2534 Callee = CurrCallee;
2535 else if (Callee != CurrCallee)
2536 return false;
2537 }
2538 }
2539
2540 // Either both `invoke`s must not have a normal destination,
2541 // or both `invoke`s must have a normal destination,
2542 auto HasNormalDest = [](InvokeInst *II) {
2543 return !isa<UnreachableInst>(II->getNormalDest()->getFirstNonPHIOrDbg());
2544 };
2545 if (any_of(Invokes, HasNormalDest)) {
2546 // Do not merge `invoke` that does not have a normal destination with one
2547 // that does have a normal destination, even though doing so would be legal.
2548 if (!all_of(Invokes, HasNormalDest))
2549 return false;
2550
2551 // All normal destinations must be identical.
2552 BasicBlock *NormalBB = nullptr;
2553 for (InvokeInst *II : Invokes) {
2554 BasicBlock *CurrNormalBB = II->getNormalDest();
2555 assert(CurrNormalBB && "There is always a 'continue to' basic block.");
2556 if (!NormalBB)
2557 NormalBB = CurrNormalBB;
2558 else if (NormalBB != CurrNormalBB)
2559 return false;
2560 }
2561
2562 // In the normal destination, the incoming values for these two `invoke`s
2563 // must be compatible.
2564 SmallPtrSet<Value *, 16> EquivalenceSet(Invokes.begin(), Invokes.end());
2566 NormalBB, {Invokes[0]->getParent(), Invokes[1]->getParent()},
2567 &EquivalenceSet))
2568 return false;
2569 }
2570
2571#ifndef NDEBUG
2572 // All unwind destinations must be identical.
2573 // We know that because we have started from said unwind destination.
2574 BasicBlock *UnwindBB = nullptr;
2575 for (InvokeInst *II : Invokes) {
2576 BasicBlock *CurrUnwindBB = II->getUnwindDest();
2577 assert(CurrUnwindBB && "There is always an 'unwind to' basic block.");
2578 if (!UnwindBB)
2579 UnwindBB = CurrUnwindBB;
2580 else
2581 assert(UnwindBB == CurrUnwindBB && "Unexpected unwind destination.");
2582 }
2583#endif
2584
2585 // In the unwind destination, the incoming values for these two `invoke`s
2586 // must be compatible.
2588 Invokes.front()->getUnwindDest(),
2589 {Invokes[0]->getParent(), Invokes[1]->getParent()}))
2590 return false;
2591
2592 // Ignoring arguments, these `invoke`s must be identical,
2593 // including operand bundles.
2594 const InvokeInst *II0 = Invokes.front();
2595 for (auto *II : Invokes.drop_front())
2596 if (!II->isSameOperationAs(II0))
2597 return false;
2598
2599 // Can we theoretically form the data operands for the merged `invoke`?
2600 auto IsIllegalToMergeArguments = [](auto Ops) {
2601 Use &U0 = std::get<0>(Ops);
2602 Use &U1 = std::get<1>(Ops);
2603 if (U0 == U1)
2604 return false;
2605 return U0->getType()->isTokenTy() ||
2606 !canReplaceOperandWithVariable(cast<Instruction>(U0.getUser()),
2607 U0.getOperandNo());
2608 };
2609 assert(Invokes.size() == 2 && "Always called with exactly two candidates.");
2610 if (any_of(zip(Invokes[0]->data_ops(), Invokes[1]->data_ops()),
2611 IsIllegalToMergeArguments))
2612 return false;
2613
2614 return true;
2615}
2616
2617} // namespace
2618
2619// Merge all invokes in the provided set, all of which are compatible
2620// as per the `CompatibleSets::shouldBelongToSameSet()`.
2622 DomTreeUpdater *DTU) {
2623 assert(Invokes.size() >= 2 && "Must have at least two invokes to merge.");
2624
2626 if (DTU)
2627 Updates.reserve(2 + 3 * Invokes.size());
2628
2629 bool HasNormalDest =
2630 !isa<UnreachableInst>(Invokes[0]->getNormalDest()->getFirstNonPHIOrDbg());
2631
2632 // Clone one of the invokes into a new basic block.
2633 // Since they are all compatible, it doesn't matter which invoke is cloned.
2634 InvokeInst *MergedInvoke = [&Invokes, HasNormalDest]() {
2635 InvokeInst *II0 = Invokes.front();
2636 BasicBlock *II0BB = II0->getParent();
2637 BasicBlock *InsertBeforeBlock =
2638 II0->getParent()->getIterator()->getNextNode();
2639 Function *Func = II0BB->getParent();
2640 LLVMContext &Ctx = II0->getContext();
2641
2642 BasicBlock *MergedInvokeBB = BasicBlock::Create(
2643 Ctx, II0BB->getName() + ".invoke", Func, InsertBeforeBlock);
2644
2645 auto *MergedInvoke = cast<InvokeInst>(II0->clone());
2646 // NOTE: all invokes have the same attributes, so no handling needed.
2647 MergedInvoke->insertInto(MergedInvokeBB, MergedInvokeBB->end());
2648
2649 if (!HasNormalDest) {
2650 // This set does not have a normal destination,
2651 // so just form a new block with unreachable terminator.
2652 BasicBlock *MergedNormalDest = BasicBlock::Create(
2653 Ctx, II0BB->getName() + ".cont", Func, InsertBeforeBlock);
2654 new UnreachableInst(Ctx, MergedNormalDest);
2655 MergedInvoke->setNormalDest(MergedNormalDest);
2656 }
2657
2658 // The unwind destination, however, remainds identical for all invokes here.
2659
2660 return MergedInvoke;
2661 }();
2662
2663 if (DTU) {
2664 // Predecessor blocks that contained these invokes will now branch to
2665 // the new block that contains the merged invoke, ...
2666 for (InvokeInst *II : Invokes)
2667 Updates.push_back(
2668 {DominatorTree::Insert, II->getParent(), MergedInvoke->getParent()});
2669
2670 // ... which has the new `unreachable` block as normal destination,
2671 // or unwinds to the (same for all `invoke`s in this set) `landingpad`,
2672 for (BasicBlock *SuccBBOfMergedInvoke : successors(MergedInvoke))
2673 Updates.push_back({DominatorTree::Insert, MergedInvoke->getParent(),
2674 SuccBBOfMergedInvoke});
2675
2676 // Since predecessor blocks now unconditionally branch to a new block,
2677 // they no longer branch to their original successors.
2678 for (InvokeInst *II : Invokes)
2679 for (BasicBlock *SuccOfPredBB : successors(II->getParent()))
2680 Updates.push_back(
2681 {DominatorTree::Delete, II->getParent(), SuccOfPredBB});
2682 }
2683
2684 bool IsIndirectCall = Invokes[0]->isIndirectCall();
2685
2686 // Form the merged operands for the merged invoke.
2687 for (Use &U : MergedInvoke->operands()) {
2688 // Only PHI together the indirect callees and data operands.
2689 if (MergedInvoke->isCallee(&U)) {
2690 if (!IsIndirectCall)
2691 continue;
2692 } else if (!MergedInvoke->isDataOperand(&U))
2693 continue;
2694
2695 // Don't create trivial PHI's with all-identical incoming values.
2696 bool NeedPHI = any_of(Invokes, [&U](InvokeInst *II) {
2697 return II->getOperand(U.getOperandNo()) != U.get();
2698 });
2699 if (!NeedPHI)
2700 continue;
2701
2702 // Form a PHI out of all the data ops under this index.
2704 U->getType(), /*NumReservedValues=*/Invokes.size(), "", MergedInvoke->getIterator());
2705 for (InvokeInst *II : Invokes)
2706 PN->addIncoming(II->getOperand(U.getOperandNo()), II->getParent());
2707
2708 U.set(PN);
2709 }
2710
2711 // We've ensured that each PHI node has compatible (identical) incoming values
2712 // when coming from each of the `invoke`s in the current merge set,
2713 // so update the PHI nodes accordingly.
2714 for (BasicBlock *Succ : successors(MergedInvoke))
2715 addPredecessorToBlock(Succ, /*NewPred=*/MergedInvoke->getParent(),
2716 /*ExistPred=*/Invokes.front()->getParent());
2717
2718 // And finally, replace the original `invoke`s with an unconditional branch
2719 // to the block with the merged `invoke`. Also, give that merged `invoke`
2720 // the merged debugloc of all the original `invoke`s.
2721 DILocation *MergedDebugLoc = nullptr;
2722 for (InvokeInst *II : Invokes) {
2723 // Compute the debug location common to all the original `invoke`s.
2724 if (!MergedDebugLoc)
2725 MergedDebugLoc = II->getDebugLoc();
2726 else
2727 MergedDebugLoc =
2728 DILocation::getMergedLocation(MergedDebugLoc, II->getDebugLoc());
2729
2730 // And replace the old `invoke` with an unconditionally branch
2731 // to the block with the merged `invoke`.
2732 for (BasicBlock *OrigSuccBB : successors(II->getParent()))
2733 OrigSuccBB->removePredecessor(II->getParent());
2734 BranchInst::Create(MergedInvoke->getParent(), II->getParent());
2735 II->replaceAllUsesWith(MergedInvoke);
2736 II->eraseFromParent();
2737 ++NumInvokesMerged;
2738 }
2739 MergedInvoke->setDebugLoc(MergedDebugLoc);
2740 ++NumInvokeSetsFormed;
2741
2742 if (DTU)
2743 DTU->applyUpdates(Updates);
2744}
2745
2746/// If this block is a `landingpad` exception handling block, categorize all
2747/// the predecessor `invoke`s into sets, with all `invoke`s in each set
2748/// being "mergeable" together, and then merge invokes in each set together.
2749///
2750/// This is a weird mix of hoisting and sinking. Visually, it goes from:
2751/// [...] [...]
2752/// | |
2753/// [invoke0] [invoke1]
2754/// / \ / \
2755/// [cont0] [landingpad] [cont1]
2756/// to:
2757/// [...] [...]
2758/// \ /
2759/// [invoke]
2760/// / \
2761/// [cont] [landingpad]
2762///
2763/// But of course we can only do that if the invokes share the `landingpad`,
2764/// edges invoke0->cont0 and invoke1->cont1 are "compatible",
2765/// and the invoked functions are "compatible".
2768 return false;
2769
2770 bool Changed = false;
2771
2772 // FIXME: generalize to all exception handling blocks?
2773 if (!BB->isLandingPad())
2774 return Changed;
2775
2776 CompatibleSets Grouper;
2777
2778 // Record all the predecessors of this `landingpad`. As per verifier,
2779 // the only allowed predecessor is the unwind edge of an `invoke`.
2780 // We want to group "compatible" `invokes` into the same set to be merged.
2781 for (BasicBlock *PredBB : predecessors(BB))
2782 Grouper.insert(cast<InvokeInst>(PredBB->getTerminator()));
2783
2784 // And now, merge `invoke`s that were grouped togeter.
2785 for (ArrayRef<InvokeInst *> Invokes : Grouper.Sets) {
2786 if (Invokes.size() < 2)
2787 continue;
2788 Changed = true;
2789 mergeCompatibleInvokesImpl(Invokes, DTU);
2790 }
2791
2792 return Changed;
2793}
2794
2795namespace {
2796/// Track ephemeral values, which should be ignored for cost-modelling
2797/// purposes. Requires walking instructions in reverse order.
2798class EphemeralValueTracker {
2800
2801 bool isEphemeral(const Instruction *I) {
2802 if (isa<AssumeInst>(I))
2803 return true;
2804 return !I->mayHaveSideEffects() && !I->isTerminator() &&
2805 all_of(I->users(), [&](const User *U) {
2806 return EphValues.count(cast<Instruction>(U));
2807 });
2808 }
2809
2810public:
2811 bool track(const Instruction *I) {
2812 if (isEphemeral(I)) {
2813 EphValues.insert(I);
2814 return true;
2815 }
2816 return false;
2817 }
2818
2819 bool contains(const Instruction *I) const { return EphValues.contains(I); }
2820};
2821} // namespace
2822
2823/// Determine if we can hoist sink a sole store instruction out of a
2824/// conditional block.
2825///
2826/// We are looking for code like the following:
2827/// BrBB:
2828/// store i32 %add, i32* %arrayidx2
2829/// ... // No other stores or function calls (we could be calling a memory
2830/// ... // function).
2831/// %cmp = icmp ult %x, %y
2832/// br i1 %cmp, label %EndBB, label %ThenBB
2833/// ThenBB:
2834/// store i32 %add5, i32* %arrayidx2
2835/// br label EndBB
2836/// EndBB:
2837/// ...
2838/// We are going to transform this into:
2839/// BrBB:
2840/// store i32 %add, i32* %arrayidx2
2841/// ... //
2842/// %cmp = icmp ult %x, %y
2843/// %add.add5 = select i1 %cmp, i32 %add, %add5
2844/// store i32 %add.add5, i32* %arrayidx2
2845/// ...
2846///
2847/// \return The pointer to the value of the previous store if the store can be
2848/// hoisted into the predecessor block. 0 otherwise.
2850 BasicBlock *StoreBB, BasicBlock *EndBB) {
2851 StoreInst *StoreToHoist = dyn_cast<StoreInst>(I);
2852 if (!StoreToHoist)
2853 return nullptr;
2854
2855 // Volatile or atomic.
2856 if (!StoreToHoist->isSimple())
2857 return nullptr;
2858
2859 Value *StorePtr = StoreToHoist->getPointerOperand();
2860 Type *StoreTy = StoreToHoist->getValueOperand()->getType();
2861
2862 // Look for a store to the same pointer in BrBB.
2863 unsigned MaxNumInstToLookAt = 9;
2864 // Skip pseudo probe intrinsic calls which are not really killing any memory
2865 // accesses.
2866 for (Instruction &CurI : reverse(BrBB->instructionsWithoutDebug(true))) {
2867 if (!MaxNumInstToLookAt)
2868 break;
2869 --MaxNumInstToLookAt;
2870
2871 // Could be calling an instruction that affects memory like free().
2872 if (CurI.mayWriteToMemory() && !isa<StoreInst>(CurI))
2873 return nullptr;
2874
2875 if (auto *SI = dyn_cast<StoreInst>(&CurI)) {
2876 // Found the previous store to same location and type. Make sure it is
2877 // simple, to avoid introducing a spurious non-atomic write after an
2878 // atomic write.
2879 if (SI->getPointerOperand() == StorePtr &&
2880 SI->getValueOperand()->getType() == StoreTy && SI->isSimple() &&
2881 SI->getAlign() >= StoreToHoist->getAlign())
2882 // Found the previous store, return its value operand.
2883 return SI->getValueOperand();
2884 return nullptr; // Unknown store.
2885 }
2886
2887 if (auto *LI = dyn_cast<LoadInst>(&CurI)) {
2888 if (LI->getPointerOperand() == StorePtr && LI->getType() == StoreTy &&
2889 LI->isSimple() && LI->getAlign() >= StoreToHoist->getAlign()) {
2890 // Local objects (created by an `alloca` instruction) are always
2891 // writable, so once we are past a read from a location it is valid to
2892 // also write to that same location.
2893 // If the address of the local object never escapes the function, that
2894 // means it's never concurrently read or written, hence moving the store
2895 // from under the condition will not introduce a data race.
2896 auto *AI = dyn_cast<AllocaInst>(getUnderlyingObject(StorePtr));
2897 if (AI && !PointerMayBeCaptured(AI, false, true))
2898 // Found a previous load, return it.
2899 return LI;
2900 }
2901 // The load didn't work out, but we may still find a store.
2902 }
2903 }
2904
2905 return nullptr;
2906}
2907
2908/// Estimate the cost of the insertion(s) and check that the PHI nodes can be
2909/// converted to selects.
2911 BasicBlock *EndBB,
2912 unsigned &SpeculatedInstructions,
2914 const TargetTransformInfo &TTI) {
2916 BB->getParent()->hasMinSize()
2919
2920 bool HaveRewritablePHIs = false;
2921 for (PHINode &PN : EndBB->phis()) {
2922 Value *OrigV = PN.getIncomingValueForBlock(BB);
2923 Value *ThenV = PN.getIncomingValueForBlock(ThenBB);
2924
2925 // FIXME: Try to remove some of the duplication with
2926 // hoistCommonCodeFromSuccessors. Skip PHIs which are trivial.
2927 if (ThenV == OrigV)
2928 continue;
2929
2930 Cost += TTI.getCmpSelInstrCost(Instruction::Select, PN.getType(), nullptr,
2932
2933 // Don't convert to selects if we could remove undefined behavior instead.
2934 if (passingValueIsAlwaysUndefined(OrigV, &PN) ||
2936 return false;
2937
2938 HaveRewritablePHIs = true;
2939 ConstantExpr *OrigCE = dyn_cast<ConstantExpr>(OrigV);
2940 ConstantExpr *ThenCE = dyn_cast<ConstantExpr>(ThenV);
2941 if (!OrigCE && !ThenCE)
2942 continue; // Known cheap (FIXME: Maybe not true for aggregates).
2943
2944 InstructionCost OrigCost = OrigCE ? computeSpeculationCost(OrigCE, TTI) : 0;
2945 InstructionCost ThenCost = ThenCE ? computeSpeculationCost(ThenCE, TTI) : 0;
2946 InstructionCost MaxCost =
2948 if (OrigCost + ThenCost > MaxCost)
2949 return false;
2950
2951 // Account for the cost of an unfolded ConstantExpr which could end up
2952 // getting expanded into Instructions.
2953 // FIXME: This doesn't account for how many operations are combined in the
2954 // constant expression.
2955 ++SpeculatedInstructions;
2956 if (SpeculatedInstructions > 1)
2957 return false;
2958 }
2959
2960 return HaveRewritablePHIs;
2961}
2962
2963static bool isProfitableToSpeculate(const BranchInst *BI, bool Invert,
2964 const TargetTransformInfo &TTI) {
2965 // If the branch is non-unpredictable, and is predicted to *not* branch to
2966 // the `then` block, then avoid speculating it.
2967 if (BI->getMetadata(LLVMContext::MD_unpredictable))
2968 return true;
2969
2970 uint64_t TWeight, FWeight;
2971 if (!extractBranchWeights(*BI, TWeight, FWeight) || (TWeight + FWeight) == 0)
2972 return true;
2973
2974 uint64_t EndWeight = Invert ? TWeight : FWeight;
2975 BranchProbability BIEndProb =
2976 BranchProbability::getBranchProbability(EndWeight, TWeight + FWeight);
2978 return BIEndProb < Likely;
2979}
2980
2981/// Speculate a conditional basic block flattening the CFG.
2982///
2983/// Note that this is a very risky transform currently. Speculating
2984/// instructions like this is most often not desirable. Instead, there is an MI
2985/// pass which can do it with full awareness of the resource constraints.
2986/// However, some cases are "obvious" and we should do directly. An example of
2987/// this is speculating a single, reasonably cheap instruction.
2988///
2989/// There is only one distinct advantage to flattening the CFG at the IR level:
2990/// it makes very common but simplistic optimizations such as are common in
2991/// instcombine and the DAG combiner more powerful by removing CFG edges and
2992/// modeling their effects with easier to reason about SSA value graphs.
2993///
2994///
2995/// An illustration of this transform is turning this IR:
2996/// \code
2997/// BB:
2998/// %cmp = icmp ult %x, %y
2999/// br i1 %cmp, label %EndBB, label %ThenBB
3000/// ThenBB:
3001/// %sub = sub %x, %y
3002/// br label BB2
3003/// EndBB:
3004/// %phi = phi [ %sub, %ThenBB ], [ 0, %EndBB ]
3005/// ...
3006/// \endcode
3007///
3008/// Into this IR:
3009/// \code
3010/// BB:
3011/// %cmp = icmp ult %x, %y
3012/// %sub = sub %x, %y
3013/// %cond = select i1 %cmp, 0, %sub
3014/// ...
3015/// \endcode
3016///
3017/// \returns true if the conditional block is removed.
3018bool SimplifyCFGOpt::speculativelyExecuteBB(BranchInst *BI,
3019 BasicBlock *ThenBB) {
3020 if (!Options.SpeculateBlocks)
3021 return false;
3022
3023 // Be conservative for now. FP select instruction can often be expensive.
3024 Value *BrCond = BI->getCondition();
3025 if (isa<FCmpInst>(BrCond))
3026 return false;
3027
3028 BasicBlock *BB = BI->getParent();
3029 BasicBlock *EndBB = ThenBB->getTerminator()->getSuccessor(0);
3030 InstructionCost Budget =
3032
3033 // If ThenBB is actually on the false edge of the conditional branch, remember
3034 // to swap the select operands later.
3035 bool Invert = false;
3036 if (ThenBB != BI->getSuccessor(0)) {
3037 assert(ThenBB == BI->getSuccessor(1) && "No edge from 'if' block?");
3038 Invert = true;
3039 }
3040 assert(EndBB == BI->getSuccessor(!Invert) && "No edge from to end block");
3041
3042 if (!isProfitableToSpeculate(BI, Invert, TTI))
3043 return false;
3044
3045 // Keep a count of how many times instructions are used within ThenBB when
3046 // they are candidates for sinking into ThenBB. Specifically:
3047 // - They are defined in BB, and
3048 // - They have no side effects, and
3049 // - All of their uses are in ThenBB.
3050 SmallDenseMap<Instruction *, unsigned, 4> SinkCandidateUseCounts;
3051
3052 SmallVector<Instruction *, 4> SpeculatedDbgIntrinsics;
3053
3054 unsigned SpeculatedInstructions = 0;
3055 Value *SpeculatedStoreValue = nullptr;
3056 StoreInst *SpeculatedStore = nullptr;
3057 EphemeralValueTracker EphTracker;
3058 for (Instruction &I : reverse(drop_end(*ThenBB))) {
3059 // Skip debug info.
3060 if (isa<DbgInfoIntrinsic>(I)) {
3061 SpeculatedDbgIntrinsics.push_back(&I);
3062 continue;
3063 }
3064
3065 // Skip pseudo probes. The consequence is we lose track of the branch
3066 // probability for ThenBB, which is fine since the optimization here takes
3067 // place regardless of the branch probability.
3068 if (isa<PseudoProbeInst>(I)) {
3069 // The probe should be deleted so that it will not be over-counted when
3070 // the samples collected on the non-conditional path are counted towards
3071 // the conditional path. We leave it for the counts inference algorithm to
3072 // figure out a proper count for an unknown probe.
3073 SpeculatedDbgIntrinsics.push_back(&I);
3074 continue;
3075 }
3076
3077 // Ignore ephemeral values, they will be dropped by the transform.
3078 if (EphTracker.track(&I))
3079 continue;
3080
3081 // Only speculatively execute a single instruction (not counting the
3082 // terminator) for now.
3083 ++SpeculatedInstructions;
3084 if (SpeculatedInstructions > 1)
3085 return false;
3086
3087 // Don't hoist the instruction if it's unsafe or expensive.
3089 !(HoistCondStores && (SpeculatedStoreValue = isSafeToSpeculateStore(
3090 &I, BB, ThenBB, EndBB))))
3091 return false;
3092 if (!SpeculatedStoreValue &&
3095 return false;
3096
3097 // Store the store speculation candidate.
3098 if (SpeculatedStoreValue)
3099 SpeculatedStore = cast<StoreInst>(&I);
3100
3101 // Do not hoist the instruction if any of its operands are defined but not
3102 // used in BB. The transformation will prevent the operand from
3103 // being sunk into the use block.
3104 for (Use &Op : I.operands()) {
3105 Instruction *OpI = dyn_cast<Instruction>(Op);
3106 if (!OpI || OpI->getParent() != BB || OpI->mayHaveSideEffects())
3107 continue; // Not a candidate for sinking.
3108
3109 ++SinkCandidateUseCounts[OpI];
3110 }
3111 }
3112
3113 // Consider any sink candidates which are only used in ThenBB as costs for
3114 // speculation. Note, while we iterate over a DenseMap here, we are summing
3115 // and so iteration order isn't significant.
3116 for (const auto &[Inst, Count] : SinkCandidateUseCounts)
3117 if (Inst->hasNUses(Count)) {
3118 ++SpeculatedInstructions;
3119 if (SpeculatedInstructions > 1)
3120 return false;
3121 }
3122
3123 // Check that we can insert the selects and that it's not too expensive to do
3124 // so.
3125 bool Convert = SpeculatedStore != nullptr;
3127 Convert |= validateAndCostRequiredSelects(BB, ThenBB, EndBB,
3128 SpeculatedInstructions,
3129 Cost, TTI);
3130 if (!Convert || Cost > Budget)
3131 return false;
3132
3133 // If we get here, we can hoist the instruction and if-convert.
3134 LLVM_DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *ThenBB << "\n";);
3135
3136 // Insert a select of the value of the speculated store.
3137 if (SpeculatedStoreValue) {
3138 IRBuilder<NoFolder> Builder(BI);
3139 Value *OrigV = SpeculatedStore->getValueOperand();
3140 Value *TrueV = SpeculatedStore->getValueOperand();
3141 Value *FalseV = SpeculatedStoreValue;
3142 if (Invert)
3143 std::swap(TrueV, FalseV);
3144 Value *S = Builder.CreateSelect(
3145 BrCond, TrueV, FalseV, "spec.store.select", BI);
3146 SpeculatedStore->setOperand(0, S);
3147 SpeculatedStore->applyMergedLocation(BI->getDebugLoc(),
3148 SpeculatedStore->getDebugLoc());
3149 // The value stored is still conditional, but the store itself is now
3150 // unconditonally executed, so we must be sure that any linked dbg.assign
3151 // intrinsics are tracking the new stored value (the result of the
3152 // select). If we don't, and the store were to be removed by another pass
3153 // (e.g. DSE), then we'd eventually end up emitting a location describing
3154 // the conditional value, unconditionally.
3155 //
3156 // === Before this transformation ===
3157 // pred:
3158 // store %one, %x.dest, !DIAssignID !1
3159 // dbg.assign %one, "x", ..., !1, ...
3160 // br %cond if.then
3161 //
3162 // if.then:
3163 // store %two, %x.dest, !DIAssignID !2
3164 // dbg.assign %two, "x", ..., !2, ...
3165 //
3166 // === After this transformation ===
3167 // pred:
3168 // store %one, %x.dest, !DIAssignID !1
3169 // dbg.assign %one, "x", ..., !1
3170 /// ...
3171 // %merge = select %cond, %two, %one
3172 // store %merge, %x.dest, !DIAssignID !2
3173 // dbg.assign %merge, "x", ..., !2
3174 auto replaceVariable = [OrigV, S](auto *DbgAssign) {
3175 if (llvm::is_contained(DbgAssign->location_ops(), OrigV))
3176 DbgAssign->replaceVariableLocationOp(OrigV, S);
3177 };
3178 for_each(at::getAssignmentMarkers(SpeculatedStore), replaceVariable);
3179 for_each(at::getDVRAssignmentMarkers(SpeculatedStore), replaceVariable);
3180 }
3181
3182 // Metadata can be dependent on the condition we are hoisting above.
3183 // Strip all UB-implying metadata on the instruction. Drop the debug loc
3184 // to avoid making it appear as if the condition is a constant, which would
3185 // be misleading while debugging.
3186 // Similarly strip attributes that maybe dependent on condition we are
3187 // hoisting above.
3188 for (auto &I : make_early_inc_range(*ThenBB)) {
3189 if (!SpeculatedStoreValue || &I != SpeculatedStore) {
3190 // Don't update the DILocation of dbg.assign intrinsics.
3191 if (!isa<DbgAssignIntrinsic>(&I))
3192 I.setDebugLoc(DebugLoc());
3193 }
3194 I.dropUBImplyingAttrsAndMetadata();
3195
3196 // Drop ephemeral values.
3197 if (EphTracker.contains(&I)) {
3198 I.replaceAllUsesWith(PoisonValue::get(I.getType()));
3199 I.eraseFromParent();
3200 }
3201 }
3202
3203 // Hoist the instructions.
3204 // In "RemoveDIs" non-instr debug-info mode, drop DbgVariableRecords attached
3205 // to these instructions, in the same way that dbg.value intrinsics are
3206 // dropped at the end of this block.
3207 for (auto &It : make_range(ThenBB->begin(), ThenBB->end()))
3208 for (DbgRecord &DR : make_early_inc_range(It.getDbgRecordRange()))
3209 // Drop all records except assign-kind DbgVariableRecords (dbg.assign
3210 // equivalent).
3211 if (DbgVariableRecord *DVR = dyn_cast<DbgVariableRecord>(&DR);
3212 !DVR || !DVR->isDbgAssign())
3213 It.dropOneDbgRecord(&DR);
3214 BB->splice(BI->getIterator(), ThenBB, ThenBB->begin(),
3215 std::prev(ThenBB->end()));
3216
3217 // Insert selects and rewrite the PHI operands.
3218 IRBuilder<NoFolder> Builder(BI);
3219 for (PHINode &PN : EndBB->phis()) {
3220 unsigned OrigI = PN.getBasicBlockIndex(BB);
3221 unsigned ThenI = PN.getBasicBlockIndex(ThenBB);
3222 Value *OrigV = PN.getIncomingValue(OrigI);
3223 Value *ThenV = PN.getIncomingValue(ThenI);
3224
3225 // Skip PHIs which are trivial.
3226 if (OrigV == ThenV)
3227 continue;
3228
3229 // Create a select whose true value is the speculatively executed value and
3230 // false value is the pre-existing value. Swap them if the branch
3231 // destinations were inverted.
3232 Value *TrueV = ThenV, *FalseV = OrigV;
3233 if (Invert)
3234 std::swap(TrueV, FalseV);
3235 Value *V = Builder.CreateSelect(BrCond, TrueV, FalseV, "spec.select", BI);
3236 PN.setIncomingValue(OrigI, V);
3237 PN.setIncomingValue(ThenI, V);
3238 }
3239
3240 // Remove speculated dbg intrinsics.
3241 // FIXME: Is it possible to do this in a more elegant way? Moving/merging the
3242 // dbg value for the different flows and inserting it after the select.
3243 for (Instruction *I : SpeculatedDbgIntrinsics) {
3244 // We still want to know that an assignment took place so don't remove
3245 // dbg.assign intrinsics.
3246 if (!isa<DbgAssignIntrinsic>(I))
3247 I->eraseFromParent();
3248 }
3249
3250 ++NumSpeculations;
3251 return true;
3252}
3253
3254/// Return true if we can thread a branch across this block.
3256 int Size = 0;
3257 EphemeralValueTracker EphTracker;
3258
3259 // Walk the loop in reverse so that we can identify ephemeral values properly
3260 // (values only feeding assumes).
3261 for (Instruction &I : reverse(BB->instructionsWithoutDebug(false))) {
3262 // Can't fold blocks that contain noduplicate or convergent calls.
3263 if (CallInst *CI = dyn_cast<CallInst>(&I))
3264 if (CI->cannotDuplicate() || CI->isConvergent())
3265 return false;
3266
3267 // Ignore ephemeral values which are deleted during codegen.
3268 // We will delete Phis while threading, so Phis should not be accounted in
3269 // block's size.
3270 if (!EphTracker.track(&I) && !isa<PHINode>(I)) {
3271 if (Size++ > MaxSmallBlockSize)
3272 return false; // Don't clone large BB's.
3273 }
3274
3275 // We can only support instructions that do not define values that are
3276 // live outside of the current basic block.
3277 for (User *U : I.users()) {
3278 Instruction *UI = cast<Instruction>(U);
3279 if (UI->getParent() != BB || isa<PHINode>(UI))
3280 return false;
3281 }
3282
3283 // Looks ok, continue checking.
3284 }
3285
3286 return true;
3287}
3288
3290 BasicBlock *To) {
3291 // Don't look past the block defining the value, we might get the value from
3292 // a previous loop iteration.
3293 auto *I = dyn_cast<Instruction>(V);
3294 if (I && I->getParent() == To)
3295 return nullptr;
3296
3297 // We know the value if the From block branches on it.
3298 auto *BI = dyn_cast<BranchInst>(From->getTerminator());
3299 if (BI && BI->isConditional() && BI->getCondition() == V &&
3300 BI->getSuccessor(0) != BI->getSuccessor(1))
3301 return BI->getSuccessor(0) == To ? ConstantInt::getTrue(BI->getContext())
3303
3304 return nullptr;
3305}
3306
3307/// If we have a conditional branch on something for which we know the constant
3308/// value in predecessors (e.g. a phi node in the current block), thread edges
3309/// from the predecessor to their ultimate destination.
3310static std::optional<bool>
3312 const DataLayout &DL,
3313 AssumptionCache *AC) {
3315 BasicBlock *BB = BI->getParent();
3316 Value *Cond = BI->getCondition();
3317 PHINode *PN = dyn_cast<PHINode>(Cond);
3318 if (PN && PN->getParent() == BB) {
3319 // Degenerate case of a single entry PHI.
3320 if (PN->getNumIncomingValues() == 1) {
3322 return true;
3323 }
3324
3325 for (Use &U : PN->incoming_values())
3326 if (auto *CB = dyn_cast<ConstantInt>(U))
3327 KnownValues[CB].insert(PN->getIncomingBlock(U));
3328 } else {
3329 for (BasicBlock *Pred : predecessors(BB)) {
3330 if (ConstantInt *CB = getKnownValueOnEdge(Cond, Pred, BB))
3331 KnownValues[CB].insert(Pred);
3332 }
3333 }
3334
3335 if (KnownValues.empty())
3336 return false;
3337
3338 // Now we know that this block has multiple preds and two succs.
3339 // Check that the block is small enough and values defined in the block are
3340 // not used outside of it.
3342 return false;
3343
3344 for (const auto &Pair : KnownValues) {
3345 // Okay, we now know that all edges from PredBB should be revectored to
3346 // branch to RealDest.
3347 ConstantInt *CB = Pair.first;
3348 ArrayRef<BasicBlock *> PredBBs = Pair.second.getArrayRef();
3349 BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
3350
3351 if (RealDest == BB)
3352 continue; // Skip self loops.
3353
3354 // Skip if the predecessor's terminator is an indirect branch.
3355 if (any_of(PredBBs, [](BasicBlock *PredBB) {
3356 return isa<IndirectBrInst>(PredBB->getTerminator());
3357 }))
3358 continue;
3359
3360 LLVM_DEBUG({
3361 dbgs() << "Condition " << *Cond << " in " << BB->getName()
3362 << " has value " << *Pair.first << " in predecessors:\n";
3363 for (const BasicBlock *PredBB : Pair.second)
3364 dbgs() << " " << PredBB->getName() << "\n";
3365 dbgs() << "Threading to destination " << RealDest->getName() << ".\n";
3366 });
3367
3368 // Split the predecessors we are threading into a new edge block. We'll
3369 // clone the instructions into this block, and then redirect it to RealDest.
3370 BasicBlock *EdgeBB = SplitBlockPredecessors(BB, PredBBs, ".critedge", DTU);
3371
3372 // TODO: These just exist to reduce test diff, we can drop them if we like.
3373 EdgeBB->setName(RealDest->getName() + ".critedge");
3374 EdgeBB->moveBefore(RealDest);
3375
3376 // Update PHI nodes.
3377 addPredecessorToBlock(RealDest, EdgeBB, BB);
3378
3379 // BB may have instructions that are being threaded over. Clone these
3380 // instructions into EdgeBB. We know that there will be no uses of the
3381 // cloned instructions outside of EdgeBB.
3382 BasicBlock::iterator InsertPt = EdgeBB->getFirstInsertionPt();
3383 DenseMap<Value *, Value *> TranslateMap; // Track translated values.
3384 TranslateMap[Cond] = CB;
3385
3386 // RemoveDIs: track instructions that we optimise away while folding, so
3387 // that we can copy DbgVariableRecords from them later.
3388 BasicBlock::iterator SrcDbgCursor = BB->begin();
3389 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
3390 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
3391 TranslateMap[PN] = PN->getIncomingValueForBlock(EdgeBB);
3392 continue;
3393 }
3394 // Clone the instruction.
3395 Instruction *N = BBI->clone();
3396 // Insert the new instruction into its new home.
3397 N->insertInto(EdgeBB, InsertPt);
3398
3399 if (BBI->hasName())
3400 N->setName(BBI->getName() + ".c");
3401
3402 // Update operands due to translation.
3403 for (Use &Op : N->operands()) {
3404 DenseMap<Value *, Value *>::iterator PI = TranslateMap.find(Op);
3405 if (PI != TranslateMap.end())
3406 Op = PI->second;
3407 }
3408
3409 // Check for trivial simplification.
3410 if (Value *V = simplifyInstruction(N, {DL, nullptr, nullptr, AC})) {
3411 if (!BBI->use_empty())
3412 TranslateMap[&*BBI] = V;
3413 if (!N->mayHaveSideEffects()) {
3414 N->eraseFromParent(); // Instruction folded away, don't need actual
3415 // inst
3416 N = nullptr;
3417 }
3418 } else {
3419 if (!BBI->use_empty())
3420 TranslateMap[&*BBI] = N;
3421 }
3422 if (N) {
3423 // Copy all debug-info attached to instructions from the last we
3424 // successfully clone, up to this instruction (they might have been
3425 // folded away).
3426 for (; SrcDbgCursor != BBI; ++SrcDbgCursor)
3427 N->cloneDebugInfoFrom(&*SrcDbgCursor);
3428 SrcDbgCursor = std::next(BBI);
3429 // Clone debug-info on this instruction too.
3430 N->cloneDebugInfoFrom(&*BBI);
3431
3432 // Register the new instruction with the assumption cache if necessary.
3433 if (auto *Assume = dyn_cast<AssumeInst>(N))
3434 if (AC)
3435 AC->registerAssumption(Assume);
3436 }
3437 }
3438
3439 for (; &*SrcDbgCursor != BI; ++SrcDbgCursor)
3440 InsertPt->cloneDebugInfoFrom(&*SrcDbgCursor);
3441 InsertPt->cloneDebugInfoFrom(BI);
3442
3443 BB->removePredecessor(EdgeBB);
3444 BranchInst *EdgeBI = cast<BranchInst>(EdgeBB->getTerminator());
3445 EdgeBI->setSuccessor(0, RealDest);
3446 EdgeBI->setDebugLoc(BI->getDebugLoc());
3447
3448 if (DTU) {
3450 Updates.push_back({DominatorTree::Delete, EdgeBB, BB});
3451 Updates.push_back({DominatorTree::Insert, EdgeBB, RealDest});
3452 DTU->applyUpdates(Updates);
3453 }
3454
3455 // For simplicity, we created a separate basic block for the edge. Merge
3456 // it back into the predecessor if possible. This not only avoids
3457 // unnecessary SimplifyCFG iterations, but also makes sure that we don't
3458 // bypass the check for trivial cycles above.
3459 MergeBlockIntoPredecessor(EdgeBB, DTU);
3460
3461 // Signal repeat, simplifying any other constants.
3462 return std::nullopt;
3463 }
3464
3465 return false;
3466}
3467
3469 DomTreeUpdater *DTU,
3470 const DataLayout &DL,
3471 AssumptionCache *AC) {
3472 std::optional<bool> Result;
3473 bool EverChanged = false;
3474 do {
3475 // Note that None means "we changed things, but recurse further."
3476 Result = foldCondBranchOnValueKnownInPredecessorImpl(BI, DTU, DL, AC);
3477 EverChanged |= Result == std::nullopt || *Result;
3478 } while (Result == std::nullopt);
3479 return EverChanged;
3480}
3481
3482/// Given a BB that starts with the specified two-entry PHI node,
3483/// see if we can eliminate it.
3485 DomTreeUpdater *DTU, const DataLayout &DL,
3486 bool SpeculateUnpredictables) {
3487 // Ok, this is a two entry PHI node. Check to see if this is a simple "if
3488 // statement", which has a very simple dominance structure. Basically, we
3489 // are trying to find the condition that is being branched on, which
3490 // subsequently causes this merge to happen. We really want control
3491 // dependence information for this check, but simplifycfg can't keep it up
3492 // to date, and this catches most of the cases we care about anyway.
3493 BasicBlock *BB = PN->getParent();
3494
3495 BasicBlock *IfTrue, *IfFalse;
3496 BranchInst *DomBI = GetIfCondition(BB, IfTrue, IfFalse);
3497 if (!DomBI)
3498 return false;
3499 Value *IfCond = DomBI->getCondition();
3500 // Don't bother if the branch will be constant folded trivially.
3501 if (isa<ConstantInt>(IfCond))
3502 return false;
3503
3504 BasicBlock *DomBlock = DomBI->getParent();
3507 PN->blocks(), std::back_inserter(IfBlocks), [](BasicBlock *IfBlock) {
3508 return cast<BranchInst>(IfBlock->getTerminator())->isUnconditional();
3509 });
3510 assert((IfBlocks.size() == 1 || IfBlocks.size() == 2) &&
3511 "Will have either one or two blocks to speculate.");
3512
3513 // If the branch is non-unpredictable, see if we either predictably jump to
3514 // the merge bb (if we have only a single 'then' block), or if we predictably
3515 // jump to one specific 'then' block (if we have two of them).
3516 // It isn't beneficial to speculatively execute the code
3517 // from the block that we know is predictably not entered.
3518 bool IsUnpredictable = DomBI->getMetadata(LLVMContext::MD_unpredictable);
3519 if (!IsUnpredictable) {
3520 uint64_t TWeight, FWeight;
3521 if (extractBranchWeights(*DomBI, TWeight, FWeight) &&
3522 (TWeight + FWeight) != 0) {
3523 BranchProbability BITrueProb =
3524 BranchProbability::getBranchProbability(TWeight, TWeight + FWeight);
3526 BranchProbability BIFalseProb = BITrueProb.getCompl();
3527 if (IfBlocks.size() == 1) {
3528 BranchProbability BIBBProb =
3529 DomBI->getSuccessor(0) == BB ? BITrueProb : BIFalseProb;
3530 if (BIBBProb >= Likely)
3531 return false;
3532 } else {
3533 if (BITrueProb >= Likely || BIFalseProb >= Likely)
3534 return false;
3535 }
3536 }
3537 }
3538
3539 // Don't try to fold an unreachable block. For example, the phi node itself
3540 // can't be the candidate if-condition for a select that we want to form.
3541 if (auto *IfCondPhiInst = dyn_cast<PHINode>(IfCond))
3542 if (IfCondPhiInst->getParent() == BB)
3543 return false;
3544
3545 // Okay, we found that we can merge this two-entry phi node into a select.
3546 // Doing so would require us to fold *all* two entry phi nodes in this block.
3547 // At some point this becomes non-profitable (particularly if the target
3548 // doesn't support cmov's). Only do this transformation if there are two or
3549 // fewer PHI nodes in this block.
3550 unsigned NumPhis = 0;
3551 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
3552 if (NumPhis > 2)
3553 return false;
3554
3555 // Loop over the PHI's seeing if we can promote them all to select
3556 // instructions. While we are at it, keep track of the instructions
3557 // that need to be moved to the dominating block.
3558 SmallPtrSet<Instruction *, 4> AggressiveInsts;
3560 InstructionCost Budget =
3562 if (SpeculateUnpredictables && IsUnpredictable)
3563 Budget += TTI.getBranchMispredictPenalty();
3564
3565 bool Changed = false;
3566 for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) {
3567 PHINode *PN = cast<PHINode>(II++);
3568 if (Value *V = simplifyInstruction(PN, {DL, PN})) {
3569 PN->replaceAllUsesWith(V);
3570 PN->eraseFromParent();
3571 Changed = true;
3572 continue;
3573 }
3574
3575 if (!dominatesMergePoint(PN->getIncomingValue(0), BB, AggressiveInsts,
3576 Cost, Budget, TTI) ||
3577 !dominatesMergePoint(PN->getIncomingValue(1), BB, AggressiveInsts,
3578 Cost, Budget, TTI))
3579 return Changed;
3580 }
3581
3582 // If we folded the first phi, PN dangles at this point. Refresh it. If
3583 // we ran out of PHIs then we simplified them all.
3584 PN = dyn_cast<PHINode>(BB->begin());
3585 if (!PN)
3586 return true;
3587
3588 // Return true if at least one of these is a 'not', and another is either
3589 // a 'not' too, or a constant.
3590 auto CanHoistNotFromBothValues = [](Value *V0, Value *V1) {
3591 if (!match(V0, m_Not(m_Value())))
3592 std::swap(V0, V1);
3593 auto Invertible = m_CombineOr(m_Not(m_Value()), m_AnyIntegralConstant());
3594 return match(V0, m_Not(m_Value())) && match(V1, Invertible);
3595 };
3596
3597 // Don't fold i1 branches on PHIs which contain binary operators or
3598 // (possibly inverted) select form of or/ands, unless one of
3599 // the incoming values is an 'not' and another one is freely invertible.
3600 // These can often be turned into switches and other things.
3601 auto IsBinOpOrAnd = [](Value *V) {
3602 return match(
3603 V, m_CombineOr(
3604 m_BinOp(),
3607 };
3608 if (PN->getType()->isIntegerTy(1) &&
3609 (IsBinOpOrAnd(PN->getIncomingValue(0)) ||
3610 IsBinOpOrAnd(PN->getIncomingValue(1)) || IsBinOpOrAnd(IfCond)) &&
3611 !CanHoistNotFromBothValues(PN->getIncomingValue(0),
3612 PN->getIncomingValue(1)))
3613 return Changed;
3614
3615 // If all PHI nodes are promotable, check to make sure that all instructions
3616 // in the predecessor blocks can be promoted as well. If not, we won't be able
3617 // to get rid of the control flow, so it's not worth promoting to select
3618 // instructions.
3619 for (BasicBlock *IfBlock : IfBlocks)
3620 for (BasicBlock::iterator I = IfBlock->begin(); !I->isTerminator(); ++I)
3621 if (!AggressiveInsts.count(&*I) && !I->isDebugOrPseudoInst()) {
3622 // This is not an aggressive instruction that we can promote.
3623 // Because of this, we won't be able to get rid of the control flow, so
3624 // the xform is not worth it.
3625 return Changed;
3626 }
3627
3628 // If either of the blocks has it's address taken, we can't do this fold.
3629 if (any_of(IfBlocks,
3630 [](BasicBlock *IfBlock) { return IfBlock->hasAddressTaken(); }))
3631 return Changed;
3632
3633 LLVM_DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond;
3634 if (IsUnpredictable) dbgs() << " (unpredictable)";
3635 dbgs() << " T: " << IfTrue->getName()
3636 << " F: " << IfFalse->getName() << "\n");
3637
3638 // If we can still promote the PHI nodes after this gauntlet of tests,
3639 // do all of the PHI's now.
3640
3641 // Move all 'aggressive' instructions, which are defined in the
3642 // conditional parts of the if's up to the dominating block.
3643 for (BasicBlock *IfBlock : IfBlocks)
3644 hoistAllInstructionsInto(DomBlock, DomBI, IfBlock);
3645
3646 IRBuilder<NoFolder> Builder(DomBI);
3647 // Propagate fast-math-flags from phi nodes to replacement selects.
3648 IRBuilder<>::FastMathFlagGuard FMFGuard(Builder);
3649 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
3650 if (isa<FPMathOperator>(PN))
3651 Builder.setFastMathFlags(PN->getFastMathFlags());
3652
3653 // Change the PHI node into a select instruction.
3654 Value *TrueVal = PN->getIncomingValueForBlock(IfTrue);
3655 Value *FalseVal = PN->getIncomingValueForBlock(IfFalse);
3656
3657 Value *Sel = Builder.CreateSelect(IfCond, TrueVal, FalseVal, "", DomBI);
3658 PN->replaceAllUsesWith(Sel);
3659 Sel->takeName(PN);
3660 PN->eraseFromParent();
3661 }
3662
3663 // At this point, all IfBlocks are empty, so our if statement
3664 // has been flattened. Change DomBlock to jump directly to our new block to
3665 // avoid other simplifycfg's kicking in on the diamond.
3666 Builder.CreateBr(BB);
3667
3669 if (DTU) {
3670 Updates.push_back({DominatorTree::Insert, DomBlock, BB});
3671 for (auto *Successor : successors(DomBlock))
3672 Updates.push_back({DominatorTree::Delete, DomBlock, Successor});
3673 }
3674
3675 DomBI->eraseFromParent();
3676 if (DTU)
3677 DTU->applyUpdates(Updates);
3678
3679 return true;
3680}
3681
3683 Instruction::BinaryOps Opc, Value *LHS,
3684 Value *RHS, const Twine &Name = "") {
3685 // Try to relax logical op to binary op.
3686 if (impliesPoison(RHS, LHS))
3687 return Builder.CreateBinOp(Opc, LHS, RHS, Name);
3688 if (Opc == Instruction::And)
3689 return Builder.CreateLogicalAnd(LHS, RHS, Name);
3690 if (Opc == Instruction::Or)
3691 return Builder.CreateLogicalOr(LHS, RHS, Name);
3692 llvm_unreachable("Invalid logical opcode");
3693}
3694
3695/// Return true if either PBI or BI has branch weight available, and store
3696/// the weights in {Pred|Succ}{True|False}Weight. If one of PBI and BI does
3697/// not have branch weight, use 1:1 as its weight.
3699 uint64_t &PredTrueWeight,
3700 uint64_t &PredFalseWeight,
3701 uint64_t &SuccTrueWeight,
3702 uint64_t &SuccFalseWeight) {
3703 bool PredHasWeights =
3704 extractBranchWeights(*PBI, PredTrueWeight, PredFalseWeight);
3705 bool SuccHasWeights =
3706 extractBranchWeights(*BI, SuccTrueWeight, SuccFalseWeight);
3707 if (PredHasWeights || SuccHasWeights) {
3708 if (!PredHasWeights)
3709 PredTrueWeight = PredFalseWeight = 1;
3710 if (!SuccHasWeights)
3711 SuccTrueWeight = SuccFalseWeight = 1;
3712 return true;
3713 } else {
3714 return false;
3715 }
3716}
3717
3718/// Determine if the two branches share a common destination and deduce a glue
3719/// that joins the branches' conditions to arrive at the common destination if
3720/// that would be profitable.
3721static std::optional<std::tuple<BasicBlock *, Instruction::BinaryOps, bool>>
3723 const TargetTransformInfo *TTI) {
3724 assert(BI && PBI && BI->isConditional() && PBI->isConditional() &&
3725 "Both blocks must end with a conditional branches.");
3727 "PredBB must be a predecessor of BB.");
3728
3729 // We have the potential to fold the conditions together, but if the
3730 // predecessor branch is predictable, we may not want to merge them.
3731 uint64_t PTWeight, PFWeight;
3732 BranchProbability PBITrueProb, Likely;
3733 if (TTI && !PBI->getMetadata(LLVMContext::MD_unpredictable) &&
3734 extractBranchWeights(*PBI, PTWeight, PFWeight) &&
3735 (PTWeight + PFWeight) != 0) {
3736 PBITrueProb =
3737 BranchProbability::getBranchProbability(PTWeight, PTWeight + PFWeight);
3739 }
3740
3741 if (PBI->getSuccessor(0) == BI->getSuccessor(0)) {
3742 // Speculate the 2nd condition unless the 1st is probably true.
3743 if (PBITrueProb.isUnknown() || PBITrueProb < Likely)
3744 return {{BI->getSuccessor(0), Instruction::Or, false}};
3745 } else if (PBI->getSuccessor(1) == BI->getSuccessor(1)) {
3746 // Speculate the 2nd condition unless the 1st is probably false.
3747 if (PBITrueProb.isUnknown() || PBITrueProb.getCompl() < Likely)
3748 return {{BI->getSuccessor(1), Instruction::And, false}};
3749 } else if (PBI->getSuccessor(0) == BI->getSuccessor(1)) {
3750 // Speculate the 2nd condition unless the 1st is probably true.
3751 if (PBITrueProb.isUnknown() || PBITrueProb < Likely)
3752 return {{BI->getSuccessor(1), Instruction::And, true}};
3753 } else if (PBI->getSuccessor(1) == BI->getSuccessor(0)) {
3754 // Speculate the 2nd condition unless the 1st is probably false.
3755 if (PBITrueProb.isUnknown() || PBITrueProb.getCompl() < Likely)
3756 return {{BI->getSuccessor(0), Instruction::Or, true}};
3757 }
3758 return std::nullopt;
3759}
3760
3762 DomTreeUpdater *DTU,
3763 MemorySSAUpdater *MSSAU,
3764 const TargetTransformInfo *TTI) {
3765 BasicBlock *BB = BI->getParent();
3766 BasicBlock *PredBlock = PBI->getParent();
3767
3768 // Determine if the two branches share a common destination.
3769 BasicBlock *CommonSucc;
3771 bool InvertPredCond;
3772 std::tie(CommonSucc, Opc, InvertPredCond) =
3774
3775 LLVM_DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
3776
3777 IRBuilder<> Builder(PBI);
3778 // The builder is used to create instructions to eliminate the branch in BB.
3779 // If BB's terminator has !annotation metadata, add it to the new
3780 // instructions.
3782 {LLVMContext::MD_annotation});
3783
3784 // If we need to invert the condition in the pred block to match, do so now.
3785 if (InvertPredCond) {
3786 InvertBranch(PBI, Builder);
3787 }
3788
3789 BasicBlock *UniqueSucc =
3790 PBI->getSuccessor(0) == BB ? BI->getSuccessor(0) : BI->getSuccessor(1);
3791
3792 // Before cloning instructions, notify the successor basic block that it
3793 // is about to have a new predecessor. This will update PHI nodes,
3794 // which will allow us to update live-out uses of bonus instructions.
3795 addPredecessorToBlock(UniqueSucc, PredBlock, BB, MSSAU);
3796
3797 // Try to update branch weights.
3798 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
3799 if (extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight,
3800 SuccTrueWeight, SuccFalseWeight)) {
3801 SmallVector<uint64_t, 8> NewWeights;
3802
3803 if (PBI->getSuccessor(0) == BB) {
3804 // PBI: br i1 %x, BB, FalseDest
3805 // BI: br i1 %y, UniqueSucc, FalseDest
3806 // TrueWeight is TrueWeight for PBI * TrueWeight for BI.
3807 NewWeights.push_back(PredTrueWeight * SuccTrueWeight);
3808 // FalseWeight is FalseWeight for PBI * TotalWeight for BI +
3809 // TrueWeight for PBI * FalseWeight for BI.
3810 // We assume that total weights of a BranchInst can fit into 32 bits.
3811 // Therefore, we will not have overflow using 64-bit arithmetic.
3812 NewWeights.push_back(PredFalseWeight *
3813 (SuccFalseWeight + SuccTrueWeight) +
3814 PredTrueWeight * SuccFalseWeight);
3815 } else {
3816 // PBI: br i1 %x, TrueDest, BB
3817 // BI: br i1 %y, TrueDest, UniqueSucc
3818 // TrueWeight is TrueWeight for PBI * TotalWeight for BI +
3819 // FalseWeight for PBI * TrueWeight for BI.
3820 NewWeights.push_back(PredTrueWeight * (SuccFalseWeight + SuccTrueWeight) +
3821 PredFalseWeight * SuccTrueWeight);
3822 // FalseWeight is FalseWeight for PBI * FalseWeight for BI.
3823 NewWeights.push_back(PredFalseWeight * SuccFalseWeight);
3824 }
3825
3826 // Halve the weights if any of them cannot fit in an uint32_t
3827 fitWeights(NewWeights);
3828
3829 SmallVector<uint32_t, 8> MDWeights(NewWeights.begin(), NewWeights.end());
3830 setBranchWeights(PBI, MDWeights[0], MDWeights[1], /*IsExpected=*/false);
3831
3832 // TODO: If BB is reachable from all paths through PredBlock, then we
3833 // could replace PBI's branch probabilities with BI's.
3834 } else
3835 PBI->setMetadata(LLVMContext::MD_prof, nullptr);
3836
3837 // Now, update the CFG.
3838 PBI->setSuccessor(PBI->getSuccessor(0) != BB, UniqueSucc);
3839
3840 if (DTU)
3841 DTU->applyUpdates({{DominatorTree::Insert, PredBlock, UniqueSucc},
3842 {DominatorTree::Delete, PredBlock, BB}});
3843
3844 // If BI was a loop latch, it may have had associated loop metadata.
3845 // We need to copy it to the new latch, that is, PBI.
3846 if (MDNode *LoopMD = BI->getMetadata(LLVMContext::MD_loop))
3847 PBI->setMetadata(LLVMContext::MD_loop, LoopMD);
3848
3849 ValueToValueMapTy VMap; // maps original values to cloned values
3851
3852 Module *M = BB->getModule();
3853
3854 if (PredBlock->IsNewDbgInfoFormat) {
3855 PredBlock->getTerminator()->cloneDebugInfoFrom(BB->getTerminator());
3856 for (DbgVariableRecord &DVR :
3858 RemapDbgRecord(M, &DVR, VMap,
3860 }
3861 }
3862
3863 // Now that the Cond was cloned into the predecessor basic block,
3864 // or/and the two conditions together.
3865 Value *BICond = VMap[BI->getCondition()];
3866 PBI->setCondition(
3867 createLogicalOp(Builder, Opc, PBI->getCondition(), BICond, "or.cond"));
3868
3869 ++NumFoldBranchToCommonDest;
3870 return true;
3871}
3872
3873/// Return if an instruction's type or any of its operands' types are a vector
3874/// type.
3875static bool isVectorOp(Instruction &I) {
3876 return I.getType()->isVectorTy() || any_of(I.operands(), [](Use &U) {
3877 return U->getType()->isVectorTy();
3878 });
3879}
3880
3881/// If this basic block is simple enough, and if a predecessor branches to us
3882/// and one of our successors, fold the block into the predecessor and use
3883/// logical operations to pick the right destination.
3885 MemorySSAUpdater *MSSAU,
3886 const TargetTransformInfo *TTI,
3887 unsigned BonusInstThreshold) {
3888 // If this block ends with an unconditional branch,
3889 // let speculativelyExecuteBB() deal with it.
3890 if (!BI->isConditional())
3891 return false;
3892
3893 BasicBlock *BB = BI->getParent();
3897
3898 Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
3899
3900 if (!Cond ||
3901 (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond) &&
3902 !isa<SelectInst>(Cond)) ||
3903 Cond->getParent() != BB || !Cond->hasOneUse())
3904 return false;
3905
3906 // Finally, don't infinitely unroll conditional loops.
3907 if (is_contained(successors(BB), BB))
3908 return false;
3909
3910 // With which predecessors will we want to deal with?
3912 for (BasicBlock *PredBlock : predecessors(BB)) {
3913 BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
3914
3915 // Check that we have two conditional branches. If there is a PHI node in
3916 // the common successor, verify that the same value flows in from both
3917 // blocks.
3918 if (!PBI || PBI->isUnconditional() || !safeToMergeTerminators(BI, PBI))
3919 continue;
3920
3921 // Determine if the two branches share a common destination.
3922 BasicBlock *CommonSucc;
3924 bool InvertPredCond;
3925 if (auto Recipe = shouldFoldCondBranchesToCommonDestination(BI, PBI, TTI))
3926 std::tie(CommonSucc, Opc, InvertPredCond) = *Recipe;
3927 else
3928 continue;
3929
3930 // Check the cost of inserting the necessary logic before performing the
3931 // transformation.
3932 if (TTI) {
3933 Type *Ty = BI->getCondition()->getType();
3935 if (InvertPredCond && (!PBI->getCondition()->hasOneUse() ||
3936 !isa<CmpInst>(PBI->getCondition())))
3937 Cost += TTI->getArithmeticInstrCost(Instruction::Xor, Ty, CostKind);
3938
3940 continue;
3941 }
3942
3943 // Ok, we do want to deal with this predecessor. Record it.
3944 Preds.emplace_back(PredBlock);
3945 }
3946
3947 // If there aren't any predecessors into which we can fold,
3948 // don't bother checking the cost.
3949 if (Preds.empty())
3950 return false;
3951
3952 // Only allow this transformation if computing the condition doesn't involve
3953 // too many instructions and these involved instructions can be executed
3954 // unconditionally. We denote all involved instructions except the condition
3955 // as "bonus instructions", and only allow this transformation when the
3956 // number of the bonus instructions we'll need to create when cloning into
3957 // each predecessor does not exceed a certain threshold.
3958 unsigned NumBonusInsts = 0;
3959 bool SawVectorOp = false;
3960 const unsigned PredCount = Preds.size();
3961 for (Instruction &I : *BB) {
3962 // Don't check the branch condition comparison itself.
3963 if (&I == Cond)
3964 continue;
3965 // Ignore dbg intrinsics, and the terminator.
3966 if (isa<DbgInfoIntrinsic>(I) || isa<BranchInst>(I))
3967 continue;
3968 // I must be safe to execute unconditionally.
3970 return false;
3971 SawVectorOp |= isVectorOp(I);
3972
3973 // Account for the cost of duplicating this instruction into each
3974 // predecessor. Ignore free instructions.
3975 if (!TTI || TTI->getInstructionCost(&I, CostKind) !=
3977 NumBonusInsts += PredCount;
3978
3979 // Early exits once we reach the limit.
3980 if (NumBonusInsts >
3981 BonusInstThreshold * BranchFoldToCommonDestVectorMultiplier)
3982 return false;
3983 }
3984
3985 auto IsBCSSAUse = [BB, &I](Use &U) {
3986 auto *UI = cast<Instruction>(U.getUser());
3987 if (auto *PN = dyn_cast<PHINode>(UI))
3988 return PN->getIncomingBlock(U) == BB;
3989 return UI->getParent() == BB && I.comesBefore(UI);
3990 };
3991
3992 // Does this instruction require rewriting of uses?
3993 if (!all_of(I.uses(), IsBCSSAUse))
3994 return false;
3995 }
3996 if (NumBonusInsts >
3997 BonusInstThreshold *
3998 (SawVectorOp ? BranchFoldToCommonDestVectorMultiplier : 1))
3999 return false;
4000
4001 // Ok, we have the budget. Perform the transformation.
4002 for (BasicBlock *PredBlock : Preds) {
4003 auto *PBI = cast<BranchInst>(PredBlock->getTerminator());
4004 return performBranchToCommonDestFolding(BI, PBI, DTU, MSSAU, TTI);
4005 }
4006 return false;
4007}
4008
4009// If there is only one store in BB1 and BB2, return it, otherwise return
4010// nullptr.
4012 StoreInst *S = nullptr;
4013 for (auto *BB : {BB1, BB2}) {
4014 if (!BB)
4015 continue;
4016 for (auto &I : *BB)
4017 if (auto *SI = dyn_cast<StoreInst>(&I)) {
4018 if (S)
4019 // Multiple stores seen.
4020 return nullptr;
4021 else
4022 S = SI;
4023 }
4024 }
4025 return S;
4026}
4027
4029 Value *AlternativeV = nullptr) {
4030 // PHI is going to be a PHI node that allows the value V that is defined in
4031 // BB to be referenced in BB's only successor.
4032 //
4033 // If AlternativeV is nullptr, the only value we care about in PHI is V. It
4034 // doesn't matter to us what the other operand is (it'll never get used). We
4035 // could just create a new PHI with an undef incoming value, but that could
4036 // increase register pressure if EarlyCSE/InstCombine can't fold it with some
4037 // other PHI. So here we directly look for some PHI in BB's successor with V
4038 // as an incoming operand. If we find one, we use it, else we create a new
4039 // one.
4040 //
4041 // If AlternativeV is not nullptr, we care about both incoming values in PHI.
4042 // PHI must be exactly: phi <ty> [ %BB, %V ], [ %OtherBB, %AlternativeV]
4043 // where OtherBB is the single other predecessor of BB's only successor.
4044 PHINode *PHI = nullptr;
4045 BasicBlock *Succ = BB->getSingleSuccessor();
4046
4047 for (auto I = Succ->begin(); isa<PHINode>(I); ++I)
4048 if (cast<PHINode>(I)->getIncomingValueForBlock(BB) == V) {
4049 PHI = cast<PHINode>(I);
4050 if (!AlternativeV)
4051 break;
4052
4053 assert(Succ->hasNPredecessors(2));
4054 auto PredI = pred_begin(Succ);
4055 BasicBlock *OtherPredBB = *PredI == BB ? *++PredI : *PredI;
4056 if (PHI->getIncomingValueForBlock(OtherPredBB) == AlternativeV)
4057 break;
4058 PHI = nullptr;
4059 }
4060 if (PHI)
4061 return PHI;
4062
4063 // If V is not an instruction defined in BB, just return it.
4064 if (!AlternativeV &&
4065 (!isa<Instruction>(V) || cast<Instruction>(V)->getParent() != BB))
4066 return V;
4067
4068 PHI = PHINode::Create(V->getType(), 2, "simplifycfg.merge");
4069 PHI->insertBefore(Succ->begin());
4070 PHI->addIncoming(V, BB);
4071 for (BasicBlock *PredBB : predecessors(Succ))
4072 if (PredBB != BB)
4073 PHI->addIncoming(
4074 AlternativeV ? AlternativeV : PoisonValue::get(V->getType()), PredBB);
4075 return PHI;
4076}
4077
4079 BasicBlock *PTB, BasicBlock *PFB, BasicBlock *QTB, BasicBlock *QFB,
4080 BasicBlock *PostBB, Value *Address, bool InvertPCond, bool InvertQCond,
4081 DomTreeUpdater *DTU, const DataLayout &DL, const TargetTransformInfo &TTI) {
4082 // For every pointer, there must be exactly two stores, one coming from
4083 // PTB or PFB, and the other from QTB or QFB. We don't support more than one
4084 // store (to any address) in PTB,PFB or QTB,QFB.
4085 // FIXME: We could relax this restriction with a bit more work and performance
4086 // testing.
4087 StoreInst *PStore = findUniqueStoreInBlocks(PTB, PFB);
4088 StoreInst *QStore = findUniqueStoreInBlocks(QTB, QFB);
4089 if (!PStore || !QStore)
4090 return false;
4091
4092 // Now check the stores are compatible.
4093 if (!QStore->isUnordered() || !PStore->isUnordered() ||
4094 PStore->getValueOperand()->getType() !=
4095 QStore->getValueOperand()->getType())
4096 return false;
4097
4098 // Check that sinking the store won't cause program behavior changes. Sinking
4099 // the store out of the Q blocks won't change any behavior as we're sinking
4100 // from a block to its unconditional successor. But we're moving a store from
4101 // the P blocks down through the middle block (QBI) and past both QFB and QTB.
4102 // So we need to check that there are no aliasing loads or stores in
4103 // QBI, QTB and QFB. We also need to check there are no conflicting memory
4104 // operations between PStore and the end of its parent block.
4105 //
4106 // The ideal way to do this is to query AliasAnalysis, but we don't
4107 // preserve AA currently so that is dangerous. Be super safe and just
4108 // check there are no other memory operations at all.
4109 for (auto &I : *QFB->getSinglePredecessor())
4110 if (I.mayReadOrWriteMemory())
4111 return false;
4112 for (auto &I : *QFB)
4113 if (&I != QStore && I.mayReadOrWriteMemory())
4114 return false;
4115 if (QTB)
4116 for (auto &I : *QTB)
4117 if (&I != QStore && I.mayReadOrWriteMemory())
4118 return false;
4119 for (auto I = BasicBlock::iterator(PStore), E = PStore->getParent()->end();
4120 I != E; ++I)
4121 if (&*I != PStore && I->mayReadOrWriteMemory())
4122 return false;
4123
4124 // If we're not in aggressive mode, we only optimize if we have some
4125 // confidence that by optimizing we'll allow P and/or Q to be if-converted.
4126 auto IsWorthwhile = [&](BasicBlock *BB, ArrayRef<StoreInst *> FreeStores) {
4127 if (!BB)
4128 return true;
4129 // Heuristic: if the block can be if-converted/phi-folded and the
4130 // instructions inside are all cheap (arithmetic/GEPs), it's worthwhile to
4131 // thread this store.
4133 InstructionCost Budget =
4135 for (auto &I : BB->instructionsWithoutDebug(false)) {
4136 // Consider terminator instruction to be free.
4137 if (I.isTerminator())
4138 continue;
4139 // If this is one the stores that we want to speculate out of this BB,
4140 // then don't count it's cost, consider it to be free.
4141 if (auto *S = dyn_cast<StoreInst>(&I))
4142 if (llvm::find(FreeStores, S))
4143 continue;
4144 // Else, we have a white-list of instructions that we are ak speculating.
4145 if (!isa<BinaryOperator>(I) && !isa<GetElementPtrInst>(I))
4146 return false; // Not in white-list - not worthwhile folding.
4147 // And finally, if this is a non-free instruction that we are okay
4148 // speculating, ensure that we consider the speculation budget.
4149 Cost +=
4151 if (Cost > Budget)
4152 return false; // Eagerly refuse to fold as soon as we're out of budget.
4153 }
4154 assert(Cost <= Budget &&
4155 "When we run out of budget we will eagerly return from within the "
4156 "per-instruction loop.");
4157 return true;
4158 };
4159
4160 const std::array<StoreInst *, 2> FreeStores = {PStore, QStore};
4162 (!IsWorthwhile(PTB, FreeStores) || !IsWorthwhile(PFB, FreeStores) ||
4163 !IsWorthwhile(QTB, FreeStores) || !IsWorthwhile(QFB, FreeStores)))
4164 return false;
4165
4166 // If PostBB has more than two predecessors, we need to split it so we can
4167 // sink the store.
4168 if (std::next(pred_begin(PostBB), 2) != pred_end(PostBB)) {
4169 // We know that QFB's only successor is PostBB. And QFB has a single
4170 // predecessor. If QTB exists, then its only successor is also PostBB.
4171 // If QTB does not exist, then QFB's only predecessor has a conditional
4172 // branch to QFB and PostBB.
4173 BasicBlock *TruePred = QTB ? QTB : QFB->getSinglePredecessor();
4174 BasicBlock *NewBB =
4175 SplitBlockPredecessors(PostBB, {QFB, TruePred}, "condstore.split", DTU);
4176 if (!NewBB)
4177 return false;
4178 PostBB = NewBB;
4179 }
4180
4181 // OK, we're going to sink the stores to PostBB. The store has to be
4182 // conditional though, so first create the predicate.
4183 Value *PCond = cast<BranchInst>(PFB->getSinglePredecessor()->getTerminator())
4184 ->getCondition();
4185 Value *QCond = cast<BranchInst>(QFB->getSinglePredecessor()->getTerminator())
4186 ->getCondition();
4187
4189 PStore->getParent());
4191 QStore->getParent(), PPHI);
4192
4193 BasicBlock::iterator PostBBFirst = PostBB->getFirstInsertionPt();
4194 IRBuilder<> QB(PostBB, PostBBFirst);
4195 QB.SetCurrentDebugLocation(PostBBFirst->getStableDebugLoc());
4196
4197 Value *PPred = PStore->getParent() == PTB ? PCond : QB.CreateNot(PCond);
4198 Value *QPred = QStore->getParent() == QTB ? QCond : QB.CreateNot(QCond);
4199
4200 if (InvertPCond)
4201 PPred = QB.CreateNot(PPred);
4202 if (InvertQCond)
4203 QPred = QB.CreateNot(QPred);
4204 Value *CombinedPred = QB.CreateOr(PPred, QPred);
4205
4206 BasicBlock::iterator InsertPt = QB.GetInsertPoint();
4207 auto *T = SplitBlockAndInsertIfThen(CombinedPred, InsertPt,
4208 /*Unreachable=*/false,
4209 /*BranchWeights=*/nullptr, DTU);
4210
4211 QB.SetInsertPoint(T);
4212 StoreInst *SI = cast<StoreInst>(QB.CreateStore(QPHI, Address));
4213 SI->setAAMetadata(PStore->getAAMetadata().merge(QStore->getAAMetadata()));
4214 // Choose the minimum alignment. If we could prove both stores execute, we
4215 // could use biggest one. In this case, though, we only know that one of the
4216 // stores executes. And we don't know it's safe to take the alignment from a
4217 // store that doesn't execute.
4218 SI->setAlignment(std::min(PStore->getAlign(), QStore->getAlign()));
4219
4220 QStore->eraseFromParent();
4221 PStore->eraseFromParent();
4222
4223 return true;
4224}
4225
4227 DomTreeUpdater *DTU, const DataLayout &DL,
4228 const TargetTransformInfo &TTI) {
4229 // The intention here is to find diamonds or triangles (see below) where each
4230 // conditional block contains a store to the same address. Both of these
4231 // stores are conditional, so they can't be unconditionally sunk. But it may
4232 // be profitable to speculatively sink the stores into one merged store at the
4233 // end, and predicate the merged store on the union of the two conditions of
4234 // PBI and QBI.
4235 //
4236 // This can reduce the number of stores executed if both of the conditions are
4237 // true, and can allow the blocks to become small enough to be if-converted.
4238 // This optimization will also chain, so that ladders of test-and-set
4239 // sequences can be if-converted away.
4240 //
4241 // We only deal with simple diamonds or triangles:
4242 //
4243 // PBI or PBI or a combination of the two
4244 // / \ | \
4245 // PTB PFB | PFB
4246 // \ / | /
4247 // QBI QBI
4248 // / \ | \
4249 // QTB QFB | QFB
4250 // \ / | /
4251 // PostBB PostBB
4252 //
4253 // We model triangles as a type of diamond with a nullptr "true" block.
4254 // Triangles are canonicalized so that the fallthrough edge is represented by
4255 // a true condition, as in the diagram above.
4256 BasicBlock *PTB = PBI->getSuccessor(0);
4257 BasicBlock *PFB = PBI->getSuccessor(1);
4258 BasicBlock *QTB = QBI->getSuccessor(0);
4259 BasicBlock *QFB = QBI->getSuccessor(1);
4260 BasicBlock *PostBB = QFB->getSingleSuccessor();
4261
4262 // Make sure we have a good guess for PostBB. If QTB's only successor is
4263 // QFB, then QFB is a better PostBB.
4264 if (QTB->getSingleSuccessor() == QFB)
4265 PostBB = QFB;
4266
4267 // If we couldn't find a good PostBB, stop.
4268 if (!PostBB)
4269 return false;
4270
4271 bool InvertPCond = false, InvertQCond = false;
4272 // Canonicalize fallthroughs to the true branches.
4273 if (PFB == QBI->getParent()) {
4274 std::swap(PFB, PTB);
4275 InvertPCond = true;
4276 }
4277 if (QFB == PostBB) {
4278 std::swap(QFB, QTB);
4279 InvertQCond = true;
4280 }
4281
4282 // From this point on we can assume PTB or QTB may be fallthroughs but PFB
4283 // and QFB may not. Model fallthroughs as a nullptr block.
4284 if (PTB == QBI->getParent())
4285 PTB = nullptr;
4286 if (QTB == PostBB)
4287 QTB = nullptr;
4288
4289 // Legality bailouts. We must have at least the non-fallthrough blocks and
4290 // the post-dominating block, and the non-fallthroughs must only have one
4291 // predecessor.
4292 auto HasOnePredAndOneSucc = [](BasicBlock *BB, BasicBlock *P, BasicBlock *S) {
4293 return BB->getSinglePredecessor() == P && BB->getSingleSuccessor() == S;
4294 };
4295 if (!HasOnePredAndOneSucc(PFB, PBI->getParent(), QBI->getParent()) ||
4296 !HasOnePredAndOneSucc(QFB, QBI->getParent(), PostBB))
4297 return false;
4298 if ((PTB && !HasOnePredAndOneSucc(PTB, PBI->getParent(), QBI->getParent())) ||
4299 (QTB && !HasOnePredAndOneSucc(QTB, QBI->getParent(), PostBB)))
4300 return false;
4301 if (!QBI->getParent()->hasNUses(2))
4302 return false;
4303
4304 // OK, this is a sequence of two diamonds or triangles.
4305 // Check if there are stores in PTB or PFB that are repeated in QTB or QFB.
4306 SmallPtrSet<Value *, 4> PStoreAddresses, QStoreAddresses;
4307 for (auto *BB : {PTB, PFB}) {
4308 if (!BB)
4309 continue;
4310 for (auto &I : *BB)
4311 if (StoreInst *SI = dyn_cast<StoreInst>(&I))
4312 PStoreAddresses.insert(SI->getPointerOperand());
4313 }
4314 for (auto *BB : {QTB, QFB}) {
4315 if (!BB)
4316 continue;
4317 for (auto &I : *BB)
4318 if (StoreInst *SI = dyn_cast<StoreInst>(&I))
4319 QStoreAddresses.insert(SI->getPointerOperand());
4320 }
4321
4322 set_intersect(PStoreAddresses, QStoreAddresses);
4323 // set_intersect mutates PStoreAddresses in place. Rename it here to make it
4324 // clear what it contains.
4325 auto &CommonAddresses = PStoreAddresses;
4326
4327 bool Changed = false;
4328 for (auto *Address : CommonAddresses)
4329 Changed |=
4330 mergeConditionalStoreToAddress(PTB, PFB, QTB, QFB, PostBB, Address,
4331 InvertPCond, InvertQCond, DTU, DL, TTI);
4332 return Changed;
4333}
4334
4335/// If the previous block ended with a widenable branch, determine if reusing
4336/// the target block is profitable and legal. This will have the effect of
4337/// "widening" PBI, but doesn't require us to reason about hosting safety.
4339 DomTreeUpdater *DTU) {
4340 // TODO: This can be generalized in two important ways:
4341 // 1) We can allow phi nodes in IfFalseBB and simply reuse all the input
4342 // values from the PBI edge.
4343 // 2) We can sink side effecting instructions into BI's fallthrough
4344 // successor provided they doesn't contribute to computation of
4345 // BI's condition.
4346 BasicBlock *IfTrueBB = PBI->getSuccessor(0);
4347 BasicBlock *IfFalseBB = PBI->getSuccessor(1);
4348 if (!isWidenableBranch(PBI) || IfTrueBB != BI->getParent() ||
4349 !BI->getParent()->getSinglePredecessor())
4350 return false;
4351 if (!IfFalseBB->phis().empty())
4352 return false; // TODO
4353 // This helps avoid infinite loop with SimplifyCondBranchToCondBranch which
4354 // may undo the transform done here.
4355 // TODO: There might be a more fine-grained solution to this.
4356 if (!llvm::succ_empty(IfFalseBB))
4357 return false;
4358 // Use lambda to lazily compute expensive condition after cheap ones.
4359 auto NoSideEffects = [](BasicBlock &BB) {
4360 return llvm::none_of(BB, [](const Instruction &I) {
4361 return I.mayWriteToMemory() || I.mayHaveSideEffects();
4362 });
4363 };
4364 if (BI->getSuccessor(1) != IfFalseBB && // no inf looping
4365 BI->getSuccessor(1)->getTerminatingDeoptimizeCall() && // profitability
4366 NoSideEffects(*BI->getParent())) {
4367 auto *OldSuccessor = BI->getSuccessor(1);
4368 OldSuccessor->removePredecessor(BI->getParent());
4369 BI->setSuccessor(1, IfFalseBB);
4370 if (DTU)
4371 DTU->applyUpdates(
4372 {{DominatorTree::Insert, BI->getParent(), IfFalseBB},
4373 {DominatorTree::Delete, BI->getParent(), OldSuccessor}});
4374 return true;
4375 }
4376 if (BI->getSuccessor(0) != IfFalseBB && // no inf looping
4377 BI->getSuccessor(0)->getTerminatingDeoptimizeCall() && // profitability
4378 NoSideEffects(*BI->getParent())) {
4379 auto *OldSuccessor = BI->getSuccessor(0);
4380 OldSuccessor->removePredecessor(BI->getParent());
4381 BI->setSuccessor(0, IfFalseBB);
4382 if (DTU)
4383 DTU->applyUpdates(
4384 {{DominatorTree::Insert, BI->getParent(), IfFalseBB},
4385 {DominatorTree::Delete, BI->getParent(), OldSuccessor}});
4386 return true;
4387 }
4388 return false;
4389}
4390
4391/// If we have a conditional branch as a predecessor of another block,
4392/// this function tries to simplify it. We know
4393/// that PBI and BI are both conditional branches, and BI is in one of the
4394/// successor blocks of PBI - PBI branches to BI.
4396 DomTreeUpdater *DTU,
4397 const DataLayout &DL,
4398 const TargetTransformInfo &TTI) {
4399 assert(PBI->isConditional() && BI->isConditional());
4400 BasicBlock *BB = BI->getParent();
4401
4402 // If this block ends with a branch instruction, and if there is a
4403 // predecessor that ends on a branch of the same condition, make
4404 // this conditional branch redundant.
4405 if (PBI->getCondition() == BI->getCondition() &&
4406 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
4407 // Okay, the outcome of this conditional branch is statically
4408 // knowable. If this block had a single pred, handle specially, otherwise
4409 // foldCondBranchOnValueKnownInPredecessor() will handle it.
4410 if (BB->getSinglePredecessor()) {
4411 // Turn this into a branch on constant.
4412 bool CondIsTrue = PBI->getSuccessor(0) == BB;
4413 BI->setCondition(
4414 ConstantInt::get(Type::getInt1Ty(BB->getContext()), CondIsTrue));
4415 return true; // Nuke the branch on constant.
4416 }
4417 }
4418
4419 // If the previous block ended with a widenable branch, determine if reusing
4420 // the target block is profitable and legal. This will have the effect of
4421 // "widening" PBI, but doesn't require us to reason about hosting safety.
4422 if (tryWidenCondBranchToCondBranch(PBI, BI, DTU))
4423 return true;
4424
4425 // If both branches are conditional and both contain stores to the same
4426 // address, remove the stores from the conditionals and create a conditional
4427 // merged store at the end.
4428 if (MergeCondStores && mergeConditionalStores(PBI, BI, DTU, DL, TTI))
4429 return true;
4430
4431 // If this is a conditional branch in an empty block, and if any
4432 // predecessors are a conditional branch to one of our destinations,
4433 // fold the conditions into logical ops and one cond br.
4434
4435 // Ignore dbg intrinsics.
4436 if (&*BB->instructionsWithoutDebug(false).begin() != BI)
4437 return false;
4438
4439 int PBIOp, BIOp;
4440 if (PBI->getSuccessor(0) == BI->getSuccessor(0)) {
4441 PBIOp = 0;
4442 BIOp = 0;
4443 } else if (PBI->getSuccessor(0) == BI->getSuccessor(1)) {
4444 PBIOp = 0;
4445 BIOp = 1;
4446 } else if (PBI->getSuccessor(1) == BI->getSuccessor(0)) {
4447 PBIOp = 1;
4448 BIOp = 0;
4449 } else if (PBI->getSuccessor(1) == BI->getSuccessor(1)) {
4450 PBIOp = 1;
4451 BIOp = 1;
4452 } else {
4453 return false;
4454 }
4455
4456 // Check to make sure that the other destination of this branch
4457 // isn't BB itself. If so, this is an infinite loop that will
4458 // keep getting unwound.
4459 if (PBI->getSuccessor(PBIOp) == BB)
4460 return false;
4461
4462 // If predecessor's branch probability to BB is too low don't merge branches.
4463 SmallVector<uint32_t, 2> PredWeights;
4464 if (!PBI->getMetadata(LLVMContext::MD_unpredictable) &&
4465 extractBranchWeights(*PBI, PredWeights) &&
4466 (static_cast<uint64_t>(PredWeights[0]) + PredWeights[1]) != 0) {
4467
4469 PredWeights[PBIOp],
4470 static_cast<uint64_t>(PredWeights[0]) + PredWeights[1]);
4471
4473 if (CommonDestProb >= Likely)
4474 return false;
4475 }
4476
4477 // Do not perform this transformation if it would require
4478 // insertion of a large number of select instructions. For targets
4479 // without predication/cmovs, this is a big pessimization.
4480
4481 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
4482 BasicBlock *RemovedDest = PBI->getSuccessor(PBIOp ^ 1);
4483 unsigned NumPhis = 0;
4484 for (BasicBlock::iterator II = CommonDest->begin(); isa<PHINode>(II);
4485 ++II, ++NumPhis) {
4486 if (NumPhis > 2) // Disable this xform.
4487 return false;
4488 }
4489
4490 // Finally, if everything is ok, fold the branches to logical ops.
4491 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
4492
4493 LLVM_DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
4494 << "AND: " << *BI->getParent());
4495
4497
4498 // If OtherDest *is* BB, then BB is a basic block with a single conditional
4499 // branch in it, where one edge (OtherDest) goes back to itself but the other
4500 // exits. We don't *know* that the program avoids the infinite loop
4501 // (even though that seems likely). If we do this xform naively, we'll end up
4502 // recursively unpeeling the loop. Since we know that (after the xform is
4503 // done) that the block *is* infinite if reached, we just make it an obviously
4504 // infinite loop with no cond branch.
4505 if (OtherDest == BB) {
4506 // Insert it at the end of the function, because it's either code,
4507 // or it won't matter if it's hot. :)
4508 BasicBlock *InfLoopBlock =
4509 BasicBlock::Create(BB->getContext(), "infloop", BB->getParent());
4510 BranchInst::Create(InfLoopBlock, InfLoopBlock);
4511 if (DTU)
4512 Updates.push_back({DominatorTree::Insert, InfLoopBlock, InfLoopBlock});
4513 OtherDest = InfLoopBlock;
4514 }
4515
4516 LLVM_DEBUG(dbgs() << *PBI->getParent()->getParent());
4517
4518 // BI may have other predecessors. Because of this, we leave
4519 // it alone, but modify PBI.
4520
4521 // Make sure we get to CommonDest on True&True directions.
4522 Value *PBICond = PBI->getCondition();
4523 IRBuilder<NoFolder> Builder(PBI);
4524 if (PBIOp)
4525 PBICond = Builder.CreateNot(PBICond, PBICond->getName() + ".not");
4526
4527 Value *BICond = BI->getCondition();
4528 if (BIOp)
4529 BICond = Builder.CreateNot(BICond, BICond->getName() + ".not");
4530
4531 // Merge the conditions.
4532 Value *Cond =
4533 createLogicalOp(Builder, Instruction::Or, PBICond, BICond, "brmerge");
4534
4535 // Modify PBI to branch on the new condition to the new dests.
4536 PBI->setCondition(Cond);
4537 PBI->setSuccessor(0, CommonDest);
4538 PBI->setSuccessor(1, OtherDest);
4539
4540 if (DTU) {
4541 Updates.push_back({DominatorTree::Insert, PBI->getParent(), OtherDest});
4542 Updates.push_back({DominatorTree::Delete, PBI->getParent(), RemovedDest});
4543
4544 DTU->applyUpdates(Updates);
4545 }
4546
4547 // Update branch weight for PBI.
4548 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
4549 uint64_t PredCommon, PredOther, SuccCommon, SuccOther;
4550 bool HasWeights =
4551 extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight,
4552 SuccTrueWeight, SuccFalseWeight);
4553 if (HasWeights) {
4554 PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
4555 PredOther = PBIOp ? PredTrueWeight : PredFalseWeight;
4556 SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
4557 SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
4558 // The weight to CommonDest should be PredCommon * SuccTotal +
4559 // PredOther * SuccCommon.
4560 // The weight to OtherDest should be PredOther * SuccOther.
4561 uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther) +
4562 PredOther * SuccCommon,
4563 PredOther * SuccOther};
4564 // Halve the weights if any of them cannot fit in an uint32_t
4565 fitWeights(NewWeights);
4566
4567 setBranchWeights(PBI, NewWeights[0], NewWeights[1], /*IsExpected=*/false);
4568 }
4569
4570 // OtherDest may have phi nodes. If so, add an entry from PBI's
4571 // block that are identical to the entries for BI's block.
4572 addPredecessorToBlock(OtherDest, PBI->getParent(), BB);
4573
4574 // We know that the CommonDest already had an edge from PBI to
4575 // it. If it has PHIs though, the PHIs may have different
4576 // entries for BB and PBI's BB. If so, insert a select to make
4577 // them agree.
4578 for (PHINode &PN : CommonDest->phis()) {
4579 Value *BIV = PN.getIncomingValueForBlock(BB);
4580 unsigned PBBIdx = PN.getBasicBlockIndex(PBI->getParent());
4581 Value *PBIV = PN.getIncomingValue(PBBIdx);
4582 if (BIV != PBIV) {
4583 // Insert a select in PBI to pick the right value.
4584 SelectInst *NV = cast<SelectInst>(
4585 Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName() + ".mux"));
4586 PN.setIncomingValue(PBBIdx, NV);
4587 // Although the select has the same condition as PBI, the original branch
4588 // weights for PBI do not apply to the new select because the select's
4589 // 'logical' edges are incoming edges of the phi that is eliminated, not
4590 // the outgoing edges of PBI.
4591 if (HasWeights) {
4592 uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
4593 uint64_t PredOther = PBIOp ? PredTrueWeight : PredFalseWeight;
4594 uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
4595 uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
4596 // The weight to PredCommonDest should be PredCommon * SuccTotal.
4597 // The weight to PredOtherDest should be PredOther * SuccCommon.
4598 uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther),
4599 PredOther * SuccCommon};
4600
4601 fitWeights(NewWeights);
4602
4603 setBranchWeights(NV, NewWeights[0], NewWeights[1],
4604 /*IsExpected=*/false);
4605 }
4606 }
4607 }
4608
4609 LLVM_DEBUG(dbgs() << "INTO: " << *PBI->getParent());
4610 LLVM_DEBUG(dbgs() << *PBI->getParent()->getParent());
4611
4612 // This basic block is probably dead. We know it has at least
4613 // one fewer predecessor.
4614 return true;
4615}
4616
4617// Simplifies a terminator by replacing it with a branch to TrueBB if Cond is
4618// true or to FalseBB if Cond is false.
4619// Takes care of updating the successors and removing the old terminator.
4620// Also makes sure not to introduce new successors by assuming that edges to
4621// non-successor TrueBBs and FalseBBs aren't reachable.
4622bool SimplifyCFGOpt::simplifyTerminatorOnSelect(Instruction *OldTerm,
4623 Value *Cond, BasicBlock *TrueBB,
4624 BasicBlock *FalseBB,
4625 uint32_t TrueWeight,
4626 uint32_t FalseWeight) {
4627 auto *BB = OldTerm->getParent();
4628 // Remove any superfluous successor edges from the CFG.
4629 // First, figure out which successors to preserve.
4630 // If TrueBB and FalseBB are equal, only try to preserve one copy of that
4631 // successor.
4632 BasicBlock *KeepEdge1 = TrueBB;
4633 BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr;
4634
4635 SmallSetVector<BasicBlock *, 2> RemovedSuccessors;
4636
4637 // Then remove the rest.
4638 for (BasicBlock *Succ : successors(OldTerm)) {
4639 // Make sure only to keep exactly one copy of each edge.
4640 if (Succ == KeepEdge1)
4641 KeepEdge1 = nullptr;
4642 else if (Succ == KeepEdge2)
4643 KeepEdge2 = nullptr;
4644 else {
4645 Succ->removePredecessor(BB,
4646 /*KeepOneInputPHIs=*/true);
4647
4648 if (Succ != TrueBB && Succ != FalseBB)
4649 RemovedSuccessors.insert(Succ);
4650 }
4651 }
4652
4653 IRBuilder<> Builder(OldTerm);
4654 Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc());
4655
4656 // Insert an appropriate new terminator.
4657 if (!KeepEdge1 && !KeepEdge2) {
4658 if (TrueBB == FalseBB) {
4659 // We were only looking for one successor, and it was present.
4660 // Create an unconditional branch to it.
4661 Builder.CreateBr(TrueBB);
4662 } else {
4663 // We found both of the successors we were looking for.
4664 // Create a conditional branch sharing the condition of the select.
4665 BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB);
4666 if (TrueWeight != FalseWeight)
4667 setBranchWeights(NewBI, TrueWeight, FalseWeight, /*IsExpected=*/false);
4668 }
4669 } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
4670 // Neither of the selected blocks were successors, so this
4671 // terminator must be unreachable.
4672 new UnreachableInst(OldTerm->getContext(), OldTerm->getIterator());
4673 } else {
4674 // One of the selected values was a successor, but the other wasn't.
4675 // Insert an unconditional branch to the one that was found;
4676 // the edge to the one that wasn't must be unreachable.
4677 if (!KeepEdge1) {
4678 // Only TrueBB was found.
4679 Builder.CreateBr(TrueBB);
4680 } else {
4681 // Only FalseBB was found.
4682 Builder.CreateBr(FalseBB);
4683 }
4684 }
4685
4687
4688 if (DTU) {
4690 Updates.reserve(RemovedSuccessors.size());
4691 for (auto *RemovedSuccessor : RemovedSuccessors)
4692 Updates.push_back({DominatorTree::Delete, BB, RemovedSuccessor});
4693 DTU->applyUpdates(Updates);
4694 }
4695
4696 return true;
4697}
4698
4699// Replaces
4700// (switch (select cond, X, Y)) on constant X, Y
4701// with a branch - conditional if X and Y lead to distinct BBs,
4702// unconditional otherwise.
4703bool SimplifyCFGOpt::simplifySwitchOnSelect(SwitchInst *SI,
4704 SelectInst *Select) {
4705 // Check for constant integer values in the select.
4706 ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue());
4707 ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue());
4708 if (!TrueVal || !FalseVal)
4709 return false;
4710
4711 // Find the relevant condition and destinations.
4712 Value *Condition = Select->getCondition();
4713 BasicBlock *TrueBB = SI->findCaseValue(TrueVal)->getCaseSuccessor();
4714 BasicBlock *FalseBB = SI->findCaseValue(FalseVal)->getCaseSuccessor();
4715
4716 // Get weight for TrueBB and FalseBB.
4717 uint32_t TrueWeight = 0, FalseWeight = 0;
4719 bool HasWeights = hasBranchWeightMD(*SI);
4720 if (HasWeights) {
4721 getBranchWeights(SI, Weights);
4722 if (Weights.size() == 1 + SI->getNumCases()) {
4723 TrueWeight =
4724 (uint32_t)Weights[SI->findCaseValue(TrueVal)->getSuccessorIndex()];
4725 FalseWeight =
4726 (uint32_t)Weights[SI->findCaseValue(FalseVal)->getSuccessorIndex()];
4727 }
4728 }
4729
4730 // Perform the actual simplification.
4731 return simplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB, TrueWeight,
4732 FalseWeight);
4733}
4734
4735// Replaces
4736// (indirectbr (select cond, blockaddress(@fn, BlockA),
4737// blockaddress(@fn, BlockB)))
4738// with
4739// (br cond, BlockA, BlockB).
4740bool SimplifyCFGOpt::simplifyIndirectBrOnSelect(IndirectBrInst *IBI,
4741 SelectInst *SI) {
4742 // Check that both operands of the select are block addresses.
4743 BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
4744 BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
4745 if (!TBA || !FBA)
4746 return false;
4747
4748 // Extract the actual blocks.
4749 BasicBlock *TrueBB = TBA->getBasicBlock();
4750 BasicBlock *FalseBB = FBA->getBasicBlock();
4751
4752 // Perform the actual simplification.
4753 return simplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB, 0,
4754 0);
4755}
4756
4757/// This is called when we find an icmp instruction
4758/// (a seteq/setne with a constant) as the only instruction in a
4759/// block that ends with an uncond branch. We are looking for a very specific
4760/// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In
4761/// this case, we merge the first two "or's of icmp" into a switch, but then the
4762/// default value goes to an uncond block with a seteq in it, we get something
4763/// like:
4764///
4765/// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ]
4766/// DEFAULT:
4767/// %tmp = icmp eq i8 %A, 92
4768/// br label %end
4769/// end:
4770/// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
4771///
4772/// We prefer to split the edge to 'end' so that there is a true/false entry to
4773/// the PHI, merging the third icmp into the switch.
4774bool SimplifyCFGOpt::tryToSimplifyUncondBranchWithICmpInIt(
4775 ICmpInst *ICI, IRBuilder<> &Builder) {
4776 BasicBlock *BB = ICI->getParent();
4777
4778 // If the block has any PHIs in it or the icmp has multiple uses, it is too
4779 // complex.
4780 if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse())
4781 return false;
4782
4783 Value *V = ICI->getOperand(0);
4784 ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1));
4785
4786 // The pattern we're looking for is where our only predecessor is a switch on
4787 // 'V' and this block is the default case for the switch. In this case we can
4788 // fold the compared value into the switch to simplify things.
4789 BasicBlock *Pred = BB->getSinglePredecessor();
4790 if (!Pred || !isa<SwitchInst>(Pred->getTerminator()))
4791 return false;
4792
4793 SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
4794 if (SI->getCondition() != V)
4795 return false;
4796
4797 // If BB is reachable on a non-default case, then we simply know the value of
4798 // V in this block. Substitute it and constant fold the icmp instruction
4799 // away.
4800 if (SI->getDefaultDest() != BB) {
4801 ConstantInt *VVal = SI->findCaseDest(BB);
4802 assert(VVal && "Should have a unique destination value");
4803 ICI->setOperand(0, VVal);
4804
4805 if (Value *V = simplifyInstruction(ICI, {DL, ICI})) {
4806 ICI->replaceAllUsesWith(V);
4807 ICI->eraseFromParent();
4808 }
4809 // BB is now empty, so it is likely to simplify away.
4810 return requestResimplify();
4811 }
4812
4813 // Ok, the block is reachable from the default dest. If the constant we're
4814 // comparing exists in one of the other edges, then we can constant fold ICI
4815 // and zap it.
4816 if (SI->findCaseValue(Cst) != SI->case_default()) {
4817 Value *V;
4818 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
4820 else
4822
4823 ICI->replaceAllUsesWith(V);
4824 ICI->eraseFromParent();
4825 // BB is now empty, so it is likely to simplify away.
4826 return requestResimplify();
4827 }
4828
4829 // The use of the icmp has to be in the 'end' block, by the only PHI node in
4830 // the block.
4831 BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
4832 PHINode *PHIUse = dyn_cast<PHINode>(ICI->user_back());
4833 if (PHIUse == nullptr || PHIUse != &SuccBlock->front() ||
4834 isa<PHINode>(++BasicBlock::iterator(PHIUse)))
4835 return false;
4836
4837 // If the icmp is a SETEQ, then the default dest gets false, the new edge gets
4838 // true in the PHI.
4839 Constant *DefaultCst = ConstantInt::getTrue(BB->getContext());
4840 Constant *NewCst = ConstantInt::getFalse(BB->getContext());
4841
4842 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
4843 std::swap(DefaultCst, NewCst);
4844
4845 // Replace ICI (which is used by the PHI for the default value) with true or
4846 // false depending on if it is EQ or NE.
4847 ICI->replaceAllUsesWith(DefaultCst);
4848 ICI->eraseFromParent();
4849
4851
4852 // Okay, the switch goes to this block on a default value. Add an edge from
4853 // the switch to the merge point on the compared value.
4854 BasicBlock *NewBB =
4855 BasicBlock::Create(BB->getContext(), "switch.edge", BB->getParent(), BB);
4856 {
4858 auto W0 = SIW.getSuccessorWeight(0);
4860 if (W0) {
4861 NewW = ((uint64_t(*W0) + 1) >> 1);
4862 SIW.setSuccessorWeight(0, *NewW);
4863 }
4864 SIW.addCase(Cst, NewBB, NewW);
4865 if (DTU)
4866 Updates.push_back({DominatorTree::Insert, Pred, NewBB});
4867 }
4868
4869 // NewBB branches to the phi block, add the uncond branch and the phi entry.
4870 Builder.SetInsertPoint(NewBB);
4871 Builder.SetCurrentDebugLocation(SI->getDebugLoc());
4872 Builder.CreateBr(SuccBlock);
4873 PHIUse->addIncoming(NewCst, NewBB);
4874 if (DTU) {
4875 Updates.push_back({DominatorTree::Insert, NewBB, SuccBlock});
4876 DTU->applyUpdates(Updates);
4877 }
4878 return true;
4879}
4880
4881/// The specified branch is a conditional branch.
4882/// Check to see if it is branching on an or/and chain of icmp instructions, and
4883/// fold it into a switch instruction if so.
4884bool SimplifyCFGOpt::simplifyBranchOnICmpChain(BranchInst *BI,
4885 IRBuilder<> &Builder,
4886 const DataLayout &DL) {
4887 Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
4888 if (!Cond)
4889 return false;
4890
4891 // Change br (X == 0 | X == 1), T, F into a switch instruction.
4892 // If this is a bunch of seteq's or'd together, or if it's a bunch of
4893 // 'setne's and'ed together, collect them.
4894
4895 // Try to gather values from a chain of and/or to be turned into a switch
4896 ConstantComparesGatherer ConstantCompare(Cond, DL);
4897 // Unpack the result
4898 SmallVectorImpl<ConstantInt *> &Values = ConstantCompare.Vals;
4899 Value *CompVal = ConstantCompare.CompValue;
4900 unsigned UsedICmps = ConstantCompare.UsedICmps;
4901 Value *ExtraCase = ConstantCompare.Extra;
4902
4903 // If we didn't have a multiply compared value, fail.
4904 if (!CompVal)
4905 return false;
4906
4907 // Avoid turning single icmps into a switch.
4908 if (UsedICmps <= 1)
4909 return false;
4910
4911 bool TrueWhenEqual = match(Cond, m_LogicalOr(m_Value(), m_Value()));
4912
4913 // There might be duplicate constants in the list, which the switch
4914 // instruction can't handle, remove them now.
4915 array_pod_sort(Values.begin(), Values.end(), constantIntSortPredicate);
4916 Values.erase(llvm::unique(Values), Values.end());
4917
4918 // If Extra was used, we require at least two switch values to do the
4919 // transformation. A switch with one value is just a conditional branch.
4920 if (ExtraCase && Values.size() < 2)
4921 return false;
4922
4923 // TODO: Preserve branch weight metadata, similarly to how
4924 // foldValueComparisonIntoPredecessors preserves it.
4925
4926 // Figure out which block is which destination.
4927 BasicBlock *DefaultBB = BI->getSuccessor(1);
4928 BasicBlock *EdgeBB = BI->getSuccessor(0);
4929 if (!TrueWhenEqual)
4930 std::swap(DefaultBB, EdgeBB);
4931
4932 BasicBlock *BB = BI->getParent();
4933
4934 LLVM_DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
4935 << " cases into SWITCH. BB is:\n"
4936 << *BB);
4937
4939
4940 // If there are any extra values that couldn't be folded into the switch
4941 // then we evaluate them with an explicit branch first. Split the block
4942 // right before the condbr to handle it.
4943 if (ExtraCase) {
4944 BasicBlock *NewBB = SplitBlock(BB, BI, DTU, /*LI=*/nullptr,
4945 /*MSSAU=*/nullptr, "switch.early.test");
4946
4947 // Remove the uncond branch added to the old block.
4948 Instruction *OldTI = BB->getTerminator();
4949 Builder.SetInsertPoint(OldTI);
4950
4951 // There can be an unintended UB if extra values are Poison. Before the
4952 // transformation, extra values may not be evaluated according to the
4953 // condition, and it will not raise UB. But after transformation, we are
4954 // evaluating extra values before checking the condition, and it will raise
4955 // UB. It can be solved by adding freeze instruction to extra values.
4956 AssumptionCache *AC = Options.AC;
4957
4958 if (!isGuaranteedNotToBeUndefOrPoison(ExtraCase, AC, BI, nullptr))
4959 ExtraCase = Builder.CreateFreeze(ExtraCase);
4960
4961 if (TrueWhenEqual)
4962 Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB);
4963 else
4964 Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB);
4965
4966 OldTI->eraseFromParent();
4967
4968 if (DTU)
4969 Updates.push_back({DominatorTree::Insert, BB, EdgeBB});
4970
4971 // If there are PHI nodes in EdgeBB, then we need to add a new entry to them
4972 // for the edge we just added.
4973 addPredecessorToBlock(EdgeBB, BB, NewBB);
4974
4975 LLVM_DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase
4976 << "\nEXTRABB = " << *BB);
4977 BB = NewBB;
4978 }
4979
4980 Builder.SetInsertPoint(BI);
4981 // Convert pointer to int before we switch.
4982 if (CompVal->getType()->isPointerTy()) {
4983 CompVal = Builder.CreatePtrToInt(
4984 CompVal, DL.getIntPtrType(CompVal->getType()), "magicptr");
4985 }
4986
4987 // Create the new switch instruction now.
4988 SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size());
4989
4990 // Add all of the 'cases' to the switch instruction.
4991 for (unsigned i = 0, e = Values.size(); i != e; ++i)
4992 New->addCase(Values[i], EdgeBB);
4993
4994 // We added edges from PI to the EdgeBB. As such, if there were any
4995 // PHI nodes in EdgeBB, they need entries to be added corresponding to
4996 // the number of edges added.
4997 for (BasicBlock::iterator BBI = EdgeBB->begin(); isa<PHINode>(BBI); ++BBI) {
4998 PHINode *PN = cast<PHINode>(BBI);
4999 Value *InVal = PN->getIncomingValueForBlock(BB);
5000 for (unsigned i = 0, e = Values.size() - 1; i != e; ++i)
5001 PN->addIncoming(InVal, BB);
5002 }
5003
5004 // Erase the old branch instruction.
5006 if (DTU)
5007 DTU->applyUpdates(Updates);
5008
5009 LLVM_DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n');
5010 return true;
5011}
5012
5013bool SimplifyCFGOpt::simplifyResume(ResumeInst *RI, IRBuilder<> &Builder) {
5014 if (isa<PHINode>(RI->getValue()))
5015 return simplifyCommonResume(RI);
5016 else if (isa<LandingPadInst>(RI->getParent()->getFirstNonPHI()) &&
5017 RI->getValue() == RI->getParent()->getFirstNonPHI())
5018 // The resume must unwind the exception that caused control to branch here.
5019 return simplifySingleResume(RI);
5020
5021 return false;
5022}
5023
5024// Check if cleanup block is empty
5026 for (Instruction &I : R) {
5027 auto *II = dyn_cast<IntrinsicInst>(&I);
5028 if (!II)
5029 return false;
5030
5031 Intrinsic::ID IntrinsicID = II->getIntrinsicID();
5032 switch (IntrinsicID) {
5033 case Intrinsic::dbg_declare:
5034 case Intrinsic::dbg_value:
5035 case Intrinsic::dbg_label:
5036 case Intrinsic::lifetime_end:
5037 break;
5038 default:
5039 return false;
5040 }
5041 }
5042 return true;
5043}
5044
5045// Simplify resume that is shared by several landing pads (phi of landing pad).
5046bool SimplifyCFGOpt::simplifyCommonResume(ResumeInst *RI) {
5047 BasicBlock *BB = RI->getParent();
5048
5049 // Check that there are no other instructions except for debug and lifetime
5050 // intrinsics between the phi's and resume instruction.
5052 make_range(RI->getParent()->getFirstNonPHI(), BB->getTerminator())))
5053 return false;
5054
5055 SmallSetVector<BasicBlock *, 4> TrivialUnwindBlocks;
5056 auto *PhiLPInst = cast<PHINode>(RI->getValue());
5057
5058 // Check incoming blocks to see if any of them are trivial.
5059 for (unsigned Idx = 0, End = PhiLPInst->getNumIncomingValues(); Idx != End;
5060 Idx++) {
5061 auto *IncomingBB = PhiLPInst->getIncomingBlock(Idx);
5062 auto *IncomingValue = PhiLPInst->getIncomingValue(Idx);
5063
5064 // If the block has other successors, we can not delete it because
5065 // it has other dependents.
5066 if (IncomingBB->getUniqueSuccessor() != BB)
5067 continue;
5068
5069 auto *LandingPad = dyn_cast<LandingPadInst>(IncomingBB->getFirstNonPHI());
5070 // Not the landing pad that caused the control to branch here.
5071 if (IncomingValue != LandingPad)
5072 continue;
5073
5075 make_range(LandingPad->getNextNode(), IncomingBB->getTerminator())))
5076 TrivialUnwindBlocks.insert(IncomingBB);
5077 }
5078
5079 // If no trivial unwind blocks, don't do any simplifications.
5080 if (TrivialUnwindBlocks.empty())
5081 return false;
5082
5083 // Turn all invokes that unwind here into calls.
5084 for (auto *TrivialBB : TrivialUnwindBlocks) {
5085 // Blocks that will be simplified should be removed from the phi node.
5086 // Note there could be multiple edges to the resume block, and we need
5087 // to remove them all.
5088 while (PhiLPInst->getBasicBlockIndex(TrivialBB) != -1)
5089 BB->removePredecessor(TrivialBB, true);
5090
5091 for (BasicBlock *Pred :
5093 removeUnwindEdge(Pred, DTU);
5094 ++NumInvokes;
5095 }
5096
5097 // In each SimplifyCFG run, only the current processed block can be erased.
5098 // Otherwise, it will break the iteration of SimplifyCFG pass. So instead
5099 // of erasing TrivialBB, we only remove the branch to the common resume
5100 // block so that we can later erase the resume block since it has no
5101 // predecessors.
5102 TrivialBB->getTerminator()->eraseFromParent();
5103 new UnreachableInst(RI->getContext(), TrivialBB);
5104 if (DTU)
5105 DTU->applyUpdates({{DominatorTree::Delete, TrivialBB, BB}});
5106 }
5107
5108 // Delete the resume block if all its predecessors have been removed.
5109 if (pred_empty(BB))
5110 DeleteDeadBlock(BB, DTU);
5111
5112 return !TrivialUnwindBlocks.empty();
5113}
5114
5115// Simplify resume that is only used by a single (non-phi) landing pad.
5116bool SimplifyCFGOpt::simplifySingleResume(ResumeInst *RI) {
5117 BasicBlock *BB = RI->getParent();
5118 auto *LPInst = cast<LandingPadInst>(BB->getFirstNonPHI());
5119 assert(RI->getValue() == LPInst &&
5120 "Resume must unwind the exception that caused control to here");
5121
5122 // Check that there are no other instructions except for debug intrinsics.
5124 make_range<Instruction *>(LPInst->getNextNode(), RI)))
5125 return false;
5126
5127 // Turn all invokes that unwind here into calls and delete the basic block.
5129 removeUnwindEdge(Pred, DTU);
5130 ++NumInvokes;
5131 }
5132
5133 // The landingpad is now unreachable. Zap it.
5134 DeleteDeadBlock(BB, DTU);
5135 return true;
5136}
5137
5139 // If this is a trivial cleanup pad that executes no instructions, it can be
5140 // eliminated. If the cleanup pad continues to the caller, any predecessor
5141 // that is an EH pad will be updated to continue to the caller and any
5142 // predecessor that terminates with an invoke instruction will have its invoke
5143 // instruction converted to a call instruction. If the cleanup pad being
5144 // simplified does not continue to the caller, each predecessor will be
5145 // updated to continue to the unwind destination of the cleanup pad being
5146 // simplified.
5147 BasicBlock *BB = RI->getParent();
5148 CleanupPadInst *CPInst = RI->getCleanupPad();
5149 if (CPInst->