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