Clang] Fix expansion of response files in -Wp after integrated-cc1 change
[llvm-project.git] / llvm / lib / Transforms / Utils / SimplifyCFG.cpp
blobd93ca4f04cdbf7bd20b811a5f98f24477899dbc4
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.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/ADT/APInt.h"
14 #include "llvm/ADT/ArrayRef.h"
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/Optional.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SetOperations.h"
19 #include "llvm/ADT/SetVector.h"
20 #include "llvm/ADT/SmallPtrSet.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/Analysis/AssumptionCache.h"
25 #include "llvm/Analysis/ConstantFolding.h"
26 #include "llvm/Analysis/EHPersonalities.h"
27 #include "llvm/Analysis/GuardUtils.h"
28 #include "llvm/Analysis/InstructionSimplify.h"
29 #include "llvm/Analysis/MemorySSA.h"
30 #include "llvm/Analysis/MemorySSAUpdater.h"
31 #include "llvm/Analysis/TargetTransformInfo.h"
32 #include "llvm/Analysis/ValueTracking.h"
33 #include "llvm/IR/Attributes.h"
34 #include "llvm/IR/BasicBlock.h"
35 #include "llvm/IR/CFG.h"
36 #include "llvm/IR/CallSite.h"
37 #include "llvm/IR/Constant.h"
38 #include "llvm/IR/ConstantRange.h"
39 #include "llvm/IR/Constants.h"
40 #include "llvm/IR/DataLayout.h"
41 #include "llvm/IR/DerivedTypes.h"
42 #include "llvm/IR/Function.h"
43 #include "llvm/IR/GlobalValue.h"
44 #include "llvm/IR/GlobalVariable.h"
45 #include "llvm/IR/IRBuilder.h"
46 #include "llvm/IR/InstrTypes.h"
47 #include "llvm/IR/Instruction.h"
48 #include "llvm/IR/Instructions.h"
49 #include "llvm/IR/IntrinsicInst.h"
50 #include "llvm/IR/Intrinsics.h"
51 #include "llvm/IR/LLVMContext.h"
52 #include "llvm/IR/MDBuilder.h"
53 #include "llvm/IR/Metadata.h"
54 #include "llvm/IR/Module.h"
55 #include "llvm/IR/NoFolder.h"
56 #include "llvm/IR/Operator.h"
57 #include "llvm/IR/PatternMatch.h"
58 #include "llvm/IR/Type.h"
59 #include "llvm/IR/Use.h"
60 #include "llvm/IR/User.h"
61 #include "llvm/IR/Value.h"
62 #include "llvm/Support/Casting.h"
63 #include "llvm/Support/CommandLine.h"
64 #include "llvm/Support/Debug.h"
65 #include "llvm/Support/ErrorHandling.h"
66 #include "llvm/Support/KnownBits.h"
67 #include "llvm/Support/MathExtras.h"
68 #include "llvm/Support/raw_ostream.h"
69 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
70 #include "llvm/Transforms/Utils/Local.h"
71 #include "llvm/Transforms/Utils/ValueMapper.h"
72 #include <algorithm>
73 #include <cassert>
74 #include <climits>
75 #include <cstddef>
76 #include <cstdint>
77 #include <iterator>
78 #include <map>
79 #include <set>
80 #include <tuple>
81 #include <utility>
82 #include <vector>
84 using namespace llvm;
85 using namespace PatternMatch;
87 #define DEBUG_TYPE "simplifycfg"
89 // Chosen as 2 so as to be cheap, but still to have enough power to fold
90 // a select, so the "clamp" idiom (of a min followed by a max) will be caught.
91 // To catch this, we need to fold a compare and a select, hence '2' being the
92 // minimum reasonable default.
93 static cl::opt<unsigned> PHINodeFoldingThreshold(
94 "phi-node-folding-threshold", cl::Hidden, cl::init(2),
95 cl::desc(
96 "Control the amount of phi node folding to perform (default = 2)"));
98 static cl::opt<unsigned> TwoEntryPHINodeFoldingThreshold(
99 "two-entry-phi-node-folding-threshold", cl::Hidden, cl::init(4),
100 cl::desc("Control the maximal total instruction cost that we are willing "
101 "to speculatively execute to fold a 2-entry PHI node into a "
102 "select (default = 4)"));
104 static cl::opt<bool> DupRet(
105 "simplifycfg-dup-ret", cl::Hidden, cl::init(false),
106 cl::desc("Duplicate return instructions into unconditional branches"));
108 static cl::opt<bool>
109 SinkCommon("simplifycfg-sink-common", cl::Hidden, cl::init(true),
110 cl::desc("Sink common instructions down to the end block"));
112 static cl::opt<bool> HoistCondStores(
113 "simplifycfg-hoist-cond-stores", cl::Hidden, cl::init(true),
114 cl::desc("Hoist conditional stores if an unconditional store precedes"));
116 static cl::opt<bool> MergeCondStores(
117 "simplifycfg-merge-cond-stores", cl::Hidden, cl::init(true),
118 cl::desc("Hoist conditional stores even if an unconditional store does not "
119 "precede - hoist multiple conditional stores into a single "
120 "predicated store"));
122 static cl::opt<bool> MergeCondStoresAggressively(
123 "simplifycfg-merge-cond-stores-aggressively", cl::Hidden, cl::init(false),
124 cl::desc("When merging conditional stores, do so even if the resultant "
125 "basic blocks are unlikely to be if-converted as a result"));
127 static cl::opt<bool> SpeculateOneExpensiveInst(
128 "speculate-one-expensive-inst", cl::Hidden, cl::init(true),
129 cl::desc("Allow exactly one expensive instruction to be speculatively "
130 "executed"));
132 static cl::opt<unsigned> MaxSpeculationDepth(
133 "max-speculation-depth", cl::Hidden, cl::init(10),
134 cl::desc("Limit maximum recursion depth when calculating costs of "
135 "speculatively executed instructions"));
137 STATISTIC(NumBitMaps, "Number of switch instructions turned into bitmaps");
138 STATISTIC(NumLinearMaps,
139 "Number of switch instructions turned into linear mapping");
140 STATISTIC(NumLookupTables,
141 "Number of switch instructions turned into lookup tables");
142 STATISTIC(
143 NumLookupTablesHoles,
144 "Number of switch instructions turned into lookup tables (holes checked)");
145 STATISTIC(NumTableCmpReuses, "Number of reused switch table lookup compares");
146 STATISTIC(NumSinkCommons,
147 "Number of common instructions sunk down to the end block");
148 STATISTIC(NumSpeculations, "Number of speculative executed instructions");
150 namespace {
152 // The first field contains the value that the switch produces when a certain
153 // case group is selected, and the second field is a vector containing the
154 // cases composing the case group.
155 using SwitchCaseResultVectorTy =
156 SmallVector<std::pair<Constant *, SmallVector<ConstantInt *, 4>>, 2>;
158 // The first field contains the phi node that generates a result of the switch
159 // and the second field contains the value generated for a certain case in the
160 // switch for that PHI.
161 using SwitchCaseResultsTy = SmallVector<std::pair<PHINode *, Constant *>, 4>;
163 /// ValueEqualityComparisonCase - Represents a case of a switch.
164 struct ValueEqualityComparisonCase {
165 ConstantInt *Value;
166 BasicBlock *Dest;
168 ValueEqualityComparisonCase(ConstantInt *Value, BasicBlock *Dest)
169 : Value(Value), Dest(Dest) {}
171 bool operator<(ValueEqualityComparisonCase RHS) const {
172 // Comparing pointers is ok as we only rely on the order for uniquing.
173 return Value < RHS.Value;
176 bool operator==(BasicBlock *RHSDest) const { return Dest == RHSDest; }
179 class SimplifyCFGOpt {
180 const TargetTransformInfo &TTI;
181 const DataLayout &DL;
182 SmallPtrSetImpl<BasicBlock *> *LoopHeaders;
183 const SimplifyCFGOptions &Options;
184 bool Resimplify;
186 Value *isValueEqualityComparison(Instruction *TI);
187 BasicBlock *GetValueEqualityComparisonCases(
188 Instruction *TI, std::vector<ValueEqualityComparisonCase> &Cases);
189 bool SimplifyEqualityComparisonWithOnlyPredecessor(Instruction *TI,
190 BasicBlock *Pred,
191 IRBuilder<> &Builder);
192 bool FoldValueComparisonIntoPredecessors(Instruction *TI,
193 IRBuilder<> &Builder);
195 bool SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder);
196 bool SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder);
197 bool SimplifySingleResume(ResumeInst *RI);
198 bool SimplifyCommonResume(ResumeInst *RI);
199 bool SimplifyCleanupReturn(CleanupReturnInst *RI);
200 bool SimplifyUnreachable(UnreachableInst *UI);
201 bool SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder);
202 bool SimplifyIndirectBr(IndirectBrInst *IBI);
203 bool SimplifyUncondBranch(BranchInst *BI, IRBuilder<> &Builder);
204 bool SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder);
206 bool tryToSimplifyUncondBranchWithICmpInIt(ICmpInst *ICI,
207 IRBuilder<> &Builder);
209 public:
210 SimplifyCFGOpt(const TargetTransformInfo &TTI, const DataLayout &DL,
211 SmallPtrSetImpl<BasicBlock *> *LoopHeaders,
212 const SimplifyCFGOptions &Opts)
213 : TTI(TTI), DL(DL), LoopHeaders(LoopHeaders), Options(Opts) {}
215 bool run(BasicBlock *BB);
216 bool simplifyOnce(BasicBlock *BB);
218 // Helper to set Resimplify and return change indication.
219 bool requestResimplify() {
220 Resimplify = true;
221 return true;
225 } // end anonymous namespace
227 /// Return true if it is safe to merge these two
228 /// terminator instructions together.
229 static bool
230 SafeToMergeTerminators(Instruction *SI1, Instruction *SI2,
231 SmallSetVector<BasicBlock *, 4> *FailBlocks = nullptr) {
232 if (SI1 == SI2)
233 return false; // Can't merge with self!
235 // It is not safe to merge these two switch instructions if they have a common
236 // successor, and if that successor has a PHI node, and if *that* PHI node has
237 // conflicting incoming values from the two switch blocks.
238 BasicBlock *SI1BB = SI1->getParent();
239 BasicBlock *SI2BB = SI2->getParent();
241 SmallPtrSet<BasicBlock *, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
242 bool Fail = false;
243 for (BasicBlock *Succ : successors(SI2BB))
244 if (SI1Succs.count(Succ))
245 for (BasicBlock::iterator BBI = Succ->begin(); isa<PHINode>(BBI); ++BBI) {
246 PHINode *PN = cast<PHINode>(BBI);
247 if (PN->getIncomingValueForBlock(SI1BB) !=
248 PN->getIncomingValueForBlock(SI2BB)) {
249 if (FailBlocks)
250 FailBlocks->insert(Succ);
251 Fail = true;
255 return !Fail;
258 /// Return true if it is safe and profitable to merge these two terminator
259 /// instructions together, where SI1 is an unconditional branch. PhiNodes will
260 /// store all PHI nodes in common successors.
261 static bool
262 isProfitableToFoldUnconditional(BranchInst *SI1, BranchInst *SI2,
263 Instruction *Cond,
264 SmallVectorImpl<PHINode *> &PhiNodes) {
265 if (SI1 == SI2)
266 return false; // Can't merge with self!
267 assert(SI1->isUnconditional() && SI2->isConditional());
269 // We fold the unconditional branch if we can easily update all PHI nodes in
270 // common successors:
271 // 1> We have a constant incoming value for the conditional branch;
272 // 2> We have "Cond" as the incoming value for the unconditional branch;
273 // 3> SI2->getCondition() and Cond have same operands.
274 CmpInst *Ci2 = dyn_cast<CmpInst>(SI2->getCondition());
275 if (!Ci2)
276 return false;
277 if (!(Cond->getOperand(0) == Ci2->getOperand(0) &&
278 Cond->getOperand(1) == Ci2->getOperand(1)) &&
279 !(Cond->getOperand(0) == Ci2->getOperand(1) &&
280 Cond->getOperand(1) == Ci2->getOperand(0)))
281 return false;
283 BasicBlock *SI1BB = SI1->getParent();
284 BasicBlock *SI2BB = SI2->getParent();
285 SmallPtrSet<BasicBlock *, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
286 for (BasicBlock *Succ : successors(SI2BB))
287 if (SI1Succs.count(Succ))
288 for (BasicBlock::iterator BBI = Succ->begin(); isa<PHINode>(BBI); ++BBI) {
289 PHINode *PN = cast<PHINode>(BBI);
290 if (PN->getIncomingValueForBlock(SI1BB) != Cond ||
291 !isa<ConstantInt>(PN->getIncomingValueForBlock(SI2BB)))
292 return false;
293 PhiNodes.push_back(PN);
295 return true;
298 /// Update PHI nodes in Succ to indicate that there will now be entries in it
299 /// from the 'NewPred' block. The values that will be flowing into the PHI nodes
300 /// will be the same as those coming in from ExistPred, an existing predecessor
301 /// of Succ.
302 static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
303 BasicBlock *ExistPred,
304 MemorySSAUpdater *MSSAU = nullptr) {
305 for (PHINode &PN : Succ->phis())
306 PN.addIncoming(PN.getIncomingValueForBlock(ExistPred), NewPred);
307 if (MSSAU)
308 if (auto *MPhi = MSSAU->getMemorySSA()->getMemoryAccess(Succ))
309 MPhi->addIncoming(MPhi->getIncomingValueForBlock(ExistPred), NewPred);
312 /// Compute an abstract "cost" of speculating the given instruction,
313 /// which is assumed to be safe to speculate. TCC_Free means cheap,
314 /// TCC_Basic means less cheap, and TCC_Expensive means prohibitively
315 /// expensive.
316 static unsigned ComputeSpeculationCost(const User *I,
317 const TargetTransformInfo &TTI) {
318 assert(isSafeToSpeculativelyExecute(I) &&
319 "Instruction is not safe to speculatively execute!");
320 return TTI.getUserCost(I);
323 /// If we have a merge point of an "if condition" as accepted above,
324 /// return true if the specified value dominates the block. We
325 /// don't handle the true generality of domination here, just a special case
326 /// which works well enough for us.
328 /// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
329 /// see if V (which must be an instruction) and its recursive operands
330 /// that do not dominate BB have a combined cost lower than CostRemaining and
331 /// are non-trapping. If both are true, the instruction is inserted into the
332 /// set and true is returned.
334 /// The cost for most non-trapping instructions is defined as 1 except for
335 /// Select whose cost is 2.
337 /// After this function returns, CostRemaining is decreased by the cost of
338 /// V plus its non-dominating operands. If that cost is greater than
339 /// CostRemaining, false is returned and CostRemaining is undefined.
340 static bool DominatesMergePoint(Value *V, BasicBlock *BB,
341 SmallPtrSetImpl<Instruction *> &AggressiveInsts,
342 int &BudgetRemaining,
343 const TargetTransformInfo &TTI,
344 unsigned Depth = 0) {
345 // It is possible to hit a zero-cost cycle (phi/gep instructions for example),
346 // so limit the recursion depth.
347 // TODO: While this recursion limit does prevent pathological behavior, it
348 // would be better to track visited instructions to avoid cycles.
349 if (Depth == MaxSpeculationDepth)
350 return false;
352 Instruction *I = dyn_cast<Instruction>(V);
353 if (!I) {
354 // Non-instructions all dominate instructions, but not all constantexprs
355 // can be executed unconditionally.
356 if (ConstantExpr *C = dyn_cast<ConstantExpr>(V))
357 if (C->canTrap())
358 return false;
359 return true;
361 BasicBlock *PBB = I->getParent();
363 // We don't want to allow weird loops that might have the "if condition" in
364 // the bottom of this block.
365 if (PBB == BB)
366 return false;
368 // If this instruction is defined in a block that contains an unconditional
369 // branch to BB, then it must be in the 'conditional' part of the "if
370 // statement". If not, it definitely dominates the region.
371 BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator());
372 if (!BI || BI->isConditional() || BI->getSuccessor(0) != BB)
373 return true;
375 // If we have seen this instruction before, don't count it again.
376 if (AggressiveInsts.count(I))
377 return true;
379 // Okay, it looks like the instruction IS in the "condition". Check to
380 // see if it's a cheap instruction to unconditionally compute, and if it
381 // only uses stuff defined outside of the condition. If so, hoist it out.
382 if (!isSafeToSpeculativelyExecute(I))
383 return false;
385 BudgetRemaining -= ComputeSpeculationCost(I, TTI);
387 // Allow exactly one instruction to be speculated regardless of its cost
388 // (as long as it is safe to do so).
389 // This is intended to flatten the CFG even if the instruction is a division
390 // or other expensive operation. The speculation of an expensive instruction
391 // is expected to be undone in CodeGenPrepare if the speculation has not
392 // enabled further IR optimizations.
393 if (BudgetRemaining < 0 &&
394 (!SpeculateOneExpensiveInst || !AggressiveInsts.empty() || Depth > 0))
395 return false;
397 // Okay, we can only really hoist these out if their operands do
398 // not take us over the cost threshold.
399 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
400 if (!DominatesMergePoint(*i, BB, AggressiveInsts, BudgetRemaining, TTI,
401 Depth + 1))
402 return false;
403 // Okay, it's safe to do this! Remember this instruction.
404 AggressiveInsts.insert(I);
405 return true;
408 /// Extract ConstantInt from value, looking through IntToPtr
409 /// and PointerNullValue. Return NULL if value is not a constant int.
410 static ConstantInt *GetConstantInt(Value *V, const DataLayout &DL) {
411 // Normal constant int.
412 ConstantInt *CI = dyn_cast<ConstantInt>(V);
413 if (CI || !isa<Constant>(V) || !V->getType()->isPointerTy())
414 return CI;
416 // This is some kind of pointer constant. Turn it into a pointer-sized
417 // ConstantInt if possible.
418 IntegerType *PtrTy = cast<IntegerType>(DL.getIntPtrType(V->getType()));
420 // Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*).
421 if (isa<ConstantPointerNull>(V))
422 return ConstantInt::get(PtrTy, 0);
424 // IntToPtr const int.
425 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
426 if (CE->getOpcode() == Instruction::IntToPtr)
427 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) {
428 // The constant is very likely to have the right type already.
429 if (CI->getType() == PtrTy)
430 return CI;
431 else
432 return cast<ConstantInt>(
433 ConstantExpr::getIntegerCast(CI, PtrTy, /*isSigned=*/false));
435 return nullptr;
438 namespace {
440 /// Given a chain of or (||) or and (&&) comparison of a value against a
441 /// constant, this will try to recover the information required for a switch
442 /// structure.
443 /// It will depth-first traverse the chain of comparison, seeking for patterns
444 /// like %a == 12 or %a < 4 and combine them to produce a set of integer
445 /// representing the different cases for the switch.
446 /// Note that if the chain is composed of '||' it will build the set of elements
447 /// that matches the comparisons (i.e. any of this value validate the chain)
448 /// while for a chain of '&&' it will build the set elements that make the test
449 /// fail.
450 struct ConstantComparesGatherer {
451 const DataLayout &DL;
453 /// Value found for the switch comparison
454 Value *CompValue = nullptr;
456 /// Extra clause to be checked before the switch
457 Value *Extra = nullptr;
459 /// Set of integers to match in switch
460 SmallVector<ConstantInt *, 8> Vals;
462 /// Number of comparisons matched in the and/or chain
463 unsigned UsedICmps = 0;
465 /// Construct and compute the result for the comparison instruction Cond
466 ConstantComparesGatherer(Instruction *Cond, const DataLayout &DL) : DL(DL) {
467 gather(Cond);
470 ConstantComparesGatherer(const ConstantComparesGatherer &) = delete;
471 ConstantComparesGatherer &
472 operator=(const ConstantComparesGatherer &) = delete;
474 private:
475 /// Try to set the current value used for the comparison, it succeeds only if
476 /// it wasn't set before or if the new value is the same as the old one
477 bool setValueOnce(Value *NewVal) {
478 if (CompValue && CompValue != NewVal)
479 return false;
480 CompValue = NewVal;
481 return (CompValue != nullptr);
484 /// Try to match Instruction "I" as a comparison against a constant and
485 /// populates the array Vals with the set of values that match (or do not
486 /// match depending on isEQ).
487 /// Return false on failure. On success, the Value the comparison matched
488 /// against is placed in CompValue.
489 /// If CompValue is already set, the function is expected to fail if a match
490 /// is found but the value compared to is different.
491 bool matchInstruction(Instruction *I, bool isEQ) {
492 // If this is an icmp against a constant, handle this as one of the cases.
493 ICmpInst *ICI;
494 ConstantInt *C;
495 if (!((ICI = dyn_cast<ICmpInst>(I)) &&
496 (C = GetConstantInt(I->getOperand(1), DL)))) {
497 return false;
500 Value *RHSVal;
501 const APInt *RHSC;
503 // Pattern match a special case
504 // (x & ~2^z) == y --> x == y || x == y|2^z
505 // This undoes a transformation done by instcombine to fuse 2 compares.
506 if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE)) {
507 // It's a little bit hard to see why the following transformations are
508 // correct. Here is a CVC3 program to verify them for 64-bit values:
511 ONE : BITVECTOR(64) = BVZEROEXTEND(0bin1, 63);
512 x : BITVECTOR(64);
513 y : BITVECTOR(64);
514 z : BITVECTOR(64);
515 mask : BITVECTOR(64) = BVSHL(ONE, z);
516 QUERY( (y & ~mask = y) =>
517 ((x & ~mask = y) <=> (x = y OR x = (y | mask)))
519 QUERY( (y | mask = y) =>
520 ((x | mask = y) <=> (x = y OR x = (y & ~mask)))
524 // Please note that each pattern must be a dual implication (<--> or
525 // iff). One directional implication can create spurious matches. If the
526 // implication is only one-way, an unsatisfiable condition on the left
527 // side can imply a satisfiable condition on the right side. Dual
528 // implication ensures that satisfiable conditions are transformed to
529 // other satisfiable conditions and unsatisfiable conditions are
530 // transformed to other unsatisfiable conditions.
532 // Here is a concrete example of a unsatisfiable condition on the left
533 // implying a satisfiable condition on the right:
535 // mask = (1 << z)
536 // (x & ~mask) == y --> (x == y || x == (y | mask))
538 // Substituting y = 3, z = 0 yields:
539 // (x & -2) == 3 --> (x == 3 || x == 2)
541 // Pattern match a special case:
543 QUERY( (y & ~mask = y) =>
544 ((x & ~mask = y) <=> (x = y OR x = (y | mask)))
547 if (match(ICI->getOperand(0),
548 m_And(m_Value(RHSVal), m_APInt(RHSC)))) {
549 APInt Mask = ~*RHSC;
550 if (Mask.isPowerOf2() && (C->getValue() & ~Mask) == C->getValue()) {
551 // If we already have a value for the switch, it has to match!
552 if (!setValueOnce(RHSVal))
553 return false;
555 Vals.push_back(C);
556 Vals.push_back(
557 ConstantInt::get(C->getContext(),
558 C->getValue() | Mask));
559 UsedICmps++;
560 return true;
564 // Pattern match a special case:
566 QUERY( (y | mask = y) =>
567 ((x | mask = y) <=> (x = y OR x = (y & ~mask)))
570 if (match(ICI->getOperand(0),
571 m_Or(m_Value(RHSVal), m_APInt(RHSC)))) {
572 APInt Mask = *RHSC;
573 if (Mask.isPowerOf2() && (C->getValue() | Mask) == C->getValue()) {
574 // If we already have a value for the switch, it has to match!
575 if (!setValueOnce(RHSVal))
576 return false;
578 Vals.push_back(C);
579 Vals.push_back(ConstantInt::get(C->getContext(),
580 C->getValue() & ~Mask));
581 UsedICmps++;
582 return true;
586 // If we already have a value for the switch, it has to match!
587 if (!setValueOnce(ICI->getOperand(0)))
588 return false;
590 UsedICmps++;
591 Vals.push_back(C);
592 return ICI->getOperand(0);
595 // If we have "x ult 3", for example, then we can add 0,1,2 to the set.
596 ConstantRange Span = ConstantRange::makeAllowedICmpRegion(
597 ICI->getPredicate(), C->getValue());
599 // Shift the range if the compare is fed by an add. This is the range
600 // compare idiom as emitted by instcombine.
601 Value *CandidateVal = I->getOperand(0);
602 if (match(I->getOperand(0), m_Add(m_Value(RHSVal), m_APInt(RHSC)))) {
603 Span = Span.subtract(*RHSC);
604 CandidateVal = RHSVal;
607 // If this is an and/!= check, then we are looking to build the set of
608 // value that *don't* pass the and chain. I.e. to turn "x ugt 2" into
609 // x != 0 && x != 1.
610 if (!isEQ)
611 Span = Span.inverse();
613 // If there are a ton of values, we don't want to make a ginormous switch.
614 if (Span.isSizeLargerThan(8) || Span.isEmptySet()) {
615 return false;
618 // If we already have a value for the switch, it has to match!
619 if (!setValueOnce(CandidateVal))
620 return false;
622 // Add all values from the range to the set
623 for (APInt Tmp = Span.getLower(); Tmp != Span.getUpper(); ++Tmp)
624 Vals.push_back(ConstantInt::get(I->getContext(), Tmp));
626 UsedICmps++;
627 return true;
630 /// Given a potentially 'or'd or 'and'd together collection of icmp
631 /// eq/ne/lt/gt instructions that compare a value against a constant, extract
632 /// the value being compared, and stick the list constants into the Vals
633 /// vector.
634 /// One "Extra" case is allowed to differ from the other.
635 void gather(Value *V) {
636 bool isEQ = (cast<Instruction>(V)->getOpcode() == Instruction::Or);
638 // Keep a stack (SmallVector for efficiency) for depth-first traversal
639 SmallVector<Value *, 8> DFT;
640 SmallPtrSet<Value *, 8> Visited;
642 // Initialize
643 Visited.insert(V);
644 DFT.push_back(V);
646 while (!DFT.empty()) {
647 V = DFT.pop_back_val();
649 if (Instruction *I = dyn_cast<Instruction>(V)) {
650 // If it is a || (or && depending on isEQ), process the operands.
651 if (I->getOpcode() == (isEQ ? Instruction::Or : Instruction::And)) {
652 if (Visited.insert(I->getOperand(1)).second)
653 DFT.push_back(I->getOperand(1));
654 if (Visited.insert(I->getOperand(0)).second)
655 DFT.push_back(I->getOperand(0));
656 continue;
659 // Try to match the current instruction
660 if (matchInstruction(I, isEQ))
661 // Match succeed, continue the loop
662 continue;
665 // One element of the sequence of || (or &&) could not be match as a
666 // comparison against the same value as the others.
667 // We allow only one "Extra" case to be checked before the switch
668 if (!Extra) {
669 Extra = V;
670 continue;
672 // Failed to parse a proper sequence, abort now
673 CompValue = nullptr;
674 break;
679 } // end anonymous namespace
681 static void EraseTerminatorAndDCECond(Instruction *TI,
682 MemorySSAUpdater *MSSAU = nullptr) {
683 Instruction *Cond = nullptr;
684 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
685 Cond = dyn_cast<Instruction>(SI->getCondition());
686 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
687 if (BI->isConditional())
688 Cond = dyn_cast<Instruction>(BI->getCondition());
689 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) {
690 Cond = dyn_cast<Instruction>(IBI->getAddress());
693 TI->eraseFromParent();
694 if (Cond)
695 RecursivelyDeleteTriviallyDeadInstructions(Cond, nullptr, MSSAU);
698 /// Return true if the specified terminator checks
699 /// to see if a value is equal to constant integer value.
700 Value *SimplifyCFGOpt::isValueEqualityComparison(Instruction *TI) {
701 Value *CV = nullptr;
702 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
703 // Do not permit merging of large switch instructions into their
704 // predecessors unless there is only one predecessor.
705 if (!SI->getParent()->hasNPredecessorsOrMore(128 / SI->getNumSuccessors()))
706 CV = SI->getCondition();
707 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI))
708 if (BI->isConditional() && BI->getCondition()->hasOneUse())
709 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition())) {
710 if (ICI->isEquality() && GetConstantInt(ICI->getOperand(1), DL))
711 CV = ICI->getOperand(0);
714 // Unwrap any lossless ptrtoint cast.
715 if (CV) {
716 if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV)) {
717 Value *Ptr = PTII->getPointerOperand();
718 if (PTII->getType() == DL.getIntPtrType(Ptr->getType()))
719 CV = Ptr;
722 return CV;
725 /// Given a value comparison instruction,
726 /// decode all of the 'cases' that it represents and return the 'default' block.
727 BasicBlock *SimplifyCFGOpt::GetValueEqualityComparisonCases(
728 Instruction *TI, std::vector<ValueEqualityComparisonCase> &Cases) {
729 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
730 Cases.reserve(SI->getNumCases());
731 for (auto Case : SI->cases())
732 Cases.push_back(ValueEqualityComparisonCase(Case.getCaseValue(),
733 Case.getCaseSuccessor()));
734 return SI->getDefaultDest();
737 BranchInst *BI = cast<BranchInst>(TI);
738 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
739 BasicBlock *Succ = BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_NE);
740 Cases.push_back(ValueEqualityComparisonCase(
741 GetConstantInt(ICI->getOperand(1), DL), Succ));
742 return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ);
745 /// Given a vector of bb/value pairs, remove any entries
746 /// in the list that match the specified block.
747 static void
748 EliminateBlockCases(BasicBlock *BB,
749 std::vector<ValueEqualityComparisonCase> &Cases) {
750 Cases.erase(std::remove(Cases.begin(), Cases.end(), BB), Cases.end());
753 /// Return true if there are any keys in C1 that exist in C2 as well.
754 static bool ValuesOverlap(std::vector<ValueEqualityComparisonCase> &C1,
755 std::vector<ValueEqualityComparisonCase> &C2) {
756 std::vector<ValueEqualityComparisonCase> *V1 = &C1, *V2 = &C2;
758 // Make V1 be smaller than V2.
759 if (V1->size() > V2->size())
760 std::swap(V1, V2);
762 if (V1->empty())
763 return false;
764 if (V1->size() == 1) {
765 // Just scan V2.
766 ConstantInt *TheVal = (*V1)[0].Value;
767 for (unsigned i = 0, e = V2->size(); i != e; ++i)
768 if (TheVal == (*V2)[i].Value)
769 return true;
772 // Otherwise, just sort both lists and compare element by element.
773 array_pod_sort(V1->begin(), V1->end());
774 array_pod_sort(V2->begin(), V2->end());
775 unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
776 while (i1 != e1 && i2 != e2) {
777 if ((*V1)[i1].Value == (*V2)[i2].Value)
778 return true;
779 if ((*V1)[i1].Value < (*V2)[i2].Value)
780 ++i1;
781 else
782 ++i2;
784 return false;
787 // Set branch weights on SwitchInst. This sets the metadata if there is at
788 // least one non-zero weight.
789 static void setBranchWeights(SwitchInst *SI, ArrayRef<uint32_t> Weights) {
790 // Check that there is at least one non-zero weight. Otherwise, pass
791 // nullptr to setMetadata which will erase the existing metadata.
792 MDNode *N = nullptr;
793 if (llvm::any_of(Weights, [](uint32_t W) { return W != 0; }))
794 N = MDBuilder(SI->getParent()->getContext()).createBranchWeights(Weights);
795 SI->setMetadata(LLVMContext::MD_prof, N);
798 // Similar to the above, but for branch and select instructions that take
799 // exactly 2 weights.
800 static void setBranchWeights(Instruction *I, uint32_t TrueWeight,
801 uint32_t FalseWeight) {
802 assert(isa<BranchInst>(I) || isa<SelectInst>(I));
803 // Check that there is at least one non-zero weight. Otherwise, pass
804 // nullptr to setMetadata which will erase the existing metadata.
805 MDNode *N = nullptr;
806 if (TrueWeight || FalseWeight)
807 N = MDBuilder(I->getParent()->getContext())
808 .createBranchWeights(TrueWeight, FalseWeight);
809 I->setMetadata(LLVMContext::MD_prof, N);
812 /// If TI is known to be a terminator instruction and its block is known to
813 /// only have a single predecessor block, check to see if that predecessor is
814 /// also a value comparison with the same value, and if that comparison
815 /// determines the outcome of this comparison. If so, simplify TI. This does a
816 /// very limited form of jump threading.
817 bool SimplifyCFGOpt::SimplifyEqualityComparisonWithOnlyPredecessor(
818 Instruction *TI, BasicBlock *Pred, IRBuilder<> &Builder) {
819 Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
820 if (!PredVal)
821 return false; // Not a value comparison in predecessor.
823 Value *ThisVal = isValueEqualityComparison(TI);
824 assert(ThisVal && "This isn't a value comparison!!");
825 if (ThisVal != PredVal)
826 return false; // Different predicates.
828 // TODO: Preserve branch weight metadata, similarly to how
829 // FoldValueComparisonIntoPredecessors preserves it.
831 // Find out information about when control will move from Pred to TI's block.
832 std::vector<ValueEqualityComparisonCase> PredCases;
833 BasicBlock *PredDef =
834 GetValueEqualityComparisonCases(Pred->getTerminator(), PredCases);
835 EliminateBlockCases(PredDef, PredCases); // Remove default from cases.
837 // Find information about how control leaves this block.
838 std::vector<ValueEqualityComparisonCase> ThisCases;
839 BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
840 EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases.
842 // If TI's block is the default block from Pred's comparison, potentially
843 // simplify TI based on this knowledge.
844 if (PredDef == TI->getParent()) {
845 // If we are here, we know that the value is none of those cases listed in
846 // PredCases. If there are any cases in ThisCases that are in PredCases, we
847 // can simplify TI.
848 if (!ValuesOverlap(PredCases, ThisCases))
849 return false;
851 if (isa<BranchInst>(TI)) {
852 // Okay, one of the successors of this condbr is dead. Convert it to a
853 // uncond br.
854 assert(ThisCases.size() == 1 && "Branch can only have one case!");
855 // Insert the new branch.
856 Instruction *NI = Builder.CreateBr(ThisDef);
857 (void)NI;
859 // Remove PHI node entries for the dead edge.
860 ThisCases[0].Dest->removePredecessor(TI->getParent());
862 LLVM_DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
863 << "Through successor TI: " << *TI << "Leaving: " << *NI
864 << "\n");
866 EraseTerminatorAndDCECond(TI);
867 return true;
870 SwitchInstProfUpdateWrapper SI = *cast<SwitchInst>(TI);
871 // Okay, TI has cases that are statically dead, prune them away.
872 SmallPtrSet<Constant *, 16> DeadCases;
873 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
874 DeadCases.insert(PredCases[i].Value);
876 LLVM_DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
877 << "Through successor TI: " << *TI);
879 for (SwitchInst::CaseIt i = SI->case_end(), e = SI->case_begin(); i != e;) {
880 --i;
881 if (DeadCases.count(i->getCaseValue())) {
882 i->getCaseSuccessor()->removePredecessor(TI->getParent());
883 SI.removeCase(i);
886 LLVM_DEBUG(dbgs() << "Leaving: " << *TI << "\n");
887 return true;
890 // Otherwise, TI's block must correspond to some matched value. Find out
891 // which value (or set of values) this is.
892 ConstantInt *TIV = nullptr;
893 BasicBlock *TIBB = TI->getParent();
894 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
895 if (PredCases[i].Dest == TIBB) {
896 if (TIV)
897 return false; // Cannot handle multiple values coming to this block.
898 TIV = PredCases[i].Value;
900 assert(TIV && "No edge from pred to succ?");
902 // Okay, we found the one constant that our value can be if we get into TI's
903 // BB. Find out which successor will unconditionally be branched to.
904 BasicBlock *TheRealDest = nullptr;
905 for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
906 if (ThisCases[i].Value == TIV) {
907 TheRealDest = ThisCases[i].Dest;
908 break;
911 // If not handled by any explicit cases, it is handled by the default case.
912 if (!TheRealDest)
913 TheRealDest = ThisDef;
915 // Remove PHI node entries for dead edges.
916 BasicBlock *CheckEdge = TheRealDest;
917 for (BasicBlock *Succ : successors(TIBB))
918 if (Succ != CheckEdge)
919 Succ->removePredecessor(TIBB);
920 else
921 CheckEdge = nullptr;
923 // Insert the new branch.
924 Instruction *NI = Builder.CreateBr(TheRealDest);
925 (void)NI;
927 LLVM_DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
928 << "Through successor TI: " << *TI << "Leaving: " << *NI
929 << "\n");
931 EraseTerminatorAndDCECond(TI);
932 return true;
935 namespace {
937 /// This class implements a stable ordering of constant
938 /// integers that does not depend on their address. This is important for
939 /// applications that sort ConstantInt's to ensure uniqueness.
940 struct ConstantIntOrdering {
941 bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
942 return LHS->getValue().ult(RHS->getValue());
946 } // end anonymous namespace
948 static int ConstantIntSortPredicate(ConstantInt *const *P1,
949 ConstantInt *const *P2) {
950 const ConstantInt *LHS = *P1;
951 const ConstantInt *RHS = *P2;
952 if (LHS == RHS)
953 return 0;
954 return LHS->getValue().ult(RHS->getValue()) ? 1 : -1;
957 static inline bool HasBranchWeights(const Instruction *I) {
958 MDNode *ProfMD = I->getMetadata(LLVMContext::MD_prof);
959 if (ProfMD && ProfMD->getOperand(0))
960 if (MDString *MDS = dyn_cast<MDString>(ProfMD->getOperand(0)))
961 return MDS->getString().equals("branch_weights");
963 return false;
966 /// Get Weights of a given terminator, the default weight is at the front
967 /// of the vector. If TI is a conditional eq, we need to swap the branch-weight
968 /// metadata.
969 static void GetBranchWeights(Instruction *TI,
970 SmallVectorImpl<uint64_t> &Weights) {
971 MDNode *MD = TI->getMetadata(LLVMContext::MD_prof);
972 assert(MD);
973 for (unsigned i = 1, e = MD->getNumOperands(); i < e; ++i) {
974 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(i));
975 Weights.push_back(CI->getValue().getZExtValue());
978 // If TI is a conditional eq, the default case is the false case,
979 // and the corresponding branch-weight data is at index 2. We swap the
980 // default weight to be the first entry.
981 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
982 assert(Weights.size() == 2);
983 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
984 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
985 std::swap(Weights.front(), Weights.back());
989 /// Keep halving the weights until all can fit in uint32_t.
990 static void FitWeights(MutableArrayRef<uint64_t> Weights) {
991 uint64_t Max = *std::max_element(Weights.begin(), Weights.end());
992 if (Max > UINT_MAX) {
993 unsigned Offset = 32 - countLeadingZeros(Max);
994 for (uint64_t &I : Weights)
995 I >>= Offset;
999 /// The specified terminator is a value equality comparison instruction
1000 /// (either a switch or a branch on "X == c").
1001 /// See if any of the predecessors of the terminator block are value comparisons
1002 /// on the same value. If so, and if safe to do so, fold them together.
1003 bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(Instruction *TI,
1004 IRBuilder<> &Builder) {
1005 BasicBlock *BB = TI->getParent();
1006 Value *CV = isValueEqualityComparison(TI); // CondVal
1007 assert(CV && "Not a comparison?");
1008 bool Changed = false;
1010 SmallVector<BasicBlock *, 16> Preds(pred_begin(BB), pred_end(BB));
1011 while (!Preds.empty()) {
1012 BasicBlock *Pred = Preds.pop_back_val();
1014 // See if the predecessor is a comparison with the same value.
1015 Instruction *PTI = Pred->getTerminator();
1016 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
1018 if (PCV == CV && TI != PTI) {
1019 SmallSetVector<BasicBlock*, 4> FailBlocks;
1020 if (!SafeToMergeTerminators(TI, PTI, &FailBlocks)) {
1021 for (auto *Succ : FailBlocks) {
1022 if (!SplitBlockPredecessors(Succ, TI->getParent(), ".fold.split"))
1023 return false;
1027 // Figure out which 'cases' to copy from SI to PSI.
1028 std::vector<ValueEqualityComparisonCase> BBCases;
1029 BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
1031 std::vector<ValueEqualityComparisonCase> PredCases;
1032 BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
1034 // Based on whether the default edge from PTI goes to BB or not, fill in
1035 // PredCases and PredDefault with the new switch cases we would like to
1036 // build.
1037 SmallVector<BasicBlock *, 8> NewSuccessors;
1039 // Update the branch weight metadata along the way
1040 SmallVector<uint64_t, 8> Weights;
1041 bool PredHasWeights = HasBranchWeights(PTI);
1042 bool SuccHasWeights = HasBranchWeights(TI);
1044 if (PredHasWeights) {
1045 GetBranchWeights(PTI, Weights);
1046 // branch-weight metadata is inconsistent here.
1047 if (Weights.size() != 1 + PredCases.size())
1048 PredHasWeights = SuccHasWeights = false;
1049 } else if (SuccHasWeights)
1050 // If there are no predecessor weights but there are successor weights,
1051 // populate Weights with 1, which will later be scaled to the sum of
1052 // successor's weights
1053 Weights.assign(1 + PredCases.size(), 1);
1055 SmallVector<uint64_t, 8> SuccWeights;
1056 if (SuccHasWeights) {
1057 GetBranchWeights(TI, SuccWeights);
1058 // branch-weight metadata is inconsistent here.
1059 if (SuccWeights.size() != 1 + BBCases.size())
1060 PredHasWeights = SuccHasWeights = false;
1061 } else if (PredHasWeights)
1062 SuccWeights.assign(1 + BBCases.size(), 1);
1064 if (PredDefault == BB) {
1065 // If this is the default destination from PTI, only the edges in TI
1066 // that don't occur in PTI, or that branch to BB will be activated.
1067 std::set<ConstantInt *, ConstantIntOrdering> PTIHandled;
1068 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
1069 if (PredCases[i].Dest != BB)
1070 PTIHandled.insert(PredCases[i].Value);
1071 else {
1072 // The default destination is BB, we don't need explicit targets.
1073 std::swap(PredCases[i], PredCases.back());
1075 if (PredHasWeights || SuccHasWeights) {
1076 // Increase weight for the default case.
1077 Weights[0] += Weights[i + 1];
1078 std::swap(Weights[i + 1], Weights.back());
1079 Weights.pop_back();
1082 PredCases.pop_back();
1083 --i;
1084 --e;
1087 // Reconstruct the new switch statement we will be building.
1088 if (PredDefault != BBDefault) {
1089 PredDefault->removePredecessor(Pred);
1090 PredDefault = BBDefault;
1091 NewSuccessors.push_back(BBDefault);
1094 unsigned CasesFromPred = Weights.size();
1095 uint64_t ValidTotalSuccWeight = 0;
1096 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
1097 if (!PTIHandled.count(BBCases[i].Value) &&
1098 BBCases[i].Dest != BBDefault) {
1099 PredCases.push_back(BBCases[i]);
1100 NewSuccessors.push_back(BBCases[i].Dest);
1101 if (SuccHasWeights || PredHasWeights) {
1102 // The default weight is at index 0, so weight for the ith case
1103 // should be at index i+1. Scale the cases from successor by
1104 // PredDefaultWeight (Weights[0]).
1105 Weights.push_back(Weights[0] * SuccWeights[i + 1]);
1106 ValidTotalSuccWeight += SuccWeights[i + 1];
1110 if (SuccHasWeights || PredHasWeights) {
1111 ValidTotalSuccWeight += SuccWeights[0];
1112 // Scale the cases from predecessor by ValidTotalSuccWeight.
1113 for (unsigned i = 1; i < CasesFromPred; ++i)
1114 Weights[i] *= ValidTotalSuccWeight;
1115 // Scale the default weight by SuccDefaultWeight (SuccWeights[0]).
1116 Weights[0] *= SuccWeights[0];
1118 } else {
1119 // If this is not the default destination from PSI, only the edges
1120 // in SI that occur in PSI with a destination of BB will be
1121 // activated.
1122 std::set<ConstantInt *, ConstantIntOrdering> PTIHandled;
1123 std::map<ConstantInt *, uint64_t> WeightsForHandled;
1124 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
1125 if (PredCases[i].Dest == BB) {
1126 PTIHandled.insert(PredCases[i].Value);
1128 if (PredHasWeights || SuccHasWeights) {
1129 WeightsForHandled[PredCases[i].Value] = Weights[i + 1];
1130 std::swap(Weights[i + 1], Weights.back());
1131 Weights.pop_back();
1134 std::swap(PredCases[i], PredCases.back());
1135 PredCases.pop_back();
1136 --i;
1137 --e;
1140 // Okay, now we know which constants were sent to BB from the
1141 // predecessor. Figure out where they will all go now.
1142 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
1143 if (PTIHandled.count(BBCases[i].Value)) {
1144 // If this is one we are capable of getting...
1145 if (PredHasWeights || SuccHasWeights)
1146 Weights.push_back(WeightsForHandled[BBCases[i].Value]);
1147 PredCases.push_back(BBCases[i]);
1148 NewSuccessors.push_back(BBCases[i].Dest);
1149 PTIHandled.erase(
1150 BBCases[i].Value); // This constant is taken care of
1153 // If there are any constants vectored to BB that TI doesn't handle,
1154 // they must go to the default destination of TI.
1155 for (ConstantInt *I : PTIHandled) {
1156 if (PredHasWeights || SuccHasWeights)
1157 Weights.push_back(WeightsForHandled[I]);
1158 PredCases.push_back(ValueEqualityComparisonCase(I, BBDefault));
1159 NewSuccessors.push_back(BBDefault);
1163 // Okay, at this point, we know which new successor Pred will get. Make
1164 // sure we update the number of entries in the PHI nodes for these
1165 // successors.
1166 for (BasicBlock *NewSuccessor : NewSuccessors)
1167 AddPredecessorToBlock(NewSuccessor, Pred, BB);
1169 Builder.SetInsertPoint(PTI);
1170 // Convert pointer to int before we switch.
1171 if (CV->getType()->isPointerTy()) {
1172 CV = Builder.CreatePtrToInt(CV, DL.getIntPtrType(CV->getType()),
1173 "magicptr");
1176 // Now that the successors are updated, create the new Switch instruction.
1177 SwitchInst *NewSI =
1178 Builder.CreateSwitch(CV, PredDefault, PredCases.size());
1179 NewSI->setDebugLoc(PTI->getDebugLoc());
1180 for (ValueEqualityComparisonCase &V : PredCases)
1181 NewSI->addCase(V.Value, V.Dest);
1183 if (PredHasWeights || SuccHasWeights) {
1184 // Halve the weights if any of them cannot fit in an uint32_t
1185 FitWeights(Weights);
1187 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
1189 setBranchWeights(NewSI, MDWeights);
1192 EraseTerminatorAndDCECond(PTI);
1194 // Okay, last check. If BB is still a successor of PSI, then we must
1195 // have an infinite loop case. If so, add an infinitely looping block
1196 // to handle the case to preserve the behavior of the code.
1197 BasicBlock *InfLoopBlock = nullptr;
1198 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
1199 if (NewSI->getSuccessor(i) == BB) {
1200 if (!InfLoopBlock) {
1201 // Insert it at the end of the function, because it's either code,
1202 // or it won't matter if it's hot. :)
1203 InfLoopBlock = BasicBlock::Create(BB->getContext(), "infloop",
1204 BB->getParent());
1205 BranchInst::Create(InfLoopBlock, InfLoopBlock);
1207 NewSI->setSuccessor(i, InfLoopBlock);
1210 Changed = true;
1213 return Changed;
1216 // If we would need to insert a select that uses the value of this invoke
1217 // (comments in HoistThenElseCodeToIf explain why we would need to do this), we
1218 // can't hoist the invoke, as there is nowhere to put the select in this case.
1219 static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2,
1220 Instruction *I1, Instruction *I2) {
1221 for (BasicBlock *Succ : successors(BB1)) {
1222 for (const PHINode &PN : Succ->phis()) {
1223 Value *BB1V = PN.getIncomingValueForBlock(BB1);
1224 Value *BB2V = PN.getIncomingValueForBlock(BB2);
1225 if (BB1V != BB2V && (BB1V == I1 || BB2V == I2)) {
1226 return false;
1230 return true;
1233 static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I);
1235 /// Given a conditional branch that goes to BB1 and BB2, hoist any common code
1236 /// in the two blocks up into the branch block. The caller of this function
1237 /// guarantees that BI's block dominates BB1 and BB2.
1238 static bool HoistThenElseCodeToIf(BranchInst *BI,
1239 const TargetTransformInfo &TTI) {
1240 // This does very trivial matching, with limited scanning, to find identical
1241 // instructions in the two blocks. In particular, we don't want to get into
1242 // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As
1243 // such, we currently just scan for obviously identical instructions in an
1244 // identical order.
1245 BasicBlock *BB1 = BI->getSuccessor(0); // The true destination.
1246 BasicBlock *BB2 = BI->getSuccessor(1); // The false destination
1248 BasicBlock::iterator BB1_Itr = BB1->begin();
1249 BasicBlock::iterator BB2_Itr = BB2->begin();
1251 Instruction *I1 = &*BB1_Itr++, *I2 = &*BB2_Itr++;
1252 // Skip debug info if it is not identical.
1253 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1254 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1255 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1256 while (isa<DbgInfoIntrinsic>(I1))
1257 I1 = &*BB1_Itr++;
1258 while (isa<DbgInfoIntrinsic>(I2))
1259 I2 = &*BB2_Itr++;
1261 // FIXME: Can we define a safety predicate for CallBr?
1262 if (isa<PHINode>(I1) || !I1->isIdenticalToWhenDefined(I2) ||
1263 (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)) ||
1264 isa<CallBrInst>(I1))
1265 return false;
1267 BasicBlock *BIParent = BI->getParent();
1269 bool Changed = false;
1270 do {
1271 // If we are hoisting the terminator instruction, don't move one (making a
1272 // broken BB), instead clone it, and remove BI.
1273 if (I1->isTerminator())
1274 goto HoistTerminator;
1276 // If we're going to hoist a call, make sure that the two instructions we're
1277 // commoning/hoisting are both marked with musttail, or neither of them is
1278 // marked as such. Otherwise, we might end up in a situation where we hoist
1279 // from a block where the terminator is a `ret` to a block where the terminator
1280 // is a `br`, and `musttail` calls expect to be followed by a return.
1281 auto *C1 = dyn_cast<CallInst>(I1);
1282 auto *C2 = dyn_cast<CallInst>(I2);
1283 if (C1 && C2)
1284 if (C1->isMustTailCall() != C2->isMustTailCall())
1285 return Changed;
1287 if (!TTI.isProfitableToHoist(I1) || !TTI.isProfitableToHoist(I2))
1288 return Changed;
1290 if (isa<DbgInfoIntrinsic>(I1) || isa<DbgInfoIntrinsic>(I2)) {
1291 assert (isa<DbgInfoIntrinsic>(I1) && isa<DbgInfoIntrinsic>(I2));
1292 // The debug location is an integral part of a debug info intrinsic
1293 // and can't be separated from it or replaced. Instead of attempting
1294 // to merge locations, simply hoist both copies of the intrinsic.
1295 BIParent->getInstList().splice(BI->getIterator(),
1296 BB1->getInstList(), I1);
1297 BIParent->getInstList().splice(BI->getIterator(),
1298 BB2->getInstList(), I2);
1299 Changed = true;
1300 } else {
1301 // For a normal instruction, we just move one to right before the branch,
1302 // then replace all uses of the other with the first. Finally, we remove
1303 // the now redundant second instruction.
1304 BIParent->getInstList().splice(BI->getIterator(),
1305 BB1->getInstList(), I1);
1306 if (!I2->use_empty())
1307 I2->replaceAllUsesWith(I1);
1308 I1->andIRFlags(I2);
1309 unsigned KnownIDs[] = {LLVMContext::MD_tbaa,
1310 LLVMContext::MD_range,
1311 LLVMContext::MD_fpmath,
1312 LLVMContext::MD_invariant_load,
1313 LLVMContext::MD_nonnull,
1314 LLVMContext::MD_invariant_group,
1315 LLVMContext::MD_align,
1316 LLVMContext::MD_dereferenceable,
1317 LLVMContext::MD_dereferenceable_or_null,
1318 LLVMContext::MD_mem_parallel_loop_access,
1319 LLVMContext::MD_access_group,
1320 LLVMContext::MD_preserve_access_index};
1321 combineMetadata(I1, I2, KnownIDs, true);
1323 // I1 and I2 are being combined into a single instruction. Its debug
1324 // location is the merged locations of the original instructions.
1325 I1->applyMergedLocation(I1->getDebugLoc(), I2->getDebugLoc());
1327 I2->eraseFromParent();
1328 Changed = true;
1331 I1 = &*BB1_Itr++;
1332 I2 = &*BB2_Itr++;
1333 // Skip debug info if it is not identical.
1334 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1335 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1336 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1337 while (isa<DbgInfoIntrinsic>(I1))
1338 I1 = &*BB1_Itr++;
1339 while (isa<DbgInfoIntrinsic>(I2))
1340 I2 = &*BB2_Itr++;
1342 } while (I1->isIdenticalToWhenDefined(I2));
1344 return true;
1346 HoistTerminator:
1347 // It may not be possible to hoist an invoke.
1348 // FIXME: Can we define a safety predicate for CallBr?
1349 if (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2))
1350 return Changed;
1352 // TODO: callbr hoisting currently disabled pending further study.
1353 if (isa<CallBrInst>(I1))
1354 return Changed;
1356 for (BasicBlock *Succ : successors(BB1)) {
1357 for (PHINode &PN : Succ->phis()) {
1358 Value *BB1V = PN.getIncomingValueForBlock(BB1);
1359 Value *BB2V = PN.getIncomingValueForBlock(BB2);
1360 if (BB1V == BB2V)
1361 continue;
1363 // Check for passingValueIsAlwaysUndefined here because we would rather
1364 // eliminate undefined control flow then converting it to a select.
1365 if (passingValueIsAlwaysUndefined(BB1V, &PN) ||
1366 passingValueIsAlwaysUndefined(BB2V, &PN))
1367 return Changed;
1369 if (isa<ConstantExpr>(BB1V) && !isSafeToSpeculativelyExecute(BB1V))
1370 return Changed;
1371 if (isa<ConstantExpr>(BB2V) && !isSafeToSpeculativelyExecute(BB2V))
1372 return Changed;
1376 // Okay, it is safe to hoist the terminator.
1377 Instruction *NT = I1->clone();
1378 BIParent->getInstList().insert(BI->getIterator(), NT);
1379 if (!NT->getType()->isVoidTy()) {
1380 I1->replaceAllUsesWith(NT);
1381 I2->replaceAllUsesWith(NT);
1382 NT->takeName(I1);
1385 // Ensure terminator gets a debug location, even an unknown one, in case
1386 // it involves inlinable calls.
1387 NT->applyMergedLocation(I1->getDebugLoc(), I2->getDebugLoc());
1389 // PHIs created below will adopt NT's merged DebugLoc.
1390 IRBuilder<NoFolder> Builder(NT);
1392 // Hoisting one of the terminators from our successor is a great thing.
1393 // Unfortunately, the successors of the if/else blocks may have PHI nodes in
1394 // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI
1395 // nodes, so we insert select instruction to compute the final result.
1396 std::map<std::pair<Value *, Value *>, SelectInst *> InsertedSelects;
1397 for (BasicBlock *Succ : successors(BB1)) {
1398 for (PHINode &PN : Succ->phis()) {
1399 Value *BB1V = PN.getIncomingValueForBlock(BB1);
1400 Value *BB2V = PN.getIncomingValueForBlock(BB2);
1401 if (BB1V == BB2V)
1402 continue;
1404 // These values do not agree. Insert a select instruction before NT
1405 // that determines the right value.
1406 SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
1407 if (!SI) {
1408 // Propagate fast-math-flags from phi node to its replacement select.
1409 IRBuilder<>::FastMathFlagGuard FMFGuard(Builder);
1410 if (isa<FPMathOperator>(PN))
1411 Builder.setFastMathFlags(PN.getFastMathFlags());
1413 SI = cast<SelectInst>(
1414 Builder.CreateSelect(BI->getCondition(), BB1V, BB2V,
1415 BB1V->getName() + "." + BB2V->getName(), BI));
1418 // Make the PHI node use the select for all incoming values for BB1/BB2
1419 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
1420 if (PN.getIncomingBlock(i) == BB1 || PN.getIncomingBlock(i) == BB2)
1421 PN.setIncomingValue(i, SI);
1425 // Update any PHI nodes in our new successors.
1426 for (BasicBlock *Succ : successors(BB1))
1427 AddPredecessorToBlock(Succ, BIParent, BB1);
1429 EraseTerminatorAndDCECond(BI);
1430 return true;
1433 // Check lifetime markers.
1434 static bool isLifeTimeMarker(const Instruction *I) {
1435 if (auto II = dyn_cast<IntrinsicInst>(I)) {
1436 switch (II->getIntrinsicID()) {
1437 default:
1438 break;
1439 case Intrinsic::lifetime_start:
1440 case Intrinsic::lifetime_end:
1441 return true;
1444 return false;
1447 // All instructions in Insts belong to different blocks that all unconditionally
1448 // branch to a common successor. Analyze each instruction and return true if it
1449 // would be possible to sink them into their successor, creating one common
1450 // instruction instead. For every value that would be required to be provided by
1451 // PHI node (because an operand varies in each input block), add to PHIOperands.
1452 static bool canSinkInstructions(
1453 ArrayRef<Instruction *> Insts,
1454 DenseMap<Instruction *, SmallVector<Value *, 4>> &PHIOperands) {
1455 // Prune out obviously bad instructions to move. Each instruction must have
1456 // exactly zero or one use, and we check later that use is by a single, common
1457 // PHI instruction in the successor.
1458 bool HasUse = !Insts.front()->user_empty();
1459 for (auto *I : Insts) {
1460 // These instructions may change or break semantics if moved.
1461 if (isa<PHINode>(I) || I->isEHPad() || isa<AllocaInst>(I) ||
1462 I->getType()->isTokenTy())
1463 return false;
1465 // Conservatively return false if I is an inline-asm instruction. Sinking
1466 // and merging inline-asm instructions can potentially create arguments
1467 // that cannot satisfy the inline-asm constraints.
1468 if (const auto *C = dyn_cast<CallBase>(I))
1469 if (C->isInlineAsm())
1470 return false;
1472 // Each instruction must have zero or one use.
1473 if (HasUse && !I->hasOneUse())
1474 return false;
1475 if (!HasUse && !I->user_empty())
1476 return false;
1479 const Instruction *I0 = Insts.front();
1480 for (auto *I : Insts)
1481 if (!I->isSameOperationAs(I0))
1482 return false;
1484 // All instructions in Insts are known to be the same opcode. If they have a
1485 // use, check that the only user is a PHI or in the same block as the
1486 // instruction, because if a user is in the same block as an instruction we're
1487 // contemplating sinking, it must already be determined to be sinkable.
1488 if (HasUse) {
1489 auto *PNUse = dyn_cast<PHINode>(*I0->user_begin());
1490 auto *Succ = I0->getParent()->getTerminator()->getSuccessor(0);
1491 if (!all_of(Insts, [&PNUse,&Succ](const Instruction *I) -> bool {
1492 auto *U = cast<Instruction>(*I->user_begin());
1493 return (PNUse &&
1494 PNUse->getParent() == Succ &&
1495 PNUse->getIncomingValueForBlock(I->getParent()) == I) ||
1496 U->getParent() == I->getParent();
1498 return false;
1501 // Because SROA can't handle speculating stores of selects, try not to sink
1502 // loads, stores or lifetime markers of allocas when we'd have to create a
1503 // PHI for the address operand. Also, because it is likely that loads or
1504 // stores of allocas will disappear when Mem2Reg/SROA is run, don't sink
1505 // them.
1506 // This can cause code churn which can have unintended consequences down
1507 // the line - see https://llvm.org/bugs/show_bug.cgi?id=30244.
1508 // FIXME: This is a workaround for a deficiency in SROA - see
1509 // https://llvm.org/bugs/show_bug.cgi?id=30188
1510 if (isa<StoreInst>(I0) && any_of(Insts, [](const Instruction *I) {
1511 return isa<AllocaInst>(I->getOperand(1)->stripPointerCasts());
1513 return false;
1514 if (isa<LoadInst>(I0) && any_of(Insts, [](const Instruction *I) {
1515 return isa<AllocaInst>(I->getOperand(0)->stripPointerCasts());
1517 return false;
1518 if (isLifeTimeMarker(I0) && any_of(Insts, [](const Instruction *I) {
1519 return isa<AllocaInst>(I->getOperand(1)->stripPointerCasts());
1521 return false;
1523 for (unsigned OI = 0, OE = I0->getNumOperands(); OI != OE; ++OI) {
1524 if (I0->getOperand(OI)->getType()->isTokenTy())
1525 // Don't touch any operand of token type.
1526 return false;
1528 auto SameAsI0 = [&I0, OI](const Instruction *I) {
1529 assert(I->getNumOperands() == I0->getNumOperands());
1530 return I->getOperand(OI) == I0->getOperand(OI);
1532 if (!all_of(Insts, SameAsI0)) {
1533 if (!canReplaceOperandWithVariable(I0, OI))
1534 // We can't create a PHI from this GEP.
1535 return false;
1536 // Don't create indirect calls! The called value is the final operand.
1537 if (isa<CallBase>(I0) && OI == OE - 1) {
1538 // FIXME: if the call was *already* indirect, we should do this.
1539 return false;
1541 for (auto *I : Insts)
1542 PHIOperands[I].push_back(I->getOperand(OI));
1545 return true;
1548 // Assuming canSinkLastInstruction(Blocks) has returned true, sink the last
1549 // instruction of every block in Blocks to their common successor, commoning
1550 // into one instruction.
1551 static bool sinkLastInstruction(ArrayRef<BasicBlock*> Blocks) {
1552 auto *BBEnd = Blocks[0]->getTerminator()->getSuccessor(0);
1554 // canSinkLastInstruction returning true guarantees that every block has at
1555 // least one non-terminator instruction.
1556 SmallVector<Instruction*,4> Insts;
1557 for (auto *BB : Blocks) {
1558 Instruction *I = BB->getTerminator();
1559 do {
1560 I = I->getPrevNode();
1561 } while (isa<DbgInfoIntrinsic>(I) && I != &BB->front());
1562 if (!isa<DbgInfoIntrinsic>(I))
1563 Insts.push_back(I);
1566 // The only checking we need to do now is that all users of all instructions
1567 // are the same PHI node. canSinkLastInstruction should have checked this but
1568 // it is slightly over-aggressive - it gets confused by commutative instructions
1569 // so double-check it here.
1570 Instruction *I0 = Insts.front();
1571 if (!I0->user_empty()) {
1572 auto *PNUse = dyn_cast<PHINode>(*I0->user_begin());
1573 if (!all_of(Insts, [&PNUse](const Instruction *I) -> bool {
1574 auto *U = cast<Instruction>(*I->user_begin());
1575 return U == PNUse;
1577 return false;
1580 // We don't need to do any more checking here; canSinkLastInstruction should
1581 // have done it all for us.
1582 SmallVector<Value*, 4> NewOperands;
1583 for (unsigned O = 0, E = I0->getNumOperands(); O != E; ++O) {
1584 // This check is different to that in canSinkLastInstruction. There, we
1585 // cared about the global view once simplifycfg (and instcombine) have
1586 // completed - it takes into account PHIs that become trivially
1587 // simplifiable. However here we need a more local view; if an operand
1588 // differs we create a PHI and rely on instcombine to clean up the very
1589 // small mess we may make.
1590 bool NeedPHI = any_of(Insts, [&I0, O](const Instruction *I) {
1591 return I->getOperand(O) != I0->getOperand(O);
1593 if (!NeedPHI) {
1594 NewOperands.push_back(I0->getOperand(O));
1595 continue;
1598 // Create a new PHI in the successor block and populate it.
1599 auto *Op = I0->getOperand(O);
1600 assert(!Op->getType()->isTokenTy() && "Can't PHI tokens!");
1601 auto *PN = PHINode::Create(Op->getType(), Insts.size(),
1602 Op->getName() + ".sink", &BBEnd->front());
1603 for (auto *I : Insts)
1604 PN->addIncoming(I->getOperand(O), I->getParent());
1605 NewOperands.push_back(PN);
1608 // Arbitrarily use I0 as the new "common" instruction; remap its operands
1609 // and move it to the start of the successor block.
1610 for (unsigned O = 0, E = I0->getNumOperands(); O != E; ++O)
1611 I0->getOperandUse(O).set(NewOperands[O]);
1612 I0->moveBefore(&*BBEnd->getFirstInsertionPt());
1614 // Update metadata and IR flags, and merge debug locations.
1615 for (auto *I : Insts)
1616 if (I != I0) {
1617 // The debug location for the "common" instruction is the merged locations
1618 // of all the commoned instructions. We start with the original location
1619 // of the "common" instruction and iteratively merge each location in the
1620 // loop below.
1621 // This is an N-way merge, which will be inefficient if I0 is a CallInst.
1622 // However, as N-way merge for CallInst is rare, so we use simplified API
1623 // instead of using complex API for N-way merge.
1624 I0->applyMergedLocation(I0->getDebugLoc(), I->getDebugLoc());
1625 combineMetadataForCSE(I0, I, true);
1626 I0->andIRFlags(I);
1629 if (!I0->user_empty()) {
1630 // canSinkLastInstruction checked that all instructions were used by
1631 // one and only one PHI node. Find that now, RAUW it to our common
1632 // instruction and nuke it.
1633 auto *PN = cast<PHINode>(*I0->user_begin());
1634 PN->replaceAllUsesWith(I0);
1635 PN->eraseFromParent();
1638 // Finally nuke all instructions apart from the common instruction.
1639 for (auto *I : Insts)
1640 if (I != I0)
1641 I->eraseFromParent();
1643 return true;
1646 namespace {
1648 // LockstepReverseIterator - Iterates through instructions
1649 // in a set of blocks in reverse order from the first non-terminator.
1650 // For example (assume all blocks have size n):
1651 // LockstepReverseIterator I([B1, B2, B3]);
1652 // *I-- = [B1[n], B2[n], B3[n]];
1653 // *I-- = [B1[n-1], B2[n-1], B3[n-1]];
1654 // *I-- = [B1[n-2], B2[n-2], B3[n-2]];
1655 // ...
1656 class LockstepReverseIterator {
1657 ArrayRef<BasicBlock*> Blocks;
1658 SmallVector<Instruction*,4> Insts;
1659 bool Fail;
1661 public:
1662 LockstepReverseIterator(ArrayRef<BasicBlock*> Blocks) : Blocks(Blocks) {
1663 reset();
1666 void reset() {
1667 Fail = false;
1668 Insts.clear();
1669 for (auto *BB : Blocks) {
1670 Instruction *Inst = BB->getTerminator();
1671 for (Inst = Inst->getPrevNode(); Inst && isa<DbgInfoIntrinsic>(Inst);)
1672 Inst = Inst->getPrevNode();
1673 if (!Inst) {
1674 // Block wasn't big enough.
1675 Fail = true;
1676 return;
1678 Insts.push_back(Inst);
1682 bool isValid() const {
1683 return !Fail;
1686 void operator--() {
1687 if (Fail)
1688 return;
1689 for (auto *&Inst : Insts) {
1690 for (Inst = Inst->getPrevNode(); Inst && isa<DbgInfoIntrinsic>(Inst);)
1691 Inst = Inst->getPrevNode();
1692 // Already at beginning of block.
1693 if (!Inst) {
1694 Fail = true;
1695 return;
1700 ArrayRef<Instruction*> operator * () const {
1701 return Insts;
1705 } // end anonymous namespace
1707 /// Check whether BB's predecessors end with unconditional branches. If it is
1708 /// true, sink any common code from the predecessors to BB.
1709 /// We also allow one predecessor to end with conditional branch (but no more
1710 /// than one).
1711 static bool SinkCommonCodeFromPredecessors(BasicBlock *BB) {
1712 // We support two situations:
1713 // (1) all incoming arcs are unconditional
1714 // (2) one incoming arc is conditional
1716 // (2) is very common in switch defaults and
1717 // else-if patterns;
1719 // if (a) f(1);
1720 // else if (b) f(2);
1722 // produces:
1724 // [if]
1725 // / \
1726 // [f(1)] [if]
1727 // | | \
1728 // | | |
1729 // | [f(2)]|
1730 // \ | /
1731 // [ end ]
1733 // [end] has two unconditional predecessor arcs and one conditional. The
1734 // conditional refers to the implicit empty 'else' arc. This conditional
1735 // arc can also be caused by an empty default block in a switch.
1737 // In this case, we attempt to sink code from all *unconditional* arcs.
1738 // If we can sink instructions from these arcs (determined during the scan
1739 // phase below) we insert a common successor for all unconditional arcs and
1740 // connect that to [end], to enable sinking:
1742 // [if]
1743 // / \
1744 // [x(1)] [if]
1745 // | | \
1746 // | | \
1747 // | [x(2)] |
1748 // \ / |
1749 // [sink.split] |
1750 // \ /
1751 // [ end ]
1753 SmallVector<BasicBlock*,4> UnconditionalPreds;
1754 Instruction *Cond = nullptr;
1755 for (auto *B : predecessors(BB)) {
1756 auto *T = B->getTerminator();
1757 if (isa<BranchInst>(T) && cast<BranchInst>(T)->isUnconditional())
1758 UnconditionalPreds.push_back(B);
1759 else if ((isa<BranchInst>(T) || isa<SwitchInst>(T)) && !Cond)
1760 Cond = T;
1761 else
1762 return false;
1764 if (UnconditionalPreds.size() < 2)
1765 return false;
1767 bool Changed = false;
1768 // We take a two-step approach to tail sinking. First we scan from the end of
1769 // each block upwards in lockstep. If the n'th instruction from the end of each
1770 // block can be sunk, those instructions are added to ValuesToSink and we
1771 // carry on. If we can sink an instruction but need to PHI-merge some operands
1772 // (because they're not identical in each instruction) we add these to
1773 // PHIOperands.
1774 unsigned ScanIdx = 0;
1775 SmallPtrSet<Value*,4> InstructionsToSink;
1776 DenseMap<Instruction*, SmallVector<Value*,4>> PHIOperands;
1777 LockstepReverseIterator LRI(UnconditionalPreds);
1778 while (LRI.isValid() &&
1779 canSinkInstructions(*LRI, PHIOperands)) {
1780 LLVM_DEBUG(dbgs() << "SINK: instruction can be sunk: " << *(*LRI)[0]
1781 << "\n");
1782 InstructionsToSink.insert((*LRI).begin(), (*LRI).end());
1783 ++ScanIdx;
1784 --LRI;
1787 auto ProfitableToSinkInstruction = [&](LockstepReverseIterator &LRI) {
1788 unsigned NumPHIdValues = 0;
1789 for (auto *I : *LRI)
1790 for (auto *V : PHIOperands[I])
1791 if (InstructionsToSink.count(V) == 0)
1792 ++NumPHIdValues;
1793 LLVM_DEBUG(dbgs() << "SINK: #phid values: " << NumPHIdValues << "\n");
1794 unsigned NumPHIInsts = NumPHIdValues / UnconditionalPreds.size();
1795 if ((NumPHIdValues % UnconditionalPreds.size()) != 0)
1796 NumPHIInsts++;
1798 return NumPHIInsts <= 1;
1801 if (ScanIdx > 0 && Cond) {
1802 // Check if we would actually sink anything first! This mutates the CFG and
1803 // adds an extra block. The goal in doing this is to allow instructions that
1804 // couldn't be sunk before to be sunk - obviously, speculatable instructions
1805 // (such as trunc, add) can be sunk and predicated already. So we check that
1806 // we're going to sink at least one non-speculatable instruction.
1807 LRI.reset();
1808 unsigned Idx = 0;
1809 bool Profitable = false;
1810 while (ProfitableToSinkInstruction(LRI) && Idx < ScanIdx) {
1811 if (!isSafeToSpeculativelyExecute((*LRI)[0])) {
1812 Profitable = true;
1813 break;
1815 --LRI;
1816 ++Idx;
1818 if (!Profitable)
1819 return false;
1821 LLVM_DEBUG(dbgs() << "SINK: Splitting edge\n");
1822 // We have a conditional edge and we're going to sink some instructions.
1823 // Insert a new block postdominating all blocks we're going to sink from.
1824 if (!SplitBlockPredecessors(BB, UnconditionalPreds, ".sink.split"))
1825 // Edges couldn't be split.
1826 return false;
1827 Changed = true;
1830 // Now that we've analyzed all potential sinking candidates, perform the
1831 // actual sink. We iteratively sink the last non-terminator of the source
1832 // blocks into their common successor unless doing so would require too
1833 // many PHI instructions to be generated (currently only one PHI is allowed
1834 // per sunk instruction).
1836 // We can use InstructionsToSink to discount values needing PHI-merging that will
1837 // actually be sunk in a later iteration. This allows us to be more
1838 // aggressive in what we sink. This does allow a false positive where we
1839 // sink presuming a later value will also be sunk, but stop half way through
1840 // and never actually sink it which means we produce more PHIs than intended.
1841 // This is unlikely in practice though.
1842 for (unsigned SinkIdx = 0; SinkIdx != ScanIdx; ++SinkIdx) {
1843 LLVM_DEBUG(dbgs() << "SINK: Sink: "
1844 << *UnconditionalPreds[0]->getTerminator()->getPrevNode()
1845 << "\n");
1847 // Because we've sunk every instruction in turn, the current instruction to
1848 // sink is always at index 0.
1849 LRI.reset();
1850 if (!ProfitableToSinkInstruction(LRI)) {
1851 // Too many PHIs would be created.
1852 LLVM_DEBUG(
1853 dbgs() << "SINK: stopping here, too many PHIs would be created!\n");
1854 break;
1857 if (!sinkLastInstruction(UnconditionalPreds))
1858 return Changed;
1859 NumSinkCommons++;
1860 Changed = true;
1862 return Changed;
1865 /// Determine if we can hoist sink a sole store instruction out of a
1866 /// conditional block.
1868 /// We are looking for code like the following:
1869 /// BrBB:
1870 /// store i32 %add, i32* %arrayidx2
1871 /// ... // No other stores or function calls (we could be calling a memory
1872 /// ... // function).
1873 /// %cmp = icmp ult %x, %y
1874 /// br i1 %cmp, label %EndBB, label %ThenBB
1875 /// ThenBB:
1876 /// store i32 %add5, i32* %arrayidx2
1877 /// br label EndBB
1878 /// EndBB:
1879 /// ...
1880 /// We are going to transform this into:
1881 /// BrBB:
1882 /// store i32 %add, i32* %arrayidx2
1883 /// ... //
1884 /// %cmp = icmp ult %x, %y
1885 /// %add.add5 = select i1 %cmp, i32 %add, %add5
1886 /// store i32 %add.add5, i32* %arrayidx2
1887 /// ...
1889 /// \return The pointer to the value of the previous store if the store can be
1890 /// hoisted into the predecessor block. 0 otherwise.
1891 static Value *isSafeToSpeculateStore(Instruction *I, BasicBlock *BrBB,
1892 BasicBlock *StoreBB, BasicBlock *EndBB) {
1893 StoreInst *StoreToHoist = dyn_cast<StoreInst>(I);
1894 if (!StoreToHoist)
1895 return nullptr;
1897 // Volatile or atomic.
1898 if (!StoreToHoist->isSimple())
1899 return nullptr;
1901 Value *StorePtr = StoreToHoist->getPointerOperand();
1903 // Look for a store to the same pointer in BrBB.
1904 unsigned MaxNumInstToLookAt = 9;
1905 for (Instruction &CurI : reverse(BrBB->instructionsWithoutDebug())) {
1906 if (!MaxNumInstToLookAt)
1907 break;
1908 --MaxNumInstToLookAt;
1910 // Could be calling an instruction that affects memory like free().
1911 if (CurI.mayHaveSideEffects() && !isa<StoreInst>(CurI))
1912 return nullptr;
1914 if (auto *SI = dyn_cast<StoreInst>(&CurI)) {
1915 // Found the previous store make sure it stores to the same location.
1916 if (SI->getPointerOperand() == StorePtr)
1917 // Found the previous store, return its value operand.
1918 return SI->getValueOperand();
1919 return nullptr; // Unknown store.
1923 return nullptr;
1926 /// Speculate a conditional basic block flattening the CFG.
1928 /// Note that this is a very risky transform currently. Speculating
1929 /// instructions like this is most often not desirable. Instead, there is an MI
1930 /// pass which can do it with full awareness of the resource constraints.
1931 /// However, some cases are "obvious" and we should do directly. An example of
1932 /// this is speculating a single, reasonably cheap instruction.
1934 /// There is only one distinct advantage to flattening the CFG at the IR level:
1935 /// it makes very common but simplistic optimizations such as are common in
1936 /// instcombine and the DAG combiner more powerful by removing CFG edges and
1937 /// modeling their effects with easier to reason about SSA value graphs.
1940 /// An illustration of this transform is turning this IR:
1941 /// \code
1942 /// BB:
1943 /// %cmp = icmp ult %x, %y
1944 /// br i1 %cmp, label %EndBB, label %ThenBB
1945 /// ThenBB:
1946 /// %sub = sub %x, %y
1947 /// br label BB2
1948 /// EndBB:
1949 /// %phi = phi [ %sub, %ThenBB ], [ 0, %EndBB ]
1950 /// ...
1951 /// \endcode
1953 /// Into this IR:
1954 /// \code
1955 /// BB:
1956 /// %cmp = icmp ult %x, %y
1957 /// %sub = sub %x, %y
1958 /// %cond = select i1 %cmp, 0, %sub
1959 /// ...
1960 /// \endcode
1962 /// \returns true if the conditional block is removed.
1963 static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB,
1964 const TargetTransformInfo &TTI) {
1965 // Be conservative for now. FP select instruction can often be expensive.
1966 Value *BrCond = BI->getCondition();
1967 if (isa<FCmpInst>(BrCond))
1968 return false;
1970 BasicBlock *BB = BI->getParent();
1971 BasicBlock *EndBB = ThenBB->getTerminator()->getSuccessor(0);
1973 // If ThenBB is actually on the false edge of the conditional branch, remember
1974 // to swap the select operands later.
1975 bool Invert = false;
1976 if (ThenBB != BI->getSuccessor(0)) {
1977 assert(ThenBB == BI->getSuccessor(1) && "No edge from 'if' block?");
1978 Invert = true;
1980 assert(EndBB == BI->getSuccessor(!Invert) && "No edge from to end block");
1982 // Keep a count of how many times instructions are used within ThenBB when
1983 // they are candidates for sinking into ThenBB. Specifically:
1984 // - They are defined in BB, and
1985 // - They have no side effects, and
1986 // - All of their uses are in ThenBB.
1987 SmallDenseMap<Instruction *, unsigned, 4> SinkCandidateUseCounts;
1989 SmallVector<Instruction *, 4> SpeculatedDbgIntrinsics;
1991 unsigned SpeculatedInstructions = 0;
1992 Value *SpeculatedStoreValue = nullptr;
1993 StoreInst *SpeculatedStore = nullptr;
1994 for (BasicBlock::iterator BBI = ThenBB->begin(),
1995 BBE = std::prev(ThenBB->end());
1996 BBI != BBE; ++BBI) {
1997 Instruction *I = &*BBI;
1998 // Skip debug info.
1999 if (isa<DbgInfoIntrinsic>(I)) {
2000 SpeculatedDbgIntrinsics.push_back(I);
2001 continue;
2004 // Only speculatively execute a single instruction (not counting the
2005 // terminator) for now.
2006 ++SpeculatedInstructions;
2007 if (SpeculatedInstructions > 1)
2008 return false;
2010 // Don't hoist the instruction if it's unsafe or expensive.
2011 if (!isSafeToSpeculativelyExecute(I) &&
2012 !(HoistCondStores && (SpeculatedStoreValue = isSafeToSpeculateStore(
2013 I, BB, ThenBB, EndBB))))
2014 return false;
2015 if (!SpeculatedStoreValue &&
2016 ComputeSpeculationCost(I, TTI) >
2017 PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic)
2018 return false;
2020 // Store the store speculation candidate.
2021 if (SpeculatedStoreValue)
2022 SpeculatedStore = cast<StoreInst>(I);
2024 // Do not hoist the instruction if any of its operands are defined but not
2025 // used in BB. The transformation will prevent the operand from
2026 // being sunk into the use block.
2027 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
2028 Instruction *OpI = dyn_cast<Instruction>(*i);
2029 if (!OpI || OpI->getParent() != BB || OpI->mayHaveSideEffects())
2030 continue; // Not a candidate for sinking.
2032 ++SinkCandidateUseCounts[OpI];
2036 // Consider any sink candidates which are only used in ThenBB as costs for
2037 // speculation. Note, while we iterate over a DenseMap here, we are summing
2038 // and so iteration order isn't significant.
2039 for (SmallDenseMap<Instruction *, unsigned, 4>::iterator
2040 I = SinkCandidateUseCounts.begin(),
2041 E = SinkCandidateUseCounts.end();
2042 I != E; ++I)
2043 if (I->first->hasNUses(I->second)) {
2044 ++SpeculatedInstructions;
2045 if (SpeculatedInstructions > 1)
2046 return false;
2049 // Check that the PHI nodes can be converted to selects.
2050 bool HaveRewritablePHIs = false;
2051 for (PHINode &PN : EndBB->phis()) {
2052 Value *OrigV = PN.getIncomingValueForBlock(BB);
2053 Value *ThenV = PN.getIncomingValueForBlock(ThenBB);
2055 // FIXME: Try to remove some of the duplication with HoistThenElseCodeToIf.
2056 // Skip PHIs which are trivial.
2057 if (ThenV == OrigV)
2058 continue;
2060 // Don't convert to selects if we could remove undefined behavior instead.
2061 if (passingValueIsAlwaysUndefined(OrigV, &PN) ||
2062 passingValueIsAlwaysUndefined(ThenV, &PN))
2063 return false;
2065 HaveRewritablePHIs = true;
2066 ConstantExpr *OrigCE = dyn_cast<ConstantExpr>(OrigV);
2067 ConstantExpr *ThenCE = dyn_cast<ConstantExpr>(ThenV);
2068 if (!OrigCE && !ThenCE)
2069 continue; // Known safe and cheap.
2071 if ((ThenCE && !isSafeToSpeculativelyExecute(ThenCE)) ||
2072 (OrigCE && !isSafeToSpeculativelyExecute(OrigCE)))
2073 return false;
2074 unsigned OrigCost = OrigCE ? ComputeSpeculationCost(OrigCE, TTI) : 0;
2075 unsigned ThenCost = ThenCE ? ComputeSpeculationCost(ThenCE, TTI) : 0;
2076 unsigned MaxCost =
2077 2 * PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic;
2078 if (OrigCost + ThenCost > MaxCost)
2079 return false;
2081 // Account for the cost of an unfolded ConstantExpr which could end up
2082 // getting expanded into Instructions.
2083 // FIXME: This doesn't account for how many operations are combined in the
2084 // constant expression.
2085 ++SpeculatedInstructions;
2086 if (SpeculatedInstructions > 1)
2087 return false;
2090 // If there are no PHIs to process, bail early. This helps ensure idempotence
2091 // as well.
2092 if (!HaveRewritablePHIs && !(HoistCondStores && SpeculatedStoreValue))
2093 return false;
2095 // If we get here, we can hoist the instruction and if-convert.
2096 LLVM_DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *ThenBB << "\n";);
2098 // Insert a select of the value of the speculated store.
2099 if (SpeculatedStoreValue) {
2100 IRBuilder<NoFolder> Builder(BI);
2101 Value *TrueV = SpeculatedStore->getValueOperand();
2102 Value *FalseV = SpeculatedStoreValue;
2103 if (Invert)
2104 std::swap(TrueV, FalseV);
2105 Value *S = Builder.CreateSelect(
2106 BrCond, TrueV, FalseV, "spec.store.select", BI);
2107 SpeculatedStore->setOperand(0, S);
2108 SpeculatedStore->applyMergedLocation(BI->getDebugLoc(),
2109 SpeculatedStore->getDebugLoc());
2112 // Metadata can be dependent on the condition we are hoisting above.
2113 // Conservatively strip all metadata on the instruction.
2114 for (auto &I : *ThenBB)
2115 I.dropUnknownNonDebugMetadata();
2117 // Hoist the instructions.
2118 BB->getInstList().splice(BI->getIterator(), ThenBB->getInstList(),
2119 ThenBB->begin(), std::prev(ThenBB->end()));
2121 // Insert selects and rewrite the PHI operands.
2122 IRBuilder<NoFolder> Builder(BI);
2123 for (PHINode &PN : EndBB->phis()) {
2124 unsigned OrigI = PN.getBasicBlockIndex(BB);
2125 unsigned ThenI = PN.getBasicBlockIndex(ThenBB);
2126 Value *OrigV = PN.getIncomingValue(OrigI);
2127 Value *ThenV = PN.getIncomingValue(ThenI);
2129 // Skip PHIs which are trivial.
2130 if (OrigV == ThenV)
2131 continue;
2133 // Create a select whose true value is the speculatively executed value and
2134 // false value is the preexisting value. Swap them if the branch
2135 // destinations were inverted.
2136 Value *TrueV = ThenV, *FalseV = OrigV;
2137 if (Invert)
2138 std::swap(TrueV, FalseV);
2139 Value *V = Builder.CreateSelect(
2140 BrCond, TrueV, FalseV, "spec.select", BI);
2141 PN.setIncomingValue(OrigI, V);
2142 PN.setIncomingValue(ThenI, V);
2145 // Remove speculated dbg intrinsics.
2146 // FIXME: Is it possible to do this in a more elegant way? Moving/merging the
2147 // dbg value for the different flows and inserting it after the select.
2148 for (Instruction *I : SpeculatedDbgIntrinsics)
2149 I->eraseFromParent();
2151 ++NumSpeculations;
2152 return true;
2155 /// Return true if we can thread a branch across this block.
2156 static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
2157 unsigned Size = 0;
2159 for (Instruction &I : BB->instructionsWithoutDebug()) {
2160 if (Size > 10)
2161 return false; // Don't clone large BB's.
2162 ++Size;
2164 // We can only support instructions that do not define values that are
2165 // live outside of the current basic block.
2166 for (User *U : I.users()) {
2167 Instruction *UI = cast<Instruction>(U);
2168 if (UI->getParent() != BB || isa<PHINode>(UI))
2169 return false;
2172 // Looks ok, continue checking.
2175 return true;
2178 /// If we have a conditional branch on a PHI node value that is defined in the
2179 /// same block as the branch and if any PHI entries are constants, thread edges
2180 /// corresponding to that entry to be branches to their ultimate destination.
2181 static bool FoldCondBranchOnPHI(BranchInst *BI, const DataLayout &DL,
2182 AssumptionCache *AC) {
2183 BasicBlock *BB = BI->getParent();
2184 PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
2185 // NOTE: we currently cannot transform this case if the PHI node is used
2186 // outside of the block.
2187 if (!PN || PN->getParent() != BB || !PN->hasOneUse())
2188 return false;
2190 // Degenerate case of a single entry PHI.
2191 if (PN->getNumIncomingValues() == 1) {
2192 FoldSingleEntryPHINodes(PN->getParent());
2193 return true;
2196 // Now we know that this block has multiple preds and two succs.
2197 if (!BlockIsSimpleEnoughToThreadThrough(BB))
2198 return false;
2200 // Can't fold blocks that contain noduplicate or convergent calls.
2201 if (any_of(*BB, [](const Instruction &I) {
2202 const CallInst *CI = dyn_cast<CallInst>(&I);
2203 return CI && (CI->cannotDuplicate() || CI->isConvergent());
2205 return false;
2207 // Okay, this is a simple enough basic block. See if any phi values are
2208 // constants.
2209 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2210 ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i));
2211 if (!CB || !CB->getType()->isIntegerTy(1))
2212 continue;
2214 // Okay, we now know that all edges from PredBB should be revectored to
2215 // branch to RealDest.
2216 BasicBlock *PredBB = PN->getIncomingBlock(i);
2217 BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
2219 if (RealDest == BB)
2220 continue; // Skip self loops.
2221 // Skip if the predecessor's terminator is an indirect branch.
2222 if (isa<IndirectBrInst>(PredBB->getTerminator()))
2223 continue;
2225 // The dest block might have PHI nodes, other predecessors and other
2226 // difficult cases. Instead of being smart about this, just insert a new
2227 // block that jumps to the destination block, effectively splitting
2228 // the edge we are about to create.
2229 BasicBlock *EdgeBB =
2230 BasicBlock::Create(BB->getContext(), RealDest->getName() + ".critedge",
2231 RealDest->getParent(), RealDest);
2232 BranchInst *CritEdgeBranch = BranchInst::Create(RealDest, EdgeBB);
2233 CritEdgeBranch->setDebugLoc(BI->getDebugLoc());
2235 // Update PHI nodes.
2236 AddPredecessorToBlock(RealDest, EdgeBB, BB);
2238 // BB may have instructions that are being threaded over. Clone these
2239 // instructions into EdgeBB. We know that there will be no uses of the
2240 // cloned instructions outside of EdgeBB.
2241 BasicBlock::iterator InsertPt = EdgeBB->begin();
2242 DenseMap<Value *, Value *> TranslateMap; // Track translated values.
2243 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
2244 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
2245 TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
2246 continue;
2248 // Clone the instruction.
2249 Instruction *N = BBI->clone();
2250 if (BBI->hasName())
2251 N->setName(BBI->getName() + ".c");
2253 // Update operands due to translation.
2254 for (User::op_iterator i = N->op_begin(), e = N->op_end(); i != e; ++i) {
2255 DenseMap<Value *, Value *>::iterator PI = TranslateMap.find(*i);
2256 if (PI != TranslateMap.end())
2257 *i = PI->second;
2260 // Check for trivial simplification.
2261 if (Value *V = SimplifyInstruction(N, {DL, nullptr, nullptr, AC})) {
2262 if (!BBI->use_empty())
2263 TranslateMap[&*BBI] = V;
2264 if (!N->mayHaveSideEffects()) {
2265 N->deleteValue(); // Instruction folded away, don't need actual inst
2266 N = nullptr;
2268 } else {
2269 if (!BBI->use_empty())
2270 TranslateMap[&*BBI] = N;
2272 if (N) {
2273 // Insert the new instruction into its new home.
2274 EdgeBB->getInstList().insert(InsertPt, N);
2276 // Register the new instruction with the assumption cache if necessary.
2277 if (AC && match(N, m_Intrinsic<Intrinsic::assume>()))
2278 AC->registerAssumption(cast<IntrinsicInst>(N));
2282 // Loop over all of the edges from PredBB to BB, changing them to branch
2283 // to EdgeBB instead.
2284 Instruction *PredBBTI = PredBB->getTerminator();
2285 for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
2286 if (PredBBTI->getSuccessor(i) == BB) {
2287 BB->removePredecessor(PredBB);
2288 PredBBTI->setSuccessor(i, EdgeBB);
2291 // Recurse, simplifying any other constants.
2292 return FoldCondBranchOnPHI(BI, DL, AC) || true;
2295 return false;
2298 /// Given a BB that starts with the specified two-entry PHI node,
2299 /// see if we can eliminate it.
2300 static bool FoldTwoEntryPHINode(PHINode *PN, const TargetTransformInfo &TTI,
2301 const DataLayout &DL) {
2302 // Ok, this is a two entry PHI node. Check to see if this is a simple "if
2303 // statement", which has a very simple dominance structure. Basically, we
2304 // are trying to find the condition that is being branched on, which
2305 // subsequently causes this merge to happen. We really want control
2306 // dependence information for this check, but simplifycfg can't keep it up
2307 // to date, and this catches most of the cases we care about anyway.
2308 BasicBlock *BB = PN->getParent();
2309 const Function *Fn = BB->getParent();
2310 if (Fn && Fn->hasFnAttribute(Attribute::OptForFuzzing))
2311 return false;
2313 BasicBlock *IfTrue, *IfFalse;
2314 Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
2315 if (!IfCond ||
2316 // Don't bother if the branch will be constant folded trivially.
2317 isa<ConstantInt>(IfCond))
2318 return false;
2320 // Okay, we found that we can merge this two-entry phi node into a select.
2321 // Doing so would require us to fold *all* two entry phi nodes in this block.
2322 // At some point this becomes non-profitable (particularly if the target
2323 // doesn't support cmov's). Only do this transformation if there are two or
2324 // fewer PHI nodes in this block.
2325 unsigned NumPhis = 0;
2326 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
2327 if (NumPhis > 2)
2328 return false;
2330 // Loop over the PHI's seeing if we can promote them all to select
2331 // instructions. While we are at it, keep track of the instructions
2332 // that need to be moved to the dominating block.
2333 SmallPtrSet<Instruction *, 4> AggressiveInsts;
2334 int BudgetRemaining =
2335 TwoEntryPHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic;
2337 for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) {
2338 PHINode *PN = cast<PHINode>(II++);
2339 if (Value *V = SimplifyInstruction(PN, {DL, PN})) {
2340 PN->replaceAllUsesWith(V);
2341 PN->eraseFromParent();
2342 continue;
2345 if (!DominatesMergePoint(PN->getIncomingValue(0), BB, AggressiveInsts,
2346 BudgetRemaining, TTI) ||
2347 !DominatesMergePoint(PN->getIncomingValue(1), BB, AggressiveInsts,
2348 BudgetRemaining, TTI))
2349 return false;
2352 // If we folded the first phi, PN dangles at this point. Refresh it. If
2353 // we ran out of PHIs then we simplified them all.
2354 PN = dyn_cast<PHINode>(BB->begin());
2355 if (!PN)
2356 return true;
2358 // Return true if at least one of these is a 'not', and another is either
2359 // a 'not' too, or a constant.
2360 auto CanHoistNotFromBothValues = [](Value *V0, Value *V1) {
2361 if (!match(V0, m_Not(m_Value())))
2362 std::swap(V0, V1);
2363 auto Invertible = m_CombineOr(m_Not(m_Value()), m_AnyIntegralConstant());
2364 return match(V0, m_Not(m_Value())) && match(V1, Invertible);
2367 // Don't fold i1 branches on PHIs which contain binary operators, unless one
2368 // of the incoming values is an 'not' and another one is freely invertible.
2369 // These can often be turned into switches and other things.
2370 if (PN->getType()->isIntegerTy(1) &&
2371 (isa<BinaryOperator>(PN->getIncomingValue(0)) ||
2372 isa<BinaryOperator>(PN->getIncomingValue(1)) ||
2373 isa<BinaryOperator>(IfCond)) &&
2374 !CanHoistNotFromBothValues(PN->getIncomingValue(0),
2375 PN->getIncomingValue(1)))
2376 return false;
2378 // If all PHI nodes are promotable, check to make sure that all instructions
2379 // in the predecessor blocks can be promoted as well. If not, we won't be able
2380 // to get rid of the control flow, so it's not worth promoting to select
2381 // instructions.
2382 BasicBlock *DomBlock = nullptr;
2383 BasicBlock *IfBlock1 = PN->getIncomingBlock(0);
2384 BasicBlock *IfBlock2 = PN->getIncomingBlock(1);
2385 if (cast<BranchInst>(IfBlock1->getTerminator())->isConditional()) {
2386 IfBlock1 = nullptr;
2387 } else {
2388 DomBlock = *pred_begin(IfBlock1);
2389 for (BasicBlock::iterator I = IfBlock1->begin(); !I->isTerminator(); ++I)
2390 if (!AggressiveInsts.count(&*I) && !isa<DbgInfoIntrinsic>(I)) {
2391 // This is not an aggressive instruction that we can promote.
2392 // Because of this, we won't be able to get rid of the control flow, so
2393 // the xform is not worth it.
2394 return false;
2398 if (cast<BranchInst>(IfBlock2->getTerminator())->isConditional()) {
2399 IfBlock2 = nullptr;
2400 } else {
2401 DomBlock = *pred_begin(IfBlock2);
2402 for (BasicBlock::iterator I = IfBlock2->begin(); !I->isTerminator(); ++I)
2403 if (!AggressiveInsts.count(&*I) && !isa<DbgInfoIntrinsic>(I)) {
2404 // This is not an aggressive instruction that we can promote.
2405 // Because of this, we won't be able to get rid of the control flow, so
2406 // the xform is not worth it.
2407 return false;
2410 assert(DomBlock && "Failed to find root DomBlock");
2412 LLVM_DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond
2413 << " T: " << IfTrue->getName()
2414 << " F: " << IfFalse->getName() << "\n");
2416 // If we can still promote the PHI nodes after this gauntlet of tests,
2417 // do all of the PHI's now.
2418 Instruction *InsertPt = DomBlock->getTerminator();
2419 IRBuilder<NoFolder> Builder(InsertPt);
2421 // Move all 'aggressive' instructions, which are defined in the
2422 // conditional parts of the if's up to the dominating block.
2423 if (IfBlock1)
2424 hoistAllInstructionsInto(DomBlock, InsertPt, IfBlock1);
2425 if (IfBlock2)
2426 hoistAllInstructionsInto(DomBlock, InsertPt, IfBlock2);
2428 // Propagate fast-math-flags from phi nodes to replacement selects.
2429 IRBuilder<>::FastMathFlagGuard FMFGuard(Builder);
2430 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
2431 if (isa<FPMathOperator>(PN))
2432 Builder.setFastMathFlags(PN->getFastMathFlags());
2434 // Change the PHI node into a select instruction.
2435 Value *TrueVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
2436 Value *FalseVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
2438 Value *Sel = Builder.CreateSelect(IfCond, TrueVal, FalseVal, "", InsertPt);
2439 PN->replaceAllUsesWith(Sel);
2440 Sel->takeName(PN);
2441 PN->eraseFromParent();
2444 // At this point, IfBlock1 and IfBlock2 are both empty, so our if statement
2445 // has been flattened. Change DomBlock to jump directly to our new block to
2446 // avoid other simplifycfg's kicking in on the diamond.
2447 Instruction *OldTI = DomBlock->getTerminator();
2448 Builder.SetInsertPoint(OldTI);
2449 Builder.CreateBr(BB);
2450 OldTI->eraseFromParent();
2451 return true;
2454 /// If we found a conditional branch that goes to two returning blocks,
2455 /// try to merge them together into one return,
2456 /// introducing a select if the return values disagree.
2457 static bool SimplifyCondBranchToTwoReturns(BranchInst *BI,
2458 IRBuilder<> &Builder) {
2459 assert(BI->isConditional() && "Must be a conditional branch");
2460 BasicBlock *TrueSucc = BI->getSuccessor(0);
2461 BasicBlock *FalseSucc = BI->getSuccessor(1);
2462 ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator());
2463 ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator());
2465 // Check to ensure both blocks are empty (just a return) or optionally empty
2466 // with PHI nodes. If there are other instructions, merging would cause extra
2467 // computation on one path or the other.
2468 if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator())
2469 return false;
2470 if (!FalseSucc->getFirstNonPHIOrDbg()->isTerminator())
2471 return false;
2473 Builder.SetInsertPoint(BI);
2474 // Okay, we found a branch that is going to two return nodes. If
2475 // there is no return value for this function, just change the
2476 // branch into a return.
2477 if (FalseRet->getNumOperands() == 0) {
2478 TrueSucc->removePredecessor(BI->getParent());
2479 FalseSucc->removePredecessor(BI->getParent());
2480 Builder.CreateRetVoid();
2481 EraseTerminatorAndDCECond(BI);
2482 return true;
2485 // Otherwise, figure out what the true and false return values are
2486 // so we can insert a new select instruction.
2487 Value *TrueValue = TrueRet->getReturnValue();
2488 Value *FalseValue = FalseRet->getReturnValue();
2490 // Unwrap any PHI nodes in the return blocks.
2491 if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue))
2492 if (TVPN->getParent() == TrueSucc)
2493 TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
2494 if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue))
2495 if (FVPN->getParent() == FalseSucc)
2496 FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
2498 // In order for this transformation to be safe, we must be able to
2499 // unconditionally execute both operands to the return. This is
2500 // normally the case, but we could have a potentially-trapping
2501 // constant expression that prevents this transformation from being
2502 // safe.
2503 if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue))
2504 if (TCV->canTrap())
2505 return false;
2506 if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue))
2507 if (FCV->canTrap())
2508 return false;
2510 // Okay, we collected all the mapped values and checked them for sanity, and
2511 // defined to really do this transformation. First, update the CFG.
2512 TrueSucc->removePredecessor(BI->getParent());
2513 FalseSucc->removePredecessor(BI->getParent());
2515 // Insert select instructions where needed.
2516 Value *BrCond = BI->getCondition();
2517 if (TrueValue) {
2518 // Insert a select if the results differ.
2519 if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) {
2520 } else if (isa<UndefValue>(TrueValue)) {
2521 TrueValue = FalseValue;
2522 } else {
2523 TrueValue =
2524 Builder.CreateSelect(BrCond, TrueValue, FalseValue, "retval", BI);
2528 Value *RI =
2529 !TrueValue ? Builder.CreateRetVoid() : Builder.CreateRet(TrueValue);
2531 (void)RI;
2533 LLVM_DEBUG(dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
2534 << "\n " << *BI << "NewRet = " << *RI << "TRUEBLOCK: "
2535 << *TrueSucc << "FALSEBLOCK: " << *FalseSucc);
2537 EraseTerminatorAndDCECond(BI);
2539 return true;
2542 /// Return true if the given instruction is available
2543 /// in its predecessor block. If yes, the instruction will be removed.
2544 static bool tryCSEWithPredecessor(Instruction *Inst, BasicBlock *PB) {
2545 if (!isa<BinaryOperator>(Inst) && !isa<CmpInst>(Inst))
2546 return false;
2547 for (Instruction &I : *PB) {
2548 Instruction *PBI = &I;
2549 // Check whether Inst and PBI generate the same value.
2550 if (Inst->isIdenticalTo(PBI)) {
2551 Inst->replaceAllUsesWith(PBI);
2552 Inst->eraseFromParent();
2553 return true;
2556 return false;
2559 /// Return true if either PBI or BI has branch weight available, and store
2560 /// the weights in {Pred|Succ}{True|False}Weight. If one of PBI and BI does
2561 /// not have branch weight, use 1:1 as its weight.
2562 static bool extractPredSuccWeights(BranchInst *PBI, BranchInst *BI,
2563 uint64_t &PredTrueWeight,
2564 uint64_t &PredFalseWeight,
2565 uint64_t &SuccTrueWeight,
2566 uint64_t &SuccFalseWeight) {
2567 bool PredHasWeights =
2568 PBI->extractProfMetadata(PredTrueWeight, PredFalseWeight);
2569 bool SuccHasWeights =
2570 BI->extractProfMetadata(SuccTrueWeight, SuccFalseWeight);
2571 if (PredHasWeights || SuccHasWeights) {
2572 if (!PredHasWeights)
2573 PredTrueWeight = PredFalseWeight = 1;
2574 if (!SuccHasWeights)
2575 SuccTrueWeight = SuccFalseWeight = 1;
2576 return true;
2577 } else {
2578 return false;
2582 /// If this basic block is simple enough, and if a predecessor branches to us
2583 /// and one of our successors, fold the block into the predecessor and use
2584 /// logical operations to pick the right destination.
2585 bool llvm::FoldBranchToCommonDest(BranchInst *BI, MemorySSAUpdater *MSSAU,
2586 unsigned BonusInstThreshold) {
2587 BasicBlock *BB = BI->getParent();
2589 const unsigned PredCount = pred_size(BB);
2591 Instruction *Cond = nullptr;
2592 if (BI->isConditional())
2593 Cond = dyn_cast<Instruction>(BI->getCondition());
2594 else {
2595 // For unconditional branch, check for a simple CFG pattern, where
2596 // BB has a single predecessor and BB's successor is also its predecessor's
2597 // successor. If such pattern exists, check for CSE between BB and its
2598 // predecessor.
2599 if (BasicBlock *PB = BB->getSinglePredecessor())
2600 if (BranchInst *PBI = dyn_cast<BranchInst>(PB->getTerminator()))
2601 if (PBI->isConditional() &&
2602 (BI->getSuccessor(0) == PBI->getSuccessor(0) ||
2603 BI->getSuccessor(0) == PBI->getSuccessor(1))) {
2604 for (auto I = BB->instructionsWithoutDebug().begin(),
2605 E = BB->instructionsWithoutDebug().end();
2606 I != E;) {
2607 Instruction *Curr = &*I++;
2608 if (isa<CmpInst>(Curr)) {
2609 Cond = Curr;
2610 break;
2612 // Quit if we can't remove this instruction.
2613 if (!tryCSEWithPredecessor(Curr, PB))
2614 return false;
2618 if (!Cond)
2619 return false;
2622 if (!Cond || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) ||
2623 Cond->getParent() != BB || !Cond->hasOneUse())
2624 return false;
2626 // Make sure the instruction after the condition is the cond branch.
2627 BasicBlock::iterator CondIt = ++Cond->getIterator();
2629 // Ignore dbg intrinsics.
2630 while (isa<DbgInfoIntrinsic>(CondIt))
2631 ++CondIt;
2633 if (&*CondIt != BI)
2634 return false;
2636 // Only allow this transformation if computing the condition doesn't involve
2637 // too many instructions and these involved instructions can be executed
2638 // unconditionally. We denote all involved instructions except the condition
2639 // as "bonus instructions", and only allow this transformation when the
2640 // number of the bonus instructions we'll need to create when cloning into
2641 // each predecessor does not exceed a certain threshold.
2642 unsigned NumBonusInsts = 0;
2643 for (auto I = BB->begin(); Cond != &*I; ++I) {
2644 // Ignore dbg intrinsics.
2645 if (isa<DbgInfoIntrinsic>(I))
2646 continue;
2647 if (!I->hasOneUse() || !isSafeToSpeculativelyExecute(&*I))
2648 return false;
2649 // I has only one use and can be executed unconditionally.
2650 Instruction *User = dyn_cast<Instruction>(I->user_back());
2651 if (User == nullptr || User->getParent() != BB)
2652 return false;
2653 // I is used in the same BB. Since BI uses Cond and doesn't have more slots
2654 // to use any other instruction, User must be an instruction between next(I)
2655 // and Cond.
2657 // Account for the cost of duplicating this instruction into each
2658 // predecessor.
2659 NumBonusInsts += PredCount;
2660 // Early exits once we reach the limit.
2661 if (NumBonusInsts > BonusInstThreshold)
2662 return false;
2665 // Cond is known to be a compare or binary operator. Check to make sure that
2666 // neither operand is a potentially-trapping constant expression.
2667 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0)))
2668 if (CE->canTrap())
2669 return false;
2670 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1)))
2671 if (CE->canTrap())
2672 return false;
2674 // Finally, don't infinitely unroll conditional loops.
2675 BasicBlock *TrueDest = BI->getSuccessor(0);
2676 BasicBlock *FalseDest = (BI->isConditional()) ? BI->getSuccessor(1) : nullptr;
2677 if (TrueDest == BB || FalseDest == BB)
2678 return false;
2680 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
2681 BasicBlock *PredBlock = *PI;
2682 BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
2684 // Check that we have two conditional branches. If there is a PHI node in
2685 // the common successor, verify that the same value flows in from both
2686 // blocks.
2687 SmallVector<PHINode *, 4> PHIs;
2688 if (!PBI || PBI->isUnconditional() ||
2689 (BI->isConditional() && !SafeToMergeTerminators(BI, PBI)) ||
2690 (!BI->isConditional() &&
2691 !isProfitableToFoldUnconditional(BI, PBI, Cond, PHIs)))
2692 continue;
2694 // Determine if the two branches share a common destination.
2695 Instruction::BinaryOps Opc = Instruction::BinaryOpsEnd;
2696 bool InvertPredCond = false;
2698 if (BI->isConditional()) {
2699 if (PBI->getSuccessor(0) == TrueDest) {
2700 Opc = Instruction::Or;
2701 } else if (PBI->getSuccessor(1) == FalseDest) {
2702 Opc = Instruction::And;
2703 } else if (PBI->getSuccessor(0) == FalseDest) {
2704 Opc = Instruction::And;
2705 InvertPredCond = true;
2706 } else if (PBI->getSuccessor(1) == TrueDest) {
2707 Opc = Instruction::Or;
2708 InvertPredCond = true;
2709 } else {
2710 continue;
2712 } else {
2713 if (PBI->getSuccessor(0) != TrueDest && PBI->getSuccessor(1) != TrueDest)
2714 continue;
2717 LLVM_DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
2718 IRBuilder<> Builder(PBI);
2720 // If we need to invert the condition in the pred block to match, do so now.
2721 if (InvertPredCond) {
2722 Value *NewCond = PBI->getCondition();
2724 if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
2725 CmpInst *CI = cast<CmpInst>(NewCond);
2726 CI->setPredicate(CI->getInversePredicate());
2727 } else {
2728 NewCond =
2729 Builder.CreateNot(NewCond, PBI->getCondition()->getName() + ".not");
2732 PBI->setCondition(NewCond);
2733 PBI->swapSuccessors();
2736 // If we have bonus instructions, clone them into the predecessor block.
2737 // Note that there may be multiple predecessor blocks, so we cannot move
2738 // bonus instructions to a predecessor block.
2739 ValueToValueMapTy VMap; // maps original values to cloned values
2740 // We already make sure Cond is the last instruction before BI. Therefore,
2741 // all instructions before Cond other than DbgInfoIntrinsic are bonus
2742 // instructions.
2743 for (auto BonusInst = BB->begin(); Cond != &*BonusInst; ++BonusInst) {
2744 if (isa<DbgInfoIntrinsic>(BonusInst))
2745 continue;
2746 Instruction *NewBonusInst = BonusInst->clone();
2747 RemapInstruction(NewBonusInst, VMap,
2748 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
2749 VMap[&*BonusInst] = NewBonusInst;
2751 // If we moved a load, we cannot any longer claim any knowledge about
2752 // its potential value. The previous information might have been valid
2753 // only given the branch precondition.
2754 // For an analogous reason, we must also drop all the metadata whose
2755 // semantics we don't understand.
2756 NewBonusInst->dropUnknownNonDebugMetadata();
2758 PredBlock->getInstList().insert(PBI->getIterator(), NewBonusInst);
2759 NewBonusInst->takeName(&*BonusInst);
2760 BonusInst->setName(BonusInst->getName() + ".old");
2763 // Clone Cond into the predecessor basic block, and or/and the
2764 // two conditions together.
2765 Instruction *CondInPred = Cond->clone();
2766 RemapInstruction(CondInPred, VMap,
2767 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
2768 PredBlock->getInstList().insert(PBI->getIterator(), CondInPred);
2769 CondInPred->takeName(Cond);
2770 Cond->setName(CondInPred->getName() + ".old");
2772 if (BI->isConditional()) {
2773 Instruction *NewCond = cast<Instruction>(
2774 Builder.CreateBinOp(Opc, PBI->getCondition(), CondInPred, "or.cond"));
2775 PBI->setCondition(NewCond);
2777 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
2778 bool HasWeights =
2779 extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight,
2780 SuccTrueWeight, SuccFalseWeight);
2781 SmallVector<uint64_t, 8> NewWeights;
2783 if (PBI->getSuccessor(0) == BB) {
2784 if (HasWeights) {
2785 // PBI: br i1 %x, BB, FalseDest
2786 // BI: br i1 %y, TrueDest, FalseDest
2787 // TrueWeight is TrueWeight for PBI * TrueWeight for BI.
2788 NewWeights.push_back(PredTrueWeight * SuccTrueWeight);
2789 // FalseWeight is FalseWeight for PBI * TotalWeight for BI +
2790 // TrueWeight for PBI * FalseWeight for BI.
2791 // We assume that total weights of a BranchInst can fit into 32 bits.
2792 // Therefore, we will not have overflow using 64-bit arithmetic.
2793 NewWeights.push_back(PredFalseWeight *
2794 (SuccFalseWeight + SuccTrueWeight) +
2795 PredTrueWeight * SuccFalseWeight);
2797 AddPredecessorToBlock(TrueDest, PredBlock, BB, MSSAU);
2798 PBI->setSuccessor(0, TrueDest);
2800 if (PBI->getSuccessor(1) == BB) {
2801 if (HasWeights) {
2802 // PBI: br i1 %x, TrueDest, BB
2803 // BI: br i1 %y, TrueDest, FalseDest
2804 // TrueWeight is TrueWeight for PBI * TotalWeight for BI +
2805 // FalseWeight for PBI * TrueWeight for BI.
2806 NewWeights.push_back(PredTrueWeight *
2807 (SuccFalseWeight + SuccTrueWeight) +
2808 PredFalseWeight * SuccTrueWeight);
2809 // FalseWeight is FalseWeight for PBI * FalseWeight for BI.
2810 NewWeights.push_back(PredFalseWeight * SuccFalseWeight);
2812 AddPredecessorToBlock(FalseDest, PredBlock, BB, MSSAU);
2813 PBI->setSuccessor(1, FalseDest);
2815 if (NewWeights.size() == 2) {
2816 // Halve the weights if any of them cannot fit in an uint32_t
2817 FitWeights(NewWeights);
2819 SmallVector<uint32_t, 8> MDWeights(NewWeights.begin(),
2820 NewWeights.end());
2821 setBranchWeights(PBI, MDWeights[0], MDWeights[1]);
2822 } else
2823 PBI->setMetadata(LLVMContext::MD_prof, nullptr);
2824 } else {
2825 // Update PHI nodes in the common successors.
2826 for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
2827 ConstantInt *PBI_C = cast<ConstantInt>(
2828 PHIs[i]->getIncomingValueForBlock(PBI->getParent()));
2829 assert(PBI_C->getType()->isIntegerTy(1));
2830 Instruction *MergedCond = nullptr;
2831 if (PBI->getSuccessor(0) == TrueDest) {
2832 // Create (PBI_Cond and PBI_C) or (!PBI_Cond and BI_Value)
2833 // PBI_C is true: PBI_Cond or (!PBI_Cond and BI_Value)
2834 // is false: !PBI_Cond and BI_Value
2835 Instruction *NotCond = cast<Instruction>(
2836 Builder.CreateNot(PBI->getCondition(), "not.cond"));
2837 MergedCond = cast<Instruction>(
2838 Builder.CreateBinOp(Instruction::And, NotCond, CondInPred,
2839 "and.cond"));
2840 if (PBI_C->isOne())
2841 MergedCond = cast<Instruction>(Builder.CreateBinOp(
2842 Instruction::Or, PBI->getCondition(), MergedCond, "or.cond"));
2843 } else {
2844 // Create (PBI_Cond and BI_Value) or (!PBI_Cond and PBI_C)
2845 // PBI_C is true: (PBI_Cond and BI_Value) or (!PBI_Cond)
2846 // is false: PBI_Cond and BI_Value
2847 MergedCond = cast<Instruction>(Builder.CreateBinOp(
2848 Instruction::And, PBI->getCondition(), CondInPred, "and.cond"));
2849 if (PBI_C->isOne()) {
2850 Instruction *NotCond = cast<Instruction>(
2851 Builder.CreateNot(PBI->getCondition(), "not.cond"));
2852 MergedCond = cast<Instruction>(Builder.CreateBinOp(
2853 Instruction::Or, NotCond, MergedCond, "or.cond"));
2856 // Update PHI Node.
2857 PHIs[i]->setIncomingValueForBlock(PBI->getParent(), MergedCond);
2860 // PBI is changed to branch to TrueDest below. Remove itself from
2861 // potential phis from all other successors.
2862 if (MSSAU)
2863 MSSAU->changeCondBranchToUnconditionalTo(PBI, TrueDest);
2865 // Change PBI from Conditional to Unconditional.
2866 BranchInst *New_PBI = BranchInst::Create(TrueDest, PBI);
2867 EraseTerminatorAndDCECond(PBI, MSSAU);
2868 PBI = New_PBI;
2871 // If BI was a loop latch, it may have had associated loop metadata.
2872 // We need to copy it to the new latch, that is, PBI.
2873 if (MDNode *LoopMD = BI->getMetadata(LLVMContext::MD_loop))
2874 PBI->setMetadata(LLVMContext::MD_loop, LoopMD);
2876 // TODO: If BB is reachable from all paths through PredBlock, then we
2877 // could replace PBI's branch probabilities with BI's.
2879 // Copy any debug value intrinsics into the end of PredBlock.
2880 for (Instruction &I : *BB)
2881 if (isa<DbgInfoIntrinsic>(I))
2882 I.clone()->insertBefore(PBI);
2884 return true;
2886 return false;
2889 // If there is only one store in BB1 and BB2, return it, otherwise return
2890 // nullptr.
2891 static StoreInst *findUniqueStoreInBlocks(BasicBlock *BB1, BasicBlock *BB2) {
2892 StoreInst *S = nullptr;
2893 for (auto *BB : {BB1, BB2}) {
2894 if (!BB)
2895 continue;
2896 for (auto &I : *BB)
2897 if (auto *SI = dyn_cast<StoreInst>(&I)) {
2898 if (S)
2899 // Multiple stores seen.
2900 return nullptr;
2901 else
2902 S = SI;
2905 return S;
2908 static Value *ensureValueAvailableInSuccessor(Value *V, BasicBlock *BB,
2909 Value *AlternativeV = nullptr) {
2910 // PHI is going to be a PHI node that allows the value V that is defined in
2911 // BB to be referenced in BB's only successor.
2913 // If AlternativeV is nullptr, the only value we care about in PHI is V. It
2914 // doesn't matter to us what the other operand is (it'll never get used). We
2915 // could just create a new PHI with an undef incoming value, but that could
2916 // increase register pressure if EarlyCSE/InstCombine can't fold it with some
2917 // other PHI. So here we directly look for some PHI in BB's successor with V
2918 // as an incoming operand. If we find one, we use it, else we create a new
2919 // one.
2921 // If AlternativeV is not nullptr, we care about both incoming values in PHI.
2922 // PHI must be exactly: phi <ty> [ %BB, %V ], [ %OtherBB, %AlternativeV]
2923 // where OtherBB is the single other predecessor of BB's only successor.
2924 PHINode *PHI = nullptr;
2925 BasicBlock *Succ = BB->getSingleSuccessor();
2927 for (auto I = Succ->begin(); isa<PHINode>(I); ++I)
2928 if (cast<PHINode>(I)->getIncomingValueForBlock(BB) == V) {
2929 PHI = cast<PHINode>(I);
2930 if (!AlternativeV)
2931 break;
2933 assert(Succ->hasNPredecessors(2));
2934 auto PredI = pred_begin(Succ);
2935 BasicBlock *OtherPredBB = *PredI == BB ? *++PredI : *PredI;
2936 if (PHI->getIncomingValueForBlock(OtherPredBB) == AlternativeV)
2937 break;
2938 PHI = nullptr;
2940 if (PHI)
2941 return PHI;
2943 // If V is not an instruction defined in BB, just return it.
2944 if (!AlternativeV &&
2945 (!isa<Instruction>(V) || cast<Instruction>(V)->getParent() != BB))
2946 return V;
2948 PHI = PHINode::Create(V->getType(), 2, "simplifycfg.merge", &Succ->front());
2949 PHI->addIncoming(V, BB);
2950 for (BasicBlock *PredBB : predecessors(Succ))
2951 if (PredBB != BB)
2952 PHI->addIncoming(
2953 AlternativeV ? AlternativeV : UndefValue::get(V->getType()), PredBB);
2954 return PHI;
2957 static bool mergeConditionalStoreToAddress(BasicBlock *PTB, BasicBlock *PFB,
2958 BasicBlock *QTB, BasicBlock *QFB,
2959 BasicBlock *PostBB, Value *Address,
2960 bool InvertPCond, bool InvertQCond,
2961 const DataLayout &DL,
2962 const TargetTransformInfo &TTI) {
2963 // For every pointer, there must be exactly two stores, one coming from
2964 // PTB or PFB, and the other from QTB or QFB. We don't support more than one
2965 // store (to any address) in PTB,PFB or QTB,QFB.
2966 // FIXME: We could relax this restriction with a bit more work and performance
2967 // testing.
2968 StoreInst *PStore = findUniqueStoreInBlocks(PTB, PFB);
2969 StoreInst *QStore = findUniqueStoreInBlocks(QTB, QFB);
2970 if (!PStore || !QStore)
2971 return false;
2973 // Now check the stores are compatible.
2974 if (!QStore->isUnordered() || !PStore->isUnordered())
2975 return false;
2977 // Check that sinking the store won't cause program behavior changes. Sinking
2978 // the store out of the Q blocks won't change any behavior as we're sinking
2979 // from a block to its unconditional successor. But we're moving a store from
2980 // the P blocks down through the middle block (QBI) and past both QFB and QTB.
2981 // So we need to check that there are no aliasing loads or stores in
2982 // QBI, QTB and QFB. We also need to check there are no conflicting memory
2983 // operations between PStore and the end of its parent block.
2985 // The ideal way to do this is to query AliasAnalysis, but we don't
2986 // preserve AA currently so that is dangerous. Be super safe and just
2987 // check there are no other memory operations at all.
2988 for (auto &I : *QFB->getSinglePredecessor())
2989 if (I.mayReadOrWriteMemory())
2990 return false;
2991 for (auto &I : *QFB)
2992 if (&I != QStore && I.mayReadOrWriteMemory())
2993 return false;
2994 if (QTB)
2995 for (auto &I : *QTB)
2996 if (&I != QStore && I.mayReadOrWriteMemory())
2997 return false;
2998 for (auto I = BasicBlock::iterator(PStore), E = PStore->getParent()->end();
2999 I != E; ++I)
3000 if (&*I != PStore && I->mayReadOrWriteMemory())
3001 return false;
3003 // If we're not in aggressive mode, we only optimize if we have some
3004 // confidence that by optimizing we'll allow P and/or Q to be if-converted.
3005 auto IsWorthwhile = [&](BasicBlock *BB, ArrayRef<StoreInst *> FreeStores) {
3006 if (!BB)
3007 return true;
3008 // Heuristic: if the block can be if-converted/phi-folded and the
3009 // instructions inside are all cheap (arithmetic/GEPs), it's worthwhile to
3010 // thread this store.
3011 int BudgetRemaining =
3012 PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic;
3013 for (auto &I : BB->instructionsWithoutDebug()) {
3014 // Consider terminator instruction to be free.
3015 if (I.isTerminator())
3016 continue;
3017 // If this is one the stores that we want to speculate out of this BB,
3018 // then don't count it's cost, consider it to be free.
3019 if (auto *S = dyn_cast<StoreInst>(&I))
3020 if (llvm::find(FreeStores, S))
3021 continue;
3022 // Else, we have a white-list of instructions that we are ak speculating.
3023 if (!isa<BinaryOperator>(I) && !isa<GetElementPtrInst>(I))
3024 return false; // Not in white-list - not worthwhile folding.
3025 // And finally, if this is a non-free instruction that we are okay
3026 // speculating, ensure that we consider the speculation budget.
3027 BudgetRemaining -= TTI.getUserCost(&I);
3028 if (BudgetRemaining < 0)
3029 return false; // Eagerly refuse to fold as soon as we're out of budget.
3031 assert(BudgetRemaining >= 0 &&
3032 "When we run out of budget we will eagerly return from within the "
3033 "per-instruction loop.");
3034 return true;
3037 const SmallVector<StoreInst *, 2> FreeStores = {PStore, QStore};
3038 if (!MergeCondStoresAggressively &&
3039 (!IsWorthwhile(PTB, FreeStores) || !IsWorthwhile(PFB, FreeStores) ||
3040 !IsWorthwhile(QTB, FreeStores) || !IsWorthwhile(QFB, FreeStores)))
3041 return false;
3043 // If PostBB has more than two predecessors, we need to split it so we can
3044 // sink the store.
3045 if (std::next(pred_begin(PostBB), 2) != pred_end(PostBB)) {
3046 // We know that QFB's only successor is PostBB. And QFB has a single
3047 // predecessor. If QTB exists, then its only successor is also PostBB.
3048 // If QTB does not exist, then QFB's only predecessor has a conditional
3049 // branch to QFB and PostBB.
3050 BasicBlock *TruePred = QTB ? QTB : QFB->getSinglePredecessor();
3051 BasicBlock *NewBB = SplitBlockPredecessors(PostBB, { QFB, TruePred},
3052 "condstore.split");
3053 if (!NewBB)
3054 return false;
3055 PostBB = NewBB;
3058 // OK, we're going to sink the stores to PostBB. The store has to be
3059 // conditional though, so first create the predicate.
3060 Value *PCond = cast<BranchInst>(PFB->getSinglePredecessor()->getTerminator())
3061 ->getCondition();
3062 Value *QCond = cast<BranchInst>(QFB->getSinglePredecessor()->getTerminator())
3063 ->getCondition();
3065 Value *PPHI = ensureValueAvailableInSuccessor(PStore->getValueOperand(),
3066 PStore->getParent());
3067 Value *QPHI = ensureValueAvailableInSuccessor(QStore->getValueOperand(),
3068 QStore->getParent(), PPHI);
3070 IRBuilder<> QB(&*PostBB->getFirstInsertionPt());
3072 Value *PPred = PStore->getParent() == PTB ? PCond : QB.CreateNot(PCond);
3073 Value *QPred = QStore->getParent() == QTB ? QCond : QB.CreateNot(QCond);
3075 if (InvertPCond)
3076 PPred = QB.CreateNot(PPred);
3077 if (InvertQCond)
3078 QPred = QB.CreateNot(QPred);
3079 Value *CombinedPred = QB.CreateOr(PPred, QPred);
3081 auto *T =
3082 SplitBlockAndInsertIfThen(CombinedPred, &*QB.GetInsertPoint(), false);
3083 QB.SetInsertPoint(T);
3084 StoreInst *SI = cast<StoreInst>(QB.CreateStore(QPHI, Address));
3085 AAMDNodes AAMD;
3086 PStore->getAAMetadata(AAMD, /*Merge=*/false);
3087 PStore->getAAMetadata(AAMD, /*Merge=*/true);
3088 SI->setAAMetadata(AAMD);
3089 unsigned PAlignment = PStore->getAlignment();
3090 unsigned QAlignment = QStore->getAlignment();
3091 unsigned TypeAlignment =
3092 DL.getABITypeAlignment(SI->getValueOperand()->getType());
3093 unsigned MinAlignment;
3094 unsigned MaxAlignment;
3095 std::tie(MinAlignment, MaxAlignment) = std::minmax(PAlignment, QAlignment);
3096 // Choose the minimum alignment. If we could prove both stores execute, we
3097 // could use biggest one. In this case, though, we only know that one of the
3098 // stores executes. And we don't know it's safe to take the alignment from a
3099 // store that doesn't execute.
3100 if (MinAlignment != 0) {
3101 // Choose the minimum of all non-zero alignments.
3102 SI->setAlignment(Align(MinAlignment));
3103 } else if (MaxAlignment != 0) {
3104 // Choose the minimal alignment between the non-zero alignment and the ABI
3105 // default alignment for the type of the stored value.
3106 SI->setAlignment(Align(std::min(MaxAlignment, TypeAlignment)));
3107 } else {
3108 // If both alignments are zero, use ABI default alignment for the type of
3109 // the stored value.
3110 SI->setAlignment(Align(TypeAlignment));
3113 QStore->eraseFromParent();
3114 PStore->eraseFromParent();
3116 return true;
3119 static bool mergeConditionalStores(BranchInst *PBI, BranchInst *QBI,
3120 const DataLayout &DL,
3121 const TargetTransformInfo &TTI) {
3122 // The intention here is to find diamonds or triangles (see below) where each
3123 // conditional block contains a store to the same address. Both of these
3124 // stores are conditional, so they can't be unconditionally sunk. But it may
3125 // be profitable to speculatively sink the stores into one merged store at the
3126 // end, and predicate the merged store on the union of the two conditions of
3127 // PBI and QBI.
3129 // This can reduce the number of stores executed if both of the conditions are
3130 // true, and can allow the blocks to become small enough to be if-converted.
3131 // This optimization will also chain, so that ladders of test-and-set
3132 // sequences can be if-converted away.
3134 // We only deal with simple diamonds or triangles:
3136 // PBI or PBI or a combination of the two
3137 // / \ | \
3138 // PTB PFB | PFB
3139 // \ / | /
3140 // QBI QBI
3141 // / \ | \
3142 // QTB QFB | QFB
3143 // \ / | /
3144 // PostBB PostBB
3146 // We model triangles as a type of diamond with a nullptr "true" block.
3147 // Triangles are canonicalized so that the fallthrough edge is represented by
3148 // a true condition, as in the diagram above.
3149 BasicBlock *PTB = PBI->getSuccessor(0);
3150 BasicBlock *PFB = PBI->getSuccessor(1);
3151 BasicBlock *QTB = QBI->getSuccessor(0);
3152 BasicBlock *QFB = QBI->getSuccessor(1);
3153 BasicBlock *PostBB = QFB->getSingleSuccessor();
3155 // Make sure we have a good guess for PostBB. If QTB's only successor is
3156 // QFB, then QFB is a better PostBB.
3157 if (QTB->getSingleSuccessor() == QFB)
3158 PostBB = QFB;
3160 // If we couldn't find a good PostBB, stop.
3161 if (!PostBB)
3162 return false;
3164 bool InvertPCond = false, InvertQCond = false;
3165 // Canonicalize fallthroughs to the true branches.
3166 if (PFB == QBI->getParent()) {
3167 std::swap(PFB, PTB);
3168 InvertPCond = true;
3170 if (QFB == PostBB) {
3171 std::swap(QFB, QTB);
3172 InvertQCond = true;
3175 // From this point on we can assume PTB or QTB may be fallthroughs but PFB
3176 // and QFB may not. Model fallthroughs as a nullptr block.
3177 if (PTB == QBI->getParent())
3178 PTB = nullptr;
3179 if (QTB == PostBB)
3180 QTB = nullptr;
3182 // Legality bailouts. We must have at least the non-fallthrough blocks and
3183 // the post-dominating block, and the non-fallthroughs must only have one
3184 // predecessor.
3185 auto HasOnePredAndOneSucc = [](BasicBlock *BB, BasicBlock *P, BasicBlock *S) {
3186 return BB->getSinglePredecessor() == P && BB->getSingleSuccessor() == S;
3188 if (!HasOnePredAndOneSucc(PFB, PBI->getParent(), QBI->getParent()) ||
3189 !HasOnePredAndOneSucc(QFB, QBI->getParent(), PostBB))
3190 return false;
3191 if ((PTB && !HasOnePredAndOneSucc(PTB, PBI->getParent(), QBI->getParent())) ||
3192 (QTB && !HasOnePredAndOneSucc(QTB, QBI->getParent(), PostBB)))
3193 return false;
3194 if (!QBI->getParent()->hasNUses(2))
3195 return false;
3197 // OK, this is a sequence of two diamonds or triangles.
3198 // Check if there are stores in PTB or PFB that are repeated in QTB or QFB.
3199 SmallPtrSet<Value *, 4> PStoreAddresses, QStoreAddresses;
3200 for (auto *BB : {PTB, PFB}) {
3201 if (!BB)
3202 continue;
3203 for (auto &I : *BB)
3204 if (StoreInst *SI = dyn_cast<StoreInst>(&I))
3205 PStoreAddresses.insert(SI->getPointerOperand());
3207 for (auto *BB : {QTB, QFB}) {
3208 if (!BB)
3209 continue;
3210 for (auto &I : *BB)
3211 if (StoreInst *SI = dyn_cast<StoreInst>(&I))
3212 QStoreAddresses.insert(SI->getPointerOperand());
3215 set_intersect(PStoreAddresses, QStoreAddresses);
3216 // set_intersect mutates PStoreAddresses in place. Rename it here to make it
3217 // clear what it contains.
3218 auto &CommonAddresses = PStoreAddresses;
3220 bool Changed = false;
3221 for (auto *Address : CommonAddresses)
3222 Changed |= mergeConditionalStoreToAddress(
3223 PTB, PFB, QTB, QFB, PostBB, Address, InvertPCond, InvertQCond, DL, TTI);
3224 return Changed;
3228 /// If the previous block ended with a widenable branch, determine if reusing
3229 /// the target block is profitable and legal. This will have the effect of
3230 /// "widening" PBI, but doesn't require us to reason about hosting safety.
3231 static bool tryWidenCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI) {
3232 // TODO: This can be generalized in two important ways:
3233 // 1) We can allow phi nodes in IfFalseBB and simply reuse all the input
3234 // values from the PBI edge.
3235 // 2) We can sink side effecting instructions into BI's fallthrough
3236 // successor provided they doesn't contribute to computation of
3237 // BI's condition.
3238 Value *CondWB, *WC;
3239 BasicBlock *IfTrueBB, *IfFalseBB;
3240 if (!parseWidenableBranch(PBI, CondWB, WC, IfTrueBB, IfFalseBB) ||
3241 IfTrueBB != BI->getParent() || !BI->getParent()->getSinglePredecessor())
3242 return false;
3243 if (!IfFalseBB->phis().empty())
3244 return false; // TODO
3245 // Use lambda to lazily compute expensive condition after cheap ones.
3246 auto NoSideEffects = [](BasicBlock &BB) {
3247 return !llvm::any_of(BB, [](const Instruction &I) {
3248 return I.mayWriteToMemory() || I.mayHaveSideEffects();
3251 if (BI->getSuccessor(1) != IfFalseBB && // no inf looping
3252 BI->getSuccessor(1)->getTerminatingDeoptimizeCall() && // profitability
3253 NoSideEffects(*BI->getParent())) {
3254 BI->getSuccessor(1)->removePredecessor(BI->getParent());
3255 BI->setSuccessor(1, IfFalseBB);
3256 return true;
3258 if (BI->getSuccessor(0) != IfFalseBB && // no inf looping
3259 BI->getSuccessor(0)->getTerminatingDeoptimizeCall() && // profitability
3260 NoSideEffects(*BI->getParent())) {
3261 BI->getSuccessor(0)->removePredecessor(BI->getParent());
3262 BI->setSuccessor(0, IfFalseBB);
3263 return true;
3265 return false;
3268 /// If we have a conditional branch as a predecessor of another block,
3269 /// this function tries to simplify it. We know
3270 /// that PBI and BI are both conditional branches, and BI is in one of the
3271 /// successor blocks of PBI - PBI branches to BI.
3272 static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI,
3273 const DataLayout &DL,
3274 const TargetTransformInfo &TTI) {
3275 assert(PBI->isConditional() && BI->isConditional());
3276 BasicBlock *BB = BI->getParent();
3278 // If this block ends with a branch instruction, and if there is a
3279 // predecessor that ends on a branch of the same condition, make
3280 // this conditional branch redundant.
3281 if (PBI->getCondition() == BI->getCondition() &&
3282 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
3283 // Okay, the outcome of this conditional branch is statically
3284 // knowable. If this block had a single pred, handle specially.
3285 if (BB->getSinglePredecessor()) {
3286 // Turn this into a branch on constant.
3287 bool CondIsTrue = PBI->getSuccessor(0) == BB;
3288 BI->setCondition(
3289 ConstantInt::get(Type::getInt1Ty(BB->getContext()), CondIsTrue));
3290 return true; // Nuke the branch on constant.
3293 // Otherwise, if there are multiple predecessors, insert a PHI that merges
3294 // in the constant and simplify the block result. Subsequent passes of
3295 // simplifycfg will thread the block.
3296 if (BlockIsSimpleEnoughToThreadThrough(BB)) {
3297 pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
3298 PHINode *NewPN = PHINode::Create(
3299 Type::getInt1Ty(BB->getContext()), std::distance(PB, PE),
3300 BI->getCondition()->getName() + ".pr", &BB->front());
3301 // Okay, we're going to insert the PHI node. Since PBI is not the only
3302 // predecessor, compute the PHI'd conditional value for all of the preds.
3303 // Any predecessor where the condition is not computable we keep symbolic.
3304 for (pred_iterator PI = PB; PI != PE; ++PI) {
3305 BasicBlock *P = *PI;
3306 if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) && PBI != BI &&
3307 PBI->isConditional() && PBI->getCondition() == BI->getCondition() &&
3308 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
3309 bool CondIsTrue = PBI->getSuccessor(0) == BB;
3310 NewPN->addIncoming(
3311 ConstantInt::get(Type::getInt1Ty(BB->getContext()), CondIsTrue),
3313 } else {
3314 NewPN->addIncoming(BI->getCondition(), P);
3318 BI->setCondition(NewPN);
3319 return true;
3323 // If the previous block ended with a widenable branch, determine if reusing
3324 // the target block is profitable and legal. This will have the effect of
3325 // "widening" PBI, but doesn't require us to reason about hosting safety.
3326 if (tryWidenCondBranchToCondBranch(PBI, BI))
3327 return true;
3329 if (auto *CE = dyn_cast<ConstantExpr>(BI->getCondition()))
3330 if (CE->canTrap())
3331 return false;
3333 // If both branches are conditional and both contain stores to the same
3334 // address, remove the stores from the conditionals and create a conditional
3335 // merged store at the end.
3336 if (MergeCondStores && mergeConditionalStores(PBI, BI, DL, TTI))
3337 return true;
3339 // If this is a conditional branch in an empty block, and if any
3340 // predecessors are a conditional branch to one of our destinations,
3341 // fold the conditions into logical ops and one cond br.
3343 // Ignore dbg intrinsics.
3344 if (&*BB->instructionsWithoutDebug().begin() != BI)
3345 return false;
3347 int PBIOp, BIOp;
3348 if (PBI->getSuccessor(0) == BI->getSuccessor(0)) {
3349 PBIOp = 0;
3350 BIOp = 0;
3351 } else if (PBI->getSuccessor(0) == BI->getSuccessor(1)) {
3352 PBIOp = 0;
3353 BIOp = 1;
3354 } else if (PBI->getSuccessor(1) == BI->getSuccessor(0)) {
3355 PBIOp = 1;
3356 BIOp = 0;
3357 } else if (PBI->getSuccessor(1) == BI->getSuccessor(1)) {
3358 PBIOp = 1;
3359 BIOp = 1;
3360 } else {
3361 return false;
3364 // Check to make sure that the other destination of this branch
3365 // isn't BB itself. If so, this is an infinite loop that will
3366 // keep getting unwound.
3367 if (PBI->getSuccessor(PBIOp) == BB)
3368 return false;
3370 // Do not perform this transformation if it would require
3371 // insertion of a large number of select instructions. For targets
3372 // without predication/cmovs, this is a big pessimization.
3374 // Also do not perform this transformation if any phi node in the common
3375 // destination block can trap when reached by BB or PBB (PR17073). In that
3376 // case, it would be unsafe to hoist the operation into a select instruction.
3378 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
3379 unsigned NumPhis = 0;
3380 for (BasicBlock::iterator II = CommonDest->begin(); isa<PHINode>(II);
3381 ++II, ++NumPhis) {
3382 if (NumPhis > 2) // Disable this xform.
3383 return false;
3385 PHINode *PN = cast<PHINode>(II);
3386 Value *BIV = PN->getIncomingValueForBlock(BB);
3387 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BIV))
3388 if (CE->canTrap())
3389 return false;
3391 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
3392 Value *PBIV = PN->getIncomingValue(PBBIdx);
3393 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PBIV))
3394 if (CE->canTrap())
3395 return false;
3398 // Finally, if everything is ok, fold the branches to logical ops.
3399 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
3401 LLVM_DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
3402 << "AND: " << *BI->getParent());
3404 // If OtherDest *is* BB, then BB is a basic block with a single conditional
3405 // branch in it, where one edge (OtherDest) goes back to itself but the other
3406 // exits. We don't *know* that the program avoids the infinite loop
3407 // (even though that seems likely). If we do this xform naively, we'll end up
3408 // recursively unpeeling the loop. Since we know that (after the xform is
3409 // done) that the block *is* infinite if reached, we just make it an obviously
3410 // infinite loop with no cond branch.
3411 if (OtherDest == BB) {
3412 // Insert it at the end of the function, because it's either code,
3413 // or it won't matter if it's hot. :)
3414 BasicBlock *InfLoopBlock =
3415 BasicBlock::Create(BB->getContext(), "infloop", BB->getParent());
3416 BranchInst::Create(InfLoopBlock, InfLoopBlock);
3417 OtherDest = InfLoopBlock;
3420 LLVM_DEBUG(dbgs() << *PBI->getParent()->getParent());
3422 // BI may have other predecessors. Because of this, we leave
3423 // it alone, but modify PBI.
3425 // Make sure we get to CommonDest on True&True directions.
3426 Value *PBICond = PBI->getCondition();
3427 IRBuilder<NoFolder> Builder(PBI);
3428 if (PBIOp)
3429 PBICond = Builder.CreateNot(PBICond, PBICond->getName() + ".not");
3431 Value *BICond = BI->getCondition();
3432 if (BIOp)
3433 BICond = Builder.CreateNot(BICond, BICond->getName() + ".not");
3435 // Merge the conditions.
3436 Value *Cond = Builder.CreateOr(PBICond, BICond, "brmerge");
3438 // Modify PBI to branch on the new condition to the new dests.
3439 PBI->setCondition(Cond);
3440 PBI->setSuccessor(0, CommonDest);
3441 PBI->setSuccessor(1, OtherDest);
3443 // Update branch weight for PBI.
3444 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
3445 uint64_t PredCommon, PredOther, SuccCommon, SuccOther;
3446 bool HasWeights =
3447 extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight,
3448 SuccTrueWeight, SuccFalseWeight);
3449 if (HasWeights) {
3450 PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
3451 PredOther = PBIOp ? PredTrueWeight : PredFalseWeight;
3452 SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
3453 SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
3454 // The weight to CommonDest should be PredCommon * SuccTotal +
3455 // PredOther * SuccCommon.
3456 // The weight to OtherDest should be PredOther * SuccOther.
3457 uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther) +
3458 PredOther * SuccCommon,
3459 PredOther * SuccOther};
3460 // Halve the weights if any of them cannot fit in an uint32_t
3461 FitWeights(NewWeights);
3463 setBranchWeights(PBI, NewWeights[0], NewWeights[1]);
3466 // OtherDest may have phi nodes. If so, add an entry from PBI's
3467 // block that are identical to the entries for BI's block.
3468 AddPredecessorToBlock(OtherDest, PBI->getParent(), BB);
3470 // We know that the CommonDest already had an edge from PBI to
3471 // it. If it has PHIs though, the PHIs may have different
3472 // entries for BB and PBI's BB. If so, insert a select to make
3473 // them agree.
3474 for (PHINode &PN : CommonDest->phis()) {
3475 Value *BIV = PN.getIncomingValueForBlock(BB);
3476 unsigned PBBIdx = PN.getBasicBlockIndex(PBI->getParent());
3477 Value *PBIV = PN.getIncomingValue(PBBIdx);
3478 if (BIV != PBIV) {
3479 // Insert a select in PBI to pick the right value.
3480 SelectInst *NV = cast<SelectInst>(
3481 Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName() + ".mux"));
3482 PN.setIncomingValue(PBBIdx, NV);
3483 // Although the select has the same condition as PBI, the original branch
3484 // weights for PBI do not apply to the new select because the select's
3485 // 'logical' edges are incoming edges of the phi that is eliminated, not
3486 // the outgoing edges of PBI.
3487 if (HasWeights) {
3488 uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
3489 uint64_t PredOther = PBIOp ? PredTrueWeight : PredFalseWeight;
3490 uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
3491 uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
3492 // The weight to PredCommonDest should be PredCommon * SuccTotal.
3493 // The weight to PredOtherDest should be PredOther * SuccCommon.
3494 uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther),
3495 PredOther * SuccCommon};
3497 FitWeights(NewWeights);
3499 setBranchWeights(NV, NewWeights[0], NewWeights[1]);
3504 LLVM_DEBUG(dbgs() << "INTO: " << *PBI->getParent());
3505 LLVM_DEBUG(dbgs() << *PBI->getParent()->getParent());
3507 // This basic block is probably dead. We know it has at least
3508 // one fewer predecessor.
3509 return true;
3512 // Simplifies a terminator by replacing it with a branch to TrueBB if Cond is
3513 // true or to FalseBB if Cond is false.
3514 // Takes care of updating the successors and removing the old terminator.
3515 // Also makes sure not to introduce new successors by assuming that edges to
3516 // non-successor TrueBBs and FalseBBs aren't reachable.
3517 static bool SimplifyTerminatorOnSelect(Instruction *OldTerm, Value *Cond,
3518 BasicBlock *TrueBB, BasicBlock *FalseBB,
3519 uint32_t TrueWeight,
3520 uint32_t FalseWeight) {
3521 // Remove any superfluous successor edges from the CFG.
3522 // First, figure out which successors to preserve.
3523 // If TrueBB and FalseBB are equal, only try to preserve one copy of that
3524 // successor.
3525 BasicBlock *KeepEdge1 = TrueBB;
3526 BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr;
3528 // Then remove the rest.
3529 for (BasicBlock *Succ : successors(OldTerm)) {
3530 // Make sure only to keep exactly one copy of each edge.
3531 if (Succ == KeepEdge1)
3532 KeepEdge1 = nullptr;
3533 else if (Succ == KeepEdge2)
3534 KeepEdge2 = nullptr;
3535 else
3536 Succ->removePredecessor(OldTerm->getParent(),
3537 /*KeepOneInputPHIs=*/true);
3540 IRBuilder<> Builder(OldTerm);
3541 Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc());
3543 // Insert an appropriate new terminator.
3544 if (!KeepEdge1 && !KeepEdge2) {
3545 if (TrueBB == FalseBB)
3546 // We were only looking for one successor, and it was present.
3547 // Create an unconditional branch to it.
3548 Builder.CreateBr(TrueBB);
3549 else {
3550 // We found both of the successors we were looking for.
3551 // Create a conditional branch sharing the condition of the select.
3552 BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB);
3553 if (TrueWeight != FalseWeight)
3554 setBranchWeights(NewBI, TrueWeight, FalseWeight);
3556 } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
3557 // Neither of the selected blocks were successors, so this
3558 // terminator must be unreachable.
3559 new UnreachableInst(OldTerm->getContext(), OldTerm);
3560 } else {
3561 // One of the selected values was a successor, but the other wasn't.
3562 // Insert an unconditional branch to the one that was found;
3563 // the edge to the one that wasn't must be unreachable.
3564 if (!KeepEdge1)
3565 // Only TrueBB was found.
3566 Builder.CreateBr(TrueBB);
3567 else
3568 // Only FalseBB was found.
3569 Builder.CreateBr(FalseBB);
3572 EraseTerminatorAndDCECond(OldTerm);
3573 return true;
3576 // Replaces
3577 // (switch (select cond, X, Y)) on constant X, Y
3578 // with a branch - conditional if X and Y lead to distinct BBs,
3579 // unconditional otherwise.
3580 static bool SimplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select) {
3581 // Check for constant integer values in the select.
3582 ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue());
3583 ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue());
3584 if (!TrueVal || !FalseVal)
3585 return false;
3587 // Find the relevant condition and destinations.
3588 Value *Condition = Select->getCondition();
3589 BasicBlock *TrueBB = SI->findCaseValue(TrueVal)->getCaseSuccessor();
3590 BasicBlock *FalseBB = SI->findCaseValue(FalseVal)->getCaseSuccessor();
3592 // Get weight for TrueBB and FalseBB.
3593 uint32_t TrueWeight = 0, FalseWeight = 0;
3594 SmallVector<uint64_t, 8> Weights;
3595 bool HasWeights = HasBranchWeights(SI);
3596 if (HasWeights) {
3597 GetBranchWeights(SI, Weights);
3598 if (Weights.size() == 1 + SI->getNumCases()) {
3599 TrueWeight =
3600 (uint32_t)Weights[SI->findCaseValue(TrueVal)->getSuccessorIndex()];
3601 FalseWeight =
3602 (uint32_t)Weights[SI->findCaseValue(FalseVal)->getSuccessorIndex()];
3606 // Perform the actual simplification.
3607 return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB, TrueWeight,
3608 FalseWeight);
3611 // Replaces
3612 // (indirectbr (select cond, blockaddress(@fn, BlockA),
3613 // blockaddress(@fn, BlockB)))
3614 // with
3615 // (br cond, BlockA, BlockB).
3616 static bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI) {
3617 // Check that both operands of the select are block addresses.
3618 BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
3619 BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
3620 if (!TBA || !FBA)
3621 return false;
3623 // Extract the actual blocks.
3624 BasicBlock *TrueBB = TBA->getBasicBlock();
3625 BasicBlock *FalseBB = FBA->getBasicBlock();
3627 // Perform the actual simplification.
3628 return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB, 0,
3632 /// This is called when we find an icmp instruction
3633 /// (a seteq/setne with a constant) as the only instruction in a
3634 /// block that ends with an uncond branch. We are looking for a very specific
3635 /// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In
3636 /// this case, we merge the first two "or's of icmp" into a switch, but then the
3637 /// default value goes to an uncond block with a seteq in it, we get something
3638 /// like:
3640 /// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ]
3641 /// DEFAULT:
3642 /// %tmp = icmp eq i8 %A, 92
3643 /// br label %end
3644 /// end:
3645 /// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
3647 /// We prefer to split the edge to 'end' so that there is a true/false entry to
3648 /// the PHI, merging the third icmp into the switch.
3649 bool SimplifyCFGOpt::tryToSimplifyUncondBranchWithICmpInIt(
3650 ICmpInst *ICI, IRBuilder<> &Builder) {
3651 BasicBlock *BB = ICI->getParent();
3653 // If the block has any PHIs in it or the icmp has multiple uses, it is too
3654 // complex.
3655 if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse())
3656 return false;
3658 Value *V = ICI->getOperand(0);
3659 ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1));
3661 // The pattern we're looking for is where our only predecessor is a switch on
3662 // 'V' and this block is the default case for the switch. In this case we can
3663 // fold the compared value into the switch to simplify things.
3664 BasicBlock *Pred = BB->getSinglePredecessor();
3665 if (!Pred || !isa<SwitchInst>(Pred->getTerminator()))
3666 return false;
3668 SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
3669 if (SI->getCondition() != V)
3670 return false;
3672 // If BB is reachable on a non-default case, then we simply know the value of
3673 // V in this block. Substitute it and constant fold the icmp instruction
3674 // away.
3675 if (SI->getDefaultDest() != BB) {
3676 ConstantInt *VVal = SI->findCaseDest(BB);
3677 assert(VVal && "Should have a unique destination value");
3678 ICI->setOperand(0, VVal);
3680 if (Value *V = SimplifyInstruction(ICI, {DL, ICI})) {
3681 ICI->replaceAllUsesWith(V);
3682 ICI->eraseFromParent();
3684 // BB is now empty, so it is likely to simplify away.
3685 return requestResimplify();
3688 // Ok, the block is reachable from the default dest. If the constant we're
3689 // comparing exists in one of the other edges, then we can constant fold ICI
3690 // and zap it.
3691 if (SI->findCaseValue(Cst) != SI->case_default()) {
3692 Value *V;
3693 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
3694 V = ConstantInt::getFalse(BB->getContext());
3695 else
3696 V = ConstantInt::getTrue(BB->getContext());
3698 ICI->replaceAllUsesWith(V);
3699 ICI->eraseFromParent();
3700 // BB is now empty, so it is likely to simplify away.
3701 return requestResimplify();
3704 // The use of the icmp has to be in the 'end' block, by the only PHI node in
3705 // the block.
3706 BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
3707 PHINode *PHIUse = dyn_cast<PHINode>(ICI->user_back());
3708 if (PHIUse == nullptr || PHIUse != &SuccBlock->front() ||
3709 isa<PHINode>(++BasicBlock::iterator(PHIUse)))
3710 return false;
3712 // If the icmp is a SETEQ, then the default dest gets false, the new edge gets
3713 // true in the PHI.
3714 Constant *DefaultCst = ConstantInt::getTrue(BB->getContext());
3715 Constant *NewCst = ConstantInt::getFalse(BB->getContext());
3717 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
3718 std::swap(DefaultCst, NewCst);
3720 // Replace ICI (which is used by the PHI for the default value) with true or
3721 // false depending on if it is EQ or NE.
3722 ICI->replaceAllUsesWith(DefaultCst);
3723 ICI->eraseFromParent();
3725 // Okay, the switch goes to this block on a default value. Add an edge from
3726 // the switch to the merge point on the compared value.
3727 BasicBlock *NewBB =
3728 BasicBlock::Create(BB->getContext(), "switch.edge", BB->getParent(), BB);
3730 SwitchInstProfUpdateWrapper SIW(*SI);
3731 auto W0 = SIW.getSuccessorWeight(0);
3732 SwitchInstProfUpdateWrapper::CaseWeightOpt NewW;
3733 if (W0) {
3734 NewW = ((uint64_t(*W0) + 1) >> 1);
3735 SIW.setSuccessorWeight(0, *NewW);
3737 SIW.addCase(Cst, NewBB, NewW);
3740 // NewBB branches to the phi block, add the uncond branch and the phi entry.
3741 Builder.SetInsertPoint(NewBB);
3742 Builder.SetCurrentDebugLocation(SI->getDebugLoc());
3743 Builder.CreateBr(SuccBlock);
3744 PHIUse->addIncoming(NewCst, NewBB);
3745 return true;
3748 /// The specified branch is a conditional branch.
3749 /// Check to see if it is branching on an or/and chain of icmp instructions, and
3750 /// fold it into a switch instruction if so.
3751 static bool SimplifyBranchOnICmpChain(BranchInst *BI, IRBuilder<> &Builder,
3752 const DataLayout &DL) {
3753 Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
3754 if (!Cond)
3755 return false;
3757 // Change br (X == 0 | X == 1), T, F into a switch instruction.
3758 // If this is a bunch of seteq's or'd together, or if it's a bunch of
3759 // 'setne's and'ed together, collect them.
3761 // Try to gather values from a chain of and/or to be turned into a switch
3762 ConstantComparesGatherer ConstantCompare(Cond, DL);
3763 // Unpack the result
3764 SmallVectorImpl<ConstantInt *> &Values = ConstantCompare.Vals;
3765 Value *CompVal = ConstantCompare.CompValue;
3766 unsigned UsedICmps = ConstantCompare.UsedICmps;
3767 Value *ExtraCase = ConstantCompare.Extra;
3769 // If we didn't have a multiply compared value, fail.
3770 if (!CompVal)
3771 return false;
3773 // Avoid turning single icmps into a switch.
3774 if (UsedICmps <= 1)
3775 return false;
3777 bool TrueWhenEqual = (Cond->getOpcode() == Instruction::Or);
3779 // There might be duplicate constants in the list, which the switch
3780 // instruction can't handle, remove them now.
3781 array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate);
3782 Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
3784 // If Extra was used, we require at least two switch values to do the
3785 // transformation. A switch with one value is just a conditional branch.
3786 if (ExtraCase && Values.size() < 2)
3787 return false;
3789 // TODO: Preserve branch weight metadata, similarly to how
3790 // FoldValueComparisonIntoPredecessors preserves it.
3792 // Figure out which block is which destination.
3793 BasicBlock *DefaultBB = BI->getSuccessor(1);
3794 BasicBlock *EdgeBB = BI->getSuccessor(0);
3795 if (!TrueWhenEqual)
3796 std::swap(DefaultBB, EdgeBB);
3798 BasicBlock *BB = BI->getParent();
3800 // MSAN does not like undefs as branch condition which can be introduced
3801 // with "explicit branch".
3802 if (ExtraCase && BB->getParent()->hasFnAttribute(Attribute::SanitizeMemory))
3803 return false;
3805 LLVM_DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
3806 << " cases into SWITCH. BB is:\n"
3807 << *BB);
3809 // If there are any extra values that couldn't be folded into the switch
3810 // then we evaluate them with an explicit branch first. Split the block
3811 // right before the condbr to handle it.
3812 if (ExtraCase) {
3813 BasicBlock *NewBB =
3814 BB->splitBasicBlock(BI->getIterator(), "switch.early.test");
3815 // Remove the uncond branch added to the old block.
3816 Instruction *OldTI = BB->getTerminator();
3817 Builder.SetInsertPoint(OldTI);
3819 if (TrueWhenEqual)
3820 Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB);
3821 else
3822 Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB);
3824 OldTI->eraseFromParent();
3826 // If there are PHI nodes in EdgeBB, then we need to add a new entry to them
3827 // for the edge we just added.
3828 AddPredecessorToBlock(EdgeBB, BB, NewBB);
3830 LLVM_DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase
3831 << "\nEXTRABB = " << *BB);
3832 BB = NewBB;
3835 Builder.SetInsertPoint(BI);
3836 // Convert pointer to int before we switch.
3837 if (CompVal->getType()->isPointerTy()) {
3838 CompVal = Builder.CreatePtrToInt(
3839 CompVal, DL.getIntPtrType(CompVal->getType()), "magicptr");
3842 // Create the new switch instruction now.
3843 SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size());
3845 // Add all of the 'cases' to the switch instruction.
3846 for (unsigned i = 0, e = Values.size(); i != e; ++i)
3847 New->addCase(Values[i], EdgeBB);
3849 // We added edges from PI to the EdgeBB. As such, if there were any
3850 // PHI nodes in EdgeBB, they need entries to be added corresponding to
3851 // the number of edges added.
3852 for (BasicBlock::iterator BBI = EdgeBB->begin(); isa<PHINode>(BBI); ++BBI) {
3853 PHINode *PN = cast<PHINode>(BBI);
3854 Value *InVal = PN->getIncomingValueForBlock(BB);
3855 for (unsigned i = 0, e = Values.size() - 1; i != e; ++i)
3856 PN->addIncoming(InVal, BB);
3859 // Erase the old branch instruction.
3860 EraseTerminatorAndDCECond(BI);
3862 LLVM_DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n');
3863 return true;
3866 bool SimplifyCFGOpt::SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder) {
3867 if (isa<PHINode>(RI->getValue()))
3868 return SimplifyCommonResume(RI);
3869 else if (isa<LandingPadInst>(RI->getParent()->getFirstNonPHI()) &&
3870 RI->getValue() == RI->getParent()->getFirstNonPHI())
3871 // The resume must unwind the exception that caused control to branch here.
3872 return SimplifySingleResume(RI);
3874 return false;
3877 // Simplify resume that is shared by several landing pads (phi of landing pad).
3878 bool SimplifyCFGOpt::SimplifyCommonResume(ResumeInst *RI) {
3879 BasicBlock *BB = RI->getParent();
3881 // Check that there are no other instructions except for debug intrinsics
3882 // between the phi of landing pads (RI->getValue()) and resume instruction.
3883 BasicBlock::iterator I = cast<Instruction>(RI->getValue())->getIterator(),
3884 E = RI->getIterator();
3885 while (++I != E)
3886 if (!isa<DbgInfoIntrinsic>(I))
3887 return false;
3889 SmallSetVector<BasicBlock *, 4> TrivialUnwindBlocks;
3890 auto *PhiLPInst = cast<PHINode>(RI->getValue());
3892 // Check incoming blocks to see if any of them are trivial.
3893 for (unsigned Idx = 0, End = PhiLPInst->getNumIncomingValues(); Idx != End;
3894 Idx++) {
3895 auto *IncomingBB = PhiLPInst->getIncomingBlock(Idx);
3896 auto *IncomingValue = PhiLPInst->getIncomingValue(Idx);
3898 // If the block has other successors, we can not delete it because
3899 // it has other dependents.
3900 if (IncomingBB->getUniqueSuccessor() != BB)
3901 continue;
3903 auto *LandingPad = dyn_cast<LandingPadInst>(IncomingBB->getFirstNonPHI());
3904 // Not the landing pad that caused the control to branch here.
3905 if (IncomingValue != LandingPad)
3906 continue;
3908 bool isTrivial = true;
3910 I = IncomingBB->getFirstNonPHI()->getIterator();
3911 E = IncomingBB->getTerminator()->getIterator();
3912 while (++I != E)
3913 if (!isa<DbgInfoIntrinsic>(I)) {
3914 isTrivial = false;
3915 break;
3918 if (isTrivial)
3919 TrivialUnwindBlocks.insert(IncomingBB);
3922 // If no trivial unwind blocks, don't do any simplifications.
3923 if (TrivialUnwindBlocks.empty())
3924 return false;
3926 // Turn all invokes that unwind here into calls.
3927 for (auto *TrivialBB : TrivialUnwindBlocks) {
3928 // Blocks that will be simplified should be removed from the phi node.
3929 // Note there could be multiple edges to the resume block, and we need
3930 // to remove them all.
3931 while (PhiLPInst->getBasicBlockIndex(TrivialBB) != -1)
3932 BB->removePredecessor(TrivialBB, true);
3934 for (pred_iterator PI = pred_begin(TrivialBB), PE = pred_end(TrivialBB);
3935 PI != PE;) {
3936 BasicBlock *Pred = *PI++;
3937 removeUnwindEdge(Pred);
3940 // In each SimplifyCFG run, only the current processed block can be erased.
3941 // Otherwise, it will break the iteration of SimplifyCFG pass. So instead
3942 // of erasing TrivialBB, we only remove the branch to the common resume
3943 // block so that we can later erase the resume block since it has no
3944 // predecessors.
3945 TrivialBB->getTerminator()->eraseFromParent();
3946 new UnreachableInst(RI->getContext(), TrivialBB);
3949 // Delete the resume block if all its predecessors have been removed.
3950 if (pred_empty(BB))
3951 BB->eraseFromParent();
3953 return !TrivialUnwindBlocks.empty();
3956 // Simplify resume that is only used by a single (non-phi) landing pad.
3957 bool SimplifyCFGOpt::SimplifySingleResume(ResumeInst *RI) {
3958 BasicBlock *BB = RI->getParent();
3959 auto *LPInst = cast<LandingPadInst>(BB->getFirstNonPHI());
3960 assert(RI->getValue() == LPInst &&
3961 "Resume must unwind the exception that caused control to here");
3963 // Check that there are no other instructions except for debug intrinsics.
3964 BasicBlock::iterator I = LPInst->getIterator(), E = RI->getIterator();
3965 while (++I != E)
3966 if (!isa<DbgInfoIntrinsic>(I))
3967 return false;
3969 // Turn all invokes that unwind here into calls and delete the basic block.
3970 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
3971 BasicBlock *Pred = *PI++;
3972 removeUnwindEdge(Pred);
3975 // The landingpad is now unreachable. Zap it.
3976 if (LoopHeaders)
3977 LoopHeaders->erase(BB);
3978 BB->eraseFromParent();
3979 return true;
3982 static bool removeEmptyCleanup(CleanupReturnInst *RI) {
3983 // If this is a trivial cleanup pad that executes no instructions, it can be
3984 // eliminated. If the cleanup pad continues to the caller, any predecessor
3985 // that is an EH pad will be updated to continue to the caller and any
3986 // predecessor that terminates with an invoke instruction will have its invoke
3987 // instruction converted to a call instruction. If the cleanup pad being
3988 // simplified does not continue to the caller, each predecessor will be
3989 // updated to continue to the unwind destination of the cleanup pad being
3990 // simplified.
3991 BasicBlock *BB = RI->getParent();
3992 CleanupPadInst *CPInst = RI->getCleanupPad();
3993 if (CPInst->getParent() != BB)
3994 // This isn't an empty cleanup.
3995 return false;
3997 // We cannot kill the pad if it has multiple uses. This typically arises
3998 // from unreachable basic blocks.
3999 if (!CPInst->hasOneUse())
4000 return false;
4002 // Check that there are no other instructions except for benign intrinsics.
4003 BasicBlock::iterator I = CPInst->getIterator(), E = RI->getIterator();
4004 while (++I != E) {
4005 auto *II = dyn_cast<IntrinsicInst>(I);
4006 if (!II)
4007 return false;
4009 Intrinsic::ID IntrinsicID = II->getIntrinsicID();
4010 switch (IntrinsicID) {
4011 case Intrinsic::dbg_declare:
4012 case Intrinsic::dbg_value:
4013 case Intrinsic::dbg_label:
4014 case Intrinsic::lifetime_end:
4015 break;
4016 default:
4017 return false;
4021 // If the cleanup return we are simplifying unwinds to the caller, this will
4022 // set UnwindDest to nullptr.
4023 BasicBlock *UnwindDest = RI->getUnwindDest();
4024 Instruction *DestEHPad = UnwindDest ? UnwindDest->getFirstNonPHI() : nullptr;
4026 // We're about to remove BB from the control flow. Before we do, sink any
4027 // PHINodes into the unwind destination. Doing this before changing the
4028 // control flow avoids some potentially slow checks, since we can currently
4029 // be certain that UnwindDest and BB have no common predecessors (since they
4030 // are both EH pads).
4031 if (UnwindDest) {
4032 // First, go through the PHI nodes in UnwindDest and update any nodes that
4033 // reference the block we are removing
4034 for (BasicBlock::iterator I = UnwindDest->begin(),
4035 IE = DestEHPad->getIterator();
4036 I != IE; ++I) {
4037 PHINode *DestPN = cast<PHINode>(I);
4039 int Idx = DestPN->getBasicBlockIndex(BB);
4040 // Since BB unwinds to UnwindDest, it has to be in the PHI node.
4041 assert(Idx != -1);
4042 // This PHI node has an incoming value that corresponds to a control
4043 // path through the cleanup pad we are removing. If the incoming
4044 // value is in the cleanup pad, it must be a PHINode (because we
4045 // verified above that the block is otherwise empty). Otherwise, the
4046 // value is either a constant or a value that dominates the cleanup
4047 // pad being removed.
4049 // Because BB and UnwindDest are both EH pads, all of their
4050 // predecessors must unwind to these blocks, and since no instruction
4051 // can have multiple unwind destinations, there will be no overlap in
4052 // incoming blocks between SrcPN and DestPN.
4053 Value *SrcVal = DestPN->getIncomingValue(Idx);
4054 PHINode *SrcPN = dyn_cast<PHINode>(SrcVal);
4056 // Remove the entry for the block we are deleting.
4057 DestPN->removeIncomingValue(Idx, false);
4059 if (SrcPN && SrcPN->getParent() == BB) {
4060 // If the incoming value was a PHI node in the cleanup pad we are
4061 // removing, we need to merge that PHI node's incoming values into
4062 // DestPN.
4063 for (unsigned SrcIdx = 0, SrcE = SrcPN->getNumIncomingValues();
4064 SrcIdx != SrcE; ++SrcIdx) {
4065 DestPN->addIncoming(SrcPN->getIncomingValue(SrcIdx),
4066 SrcPN->getIncomingBlock(SrcIdx));
4068 } else {
4069 // Otherwise, the incoming value came from above BB and
4070 // so we can just reuse it. We must associate all of BB's
4071 // predecessors with this value.
4072 for (auto *pred : predecessors(BB)) {
4073 DestPN->addIncoming(SrcVal, pred);
4078 // Sink any remaining PHI nodes directly into UnwindDest.
4079 Instruction *InsertPt = DestEHPad;
4080 for (BasicBlock::iterator I = BB->begin(),
4081 IE = BB->getFirstNonPHI()->getIterator();
4082 I != IE;) {
4083 // The iterator must be incremented here because the instructions are
4084 // being moved to another block.
4085 PHINode *PN = cast<PHINode>(I++);
4086 if (PN->use_empty())
4087 // If the PHI node has no uses, just leave it. It will be erased
4088 // when we erase BB below.
4089 continue;
4091 // Otherwise, sink this PHI node into UnwindDest.
4092 // Any predecessors to UnwindDest which are not already represented
4093 // must be back edges which inherit the value from the path through
4094 // BB. In this case, the PHI value must reference itself.
4095 for (auto *pred : predecessors(UnwindDest))
4096 if (pred != BB)
4097 PN->addIncoming(PN, pred);
4098 PN->moveBefore(InsertPt);
4102 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
4103 // The iterator must be updated here because we are removing this pred.
4104 BasicBlock *PredBB = *PI++;
4105 if (UnwindDest == nullptr) {
4106 removeUnwindEdge(PredBB);
4107 } else {
4108 Instruction *TI = PredBB->getTerminator();
4109 TI->replaceUsesOfWith(BB, UnwindDest);
4113 // The cleanup pad is now unreachable. Zap it.
4114 BB->eraseFromParent();
4115 return true;
4118 // Try to merge two cleanuppads together.
4119 static bool mergeCleanupPad(CleanupReturnInst *RI) {
4120 // Skip any cleanuprets which unwind to caller, there is nothing to merge
4121 // with.
4122 BasicBlock *UnwindDest = RI->getUnwindDest();
4123 if (!UnwindDest)
4124 return false;
4126 // This cleanupret isn't the only predecessor of this cleanuppad, it wouldn't
4127 // be safe to merge without code duplication.
4128 if (UnwindDest->getSinglePredecessor() != RI->getParent())
4129 return false;
4131 // Verify that our cleanuppad's unwind destination is another cleanuppad.
4132 auto *SuccessorCleanupPad = dyn_cast<CleanupPadInst>(&UnwindDest->front());
4133 if (!SuccessorCleanupPad)
4134 return false;
4136 CleanupPadInst *PredecessorCleanupPad = RI->getCleanupPad();
4137 // Replace any uses of the successor cleanupad with the predecessor pad
4138 // The only cleanuppad uses should be this cleanupret, it's cleanupret and
4139 // funclet bundle operands.
4140 SuccessorCleanupPad->replaceAllUsesWith(PredecessorCleanupPad);
4141 // Remove the old cleanuppad.
4142 SuccessorCleanupPad->eraseFromParent();
4143 // Now, we simply replace the cleanupret with a branch to the unwind
4144 // destination.
4145 BranchInst::Create(UnwindDest, RI->getParent());
4146 RI->eraseFromParent();
4148 return true;
4151 bool SimplifyCFGOpt::SimplifyCleanupReturn(CleanupReturnInst *RI) {
4152 // It is possible to transiantly have an undef cleanuppad operand because we
4153 // have deleted some, but not all, dead blocks.
4154 // Eventually, this block will be deleted.
4155 if (isa<UndefValue>(RI->getOperand(0)))
4156 return false;
4158 if (mergeCleanupPad(RI))
4159 return true;
4161 if (removeEmptyCleanup(RI))
4162 return true;
4164 return false;
4167 bool SimplifyCFGOpt::SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder) {
4168 BasicBlock *BB = RI->getParent();
4169 if (!BB->getFirstNonPHIOrDbg()->isTerminator())
4170 return false;
4172 // Find predecessors that end with branches.
4173 SmallVector<BasicBlock *, 8> UncondBranchPreds;
4174 SmallVector<BranchInst *, 8> CondBranchPreds;
4175 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
4176 BasicBlock *P = *PI;
4177 Instruction *PTI = P->getTerminator();
4178 if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
4179 if (BI->isUnconditional())
4180 UncondBranchPreds.push_back(P);
4181 else
4182 CondBranchPreds.push_back(BI);
4186 // If we found some, do the transformation!
4187 if (!UncondBranchPreds.empty() && DupRet) {
4188 while (!UncondBranchPreds.empty()) {
4189 BasicBlock *Pred = UncondBranchPreds.pop_back_val();
4190 LLVM_DEBUG(dbgs() << "FOLDING: " << *BB
4191 << "INTO UNCOND BRANCH PRED: " << *Pred);
4192 (void)FoldReturnIntoUncondBranch(RI, BB, Pred);
4195 // If we eliminated all predecessors of the block, delete the block now.
4196 if (pred_empty(BB)) {
4197 // We know there are no successors, so just nuke the block.
4198 if (LoopHeaders)
4199 LoopHeaders->erase(BB);
4200 BB->eraseFromParent();
4203 return true;
4206 // Check out all of the conditional branches going to this return
4207 // instruction. If any of them just select between returns, change the
4208 // branch itself into a select/return pair.
4209 while (!CondBranchPreds.empty()) {
4210 BranchInst *BI = CondBranchPreds.pop_back_val();
4212 // Check to see if the non-BB successor is also a return block.
4213 if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) &&
4214 isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) &&
4215 SimplifyCondBranchToTwoReturns(BI, Builder))
4216 return true;
4218 return false;
4221 bool SimplifyCFGOpt::SimplifyUnreachable(UnreachableInst *UI) {
4222 BasicBlock *BB = UI->getParent();
4224 bool Changed = false;
4226 // If there are any instructions immediately before the unreachable that can
4227 // be removed, do so.
4228 while (UI->getIterator() != BB->begin()) {
4229 BasicBlock::iterator BBI = UI->getIterator();
4230 --BBI;
4231 // Do not delete instructions that can have side effects which might cause
4232 // the unreachable to not be reachable; specifically, calls and volatile
4233 // operations may have this effect.
4234 if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI))
4235 break;
4237 if (BBI->mayHaveSideEffects()) {
4238 if (auto *SI = dyn_cast<StoreInst>(BBI)) {
4239 if (SI->isVolatile())
4240 break;
4241 } else if (auto *LI = dyn_cast<LoadInst>(BBI)) {
4242 if (LI->isVolatile())
4243 break;
4244 } else if (auto *RMWI = dyn_cast<AtomicRMWInst>(BBI)) {
4245 if (RMWI->isVolatile())
4246 break;
4247 } else if (auto *CXI = dyn_cast<AtomicCmpXchgInst>(BBI)) {
4248 if (CXI->isVolatile())
4249 break;
4250 } else if (isa<CatchPadInst>(BBI)) {
4251 // A catchpad may invoke exception object constructors and such, which
4252 // in some languages can be arbitrary code, so be conservative by
4253 // default.
4254 // For CoreCLR, it just involves a type test, so can be removed.
4255 if (classifyEHPersonality(BB->getParent()->getPersonalityFn()) !=
4256 EHPersonality::CoreCLR)
4257 break;
4258 } else if (!isa<FenceInst>(BBI) && !isa<VAArgInst>(BBI) &&
4259 !isa<LandingPadInst>(BBI)) {
4260 break;
4262 // Note that deleting LandingPad's here is in fact okay, although it
4263 // involves a bit of subtle reasoning. If this inst is a LandingPad,
4264 // all the predecessors of this block will be the unwind edges of Invokes,
4265 // and we can therefore guarantee this block will be erased.
4268 // Delete this instruction (any uses are guaranteed to be dead)
4269 if (!BBI->use_empty())
4270 BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
4271 BBI->eraseFromParent();
4272 Changed = true;
4275 // If the unreachable instruction is the first in the block, take a gander
4276 // at all of the predecessors of this instruction, and simplify them.
4277 if (&BB->front() != UI)
4278 return Changed;
4280 SmallVector<BasicBlock *, 8> Preds(pred_begin(BB), pred_end(BB));
4281 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
4282 Instruction *TI = Preds[i]->getTerminator();
4283 IRBuilder<> Builder(TI);
4284 if (auto *BI = dyn_cast<BranchInst>(TI)) {
4285 if (BI->isUnconditional()) {
4286 assert(BI->getSuccessor(0) == BB && "Incorrect CFG");
4287 new UnreachableInst(TI->getContext(), TI);
4288 TI->eraseFromParent();
4289 Changed = true;
4290 } else {
4291 Value* Cond = BI->getCondition();
4292 if (BI->getSuccessor(0) == BB) {
4293 Builder.CreateAssumption(Builder.CreateNot(Cond));
4294 Builder.CreateBr(BI->getSuccessor(1));
4295 } else {
4296 assert(BI->getSuccessor(1) == BB && "Incorrect CFG");
4297 Builder.CreateAssumption(Cond);
4298 Builder.CreateBr(BI->getSuccessor(0));
4300 EraseTerminatorAndDCECond(BI);
4301 Changed = true;
4303 } else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
4304 SwitchInstProfUpdateWrapper SU(*SI);
4305 for (auto i = SU->case_begin(), e = SU->case_end(); i != e;) {
4306 if (i->getCaseSuccessor() != BB) {
4307 ++i;
4308 continue;
4310 BB->removePredecessor(SU->getParent());
4311 i = SU.removeCase(i);
4312 e = SU->case_end();
4313 Changed = true;
4315 } else if (auto *II = dyn_cast<InvokeInst>(TI)) {
4316 if (II->getUnwindDest() == BB) {
4317 removeUnwindEdge(TI->getParent());
4318 Changed = true;
4320 } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) {
4321 if (CSI->getUnwindDest() == BB) {
4322 removeUnwindEdge(TI->getParent());
4323 Changed = true;
4324 continue;
4327 for (CatchSwitchInst::handler_iterator I = CSI->handler_begin(),
4328 E = CSI->handler_end();
4329 I != E; ++I) {
4330 if (*I == BB) {
4331 CSI->removeHandler(I);
4332 --I;
4333 --E;
4334 Changed = true;
4337 if (CSI->getNumHandlers() == 0) {
4338 BasicBlock *CatchSwitchBB = CSI->getParent();
4339 if (CSI->hasUnwindDest()) {
4340 // Redirect preds to the unwind dest
4341 CatchSwitchBB->replaceAllUsesWith(CSI->getUnwindDest());
4342 } else {
4343 // Rewrite all preds to unwind to caller (or from invoke to call).
4344 SmallVector<BasicBlock *, 8> EHPreds(predecessors(CatchSwitchBB));
4345 for (BasicBlock *EHPred : EHPreds)
4346 removeUnwindEdge(EHPred);
4348 // The catchswitch is no longer reachable.
4349 new UnreachableInst(CSI->getContext(), CSI);
4350 CSI->eraseFromParent();
4351 Changed = true;
4353 } else if (isa<CleanupReturnInst>(TI)) {
4354 new UnreachableInst(TI->getContext(), TI);
4355 TI->eraseFromParent();
4356 Changed = true;
4360 // If this block is now dead, remove it.
4361 if (pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()) {
4362 // We know there are no successors, so just nuke the block.
4363 if (LoopHeaders)
4364 LoopHeaders->erase(BB);
4365 BB->eraseFromParent();
4366 return true;
4369 return Changed;
4372 static bool CasesAreContiguous(SmallVectorImpl<ConstantInt *> &Cases) {
4373 assert(Cases.size() >= 1);
4375 array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate);
4376 for (size_t I = 1, E = Cases.size(); I != E; ++I) {
4377 if (Cases[I - 1]->getValue() != Cases[I]->getValue() + 1)
4378 return false;
4380 return true;
4383 static void createUnreachableSwitchDefault(SwitchInst *Switch) {
4384 LLVM_DEBUG(dbgs() << "SimplifyCFG: switch default is dead.\n");
4385 BasicBlock *NewDefaultBlock =
4386 SplitBlockPredecessors(Switch->getDefaultDest(), Switch->getParent(), "");
4387 Switch->setDefaultDest(&*NewDefaultBlock);
4388 SplitBlock(&*NewDefaultBlock, &NewDefaultBlock->front());
4389 auto *NewTerminator = NewDefaultBlock->getTerminator();
4390 new UnreachableInst(Switch->getContext(), NewTerminator);
4391 EraseTerminatorAndDCECond(NewTerminator);
4394 /// Turn a switch with two reachable destinations into an integer range
4395 /// comparison and branch.
4396 static bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder) {
4397 assert(SI->getNumCases() > 1 && "Degenerate switch?");
4399 bool HasDefault =
4400 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
4402 // Partition the cases into two sets with different destinations.
4403 BasicBlock *DestA = HasDefault ? SI->getDefaultDest() : nullptr;
4404 BasicBlock *DestB = nullptr;
4405 SmallVector<ConstantInt *, 16> CasesA;
4406 SmallVector<ConstantInt *, 16> CasesB;
4408 for (auto Case : SI->cases()) {
4409 BasicBlock *Dest = Case.getCaseSuccessor();
4410 if (!DestA)
4411 DestA = Dest;
4412 if (Dest == DestA) {
4413 CasesA.push_back(Case.getCaseValue());
4414 continue;
4416 if (!DestB)
4417 DestB = Dest;
4418 if (Dest == DestB) {
4419 CasesB.push_back(Case.getCaseValue());
4420 continue;
4422 return false; // More than two destinations.
4425 assert(DestA && DestB &&
4426 "Single-destination switch should have been folded.");
4427 assert(DestA != DestB);
4428 assert(DestB != SI->getDefaultDest());
4429 assert(!CasesB.empty() && "There must be non-default cases.");
4430 assert(!CasesA.empty() || HasDefault);
4432 // Figure out if one of the sets of cases form a contiguous range.
4433 SmallVectorImpl<ConstantInt *> *ContiguousCases = nullptr;
4434 BasicBlock *ContiguousDest = nullptr;
4435 BasicBlock *OtherDest = nullptr;
4436 if (!CasesA.empty() && CasesAreContiguous(CasesA)) {
4437 ContiguousCases = &CasesA;
4438 ContiguousDest = DestA;
4439 OtherDest = DestB;
4440 } else if (CasesAreContiguous(CasesB)) {
4441 ContiguousCases = &CasesB;
4442 ContiguousDest = DestB;
4443 OtherDest = DestA;
4444 } else
4445 return false;
4447 // Start building the compare and branch.
4449 Constant *Offset = ConstantExpr::getNeg(ContiguousCases->back());
4450 Constant *NumCases =
4451 ConstantInt::get(Offset->getType(), ContiguousCases->size());
4453 Value *Sub = SI->getCondition();
4454 if (!Offset->isNullValue())
4455 Sub = Builder.CreateAdd(Sub, Offset, Sub->getName() + ".off");
4457 Value *Cmp;
4458 // If NumCases overflowed, then all possible values jump to the successor.
4459 if (NumCases->isNullValue() && !ContiguousCases->empty())
4460 Cmp = ConstantInt::getTrue(SI->getContext());
4461 else
4462 Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch");
4463 BranchInst *NewBI = Builder.CreateCondBr(Cmp, ContiguousDest, OtherDest);
4465 // Update weight for the newly-created conditional branch.
4466 if (HasBranchWeights(SI)) {
4467 SmallVector<uint64_t, 8> Weights;
4468 GetBranchWeights(SI, Weights);
4469 if (Weights.size() == 1 + SI->getNumCases()) {
4470 uint64_t TrueWeight = 0;
4471 uint64_t FalseWeight = 0;
4472 for (size_t I = 0, E = Weights.size(); I != E; ++I) {
4473 if (SI->getSuccessor(I) == ContiguousDest)
4474 TrueWeight += Weights[I];
4475 else
4476 FalseWeight += Weights[I];
4478 while (TrueWeight > UINT32_MAX || FalseWeight > UINT32_MAX) {
4479 TrueWeight /= 2;
4480 FalseWeight /= 2;
4482 setBranchWeights(NewBI, TrueWeight, FalseWeight);
4486 // Prune obsolete incoming values off the successors' PHI nodes.
4487 for (auto BBI = ContiguousDest->begin(); isa<PHINode>(BBI); ++BBI) {
4488 unsigned PreviousEdges = ContiguousCases->size();
4489 if (ContiguousDest == SI->getDefaultDest())
4490 ++PreviousEdges;
4491 for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
4492 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
4494 for (auto BBI = OtherDest->begin(); isa<PHINode>(BBI); ++BBI) {
4495 unsigned PreviousEdges = SI->getNumCases() - ContiguousCases->size();
4496 if (OtherDest == SI->getDefaultDest())
4497 ++PreviousEdges;
4498 for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
4499 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
4502 // Clean up the default block - it may have phis or other instructions before
4503 // the unreachable terminator.
4504 if (!HasDefault)
4505 createUnreachableSwitchDefault(SI);
4507 // Drop the switch.
4508 SI->eraseFromParent();
4510 return true;
4513 /// Compute masked bits for the condition of a switch
4514 /// and use it to remove dead cases.
4515 static bool eliminateDeadSwitchCases(SwitchInst *SI, AssumptionCache *AC,
4516 const DataLayout &DL) {
4517 Value *Cond = SI->getCondition();
4518 unsigned Bits = Cond->getType()->getIntegerBitWidth();
4519 KnownBits Known = computeKnownBits(Cond, DL, 0, AC, SI);
4521 // We can also eliminate cases by determining that their values are outside of
4522 // the limited range of the condition based on how many significant (non-sign)
4523 // bits are in the condition value.
4524 unsigned ExtraSignBits = ComputeNumSignBits(Cond, DL, 0, AC, SI) - 1;
4525 unsigned MaxSignificantBitsInCond = Bits - ExtraSignBits;
4527 // Gather dead cases.
4528 SmallVector<ConstantInt *, 8> DeadCases;
4529 for (auto &Case : SI->cases()) {
4530 const APInt &CaseVal = Case.getCaseValue()->getValue();
4531 if (Known.Zero.intersects(CaseVal) || !Known.One.isSubsetOf(CaseVal) ||
4532 (CaseVal.getMinSignedBits() > MaxSignificantBitsInCond)) {
4533 DeadCases.push_back(Case.getCaseValue());
4534 LLVM_DEBUG(dbgs() << "SimplifyCFG: switch case " << CaseVal
4535 << " is dead.\n");
4539 // If we can prove that the cases must cover all possible values, the
4540 // default destination becomes dead and we can remove it. If we know some
4541 // of the bits in the value, we can use that to more precisely compute the
4542 // number of possible unique case values.
4543 bool HasDefault =
4544 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
4545 const unsigned NumUnknownBits =
4546 Bits - (Known.Zero | Known.One).countPopulation();
4547 assert(NumUnknownBits <= Bits);
4548 if (HasDefault && DeadCases.empty() &&
4549 NumUnknownBits < 64 /* avoid overflow */ &&
4550 SI->getNumCases() == (1ULL << NumUnknownBits)) {
4551 createUnreachableSwitchDefault(SI);
4552 return true;
4555 if (DeadCases.empty())
4556 return false;
4558 SwitchInstProfUpdateWrapper SIW(*SI);
4559 for (ConstantInt *DeadCase : DeadCases) {
4560 SwitchInst::CaseIt CaseI = SI->findCaseValue(DeadCase);
4561 assert(CaseI != SI->case_default() &&
4562 "Case was not found. Probably mistake in DeadCases forming.");
4563 // Prune unused values from PHI nodes.
4564 CaseI->getCaseSuccessor()->removePredecessor(SI->getParent());
4565 SIW.removeCase(CaseI);
4568 return true;
4571 /// If BB would be eligible for simplification by
4572 /// TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated
4573 /// by an unconditional branch), look at the phi node for BB in the successor
4574 /// block and see if the incoming value is equal to CaseValue. If so, return
4575 /// the phi node, and set PhiIndex to BB's index in the phi node.
4576 static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue,
4577 BasicBlock *BB, int *PhiIndex) {
4578 if (BB->getFirstNonPHIOrDbg() != BB->getTerminator())
4579 return nullptr; // BB must be empty to be a candidate for simplification.
4580 if (!BB->getSinglePredecessor())
4581 return nullptr; // BB must be dominated by the switch.
4583 BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator());
4584 if (!Branch || !Branch->isUnconditional())
4585 return nullptr; // Terminator must be unconditional branch.
4587 BasicBlock *Succ = Branch->getSuccessor(0);
4589 for (PHINode &PHI : Succ->phis()) {
4590 int Idx = PHI.getBasicBlockIndex(BB);
4591 assert(Idx >= 0 && "PHI has no entry for predecessor?");
4593 Value *InValue = PHI.getIncomingValue(Idx);
4594 if (InValue != CaseValue)
4595 continue;
4597 *PhiIndex = Idx;
4598 return &PHI;
4601 return nullptr;
4604 /// Try to forward the condition of a switch instruction to a phi node
4605 /// dominated by the switch, if that would mean that some of the destination
4606 /// blocks of the switch can be folded away. Return true if a change is made.
4607 static bool ForwardSwitchConditionToPHI(SwitchInst *SI) {
4608 using ForwardingNodesMap = DenseMap<PHINode *, SmallVector<int, 4>>;
4610 ForwardingNodesMap ForwardingNodes;
4611 BasicBlock *SwitchBlock = SI->getParent();
4612 bool Changed = false;
4613 for (auto &Case : SI->cases()) {
4614 ConstantInt *CaseValue = Case.getCaseValue();
4615 BasicBlock *CaseDest = Case.getCaseSuccessor();
4617 // Replace phi operands in successor blocks that are using the constant case
4618 // value rather than the switch condition variable:
4619 // switchbb:
4620 // switch i32 %x, label %default [
4621 // i32 17, label %succ
4622 // ...
4623 // succ:
4624 // %r = phi i32 ... [ 17, %switchbb ] ...
4625 // -->
4626 // %r = phi i32 ... [ %x, %switchbb ] ...
4628 for (PHINode &Phi : CaseDest->phis()) {
4629 // This only works if there is exactly 1 incoming edge from the switch to
4630 // a phi. If there is >1, that means multiple cases of the switch map to 1
4631 // value in the phi, and that phi value is not the switch condition. Thus,
4632 // this transform would not make sense (the phi would be invalid because
4633 // a phi can't have different incoming values from the same block).
4634 int SwitchBBIdx = Phi.getBasicBlockIndex(SwitchBlock);
4635 if (Phi.getIncomingValue(SwitchBBIdx) == CaseValue &&
4636 count(Phi.blocks(), SwitchBlock) == 1) {
4637 Phi.setIncomingValue(SwitchBBIdx, SI->getCondition());
4638 Changed = true;
4642 // Collect phi nodes that are indirectly using this switch's case constants.
4643 int PhiIdx;
4644 if (auto *Phi = FindPHIForConditionForwarding(CaseValue, CaseDest, &PhiIdx))
4645 ForwardingNodes[Phi].push_back(PhiIdx);
4648 for (auto &ForwardingNode : ForwardingNodes) {
4649 PHINode *Phi = ForwardingNode.first;
4650 SmallVectorImpl<int> &Indexes = ForwardingNode.second;
4651 if (Indexes.size() < 2)
4652 continue;
4654 for (int Index : Indexes)
4655 Phi->setIncomingValue(Index, SI->getCondition());
4656 Changed = true;
4659 return Changed;
4662 /// Return true if the backend will be able to handle
4663 /// initializing an array of constants like C.
4664 static bool ValidLookupTableConstant(Constant *C, const TargetTransformInfo &TTI) {
4665 if (C->isThreadDependent())
4666 return false;
4667 if (C->isDLLImportDependent())
4668 return false;
4670 if (!isa<ConstantFP>(C) && !isa<ConstantInt>(C) &&
4671 !isa<ConstantPointerNull>(C) && !isa<GlobalValue>(C) &&
4672 !isa<UndefValue>(C) && !isa<ConstantExpr>(C))
4673 return false;
4675 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
4676 if (!CE->isGEPWithNoNotionalOverIndexing())
4677 return false;
4678 if (!ValidLookupTableConstant(CE->getOperand(0), TTI))
4679 return false;
4682 if (!TTI.shouldBuildLookupTablesForConstant(C))
4683 return false;
4685 return true;
4688 /// If V is a Constant, return it. Otherwise, try to look up
4689 /// its constant value in ConstantPool, returning 0 if it's not there.
4690 static Constant *
4691 LookupConstant(Value *V,
4692 const SmallDenseMap<Value *, Constant *> &ConstantPool) {
4693 if (Constant *C = dyn_cast<Constant>(V))
4694 return C;
4695 return ConstantPool.lookup(V);
4698 /// Try to fold instruction I into a constant. This works for
4699 /// simple instructions such as binary operations where both operands are
4700 /// constant or can be replaced by constants from the ConstantPool. Returns the
4701 /// resulting constant on success, 0 otherwise.
4702 static Constant *
4703 ConstantFold(Instruction *I, const DataLayout &DL,
4704 const SmallDenseMap<Value *, Constant *> &ConstantPool) {
4705 if (SelectInst *Select = dyn_cast<SelectInst>(I)) {
4706 Constant *A = LookupConstant(Select->getCondition(), ConstantPool);
4707 if (!A)
4708 return nullptr;
4709 if (A->isAllOnesValue())
4710 return LookupConstant(Select->getTrueValue(), ConstantPool);
4711 if (A->isNullValue())
4712 return LookupConstant(Select->getFalseValue(), ConstantPool);
4713 return nullptr;
4716 SmallVector<Constant *, 4> COps;
4717 for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) {
4718 if (Constant *A = LookupConstant(I->getOperand(N), ConstantPool))
4719 COps.push_back(A);
4720 else
4721 return nullptr;
4724 if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
4725 return ConstantFoldCompareInstOperands(Cmp->getPredicate(), COps[0],
4726 COps[1], DL);
4729 return ConstantFoldInstOperands(I, COps, DL);
4732 /// Try to determine the resulting constant values in phi nodes
4733 /// at the common destination basic block, *CommonDest, for one of the case
4734 /// destionations CaseDest corresponding to value CaseVal (0 for the default
4735 /// case), of a switch instruction SI.
4736 static bool
4737 GetCaseResults(SwitchInst *SI, ConstantInt *CaseVal, BasicBlock *CaseDest,
4738 BasicBlock **CommonDest,
4739 SmallVectorImpl<std::pair<PHINode *, Constant *>> &Res,
4740 const DataLayout &DL, const TargetTransformInfo &TTI) {
4741 // The block from which we enter the common destination.
4742 BasicBlock *Pred = SI->getParent();
4744 // If CaseDest is empty except for some side-effect free instructions through
4745 // which we can constant-propagate the CaseVal, continue to its successor.
4746 SmallDenseMap<Value *, Constant *> ConstantPool;
4747 ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal));
4748 for (Instruction &I :CaseDest->instructionsWithoutDebug()) {
4749 if (I.isTerminator()) {
4750 // If the terminator is a simple branch, continue to the next block.
4751 if (I.getNumSuccessors() != 1 || I.isExceptionalTerminator())
4752 return false;
4753 Pred = CaseDest;
4754 CaseDest = I.getSuccessor(0);
4755 } else if (Constant *C = ConstantFold(&I, DL, ConstantPool)) {
4756 // Instruction is side-effect free and constant.
4758 // If the instruction has uses outside this block or a phi node slot for
4759 // the block, it is not safe to bypass the instruction since it would then
4760 // no longer dominate all its uses.
4761 for (auto &Use : I.uses()) {
4762 User *User = Use.getUser();
4763 if (Instruction *I = dyn_cast<Instruction>(User))
4764 if (I->getParent() == CaseDest)
4765 continue;
4766 if (PHINode *Phi = dyn_cast<PHINode>(User))
4767 if (Phi->getIncomingBlock(Use) == CaseDest)
4768 continue;
4769 return false;
4772 ConstantPool.insert(std::make_pair(&I, C));
4773 } else {
4774 break;
4778 // If we did not have a CommonDest before, use the current one.
4779 if (!*CommonDest)
4780 *CommonDest = CaseDest;
4781 // If the destination isn't the common one, abort.
4782 if (CaseDest != *CommonDest)
4783 return false;
4785 // Get the values for this case from phi nodes in the destination block.
4786 for (PHINode &PHI : (*CommonDest)->phis()) {
4787 int Idx = PHI.getBasicBlockIndex(Pred);
4788 if (Idx == -1)
4789 continue;
4791 Constant *ConstVal =
4792 LookupConstant(PHI.getIncomingValue(Idx), ConstantPool);
4793 if (!ConstVal)
4794 return false;
4796 // Be conservative about which kinds of constants we support.
4797 if (!ValidLookupTableConstant(ConstVal, TTI))
4798 return false;
4800 Res.push_back(std::make_pair(&PHI, ConstVal));
4803 return Res.size() > 0;
4806 // Helper function used to add CaseVal to the list of cases that generate
4807 // Result. Returns the updated number of cases that generate this result.
4808 static uintptr_t MapCaseToResult(ConstantInt *CaseVal,
4809 SwitchCaseResultVectorTy &UniqueResults,
4810 Constant *Result) {
4811 for (auto &I : UniqueResults) {
4812 if (I.first == Result) {
4813 I.second.push_back(CaseVal);
4814 return I.second.size();
4817 UniqueResults.push_back(
4818 std::make_pair(Result, SmallVector<ConstantInt *, 4>(1, CaseVal)));
4819 return 1;
4822 // Helper function that initializes a map containing
4823 // results for the PHI node of the common destination block for a switch
4824 // instruction. Returns false if multiple PHI nodes have been found or if
4825 // there is not a common destination block for the switch.
4826 static bool
4827 InitializeUniqueCases(SwitchInst *SI, PHINode *&PHI, BasicBlock *&CommonDest,
4828 SwitchCaseResultVectorTy &UniqueResults,
4829 Constant *&DefaultResult, const DataLayout &DL,
4830 const TargetTransformInfo &TTI,
4831 uintptr_t MaxUniqueResults, uintptr_t MaxCasesPerResult) {
4832 for (auto &I : SI->cases()) {
4833 ConstantInt *CaseVal = I.getCaseValue();
4835 // Resulting value at phi nodes for this case value.
4836 SwitchCaseResultsTy Results;
4837 if (!GetCaseResults(SI, CaseVal, I.getCaseSuccessor(), &CommonDest, Results,
4838 DL, TTI))
4839 return false;
4841 // Only one value per case is permitted.
4842 if (Results.size() > 1)
4843 return false;
4845 // Add the case->result mapping to UniqueResults.
4846 const uintptr_t NumCasesForResult =
4847 MapCaseToResult(CaseVal, UniqueResults, Results.begin()->second);
4849 // Early out if there are too many cases for this result.
4850 if (NumCasesForResult > MaxCasesPerResult)
4851 return false;
4853 // Early out if there are too many unique results.
4854 if (UniqueResults.size() > MaxUniqueResults)
4855 return false;
4857 // Check the PHI consistency.
4858 if (!PHI)
4859 PHI = Results[0].first;
4860 else if (PHI != Results[0].first)
4861 return false;
4863 // Find the default result value.
4864 SmallVector<std::pair<PHINode *, Constant *>, 1> DefaultResults;
4865 BasicBlock *DefaultDest = SI->getDefaultDest();
4866 GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest, DefaultResults,
4867 DL, TTI);
4868 // If the default value is not found abort unless the default destination
4869 // is unreachable.
4870 DefaultResult =
4871 DefaultResults.size() == 1 ? DefaultResults.begin()->second : nullptr;
4872 if ((!DefaultResult &&
4873 !isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg())))
4874 return false;
4876 return true;
4879 // Helper function that checks if it is possible to transform a switch with only
4880 // two cases (or two cases + default) that produces a result into a select.
4881 // Example:
4882 // switch (a) {
4883 // case 10: %0 = icmp eq i32 %a, 10
4884 // return 10; %1 = select i1 %0, i32 10, i32 4
4885 // case 20: ----> %2 = icmp eq i32 %a, 20
4886 // return 2; %3 = select i1 %2, i32 2, i32 %1
4887 // default:
4888 // return 4;
4889 // }
4890 static Value *ConvertTwoCaseSwitch(const SwitchCaseResultVectorTy &ResultVector,
4891 Constant *DefaultResult, Value *Condition,
4892 IRBuilder<> &Builder) {
4893 assert(ResultVector.size() == 2 &&
4894 "We should have exactly two unique results at this point");
4895 // If we are selecting between only two cases transform into a simple
4896 // select or a two-way select if default is possible.
4897 if (ResultVector[0].second.size() == 1 &&
4898 ResultVector[1].second.size() == 1) {
4899 ConstantInt *const FirstCase = ResultVector[0].second[0];
4900 ConstantInt *const SecondCase = ResultVector[1].second[0];
4902 bool DefaultCanTrigger = DefaultResult;
4903 Value *SelectValue = ResultVector[1].first;
4904 if (DefaultCanTrigger) {
4905 Value *const ValueCompare =
4906 Builder.CreateICmpEQ(Condition, SecondCase, "switch.selectcmp");
4907 SelectValue = Builder.CreateSelect(ValueCompare, ResultVector[1].first,
4908 DefaultResult, "switch.select");
4910 Value *const ValueCompare =
4911 Builder.CreateICmpEQ(Condition, FirstCase, "switch.selectcmp");
4912 return Builder.CreateSelect(ValueCompare, ResultVector[0].first,
4913 SelectValue, "switch.select");
4916 return nullptr;
4919 // Helper function to cleanup a switch instruction that has been converted into
4920 // a select, fixing up PHI nodes and basic blocks.
4921 static void RemoveSwitchAfterSelectConversion(SwitchInst *SI, PHINode *PHI,
4922 Value *SelectValue,
4923 IRBuilder<> &Builder) {
4924 BasicBlock *SelectBB = SI->getParent();
4925 while (PHI->getBasicBlockIndex(SelectBB) >= 0)
4926 PHI->removeIncomingValue(SelectBB);
4927 PHI->addIncoming(SelectValue, SelectBB);
4929 Builder.CreateBr(PHI->getParent());
4931 // Remove the switch.
4932 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
4933 BasicBlock *Succ = SI->getSuccessor(i);
4935 if (Succ == PHI->getParent())
4936 continue;
4937 Succ->removePredecessor(SelectBB);
4939 SI->eraseFromParent();
4942 /// If the switch is only used to initialize one or more
4943 /// phi nodes in a common successor block with only two different
4944 /// constant values, replace the switch with select.
4945 static bool switchToSelect(SwitchInst *SI, IRBuilder<> &Builder,
4946 const DataLayout &DL,
4947 const TargetTransformInfo &TTI) {
4948 Value *const Cond = SI->getCondition();
4949 PHINode *PHI = nullptr;
4950 BasicBlock *CommonDest = nullptr;
4951 Constant *DefaultResult;
4952 SwitchCaseResultVectorTy UniqueResults;
4953 // Collect all the cases that will deliver the same value from the switch.
4954 if (!InitializeUniqueCases(SI, PHI, CommonDest, UniqueResults, DefaultResult,
4955 DL, TTI, 2, 1))
4956 return false;
4957 // Selects choose between maximum two values.
4958 if (UniqueResults.size() != 2)
4959 return false;
4960 assert(PHI != nullptr && "PHI for value select not found");
4962 Builder.SetInsertPoint(SI);
4963 Value *SelectValue =
4964 ConvertTwoCaseSwitch(UniqueResults, DefaultResult, Cond, Builder);
4965 if (SelectValue) {
4966 RemoveSwitchAfterSelectConversion(SI, PHI, SelectValue, Builder);
4967 return true;
4969 // The switch couldn't be converted into a select.
4970 return false;
4973 namespace {
4975 /// This class represents a lookup table that can be used to replace a switch.
4976 class SwitchLookupTable {
4977 public:
4978 /// Create a lookup table to use as a switch replacement with the contents
4979 /// of Values, using DefaultValue to fill any holes in the table.
4980 SwitchLookupTable(
4981 Module &M, uint64_t TableSize, ConstantInt *Offset,
4982 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
4983 Constant *DefaultValue, const DataLayout &DL, const StringRef &FuncName);
4985 /// Build instructions with Builder to retrieve the value at
4986 /// the position given by Index in the lookup table.
4987 Value *BuildLookup(Value *Index, IRBuilder<> &Builder);
4989 /// Return true if a table with TableSize elements of
4990 /// type ElementType would fit in a target-legal register.
4991 static bool WouldFitInRegister(const DataLayout &DL, uint64_t TableSize,
4992 Type *ElementType);
4994 private:
4995 // Depending on the contents of the table, it can be represented in
4996 // different ways.
4997 enum {
4998 // For tables where each element contains the same value, we just have to
4999 // store that single value and return it for each lookup.
5000 SingleValueKind,
5002 // For tables where there is a linear relationship between table index
5003 // and values. We calculate the result with a simple multiplication
5004 // and addition instead of a table lookup.
5005 LinearMapKind,
5007 // For small tables with integer elements, we can pack them into a bitmap
5008 // that fits into a target-legal register. Values are retrieved by
5009 // shift and mask operations.
5010 BitMapKind,
5012 // The table is stored as an array of values. Values are retrieved by load
5013 // instructions from the table.
5014 ArrayKind
5015 } Kind;
5017 // For SingleValueKind, this is the single value.
5018 Constant *SingleValue = nullptr;
5020 // For BitMapKind, this is the bitmap.
5021 ConstantInt *BitMap = nullptr;
5022 IntegerType *BitMapElementTy = nullptr;
5024 // For LinearMapKind, these are the constants used to derive the value.
5025 ConstantInt *LinearOffset = nullptr;
5026 ConstantInt *LinearMultiplier = nullptr;
5028 // For ArrayKind, this is the array.
5029 GlobalVariable *Array = nullptr;
5032 } // end anonymous namespace
5034 SwitchLookupTable::SwitchLookupTable(
5035 Module &M, uint64_t TableSize, ConstantInt *Offset,
5036 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
5037 Constant *DefaultValue, const DataLayout &DL, const StringRef &FuncName) {
5038 assert(Values.size() && "Can't build lookup table without values!");
5039 assert(TableSize >= Values.size() && "Can't fit values in table!");
5041 // If all values in the table are equal, this is that value.
5042 SingleValue = Values.begin()->second;
5044 Type *ValueType = Values.begin()->second->getType();
5046 // Build up the table contents.
5047 SmallVector<Constant *, 64> TableContents(TableSize);
5048 for (size_t I = 0, E = Values.size(); I != E; ++I) {
5049 ConstantInt *CaseVal = Values[I].first;
5050 Constant *CaseRes = Values[I].second;
5051 assert(CaseRes->getType() == ValueType);
5053 uint64_t Idx = (CaseVal->getValue() - Offset->getValue()).getLimitedValue();
5054 TableContents[Idx] = CaseRes;
5056 if (CaseRes != SingleValue)
5057 SingleValue = nullptr;
5060 // Fill in any holes in the table with the default result.
5061 if (Values.size() < TableSize) {
5062 assert(DefaultValue &&
5063 "Need a default value to fill the lookup table holes.");
5064 assert(DefaultValue->getType() == ValueType);
5065 for (uint64_t I = 0; I < TableSize; ++I) {
5066 if (!TableContents[I])
5067 TableContents[I] = DefaultValue;
5070 if (DefaultValue != SingleValue)
5071 SingleValue = nullptr;
5074 // If each element in the table contains the same value, we only need to store
5075 // that single value.
5076 if (SingleValue) {
5077 Kind = SingleValueKind;
5078 return;
5081 // Check if we can derive the value with a linear transformation from the
5082 // table index.
5083 if (isa<IntegerType>(ValueType)) {
5084 bool LinearMappingPossible = true;
5085 APInt PrevVal;
5086 APInt DistToPrev;
5087 assert(TableSize >= 2 && "Should be a SingleValue table.");
5088 // Check if there is the same distance between two consecutive values.
5089 for (uint64_t I = 0; I < TableSize; ++I) {
5090 ConstantInt *ConstVal = dyn_cast<ConstantInt>(TableContents[I]);
5091 if (!ConstVal) {
5092 // This is an undef. We could deal with it, but undefs in lookup tables
5093 // are very seldom. It's probably not worth the additional complexity.
5094 LinearMappingPossible = false;
5095 break;
5097 const APInt &Val = ConstVal->getValue();
5098 if (I != 0) {
5099 APInt Dist = Val - PrevVal;
5100 if (I == 1) {
5101 DistToPrev = Dist;
5102 } else if (Dist != DistToPrev) {
5103 LinearMappingPossible = false;
5104 break;
5107 PrevVal = Val;
5109 if (LinearMappingPossible) {
5110 LinearOffset = cast<ConstantInt>(TableContents[0]);
5111 LinearMultiplier = ConstantInt::get(M.getContext(), DistToPrev);
5112 Kind = LinearMapKind;
5113 ++NumLinearMaps;
5114 return;
5118 // If the type is integer and the table fits in a register, build a bitmap.
5119 if (WouldFitInRegister(DL, TableSize, ValueType)) {
5120 IntegerType *IT = cast<IntegerType>(ValueType);
5121 APInt TableInt(TableSize * IT->getBitWidth(), 0);
5122 for (uint64_t I = TableSize; I > 0; --I) {
5123 TableInt <<= IT->getBitWidth();
5124 // Insert values into the bitmap. Undef values are set to zero.
5125 if (!isa<UndefValue>(TableContents[I - 1])) {
5126 ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]);
5127 TableInt |= Val->getValue().zext(TableInt.getBitWidth());
5130 BitMap = ConstantInt::get(M.getContext(), TableInt);
5131 BitMapElementTy = IT;
5132 Kind = BitMapKind;
5133 ++NumBitMaps;
5134 return;
5137 // Store the table in an array.
5138 ArrayType *ArrayTy = ArrayType::get(ValueType, TableSize);
5139 Constant *Initializer = ConstantArray::get(ArrayTy, TableContents);
5141 Array = new GlobalVariable(M, ArrayTy, /*isConstant=*/true,
5142 GlobalVariable::PrivateLinkage, Initializer,
5143 "switch.table." + FuncName);
5144 Array->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
5145 // Set the alignment to that of an array items. We will be only loading one
5146 // value out of it.
5147 Array->setAlignment(Align(DL.getPrefTypeAlignment(ValueType)));
5148 Kind = ArrayKind;
5151 Value *SwitchLookupTable::BuildLookup(Value *Index, IRBuilder<> &Builder) {
5152 switch (Kind) {
5153 case SingleValueKind:
5154 return SingleValue;
5155 case LinearMapKind: {
5156 // Derive the result value from the input value.
5157 Value *Result = Builder.CreateIntCast(Index, LinearMultiplier->getType(),
5158 false, "switch.idx.cast");
5159 if (!LinearMultiplier->isOne())
5160 Result = Builder.CreateMul(Result, LinearMultiplier, "switch.idx.mult");
5161 if (!LinearOffset->isZero())
5162 Result = Builder.CreateAdd(Result, LinearOffset, "switch.offset");
5163 return Result;
5165 case BitMapKind: {
5166 // Type of the bitmap (e.g. i59).
5167 IntegerType *MapTy = BitMap->getType();
5169 // Cast Index to the same type as the bitmap.
5170 // Note: The Index is <= the number of elements in the table, so
5171 // truncating it to the width of the bitmask is safe.
5172 Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast");
5174 // Multiply the shift amount by the element width.
5175 ShiftAmt = Builder.CreateMul(
5176 ShiftAmt, ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()),
5177 "switch.shiftamt");
5179 // Shift down.
5180 Value *DownShifted =
5181 Builder.CreateLShr(BitMap, ShiftAmt, "switch.downshift");
5182 // Mask off.
5183 return Builder.CreateTrunc(DownShifted, BitMapElementTy, "switch.masked");
5185 case ArrayKind: {
5186 // Make sure the table index will not overflow when treated as signed.
5187 IntegerType *IT = cast<IntegerType>(Index->getType());
5188 uint64_t TableSize =
5189 Array->getInitializer()->getType()->getArrayNumElements();
5190 if (TableSize > (1ULL << (IT->getBitWidth() - 1)))
5191 Index = Builder.CreateZExt(
5192 Index, IntegerType::get(IT->getContext(), IT->getBitWidth() + 1),
5193 "switch.tableidx.zext");
5195 Value *GEPIndices[] = {Builder.getInt32(0), Index};
5196 Value *GEP = Builder.CreateInBoundsGEP(Array->getValueType(), Array,
5197 GEPIndices, "switch.gep");
5198 return Builder.CreateLoad(
5199 cast<ArrayType>(Array->getValueType())->getElementType(), GEP,
5200 "switch.load");
5203 llvm_unreachable("Unknown lookup table kind!");
5206 bool SwitchLookupTable::WouldFitInRegister(const DataLayout &DL,
5207 uint64_t TableSize,
5208 Type *ElementType) {
5209 auto *IT = dyn_cast<IntegerType>(ElementType);
5210 if (!IT)
5211 return false;
5212 // FIXME: If the type is wider than it needs to be, e.g. i8 but all values
5213 // are <= 15, we could try to narrow the type.
5215 // Avoid overflow, fitsInLegalInteger uses unsigned int for the width.
5216 if (TableSize >= UINT_MAX / IT->getBitWidth())
5217 return false;
5218 return DL.fitsInLegalInteger(TableSize * IT->getBitWidth());
5221 /// Determine whether a lookup table should be built for this switch, based on
5222 /// the number of cases, size of the table, and the types of the results.
5223 static bool
5224 ShouldBuildLookupTable(SwitchInst *SI, uint64_t TableSize,
5225 const TargetTransformInfo &TTI, const DataLayout &DL,
5226 const SmallDenseMap<PHINode *, Type *> &ResultTypes) {
5227 if (SI->getNumCases() > TableSize || TableSize >= UINT64_MAX / 10)
5228 return false; // TableSize overflowed, or mul below might overflow.
5230 bool AllTablesFitInRegister = true;
5231 bool HasIllegalType = false;
5232 for (const auto &I : ResultTypes) {
5233 Type *Ty = I.second;
5235 // Saturate this flag to true.
5236 HasIllegalType = HasIllegalType || !TTI.isTypeLegal(Ty);
5238 // Saturate this flag to false.
5239 AllTablesFitInRegister =
5240 AllTablesFitInRegister &&
5241 SwitchLookupTable::WouldFitInRegister(DL, TableSize, Ty);
5243 // If both flags saturate, we're done. NOTE: This *only* works with
5244 // saturating flags, and all flags have to saturate first due to the
5245 // non-deterministic behavior of iterating over a dense map.
5246 if (HasIllegalType && !AllTablesFitInRegister)
5247 break;
5250 // If each table would fit in a register, we should build it anyway.
5251 if (AllTablesFitInRegister)
5252 return true;
5254 // Don't build a table that doesn't fit in-register if it has illegal types.
5255 if (HasIllegalType)
5256 return false;
5258 // The table density should be at least 40%. This is the same criterion as for
5259 // jump tables, see SelectionDAGBuilder::handleJTSwitchCase.
5260 // FIXME: Find the best cut-off.
5261 return SI->getNumCases() * 10 >= TableSize * 4;
5264 /// Try to reuse the switch table index compare. Following pattern:
5265 /// \code
5266 /// if (idx < tablesize)
5267 /// r = table[idx]; // table does not contain default_value
5268 /// else
5269 /// r = default_value;
5270 /// if (r != default_value)
5271 /// ...
5272 /// \endcode
5273 /// Is optimized to:
5274 /// \code
5275 /// cond = idx < tablesize;
5276 /// if (cond)
5277 /// r = table[idx];
5278 /// else
5279 /// r = default_value;
5280 /// if (cond)
5281 /// ...
5282 /// \endcode
5283 /// Jump threading will then eliminate the second if(cond).
5284 static void reuseTableCompare(
5285 User *PhiUser, BasicBlock *PhiBlock, BranchInst *RangeCheckBranch,
5286 Constant *DefaultValue,
5287 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values) {
5288 ICmpInst *CmpInst = dyn_cast<ICmpInst>(PhiUser);
5289 if (!CmpInst)
5290 return;
5292 // We require that the compare is in the same block as the phi so that jump
5293 // threading can do its work afterwards.
5294 if (CmpInst->getParent() != PhiBlock)
5295 return;
5297 Constant *CmpOp1 = dyn_cast<Constant>(CmpInst->getOperand(1));
5298 if (!CmpOp1)
5299 return;
5301 Value *RangeCmp = RangeCheckBranch->getCondition();
5302 Constant *TrueConst = ConstantInt::getTrue(RangeCmp->getType());
5303 Constant *FalseConst = ConstantInt::getFalse(RangeCmp->getType());
5305 // Check if the compare with the default value is constant true or false.
5306 Constant *DefaultConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
5307 DefaultValue, CmpOp1, true);
5308 if (DefaultConst != TrueConst && DefaultConst != FalseConst)
5309 return;
5311 // Check if the compare with the case values is distinct from the default
5312 // compare result.
5313 for (auto ValuePair : Values) {
5314 Constant *CaseConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
5315 ValuePair.second, CmpOp1, true);
5316 if (!CaseConst || CaseConst == DefaultConst || isa<UndefValue>(CaseConst))
5317 return;
5318 assert((CaseConst == TrueConst || CaseConst == FalseConst) &&
5319 "Expect true or false as compare result.");
5322 // Check if the branch instruction dominates the phi node. It's a simple
5323 // dominance check, but sufficient for our needs.
5324 // Although this check is invariant in the calling loops, it's better to do it
5325 // at this late stage. Practically we do it at most once for a switch.
5326 BasicBlock *BranchBlock = RangeCheckBranch->getParent();
5327 for (auto PI = pred_begin(PhiBlock), E = pred_end(PhiBlock); PI != E; ++PI) {
5328 BasicBlock *Pred = *PI;
5329 if (Pred != BranchBlock && Pred->getUniquePredecessor() != BranchBlock)
5330 return;
5333 if (DefaultConst == FalseConst) {
5334 // The compare yields the same result. We can replace it.
5335 CmpInst->replaceAllUsesWith(RangeCmp);
5336 ++NumTableCmpReuses;
5337 } else {
5338 // The compare yields the same result, just inverted. We can replace it.
5339 Value *InvertedTableCmp = BinaryOperator::CreateXor(
5340 RangeCmp, ConstantInt::get(RangeCmp->getType(), 1), "inverted.cmp",
5341 RangeCheckBranch);
5342 CmpInst->replaceAllUsesWith(InvertedTableCmp);
5343 ++NumTableCmpReuses;
5347 /// If the switch is only used to initialize one or more phi nodes in a common
5348 /// successor block with different constant values, replace the switch with
5349 /// lookup tables.
5350 static bool SwitchToLookupTable(SwitchInst *SI, IRBuilder<> &Builder,
5351 const DataLayout &DL,
5352 const TargetTransformInfo &TTI) {
5353 assert(SI->getNumCases() > 1 && "Degenerate switch?");
5355 Function *Fn = SI->getParent()->getParent();
5356 // Only build lookup table when we have a target that supports it or the
5357 // attribute is not set.
5358 if (!TTI.shouldBuildLookupTables() ||
5359 (Fn->getFnAttribute("no-jump-tables").getValueAsString() == "true"))
5360 return false;
5362 // FIXME: If the switch is too sparse for a lookup table, perhaps we could
5363 // split off a dense part and build a lookup table for that.
5365 // FIXME: This creates arrays of GEPs to constant strings, which means each
5366 // GEP needs a runtime relocation in PIC code. We should just build one big
5367 // string and lookup indices into that.
5369 // Ignore switches with less than three cases. Lookup tables will not make
5370 // them faster, so we don't analyze them.
5371 if (SI->getNumCases() < 3)
5372 return false;
5374 // Figure out the corresponding result for each case value and phi node in the
5375 // common destination, as well as the min and max case values.
5376 assert(!SI->cases().empty());
5377 SwitchInst::CaseIt CI = SI->case_begin();
5378 ConstantInt *MinCaseVal = CI->getCaseValue();
5379 ConstantInt *MaxCaseVal = CI->getCaseValue();
5381 BasicBlock *CommonDest = nullptr;
5383 using ResultListTy = SmallVector<std::pair<ConstantInt *, Constant *>, 4>;
5384 SmallDenseMap<PHINode *, ResultListTy> ResultLists;
5386 SmallDenseMap<PHINode *, Constant *> DefaultResults;
5387 SmallDenseMap<PHINode *, Type *> ResultTypes;
5388 SmallVector<PHINode *, 4> PHIs;
5390 for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) {
5391 ConstantInt *CaseVal = CI->getCaseValue();
5392 if (CaseVal->getValue().slt(MinCaseVal->getValue()))
5393 MinCaseVal = CaseVal;
5394 if (CaseVal->getValue().sgt(MaxCaseVal->getValue()))
5395 MaxCaseVal = CaseVal;
5397 // Resulting value at phi nodes for this case value.
5398 using ResultsTy = SmallVector<std::pair<PHINode *, Constant *>, 4>;
5399 ResultsTy Results;
5400 if (!GetCaseResults(SI, CaseVal, CI->getCaseSuccessor(), &CommonDest,
5401 Results, DL, TTI))
5402 return false;
5404 // Append the result from this case to the list for each phi.
5405 for (const auto &I : Results) {
5406 PHINode *PHI = I.first;
5407 Constant *Value = I.second;
5408 if (!ResultLists.count(PHI))
5409 PHIs.push_back(PHI);
5410 ResultLists[PHI].push_back(std::make_pair(CaseVal, Value));
5414 // Keep track of the result types.
5415 for (PHINode *PHI : PHIs) {
5416 ResultTypes[PHI] = ResultLists[PHI][0].second->getType();
5419 uint64_t NumResults = ResultLists[PHIs[0]].size();
5420 APInt RangeSpread = MaxCaseVal->getValue() - MinCaseVal->getValue();
5421 uint64_t TableSize = RangeSpread.getLimitedValue() + 1;
5422 bool TableHasHoles = (NumResults < TableSize);
5424 // If the table has holes, we need a constant result for the default case
5425 // or a bitmask that fits in a register.
5426 SmallVector<std::pair<PHINode *, Constant *>, 4> DefaultResultsList;
5427 bool HasDefaultResults =
5428 GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest,
5429 DefaultResultsList, DL, TTI);
5431 bool NeedMask = (TableHasHoles && !HasDefaultResults);
5432 if (NeedMask) {
5433 // As an extra penalty for the validity test we require more cases.
5434 if (SI->getNumCases() < 4) // FIXME: Find best threshold value (benchmark).
5435 return false;
5436 if (!DL.fitsInLegalInteger(TableSize))
5437 return false;
5440 for (const auto &I : DefaultResultsList) {
5441 PHINode *PHI = I.first;
5442 Constant *Result = I.second;
5443 DefaultResults[PHI] = Result;
5446 if (!ShouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes))
5447 return false;
5449 // Create the BB that does the lookups.
5450 Module &Mod = *CommonDest->getParent()->getParent();
5451 BasicBlock *LookupBB = BasicBlock::Create(
5452 Mod.getContext(), "switch.lookup", CommonDest->getParent(), CommonDest);
5454 // Compute the table index value.
5455 Builder.SetInsertPoint(SI);
5456 Value *TableIndex;
5457 if (MinCaseVal->isNullValue())
5458 TableIndex = SI->getCondition();
5459 else
5460 TableIndex = Builder.CreateSub(SI->getCondition(), MinCaseVal,
5461 "switch.tableidx");
5463 // Compute the maximum table size representable by the integer type we are
5464 // switching upon.
5465 unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits();
5466 uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize;
5467 assert(MaxTableSize >= TableSize &&
5468 "It is impossible for a switch to have more entries than the max "
5469 "representable value of its input integer type's size.");
5471 // If the default destination is unreachable, or if the lookup table covers
5472 // all values of the conditional variable, branch directly to the lookup table
5473 // BB. Otherwise, check that the condition is within the case range.
5474 const bool DefaultIsReachable =
5475 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
5476 const bool GeneratingCoveredLookupTable = (MaxTableSize == TableSize);
5477 BranchInst *RangeCheckBranch = nullptr;
5479 if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
5480 Builder.CreateBr(LookupBB);
5481 // Note: We call removeProdecessor later since we need to be able to get the
5482 // PHI value for the default case in case we're using a bit mask.
5483 } else {
5484 Value *Cmp = Builder.CreateICmpULT(
5485 TableIndex, ConstantInt::get(MinCaseVal->getType(), TableSize));
5486 RangeCheckBranch =
5487 Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest());
5490 // Populate the BB that does the lookups.
5491 Builder.SetInsertPoint(LookupBB);
5493 if (NeedMask) {
5494 // Before doing the lookup, we do the hole check. The LookupBB is therefore
5495 // re-purposed to do the hole check, and we create a new LookupBB.
5496 BasicBlock *MaskBB = LookupBB;
5497 MaskBB->setName("switch.hole_check");
5498 LookupBB = BasicBlock::Create(Mod.getContext(), "switch.lookup",
5499 CommonDest->getParent(), CommonDest);
5501 // Make the mask's bitwidth at least 8-bit and a power-of-2 to avoid
5502 // unnecessary illegal types.
5503 uint64_t TableSizePowOf2 = NextPowerOf2(std::max(7ULL, TableSize - 1ULL));
5504 APInt MaskInt(TableSizePowOf2, 0);
5505 APInt One(TableSizePowOf2, 1);
5506 // Build bitmask; fill in a 1 bit for every case.
5507 const ResultListTy &ResultList = ResultLists[PHIs[0]];
5508 for (size_t I = 0, E = ResultList.size(); I != E; ++I) {
5509 uint64_t Idx = (ResultList[I].first->getValue() - MinCaseVal->getValue())
5510 .getLimitedValue();
5511 MaskInt |= One << Idx;
5513 ConstantInt *TableMask = ConstantInt::get(Mod.getContext(), MaskInt);
5515 // Get the TableIndex'th bit of the bitmask.
5516 // If this bit is 0 (meaning hole) jump to the default destination,
5517 // else continue with table lookup.
5518 IntegerType *MapTy = TableMask->getType();
5519 Value *MaskIndex =
5520 Builder.CreateZExtOrTrunc(TableIndex, MapTy, "switch.maskindex");
5521 Value *Shifted = Builder.CreateLShr(TableMask, MaskIndex, "switch.shifted");
5522 Value *LoBit = Builder.CreateTrunc(
5523 Shifted, Type::getInt1Ty(Mod.getContext()), "switch.lobit");
5524 Builder.CreateCondBr(LoBit, LookupBB, SI->getDefaultDest());
5526 Builder.SetInsertPoint(LookupBB);
5527 AddPredecessorToBlock(SI->getDefaultDest(), MaskBB, SI->getParent());
5530 if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
5531 // We cached PHINodes in PHIs. To avoid accessing deleted PHINodes later,
5532 // do not delete PHINodes here.
5533 SI->getDefaultDest()->removePredecessor(SI->getParent(),
5534 /*KeepOneInputPHIs=*/true);
5537 bool ReturnedEarly = false;
5538 for (PHINode *PHI : PHIs) {
5539 const ResultListTy &ResultList = ResultLists[PHI];
5541 // If using a bitmask, use any value to fill the lookup table holes.
5542 Constant *DV = NeedMask ? ResultLists[PHI][0].second : DefaultResults[PHI];
5543 StringRef FuncName = Fn->getName();
5544 SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultList, DV, DL,
5545 FuncName);
5547 Value *Result = Table.BuildLookup(TableIndex, Builder);
5549 // If the result is used to return immediately from the function, we want to
5550 // do that right here.
5551 if (PHI->hasOneUse() && isa<ReturnInst>(*PHI->user_begin()) &&
5552 PHI->user_back() == CommonDest->getFirstNonPHIOrDbg()) {
5553 Builder.CreateRet(Result);
5554 ReturnedEarly = true;
5555 break;
5558 // Do a small peephole optimization: re-use the switch table compare if
5559 // possible.
5560 if (!TableHasHoles && HasDefaultResults && RangeCheckBranch) {
5561 BasicBlock *PhiBlock = PHI->getParent();
5562 // Search for compare instructions which use the phi.
5563 for (auto *User : PHI->users()) {
5564 reuseTableCompare(User, PhiBlock, RangeCheckBranch, DV, ResultList);
5568 PHI->addIncoming(Result, LookupBB);
5571 if (!ReturnedEarly)
5572 Builder.CreateBr(CommonDest);
5574 // Remove the switch.
5575 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
5576 BasicBlock *Succ = SI->getSuccessor(i);
5578 if (Succ == SI->getDefaultDest())
5579 continue;
5580 Succ->removePredecessor(SI->getParent());
5582 SI->eraseFromParent();
5584 ++NumLookupTables;
5585 if (NeedMask)
5586 ++NumLookupTablesHoles;
5587 return true;
5590 static bool isSwitchDense(ArrayRef<int64_t> Values) {
5591 // See also SelectionDAGBuilder::isDense(), which this function was based on.
5592 uint64_t Diff = (uint64_t)Values.back() - (uint64_t)Values.front();
5593 uint64_t Range = Diff + 1;
5594 uint64_t NumCases = Values.size();
5595 // 40% is the default density for building a jump table in optsize/minsize mode.
5596 uint64_t MinDensity = 40;
5598 return NumCases * 100 >= Range * MinDensity;
5601 /// Try to transform a switch that has "holes" in it to a contiguous sequence
5602 /// of cases.
5604 /// A switch such as: switch(i) {case 5: case 9: case 13: case 17:} can be
5605 /// range-reduced to: switch ((i-5) / 4) {case 0: case 1: case 2: case 3:}.
5607 /// This converts a sparse switch into a dense switch which allows better
5608 /// lowering and could also allow transforming into a lookup table.
5609 static bool ReduceSwitchRange(SwitchInst *SI, IRBuilder<> &Builder,
5610 const DataLayout &DL,
5611 const TargetTransformInfo &TTI) {
5612 auto *CondTy = cast<IntegerType>(SI->getCondition()->getType());
5613 if (CondTy->getIntegerBitWidth() > 64 ||
5614 !DL.fitsInLegalInteger(CondTy->getIntegerBitWidth()))
5615 return false;
5616 // Only bother with this optimization if there are more than 3 switch cases;
5617 // SDAG will only bother creating jump tables for 4 or more cases.
5618 if (SI->getNumCases() < 4)
5619 return false;
5621 // This transform is agnostic to the signedness of the input or case values. We
5622 // can treat the case values as signed or unsigned. We can optimize more common
5623 // cases such as a sequence crossing zero {-4,0,4,8} if we interpret case values
5624 // as signed.
5625 SmallVector<int64_t,4> Values;
5626 for (auto &C : SI->cases())
5627 Values.push_back(C.getCaseValue()->getValue().getSExtValue());
5628 llvm::sort(Values);
5630 // If the switch is already dense, there's nothing useful to do here.
5631 if (isSwitchDense(Values))
5632 return false;
5634 // First, transform the values such that they start at zero and ascend.
5635 int64_t Base = Values[0];
5636 for (auto &V : Values)
5637 V -= (uint64_t)(Base);
5639 // Now we have signed numbers that have been shifted so that, given enough
5640 // precision, there are no negative values. Since the rest of the transform
5641 // is bitwise only, we switch now to an unsigned representation.
5643 // This transform can be done speculatively because it is so cheap - it
5644 // results in a single rotate operation being inserted.
5645 // FIXME: It's possible that optimizing a switch on powers of two might also
5646 // be beneficial - flag values are often powers of two and we could use a CLZ
5647 // as the key function.
5649 // countTrailingZeros(0) returns 64. As Values is guaranteed to have more than
5650 // one element and LLVM disallows duplicate cases, Shift is guaranteed to be
5651 // less than 64.
5652 unsigned Shift = 64;
5653 for (auto &V : Values)
5654 Shift = std::min(Shift, countTrailingZeros((uint64_t)V));
5655 assert(Shift < 64);
5656 if (Shift > 0)
5657 for (auto &V : Values)
5658 V = (int64_t)((uint64_t)V >> Shift);
5660 if (!isSwitchDense(Values))
5661 // Transform didn't create a dense switch.
5662 return false;
5664 // The obvious transform is to shift the switch condition right and emit a
5665 // check that the condition actually cleanly divided by GCD, i.e.
5666 // C & (1 << Shift - 1) == 0
5667 // inserting a new CFG edge to handle the case where it didn't divide cleanly.
5669 // A cheaper way of doing this is a simple ROTR(C, Shift). This performs the
5670 // shift and puts the shifted-off bits in the uppermost bits. If any of these
5671 // are nonzero then the switch condition will be very large and will hit the
5672 // default case.
5674 auto *Ty = cast<IntegerType>(SI->getCondition()->getType());
5675 Builder.SetInsertPoint(SI);
5676 auto *ShiftC = ConstantInt::get(Ty, Shift);
5677 auto *Sub = Builder.CreateSub(SI->getCondition(), ConstantInt::get(Ty, Base));
5678 auto *LShr = Builder.CreateLShr(Sub, ShiftC);
5679 auto *Shl = Builder.CreateShl(Sub, Ty->getBitWidth() - Shift);
5680 auto *Rot = Builder.CreateOr(LShr, Shl);
5681 SI->replaceUsesOfWith(SI->getCondition(), Rot);
5683 for (auto Case : SI->cases()) {
5684 auto *Orig = Case.getCaseValue();
5685 auto Sub = Orig->getValue() - APInt(Ty->getBitWidth(), Base);
5686 Case.setValue(
5687 cast<ConstantInt>(ConstantInt::get(Ty, Sub.lshr(ShiftC->getValue()))));
5689 return true;
5692 bool SimplifyCFGOpt::SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) {
5693 BasicBlock *BB = SI->getParent();
5695 if (isValueEqualityComparison(SI)) {
5696 // If we only have one predecessor, and if it is a branch on this value,
5697 // see if that predecessor totally determines the outcome of this switch.
5698 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
5699 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder))
5700 return requestResimplify();
5702 Value *Cond = SI->getCondition();
5703 if (SelectInst *Select = dyn_cast<SelectInst>(Cond))
5704 if (SimplifySwitchOnSelect(SI, Select))
5705 return requestResimplify();
5707 // If the block only contains the switch, see if we can fold the block
5708 // away into any preds.
5709 if (SI == &*BB->instructionsWithoutDebug().begin())
5710 if (FoldValueComparisonIntoPredecessors(SI, Builder))
5711 return requestResimplify();
5714 // Try to transform the switch into an icmp and a branch.
5715 if (TurnSwitchRangeIntoICmp(SI, Builder))
5716 return requestResimplify();
5718 // Remove unreachable cases.
5719 if (eliminateDeadSwitchCases(SI, Options.AC, DL))
5720 return requestResimplify();
5722 if (switchToSelect(SI, Builder, DL, TTI))
5723 return requestResimplify();
5725 if (Options.ForwardSwitchCondToPhi && ForwardSwitchConditionToPHI(SI))
5726 return requestResimplify();
5728 // The conversion from switch to lookup tables results in difficult-to-analyze
5729 // code and makes pruning branches much harder. This is a problem if the
5730 // switch expression itself can still be restricted as a result of inlining or
5731 // CVP. Therefore, only apply this transformation during late stages of the
5732 // optimisation pipeline.
5733 if (Options.ConvertSwitchToLookupTable &&
5734 SwitchToLookupTable(SI, Builder, DL, TTI))
5735 return requestResimplify();
5737 if (ReduceSwitchRange(SI, Builder, DL, TTI))
5738 return requestResimplify();
5740 return false;
5743 bool SimplifyCFGOpt::SimplifyIndirectBr(IndirectBrInst *IBI) {
5744 BasicBlock *BB = IBI->getParent();
5745 bool Changed = false;
5747 // Eliminate redundant destinations.
5748 SmallPtrSet<Value *, 8> Succs;
5749 for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
5750 BasicBlock *Dest = IBI->getDestination(i);
5751 if (!Dest->hasAddressTaken() || !Succs.insert(Dest).second) {
5752 Dest->removePredecessor(BB);
5753 IBI->removeDestination(i);
5754 --i;
5755 --e;
5756 Changed = true;
5760 if (IBI->getNumDestinations() == 0) {
5761 // If the indirectbr has no successors, change it to unreachable.
5762 new UnreachableInst(IBI->getContext(), IBI);
5763 EraseTerminatorAndDCECond(IBI);
5764 return true;
5767 if (IBI->getNumDestinations() == 1) {
5768 // If the indirectbr has one successor, change it to a direct branch.
5769 BranchInst::Create(IBI->getDestination(0), IBI);
5770 EraseTerminatorAndDCECond(IBI);
5771 return true;
5774 if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) {
5775 if (SimplifyIndirectBrOnSelect(IBI, SI))
5776 return requestResimplify();
5778 return Changed;
5781 /// Given an block with only a single landing pad and a unconditional branch
5782 /// try to find another basic block which this one can be merged with. This
5783 /// handles cases where we have multiple invokes with unique landing pads, but
5784 /// a shared handler.
5786 /// We specifically choose to not worry about merging non-empty blocks
5787 /// here. That is a PRE/scheduling problem and is best solved elsewhere. In
5788 /// practice, the optimizer produces empty landing pad blocks quite frequently
5789 /// when dealing with exception dense code. (see: instcombine, gvn, if-else
5790 /// sinking in this file)
5792 /// This is primarily a code size optimization. We need to avoid performing
5793 /// any transform which might inhibit optimization (such as our ability to
5794 /// specialize a particular handler via tail commoning). We do this by not
5795 /// merging any blocks which require us to introduce a phi. Since the same
5796 /// values are flowing through both blocks, we don't lose any ability to
5797 /// specialize. If anything, we make such specialization more likely.
5799 /// TODO - This transformation could remove entries from a phi in the target
5800 /// block when the inputs in the phi are the same for the two blocks being
5801 /// merged. In some cases, this could result in removal of the PHI entirely.
5802 static bool TryToMergeLandingPad(LandingPadInst *LPad, BranchInst *BI,
5803 BasicBlock *BB) {
5804 auto Succ = BB->getUniqueSuccessor();
5805 assert(Succ);
5806 // If there's a phi in the successor block, we'd likely have to introduce
5807 // a phi into the merged landing pad block.
5808 if (isa<PHINode>(*Succ->begin()))
5809 return false;
5811 for (BasicBlock *OtherPred : predecessors(Succ)) {
5812 if (BB == OtherPred)
5813 continue;
5814 BasicBlock::iterator I = OtherPred->begin();
5815 LandingPadInst *LPad2 = dyn_cast<LandingPadInst>(I);
5816 if (!LPad2 || !LPad2->isIdenticalTo(LPad))
5817 continue;
5818 for (++I; isa<DbgInfoIntrinsic>(I); ++I)
5820 BranchInst *BI2 = dyn_cast<BranchInst>(I);
5821 if (!BI2 || !BI2->isIdenticalTo(BI))
5822 continue;
5824 // We've found an identical block. Update our predecessors to take that
5825 // path instead and make ourselves dead.
5826 SmallPtrSet<BasicBlock *, 16> Preds;
5827 Preds.insert(pred_begin(BB), pred_end(BB));
5828 for (BasicBlock *Pred : Preds) {
5829 InvokeInst *II = cast<InvokeInst>(Pred->getTerminator());
5830 assert(II->getNormalDest() != BB && II->getUnwindDest() == BB &&
5831 "unexpected successor");
5832 II->setUnwindDest(OtherPred);
5835 // The debug info in OtherPred doesn't cover the merged control flow that
5836 // used to go through BB. We need to delete it or update it.
5837 for (auto I = OtherPred->begin(), E = OtherPred->end(); I != E;) {
5838 Instruction &Inst = *I;
5839 I++;
5840 if (isa<DbgInfoIntrinsic>(Inst))
5841 Inst.eraseFromParent();
5844 SmallPtrSet<BasicBlock *, 16> Succs;
5845 Succs.insert(succ_begin(BB), succ_end(BB));
5846 for (BasicBlock *Succ : Succs) {
5847 Succ->removePredecessor(BB);
5850 IRBuilder<> Builder(BI);
5851 Builder.CreateUnreachable();
5852 BI->eraseFromParent();
5853 return true;
5855 return false;
5858 bool SimplifyCFGOpt::SimplifyUncondBranch(BranchInst *BI,
5859 IRBuilder<> &Builder) {
5860 BasicBlock *BB = BI->getParent();
5861 BasicBlock *Succ = BI->getSuccessor(0);
5863 // If the Terminator is the only non-phi instruction, simplify the block.
5864 // If LoopHeader is provided, check if the block or its successor is a loop
5865 // header. (This is for early invocations before loop simplify and
5866 // vectorization to keep canonical loop forms for nested loops. These blocks
5867 // can be eliminated when the pass is invoked later in the back-end.)
5868 // Note that if BB has only one predecessor then we do not introduce new
5869 // backedge, so we can eliminate BB.
5870 bool NeedCanonicalLoop =
5871 Options.NeedCanonicalLoop &&
5872 (LoopHeaders && BB->hasNPredecessorsOrMore(2) &&
5873 (LoopHeaders->count(BB) || LoopHeaders->count(Succ)));
5874 BasicBlock::iterator I = BB->getFirstNonPHIOrDbg()->getIterator();
5875 if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
5876 !NeedCanonicalLoop && TryToSimplifyUncondBranchFromEmptyBlock(BB))
5877 return true;
5879 // If the only instruction in the block is a seteq/setne comparison against a
5880 // constant, try to simplify the block.
5881 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I))
5882 if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
5883 for (++I; isa<DbgInfoIntrinsic>(I); ++I)
5885 if (I->isTerminator() &&
5886 tryToSimplifyUncondBranchWithICmpInIt(ICI, Builder))
5887 return true;
5890 // See if we can merge an empty landing pad block with another which is
5891 // equivalent.
5892 if (LandingPadInst *LPad = dyn_cast<LandingPadInst>(I)) {
5893 for (++I; isa<DbgInfoIntrinsic>(I); ++I)
5895 if (I->isTerminator() && TryToMergeLandingPad(LPad, BI, BB))
5896 return true;
5899 // If this basic block is ONLY a compare and a branch, and if a predecessor
5900 // branches to us and our successor, fold the comparison into the
5901 // predecessor and use logical operations to update the incoming value
5902 // for PHI nodes in common successor.
5903 if (FoldBranchToCommonDest(BI, nullptr, Options.BonusInstThreshold))
5904 return requestResimplify();
5905 return false;
5908 static BasicBlock *allPredecessorsComeFromSameSource(BasicBlock *BB) {
5909 BasicBlock *PredPred = nullptr;
5910 for (auto *P : predecessors(BB)) {
5911 BasicBlock *PPred = P->getSinglePredecessor();
5912 if (!PPred || (PredPred && PredPred != PPred))
5913 return nullptr;
5914 PredPred = PPred;
5916 return PredPred;
5919 bool SimplifyCFGOpt::SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) {
5920 BasicBlock *BB = BI->getParent();
5921 const Function *Fn = BB->getParent();
5922 if (Fn && Fn->hasFnAttribute(Attribute::OptForFuzzing))
5923 return false;
5925 // Conditional branch
5926 if (isValueEqualityComparison(BI)) {
5927 // If we only have one predecessor, and if it is a branch on this value,
5928 // see if that predecessor totally determines the outcome of this
5929 // switch.
5930 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
5931 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder))
5932 return requestResimplify();
5934 // This block must be empty, except for the setcond inst, if it exists.
5935 // Ignore dbg intrinsics.
5936 auto I = BB->instructionsWithoutDebug().begin();
5937 if (&*I == BI) {
5938 if (FoldValueComparisonIntoPredecessors(BI, Builder))
5939 return requestResimplify();
5940 } else if (&*I == cast<Instruction>(BI->getCondition())) {
5941 ++I;
5942 if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder))
5943 return requestResimplify();
5947 // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction.
5948 if (SimplifyBranchOnICmpChain(BI, Builder, DL))
5949 return true;
5951 // If this basic block has dominating predecessor blocks and the dominating
5952 // blocks' conditions imply BI's condition, we know the direction of BI.
5953 Optional<bool> Imp = isImpliedByDomCondition(BI->getCondition(), BI, DL);
5954 if (Imp) {
5955 // Turn this into a branch on constant.
5956 auto *OldCond = BI->getCondition();
5957 ConstantInt *TorF = *Imp ? ConstantInt::getTrue(BB->getContext())
5958 : ConstantInt::getFalse(BB->getContext());
5959 BI->setCondition(TorF);
5960 RecursivelyDeleteTriviallyDeadInstructions(OldCond);
5961 return requestResimplify();
5964 // If this basic block is ONLY a compare and a branch, and if a predecessor
5965 // branches to us and one of our successors, fold the comparison into the
5966 // predecessor and use logical operations to pick the right destination.
5967 if (FoldBranchToCommonDest(BI, nullptr, Options.BonusInstThreshold))
5968 return requestResimplify();
5970 // We have a conditional branch to two blocks that are only reachable
5971 // from BI. We know that the condbr dominates the two blocks, so see if
5972 // there is any identical code in the "then" and "else" blocks. If so, we
5973 // can hoist it up to the branching block.
5974 if (BI->getSuccessor(0)->getSinglePredecessor()) {
5975 if (BI->getSuccessor(1)->getSinglePredecessor()) {
5976 if (HoistThenElseCodeToIf(BI, TTI))
5977 return requestResimplify();
5978 } else {
5979 // If Successor #1 has multiple preds, we may be able to conditionally
5980 // execute Successor #0 if it branches to Successor #1.
5981 Instruction *Succ0TI = BI->getSuccessor(0)->getTerminator();
5982 if (Succ0TI->getNumSuccessors() == 1 &&
5983 Succ0TI->getSuccessor(0) == BI->getSuccessor(1))
5984 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0), TTI))
5985 return requestResimplify();
5987 } else if (BI->getSuccessor(1)->getSinglePredecessor()) {
5988 // If Successor #0 has multiple preds, we may be able to conditionally
5989 // execute Successor #1 if it branches to Successor #0.
5990 Instruction *Succ1TI = BI->getSuccessor(1)->getTerminator();
5991 if (Succ1TI->getNumSuccessors() == 1 &&
5992 Succ1TI->getSuccessor(0) == BI->getSuccessor(0))
5993 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1), TTI))
5994 return requestResimplify();
5997 // If this is a branch on a phi node in the current block, thread control
5998 // through this block if any PHI node entries are constants.
5999 if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
6000 if (PN->getParent() == BI->getParent())
6001 if (FoldCondBranchOnPHI(BI, DL, Options.AC))
6002 return requestResimplify();
6004 // Scan predecessor blocks for conditional branches.
6005 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
6006 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
6007 if (PBI != BI && PBI->isConditional())
6008 if (SimplifyCondBranchToCondBranch(PBI, BI, DL, TTI))
6009 return requestResimplify();
6011 // Look for diamond patterns.
6012 if (MergeCondStores)
6013 if (BasicBlock *PrevBB = allPredecessorsComeFromSameSource(BB))
6014 if (BranchInst *PBI = dyn_cast<BranchInst>(PrevBB->getTerminator()))
6015 if (PBI != BI && PBI->isConditional())
6016 if (mergeConditionalStores(PBI, BI, DL, TTI))
6017 return requestResimplify();
6019 return false;
6022 /// Check if passing a value to an instruction will cause undefined behavior.
6023 static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I) {
6024 Constant *C = dyn_cast<Constant>(V);
6025 if (!C)
6026 return false;
6028 if (I->use_empty())
6029 return false;
6031 if (C->isNullValue() || isa<UndefValue>(C)) {
6032 // Only look at the first use, avoid hurting compile time with long uselists
6033 User *Use = *I->user_begin();
6035 // Now make sure that there are no instructions in between that can alter
6036 // control flow (eg. calls)
6037 for (BasicBlock::iterator
6038 i = ++BasicBlock::iterator(I),
6039 UI = BasicBlock::iterator(dyn_cast<Instruction>(Use));
6040 i != UI; ++i)
6041 if (i == I->getParent()->end() || i->mayHaveSideEffects())
6042 return false;
6044 // Look through GEPs. A load from a GEP derived from NULL is still undefined
6045 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use))
6046 if (GEP->getPointerOperand() == I)
6047 return passingValueIsAlwaysUndefined(V, GEP);
6049 // Look through bitcasts.
6050 if (BitCastInst *BC = dyn_cast<BitCastInst>(Use))
6051 return passingValueIsAlwaysUndefined(V, BC);
6053 // Load from null is undefined.
6054 if (LoadInst *LI = dyn_cast<LoadInst>(Use))
6055 if (!LI->isVolatile())
6056 return !NullPointerIsDefined(LI->getFunction(),
6057 LI->getPointerAddressSpace());
6059 // Store to null is undefined.
6060 if (StoreInst *SI = dyn_cast<StoreInst>(Use))
6061 if (!SI->isVolatile())
6062 return (!NullPointerIsDefined(SI->getFunction(),
6063 SI->getPointerAddressSpace())) &&
6064 SI->getPointerOperand() == I;
6066 // A call to null is undefined.
6067 if (auto CS = CallSite(Use))
6068 return !NullPointerIsDefined(CS->getFunction()) &&
6069 CS.getCalledValue() == I;
6071 return false;
6074 /// If BB has an incoming value that will always trigger undefined behavior
6075 /// (eg. null pointer dereference), remove the branch leading here.
6076 static bool removeUndefIntroducingPredecessor(BasicBlock *BB) {
6077 for (PHINode &PHI : BB->phis())
6078 for (unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i)
6079 if (passingValueIsAlwaysUndefined(PHI.getIncomingValue(i), &PHI)) {
6080 Instruction *T = PHI.getIncomingBlock(i)->getTerminator();
6081 IRBuilder<> Builder(T);
6082 if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
6083 BB->removePredecessor(PHI.getIncomingBlock(i));
6084 // Turn uncoditional branches into unreachables and remove the dead
6085 // destination from conditional branches.
6086 if (BI->isUnconditional())
6087 Builder.CreateUnreachable();
6088 else
6089 Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1)
6090 : BI->getSuccessor(0));
6091 BI->eraseFromParent();
6092 return true;
6094 // TODO: SwitchInst.
6097 return false;
6100 bool SimplifyCFGOpt::simplifyOnce(BasicBlock *BB) {
6101 bool Changed = false;
6103 assert(BB && BB->getParent() && "Block not embedded in function!");
6104 assert(BB->getTerminator() && "Degenerate basic block encountered!");
6106 // Remove basic blocks that have no predecessors (except the entry block)...
6107 // or that just have themself as a predecessor. These are unreachable.
6108 if ((pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()) ||
6109 BB->getSinglePredecessor() == BB) {
6110 LLVM_DEBUG(dbgs() << "Removing BB: \n" << *BB);
6111 DeleteDeadBlock(BB);
6112 return true;
6115 // Check to see if we can constant propagate this terminator instruction
6116 // away...
6117 Changed |= ConstantFoldTerminator(BB, true);
6119 // Check for and eliminate duplicate PHI nodes in this block.
6120 Changed |= EliminateDuplicatePHINodes(BB);
6122 // Check for and remove branches that will always cause undefined behavior.
6123 Changed |= removeUndefIntroducingPredecessor(BB);
6125 // Merge basic blocks into their predecessor if there is only one distinct
6126 // pred, and if there is only one distinct successor of the predecessor, and
6127 // if there are no PHI nodes.
6128 if (MergeBlockIntoPredecessor(BB))
6129 return true;
6131 if (SinkCommon && Options.SinkCommonInsts)
6132 Changed |= SinkCommonCodeFromPredecessors(BB);
6134 IRBuilder<> Builder(BB);
6136 // If there is a trivial two-entry PHI node in this basic block, and we can
6137 // eliminate it, do so now.
6138 if (auto *PN = dyn_cast<PHINode>(BB->begin()))
6139 if (PN->getNumIncomingValues() == 2)
6140 Changed |= FoldTwoEntryPHINode(PN, TTI, DL);
6142 Builder.SetInsertPoint(BB->getTerminator());
6143 if (auto *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
6144 if (BI->isUnconditional()) {
6145 if (SimplifyUncondBranch(BI, Builder))
6146 return true;
6147 } else {
6148 if (SimplifyCondBranch(BI, Builder))
6149 return true;
6151 } else if (auto *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
6152 if (SimplifyReturn(RI, Builder))
6153 return true;
6154 } else if (auto *RI = dyn_cast<ResumeInst>(BB->getTerminator())) {
6155 if (SimplifyResume(RI, Builder))
6156 return true;
6157 } else if (auto *RI = dyn_cast<CleanupReturnInst>(BB->getTerminator())) {
6158 if (SimplifyCleanupReturn(RI))
6159 return true;
6160 } else if (auto *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
6161 if (SimplifySwitch(SI, Builder))
6162 return true;
6163 } else if (auto *UI = dyn_cast<UnreachableInst>(BB->getTerminator())) {
6164 if (SimplifyUnreachable(UI))
6165 return true;
6166 } else if (auto *IBI = dyn_cast<IndirectBrInst>(BB->getTerminator())) {
6167 if (SimplifyIndirectBr(IBI))
6168 return true;
6171 return Changed;
6174 bool SimplifyCFGOpt::run(BasicBlock *BB) {
6175 bool Changed = false;
6177 // Repeated simplify BB as long as resimplification is requested.
6178 do {
6179 Resimplify = false;
6181 // Perform one round of simplifcation. Resimplify flag will be set if
6182 // another iteration is requested.
6183 Changed |= simplifyOnce(BB);
6184 } while (Resimplify);
6186 return Changed;
6189 bool llvm::simplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI,
6190 const SimplifyCFGOptions &Options,
6191 SmallPtrSetImpl<BasicBlock *> *LoopHeaders) {
6192 return SimplifyCFGOpt(TTI, BB->getModule()->getDataLayout(), LoopHeaders,
6193 Options)
6194 .run(BB);