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