LLVM 17.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/ScopeExit.h"
19#include "llvm/ADT/Sequence.h"
21#include "llvm/ADT/SetVector.h"
24#include "llvm/ADT/Statistic.h"
25#include "llvm/ADT/StringRef.h"
36#include "llvm/IR/Attributes.h"
37#include "llvm/IR/BasicBlock.h"
38#include "llvm/IR/CFG.h"
39#include "llvm/IR/Constant.h"
41#include "llvm/IR/Constants.h"
42#include "llvm/IR/DataLayout.h"
43#include "llvm/IR/DebugInfo.h"
45#include "llvm/IR/Function.h"
46#include "llvm/IR/GlobalValue.h"
48#include "llvm/IR/IRBuilder.h"
49#include "llvm/IR/InstrTypes.h"
50#include "llvm/IR/Instruction.h"
53#include "llvm/IR/LLVMContext.h"
54#include "llvm/IR/MDBuilder.h"
55#include "llvm/IR/Metadata.h"
56#include "llvm/IR/Module.h"
57#include "llvm/IR/NoFolder.h"
58#include "llvm/IR/Operator.h"
61#include "llvm/IR/Type.h"
62#include "llvm/IR/Use.h"
63#include "llvm/IR/User.h"
64#include "llvm/IR/Value.h"
65#include "llvm/IR/ValueHandle.h"
69#include "llvm/Support/Debug.h"
77#include <algorithm>
78#include <cassert>
79#include <climits>
80#include <cstddef>
81#include <cstdint>
82#include <iterator>
83#include <map>
84#include <optional>
85#include <set>
86#include <tuple>
87#include <utility>
88#include <vector>
89
90using namespace llvm;
91using namespace PatternMatch;
92
93#define DEBUG_TYPE "simplifycfg"
94
96 "simplifycfg-require-and-preserve-domtree", cl::Hidden,
97
98 cl::desc("Temorary development switch used to gradually uplift SimplifyCFG "
99 "into preserving DomTree,"));
100
101// Chosen as 2 so as to be cheap, but still to have enough power to fold
102// a select, so the "clamp" idiom (of a min followed by a max) will be caught.
103// To catch this, we need to fold a compare and a select, hence '2' being the
104// minimum reasonable default.
106 "phi-node-folding-threshold", cl::Hidden, cl::init(2),
107 cl::desc(
108 "Control the amount of phi node folding to perform (default = 2)"));
109
111 "two-entry-phi-node-folding-threshold", cl::Hidden, cl::init(4),
112 cl::desc("Control the maximal total instruction cost that we are willing "
113 "to speculatively execute to fold a 2-entry PHI node into a "
114 "select (default = 4)"));
115
116static cl::opt<bool>
117 HoistCommon("simplifycfg-hoist-common", cl::Hidden, cl::init(true),
118 cl::desc("Hoist common instructions up to the parent block"));
119
121 HoistCommonSkipLimit("simplifycfg-hoist-common-skip-limit", cl::Hidden,
122 cl::init(20),
123 cl::desc("Allow reordering across at most this many "
124 "instructions when hoisting"));
125
126static cl::opt<bool>
127 SinkCommon("simplifycfg-sink-common", cl::Hidden, cl::init(true),
128 cl::desc("Sink common instructions down to the end block"));
129
131 "simplifycfg-hoist-cond-stores", cl::Hidden, cl::init(true),
132 cl::desc("Hoist conditional stores if an unconditional store precedes"));
133
135 "simplifycfg-merge-cond-stores", cl::Hidden, cl::init(true),
136 cl::desc("Hoist conditional stores even if an unconditional store does not "
137 "precede - hoist multiple conditional stores into a single "
138 "predicated store"));
139
141 "simplifycfg-merge-cond-stores-aggressively", cl::Hidden, cl::init(false),
142 cl::desc("When merging conditional stores, do so even if the resultant "
143 "basic blocks are unlikely to be if-converted as a result"));
144
146 "speculate-one-expensive-inst", cl::Hidden, cl::init(true),
147 cl::desc("Allow exactly one expensive instruction to be speculatively "
148 "executed"));
149
151 "max-speculation-depth", cl::Hidden, cl::init(10),
152 cl::desc("Limit maximum recursion depth when calculating costs of "
153 "speculatively executed instructions"));
154
155static cl::opt<int>
156 MaxSmallBlockSize("simplifycfg-max-small-block-size", cl::Hidden,
157 cl::init(10),
158 cl::desc("Max size of a block which is still considered "
159 "small enough to thread through"));
160
161// Two is chosen to allow one negation and a logical combine.
163 BranchFoldThreshold("simplifycfg-branch-fold-threshold", cl::Hidden,
164 cl::init(2),
165 cl::desc("Maximum cost of combining conditions when "
166 "folding branches"));
167
169 "simplifycfg-branch-fold-common-dest-vector-multiplier", cl::Hidden,
170 cl::init(2),
171 cl::desc("Multiplier to apply to threshold when determining whether or not "
172 "to fold branch to common destination when vector operations are "
173 "present"));
174
176 "simplifycfg-merge-compatible-invokes", cl::Hidden, cl::init(true),
177 cl::desc("Allow SimplifyCFG to merge invokes together when appropriate"));
178
180 "max-switch-cases-per-result", cl::Hidden, cl::init(16),
181 cl::desc("Limit cases to analyze when converting a switch to select"));
182
183STATISTIC(NumBitMaps, "Number of switch instructions turned into bitmaps");
184STATISTIC(NumLinearMaps,
185 "Number of switch instructions turned into linear mapping");
186STATISTIC(NumLookupTables,
187 "Number of switch instructions turned into lookup tables");
189 NumLookupTablesHoles,
190 "Number of switch instructions turned into lookup tables (holes checked)");
191STATISTIC(NumTableCmpReuses, "Number of reused switch table lookup compares");
192STATISTIC(NumFoldValueComparisonIntoPredecessors,
193 "Number of value comparisons folded into predecessor basic blocks");
194STATISTIC(NumFoldBranchToCommonDest,
195 "Number of branches folded into predecessor basic block");
197 NumHoistCommonCode,
198 "Number of common instruction 'blocks' hoisted up to the begin block");
199STATISTIC(NumHoistCommonInstrs,
200 "Number of common instructions hoisted up to the begin block");
201STATISTIC(NumSinkCommonCode,
202 "Number of common instruction 'blocks' sunk down to the end block");
203STATISTIC(NumSinkCommonInstrs,
204 "Number of common instructions sunk down to the end block");
205STATISTIC(NumSpeculations, "Number of speculative executed instructions");
206STATISTIC(NumInvokes,
207 "Number of invokes with empty resume blocks simplified into calls");
208STATISTIC(NumInvokesMerged, "Number of invokes that were merged together");
209STATISTIC(NumInvokeSetsFormed, "Number of invoke sets that were formed");
210
211namespace {
212
213// The first field contains the value that the switch produces when a certain
214// case group is selected, and the second field is a vector containing the
215// cases composing the case group.
216using SwitchCaseResultVectorTy =
218
219// The first field contains the phi node that generates a result of the switch
220// and the second field contains the value generated for a certain case in the
221// switch for that PHI.
222using SwitchCaseResultsTy = SmallVector<std::pair<PHINode *, Constant *>, 4>;
223
224/// ValueEqualityComparisonCase - Represents a case of a switch.
225struct ValueEqualityComparisonCase {
227 BasicBlock *Dest;
228
229 ValueEqualityComparisonCase(ConstantInt *Value, BasicBlock *Dest)
230 : Value(Value), Dest(Dest) {}
231
232 bool operator<(ValueEqualityComparisonCase RHS) const {
233 // Comparing pointers is ok as we only rely on the order for uniquing.
234 return Value < RHS.Value;
235 }
236
237 bool operator==(BasicBlock *RHSDest) const { return Dest == RHSDest; }
238};
239
240class SimplifyCFGOpt {
242 DomTreeUpdater *DTU;
243 const DataLayout &DL;
244 ArrayRef<WeakVH> LoopHeaders;
246 bool Resimplify;
247
248 Value *isValueEqualityComparison(Instruction *TI);
249 BasicBlock *GetValueEqualityComparisonCases(
250 Instruction *TI, std::vector<ValueEqualityComparisonCase> &Cases);
251 bool SimplifyEqualityComparisonWithOnlyPredecessor(Instruction *TI,
252 BasicBlock *Pred,
253 IRBuilder<> &Builder);
254 bool PerformValueComparisonIntoPredecessorFolding(Instruction *TI, Value *&CV,
255 Instruction *PTI,
256 IRBuilder<> &Builder);
257 bool FoldValueComparisonIntoPredecessors(Instruction *TI,
258 IRBuilder<> &Builder);
259
260 bool simplifyResume(ResumeInst *RI, IRBuilder<> &Builder);
261 bool simplifySingleResume(ResumeInst *RI);
262 bool simplifyCommonResume(ResumeInst *RI);
263 bool simplifyCleanupReturn(CleanupReturnInst *RI);
264 bool simplifyUnreachable(UnreachableInst *UI);
265 bool simplifySwitch(SwitchInst *SI, IRBuilder<> &Builder);
266 bool simplifyIndirectBr(IndirectBrInst *IBI);
267 bool simplifyBranch(BranchInst *Branch, IRBuilder<> &Builder);
268 bool simplifyUncondBranch(BranchInst *BI, IRBuilder<> &Builder);
269 bool simplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder);
270
271 bool tryToSimplifyUncondBranchWithICmpInIt(ICmpInst *ICI,
272 IRBuilder<> &Builder);
273
274 bool HoistThenElseCodeToIf(BranchInst *BI, const TargetTransformInfo &TTI,
275 bool EqTermsOnly);
276 bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB,
277 const TargetTransformInfo &TTI);
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,
413 InstructionCost &Cost,
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 ConstantExpr::getIntegerCast(CI, PtrTy, /*isSigned=*/false));
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_value(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 (isa<DbgInfoIntrinsic>(BonusInst) || BonusInst.isTerminator())
1104 continue;
1105
1106 Instruction *NewBonusInst = BonusInst.clone();
1107
1108 if (PTI->getDebugLoc() != NewBonusInst->getDebugLoc()) {
1109 // Unless the instruction has the same !dbg location as the original
1110 // branch, drop it. When we fold the bonus instructions we want to make
1111 // sure we reset their debug locations in order to avoid stepping on
1112 // dead code caused by folding dead branches.
1113 NewBonusInst->setDebugLoc(DebugLoc());
1114 }
1115
1116 RemapInstruction(NewBonusInst, VMap,
1118 VMap[&BonusInst] = NewBonusInst;
1119
1120 // If we moved a load, we cannot any longer claim any knowledge about
1121 // its potential value. The previous information might have been valid
1122 // only given the branch precondition.
1123 // For an analogous reason, we must also drop all the metadata whose
1124 // semantics we don't understand. We *can* preserve !annotation, because
1125 // it is tied to the instruction itself, not the value or position.
1126 // Similarly strip attributes on call parameters that may cause UB in
1127 // location the call is moved to.
1129 LLVMContext::MD_annotation);
1130
1131 NewBonusInst->insertInto(PredBlock, PTI->getIterator());
1132 NewBonusInst->takeName(&BonusInst);
1133 BonusInst.setName(NewBonusInst->getName() + ".old");
1134
1135 // Update (liveout) uses of bonus instructions,
1136 // now that the bonus instruction has been cloned into predecessor.
1137 // Note that we expect to be in a block-closed SSA form for this to work!
1138 for (Use &U : make_early_inc_range(BonusInst.uses())) {
1139 auto *UI = cast<Instruction>(U.getUser());
1140 auto *PN = dyn_cast<PHINode>(UI);
1141 if (!PN) {
1142 assert(UI->getParent() == BB && BonusInst.comesBefore(UI) &&
1143 "If the user is not a PHI node, then it should be in the same "
1144 "block as, and come after, the original bonus instruction.");
1145 continue; // Keep using the original bonus instruction.
1146 }
1147 // Is this the block-closed SSA form PHI node?
1148 if (PN->getIncomingBlock(U) == BB)
1149 continue; // Great, keep using the original bonus instruction.
1150 // The only other alternative is an "use" when coming from
1151 // the predecessor block - here we should refer to the cloned bonus instr.
1152 assert(PN->getIncomingBlock(U) == PredBlock &&
1153 "Not in block-closed SSA form?");
1154 U.set(NewBonusInst);
1155 }
1156 }
1157}
1158
1159bool SimplifyCFGOpt::PerformValueComparisonIntoPredecessorFolding(
1160 Instruction *TI, Value *&CV, Instruction *PTI, IRBuilder<> &Builder) {
1161 BasicBlock *BB = TI->getParent();
1162 BasicBlock *Pred = PTI->getParent();
1163
1165
1166 // Figure out which 'cases' to copy from SI to PSI.
1167 std::vector<ValueEqualityComparisonCase> BBCases;
1168 BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
1169
1170 std::vector<ValueEqualityComparisonCase> PredCases;
1171 BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
1172
1173 // Based on whether the default edge from PTI goes to BB or not, fill in
1174 // PredCases and PredDefault with the new switch cases we would like to
1175 // build.
1177
1178 // Update the branch weight metadata along the way
1180 bool PredHasWeights = hasBranchWeightMD(*PTI);
1181 bool SuccHasWeights = hasBranchWeightMD(*TI);
1182
1183 if (PredHasWeights) {
1184 GetBranchWeights(PTI, Weights);
1185 // branch-weight metadata is inconsistent here.
1186 if (Weights.size() != 1 + PredCases.size())
1187 PredHasWeights = SuccHasWeights = false;
1188 } else if (SuccHasWeights)
1189 // If there are no predecessor weights but there are successor weights,
1190 // populate Weights with 1, which will later be scaled to the sum of
1191 // successor's weights
1192 Weights.assign(1 + PredCases.size(), 1);
1193
1194 SmallVector<uint64_t, 8> SuccWeights;
1195 if (SuccHasWeights) {
1196 GetBranchWeights(TI, SuccWeights);
1197 // branch-weight metadata is inconsistent here.
1198 if (SuccWeights.size() != 1 + BBCases.size())
1199 PredHasWeights = SuccHasWeights = false;
1200 } else if (PredHasWeights)
1201 SuccWeights.assign(1 + BBCases.size(), 1);
1202
1203 if (PredDefault == BB) {
1204 // If this is the default destination from PTI, only the edges in TI
1205 // that don't occur in PTI, or that branch to BB will be activated.
1206 std::set<ConstantInt *, ConstantIntOrdering> PTIHandled;
1207 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
1208 if (PredCases[i].Dest != BB)
1209 PTIHandled.insert(PredCases[i].Value);
1210 else {
1211 // The default destination is BB, we don't need explicit targets.
1212 std::swap(PredCases[i], PredCases.back());
1213
1214 if (PredHasWeights || SuccHasWeights) {
1215 // Increase weight for the default case.
1216 Weights[0] += Weights[i + 1];
1217 std::swap(Weights[i + 1], Weights.back());
1218 Weights.pop_back();
1219 }
1220
1221 PredCases.pop_back();
1222 --i;
1223 --e;
1224 }
1225
1226 // Reconstruct the new switch statement we will be building.
1227 if (PredDefault != BBDefault) {
1228 PredDefault->removePredecessor(Pred);
1229 if (DTU && PredDefault != BB)
1230 Updates.push_back({DominatorTree::Delete, Pred, PredDefault});
1231 PredDefault = BBDefault;
1232 ++NewSuccessors[BBDefault];
1233 }
1234
1235 unsigned CasesFromPred = Weights.size();
1236 uint64_t ValidTotalSuccWeight = 0;
1237 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
1238 if (!PTIHandled.count(BBCases[i].Value) && BBCases[i].Dest != BBDefault) {
1239 PredCases.push_back(BBCases[i]);
1240 ++NewSuccessors[BBCases[i].Dest];
1241 if (SuccHasWeights || PredHasWeights) {
1242 // The default weight is at index 0, so weight for the ith case
1243 // should be at index i+1. Scale the cases from successor by
1244 // PredDefaultWeight (Weights[0]).
1245 Weights.push_back(Weights[0] * SuccWeights[i + 1]);
1246 ValidTotalSuccWeight += SuccWeights[i + 1];
1247 }
1248 }
1249
1250 if (SuccHasWeights || PredHasWeights) {
1251 ValidTotalSuccWeight += SuccWeights[0];
1252 // Scale the cases from predecessor by ValidTotalSuccWeight.
1253 for (unsigned i = 1; i < CasesFromPred; ++i)
1254 Weights[i] *= ValidTotalSuccWeight;
1255 // Scale the default weight by SuccDefaultWeight (SuccWeights[0]).
1256 Weights[0] *= SuccWeights[0];
1257 }
1258 } else {
1259 // If this is not the default destination from PSI, only the edges
1260 // in SI that occur in PSI with a destination of BB will be
1261 // activated.
1262 std::set<ConstantInt *, ConstantIntOrdering> PTIHandled;
1263 std::map<ConstantInt *, uint64_t> WeightsForHandled;
1264 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
1265 if (PredCases[i].Dest == BB) {
1266 PTIHandled.insert(PredCases[i].Value);
1267
1268 if (PredHasWeights || SuccHasWeights) {
1269 WeightsForHandled[PredCases[i].Value] = Weights[i + 1];
1270 std::swap(Weights[i + 1], Weights.back());
1271 Weights.pop_back();
1272 }
1273
1274 std::swap(PredCases[i], PredCases.back());
1275 PredCases.pop_back();
1276 --i;
1277 --e;
1278 }
1279
1280 // Okay, now we know which constants were sent to BB from the
1281 // predecessor. Figure out where they will all go now.
1282 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
1283 if (PTIHandled.count(BBCases[i].Value)) {
1284 // If this is one we are capable of getting...
1285 if (PredHasWeights || SuccHasWeights)
1286 Weights.push_back(WeightsForHandled[BBCases[i].Value]);
1287 PredCases.push_back(BBCases[i]);
1288 ++NewSuccessors[BBCases[i].Dest];
1289 PTIHandled.erase(BBCases[i].Value); // This constant is taken care of
1290 }
1291
1292 // If there are any constants vectored to BB that TI doesn't handle,
1293 // they must go to the default destination of TI.
1294 for (ConstantInt *I : PTIHandled) {
1295 if (PredHasWeights || SuccHasWeights)
1296 Weights.push_back(WeightsForHandled[I]);
1297 PredCases.push_back(ValueEqualityComparisonCase(I, BBDefault));
1298 ++NewSuccessors[BBDefault];
1299 }
1300 }
1301
1302 // Okay, at this point, we know which new successor Pred will get. Make
1303 // sure we update the number of entries in the PHI nodes for these
1304 // successors.
1305 SmallPtrSet<BasicBlock *, 2> SuccsOfPred;
1306 if (DTU) {
1307 SuccsOfPred = {succ_begin(Pred), succ_end(Pred)};
1308 Updates.reserve(Updates.size() + NewSuccessors.size());
1309 }
1310 for (const std::pair<BasicBlock *, int /*Num*/> &NewSuccessor :
1311 NewSuccessors) {
1312 for (auto I : seq(0, NewSuccessor.second)) {
1313 (void)I;
1314 AddPredecessorToBlock(NewSuccessor.first, Pred, BB);
1315 }
1316 if (DTU && !SuccsOfPred.contains(NewSuccessor.first))
1317 Updates.push_back({DominatorTree::Insert, Pred, NewSuccessor.first});
1318 }
1319
1320 Builder.SetInsertPoint(PTI);
1321 // Convert pointer to int before we switch.
1322 if (CV->getType()->isPointerTy()) {
1323 CV =
1324 Builder.CreatePtrToInt(CV, DL.getIntPtrType(CV->getType()), "magicptr");
1325 }
1326
1327 // Now that the successors are updated, create the new Switch instruction.
1328 SwitchInst *NewSI = Builder.CreateSwitch(CV, PredDefault, PredCases.size());
1329 NewSI->setDebugLoc(PTI->getDebugLoc());
1330 for (ValueEqualityComparisonCase &V : PredCases)
1331 NewSI->addCase(V.Value, V.Dest);
1332
1333 if (PredHasWeights || SuccHasWeights) {
1334 // Halve the weights if any of them cannot fit in an uint32_t
1335 FitWeights(Weights);
1336
1337 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
1338
1339 setBranchWeights(NewSI, MDWeights);
1340 }
1341
1343
1344 // Okay, last check. If BB is still a successor of PSI, then we must
1345 // have an infinite loop case. If so, add an infinitely looping block
1346 // to handle the case to preserve the behavior of the code.
1347 BasicBlock *InfLoopBlock = nullptr;
1348 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
1349 if (NewSI->getSuccessor(i) == BB) {
1350 if (!InfLoopBlock) {
1351 // Insert it at the end of the function, because it's either code,
1352 // or it won't matter if it's hot. :)
1353 InfLoopBlock =
1354 BasicBlock::Create(BB->getContext(), "infloop", BB->getParent());
1355 BranchInst::Create(InfLoopBlock, InfLoopBlock);
1356 if (DTU)
1357 Updates.push_back(
1358 {DominatorTree::Insert, InfLoopBlock, InfLoopBlock});
1359 }
1360 NewSI->setSuccessor(i, InfLoopBlock);
1361 }
1362
1363 if (DTU) {
1364 if (InfLoopBlock)
1365 Updates.push_back({DominatorTree::Insert, Pred, InfLoopBlock});
1366
1367 Updates.push_back({DominatorTree::Delete, Pred, BB});
1368
1369 DTU->applyUpdates(Updates);
1370 }
1371
1372 ++NumFoldValueComparisonIntoPredecessors;
1373 return true;
1374}
1375
1376/// The specified terminator is a value equality comparison instruction
1377/// (either a switch or a branch on "X == c").
1378/// See if any of the predecessors of the terminator block are value comparisons
1379/// on the same value. If so, and if safe to do so, fold them together.
1380bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(Instruction *TI,
1381 IRBuilder<> &Builder) {
1382 BasicBlock *BB = TI->getParent();
1383 Value *CV = isValueEqualityComparison(TI); // CondVal
1384 assert(CV && "Not a comparison?");
1385
1386 bool Changed = false;
1387
1389 while (!Preds.empty()) {
1390 BasicBlock *Pred = Preds.pop_back_val();
1391 Instruction *PTI = Pred->getTerminator();
1392
1393 // Don't try to fold into itself.
1394 if (Pred == BB)
1395 continue;
1396
1397 // See if the predecessor is a comparison with the same value.
1398 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
1399 if (PCV != CV)
1400 continue;
1401
1403 if (!SafeToMergeTerminators(TI, PTI, &FailBlocks)) {
1404 for (auto *Succ : FailBlocks) {
1405 if (!SplitBlockPredecessors(Succ, TI->getParent(), ".fold.split", DTU))
1406 return false;
1407 }
1408 }
1409
1410 PerformValueComparisonIntoPredecessorFolding(TI, CV, PTI, Builder);
1411 Changed = true;
1412 }
1413 return Changed;
1414}
1415
1416// If we would need to insert a select that uses the value of this invoke
1417// (comments in HoistThenElseCodeToIf explain why we would need to do this), we
1418// can't hoist the invoke, as there is nowhere to put the select in this case.
1420 Instruction *I1, Instruction *I2) {
1421 for (BasicBlock *Succ : successors(BB1)) {
1422 for (const PHINode &PN : Succ->phis()) {
1423 Value *BB1V = PN.getIncomingValueForBlock(BB1);
1424 Value *BB2V = PN.getIncomingValueForBlock(BB2);
1425 if (BB1V != BB2V && (BB1V == I1 || BB2V == I2)) {
1426 return false;
1427 }
1428 }
1429 }
1430 return true;
1431}
1432
1433// Get interesting characteristics of instructions that `HoistThenElseCodeToIf`
1434// didn't hoist. They restrict what kind of instructions can be reordered
1435// across.
1441
1443 unsigned Flags = 0;
1444 if (I->mayReadFromMemory())
1445 Flags |= SkipReadMem;
1446 // We can't arbitrarily move around allocas, e.g. moving allocas (especially
1447 // inalloca) across stacksave/stackrestore boundaries.
1448 if (I->mayHaveSideEffects() || isa<AllocaInst>(I))
1452 return Flags;
1453}
1454
1455// Returns true if it is safe to reorder an instruction across preceding
1456// instructions in a basic block.
1457static bool isSafeToHoistInstr(Instruction *I, unsigned Flags) {
1458 // Don't reorder a store over a load.
1459 if ((Flags & SkipReadMem) && I->mayWriteToMemory())
1460 return false;
1461
1462 // If we have seen an instruction with side effects, it's unsafe to reorder an
1463 // instruction which reads memory or itself has side effects.
1464 if ((Flags & SkipSideEffect) &&
1465 (I->mayReadFromMemory() || I->mayHaveSideEffects()))
1466 return false;
1467
1468 // Reordering across an instruction which does not necessarily transfer
1469 // control to the next instruction is speculation.
1471 return false;
1472
1473 // Hoisting of llvm.deoptimize is only legal together with the next return
1474 // instruction, which this pass is not always able to do.
1475 if (auto *CB = dyn_cast<CallBase>(I))
1476 if (CB->getIntrinsicID() == Intrinsic::experimental_deoptimize)
1477 return false;
1478
1479 // It's also unsafe/illegal to hoist an instruction above its instruction
1480 // operands
1481 BasicBlock *BB = I->getParent();
1482 for (Value *Op : I->operands()) {
1483 if (auto *J = dyn_cast<Instruction>(Op))
1484 if (J->getParent() == BB)
1485 return false;
1486 }
1487
1488 return true;
1489}
1490
1491static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I, bool PtrValueMayBeModified = false);
1492
1493/// Given a conditional branch that goes to BB1 and BB2, hoist any common code
1494/// in the two blocks up into the branch block. The caller of this function
1495/// guarantees that BI's block dominates BB1 and BB2. If EqTermsOnly is given,
1496/// only perform hoisting in case both blocks only contain a terminator. In that
1497/// case, only the original BI will be replaced and selects for PHIs are added.
1498bool SimplifyCFGOpt::HoistThenElseCodeToIf(BranchInst *BI,
1499 const TargetTransformInfo &TTI,
1500 bool EqTermsOnly) {
1501 // This does very trivial matching, with limited scanning, to find identical
1502 // instructions in the two blocks. In particular, we don't want to get into
1503 // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As
1504 // such, we currently just scan for obviously identical instructions in an
1505 // identical order, possibly separated by the same number of non-identical
1506 // instructions.
1507 BasicBlock *BB1 = BI->getSuccessor(0); // The true destination.
1508 BasicBlock *BB2 = BI->getSuccessor(1); // The false destination
1509
1510 // If either of the blocks has it's address taken, then we can't do this fold,
1511 // because the code we'd hoist would no longer run when we jump into the block
1512 // by it's address.
1513 if (BB1->hasAddressTaken() || BB2->hasAddressTaken())
1514 return false;
1515
1516 BasicBlock::iterator BB1_Itr = BB1->begin();
1517 BasicBlock::iterator BB2_Itr = BB2->begin();
1518
1519 Instruction *I1 = &*BB1_Itr++, *I2 = &*BB2_Itr++;
1520 // Skip debug info if it is not identical.
1521 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1522 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1523 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1524 while (isa<DbgInfoIntrinsic>(I1))
1525 I1 = &*BB1_Itr++;
1526 while (isa<DbgInfoIntrinsic>(I2))
1527 I2 = &*BB2_Itr++;
1528 }
1529 if (isa<PHINode>(I1))
1530 return false;
1531
1532 BasicBlock *BIParent = BI->getParent();
1533
1534 bool Changed = false;
1535
1536 auto _ = make_scope_exit([&]() {
1537 if (Changed)
1538 ++NumHoistCommonCode;
1539 });
1540
1541 // Check if only hoisting terminators is allowed. This does not add new
1542 // instructions to the hoist location.
1543 if (EqTermsOnly) {
1544 // Skip any debug intrinsics, as they are free to hoist.
1545 auto *I1NonDbg = &*skipDebugIntrinsics(I1->getIterator());
1546 auto *I2NonDbg = &*skipDebugIntrinsics(I2->getIterator());
1547 if (!I1NonDbg->isIdenticalToWhenDefined(I2NonDbg))
1548 return false;
1549 if (!I1NonDbg->isTerminator())
1550 return false;
1551 // Now we know that we only need to hoist debug intrinsics and the
1552 // terminator. Let the loop below handle those 2 cases.
1553 }
1554
1555 // Count how many instructions were not hoisted so far. There's a limit on how
1556 // many instructions we skip, serving as a compilation time control as well as
1557 // preventing excessive increase of life ranges.
1558 unsigned NumSkipped = 0;
1559
1560 // Record any skipped instuctions that may read memory, write memory or have
1561 // side effects, or have implicit control flow.
1562 unsigned SkipFlagsBB1 = 0;
1563 unsigned SkipFlagsBB2 = 0;
1564
1565 for (;;) {
1566 // If we are hoisting the terminator instruction, don't move one (making a
1567 // broken BB), instead clone it, and remove BI.
1568 if (I1->isTerminator() || I2->isTerminator()) {
1569 // If any instructions remain in the block, we cannot hoist terminators.
1570 if (NumSkipped || !I1->isIdenticalToWhenDefined(I2))
1571 return Changed;
1572 goto HoistTerminator;
1573 }
1574
1575 if (I1->isIdenticalToWhenDefined(I2)) {
1576 // Even if the instructions are identical, it may not be safe to hoist
1577 // them if we have skipped over instructions with side effects or their
1578 // operands weren't hoisted.
1579 if (!isSafeToHoistInstr(I1, SkipFlagsBB1) ||
1580 !isSafeToHoistInstr(I2, SkipFlagsBB2))
1581 return Changed;
1582
1583 // If we're going to hoist a call, make sure that the two instructions
1584 // we're commoning/hoisting are both marked with musttail, or neither of
1585 // them is marked as such. Otherwise, we might end up in a situation where
1586 // we hoist from a block where the terminator is a `ret` to a block where
1587 // the terminator is a `br`, and `musttail` calls expect to be followed by
1588 // a return.
1589 auto *C1 = dyn_cast<CallInst>(I1);
1590 auto *C2 = dyn_cast<CallInst>(I2);
1591 if (C1 && C2)
1592 if (C1->isMustTailCall() != C2->isMustTailCall())
1593 return Changed;
1594
1596 return Changed;
1597
1598 // If any of the two call sites has nomerge or convergent attribute, stop
1599 // hoisting.
1600 if (const auto *CB1 = dyn_cast<CallBase>(I1))
1601 if (CB1->cannotMerge() || CB1->isConvergent())
1602 return Changed;
1603 if (const auto *CB2 = dyn_cast<CallBase>(I2))
1604 if (CB2->cannotMerge() || CB2->isConvergent())
1605 return Changed;
1606
1607 if (isa<DbgInfoIntrinsic>(I1) || isa<DbgInfoIntrinsic>(I2)) {
1608 assert(isa<DbgInfoIntrinsic>(I1) && isa<DbgInfoIntrinsic>(I2));
1609 // The debug location is an integral part of a debug info intrinsic
1610 // and can't be separated from it or replaced. Instead of attempting
1611 // to merge locations, simply hoist both copies of the intrinsic.
1612 BIParent->splice(BI->getIterator(), BB1, I1->getIterator());
1613 BIParent->splice(BI->getIterator(), BB2, I2->getIterator());
1614 } else {
1615 // For a normal instruction, we just move one to right before the
1616 // branch, then replace all uses of the other with the first. Finally,
1617 // we remove the now redundant second instruction.
1618 BIParent->splice(BI->getIterator(), BB1, I1->getIterator());
1619 if (!I2->use_empty())
1620 I2->replaceAllUsesWith(I1);
1621 I1->andIRFlags(I2);
1622 combineMetadataForCSE(I1, I2, true);
1623
1624 // I1 and I2 are being combined into a single instruction. Its debug
1625 // location is the merged locations of the original instructions.
1626 I1->applyMergedLocation(I1->getDebugLoc(), I2->getDebugLoc());
1627
1628 I2->eraseFromParent();
1629 }
1630 Changed = true;
1631 ++NumHoistCommonInstrs;
1632 } else {
1633 if (NumSkipped >= HoistCommonSkipLimit)
1634 return Changed;
1635 // We are about to skip over a pair of non-identical instructions. Record
1636 // if any have characteristics that would prevent reordering instructions
1637 // across them.
1638 SkipFlagsBB1 |= skippedInstrFlags(I1);
1639 SkipFlagsBB2 |= skippedInstrFlags(I2);
1640 ++NumSkipped;
1641 }
1642
1643 I1 = &*BB1_Itr++;
1644 I2 = &*BB2_Itr++;
1645 // Skip debug info if it is not identical.
1646 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1647 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1648 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1649 while (isa<DbgInfoIntrinsic>(I1))
1650 I1 = &*BB1_Itr++;
1651 while (isa<DbgInfoIntrinsic>(I2))
1652 I2 = &*BB2_Itr++;
1653 }
1654 }
1655
1656 return Changed;
1657
1658HoistTerminator:
1659 // It may not be possible to hoist an invoke.
1660 // FIXME: Can we define a safety predicate for CallBr?
1661 if (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2))
1662 return Changed;
1663
1664 // TODO: callbr hoisting currently disabled pending further study.
1665 if (isa<CallBrInst>(I1))
1666 return Changed;
1667
1668 for (BasicBlock *Succ : successors(BB1)) {
1669 for (PHINode &PN : Succ->phis()) {
1670 Value *BB1V = PN.getIncomingValueForBlock(BB1);
1671 Value *BB2V = PN.getIncomingValueForBlock(BB2);
1672 if (BB1V == BB2V)
1673 continue;
1674
1675 // Check for passingValueIsAlwaysUndefined here because we would rather
1676 // eliminate undefined control flow then converting it to a select.
1677 if (passingValueIsAlwaysUndefined(BB1V, &PN) ||
1679 return Changed;
1680 }
1681 }
1682
1683 // Okay, it is safe to hoist the terminator.
1684 Instruction *NT = I1->clone();
1685 NT->insertInto(BIParent, BI->getIterator());
1686 if (!NT->getType()->isVoidTy()) {
1687 I1->replaceAllUsesWith(NT);
1688 I2->replaceAllUsesWith(NT);
1689 NT->takeName(I1);
1690 }
1691 Changed = true;
1692 ++NumHoistCommonInstrs;
1693
1694 // Ensure terminator gets a debug location, even an unknown one, in case
1695 // it involves inlinable calls.
1696 NT->applyMergedLocation(I1->getDebugLoc(), I2->getDebugLoc());
1697
1698 // PHIs created below will adopt NT's merged DebugLoc.
1700
1701 // Hoisting one of the terminators from our successor is a great thing.
1702 // Unfortunately, the successors of the if/else blocks may have PHI nodes in
1703 // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI
1704 // nodes, so we insert select instruction to compute the final result.
1705 std::map<std::pair<Value *, Value *>, SelectInst *> InsertedSelects;
1706 for (BasicBlock *Succ : successors(BB1)) {
1707 for (PHINode &PN : Succ->phis()) {
1708 Value *BB1V = PN.getIncomingValueForBlock(BB1);
1709 Value *BB2V = PN.getIncomingValueForBlock(BB2);
1710 if (BB1V == BB2V)
1711 continue;
1712
1713 // These values do not agree. Insert a select instruction before NT
1714 // that determines the right value.
1715 SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
1716 if (!SI) {
1717 // Propagate fast-math-flags from phi node to its replacement select.
1718 IRBuilder<>::FastMathFlagGuard FMFGuard(Builder);
1719 if (isa<FPMathOperator>(PN))
1720 Builder.setFastMathFlags(PN.getFastMathFlags());
1721
1722 SI = cast<SelectInst>(
1723 Builder.CreateSelect(BI->getCondition(), BB1V, BB2V,
1724 BB1V->getName() + "." + BB2V->getName(), BI));
1725 }
1726
1727 // Make the PHI node use the select for all incoming values for BB1/BB2
1728 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
1729 if (PN.getIncomingBlock(i) == BB1 || PN.getIncomingBlock(i) == BB2)
1730 PN.setIncomingValue(i, SI);
1731 }
1732 }
1733
1735
1736 // Update any PHI nodes in our new successors.
1737 for (BasicBlock *Succ : successors(BB1)) {
1738 AddPredecessorToBlock(Succ, BIParent, BB1);
1739 if (DTU)
1740 Updates.push_back({DominatorTree::Insert, BIParent, Succ});
1741 }
1742
1743 if (DTU)
1744 for (BasicBlock *Succ : successors(BI))
1745 Updates.push_back({DominatorTree::Delete, BIParent, Succ});
1746
1748 if (DTU)
1749 DTU->applyUpdates(Updates);
1750 return Changed;
1751}
1752
1753// Check lifetime markers.
1754static bool isLifeTimeMarker(const Instruction *I) {
1755 if (auto II = dyn_cast<IntrinsicInst>(I)) {
1756 switch (II->getIntrinsicID()) {
1757 default:
1758 break;
1759 case Intrinsic::lifetime_start:
1760 case Intrinsic::lifetime_end:
1761 return true;
1762 }
1763 }
1764 return false;
1765}
1766
1767// TODO: Refine this. This should avoid cases like turning constant memcpy sizes
1768// into variables.
1770 int OpIdx) {
1771 return !isa<IntrinsicInst>(I);
1772}
1773
1774// All instructions in Insts belong to different blocks that all unconditionally
1775// branch to a common successor. Analyze each instruction and return true if it
1776// would be possible to sink them into their successor, creating one common
1777// instruction instead. For every value that would be required to be provided by
1778// PHI node (because an operand varies in each input block), add to PHIOperands.
1781 DenseMap<Instruction *, SmallVector<Value *, 4>> &PHIOperands) {
1782 // Prune out obviously bad instructions to move. Each instruction must have
1783 // exactly zero or one use, and we check later that use is by a single, common
1784 // PHI instruction in the successor.
1785 bool HasUse = !Insts.front()->user_empty();
1786 for (auto *I : Insts) {
1787 // These instructions may change or break semantics if moved.
1788 if (isa<PHINode>(I) || I->isEHPad() || isa<AllocaInst>(I) ||
1789 I->getType()->isTokenTy())
1790 return false;
1791
1792 // Do not try to sink an instruction in an infinite loop - it can cause
1793 // this algorithm to infinite loop.
1794 if (I->getParent()->getSingleSuccessor() == I->getParent())
1795 return false;
1796
1797 // Conservatively return false if I is an inline-asm instruction. Sinking
1798 // and merging inline-asm instructions can potentially create arguments
1799 // that cannot satisfy the inline-asm constraints.
1800 // If the instruction has nomerge or convergent attribute, return false.
1801 if (const auto *C = dyn_cast<CallBase>(I))
1802 if (C->isInlineAsm() || C->cannotMerge() || C->isConvergent())
1803 return false;
1804
1805 // Each instruction must have zero or one use.
1806 if (HasUse && !I->hasOneUse())
1807 return false;
1808 if (!HasUse && !I->user_empty())
1809 return false;
1810 }
1811
1812 const Instruction *I0 = Insts.front();
1813 for (auto *I : Insts)
1814 if (!I->isSameOperationAs(I0))
1815 return false;
1816
1817 // All instructions in Insts are known to be the same opcode. If they have a
1818 // use, check that the only user is a PHI or in the same block as the
1819 // instruction, because if a user is in the same block as an instruction we're
1820 // contemplating sinking, it must already be determined to be sinkable.
1821 if (HasUse) {
1822 auto *PNUse = dyn_cast<PHINode>(*I0->user_begin());
1823 auto *Succ = I0->getParent()->getTerminator()->getSuccessor(0);
1824 if (!all_of(Insts, [&PNUse,&Succ](const Instruction *I) -> bool {
1825 auto *U = cast<Instruction>(*I->user_begin());
1826 return (PNUse &&
1827 PNUse->getParent() == Succ &&
1828 PNUse->getIncomingValueForBlock(I->getParent()) == I) ||
1829 U->getParent() == I->getParent();
1830 }))
1831 return false;
1832 }
1833
1834 // Because SROA can't handle speculating stores of selects, try not to sink
1835 // loads, stores or lifetime markers of allocas when we'd have to create a
1836 // PHI for the address operand. Also, because it is likely that loads or
1837 // stores of allocas will disappear when Mem2Reg/SROA is run, don't sink
1838 // them.
1839 // This can cause code churn which can have unintended consequences down
1840 // the line - see https://llvm.org/bugs/show_bug.cgi?id=30244.
1841 // FIXME: This is a workaround for a deficiency in SROA - see
1842 // https://llvm.org/bugs/show_bug.cgi?id=30188
1843 if (isa<StoreInst>(I0) && any_of(Insts, [](const Instruction *I) {
1844 return isa<AllocaInst>(I->getOperand(1)->stripPointerCasts());
1845 }))
1846 return false;
1847 if (isa<LoadInst>(I0) && any_of(Insts, [](const Instruction *I) {
1848 return isa<AllocaInst>(I->getOperand(0)->stripPointerCasts());
1849 }))
1850 return false;
1851 if (isLifeTimeMarker(I0) && any_of(Insts, [](const Instruction *I) {
1852 return isa<AllocaInst>(I->getOperand(1)->stripPointerCasts());
1853 }))
1854 return false;
1855
1856 // For calls to be sinkable, they must all be indirect, or have same callee.
1857 // I.e. if we have two direct calls to different callees, we don't want to
1858 // turn that into an indirect call. Likewise, if we have an indirect call,
1859 // and a direct call, we don't actually want to have a single indirect call.
1860 if (isa<CallBase>(I0)) {
1861 auto IsIndirectCall = [](const Instruction *I) {
1862 return cast<CallBase>(I)->isIndirectCall();
1863 };
1864 bool HaveIndirectCalls = any_of(Insts, IsIndirectCall);
1865 bool AllCallsAreIndirect = all_of(Insts, IsIndirectCall);
1866 if (HaveIndirectCalls) {
1867 if (!AllCallsAreIndirect)
1868 return false;
1869 } else {
1870 // All callees must be identical.
1871 Value *Callee = nullptr;
1872 for (const Instruction *I : Insts) {
1873 Value *CurrCallee = cast<CallBase>(I)->getCalledOperand();
1874 if (!Callee)
1875 Callee = CurrCallee;
1876 else if (Callee != CurrCallee)
1877 return false;
1878 }
1879 }
1880 }
1881
1882 for (unsigned OI = 0, OE = I0->getNumOperands(); OI != OE; ++OI) {
1883 Value *Op = I0->getOperand(OI);
1884 if (Op->getType()->isTokenTy())
1885 // Don't touch any operand of token type.
1886 return false;
1887
1888 auto SameAsI0 = [&I0, OI](const Instruction *I) {
1889 assert(I->getNumOperands() == I0->getNumOperands());
1890 return I->getOperand(OI) == I0->getOperand(OI);
1891 };
1892 if (!all_of(Insts, SameAsI0)) {
1893 if ((isa<Constant>(Op) && !replacingOperandWithVariableIsCheap(I0, OI)) ||
1895 // We can't create a PHI from this GEP.
1896 return false;
1897 for (auto *I : Insts)
1898 PHIOperands[I].push_back(I->getOperand(OI));
1899 }
1900 }
1901 return true;
1902}
1903
1904// Assuming canSinkInstructions(Blocks) has returned true, sink the last
1905// instruction of every block in Blocks to their common successor, commoning
1906// into one instruction.
1908 auto *BBEnd = Blocks[0]->getTerminator()->getSuccessor(0);
1909
1910 // canSinkInstructions returning true guarantees that every block has at
1911 // least one non-terminator instruction.
1913 for (auto *BB : Blocks) {
1914 Instruction *I = BB->getTerminator();
1915 do {
1916 I = I->getPrevNode();
1917 } while (isa<DbgInfoIntrinsic>(I) && I != &BB->front());
1918 if (!isa<DbgInfoIntrinsic>(I))
1919 Insts.push_back(I);
1920 }
1921
1922 // The only checking we need to do now is that all users of all instructions
1923 // are the same PHI node. canSinkInstructions should have checked this but
1924 // it is slightly over-aggressive - it gets confused by commutative
1925 // instructions so double-check it here.
1926 Instruction *I0 = Insts.front();
1927 if (!I0->user_empty()) {
1928 auto *PNUse = dyn_cast<PHINode>(*I0->user_begin());
1929 if (!all_of(Insts, [&PNUse](const Instruction *I) -> bool {
1930 auto *U = cast<Instruction>(*I->user_begin());
1931 return U == PNUse;
1932 }))
1933 return false;
1934 }
1935
1936 // We don't need to do any more checking here; canSinkInstructions should
1937 // have done it all for us.
1938 SmallVector<Value*, 4> NewOperands;
1939 for (unsigned O = 0, E = I0->getNumOperands(); O != E; ++O) {
1940 // This check is different to that in canSinkInstructions. There, we
1941 // cared about the global view once simplifycfg (and instcombine) have
1942 // completed - it takes into account PHIs that become trivially
1943 // simplifiable. However here we need a more local view; if an operand
1944 // differs we create a PHI and rely on instcombine to clean up the very
1945 // small mess we may make.
1946 bool NeedPHI = any_of(Insts, [&I0, O](const Instruction *I) {
1947 return I->getOperand(O) != I0->getOperand(O);
1948 });
1949 if (!NeedPHI) {
1950 NewOperands.push_back(I0->getOperand(O));
1951 continue;
1952 }
1953
1954 // Create a new PHI in the successor block and populate it.
1955 auto *Op = I0->getOperand(O);
1956 assert(!Op->getType()->isTokenTy() && "Can't PHI tokens!");
1957 auto *PN = PHINode::Create(Op->getType(), Insts.size(),
1958 Op->getName() + ".sink", &BBEnd->front());
1959 for (auto *I : Insts)
1960 PN->addIncoming(I->getOperand(O), I->getParent());
1961 NewOperands.push_back(PN);
1962 }
1963
1964 // Arbitrarily use I0 as the new "common" instruction; remap its operands
1965 // and move it to the start of the successor block.
1966 for (unsigned O = 0, E = I0->getNumOperands(); O != E; ++O)
1967 I0->getOperandUse(O).set(NewOperands[O]);
1968 I0->moveBefore(&*BBEnd->getFirstInsertionPt());
1969
1970 // Update metadata and IR flags, and merge debug locations.
1971 for (auto *I : Insts)
1972 if (I != I0) {
1973 // The debug location for the "common" instruction is the merged locations
1974 // of all the commoned instructions. We start with the original location
1975 // of the "common" instruction and iteratively merge each location in the
1976 // loop below.
1977 // This is an N-way merge, which will be inefficient if I0 is a CallInst.
1978 // However, as N-way merge for CallInst is rare, so we use simplified API
1979 // instead of using complex API for N-way merge.
1980 I0->applyMergedLocation(I0->getDebugLoc(), I->getDebugLoc());
1981 combineMetadataForCSE(I0, I, true);
1982 I0->andIRFlags(I);
1983 }
1984
1985 if (!I0->user_empty()) {
1986 // canSinkLastInstruction checked that all instructions were used by
1987 // one and only one PHI node. Find that now, RAUW it to our common
1988 // instruction and nuke it.
1989 auto *PN = cast<PHINode>(*I0->user_begin());
1990 PN->replaceAllUsesWith(I0);
1991 PN->eraseFromParent();
1992 }
1993
1994 // Finally nuke all instructions apart from the common instruction.
1995 for (auto *I : Insts) {
1996 if (I == I0)
1997 continue;
1998 // The remaining uses are debug users, replace those with the common inst.
1999 // In most (all?) cases this just introduces a use-before-def.
2000 assert(I->user_empty() && "Inst unexpectedly still has non-dbg users");
2001 I->replaceAllUsesWith(I0);
2002 I->eraseFromParent();
2003 }
2004
2005 return true;
2006}
2007
2008namespace {
2009
2010 // LockstepReverseIterator - Iterates through instructions
2011 // in a set of blocks in reverse order from the first non-terminator.
2012 // For example (assume all blocks have size n):
2013 // LockstepReverseIterator I([B1, B2, B3]);
2014 // *I-- = [B1[n], B2[n], B3[n]];
2015 // *I-- = [B1[n-1], B2[n-1], B3[n-1]];
2016 // *I-- = [B1[n-2], B2[n-2], B3[n-2]];
2017 // ...
2018 class LockstepReverseIterator {
2019 ArrayRef<BasicBlock*> Blocks;
2021 bool Fail;
2022
2023 public:
2024 LockstepReverseIterator(ArrayRef<BasicBlock*> Blocks) : Blocks(Blocks) {
2025 reset();
2026 }
2027
2028 void reset() {
2029 Fail = false;
2030 Insts.clear();
2031 for (auto *BB : Blocks) {
2032 Instruction *Inst = BB->getTerminator();
2033 for (Inst = Inst->getPrevNode(); Inst && isa<DbgInfoIntrinsic>(Inst);)
2034 Inst = Inst->getPrevNode();
2035 if (!Inst) {
2036 // Block wasn't big enough.
2037 Fail = true;
2038 return;
2039 }
2040 Insts.push_back(Inst);
2041 }
2042 }
2043
2044 bool isValid() const {
2045 return !Fail;
2046 }
2047
2048 void operator--() {
2049 if (Fail)
2050 return;
2051 for (auto *&Inst : Insts) {
2052 for (Inst = Inst->getPrevNode(); Inst && isa<DbgInfoIntrinsic>(Inst);)
2053 Inst = Inst->getPrevNode();
2054 // Already at beginning of block.
2055 if (!Inst) {
2056 Fail = true;
2057 return;
2058 }
2059 }
2060 }
2061
2062 void operator++() {
2063 if (Fail)
2064 return;
2065 for (auto *&Inst : Insts) {
2066 for (Inst = Inst->getNextNode(); Inst && isa<DbgInfoIntrinsic>(Inst);)
2067 Inst = Inst->getNextNode();
2068 // Already at end of block.
2069 if (!Inst) {
2070 Fail = true;
2071 return;
2072 }
2073 }
2074 }
2075
2077 return Insts;
2078 }
2079 };
2080
2081} // end anonymous namespace
2082
2083/// Check whether BB's predecessors end with unconditional branches. If it is
2084/// true, sink any common code from the predecessors to BB.
2086 DomTreeUpdater *DTU) {
2087 // We support two situations:
2088 // (1) all incoming arcs are unconditional
2089 // (2) there are non-unconditional incoming arcs
2090 //
2091 // (2) is very common in switch defaults and
2092 // else-if patterns;
2093 //
2094 // if (a) f(1);
2095 // else if (b) f(2);
2096 //
2097 // produces:
2098 //
2099 // [if]
2100 // / \
2101 // [f(1)] [if]
2102 // | | \
2103 // | | |
2104 // | [f(2)]|
2105 // \ | /
2106 // [ end ]
2107 //
2108 // [end] has two unconditional predecessor arcs and one conditional. The
2109 // conditional refers to the implicit empty 'else' arc. This conditional
2110 // arc can also be caused by an empty default block in a switch.
2111 //
2112 // In this case, we attempt to sink code from all *unconditional* arcs.
2113 // If we can sink instructions from these arcs (determined during the scan
2114 // phase below) we insert a common successor for all unconditional arcs and
2115 // connect that to [end], to enable sinking:
2116 //
2117 // [if]
2118 // / \
2119 // [x(1)] [if]
2120 // | | \
2121 // | | \
2122 // | [x(2)] |
2123 // \ / |
2124 // [sink.split] |
2125 // \ /
2126 // [ end ]
2127 //
2128 SmallVector<BasicBlock*,4> UnconditionalPreds;
2129 bool HaveNonUnconditionalPredecessors = false;
2130 for (auto *PredBB : predecessors(BB)) {
2131 auto *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator());
2132 if (PredBr && PredBr->isUnconditional())
2133 UnconditionalPreds.push_back(PredBB);
2134 else
2135 HaveNonUnconditionalPredecessors = true;
2136 }
2137 if (UnconditionalPreds.size() < 2)
2138 return false;
2139
2140 // We take a two-step approach to tail sinking. First we scan from the end of
2141 // each block upwards in lockstep. If the n'th instruction from the end of each
2142 // block can be sunk, those instructions are added to ValuesToSink and we
2143 // carry on. If we can sink an instruction but need to PHI-merge some operands
2144 // (because they're not identical in each instruction) we add these to
2145 // PHIOperands.
2146 int ScanIdx = 0;
2147 SmallPtrSet<Value*,4> InstructionsToSink;
2149 LockstepReverseIterator LRI(UnconditionalPreds);
2150 while (LRI.isValid() &&
2151 canSinkInstructions(*LRI, PHIOperands)) {
2152 LLVM_DEBUG(dbgs() << "SINK: instruction can be sunk: " << *(*LRI)[0]
2153 << "\n");
2154 InstructionsToSink.insert((*LRI).begin(), (*LRI).end());
2155 ++ScanIdx;
2156 --LRI;
2157 }
2158
2159 // If no instructions can be sunk, early-return.
2160 if (ScanIdx == 0)
2161 return false;
2162
2163 bool followedByDeoptOrUnreachable = IsBlockFollowedByDeoptOrUnreachable(BB);
2164
2165 if (!followedByDeoptOrUnreachable) {
2166 // Okay, we *could* sink last ScanIdx instructions. But how many can we
2167 // actually sink before encountering instruction that is unprofitable to
2168 // sink?
2169 auto ProfitableToSinkInstruction = [&](LockstepReverseIterator &LRI) {
2170 unsigned NumPHIdValues = 0;
2171 for (auto *I : *LRI)
2172 for (auto *V : PHIOperands[I]) {
2173 if (!InstructionsToSink.contains(V))
2174 ++NumPHIdValues;
2175 // FIXME: this check is overly optimistic. We may end up not sinking
2176 // said instruction, due to the very same profitability check.
2177 // See @creating_too_many_phis in sink-common-code.ll.
2178 }
2179 LLVM_DEBUG(dbgs() << "SINK: #phid values: " << NumPHIdValues << "\n");
2180 unsigned NumPHIInsts = NumPHIdValues / UnconditionalPreds.size();
2181 if ((NumPHIdValues % UnconditionalPreds.size()) != 0)
2182 NumPHIInsts++;
2183
2184 return NumPHIInsts <= 1;
2185 };
2186
2187 // We've determined that we are going to sink last ScanIdx instructions,
2188 // and recorded them in InstructionsToSink. Now, some instructions may be
2189 // unprofitable to sink. But that determination depends on the instructions
2190 // that we are going to sink.
2191
2192 // First, forward scan: find the first instruction unprofitable to sink,
2193 // recording all the ones that are profitable to sink.
2194 // FIXME: would it be better, after we detect that not all are profitable.
2195 // to either record the profitable ones, or erase the unprofitable ones?
2196 // Maybe we need to choose (at runtime) the one that will touch least
2197 // instrs?
2198 LRI.reset();
2199 int Idx = 0;
2200 SmallPtrSet<Value *, 4> InstructionsProfitableToSink;
2201 while (Idx < ScanIdx) {
2202 if (!ProfitableToSinkInstruction(LRI)) {
2203 // Too many PHIs would be created.
2204 LLVM_DEBUG(
2205 dbgs() << "SINK: stopping here, too many PHIs would be created!\n");
2206 break;
2207 }
2208 InstructionsProfitableToSink.insert((*LRI).begin(), (*LRI).end());
2209 --LRI;
2210 ++Idx;
2211 }
2212
2213 // If no instructions can be sunk, early-return.
2214 if (Idx == 0)
2215 return false;
2216
2217 // Did we determine that (only) some instructions are unprofitable to sink?
2218 if (Idx < ScanIdx) {
2219 // Okay, some instructions are unprofitable.
2220 ScanIdx = Idx;
2221 InstructionsToSink = InstructionsProfitableToSink;
2222
2223 // But, that may make other instructions unprofitable, too.
2224 // So, do a backward scan, do any earlier instructions become
2225 // unprofitable?
2226 assert(
2227 !ProfitableToSinkInstruction(LRI) &&
2228 "We already know that the last instruction is unprofitable to sink");
2229 ++LRI;
2230 --Idx;
2231 while (Idx >= 0) {
2232 // If we detect that an instruction becomes unprofitable to sink,
2233 // all earlier instructions won't be sunk either,
2234 // so preemptively keep InstructionsProfitableToSink in sync.
2235 // FIXME: is this the most performant approach?
2236 for (auto *I : *LRI)
2237 InstructionsProfitableToSink.erase(I);
2238 if (!ProfitableToSinkInstruction(LRI)) {
2239 // Everything starting with this instruction won't be sunk.
2240 ScanIdx = Idx;
2241 InstructionsToSink = InstructionsProfitableToSink;
2242 }
2243 ++LRI;
2244 --Idx;
2245 }
2246 }
2247
2248 // If no instructions can be sunk, early-return.
2249 if (ScanIdx == 0)
2250 return false;
2251 }
2252
2253 bool Changed = false;
2254
2255 if (HaveNonUnconditionalPredecessors) {
2256 if (!followedByDeoptOrUnreachable) {
2257 // It is always legal to sink common instructions from unconditional
2258 // predecessors. However, if not all predecessors are unconditional,
2259 // this transformation might be pessimizing. So as a rule of thumb,
2260 // don't do it unless we'd sink at least one non-speculatable instruction.
2261 // See https://bugs.llvm.org/show_bug.cgi?id=30244
2262 LRI.reset();
2263 int Idx = 0;
2264 bool Profitable = false;
2265 while (Idx < ScanIdx) {
2266 if (!isSafeToSpeculativelyExecute((*LRI)[0])) {
2267 Profitable = true;
2268 break;
2269 }
2270 --LRI;
2271 ++Idx;
2272 }
2273 if (!Profitable)
2274 return false;
2275 }
2276
2277 LLVM_DEBUG(dbgs() << "SINK: Splitting edge\n");
2278 // We have a conditional edge and we're going to sink some instructions.
2279 // Insert a new block postdominating all blocks we're going to sink from.
2280 if (!SplitBlockPredecessors(BB, UnconditionalPreds, ".sink.split", DTU))
2281 // Edges couldn't be split.
2282 return false;
2283 Changed = true;
2284 }
2285
2286 // Now that we've analyzed all potential sinking candidates, perform the
2287 // actual sink. We iteratively sink the last non-terminator of the source
2288 // blocks into their common successor unless doing so would require too
2289 // many PHI instructions to be generated (currently only one PHI is allowed
2290 // per sunk instruction).
2291 //
2292 // We can use InstructionsToSink to discount values needing PHI-merging that will
2293 // actually be sunk in a later iteration. This allows us to be more
2294 // aggressive in what we sink. This does allow a false positive where we
2295 // sink presuming a later value will also be sunk, but stop half way through
2296 // and never actually sink it which means we produce more PHIs than intended.
2297 // This is unlikely in practice though.
2298 int SinkIdx = 0;
2299 for (; SinkIdx != ScanIdx; ++SinkIdx) {
2300 LLVM_DEBUG(dbgs() << "SINK: Sink: "
2301 << *UnconditionalPreds[0]->getTerminator()->getPrevNode()
2302 << "\n");
2303
2304 // Because we've sunk every instruction in turn, the current instruction to
2305 // sink is always at index 0.
2306 LRI.reset();
2307
2308 if (!sinkLastInstruction(UnconditionalPreds)) {
2309 LLVM_DEBUG(
2310 dbgs()
2311 << "SINK: stopping here, failed to actually sink instruction!\n");
2312 break;
2313 }
2314
2315 NumSinkCommonInstrs++;
2316 Changed = true;
2317 }
2318 if (SinkIdx != 0)
2319 ++NumSinkCommonCode;
2320 return Changed;
2321}
2322
2323namespace {
2324
2325struct CompatibleSets {
2326 using SetTy = SmallVector<InvokeInst *, 2>;
2327
2329
2330 static bool shouldBelongToSameSet(ArrayRef<InvokeInst *> Invokes);
2331
2332 SetTy &getCompatibleSet(InvokeInst *II);
2333
2334 void insert(InvokeInst *II);
2335};
2336
2337CompatibleSets::SetTy &CompatibleSets::getCompatibleSet(InvokeInst *II) {
2338 // Perform a linear scan over all the existing sets, see if the new `invoke`
2339 // is compatible with any particular set. Since we know that all the `invokes`
2340 // within a set are compatible, only check the first `invoke` in each set.
2341 // WARNING: at worst, this has quadratic complexity.
2342 for (CompatibleSets::SetTy &Set : Sets) {
2343 if (CompatibleSets::shouldBelongToSameSet({Set.front(), II}))
2344 return Set;
2345 }
2346
2347 // Otherwise, we either had no sets yet, or this invoke forms a new set.
2348 return Sets.emplace_back();
2349}
2350
2351void CompatibleSets::insert(InvokeInst *II) {
2352 getCompatibleSet(II).emplace_back(II);
2353}
2354
2355bool CompatibleSets::shouldBelongToSameSet(ArrayRef<InvokeInst *> Invokes) {
2356 assert(Invokes.size() == 2 && "Always called with exactly two candidates.");
2357
2358 // Can we theoretically merge these `invoke`s?
2359 auto IsIllegalToMerge = [](InvokeInst *II) {
2360 return II->cannotMerge() || II->isInlineAsm();
2361 };
2362 if (any_of(Invokes, IsIllegalToMerge))
2363 return false;
2364
2365 // Either both `invoke`s must be direct,
2366 // or both `invoke`s must be indirect.
2367 auto IsIndirectCall = [](InvokeInst *II) { return II->isIndirectCall(); };
2368 bool HaveIndirectCalls = any_of(Invokes, IsIndirectCall);
2369 bool AllCallsAreIndirect = all_of(Invokes, IsIndirectCall);
2370 if (HaveIndirectCalls) {
2371 if (!AllCallsAreIndirect)
2372 return false;
2373 } else {
2374 // All callees must be identical.
2375 Value *Callee = nullptr;
2376 for (InvokeInst *II : Invokes) {
2377 Value *CurrCallee = II->getCalledOperand();
2378 assert(CurrCallee && "There is always a called operand.");
2379 if (!Callee)
2380 Callee = CurrCallee;
2381 else if (Callee != CurrCallee)
2382 return false;
2383 }
2384 }
2385
2386 // Either both `invoke`s must not have a normal destination,
2387 // or both `invoke`s must have a normal destination,
2388 auto HasNormalDest = [](InvokeInst *II) {
2389 return !isa<UnreachableInst>(II->getNormalDest()->getFirstNonPHIOrDbg());
2390 };
2391 if (any_of(Invokes, HasNormalDest)) {
2392 // Do not merge `invoke` that does not have a normal destination with one
2393 // that does have a normal destination, even though doing so would be legal.
2394 if (!all_of(Invokes, HasNormalDest))
2395 return false;
2396
2397 // All normal destinations must be identical.
2398 BasicBlock *NormalBB = nullptr;
2399 for (InvokeInst *II : Invokes) {
2400 BasicBlock *CurrNormalBB = II->getNormalDest();
2401 assert(CurrNormalBB && "There is always a 'continue to' basic block.");
2402 if (!NormalBB)
2403 NormalBB = CurrNormalBB;
2404 else if (NormalBB != CurrNormalBB)
2405 return false;
2406 }
2407
2408 // In the normal destination, the incoming values for these two `invoke`s
2409 // must be compatible.
2410 SmallPtrSet<Value *, 16> EquivalenceSet(Invokes.begin(), Invokes.end());
2412 NormalBB, {Invokes[0]->getParent(), Invokes[1]->getParent()},
2413 &EquivalenceSet))
2414 return false;
2415 }
2416
2417#ifndef NDEBUG
2418 // All unwind destinations must be identical.
2419 // We know that because we have started from said unwind destination.
2420 BasicBlock *UnwindBB = nullptr;
2421 for (InvokeInst *II : Invokes) {
2422 BasicBlock *CurrUnwindBB = II->getUnwindDest();
2423 assert(CurrUnwindBB && "There is always an 'unwind to' basic block.");
2424 if (!UnwindBB)
2425 UnwindBB = CurrUnwindBB;
2426 else
2427 assert(UnwindBB == CurrUnwindBB && "Unexpected unwind destination.");
2428 }
2429#endif
2430
2431 // In the unwind destination, the incoming values for these two `invoke`s
2432 // must be compatible.
2434 Invokes.front()->getUnwindDest(),
2435 {Invokes[0]->getParent(), Invokes[1]->getParent()}))
2436 return false;
2437
2438 // Ignoring arguments, these `invoke`s must be identical,
2439 // including operand bundles.
2440 const InvokeInst *II0 = Invokes.front();
2441 for (auto *II : Invokes.drop_front())
2442 if (!II->isSameOperationAs(II0))
2443 return false;
2444
2445 // Can we theoretically form the data operands for the merged `invoke`?
2446 auto IsIllegalToMergeArguments = [](auto Ops) {
2447 Type *Ty = std::get<0>(Ops)->getType();
2448 assert(Ty == std::get<1>(Ops)->getType() && "Incompatible types?");
2449 return Ty->isTokenTy() && std::get<0>(Ops) != std::get<1>(Ops);
2450 };
2451 assert(Invokes.size() == 2 && "Always called with exactly two candidates.");
2452 if (any_of(zip(Invokes[0]->data_ops(), Invokes[1]->data_ops()),
2453 IsIllegalToMergeArguments))
2454 return false;
2455
2456 return true;
2457}
2458
2459} // namespace
2460
2461// Merge all invokes in the provided set, all of which are compatible
2462// as per the `CompatibleSets::shouldBelongToSameSet()`.
2464 DomTreeUpdater *DTU) {
2465 assert(Invokes.size() >= 2 && "Must have at least two invokes to merge.");
2466
2468 if (DTU)
2469 Updates.reserve(2 + 3 * Invokes.size());
2470
2471 bool HasNormalDest =
2472 !isa<UnreachableInst>(Invokes[0]->getNormalDest()->getFirstNonPHIOrDbg());
2473
2474 // Clone one of the invokes into a new basic block.
2475 // Since they are all compatible, it doesn't matter which invoke is cloned.
2476 InvokeInst *MergedInvoke = [&Invokes, HasNormalDest]() {
2477 InvokeInst *II0 = Invokes.front();
2478 BasicBlock *II0BB = II0->getParent();
2479 BasicBlock *InsertBeforeBlock =
2480 II0->getParent()->getIterator()->getNextNode();
2481 Function *Func = II0BB->getParent();
2482 LLVMContext &Ctx = II0->getContext();
2483
2484 BasicBlock *MergedInvokeBB = BasicBlock::Create(
2485 Ctx, II0BB->getName() + ".invoke", Func, InsertBeforeBlock);
2486
2487 auto *MergedInvoke = cast<InvokeInst>(II0->clone());
2488 // NOTE: all invokes have the same attributes, so no handling needed.
2489 MergedInvoke->insertInto(MergedInvokeBB, MergedInvokeBB->end());
2490
2491 if (!HasNormalDest) {
2492 // This set does not have a normal destination,
2493 // so just form a new block with unreachable terminator.
2494 BasicBlock *MergedNormalDest = BasicBlock::Create(
2495 Ctx, II0BB->getName() + ".cont", Func, InsertBeforeBlock);
2496 new UnreachableInst(Ctx, MergedNormalDest);
2497 MergedInvoke->setNormalDest(MergedNormalDest);
2498 }
2499
2500 // The unwind destination, however, remainds identical for all invokes here.
2501
2502 return MergedInvoke;
2503 }();
2504
2505 if (DTU) {
2506 // Predecessor blocks that contained these invokes will now branch to
2507 // the new block that contains the merged invoke, ...
2508 for (InvokeInst *II : Invokes)
2509 Updates.push_back(
2510 {DominatorTree::Insert, II->getParent(), MergedInvoke->getParent()});
2511
2512 // ... which has the new `unreachable` block as normal destination,
2513 // or unwinds to the (same for all `invoke`s in this set) `landingpad`,
2514 for (BasicBlock *SuccBBOfMergedInvoke : successors(MergedInvoke))
2515 Updates.push_back({DominatorTree::Insert, MergedInvoke->getParent(),
2516 SuccBBOfMergedInvoke});
2517
2518 // Since predecessor blocks now unconditionally branch to a new block,
2519 // they no longer branch to their original successors.
2520 for (InvokeInst *II : Invokes)
2521 for (BasicBlock *SuccOfPredBB : successors(II->getParent()))
2522 Updates.push_back(
2523 {DominatorTree::Delete, II->getParent(), SuccOfPredBB});
2524 }
2525
2526 bool IsIndirectCall = Invokes[0]->isIndirectCall();
2527
2528 // Form the merged operands for the merged invoke.
2529 for (Use &U : MergedInvoke->operands()) {
2530 // Only PHI together the indirect callees and data operands.
2531 if (MergedInvoke->isCallee(&U)) {
2532 if (!IsIndirectCall)
2533 continue;
2534 } else if (!MergedInvoke->isDataOperand(&U))
2535 continue;
2536
2537 // Don't create trivial PHI's with all-identical incoming values.
2538 bool NeedPHI = any_of(Invokes, [&U](InvokeInst *II) {
2539 return II->getOperand(U.getOperandNo()) != U.get();
2540 });
2541 if (!NeedPHI)
2542 continue;
2543
2544 // Form a PHI out of all the data ops under this index.
2546 U->getType(), /*NumReservedValues=*/Invokes.size(), "", MergedInvoke);
2547 for (InvokeInst *II : Invokes)
2548 PN->addIncoming(II->getOperand(U.getOperandNo()), II->getParent());
2549
2550 U.set(PN);
2551 }
2552
2553 // We've ensured that each PHI node has compatible (identical) incoming values
2554 // when coming from each of the `invoke`s in the current merge set,
2555 // so update the PHI nodes accordingly.
2556 for (BasicBlock *Succ : successors(MergedInvoke))
2557 AddPredecessorToBlock(Succ, /*NewPred=*/MergedInvoke->getParent(),
2558 /*ExistPred=*/Invokes.front()->getParent());
2559
2560 // And finally, replace the original `invoke`s with an unconditional branch
2561 // to the block with the merged `invoke`. Also, give that merged `invoke`
2562 // the merged debugloc of all the original `invoke`s.
2563 const DILocation *MergedDebugLoc = nullptr;
2564 for (InvokeInst *II : Invokes) {
2565 // Compute the debug location common to all the original `invoke`s.
2566 if (!MergedDebugLoc)
2567 MergedDebugLoc = II->getDebugLoc();
2568 else
2569 MergedDebugLoc =
2570 DILocation::getMergedLocation(MergedDebugLoc, II->getDebugLoc());
2571
2572 // And replace the old `invoke` with an unconditionally branch
2573 // to the block with the merged `invoke`.
2574 for (BasicBlock *OrigSuccBB : successors(II->getParent()))
2575 OrigSuccBB->removePredecessor(II->getParent());
2576 BranchInst::Create(MergedInvoke->getParent(), II->getParent());
2577 II->replaceAllUsesWith(MergedInvoke);
2578 II->eraseFromParent();
2579 ++NumInvokesMerged;
2580 }
2581 MergedInvoke->setDebugLoc(MergedDebugLoc);
2582 ++NumInvokeSetsFormed;
2583
2584 if (DTU)
2585 DTU->applyUpdates(Updates);
2586}
2587
2588/// If this block is a `landingpad` exception handling block, categorize all
2589/// the predecessor `invoke`s into sets, with all `invoke`s in each set
2590/// being "mergeable" together, and then merge invokes in each set together.
2591///
2592/// This is a weird mix of hoisting and sinking. Visually, it goes from:
2593/// [...] [...]
2594/// | |
2595/// [invoke0] [invoke1]
2596/// / \ / \
2597/// [cont0] [landingpad] [cont1]
2598/// to:
2599/// [...] [...]
2600/// \ /
2601/// [invoke]
2602/// / \
2603/// [cont] [landingpad]
2604///
2605/// But of course we can only do that if the invokes share the `landingpad`,
2606/// edges invoke0->cont0 and invoke1->cont1 are "compatible",
2607/// and the invoked functions are "compatible".
2610 return false;
2611
2612 bool Changed = false;
2613
2614 // FIXME: generalize to all exception handling blocks?
2615 if (!BB->isLandingPad())
2616 return Changed;
2617
2618 CompatibleSets Grouper;
2619
2620 // Record all the predecessors of this `landingpad`. As per verifier,
2621 // the only allowed predecessor is the unwind edge of an `invoke`.
2622 // We want to group "compatible" `invokes` into the same set to be merged.
2623 for (BasicBlock *PredBB : predecessors(BB))
2624 Grouper.insert(cast<InvokeInst>(PredBB->getTerminator()));
2625
2626 // And now, merge `invoke`s that were grouped togeter.
2627 for (ArrayRef<InvokeInst *> Invokes : Grouper.Sets) {
2628 if (Invokes.size() < 2)
2629 continue;
2630 Changed = true;
2631 MergeCompatibleInvokesImpl(Invokes, DTU);
2632 }
2633
2634 return Changed;
2635}
2636
2637namespace {
2638/// Track ephemeral values, which should be ignored for cost-modelling
2639/// purposes. Requires walking instructions in reverse order.
2640class EphemeralValueTracker {
2642
2643 bool isEphemeral(const Instruction *I) {
2644 if (isa<AssumeInst>(I))
2645 return true;
2646 return !I->mayHaveSideEffects() && !I->isTerminator() &&
2647 all_of(I->users(), [&](const User *U) {
2648 return EphValues.count(cast<Instruction>(U));
2649 });
2650 }
2651
2652public:
2653 bool track(const Instruction *I) {
2654 if (isEphemeral(I)) {
2655 EphValues.insert(I);
2656 return true;
2657 }
2658 return false;
2659 }
2660
2661 bool contains(const Instruction *I) const { return EphValues.contains(I); }
2662};
2663} // namespace
2664
2665/// Determine if we can hoist sink a sole store instruction out of a
2666/// conditional block.
2667///
2668/// We are looking for code like the following:
2669/// BrBB:
2670/// store i32 %add, i32* %arrayidx2
2671/// ... // No other stores or function calls (we could be calling a memory
2672/// ... // function).
2673/// %cmp = icmp ult %x, %y
2674/// br i1 %cmp, label %EndBB, label %ThenBB
2675/// ThenBB:
2676/// store i32 %add5, i32* %arrayidx2
2677/// br label EndBB
2678/// EndBB:
2679/// ...
2680/// We are going to transform this into:
2681/// BrBB:
2682/// store i32 %add, i32* %arrayidx2
2683/// ... //
2684/// %cmp = icmp ult %x, %y
2685/// %add.add5 = select i1 %cmp, i32 %add, %add5
2686/// store i32 %add.add5, i32* %arrayidx2
2687/// ...
2688///
2689/// \return The pointer to the value of the previous store if the store can be
2690/// hoisted into the predecessor block. 0 otherwise.
2692 BasicBlock *StoreBB, BasicBlock *EndBB) {
2693 StoreInst *StoreToHoist = dyn_cast<StoreInst>(I);
2694 if (!StoreToHoist)
2695 return nullptr;
2696
2697 // Volatile or atomic.
2698 if (!StoreToHoist->isSimple())
2699 return nullptr;
2700
2701 Value *StorePtr = StoreToHoist->getPointerOperand();
2702 Type *StoreTy = StoreToHoist->getValueOperand()->getType();
2703
2704 // Look for a store to the same pointer in BrBB.
2705 unsigned MaxNumInstToLookAt = 9;
2706 // Skip pseudo probe intrinsic calls which are not really killing any memory
2707 // accesses.
2708 for (Instruction &CurI : reverse(BrBB->instructionsWithoutDebug(true))) {
2709 if (!MaxNumInstToLookAt)
2710 break;
2711 --MaxNumInstToLookAt;
2712
2713 // Could be calling an instruction that affects memory like free().
2714 if (CurI.mayWriteToMemory() && !isa<StoreInst>(CurI))
2715 return nullptr;
2716
2717 if (auto *SI = dyn_cast<StoreInst>(&CurI)) {
2718 // Found the previous store to same location and type. Make sure it is
2719 // simple, to avoid introducing a spurious non-atomic write after an
2720 // atomic write.
2721 if (SI->getPointerOperand() == StorePtr &&
2722 SI->getValueOperand()->getType() == StoreTy && SI->isSimple())
2723 // Found the previous store, return its value operand.
2724 return SI->getValueOperand();
2725 return nullptr; // Unknown store.
2726 }
2727
2728 if (auto *LI = dyn_cast<LoadInst>(&CurI)) {
2729 if (LI->getPointerOperand() == StorePtr && LI->getType() == StoreTy &&
2730 LI->isSimple()) {
2731 // Local objects (created by an `alloca` instruction) are always
2732 // writable, so once we are past a read from a location it is valid to
2733 // also write to that same location.
2734 // If the address of the local object never escapes the function, that
2735 // means it's never concurrently read or written, hence moving the store
2736 // from under the condition will not introduce a data race.
2737 auto *AI = dyn_cast<AllocaInst>(getUnderlyingObject(StorePtr));
2738 if (AI && !PointerMayBeCaptured(AI, false, true))
2739 // Found a previous load, return it.
2740 return LI;
2741 }
2742 // The load didn't work out, but we may still find a store.
2743 }
2744 }
2745
2746 return nullptr;
2747}
2748
2749/// Estimate the cost of the insertion(s) and check that the PHI nodes can be
2750/// converted to selects.
2752 BasicBlock *EndBB,
2753 unsigned &SpeculatedInstructions,
2754 InstructionCost &Cost,
2755 const TargetTransformInfo &TTI) {
2757 BB->getParent()->hasMinSize()
2760
2761 bool HaveRewritablePHIs = false;
2762 for (PHINode &PN : EndBB->phis()) {
2763 Value *OrigV = PN.getIncomingValueForBlock(BB);
2764 Value *ThenV = PN.getIncomingValueForBlock(ThenBB);
2765
2766 // FIXME: Try to remove some of the duplication with HoistThenElseCodeToIf.
2767 // Skip PHIs which are trivial.
2768 if (ThenV == OrigV)
2769 continue;
2770
2771 Cost += TTI.getCmpSelInstrCost(Instruction::Select, PN.getType(), nullptr,
2773
2774 // Don't convert to selects if we could remove undefined behavior instead.
2775 if (passingValueIsAlwaysUndefined(OrigV, &PN) ||
2777 return false;
2778
2779 HaveRewritablePHIs = true;
2780 ConstantExpr *OrigCE = dyn_cast<ConstantExpr>(OrigV);
2781 ConstantExpr *ThenCE = dyn_cast<ConstantExpr>(ThenV);
2782 if (!OrigCE && !ThenCE)
2783 continue; // Known cheap (FIXME: Maybe not true for aggregates).
2784
2785 InstructionCost OrigCost = OrigCE ? computeSpeculationCost(OrigCE, TTI) : 0;
2786 InstructionCost ThenCost = ThenCE ? computeSpeculationCost(ThenCE, TTI) : 0;
2787 InstructionCost MaxCost =
2789 if (OrigCost + ThenCost > MaxCost)
2790 return false;
2791
2792 // Account for the cost of an unfolded ConstantExpr which could end up
2793 // getting expanded into Instructions.
2794 // FIXME: This doesn't account for how many operations are combined in the
2795 // constant expression.
2796 ++SpeculatedInstructions;
2797 if (SpeculatedInstructions > 1)
2798 return false;
2799 }
2800
2801 return HaveRewritablePHIs;
2802}
2803
2804/// Speculate a conditional basic block flattening the CFG.
2805///
2806/// Note that this is a very risky transform currently. Speculating
2807/// instructions like this is most often not desirable. Instead, there is an MI
2808/// pass which can do it with full awareness of the resource constraints.
2809/// However, some cases are "obvious" and we should do directly. An example of
2810/// this is speculating a single, reasonably cheap instruction.
2811///
2812/// There is only one distinct advantage to flattening the CFG at the IR level:
2813/// it makes very common but simplistic optimizations such as are common in
2814/// instcombine and the DAG combiner more powerful by removing CFG edges and
2815/// modeling their effects with easier to reason about SSA value graphs.
2816///
2817///
2818/// An illustration of this transform is turning this IR:
2819/// \code
2820/// BB:
2821/// %cmp = icmp ult %x, %y
2822/// br i1 %cmp, label %EndBB, label %ThenBB
2823/// ThenBB:
2824/// %sub = sub %x, %y
2825/// br label BB2
2826/// EndBB:
2827/// %phi = phi [ %sub, %ThenBB ], [ 0, %EndBB ]
2828/// ...
2829/// \endcode
2830///
2831/// Into this IR:
2832/// \code
2833/// BB:
2834/// %cmp = icmp ult %x, %y
2835/// %sub = sub %x, %y
2836/// %cond = select i1 %cmp, 0, %sub
2837/// ...
2838/// \endcode
2839///
2840/// \returns true if the conditional block is removed.
2841bool SimplifyCFGOpt::SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB,
2842 const TargetTransformInfo &TTI) {
2843 // Be conservative for now. FP select instruction can often be expensive.
2844 Value *BrCond = BI->getCondition();
2845 if (isa<FCmpInst>(BrCond))
2846 return false;
2847
2848 BasicBlock *BB = BI->getParent();
2849 BasicBlock *EndBB = ThenBB->getTerminator()->getSuccessor(0);
2850 InstructionCost Budget =
2852
2853 // If ThenBB is actually on the false edge of the conditional branch, remember
2854 // to swap the select operands later.
2855 bool Invert = false;
2856 if (ThenBB != BI->getSuccessor(0)) {
2857 assert(ThenBB == BI->getSuccessor(1) && "No edge from 'if' block?");
2858 Invert = true;
2859 }
2860 assert(EndBB == BI->getSuccessor(!Invert) && "No edge from to end block");
2861
2862 // If the branch is non-unpredictable, and is predicted to *not* branch to
2863 // the `then` block, then avoid speculating it.
2864 if (!BI->getMetadata(LLVMContext::MD_unpredictable)) {
2865 uint64_t TWeight, FWeight;
2866 if (extractBranchWeights(*BI, TWeight, FWeight) &&
2867 (TWeight + FWeight) != 0) {
2868 uint64_t EndWeight = Invert ? TWeight : FWeight;
2869 BranchProbability BIEndProb =
2870 BranchProbability::getBranchProbability(EndWeight, TWeight + FWeight);
2872 if (BIEndProb >= Likely)
2873 return false;
2874 }
2875 }
2876
2877 // Keep a count of how many times instructions are used within ThenBB when
2878 // they are candidates for sinking into ThenBB. Specifically:
2879 // - They are defined in BB, and
2880 // - They have no side effects, and
2881 // - All of their uses are in ThenBB.
2882 SmallDenseMap<Instruction *, unsigned, 4> SinkCandidateUseCounts;
2883
2884 SmallVector<Instruction *, 4> SpeculatedDbgIntrinsics;
2885
2886 unsigned SpeculatedInstructions = 0;
2887 Value *SpeculatedStoreValue = nullptr;
2888 StoreInst *SpeculatedStore = nullptr;
2889 EphemeralValueTracker EphTracker;
2890 for (Instruction &I : reverse(drop_end(*ThenBB))) {
2891 // Skip debug info.
2892 if (isa<DbgInfoIntrinsic>(I)) {
2893 SpeculatedDbgIntrinsics.push_back(&I);
2894 continue;
2895 }
2896
2897 // Skip pseudo probes. The consequence is we lose track of the branch
2898 // probability for ThenBB, which is fine since the optimization here takes
2899 // place regardless of the branch probability.
2900 if (isa<PseudoProbeInst>(I)) {
2901 // The probe should be deleted so that it will not be over-counted when
2902 // the samples collected on the non-conditional path are counted towards
2903 // the conditional path. We leave it for the counts inference algorithm to
2904 // figure out a proper count for an unknown probe.
2905 SpeculatedDbgIntrinsics.push_back(&I);
2906 continue;
2907 }
2908
2909 // Ignore ephemeral values, they will be dropped by the transform.
2910 if (EphTracker.track(&I))
2911 continue;
2912
2913 // Only speculatively execute a single instruction (not counting the
2914 // terminator) for now.
2915 ++SpeculatedInstructions;
2916 if (SpeculatedInstructions > 1)
2917 return false;
2918
2919 // Don't hoist the instruction if it's unsafe or expensive.
2921 !(HoistCondStores && (SpeculatedStoreValue = isSafeToSpeculateStore(
2922 &I, BB, ThenBB, EndBB))))
2923 return false;
2924 if (!SpeculatedStoreValue &&
2927 return false;
2928
2929 // Store the store speculation candidate.
2930 if (SpeculatedStoreValue)
2931 SpeculatedStore = cast<StoreInst>(&I);
2932
2933 // Do not hoist the instruction if any of its operands are defined but not
2934 // used in BB. The transformation will prevent the operand from
2935 // being sunk into the use block.
2936 for (Use &Op : I.operands()) {
2937 Instruction *OpI = dyn_cast<Instruction>(Op);
2938 if (!OpI || OpI->getParent() != BB || OpI->mayHaveSideEffects())
2939 continue; // Not a candidate for sinking.
2940
2941 ++SinkCandidateUseCounts[OpI];
2942 }
2943 }
2944
2945 // Consider any sink candidates which are only used in ThenBB as costs for
2946 // speculation. Note, while we iterate over a DenseMap here, we are summing
2947 // and so iteration order isn't significant.
2948 for (const auto &[Inst, Count] : SinkCandidateUseCounts)
2949 if (Inst->hasNUses(Count)) {
2950 ++SpeculatedInstructions;
2951 if (SpeculatedInstructions > 1)
2952 return false;
2953 }
2954
2955 // Check that we can insert the selects and that it's not too expensive to do
2956 // so.
2957 bool Convert = SpeculatedStore != nullptr;
2959 Convert |= validateAndCostRequiredSelects(BB, ThenBB, EndBB,
2960 SpeculatedInstructions,
2961 Cost, TTI);
2962 if (!Convert || Cost > Budget)
2963 return false;
2964
2965 // If we get here, we can hoist the instruction and if-convert.
2966 LLVM_DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *ThenBB << "\n";);
2967
2968 // Insert a select of the value of the speculated store.
2969 if (SpeculatedStoreValue) {
2971 Value *OrigV = SpeculatedStore->getValueOperand();
2972 Value *TrueV = SpeculatedStore->getValueOperand();
2973 Value *FalseV = SpeculatedStoreValue;
2974 if (Invert)
2975 std::swap(TrueV, FalseV);
2976 Value *S = Builder.CreateSelect(
2977 BrCond, TrueV, FalseV, "spec.store.select", BI);
2978 SpeculatedStore->setOperand(0, S);
2979 SpeculatedStore->applyMergedLocation(BI->getDebugLoc(),
2980 SpeculatedStore->getDebugLoc());
2981 // The value stored is still conditional, but the store itself is now
2982 // unconditonally executed, so we must be sure that any linked dbg.assign
2983 // intrinsics are tracking the new stored value (the result of the
2984 // select). If we don't, and the store were to be removed by another pass
2985 // (e.g. DSE), then we'd eventually end up emitting a location describing
2986 // the conditional value, unconditionally.
2987 //
2988 // === Before this transformation ===
2989 // pred:
2990 // store %one, %x.dest, !DIAssignID !1
2991 // dbg.assign %one, "x", ..., !1, ...
2992 // br %cond if.then
2993 //
2994 // if.then:
2995 // store %two, %x.dest, !DIAssignID !2
2996 // dbg.assign %two, "x", ..., !2, ...
2997 //
2998 // === After this transformation ===
2999 // pred:
3000 // store %one, %x.dest, !DIAssignID !1
3001 // dbg.assign %one, "x", ..., !1
3002 /// ...
3003 // %merge = select %cond, %two, %one
3004 // store %merge, %x.dest, !DIAssignID !2
3005 // dbg.assign %merge, "x", ..., !2
3006 for (auto *DAI : at::getAssignmentMarkers(SpeculatedStore)) {
3007 if (any_of(DAI->location_ops(), [&](Value *V) { return V == OrigV; }))
3008 DAI->replaceVariableLocationOp(OrigV, S);
3009 }
3010 }
3011
3012 // Metadata can be dependent on the condition we are hoisting above.
3013 // Conservatively strip all metadata on the instruction. Drop the debug loc
3014 // to avoid making it appear as if the condition is a constant, which would
3015 // be misleading while debugging.
3016 // Similarly strip attributes that maybe dependent on condition we are
3017 // hoisting above.
3018 for (auto &I : make_early_inc_range(*ThenBB)) {
3019 if (!SpeculatedStoreValue || &I != SpeculatedStore) {
3020 // Don't update the DILocation of dbg.assign intrinsics.
3021 if (!isa<DbgAssignIntrinsic>(&I))
3022 I.setDebugLoc(DebugLoc());
3023 }
3024 I.dropUndefImplyingAttrsAndUnknownMetadata();
3025
3026 // Drop ephemeral values.
3027 if (EphTracker.contains(&I)) {
3028 I.replaceAllUsesWith(PoisonValue::get(I.getType()));
3029 I.eraseFromParent();
3030 }
3031 }
3032
3033 // Hoist the instructions.
3034 BB->splice(BI->getIterator(), ThenBB, ThenBB->begin(),
3035 std::prev(ThenBB->end()));
3036
3037 // Insert selects and rewrite the PHI operands.
3039 for (PHINode &PN : EndBB->phis()) {
3040 unsigned OrigI = PN.getBasicBlockIndex(BB);
3041 unsigned ThenI = PN.getBasicBlockIndex(ThenBB);
3042 Value *OrigV = PN.getIncomingValue(OrigI);
3043 Value *ThenV = PN.getIncomingValue(ThenI);
3044
3045 // Skip PHIs which are trivial.
3046 if (OrigV == ThenV)
3047 continue;
3048
3049 // Create a select whose true value is the speculatively executed value and
3050 // false value is the pre-existing value. Swap them if the branch
3051 // destinations were inverted.
3052 Value *TrueV = ThenV, *FalseV = OrigV;
3053 if (Invert)
3054 std::swap(TrueV, FalseV);
3055 Value *V = Builder.CreateSelect(BrCond, TrueV, FalseV, "spec.select", BI);
3056 PN.setIncomingValue(OrigI, V);
3057 PN.setIncomingValue(ThenI, V);
3058 }
3059
3060 // Remove speculated dbg intrinsics.
3061 // FIXME: Is it possible to do this in a more elegant way? Moving/merging the
3062 // dbg value for the different flows and inserting it after the select.
3063 for (Instruction *I : SpeculatedDbgIntrinsics) {
3064 // We still want to know that an assignment took place so don't remove
3065 // dbg.assign intrinsics.
3066 if (!isa<DbgAssignIntrinsic>(I))
3067 I->eraseFromParent();
3068 }
3069
3070 ++NumSpeculations;
3071 return true;
3072}
3073
3074/// Return true if we can thread a branch across this block.
3076 int Size = 0;
3077 EphemeralValueTracker EphTracker;
3078
3079 // Walk the loop in reverse so that we can identify ephemeral values properly
3080 // (values only feeding assumes).
3081 for (Instruction &I : reverse(BB->instructionsWithoutDebug(false))) {
3082 // Can't fold blocks that contain noduplicate or convergent calls.
3083 if (CallInst *CI = dyn_cast<CallInst>(&I))
3084 if (CI->cannotDuplicate() || CI->isConvergent())
3085 return false;
3086
3087 // Ignore ephemeral values which are deleted during codegen.
3088 // We will delete Phis while threading, so Phis should not be accounted in
3089 // block's size.
3090 if (!EphTracker.track(&I) && !isa<PHINode>(I)) {
3091 if (Size++ > MaxSmallBlockSize)
3092 return false; // Don't clone large BB's.
3093 }
3094
3095 // We can only support instructions that do not define values that are
3096 // live outside of the current basic block.
3097 for (User *U : I.users()) {
3098 Instruction *UI = cast<Instruction>(U);
3099 if (UI->getParent() != BB || isa<PHINode>(UI))
3100 return false;
3101 }
3102
3103 // Looks ok, continue checking.
3104 }
3105
3106 return true;
3107}
3108
3110 BasicBlock *To) {
3111 // Don't look past the block defining the value, we might get the value from
3112 // a previous loop iteration.
3113 auto *I = dyn_cast<Instruction>(V);
3114 if (I && I->getParent() == To)
3115 return nullptr;
3116
3117 // We know the value if the From block branches on it.
3118 auto *BI = dyn_cast<BranchInst>(From->getTerminator());
3119 if (BI && BI->isConditional() && BI->getCondition() == V &&
3120 BI->getSuccessor(0) != BI->getSuccessor(1))
3121 return BI->getSuccessor(0) == To ? ConstantInt::getTrue(BI->getContext())
3123
3124 return nullptr;
3125}
3126
3127/// If we have a conditional branch on something for which we know the constant
3128/// value in predecessors (e.g. a phi node in the current block), thread edges
3129/// from the predecessor to their ultimate destination.
3130static std::optional<bool>
3132 const DataLayout &DL,
3133 AssumptionCache *AC) {
3135 BasicBlock *BB = BI->getParent();
3136 Value *Cond = BI->getCondition();
3137 PHINode *PN = dyn_cast<PHINode>(Cond);
3138 if (PN && PN->getParent() == BB) {
3139 // Degenerate case of a single entry PHI.
3140 if (PN->getNumIncomingValues() == 1) {
3142 return true;
3143 }
3144
3145 for (Use &U : PN->incoming_values())
3146 if (auto *CB = dyn_cast<ConstantInt>(U))
3147 KnownValues[CB].insert(PN->getIncomingBlock(U));
3148 } else {
3149 for (BasicBlock *Pred : predecessors(BB)) {
3150 if (ConstantInt *CB = getKnownValueOnEdge(Cond, Pred, BB))
3151 KnownValues[CB].insert(Pred);
3152 }
3153 }
3154
3155 if (KnownValues.empty())
3156 return false;
3157
3158 // Now we know that this block has multiple preds and two succs.
3159 // Check that the block is small enough and values defined in the block are
3160 // not used outside of it.
3162 return false;
3163
3164 for (const auto &Pair : KnownValues) {
3165 // Okay, we now know that all edges from PredBB should be revectored to
3166 // branch to RealDest.
3167 ConstantInt *CB = Pair.first;
3168 ArrayRef<BasicBlock *> PredBBs = Pair.second.getArrayRef();
3169 BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
3170
3171 if (RealDest == BB)
3172 continue; // Skip self loops.
3173
3174 // Skip if the predecessor's terminator is an indirect branch.
3175 if (any_of(PredBBs, [](BasicBlock *PredBB) {
3176 return isa<IndirectBrInst>(PredBB->getTerminator());
3177 }))
3178 continue;
3179
3180 LLVM_DEBUG({
3181 dbgs() << "Condition " << *Cond << " in " << BB->getName()
3182 << " has value " << *Pair.first << " in predecessors:\n";
3183 for (const BasicBlock *PredBB : Pair.second)
3184 dbgs() << " " << PredBB->getName() << "\n";
3185 dbgs() << "Threading to destination " << RealDest->getName() << ".\n";
3186 });
3187
3188 // Split the predecessors we are threading into a new edge block. We'll
3189 // clone the instructions into this block, and then redirect it to RealDest.
3190 BasicBlock *EdgeBB = SplitBlockPredecessors(BB, PredBBs, ".critedge", DTU);
3191
3192 // TODO: These just exist to reduce test diff, we can drop them if we like.
3193 EdgeBB->setName(RealDest->getName() + ".critedge");
3194 EdgeBB->moveBefore(RealDest);
3195
3196 // Update PHI nodes.
3197 AddPredecessorToBlock(RealDest, EdgeBB, BB);
3198
3199 // BB may have instructions that are being threaded over. Clone these
3200 // instructions into EdgeBB. We know that there will be no uses of the
3201 // cloned instructions outside of EdgeBB.
3202 BasicBlock::iterator InsertPt = EdgeBB->getFirstInsertionPt();
3203 DenseMap<Value *, Value *> TranslateMap; // Track translated values.
3204 TranslateMap[Cond] = CB;
3205 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
3206 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
3207 TranslateMap[PN] = PN->getIncomingValueForBlock(EdgeBB);
3208 continue;
3209 }
3210 // Clone the instruction.
3211 Instruction *N = BBI->clone();
3212 if (BBI->hasName())
3213 N->setName(BBI->getName() + ".c");
3214
3215 // Update operands due to translation.
3216 for (Use &Op : N->operands()) {
3217 DenseMap<Value *, Value *>::iterator PI = TranslateMap.find(Op);
3218 if (PI != TranslateMap.end())
3219 Op = PI->second;
3220 }
3221
3222 // Check for trivial simplification.
3223 if (Value *V = simplifyInstruction(N, {DL, nullptr, nullptr, AC})) {
3224 if (!BBI->use_empty())
3225 TranslateMap[&*BBI] = V;
3226 if (!N->mayHaveSideEffects()) {
3227 N->deleteValue(); // Instruction folded away, don't need actual inst
3228 N = nullptr;
3229 }
3230 } else {
3231 if (!BBI->use_empty())
3232 TranslateMap[&*BBI] = N;
3233 }
3234 if (N) {
3235 // Insert the new instruction into its new home.
3236 N->insertInto(EdgeBB, InsertPt);
3237
3238 // Register the new instruction with the assumption cache if necessary.
3239 if (auto *Assume = dyn_cast<AssumeInst>(N))
3240 if (AC)
3241 AC->registerAssumption(Assume);
3242 }
3243 }
3244
3245 BB->removePredecessor(EdgeBB);
3246 BranchInst *EdgeBI = cast<BranchInst>(EdgeBB->getTerminator());
3247 EdgeBI->setSuccessor(0, RealDest);
3248 EdgeBI->setDebugLoc(BI->getDebugLoc());
3249
3250 if (DTU) {
3252 Updates.push_back({DominatorTree::Delete, EdgeBB, BB});
3253 Updates.push_back({DominatorTree::Insert, EdgeBB, RealDest});
3254 DTU->applyUpdates(Updates);
3255 }
3256
3257 // For simplicity, we created a separate basic block for the edge. Merge
3258 // it back into the predecessor if possible. This not only avoids
3259 // unnecessary SimplifyCFG iterations, but also makes sure that we don't
3260 // bypass the check for trivial cycles above.
3261 MergeBlockIntoPredecessor(EdgeBB, DTU);
3262
3263 // Signal repeat, simplifying any other constants.
3264 return std::nullopt;
3265 }
3266
3267 return false;
3268}
3269
3271 DomTreeUpdater *DTU,
3272 const DataLayout &DL,
3273 AssumptionCache *AC) {
3274 std::optional<bool> Result;
3275 bool EverChanged = false;
3276 do {
3277 // Note that None means "we changed things, but recurse further."
3278 Result = FoldCondBranchOnValueKnownInPredecessorImpl(BI, DTU, DL, AC);
3279 EverChanged |= Result == std::nullopt || *Result;
3280 } while (Result == std::nullopt);
3281 return EverChanged;
3282}
3283
3284/// Given a BB that starts with the specified two-entry PHI node,
3285/// see if we can eliminate it.
3287 DomTreeUpdater *DTU, const DataLayout &DL) {
3288 // Ok, this is a two entry PHI node. Check to see if this is a simple "if
3289 // statement", which has a very simple dominance structure. Basically, we
3290 // are trying to find the condition that is being branched on, which
3291 // subsequently causes this merge to happen. We really want control
3292 // dependence information for this check, but simplifycfg can't keep it up
3293 // to date, and this catches most of the cases we care about anyway.
3294 BasicBlock *BB = PN->getParent();
3295
3296 BasicBlock *IfTrue, *IfFalse;
3297 BranchInst *DomBI = GetIfCondition(BB, IfTrue, IfFalse);
3298 if (!DomBI)
3299 return false;
3300 Value *IfCond = DomBI->getCondition();
3301 // Don't bother if the branch will be constant folded trivially.
3302 if (isa<ConstantInt>(IfCond))
3303 return false;
3304
3305 BasicBlock *DomBlock = DomBI->getParent();
3308 PN->blocks(), std::back_inserter(IfBlocks), [](BasicBlock *IfBlock) {
3309 return cast<BranchInst>(IfBlock->getTerminator())->isUnconditional();
3310 });
3311 assert((IfBlocks.size() == 1 || IfBlocks.size() == 2) &&
3312 "Will have either one or two blocks to speculate.");
3313
3314 // If the branch is non-unpredictable, see if we either predictably jump to
3315 // the merge bb (if we have only a single 'then' block), or if we predictably
3316 // jump to one specific 'then' block (if we have two of them).
3317 // It isn't beneficial to speculatively execute the code
3318 // from the block that we know is predictably not entered.
3319 if (!DomBI->getMetadata(LLVMContext::MD_unpredictable)) {
3320 uint64_t TWeight, FWeight;
3321 if (extractBranchWeights(*DomBI, TWeight, FWeight) &&
3322 (TWeight + FWeight) != 0) {
3323 BranchProbability BITrueProb =
3324 BranchProbability::getBranchProbability(TWeight, TWeight + FWeight);
3326 BranchProbability BIFalseProb = BITrueProb.getCompl();
3327 if (IfBlocks.size() == 1) {
3328 BranchProbability BIBBProb =
3329 DomBI->getSuccessor(0) == BB ? BITrueProb : BIFalseProb;
3330 if (BIBBProb >= Likely)
3331 return false;
3332 } else {
3333 if (BITrueProb >= Likely || BIFalseProb >= Likely)
3334 return false;
3335 }
3336 }
3337 }
3338
3339 // Don't try to fold an unreachable block. For example, the phi node itself
3340 // can't be the candidate if-condition for a select that we want to form.
3341 if (auto *IfCondPhiInst = dyn_cast<PHINode>(IfCond))
3342 if (IfCondPhiInst->getParent() == BB)
3343 return false;
3344
3345 // Okay, we found that we can merge this two-entry phi node into a select.
3346 // Doing so would require us to fold *all* two entry phi nodes in this block.
3347 // At some point this becomes non-profitable (particularly if the target
3348 // doesn't support cmov's). Only do this transformation if there are two or
3349 // fewer PHI nodes in this block.
3350 unsigned NumPhis = 0;
3351 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
3352 if (NumPhis > 2)
3353 return false;
3354
3355 // Loop over the PHI's seeing if we can promote them all to select
3356 // instructions. While we are at it, keep track of the instructions
3357 // that need to be moved to the dominating block.
3358 SmallPtrSet<Instruction *, 4> AggressiveInsts;
3360 InstructionCost Budget =
3362
3363 bool Changed = false;
3364 for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) {
3365 PHINode *PN = cast<PHINode>(II++);
3366 if (Value *V = simplifyInstruction(PN, {DL, PN})) {
3367 PN->replaceAllUsesWith(V);
3368 PN->eraseFromParent();
3369 Changed = true;
3370 continue;
3371 }
3372
3373 if (!dominatesMergePoint(PN->getIncomingValue(0), BB, AggressiveInsts,
3374 Cost, Budget, TTI) ||
3375 !dominatesMergePoint(PN->getIncomingValue(1), BB, AggressiveInsts,
3376 Cost, Budget, TTI))
3377 return Changed;
3378 }
3379
3380 // If we folded the first phi, PN dangles at this point. Refresh it. If
3381 // we ran out of PHIs then we simplified them all.
3382 PN = dyn_cast<PHINode>(BB->begin());
3383 if (!PN)
3384 return true;
3385
3386 // Return true if at least one of these is a 'not', and another is either
3387 // a 'not' too, or a constant.
3388 auto CanHoistNotFromBothValues = [](Value *V0, Value *V1) {
3389 if (!match(V0, m_Not(m_Value())))
3390 std::swap(V0, V1);
3391 auto Invertible = m_CombineOr(m_Not(m_Value()), m_AnyIntegralConstant());
3392 return match(V0, m_Not(m_Value())) && match(V1, Invertible);
3393 };
3394
3395 // Don't fold i1 branches on PHIs which contain binary operators or
3396 // (possibly inverted) select form of or/ands, unless one of
3397 // the incoming values is an 'not' and another one is freely invertible.
3398 // These can often be turned into switches and other things.
3399 auto IsBinOpOrAnd = [](Value *V) {
3400 return match(
3401 V, m_CombineOr(
3402 m_BinOp(),
3405 };
3406 if (PN->getType()->isIntegerTy(1) &&
3407 (IsBinOpOrAnd(PN->getIncomingValue(0)) ||
3408 IsBinOpOrAnd(PN->getIncomingValue(1)) || IsBinOpOrAnd(IfCond)) &&
3409 !CanHoistNotFromBothValues(PN->getIncomingValue(0),
3410 PN->getIncomingValue(1)))
3411 return Changed;
3412
3413 // If all PHI nodes are promotable, check to make sure that all instructions
3414 // in the predecessor blocks can be promoted as well. If not, we won't be able
3415 // to get rid of the control flow, so it's not worth promoting to select
3416 // instructions.
3417 for (BasicBlock *IfBlock : IfBlocks)
3418 for (BasicBlock::iterator I = IfBlock->begin(); !I->isTerminator(); ++I)
3419 if (!AggressiveInsts.count(&*I) && !I->isDebugOrPseudoInst()) {
3420 // This is not an aggressive instruction that we can promote.
3421 // Because of this, we won't be able to get rid of the control flow, so
3422 // the xform is not worth it.
3423 return Changed;
3424 }
3425
3426 // If either of the blocks has it's address taken, we can't do this fold.
3427 if (any_of(IfBlocks,
3428 [](BasicBlock *IfBlock) { return IfBlock->hasAddressTaken(); }))
3429 return Changed;
3430
3431 LLVM_DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond
3432 << " T: " << IfTrue->getName()
3433 << " F: " << IfFalse->getName() << "\n");
3434
3435 // If we can still promote the PHI nodes after this gauntlet of tests,
3436 // do all of the PHI's now.
3437
3438 // Move all 'aggressive' instructions, which are defined in the
3439 // conditional parts of the if's up to the dominating block.
3440 for (BasicBlock *IfBlock : IfBlocks)
3441 hoistAllInstructionsInto(DomBlock, DomBI, IfBlock);
3442
3444 // Propagate fast-math-flags from phi nodes to replacement selects.
3446 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
3447 if (isa<FPMathOperator>(PN))
3448 Builder.setFastMathFlags(PN->getFastMathFlags());
3449
3450 // Change the PHI node into a select instruction.
3451 Value *TrueVal = PN->getIncomingValueForBlock(IfTrue);
3452 Value *FalseVal = PN->getIncomingValueForBlock(IfFalse);
3453
3454 Value *Sel = Builder.CreateSelect(IfCond, TrueVal, FalseVal, "", DomBI);
3455 PN->replaceAllUsesWith(Sel);
3456 Sel->takeName(PN);
3457 PN->eraseFromParent();
3458 }
3459
3460 // At this point, all IfBlocks are empty, so our if statement
3461 // has been flattened. Change DomBlock to jump directly to our new block to
3462 // avoid other simplifycfg's kicking in on the diamond.
3463 Builder.CreateBr(BB);
3464
3466 if (DTU) {
3467 Updates.push_back({DominatorTree::Insert, DomBlock, BB});
3468 for (auto *Successor : successors(DomBlock))
3469 Updates.push_back({DominatorTree::Delete, DomBlock, Successor});
3470 }
3471
3472 DomBI->eraseFromParent();
3473 if (DTU)
3474 DTU->applyUpdates(Updates);
3475
3476 return true;
3477}
3478
3480 Instruction::BinaryOps Opc, Value *LHS,
3481 Value *RHS, const Twine &Name = "") {
3482 // Try to relax logical op to binary op.
3483 if (impliesPoison(RHS, LHS))
3484 return Builder.CreateBinOp(Opc, LHS, RHS, Name);
3485 if (Opc == Instruction::And)
3486 return Builder.CreateLogicalAnd(LHS, RHS, Name);
3487 if (Opc == Instruction::Or)
3488 return Builder.CreateLogicalOr(LHS, RHS, Name);
3489 llvm_unreachable("Invalid logical opcode");
3490}
3491
3492/// Return true if either PBI or BI has branch weight available, and store
3493/// the weights in {Pred|Succ}{True|False}Weight. If one of PBI and BI does
3494/// not have branch weight, use 1:1 as its weight.
3496 uint64_t &PredTrueWeight,
3497 uint64_t &PredFalseWeight,
3498 uint64_t &SuccTrueWeight,
3499 uint64_t &SuccFalseWeight) {
3500 bool PredHasWeights =
3501 extractBranchWeights(*PBI, PredTrueWeight, PredFalseWeight);
3502 bool SuccHasWeights =
3503 extractBranchWeights(*BI, SuccTrueWeight, SuccFalseWeight);
3504 if (PredHasWeights || SuccHasWeights) {
3505 if (!PredHasWeights)
3506 PredTrueWeight = PredFalseWeight = 1;
3507 if (!SuccHasWeights)
3508 SuccTrueWeight = SuccFalseWeight = 1;
3509 return true;
3510 } else {
3511 return false;
3512 }
3513}
3514
3515/// Determine if the two branches share a common destination and deduce a glue
3516/// that joins the branches' conditions to arrive at the common destination if
3517/// that would be profitable.
3518static std::optional<std::tuple<BasicBlock *, Instruction::BinaryOps, bool>>
3520 const TargetTransformInfo *TTI) {
3521 assert(BI && PBI && BI->isConditional() && PBI->isConditional() &&
3522 "Both blocks must end with a conditional branches.");
3524 "PredBB must be a predecessor of BB.");
3525
3526 // We have the potential to fold the conditions together, but if the
3527 // predecessor branch is predictable, we may not want to merge them.
3528 uint64_t PTWeight, PFWeight;
3529 BranchProbability PBITrueProb, Likely;
3530 if (TTI && !PBI->getMetadata(LLVMContext::MD_unpredictable) &&
3531 extractBranchWeights(*PBI, PTWeight, PFWeight) &&
3532 (PTWeight + PFWeight) != 0) {
3533 PBITrueProb =
3534 BranchProbability::getBranchProbability(PTWeight, PTWeight + PFWeight);
3536 }
3537
3538 if (PBI->getSuccessor(0) == BI->getSuccessor(0)) {
3539 // Speculate the 2nd condition unless the 1st is probably true.
3540 if (PBITrueProb.isUnknown() || PBITrueProb < Likely)
3541 return {{BI->getSuccessor(0), Instruction::Or, false}};
3542 } else if (PBI->getSuccessor(1) == BI->getSuccessor(1)) {
3543 // Speculate the 2nd condition unless the 1st is probably false.
3544 if (PBITrueProb.isUnknown() || PBITrueProb.getCompl() < Likely)
3545 return {{BI->getSuccessor(1), Instruction::And, false}};
3546 } else if (PBI->getSuccessor(0) == BI->getSuccessor(1)) {
3547 // Speculate the 2nd condition unless the 1st is probably true.
3548 if (PBITrueProb.isUnknown() || PBITrueProb < Likely)
3549 return {{BI->getSuccessor(1), Instruction::And, true}};
3550 } else if (PBI->getSuccessor(1) == BI->getSuccessor(0)) {
3551 // Speculate the 2nd condition unless the 1st is probably false.
3552 if (PBITrueProb.isUnknown() || PBITrueProb.getCompl() < Likely)
3553 return {{BI->getSuccessor(0), Instruction::Or, true}};
3554 }
3555 return std::nullopt;
3556}
3557
3559 DomTreeUpdater *DTU,
3560 MemorySSAUpdater *MSSAU,
3561 const TargetTransformInfo *TTI) {
3562 BasicBlock *BB = BI->getParent();
3563 BasicBlock *PredBlock = PBI->getParent();
3564
3565 // Determine if the two branches share a common destination.
3566 BasicBlock *CommonSucc;
3568 bool InvertPredCond;
3569 std::tie(CommonSucc, Opc, InvertPredCond) =
3571
3572 LLVM_DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
3573
3574 IRBuilder<> Builder(PBI);
3575 // The builder is used to create instructions to eliminate the branch in BB.
3576 // If BB's terminator has !annotation metadata, add it to the new
3577 // instructions.
3578 Builder.CollectMetadataToCopy(BB->getTerminator(),
3579 {LLVMContext::MD_annotation});
3580
3581 // If we need to invert the condition in the pred block to match, do so now.
3582 if (InvertPredCond) {
3583 Value *NewCond = PBI->getCondition();
3584 if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
3585 CmpInst *CI = cast<CmpInst>(NewCond);
3587 } else {
3588 NewCond =
3589 Builder.CreateNot(NewCond, PBI->getCondition()->getName() + ".not");
3590 }
3591
3592 PBI->setCondition(NewCond);
3593 PBI->swapSuccessors();
3594 }
3595
3596 BasicBlock *UniqueSucc =
3597 PBI->getSuccessor(0) == BB ? BI->getSuccessor(0) : BI->getSuccessor(1);
3598
3599 // Before cloning instructions, notify the successor basic block that it
3600 // is about to have a new predecessor. This will update PHI nodes,
3601 // which will allow us to update live-out uses of bonus instructions.
3602 AddPredecessorToBlock(UniqueSucc, PredBlock, BB, MSSAU);
3603
3604 // Try to update branch weights.
3605 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
3606 if (extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight,
3607 SuccTrueWeight, SuccFalseWeight)) {
3608 SmallVector<uint64_t, 8> NewWeights;
3609
3610 if (PBI->getSuccessor(0) == BB) {
3611 // PBI: br i1 %x, BB, FalseDest
3612 // BI: br i1 %y, UniqueSucc, FalseDest
3613 // TrueWeight is TrueWeight for PBI * TrueWeight for BI.
3614 NewWeights.push_back(PredTrueWeight * SuccTrueWeight);
3615 // FalseWeight is FalseWeight for PBI * TotalWeight for BI +
3616 // TrueWeight for PBI * FalseWeight for BI.
3617 // We assume that total weights of a BranchInst can fit into 32 bits.
3618 // Therefore, we will not have overflow using 64-bit arithmetic.
3619 NewWeights.push_back(PredFalseWeight *
3620 (SuccFalseWeight + SuccTrueWeight) +
3621 PredTrueWeight * SuccFalseWeight);
3622 } else {
3623 // PBI: br i1 %x, TrueDest, BB
3624 // BI: br i1 %y, TrueDest, UniqueSucc
3625 // TrueWeight is TrueWeight for PBI * TotalWeight for BI +
3626 // FalseWeight for PBI * TrueWeight for BI.
3627 NewWeights.push_back(PredTrueWeight * (SuccFalseWeight + SuccTrueWeight) +
3628 PredFalseWeight * SuccTrueWeight);
3629 // FalseWeight is FalseWeight for PBI * FalseWeight for BI.
3630 NewWeights.push_back(PredFalseWeight * SuccFalseWeight);
3631 }
3632
3633 // Halve the weights if any of them cannot fit in an uint32_t
3634 FitWeights(NewWeights);
3635
3636 SmallVector<uint32_t, 8> MDWeights(NewWeights.begin(), NewWeights.end());
3637 setBranchWeights(PBI, MDWeights[0], MDWeights[1]);
3638
3639 // TODO: If BB is reachable from all paths through PredBlock, then we
3640 // could replace PBI's branch probabilities with BI's.
3641 } else
3642 PBI->setMetadata(LLVMContext::MD_prof, nullptr);
3643
3644 // Now, update the CFG.
3645 PBI->setSuccessor(PBI->getSuccessor(0) != BB, UniqueSucc);
3646
3647 if (DTU)
3648 DTU->applyUpdates({{DominatorTree::Insert, PredBlock, UniqueSucc},
3649 {DominatorTree::Delete, PredBlock, BB}});
3650
3651 // If BI was a loop latch, it may have had associated loop metadata.
3652 // We need to copy it to the new latch, that is, PBI.
3653 if (MDNode *LoopMD = BI->getMetadata(LLVMContext::MD_loop))
3654 PBI->setMetadata(LLVMContext::MD_loop, LoopMD);
3655
3656 ValueToValueMapTy VMap; // maps original values to cloned values
3658
3659 // Now that the Cond was cloned into the predecessor basic block,
3660 // or/and the two conditions together.
3661 Value *BICond = VMap[BI->getCondition()];
3662 PBI->setCondition(
3663 createLogicalOp(Builder, Opc, PBI->getCondition(), BICond, "or.cond"));
3664
3665 // Copy any debug value intrinsics into the end of PredBlock.
3666 for (Instruction &I : *BB) {
3667 if (isa<DbgInfoIntrinsic>(I)) {
3668 Instruction *NewI = I.clone();
3669 RemapInstruction(NewI, VMap,
3671 NewI->insertBefore(PBI);
3672 }
3673 }
3674
3675 ++NumFoldBranchToCommonDest;
3676 return true;
3677}
3678
3679/// Return if an instruction's type or any of its operands' types are a vector
3680/// type.
3681static bool isVectorOp(Instruction &I) {
3682 return I.getType()->isVectorTy() || any_of(I.operands(), [](Use &U) {
3683 return U->getType()->isVectorTy();
3684 });
3685}
3686
3687/// If this basic block is simple enough, and if a predecessor branches to us
3688/// and one of our successors, fold the block into the predecessor and use
3689/// logical operations to pick the right destination.
3691 MemorySSAUpdater *MSSAU,
3692 const TargetTransformInfo *TTI,
3693 unsigned BonusInstThreshold) {
3694 // If this block ends with an unconditional branch,
3695 // let SpeculativelyExecuteBB() deal with it.
3696 if (!BI->isConditional())
3697 return false;
3698
3699 BasicBlock *BB = BI->getParent();
3703
3704 Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
3705
3706 if (!Cond ||
3707 (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond) &&
3708 !isa<SelectInst>(Cond)) ||
3709 Cond->getParent() != BB || !Cond->hasOneUse())
3710 return false;
3711
3712 // Finally, don't infinitely unroll conditional loops.
3713 if (is_contained(successors(BB), BB))
3714 return false;
3715
3716 // With which predecessors will we want to deal with?
3718 for (BasicBlock *PredBlock : predecessors(BB)) {
3719 BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
3720
3721 // Check that we have two conditional branches. If there is a PHI node in
3722 // the common successor, verify that the same value flows in from both
3723 // blocks.
3724 if (!PBI || PBI->isUnconditional() || !SafeToMergeTerminators(BI, PBI))
3725 continue;
3726
3727 // Determine if the two branches share a common destination.
3728 BasicBlock *CommonSucc;
3730 bool InvertPredCond;
3731 if (auto Recipe = shouldFoldCondBranchesToCommonDestination(BI, PBI, TTI))
3732 std::tie(CommonSucc, Opc, InvertPredCond) = *Recipe;
3733 else
3734 continue;
3735
3736 // Check the cost of inserting the necessary logic before performing the
3737 // transformation.
3738 if (TTI) {
3739 Type *Ty = BI->getCondition()->getType();
3741 if (InvertPredCond && (!PBI->getCondition()->hasOneUse() ||
3742 !isa<CmpInst>(PBI->getCondition())))
3743 Cost += TTI->getArithmeticInstrCost(Instruction::Xor, Ty, CostKind);
3744
3746 continue;
3747 }
3748
3749 // Ok, we do want to deal with this predecessor. Record it.
3750 Preds.emplace_back(PredBlock);
3751 }
3752
3753 // If there aren't any predecessors into which we can fold,
3754 // don't bother checking the cost.
3755 if (Preds.empty())
3756 return false;
3757
3758 // Only allow this transformation if computing the condition doesn't involve
3759 // too many instructions and these involved instructions can be executed
3760 // unconditionally. We denote all involved instructions except the condition
3761 // as "bonus instructions", and only allow this transformation when the
3762 // number of the bonus instructions we'll need to create when cloning into
3763 // each predecessor does not exceed a certain threshold.
3764 unsigned NumBonusInsts = 0;
3765 bool SawVectorOp = false;
3766 const unsigned PredCount = Preds.size();
3767 for (Instruction &I : *BB) {
3768 // Don't check the branch condition comparison itself.
3769 if (&I == Cond)
3770 continue;
3771 // Ignore dbg intrinsics, and the terminator.
3772 if (isa<DbgInfoIntrinsic>(I) || isa<BranchInst>(I))
3773 continue;
3774 // I must be safe to execute unconditionally.
3776 return false;
3777 SawVectorOp |= isVectorOp(I);
3778
3779 // Account for the cost of duplicating this instruction into each
3780 // predecessor. Ignore free instructions.
3781 if (!TTI || TTI->getInstructionCost(&I, CostKind) !=
3783 NumBonusInsts += PredCount;
3784
3785 // Early exits once we reach the limit.
3786 if (NumBonusInsts >
3787 BonusInstThreshold * BranchFoldToCommonDestVectorMultiplier)
3788 return false;
3789 }
3790
3791 auto IsBCSSAUse = [BB, &I](Use &U) {
3792 auto *UI = cast<Instruction>(U.getUser());
3793 if (auto *PN = dyn_cast<PHINode>(UI))
3794 return PN->getIncomingBlock(U) == BB;
3795 return UI->getParent() == BB && I.comesBefore(UI);
3796 };
3797
3798 // Does this instruction require rewriting of uses?
3799 if (!all_of(I.uses(), IsBCSSAUse))
3800 return false;
3801 }
3802 if (NumBonusInsts >
3803 BonusInstThreshold *
3804 (SawVectorOp ? BranchFoldToCommonDestVectorMultiplier : 1))
3805 return false;
3806
3807 // Ok, we have the budget. Perform the transformation.
3808 for (BasicBlock *PredBlock : Preds) {
3809 auto *PBI = cast<BranchInst>(PredBlock->getTerminator());
3810 return performBranchToCommonDestFolding(BI, PBI, DTU, MSSAU, TTI);
3811 }
3812 return false;
3813}
3814
3815// If there is only one store in BB1 and BB2, return it, otherwise return
3816// nullptr.
3818 StoreInst *S = nullptr;
3819 for (auto *BB : {BB1, BB2}) {
3820 if (!BB)
3821 continue;
3822 for (auto &I : *BB)
3823 if (auto *SI = dyn_cast<StoreInst>(&I)) {
3824 if (S)
3825 // Multiple stores seen.
3826 return nullptr;
3827 else
3828 S = SI;
3829 }
3830 }
3831 return S;
3832}
3833
3835 Value *AlternativeV = nullptr) {
3836 // PHI is going to be a PHI node that allows the value V that is defined in
3837 // BB to be referenced in BB's only successor.
3838 //
3839 // If AlternativeV is nullptr, the only value we care about in PHI is V. It
3840 // doesn't matter to us what the other operand is (it'll never get used). We
3841 // could just create a new PHI with an undef incoming value, but that could
3842 // increase register pressure if EarlyCSE/InstCombine can't fold it with some
3843 // other PHI. So here we directly look for some PHI in BB's successor with V
3844 // as an incoming operand. If we find one, we use it, else we create a new
3845 // one.
3846 //
3847 // If AlternativeV is not nullptr, we care about both incoming values in PHI.
3848 // PHI must be exactly: phi <ty> [ %BB, %V ], [ %OtherBB, %AlternativeV]
3849 // where OtherBB is the single other predecessor of BB's only successor.
3850 PHINode *PHI = nullptr;
3851 BasicBlock *Succ = BB->getSingleSuccessor();
3852
3853 for (auto I = Succ->begin(); isa<PHINode>(I); ++I)
3854 if (cast<PHINode>(I)->getIncomingValueForBlock(BB) == V) {
3855 PHI = cast<PHINode>(I);
3856 if (!AlternativeV)
3857 break;
3858
3859 assert(Succ->hasNPredecessors(2));
3860 auto PredI = pred_begin(Succ);
3861 BasicBlock *OtherPredBB = *PredI == BB ? *++PredI : *PredI;
3862 if (PHI->getIncomingValueForBlock(OtherPredBB) == AlternativeV)
3863 break;
3864 PHI = nullptr;
3865 }
3866 if (PHI)
3867 return PHI;
3868
3869 // If V is not an instruction defined in BB, just return it.
3870 if (!AlternativeV &&
3871 (!isa<Instruction>(V) || cast<Instruction>(V)->getParent() != BB))
3872 return V;
3873
3874 PHI = PHINode::Create(V->getType(), 2, "simplifycfg.merge", &Succ->front());
3875 PHI->addIncoming(V, BB);
3876 for (BasicBlock *PredBB : predecessors(Succ))
3877 if (PredBB != BB)
3878 PHI->addIncoming(
3879 AlternativeV ? AlternativeV : UndefValue::get(V->getType()), PredBB);
3880 return PHI;
3881}
3882
3884 BasicBlock *PTB, BasicBlock *PFB, BasicBlock *QTB, BasicBlock *QFB,
3885 BasicBlock *PostBB, Value *Address, bool InvertPCond, bool InvertQCond,
3886 DomTreeUpdater *DTU, const DataLayout &DL, const TargetTransformInfo &TTI) {
3887 // For every pointer, there must be exactly two stores, one coming from
3888 // PTB or PFB, and the other from QTB or QFB. We don't support more than one
3889 // store (to any address) in PTB,PFB or QTB,QFB.
3890 // FIXME: We could relax this restriction with a bit more work and performance
3891 // testing.
3892 StoreInst *PStore = findUniqueStoreInBlocks(PTB, PFB);
3893 StoreInst *QStore = findUniqueStoreInBlocks(QTB, QFB);
3894 if (!PStore || !QStore)
3895 return false;
3896
3897 // Now check the stores are compatible.
3898 if (!QStore->isUnordered() || !PStore->isUnordered() ||
3899 PStore->getValueOperand()->getType() !=
3900 QStore->getValueOperand()->getType())
3901 return false;
3902
3903 // Check that sinking the store won't cause program behavior changes. Sinking
3904 // the store out of the Q blocks won't change any behavior as we're sinking
3905 // from a block to its unconditional successor. But we're moving a store from
3906 // the P blocks down through the middle block (QBI) and past both QFB and QTB.
3907 // So we need to check that there are no aliasing loads or stores in
3908 // QBI, QTB and QFB. We also need to check there are no conflicting memory
3909 // operations between PStore and the end of its parent block.
3910 //
3911 // The ideal way to do this is to query AliasAnalysis, but we don't
3912 // preserve AA currently so that is dangerous. Be super safe and just
3913 // check there are no other memory operations at all.
3914 for (auto &I : *QFB->getSinglePredecessor())
3915 if (I.mayReadOrWriteMemory())
3916 return false;
3917 for (auto &I : *QFB)
3918 if (&I != QStore && I.mayReadOrWriteMemory())
3919 return false;
3920 if (QTB)
3921 for (auto &I : *QTB)
3922 if (&I != QStore && I.mayReadOrWriteMemory())
3923 return false;
3924 for (auto I = BasicBlock::iterator(PStore), E = PStore->getParent()->end();
3925 I != E; ++I)
3926 if (&*I != PStore && I->mayReadOrWriteMemory())
3927 return false;
3928
3929 // If we're not in aggressive mode, we only optimize if we have some
3930 // confidence that by optimizing we'll allow P and/or Q to be if-converted.
3931 auto IsWorthwhile = [&](BasicBlock *BB, ArrayRef<StoreInst *> FreeStores) {
3932 if (!BB)
3933 return true;
3934 // Heuristic: if the block can be if-converted/phi-folded and the
3935 // instructions inside are all cheap (arithmetic/GEPs), it's worthwhile to
3936 // thread this store.
3938 InstructionCost Budget =
3940 for (auto &I : BB->instructionsWithoutDebug(false)) {
3941 // Consider terminator instruction to be free.
3942 if (I.isTerminator())
3943 continue;
3944 // If this is one the stores that we want to speculate out of this BB,
3945 // then don't count it's cost, consider it to be free.
3946 if (auto *S = dyn_cast<StoreInst>(&I))
3947 if (llvm::find(FreeStores, S))
3948 continue;
3949 // Else, we have a white-list of instructions that we are ak speculating.
3950 if (!isa<BinaryOperator>(I) && !isa<GetElementPtrInst>(I))
3951 return false; // Not in white-list - not worthwhile folding.
3952 // And finally, if this is a non-free instruction that we are okay
3953 // speculating, ensure that we consider the speculation budget.
3954 Cost +=
3956 if (Cost > Budget)
3957 return false; // Eagerly refuse to fold as soon as we're out of budget.
3958 }
3959 assert(Cost <= Budget &&
3960 "When we run out of budget we will eagerly return from within the "
3961 "per-instruction loop.");
3962 return true;
3963 };
3964
3965 const std::array<StoreInst *, 2> FreeStores = {PStore, QStore};
3967 (!IsWorthwhile(PTB, FreeStores) || !IsWorthwhile(PFB, FreeStores) ||
3968 !IsWorthwhile(QTB, FreeStores) || !IsWorthwhile(QFB, FreeStores)))
3969 return false;
3970
3971 // If PostBB has more than two predecessors, we need to split it so we can
3972 // sink the store.
3973 if (std::next(pred_begin(PostBB), 2) != pred_end(PostBB)) {
3974 // We know that QFB's only successor is PostBB. And QFB has a single
3975 // predecessor. If QTB exists, then its only successor is also PostBB.
3976 // If QTB does not exist, then QFB's only predecessor has a conditional
3977 // branch to QFB and PostBB.
3978 BasicBlock *TruePred = QTB ? QTB : QFB->getSinglePredecessor();
3979 BasicBlock *NewBB =
3980 SplitBlockPredecessors(PostBB, {QFB, TruePred}, "condstore.split", DTU);
3981 if (!NewBB)
3982 return false;
3983 PostBB = NewBB;
3984 }
3985
3986 // OK, we're going to sink the stores to PostBB. The store has to be
3987 // conditional though, so first create the predicate.
3988 Value *PCond = cast<BranchInst>(PFB->getSinglePredecessor()->getTerminator())
3989 ->getCondition();
3990 Value *QCond = cast<BranchInst>(QFB->getSinglePredecessor()->getTerminator())
3991 ->getCondition();
3992
3994 PStore->getParent());
3996 QStore->getParent(), PPHI);
3997
3998 IRBuilder<> QB(&*PostBB->getFirstInsertionPt());
3999
4000 Value *PPred = PStore->getParent() == PTB ? PCond : QB.CreateNot(PCond);
4001 Value *QPred = QStore->getParent() == QTB ? QCond : QB.CreateNot(QCond);
4002
4003 if (InvertPCond)
4004 PPred = QB.CreateNot(PPred);
4005 if (InvertQCond)
4006 QPred = QB.CreateNot(QPred);
4007 Value *CombinedPred = QB.CreateOr(PPred, QPred);
4008
4009 auto *T = SplitBlockAndInsertIfThen(CombinedPred, &*QB.GetInsertPoint(),
4010 /*Unreachable=*/false,
4011 /*BranchWeights=*/nullptr, DTU);
4012 QB.SetInsertPoint(T);
4013 StoreInst *SI = cast<StoreInst>(QB.CreateStore(QPHI, Address));
4014 SI->setAAMetadata(PStore->getAAMetadata().merge(QStore->getAAMetadata()));
4015 // Choose the minimum alignment. If we could prove both stores execute, we
4016 // could use biggest one. In this case, though, we only know that one of the
4017 // stores executes. And we don't know it's safe to take the alignment from a
4018 // store that doesn't execute.
4019 SI->setAlignment(std::min(PStore->getAlign(), QStore->getAlign()));
4020
4021 QStore->eraseFromParent();
4022 PStore->eraseFromParent();
4023
4024 return true;
4025}
4026
4028 DomTreeUpdater *DTU, const DataLayout &DL,
4029 const TargetTransformInfo &TTI) {
4030 // The intention here is to find diamonds or triangles (see below) where each
4031 // conditional block contains a store to the same address. Both of these
4032 // stores are conditional, so they can't be unconditionally sunk. But it may
4033 // be profitable to speculatively sink the stores into one merged store at the
4034 // end, and predicate the merged store on the union of the two conditions of
4035 // PBI and QBI.
4036 //
4037 // This can reduce the number of stores executed if both of the conditions are
4038 // true, and can allow the blocks to become small enough to be if-converted.
4039 // This optimization will also chain, so that ladders of test-and-set
4040 // sequences can be if-converted away.
4041 //
4042 // We only deal with simple diamonds or triangles:
4043 //
4044 // PBI or PBI or a combination of the two
4045 // / \ | \
4046 // PTB PFB | PFB
4047 // \ / | /
4048 // QBI QBI
4049 // / \ | \
4050 // QTB QFB | QFB
4051 // \ / | /
4052 // PostBB PostBB
4053 //
4054 // We model triangles as a type of diamond with a nullptr "true" block.
4055 // Triangles are canonicalized so that the fallthrough edge is represented by
4056 // a true condition, as in the diagram above.
4057 BasicBlock *PTB = PBI->getSuccessor(0);
4058 BasicBlock *PFB = PBI->getSuccessor(1);
4059 BasicBlock *QTB = QBI->getSuccessor(0);
4060 BasicBlock *QFB = QBI->getSuccessor(1);
4061 BasicBlock *PostBB = QFB->getSingleSuccessor();
4062
4063 // Make sure we have a good guess for PostBB. If QTB's only successor is
4064 // QFB, then QFB is a better PostBB.
4065 if (QTB->getSingleSuccessor() == QFB)
4066 PostBB = QFB;
4067
4068 // If we couldn't find a good PostBB, stop.
4069 if (!PostBB)
4070 return false;
4071
4072 bool InvertPCond = false, InvertQCond = false;
4073 // Canonicalize fallthroughs to the true branches.
4074 if (PFB == QBI->getParent()) {
4075 std::swap(PFB, PTB);
4076 InvertPCond = true;
4077 }
4078 if (QFB == PostBB) {
4079 std::swap(QFB, QTB);
4080 InvertQCond = true;
4081 }
4082
4083 // From this point on we can assume PTB or QTB may be fallthroughs but PFB
4084 // and QFB may not. Model fallthroughs as a nullptr block.
4085 if (PTB == QBI->getParent())
4086 PTB = nullptr;
4087 if (QTB == PostBB)
4088 QTB = nullptr;
4089
4090 // Legality bailouts. We must have at least the non-fallthrough blocks and
4091 // the post-dominating block, and the non-fallthroughs must only have one
4092 // predecessor.
4093 auto HasOnePredAndOneSucc = [](BasicBlock *BB, BasicBlock *P, BasicBlock *S) {
4094 return BB->getSinglePredecessor() == P && BB->getSingleSuccessor() == S;
4095 };
4096 if (!HasOnePredAndOneSucc(PFB, PBI->getParent(), QBI->getParent()) ||
4097 !HasOnePredAndOneSucc(QFB, QBI->getParent(), PostBB))
4098 return false;
4099 if ((PTB && !HasOnePredAndOneSucc(PTB, PBI->getParent(), QBI->getParent())) ||
4100 (QTB && !HasOnePredAndOneSucc(QTB, QBI->getParent(), PostBB)))
4101 return false;
4102 if (!QBI->getParent()->hasNUses(2))
4103 return false;
4104
4105 // OK, this is a sequence of two diamonds or triangles.
4106 // Check if there are stores in PTB or PFB that are repeated in QTB or QFB.
4107 SmallPtrSet<Value *, 4> PStoreAddresses, QStoreAddresses;
4108 for (auto *BB : {PTB, PFB}) {
4109 if (!BB)
4110 continue;
4111 for (auto &I : *BB)
4112 if (StoreInst *SI = dyn_cast<StoreInst>(&I))
4113 PStoreAddresses.insert(SI->getPointerOperand());
4114 }
4115 for (auto *BB : {QTB, QFB}) {
4116 if (!BB)
4117 continue;
4118 for (auto &I : *BB)
4119 if (StoreInst *SI = dyn_cast<StoreInst>(&I))
4120 QStoreAddresses.insert(SI->getPointerOperand());
4121 }
4122
4123 set_intersect(PStoreAddresses, QStoreAddresses);
4124 // set_intersect mutates PStoreAddresses in place. Rename it here to make it
4125 // clear what it contains.
4126 auto &CommonAddresses = PStoreAddresses;
4127
4128 bool Changed = false;
4129 for (auto *Address : CommonAddresses)
4130 Changed |=
4131 mergeConditionalStoreToAddress(PTB, PFB, QTB, QFB, PostBB, Address,
4132 InvertPCond, InvertQCond, DTU, DL, TTI);
4133 return Changed;
4134}
4135
4136/// If the previous block ended with a widenable branch, determine if reusing
4137/// the target block is profitable and legal. This will have the effect of
4138/// "widening" PBI, but doesn't require us to reason about hosting safety.
4140 DomTreeUpdater *DTU) {
4141 // TODO: This can be generalized in two important ways:
4142 // 1) We can allow phi nodes in IfFalseBB and simply reuse all the input
4143 // values from the PBI edge.
4144 // 2) We can sink side effecting instructions into BI's fallthrough
4145 // successor provided they doesn't contribute to computation of
4146 // BI's condition.
4147 Value *CondWB, *WC;
4148 BasicBlock *IfTrueBB, *IfFalseBB;
4149 if (!parseWidenableBranch(PBI, CondWB, WC, IfTrueBB, IfFalseBB) ||
4150 IfTrueBB != BI->getParent() || !BI->getParent()->getSinglePredecessor())
4151 return false;
4152 if (!IfFalseBB->phis().empty())
4153 return false; // TODO
4154 // This helps avoid infinite loop with SimplifyCondBranchToCondBranch which
4155 // may undo the transform done here.
4156 // TODO: There might be a more fine-grained solution to this.
4157 if (!llvm::succ_empty(IfFalseBB))
4158 return false;
4159 // Use lambda to lazily compute expensive condition after cheap ones.
4160 auto NoSideEffects = [](BasicBlock &BB) {
4161 return llvm::none_of(BB, [](const Instruction &I) {
4162 return I.mayWriteToMemory() || I.mayHaveSideEffects();
4163 });
4164 };
4165 if (BI->getSuccessor(1) != IfFalseBB && // no inf looping
4166 BI->getSuccessor(1)->getTerminatingDeoptimizeCall() && // profitability
4167 NoSideEffects(*BI->getParent())) {
4168 auto *OldSuccessor = BI->getSuccessor(1);
4169 OldSuccessor->removePredecessor(BI->getParent());
4170 BI->setSuccessor(1, IfFalseBB);
4171 if (DTU)
4172 DTU->applyUpdates(
4173 {{DominatorTree::Insert, BI->getParent(), IfFalseBB},
4174 {DominatorTree::Delete, BI->getParent(), OldSuccessor}});
4175 return true;
4176 }
4177 if (BI->getSuccessor(0) != IfFalseBB && // no inf looping
4178 BI->getSuccessor(0)->getTerminatingDeoptimizeCall() && // profitability
4179 NoSideEffects(*BI->getParent())) {
4180 auto *OldSuccessor = BI->getSuccessor(0);
4181 OldSuccessor->removePredecessor(BI->getParent());
4182 BI->setSuccessor(0, IfFalseBB);
4183 if (DTU)
4184 DTU->applyUpdates(
4185 {{DominatorTree::Insert, BI->getParent(), IfFalseBB},
4186 {DominatorTree::Delete, BI->getParent(), OldSuccessor}});
4187 return true;
4188 }
4189 return false;
4190}
4191
4192/// If we have a conditional branch as a predecessor of another block,
4193/// this function tries to simplify it. We know
4194/// that PBI and BI are both conditional branches, and BI is in one of the
4195/// successor blocks of PBI - PBI branches to BI.
4197 DomTreeUpdater *DTU,
4198 const DataLayout &DL,
4199 const TargetTransformInfo &TTI) {
4200 assert(PBI->isConditional() && BI->isConditional());
4201 BasicBlock *BB = BI->getParent();
4202
4203 // If this block ends with a branch instruction, and if there is a
4204 // predecessor that ends on a branch of the same condition, make
4205 // this conditional branch redundant.
4206 if (PBI->getCondition() == BI->getCondition() &&
4207 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
4208 // Okay, the outcome of this conditional branch is statically
4209 // knowable. If this block had a single pred, handle specially, otherwise
4210 // FoldCondBranchOnValueKnownInPredecessor() will handle it.
4211 if (BB->getSinglePredecessor()) {
4212 // Turn this into a branch on constant.
4213 bool CondIsTrue = PBI->getSuccessor(0) == BB;
4214 BI->setCondition(
4215 ConstantInt::get(Type::getInt1Ty(BB->getContext()), CondIsTrue));
4216 return true; // Nuke the branch on constant.
4217 }
4218 }
4219
4220 // If the previous block ended with a widenable branch, determine if reusing
4221 // the target block is profitable and legal. This will have the effect of
4222 // "widening" PBI, but doesn't require us to reason about hosting safety.
4223 if (tryWidenCondBranchToCondBranch(PBI, BI, DTU))
4224 return true;
4225
4226 // If both branches are conditional and both contain stores to the same
4227 // address, remove the stores from the conditionals and create a conditional
4228 // merged store at the end.
4229 if (MergeCondStores && mergeConditionalStores(PBI, BI, DTU, DL, TTI))
4230 return true;
4231
4232 // If this is a conditional branch in an empty block, and if any
4233 // predecessors are a conditional branch to one of our destinations,
4234 // fold the conditions into logical ops and one cond br.
4235
4236 // Ignore dbg intrinsics.
4237 if (&*BB->instructionsWithoutDebug(false).begin() != BI)
4238 return false;
4239
4240 int PBIOp, BIOp;
4241 if (PBI->getSuccessor(0) == BI->getSuccessor(0)) {
4242 PBIOp = 0;
4243 BIOp = 0;
4244 } else if (PBI->getSuccessor(0) == BI->getSuccessor(1)) {
4245 PBIOp = 0;
4246 BIOp = 1;
4247 } else if (PBI->getSuccessor(1) == BI->getSuccessor(0)) {
4248 PBIOp = 1;
4249 BIOp = 0;
4250 } else if (PBI->getSuccessor(1) == BI->getSuccessor(1)) {
4251 PBIOp = 1;
4252 BIOp = 1;
4253 } else {
4254 return false;
4255 }
4256
4257 // Check to make sure that the other destination of this branch
4258 // isn't BB itself. If so, this is an infinite loop that will
4259 // keep getting unwound.
4260 if (PBI->getSuccessor(PBIOp) == BB)
4261 return false;
4262
4263 // Do not perform this transformation if it would require
4264 // insertion of a large number of select instructions. For targets
4265 // without predication/cmovs, this is a big pessimization.
4266
4267 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
4268 BasicBlock *RemovedDest = PBI->getSuccessor(PBIOp ^ 1);
4269 unsigned NumPhis = 0;
4270 for (BasicBlock::iterator II = CommonDest->begin(); isa<PHINode>(II);
4271 ++II, ++NumPhis) {
4272 if (NumPhis > 2) // Disable this xform.
4273 return false;
4274 }
4275
4276 // Finally, if everything is ok, fold the branches to logical ops.
4277 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
4278
4279 LLVM_DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
4280 << "AND: " << *BI->getParent());
4281
4283
4284 // If OtherDest *is* BB, then BB is a basic block with a single conditional
4285 // branch in it, where one edge (OtherDest) goes back to itself but the other
4286 // exits. We don't *know* that the program avoids the infinite loop
4287 // (even though that seems likely). If we do this xform naively, we'll end up
4288 // recursively unpeeling the loop. Since we know that (after the xform is
4289 // done) that the block *is* infinite if reached, we just make it an obviously
4290 // infinite loop with no cond branch.
4291 if (OtherDest == BB) {
4292 // Insert it at the end of the function, because it's either code,
4293 // or it won't matter if it's hot. :)
4294 BasicBlock *InfLoopBlock =
4295 BasicBlock::Create(BB->getContext(), "infloop", BB->getParent());
4296 BranchInst::Create(InfLoopBlock, InfLoopBlock);
4297 if (DTU)
4298 Updates.push_back({DominatorTree::Insert, InfLoopBlock, InfLoopBlock});
4299 OtherDest = InfLoopBlock;
4300 }
4301
4302 LLVM_DEBUG(dbgs() << *PBI->getParent()->getParent());
4303
4304 // BI may have other predecessors. Because of this, we leave
4305 // it alone, but modify PBI.
4306
4307 // Make sure we get to CommonDest on True&True directions.
4308 Value *PBICond = PBI->getCondition();
4310 if (PBIOp)
4311 PBICond = Builder.CreateNot(PBICond, PBICond->getName() + ".not");
4312
4313 Value *BICond = BI->getCondition();
4314 if (BIOp)
4315 BICond = Builder.CreateNot(BICond, BICond->getName() + ".not");
4316
4317 // Merge the conditions.
4318 Value *Cond =
4319 createLogicalOp(Builder, Instruction::Or, PBICond, BICond, "brmerge");
4320
4321 // Modify PBI to branch on the new condition to the new dests.
4322 PBI->setCondition(Cond);
4323 PBI->setSuccessor(0, CommonDest);
4324 PBI->setSuccessor(1, OtherDest);
4325
4326 if (DTU) {
4327 Updates.push_back({DominatorTree::Insert, PBI->getParent(), OtherDest});
4328 Updates.push_back({DominatorTree::Delete, PBI->getParent(), RemovedDest});
4329
4330 DTU->applyUpdates(Updates);
4331 }
4332
4333 // Update branch weight for PBI.
4334 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
4335 uint64_t PredCommon, PredOther, SuccCommon, SuccOther;
4336 bool HasWeights =
4337 extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight,
4338 SuccTrueWeight, SuccFalseWeight);
4339 if (HasWeights) {
4340 PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
4341 PredOther = PBIOp ? PredTrueWeight : PredFalseWeight;
4342 SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
4343 SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
4344 // The weight to CommonDest should be PredCommon * SuccTotal +
4345 // PredOther * SuccCommon.
4346 // The weight to OtherDest should be PredOther * SuccOther.
4347 uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther) +
4348 PredOther * SuccCommon,
4349 PredOther * SuccOther};
4350 // Halve the weights if any of them cannot fit in an uint32_t
4351 FitWeights(NewWeights);
4352
4353 setBranchWeights(PBI, NewWeights[0], NewWeights[1]);
4354 }
4355
4356 // OtherDest may have phi nodes. If so, add an entry from PBI's
4357 // block that are identical to the entries for BI's block.
4358 AddPredecessorToBlock(OtherDest, PBI->getParent(), BB);
4359
4360 // We know that the CommonDest already had an edge from PBI to
4361 // it. If it has PHIs though, the PHIs may have different
4362 // entries for BB and PBI's BB. If so, insert a select to make
4363 // them agree.
4364 for (PHINode &PN : CommonDest->phis()) {
4365 Value *BIV = PN.getIncomingValueForBlock(BB);
4366 unsigned PBBIdx = PN.getBasicBlockIndex(PBI->getParent());
4367 Value *PBIV = PN.getIncomingValue(PBBIdx);
4368 if (BIV != PBIV) {
4369 // Insert a select in PBI to pick the right value.
4370 SelectInst *NV = cast<SelectInst>(
4371 Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName() + ".mux"));
4372 PN.setIncomingValue(PBBIdx, NV);
4373 // Although the select has the same condition as PBI, the original branch
4374 // weights for PBI do not apply to the new select because the select's
4375 // 'logical' edges are incoming edges of the phi that is eliminated, not
4376 // the outgoing edges of PBI.
4377 if (HasWeights) {
4378 uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
4379 uint64_t PredOther = PBIOp ? PredTrueWeight : PredFalseWeight;
4380 uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
4381 uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
4382 // The weight to PredCommonDest should be PredCommon * SuccTotal.
4383 // The weight to PredOtherDest should be PredOther * SuccCommon.
4384 uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther),
4385 PredOther * SuccCommon};
4386
4387 FitWeights(NewWeights);
4388
4389 setBranchWeights(NV, NewWeights[0], NewWeights[1]);
4390 }
4391 }
4392 }
4393
4394 LLVM_DEBUG(dbgs() << "INTO: " << *PBI->getParent());
4395 LLVM_DEBUG(dbgs() << *PBI->getParent()->getParent());
4396
4397 // This basic block is probably dead. We know it has at least
4398 // one fewer predecessor.
4399 return true;
4400}
4401
4402// Simplifies a terminator by replacing it with a branch to TrueBB if Cond is
4403// true or to FalseBB if Cond is false.
4404// Takes care of updating the successors and removing the old terminator.
4405// Also makes sure not to introduce new successors by assuming that edges to
4406// non-successor TrueBBs and FalseBBs aren't reachable.
4407bool SimplifyCFGOpt::SimplifyTerminatorOnSelect(Instruction *OldTerm,
4408 Value *Cond, BasicBlock *TrueBB,
4409 BasicBlock *FalseBB,
4410 uint32_t TrueWeight,
4411 uint32_t FalseWeight) {
4412 auto *BB = OldTerm->getParent();
4413 // Remove any superfluous successor edges from the CFG.
4414 // First, figure out which successors to preserve.
4415 // If TrueBB and FalseBB are equal, only try to preserve one copy of that
4416 // successor.
4417 BasicBlock *KeepEdge1 = TrueBB;
4418 BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr;
4419
4420 SmallSetVector<BasicBlock *, 2> RemovedSuccessors;
4421
4422 // Then remove the rest.
4423 for (BasicBlock *Succ : successors(OldTerm)) {
4424 // Make sure only to keep exactly one copy of each edge.
4425 if (Succ == KeepEdge1)
4426 KeepEdge1 = nullptr;
4427 else if (Succ == KeepEdge2)
4428 KeepEdge2 = nullptr;
4429 else {
4430 Succ->removePredecessor(BB,
4431 /*KeepOneInputPHIs=*/true);
4432
4433 if (Succ != TrueBB && Succ != FalseBB)
4434 RemovedSuccessors.insert(Succ);
4435 }
4436 }
4437
4438 IRBuilder<> Builder(OldTerm);
4439 Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc());
4440
4441 // Insert an appropriate new terminator.
4442 if (!KeepEdge1 && !KeepEdge2) {
4443 if (TrueBB == FalseBB) {
4444 // We were only looking for one successor, and it was present.
4445 // Create an unconditional branch to it.
4446 Builder.CreateBr(TrueBB);
4447 } else {
4448 // We found both of the successors we were looking for.
4449 // Create a conditional branch sharing the condition of the select.
4450 BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB);
4451 if (TrueWeight != FalseWeight)
4452 setBranchWeights(NewBI, TrueWeight, FalseWeight);
4453 }
4454 } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
4455 // Neither of the selected blocks were successors, so this
4456 // terminator must be unreachable.
4457 new UnreachableInst(OldTerm->getContext(), OldTerm);
4458 } else {
4459 // One of the selected values was a successor, but the other wasn't.
4460 // Insert an unconditional branch to the one that was found;
4461 // the edge to the one that wasn't must be unreachable.
4462 if (!KeepEdge1) {
4463 // Only TrueBB was found.
4464 Builder.CreateBr(TrueBB);
4465 } else {
4466 // Only FalseBB was found.
4467 Builder.CreateBr(FalseBB);
4468 }
4469 }
4470
4472
4473 if (DTU) {
4475 Updates.reserve(RemovedSuccessors.size());
4476 for (auto *RemovedSuccessor : RemovedSuccessors)
4477 Updates.push_back({DominatorTree::Delete, BB, RemovedSuccessor});
4478 DTU->applyUpdates(Updates);
4479 }
4480
4481 return true;
4482}
4483
4484// Replaces
4485// (switch (select cond, X, Y)) on constant X, Y
4486// with a branch - conditional if X and Y lead to distinct BBs,
4487// unconditional otherwise.
4488bool SimplifyCFGOpt::SimplifySwitchOnSelect(SwitchInst *SI,
4489 SelectInst *Select) {
4490 // Check for constant integer values in the select.
4491 ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue());
4492 ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue());
4493 if (!TrueVal || !FalseVal)
4494 return false;
4495
4496 // Find the relevant condition and destinations.
4497 Value *Condition = Select->getCondition();
4498 BasicBlock *TrueBB = SI->findCaseValue(TrueVal)->getCaseSuccessor();
4499 BasicBlock *FalseBB = SI->findCaseValue(FalseVal)->getCaseSuccessor();
4500
4501 // Get weight for TrueBB and FalseBB.
4502 uint32_t TrueWeight = 0, FalseWeight = 0;
4504 bool HasWeights = hasBranchWeightMD(*SI);
4505 if (HasWeights) {
4506 GetBranchWeights(SI, Weights);
4507 if (Weights.size() == 1 + SI->getNumCases()) {
4508 TrueWeight =
4509 (uint32_t)Weights[SI->findCaseValue(TrueVal)->getSuccessorIndex()];
4510 FalseWeight =
4511 (uint32_t)Weights[SI->findCaseValue(FalseVal)->getSuccessorIndex()];
4512 }
4513 }
4514
4515 // Perform the actual simplification.
4516 return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB, TrueWeight,
4517 FalseWeight);
4518}
4519
4520// Replaces
4521// (indirectbr (select cond, blockaddress(@fn, BlockA),
4522// blockaddress(@fn, BlockB)))
4523// with
4524// (br cond, BlockA, BlockB).
4525bool SimplifyCFGOpt::SimplifyIndirectBrOnSelect(IndirectBrInst *IBI,
4526 SelectInst *SI) {
4527 // Check that both operands of the select are block addresses.
4528 BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
4529 BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
4530 if (!TBA || !FBA)
4531 return false;
4532
4533 // Extract the actual blocks.
4534 BasicBlock *TrueBB = TBA->getBasicBlock();
4535 BasicBlock *FalseBB = FBA->getBasicBlock();
4536
4537 // Perform the actual simplification.
4538 return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB, 0,
4539 0);
4540}
4541
4542/// This is called when we find an icmp instruction
4543/// (a seteq/setne with a constant) as the only instruction in a
4544/// block that ends with an uncond branch. We are looking for a very specific
4545/// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In
4546/// this case, we merge the first two "or's of icmp" into a switch, but then the
4547/// default value goes to an uncond block with a seteq in it, we get something
4548/// like:
4549///
4550/// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ]
4551/// DEFAULT:
4552/// %tmp = icmp eq i8 %A, 92
4553/// br label %end
4554/// end:
4555/// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
4556///
4557/// We prefer to split the edge to 'end' so that there is a true/false entry to
4558/// the PHI, merging the third icmp into the switch.
4559bool SimplifyCFGOpt::tryToSimplifyUncondBranchWithICmpInIt(
4560 ICmpInst *ICI, IRBuilder<> &Builder) {
4561 BasicBlock *BB = ICI->getParent();
4562
4563 // If the block has any PHIs in it or the icmp has multiple uses, it is too
4564 // complex.
4565 if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse())
4566 return false;
4567
4568 Value *V = ICI->getOperand(0);
4569 ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1));
4570
4571 // The pattern we're looking for is where our only predecessor is a switch on
4572 // 'V' and this block is the default case for the switch. In this case we can
4573 // fold the compared value into the switch to simplify things.
4574 BasicBlock *Pred = BB->getSinglePredecessor();
4575 if (!Pred || !isa<SwitchInst>(Pred->getTerminator()))
4576 return false;
4577
4578 SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
4579 if (SI->getCondition() != V)
4580 return false;
4581
4582 // If BB is reachable on a non-default case, then we simply know the value of
4583 // V in this block. Substitute it and constant fold the icmp instruction
4584 // away.
4585 if (SI->getDefaultDest() != BB) {
4586 ConstantInt *VVal = SI->findCaseDest(BB);
4587 assert(VVal && "Should have a unique destination value");
4588 ICI->setOperand(0, VVal);
4589
4590 if (Value *V = simplifyInstruction(ICI, {DL, ICI})) {
4591 ICI->replaceAllUsesWith(V);
4592 ICI->eraseFromParent();
4593 }
4594 // BB is now empty, so it is likely to simplify away.
4595 return requestResimplify();
4596 }
4597
4598 // Ok, the block is reachable from the default dest. If the constant we're
4599 // comparing exists in one of the other edges, then we can constant fold ICI
4600 // and zap it.
4601 if (SI->findCaseValue(Cst) != SI->case_default()) {
4602 Value *V;
4603 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
4605 else
4607
4608 ICI->replaceAllUsesWith(V);
4609 ICI->eraseFromParent();
4610 // BB is now empty, so it is likely to simplify away.
4611 return requestResimplify();
4612 }
4613
4614 // The use of the icmp has to be in the 'end' block, by the only PHI node in
4615 // the block.
4616 BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
4617 PHINode *PHIUse = dyn_cast<PHINode>(ICI->user_back());
4618 if (PHIUse == nullptr || PHIUse != &SuccBlock->front() ||
4619 isa<PHINode>(++BasicBlock::iterator(PHIUse)))
4620 return false;
4621
4622 // If the icmp is a SETEQ, then the default dest gets false, the new edge gets
4623 // true in the PHI.
4624 Constant *DefaultCst = ConstantInt::getTrue(BB->getContext());
4625 Constant *NewCst = ConstantInt::getFalse(BB->getContext());
4626
4627 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
4628 std::swap(DefaultCst, NewCst);
4629
4630 // Replace ICI (which is used by the PHI for the default value) with true or
4631 // false depending on if it is EQ or NE.
4632 ICI->replaceAllUsesWith(DefaultCst);
4633 ICI->eraseFromParent();
4634
4636
4637 // Okay, the switch goes to this block on a default value. Add an edge from
4638 // the switch to the merge point on the compared value.
4639 BasicBlock *NewBB =
4640 BasicBlock::Create(BB->getContext(), "switch.edge", BB->getParent(), BB);
4641 {
4643 auto W0 = SIW.getSuccessorWeight(0);
4645 if (W0) {
4646 NewW = ((uint64_t(*W0) + 1) >> 1);
4647 SIW.setSuccessorWeight(0, *NewW);
4648 }
4649 SIW.addCase(Cst, NewBB, NewW);
4650 if (DTU)
4651 Updates.push_back({DominatorTree::Insert, Pred, NewBB});
4652 }
4653
4654 // NewBB branches to the phi block, add the uncond branch and the phi entry.
4655 Builder.SetInsertPoint(NewBB);
4656 Builder.SetCurrentDebugLocation(SI->getDebugLoc());
4657 Builder.CreateBr(SuccBlock);
4658 PHIUse->addIncoming(NewCst, NewBB);
4659 if (DTU) {
4660 Updates.push_back({DominatorTree::Insert, NewBB, SuccBlock});
4661 DTU->applyUpdates(Updates);
4662 }
4663 return true;
4664}
4665
4666/// The specified branch is a conditional branch.
4667/// Check to see if it is branching on an or/and chain of icmp instructions, and
4668/// fold it into a switch instruction if so.
4669bool SimplifyCFGOpt::SimplifyBranchOnICmpChain(BranchInst *BI,
4670 IRBuilder<> &Builder,
4671 const DataLayout &DL) {
4672 Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
4673 if (!Cond)
4674 return false;
4675
4676 // Change br (X == 0 | X == 1), T, F into a switch instruction.
4677 // If this is a bunch of seteq's or'd together, or if it's a bunch of
4678 // 'setne's and'ed together, collect them.
4679
4680 // Try to gather values from a chain of and/or to be turned into a switch
4681 ConstantComparesGatherer ConstantCompare(Cond, DL);
4682 // Unpack the result
4683 SmallVectorImpl<ConstantInt *> &Values = ConstantCompare.Vals;
4684 Value *CompVal = ConstantCompare.CompValue;
4685 unsigned UsedICmps = ConstantCompare.UsedICmps;
4686 Value *ExtraCase = ConstantCompare.Extra;
4687
4688 // If we didn't have a multiply compared value, fail.
4689 if (!CompVal)
4690 return false;
4691
4692 // Avoid turning single icmps into a switch.
4693 if (UsedICmps <= 1)
4694 return false;
4695
4696 bool TrueWhenEqual = match(Cond, m_LogicalOr(m_Value(), m_Value()));
4697
4698 // There might be duplicate constants in the list, which the switch
4699 // instruction can't handle, remove them now.
4700 array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate);
4701 Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
4702
4703 // If Extra was used, we require at least two switch values to do the
4704 // transformation. A switch with one value is just a conditional branch.
4705 if (ExtraCase && Values.size() < 2)
4706 return false;
4707
4708 // TODO: Preserve branch weight metadata, similarly to how
4709 // FoldValueComparisonIntoPredecessors preserves it.
4710
4711 // Figure out which block is which destination.
4712 BasicBlock *DefaultBB = BI->getSuccessor(1);
4713 BasicBlock *EdgeBB = BI->getSuccessor(0);
4714 if (!TrueWhenEqual)
4715 std::swap(DefaultBB, EdgeBB);
4716
4717 BasicBlock *BB = BI->getParent();
4718
4719 LLVM_DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
4720 << " cases into SWITCH. BB is:\n"
4721 << *BB);
4722
4724
4725 // If there are any extra values that couldn't be folded into the switch
4726 // then we evaluate them with an explicit branch first. Split the block
4727 // right before the condbr to handle it.
4728 if (ExtraCase) {
4729 BasicBlock *NewBB = SplitBlock(BB, BI, DTU, /*LI=*/nullptr,
4730 /*MSSAU=*/nullptr, "switch.early.test");
4731
4732 // Remove the uncond branch added to the old block.
4733 Instruction *OldTI = BB->getTerminator();
4734 Builder.SetInsertPoint(OldTI);
4735
4736 // There can be an unintended UB if extra values are Poison. Before the
4737 // transformation, extra values may not be evaluated according to the
4738 // condition, and it will not raise UB. But after transformation, we are
4739 // evaluating extra values before checking the condition, and it will raise
4740 // UB. It can be solved by adding freeze instruction to extra values.
4741 AssumptionCache *AC = Options.AC;
4742
4743 if (!isGuaranteedNotToBeUndefOrPoison(ExtraCase, AC, BI, nullptr))
4744 ExtraCase = Builder.CreateFreeze(ExtraCase);
4745
4746 if (TrueWhenEqual)
4747 Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB);
4748 else
4749 Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB);
4750
4751 OldTI->eraseFromParent();
4752
4753 if (DTU)
4754 Updates.push_back({DominatorTree::Insert, BB, EdgeBB});
4755
4756 // If there are PHI nodes in EdgeBB, then we need to add a new entry to them
4757 // for the edge we just added.
4758 AddPredecessorToBlock(EdgeBB, BB, NewBB);
4759
4760 LLVM_DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase
4761 << "\nEXTRABB = " << *BB);
4762 BB = NewBB;
4763 }
4764
4765 Builder.SetInsertPoint(BI);
4766 // Convert pointer to int before we switch.
4767 if (CompVal->getType()->isPointerTy()) {
4768 CompVal = Builder.CreatePtrToInt(
4769 CompVal, DL.getIntPtrType(CompVal->getType()), "magicptr");
4770 }
4771
4772 // Create the new switch instruction now.
4773 SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size());
4774
4775 // Add all of the 'cases' to the switch instruction.
4776 for (unsigned i = 0, e = Values.size(); i != e; ++i)
4777 New->addCase(Values[i], EdgeBB);
4778
4779 // We added edges from PI to the EdgeBB. As such, if there were any
4780 // PHI nodes in EdgeBB, they need entries to be added corresponding to
4781 // the number of edges added.
4782 for (BasicBlock::iterator BBI = EdgeBB->begin(); isa<PHINode>(BBI); ++BBI) {
4783 PHINode *PN = cast<PHINode>(BBI);
4784 Value *InVal = PN->getIncomingValueForBlock(BB);
4785 for (unsigned i = 0, e = Values.size() - 1; i != e; ++i)
4786 PN->addIncoming(InVal, BB);
4787 }
4788
4789 // Erase the old branch instruction.
4791 if (DTU)
4792 DTU->applyUpdates(Updates);
4793
4794 LLVM_DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n');
4795 return true;
4796}
4797
4798bool SimplifyCFGOpt::simplifyResume(ResumeInst *RI, IRBuilder<> &Builder) {
4799 if (isa<PHINode>(RI->getValue()))
4800 return simplifyCommonResume(RI);
4801 else if (isa<LandingPadInst>(RI->getParent()->getFirstNonPHI()) &&
4802 RI->getValue() == RI->getParent()->getFirstNonPHI())
4803 // The resume must unwind the exception that caused control to branch here.
4804 return simplifySingleResume(RI);
4805
4806 return false;
4807}
4808
4809// Check if cleanup block is empty
4811 for (Instruction &I : R) {
4812 auto *II = dyn_cast<IntrinsicInst>(&I);
4813 if (!II)
4814 return false;
4815
4816 Intrinsic::ID IntrinsicID = II->getIntrinsicID();
4817 switch (IntrinsicID) {
4818 case Intrinsic::dbg_declare:
4819 case Intrinsic::dbg_value:
4820 case Intrinsic::dbg_label:
4821 case Intrinsic::lifetime_end:
4822 break;
4823 default:
4824 return false;
4825 }
4826 }
4827 return true;
4828}
4829
4830// Simplify resume that is shared by several landing pads (phi of landing pad).
4831bool SimplifyCFGOpt::simplifyCommonResume(ResumeInst *RI) {
4832 BasicBlock *BB = RI->getParent();
4833
4834 // Check that there are no other instructions except for debug and lifetime
4835 // intrinsics between the phi's and resume instruction.
4838 return false;
4839
4840 SmallSetVector<BasicBlock *, 4> TrivialUnwindBlocks;
4841 auto *PhiLPInst = cast<PHINode>(RI->getValue());
4842
4843 // Check incoming blocks to see if any of them are trivial.
4844 for (unsigned Idx = 0, End = PhiLPInst->getNumIncomingValues(); Idx != End;
4845 Idx++) {
4846 auto *IncomingBB = PhiLPInst->getIncomingBlock(Idx);
4847 auto *IncomingValue = PhiLPInst->getIncomingValue(Idx);
4848
4849 // If the block has other successors, we can not delete it because
4850 // it has other dependents.
4851 if (IncomingBB->getUniqueSuccessor() != BB)
4852 continue;
4853
4854 auto *LandingPad = dyn_cast<LandingPadInst>(IncomingBB->getFirstNonPHI());
4855 // Not the landing pad that caused the control to branch here.
4856 if (IncomingValue != LandingPad)
4857 continue;
4858
4860 make_range(LandingPad->getNextNode(), IncomingBB->getTerminator())))
4861 TrivialUnwindBlocks.insert(IncomingBB);
4862 }
4863
4864 // If no trivial unwind blocks, don't do any simplifications.
4865 if (TrivialUnwindBlocks.empty())
4866 return false;
4867
4868 // Turn all invokes that unwind here into calls.
4869 for (auto *TrivialBB : TrivialUnwindBlocks) {
4870 // Blocks that will be simplified should be removed from the phi node.
4871 // Note there could be multiple edges to the resume block, and we need
4872 // to remove them all.
4873 while (PhiLPInst->getBasicBlockIndex(TrivialBB) != -1)
4874 BB->removePredecessor(TrivialBB, true);
4875
4876 for (BasicBlock *Pred :
4878 removeUnwindEdge(Pred, DTU);
4879 ++NumInvokes;
4880 }
4881
4882 // In each SimplifyCFG run, only the current processed block can be erased.
4883 // Otherwise, it will break the iteration of SimplifyCFG pass. So instead
4884 // of erasing TrivialBB, we only remove the branch to the common resume
4885 // block so that we can later erase the resume block since it has no
4886 // predecessors.
4887 TrivialBB->getTerminator()->eraseFromParent();
4888 new UnreachableInst(RI->getContext(), TrivialBB);
4889 if (DTU)
4890 DTU->applyUpdates({{DominatorTree::Delete, TrivialBB, BB}});
4891 }
4892
4893 // Delete the resume block if all its predecessors have been removed.
4894 if (pred_empty(BB))
4895 DeleteDeadBlock(BB, DTU);
4896
4897 return !TrivialUnwindBlocks.empty();
4898}
4899
4900// Simplify resume that is only used by a single (non-phi) landing pad.
4901bool SimplifyCFGOpt::simplifySingleResume(ResumeInst *RI) {
4902 BasicBlock *BB = RI->getParent();
4903 auto *LPInst = cast<LandingPadInst>(BB->getFirstNonPHI());
4904 assert(RI->getValue() == LPInst &&
4905 "Resume must unwind the exception that caused control to here");
4906
4907 // Check that there are no other instructions except for debug intrinsics.
4909 make_range<Instruction *>(LPInst->getNextNode(), RI)))
4910 return false;
4911
4912 // Turn all invokes that unwind here into calls and delete the basic block.
4914 removeUnwindEdge(Pred, DTU);
4915 ++NumInvokes;
4916 }
4917
4918 // The landingpad is now unreachable. Zap it.
4919 DeleteDeadBlock(BB, DTU);
4920 return true;
4921}
4922
4924 // If this is a trivial cleanup pad that executes no instructions, it can be
4925 // eliminated. If the cleanup pad continues to the caller, any predecessor
4926 // that is an EH pad will be updated to continue to the caller and any
4927 // predecessor that terminates with an invoke instruction will have its invoke
4928 // instruction converted to a call instruction. If the cleanup pad being
4929 // simplified does not continue to the caller, each predecessor will be
4930 // updated to continue to the unwind destination of the cleanup pad being
4931 // simplified.
4932 BasicBlock *BB = RI->getParent();
4933 CleanupPadInst *CPInst = RI->getCleanupPad();
4934 if (CPInst->getParent() != BB)
4935 // This isn't an empty cleanup.
4936 return false;
4937
4938 // We cannot kill the pad if it has multiple uses. This typically arises
4939 // from unreachable basic blocks.
4940 if (!CPInst->hasOneUse())
4941 return false;
4942
4943 // Check that there are no other instructions except for benign intrinsics.
4945 make_range<Instruction *>(CPInst->getNextNode(), RI)))
4946 return false;
4947
4948 // If the cleanup return we are simplifying unwinds to the caller, this will
4949 // set UnwindDest to nullptr.
4950 BasicBlock *UnwindDest = RI->getUnwindDest();
4951 Instruction *DestEHPad = UnwindDest ? UnwindDest->getFirstNonPHI() : nullptr;
4952
4953 // We're about to remove BB from the control flow. Before we do, sink any
4954 // PHINodes into the unwind destination. Doing this before changing the
4955 // control flow avoids some potentially slow checks, since we can currently
4956 // be certain that UnwindDest and BB have no common predecessors (since they
4957 // are both EH pads).
4958 if (UnwindDest) {
4959 // First, go through the PHI nodes in UnwindDest and update any nodes that
4960 // reference the block we are removing
4961 for (PHINode &DestPN : UnwindDest->phis()) {
4962 int Idx = DestPN.getBasicBlockIndex(BB);
4963 // Since BB unwinds to UnwindDest, it has to be in the PHI node.
4964 assert(Idx != -1);
4965 // This PHI node has an incoming value that corresponds to a control
4966 // path through the cleanup pad we are removing. If the incoming
4967 // value is in the cleanup pad, it must be a PHINode (because we
4968 // verified above that the block is otherwise empty). Otherwise, the
4969 // value is either a constant or a value that dominates the cleanup
4970 // pad being removed.
4971 //
4972 // Because BB and UnwindDest are both EH pads, all of their
4973 // predecessors must unwind to these blocks, and since no instruction
4974 // can have multiple unwind destinations, there will be no overlap in
4975 // incoming blocks between SrcPN and DestPN.
4976 Value *SrcVal = DestPN.getIncomingValue(Idx);
4977 PHINode *SrcPN = dyn_cast<PHINode>(SrcVal);
4978
4979 bool NeedPHITranslation = SrcPN && SrcPN->getParent() == BB;
4980 for (auto *Pred : predecessors(BB)) {
4981 Value *Incoming =
4982 NeedPHITranslation ? SrcPN->getIncomingValueForBlock(Pred) : SrcVal;
4983 DestPN.addIncoming(Incoming, Pred);
4984 }
4985 }
4986
4987 // Sink any remaining PHI nodes directly into UnwindDest.
4988 Instruction *InsertPt = DestEHPad;
4989 for (PHINode &PN : make_early_inc_range(BB->phis())) {
4990 if (PN.use_empty() || !PN.isUsedOutsideOfBlock(BB))
4991 // If the PHI node has no uses or all of its uses are in this basic
4992 // block (meaning they are debug or lifetime intrinsics), just leave
4993 // it. It will be erased when we erase BB below.
4994 continue;
4995
4996 // Otherwise, sink this PHI node into UnwindDest.
4997 // Any predecessors to UnwindDest which are not already represented
4998 // must be back edges which inherit the value from the path through
4999 // BB. In this case, the PHI value must reference itself.
5000 for (auto *pred : predecessors(UnwindDest))
5001 if (pred != BB)
5002 PN.addIncoming(&PN, pred);
5003 PN.moveBefore(InsertPt);
5004 // Also, add a dummy incoming value for the original BB itself,
5005 // so that the PHI is well-formed until we drop said predecessor.
5006 PN.addIncoming(PoisonValue::get(PN.getType()), BB);
5007 }
5008 }
5009
5010 std::vector<DominatorTree::UpdateType> Updates;
5011
5012 // We use make_early_inc_range here because we will remove all predecessors.
5014 if (UnwindDest == nullptr) {
5015 if (DTU) {
5016 DTU->applyUpdates(Updates);
5017 Updates.clear();
5018 }
5019 removeUnwindEdge(PredBB, DTU);
5020 ++NumInvokes;
5021 } else {
5022 BB->removePredecessor(PredBB);
5023 Instruction *TI = PredBB->getTerminator();
5024 TI->replaceUsesOfWith(BB, UnwindDest);
5025 if (DTU) {
5026 Updates.push_back({DominatorTree::Insert, PredBB, UnwindDest});
5027 Updates.push_back({DominatorTree::Delete, PredBB, BB});
5028 }
5029 }
5030 }
5031
5032 if (DTU)
5033 DTU->applyUpdates(Updates);
5034
5035 DeleteDeadBlock(BB, DTU);
5036
5037 return true;
5038}
5039
5040// Try to merge two cleanuppads together.
5042 // Skip any cleanuprets which unwind to caller, there is nothing to merge
5043 // with.
5044 BasicBlock *UnwindDest = RI->getUnwindDest();
5045 if (!UnwindDest)
5046 return false;
5047
5048 // This cleanupret isn't the only predecessor of this cleanuppad, it wouldn't
5049 // be safe to merge without code duplication.
5050 if (UnwindDest->getSinglePredecessor() != RI->getParent())
5051 return false;
5052
5053 // Verify that our cleanuppad's unwind destination is another cleanuppad.
5054 auto *SuccessorCleanupPad = dyn_cast<CleanupPadInst>(&UnwindDest->front());
5055 if (!SuccessorCleanupPad)
5056 return false;
5057
5058 CleanupPadInst *PredecessorCleanupPad = RI->getCleanupPad();
5059 // Replace any uses of the successor cleanupad with the predecessor pad
5060 // The only cleanuppad uses should be this cleanupret, it's cleanupret and
5061 // funclet bundle operands.
5062 SuccessorCleanupPad->replaceAllUsesWith(PredecessorCleanupPad);
5063 // Remove the old cleanuppad.
5064 SuccessorCleanupPad->eraseFromParent();
5065 // Now, we simply replace the cleanupret with a branch to the unwind
5066 // destination.
5067 BranchInst::Create(UnwindDest, RI->getParent());
5068 RI->eraseFromParent();
5069
5070 return true;
5071}
5072
5073bool SimplifyCFGOpt::simplifyCleanupReturn(CleanupReturnInst *RI) {
5074 // It is possible to transiantly have an undef cleanuppad operand because we
5075 // have deleted some, but not all, dead blocks.
5076 // Eventually, this block will be deleted.
5077 if (isa<UndefValue>(RI->getOperand(0)))
5078 return false;
5079
5080 if (mergeCleanupPad(RI))
5081 return true;
5082
5083 if (removeEmptyCleanup(RI, DTU))
5084 return true;
5085
5086 return false;
5087}
5088
5089// WARNING: keep in sync with InstCombinerImpl::visitUnreachableInst()!
5090bool SimplifyCFGOpt::simplifyUnreachable(UnreachableInst *UI) {
5091 BasicBlock *BB = UI->getParent();
5092
5093 bool Changed = false;
5094
5095 // If there are any instructions immediately before the unreachable that can
5096 // be removed, do so.
5097 while (UI->getIterator() != BB->begin()) {
5099 --BBI;
5100
5102 break; // Can not drop any more instructions. We're done here.
5103 // Otherwise, this instruction can be freely erased,
5104 // even if it is not side-effect free.
5105
5106 // Note that deleting EH's here is in fact okay, although it involves a bit
5107 // of subtle reasoning. If this inst is an EH, all the predecessors of this
5108 // block will be the unwind edges of Invoke/CatchSwitch/CleanupReturn,
5109 // and we can therefore guarantee this block will be erased.
5110
5111 // Delete this instruction (any uses are guaranteed to be dead)
5112 BBI->replaceAllUsesWith(PoisonValue::get(BBI->getType()));
5113 BBI->eraseFromParent();
5114 Changed = true;
5115 }
5116
5117 // If the unreachable instruction is the first in the block, take a gander
5118 // at all of the predecessors of this instruction, and simplify them.
5119 if (&BB->front() != UI)
5120 return Changed;
5121
5122 std::vector<DominatorTree::UpdateType> Updates;
5123
5125 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
5126 auto *Predecessor = Preds[i];
5127 Instruction *TI = Predecessor->getTerminator();
5128 IRBuilder<> Builder(TI);
5129 if (auto *BI = dyn_cast<BranchInst>(TI)) {
5130 // We could either have a proper unconditional branch,
5131 // or a degenerate conditional branch with matching destinations.
5132 if (all_of(BI->successors(),
5133 [BB](auto *Successor) { return Successor == BB; })) {
5134 new UnreachableInst(TI->getContext(), TI);
5135 TI->eraseFromParent();
5136 Changed = true;
5137 } else {
5138 assert(BI->isConditional() && "Can't get here with an uncond branch.");
5139 Value* Cond = BI->getCondition();
5140 assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
5141 "The destinations are guaranteed to be different here.");
5142 if (BI->getSuccessor(0) == BB) {
5143 Builder.CreateAssumption(Builder.CreateNot(Cond));
5144 Builder.CreateBr(BI->getSuccessor(1));
5145 } else {
5146 assert(BI->getSuccessor(1) == BB && "Incorrect CFG");
5147 Builder.CreateAssumption(Cond);
5148 Builder.CreateBr(BI->getSuccessor(0));
5149 }
5151 Changed = true;