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