1//===- SimplifyCFG.cpp - Code to perform CFG simplification ---------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// Peephole optimize the CFG.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/ADT/APInt.h"
14#include "llvm/ADT/ArrayRef.h"
15#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/MapVector.h"
17#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/Sequence.h"
19#include "llvm/ADT/SetOperations.h"
20#include "llvm/ADT/SetVector.h"
21#include "llvm/ADT/SmallPtrSet.h"
22#include "llvm/ADT/SmallVector.h"
23#include "llvm/ADT/Statistic.h"
24#include "llvm/ADT/StringRef.h"
25#include "llvm/Analysis/AssumptionCache.h"
26#include "llvm/Analysis/CaptureTracking.h"
27#include "llvm/Analysis/ConstantFolding.h"
28#include "llvm/Analysis/DomTreeUpdater.h"
29#include "llvm/Analysis/GuardUtils.h"
30#include "llvm/Analysis/InstructionSimplify.h"
31#include "llvm/Analysis/Loads.h"
32#include "llvm/Analysis/MemorySSA.h"
33#include "llvm/Analysis/MemorySSAUpdater.h"
34#include "llvm/Analysis/TargetTransformInfo.h"
35#include "llvm/Analysis/ValueTracking.h"
36#include "llvm/IR/Attributes.h"
37#include "llvm/IR/BasicBlock.h"
38#include "llvm/IR/CFG.h"
39#include "llvm/IR/Constant.h"
40#include "llvm/IR/ConstantRange.h"
41#include "llvm/IR/Constants.h"
42#include "llvm/IR/DataLayout.h"
43#include "llvm/IR/DebugInfo.h"
44#include "llvm/IR/DerivedTypes.h"
45#include "llvm/IR/Function.h"
46#include "llvm/IR/GlobalValue.h"
47#include "llvm/IR/GlobalVariable.h"
48#include "llvm/IR/IRBuilder.h"
49#include "llvm/IR/InstrTypes.h"
50#include "llvm/IR/Instruction.h"
51#include "llvm/IR/Instructions.h"
52#include "llvm/IR/IntrinsicInst.h"
53#include "llvm/IR/LLVMContext.h"
54#include "llvm/IR/MDBuilder.h"
55#include "llvm/IR/MemoryModelRelaxationAnnotations.h"
56#include "llvm/IR/Metadata.h"
57#include "llvm/IR/Module.h"
58#include "llvm/IR/NoFolder.h"
59#include "llvm/IR/Operator.h"
60#include "llvm/IR/PatternMatch.h"
61#include "llvm/IR/ProfDataUtils.h"
62#include "llvm/IR/Type.h"
63#include "llvm/IR/Use.h"
64#include "llvm/IR/User.h"
65#include "llvm/IR/Value.h"
66#include "llvm/IR/ValueHandle.h"
67#include "llvm/Support/BranchProbability.h"
68#include "llvm/Support/Casting.h"
69#include "llvm/Support/CommandLine.h"
70#include "llvm/Support/Debug.h"
71#include "llvm/Support/ErrorHandling.h"
72#include "llvm/Support/KnownBits.h"
73#include "llvm/Support/MathExtras.h"
74#include "llvm/Support/raw_ostream.h"
75#include "llvm/Transforms/Utils/BasicBlockUtils.h"
76#include "llvm/Transforms/Utils/Cloning.h"
77#include "llvm/Transforms/Utils/Local.h"
78#include "llvm/Transforms/Utils/LockstepReverseIterator.h"
79#include "llvm/Transforms/Utils/ValueMapper.h"
80#include <algorithm>
81#include <cassert>
82#include <climits>
83#include <cstddef>
84#include <cstdint>
85#include <iterator>
86#include <map>
87#include <optional>
88#include <set>
89#include <tuple>
90#include <utility>
91#include <vector>
92
93using namespace llvm;
94using namespace PatternMatch;
95
96#define DEBUG_TYPE "simplifycfg"
97
98namespace llvm {
99
100cl::opt<bool> RequireAndPreserveDomTree(
101 "simplifycfg-require-and-preserve-domtree", cl::Hidden,
102
103 cl::desc(
104 "Temporary development switch used to gradually uplift SimplifyCFG "
105 "into preserving DomTree,"));
106
107// Chosen as 2 so as to be cheap, but still to have enough power to fold
108// a select, so the "clamp" idiom (of a min followed by a max) will be caught.
109// To catch this, we need to fold a compare and a select, hence '2' being the
110// minimum reasonable default.
111static cl::opt<unsigned> PHINodeFoldingThreshold(
112 "phi-node-folding-threshold", cl::Hidden, cl::init(Val: 2),
113 cl::desc(
114 "Control the amount of phi node folding to perform (default = 2)"));
115
116static cl::opt<unsigned> TwoEntryPHINodeFoldingThreshold(
117 "two-entry-phi-node-folding-threshold", cl::Hidden, cl::init(Val: 4),
118 cl::desc("Control the maximal total instruction cost that we are willing "
119 "to speculatively execute to fold a 2-entry PHI node into a "
120 "select (default = 4)"));
121
122static cl::opt<bool>
123 HoistCommon("simplifycfg-hoist-common", cl::Hidden, cl::init(Val: true),
124 cl::desc("Hoist common instructions up to the parent block"));
125
126static cl::opt<bool> HoistLoadsWithCondFaulting(
127 "simplifycfg-hoist-loads-with-cond-faulting", cl::Hidden, cl::init(Val: true),
128 cl::desc("Hoist loads if the target supports conditional faulting"));
129
130static cl::opt<bool> HoistStoresWithCondFaulting(
131 "simplifycfg-hoist-stores-with-cond-faulting", cl::Hidden, cl::init(Val: true),
132 cl::desc("Hoist stores if the target supports conditional faulting"));
133
134static cl::opt<unsigned> HoistLoadsStoresWithCondFaultingThreshold(
135 "hoist-loads-stores-with-cond-faulting-threshold", cl::Hidden, cl::init(Val: 6),
136 cl::desc("Control the maximal conditional load/store that we are willing "
137 "to speculatively execute to eliminate conditional branch "
138 "(default = 6)"));
139
140static cl::opt<unsigned>
141 HoistCommonSkipLimit("simplifycfg-hoist-common-skip-limit", cl::Hidden,
142 cl::init(Val: 20),
143 cl::desc("Allow reordering across at most this many "
144 "instructions when hoisting"));
145
146static cl::opt<bool>
147 SinkCommon("simplifycfg-sink-common", cl::Hidden, cl::init(Val: true),
148 cl::desc("Sink common instructions down to the end block"));
149
150static cl::opt<bool> HoistCondStores(
151 "simplifycfg-hoist-cond-stores", cl::Hidden, cl::init(Val: true),
152 cl::desc("Hoist conditional stores if an unconditional store precedes"));
153
154static cl::opt<bool> MergeCondStores(
155 "simplifycfg-merge-cond-stores", cl::Hidden, cl::init(Val: true),
156 cl::desc("Hoist conditional stores even if an unconditional store does not "
157 "precede - hoist multiple conditional stores into a single "
158 "predicated store"));
159
160static cl::opt<bool> MergeCondStoresAggressively(
161 "simplifycfg-merge-cond-stores-aggressively", cl::Hidden, cl::init(Val: false),
162 cl::desc("When merging conditional stores, do so even if the resultant "
163 "basic blocks are unlikely to be if-converted as a result"));
164
165static cl::opt<bool> SpeculateOneExpensiveInst(
166 "speculate-one-expensive-inst", cl::Hidden, cl::init(Val: true),
167 cl::desc("Allow exactly one expensive instruction to be speculatively "
168 "executed"));
169
170static cl::opt<unsigned> MaxSpeculationDepth(
171 "max-speculation-depth", cl::Hidden, cl::init(Val: 10),
172 cl::desc("Limit maximum recursion depth when calculating costs of "
173 "speculatively executed instructions"));
174
175static cl::opt<int>
176 MaxSmallBlockSize("simplifycfg-max-small-block-size", cl::Hidden,
177 cl::init(Val: 10),
178 cl::desc("Max size of a block which is still considered "
179 "small enough to thread through"));
180
181// Two is chosen to allow one negation and a logical combine.
182static cl::opt<unsigned>
183 BranchFoldThreshold("simplifycfg-branch-fold-threshold", cl::Hidden,
184 cl::init(Val: 2),
185 cl::desc("Maximum cost of combining conditions when "
186 "folding branches"));
187
188static cl::opt<unsigned> BranchFoldToCommonDestVectorMultiplier(
189 "simplifycfg-branch-fold-common-dest-vector-multiplier", cl::Hidden,
190 cl::init(Val: 2),
191 cl::desc("Multiplier to apply to threshold when determining whether or not "
192 "to fold branch to common destination when vector operations are "
193 "present"));
194
195static cl::opt<bool> EnableMergeCompatibleInvokes(
196 "simplifycfg-merge-compatible-invokes", cl::Hidden, cl::init(Val: true),
197 cl::desc("Allow SimplifyCFG to merge invokes together when appropriate"));
198
199static cl::opt<unsigned> MaxSwitchCasesPerResult(
200 "max-switch-cases-per-result", cl::Hidden, cl::init(Val: 16),
201 cl::desc("Limit cases to analyze when converting a switch to select"));
202
203static cl::opt<unsigned> MaxJumpThreadingLiveBlocks(
204 "max-jump-threading-live-blocks", cl::Hidden, cl::init(Val: 24),
205 cl::desc("Limit number of blocks a define in a threaded block is allowed "
206 "to be live in"));
207
208extern cl::opt<bool> ProfcheckDisableMetadataFixes;
209
210} // end namespace llvm
211
212STATISTIC(NumBitMaps, "Number of switch instructions turned into bitmaps");
213STATISTIC(NumLinearMaps,
214 "Number of switch instructions turned into linear mapping");
215STATISTIC(NumLookupTables,
216 "Number of switch instructions turned into lookup tables");
217STATISTIC(
218 NumLookupTablesHoles,
219 "Number of switch instructions turned into lookup tables (holes checked)");
220STATISTIC(NumTableCmpReuses, "Number of reused switch table lookup compares");
221STATISTIC(NumFoldValueComparisonIntoPredecessors,
222 "Number of value comparisons folded into predecessor basic blocks");
223STATISTIC(NumFoldBranchToCommonDest,
224 "Number of branches folded into predecessor basic block");
225STATISTIC(
226 NumHoistCommonCode,
227 "Number of common instruction 'blocks' hoisted up to the begin block");
228STATISTIC(NumHoistCommonInstrs,
229 "Number of common instructions hoisted up to the begin block");
230STATISTIC(NumSinkCommonCode,
231 "Number of common instruction 'blocks' sunk down to the end block");
232STATISTIC(NumSinkCommonInstrs,
233 "Number of common instructions sunk down to the end block");
234STATISTIC(NumSpeculations, "Number of speculative executed instructions");
235STATISTIC(NumInvokes,
236 "Number of invokes with empty resume blocks simplified into calls");
237STATISTIC(NumInvokesMerged, "Number of invokes that were merged together");
238STATISTIC(NumInvokeSetsFormed, "Number of invoke sets that were formed");
239
240namespace {
241
242// The first field contains the value that the switch produces when a certain
243// case group is selected, and the second field is a vector containing the
244// cases composing the case group.
245using SwitchCaseResultVectorTy =
246 SmallVector<std::pair<Constant *, SmallVector<ConstantInt *, 4>>, 2>;
247
248// The first field contains the phi node that generates a result of the switch
249// and the second field contains the value generated for a certain case in the
250// switch for that PHI.
251using SwitchCaseResultsTy = SmallVector<std::pair<PHINode *, Constant *>, 4>;
252
253/// ValueEqualityComparisonCase - Represents a case of a switch.
254struct ValueEqualityComparisonCase {
255 ConstantInt *Value;
256 BasicBlock *Dest;
257
258 ValueEqualityComparisonCase(ConstantInt *Value, BasicBlock *Dest)
259 : Value(Value), Dest(Dest) {}
260
261 bool operator<(ValueEqualityComparisonCase RHS) const {
262 // Comparing pointers is ok as we only rely on the order for uniquing.
263 return Value < RHS.Value;
264 }
265
266 bool operator==(BasicBlock *RHSDest) const { return Dest == RHSDest; }
267};
268
269class SimplifyCFGOpt {
270 const TargetTransformInfo &TTI;
271 DomTreeUpdater *DTU;
272 const DataLayout &DL;
273 ArrayRef<WeakVH> LoopHeaders;
274 const SimplifyCFGOptions &Options;
275 bool Resimplify;
276
277 Value *isValueEqualityComparison(Instruction *TI);
278 BasicBlock *getValueEqualityComparisonCases(
279 Instruction *TI, std::vector<ValueEqualityComparisonCase> &Cases);
280 bool simplifyEqualityComparisonWithOnlyPredecessor(Instruction *TI,
281 BasicBlock *Pred,
282 IRBuilder<> &Builder);
283 bool performValueComparisonIntoPredecessorFolding(Instruction *TI, Value *&CV,
284 Instruction *PTI,
285 IRBuilder<> &Builder);
286 bool foldValueComparisonIntoPredecessors(Instruction *TI,
287 IRBuilder<> &Builder);
288
289 bool simplifyResume(ResumeInst *RI, IRBuilder<> &Builder);
290 bool simplifySingleResume(ResumeInst *RI);
291 bool simplifyCommonResume(ResumeInst *RI);
292 bool simplifyCleanupReturn(CleanupReturnInst *RI);
293 bool simplifyUnreachable(UnreachableInst *UI);
294 bool simplifySwitch(SwitchInst *SI, IRBuilder<> &Builder);
295 bool simplifyDuplicateSwitchArms(SwitchInst *SI, DomTreeUpdater *DTU);
296 bool simplifyIndirectBr(IndirectBrInst *IBI);
297 bool simplifyUncondBranch(UncondBrInst *BI, IRBuilder<> &Builder);
298 bool simplifyCondBranch(CondBrInst *BI, IRBuilder<> &Builder);
299 bool foldCondBranchOnValueKnownInPredecessor(CondBrInst *BI);
300
301 bool tryToSimplifyUncondBranchWithICmpInIt(ICmpInst *ICI,
302 IRBuilder<> &Builder);
303 bool tryToSimplifyUncondBranchWithICmpSelectInIt(ICmpInst *ICI,
304 SelectInst *Select,
305 IRBuilder<> &Builder);
306 bool hoistCommonCodeFromSuccessors(Instruction *TI, bool AllInstsEqOnly);
307 bool hoistSuccIdenticalTerminatorToSwitchOrIf(
308 Instruction *TI, Instruction *I1,
309 SmallVectorImpl<Instruction *> &OtherSuccTIs,
310 ArrayRef<BasicBlock *> UniqueSuccessors);
311 bool speculativelyExecuteBB(CondBrInst *BI, BasicBlock *ThenBB);
312 bool simplifyTerminatorOnSelect(Instruction *OldTerm, Value *Cond,
313 BasicBlock *TrueBB, BasicBlock *FalseBB,
314 uint32_t TrueWeight, uint32_t FalseWeight);
315 bool simplifyBranchOnICmpChain(CondBrInst *BI, IRBuilder<> &Builder,
316 const DataLayout &DL);
317 bool simplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select);
318 bool simplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI);
319 bool turnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder);
320 bool simplifyDuplicatePredecessors(BasicBlock *Succ, DomTreeUpdater *DTU);
321
322public:
323 SimplifyCFGOpt(const TargetTransformInfo &TTI, DomTreeUpdater *DTU,
324 const DataLayout &DL, ArrayRef<WeakVH> LoopHeaders,
325 const SimplifyCFGOptions &Opts)
326 : TTI(TTI), DTU(DTU), DL(DL), LoopHeaders(LoopHeaders), Options(Opts) {
327 assert((!DTU || !DTU->hasPostDomTree()) &&
328 "SimplifyCFG is not yet capable of maintaining validity of a "
329 "PostDomTree, so don't ask for it.");
330 }
331
332 bool simplifyOnce(BasicBlock *BB);
333 bool run(BasicBlock *BB);
334
335 // Helper to set Resimplify and return change indication.
336 bool requestResimplify() {
337 Resimplify = true;
338 return true;
339 }
340};
341
342// we synthesize a || b as select a, true, b
343// we synthesize a && b as select a, b, false
344// this function determines if SI is playing one of those roles.
345[[maybe_unused]] bool
346isSelectInRoleOfConjunctionOrDisjunction(const SelectInst *SI) {
347 return ((isa<ConstantInt>(Val: SI->getTrueValue()) &&
348 (dyn_cast<ConstantInt>(Val: SI->getTrueValue())->isOne())) ||
349 (isa<ConstantInt>(Val: SI->getFalseValue()) &&
350 (dyn_cast<ConstantInt>(Val: SI->getFalseValue())->isNullValue())));
351}
352
353} // end anonymous namespace
354
355/// Return true if all the PHI nodes in the basic block \p BB
356/// receive compatible (identical) incoming values when coming from
357/// all of the predecessor blocks that are specified in \p IncomingBlocks.
358///
359/// Note that if the values aren't exactly identical, but \p EquivalenceSet
360/// is provided, and *both* of the values are present in the set,
361/// then they are considered equal.
362static bool incomingValuesAreCompatible(
363 BasicBlock *BB, ArrayRef<BasicBlock *> IncomingBlocks,
364 SmallPtrSetImpl<Value *> *EquivalenceSet = nullptr) {
365 assert(IncomingBlocks.size() == 2 &&
366 "Only for a pair of incoming blocks at the time!");
367
368 // FIXME: it is okay if one of the incoming values is an `undef` value,
369 // iff the other incoming value is guaranteed to be a non-poison value.
370 // FIXME: it is okay if one of the incoming values is a `poison` value.
371 return all_of(Range: BB->phis(), P: [IncomingBlocks, EquivalenceSet](PHINode &PN) {
372 Value *IV0 = PN.getIncomingValueForBlock(BB: IncomingBlocks[0]);
373 Value *IV1 = PN.getIncomingValueForBlock(BB: IncomingBlocks[1]);
374 if (IV0 == IV1)
375 return true;
376 if (EquivalenceSet && EquivalenceSet->contains(Ptr: IV0) &&
377 EquivalenceSet->contains(Ptr: IV1))
378 return true;
379 return false;
380 });
381}
382
383/// Return true if it is safe to merge these two
384/// terminator instructions together.
385static bool
386safeToMergeTerminators(Instruction *SI1, Instruction *SI2,
387 SmallSetVector<BasicBlock *, 4> *FailBlocks = nullptr) {
388 if (SI1 == SI2)
389 return false; // Can't merge with self!
390
391 // It is not safe to merge these two switch instructions if they have a common
392 // successor, and if that successor has a PHI node, and if *that* PHI node has
393 // conflicting incoming values from the two switch blocks.
394 BasicBlock *SI1BB = SI1->getParent();
395 BasicBlock *SI2BB = SI2->getParent();
396
397 SmallPtrSet<BasicBlock *, 16> SI1Succs(llvm::from_range, successors(BB: SI1BB));
398 bool Fail = false;
399 for (BasicBlock *Succ : successors(BB: SI2BB)) {
400 if (!SI1Succs.count(Ptr: Succ))
401 continue;
402 if (incomingValuesAreCompatible(BB: Succ, IncomingBlocks: {SI1BB, SI2BB}))
403 continue;
404 Fail = true;
405 if (FailBlocks)
406 FailBlocks->insert(X: Succ);
407 else
408 break;
409 }
410
411 return !Fail;
412}
413
414/// Update PHI nodes in Succ to indicate that there will now be entries in it
415/// from the 'NewPred' block. The values that will be flowing into the PHI nodes
416/// will be the same as those coming in from ExistPred, an existing predecessor
417/// of Succ.
418static void addPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
419 BasicBlock *ExistPred,
420 MemorySSAUpdater *MSSAU = nullptr) {
421 for (PHINode &PN : Succ->phis())
422 PN.addIncoming(V: PN.getIncomingValueForBlock(BB: ExistPred), BB: NewPred);
423 if (MSSAU)
424 if (auto *MPhi = MSSAU->getMemorySSA()->getMemoryAccess(BB: Succ))
425 MPhi->addIncoming(V: MPhi->getIncomingValueForBlock(BB: ExistPred), BB: NewPred);
426}
427
428/// Compute an abstract "cost" of speculating the given instruction,
429/// which is assumed to be safe to speculate. TCC_Free means cheap,
430/// TCC_Basic means less cheap, and TCC_Expensive means prohibitively
431/// expensive.
432static InstructionCost computeSpeculationCost(const User *I,
433 const TargetTransformInfo &TTI) {
434 return TTI.getInstructionCost(U: I, CostKind: TargetTransformInfo::TCK_SizeAndLatency);
435}
436
437/// If we have a merge point of an "if condition" as accepted above,
438/// return true if the specified value dominates the block. We don't handle
439/// the true generality of domination here, just a special case which works
440/// well enough for us.
441///
442/// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
443/// see if V (which must be an instruction) and its recursive operands
444/// that do not dominate BB have a combined cost lower than Budget and
445/// are non-trapping. If both are true, the instruction is inserted into the
446/// set and true is returned.
447///
448/// The cost for most non-trapping instructions is defined as 1 except for
449/// Select whose cost is 2.
450///
451/// After this function returns, Cost is increased by the cost of
452/// V plus its non-dominating operands. If that cost is greater than
453/// Budget, false is returned and Cost is undefined.
454static bool dominatesMergePoint(
455 Value *V, BasicBlock *BB, Instruction *InsertPt,
456 SmallPtrSetImpl<Instruction *> &AggressiveInsts, InstructionCost &Cost,
457 InstructionCost Budget, const TargetTransformInfo &TTI, AssumptionCache *AC,
458 SmallPtrSetImpl<Instruction *> &ZeroCostInstructions, unsigned Depth = 0) {
459 // It is possible to hit a zero-cost cycle (phi/gep instructions for example),
460 // so limit the recursion depth.
461 // TODO: While this recursion limit does prevent pathological behavior, it
462 // would be better to track visited instructions to avoid cycles.
463 if (Depth == MaxSpeculationDepth)
464 return false;
465
466 Instruction *I = dyn_cast<Instruction>(Val: V);
467 if (!I) {
468 // Non-instructions dominate all instructions and can be executed
469 // unconditionally.
470 return true;
471 }
472 BasicBlock *PBB = I->getParent();
473
474 // We don't want to allow weird loops that might have the "if condition" in
475 // the bottom of this block.
476 if (PBB == BB)
477 return false;
478
479 // If this instruction is defined in a block that contains an unconditional
480 // branch to BB, then it must be in the 'conditional' part of the "if
481 // statement". If not, it definitely dominates the region.
482 UncondBrInst *BI = dyn_cast<UncondBrInst>(Val: PBB->getTerminator());
483 if (!BI || BI->getSuccessor() != BB)
484 return true;
485
486 // If we have seen this instruction before, don't count it again.
487 if (AggressiveInsts.count(Ptr: I))
488 return true;
489
490 // Okay, it looks like the instruction IS in the "condition". Check to
491 // see if it's a cheap instruction to unconditionally compute, and if it
492 // only uses stuff defined outside of the condition. If so, hoist it out.
493 if (!isSafeToSpeculativelyExecute(I, CtxI: InsertPt, AC))
494 return false;
495
496 // Overflow arithmetic instruction plus extract value are usually generated
497 // when a division is being replaced. But, in this case, the zero check may
498 // still be kept in the code. In that case it would be worth to hoist these
499 // two instruction out of the basic block. Let's treat this pattern as one
500 // single cheap instruction here!
501 WithOverflowInst *OverflowInst;
502 if (match(V: I, P: m_ExtractValue<1>(V: m_OneUse(SubPattern: m_WithOverflowInst(I&: OverflowInst))))) {
503 ZeroCostInstructions.insert(Ptr: OverflowInst);
504 Cost += 1;
505 } else if (!ZeroCostInstructions.contains(Ptr: I))
506 Cost += computeSpeculationCost(I, TTI);
507
508 // Allow exactly one instruction to be speculated regardless of its cost
509 // (as long as it is safe to do so).
510 // This is intended to flatten the CFG even if the instruction is a division
511 // or other expensive operation. The speculation of an expensive instruction
512 // is expected to be undone in CodeGenPrepare if the speculation has not
513 // enabled further IR optimizations.
514 if (Cost > Budget &&
515 (!SpeculateOneExpensiveInst || !AggressiveInsts.empty() || Depth > 0 ||
516 !Cost.isValid()))
517 return false;
518
519 // Okay, we can only really hoist these out if their operands do
520 // not take us over the cost threshold.
521 for (Use &Op : I->operands())
522 if (!dominatesMergePoint(V: Op, BB, InsertPt, AggressiveInsts, Cost, Budget,
523 TTI, AC, ZeroCostInstructions, Depth: Depth + 1))
524 return false;
525 // Okay, it's safe to do this! Remember this instruction.
526 AggressiveInsts.insert(Ptr: I);
527 return true;
528}
529
530/// Extract ConstantInt from value, looking through IntToPtr
531/// and PointerNullValue. Return NULL if value is not a constant int.
532static ConstantInt *getConstantInt(Value *V, const DataLayout &DL) {
533 // Normal constant int.
534 ConstantInt *CI = dyn_cast<ConstantInt>(Val: V);
535 if (CI || !isa<Constant>(Val: V) || !V->getType()->isPointerTy())
536 return CI;
537
538 // It is not safe to look through inttoptr or ptrtoint when using unstable
539 // pointer types.
540 if (DL.hasUnstableRepresentation(Ty: V->getType()))
541 return nullptr;
542
543 // This is some kind of pointer constant. Turn it into a pointer-sized
544 // ConstantInt if possible.
545 IntegerType *IntPtrTy = cast<IntegerType>(Val: DL.getIntPtrType(V->getType()));
546
547 // Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*).
548 if (isa<ConstantPointerNull>(Val: V))
549 return ConstantInt::get(Ty: IntPtrTy, V: 0);
550
551 // IntToPtr const int, we can look through this if the semantics of
552 // inttoptr for this address space are a simple (truncating) bitcast.
553 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Val: V))
554 if (CE->getOpcode() == Instruction::IntToPtr)
555 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val: CE->getOperand(i_nocapture: 0))) {
556 // The constant is very likely to have the right type already.
557 if (CI->getType() == IntPtrTy)
558 return CI;
559 else
560 return cast<ConstantInt>(
561 Val: ConstantFoldIntegerCast(C: CI, DestTy: IntPtrTy, /*isSigned=*/IsSigned: false, DL));
562 }
563 return nullptr;
564}
565
566namespace {
567
568/// Given a chain of or (||) or and (&&) comparison of a value against a
569/// constant, this will try to recover the information required for a switch
570/// structure.
571/// It will depth-first traverse the chain of comparison, seeking for patterns
572/// like %a == 12 or %a < 4 and combine them to produce a set of integer
573/// representing the different cases for the switch.
574/// Note that if the chain is composed of '||' it will build the set of elements
575/// that matches the comparisons (i.e. any of this value validate the chain)
576/// while for a chain of '&&' it will build the set elements that make the test
577/// fail.
578struct ConstantComparesGatherer {
579 const DataLayout &DL;
580
581 /// Value found for the switch comparison
582 Value *CompValue = nullptr;
583
584 /// Extra clause to be checked before the switch
585 Value *Extra = nullptr;
586
587 /// Set of integers to match in switch
588 SmallVector<ConstantInt *, 8> Vals;
589
590 /// Number of comparisons matched in the and/or chain
591 unsigned UsedICmps = 0;
592
593 /// If the elements in Vals matches the comparisons
594 bool IsEq = false;
595
596 // Used to check if the first matched CompValue shall be the Extra check.
597 bool IgnoreFirstMatch = false;
598 bool MultipleMatches = false;
599
600 /// Construct and compute the result for the comparison instruction Cond
601 ConstantComparesGatherer(Instruction *Cond, const DataLayout &DL) : DL(DL) {
602 gather(V: Cond);
603 if (CompValue || !MultipleMatches)
604 return;
605 Extra = nullptr;
606 Vals.clear();
607 UsedICmps = 0;
608 IgnoreFirstMatch = true;
609 gather(V: Cond);
610 }
611
612 ConstantComparesGatherer(const ConstantComparesGatherer &) = delete;
613 ConstantComparesGatherer &
614 operator=(const ConstantComparesGatherer &) = delete;
615
616private:
617 /// Try to set the current value used for the comparison, it succeeds only if
618 /// it wasn't set before or if the new value is the same as the old one
619 bool setValueOnce(Value *NewVal) {
620 if (IgnoreFirstMatch) {
621 IgnoreFirstMatch = false;
622 return false;
623 }
624 if (CompValue && CompValue != NewVal) {
625 MultipleMatches = true;
626 return false;
627 }
628 CompValue = NewVal;
629 return true;
630 }
631
632 /// Try to match Instruction "I" as a comparison against a constant and
633 /// populates the array Vals with the set of values that match (or do not
634 /// match depending on isEQ).
635 /// Return false on failure. On success, the Value the comparison matched
636 /// against is placed in CompValue.
637 /// If CompValue is already set, the function is expected to fail if a match
638 /// is found but the value compared to is different.
639 bool matchInstruction(Instruction *I, bool isEQ) {
640 if (match(V: I, P: m_Not(V: m_Instruction(I))))
641 isEQ = !isEQ;
642
643 Value *Val;
644 if (match(V: I, P: m_NUWTrunc(Op: m_Value(V&: Val)))) {
645 // If we already have a value for the switch, it has to match!
646 if (!setValueOnce(Val))
647 return false;
648 UsedICmps++;
649 Vals.push_back(Elt: ConstantInt::get(Ty: cast<IntegerType>(Val: Val->getType()), V: isEQ));
650 return true;
651 }
652 // If this is an icmp against a constant, handle this as one of the cases.
653 ICmpInst *ICI;
654 ConstantInt *C;
655 if (!((ICI = dyn_cast<ICmpInst>(Val: I)) &&
656 (C = getConstantInt(V: I->getOperand(i: 1), DL)))) {
657 return false;
658 }
659
660 Value *RHSVal;
661 const APInt *RHSC;
662
663 // Pattern match a special case
664 // (x & ~2^z) == y --> x == y || x == y|2^z
665 // This undoes a transformation done by instcombine to fuse 2 compares.
666 if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE)) {
667 // It's a little bit hard to see why the following transformations are
668 // correct. Here is a CVC3 program to verify them for 64-bit values:
669
670 /*
671 ONE : BITVECTOR(64) = BVZEROEXTEND(0bin1, 63);
672 x : BITVECTOR(64);
673 y : BITVECTOR(64);
674 z : BITVECTOR(64);
675 mask : BITVECTOR(64) = BVSHL(ONE, z);
676 QUERY( (y & ~mask = y) =>
677 ((x & ~mask = y) <=> (x = y OR x = (y | mask)))
678 );
679 QUERY( (y | mask = y) =>
680 ((x | mask = y) <=> (x = y OR x = (y & ~mask)))
681 );
682 */
683
684 // Please note that each pattern must be a dual implication (<--> or
685 // iff). One directional implication can create spurious matches. If the
686 // implication is only one-way, an unsatisfiable condition on the left
687 // side can imply a satisfiable condition on the right side. Dual
688 // implication ensures that satisfiable conditions are transformed to
689 // other satisfiable conditions and unsatisfiable conditions are
690 // transformed to other unsatisfiable conditions.
691
692 // Here is a concrete example of a unsatisfiable condition on the left
693 // implying a satisfiable condition on the right:
694 //
695 // mask = (1 << z)
696 // (x & ~mask) == y --> (x == y || x == (y | mask))
697 //
698 // Substituting y = 3, z = 0 yields:
699 // (x & -2) == 3 --> (x == 3 || x == 2)
700
701 // Pattern match a special case:
702 /*
703 QUERY( (y & ~mask = y) =>
704 ((x & ~mask = y) <=> (x = y OR x = (y | mask)))
705 );
706 */
707 if (match(V: ICI->getOperand(i_nocapture: 0),
708 P: m_And(L: m_Value(V&: RHSVal), R: m_APInt(Res&: RHSC)))) {
709 APInt Mask = ~*RHSC;
710 if (Mask.isPowerOf2() && (C->getValue() & ~Mask) == C->getValue()) {
711 // If we already have a value for the switch, it has to match!
712 if (!setValueOnce(RHSVal))
713 return false;
714
715 Vals.push_back(Elt: C);
716 Vals.push_back(
717 Elt: ConstantInt::get(Context&: C->getContext(),
718 V: C->getValue() | Mask));
719 UsedICmps++;
720 return true;
721 }
722 }
723
724 // Pattern match a special case:
725 /*
726 QUERY( (y | mask = y) =>
727 ((x | mask = y) <=> (x = y OR x = (y & ~mask)))
728 );
729 */
730 if (match(V: ICI->getOperand(i_nocapture: 0),
731 P: m_Or(L: m_Value(V&: RHSVal), R: m_APInt(Res&: RHSC)))) {
732 APInt Mask = *RHSC;
733 if (Mask.isPowerOf2() && (C->getValue() | Mask) == C->getValue()) {
734 // If we already have a value for the switch, it has to match!
735 if (!setValueOnce(RHSVal))
736 return false;
737
738 Vals.push_back(Elt: C);
739 Vals.push_back(Elt: ConstantInt::get(Context&: C->getContext(),
740 V: C->getValue() & ~Mask));
741 UsedICmps++;
742 return true;
743 }
744 }
745
746 // If we already have a value for the switch, it has to match!
747 if (!setValueOnce(ICI->getOperand(i_nocapture: 0)))
748 return false;
749
750 UsedICmps++;
751 Vals.push_back(Elt: C);
752 return true;
753 }
754
755 // If we have "x ult 3", for example, then we can add 0,1,2 to the set.
756 ConstantRange Span =
757 ConstantRange::makeExactICmpRegion(Pred: ICI->getPredicate(), Other: C->getValue());
758
759 // Shift the range if the compare is fed by an add. This is the range
760 // compare idiom as emitted by instcombine.
761 Value *CandidateVal = I->getOperand(i: 0);
762 if (match(V: I->getOperand(i: 0), P: m_Add(L: m_Value(V&: RHSVal), R: m_APInt(Res&: RHSC)))) {
763 Span = Span.subtract(CI: *RHSC);
764 CandidateVal = RHSVal;
765 }
766
767 // If this is an and/!= check, then we are looking to build the set of
768 // value that *don't* pass the and chain. I.e. to turn "x ugt 2" into
769 // x != 0 && x != 1.
770 if (!isEQ)
771 Span = Span.inverse();
772
773 // If there are a ton of values, we don't want to make a ginormous switch.
774 if (Span.isSizeLargerThan(MaxSize: 8) || Span.isEmptySet()) {
775 return false;
776 }
777
778 // If we already have a value for the switch, it has to match!
779 if (!setValueOnce(CandidateVal))
780 return false;
781
782 // Add all values from the range to the set
783 APInt Tmp = Span.getLower();
784 do
785 Vals.push_back(Elt: ConstantInt::get(Context&: I->getContext(), V: Tmp));
786 while (++Tmp != Span.getUpper());
787
788 UsedICmps++;
789 return true;
790 }
791
792 /// Given a potentially 'or'd or 'and'd together collection of icmp
793 /// eq/ne/lt/gt instructions that compare a value against a constant, extract
794 /// the value being compared, and stick the list constants into the Vals
795 /// vector.
796 /// One "Extra" case is allowed to differ from the other.
797 void gather(Value *V) {
798 Value *Op0, *Op1;
799 if (match(V, P: m_LogicalOr(L: m_Value(V&: Op0), R: m_Value(V&: Op1))))
800 IsEq = true;
801 else if (match(V, P: m_LogicalAnd(L: m_Value(V&: Op0), R: m_Value(V&: Op1))))
802 IsEq = false;
803 else
804 return;
805 // Keep a stack (SmallVector for efficiency) for depth-first traversal
806 SmallVector<Value *, 8> DFT{Op0, Op1};
807 SmallPtrSet<Value *, 8> Visited{V, Op0, Op1};
808
809 while (!DFT.empty()) {
810 V = DFT.pop_back_val();
811
812 if (Instruction *I = dyn_cast<Instruction>(Val: V)) {
813 // If it is a || (or && depending on isEQ), process the operands.
814 if (IsEq ? match(V: I, P: m_LogicalOr(L: m_Value(V&: Op0), R: m_Value(V&: Op1)))
815 : match(V: I, P: m_LogicalAnd(L: m_Value(V&: Op0), R: m_Value(V&: Op1)))) {
816 if (Visited.insert(Ptr: Op1).second)
817 DFT.push_back(Elt: Op1);
818 if (Visited.insert(Ptr: Op0).second)
819 DFT.push_back(Elt: Op0);
820
821 continue;
822 }
823
824 // Try to match the current instruction
825 if (matchInstruction(I, isEQ: IsEq))
826 // Match succeed, continue the loop
827 continue;
828 }
829
830 // One element of the sequence of || (or &&) could not be match as a
831 // comparison against the same value as the others.
832 // We allow only one "Extra" case to be checked before the switch
833 if (!Extra) {
834 Extra = V;
835 continue;
836 }
837 // Failed to parse a proper sequence, abort now
838 CompValue = nullptr;
839 break;
840 }
841 }
842};
843
844} // end anonymous namespace
845
846static void eraseTerminatorAndDCECond(Instruction *TI,
847 MemorySSAUpdater *MSSAU = nullptr) {
848 Instruction *Cond = nullptr;
849 if (SwitchInst *SI = dyn_cast<SwitchInst>(Val: TI)) {
850 Cond = dyn_cast<Instruction>(Val: SI->getCondition());
851 } else if (CondBrInst *BI = dyn_cast<CondBrInst>(Val: TI)) {
852 Cond = dyn_cast<Instruction>(Val: BI->getCondition());
853 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(Val: TI)) {
854 Cond = dyn_cast<Instruction>(Val: IBI->getAddress());
855 }
856
857 TI->eraseFromParent();
858 if (Cond)
859 RecursivelyDeleteTriviallyDeadInstructions(V: Cond, TLI: nullptr, MSSAU);
860}
861
862/// Return true if the specified terminator checks
863/// to see if a value is equal to constant integer value.
864Value *SimplifyCFGOpt::isValueEqualityComparison(Instruction *TI) {
865 Value *CV = nullptr;
866 if (SwitchInst *SI = dyn_cast<SwitchInst>(Val: TI)) {
867 // Do not permit merging of large switch instructions into their
868 // predecessors unless there is only one predecessor.
869 if (!SI->getParent()->hasNPredecessorsOrMore(N: 128 / SI->getNumSuccessors()))
870 CV = SI->getCondition();
871 } else if (CondBrInst *BI = dyn_cast<CondBrInst>(Val: TI))
872 if (BI->getCondition()->hasOneUse()) {
873 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Val: BI->getCondition())) {
874 if (ICI->isEquality() && getConstantInt(V: ICI->getOperand(i_nocapture: 1), DL))
875 CV = ICI->getOperand(i_nocapture: 0);
876 } else if (auto *Trunc = dyn_cast<TruncInst>(Val: BI->getCondition())) {
877 if (Trunc->hasNoUnsignedWrap())
878 CV = Trunc->getOperand(i_nocapture: 0);
879 }
880 }
881
882 // Unwrap any lossless ptrtoint cast (except for unstable pointers).
883 if (CV) {
884 if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(Val: CV)) {
885 Value *Ptr = PTII->getPointerOperand();
886 if (DL.hasUnstableRepresentation(Ty: Ptr->getType()))
887 return CV;
888 if (PTII->getType() == DL.getIntPtrType(Ptr->getType()))
889 CV = Ptr;
890 }
891 }
892 return CV;
893}
894
895/// Given a value comparison instruction,
896/// decode all of the 'cases' that it represents and return the 'default' block.
897BasicBlock *SimplifyCFGOpt::getValueEqualityComparisonCases(
898 Instruction *TI, std::vector<ValueEqualityComparisonCase> &Cases) {
899 if (SwitchInst *SI = dyn_cast<SwitchInst>(Val: TI)) {
900 Cases.reserve(n: SI->getNumCases());
901 for (auto Case : SI->cases())
902 Cases.push_back(x: ValueEqualityComparisonCase(Case.getCaseValue(),
903 Case.getCaseSuccessor()));
904 return SI->getDefaultDest();
905 }
906
907 CondBrInst *BI = cast<CondBrInst>(Val: TI);
908 Value *Cond = BI->getCondition();
909 ICmpInst::Predicate Pred;
910 ConstantInt *C;
911 if (auto *ICI = dyn_cast<ICmpInst>(Val: Cond)) {
912 Pred = ICI->getPredicate();
913 C = getConstantInt(V: ICI->getOperand(i_nocapture: 1), DL);
914 } else {
915 Pred = ICmpInst::ICMP_NE;
916 auto *Trunc = cast<TruncInst>(Val: Cond);
917 C = ConstantInt::get(Ty: cast<IntegerType>(Val: Trunc->getOperand(i_nocapture: 0)->getType()), V: 0);
918 }
919 BasicBlock *Succ = BI->getSuccessor(i: Pred == ICmpInst::ICMP_NE);
920 Cases.push_back(x: ValueEqualityComparisonCase(C, Succ));
921 return BI->getSuccessor(i: Pred == ICmpInst::ICMP_EQ);
922}
923
924/// Given a vector of bb/value pairs, remove any entries
925/// in the list that match the specified block.
926static void
927eliminateBlockCases(BasicBlock *BB,
928 std::vector<ValueEqualityComparisonCase> &Cases) {
929 llvm::erase(C&: Cases, V: BB);
930}
931
932/// Return true if there are any keys in C1 that exist in C2 as well.
933static bool valuesOverlap(std::vector<ValueEqualityComparisonCase> &C1,
934 std::vector<ValueEqualityComparisonCase> &C2) {
935 std::vector<ValueEqualityComparisonCase> *V1 = &C1, *V2 = &C2;
936
937 // Make V1 be smaller than V2.
938 if (V1->size() > V2->size())
939 std::swap(a&: V1, b&: V2);
940
941 if (V1->empty())
942 return false;
943 if (V1->size() == 1) {
944 // Just scan V2.
945 ConstantInt *TheVal = (*V1)[0].Value;
946 for (const ValueEqualityComparisonCase &VECC : *V2)
947 if (TheVal == VECC.Value)
948 return true;
949 }
950
951 // Otherwise, just sort both lists and compare element by element.
952 array_pod_sort(Start: V1->begin(), End: V1->end());
953 array_pod_sort(Start: V2->begin(), End: V2->end());
954 unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
955 while (i1 != e1 && i2 != e2) {
956 if ((*V1)[i1].Value == (*V2)[i2].Value)
957 return true;
958 if ((*V1)[i1].Value < (*V2)[i2].Value)
959 ++i1;
960 else
961 ++i2;
962 }
963 return false;
964}
965
966/// If TI is known to be a terminator instruction and its block is known to
967/// only have a single predecessor block, check to see if that predecessor is
968/// also a value comparison with the same value, and if that comparison
969/// determines the outcome of this comparison. If so, simplify TI. This does a
970/// very limited form of jump threading.
971bool SimplifyCFGOpt::simplifyEqualityComparisonWithOnlyPredecessor(
972 Instruction *TI, BasicBlock *Pred, IRBuilder<> &Builder) {
973 Value *PredVal = isValueEqualityComparison(TI: Pred->getTerminator());
974 if (!PredVal)
975 return false; // Not a value comparison in predecessor.
976
977 Value *ThisVal = isValueEqualityComparison(TI);
978 assert(ThisVal && "This isn't a value comparison!!");
979 if (ThisVal != PredVal)
980 return false; // Different predicates.
981
982 // TODO: Preserve branch weight metadata, similarly to how
983 // foldValueComparisonIntoPredecessors preserves it.
984
985 // Find out information about when control will move from Pred to TI's block.
986 std::vector<ValueEqualityComparisonCase> PredCases;
987 BasicBlock *PredDef =
988 getValueEqualityComparisonCases(TI: Pred->getTerminator(), Cases&: PredCases);
989 eliminateBlockCases(BB: PredDef, Cases&: PredCases); // Remove default from cases.
990
991 // Find information about how control leaves this block.
992 std::vector<ValueEqualityComparisonCase> ThisCases;
993 BasicBlock *ThisDef = getValueEqualityComparisonCases(TI, Cases&: ThisCases);
994 eliminateBlockCases(BB: ThisDef, Cases&: ThisCases); // Remove default from cases.
995
996 // If TI's block is the default block from Pred's comparison, potentially
997 // simplify TI based on this knowledge.
998 if (PredDef == TI->getParent()) {
999 // If we are here, we know that the value is none of those cases listed in
1000 // PredCases. If there are any cases in ThisCases that are in PredCases, we
1001 // can simplify TI.
1002 if (!valuesOverlap(C1&: PredCases, C2&: ThisCases))
1003 return false;
1004
1005 if (isa<CondBrInst>(Val: TI)) {
1006 // Okay, one of the successors of this condbr is dead. Convert it to a
1007 // uncond br.
1008 assert(ThisCases.size() == 1 && "Branch can only have one case!");
1009 // Insert the new branch.
1010 Instruction *NI = Builder.CreateBr(Dest: ThisDef);
1011 (void)NI;
1012
1013 // Remove PHI node entries for the dead edge.
1014 ThisCases[0].Dest->removePredecessor(Pred: PredDef);
1015
1016 LLVM_DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
1017 << "Through successor TI: " << *TI << "Leaving: " << *NI
1018 << "\n");
1019
1020 eraseTerminatorAndDCECond(TI);
1021
1022 if (DTU)
1023 DTU->applyUpdates(
1024 Updates: {{DominatorTree::Delete, PredDef, ThisCases[0].Dest}});
1025
1026 return true;
1027 }
1028
1029 SwitchInstProfUpdateWrapper SI = *cast<SwitchInst>(Val: TI);
1030 // Okay, TI has cases that are statically dead, prune them away.
1031 SmallPtrSet<Constant *, 16> DeadCases;
1032 for (const ValueEqualityComparisonCase &Case : PredCases)
1033 DeadCases.insert(Ptr: Case.Value);
1034
1035 LLVM_DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
1036 << "Through successor TI: " << *TI);
1037
1038 SmallDenseMap<BasicBlock *, int, 8> NumPerSuccessorCases;
1039 for (SwitchInst::CaseIt i = SI->case_end(), e = SI->case_begin(); i != e;) {
1040 --i;
1041 auto *Successor = i->getCaseSuccessor();
1042 if (DTU)
1043 ++NumPerSuccessorCases[Successor];
1044 if (DeadCases.count(Ptr: i->getCaseValue())) {
1045 Successor->removePredecessor(Pred: PredDef);
1046 SI.removeCase(I: i);
1047 if (DTU)
1048 --NumPerSuccessorCases[Successor];
1049 }
1050 }
1051
1052 if (DTU) {
1053 std::vector<DominatorTree::UpdateType> Updates;
1054 for (const std::pair<BasicBlock *, int> &I : NumPerSuccessorCases)
1055 if (I.second == 0)
1056 Updates.push_back(x: {DominatorTree::Delete, PredDef, I.first});
1057 DTU->applyUpdates(Updates);
1058 }
1059
1060 LLVM_DEBUG(dbgs() << "Leaving: " << *TI << "\n");
1061 return true;
1062 }
1063
1064 // Otherwise, TI's block must correspond to some matched value. Find out
1065 // which value (or set of values) this is.
1066 ConstantInt *TIV = nullptr;
1067 BasicBlock *TIBB = TI->getParent();
1068 for (const auto &[Value, Dest] : PredCases)
1069 if (Dest == TIBB) {
1070 if (TIV)
1071 return false; // Cannot handle multiple values coming to this block.
1072 TIV = Value;
1073 }
1074 assert(TIV && "No edge from pred to succ?");
1075
1076 // Okay, we found the one constant that our value can be if we get into TI's
1077 // BB. Find out which successor will unconditionally be branched to.
1078 BasicBlock *TheRealDest = nullptr;
1079 for (const auto &[Value, Dest] : ThisCases)
1080 if (Value == TIV) {
1081 TheRealDest = Dest;
1082 break;
1083 }
1084
1085 // If not handled by any explicit cases, it is handled by the default case.
1086 if (!TheRealDest)
1087 TheRealDest = ThisDef;
1088
1089 SmallPtrSet<BasicBlock *, 2> RemovedSuccs;
1090
1091 // Remove PHI node entries for dead edges.
1092 BasicBlock *CheckEdge = TheRealDest;
1093 for (BasicBlock *Succ : successors(BB: TIBB))
1094 if (Succ != CheckEdge) {
1095 if (Succ != TheRealDest)
1096 RemovedSuccs.insert(Ptr: Succ);
1097 Succ->removePredecessor(Pred: TIBB);
1098 } else
1099 CheckEdge = nullptr;
1100
1101 // Insert the new branch.
1102 Instruction *NI = Builder.CreateBr(Dest: TheRealDest);
1103 (void)NI;
1104
1105 LLVM_DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
1106 << "Through successor TI: " << *TI << "Leaving: " << *NI
1107 << "\n");
1108
1109 eraseTerminatorAndDCECond(TI);
1110 if (DTU) {
1111 SmallVector<DominatorTree::UpdateType, 2> Updates;
1112 Updates.reserve(N: RemovedSuccs.size());
1113 for (auto *RemovedSucc : RemovedSuccs)
1114 Updates.push_back(Elt: {DominatorTree::Delete, TIBB, RemovedSucc});
1115 DTU->applyUpdates(Updates);
1116 }
1117 return true;
1118}
1119
1120namespace {
1121
1122/// This class implements a stable ordering of constant
1123/// integers that does not depend on their address. This is important for
1124/// applications that sort ConstantInt's to ensure uniqueness.
1125struct ConstantIntOrdering {
1126 bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
1127 return LHS->getValue().ult(RHS: RHS->getValue());
1128 }
1129};
1130
1131} // end anonymous namespace
1132
1133static int constantIntSortPredicate(ConstantInt *const *P1,
1134 ConstantInt *const *P2) {
1135 const ConstantInt *LHS = *P1;
1136 const ConstantInt *RHS = *P2;
1137 if (LHS == RHS)
1138 return 0;
1139 return LHS->getValue().ult(RHS: RHS->getValue()) ? 1 : -1;
1140}
1141
1142/// Get Weights of a given terminator, the default weight is at the front
1143/// of the vector. If TI is a conditional eq, we need to swap the branch-weight
1144/// metadata.
1145static void getBranchWeights(Instruction *TI,
1146 SmallVectorImpl<uint64_t> &Weights) {
1147 MDNode *MD = TI->getMetadata(KindID: LLVMContext::MD_prof);
1148 assert(MD && "Invalid branch-weight metadata");
1149 extractFromBranchWeightMD64(ProfileData: MD, Weights);
1150
1151 // If TI is a conditional eq, the default case is the false case,
1152 // and the corresponding branch-weight data is at index 2. We swap the
1153 // default weight to be the first entry.
1154 if (CondBrInst *BI = dyn_cast<CondBrInst>(Val: TI)) {
1155 assert(Weights.size() == 2);
1156 auto *ICI = dyn_cast<ICmpInst>(Val: BI->getCondition());
1157 if (!ICI)
1158 return;
1159
1160 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
1161 std::swap(a&: Weights.front(), b&: Weights.back());
1162 }
1163}
1164
1165static void cloneInstructionsIntoPredecessorBlockAndUpdateSSAUses(
1166 BasicBlock *BB, BasicBlock *PredBlock, ValueToValueMapTy &VMap) {
1167 Instruction *PTI = PredBlock->getTerminator();
1168
1169 // If we have bonus instructions, clone them into the predecessor block.
1170 // Note that there may be multiple predecessor blocks, so we cannot move
1171 // bonus instructions to a predecessor block.
1172 for (Instruction &BonusInst : *BB) {
1173 if (BonusInst.isTerminator())
1174 continue;
1175
1176 // Skip cloning pseudo probes into the predecessor, as it would overcount
1177 // otherwise.
1178 if (isa<PseudoProbeInst>(Val: BonusInst))
1179 continue;
1180
1181 Instruction *NewBonusInst = BonusInst.clone();
1182
1183 if (!NewBonusInst->getDebugLoc().isSameSourceLocation(Other: PTI->getDebugLoc())) {
1184 // Unless the instruction has the same !dbg location as the original
1185 // branch, drop it. When we fold the bonus instructions we want to make
1186 // sure we reset their debug locations in order to avoid stepping on
1187 // dead code caused by folding dead branches.
1188 NewBonusInst->setDebugLoc(DebugLoc::getDropped());
1189 } else if (const DebugLoc &DL = NewBonusInst->getDebugLoc()) {
1190 mapAtomInstance(DL, VMap);
1191 }
1192
1193 RemapInstruction(I: NewBonusInst, VM&: VMap,
1194 Flags: RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
1195
1196 // If we speculated an instruction, we need to drop any metadata that may
1197 // result in undefined behavior, as the metadata might have been valid
1198 // only given the branch precondition.
1199 // Similarly strip attributes on call parameters that may cause UB in
1200 // location the call is moved to.
1201 NewBonusInst->dropUBImplyingAttrsAndMetadata();
1202
1203 NewBonusInst->insertInto(ParentBB: PredBlock, It: PTI->getIterator());
1204 auto Range = NewBonusInst->cloneDebugInfoFrom(From: &BonusInst);
1205 RemapDbgRecordRange(M: NewBonusInst->getModule(), Range, VM&: VMap,
1206 Flags: RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
1207
1208 NewBonusInst->takeName(V: &BonusInst);
1209 BonusInst.setName(NewBonusInst->getName() + ".old");
1210 VMap[&BonusInst] = NewBonusInst;
1211
1212 // Update (liveout) uses of bonus instructions,
1213 // now that the bonus instruction has been cloned into predecessor.
1214 // Note that we expect to be in a block-closed SSA form for this to work!
1215 for (Use &U : make_early_inc_range(Range: BonusInst.uses())) {
1216 auto *UI = cast<Instruction>(Val: U.getUser());
1217 auto *PN = dyn_cast<PHINode>(Val: UI);
1218 if (!PN) {
1219 assert(UI->getParent() == BB && BonusInst.comesBefore(UI) &&
1220 "If the user is not a PHI node, then it should be in the same "
1221 "block as, and come after, the original bonus instruction.");
1222 continue; // Keep using the original bonus instruction.
1223 }
1224 // Is this the block-closed SSA form PHI node?
1225 if (PN->getIncomingBlock(U) == BB)
1226 continue; // Great, keep using the original bonus instruction.
1227 // The only other alternative is an "use" when coming from
1228 // the predecessor block - here we should refer to the cloned bonus instr.
1229 assert(PN->getIncomingBlock(U) == PredBlock &&
1230 "Not in block-closed SSA form?");
1231 U.set(NewBonusInst);
1232 }
1233 }
1234
1235 // Key Instructions: We may have propagated atom info into the pred. If the
1236 // pred's terminator already has atom info do nothing as merging would drop
1237 // one atom group anyway. If it doesn't, propagte the remapped atom group
1238 // from BB's terminator.
1239 if (auto &PredDL = PTI->getDebugLoc()) {
1240 auto &DL = BB->getTerminator()->getDebugLoc();
1241 if (!PredDL->getAtomGroup() && DL && DL->getAtomGroup() &&
1242 PredDL.isSameSourceLocation(Other: DL)) {
1243 PTI->setDebugLoc(DL);
1244 RemapSourceAtom(I: PTI, VM&: VMap);
1245 }
1246 }
1247}
1248
1249bool SimplifyCFGOpt::performValueComparisonIntoPredecessorFolding(
1250 Instruction *TI, Value *&CV, Instruction *PTI, IRBuilder<> &Builder) {
1251 BasicBlock *BB = TI->getParent();
1252 BasicBlock *Pred = PTI->getParent();
1253
1254 SmallVector<DominatorTree::UpdateType, 32> Updates;
1255
1256 // Figure out which 'cases' to copy from SI to PSI.
1257 std::vector<ValueEqualityComparisonCase> BBCases;
1258 BasicBlock *BBDefault = getValueEqualityComparisonCases(TI, Cases&: BBCases);
1259
1260 std::vector<ValueEqualityComparisonCase> PredCases;
1261 BasicBlock *PredDefault = getValueEqualityComparisonCases(TI: PTI, Cases&: PredCases);
1262
1263 // Based on whether the default edge from PTI goes to BB or not, fill in
1264 // PredCases and PredDefault with the new switch cases we would like to
1265 // build.
1266 SmallMapVector<BasicBlock *, int, 8> NewSuccessors;
1267
1268 // Update the branch weight metadata along the way
1269 SmallVector<uint64_t, 8> Weights;
1270 bool PredHasWeights = hasBranchWeightMD(I: *PTI);
1271 bool SuccHasWeights = hasBranchWeightMD(I: *TI);
1272
1273 if (PredHasWeights) {
1274 getBranchWeights(TI: PTI, Weights);
1275 // branch-weight metadata is inconsistent here.
1276 if (Weights.size() != 1 + PredCases.size())
1277 PredHasWeights = SuccHasWeights = false;
1278 } else if (SuccHasWeights)
1279 // If there are no predecessor weights but there are successor weights,
1280 // populate Weights with 1, which will later be scaled to the sum of
1281 // successor's weights
1282 Weights.assign(NumElts: 1 + PredCases.size(), Elt: 1);
1283
1284 SmallVector<uint64_t, 8> SuccWeights;
1285 if (SuccHasWeights) {
1286 getBranchWeights(TI, Weights&: SuccWeights);
1287 // branch-weight metadata is inconsistent here.
1288 if (SuccWeights.size() != 1 + BBCases.size())
1289 PredHasWeights = SuccHasWeights = false;
1290 } else if (PredHasWeights)
1291 SuccWeights.assign(NumElts: 1 + BBCases.size(), Elt: 1);
1292
1293 if (PredDefault == BB) {
1294 // If this is the default destination from PTI, only the edges in TI
1295 // that don't occur in PTI, or that branch to BB will be activated.
1296 std::set<ConstantInt *, ConstantIntOrdering> PTIHandled;
1297 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
1298 if (PredCases[i].Dest != BB)
1299 PTIHandled.insert(x: PredCases[i].Value);
1300 else {
1301 // The default destination is BB, we don't need explicit targets.
1302 std::swap(a&: PredCases[i], b&: PredCases.back());
1303
1304 if (PredHasWeights || SuccHasWeights) {
1305 // Increase weight for the default case.
1306 Weights[0] += Weights[i + 1];
1307 std::swap(a&: Weights[i + 1], b&: Weights.back());
1308 Weights.pop_back();
1309 }
1310
1311 PredCases.pop_back();
1312 --i;
1313 --e;
1314 }
1315
1316 // Reconstruct the new switch statement we will be building.
1317 if (PredDefault != BBDefault) {
1318 PredDefault->removePredecessor(Pred);
1319 if (DTU && PredDefault != BB)
1320 Updates.push_back(Elt: {DominatorTree::Delete, Pred, PredDefault});
1321 PredDefault = BBDefault;
1322 ++NewSuccessors[BBDefault];
1323 }
1324
1325 unsigned CasesFromPred = Weights.size();
1326 uint64_t ValidTotalSuccWeight = 0;
1327 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
1328 if (!PTIHandled.count(x: BBCases[i].Value) && BBCases[i].Dest != BBDefault) {
1329 PredCases.push_back(x: BBCases[i]);
1330 ++NewSuccessors[BBCases[i].Dest];
1331 if (SuccHasWeights || PredHasWeights) {
1332 // The default weight is at index 0, so weight for the ith case
1333 // should be at index i+1. Scale the cases from successor by
1334 // PredDefaultWeight (Weights[0]).
1335 Weights.push_back(Elt: Weights[0] * SuccWeights[i + 1]);
1336 ValidTotalSuccWeight += SuccWeights[i + 1];
1337 }
1338 }
1339
1340 if (SuccHasWeights || PredHasWeights) {
1341 ValidTotalSuccWeight += SuccWeights[0];
1342 // Scale the cases from predecessor by ValidTotalSuccWeight.
1343 for (unsigned i = 1; i < CasesFromPred; ++i)
1344 Weights[i] *= ValidTotalSuccWeight;
1345 // Scale the default weight by SuccDefaultWeight (SuccWeights[0]).
1346 Weights[0] *= SuccWeights[0];
1347 }
1348 } else {
1349 // If this is not the default destination from PSI, only the edges
1350 // in SI that occur in PSI with a destination of BB will be
1351 // activated.
1352 std::set<ConstantInt *, ConstantIntOrdering> PTIHandled;
1353 std::map<ConstantInt *, uint64_t> WeightsForHandled;
1354 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
1355 if (PredCases[i].Dest == BB) {
1356 PTIHandled.insert(x: PredCases[i].Value);
1357
1358 if (PredHasWeights || SuccHasWeights) {
1359 WeightsForHandled[PredCases[i].Value] = Weights[i + 1];
1360 std::swap(a&: Weights[i + 1], b&: Weights.back());
1361 Weights.pop_back();
1362 }
1363
1364 std::swap(a&: PredCases[i], b&: PredCases.back());
1365 PredCases.pop_back();
1366 --i;
1367 --e;
1368 }
1369
1370 // Okay, now we know which constants were sent to BB from the
1371 // predecessor. Figure out where they will all go now.
1372 for (const ValueEqualityComparisonCase &Case : BBCases)
1373 if (PTIHandled.count(x: Case.Value)) {
1374 // If this is one we are capable of getting...
1375 if (PredHasWeights || SuccHasWeights)
1376 Weights.push_back(Elt: WeightsForHandled[Case.Value]);
1377 PredCases.push_back(x: Case);
1378 ++NewSuccessors[Case.Dest];
1379 PTIHandled.erase(x: Case.Value); // This constant is taken care of
1380 }
1381
1382 // If there are any constants vectored to BB that TI doesn't handle,
1383 // they must go to the default destination of TI.
1384 for (ConstantInt *I : PTIHandled) {
1385 if (PredHasWeights || SuccHasWeights)
1386 Weights.push_back(Elt: WeightsForHandled[I]);
1387 PredCases.push_back(x: ValueEqualityComparisonCase(I, BBDefault));
1388 ++NewSuccessors[BBDefault];
1389 }
1390 }
1391
1392 // Okay, at this point, we know which new successor Pred will get. Make
1393 // sure we update the number of entries in the PHI nodes for these
1394 // successors.
1395 SmallPtrSet<BasicBlock *, 2> SuccsOfPred;
1396 if (DTU) {
1397 SuccsOfPred = {llvm::from_range, successors(BB: Pred)};
1398 Updates.reserve(N: Updates.size() + NewSuccessors.size());
1399 }
1400 for (const std::pair<BasicBlock *, int /*Num*/> &NewSuccessor :
1401 NewSuccessors) {
1402 for (auto I : seq(Size: NewSuccessor.second)) {
1403 (void)I;
1404 addPredecessorToBlock(Succ: NewSuccessor.first, NewPred: Pred, ExistPred: BB);
1405 }
1406 if (DTU && !SuccsOfPred.contains(Ptr: NewSuccessor.first))
1407 Updates.push_back(Elt: {DominatorTree::Insert, Pred, NewSuccessor.first});
1408 }
1409
1410 Builder.SetInsertPoint(PTI);
1411 // Convert pointer to int before we switch.
1412 if (CV->getType()->isPointerTy()) {
1413 assert(!DL.hasUnstableRepresentation(CV->getType()) &&
1414 "Should not end up here with unstable pointers");
1415 CV =
1416 Builder.CreatePtrToInt(V: CV, DestTy: DL.getIntPtrType(CV->getType()), Name: "magicptr");
1417 }
1418
1419 // Now that the successors are updated, create the new Switch instruction.
1420 SwitchInst *NewSI = Builder.CreateSwitch(V: CV, Dest: PredDefault, NumCases: PredCases.size());
1421 NewSI->setDebugLoc(PTI->getDebugLoc());
1422 for (ValueEqualityComparisonCase &V : PredCases)
1423 NewSI->addCase(OnVal: V.Value, Dest: V.Dest);
1424
1425 if (PredHasWeights || SuccHasWeights)
1426 setFittedBranchWeights(I&: *NewSI, Weights, /*IsExpected=*/false,
1427 /*ElideAllZero=*/true);
1428
1429 eraseTerminatorAndDCECond(TI: PTI);
1430
1431 // Okay, last check. If BB is still a successor of PSI, then we must
1432 // have an infinite loop case. If so, add an infinitely looping block
1433 // to handle the case to preserve the behavior of the code.
1434 BasicBlock *InfLoopBlock = nullptr;
1435 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
1436 if (NewSI->getSuccessor(idx: i) == BB) {
1437 if (!InfLoopBlock) {
1438 // Insert it at the end of the function, because it's either code,
1439 // or it won't matter if it's hot. :)
1440 InfLoopBlock =
1441 BasicBlock::Create(Context&: BB->getContext(), Name: "infloop", Parent: BB->getParent());
1442 UncondBrInst::Create(Target: InfLoopBlock, InsertBefore: InfLoopBlock);
1443 if (DTU)
1444 Updates.push_back(
1445 Elt: {DominatorTree::Insert, InfLoopBlock, InfLoopBlock});
1446 }
1447 NewSI->setSuccessor(idx: i, NewSucc: InfLoopBlock);
1448 }
1449
1450 if (DTU) {
1451 if (InfLoopBlock)
1452 Updates.push_back(Elt: {DominatorTree::Insert, Pred, InfLoopBlock});
1453
1454 Updates.push_back(Elt: {DominatorTree::Delete, Pred, BB});
1455
1456 DTU->applyUpdates(Updates);
1457 }
1458
1459 ++NumFoldValueComparisonIntoPredecessors;
1460 return true;
1461}
1462
1463/// The specified terminator is a value equality comparison instruction
1464/// (either a switch or a branch on "X == c").
1465/// See if any of the predecessors of the terminator block are value comparisons
1466/// on the same value. If so, and if safe to do so, fold them together.
1467bool SimplifyCFGOpt::foldValueComparisonIntoPredecessors(Instruction *TI,
1468 IRBuilder<> &Builder) {
1469 BasicBlock *BB = TI->getParent();
1470 Value *CV = isValueEqualityComparison(TI); // CondVal
1471 assert(CV && "Not a comparison?");
1472
1473 bool Changed = false;
1474
1475 SmallSetVector<BasicBlock *, 16> Preds(pred_begin(BB), pred_end(BB));
1476 while (!Preds.empty()) {
1477 BasicBlock *Pred = Preds.pop_back_val();
1478 Instruction *PTI = Pred->getTerminator();
1479
1480 // Don't try to fold into itself.
1481 if (Pred == BB)
1482 continue;
1483
1484 // See if the predecessor is a comparison with the same value.
1485 Value *PCV = isValueEqualityComparison(TI: PTI); // PredCondVal
1486 if (PCV != CV)
1487 continue;
1488
1489 SmallSetVector<BasicBlock *, 4> FailBlocks;
1490 if (!safeToMergeTerminators(SI1: TI, SI2: PTI, FailBlocks: &FailBlocks)) {
1491 for (auto *Succ : FailBlocks) {
1492 if (!SplitBlockPredecessors(BB: Succ, Preds: TI->getParent(), Suffix: ".fold.split", DTU))
1493 return false;
1494 }
1495 }
1496
1497 performValueComparisonIntoPredecessorFolding(TI, CV, PTI, Builder);
1498 Changed = true;
1499 }
1500 return Changed;
1501}
1502
1503// If we would need to insert a select that uses the value of this invoke
1504// (comments in hoistSuccIdenticalTerminatorToSwitchOrIf explain why we would
1505// need to do this), we can't hoist the invoke, as there is nowhere to put the
1506// select in this case.
1507static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2,
1508 Instruction *I1, Instruction *I2) {
1509 for (BasicBlock *Succ : successors(BB: BB1)) {
1510 for (const PHINode &PN : Succ->phis()) {
1511 Value *BB1V = PN.getIncomingValueForBlock(BB: BB1);
1512 Value *BB2V = PN.getIncomingValueForBlock(BB: BB2);
1513 if (BB1V != BB2V && (BB1V == I1 || BB2V == I2)) {
1514 return false;
1515 }
1516 }
1517 }
1518 return true;
1519}
1520
1521// Get interesting characteristics of instructions that
1522// `hoistCommonCodeFromSuccessors` didn't hoist. They restrict what kind of
1523// instructions can be reordered across.
1524enum SkipFlags {
1525 SkipReadMem = 1,
1526 SkipSideEffect = 2,
1527 SkipImplicitControlFlow = 4
1528};
1529
1530static unsigned skippedInstrFlags(Instruction *I) {
1531 // Pseudo probes don't constrain reordering of other instructions.
1532 if (isa<PseudoProbeInst>(Val: I))
1533 return 0;
1534 unsigned Flags = 0;
1535 if (I->mayReadFromMemory())
1536 Flags |= SkipReadMem;
1537 // We can't arbitrarily move around allocas, e.g. moving allocas (especially
1538 // inalloca) across stacksave/stackrestore boundaries.
1539 if (I->mayHaveSideEffects() || isa<AllocaInst>(Val: I))
1540 Flags |= SkipSideEffect;
1541 if (!isGuaranteedToTransferExecutionToSuccessor(I))
1542 Flags |= SkipImplicitControlFlow;
1543 return Flags;
1544}
1545
1546// Returns true if it is safe to reorder an instruction across preceding
1547// instructions in a basic block.
1548static bool isSafeToHoistInstr(Instruction *I, unsigned Flags) {
1549 // Don't reorder a store over a load.
1550 if ((Flags & SkipReadMem) && I->mayWriteToMemory())
1551 return false;
1552
1553 // If we have seen an instruction with side effects, it's unsafe to reorder an
1554 // instruction which reads memory or itself has side effects.
1555 if ((Flags & SkipSideEffect) &&
1556 (I->mayReadFromMemory() || I->mayHaveSideEffects() || isa<AllocaInst>(Val: I)))
1557 return false;
1558
1559 // Reordering across an instruction which does not necessarily transfer
1560 // control to the next instruction is speculation.
1561 if ((Flags & SkipImplicitControlFlow) && !isSafeToSpeculativelyExecute(I))
1562 return false;
1563
1564 // Hoisting of llvm.deoptimize is only legal together with the next return
1565 // instruction, which this pass is not always able to do.
1566 if (auto *CB = dyn_cast<CallBase>(Val: I))
1567 if (CB->getIntrinsicID() == Intrinsic::experimental_deoptimize)
1568 return false;
1569
1570 // It's also unsafe/illegal to hoist an instruction above its instruction
1571 // operands
1572 BasicBlock *BB = I->getParent();
1573 for (Value *Op : I->operands()) {
1574 if (auto *J = dyn_cast<Instruction>(Val: Op))
1575 if (J->getParent() == BB)
1576 return false;
1577 }
1578
1579 return true;
1580}
1581
1582static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I, bool PtrValueMayBeModified = false);
1583
1584/// Helper function for hoistCommonCodeFromSuccessors. Return true if identical
1585/// instructions \p I1 and \p I2 can and should be hoisted.
1586static bool shouldHoistCommonInstructions(Instruction *I1, Instruction *I2,
1587 const TargetTransformInfo &TTI) {
1588 // If we're going to hoist a call, make sure that the two instructions
1589 // we're commoning/hoisting are both marked with musttail, or neither of
1590 // them is marked as such. Otherwise, we might end up in a situation where
1591 // we hoist from a block where the terminator is a `ret` to a block where
1592 // the terminator is a `br`, and `musttail` calls expect to be followed by
1593 // a return.
1594 auto *C1 = dyn_cast<CallInst>(Val: I1);
1595 auto *C2 = dyn_cast<CallInst>(Val: I2);
1596 if (C1 && C2)
1597 if (C1->isMustTailCall() != C2->isMustTailCall())
1598 return false;
1599
1600 if (!TTI.isProfitableToHoist(I: I1) || !TTI.isProfitableToHoist(I: I2))
1601 return false;
1602
1603 // If any of the two call sites has nomerge or convergent attribute, stop
1604 // hoisting.
1605 if (const auto *CB1 = dyn_cast<CallBase>(Val: I1))
1606 if (CB1->cannotMerge() || CB1->isConvergent())
1607 return false;
1608 if (const auto *CB2 = dyn_cast<CallBase>(Val: I2))
1609 if (CB2->cannotMerge() || CB2->isConvergent())
1610 return false;
1611
1612 return true;
1613}
1614
1615/// Hoists DbgVariableRecords from \p I1 and \p OtherInstrs that are identical
1616/// in lock-step to \p TI. This matches how dbg.* intrinsics are hoisting in
1617/// hoistCommonCodeFromSuccessors. e.g. The input:
1618/// I1 DVRs: { x, z },
1619/// OtherInsts: { I2 DVRs: { x, y, z } }
1620/// would result in hoisting only DbgVariableRecord x.
1621static void hoistLockstepIdenticalDbgVariableRecords(
1622 Instruction *TI, Instruction *I1,
1623 SmallVectorImpl<Instruction *> &OtherInsts) {
1624 if (!I1->hasDbgRecords())
1625 return;
1626 using CurrentAndEndIt =
1627 std::pair<DbgRecord::self_iterator, DbgRecord::self_iterator>;
1628 // Vector of {Current, End} iterators.
1629 SmallVector<CurrentAndEndIt> Itrs;
1630 Itrs.reserve(N: OtherInsts.size() + 1);
1631 // Helper lambdas for lock-step checks:
1632 // Return true if this Current == End.
1633 auto atEnd = [](const CurrentAndEndIt &Pair) {
1634 return Pair.first == Pair.second;
1635 };
1636 // Return true if all Current are identical.
1637 auto allIdentical = [](const SmallVector<CurrentAndEndIt> &Itrs) {
1638 return all_of(Range: make_first_range(c: ArrayRef(Itrs).drop_front()),
1639 P: [&](DbgRecord::self_iterator I) {
1640 return Itrs[0].first->isIdenticalToWhenDefined(R: *I);
1641 });
1642 };
1643
1644 // Collect the iterators.
1645 Itrs.push_back(
1646 Elt: {I1->getDbgRecordRange().begin(), I1->getDbgRecordRange().end()});
1647 for (Instruction *Other : OtherInsts) {
1648 if (!Other->hasDbgRecords())
1649 return;
1650 Itrs.push_back(
1651 Elt: {Other->getDbgRecordRange().begin(), Other->getDbgRecordRange().end()});
1652 }
1653
1654 // Iterate in lock-step until any of the DbgRecord lists are exausted. If
1655 // the lock-step DbgRecord are identical, hoist all of them to TI.
1656 // This replicates the dbg.* intrinsic behaviour in
1657 // hoistCommonCodeFromSuccessors.
1658 while (none_of(Range&: Itrs, P: atEnd)) {
1659 bool HoistDVRs = allIdentical(Itrs);
1660 for (CurrentAndEndIt &Pair : Itrs) {
1661 // Increment Current iterator now as we may be about to move the
1662 // DbgRecord.
1663 DbgRecord &DR = *Pair.first++;
1664 if (HoistDVRs) {
1665 DR.removeFromParent();
1666 TI->getParent()->insertDbgRecordBefore(DR: &DR, Here: TI->getIterator());
1667 }
1668 }
1669 }
1670}
1671
1672static bool areIdenticalUpToCommutativity(const Instruction *I1,
1673 const Instruction *I2) {
1674 if (I1->isIdenticalToWhenDefined(I: I2, /*IntersectAttrs=*/true))
1675 return true;
1676
1677 if (auto *Cmp1 = dyn_cast<CmpInst>(Val: I1))
1678 if (auto *Cmp2 = dyn_cast<CmpInst>(Val: I2))
1679 return Cmp1->getPredicate() == Cmp2->getSwappedPredicate() &&
1680 Cmp1->getOperand(i_nocapture: 0) == Cmp2->getOperand(i_nocapture: 1) &&
1681 Cmp1->getOperand(i_nocapture: 1) == Cmp2->getOperand(i_nocapture: 0);
1682
1683 if (I1->isCommutative() && I1->isSameOperationAs(I: I2)) {
1684 return I1->getOperand(i: 0) == I2->getOperand(i: 1) &&
1685 I1->getOperand(i: 1) == I2->getOperand(i: 0) &&
1686 equal(LRange: drop_begin(RangeOrContainer: I1->operands(), N: 2), RRange: drop_begin(RangeOrContainer: I2->operands(), N: 2));
1687 }
1688
1689 return false;
1690}
1691
1692/// If the target supports conditional faulting,
1693/// we look for the following pattern:
1694/// \code
1695/// BB:
1696/// ...
1697/// %cond = icmp ult %x, %y
1698/// br i1 %cond, label %TrueBB, label %FalseBB
1699/// FalseBB:
1700/// store i32 1, ptr %q, align 4
1701/// ...
1702/// TrueBB:
1703/// %maskedloadstore = load i32, ptr %b, align 4
1704/// store i32 %maskedloadstore, ptr %p, align 4
1705/// ...
1706/// \endcode
1707///
1708/// and transform it into:
1709///
1710/// \code
1711/// BB:
1712/// ...
1713/// %cond = icmp ult %x, %y
1714/// %maskedloadstore = cload i32, ptr %b, %cond
1715/// cstore i32 %maskedloadstore, ptr %p, %cond
1716/// cstore i32 1, ptr %q, ~%cond
1717/// br i1 %cond, label %TrueBB, label %FalseBB
1718/// FalseBB:
1719/// ...
1720/// TrueBB:
1721/// ...
1722/// \endcode
1723///
1724/// where cload/cstore are represented by llvm.masked.load/store intrinsics,
1725/// e.g.
1726///
1727/// \code
1728/// %vcond = bitcast i1 %cond to <1 x i1>
1729/// %v0 = call <1 x i32> @llvm.masked.load.v1i32.p0
1730/// (ptr %b, i32 4, <1 x i1> %vcond, <1 x i32> poison)
1731/// %maskedloadstore = bitcast <1 x i32> %v0 to i32
1732/// call void @llvm.masked.store.v1i32.p0
1733/// (<1 x i32> %v0, ptr %p, i32 4, <1 x i1> %vcond)
1734/// %cond.not = xor i1 %cond, true
1735/// %vcond.not = bitcast i1 %cond.not to <1 x i>
1736/// call void @llvm.masked.store.v1i32.p0
1737/// (<1 x i32> <i32 1>, ptr %q, i32 4, <1x i1> %vcond.not)
1738/// \endcode
1739///
1740/// So we need to turn hoisted load/store into cload/cstore.
1741///
1742/// \param BI The branch instruction.
1743/// \param SpeculatedConditionalLoadsStores The load/store instructions that
1744/// will be speculated.
1745/// \param Invert indicates if speculates FalseBB. Only used in triangle CFG.
1746static void hoistConditionalLoadsStores(
1747 CondBrInst *BI,
1748 SmallVectorImpl<Instruction *> &SpeculatedConditionalLoadsStores,
1749 std::optional<bool> Invert, Instruction *Sel) {
1750 auto &Context = BI->getParent()->getContext();
1751 auto *VCondTy = FixedVectorType::get(ElementType: Type::getInt1Ty(C&: Context), NumElts: 1);
1752 auto *Cond = BI->getCondition();
1753 // Construct the condition if needed.
1754 BasicBlock *BB = BI->getParent();
1755 Value *Mask = nullptr;
1756 Value *MaskFalse = nullptr;
1757 Value *MaskTrue = nullptr;
1758 if (Invert.has_value()) {
1759 IRBuilder<> Builder(Sel ? Sel : SpeculatedConditionalLoadsStores.back());
1760 Mask = Builder.CreateBitCast(
1761 V: *Invert ? Builder.CreateXor(LHS: Cond, RHS: ConstantInt::getTrue(Context)) : Cond,
1762 DestTy: VCondTy);
1763 } else {
1764 IRBuilder<> Builder(BI);
1765 MaskFalse = Builder.CreateBitCast(
1766 V: Builder.CreateXor(LHS: Cond, RHS: ConstantInt::getTrue(Context)), DestTy: VCondTy);
1767 MaskTrue = Builder.CreateBitCast(V: Cond, DestTy: VCondTy);
1768 }
1769 auto PeekThroughBitcasts = [](Value *V) {
1770 while (auto *BitCast = dyn_cast<BitCastInst>(Val: V))
1771 V = BitCast->getOperand(i_nocapture: 0);
1772 return V;
1773 };
1774 for (auto *I : SpeculatedConditionalLoadsStores) {
1775 IRBuilder<> Builder(Invert.has_value() ? I : BI);
1776 if (!Invert.has_value())
1777 Mask = I->getParent() == BI->getSuccessor(i: 0) ? MaskTrue : MaskFalse;
1778 // We currently assume conditional faulting load/store is supported for
1779 // scalar types only when creating new instructions. This can be easily
1780 // extended for vector types in the future.
1781 assert(!getLoadStoreType(I)->isVectorTy() && "not implemented");
1782 auto *Op0 = I->getOperand(i: 0);
1783 CallInst *MaskedLoadStore = nullptr;
1784 if (auto *LI = dyn_cast<LoadInst>(Val: I)) {
1785 // Handle Load.
1786 auto *Ty = I->getType();
1787 PHINode *PN = nullptr;
1788 Value *PassThru = nullptr;
1789 if (Invert.has_value())
1790 for (User *U : I->users()) {
1791 if ((PN = dyn_cast<PHINode>(Val: U))) {
1792 PassThru = Builder.CreateBitCast(
1793 V: PeekThroughBitcasts(PN->getIncomingValueForBlock(BB)),
1794 DestTy: FixedVectorType::get(ElementType: Ty, NumElts: 1));
1795 } else if (auto *Ins = cast<Instruction>(Val: U);
1796 Sel && Ins->getParent() == BB) {
1797 // This happens when store or/and a speculative instruction between
1798 // load and store were hoisted to the BB. Make sure the masked load
1799 // inserted before its use.
1800 // We assume there's one of such use.
1801 Builder.SetInsertPoint(Ins);
1802 }
1803 }
1804 MaskedLoadStore = Builder.CreateMaskedLoad(
1805 Ty: FixedVectorType::get(ElementType: Ty, NumElts: 1), Ptr: Op0, Alignment: LI->getAlign(), Mask, PassThru);
1806 Value *NewLoadStore = Builder.CreateBitCast(V: MaskedLoadStore, DestTy: Ty);
1807 if (PN)
1808 PN->setIncomingValue(i: PN->getBasicBlockIndex(BB), V: NewLoadStore);
1809 I->replaceAllUsesWith(V: NewLoadStore);
1810 } else {
1811 // Handle Store.
1812 auto *StoredVal = Builder.CreateBitCast(
1813 V: PeekThroughBitcasts(Op0), DestTy: FixedVectorType::get(ElementType: Op0->getType(), NumElts: 1));
1814 MaskedLoadStore = Builder.CreateMaskedStore(
1815 Val: StoredVal, Ptr: I->getOperand(i: 1), Alignment: cast<StoreInst>(Val: I)->getAlign(), Mask);
1816 }
1817 // For non-debug metadata, only !annotation, !range, !nonnull and !align are
1818 // kept when hoisting (see Instruction::dropUBImplyingAttrsAndMetadata).
1819 //
1820 // !nonnull, !align : Not support pointer type, no need to keep.
1821 // !range: Load type is changed from scalar to vector, but the metadata on
1822 // vector specifies a per-element range, so the semantics stay the
1823 // same. Keep it.
1824 // !annotation: Not impact semantics. Keep it.
1825 if (const MDNode *Ranges = I->getMetadata(KindID: LLVMContext::MD_range))
1826 MaskedLoadStore->addRangeRetAttr(CR: getConstantRangeFromMetadata(RangeMD: *Ranges));
1827 I->dropUBImplyingAttrsAndUnknownMetadata(KnownIDs: {LLVMContext::MD_annotation});
1828 // FIXME: DIAssignID is not supported for masked store yet.
1829 // (Verifier::visitDIAssignIDMetadata)
1830 at::deleteAssignmentMarkers(Inst: I);
1831 I->eraseMetadataIf(Pred: [](unsigned MDKind, MDNode *Node) {
1832 return Node->getMetadataID() == Metadata::DIAssignIDKind;
1833 });
1834 MaskedLoadStore->copyMetadata(SrcInst: *I);
1835 I->eraseFromParent();
1836 }
1837}
1838
1839static bool isSafeCheapLoadStore(const Instruction *I,
1840 const TargetTransformInfo &TTI) {
1841 // Not handle volatile or atomic.
1842 bool IsStore = false;
1843 if (auto *L = dyn_cast<LoadInst>(Val: I)) {
1844 if (!L->isSimple() || !HoistLoadsWithCondFaulting)
1845 return false;
1846 } else if (auto *S = dyn_cast<StoreInst>(Val: I)) {
1847 if (!S->isSimple() || !HoistStoresWithCondFaulting)
1848 return false;
1849 IsStore = true;
1850 } else
1851 return false;
1852
1853 // llvm.masked.load/store use i32 for alignment while load/store use i64.
1854 // That's why we have the alignment limitation.
1855 // FIXME: Update the prototype of the intrinsics?
1856 return TTI.hasConditionalLoadStoreForType(Ty: getLoadStoreType(I), IsStore) &&
1857 getLoadStoreAlignment(I) < Value::MaximumAlignment;
1858}
1859
1860/// Hoist any common code in the successor blocks up into the block. This
1861/// function guarantees that BB dominates all successors. If AllInstsEqOnly is
1862/// given, only perform hoisting in case all successors blocks contain matching
1863/// instructions only. In that case, all instructions can be hoisted and the
1864/// original branch will be replaced and selects for PHIs are added.
1865bool SimplifyCFGOpt::hoistCommonCodeFromSuccessors(Instruction *TI,
1866 bool AllInstsEqOnly) {
1867 // This does very trivial matching, with limited scanning, to find identical
1868 // instructions in the two blocks. In particular, we don't want to get into
1869 // O(N1*N2*...) situations here where Ni are the sizes of these successors. As
1870 // such, we currently just scan for obviously identical instructions in an
1871 // identical order, possibly separated by the same number of non-identical
1872 // instructions.
1873 BasicBlock *BB = TI->getParent();
1874 unsigned int SuccSize = succ_size(BB);
1875 if (SuccSize < 2)
1876 return false;
1877
1878 // If either of the blocks has it's address taken, then we can't do this fold,
1879 // because the code we'd hoist would no longer run when we jump into the block
1880 // by it's address.
1881 SmallSetVector<BasicBlock *, 4> UniqueSuccessors(from_range, successors(BB));
1882 for (auto *Succ : UniqueSuccessors) {
1883 if (Succ->hasAddressTaken())
1884 return false;
1885 // Use getUniquePredecessor instead of getSinglePredecessor to support
1886 // multi-cases successors in switch.
1887 if (Succ->getUniquePredecessor())
1888 continue;
1889 // If Succ has >1 predecessors, continue to check if the Succ contains only
1890 // one `unreachable` inst. Since executing `unreachable` inst is an UB, we
1891 // can relax the condition based on the assumptiom that the program would
1892 // never enter Succ and trigger such an UB.
1893 if (isa<UnreachableInst>(Val: *Succ->begin()))
1894 continue;
1895 return false;
1896 }
1897 // The second of pair is a SkipFlags bitmask.
1898 using SuccIterPair = std::pair<BasicBlock::iterator, unsigned>;
1899 SmallVector<SuccIterPair, 8> SuccIterPairs;
1900 for (auto *Succ : UniqueSuccessors) {
1901 BasicBlock::iterator SuccItr = Succ->begin();
1902 if (isa<PHINode>(Val: *SuccItr))
1903 return false;
1904 SuccIterPairs.push_back(Elt: SuccIterPair(SuccItr, 0));
1905 }
1906
1907 if (AllInstsEqOnly) {
1908 // Check if all instructions in the successor blocks match. This allows
1909 // hoisting all instructions and removing the blocks we are hoisting from,
1910 // so does not add any new instructions.
1911
1912 // Check if sizes and terminators of all successors match.
1913 unsigned Size0 = UniqueSuccessors[0]->size();
1914 Instruction *Term0 = UniqueSuccessors[0]->getTerminator();
1915 bool AllSame =
1916 all_of(Range: drop_begin(RangeOrContainer&: UniqueSuccessors), P: [Term0, Size0](BasicBlock *Succ) {
1917 return Succ->getTerminator()->isIdenticalTo(I: Term0) &&
1918 Succ->size() == Size0;
1919 });
1920 if (!AllSame)
1921 return false;
1922 LockstepReverseIterator<true> LRI(UniqueSuccessors.getArrayRef());
1923 while (LRI.isValid()) {
1924 Instruction *I0 = (*LRI)[0];
1925 if (any_of(Range: *LRI, P: [I0](Instruction *I) {
1926 return !areIdenticalUpToCommutativity(I1: I0, I2: I);
1927 })) {
1928 return false;
1929 }
1930 --LRI;
1931 }
1932 // Now we know that all instructions in all successors can be hoisted. Let
1933 // the loop below handle the hoisting.
1934 }
1935
1936 // Count how many instructions were not hoisted so far. There's a limit on how
1937 // many instructions we skip, serving as a compilation time control as well as
1938 // preventing excessive increase of life ranges.
1939 unsigned NumSkipped = 0;
1940 // If we find an unreachable instruction at the beginning of a basic block, we
1941 // can still hoist instructions from the rest of the basic blocks.
1942 if (SuccIterPairs.size() > 2) {
1943 erase_if(C&: SuccIterPairs,
1944 P: [](const auto &Pair) { return isa<UnreachableInst>(Pair.first); });
1945 if (SuccIterPairs.size() < 2)
1946 return false;
1947 }
1948
1949 bool Changed = false;
1950
1951 for (;;) {
1952 auto *SuccIterPairBegin = SuccIterPairs.begin();
1953 auto &BB1ItrPair = *SuccIterPairBegin++;
1954 auto OtherSuccIterPairRange =
1955 iterator_range(SuccIterPairBegin, SuccIterPairs.end());
1956 auto OtherSuccIterRange = make_first_range(c&: OtherSuccIterPairRange);
1957
1958 Instruction *I1 = &*BB1ItrPair.first;
1959
1960 bool AllInstsAreIdentical = true;
1961 bool HasTerminator = I1->isTerminator();
1962 for (auto &SuccIter : OtherSuccIterRange) {
1963 Instruction *I2 = &*SuccIter;
1964 HasTerminator |= I2->isTerminator();
1965 if (AllInstsAreIdentical && (!areIdenticalUpToCommutativity(I1, I2) ||
1966 MMRAMetadata(*I1) != MMRAMetadata(*I2)))
1967 AllInstsAreIdentical = false;
1968 }
1969
1970 SmallVector<Instruction *, 8> OtherInsts;
1971 for (auto &SuccIter : OtherSuccIterRange)
1972 OtherInsts.push_back(Elt: &*SuccIter);
1973
1974 // If we are hoisting the terminator instruction, don't move one (making a
1975 // broken BB), instead clone it, and remove BI.
1976 if (HasTerminator) {
1977 // Even if BB, which contains only one unreachable instruction, is ignored
1978 // at the beginning of the loop, we can hoist the terminator instruction.
1979 // If any instructions remain in the block, we cannot hoist terminators.
1980 if (NumSkipped || !AllInstsAreIdentical) {
1981 hoistLockstepIdenticalDbgVariableRecords(TI, I1, OtherInsts);
1982 return Changed;
1983 }
1984
1985 return hoistSuccIdenticalTerminatorToSwitchOrIf(
1986 TI, I1, OtherSuccTIs&: OtherInsts, UniqueSuccessors: UniqueSuccessors.getArrayRef()) ||
1987 Changed;
1988 }
1989
1990 if (AllInstsAreIdentical) {
1991 unsigned SkipFlagsBB1 = BB1ItrPair.second;
1992 AllInstsAreIdentical =
1993 isSafeToHoistInstr(I: I1, Flags: SkipFlagsBB1) &&
1994 all_of(Range&: OtherSuccIterPairRange, P: [=](const auto &Pair) {
1995 Instruction *I2 = &*Pair.first;
1996 unsigned SkipFlagsBB2 = Pair.second;
1997 // Even if the instructions are identical, it may not
1998 // be safe to hoist them if we have skipped over
1999 // instructions with side effects or their operands
2000 // weren't hoisted.
2001 return isSafeToHoistInstr(I: I2, Flags: SkipFlagsBB2) &&
2002 shouldHoistCommonInstructions(I1, I2, TTI);
2003 });
2004 }
2005
2006 // A musttail call must be immediately followed by a ret, so hoisting is
2007 // only legal if its ret is hoisted with it on the next iteration. That is,
2008 // no instruction has been skipped (the entire successor can be hoisted into
2009 // the predecessor) and the call is directly followed by a ret.
2010 if (auto *CI = dyn_cast<CallInst>(Val: I1);
2011 AllInstsAreIdentical && CI && CI->isMustTailCall()) {
2012 AllInstsAreIdentical =
2013 NumSkipped == 0 && all_of(Range&: SuccIterPairs, P: [](const SuccIterPair &P) {
2014 return isa<ReturnInst>(Val: *std::next(x: P.first));
2015 });
2016 }
2017
2018 if (AllInstsAreIdentical) {
2019 BB1ItrPair.first++;
2020 // For a normal instruction, we just move one to right before the
2021 // branch, then replace all uses of the other with the first. Finally,
2022 // we remove the now redundant second instruction.
2023 hoistLockstepIdenticalDbgVariableRecords(TI, I1, OtherInsts);
2024 // We've just hoisted DbgVariableRecords; move I1 after them (before TI)
2025 // and leave any that were not hoisted behind (by calling moveBefore
2026 // rather than moveBeforePreserving).
2027 I1->moveBefore(InsertPos: TI->getIterator());
2028 for (auto &SuccIter : OtherSuccIterRange) {
2029 Instruction *I2 = &*SuccIter++;
2030 assert(I2 != I1);
2031 if (!I2->use_empty())
2032 I2->replaceAllUsesWith(V: I1);
2033 I1->andIRFlags(V: I2);
2034 if (auto *CB = dyn_cast<CallBase>(Val: I1)) {
2035 bool Success = CB->tryIntersectAttributes(Other: cast<CallBase>(Val: I2));
2036 assert(Success && "We should not be trying to hoist callbases "
2037 "with non-intersectable attributes");
2038 // For NDEBUG Compile.
2039 (void)Success;
2040 }
2041
2042 combineMetadataForCSE(K: I1, J: I2, DoesKMove: true);
2043 // I1 and I2 are being combined into a single instruction. Its debug
2044 // location is the merged locations of the original instructions.
2045 I1->applyMergedLocation(LocA: I1->getDebugLoc(), LocB: I2->getDebugLoc());
2046 I2->eraseFromParent();
2047 }
2048 if (!Changed)
2049 NumHoistCommonCode += SuccIterPairs.size();
2050 Changed = true;
2051 NumHoistCommonInstrs += SuccIterPairs.size();
2052 } else {
2053 if (NumSkipped >= HoistCommonSkipLimit) {
2054 hoistLockstepIdenticalDbgVariableRecords(TI, I1, OtherInsts);
2055 return Changed;
2056 }
2057 // We are about to skip over a pair of non-identical instructions. Record
2058 // if any have characteristics that would prevent reordering instructions
2059 // across them.
2060 for (auto &SuccIterPair : SuccIterPairs) {
2061 Instruction *I = &*SuccIterPair.first++;
2062 SuccIterPair.second |= skippedInstrFlags(I);
2063 }
2064 ++NumSkipped;
2065 }
2066 }
2067}
2068
2069bool SimplifyCFGOpt::hoistSuccIdenticalTerminatorToSwitchOrIf(
2070 Instruction *TI, Instruction *I1,
2071 SmallVectorImpl<Instruction *> &OtherSuccTIs,
2072 ArrayRef<BasicBlock *> UniqueSuccessors) {
2073
2074 auto *BI = dyn_cast<CondBrInst>(Val: TI);
2075
2076 bool Changed = false;
2077 BasicBlock *TIParent = TI->getParent();
2078 BasicBlock *BB1 = I1->getParent();
2079
2080 // Use only for an if statement.
2081 auto *I2 = *OtherSuccTIs.begin();
2082 auto *BB2 = I2->getParent();
2083 if (BI) {
2084 assert(OtherSuccTIs.size() == 1);
2085 assert(BI->getSuccessor(0) == I1->getParent());
2086 assert(BI->getSuccessor(1) == I2->getParent());
2087 }
2088
2089 // In the case of an if statement, we try to hoist an invoke.
2090 // FIXME: Can we define a safety predicate for CallBr?
2091 // FIXME: Test case llvm/test/Transforms/SimplifyCFG/2009-06-15-InvokeCrash.ll
2092 // removed in 4c923b3b3fd0ac1edebf0603265ca3ba51724937 commit?
2093 if (isa<InvokeInst>(Val: I1) && (!BI || !isSafeToHoistInvoke(BB1, BB2, I1, I2)))
2094 return false;
2095
2096 // TODO: callbr hoisting currently disabled pending further study.
2097 if (isa<CallBrInst>(Val: I1))
2098 return false;
2099
2100 for (BasicBlock *Succ : successors(BB: BB1)) {
2101 for (PHINode &PN : Succ->phis()) {
2102 Value *BB1V = PN.getIncomingValueForBlock(BB: BB1);
2103 for (Instruction *OtherSuccTI : OtherSuccTIs) {
2104 Value *BB2V = PN.getIncomingValueForBlock(BB: OtherSuccTI->getParent());
2105 if (BB1V == BB2V)
2106 continue;
2107
2108 // In the case of an if statement, check for
2109 // passingValueIsAlwaysUndefined here because we would rather eliminate
2110 // undefined control flow then converting it to a select.
2111 if (!BI || passingValueIsAlwaysUndefined(V: BB1V, I: &PN) ||
2112 passingValueIsAlwaysUndefined(V: BB2V, I: &PN))
2113 return false;
2114 }
2115 }
2116 }
2117
2118 // Hoist DbgVariableRecords attached to the terminator to match dbg.*
2119 // intrinsic hoisting behaviour in hoistCommonCodeFromSuccessors.
2120 hoistLockstepIdenticalDbgVariableRecords(TI, I1, OtherInsts&: OtherSuccTIs);
2121 // Clone the terminator and hoist it into the pred, without any debug info.
2122 Instruction *NT = I1->clone();
2123 NT->insertInto(ParentBB: TIParent, It: TI->getIterator());
2124 if (!NT->getType()->isVoidTy()) {
2125 I1->replaceAllUsesWith(V: NT);
2126 for (Instruction *OtherSuccTI : OtherSuccTIs)
2127 OtherSuccTI->replaceAllUsesWith(V: NT);
2128 NT->takeName(V: I1);
2129 }
2130 Changed = true;
2131 NumHoistCommonInstrs += OtherSuccTIs.size() + 1;
2132
2133 // Ensure terminator gets a debug location, even an unknown one, in case
2134 // it involves inlinable calls.
2135 SmallVector<DebugLoc, 4> Locs;
2136 Locs.push_back(Elt: I1->getDebugLoc());
2137 for (auto *OtherSuccTI : OtherSuccTIs)
2138 Locs.push_back(Elt: OtherSuccTI->getDebugLoc());
2139 NT->setDebugLoc(DebugLoc::getMergedLocations(Locs));
2140
2141 // PHIs created below will adopt NT's merged DebugLoc.
2142 IRBuilder<NoFolder> Builder(NT);
2143
2144 // In the case of an if statement, hoisting one of the terminators from our
2145 // successor is a great thing. Unfortunately, the successors of the if/else
2146 // blocks may have PHI nodes in them. If they do, all PHI entries for BB1/BB2
2147 // must agree for all PHI nodes, so we insert select instruction to compute
2148 // the final result.
2149 if (BI) {
2150 std::map<std::pair<Value *, Value *>, SelectInst *> InsertedSelects;
2151 for (BasicBlock *Succ : successors(BB: BB1)) {
2152 for (PHINode &PN : Succ->phis()) {
2153 Value *BB1V = PN.getIncomingValueForBlock(BB: BB1);
2154 Value *BB2V = PN.getIncomingValueForBlock(BB: BB2);
2155 if (BB1V == BB2V)
2156 continue;
2157
2158 // These values do not agree. Insert a select instruction before NT
2159 // that determines the right value.
2160 SelectInst *&SI = InsertedSelects[std::make_pair(x&: BB1V, y&: BB2V)];
2161 if (!SI) {
2162 // Propagate fast-math-flags from phi node to its replacement select.
2163 SI = cast<SelectInst>(Val: Builder.CreateSelectFMF(
2164 C: BI->getCondition(), True: BB1V, False: BB2V,
2165 FMFSource: isa<FPMathOperator>(Val: PN) ? &PN : nullptr,
2166 Name: BB1V->getName() + "." + BB2V->getName(), MDFrom: BI));
2167 }
2168
2169 // Make the PHI node use the select for all incoming values for BB1/BB2
2170 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
2171 if (PN.getIncomingBlock(i) == BB1 || PN.getIncomingBlock(i) == BB2)
2172 PN.setIncomingValue(i, V: SI);
2173 }
2174 }
2175 }
2176
2177 SmallVector<DominatorTree::UpdateType, 4> Updates;
2178
2179 // Update any PHI nodes in our new successors.
2180 SmallPtrSet<BasicBlock *, 8> VisitedSuccs;
2181 for (BasicBlock *Succ : successors(BB: BB1)) {
2182 addPredecessorToBlock(Succ, NewPred: TIParent, ExistPred: BB1);
2183
2184 if (DTU && VisitedSuccs.insert(Ptr: Succ).second)
2185 Updates.push_back(Elt: {DominatorTree::Insert, TIParent, Succ});
2186 }
2187
2188 if (DTU) {
2189 // TI might be a switch with multi-cases destination, so we need to care for
2190 // the duplication of successors.
2191 for (BasicBlock *Succ : UniqueSuccessors)
2192 Updates.push_back(Elt: {DominatorTree::Delete, TIParent, Succ});
2193 }
2194
2195 eraseTerminatorAndDCECond(TI);
2196 if (DTU)
2197 DTU->applyUpdates(Updates);
2198 return Changed;
2199}
2200
2201// TODO: Refine this. This should avoid cases like turning constant memcpy sizes
2202// into variables.
2203static bool replacingOperandWithVariableIsCheap(const Instruction *I,
2204 int OpIdx) {
2205 // Divide/Remainder by constant is typically much cheaper than by variable.
2206 if (I->isIntDivRem())
2207 return OpIdx != 1;
2208 return !isa<IntrinsicInst>(Val: I);
2209}
2210
2211// All instructions in Insts belong to different blocks that all unconditionally
2212// branch to a common successor. Analyze each instruction and return true if it
2213// would be possible to sink them into their successor, creating one common
2214// instruction instead. For every value that would be required to be provided by
2215// PHI node (because an operand varies in each input block), add to PHIOperands.
2216static bool canSinkInstructions(
2217 ArrayRef<Instruction *> Insts,
2218 DenseMap<const Use *, SmallVector<Value *, 4>> &PHIOperands) {
2219 // Prune out obviously bad instructions to move. Each instruction must have
2220 // the same number of uses, and we check later that the uses are consistent.
2221 std::optional<unsigned> NumUses;
2222 for (auto *I : Insts) {
2223 // These instructions may change or break semantics if moved.
2224 if (isa<PHINode>(Val: I) || I->isEHPad() || isa<AllocaInst>(Val: I) ||
2225 I->getType()->isTokenTy())
2226 return false;
2227
2228 // Do not try to sink an instruction in an infinite loop - it can cause
2229 // this algorithm to infinite loop.
2230 if (I->getParent()->getSingleSuccessor() == I->getParent())
2231 return false;
2232
2233 // Conservatively return false if I is an inline-asm instruction. Sinking
2234 // and merging inline-asm instructions can potentially create arguments
2235 // that cannot satisfy the inline-asm constraints.
2236 // If the instruction has nomerge or convergent attribute, return false.
2237 if (const auto *C = dyn_cast<CallBase>(Val: I))
2238 if (C->isInlineAsm() || C->cannotMerge() || C->isConvergent())
2239 return false;
2240
2241 if (!NumUses)
2242 NumUses = I->getNumUses();
2243 else if (NumUses != I->getNumUses())
2244 return false;
2245 }
2246
2247 const Instruction *I0 = Insts.front();
2248 const auto I0MMRA = MMRAMetadata(*I0);
2249 for (auto *I : Insts) {
2250 if (!I->isSameOperationAs(I: I0, flags: Instruction::CompareUsingIntersectedAttrs))
2251 return false;
2252
2253 // Treat MMRAs conservatively. This pass can be quite aggressive and
2254 // could drop a lot of MMRAs otherwise.
2255 if (MMRAMetadata(*I) != I0MMRA)
2256 return false;
2257 }
2258
2259 // Uses must be consistent: If I0 is used in a phi node in the sink target,
2260 // then the other phi operands must match the instructions from Insts. This
2261 // also has to hold true for any phi nodes that would be created as a result
2262 // of sinking. Both of these cases are represented by PhiOperands.
2263 for (const Use &U : I0->uses()) {
2264 auto It = PHIOperands.find(Val: &U);
2265 if (It == PHIOperands.end())
2266 // There may be uses in other blocks when sinking into a loop header.
2267 return false;
2268 if (!equal(LRange&: Insts, RRange&: It->second))
2269 return false;
2270 }
2271
2272 // For calls to be sinkable, they must all be indirect, or have same callee.
2273 // I.e. if we have two direct calls to different callees, we don't want to
2274 // turn that into an indirect call. Likewise, if we have an indirect call,
2275 // and a direct call, we don't actually want to have a single indirect call.
2276 if (isa<CallBase>(Val: I0)) {
2277 auto IsIndirectCall = [](const Instruction *I) {
2278 return cast<CallBase>(Val: I)->isIndirectCall();
2279 };
2280 bool HaveIndirectCalls = any_of(Range&: Insts, P: IsIndirectCall);
2281 bool AllCallsAreIndirect = all_of(Range&: Insts, P: IsIndirectCall);
2282 if (HaveIndirectCalls) {
2283 if (!AllCallsAreIndirect)
2284 return false;
2285 } else {
2286 // All callees must be identical.
2287 Value *Callee = nullptr;
2288 for (const Instruction *I : Insts) {
2289 Value *CurrCallee = cast<CallBase>(Val: I)->getCalledOperand();
2290 if (!Callee)
2291 Callee = CurrCallee;
2292 else if (Callee != CurrCallee)
2293 return false;
2294 }
2295 }
2296 }
2297
2298 for (unsigned OI = 0, OE = I0->getNumOperands(); OI != OE; ++OI) {
2299 Value *Op = I0->getOperand(i: OI);
2300 auto SameAsI0 = [&I0, OI](const Instruction *I) {
2301 assert(I->getNumOperands() == I0->getNumOperands());
2302 return I->getOperand(i: OI) == I0->getOperand(i: OI);
2303 };
2304 if (!all_of(Range&: Insts, P: SameAsI0)) {
2305 auto CanReplaceOperand = [OI](const Instruction *I) {
2306 return canReplaceOperandWithVariable(I, OpIdx: OI);
2307 };
2308 if ((isa<Constant>(Val: Op) && !replacingOperandWithVariableIsCheap(I: I0, OpIdx: OI)) ||
2309 !all_of(Range&: Insts, P: CanReplaceOperand))
2310 // We can't create a PHI from this operand.
2311 return false;
2312 auto &Ops = PHIOperands[&I0->getOperandUse(i: OI)];
2313 for (auto *I : Insts)
2314 Ops.push_back(Elt: I->getOperand(i: OI));
2315 }
2316 }
2317 return true;
2318}
2319
2320// Assuming canSinkInstructions(Blocks) has returned true, sink the last
2321// instruction of every block in Blocks to their common successor, commoning
2322// into one instruction.
2323static void sinkLastInstruction(ArrayRef<BasicBlock*> Blocks) {
2324 auto *BBEnd = Blocks[0]->getTerminator()->getSuccessor(Idx: 0);
2325
2326 // canSinkInstructions returning true guarantees that every block has at
2327 // least one non-terminator instruction.
2328 SmallVector<Instruction*,4> Insts;
2329 for (auto *BB : Blocks) {
2330 Instruction *I = BB->getTerminator();
2331 I = I->getPrevNode();
2332 Insts.push_back(Elt: I);
2333 }
2334
2335 // We don't need to do any more checking here; canSinkInstructions should
2336 // have done it all for us.
2337 SmallVector<Value*, 4> NewOperands;
2338 Instruction *I0 = Insts.front();
2339 for (unsigned O = 0, E = I0->getNumOperands(); O != E; ++O) {
2340 // This check is different to that in canSinkInstructions. There, we
2341 // cared about the global view once simplifycfg (and instcombine) have
2342 // completed - it takes into account PHIs that become trivially
2343 // simplifiable. However here we need a more local view; if an operand
2344 // differs we create a PHI and rely on instcombine to clean up the very
2345 // small mess we may make.
2346 bool NeedPHI = any_of(Range&: Insts, P: [&I0, O](const Instruction *I) {
2347 return I->getOperand(i: O) != I0->getOperand(i: O);
2348 });
2349 if (!NeedPHI) {
2350 NewOperands.push_back(Elt: I0->getOperand(i: O));
2351 continue;
2352 }
2353
2354 // Create a new PHI in the successor block and populate it.
2355 auto *Op = I0->getOperand(i: O);
2356 assert(!Op->getType()->isTokenTy() && "Can't PHI tokens!");
2357 auto *PN =
2358 PHINode::Create(Ty: Op->getType(), NumReservedValues: Insts.size(), NameStr: Op->getName() + ".sink");
2359 PN->insertBefore(InsertPos: BBEnd->begin());
2360 for (auto *I : Insts)
2361 PN->addIncoming(V: I->getOperand(i: O), BB: I->getParent());
2362 NewOperands.push_back(Elt: PN);
2363 }
2364
2365 // Arbitrarily use I0 as the new "common" instruction; remap its operands
2366 // and move it to the start of the successor block.
2367 for (unsigned O = 0, E = I0->getNumOperands(); O != E; ++O)
2368 I0->getOperandUse(i: O).set(NewOperands[O]);
2369
2370 I0->moveBefore(BB&: *BBEnd, I: BBEnd->getFirstInsertionPt());
2371
2372 // Update metadata and IR flags, and merge debug locations.
2373 for (auto *I : Insts)
2374 if (I != I0) {
2375 // The debug location for the "common" instruction is the merged locations
2376 // of all the commoned instructions. We start with the original location
2377 // of the "common" instruction and iteratively merge each location in the
2378 // loop below.
2379 // This is an N-way merge, which will be inefficient if I0 is a CallInst.
2380 // However, as N-way merge for CallInst is rare, so we use simplified API
2381 // instead of using complex API for N-way merge.
2382 I0->applyMergedLocation(LocA: I0->getDebugLoc(), LocB: I->getDebugLoc());
2383 combineMetadataForCSE(K: I0, J: I, DoesKMove: true);
2384 I0->andIRFlags(V: I);
2385 if (auto *CB = dyn_cast<CallBase>(Val: I0)) {
2386 bool Success = CB->tryIntersectAttributes(Other: cast<CallBase>(Val: I));
2387 assert(Success && "We should not be trying to sink callbases "
2388 "with non-intersectable attributes");
2389 // For NDEBUG Compile.
2390 (void)Success;
2391 }
2392 }
2393
2394 for (User *U : make_early_inc_range(Range: I0->users())) {
2395 // canSinkLastInstruction checked that all instructions are only used by
2396 // phi nodes in a way that allows replacing the phi node with the common
2397 // instruction.
2398 auto *PN = cast<PHINode>(Val: U);
2399 PN->replaceAllUsesWith(V: I0);
2400 PN->eraseFromParent();
2401 }
2402
2403 // Finally nuke all instructions apart from the common instruction.
2404 for (auto *I : Insts) {
2405 if (I == I0)
2406 continue;
2407 // The remaining uses are debug users, replace those with the common inst.
2408 // In most (all?) cases this just introduces a use-before-def.
2409 assert(I->user_empty() && "Inst unexpectedly still has non-dbg users");
2410 I->replaceAllUsesWith(V: I0);
2411 I->eraseFromParent();
2412 }
2413}
2414
2415/// Check whether BB's predecessors end with unconditional branches. If it is
2416/// true, sink any common code from the predecessors to BB.
2417static bool sinkCommonCodeFromPredecessors(BasicBlock *BB,
2418 DomTreeUpdater *DTU) {
2419 // We support two situations:
2420 // (1) all incoming arcs are unconditional
2421 // (2) there are non-unconditional incoming arcs
2422 //
2423 // (2) is very common in switch defaults and
2424 // else-if patterns;
2425 //
2426 // if (a) f(1);
2427 // else if (b) f(2);
2428 //
2429 // produces:
2430 //
2431 // [if]
2432 // / \
2433 // [f(1)] [if]
2434 // | | \
2435 // | | |
2436 // | [f(2)]|
2437 // \ | /
2438 // [ end ]
2439 //
2440 // [end] has two unconditional predecessor arcs and one conditional. The
2441 // conditional refers to the implicit empty 'else' arc. This conditional
2442 // arc can also be caused by an empty default block in a switch.
2443 //
2444 // In this case, we attempt to sink code from all *unconditional* arcs.
2445 // If we can sink instructions from these arcs (determined during the scan
2446 // phase below) we insert a common successor for all unconditional arcs and
2447 // connect that to [end], to enable sinking:
2448 //
2449 // [if]
2450 // / \
2451 // [x(1)] [if]
2452 // | | \
2453 // | | \
2454 // | [x(2)] |
2455 // \ / |
2456 // [sink.split] |
2457 // \ /
2458 // [ end ]
2459 //
2460 SmallVector<BasicBlock*,4> UnconditionalPreds;
2461 bool HaveNonUnconditionalPredecessors = false;
2462 for (auto *PredBB : predecessors(BB)) {
2463 auto *PredBr = dyn_cast<UncondBrInst>(Val: PredBB->getTerminator());
2464 if (PredBr)
2465 UnconditionalPreds.push_back(Elt: PredBB);
2466 else
2467 HaveNonUnconditionalPredecessors = true;
2468 }
2469 if (UnconditionalPreds.size() < 2)
2470 return false;
2471
2472 // We take a two-step approach to tail sinking. First we scan from the end of
2473 // each block upwards in lockstep. If the n'th instruction from the end of each
2474 // block can be sunk, those instructions are added to ValuesToSink and we
2475 // carry on. If we can sink an instruction but need to PHI-merge some operands
2476 // (because they're not identical in each instruction) we add these to
2477 // PHIOperands.
2478 // We prepopulate PHIOperands with the phis that already exist in BB.
2479 DenseMap<const Use *, SmallVector<Value *, 4>> PHIOperands;
2480 for (PHINode &PN : BB->phis()) {
2481 SmallDenseMap<BasicBlock *, const Use *, 4> IncomingVals;
2482 for (const Use &U : PN.incoming_values())
2483 IncomingVals.insert(KV: {PN.getIncomingBlock(U), &U});
2484 auto &Ops = PHIOperands[IncomingVals[UnconditionalPreds[0]]];
2485 for (BasicBlock *Pred : UnconditionalPreds)
2486 Ops.push_back(Elt: *IncomingVals[Pred]);
2487 }
2488
2489 int ScanIdx = 0;
2490 SmallPtrSet<Value*,4> InstructionsToSink;
2491 LockstepReverseIterator<true> LRI(UnconditionalPreds);
2492 while (LRI.isValid() &&
2493 canSinkInstructions(Insts: *LRI, PHIOperands)) {
2494 LLVM_DEBUG(dbgs() << "SINK: instruction can be sunk: " << *(*LRI)[0]
2495 << "\n");
2496 InstructionsToSink.insert_range(R: *LRI);
2497 ++ScanIdx;
2498 --LRI;
2499 }
2500
2501 // If no instructions can be sunk, early-return.
2502 if (ScanIdx == 0)
2503 return false;
2504
2505 bool followedByDeoptOrUnreachable = IsBlockFollowedByDeoptOrUnreachable(BB);
2506
2507 if (!followedByDeoptOrUnreachable) {
2508 // Check whether this is the pointer operand of a load/store.
2509 auto IsMemOperand = [](Use &U) {
2510 auto *I = cast<Instruction>(Val: U.getUser());
2511 if (isa<LoadInst>(Val: I))
2512 return U.getOperandNo() == LoadInst::getPointerOperandIndex();
2513 if (isa<StoreInst>(Val: I))
2514 return U.getOperandNo() == StoreInst::getPointerOperandIndex();
2515 return false;
2516 };
2517
2518 // Okay, we *could* sink last ScanIdx instructions. But how many can we
2519 // actually sink before encountering instruction that is unprofitable to
2520 // sink?
2521 auto ProfitableToSinkInstruction = [&](LockstepReverseIterator<true> &LRI) {
2522 unsigned NumPHIInsts = 0;
2523 for (Use &U : (*LRI)[0]->operands()) {
2524 auto It = PHIOperands.find(Val: &U);
2525 if (It != PHIOperands.end() && !all_of(Range&: It->second, P: [&](Value *V) {
2526 return InstructionsToSink.contains(Ptr: V);
2527 })) {
2528 ++NumPHIInsts;
2529 // Do not separate a load/store from the gep producing the address.
2530 // The gep can likely be folded into the load/store as an addressing
2531 // mode. Additionally, a load of a gep is easier to analyze than a
2532 // load of a phi.
2533 if (IsMemOperand(U) &&
2534 any_of(Range&: It->second, P: [](Value *V) { return isa<GEPOperator>(Val: V); }))
2535 return false;
2536 // FIXME: this check is overly optimistic. We may end up not sinking
2537 // said instruction, due to the very same profitability check.
2538 // See @creating_too_many_phis in sink-common-code.ll.
2539 }
2540 }
2541 LLVM_DEBUG(dbgs() << "SINK: #phi insts: " << NumPHIInsts << "\n");
2542 return NumPHIInsts <= 1;
2543 };
2544
2545 // We've determined that we are going to sink last ScanIdx instructions,
2546 // and recorded them in InstructionsToSink. Now, some instructions may be
2547 // unprofitable to sink. But that determination depends on the instructions
2548 // that we are going to sink.
2549
2550 // First, forward scan: find the first instruction unprofitable to sink,
2551 // recording all the ones that are profitable to sink.
2552 // FIXME: would it be better, after we detect that not all are profitable.
2553 // to either record the profitable ones, or erase the unprofitable ones?
2554 // Maybe we need to choose (at runtime) the one that will touch least
2555 // instrs?
2556 LRI.reset();
2557 int Idx = 0;
2558 SmallPtrSet<Value *, 4> InstructionsProfitableToSink;
2559 while (Idx < ScanIdx) {
2560 if (!ProfitableToSinkInstruction(LRI)) {
2561 // Too many PHIs would be created.
2562 LLVM_DEBUG(
2563 dbgs() << "SINK: stopping here, too many PHIs would be created!\n");
2564 break;
2565 }
2566 InstructionsProfitableToSink.insert_range(R: *LRI);
2567 --LRI;
2568 ++Idx;
2569 }
2570
2571 // If no instructions can be sunk, early-return.
2572 if (Idx == 0)
2573 return false;
2574
2575 // Did we determine that (only) some instructions are unprofitable to sink?
2576 if (Idx < ScanIdx) {
2577 // Okay, some instructions are unprofitable.
2578 ScanIdx = Idx;
2579 InstructionsToSink = InstructionsProfitableToSink;
2580
2581 // But, that may make other instructions unprofitable, too.
2582 // So, do a backward scan, do any earlier instructions become
2583 // unprofitable?
2584 assert(
2585 !ProfitableToSinkInstruction(LRI) &&
2586 "We already know that the last instruction is unprofitable to sink");
2587 ++LRI;
2588 --Idx;
2589 while (Idx >= 0) {
2590 // If we detect that an instruction becomes unprofitable to sink,
2591 // all earlier instructions won't be sunk either,
2592 // so preemptively keep InstructionsProfitableToSink in sync.
2593 // FIXME: is this the most performant approach?
2594 for (auto *I : *LRI)
2595 InstructionsProfitableToSink.erase(Ptr: I);
2596 if (!ProfitableToSinkInstruction(LRI)) {
2597 // Everything starting with this instruction won't be sunk.
2598 ScanIdx = Idx;
2599 InstructionsToSink = InstructionsProfitableToSink;
2600 }
2601 ++LRI;
2602 --Idx;
2603 }
2604 }
2605
2606 // If no instructions can be sunk, early-return.
2607 if (ScanIdx == 0)
2608 return false;
2609 }
2610
2611 bool Changed = false;
2612
2613 if (HaveNonUnconditionalPredecessors) {
2614 if (!followedByDeoptOrUnreachable) {
2615 // It is always legal to sink common instructions from unconditional
2616 // predecessors. However, if not all predecessors are unconditional,
2617 // this transformation might be pessimizing. So as a rule of thumb,
2618 // don't do it unless we'd sink at least one non-speculatable instruction.
2619 // See https://bugs.llvm.org/show_bug.cgi?id=30244
2620 LRI.reset();
2621 int Idx = 0;
2622 bool Profitable = false;
2623 while (Idx < ScanIdx) {
2624 if (!isSafeToSpeculativelyExecute(I: (*LRI)[0])) {
2625 Profitable = true;
2626 break;
2627 }
2628 --LRI;
2629 ++Idx;
2630 }
2631 if (!Profitable)
2632 return false;
2633 }
2634
2635 LLVM_DEBUG(dbgs() << "SINK: Splitting edge\n");
2636 // We have a conditional edge and we're going to sink some instructions.
2637 // Insert a new block postdominating all blocks we're going to sink from.
2638 if (!SplitBlockPredecessors(BB, Preds: UnconditionalPreds, Suffix: ".sink.split", DTU))
2639 // Edges couldn't be split.
2640 return false;
2641 Changed = true;
2642 }
2643
2644 // Now that we've analyzed all potential sinking candidates, perform the
2645 // actual sink. We iteratively sink the last non-terminator of the source
2646 // blocks into their common successor unless doing so would require too
2647 // many PHI instructions to be generated (currently only one PHI is allowed
2648 // per sunk instruction).
2649 //
2650 // We can use InstructionsToSink to discount values needing PHI-merging that will
2651 // actually be sunk in a later iteration. This allows us to be more
2652 // aggressive in what we sink. This does allow a false positive where we
2653 // sink presuming a later value will also be sunk, but stop half way through
2654 // and never actually sink it which means we produce more PHIs than intended.
2655 // This is unlikely in practice though.
2656 int SinkIdx = 0;
2657 for (; SinkIdx != ScanIdx; ++SinkIdx) {
2658 LLVM_DEBUG(dbgs() << "SINK: Sink: "
2659 << *UnconditionalPreds[0]->getTerminator()->getPrevNode()
2660 << "\n");
2661
2662 // Because we've sunk every instruction in turn, the current instruction to
2663 // sink is always at index 0.
2664 LRI.reset();
2665
2666 sinkLastInstruction(Blocks: UnconditionalPreds);
2667 NumSinkCommonInstrs++;
2668 Changed = true;
2669 }
2670 if (SinkIdx != 0)
2671 ++NumSinkCommonCode;
2672 return Changed;
2673}
2674
2675namespace {
2676
2677struct CompatibleSets {
2678 using SetTy = SmallVector<InvokeInst *, 2>;
2679
2680 SmallVector<SetTy, 1> Sets;
2681
2682 static bool shouldBelongToSameSet(ArrayRef<InvokeInst *> Invokes);
2683
2684 SetTy &getCompatibleSet(InvokeInst *II);
2685
2686 void insert(InvokeInst *II);
2687};
2688
2689CompatibleSets::SetTy &CompatibleSets::getCompatibleSet(InvokeInst *II) {
2690 // Perform a linear scan over all the existing sets, see if the new `invoke`
2691 // is compatible with any particular set. Since we know that all the `invokes`
2692 // within a set are compatible, only check the first `invoke` in each set.
2693 // WARNING: at worst, this has quadratic complexity.
2694 for (CompatibleSets::SetTy &Set : Sets) {
2695 if (CompatibleSets::shouldBelongToSameSet(Invokes: {Set.front(), II}))
2696 return Set;
2697 }
2698
2699 // Otherwise, we either had no sets yet, or this invoke forms a new set.
2700 return Sets.emplace_back();
2701}
2702
2703void CompatibleSets::insert(InvokeInst *II) {
2704 getCompatibleSet(II).emplace_back(Args&: II);
2705}
2706
2707bool CompatibleSets::shouldBelongToSameSet(ArrayRef<InvokeInst *> Invokes) {
2708 assert(Invokes.size() == 2 && "Always called with exactly two candidates.");
2709
2710 // Can we theoretically merge these `invoke`s?
2711 auto IsIllegalToMerge = [](InvokeInst *II) {
2712 return II->cannotMerge() || II->isInlineAsm();
2713 };
2714 if (any_of(Range&: Invokes, P: IsIllegalToMerge))
2715 return false;
2716
2717 // Either both `invoke`s must be direct,
2718 // or both `invoke`s must be indirect.
2719 auto IsIndirectCall = [](InvokeInst *II) { return II->isIndirectCall(); };
2720 bool HaveIndirectCalls = any_of(Range&: Invokes, P: IsIndirectCall);
2721 bool AllCallsAreIndirect = all_of(Range&: Invokes, P: IsIndirectCall);
2722 if (HaveIndirectCalls) {
2723 if (!AllCallsAreIndirect)
2724 return false;
2725 } else {
2726 // All callees must be identical.
2727 Value *Callee = nullptr;
2728 for (InvokeInst *II : Invokes) {
2729 Value *CurrCallee = II->getCalledOperand();
2730 assert(CurrCallee && "There is always a called operand.");
2731 if (!Callee)
2732 Callee = CurrCallee;
2733 else if (Callee != CurrCallee)
2734 return false;
2735 }
2736 }
2737
2738 // Either both `invoke`s must not have a normal destination,
2739 // or both `invoke`s must have a normal destination,
2740 auto HasNormalDest = [](InvokeInst *II) {
2741 return !isa<UnreachableInst>(Val: II->getNormalDest()->getFirstNonPHIOrDbg());
2742 };
2743 if (any_of(Range&: Invokes, P: HasNormalDest)) {
2744 // Do not merge `invoke` that does not have a normal destination with one
2745 // that does have a normal destination, even though doing so would be legal.
2746 if (!all_of(Range&: Invokes, P: HasNormalDest))
2747 return false;
2748
2749 // All normal destinations must be identical.
2750 BasicBlock *NormalBB = nullptr;
2751 for (InvokeInst *II : Invokes) {
2752 BasicBlock *CurrNormalBB = II->getNormalDest();
2753 assert(CurrNormalBB && "There is always a 'continue to' basic block.");
2754 if (!NormalBB)
2755 NormalBB = CurrNormalBB;
2756 else if (NormalBB != CurrNormalBB)
2757 return false;
2758 }
2759
2760 // In the normal destination, the incoming values for these two `invoke`s
2761 // must be compatible.
2762 SmallPtrSet<Value *, 16> EquivalenceSet(llvm::from_range, Invokes);
2763 if (!incomingValuesAreCompatible(
2764 BB: NormalBB, IncomingBlocks: {Invokes[0]->getParent(), Invokes[1]->getParent()},
2765 EquivalenceSet: &EquivalenceSet))
2766 return false;
2767 }
2768
2769#ifndef NDEBUG
2770 // All unwind destinations must be identical.
2771 // We know that because we have started from said unwind destination.
2772 BasicBlock *UnwindBB = nullptr;
2773 for (InvokeInst *II : Invokes) {
2774 BasicBlock *CurrUnwindBB = II->getUnwindDest();
2775 assert(CurrUnwindBB && "There is always an 'unwind to' basic block.");
2776 if (!UnwindBB)
2777 UnwindBB = CurrUnwindBB;
2778 else
2779 assert(UnwindBB == CurrUnwindBB && "Unexpected unwind destination.");
2780 }
2781#endif
2782
2783 // In the unwind destination, the incoming values for these two `invoke`s
2784 // must be compatible.
2785 if (!incomingValuesAreCompatible(
2786 BB: Invokes.front()->getUnwindDest(),
2787 IncomingBlocks: {Invokes[0]->getParent(), Invokes[1]->getParent()}))
2788 return false;
2789
2790 // Ignoring arguments, these `invoke`s must be identical,
2791 // including operand bundles.
2792 const InvokeInst *II0 = Invokes.front();
2793 for (auto *II : Invokes.drop_front())
2794 if (!II->isSameOperationAs(I: II0, flags: Instruction::CompareUsingIntersectedAttrs))
2795 return false;
2796
2797 // Can we theoretically form the data operands for the merged `invoke`?
2798 auto IsIllegalToMergeArguments = [](auto Ops) {
2799 Use &U0 = std::get<0>(Ops);
2800 Use &U1 = std::get<1>(Ops);
2801 if (U0 == U1)
2802 return false;
2803 return !canReplaceOperandWithVariable(I: cast<Instruction>(Val: U0.getUser()),
2804 OpIdx: U0.getOperandNo());
2805 };
2806 assert(Invokes.size() == 2 && "Always called with exactly two candidates.");
2807 if (any_of(Range: zip(t: Invokes[0]->data_ops(), u: Invokes[1]->data_ops()),
2808 P: IsIllegalToMergeArguments))
2809 return false;
2810
2811 return true;
2812}
2813
2814} // namespace
2815
2816// Merge all invokes in the provided set, all of which are compatible
2817// as per the `CompatibleSets::shouldBelongToSameSet()`.
2818static void mergeCompatibleInvokesImpl(ArrayRef<InvokeInst *> Invokes,
2819 DomTreeUpdater *DTU) {
2820 assert(Invokes.size() >= 2 && "Must have at least two invokes to merge.");
2821
2822 SmallVector<DominatorTree::UpdateType, 8> Updates;
2823 if (DTU)
2824 Updates.reserve(N: 2 + 3 * Invokes.size());
2825
2826 bool HasNormalDest =
2827 !isa<UnreachableInst>(Val: Invokes[0]->getNormalDest()->getFirstNonPHIOrDbg());
2828
2829 // Clone one of the invokes into a new basic block.
2830 // Since they are all compatible, it doesn't matter which invoke is cloned.
2831 InvokeInst *MergedInvoke = [&Invokes, HasNormalDest]() {
2832 InvokeInst *II0 = Invokes.front();
2833 BasicBlock *II0BB = II0->getParent();
2834 BasicBlock *InsertBeforeBlock =
2835 II0->getParent()->getIterator()->getNextNode();
2836 Function *Func = II0BB->getParent();
2837 LLVMContext &Ctx = II0->getContext();
2838
2839 BasicBlock *MergedInvokeBB = BasicBlock::Create(
2840 Context&: Ctx, Name: II0BB->getName() + ".invoke", Parent: Func, InsertBefore: InsertBeforeBlock);
2841
2842 auto *MergedInvoke = cast<InvokeInst>(Val: II0->clone());
2843 // NOTE: all invokes have the same attributes, so no handling needed.
2844 MergedInvoke->insertInto(ParentBB: MergedInvokeBB, It: MergedInvokeBB->end());
2845
2846 if (!HasNormalDest) {
2847 // This set does not have a normal destination,
2848 // so just form a new block with unreachable terminator.
2849 BasicBlock *MergedNormalDest = BasicBlock::Create(
2850 Context&: Ctx, Name: II0BB->getName() + ".cont", Parent: Func, InsertBefore: InsertBeforeBlock);
2851 auto *UI = new UnreachableInst(Ctx, MergedNormalDest);
2852 UI->setDebugLoc(DebugLoc::getTemporary());
2853 MergedInvoke->setNormalDest(MergedNormalDest);
2854 }
2855
2856 // The unwind destination, however, remainds identical for all invokes here.
2857
2858 return MergedInvoke;
2859 }();
2860
2861 if (DTU) {
2862 // Predecessor blocks that contained these invokes will now branch to
2863 // the new block that contains the merged invoke, ...
2864 for (InvokeInst *II : Invokes)
2865 Updates.push_back(
2866 Elt: {DominatorTree::Insert, II->getParent(), MergedInvoke->getParent()});
2867
2868 // ... which has the new `unreachable` block as normal destination,
2869 // or unwinds to the (same for all `invoke`s in this set) `landingpad`,
2870 for (BasicBlock *SuccBBOfMergedInvoke : successors(I: MergedInvoke))
2871 Updates.push_back(Elt: {DominatorTree::Insert, MergedInvoke->getParent(),
2872 SuccBBOfMergedInvoke});
2873
2874 // Since predecessor blocks now unconditionally branch to a new block,
2875 // they no longer branch to their original successors.
2876 for (InvokeInst *II : Invokes)
2877 for (BasicBlock *SuccOfPredBB : successors(BB: II->getParent()))
2878 Updates.push_back(
2879 Elt: {DominatorTree::Delete, II->getParent(), SuccOfPredBB});
2880 }
2881
2882 bool IsIndirectCall = Invokes[0]->isIndirectCall();
2883
2884 // Form the merged operands for the merged invoke.
2885 for (Use &U : MergedInvoke->operands()) {
2886 // Only PHI together the indirect callees and data operands.
2887 if (MergedInvoke->isCallee(U: &U)) {
2888 if (!IsIndirectCall)
2889 continue;
2890 } else if (!MergedInvoke->isDataOperand(U: &U))
2891 continue;
2892
2893 // Don't create trivial PHI's with all-identical incoming values.
2894 bool NeedPHI = any_of(Range&: Invokes, P: [&U](InvokeInst *II) {
2895 return II->getOperand(i_nocapture: U.getOperandNo()) != U.get();
2896 });
2897 if (!NeedPHI)
2898 continue;
2899
2900 // Form a PHI out of all the data ops under this index.
2901 PHINode *PN = PHINode::Create(
2902 Ty: U->getType(), /*NumReservedValues=*/Invokes.size(), NameStr: "", InsertBefore: MergedInvoke->getIterator());
2903 for (InvokeInst *II : Invokes)
2904 PN->addIncoming(V: II->getOperand(i_nocapture: U.getOperandNo()), BB: II->getParent());
2905
2906 U.set(PN);
2907 }
2908
2909 // We've ensured that each PHI node has compatible (identical) incoming values
2910 // when coming from each of the `invoke`s in the current merge set,
2911 // so update the PHI nodes accordingly.
2912 for (BasicBlock *Succ : successors(I: MergedInvoke))
2913 addPredecessorToBlock(Succ, /*NewPred=*/MergedInvoke->getParent(),
2914 /*ExistPred=*/Invokes.front()->getParent());
2915
2916 // And finally, replace the original `invoke`s with an unconditional branch
2917 // to the block with the merged `invoke`. Also, give that merged `invoke`
2918 // the merged debugloc of all the original `invoke`s.
2919 DILocation *MergedDebugLoc = nullptr;
2920 for (InvokeInst *II : Invokes) {
2921 // Compute the debug location common to all the original `invoke`s.
2922 if (!MergedDebugLoc)
2923 MergedDebugLoc = II->getDebugLoc();
2924 else
2925 MergedDebugLoc =
2926 DebugLoc::getMergedLocation(LocA: MergedDebugLoc, LocB: II->getDebugLoc());
2927
2928 // And replace the old `invoke` with an unconditionally branch
2929 // to the block with the merged `invoke`.
2930 for (BasicBlock *OrigSuccBB : successors(BB: II->getParent()))
2931 OrigSuccBB->removePredecessor(Pred: II->getParent());
2932 auto *BI = UncondBrInst::Create(Target: MergedInvoke->getParent(), InsertBefore: II->getParent());
2933 // The unconditional branch is part of the replacement for the original
2934 // invoke, so should use its DebugLoc.
2935 BI->setDebugLoc(II->getDebugLoc());
2936 bool Success = MergedInvoke->tryIntersectAttributes(Other: II);
2937 assert(Success && "Merged invokes with incompatible attributes");
2938 // For NDEBUG Compile
2939 (void)Success;
2940 II->replaceAllUsesWith(V: MergedInvoke);
2941 II->eraseFromParent();
2942 ++NumInvokesMerged;
2943 }
2944 MergedInvoke->setDebugLoc(MergedDebugLoc);
2945 ++NumInvokeSetsFormed;
2946
2947 if (DTU)
2948 DTU->applyUpdates(Updates);
2949}
2950
2951/// If this block is a `landingpad` exception handling block, categorize all
2952/// the predecessor `invoke`s into sets, with all `invoke`s in each set
2953/// being "mergeable" together, and then merge invokes in each set together.
2954///
2955/// This is a weird mix of hoisting and sinking. Visually, it goes from:
2956/// [...] [...]
2957/// | |
2958/// [invoke0] [invoke1]
2959/// / \ / \
2960/// [cont0] [landingpad] [cont1]
2961/// to:
2962/// [...] [...]
2963/// \ /
2964/// [invoke]
2965/// / \
2966/// [cont] [landingpad]
2967///
2968/// But of course we can only do that if the invokes share the `landingpad`,
2969/// edges invoke0->cont0 and invoke1->cont1 are "compatible",
2970/// and the invoked functions are "compatible".
2971static bool mergeCompatibleInvokes(BasicBlock *BB, DomTreeUpdater *DTU) {
2972 if (!EnableMergeCompatibleInvokes)
2973 return false;
2974
2975 bool Changed = false;
2976
2977 // FIXME: generalize to all exception handling blocks?
2978 if (!BB->isLandingPad())
2979 return Changed;
2980
2981 CompatibleSets Grouper;
2982
2983 // Record all the predecessors of this `landingpad`. As per verifier,
2984 // the only allowed predecessor is the unwind edge of an `invoke`.
2985 // We want to group "compatible" `invokes` into the same set to be merged.
2986 for (BasicBlock *PredBB : predecessors(BB))
2987 Grouper.insert(II: cast<InvokeInst>(Val: PredBB->getTerminator()));
2988
2989 // And now, merge `invoke`s that were grouped togeter.
2990 for (ArrayRef<InvokeInst *> Invokes : Grouper.Sets) {
2991 if (Invokes.size() < 2)
2992 continue;
2993 Changed = true;
2994 mergeCompatibleInvokesImpl(Invokes, DTU);
2995 }
2996
2997 return Changed;
2998}
2999
3000namespace {
3001/// Track ephemeral values, which should be ignored for cost-modelling
3002/// purposes. Requires walking instructions in reverse order.
3003class EphemeralValueTracker {
3004 SmallPtrSet<const Instruction *, 32> EphValues;
3005
3006 bool isEphemeral(const Instruction *I) {
3007 if (isa<AssumeInst>(Val: I))
3008 return true;
3009 return !I->mayHaveSideEffects() && !I->isTerminator() &&
3010 all_of(Range: I->users(), P: [&](const User *U) {
3011 return EphValues.count(Ptr: cast<Instruction>(Val: U));
3012 });
3013 }
3014
3015public:
3016 bool track(const Instruction *I) {
3017 if (isEphemeral(I)) {
3018 EphValues.insert(Ptr: I);
3019 return true;
3020 }
3021 return false;
3022 }
3023
3024 bool contains(const Instruction *I) const { return EphValues.contains(Ptr: I); }
3025};
3026} // namespace
3027
3028/// Determine if we can hoist sink a sole store instruction out of a
3029/// conditional block.
3030///
3031/// We are looking for code like the following:
3032/// BrBB:
3033/// store i32 %add, i32* %arrayidx2
3034/// ... // No other stores or function calls (we could be calling a memory
3035/// ... // function).
3036/// %cmp = icmp ult %x, %y
3037/// br i1 %cmp, label %EndBB, label %ThenBB
3038/// ThenBB:
3039/// store i32 %add5, i32* %arrayidx2
3040/// br label EndBB
3041/// EndBB:
3042/// ...
3043/// We are going to transform this into:
3044/// BrBB:
3045/// store i32 %add, i32* %arrayidx2
3046/// ... //
3047/// %cmp = icmp ult %x, %y
3048/// %add.add5 = select i1 %cmp, i32 %add, %add5
3049/// store i32 %add.add5, i32* %arrayidx2
3050/// ...
3051///
3052/// \return The pointer to the value of the previous store if the store can be
3053/// hoisted into the predecessor block. 0 otherwise.
3054static Value *isSafeToSpeculateStore(Instruction *I, BasicBlock *BrBB,
3055 BasicBlock *StoreBB, BasicBlock *EndBB) {
3056 StoreInst *StoreToHoist = dyn_cast<StoreInst>(Val: I);
3057 if (!StoreToHoist)
3058 return nullptr;
3059
3060 // Volatile or atomic.
3061 if (!StoreToHoist->isSimple())
3062 return nullptr;
3063
3064 Value *StorePtr = StoreToHoist->getPointerOperand();
3065 Type *StoreTy = StoreToHoist->getValueOperand()->getType();
3066
3067 // Look for a store to the same pointer in BrBB.
3068 unsigned MaxNumInstToLookAt = 9;
3069 // Skip pseudo probe intrinsic calls which are not really killing any memory
3070 // accesses.
3071 for (Instruction &CurI : reverse(C&: *BrBB)) {
3072 if (!MaxNumInstToLookAt)
3073 break;
3074 --MaxNumInstToLookAt;
3075
3076 if (isa<PseudoProbeInst>(Val: CurI))
3077 continue;
3078
3079 // Could be calling an instruction that affects memory like free().
3080 if (CurI.mayWriteToMemory() && !isa<StoreInst>(Val: CurI))
3081 return nullptr;
3082
3083 if (auto *SI = dyn_cast<StoreInst>(Val: &CurI)) {
3084 // Found the previous store to same location and type. Make sure it is
3085 // simple, to avoid introducing a spurious non-atomic write after an
3086 // atomic write.
3087 if (SI->getPointerOperand() == StorePtr &&
3088 SI->getValueOperand()->getType() == StoreTy && SI->isSimple() &&
3089 SI->getAlign() >= StoreToHoist->getAlign())
3090 // Found the previous store, return its value operand.
3091 return SI->getValueOperand();
3092 return nullptr; // Unknown store.
3093 }
3094
3095 if (auto *LI = dyn_cast<LoadInst>(Val: &CurI)) {
3096 if (LI->getPointerOperand() == StorePtr && LI->getType() == StoreTy &&
3097 LI->isSimple() && LI->getAlign() >= StoreToHoist->getAlign()) {
3098 Value *Obj = getUnderlyingObject(V: StorePtr);
3099 bool ExplicitlyDereferenceableOnly;
3100 // The dereferenceability query here is only required to satisfy the
3101 // writable contract, actual dereferenceability is proven by the
3102 // presence of an access. As such, we can ignore frees.
3103 if (isWritableObject(Object: Obj, ExplicitlyDereferenceableOnly) &&
3104 capturesNothing(
3105 CC: PointerMayBeCaptured(V: Obj, Mask: CaptureComponents::Provenance)
3106 .WithoutRet) &&
3107 (!ExplicitlyDereferenceableOnly ||
3108 isDereferenceablePointer(V: StorePtr, Ty: StoreTy, Q: LI->getDataLayout(),
3109 /*IgnoreFree=*/true))) {
3110 // Found a previous load, return it.
3111 return LI;
3112 }
3113 }
3114 // The load didn't work out, but we may still find a store.
3115 }
3116 }
3117
3118 return nullptr;
3119}
3120
3121/// Estimate the cost of the insertion(s) and check that the PHI nodes can be
3122/// converted to selects.
3123static bool validateAndCostRequiredSelects(BasicBlock *BB, BasicBlock *ThenBB,
3124 BasicBlock *EndBB,
3125 unsigned &SpeculatedInstructions,
3126 InstructionCost &Cost,
3127 const TargetTransformInfo &TTI) {
3128 TargetTransformInfo::TargetCostKind CostKind =
3129 BB->getParent()->hasMinSize()
3130 ? TargetTransformInfo::TCK_CodeSize
3131 : TargetTransformInfo::TCK_SizeAndLatency;
3132
3133 bool HaveRewritablePHIs = false;
3134 for (PHINode &PN : EndBB->phis()) {
3135 Value *OrigV = PN.getIncomingValueForBlock(BB);
3136 Value *ThenV = PN.getIncomingValueForBlock(BB: ThenBB);
3137
3138 // FIXME: Try to remove some of the duplication with
3139 // hoistCommonCodeFromSuccessors. Skip PHIs which are trivial.
3140 if (ThenV == OrigV)
3141 continue;
3142
3143 Cost += TTI.getCmpSelInstrCost(Opcode: Instruction::Select, ValTy: PN.getType(),
3144 CondTy: CmpInst::makeCmpResultType(opnd_type: PN.getType()),
3145 VecPred: CmpInst::BAD_ICMP_PREDICATE, CostKind);
3146
3147 // Don't convert to selects if we could remove undefined behavior instead.
3148 if (passingValueIsAlwaysUndefined(V: OrigV, I: &PN) ||
3149 passingValueIsAlwaysUndefined(V: ThenV, I: &PN))
3150 return false;
3151
3152 HaveRewritablePHIs = true;
3153 ConstantExpr *OrigCE = dyn_cast<ConstantExpr>(Val: OrigV);
3154 ConstantExpr *ThenCE = dyn_cast<ConstantExpr>(Val: ThenV);
3155 if (!OrigCE && !ThenCE)
3156 continue; // Known cheap (FIXME: Maybe not true for aggregates).
3157
3158 InstructionCost OrigCost = OrigCE ? computeSpeculationCost(I: OrigCE, TTI) : 0;
3159 InstructionCost ThenCost = ThenCE ? computeSpeculationCost(I: ThenCE, TTI) : 0;
3160 InstructionCost MaxCost =
3161 2 * PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic;
3162 if (OrigCost + ThenCost > MaxCost)
3163 return false;
3164
3165 // Account for the cost of an unfolded ConstantExpr which could end up
3166 // getting expanded into Instructions.
3167 // FIXME: This doesn't account for how many operations are combined in the
3168 // constant expression.
3169 ++SpeculatedInstructions;
3170 if (SpeculatedInstructions > 1)
3171 return false;
3172 }
3173
3174 return HaveRewritablePHIs;
3175}
3176
3177static bool isProfitableToSpeculate(const CondBrInst *BI,
3178 std::optional<bool> Invert,
3179 const TargetTransformInfo &TTI) {
3180 // If the branch is non-unpredictable, and is predicted to *not* branch to
3181 // the `then` block, then avoid speculating it.
3182 if (BI->getMetadata(KindID: LLVMContext::MD_unpredictable))
3183 return true;
3184
3185 uint64_t TWeight, FWeight;
3186 if (!extractBranchWeights(I: *BI, TrueVal&: TWeight, FalseVal&: FWeight) || (TWeight + FWeight) == 0)
3187 return true;
3188
3189 if (!Invert.has_value())
3190 return false;
3191
3192 uint64_t EndWeight = *Invert ? TWeight : FWeight;
3193 BranchProbability BIEndProb =
3194 BranchProbability::getBranchProbability(Numerator: EndWeight, Denominator: TWeight + FWeight);
3195 BranchProbability Likely = TTI.getPredictableBranchThreshold();
3196 return BIEndProb < Likely;
3197}
3198
3199/// Speculate a conditional basic block flattening the CFG.
3200///
3201/// Note that this is a very risky transform currently. Speculating
3202/// instructions like this is most often not desirable. Instead, there is an MI
3203/// pass which can do it with full awareness of the resource constraints.
3204/// However, some cases are "obvious" and we should do directly. An example of
3205/// this is speculating a single, reasonably cheap instruction.
3206///
3207/// There is only one distinct advantage to flattening the CFG at the IR level:
3208/// it makes very common but simplistic optimizations such as are common in
3209/// instcombine and the DAG combiner more powerful by removing CFG edges and
3210/// modeling their effects with easier to reason about SSA value graphs.
3211///
3212///
3213/// An illustration of this transform is turning this IR:
3214/// \code
3215/// BB:
3216/// %cmp = icmp ult %x, %y
3217/// br i1 %cmp, label %EndBB, label %ThenBB
3218/// ThenBB:
3219/// %sub = sub %x, %y
3220/// br label BB2
3221/// EndBB:
3222/// %phi = phi [ %sub, %ThenBB ], [ 0, %BB ]
3223/// ...
3224/// \endcode
3225///
3226/// Into this IR:
3227/// \code
3228/// BB:
3229/// %cmp = icmp ult %x, %y
3230/// %sub = sub %x, %y
3231/// %cond = select i1 %cmp, 0, %sub
3232/// ...
3233/// \endcode
3234///
3235/// \returns true if the conditional block is removed.
3236bool SimplifyCFGOpt::speculativelyExecuteBB(CondBrInst *BI,
3237 BasicBlock *ThenBB) {
3238 if (!Options.SpeculateBlocks)
3239 return false;
3240
3241 BasicBlock *BB = BI->getParent();
3242 BasicBlock *EndBB = ThenBB->getTerminator()->getSuccessor(Idx: 0);
3243 InstructionCost Budget =
3244 PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic;
3245
3246 // If ThenBB is actually on the false edge of the conditional branch, remember
3247 // to swap the select operands later.
3248 bool Invert = false;
3249 if (ThenBB != BI->getSuccessor(i: 0)) {
3250 assert(ThenBB == BI->getSuccessor(1) && "No edge from 'if' block?");
3251 Invert = true;
3252 }
3253 assert(EndBB == BI->getSuccessor(!Invert) && "No edge from to end block");
3254
3255 if (!isProfitableToSpeculate(BI, Invert, TTI))
3256 return false;
3257
3258 // Keep a count of how many times instructions are used within ThenBB when
3259 // they are candidates for sinking into ThenBB. Specifically:
3260 // - They are defined in BB, and
3261 // - They have no side effects, and
3262 // - All of their uses are in ThenBB.
3263 SmallDenseMap<Instruction *, unsigned, 4> SinkCandidateUseCounts;
3264
3265 SmallVector<Instruction *, 4> SpeculatedPseudoProbes;
3266
3267 unsigned SpeculatedInstructions = 0;
3268 bool HoistLoadsStores = Options.HoistLoadsStoresWithCondFaulting;
3269 SmallVector<Instruction *, 2> SpeculatedConditionalLoadsStores;
3270 Value *SpeculatedStoreValue = nullptr;
3271 StoreInst *SpeculatedStore = nullptr;
3272 EphemeralValueTracker EphTracker;
3273 for (Instruction &I : reverse(C: drop_end(RangeOrContainer&: *ThenBB))) {
3274 // Skip pseudo probes. The consequence is we lose track of the branch
3275 // probability for ThenBB, which is fine since the optimization here takes
3276 // place regardless of the branch probability.
3277 if (isa<PseudoProbeInst>(Val: I)) {
3278 // The probe should be deleted so that it will not be over-counted when
3279 // the samples collected on the non-conditional path are counted towards
3280 // the conditional path. We leave it for the counts inference algorithm to
3281 // figure out a proper count for an unknown probe.
3282 SpeculatedPseudoProbes.push_back(Elt: &I);
3283 continue;
3284 }
3285
3286 // Ignore ephemeral values, they will be dropped by the transform.
3287 if (EphTracker.track(I: &I))
3288 continue;
3289
3290 // Only speculatively execute a single instruction (not counting the
3291 // terminator) for now.
3292 bool IsSafeCheapLoadStore = HoistLoadsStores &&
3293 isSafeCheapLoadStore(I: &I, TTI) &&
3294 SpeculatedConditionalLoadsStores.size() <
3295 HoistLoadsStoresWithCondFaultingThreshold;
3296 // Not count load/store into cost if target supports conditional faulting
3297 // b/c it's cheap to speculate it.
3298 if (IsSafeCheapLoadStore)
3299 SpeculatedConditionalLoadsStores.push_back(Elt: &I);
3300 else
3301 ++SpeculatedInstructions;
3302
3303 if (SpeculatedInstructions > 1)
3304 return false;
3305
3306 // Don't hoist the instruction if it's unsafe or expensive.
3307 if (!IsSafeCheapLoadStore &&
3308 !isSafeToSpeculativelyExecute(I: &I, CtxI: BI, AC: Options.AC) &&
3309 !(HoistCondStores && !SpeculatedStoreValue &&
3310 (SpeculatedStoreValue =
3311 isSafeToSpeculateStore(I: &I, BrBB: BB, StoreBB: ThenBB, EndBB))))
3312 return false;
3313 if (!IsSafeCheapLoadStore && !SpeculatedStoreValue &&
3314 computeSpeculationCost(I: &I, TTI) >
3315 PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic)
3316 return false;
3317
3318 // Store the store speculation candidate.
3319 if (!SpeculatedStore && SpeculatedStoreValue)
3320 SpeculatedStore = cast<StoreInst>(Val: &I);
3321
3322 // Do not hoist the instruction if any of its operands are defined but not
3323 // used in BB. The transformation will prevent the operand from
3324 // being sunk into the use block.
3325 for (Use &Op : I.operands()) {
3326 Instruction *OpI = dyn_cast<Instruction>(Val&: Op);
3327 if (!OpI || OpI->getParent() != BB || OpI->mayHaveSideEffects())
3328 continue; // Not a candidate for sinking.
3329
3330 ++SinkCandidateUseCounts[OpI];
3331 }
3332 }
3333
3334 // Consider any sink candidates which are only used in ThenBB as costs for
3335 // speculation. Note, while we iterate over a DenseMap here, we are summing
3336 // and so iteration order isn't significant.
3337 for (const auto &[Inst, Count] : SinkCandidateUseCounts)
3338 if (Inst->hasNUses(N: Count)) {
3339 ++SpeculatedInstructions;
3340 if (SpeculatedInstructions > 1)
3341 return false;
3342 }
3343
3344 // Check that we can insert the selects and that it's not too expensive to do
3345 // so.
3346 bool Convert =
3347 SpeculatedStore != nullptr || !SpeculatedConditionalLoadsStores.empty();
3348 InstructionCost Cost = 0;
3349 Convert |= validateAndCostRequiredSelects(BB, ThenBB, EndBB,
3350 SpeculatedInstructions, Cost, TTI);
3351 if (!Convert || Cost > Budget)
3352 return false;
3353
3354 // If we get here, we can hoist the instruction and if-convert.
3355 LLVM_DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *ThenBB << "\n";);
3356
3357 Instruction *Sel = nullptr;
3358 Value *BrCond = BI->getCondition();
3359 // Insert a select of the value of the speculated store.
3360 if (SpeculatedStoreValue) {
3361 IRBuilder<NoFolder> Builder(BI);
3362 Value *OrigV = SpeculatedStore->getValueOperand();
3363 Value *TrueV = SpeculatedStore->getValueOperand();
3364 Value *FalseV = SpeculatedStoreValue;
3365 if (Invert)
3366 std::swap(a&: TrueV, b&: FalseV);
3367 Value *S = Builder.CreateSelect(
3368 C: BrCond, True: TrueV, False: FalseV, Name: "spec.store.select", MDFrom: BI);
3369 Sel = cast<Instruction>(Val: S);
3370 SpeculatedStore->setOperand(i_nocapture: 0, Val_nocapture: S);
3371 SpeculatedStore->applyMergedLocation(LocA: BI->getDebugLoc(),
3372 LocB: SpeculatedStore->getDebugLoc());
3373 // The value stored is still conditional, but the store itself is now
3374 // unconditionally executed, so we must be sure that any linked dbg.assign
3375 // intrinsics are tracking the new stored value (the result of the
3376 // select). If we don't, and the store were to be removed by another pass
3377 // (e.g. DSE), then we'd eventually end up emitting a location describing
3378 // the conditional value, unconditionally.
3379 //
3380 // === Before this transformation ===
3381 // pred:
3382 // store %one, %x.dest, !DIAssignID !1
3383 // dbg.assign %one, "x", ..., !1, ...
3384 // br %cond if.then
3385 //
3386 // if.then:
3387 // store %two, %x.dest, !DIAssignID !2
3388 // dbg.assign %two, "x", ..., !2, ...
3389 //
3390 // === After this transformation ===
3391 // pred:
3392 // store %one, %x.dest, !DIAssignID !1
3393 // dbg.assign %one, "x", ..., !1
3394 /// ...
3395 // %merge = select %cond, %two, %one
3396 // store %merge, %x.dest, !DIAssignID !2
3397 // dbg.assign %merge, "x", ..., !2
3398 for (DbgVariableRecord *DbgAssign :
3399 at::getDVRAssignmentMarkers(Inst: SpeculatedStore))
3400 if (llvm::is_contained(Range: DbgAssign->location_ops(), Element: OrigV))
3401 DbgAssign->replaceVariableLocationOp(OldValue: OrigV, NewValue: S);
3402 }
3403
3404 // Metadata can be dependent on the condition we are hoisting above.
3405 // Strip all UB-implying metadata on the instruction. Drop the debug loc
3406 // to avoid making it appear as if the condition is a constant, which would
3407 // be misleading while debugging.
3408 // Similarly strip attributes that maybe dependent on condition we are
3409 // hoisting above.
3410 for (auto &I : make_early_inc_range(Range&: *ThenBB)) {
3411 if (!SpeculatedStoreValue || &I != SpeculatedStore) {
3412 I.dropLocation();
3413 }
3414 I.dropUBImplyingAttrsAndMetadata();
3415
3416 // Drop ephemeral values.
3417 if (EphTracker.contains(I: &I)) {
3418 I.replaceAllUsesWith(V: PoisonValue::get(T: I.getType()));
3419 I.eraseFromParent();
3420 }
3421 }
3422
3423 // Hoist the instructions.
3424 // Drop DbgVariableRecords attached to these instructions.
3425 for (auto &It : *ThenBB)
3426 for (DbgRecord &DR : make_early_inc_range(Range: It.getDbgRecordRange()))
3427 // Drop all records except assign-kind DbgVariableRecords (dbg.assign
3428 // equivalent).
3429 if (DbgVariableRecord *DVR = dyn_cast<DbgVariableRecord>(Val: &DR);
3430 !DVR || !DVR->isDbgAssign())
3431 It.dropOneDbgRecord(I: &DR);
3432 BB->splice(ToIt: BI->getIterator(), FromBB: ThenBB, FromBeginIt: ThenBB->begin(),
3433 FromEndIt: std::prev(x: ThenBB->end()));
3434
3435 if (!SpeculatedConditionalLoadsStores.empty())
3436 hoistConditionalLoadsStores(BI, SpeculatedConditionalLoadsStores, Invert,
3437 Sel);
3438
3439 // Insert selects and rewrite the PHI operands.
3440 IRBuilder<NoFolder> Builder(BI);
3441 for (PHINode &PN : EndBB->phis()) {
3442 unsigned OrigI = PN.getBasicBlockIndex(BB);
3443 unsigned ThenI = PN.getBasicBlockIndex(BB: ThenBB);
3444 Value *OrigV = PN.getIncomingValue(i: OrigI);
3445 Value *ThenV = PN.getIncomingValue(i: ThenI);
3446
3447 // Skip PHIs which are trivial.
3448 if (OrigV == ThenV)
3449 continue;
3450
3451 // Create a select whose true value is the speculatively executed value and
3452 // false value is the pre-existing value. Swap them if the branch
3453 // destinations were inverted.
3454 Value *TrueV = ThenV, *FalseV = OrigV;
3455 if (Invert)
3456 std::swap(a&: TrueV, b&: FalseV);
3457 // Propagate fast-math flags from the phi node to the replacement select.
3458 Value *V = Builder.CreateSelectFMF(
3459 C: BrCond, True: TrueV, False: FalseV, FMFSource: PN.getFastMathFlagsOrNone(), Name: "spec.select", MDFrom: BI);
3460 PN.setIncomingValue(i: OrigI, V);
3461 PN.setIncomingValue(i: ThenI, V);
3462 }
3463
3464 // Remove speculated pseudo probes.
3465 for (Instruction *I : SpeculatedPseudoProbes)
3466 I->eraseFromParent();
3467
3468 ++NumSpeculations;
3469 return true;
3470}
3471
3472using BlocksSet = SmallPtrSet<BasicBlock *, 8>;
3473
3474// Return false if number of blocks searched is too much.
3475static bool findReaching(BasicBlock *BB, BasicBlock *DefBB,
3476 BlocksSet &ReachesNonLocalUses) {
3477 if (BB == DefBB)
3478 return true;
3479 if (!ReachesNonLocalUses.insert(Ptr: BB).second)
3480 return true;
3481
3482 if (ReachesNonLocalUses.size() > MaxJumpThreadingLiveBlocks)
3483 return false;
3484 for (BasicBlock *Pred : predecessors(BB))
3485 if (!findReaching(BB: Pred, DefBB, ReachesNonLocalUses))
3486 return false;
3487 return true;
3488}
3489
3490/// Return true if we can thread a branch across this block.
3491static bool blockIsSimpleEnoughToThreadThrough(BasicBlock *BB,
3492 BlocksSet &NonLocalUseBlocks) {
3493 int Size = 0;
3494 EphemeralValueTracker EphTracker;
3495
3496 // Walk the loop in reverse so that we can identify ephemeral values properly
3497 // (values only feeding assumes).
3498 for (Instruction &I : reverse(C&: *BB)) {
3499 // Can't fold blocks that contain noduplicate or convergent calls.
3500 if (CallInst *CI = dyn_cast<CallInst>(Val: &I))
3501 if (CI->cannotDuplicate() || CI->isConvergent())
3502 return false;
3503
3504 // Ignore ephemeral values which are deleted during codegen.
3505 // We will delete Phis while threading, so Phis should not be accounted in
3506 // block's size.
3507 if (!EphTracker.track(I: &I) && !isa<PHINode>(Val: I)) {
3508 if (Size++ > MaxSmallBlockSize)
3509 return false; // Don't clone large BB's.
3510 }
3511
3512 // Record blocks with non-local uses of values defined in the current basic
3513 // block.
3514 for (User *U : I.users()) {
3515 Instruction *UI = cast<Instruction>(Val: U);
3516 BasicBlock *UsedInBB = UI->getParent();
3517 if (UsedInBB == BB) {
3518 if (isa<PHINode>(Val: UI))
3519 return false;
3520 } else
3521 NonLocalUseBlocks.insert(Ptr: UsedInBB);
3522 }
3523
3524 // Looks ok, continue checking.
3525 }
3526
3527 return true;
3528}
3529
3530static ConstantInt *getKnownValueOnEdge(Value *V, BasicBlock *From,
3531 BasicBlock *To) {
3532 // Don't look past the block defining the value, we might get the value from
3533 // a previous loop iteration.
3534 auto *I = dyn_cast<Instruction>(Val: V);
3535 if (I && I->getParent() == To)
3536 return nullptr;
3537
3538 // We know the value if the From block branches on it.
3539 auto *BI = dyn_cast<CondBrInst>(Val: From->getTerminator());
3540 if (BI && BI->getCondition() == V &&
3541 BI->getSuccessor(i: 0) != BI->getSuccessor(i: 1))
3542 return BI->getSuccessor(i: 0) == To ? ConstantInt::getTrue(Context&: BI->getContext())
3543 : ConstantInt::getFalse(Context&: BI->getContext());
3544
3545 return nullptr;
3546}
3547
3548static bool isUncontrolledConvergentCall(CallBase *CB) {
3549 return CB->isConvergent() && !isa<ConvergenceControlInst>(Val: CB) &&
3550 !CB->getConvergenceControlToken();
3551}
3552
3553static bool reachesUncontrolledConvergentCallBeforeBlock(BasicBlock *From,
3554 BasicBlock *StopBB) {
3555 static constexpr unsigned MaxInstructionsToScan = 512;
3556
3557 // Walk predecessors of StopBB to find blocks that can reach it. Only
3558 // convergent calls on a cycle with StopBB matter - a convergent call on a
3559 // path to function exit cannot have its dynamic instance changed by
3560 // threading.
3561 SmallPtrSet<BasicBlock *, 8> CanReachStop;
3562 SmallPtrSet<BasicBlock *, 8> BlocksWithUncontrolledConvergentCalls;
3563 SmallVector<BasicBlock *, 8> Worklist;
3564 for (BasicBlock *Pred : predecessors(BB: StopBB))
3565 Worklist.push_back(Elt: Pred);
3566
3567 // Cache blocks with relevant calls while building CanReachStop. This keeps
3568 // the instruction scan bounded without a separate block limit.
3569 unsigned NumScannedInstructions = 0;
3570 while (!Worklist.empty()) {
3571 BasicBlock *BB = Worklist.pop_back_val();
3572 if (BB == StopBB)
3573 continue;
3574 if (!CanReachStop.insert(Ptr: BB).second)
3575 continue;
3576
3577 for (Instruction &I : *BB) {
3578 if (++NumScannedInstructions > MaxInstructionsToScan)
3579 return true;
3580 auto *CB = dyn_cast<CallBase>(Val: &I);
3581 if (CB && isUncontrolledConvergentCall(CB)) {
3582 BlocksWithUncontrolledConvergentCalls.insert(Ptr: BB);
3583 break;
3584 }
3585 }
3586
3587 append_range(C&: Worklist, R: predecessors(BB));
3588 }
3589
3590 if (!CanReachStop.contains(Ptr: From))
3591 return false;
3592
3593 SmallPtrSet<BasicBlock *, 8> Visited;
3594 Worklist.push_back(Elt: From);
3595
3596 while (!Worklist.empty()) {
3597 BasicBlock *BB = Worklist.pop_back_val();
3598 if (BB == StopBB || !CanReachStop.contains(Ptr: BB))
3599 continue;
3600
3601 if (!Visited.insert(Ptr: BB).second)
3602 continue;
3603
3604 if (BlocksWithUncontrolledConvergentCalls.contains(Ptr: BB))
3605 return true;
3606
3607 append_range(C&: Worklist, R: successors(BB));
3608 }
3609
3610 return false;
3611}
3612
3613/// If we have a conditional branch on something for which we know the constant
3614/// value in predecessors (e.g. a phi node in the current block), thread edges
3615/// from the predecessor to their ultimate destination.
3616static std::optional<bool> foldCondBranchOnValueKnownInPredecessorImpl(
3617 CondBrInst *BI, const TargetTransformInfo &TTI, DomTreeUpdater *DTU,
3618 AssumptionCache *AC, const DataLayout &DL) {
3619 SmallMapVector<ConstantInt *, SmallSetVector<BasicBlock *, 2>, 2> KnownValues;
3620 BasicBlock *BB = BI->getParent();
3621 Value *Cond = BI->getCondition();
3622 PHINode *PN = dyn_cast<PHINode>(Val: Cond);
3623 if (PN && PN->getParent() == BB) {
3624 // Degenerate case of a single entry PHI.
3625 if (PN->getNumIncomingValues() == 1) {
3626 FoldSingleEntryPHINodes(BB: PN->getParent());
3627 return true;
3628 }
3629
3630 for (Use &U : PN->incoming_values())
3631 if (auto *CB = dyn_cast<ConstantInt>(Val&: U))
3632 KnownValues[CB].insert(X: PN->getIncomingBlock(U));
3633 } else {
3634 for (BasicBlock *Pred : predecessors(BB)) {
3635 if (ConstantInt *CB = getKnownValueOnEdge(V: Cond, From: Pred, To: BB))
3636 KnownValues[CB].insert(X: Pred);
3637 }
3638 }
3639
3640 if (KnownValues.empty())
3641 return false;
3642
3643 // Now we know that this block has multiple preds and two succs.
3644 // Check that the block is small enough and record which non-local blocks use
3645 // values defined in the block.
3646
3647 BlocksSet NonLocalUseBlocks;
3648 BlocksSet ReachesNonLocalUseBlocks;
3649 if (!blockIsSimpleEnoughToThreadThrough(BB, NonLocalUseBlocks))
3650 return false;
3651
3652 // Jump-threading can only be done to destinations where no values defined
3653 // in BB are live.
3654
3655 // Quickly check if both destinations have uses. If so, jump-threading cannot
3656 // be done.
3657 if (NonLocalUseBlocks.contains(Ptr: BI->getSuccessor(i: 0)) &&
3658 NonLocalUseBlocks.contains(Ptr: BI->getSuccessor(i: 1)))
3659 return false;
3660
3661 // Search backward from NonLocalUseBlocks to find which blocks
3662 // reach non-local uses.
3663 for (BasicBlock *UseBB : NonLocalUseBlocks)
3664 // Give up if too many blocks are searched.
3665 if (!findReaching(BB: UseBB, DefBB: BB, ReachesNonLocalUses&: ReachesNonLocalUseBlocks))
3666 return false;
3667
3668 for (const auto &Pair : KnownValues) {
3669 ConstantInt *CB = Pair.first;
3670 ArrayRef<BasicBlock *> PredBBs = Pair.second.getArrayRef();
3671 BasicBlock *RealDest = BI->getSuccessor(i: !CB->getZExtValue());
3672
3673 // Okay, we now know that all edges from PredBB should be revectored to
3674 // branch to RealDest.
3675 if (RealDest == BB)
3676 continue; // Skip self loops.
3677
3678 // Skip if the predecessor's terminator is an indirect branch.
3679 if (any_of(Range&: PredBBs, P: [](BasicBlock *PredBB) {
3680 return isa<IndirectBrInst>(Val: PredBB->getTerminator());
3681 }))
3682 continue;
3683
3684 // Only revector to RealDest if no values defined in BB are live.
3685 if (ReachesNonLocalUseBlocks.contains(Ptr: RealDest))
3686 continue;
3687
3688 // Threading through a branch can bypass a reconvergence point. If the
3689 // destination can execute an uncontrolled convergent operation before
3690 // returning to this block, this may change the dynamic instance of that
3691 // operation.
3692 if (TTI.hasBranchDivergence(F: BB->getParent()) &&
3693 reachesUncontrolledConvergentCallBeforeBlock(From: RealDest, StopBB: BB))
3694 continue;
3695
3696 LLVM_DEBUG({
3697 dbgs() << "Condition " << *Cond << " in " << BB->getName()
3698 << " has value " << *Pair.first << " in predecessors:\n";
3699 for (const BasicBlock *PredBB : Pair.second)
3700 dbgs() << " " << PredBB->getName() << "\n";
3701 dbgs() << "Threading to destination " << RealDest->getName() << ".\n";
3702 });
3703
3704 // Split the predecessors we are threading into a new edge block. We'll
3705 // clone the instructions into this block, and then redirect it to RealDest.
3706 BasicBlock *EdgeBB = SplitBlockPredecessors(BB, Preds: PredBBs, Suffix: ".critedge", DTU);
3707 if (!EdgeBB)
3708 continue;
3709
3710 // TODO: These just exist to reduce test diff, we can drop them if we like.
3711 EdgeBB->setName(RealDest->getName() + ".critedge");
3712 EdgeBB->moveBefore(MovePos: RealDest);
3713
3714 // Update PHI nodes.
3715 addPredecessorToBlock(Succ: RealDest, NewPred: EdgeBB, ExistPred: BB);
3716
3717 // BB may have instructions that are being threaded over. Clone these
3718 // instructions into EdgeBB. We know that there will be no uses of the
3719 // cloned instructions outside of EdgeBB.
3720 BasicBlock::iterator InsertPt = EdgeBB->getFirstInsertionPt();
3721 ValueToValueMapTy TranslateMap; // Track translated values.
3722 TranslateMap[Cond] = CB;
3723
3724 // RemoveDIs: track instructions that we optimise away while folding, so
3725 // that we can copy DbgVariableRecords from them later.
3726 BasicBlock::iterator SrcDbgCursor = BB->begin();
3727 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
3728 if (PHINode *PN = dyn_cast<PHINode>(Val&: BBI)) {
3729 TranslateMap[PN] = PN->getIncomingValueForBlock(BB: EdgeBB);
3730 continue;
3731 }
3732 // Clone the instruction.
3733 Instruction *N = BBI->clone();
3734 // Insert the new instruction into its new home.
3735 N->insertInto(ParentBB: EdgeBB, It: InsertPt);
3736
3737 if (BBI->hasName())
3738 N->setName(BBI->getName() + ".c");
3739
3740 // Update operands due to translation.
3741 // Key Instructions: Remap all the atom groups.
3742 if (const DebugLoc &DL = BBI->getDebugLoc())
3743 mapAtomInstance(DL, VMap&: TranslateMap);
3744 RemapInstruction(I: N, VM&: TranslateMap,
3745 Flags: RF_IgnoreMissingLocals | RF_NoModuleLevelChanges);
3746
3747 // Check for trivial simplification.
3748 if (Value *V = simplifyInstruction(I: N, Q: {DL, nullptr, nullptr, AC})) {
3749 if (!BBI->use_empty())
3750 TranslateMap[&*BBI] = V;
3751 if (!N->mayHaveSideEffects()) {
3752 N->eraseFromParent(); // Instruction folded away, don't need actual
3753 // inst
3754 N = nullptr;
3755 }
3756 } else {
3757 if (!BBI->use_empty())
3758 TranslateMap[&*BBI] = N;
3759 }
3760 if (N) {
3761 // Copy all debug-info attached to instructions from the last we
3762 // successfully clone, up to this instruction (they might have been
3763 // folded away).
3764 for (; SrcDbgCursor != BBI; ++SrcDbgCursor)
3765 N->cloneDebugInfoFrom(From: &*SrcDbgCursor);
3766 SrcDbgCursor = std::next(x: BBI);
3767 // Clone debug-info on this instruction too.
3768 N->cloneDebugInfoFrom(From: &*BBI);
3769
3770 // Register the new instruction with the assumption cache if necessary.
3771 if (auto *Assume = dyn_cast<AssumeInst>(Val: N))
3772 if (AC)
3773 AC->registerAssumption(CI: Assume);
3774 }
3775 }
3776
3777 for (; &*SrcDbgCursor != BI; ++SrcDbgCursor)
3778 InsertPt->cloneDebugInfoFrom(From: &*SrcDbgCursor);
3779 InsertPt->cloneDebugInfoFrom(From: BI);
3780
3781 BB->removePredecessor(Pred: EdgeBB);
3782 UncondBrInst *EdgeBI = cast<UncondBrInst>(Val: EdgeBB->getTerminator());
3783 EdgeBI->setSuccessor(idx: 0, NewSucc: RealDest);
3784 EdgeBI->setDebugLoc(BI->getDebugLoc());
3785
3786 if (DTU) {
3787 SmallVector<DominatorTree::UpdateType, 2> Updates;
3788 Updates.push_back(Elt: {DominatorTree::Delete, EdgeBB, BB});
3789 Updates.push_back(Elt: {DominatorTree::Insert, EdgeBB, RealDest});
3790 DTU->applyUpdates(Updates);
3791 }
3792
3793 // For simplicity, we created a separate basic block for the edge. Merge
3794 // it back into the predecessor if possible. This not only avoids
3795 // unnecessary SimplifyCFG iterations, but also makes sure that we don't
3796 // bypass the check for trivial cycles above.
3797 MergeBlockIntoPredecessor(BB: EdgeBB, DTU);
3798
3799 // Signal repeat, simplifying any other constants.
3800 return std::nullopt;
3801 }
3802
3803 return false;
3804}
3805
3806bool SimplifyCFGOpt::foldCondBranchOnValueKnownInPredecessor(CondBrInst *BI) {
3807 // Note: If BB is a loop header then there is a risk that threading introduces
3808 // a non-canonical loop by moving a back edge. So we avoid this optimization
3809 // for loop headers if NeedCanonicalLoop is set.
3810 if (Options.NeedCanonicalLoop && is_contained(Range&: LoopHeaders, Element: BI->getParent()))
3811 return false;
3812
3813 std::optional<bool> Result;
3814 bool EverChanged = false;
3815 do {
3816 // Note that None means "we changed things, but recurse further."
3817 Result = foldCondBranchOnValueKnownInPredecessorImpl(BI, TTI, DTU,
3818 AC: Options.AC, DL);
3819 EverChanged |= Result == std::nullopt || *Result;
3820 } while (Result == std::nullopt);
3821 return EverChanged;
3822}
3823
3824/// Given a BB that starts with the specified two-entry PHI node,
3825/// see if we can eliminate it.
3826static bool foldTwoEntryPHINode(PHINode *PN, const TargetTransformInfo &TTI,
3827 DomTreeUpdater *DTU, AssumptionCache *AC,
3828 const DataLayout &DL,
3829 bool SpeculateUnpredictables) {
3830 // Ok, this is a two entry PHI node. Check to see if this is a simple "if
3831 // statement", which has a very simple dominance structure. Basically, we
3832 // are trying to find the condition that is being branched on, which
3833 // subsequently causes this merge to happen. We really want control
3834 // dependence information for this check, but simplifycfg can't keep it up
3835 // to date, and this catches most of the cases we care about anyway.
3836 BasicBlock *BB = PN->getParent();
3837
3838 BasicBlock *IfTrue, *IfFalse;
3839 CondBrInst *DomBI = GetIfCondition(BB, IfTrue, IfFalse);
3840 if (!DomBI)
3841 return false;
3842 Value *IfCond = DomBI->getCondition();
3843 // Don't bother if the branch will be constant folded trivially.
3844 if (isa<ConstantInt>(Val: IfCond))
3845 return false;
3846
3847 BasicBlock *DomBlock = DomBI->getParent();
3848 SmallVector<BasicBlock *, 2> IfBlocks;
3849 llvm::copy_if(Range: PN->blocks(), Out: std::back_inserter(x&: IfBlocks),
3850 P: [](BasicBlock *IfBlock) {
3851 return isa<UncondBrInst>(Val: IfBlock->getTerminator());
3852 });
3853 assert((IfBlocks.size() == 1 || IfBlocks.size() == 2) &&
3854 "Will have either one or two blocks to speculate.");
3855
3856 // If the branch is non-unpredictable, see if we either predictably jump to
3857 // the merge bb (if we have only a single 'then' block), or if we predictably
3858 // jump to one specific 'then' block (if we have two of them).
3859 // It isn't beneficial to speculatively execute the code
3860 // from the block that we know is predictably not entered.
3861 bool IsUnpredictable = DomBI->getMetadata(KindID: LLVMContext::MD_unpredictable);
3862 if (!IsUnpredictable) {
3863 uint64_t TWeight, FWeight;
3864 if (extractBranchWeights(I: *DomBI, TrueVal&: TWeight, FalseVal&: FWeight) &&
3865 (TWeight + FWeight) != 0) {
3866 BranchProbability BITrueProb =
3867 BranchProbability::getBranchProbability(Numerator: TWeight, Denominator: TWeight + FWeight);
3868 BranchProbability Likely = TTI.getPredictableBranchThreshold();
3869 BranchProbability BIFalseProb = BITrueProb.getCompl();
3870 if (IfBlocks.size() == 1) {
3871 BranchProbability BIBBProb =
3872 DomBI->getSuccessor(i: 0) == BB ? BITrueProb : BIFalseProb;
3873 if (BIBBProb >= Likely)
3874 return false;
3875 } else {
3876 if (BITrueProb >= Likely || BIFalseProb >= Likely)
3877 return false;
3878 }
3879 }
3880 }
3881
3882 // Don't try to fold an unreachable block. For example, the phi node itself
3883 // can't be the candidate if-condition for a select that we want to form.
3884 if (auto *IfCondPhiInst = dyn_cast<PHINode>(Val: IfCond))
3885 if (IfCondPhiInst->getParent() == BB)
3886 return false;
3887
3888 // Okay, we found that we can merge this two-entry phi node into a select.
3889 // Doing so would require us to fold *all* two entry phi nodes in this block.
3890 // At some point this becomes non-profitable (particularly if the target
3891 // doesn't support cmov's). Only do this transformation if there are two or
3892 // fewer PHI nodes in this block.
3893 unsigned NumPhis = 0;
3894 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(Val: I); ++NumPhis, ++I)
3895 if (NumPhis > 2)
3896 return false;
3897
3898 // Loop over the PHI's seeing if we can promote them all to select
3899 // instructions. While we are at it, keep track of the instructions
3900 // that need to be moved to the dominating block.
3901 SmallPtrSet<Instruction *, 4> AggressiveInsts;
3902 SmallPtrSet<Instruction *, 2> ZeroCostInstructions;
3903 InstructionCost Cost = 0;
3904 InstructionCost Budget =
3905 TwoEntryPHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic;
3906 if (SpeculateUnpredictables && IsUnpredictable)
3907 Budget += TTI.getBranchMispredictPenalty();
3908
3909 bool Changed = false;
3910 for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(Val: II);) {
3911 PHINode *PN = cast<PHINode>(Val: II++);
3912 if (Value *V = simplifyInstruction(I: PN, Q: {DL, PN})) {
3913 PN->replaceAllUsesWith(V);
3914 PN->eraseFromParent();
3915 Changed = true;
3916 continue;
3917 }
3918
3919 if (!dominatesMergePoint(V: PN->getIncomingValue(i: 0), BB, InsertPt: DomBI,
3920 AggressiveInsts, Cost, Budget, TTI, AC,
3921 ZeroCostInstructions) ||
3922 !dominatesMergePoint(V: PN->getIncomingValue(i: 1), BB, InsertPt: DomBI,
3923 AggressiveInsts, Cost, Budget, TTI, AC,
3924 ZeroCostInstructions))
3925 return Changed;
3926 }
3927
3928 // If we folded the first phi, PN dangles at this point. Refresh it. If
3929 // we ran out of PHIs then we simplified them all.
3930 PN = dyn_cast<PHINode>(Val: BB->begin());
3931 if (!PN)
3932 return true;
3933
3934 // Don't fold i1 branches on PHIs which contain binary operators or
3935 // (possibly inverted) select form of or/ands if their parameters are
3936 // an equality test.
3937 auto IsBinOpOrAndEq = [](Value *V) {
3938 CmpPredicate Pred;
3939 if (match(V, P: m_CombineOr(
3940 Ps: m_CombineOr(
3941 Ps: m_BinOp(L: m_Cmp(Pred, L: m_Value(), R: m_Value()), R: m_Value()),
3942 Ps: m_BinOp(L: m_Value(), R: m_Cmp(Pred, L: m_Value(), R: m_Value()))),
3943 Ps: m_c_Select(L: m_ImmConstant(),
3944 R: m_Cmp(Pred, L: m_Value(), R: m_Value()))))) {
3945 return CmpInst::isEquality(pred: Pred);
3946 }
3947 return false;
3948 };
3949 if (PN->getType()->isIntegerTy(BitWidth: 1) &&
3950 (IsBinOpOrAndEq(PN->getIncomingValue(i: 0)) ||
3951 IsBinOpOrAndEq(PN->getIncomingValue(i: 1)) || IsBinOpOrAndEq(IfCond)))
3952 return Changed;
3953
3954 // If all PHI nodes are promotable, check to make sure that all instructions
3955 // in the predecessor blocks can be promoted as well. If not, we won't be able
3956 // to get rid of the control flow, so it's not worth promoting to select
3957 // instructions.
3958 for (BasicBlock *IfBlock : IfBlocks)
3959 for (BasicBlock::iterator I = IfBlock->begin(); !I->isTerminator(); ++I)
3960 if (!AggressiveInsts.count(Ptr: &*I) && !I->isDebugOrPseudoInst()) {
3961 // This is not an aggressive instruction that we can promote.
3962 // Because of this, we won't be able to get rid of the control flow, so
3963 // the xform is not worth it.
3964 return Changed;
3965 }
3966
3967 // If either of the blocks has it's address taken, we can't do this fold.
3968 if (any_of(Range&: IfBlocks,
3969 P: [](BasicBlock *IfBlock) { return IfBlock->hasAddressTaken(); }))
3970 return Changed;
3971
3972 LLVM_DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond;
3973 if (IsUnpredictable) dbgs() << " (unpredictable)";
3974 dbgs() << " T: " << IfTrue->getName()
3975 << " F: " << IfFalse->getName() << "\n");
3976
3977 // If we can still promote the PHI nodes after this gauntlet of tests,
3978 // do all of the PHI's now.
3979
3980 // Move all 'aggressive' instructions, which are defined in the
3981 // conditional parts of the if's up to the dominating block.
3982 for (BasicBlock *IfBlock : IfBlocks)
3983 hoistAllInstructionsInto(DomBlock, InsertPt: DomBI, BB: IfBlock);
3984
3985 IRBuilder<NoFolder> Builder(DomBI);
3986 // Propagate fast-math-flags from phi nodes to replacement selects.
3987 while (PHINode *PN = dyn_cast<PHINode>(Val: BB->begin())) {
3988 // Change the PHI node into a select instruction.
3989 Value *TrueVal = PN->getIncomingValueForBlock(BB: IfTrue);
3990 Value *FalseVal = PN->getIncomingValueForBlock(BB: IfFalse);
3991
3992 Value *Sel = Builder.CreateSelectFMF(C: IfCond, True: TrueVal, False: FalseVal,
3993 FMFSource: isa<FPMathOperator>(Val: PN) ? PN : nullptr,
3994 Name: "", MDFrom: DomBI);
3995 PN->replaceAllUsesWith(V: Sel);
3996 Sel->takeName(V: PN);
3997 PN->eraseFromParent();
3998 }
3999
4000 // At this point, all IfBlocks are empty, so our if statement
4001 // has been flattened. Change DomBlock to jump directly to our new block to
4002 // avoid other simplifycfg's kicking in on the diamond.
4003 Builder.CreateBr(Dest: BB);
4004
4005 SmallVector<DominatorTree::UpdateType, 3> Updates;
4006 if (DTU) {
4007 Updates.push_back(Elt: {DominatorTree::Insert, DomBlock, BB});
4008 for (auto *Successor : successors(BB: DomBlock))
4009 Updates.push_back(Elt: {DominatorTree::Delete, DomBlock, Successor});
4010 }
4011
4012 DomBI->eraseFromParent();
4013 if (DTU)
4014 DTU->applyUpdates(Updates);
4015
4016 return true;
4017}
4018
4019static Value *createLogicalOp(IRBuilderBase &Builder,
4020 Instruction::BinaryOps Opc, Value *LHS,
4021 Value *RHS, const Twine &Name = "") {
4022 // Try to relax logical op to binary op.
4023 if (impliesPoison(ValAssumedPoison: RHS, V: LHS))
4024 return Builder.CreateBinOp(Opc, LHS, RHS, Name);
4025 if (Opc == Instruction::And)
4026 return Builder.CreateLogicalAnd(Cond1: LHS, Cond2: RHS, Name);
4027 if (Opc == Instruction::Or)
4028 return Builder.CreateLogicalOr(Cond1: LHS, Cond2: RHS, Name);
4029 llvm_unreachable("Invalid logical opcode");
4030}
4031
4032/// Return true if either PBI or BI has branch weight available, and store
4033/// the weights in {Pred|Succ}{True|False}Weight. If one of PBI and BI does
4034/// not have branch weight, use 1:1 as its weight.
4035static bool extractPredSuccWeights(CondBrInst *PBI, CondBrInst *BI,
4036 uint64_t &PredTrueWeight,
4037 uint64_t &PredFalseWeight,
4038 uint64_t &SuccTrueWeight,
4039 uint64_t &SuccFalseWeight) {
4040 bool PredHasWeights =
4041 extractBranchWeights(I: *PBI, TrueVal&: PredTrueWeight, FalseVal&: PredFalseWeight);
4042 bool SuccHasWeights =
4043 extractBranchWeights(I: *BI, TrueVal&: SuccTrueWeight, FalseVal&: SuccFalseWeight);
4044 if (PredHasWeights || SuccHasWeights) {
4045 if (!PredHasWeights)
4046 PredTrueWeight = PredFalseWeight = 1;
4047 if (!SuccHasWeights)
4048 SuccTrueWeight = SuccFalseWeight = 1;
4049 return true;
4050 } else {
4051 return false;
4052 }
4053}
4054
4055/// Determine if the two branches share a common destination and deduce a glue
4056/// that joins the branches' conditions to arrive at the common destination if
4057/// that would be profitable.
4058static std::optional<std::tuple<BasicBlock *, Instruction::BinaryOps, bool>>
4059shouldFoldCondBranchesToCommonDestination(CondBrInst *BI, CondBrInst *PBI,
4060 const TargetTransformInfo *TTI) {
4061 assert(BI && PBI && "Both blocks must end with a conditional branches.");
4062 assert(is_contained(predecessors(BI->getParent()), PBI->getParent()) &&
4063 "PredBB must be a predecessor of BB.");
4064
4065 // We have the potential to fold the conditions together, but if the
4066 // predecessor branch is predictable, we may not want to merge them.
4067 uint64_t PTWeight, PFWeight;
4068 BranchProbability PBITrueProb, Likely;
4069 if (TTI && !PBI->getMetadata(KindID: LLVMContext::MD_unpredictable) &&
4070 extractBranchWeights(I: *PBI, TrueVal&: PTWeight, FalseVal&: PFWeight) &&
4071 (PTWeight + PFWeight) != 0) {
4072 PBITrueProb =
4073 BranchProbability::getBranchProbability(Numerator: PTWeight, Denominator: PTWeight + PFWeight);
4074 Likely = TTI->getPredictableBranchThreshold();
4075 }
4076
4077 if (PBI->getSuccessor(i: 0) == BI->getSuccessor(i: 0)) {
4078 // Speculate the 2nd condition unless the 1st is probably true.
4079 if (PBITrueProb.isUnknown() || PBITrueProb < Likely)
4080 return {{BI->getSuccessor(i: 0), Instruction::Or, false}};
4081 } else if (PBI->getSuccessor(i: 1) == BI->getSuccessor(i: 1)) {
4082 // Speculate the 2nd condition unless the 1st is probably false.
4083 if (PBITrueProb.isUnknown() || PBITrueProb.getCompl() < Likely)
4084 return {{BI->getSuccessor(i: 1), Instruction::And, false}};
4085 } else if (PBI->getSuccessor(i: 0) == BI->getSuccessor(i: 1)) {
4086 // Speculate the 2nd condition unless the 1st is probably true.
4087 if (PBITrueProb.isUnknown() || PBITrueProb < Likely)
4088 return {{BI->getSuccessor(i: 1), Instruction::And, true}};
4089 } else if (PBI->getSuccessor(i: 1) == BI->getSuccessor(i: 0)) {
4090 // Speculate the 2nd condition unless the 1st is probably false.
4091 if (PBITrueProb.isUnknown() || PBITrueProb.getCompl() < Likely)
4092 return {{BI->getSuccessor(i: 0), Instruction::Or, true}};
4093 }
4094 return std::nullopt;
4095}
4096
4097static bool performBranchToCommonDestFolding(CondBrInst *BI, CondBrInst *PBI,
4098 DomTreeUpdater *DTU,
4099 MemorySSAUpdater *MSSAU,
4100 const TargetTransformInfo *TTI) {
4101 BasicBlock *BB = BI->getParent();
4102 BasicBlock *PredBlock = PBI->getParent();
4103
4104 // Determine if the two branches share a common destination.
4105 BasicBlock *CommonSucc;
4106 Instruction::BinaryOps Opc;
4107 bool InvertPredCond;
4108 std::tie(args&: CommonSucc, args&: Opc, args&: InvertPredCond) =
4109 *shouldFoldCondBranchesToCommonDestination(BI, PBI, TTI);
4110
4111 LLVM_DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
4112
4113 IRBuilder<ConstantFolder, IRBuilderCallbackInserter> Builder(
4114 BB->getContext(), ConstantFolder{},
4115 IRBuilderCallbackInserter([&BB](Instruction *I) {
4116 // The builder is used to create instructions to eliminate the branch in
4117 // BB. If BB's terminator has !annotation metadata, add it to the new
4118 // instructions.
4119 I->copyMetadata(SrcInst: *BB->getTerminator(), WL: LLVMContext::MD_annotation);
4120 }));
4121 Builder.SetInsertPoint(PBI);
4122
4123 // If we need to invert the condition in the pred block to match, do so now.
4124 if (InvertPredCond) {
4125 InvertBranch(PBI, Builder);
4126 }
4127
4128 BasicBlock *UniqueSucc =
4129 PBI->getSuccessor(i: 0) == BB ? BI->getSuccessor(i: 0) : BI->getSuccessor(i: 1);
4130
4131 // Before cloning instructions, notify the successor basic block that it
4132 // is about to have a new predecessor. This will update PHI nodes,
4133 // which will allow us to update live-out uses of bonus instructions.
4134 addPredecessorToBlock(Succ: UniqueSucc, NewPred: PredBlock, ExistPred: BB, MSSAU);
4135
4136 // Try to update branch weights.
4137 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
4138 SmallVector<uint64_t, 2> MDWeights;
4139 if (extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight,
4140 SuccTrueWeight, SuccFalseWeight)) {
4141
4142 if (PBI->getSuccessor(i: 0) == BB) {
4143 // PBI: br i1 %x, BB, FalseDest
4144 // BI: br i1 %y, UniqueSucc, FalseDest
4145 // TrueWeight is TrueWeight for PBI * TrueWeight for BI.
4146 MDWeights.push_back(Elt: PredTrueWeight * SuccTrueWeight);
4147 // FalseWeight is FalseWeight for PBI * TotalWeight for BI +
4148 // TrueWeight for PBI * FalseWeight for BI.
4149 // We assume that total weights of a CondBrInst can fit into 32 bits.
4150 // Therefore, we will not have overflow using 64-bit arithmetic.
4151 MDWeights.push_back(Elt: PredFalseWeight * (SuccFalseWeight + SuccTrueWeight) +
4152 PredTrueWeight * SuccFalseWeight);
4153 } else {
4154 // PBI: br i1 %x, TrueDest, BB
4155 // BI: br i1 %y, TrueDest, UniqueSucc
4156 // TrueWeight is TrueWeight for PBI * TotalWeight for BI +
4157 // FalseWeight for PBI * TrueWeight for BI.
4158 MDWeights.push_back(Elt: PredTrueWeight * (SuccFalseWeight + SuccTrueWeight) +
4159 PredFalseWeight * SuccTrueWeight);
4160 // FalseWeight is FalseWeight for PBI * FalseWeight for BI.
4161 MDWeights.push_back(Elt: PredFalseWeight * SuccFalseWeight);
4162 }
4163
4164 setFittedBranchWeights(I&: *PBI, Weights: MDWeights, /*IsExpected=*/false,
4165 /*ElideAllZero=*/true);
4166
4167 // TODO: If BB is reachable from all paths through PredBlock, then we
4168 // could replace PBI's branch probabilities with BI's.
4169 } else
4170 PBI->setMetadata(KindID: LLVMContext::MD_prof, Node: nullptr);
4171
4172 // Now, update the CFG.
4173 PBI->setSuccessor(idx: PBI->getSuccessor(i: 0) != BB, NewSucc: UniqueSucc);
4174
4175 if (DTU)
4176 DTU->applyUpdates(Updates: {{DominatorTree::Insert, PredBlock, UniqueSucc},
4177 {DominatorTree::Delete, PredBlock, BB}});
4178
4179 // If BI was a loop latch, it may have had associated loop metadata.
4180 // We need to copy it to the new latch, that is, PBI.
4181 if (MDNode *LoopMD = BI->getMetadata(KindID: LLVMContext::MD_loop))
4182 PBI->setMetadata(KindID: LLVMContext::MD_loop, Node: LoopMD);
4183
4184 ValueToValueMapTy VMap; // maps original values to cloned values
4185 cloneInstructionsIntoPredecessorBlockAndUpdateSSAUses(BB, PredBlock, VMap);
4186
4187 Module *M = BB->getModule();
4188
4189 PredBlock->getTerminator()->cloneDebugInfoFrom(From: BB->getTerminator());
4190 for (DbgVariableRecord &DVR :
4191 filterDbgVars(R: PredBlock->getTerminator()->getDbgRecordRange())) {
4192 RemapDbgRecord(M, DR: &DVR, VM&: VMap,
4193 Flags: RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
4194 }
4195
4196 // Now that the Cond was cloned into the predecessor basic block,
4197 // or/and the two conditions together.
4198 Value *BICond = VMap[BI->getCondition()];
4199 PBI->setCondition(
4200 createLogicalOp(Builder, Opc, LHS: PBI->getCondition(), RHS: BICond, Name: "or.cond"));
4201 if (!ProfcheckDisableMetadataFixes)
4202 if (auto *SI = dyn_cast<SelectInst>(Val: PBI->getCondition()))
4203 if (!MDWeights.empty()) {
4204 assert(isSelectInRoleOfConjunctionOrDisjunction(SI));
4205 setFittedBranchWeights(I&: *SI, Weights: {MDWeights[0], MDWeights[1]},
4206 /*IsExpected=*/false, /*ElideAllZero=*/true);
4207 }
4208
4209 ++NumFoldBranchToCommonDest;
4210 return true;
4211}
4212
4213/// Return if an instruction's type or any of its operands' types are a vector
4214/// type.
4215static bool isVectorOp(Instruction &I) {
4216 return I.getType()->isVectorTy() || any_of(Range: I.operands(), P: [](Use &U) {
4217 return U->getType()->isVectorTy();
4218 });
4219}
4220
4221/// If this basic block is simple enough, and if a predecessor branches to us
4222/// and one of our successors, fold the block into the predecessor and use
4223/// logical operations to pick the right destination.
4224bool llvm::foldBranchToCommonDest(CondBrInst *BI, DomTreeUpdater *DTU,
4225 MemorySSAUpdater *MSSAU,
4226 const TargetTransformInfo *TTI,
4227 AssumptionCache *AC,
4228 unsigned BonusInstThreshold) {
4229 BasicBlock *BB = BI->getParent();
4230 TargetTransformInfo::TargetCostKind CostKind =
4231 BB->getParent()->hasMinSize() ? TargetTransformInfo::TCK_CodeSize
4232 : TargetTransformInfo::TCK_SizeAndLatency;
4233
4234 Instruction *Cond = dyn_cast<Instruction>(Val: BI->getCondition());
4235
4236 if (!Cond || !isa<CmpInst, BinaryOperator, SelectInst, TruncInst>(Val: Cond) ||
4237 Cond->getParent() != BB || !Cond->hasOneUse())
4238 return false;
4239
4240 // Finally, don't infinitely unroll conditional loops.
4241 if (is_contained(Range: successors(BB), Element: BB))
4242 return false;
4243
4244 // With which predecessors will we want to deal with?
4245 SmallVector<BasicBlock *, 8> Preds;
4246 for (BasicBlock *PredBlock : predecessors(BB)) {
4247 CondBrInst *PBI = dyn_cast<CondBrInst>(Val: PredBlock->getTerminator());
4248
4249 // Check that we have two conditional branches. If there is a PHI node in
4250 // the common successor, verify that the same value flows in from both
4251 // blocks.
4252 if (!PBI || !safeToMergeTerminators(SI1: BI, SI2: PBI))
4253 continue;
4254
4255 // Determine if the two branches share a common destination.
4256 BasicBlock *CommonSucc;
4257 Instruction::BinaryOps Opc;
4258 bool InvertPredCond;
4259 if (auto Recipe = shouldFoldCondBranchesToCommonDestination(BI, PBI, TTI))
4260 std::tie(args&: CommonSucc, args&: Opc, args&: InvertPredCond) = *Recipe;
4261 else
4262 continue;
4263
4264 // Check the cost of inserting the necessary logic before performing the
4265 // transformation.
4266 if (TTI) {
4267 Type *Ty = BI->getCondition()->getType();
4268 InstructionCost Cost = TTI->getArithmeticInstrCost(Opcode: Opc, Ty, CostKind);
4269 if (InvertPredCond && (!PBI->getCondition()->hasOneUse() ||
4270 !isa<CmpInst>(Val: PBI->getCondition())))
4271 Cost += TTI->getArithmeticInstrCost(Opcode: Instruction::Xor, Ty, CostKind);
4272
4273 if (Cost > BranchFoldThreshold)
4274 continue;
4275 }
4276
4277 // Ok, we do want to deal with this predecessor. Record it.
4278 Preds.emplace_back(Args&: PredBlock);
4279 }
4280
4281 // If there aren't any predecessors into which we can fold,
4282 // don't bother checking the cost.
4283 if (Preds.empty())
4284 return false;
4285
4286 // Only allow this transformation if computing the condition doesn't involve
4287 // too many instructions and these involved instructions can be executed
4288 // unconditionally. We denote all involved instructions except the condition
4289 // as "bonus instructions", and only allow this transformation when the
4290 // number of the bonus instructions we'll need to create when cloning into
4291 // each predecessor does not exceed a certain threshold.
4292 unsigned NumBonusInsts = 0;
4293 bool SawVectorOp = false;
4294 const unsigned PredCount = Preds.size();
4295 // Speculated instructions will be inserted before the terminator of the
4296 // predecessor. Only handle the simple case of one predecessor.
4297 const Instruction *CxtI =
4298 PredCount == 1 ? Preds[0]->getTerminator() : nullptr;
4299 for (Instruction &I : *BB) {
4300 // Don't check the branch condition comparison itself.
4301 if (&I == Cond)
4302 continue;
4303 // Ignore the terminator.
4304 if (isa<UncondBrInst, CondBrInst>(Val: I))
4305 continue;
4306 // Pseudo probes aren't speculatable but can be dropped on fold.
4307 if (isa<PseudoProbeInst>(Val: I))
4308 continue;
4309 // I must be safe to execute unconditionally.
4310 if (!isSafeToSpeculativelyExecute(I: &I, CtxI: CxtI, AC))
4311 return false;
4312 SawVectorOp |= isVectorOp(I);
4313
4314 // Account for the cost of duplicating this instruction into each
4315 // predecessor. Ignore free instructions.
4316 if (!TTI || TTI->getInstructionCost(U: &I, CostKind) !=
4317 TargetTransformInfo::TCC_Free) {
4318 NumBonusInsts += PredCount;
4319
4320 // Early exits once we reach the limit.
4321 if (NumBonusInsts >
4322 BonusInstThreshold * BranchFoldToCommonDestVectorMultiplier)
4323 return false;
4324 }
4325
4326 auto IsBCSSAUse = [BB, &I](Use &U) {
4327 auto *UI = cast<Instruction>(Val: U.getUser());
4328 if (auto *PN = dyn_cast<PHINode>(Val: UI))
4329 return PN->getIncomingBlock(U) == BB;
4330 return UI->getParent() == BB && I.comesBefore(Other: UI);
4331 };
4332
4333 // Does this instruction require rewriting of uses?
4334 if (!all_of(Range: I.uses(), P: IsBCSSAUse))
4335 return false;
4336 }
4337 if (NumBonusInsts >
4338 BonusInstThreshold *
4339 (SawVectorOp ? BranchFoldToCommonDestVectorMultiplier : 1))
4340 return false;
4341
4342 // Ok, we have the budget. Perform the transformation.
4343 for (BasicBlock *PredBlock : Preds) {
4344 auto *PBI = cast<CondBrInst>(Val: PredBlock->getTerminator());
4345 return performBranchToCommonDestFolding(BI, PBI, DTU, MSSAU, TTI);
4346 }
4347 return false;
4348}
4349
4350// If there is only one store in BB1 and BB2, return it, otherwise return
4351// nullptr.
4352static StoreInst *findUniqueStoreInBlocks(BasicBlock *BB1, BasicBlock *BB2) {
4353 StoreInst *S = nullptr;
4354 for (auto *BB : {BB1, BB2}) {
4355 if (!BB)
4356 continue;
4357 for (auto &I : *BB)
4358 if (auto *SI = dyn_cast<StoreInst>(Val: &I)) {
4359 if (S)
4360 // Multiple stores seen.
4361 return nullptr;
4362 else
4363 S = SI;
4364 }
4365 }
4366 return S;
4367}
4368
4369static Value *ensureValueAvailableInSuccessor(Value *V, BasicBlock *BB,
4370 Value *AlternativeV = nullptr) {
4371 // PHI is going to be a PHI node that allows the value V that is defined in
4372 // BB to be referenced in BB's only successor.
4373 //
4374 // If AlternativeV is nullptr, the only value we care about in PHI is V. It
4375 // doesn't matter to us what the other operand is (it'll never get used). We
4376 // could just create a new PHI with an undef incoming value, but that could
4377 // increase register pressure if EarlyCSE/InstCombine can't fold it with some
4378 // other PHI. So here we directly look for some PHI in BB's successor with V
4379 // as an incoming operand. If we find one, we use it, else we create a new
4380 // one.
4381 //
4382 // If AlternativeV is not nullptr, we care about both incoming values in PHI.
4383 // PHI must be exactly: phi <ty> [ %BB, %V ], [ %OtherBB, %AlternativeV]
4384 // where OtherBB is the single other predecessor of BB's only successor.
4385 PHINode *PHI = nullptr;
4386 BasicBlock *Succ = BB->getSingleSuccessor();
4387
4388 for (auto I = Succ->begin(); isa<PHINode>(Val: I); ++I)
4389 if (cast<PHINode>(Val&: I)->getIncomingValueForBlock(BB) == V) {
4390 PHI = cast<PHINode>(Val&: I);
4391 if (!AlternativeV)
4392 break;
4393
4394 assert(Succ->hasNPredecessors(2));
4395 auto PredI = pred_begin(BB: Succ);
4396 BasicBlock *OtherPredBB = *PredI == BB ? *++PredI : *PredI;
4397 if (PHI->getIncomingValueForBlock(BB: OtherPredBB) == AlternativeV)
4398 break;
4399 PHI = nullptr;
4400 }
4401 if (PHI)
4402 return PHI;
4403
4404 // If V is not an instruction defined in BB, just return it.
4405 if (!AlternativeV &&
4406 (!isa<Instruction>(Val: V) || cast<Instruction>(Val: V)->getParent() != BB))
4407 return V;
4408
4409 PHI = PHINode::Create(Ty: V->getType(), NumReservedValues: 2, NameStr: "simplifycfg.merge");
4410 PHI->insertBefore(InsertPos: Succ->begin());
4411 PHI->addIncoming(V, BB);
4412 for (BasicBlock *PredBB : predecessors(BB: Succ))
4413 if (PredBB != BB)
4414 PHI->addIncoming(
4415 V: AlternativeV ? AlternativeV : PoisonValue::get(T: V->getType()), BB: PredBB);
4416 return PHI;
4417}
4418
4419static bool mergeConditionalStoreToAddress(
4420 BasicBlock *PTB, BasicBlock *PFB, BasicBlock *QTB, BasicBlock *QFB,
4421 BasicBlock *PostBB, Value *Address, bool InvertPCond, bool InvertQCond,
4422 DomTreeUpdater *DTU, const DataLayout &DL, const TargetTransformInfo &TTI) {
4423 // For every pointer, there must be exactly two stores, one coming from
4424 // PTB or PFB, and the other from QTB or QFB. We don't support more than one
4425 // store (to any address) in PTB,PFB or QTB,QFB.
4426 // FIXME: We could relax this restriction with a bit more work and performance
4427 // testing.
4428 StoreInst *PStore = findUniqueStoreInBlocks(BB1: PTB, BB2: PFB);
4429 StoreInst *QStore = findUniqueStoreInBlocks(BB1: QTB, BB2: QFB);
4430 if (!PStore || !QStore)
4431 return false;
4432
4433 // Now check the stores are compatible.
4434 if (!QStore->isUnordered() || !PStore->isUnordered() ||
4435 PStore->getOrdering() != QStore->getOrdering() ||
4436 PStore->getSyncScopeID() != QStore->getSyncScopeID() ||
4437 PStore->getValueOperand()->getType() !=
4438 QStore->getValueOperand()->getType())
4439 return false;
4440
4441 // Check that sinking the store won't cause program behavior changes. Sinking
4442 // the store out of the Q blocks won't change any behavior as we're sinking
4443 // from a block to its unconditional successor. But we're moving a store from
4444 // the P blocks down through the middle block (QBI) and past both QFB and QTB.
4445 // So we need to check that there are no aliasing loads or stores in
4446 // QBI, QTB and QFB. We also need to check there are no conflicting memory
4447 // operations between PStore and the end of its parent block.
4448 //
4449 // The ideal way to do this is to query AliasAnalysis, but we don't
4450 // preserve AA currently so that is dangerous. Be super safe and just
4451 // check there are no other memory operations at all.
4452 for (auto &I : *QFB->getSinglePredecessor())
4453 if (I.mayReadOrWriteMemory())
4454 return false;
4455 for (auto &I : *QFB)
4456 if (&I != QStore && I.mayReadOrWriteMemory())
4457 return false;
4458 if (QTB)
4459 for (auto &I : *QTB)
4460 if (&I != QStore && I.mayReadOrWriteMemory())
4461 return false;
4462 for (auto I = BasicBlock::iterator(PStore), E = PStore->getParent()->end();
4463 I != E; ++I)
4464 if (&*I != PStore && I->mayReadOrWriteMemory())
4465 return false;
4466
4467 // If we're not in aggressive mode, we only optimize if we have some
4468 // confidence that by optimizing we'll allow P and/or Q to be if-converted.
4469 auto IsWorthwhile = [&](BasicBlock *BB, ArrayRef<StoreInst *> FreeStores) {
4470 if (!BB)
4471 return true;
4472 // Heuristic: if the block can be if-converted/phi-folded and the
4473 // instructions inside are all cheap (arithmetic/GEPs), it's worthwhile to
4474 // thread this store.
4475 InstructionCost Cost = 0;
4476 InstructionCost Budget =
4477 PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic;
4478 for (auto &I : *BB) {
4479 // Consider terminator instruction to be free.
4480 if (I.isTerminator())
4481 continue;
4482 // If this is one the stores that we want to speculate out of this BB,
4483 // then don't count it's cost, consider it to be free.
4484 if (auto *S = dyn_cast<StoreInst>(Val: &I))
4485 if (llvm::find(Range&: FreeStores, Val: S))
4486 continue;
4487 // Else, we have a white-list of instructions that we are ak speculating.
4488 if (!isa<BinaryOperator>(Val: I) && !isa<GetElementPtrInst>(Val: I))
4489 return false; // Not in white-list - not worthwhile folding.
4490 // And finally, if this is a non-free instruction that we are okay
4491 // speculating, ensure that we consider the speculation budget.
4492 Cost +=
4493 TTI.getInstructionCost(U: &I, CostKind: TargetTransformInfo::TCK_SizeAndLatency);
4494 if (Cost > Budget)
4495 return false; // Eagerly refuse to fold as soon as we're out of budget.
4496 }
4497 assert(Cost <= Budget &&
4498 "When we run out of budget we will eagerly return from within the "
4499 "per-instruction loop.");
4500 return true;
4501 };
4502
4503 const std::array<StoreInst *, 2> FreeStores = {PStore, QStore};
4504 if (!MergeCondStoresAggressively &&
4505 (!IsWorthwhile(PTB, FreeStores) || !IsWorthwhile(PFB, FreeStores) ||
4506 !IsWorthwhile(QTB, FreeStores) || !IsWorthwhile(QFB, FreeStores)))
4507 return false;
4508
4509 // If PostBB has more than two predecessors, we need to split it so we can
4510 // sink the store.
4511 if (std::next(x: pred_begin(BB: PostBB), n: 2) != pred_end(BB: PostBB)) {
4512 // We know that QFB's only successor is PostBB. And QFB has a single
4513 // predecessor. If QTB exists, then its only successor is also PostBB.
4514 // If QTB does not exist, then QFB's only predecessor has a conditional
4515 // branch to QFB and PostBB.
4516 BasicBlock *TruePred = QTB ? QTB : QFB->getSinglePredecessor();
4517 BasicBlock *NewBB =
4518 SplitBlockPredecessors(BB: PostBB, Preds: {QFB, TruePred}, Suffix: "condstore.split", DTU);
4519 if (!NewBB)
4520 return false;
4521 PostBB = NewBB;
4522 }
4523
4524 // OK, we're going to sink the stores to PostBB. The store has to be
4525 // conditional though, so first create the predicate.
4526 CondBrInst *PBranch =
4527 cast<CondBrInst>(Val: PFB->getSinglePredecessor()->getTerminator());
4528 CondBrInst *QBranch =
4529 cast<CondBrInst>(Val: QFB->getSinglePredecessor()->getTerminator());
4530 Value *PCond = PBranch->getCondition();
4531 Value *QCond = QBranch->getCondition();
4532
4533 Value *PPHI = ensureValueAvailableInSuccessor(V: PStore->getValueOperand(),
4534 BB: PStore->getParent());
4535 Value *QPHI = ensureValueAvailableInSuccessor(V: QStore->getValueOperand(),
4536 BB: QStore->getParent(), AlternativeV: PPHI);
4537
4538 BasicBlock::iterator PostBBFirst = PostBB->getFirstInsertionPt();
4539 IRBuilder<> QB(PostBB, PostBBFirst);
4540 QB.SetCurrentDebugLocation(PostBBFirst->getStableDebugLoc());
4541
4542 InvertPCond ^= (PStore->getParent() != PTB);
4543 InvertQCond ^= (QStore->getParent() != QTB);
4544 Value *PPred = InvertPCond ? QB.CreateNot(V: PCond) : PCond;
4545 Value *QPred = InvertQCond ? QB.CreateNot(V: QCond) : QCond;
4546
4547 Value *CombinedPred = QB.CreateOr(LHS: PPred, RHS: QPred);
4548
4549 BasicBlock::iterator InsertPt = QB.GetInsertPoint();
4550 auto *T = SplitBlockAndInsertIfThen(Cond: CombinedPred, SplitBefore: InsertPt,
4551 /*Unreachable=*/false,
4552 /*BranchWeights=*/nullptr, DTU);
4553 if (hasBranchWeightMD(I: *PBranch) && hasBranchWeightMD(I: *QBranch) &&
4554 !ProfcheckDisableMetadataFixes) {
4555 SmallVector<uint32_t, 2> PWeights, QWeights;
4556 extractBranchWeights(I: *PBranch, Weights&: PWeights);
4557 extractBranchWeights(I: *QBranch, Weights&: QWeights);
4558 if (InvertPCond)
4559 std::swap(a&: PWeights[0], b&: PWeights[1]);
4560 if (InvertQCond)
4561 std::swap(a&: QWeights[0], b&: QWeights[1]);
4562 auto CombinedWeights = getDisjunctionWeights(B1: PWeights, B2: QWeights);
4563 setFittedBranchWeights(I&: *PostBB->getTerminator(),
4564 Weights: {CombinedWeights[0], CombinedWeights[1]},
4565 /*IsExpected=*/false, /*ElideAllZero=*/true);
4566 }
4567
4568 QB.SetInsertPoint(T);
4569 StoreInst *SI = cast<StoreInst>(Val: QB.CreateStore(Val: QPHI, Ptr: Address));
4570 combineMetadataForCSE(K: QStore, J: PStore, DoesKMove: true);
4571 SI->copyMetadata(SrcInst: *QStore);
4572 // Update any dbg.assign intrinsics to track the merged value (QPHI) instead
4573 // of the original constant values, likely making these identical.
4574 for (auto *DbgAssign : at::getDVRAssignmentMarkers(Inst: SI)) {
4575 if (llvm::is_contained(Range: DbgAssign->location_ops(),
4576 Element: PStore->getValueOperand()))
4577 DbgAssign->replaceVariableLocationOp(OldValue: PStore->getValueOperand(), NewValue: QPHI);
4578 if (llvm::is_contained(Range: DbgAssign->location_ops(),
4579 Element: QStore->getValueOperand()))
4580 DbgAssign->replaceVariableLocationOp(OldValue: QStore->getValueOperand(), NewValue: QPHI);
4581 }
4582
4583 // Choose the minimum alignment. If we could prove both stores execute, we
4584 // could use biggest one. In this case, though, we only know that one of the
4585 // stores executes. And we don't know it's safe to take the alignment from a
4586 // store that doesn't execute.
4587 SI->setAlignment(std::min(a: PStore->getAlign(), b: QStore->getAlign()));
4588
4589 if (QStore->isAtomic())
4590 SI->setAtomic(Ordering: QStore->getOrdering(), SSID: QStore->getSyncScopeID());
4591
4592 QStore->eraseFromParent();
4593 PStore->eraseFromParent();
4594
4595 return true;
4596}
4597
4598static bool mergeConditionalStores(CondBrInst *PBI, CondBrInst *QBI,
4599 DomTreeUpdater *DTU, const DataLayout &DL,
4600 const TargetTransformInfo &TTI) {
4601 // The intention here is to find diamonds or triangles (see below) where each
4602 // conditional block contains a store to the same address. Both of these
4603 // stores are conditional, so they can't be unconditionally sunk. But it may
4604 // be profitable to speculatively sink the stores into one merged store at the
4605 // end, and predicate the merged store on the union of the two conditions of
4606 // PBI and QBI.
4607 //
4608 // This can reduce the number of stores executed if both of the conditions are
4609 // true, and can allow the blocks to become small enough to be if-converted.
4610 // This optimization will also chain, so that ladders of test-and-set
4611 // sequences can be if-converted away.
4612 //
4613 // We only deal with simple diamonds or triangles:
4614 //
4615 // PBI or PBI or a combination of the two
4616 // / \ | \
4617 // PTB PFB | PFB
4618 // \ / | /
4619 // QBI QBI
4620 // / \ | \
4621 // QTB QFB | QFB
4622 // \ / | /
4623 // PostBB PostBB
4624 //
4625 // We model triangles as a type of diamond with a nullptr "true" block.
4626 // Triangles are canonicalized so that the fallthrough edge is represented by
4627 // a true condition, as in the diagram above.
4628 BasicBlock *PTB = PBI->getSuccessor(i: 0);
4629 BasicBlock *PFB = PBI->getSuccessor(i: 1);
4630 BasicBlock *QTB = QBI->getSuccessor(i: 0);
4631 BasicBlock *QFB = QBI->getSuccessor(i: 1);
4632 BasicBlock *PostBB = QFB->getSingleSuccessor();
4633
4634 // Make sure we have a good guess for PostBB. If QTB's only successor is
4635 // QFB, then QFB is a better PostBB.
4636 if (QTB->getSingleSuccessor() == QFB)
4637 PostBB = QFB;
4638
4639 // If we couldn't find a good PostBB, stop.
4640 if (!PostBB)
4641 return false;
4642
4643 bool InvertPCond = false, InvertQCond = false;
4644 // Canonicalize fallthroughs to the true branches.
4645 if (PFB == QBI->getParent()) {
4646 std::swap(a&: PFB, b&: PTB);
4647 InvertPCond = true;
4648 }
4649 if (QFB == PostBB) {
4650 std::swap(a&: QFB, b&: QTB);
4651 InvertQCond = true;
4652 }
4653
4654 // From this point on we can assume PTB or QTB may be fallthroughs but PFB
4655 // and QFB may not. Model fallthroughs as a nullptr block.
4656 if (PTB == QBI->getParent())
4657 PTB = nullptr;
4658 if (QTB == PostBB)
4659 QTB = nullptr;
4660
4661 // Legality bailouts. We must have at least the non-fallthrough blocks and
4662 // the post-dominating block, and the non-fallthroughs must only have one
4663 // predecessor.
4664 auto HasOnePredAndOneSucc = [](BasicBlock *BB, BasicBlock *P, BasicBlock *S) {
4665 return BB->getSinglePredecessor() == P && BB->getSingleSuccessor() == S;
4666 };
4667 if (!HasOnePredAndOneSucc(PFB, PBI->getParent(), QBI->getParent()) ||
4668 !HasOnePredAndOneSucc(QFB, QBI->getParent(), PostBB))
4669 return false;
4670 if ((PTB && !HasOnePredAndOneSucc(PTB, PBI->getParent(), QBI->getParent())) ||
4671 (QTB && !HasOnePredAndOneSucc(QTB, QBI->getParent(), PostBB)))
4672 return false;
4673 if (!QBI->getParent()->hasNUses(N: 2))
4674 return false;
4675
4676 // OK, this is a sequence of two diamonds or triangles.
4677 // Check if there are stores in PTB or PFB that are repeated in QTB or QFB.
4678 SmallPtrSet<Value *, 4> PStoreAddresses, QStoreAddresses;
4679 for (auto *BB : {PTB, PFB}) {
4680 if (!BB)
4681 continue;
4682 for (auto &I : *BB)
4683 if (StoreInst *SI = dyn_cast<StoreInst>(Val: &I))
4684 PStoreAddresses.insert(Ptr: SI->getPointerOperand());
4685 }
4686 for (auto *BB : {QTB, QFB}) {
4687 if (!BB)
4688 continue;
4689 for (auto &I : *BB)
4690 if (StoreInst *SI = dyn_cast<StoreInst>(Val: &I))
4691 QStoreAddresses.insert(Ptr: SI->getPointerOperand());
4692 }
4693
4694 set_intersect(S1&: PStoreAddresses, S2: QStoreAddresses);
4695 // set_intersect mutates PStoreAddresses in place. Rename it here to make it
4696 // clear what it contains.
4697 auto &CommonAddresses = PStoreAddresses;
4698
4699 bool Changed = false;
4700 for (auto *Address : CommonAddresses)
4701 Changed |=
4702 mergeConditionalStoreToAddress(PTB, PFB, QTB, QFB, PostBB, Address,
4703 InvertPCond, InvertQCond, DTU, DL, TTI);
4704 return Changed;
4705}
4706
4707/// If the previous block ended with a widenable branch, determine if reusing
4708/// the target block is profitable and legal. This will have the effect of
4709/// "widening" PBI, but doesn't require us to reason about hosting safety.
4710static bool tryWidenCondBranchToCondBranch(CondBrInst *PBI, CondBrInst *BI,
4711 DomTreeUpdater *DTU) {
4712 // TODO: This can be generalized in two important ways:
4713 // 1) We can allow phi nodes in IfFalseBB and simply reuse all the input
4714 // values from the PBI edge.
4715 // 2) We can sink side effecting instructions into BI's fallthrough
4716 // successor provided they doesn't contribute to computation of
4717 // BI's condition.
4718 BasicBlock *IfTrueBB = PBI->getSuccessor(i: 0);
4719 BasicBlock *IfFalseBB = PBI->getSuccessor(i: 1);
4720 if (!isWidenableBranch(U: PBI) || IfTrueBB != BI->getParent() ||
4721 !BI->getParent()->getSinglePredecessor())
4722 return false;
4723 if (!IfFalseBB->phis().empty())
4724 return false; // TODO
4725 // This helps avoid infinite loop with SimplifyCondBranchToCondBranch which
4726 // may undo the transform done here.
4727 // TODO: There might be a more fine-grained solution to this.
4728 if (!llvm::succ_empty(BB: IfFalseBB))
4729 return false;
4730 // Use lambda to lazily compute expensive condition after cheap ones.
4731 auto NoSideEffects = [](BasicBlock &BB) {
4732 return llvm::none_of(Range&: BB, P: [](const Instruction &I) {
4733 return I.mayWriteToMemory() || I.mayHaveSideEffects();
4734 });
4735 };
4736 if (BI->getSuccessor(i: 1) != IfFalseBB && // no inf looping
4737 BI->getSuccessor(i: 1)->getTerminatingDeoptimizeCall() && // profitability
4738 NoSideEffects(*BI->getParent())) {
4739 auto *OldSuccessor = BI->getSuccessor(i: 1);
4740 OldSuccessor->removePredecessor(Pred: BI->getParent());
4741 BI->setSuccessor(idx: 1, NewSucc: IfFalseBB);
4742 if (DTU)
4743 DTU->applyUpdates(
4744 Updates: {{DominatorTree::Insert, BI->getParent(), IfFalseBB},
4745 {DominatorTree::Delete, BI->getParent(), OldSuccessor}});
4746 return true;
4747 }
4748 if (BI->getSuccessor(i: 0) != IfFalseBB && // no inf looping
4749 BI->getSuccessor(i: 0)->getTerminatingDeoptimizeCall() && // profitability
4750 NoSideEffects(*BI->getParent())) {
4751 auto *OldSuccessor = BI->getSuccessor(i: 0);
4752 OldSuccessor->removePredecessor(Pred: BI->getParent());
4753 BI->setSuccessor(idx: 0, NewSucc: IfFalseBB);
4754 if (DTU)
4755 DTU->applyUpdates(
4756 Updates: {{DominatorTree::Insert, BI->getParent(), IfFalseBB},
4757 {DominatorTree::Delete, BI->getParent(), OldSuccessor}});
4758 return true;
4759 }
4760 return false;
4761}
4762
4763/// If we have a conditional branch as a predecessor of another block,
4764/// this function tries to simplify it. We know
4765/// that PBI and BI are both conditional branches, and BI is in one of the
4766/// successor blocks of PBI - PBI branches to BI.
4767static bool SimplifyCondBranchToCondBranch(CondBrInst *PBI, CondBrInst *BI,
4768 DomTreeUpdater *DTU,
4769 const DataLayout &DL,
4770 const TargetTransformInfo &TTI) {
4771 BasicBlock *BB = BI->getParent();
4772
4773 // If this block ends with a branch instruction, and if there is a
4774 // predecessor that ends on a branch of the same condition, make
4775 // this conditional branch redundant.
4776 if (PBI->getCondition() == BI->getCondition() &&
4777 PBI->getSuccessor(i: 0) != PBI->getSuccessor(i: 1)) {
4778 // Okay, the outcome of this conditional branch is statically
4779 // knowable. If this block had a single pred, handle specially, otherwise
4780 // foldCondBranchOnValueKnownInPredecessor() will handle it.
4781 if (BB->getSinglePredecessor()) {
4782 // Turn this into a branch on constant.
4783 bool CondIsTrue = PBI->getSuccessor(i: 0) == BB;
4784 BI->setCondition(
4785 ConstantInt::get(Ty: Type::getInt1Ty(C&: BB->getContext()), V: CondIsTrue));
4786 return true; // Nuke the branch on constant.
4787 }
4788 }
4789
4790 // If the previous block ended with a widenable branch, determine if reusing
4791 // the target block is profitable and legal. This will have the effect of
4792 // "widening" PBI, but doesn't require us to reason about hosting safety.
4793 if (tryWidenCondBranchToCondBranch(PBI, BI, DTU))
4794 return true;
4795
4796 // If both branches are conditional and both contain stores to the same
4797 // address, remove the stores from the conditionals and create a conditional
4798 // merged store at the end.
4799 if (MergeCondStores && mergeConditionalStores(PBI, QBI: BI, DTU, DL, TTI))
4800 return true;
4801
4802 // If this is a conditional branch in an empty block, and if any
4803 // predecessors are a conditional branch to one of our destinations,
4804 // fold the conditions into logical ops and one cond br.
4805
4806 // Ignore dbg intrinsics.
4807 if (&*BB->begin() != BI)
4808 return false;
4809
4810 int PBIOp, BIOp;
4811 if (PBI->getSuccessor(i: 0) == BI->getSuccessor(i: 0)) {
4812 PBIOp = 0;
4813 BIOp = 0;
4814 } else if (PBI->getSuccessor(i: 0) == BI->getSuccessor(i: 1)) {
4815 PBIOp = 0;
4816 BIOp = 1;
4817 } else if (PBI->getSuccessor(i: 1) == BI->getSuccessor(i: 0)) {
4818 PBIOp = 1;
4819 BIOp = 0;
4820 } else if (PBI->getSuccessor(i: 1) == BI->getSuccessor(i: 1)) {
4821 PBIOp = 1;
4822 BIOp = 1;
4823 } else {
4824 return false;
4825 }
4826
4827 // Check to make sure that the other destination of this branch
4828 // isn't BB itself. If so, this is an infinite loop that will
4829 // keep getting unwound.
4830 if (PBI->getSuccessor(i: PBIOp) == BB)
4831 return false;
4832
4833 // If predecessor's branch probability to BB is too low don't merge branches.
4834 SmallVector<uint32_t, 2> PredWeights;
4835 if (!PBI->getMetadata(KindID: LLVMContext::MD_unpredictable) &&
4836 extractBranchWeights(I: *PBI, Weights&: PredWeights) &&
4837 (static_cast<uint64_t>(PredWeights[0]) + PredWeights[1]) != 0) {
4838
4839 BranchProbability CommonDestProb = BranchProbability::getBranchProbability(
4840 Numerator: PredWeights[PBIOp],
4841 Denominator: static_cast<uint64_t>(PredWeights[0]) + PredWeights[1]);
4842
4843 BranchProbability Likely = TTI.getPredictableBranchThreshold();
4844 if (CommonDestProb >= Likely)
4845 return false;
4846 }
4847
4848 // Do not perform this transformation if it would require
4849 // insertion of a large number of select instructions. For targets
4850 // without predication/cmovs, this is a big pessimization.
4851
4852 BasicBlock *CommonDest = PBI->getSuccessor(i: PBIOp);
4853 BasicBlock *RemovedDest = PBI->getSuccessor(i: PBIOp ^ 1);
4854 unsigned NumPhis = 0;
4855 for (BasicBlock::iterator II = CommonDest->begin(); isa<PHINode>(Val: II);
4856 ++II, ++NumPhis) {
4857 if (NumPhis > 2) // Disable this xform.
4858 return false;
4859 }
4860
4861 // Finally, if everything is ok, fold the branches to logical ops.
4862 BasicBlock *OtherDest = BI->getSuccessor(i: BIOp ^ 1);
4863
4864 LLVM_DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
4865 << "AND: " << *BI->getParent());
4866
4867 SmallVector<DominatorTree::UpdateType, 5> Updates;
4868
4869 // If OtherDest *is* BB, then BB is a basic block with a single conditional
4870 // branch in it, where one edge (OtherDest) goes back to itself but the other
4871 // exits. We don't *know* that the program avoids the infinite loop
4872 // (even though that seems likely). If we do this xform naively, we'll end up
4873 // recursively unpeeling the loop. Since we know that (after the xform is
4874 // done) that the block *is* infinite if reached, we just make it an obviously
4875 // infinite loop with no cond branch.
4876 if (OtherDest == BB) {
4877 // Insert it at the end of the function, because it's either code,
4878 // or it won't matter if it's hot. :)
4879 BasicBlock *InfLoopBlock =
4880 BasicBlock::Create(Context&: BB->getContext(), Name: "infloop", Parent: BB->getParent());
4881 UncondBrInst::Create(Target: InfLoopBlock, InsertBefore: InfLoopBlock);
4882 if (DTU)
4883 Updates.push_back(Elt: {DominatorTree::Insert, InfLoopBlock, InfLoopBlock});
4884 OtherDest = InfLoopBlock;
4885 }
4886
4887 LLVM_DEBUG(dbgs() << *PBI->getParent()->getParent());
4888
4889 // BI may have other predecessors. Because of this, we leave
4890 // it alone, but modify PBI.
4891
4892 // Make sure we get to CommonDest on True&True directions.
4893 Value *PBICond = PBI->getCondition();
4894 IRBuilder<NoFolder> Builder(PBI);
4895 if (PBIOp)
4896 PBICond = Builder.CreateNot(V: PBICond, Name: PBICond->getName() + ".not");
4897
4898 Value *BICond = BI->getCondition();
4899 if (BIOp)
4900 BICond = Builder.CreateNot(V: BICond, Name: BICond->getName() + ".not");
4901
4902 // Merge the conditions.
4903 Value *Cond =
4904 createLogicalOp(Builder, Opc: Instruction::Or, LHS: PBICond, RHS: BICond, Name: "brmerge");
4905
4906 // Modify PBI to branch on the new condition to the new dests.
4907 PBI->setCondition(Cond);
4908 PBI->setSuccessor(idx: 0, NewSucc: CommonDest);
4909 PBI->setSuccessor(idx: 1, NewSucc: OtherDest);
4910
4911 if (DTU) {
4912 Updates.push_back(Elt: {DominatorTree::Insert, PBI->getParent(), OtherDest});
4913 Updates.push_back(Elt: {DominatorTree::Delete, PBI->getParent(), RemovedDest});
4914
4915 DTU->applyUpdates(Updates);
4916 }
4917
4918 // Update branch weight for PBI.
4919 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
4920 uint64_t PredCommon, PredOther, SuccCommon, SuccOther;
4921 bool HasWeights =
4922 extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight,
4923 SuccTrueWeight, SuccFalseWeight);
4924 if (HasWeights) {
4925 PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
4926 PredOther = PBIOp ? PredTrueWeight : PredFalseWeight;
4927 SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
4928 SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
4929 // The weight to CommonDest should be PredCommon * SuccTotal +
4930 // PredOther * SuccCommon.
4931 // The weight to OtherDest should be PredOther * SuccOther.
4932 uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther) +
4933 PredOther * SuccCommon,
4934 PredOther * SuccOther};
4935
4936 setFittedBranchWeights(I&: *PBI, Weights: NewWeights, /*IsExpected=*/false,
4937 /*ElideAllZero=*/true);
4938 // Cond may be a select instruction with the first operand set to "true", or
4939 // the second to "false" (see how createLogicalOp works for `and` and `or`)
4940 if (!ProfcheckDisableMetadataFixes)
4941 if (auto *SI = dyn_cast<SelectInst>(Val: Cond)) {
4942 assert(isSelectInRoleOfConjunctionOrDisjunction(SI));
4943 // The select is predicated on PBICond
4944 assert(SI->getCondition() == PBICond);
4945 // The corresponding probabilities are what was referred to above as
4946 // PredCommon and PredOther.
4947 setFittedBranchWeights(I&: *SI, Weights: {PredCommon, PredOther},
4948 /*IsExpected=*/false, /*ElideAllZero=*/true);
4949 }
4950 }
4951
4952 // OtherDest may have phi nodes. If so, add an entry from PBI's
4953 // block that are identical to the entries for BI's block.
4954 addPredecessorToBlock(Succ: OtherDest, NewPred: PBI->getParent(), ExistPred: BB);
4955
4956 // We know that the CommonDest already had an edge from PBI to
4957 // it. If it has PHIs though, the PHIs may have different
4958 // entries for BB and PBI's BB. If so, insert a select to make
4959 // them agree.
4960 for (PHINode &PN : CommonDest->phis()) {
4961 Value *BIV = PN.getIncomingValueForBlock(BB);
4962 unsigned PBBIdx = PN.getBasicBlockIndex(BB: PBI->getParent());
4963 Value *PBIV = PN.getIncomingValue(i: PBBIdx);
4964 if (BIV != PBIV) {
4965 // Insert a select in PBI to pick the right value.
4966 SelectInst *NV = cast<SelectInst>(
4967 Val: Builder.CreateSelect(C: PBICond, True: PBIV, False: BIV, Name: PBIV->getName() + ".mux"));
4968 PN.setIncomingValue(i: PBBIdx, V: NV);
4969 // The select has the same condition as PBI, in the same BB. The
4970 // probabilities don't change.
4971 if (HasWeights) {
4972 uint64_t TrueWeight = PBIOp ? PredFalseWeight : PredTrueWeight;
4973 uint64_t FalseWeight = PBIOp ? PredTrueWeight : PredFalseWeight;
4974 setFittedBranchWeights(I&: *NV, Weights: {TrueWeight, FalseWeight},
4975 /*IsExpected=*/false, /*ElideAllZero=*/true);
4976 }
4977 }
4978 }
4979
4980 LLVM_DEBUG(dbgs() << "INTO: " << *PBI->getParent());
4981 LLVM_DEBUG(dbgs() << *PBI->getParent()->getParent());
4982
4983 // This basic block is probably dead. We know it has at least
4984 // one fewer predecessor.
4985 return true;
4986}
4987
4988// Simplifies a terminator by replacing it with a branch to TrueBB if Cond is
4989// true or to FalseBB if Cond is false.
4990// Takes care of updating the successors and removing the old terminator.
4991// Also makes sure not to introduce new successors by assuming that edges to
4992// non-successor TrueBBs and FalseBBs aren't reachable.
4993bool SimplifyCFGOpt::simplifyTerminatorOnSelect(Instruction *OldTerm,
4994 Value *Cond, BasicBlock *TrueBB,
4995 BasicBlock *FalseBB,
4996 uint32_t TrueWeight,
4997 uint32_t FalseWeight) {
4998 auto *BB = OldTerm->getParent();
4999 // Remove any superfluous successor edges from the CFG.
5000 // First, figure out which successors to preserve.
5001 // If TrueBB and FalseBB are equal, only try to preserve one copy of that
5002 // successor.
5003 BasicBlock *KeepEdge1 = TrueBB;
5004 BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr;
5005
5006 SmallSetVector<BasicBlock *, 2> RemovedSuccessors;
5007
5008 // Then remove the rest.
5009 for (BasicBlock *Succ : successors(I: OldTerm)) {
5010 // Make sure only to keep exactly one copy of each edge.
5011 if (Succ == KeepEdge1)
5012 KeepEdge1 = nullptr;
5013 else if (Succ == KeepEdge2)
5014 KeepEdge2 = nullptr;
5015 else {
5016 Succ->removePredecessor(Pred: BB,
5017 /*KeepOneInputPHIs=*/true);
5018
5019 if (Succ != TrueBB && Succ != FalseBB)
5020 RemovedSuccessors.insert(X: Succ);
5021 }
5022 }
5023
5024 IRBuilder<> Builder(OldTerm);
5025 Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc());
5026
5027 // Insert an appropriate new terminator.
5028 if (!KeepEdge1 && !KeepEdge2) {
5029 if (TrueBB == FalseBB) {
5030 // We were only looking for one successor, and it was present.
5031 // Create an unconditional branch to it.
5032 Builder.CreateBr(Dest: TrueBB);
5033 } else {
5034 // We found both of the successors we were looking for.
5035 // Create a conditional branch sharing the condition of the select.
5036 CondBrInst *NewBI = Builder.CreateCondBr(Cond, True: TrueBB, False: FalseBB);
5037 setBranchWeights(I&: *NewBI, Weights: {TrueWeight, FalseWeight},
5038 /*IsExpected=*/false, /*ElideAllZero=*/true);
5039 }
5040 } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
5041 // Neither of the selected blocks were successors, so this
5042 // terminator must be unreachable.
5043 new UnreachableInst(OldTerm->getContext(), OldTerm->getIterator());
5044 } else {
5045 // One of the selected values was a successor, but the other wasn't.
5046 // Insert an unconditional branch to the one that was found;
5047 // the edge to the one that wasn't must be unreachable.
5048 if (!KeepEdge1) {
5049 // Only TrueBB was found.
5050 Builder.CreateBr(Dest: TrueBB);
5051 } else {
5052 // Only FalseBB was found.
5053 Builder.CreateBr(Dest: FalseBB);
5054 }
5055 }
5056
5057 eraseTerminatorAndDCECond(TI: OldTerm);
5058
5059 if (DTU) {
5060 SmallVector<DominatorTree::UpdateType, 2> Updates;
5061 Updates.reserve(N: RemovedSuccessors.size());
5062 for (auto *RemovedSuccessor : RemovedSuccessors)
5063 Updates.push_back(Elt: {DominatorTree::Delete, BB, RemovedSuccessor});
5064 DTU->applyUpdates(Updates);
5065 }
5066
5067 return true;
5068}
5069
5070// Replaces
5071// (switch (select cond, X, Y)) on constant X, Y
5072// with a branch - conditional if X and Y lead to distinct BBs,
5073// unconditional otherwise.
5074bool SimplifyCFGOpt::simplifySwitchOnSelect(SwitchInst *SI,
5075 SelectInst *Select) {
5076 // Check for constant integer values in the select.
5077 ConstantInt *TrueVal = dyn_cast<ConstantInt>(Val: Select->getTrueValue());
5078 ConstantInt *FalseVal = dyn_cast<ConstantInt>(Val: Select->getFalseValue());
5079 if (!TrueVal || !FalseVal)
5080 return false;
5081
5082 // Find the relevant condition and destinations.
5083 Value *Condition = Select->getCondition();
5084 BasicBlock *TrueBB = SI->findCaseValue(C: TrueVal)->getCaseSuccessor();
5085 BasicBlock *FalseBB = SI->findCaseValue(C: FalseVal)->getCaseSuccessor();
5086
5087 // Get weight for TrueBB and FalseBB.
5088 uint32_t TrueWeight = 0, FalseWeight = 0;
5089 SmallVector<uint64_t, 8> Weights;
5090 bool HasWeights = hasBranchWeightMD(I: *SI);
5091 if (HasWeights) {
5092 getBranchWeights(TI: SI, Weights);
5093 if (Weights.size() == 1 + SI->getNumCases()) {
5094 TrueWeight =
5095 (uint32_t)Weights[SI->findCaseValue(C: TrueVal)->getSuccessorIndex()];
5096 FalseWeight =
5097 (uint32_t)Weights[SI->findCaseValue(C: FalseVal)->getSuccessorIndex()];
5098 }
5099 }
5100
5101 // Perform the actual simplification.
5102 return simplifyTerminatorOnSelect(OldTerm: SI, Cond: Condition, TrueBB, FalseBB, TrueWeight,
5103 FalseWeight);
5104}
5105
5106// Replaces
5107// (indirectbr (select cond, blockaddress(@fn, BlockA),
5108// blockaddress(@fn, BlockB)))
5109// with
5110// (br cond, BlockA, BlockB).
5111bool SimplifyCFGOpt::simplifyIndirectBrOnSelect(IndirectBrInst *IBI,
5112 SelectInst *SI) {
5113 // Check that both operands of the select are block addresses.
5114 BlockAddress *TBA = dyn_cast<BlockAddress>(Val: SI->getTrueValue());
5115 BlockAddress *FBA = dyn_cast<BlockAddress>(Val: SI->getFalseValue());
5116 if (!TBA || !FBA)
5117 return false;
5118
5119 // Extract the actual blocks.
5120 BasicBlock *TrueBB = TBA->getBasicBlock();
5121 BasicBlock *FalseBB = FBA->getBasicBlock();
5122
5123 // The select's profile becomes the profile of the conditional branch that
5124 // replaces the indirect branch.
5125 SmallVector<uint32_t> SelectBranchWeights(2);
5126 if (!ProfcheckDisableMetadataFixes)
5127 extractBranchWeights(I: *SI, Weights&: SelectBranchWeights);
5128 // Perform the actual simplification.
5129 return simplifyTerminatorOnSelect(OldTerm: IBI, Cond: SI->getCondition(), TrueBB, FalseBB,
5130 TrueWeight: SelectBranchWeights[0],
5131 FalseWeight: SelectBranchWeights[1]);
5132}
5133
5134/// This is called when we find an icmp instruction
5135/// (a seteq/setne with a constant) as the only instruction in a
5136/// block that ends with an uncond branch. We are looking for a very specific
5137/// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In
5138/// this case, we merge the first two "or's of icmp" into a switch, but then the
5139/// default value goes to an uncond block with a seteq in it, we get something
5140/// like:
5141///
5142/// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ]
5143/// DEFAULT:
5144/// %tmp = icmp eq i8 %A, 92
5145/// br label %end
5146/// end:
5147/// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
5148///
5149/// We prefer to split the edge to 'end' so that there is a true/false entry to
5150/// the PHI, merging the third icmp into the switch.
5151bool SimplifyCFGOpt::tryToSimplifyUncondBranchWithICmpInIt(
5152 ICmpInst *ICI, IRBuilder<> &Builder) {
5153 // Select == nullptr means we assume that there is a hidden no-op select
5154 // instruction of `_ = select %icmp, true, false` after `%icmp = icmp ...`
5155 return tryToSimplifyUncondBranchWithICmpSelectInIt(ICI, Select: nullptr, Builder);
5156}
5157
5158/// Similar to tryToSimplifyUncondBranchWithICmpInIt, but handle a more generic
5159/// case. This is called when we find an icmp instruction (a seteq/setne with a
5160/// constant) and its following select instruction as the only TWO instructions
5161/// in a block that ends with an uncond branch. We are looking for a very
5162/// specific pattern that occurs when "
5163/// if (A == 1) return C1;
5164/// if (A == 2) return C2;
5165/// if (A < 3) return C3;
5166/// return C4;
5167/// " gets simplified. In this case, we merge the first two "branches of icmp"
5168/// into a switch, but then the default value goes to an uncond block with a lt
5169/// icmp and select in it, as InstCombine can not simplify "A < 3" as "A == 2".
5170/// After SimplifyCFG and other subsequent optimizations (e.g., SCCP), we might
5171/// get something like:
5172///
5173/// case1:
5174/// switch i8 %A, label %DEFAULT [ i8 0, label %end i8 1, label %case2 ]
5175/// case2:
5176/// br label %end
5177/// DEFAULT:
5178/// %tmp = icmp eq i8 %A, 2
5179/// %val = select i1 %tmp, i8 C3, i8 C4
5180/// br label %end
5181/// end:
5182/// _ = phi i8 [ C1, %case1 ], [ C2, %case2 ], [ %val, %DEFAULT ]
5183///
5184/// We prefer to split the edge to 'end' so that there are TWO entries of V3/V4
5185/// to the PHI, merging the icmp & select into the switch, as follows:
5186///
5187/// case1:
5188/// switch i8 %A, label %DEFAULT [
5189/// i8 0, label %end
5190/// i8 1, label %case2
5191/// i8 2, label %case3
5192/// ]
5193/// case2:
5194/// br label %end
5195/// case3:
5196/// br label %end
5197/// DEFAULT:
5198/// br label %end
5199/// end:
5200/// _ = phi i8 [ C1, %case1 ], [ C2, %case2 ], [ C3, %case2 ], [ C4, %DEFAULT]
5201bool SimplifyCFGOpt::tryToSimplifyUncondBranchWithICmpSelectInIt(
5202 ICmpInst *ICI, SelectInst *Select, IRBuilder<> &Builder) {
5203 BasicBlock *BB = ICI->getParent();
5204
5205 // If the block has any PHIs in it or the icmp/select has multiple uses, it is
5206 // too complex.
5207 /// TODO: support multi-phis in succ BB of select's BB.
5208 if (isa<PHINode>(Val: BB->begin()) || !ICI->hasOneUse() ||
5209 (Select && !Select->hasOneUse()))
5210 return false;
5211
5212 // The pattern we're looking for is where our only predecessor is a switch on
5213 // 'V' and this block is the default case for the switch. In this case we can
5214 // fold the compared value into the switch to simplify things.
5215 BasicBlock *Pred = BB->getSinglePredecessor();
5216 if (!Pred || !isa<SwitchInst>(Val: Pred->getTerminator()))
5217 return false;
5218
5219 Value *IcmpCond;
5220 ConstantInt *NewCaseVal;
5221 CmpPredicate Predicate;
5222
5223 // Match icmp X, C
5224 if (!match(V: ICI,
5225 P: m_ICmp(Pred&: Predicate, L: m_Value(V&: IcmpCond), R: m_ConstantInt(CI&: NewCaseVal))))
5226 return false;
5227
5228 Value *SelectCond, *SelectTrueVal, *SelectFalseVal;
5229 Instruction *User;
5230 if (!Select) {
5231 // If Select == nullptr, we can assume that there is a hidden no-op select
5232 // just after icmp
5233 SelectCond = ICI;
5234 SelectTrueVal = Builder.getTrue();
5235 SelectFalseVal = Builder.getFalse();
5236 User = ICI->user_back();
5237 } else {
5238 SelectCond = Select->getCondition();
5239 // Check if the select condition is the same as the icmp condition.
5240 if (SelectCond != ICI)
5241 return false;
5242 SelectTrueVal = Select->getTrueValue();
5243 SelectFalseVal = Select->getFalseValue();
5244 User = Select->user_back();
5245 }
5246
5247 SwitchInst *SI = cast<SwitchInst>(Val: Pred->getTerminator());
5248 if (SI->getCondition() != IcmpCond)
5249 return false;
5250
5251 // If BB is reachable on a non-default case, then we simply know the value of
5252 // V in this block. Substitute it and constant fold the icmp instruction
5253 // away.
5254 if (SI->getDefaultDest() != BB) {
5255 ConstantInt *VVal = SI->findCaseDest(BB);
5256 assert(VVal && "Should have a unique destination value");
5257 ICI->setOperand(i_nocapture: 0, Val_nocapture: VVal);
5258
5259 if (Value *V = simplifyInstruction(I: ICI, Q: {DL, ICI})) {
5260 ICI->replaceAllUsesWith(V);
5261 ICI->eraseFromParent();
5262 }
5263 // BB is now empty, so it is likely to simplify away.
5264 return requestResimplify();
5265 }
5266
5267 // Ok, the block is reachable from the default dest. If the constant we're
5268 // comparing exists in one of the other edges, then we can constant fold ICI
5269 // and zap it.
5270 if (SI->findCaseValue(C: NewCaseVal) != SI->case_default()) {
5271 Value *V;
5272 if (Predicate == ICmpInst::ICMP_EQ)
5273 V = ConstantInt::getFalse(Context&: BB->getContext());
5274 else
5275 V = ConstantInt::getTrue(Context&: BB->getContext());
5276
5277 ICI->replaceAllUsesWith(V);
5278 ICI->eraseFromParent();
5279 // BB is now empty, so it is likely to simplify away.
5280 return requestResimplify();
5281 }
5282
5283 // The use of the select has to be in the 'end' block, by the only PHI node in
5284 // the block.
5285 BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(Idx: 0);
5286 PHINode *PHIUse = dyn_cast<PHINode>(Val: User);
5287 if (PHIUse == nullptr || PHIUse != &SuccBlock->front() ||
5288 isa<PHINode>(Val: ++BasicBlock::iterator(PHIUse)))
5289 return false;
5290
5291 // If the icmp is a SETEQ, then the default dest gets SelectFalseVal, the new
5292 // edge gets SelectTrueVal in the PHI.
5293 Value *DefaultCst = SelectFalseVal;
5294 Value *NewCst = SelectTrueVal;
5295
5296 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
5297 std::swap(a&: DefaultCst, b&: NewCst);
5298
5299 // Replace Select (which is used by the PHI for the default value) with
5300 // SelectFalseVal or SelectTrueVal depending on if ICI is EQ or NE.
5301 if (Select) {
5302 Select->replaceAllUsesWith(V: DefaultCst);
5303 Select->eraseFromParent();
5304 } else {
5305 ICI->replaceAllUsesWith(V: DefaultCst);
5306 }
5307 ICI->eraseFromParent();
5308
5309 SmallVector<DominatorTree::UpdateType, 2> Updates;
5310
5311 // Okay, the switch goes to this block on a default value. Add an edge from
5312 // the switch to the merge point on the compared value.
5313 BasicBlock *NewBB =
5314 BasicBlock::Create(Context&: BB->getContext(), Name: "switch.edge", Parent: BB->getParent(), InsertBefore: BB);
5315 {
5316 SwitchInstProfUpdateWrapper SIW(*SI);
5317 auto W0 = SIW.getSuccessorWeight(idx: 0);
5318 SwitchInstProfUpdateWrapper::CaseWeightOpt NewW;
5319 if (W0) {
5320 NewW = ((uint64_t(*W0) + 1) >> 1);
5321 SIW.setSuccessorWeight(idx: 0, W: *NewW);
5322 }
5323 SIW.addCase(OnVal: NewCaseVal, Dest: NewBB, W: NewW);
5324 if (DTU)
5325 Updates.push_back(Elt: {DominatorTree::Insert, Pred, NewBB});
5326 }
5327
5328 // NewBB branches to the phi block, add the uncond branch and the phi entry.
5329 Builder.SetInsertPoint(NewBB);
5330 Builder.SetCurrentDebugLocation(SI->getDebugLoc());
5331 Builder.CreateBr(Dest: SuccBlock);
5332 PHIUse->addIncoming(V: NewCst, BB: NewBB);
5333 if (DTU) {
5334 Updates.push_back(Elt: {DominatorTree::Insert, NewBB, SuccBlock});
5335 DTU->applyUpdates(Updates);
5336 }
5337 return true;
5338}
5339
5340/// Check to see if it is branching on an or/and chain of icmp instructions, and
5341/// fold it into a switch instruction if so.
5342bool SimplifyCFGOpt::simplifyBranchOnICmpChain(CondBrInst *BI,
5343 IRBuilder<> &Builder,
5344 const DataLayout &DL) {
5345 Instruction *Cond = dyn_cast<Instruction>(Val: BI->getCondition());
5346 if (!Cond)
5347 return false;
5348
5349 // Change br (X == 0 | X == 1), T, F into a switch instruction.
5350 // If this is a bunch of seteq's or'd together, or if it's a bunch of
5351 // 'setne's and'ed together, collect them.
5352
5353 // Try to gather values from a chain of and/or to be turned into a switch
5354 ConstantComparesGatherer ConstantCompare(Cond, DL);
5355 // Unpack the result
5356 SmallVectorImpl<ConstantInt *> &Values = ConstantCompare.Vals;
5357 Value *CompVal = ConstantCompare.CompValue;
5358 unsigned UsedICmps = ConstantCompare.UsedICmps;
5359 Value *ExtraCase = ConstantCompare.Extra;
5360 bool TrueWhenEqual = ConstantCompare.IsEq;
5361
5362 // If we didn't have a multiply compared value, fail.
5363 if (!CompVal)
5364 return false;
5365
5366 // Avoid turning single icmps into a switch.
5367 if (UsedICmps <= 1)
5368 return false;
5369
5370 // There might be duplicate constants in the list, which the switch
5371 // instruction can't handle, remove them now.
5372 array_pod_sort(Start: Values.begin(), End: Values.end(), Compare: constantIntSortPredicate);
5373 Values.erase(CS: llvm::unique(R&: Values), CE: Values.end());
5374
5375 // If Extra was used, we require at least two switch values to do the
5376 // transformation. A switch with one value is just a conditional branch.
5377 if (ExtraCase && Values.size() < 2)
5378 return false;
5379
5380 SmallVector<uint32_t> BranchWeights;
5381 const bool HasProfile = !ProfcheckDisableMetadataFixes &&
5382 extractBranchWeights(I: *BI, Weights&: BranchWeights);
5383
5384 // Figure out which block is which destination.
5385 BasicBlock *DefaultBB = BI->getSuccessor(i: 1);
5386 BasicBlock *EdgeBB = BI->getSuccessor(i: 0);
5387 if (!TrueWhenEqual) {
5388 std::swap(a&: DefaultBB, b&: EdgeBB);
5389 if (HasProfile)
5390 std::swap(a&: BranchWeights[0], b&: BranchWeights[1]);
5391 }
5392
5393 BasicBlock *BB = BI->getParent();
5394
5395 LLVM_DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
5396 << " cases into SWITCH. BB is:\n"
5397 << *BB);
5398
5399 SmallVector<DominatorTree::UpdateType, 2> Updates;
5400
5401 // If there are any extra values that couldn't be folded into the switch
5402 // then we evaluate them with an explicit branch first. Split the block
5403 // right before the condbr to handle it.
5404 if (ExtraCase) {
5405 BasicBlock *NewBB = SplitBlock(Old: BB, SplitPt: BI, DTU, /*LI=*/nullptr,
5406 /*MSSAU=*/nullptr, BBName: "switch.early.test");
5407
5408 // Remove the uncond branch added to the old block.
5409 Instruction *OldTI = BB->getTerminator();
5410 Builder.SetInsertPoint(OldTI);
5411
5412 // There can be an unintended UB if extra values are Poison. Before the
5413 // transformation, extra values may not be evaluated according to the
5414 // condition, and it will not raise UB. But after transformation, we are
5415 // evaluating extra values before checking the condition, and it will raise
5416 // UB. It can be solved by adding freeze instruction to extra values.
5417 AssumptionCache *AC = Options.AC;
5418
5419 if (!isGuaranteedNotToBeUndefOrPoison(V: ExtraCase, AC, CtxI: BI, DT: nullptr))
5420 ExtraCase = Builder.CreateFreeze(V: ExtraCase);
5421
5422 // We don't have any info about this condition.
5423 auto *Br = TrueWhenEqual ? Builder.CreateCondBr(Cond: ExtraCase, True: EdgeBB, False: NewBB)
5424 : Builder.CreateCondBr(Cond: ExtraCase, True: NewBB, False: EdgeBB);
5425 setExplicitlyUnknownBranchWeightsIfProfiled(I&: *Br, DEBUG_TYPE);
5426
5427 OldTI->eraseFromParent();
5428
5429 if (DTU)
5430 Updates.push_back(Elt: {DominatorTree::Insert, BB, EdgeBB});
5431
5432 // If there are PHI nodes in EdgeBB, then we need to add a new entry to them
5433 // for the edge we just added.
5434 addPredecessorToBlock(Succ: EdgeBB, NewPred: BB, ExistPred: NewBB);
5435
5436 LLVM_DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase
5437 << "\nEXTRABB = " << *BB);
5438 BB = NewBB;
5439 }
5440
5441 Builder.SetInsertPoint(BI);
5442 // Convert pointer to int before we switch.
5443 if (CompVal->getType()->isPointerTy()) {
5444 assert(!DL.hasUnstableRepresentation(CompVal->getType()) &&
5445 "Should not end up here with unstable pointers");
5446 CompVal = Builder.CreatePtrToInt(
5447 V: CompVal, DestTy: DL.getIntPtrType(CompVal->getType()), Name: "magicptr");
5448 }
5449
5450 // Check if we can represent the values as a contiguous range. If so, we use a
5451 // range check + conditional branch instead of a switch.
5452 if (Values.front()->getValue() - Values.back()->getValue() ==
5453 Values.size() - 1) {
5454 ConstantRange RangeToCheck = ConstantRange::getNonEmpty(
5455 Lower: Values.back()->getValue(), Upper: Values.front()->getValue() + 1);
5456 APInt Offset, RHS;
5457 ICmpInst::Predicate Pred;
5458 RangeToCheck.getEquivalentICmp(Pred, RHS, Offset);
5459 Value *X = CompVal;
5460 if (!Offset.isZero())
5461 X = Builder.CreateAdd(LHS: X, RHS: ConstantInt::get(Ty: CompVal->getType(), V: Offset));
5462 Value *Cond =
5463 Builder.CreateICmp(P: Pred, LHS: X, RHS: ConstantInt::get(Ty: CompVal->getType(), V: RHS));
5464 CondBrInst *NewBI = Builder.CreateCondBr(Cond, True: EdgeBB, False: DefaultBB);
5465 if (HasProfile)
5466 setBranchWeights(I&: *NewBI, Weights: BranchWeights, /*IsExpected=*/false);
5467 // We don't need to update PHI nodes since we don't add any new edges.
5468 } else {
5469 // Create the new switch instruction now.
5470 SwitchInst *New = Builder.CreateSwitch(V: CompVal, Dest: DefaultBB, NumCases: Values.size());
5471 if (HasProfile) {
5472 // We know the weight of the default case. We don't know the weight of the
5473 // other cases, but rather than completely lose profiling info, we split
5474 // the remaining probability equally over them.
5475 SmallVector<uint32_t> NewWeights(Values.size() + 1);
5476 NewWeights[0] = BranchWeights[1]; // this is the default, and we swapped
5477 // if TrueWhenEqual.
5478 for (auto &V : drop_begin(RangeOrContainer&: NewWeights))
5479 V = BranchWeights[0] / Values.size();
5480 setBranchWeights(I&: *New, Weights: NewWeights, /*IsExpected=*/false);
5481 }
5482
5483 // Add all of the 'cases' to the switch instruction.
5484 for (ConstantInt *Val : Values)
5485 New->addCase(OnVal: Val, Dest: EdgeBB);
5486
5487 // We added edges from PI to the EdgeBB. As such, if there were any
5488 // PHI nodes in EdgeBB, they need entries to be added corresponding to
5489 // the number of edges added.
5490 for (BasicBlock::iterator BBI = EdgeBB->begin(); isa<PHINode>(Val: BBI); ++BBI) {
5491 PHINode *PN = cast<PHINode>(Val&: BBI);
5492 Value *InVal = PN->getIncomingValueForBlock(BB);
5493 for (unsigned i = 0, e = Values.size() - 1; i != e; ++i)
5494 PN->addIncoming(V: InVal, BB);
5495 }
5496 }
5497
5498 // Erase the old branch instruction.
5499 eraseTerminatorAndDCECond(TI: BI);
5500 if (DTU)
5501 DTU->applyUpdates(Updates);
5502
5503 LLVM_DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n');
5504 return true;
5505}
5506
5507bool SimplifyCFGOpt::simplifyResume(ResumeInst *RI, IRBuilder<> &Builder) {
5508 if (isa<PHINode>(Val: RI->getValue()))
5509 return simplifyCommonResume(RI);
5510 else if (isa<LandingPadInst>(Val: RI->getParent()->getFirstNonPHIIt()) &&
5511 RI->getValue() == &*RI->getParent()->getFirstNonPHIIt())
5512 // The resume must unwind the exception that caused control to branch here.
5513 return simplifySingleResume(RI);
5514
5515 return false;
5516}
5517
5518// Check if cleanup block is empty
5519static bool isCleanupBlockEmpty(iterator_range<BasicBlock::iterator> R) {
5520 for (Instruction &I : R) {
5521 auto *II = dyn_cast<IntrinsicInst>(Val: &I);
5522 if (!II)
5523 return false;
5524
5525 Intrinsic::ID IntrinsicID = II->getIntrinsicID();
5526 switch (IntrinsicID) {
5527 case Intrinsic::dbg_declare:
5528 case Intrinsic::dbg_value:
5529 case Intrinsic::dbg_label:
5530 case Intrinsic::lifetime_end:
5531 break;
5532 default:
5533 return false;
5534 }
5535 }
5536 return true;
5537}
5538
5539// Simplify resume that is shared by several landing pads (phi of landing pad).
5540bool SimplifyCFGOpt::simplifyCommonResume(ResumeInst *RI) {
5541 BasicBlock *BB = RI->getParent();
5542
5543 // Check that there are no other instructions except for debug and lifetime
5544 // intrinsics between the phi's and resume instruction.
5545 if (!isCleanupBlockEmpty(R: make_range(x: RI->getParent()->getFirstNonPHIIt(),
5546 y: BB->getTerminator()->getIterator())))
5547 return false;
5548
5549 SmallSetVector<BasicBlock *, 4> TrivialUnwindBlocks;
5550 auto *PhiLPInst = cast<PHINode>(Val: RI->getValue());
5551
5552 // Check incoming blocks to see if any of them are trivial.
5553 for (unsigned Idx = 0, End = PhiLPInst->getNumIncomingValues(); Idx != End;
5554 Idx++) {
5555 auto *IncomingBB = PhiLPInst->getIncomingBlock(i: Idx);
5556 auto *IncomingValue = PhiLPInst->getIncomingValue(i: Idx);
5557
5558 // If the block has other successors, we can not delete it because
5559 // it has other dependents.
5560 if (IncomingBB->getUniqueSuccessor() != BB)
5561 continue;
5562
5563 auto *LandingPad = dyn_cast<LandingPadInst>(Val: IncomingBB->getFirstNonPHIIt());
5564 // Not the landing pad that caused the control to branch here.
5565 if (IncomingValue != LandingPad)
5566 continue;
5567
5568 if (isCleanupBlockEmpty(
5569 R: make_range(x: LandingPad->getNextNode(), y: IncomingBB->getTerminator())))
5570 TrivialUnwindBlocks.insert(X: IncomingBB);
5571 }
5572
5573 // If no trivial unwind blocks, don't do any simplifications.
5574 if (TrivialUnwindBlocks.empty())
5575 return false;
5576
5577 // Turn all invokes that unwind here into calls.
5578 for (auto *TrivialBB : TrivialUnwindBlocks) {
5579 // Blocks that will be simplified should be removed from the phi node.
5580 // Note there could be multiple edges to the resume block, and we need
5581 // to remove them all.
5582 while (PhiLPInst->getBasicBlockIndex(BB: TrivialBB) != -1)
5583 BB->removePredecessor(Pred: TrivialBB, KeepOneInputPHIs: true);
5584
5585 for (BasicBlock *Pred :
5586 llvm::make_early_inc_range(Range: predecessors(BB: TrivialBB))) {
5587 removeUnwindEdge(BB: Pred, DTU);
5588 ++NumInvokes;
5589 }
5590
5591 // In each SimplifyCFG run, only the current processed block can be erased.
5592 // Otherwise, it will break the iteration of SimplifyCFG pass. So instead
5593 // of erasing TrivialBB, we only remove the branch to the common resume
5594 // block so that we can later erase the resume block since it has no
5595 // predecessors.
5596 TrivialBB->getTerminator()->eraseFromParent();
5597 new UnreachableInst(RI->getContext(), TrivialBB);
5598 if (DTU)
5599 DTU->applyUpdates(Updates: {{DominatorTree::Delete, TrivialBB, BB}});
5600 }
5601
5602 // Delete the resume block if all its predecessors have been removed.
5603 if (pred_empty(BB))
5604 DeleteDeadBlock(BB, DTU);
5605
5606 return !TrivialUnwindBlocks.empty();
5607}
5608
5609// Simplify resume that is only used by a single (non-phi) landing pad.
5610bool SimplifyCFGOpt::simplifySingleResume(ResumeInst *RI) {
5611 BasicBlock *BB = RI->getParent();
5612 auto *LPInst = cast<LandingPadInst>(Val: BB->getFirstNonPHIIt());
5613 assert(RI->getValue() == LPInst &&
5614 "Resume must unwind the exception that caused control to here");
5615
5616 // Check that there are no other instructions except for debug intrinsics.
5617 if (!isCleanupBlockEmpty(
5618 R: make_range<Instruction *>(x: LPInst->getNextNode(), y: RI)))
5619 return false;
5620
5621 // Turn all invokes that unwind here into calls and delete the basic block.
5622 for (BasicBlock *Pred : llvm::make_early_inc_range(Range: predecessors(BB))) {
5623 removeUnwindEdge(BB: Pred, DTU);
5624 ++NumInvokes;
5625 }
5626
5627 // The landingpad is now unreachable. Zap it.
5628 DeleteDeadBlock(BB, DTU);
5629 return true;
5630}
5631
5632static bool removeEmptyCleanup(CleanupReturnInst *RI, DomTreeUpdater *DTU) {
5633 // If this is a trivial cleanup pad that executes no instructions, it can be
5634 // eliminated. If the cleanup pad continues to the caller, any predecessor
5635 // that is an EH pad will be updated to continue to the caller and any
5636 // predecessor that terminates with an invoke instruction will have its invoke
5637 // instruction converted to a call instruction. If the cleanup pad being
5638 // simplified does not continue to the caller, each predecessor will be
5639 // updated to continue to the unwind destination of the cleanup pad being
5640 // simplified.
5641 BasicBlock *BB = RI->getParent();
5642 CleanupPadInst *CPInst = RI->getCleanupPad();
5643 if (CPInst->getParent() != BB)
5644 // This isn't an empty cleanup.
5645 return false;
5646
5647 // We cannot kill the pad if it has multiple uses. This typically arises
5648 // from unreachable basic blocks.
5649 if (!CPInst->hasOneUse())
5650 return false;
5651
5652 // Check that there are no other instructions except for benign intrinsics.
5653 if (!isCleanupBlockEmpty(
5654 R: make_range<Instruction *>(x: CPInst->getNextNode(), y: RI)))
5655 return false;
5656
5657 // If the cleanup return we are simplifying unwinds to the caller, this will
5658 // set UnwindDest to nullptr.
5659 BasicBlock *UnwindDest = RI->getUnwindDest();
5660
5661 // We're about to remove BB from the control flow. Before we do, sink any
5662 // PHINodes into the unwind destination. Doing this before changing the
5663 // control flow avoids some potentially slow checks, since we can currently
5664 // be certain that UnwindDest and BB have no common predecessors (since they
5665 // are both EH pads).
5666 if (UnwindDest) {
5667 // First, go through the PHI nodes in UnwindDest and update any nodes that
5668 // reference the block we are removing
5669 for (PHINode &DestPN : UnwindDest->phis()) {
5670 int Idx = DestPN.getBasicBlockIndex(BB);
5671 // Since BB unwinds to UnwindDest, it has to be in the PHI node.
5672 assert(Idx != -1);
5673 // This PHI node has an incoming value that corresponds to a control
5674 // path through the cleanup pad we are removing. If the incoming
5675 // value is in the cleanup pad, it must be a PHINode (because we
5676 // verified above that the block is otherwise empty). Otherwise, the
5677 // value is either a constant or a value that dominates the cleanup
5678 // pad being removed.
5679 //
5680 // Because BB and UnwindDest are both EH pads, all of their
5681 // predecessors must unwind to these blocks, and since no instruction
5682 // can have multiple unwind destinations, there will be no overlap in
5683 // incoming blocks between SrcPN and DestPN.
5684 Value *SrcVal = DestPN.getIncomingValue(i: Idx);
5685 PHINode *SrcPN = dyn_cast<PHINode>(Val: SrcVal);
5686
5687 bool NeedPHITranslation = SrcPN && SrcPN->getParent() == BB;
5688 for (auto *Pred : predecessors(BB)) {
5689 Value *Incoming =
5690 NeedPHITranslation ? SrcPN->getIncomingValueForBlock(BB: Pred) : SrcVal;
5691 DestPN.addIncoming(V: Incoming, BB: Pred);
5692 }
5693 }
5694
5695 // Sink any remaining PHI nodes directly into UnwindDest.
5696 BasicBlock::iterator InsertPt = UnwindDest->getFirstNonPHIIt();
5697 for (PHINode &PN : make_early_inc_range(Range: BB->phis())) {
5698 if (PN.use_empty() || !PN.isUsedOutsideOfBlock(BB))
5699 // If the PHI node has no uses or all of its uses are in this basic
5700 // block (meaning they are debug or lifetime intrinsics), just leave
5701 // it. It will be erased when we erase BB below.
5702 continue;
5703
5704 // Otherwise, sink this PHI node into UnwindDest.
5705 // Any predecessors to UnwindDest which are not already represented
5706 // must be back edges which inherit the value from the path through
5707 // BB. In this case, the PHI value must reference itself.
5708 for (auto *pred : predecessors(BB: UnwindDest))
5709 if (pred != BB)
5710 PN.addIncoming(V: &PN, BB: pred);
5711 PN.moveBefore(InsertPos: InsertPt);
5712 // Also, add a dummy incoming value for the original BB itself,
5713 // so that the PHI is well-formed until we drop said predecessor.
5714 PN.addIncoming(V: PoisonValue::get(T: PN.getType()), BB);
5715 }
5716 }
5717
5718 std::vector<DominatorTree::UpdateType> Updates;
5719
5720 // We use make_early_inc_range here because we will remove all predecessors.
5721 for (BasicBlock *PredBB : llvm::make_early_inc_range(Range: predecessors(BB))) {
5722 if (UnwindDest == nullptr) {
5723 if (DTU) {
5724 DTU->applyUpdates(Updates);
5725 Updates.clear();
5726 }
5727 removeUnwindEdge(BB: PredBB, DTU);
5728 ++NumInvokes;
5729 } else {
5730 BB->removePredecessor(Pred: PredBB);
5731 Instruction *TI = PredBB->getTerminator();
5732 TI->replaceUsesOfWith(From: BB, To: UnwindDest);
5733 if (DTU) {
5734 Updates.push_back(x: {DominatorTree::Insert, PredBB, UnwindDest});
5735 Updates.push_back(x: {DominatorTree::Delete, PredBB, BB});
5736 }
5737 }
5738 }
5739
5740 if (DTU)
5741 DTU->applyUpdates(Updates);
5742
5743 DeleteDeadBlock(BB, DTU);
5744
5745 return true;
5746}
5747
5748// Try to merge two cleanuppads together.
5749static bool mergeCleanupPad(CleanupReturnInst *RI) {
5750 // Skip any cleanuprets which unwind to caller, there is nothing to merge
5751 // with.
5752 BasicBlock *UnwindDest = RI->getUnwindDest();
5753 if (!UnwindDest)
5754 return false;
5755
5756 // This cleanupret isn't the only predecessor of this cleanuppad, it wouldn't
5757 // be safe to merge without code duplication.
5758 if (UnwindDest->getSinglePredecessor() != RI->getParent())
5759 return false;
5760
5761 // Verify that our cleanuppad's unwind destination is another cleanuppad.
5762 auto *SuccessorCleanupPad = dyn_cast<CleanupPadInst>(Val: &UnwindDest->front());
5763 if (!SuccessorCleanupPad)
5764 return false;
5765
5766 CleanupPadInst *PredecessorCleanupPad = RI->getCleanupPad();
5767 // Replace any uses of the successor cleanupad with the predecessor pad
5768 // The only cleanuppad uses should be this cleanupret, it's cleanupret and
5769 // funclet bundle operands.
5770 SuccessorCleanupPad->replaceAllUsesWith(V: PredecessorCleanupPad);
5771 // Remove the old cleanuppad.
5772 SuccessorCleanupPad->eraseFromParent();
5773 // Now, we simply replace the cleanupret with a branch to the unwind
5774 // destination.
5775 UncondBrInst::Create(Target: UnwindDest, InsertBefore: RI->getParent());
5776 RI->eraseFromParent();
5777
5778 return true;
5779}
5780
5781bool SimplifyCFGOpt::simplifyCleanupReturn(CleanupReturnInst *RI) {
5782 // It is possible to transiantly have an undef cleanuppad operand because we
5783 // have deleted some, but not all, dead blocks.
5784 // Eventually, this block will be deleted.
5785 if (isa<UndefValue>(Val: RI->getOperand(i_nocapture: 0)))
5786 return false;
5787
5788 if (mergeCleanupPad(RI))
5789 return true;
5790
5791 if (removeEmptyCleanup(RI, DTU))
5792 return true;
5793
5794 return false;
5795}
5796
5797// WARNING: keep in sync with InstCombinerImpl::visitUnreachableInst()!
5798bool SimplifyCFGOpt::simplifyUnreachable(UnreachableInst *UI) {
5799 BasicBlock *BB = UI->getParent();
5800
5801 bool Changed = false;
5802
5803 // Ensure that any debug-info records that used to occur after the Unreachable
5804 // are moved to in front of it -- otherwise they'll "dangle" at the end of
5805 // the block.
5806 BB->flushTerminatorDbgRecords();
5807
5808 // Debug-info records on the unreachable inst itself should be deleted, as
5809 // below we delete everything past the final executable instruction.
5810 UI->dropDbgRecords();
5811
5812 // If there are any instructions immediately before the unreachable that can
5813 // be removed, do so.
5814 while (UI->getIterator() != BB->begin()) {
5815 BasicBlock::iterator BBI = UI->getIterator();
5816 --BBI;
5817
5818 if (!isGuaranteedToTransferExecutionToSuccessor(I: &*BBI))
5819 break; // Can not drop any more instructions. We're done here.
5820 // Otherwise, this instruction can be freely erased,
5821 // even if it is not side-effect free.
5822
5823 // Note that deleting EH's here is in fact okay, although it involves a bit
5824 // of subtle reasoning. If this inst is an EH, all the predecessors of this
5825 // block will be the unwind edges of Invoke/CatchSwitch/CleanupReturn,
5826 // and we can therefore guarantee this block will be erased.
5827
5828 // If we're deleting this, we're deleting any subsequent debug info, so
5829 // delete DbgRecords.
5830 BBI->dropDbgRecords();
5831
5832 // Delete this instruction (any uses are guaranteed to be dead)
5833 BBI->replaceAllUsesWith(V: PoisonValue::get(T: BBI->getType()));
5834 BBI->eraseFromParent();
5835 Changed = true;
5836 }
5837
5838 // If the unreachable instruction is the first in the block, take a gander
5839 // at all of the predecessors of this instruction, and simplify them.
5840 if (&BB->front() != UI)
5841 return Changed;
5842
5843 std::vector<DominatorTree::UpdateType> Updates;
5844
5845 SmallSetVector<BasicBlock *, 8> Preds(pred_begin(BB), pred_end(BB));
5846 for (BasicBlock *Predecessor : Preds) {
5847 Instruction *TI = Predecessor->getTerminator();
5848 IRBuilder<> Builder(TI);
5849 if (isa<UncondBrInst>(Val: TI)) {
5850 new UnreachableInst(TI->getContext(), TI->getIterator());
5851 TI->eraseFromParent();
5852 Changed = true;
5853 if (DTU)
5854 Updates.push_back(x: {DominatorTree::Delete, Predecessor, BB});
5855 } else if (auto *BI = dyn_cast<CondBrInst>(Val: TI)) {
5856 // We could either have a proper unconditional branch,
5857 // or a degenerate conditional branch with matching destinations.
5858 if (BI->getSuccessor(i: 0) == BI->getSuccessor(i: 1)) {
5859 new UnreachableInst(TI->getContext(), TI->getIterator());
5860 TI->eraseFromParent();
5861 Changed = true;
5862 } else {
5863 Value* Cond = BI->getCondition();
5864 assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
5865 "The destinations are guaranteed to be different here.");
5866 CallInst *Assumption;
5867 if (BI->getSuccessor(i: 0) == BB) {
5868 Assumption = Builder.CreateAssumption(Cond: Builder.CreateNot(V: Cond));
5869 Builder.CreateBr(Dest: BI->getSuccessor(i: 1));
5870 } else {
5871 assert(BI->getSuccessor(1) == BB && "Incorrect CFG");
5872 Assumption = Builder.CreateAssumption(Cond);
5873 Builder.CreateBr(Dest: BI->getSuccessor(i: 0));
5874 }
5875 if (Options.AC)
5876 Options.AC->registerAssumption(CI: cast<AssumeInst>(Val: Assumption));
5877
5878 eraseTerminatorAndDCECond(TI: BI);
5879 Changed = true;
5880 }
5881 if (DTU)
5882 Updates.push_back(x: {DominatorTree::Delete, Predecessor, BB});
5883 } else if (auto *SI = dyn_cast<SwitchInst>(Val: TI)) {
5884 SwitchInstProfUpdateWrapper SU(*SI);
5885 for (auto i = SU->case_begin(), e = SU->case_end(); i != e;) {
5886 if (i->getCaseSuccessor() != BB) {
5887 ++i;
5888 continue;
5889 }
5890 BB->removePredecessor(Pred: SU->getParent());
5891 i = SU.removeCase(I: i);
5892 e = SU->case_end();
5893 Changed = true;
5894 }
5895 // Note that the default destination can't be removed!
5896 if (DTU && SI->getDefaultDest() != BB)
5897 Updates.push_back(x: {DominatorTree::Delete, Predecessor, BB});
5898 } else if (auto *II = dyn_cast<InvokeInst>(Val: TI)) {
5899 if (II->getUnwindDest() == BB) {
5900 if (DTU) {
5901 DTU->applyUpdates(Updates);
5902 Updates.clear();
5903 }
5904 auto *CI = cast<CallInst>(Val: removeUnwindEdge(BB: TI->getParent(), DTU));
5905 if (!CI->doesNotThrow())
5906 CI->setDoesNotThrow();
5907 Changed = true;
5908 }
5909 } else if (auto *CSI = dyn_cast<CatchSwitchInst>(Val: TI)) {
5910 if (CSI->getUnwindDest() == BB) {
5911 if (DTU) {
5912 DTU->applyUpdates(Updates);
5913 Updates.clear();
5914 }
5915 removeUnwindEdge(BB: TI->getParent(), DTU);
5916 Changed = true;
5917 continue;
5918 }
5919
5920 for (CatchSwitchInst::handler_iterator I = CSI->handler_begin(),
5921 E = CSI->handler_end();
5922 I != E; ++I) {
5923 if (*I == BB) {
5924 CSI->removeHandler(HI: I);
5925 --I;
5926 --E;
5927 Changed = true;
5928 }
5929 }
5930 if (DTU)
5931 Updates.push_back(x: {DominatorTree::Delete, Predecessor, BB});
5932 if (CSI->getNumHandlers() == 0) {
5933 if (CSI->hasUnwindDest()) {
5934 // Redirect all predecessors of the block containing CatchSwitchInst
5935 // to instead branch to the CatchSwitchInst's unwind destination.
5936 if (DTU) {
5937 for (auto *PredecessorOfPredecessor : predecessors(BB: Predecessor)) {
5938 Updates.push_back(x: {DominatorTree::Insert,
5939 PredecessorOfPredecessor,
5940 CSI->getUnwindDest()});
5941 Updates.push_back(x: {DominatorTree::Delete,
5942 PredecessorOfPredecessor, Predecessor});
5943 }
5944 }
5945 Predecessor->replaceAllUsesWith(V: CSI->getUnwindDest());
5946 } else {
5947 // Rewrite all preds to unwind to caller (or from invoke to call).
5948 if (DTU) {
5949 DTU->applyUpdates(Updates);
5950 Updates.clear();
5951 }
5952 SmallVector<BasicBlock *, 8> EHPreds(predecessors(BB: Predecessor));
5953 for (BasicBlock *EHPred : EHPreds)
5954 removeUnwindEdge(BB: EHPred, DTU);
5955 }
5956 // The catchswitch is no longer reachable.
5957 new UnreachableInst(CSI->getContext(), CSI->getIterator());
5958 CSI->eraseFromParent();
5959 Changed = true;
5960 }
5961 } else if (auto *CRI = dyn_cast<CleanupReturnInst>(Val: TI)) {
5962 (void)CRI;
5963 assert(CRI->hasUnwindDest() && CRI->getUnwindDest() == BB &&
5964 "Expected to always have an unwind to BB.");
5965 if (DTU)
5966 Updates.push_back(x: {DominatorTree::Delete, Predecessor, BB});
5967 new UnreachableInst(TI->getContext(), TI->getIterator());
5968 TI->eraseFromParent();
5969 Changed = true;
5970 }
5971 }
5972
5973 if (DTU)
5974 DTU->applyUpdates(Updates);
5975
5976 // If this block is now dead, remove it.
5977 if (pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()) {
5978 DeleteDeadBlock(BB, DTU);
5979 return true;
5980 }
5981
5982 return Changed;
5983}
5984
5985struct ContiguousCasesResult {
5986 ConstantInt *Min;
5987 ConstantInt *Max;
5988 BasicBlock *Dest;
5989 BasicBlock *OtherDest;
5990 SmallVectorImpl<ConstantInt *> *Cases;
5991 SmallVectorImpl<ConstantInt *> *OtherCases;
5992};
5993
5994static std::optional<ContiguousCasesResult>
5995findContiguousCases(Value *Condition, SmallVectorImpl<ConstantInt *> &Cases,
5996 SmallVectorImpl<ConstantInt *> &OtherCases,
5997 BasicBlock *Dest, BasicBlock *OtherDest) {
5998 assert(Cases.size() >= 1);
5999
6000 array_pod_sort(Start: Cases.begin(), End: Cases.end(), Compare: constantIntSortPredicate);
6001 const APInt &Min = Cases.back()->getValue();
6002 const APInt &Max = Cases.front()->getValue();
6003 APInt Offset = Max - Min;
6004 size_t ContiguousOffset = Cases.size() - 1;
6005 if (Offset == ContiguousOffset) {
6006 return ContiguousCasesResult{
6007 /*Min=*/Cases.back(),
6008 /*Max=*/Cases.front(),
6009 /*Dest=*/Dest,
6010 /*OtherDest=*/OtherDest,
6011 /*Cases=*/&Cases,
6012 /*OtherCases=*/&OtherCases,
6013 };
6014 }
6015 ConstantRange CR = computeConstantRange(V: Condition, /*ForSigned=*/false,
6016 SQ: SimplifyQuery(Dest->getDataLayout()));
6017 // If this is a wrapping contiguous range, that is, [Min, OtherMin] +
6018 // [OtherMax, Max] (also [OtherMax, OtherMin]), [OtherMin+1, OtherMax-1] is a
6019 // contiguous range for the other destination. N.B. If CR is not a full range,
6020 // Max+1 is not equal to Min. It's not continuous in arithmetic.
6021 if (Max == CR.getUnsignedMax() && Min == CR.getUnsignedMin()) {
6022 assert(Cases.size() >= 2);
6023 auto *It =
6024 std::adjacent_find(first: Cases.begin(), last: Cases.end(), binary_pred: [](auto L, auto R) {
6025 return L->getValue() != R->getValue() + 1;
6026 });
6027 if (It == Cases.end())
6028 return std::nullopt;
6029 auto [OtherMax, OtherMin] = std::make_pair(x&: *It, y&: *std::next(x: It));
6030 if ((Max - OtherMax->getValue()) + (OtherMin->getValue() - Min) ==
6031 Cases.size() - 2) {
6032 return ContiguousCasesResult{
6033 /*Min=*/cast<ConstantInt>(
6034 Val: ConstantInt::get(Ty: OtherMin->getType(), V: OtherMin->getValue() + 1)),
6035 /*Max=*/
6036 cast<ConstantInt>(
6037 Val: ConstantInt::get(Ty: OtherMax->getType(), V: OtherMax->getValue() - 1)),
6038 /*Dest=*/OtherDest,
6039 /*OtherDest=*/Dest,
6040 /*Cases=*/&OtherCases,
6041 /*OtherCases=*/&Cases,
6042 };
6043 }
6044 }
6045 return std::nullopt;
6046}
6047
6048static void createUnreachableSwitchDefault(SwitchInst *Switch,
6049 DomTreeUpdater *DTU,
6050 bool RemoveOrigDefaultBlock = true) {
6051 LLVM_DEBUG(dbgs() << "SimplifyCFG: switch default is dead.\n");
6052 auto *BB = Switch->getParent();
6053 auto *OrigDefaultBlock = Switch->getDefaultDest();
6054 if (RemoveOrigDefaultBlock)
6055 OrigDefaultBlock->removePredecessor(Pred: BB);
6056 BasicBlock *NewDefaultBlock = BasicBlock::Create(
6057 Context&: BB->getContext(), Name: BB->getName() + ".unreachabledefault", Parent: BB->getParent(),
6058 InsertBefore: OrigDefaultBlock);
6059 auto *UI = new UnreachableInst(Switch->getContext(), NewDefaultBlock);
6060 UI->setDebugLoc(DebugLoc::getTemporary());
6061 Switch->setDefaultDest(&*NewDefaultBlock);
6062 if (DTU) {
6063 SmallVector<DominatorTree::UpdateType, 2> Updates;
6064 Updates.push_back(Elt: {DominatorTree::Insert, BB, &*NewDefaultBlock});
6065 if (RemoveOrigDefaultBlock &&
6066 !is_contained(Range: successors(BB), Element: OrigDefaultBlock))
6067 Updates.push_back(Elt: {DominatorTree::Delete, BB, &*OrigDefaultBlock});
6068 DTU->applyUpdates(Updates);
6069 }
6070}
6071
6072/// Turn a switch into an integer range comparison and branch.
6073/// Switches with more than 2 destinations are ignored.
6074/// Switches with 1 destination are also ignored.
6075bool SimplifyCFGOpt::turnSwitchRangeIntoICmp(SwitchInst *SI,
6076 IRBuilder<> &Builder) {
6077 assert(SI->getNumCases() > 1 && "Degenerate switch?");
6078
6079 bool HasDefault = !SI->defaultDestUnreachable();
6080
6081 auto *BB = SI->getParent();
6082 // Partition the cases into two sets with different destinations.
6083 BasicBlock *DestA = HasDefault ? SI->getDefaultDest() : nullptr;
6084 BasicBlock *DestB = nullptr;
6085 SmallVector<ConstantInt *, 16> CasesA;
6086 SmallVector<ConstantInt *, 16> CasesB;
6087
6088 for (auto Case : SI->cases()) {
6089 BasicBlock *Dest = Case.getCaseSuccessor();
6090 if (!DestA)
6091 DestA = Dest;
6092 if (Dest == DestA) {
6093 CasesA.push_back(Elt: Case.getCaseValue());
6094 continue;
6095 }
6096 if (!DestB)
6097 DestB = Dest;
6098 if (Dest == DestB) {
6099 CasesB.push_back(Elt: Case.getCaseValue());
6100 continue;
6101 }
6102 return false; // More than two destinations.
6103 }
6104 if (!DestB)
6105 return false; // All destinations are the same and the default is unreachable
6106
6107 assert(DestA && DestB &&
6108 "Single-destination switch should have been folded.");
6109 assert(DestA != DestB);
6110 assert(DestB != SI->getDefaultDest());
6111 assert(!CasesB.empty() && "There must be non-default cases.");
6112 assert(!CasesA.empty() || HasDefault);
6113
6114 // Figure out if one of the sets of cases form a contiguous range.
6115 std::optional<ContiguousCasesResult> ContiguousCases;
6116
6117 // Only one icmp is needed when there is only one case.
6118 if (!HasDefault && CasesA.size() == 1)
6119 ContiguousCases = ContiguousCasesResult{
6120 /*Min=*/CasesA[0],
6121 /*Max=*/CasesA[0],
6122 /*Dest=*/DestA,
6123 /*OtherDest=*/DestB,
6124 /*Cases=*/&CasesA,
6125 /*OtherCases=*/&CasesB,
6126 };
6127 else if (CasesB.size() == 1)
6128 ContiguousCases = ContiguousCasesResult{
6129 /*Min=*/CasesB[0],
6130 /*Max=*/CasesB[0],
6131 /*Dest=*/DestB,
6132 /*OtherDest=*/DestA,
6133 /*Cases=*/&CasesB,
6134 /*OtherCases=*/&CasesA,
6135 };
6136 // Correctness: Cases to the default destination cannot be contiguous cases.
6137 else if (!HasDefault)
6138 ContiguousCases =
6139 findContiguousCases(Condition: SI->getCondition(), Cases&: CasesA, OtherCases&: CasesB, Dest: DestA, OtherDest: DestB);
6140
6141 if (!ContiguousCases)
6142 ContiguousCases =
6143 findContiguousCases(Condition: SI->getCondition(), Cases&: CasesB, OtherCases&: CasesA, Dest: DestB, OtherDest: DestA);
6144
6145 if (!ContiguousCases)
6146 return false;
6147
6148 auto [Min, Max, Dest, OtherDest, Cases, OtherCases] = *ContiguousCases;
6149
6150 // Start building the compare and branch.
6151
6152 Constant *Offset = ConstantExpr::getNeg(C: Min);
6153 Constant *NumCases = ConstantInt::get(Ty: Offset->getType(),
6154 V: Max->getValue() - Min->getValue() + 1);
6155 Instruction *NewBI;
6156 if (NumCases->isOneValue()) {
6157 assert(Max->getValue() == Min->getValue());
6158 Value *Cmp = Builder.CreateICmpEQ(LHS: SI->getCondition(), RHS: Min);
6159 NewBI = Builder.CreateCondBr(Cond: Cmp, True: Dest, False: OtherDest);
6160 }
6161 // If NumCases overflowed, then all possible values jump to the successor.
6162 else if (NumCases->isNullValue() && !Cases->empty()) {
6163 NewBI = Builder.CreateBr(Dest);
6164 } else {
6165 Value *Sub = SI->getCondition();
6166 if (!Offset->isNullValue())
6167 Sub = Builder.CreateAdd(LHS: Sub, RHS: Offset, Name: Sub->getName() + ".off");
6168 Value *Cmp = Builder.CreateICmpULT(LHS: Sub, RHS: NumCases, Name: "switch");
6169 NewBI = Builder.CreateCondBr(Cond: Cmp, True: Dest, False: OtherDest);
6170 }
6171
6172 // Update weight for the newly-created conditional branch.
6173 if (hasBranchWeightMD(I: *SI) && isa<CondBrInst>(Val: NewBI)) {
6174 SmallVector<uint64_t, 8> Weights;
6175 getBranchWeights(TI: SI, Weights);
6176 if (Weights.size() == 1 + SI->getNumCases()) {
6177 uint64_t TrueWeight = 0;
6178 uint64_t FalseWeight = 0;
6179 for (size_t I = 0, E = Weights.size(); I != E; ++I) {
6180 if (SI->getSuccessor(idx: I) == Dest)
6181 TrueWeight += Weights[I];
6182 else
6183 FalseWeight += Weights[I];
6184 }
6185 while (TrueWeight > UINT32_MAX || FalseWeight > UINT32_MAX) {
6186 TrueWeight /= 2;
6187 FalseWeight /= 2;
6188 }
6189 setFittedBranchWeights(I&: *NewBI, Weights: {TrueWeight, FalseWeight},
6190 /*IsExpected=*/false, /*ElideAllZero=*/true);
6191 }
6192 }
6193
6194 // Prune obsolete incoming values off the successors' PHI nodes.
6195 for (auto &PHI : make_early_inc_range(Range: Dest->phis())) {
6196 unsigned PreviousEdges = Cases->size();
6197 if (Dest == SI->getDefaultDest())
6198 ++PreviousEdges;
6199 for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
6200 PHI.removeIncomingValue(BB: SI->getParent());
6201 }
6202 for (auto &PHI : make_early_inc_range(Range: OtherDest->phis())) {
6203 unsigned PreviousEdges = OtherCases->size();
6204 if (OtherDest == SI->getDefaultDest())
6205 ++PreviousEdges;
6206 unsigned E = PreviousEdges - 1;
6207 // Remove all incoming values from OtherDest if OtherDest is unreachable.
6208 if (isa<UncondBrInst>(Val: NewBI))
6209 ++E;
6210 for (unsigned I = 0; I != E; ++I)
6211 PHI.removeIncomingValue(BB: SI->getParent());
6212 }
6213
6214 // Clean up the default block.
6215 SmallVector<DominatorTree::UpdateType, 2> Updates;
6216 if (!HasDefault) {
6217 BasicBlock *OrigDefaultBlock = SI->getDefaultDest();
6218 OrigDefaultBlock->removePredecessor(Pred: BB);
6219 Updates.push_back(Elt: {DominatorTree::Delete, BB, OrigDefaultBlock});
6220 }
6221
6222 // Drop the switch.
6223 SI->eraseFromParent();
6224
6225 if (isa<UncondBrInst>(Val: NewBI))
6226 Updates.push_back(Elt: {DominatorTree::Delete, BB, OtherDest});
6227
6228 if (DTU)
6229 DTU->applyUpdates(Updates);
6230 return true;
6231}
6232
6233/// Compute masked bits for the condition of a switch
6234/// and use it to remove dead cases.
6235static bool eliminateDeadSwitchCases(SwitchInst *SI, DomTreeUpdater *DTU,
6236 AssumptionCache *AC,
6237 const DataLayout &DL) {
6238 Value *Cond = SI->getCondition();
6239 KnownBits Known = computeKnownBits(V: Cond, DL, AC, CxtI: SI);
6240 SmallPtrSet<const Constant *, 4> KnownValues;
6241 bool IsKnownValuesValid = collectPossibleValues(V: Cond, Constants&: KnownValues, MaxCount: 4);
6242
6243 // We can also eliminate cases by determining that their values are outside of
6244 // the limited range of the condition based on how many significant (non-sign)
6245 // bits are in the condition value.
6246 unsigned MaxSignificantBitsInCond =
6247 ComputeMaxSignificantBits(Op: Cond, DL, AC, CxtI: SI);
6248
6249 // Gather dead cases.
6250 SmallVector<ConstantInt *, 8> DeadCases;
6251 SmallDenseMap<BasicBlock *, int, 8> NumPerSuccessorCases;
6252 SmallVector<BasicBlock *, 8> UniqueSuccessors;
6253 for (const auto &Case : SI->cases()) {
6254 auto *Successor = Case.getCaseSuccessor();
6255 if (DTU) {
6256 auto [It, Inserted] = NumPerSuccessorCases.try_emplace(Key: Successor);
6257 if (Inserted)
6258 UniqueSuccessors.push_back(Elt: Successor);
6259 ++It->second;
6260 }
6261 ConstantInt *CaseC = Case.getCaseValue();
6262 const APInt &CaseVal = CaseC->getValue();
6263 if (Known.Zero.intersects(RHS: CaseVal) || !Known.One.isSubsetOf(RHS: CaseVal) ||
6264 (CaseVal.getSignificantBits() > MaxSignificantBitsInCond) ||
6265 (IsKnownValuesValid && !KnownValues.contains(Ptr: CaseC))) {
6266 DeadCases.push_back(Elt: CaseC);
6267 if (DTU)
6268 --NumPerSuccessorCases[Successor];
6269 LLVM_DEBUG(dbgs() << "SimplifyCFG: switch case " << CaseVal
6270 << " is dead.\n");
6271 } else if (IsKnownValuesValid)
6272 KnownValues.erase(Ptr: CaseC);
6273 }
6274
6275 // If we can prove that the cases must cover all possible values, the
6276 // default destination becomes dead and we can remove it. If we know some
6277 // of the bits in the value, we can use that to more precisely compute the
6278 // number of possible unique case values.
6279 bool HasDefault = !SI->defaultDestUnreachable();
6280 const unsigned NumUnknownBits =
6281 Known.getBitWidth() - (Known.Zero | Known.One).popcount();
6282 assert(NumUnknownBits <= Known.getBitWidth());
6283 if (HasDefault && DeadCases.empty()) {
6284 if (IsKnownValuesValid && all_of(Range&: KnownValues, P: IsaPred<UndefValue>)) {
6285 createUnreachableSwitchDefault(Switch: SI, DTU);
6286 return true;
6287 }
6288
6289 if (NumUnknownBits < 64 /* avoid overflow */) {
6290 uint64_t AllNumCases = 1ULL << NumUnknownBits;
6291 if (SI->getNumCases() == AllNumCases) {
6292 createUnreachableSwitchDefault(Switch: SI, DTU);
6293 return true;
6294 }
6295 // When only one case value is missing, replace default with that case.
6296 // Eliminating the default branch will provide more opportunities for
6297 // optimization, such as lookup tables.
6298 if (SI->getNumCases() == AllNumCases - 1) {
6299 assert(NumUnknownBits > 1 && "Should be canonicalized to a branch");
6300 IntegerType *CondTy = cast<IntegerType>(Val: Cond->getType());
6301 if (CondTy->getIntegerBitWidth() > 64 ||
6302 !DL.fitsInLegalInteger(Width: CondTy->getIntegerBitWidth()))
6303 return false;
6304
6305 uint64_t MissingCaseVal = 0;
6306 for (const auto &Case : SI->cases())
6307 MissingCaseVal ^= Case.getCaseValue()->getValue().getLimitedValue();
6308 auto *MissingCase = cast<ConstantInt>(
6309 Val: ConstantInt::get(Ty: Cond->getType(), V: MissingCaseVal));
6310 SwitchInstProfUpdateWrapper SIW(*SI);
6311 SIW.addCase(OnVal: MissingCase, Dest: SI->getDefaultDest(),
6312 W: SIW.getSuccessorWeight(idx: 0));
6313 createUnreachableSwitchDefault(Switch: SI, DTU,
6314 /*RemoveOrigDefaultBlock*/ false);
6315 SIW.setSuccessorWeight(idx: 0, W: 0);
6316 return true;
6317 }
6318 }
6319 }
6320
6321 if (DeadCases.empty())
6322 return false;
6323
6324 SwitchInstProfUpdateWrapper SIW(*SI);
6325 for (ConstantInt *DeadCase : DeadCases) {
6326 SwitchInst::CaseIt CaseI = SI->findCaseValue(C: DeadCase);
6327 assert(CaseI != SI->case_default() &&
6328 "Case was not found. Probably mistake in DeadCases forming.");
6329 // Prune unused values from PHI nodes.
6330 CaseI->getCaseSuccessor()->removePredecessor(Pred: SI->getParent());
6331 SIW.removeCase(I: CaseI);
6332 }
6333
6334 if (DTU) {
6335 std::vector<DominatorTree::UpdateType> Updates;
6336 for (auto *Successor : UniqueSuccessors)
6337 if (NumPerSuccessorCases[Successor] == 0)
6338 Updates.push_back(x: {DominatorTree::Delete, SI->getParent(), Successor});
6339 DTU->applyUpdates(Updates);
6340 }
6341
6342 return true;
6343}
6344
6345/// If BB would be eligible for simplification by
6346/// TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated
6347/// by an unconditional branch), look at the phi node for BB in the successor
6348/// block and see if the incoming value is equal to CaseValue. If so, return
6349/// the phi node, and set PhiIndex to BB's index in the phi node.
6350static PHINode *findPHIForConditionForwarding(ConstantInt *CaseValue,
6351 BasicBlock *BB, int *PhiIndex) {
6352 if (&*BB->getFirstNonPHIIt() != BB->getTerminator())
6353 return nullptr; // BB must be empty to be a candidate for simplification.
6354 if (!BB->getSinglePredecessor())
6355 return nullptr; // BB must be dominated by the switch.
6356
6357 UncondBrInst *Branch = dyn_cast<UncondBrInst>(Val: BB->getTerminator());
6358 if (!Branch)
6359 return nullptr; // Terminator must be unconditional branch.
6360
6361 BasicBlock *Succ = Branch->getSuccessor();
6362
6363 for (PHINode &PHI : Succ->phis()) {
6364 int Idx = PHI.getBasicBlockIndex(BB);
6365 assert(Idx >= 0 && "PHI has no entry for predecessor?");
6366
6367 Value *InValue = PHI.getIncomingValue(i: Idx);
6368 if (InValue != CaseValue)
6369 continue;
6370
6371 *PhiIndex = Idx;
6372 return &PHI;
6373 }
6374
6375 return nullptr;
6376}
6377
6378/// Try to forward the condition of a switch instruction to a phi node
6379/// dominated by the switch, if that would mean that some of the destination
6380/// blocks of the switch can be folded away. Return true if a change is made.
6381static bool forwardSwitchConditionToPHI(SwitchInst *SI) {
6382 using ForwardingNodesMap = DenseMap<PHINode *, SmallVector<int, 4>>;
6383
6384 ForwardingNodesMap ForwardingNodes;
6385 BasicBlock *SwitchBlock = SI->getParent();
6386 bool Changed = false;
6387 for (const auto &Case : SI->cases()) {
6388 ConstantInt *CaseValue = Case.getCaseValue();
6389 BasicBlock *CaseDest = Case.getCaseSuccessor();
6390
6391 // Replace phi operands in successor blocks that are using the constant case
6392 // value rather than the switch condition variable:
6393 // switchbb:
6394 // switch i32 %x, label %default [
6395 // i32 17, label %succ
6396 // ...
6397 // succ:
6398 // %r = phi i32 ... [ 17, %switchbb ] ...
6399 // -->
6400 // %r = phi i32 ... [ %x, %switchbb ] ...
6401
6402 for (PHINode &Phi : CaseDest->phis()) {
6403 // This only works if there is exactly 1 incoming edge from the switch to
6404 // a phi. If there is >1, that means multiple cases of the switch map to 1
6405 // value in the phi, and that phi value is not the switch condition. Thus,
6406 // this transform would not make sense (the phi would be invalid because
6407 // a phi can't have different incoming values from the same block).
6408 int SwitchBBIdx = Phi.getBasicBlockIndex(BB: SwitchBlock);
6409 if (Phi.getIncomingValue(i: SwitchBBIdx) == CaseValue &&
6410 count(Range: Phi.blocks(), Element: SwitchBlock) == 1) {
6411 Phi.setIncomingValue(i: SwitchBBIdx, V: SI->getCondition());
6412 Changed = true;
6413 }
6414 }
6415
6416 // Collect phi nodes that are indirectly using this switch's case constants.
6417 int PhiIdx;
6418 if (auto *Phi = findPHIForConditionForwarding(CaseValue, BB: CaseDest, PhiIndex: &PhiIdx))
6419 ForwardingNodes[Phi].push_back(Elt: PhiIdx);
6420 }
6421
6422 for (auto &ForwardingNode : ForwardingNodes) {
6423 PHINode *Phi = ForwardingNode.first;
6424 SmallVectorImpl<int> &Indexes = ForwardingNode.second;
6425 // Check if it helps to fold PHI.
6426 if (Indexes.size() < 2 && !llvm::is_contained(Range: Phi->incoming_values(), Element: SI->getCondition()))
6427 continue;
6428
6429 for (int Index : Indexes)
6430 Phi->setIncomingValue(i: Index, V: SI->getCondition());
6431 Changed = true;
6432 }
6433
6434 return Changed;
6435}
6436
6437/// Return true if the backend will be able to handle
6438/// initializing an array of constants like C.
6439static bool validLookupTableConstant(Constant *C, const TargetTransformInfo &TTI) {
6440 if (C->isThreadDependent())
6441 return false;
6442 if (C->isDLLImportDependent())
6443 return false;
6444
6445 if (!isa<ConstantDataVector, ConstantExpr, ConstantFP, ConstantInt,
6446 ConstantPointerNull, GlobalValue, UndefValue>(Val: C))
6447 return false;
6448
6449 // Globals cannot contain scalable types.
6450 if (C->getType()->isScalableTy())
6451 return false;
6452
6453 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Val: C)) {
6454 // Pointer casts and in-bounds GEPs will not prohibit the backend from
6455 // materializing the array of constants.
6456 Constant *StrippedC = cast<Constant>(Val: CE->stripInBoundsConstantOffsets());
6457 if (StrippedC == C || !validLookupTableConstant(C: StrippedC, TTI))
6458 return false;
6459 }
6460
6461 if (!TTI.shouldBuildLookupTablesForConstant(C))
6462 return false;
6463
6464 return true;
6465}
6466
6467/// If V is a Constant, return it. Otherwise, try to look up
6468/// its constant value in ConstantPool, returning 0 if it's not there.
6469static Constant *
6470lookupConstant(Value *V,
6471 const SmallDenseMap<Value *, Constant *> &ConstantPool) {
6472 if (Constant *C = dyn_cast<Constant>(Val: V))
6473 return C;
6474 return ConstantPool.lookup(Val: V);
6475}
6476
6477/// Try to fold instruction I into a constant. This works for
6478/// simple instructions such as binary operations where both operands are
6479/// constant or can be replaced by constants from the ConstantPool. Returns the
6480/// resulting constant on success, 0 otherwise.
6481static Constant *
6482constantFold(Instruction *I, const DataLayout &DL,
6483 const SmallDenseMap<Value *, Constant *> &ConstantPool) {
6484 if (SelectInst *Select = dyn_cast<SelectInst>(Val: I)) {
6485 Constant *A = lookupConstant(V: Select->getCondition(), ConstantPool);
6486 if (!A)
6487 return nullptr;
6488 if (A->isAllOnesValue())
6489 return lookupConstant(V: Select->getTrueValue(), ConstantPool);
6490 if (A->isNullValue())
6491 return lookupConstant(V: Select->getFalseValue(), ConstantPool);
6492 return nullptr;
6493 }
6494
6495 SmallVector<Constant *, 4> COps;
6496 for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) {
6497 if (Constant *A = lookupConstant(V: I->getOperand(i: N), ConstantPool))
6498 COps.push_back(Elt: A);
6499 else
6500 return nullptr;
6501 }
6502
6503 return ConstantFoldInstOperands(I, Ops: COps, DL);
6504}
6505
6506/// Try to determine the resulting constant values in phi nodes
6507/// at the common destination basic block, *CommonDest, for one of the case
6508/// destinations CaseDest corresponding to value CaseVal (nullptr for the
6509/// default case), of a switch instruction SI.
6510static bool
6511getCaseResults(SwitchInst *SI, ConstantInt *CaseVal, BasicBlock *CaseDest,
6512 BasicBlock **CommonDest,
6513 SmallVectorImpl<std::pair<PHINode *, Constant *>> &Res,
6514 const DataLayout &DL, const TargetTransformInfo &TTI) {
6515 // The block from which we enter the common destination.
6516 BasicBlock *Pred = SI->getParent();
6517
6518 // If CaseDest is empty except for some side-effect free instructions through
6519 // which we can constant-propagate the CaseVal, continue to its successor.
6520 SmallDenseMap<Value *, Constant *> ConstantPool;
6521 ConstantPool.insert(KV: std::make_pair(x: SI->getCondition(), y&: CaseVal));
6522 for (Instruction &I : *CaseDest) {
6523 if (I.isTerminator()) {
6524 // If the terminator is a simple branch, continue to the next block.
6525 if (I.getNumSuccessors() != 1 || I.isSpecialTerminator())
6526 return false;
6527 Pred = CaseDest;
6528 CaseDest = I.getSuccessor(Idx: 0);
6529 } else if (Constant *C = constantFold(I: &I, DL, ConstantPool)) {
6530 // Instruction is side-effect free and constant.
6531
6532 // If the instruction has uses outside this block or a phi node slot for
6533 // the block, it is not safe to bypass the instruction since it would then
6534 // no longer dominate all its uses.
6535 for (auto &Use : I.uses()) {
6536 User *User = Use.getUser();
6537 if (Instruction *I = dyn_cast<Instruction>(Val: User))
6538 if (I->getParent() == CaseDest)
6539 continue;
6540 if (PHINode *Phi = dyn_cast<PHINode>(Val: User))
6541 if (Phi->getIncomingBlock(U: Use) == CaseDest)
6542 continue;
6543 return false;
6544 }
6545
6546 ConstantPool.insert(KV: std::make_pair(x: &I, y&: C));
6547 } else {
6548 break;
6549 }
6550 }
6551
6552 // If we did not have a CommonDest before, use the current one.
6553 if (!*CommonDest)
6554 *CommonDest = CaseDest;
6555 // If the destination isn't the common one, abort.
6556 if (CaseDest != *CommonDest)
6557 return false;
6558
6559 // Get the values for this case from phi nodes in the destination block.
6560 for (PHINode &PHI : (*CommonDest)->phis()) {
6561 int Idx = PHI.getBasicBlockIndex(BB: Pred);
6562 if (Idx == -1)
6563 continue;
6564
6565 Constant *ConstVal =
6566 lookupConstant(V: PHI.getIncomingValue(i: Idx), ConstantPool);
6567 if (!ConstVal)
6568 return false;
6569
6570 // Be conservative about which kinds of constants we support.
6571 if (!validLookupTableConstant(C: ConstVal, TTI))
6572 return false;
6573
6574 Res.push_back(Elt: std::make_pair(x: &PHI, y&: ConstVal));
6575 }
6576
6577 return Res.size() > 0;
6578}
6579
6580// Helper function used to add CaseVal to the list of cases that generate
6581// Result. Returns the updated number of cases that generate this result.
6582static size_t mapCaseToResult(ConstantInt *CaseVal,
6583 SwitchCaseResultVectorTy &UniqueResults,
6584 Constant *Result) {
6585 for (auto &I : UniqueResults) {
6586 if (I.first == Result) {
6587 I.second.push_back(Elt: CaseVal);
6588 return I.second.size();
6589 }
6590 }
6591 UniqueResults.push_back(
6592 Elt: std::make_pair(x&: Result, y: SmallVector<ConstantInt *, 4>(1, CaseVal)));
6593 return 1;
6594}
6595
6596// Helper function that initializes a map containing
6597// results for the PHI node of the common destination block for a switch
6598// instruction. Returns false if multiple PHI nodes have been found or if
6599// there is not a common destination block for the switch.
6600static bool initializeUniqueCases(SwitchInst *SI, PHINode *&PHI,
6601 BasicBlock *&CommonDest,
6602 SwitchCaseResultVectorTy &UniqueResults,
6603 Constant *&DefaultResult,
6604 const DataLayout &DL,
6605 const TargetTransformInfo &TTI,
6606 uintptr_t MaxUniqueResults) {
6607 for (const auto &I : SI->cases()) {
6608 ConstantInt *CaseVal = I.getCaseValue();
6609
6610 // Resulting value at phi nodes for this case value.
6611 SwitchCaseResultsTy Results;
6612 if (!getCaseResults(SI, CaseVal, CaseDest: I.getCaseSuccessor(), CommonDest: &CommonDest, Res&: Results,
6613 DL, TTI))
6614 return false;
6615
6616 // Only one value per case is permitted.
6617 if (Results.size() > 1)
6618 return false;
6619
6620 // Add the case->result mapping to UniqueResults.
6621 const size_t NumCasesForResult =
6622 mapCaseToResult(CaseVal, UniqueResults, Result: Results.begin()->second);
6623
6624 // Early out if there are too many cases for this result.
6625 if (NumCasesForResult > MaxSwitchCasesPerResult)
6626 return false;
6627
6628 // Early out if there are too many unique results.
6629 if (UniqueResults.size() > MaxUniqueResults)
6630 return false;
6631
6632 // Check the PHI consistency.
6633 if (!PHI)
6634 PHI = Results[0].first;
6635 else if (PHI != Results[0].first)
6636 return false;
6637 }
6638 // Find the default result value.
6639 SmallVector<std::pair<PHINode *, Constant *>, 1> DefaultResults;
6640 getCaseResults(SI, CaseVal: nullptr, CaseDest: SI->getDefaultDest(), CommonDest: &CommonDest, Res&: DefaultResults,
6641 DL, TTI);
6642 // If the default value is not found abort unless the default destination
6643 // is unreachable.
6644 DefaultResult =
6645 DefaultResults.size() == 1 ? DefaultResults.begin()->second : nullptr;
6646
6647 return DefaultResult || SI->defaultDestUnreachable();
6648}
6649
6650// Helper function that checks if it is possible to transform a switch with only
6651// two cases (or two cases + default) that produces a result into a select.
6652// TODO: Handle switches with more than 2 cases that map to the same result.
6653// The branch weights correspond to the provided Condition (i.e. if Condition is
6654// modified from the original SwitchInst, the caller must adjust the weights)
6655static Value *foldSwitchToSelect(const SwitchCaseResultVectorTy &ResultVector,
6656 Constant *DefaultResult, Value *Condition,
6657 IRBuilder<> &Builder, const DataLayout &DL,
6658 ArrayRef<uint32_t> BranchWeights) {
6659 // If we are selecting between only two cases transform into a simple
6660 // select or a two-way select if default is possible.
6661 // Example:
6662 // switch (a) { %0 = icmp eq i32 %a, 10
6663 // case 10: return 42; %1 = select i1 %0, i32 42, i32 4
6664 // case 20: return 2; ----> %2 = icmp eq i32 %a, 20
6665 // default: return 4; %3 = select i1 %2, i32 2, i32 %1
6666 // }
6667
6668 const bool HasBranchWeights =
6669 !BranchWeights.empty() && !ProfcheckDisableMetadataFixes;
6670
6671 if (ResultVector.size() == 2 && ResultVector[0].second.size() == 1 &&
6672 ResultVector[1].second.size() == 1) {
6673 ConstantInt *FirstCase = ResultVector[0].second[0];
6674 ConstantInt *SecondCase = ResultVector[1].second[0];
6675 Value *SelectValue = ResultVector[1].first;
6676 if (DefaultResult) {
6677 Value *ValueCompare =
6678 Builder.CreateICmpEQ(LHS: Condition, RHS: SecondCase, Name: "switch.selectcmp");
6679 SelectValue = Builder.CreateSelect(C: ValueCompare, True: ResultVector[1].first,
6680 False: DefaultResult, Name: "switch.select");
6681 if (auto *SI = dyn_cast<SelectInst>(Val: SelectValue);
6682 SI && HasBranchWeights) {
6683 // We start with 3 probabilities, where the numerator is the
6684 // corresponding BranchWeights[i], and the denominator is the sum over
6685 // BranchWeights. We want the probability and negative probability of
6686 // Condition == SecondCase.
6687 assert(BranchWeights.size() == 3);
6688 setBranchWeights(
6689 I&: *SI, Weights: {BranchWeights[2], BranchWeights[0] + BranchWeights[1]},
6690 /*IsExpected=*/false, /*ElideAllZero=*/true);
6691 }
6692 }
6693 Value *ValueCompare =
6694 Builder.CreateICmpEQ(LHS: Condition, RHS: FirstCase, Name: "switch.selectcmp");
6695 Value *Ret = Builder.CreateSelect(C: ValueCompare, True: ResultVector[0].first,
6696 False: SelectValue, Name: "switch.select");
6697 if (auto *SI = dyn_cast<SelectInst>(Val: Ret); SI && HasBranchWeights) {
6698 // We may have had a DefaultResult. Base the position of the first and
6699 // second's branch weights accordingly. Also the proability that Condition
6700 // != FirstCase needs to take that into account.
6701 assert(BranchWeights.size() >= 2);
6702 size_t FirstCasePos = (Condition != nullptr);
6703 size_t SecondCasePos = FirstCasePos + 1;
6704 uint32_t DefaultCase = (Condition != nullptr) ? BranchWeights[0] : 0;
6705 setBranchWeights(I&: *SI,
6706 Weights: {BranchWeights[FirstCasePos],
6707 DefaultCase + BranchWeights[SecondCasePos]},
6708 /*IsExpected=*/false, /*ElideAllZero=*/true);
6709 }
6710 return Ret;
6711 }
6712
6713 // Handle the degenerate case where two cases have the same result value.
6714 if (ResultVector.size() == 1 && DefaultResult) {
6715 ArrayRef<ConstantInt *> CaseValues = ResultVector[0].second;
6716 unsigned CaseCount = CaseValues.size();
6717 // n bits group cases map to the same result:
6718 // case 0,4 -> Cond & 0b1..1011 == 0 ? result : default
6719 // case 0,2,4,6 -> Cond & 0b1..1001 == 0 ? result : default
6720 // case 0,2,8,10 -> Cond & 0b1..0101 == 0 ? result : default
6721 if (isPowerOf2_32(Value: CaseCount)) {
6722 ConstantInt *MinCaseVal = CaseValues[0];
6723 // If there are bits that are set exclusively by CaseValues, we
6724 // can transform the switch into a select if the conjunction of
6725 // all the values uniquely identify CaseValues.
6726 APInt AndMask = APInt::getAllOnes(numBits: MinCaseVal->getBitWidth());
6727
6728 // Find the minimum value and compute the and of all the case values.
6729 for (auto *Case : CaseValues) {
6730 if (Case->getValue().slt(RHS: MinCaseVal->getValue()))
6731 MinCaseVal = Case;
6732 AndMask &= Case->getValue();
6733 }
6734 KnownBits Known = computeKnownBits(V: Condition, DL);
6735
6736 if (!AndMask.isZero() && Known.getMaxValue().uge(RHS: AndMask)) {
6737 // Compute the number of bits that are free to vary.
6738 unsigned FreeBits = Known.countMaxActiveBits() - AndMask.popcount();
6739
6740 // Check if the number of values covered by the mask is equal
6741 // to the number of cases.
6742 if (FreeBits == Log2_32(Value: CaseCount)) {
6743 Value *And = Builder.CreateAnd(LHS: Condition, RHS: AndMask);
6744 Value *Cmp = Builder.CreateICmpEQ(
6745 LHS: And, RHS: Constant::getIntegerValue(Ty: And->getType(), V: AndMask));
6746 Value *Ret =
6747 Builder.CreateSelect(C: Cmp, True: ResultVector[0].first, False: DefaultResult);
6748 if (auto *SI = dyn_cast<SelectInst>(Val: Ret); SI && HasBranchWeights) {
6749 // We know there's a Default case. We base the resulting branch
6750 // weights off its probability.
6751 assert(BranchWeights.size() >= 2);
6752 setBranchWeights(
6753 I&: *SI,
6754 Weights: {accumulate(Range: drop_begin(RangeOrContainer&: BranchWeights), Init: 0U), BranchWeights[0]},
6755 /*IsExpected=*/false, /*ElideAllZero=*/true);
6756 }
6757 return Ret;
6758 }
6759 }
6760
6761 // Mark the bits case number touched.
6762 APInt BitMask = APInt::getZero(numBits: MinCaseVal->getBitWidth());
6763 for (auto *Case : CaseValues)
6764 BitMask |= (Case->getValue() - MinCaseVal->getValue());
6765
6766 // Check if cases with the same result can cover all number
6767 // in touched bits.
6768 if (BitMask.popcount() == Log2_32(Value: CaseCount)) {
6769 if (!MinCaseVal->isNullValue())
6770 Condition = Builder.CreateSub(LHS: Condition, RHS: MinCaseVal);
6771 Value *And = Builder.CreateAnd(LHS: Condition, RHS: ~BitMask, Name: "switch.and");
6772 Value *Cmp = Builder.CreateICmpEQ(
6773 LHS: And, RHS: Constant::getNullValue(Ty: And->getType()), Name: "switch.selectcmp");
6774 Value *Ret =
6775 Builder.CreateSelect(C: Cmp, True: ResultVector[0].first, False: DefaultResult);
6776 if (auto *SI = dyn_cast<SelectInst>(Val: Ret); SI && HasBranchWeights) {
6777 assert(BranchWeights.size() >= 2);
6778 setBranchWeights(
6779 I&: *SI,
6780 Weights: {accumulate(Range: drop_begin(RangeOrContainer&: BranchWeights), Init: 0U), BranchWeights[0]},
6781 /*IsExpected=*/false, /*ElideAllZero=*/true);
6782 }
6783 return Ret;
6784 }
6785 }
6786
6787 // Handle the degenerate case where two cases have the same value.
6788 if (CaseValues.size() == 2) {
6789 Value *Cmp1 = Builder.CreateICmpEQ(LHS: Condition, RHS: CaseValues[0],
6790 Name: "switch.selectcmp.case1");
6791 Value *Cmp2 = Builder.CreateICmpEQ(LHS: Condition, RHS: CaseValues[1],
6792 Name: "switch.selectcmp.case2");
6793 Value *Cmp = Builder.CreateOr(LHS: Cmp1, RHS: Cmp2, Name: "switch.selectcmp");
6794 Value *Ret =
6795 Builder.CreateSelect(C: Cmp, True: ResultVector[0].first, False: DefaultResult);
6796 if (auto *SI = dyn_cast<SelectInst>(Val: Ret); SI && HasBranchWeights) {
6797 assert(BranchWeights.size() >= 2);
6798 setBranchWeights(
6799 I&: *SI, Weights: {accumulate(Range: drop_begin(RangeOrContainer&: BranchWeights), Init: 0U), BranchWeights[0]},
6800 /*IsExpected=*/false, /*ElideAllZero=*/true);
6801 }
6802 return Ret;
6803 }
6804 }
6805
6806 return nullptr;
6807}
6808
6809// Helper function to cleanup a switch instruction that has been converted into
6810// a select, fixing up PHI nodes and basic blocks.
6811static void removeSwitchAfterSelectFold(SwitchInst *SI, PHINode *PHI,
6812 Value *SelectValue,
6813 IRBuilder<> &Builder,
6814 DomTreeUpdater *DTU) {
6815 std::vector<DominatorTree::UpdateType> Updates;
6816
6817 BasicBlock *SelectBB = SI->getParent();
6818 BasicBlock *DestBB = PHI->getParent();
6819
6820 if (DTU && !is_contained(Range: predecessors(BB: DestBB), Element: SelectBB))
6821 Updates.push_back(x: {DominatorTree::Insert, SelectBB, DestBB});
6822 Builder.CreateBr(Dest: DestBB);
6823
6824 // Remove the switch.
6825
6826 PHI->removeIncomingValueIf(
6827 Predicate: [&](unsigned Idx) { return PHI->getIncomingBlock(i: Idx) == SelectBB; });
6828 PHI->addIncoming(V: SelectValue, BB: SelectBB);
6829
6830 SmallPtrSet<BasicBlock *, 4> RemovedSuccessors;
6831 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
6832 BasicBlock *Succ = SI->getSuccessor(idx: i);
6833
6834 if (Succ == DestBB)
6835 continue;
6836 Succ->removePredecessor(Pred: SelectBB);
6837 if (DTU && RemovedSuccessors.insert(Ptr: Succ).second)
6838 Updates.push_back(x: {DominatorTree::Delete, SelectBB, Succ});
6839 }
6840 SI->eraseFromParent();
6841 if (DTU)
6842 DTU->applyUpdates(Updates);
6843}
6844
6845/// If a switch is only used to initialize one or more phi nodes in a common
6846/// successor block with only two different constant values, try to replace the
6847/// switch with a select. Returns true if the fold was made.
6848static bool trySwitchToSelect(SwitchInst *SI, IRBuilder<> &Builder,
6849 DomTreeUpdater *DTU, const DataLayout &DL,
6850 const TargetTransformInfo &TTI) {
6851 Value *const Cond = SI->getCondition();
6852 PHINode *PHI = nullptr;
6853 BasicBlock *CommonDest = nullptr;
6854 Constant *DefaultResult;
6855 SwitchCaseResultVectorTy UniqueResults;
6856 // Collect all the cases that will deliver the same value from the switch.
6857 if (!initializeUniqueCases(SI, PHI, CommonDest, UniqueResults, DefaultResult,
6858 DL, TTI, /*MaxUniqueResults*/ 2))
6859 return false;
6860
6861 assert(PHI != nullptr && "PHI for value select not found");
6862 Builder.SetInsertPoint(SI);
6863 SmallVector<uint32_t, 4> BranchWeights;
6864 if (!ProfcheckDisableMetadataFixes) {
6865 [[maybe_unused]] auto HasWeights =
6866 extractBranchWeights(ProfileData: getBranchWeightMDNode(I: *SI), Weights&: BranchWeights);
6867 assert(!HasWeights == (BranchWeights.empty()));
6868 }
6869 assert(BranchWeights.empty() ||
6870 (BranchWeights.size() >=
6871 UniqueResults.size() + (DefaultResult != nullptr)));
6872
6873 Value *SelectValue = foldSwitchToSelect(ResultVector: UniqueResults, DefaultResult, Condition: Cond,
6874 Builder, DL, BranchWeights);
6875 if (!SelectValue)
6876 return false;
6877
6878 removeSwitchAfterSelectFold(SI, PHI, SelectValue, Builder, DTU);
6879 return true;
6880}
6881
6882namespace {
6883
6884/// This class finds alternatives for switches to ultimately
6885/// replace the switch.
6886class SwitchReplacement {
6887public:
6888 /// Create a helper for optimizations to use as a switch replacement.
6889 /// Find a better representation for the content of Values,
6890 /// using DefaultValue to fill any holes in the table.
6891 SwitchReplacement(
6892 Module &M, uint64_t TableSize, ConstantInt *Offset,
6893 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
6894 Constant *DefaultValue, const DataLayout &DL,
6895 const TargetTransformInfo &TTI, const StringRef &FuncName);
6896
6897 /// Build instructions with Builder to retrieve values using Index
6898 /// and replace the switch.
6899 Value *replaceSwitch(Value *Index, IRBuilder<> &Builder, const DataLayout &DL,
6900 Function *Func);
6901
6902 /// Return true if a table with TableSize elements of
6903 /// type ElementType would fit in a target-legal register.
6904 static bool wouldFitInRegister(const DataLayout &DL, uint64_t TableSize,
6905 Type *ElementType);
6906
6907 /// Return the default value of the switch.
6908 Constant *getDefaultValue();
6909
6910 /// Return true if the replacement is a lookup table.
6911 bool isLookupTable();
6912
6913 /// Return true if the replacement is a bit map.
6914 bool isBitMap();
6915
6916private:
6917 // Depending on the switch, there are different alternatives.
6918 enum {
6919 // For switches where each case contains the same value, we just have to
6920 // store that single value and return it for each lookup.
6921 SingleValueKind,
6922
6923 // For switches where there is a linear relationship between table index
6924 // and values. We calculate the result with a simple multiplication
6925 // and addition instead of a table lookup.
6926 LinearMapKind,
6927
6928 // For small tables with integer elements, we can pack them into a bitmap
6929 // that fits into a target-legal register. Values are retrieved by
6930 // shift and mask operations.
6931 BitMapKind,
6932
6933 // The table is stored as an array of values. Values are retrieved by load
6934 // instructions from the table.
6935 LookupTableKind
6936 } Kind;
6937
6938 // The default value of the switch.
6939 Constant *DefaultValue;
6940
6941 // The type of the output values.
6942 Type *ValueType;
6943
6944 // For SingleValueKind, this is the single value.
6945 Constant *SingleValue = nullptr;
6946
6947 // For BitMapKind, this is the bitmap.
6948 ConstantInt *BitMap = nullptr;
6949 IntegerType *BitMapElementTy = nullptr;
6950
6951 // For LinearMapKind, these are the constants used to derive the value.
6952 ConstantInt *LinearOffset = nullptr;
6953 ConstantInt *LinearMultiplier = nullptr;
6954 bool LinearMapValWrapped = false;
6955
6956 // For LookupTableKind, this is the table.
6957 Constant *Initializer = nullptr;
6958};
6959
6960} // end anonymous namespace
6961
6962SwitchReplacement::SwitchReplacement(
6963 Module &M, uint64_t TableSize, ConstantInt *Offset,
6964 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
6965 Constant *DefaultValue, const DataLayout &DL,
6966 const TargetTransformInfo &TTI, const StringRef &FuncName)
6967 : DefaultValue(DefaultValue) {
6968 assert(Values.size() && "Can't build lookup table without values!");
6969 assert(TableSize >= Values.size() && "Can't fit values in table!");
6970
6971 // If all values in the table are equal, this is that value.
6972 SingleValue = Values.begin()->second;
6973
6974 ValueType = Values.begin()->second->getType();
6975
6976 // Build up the table contents.
6977 SmallVector<Constant *, 64> TableContents(TableSize);
6978 for (const auto &[CaseVal, CaseRes] : Values) {
6979 assert(CaseRes->getType() == ValueType);
6980
6981 uint64_t Idx = (CaseVal->getValue() - Offset->getValue()).getLimitedValue();
6982 TableContents[Idx] = CaseRes;
6983
6984 if (SingleValue && !isa<PoisonValue>(Val: CaseRes) && CaseRes != SingleValue)
6985 SingleValue = isa<PoisonValue>(Val: SingleValue) ? CaseRes : nullptr;
6986 }
6987
6988 // Fill in any holes in the table with the default result.
6989 if (Values.size() < TableSize) {
6990 assert(DefaultValue &&
6991 "Need a default value to fill the lookup table holes.");
6992 assert(DefaultValue->getType() == ValueType);
6993 for (uint64_t I = 0; I < TableSize; ++I) {
6994 if (!TableContents[I])
6995 TableContents[I] = DefaultValue;
6996 }
6997
6998 // If the default value is poison, all the holes are poison.
6999 bool DefaultValueIsPoison = isa<PoisonValue>(Val: DefaultValue);
7000
7001 if (DefaultValue != SingleValue && !DefaultValueIsPoison)
7002 SingleValue = nullptr;
7003 }
7004
7005 // If each element in the table contains the same value, we only need to store
7006 // that single value.
7007 if (SingleValue) {
7008 Kind = SingleValueKind;
7009 return;
7010 }
7011
7012 // Check if we can derive the value with a linear transformation from the
7013 // table index.
7014 if (isa<IntegerType>(Val: ValueType)) {
7015 bool LinearMappingPossible = true;
7016 APInt PrevVal;
7017 APInt DistToPrev;
7018 // When linear map is monotonic and signed overflow doesn't happen on
7019 // maximum index, we can attach nsw on Add and Mul.
7020 bool NonMonotonic = false;
7021 assert(TableSize >= 2 && "Should be a SingleValue table.");
7022 // Check if there is the same distance between two consecutive values.
7023 for (uint64_t I = 0; I < TableSize; ++I) {
7024 ConstantInt *ConstVal = dyn_cast<ConstantInt>(Val: TableContents[I]);
7025
7026 if (!ConstVal && isa<PoisonValue>(Val: TableContents[I])) {
7027 // This is an poison, so it's (probably) a lookup table hole.
7028 // To prevent any regressions from before we switched to using poison as
7029 // the default value, holes will fall back to using the first value.
7030 // This can be removed once we add proper handling for poisons in lookup
7031 // tables.
7032 ConstVal = dyn_cast<ConstantInt>(Val: Values[0].second);
7033 }
7034
7035 if (!ConstVal) {
7036 // This is an undef. We could deal with it, but undefs in lookup tables
7037 // are very seldom. It's probably not worth the additional complexity.
7038 LinearMappingPossible = false;
7039 break;
7040 }
7041 const APInt &Val = ConstVal->getValue();
7042 if (I != 0) {
7043 APInt Dist = Val - PrevVal;
7044 if (I == 1) {
7045 DistToPrev = Dist;
7046 } else if (Dist != DistToPrev) {
7047 LinearMappingPossible = false;
7048 break;
7049 }
7050 NonMonotonic |=
7051 Dist.isStrictlyPositive() ? Val.sle(RHS: PrevVal) : Val.sgt(RHS: PrevVal);
7052 }
7053 PrevVal = Val;
7054 }
7055 if (LinearMappingPossible) {
7056 LinearOffset = cast<ConstantInt>(Val: TableContents[0]);
7057 LinearMultiplier = ConstantInt::get(Context&: M.getContext(), V: DistToPrev);
7058 APInt M = LinearMultiplier->getValue();
7059 bool MayWrap = true;
7060 if (isIntN(N: M.getBitWidth(), x: TableSize - 1))
7061 (void)M.smul_ov(RHS: APInt(M.getBitWidth(), TableSize - 1), Overflow&: MayWrap);
7062 LinearMapValWrapped = NonMonotonic || MayWrap;
7063 Kind = LinearMapKind;
7064 return;
7065 }
7066 }
7067
7068 // If the type is integer and the table fits in a register, build a bitmap.
7069 if (wouldFitInRegister(DL, TableSize, ElementType: ValueType)) {
7070 IntegerType *IT = cast<IntegerType>(Val: ValueType);
7071 APInt TableInt(TableSize * IT->getBitWidth(), 0);
7072 for (uint64_t I = TableSize; I > 0; --I) {
7073 TableInt <<= IT->getBitWidth();
7074 // Insert values into the bitmap. Undef values are set to zero.
7075 if (!isa<UndefValue>(Val: TableContents[I - 1])) {
7076 ConstantInt *Val = cast<ConstantInt>(Val: TableContents[I - 1]);
7077 TableInt |= Val->getValue().zext(width: TableInt.getBitWidth());
7078 }
7079 }
7080 BitMap = ConstantInt::get(Context&: M.getContext(), V: TableInt);
7081 BitMapElementTy = IT;
7082 Kind = BitMapKind;
7083 return;
7084 }
7085
7086 if (auto *IT = dyn_cast<IntegerType>(Val: ValueType)) {
7087 ConstantRange Range(IT->getBitWidth(), false);
7088 for (Constant *Value : TableContents)
7089 if (!isa<UndefValue>(Val: Value))
7090 Range = Range.unionWith(CR: cast<ConstantInt>(Val: Value)->getValue());
7091 // TODO: handle sign extension as well?
7092 unsigned NeededBitWidth =
7093 std::max(a: TTI.getMinimumLookupTableEntryBitWidth(),
7094 b: unsigned(PowerOf2Ceil(A: Range.getActiveBits())));
7095 if (NeededBitWidth < IT->getBitWidth()) {
7096 IntegerType *DstTy = IntegerType::get(C&: IT->getContext(), NumBits: NeededBitWidth);
7097 for (Constant *&Value : TableContents)
7098 Value = ConstantFoldCastInstruction(opcode: Instruction::Trunc, V: Value, DestTy: DstTy);
7099 }
7100 }
7101
7102 // Store the table in an array.
7103 auto *TableTy = ArrayType::get(ElementType: TableContents[0]->getType(), NumElements: TableSize);
7104 Initializer = ConstantArray::get(T: TableTy, V: TableContents);
7105
7106 Kind = LookupTableKind;
7107}
7108
7109Value *SwitchReplacement::replaceSwitch(Value *Index, IRBuilder<> &Builder,
7110 const DataLayout &DL, Function *Func) {
7111 switch (Kind) {
7112 case SingleValueKind:
7113 return SingleValue;
7114 case LinearMapKind: {
7115 ++NumLinearMaps;
7116 // Derive the result value from the input value.
7117 Value *Result = Builder.CreateIntCast(V: Index, DestTy: LinearMultiplier->getType(),
7118 isSigned: false, Name: "switch.idx.cast");
7119 if (!LinearMultiplier->isOne())
7120 Result = Builder.CreateMul(LHS: Result, RHS: LinearMultiplier, Name: "switch.idx.mult",
7121 /*HasNUW = */ false,
7122 /*HasNSW = */ !LinearMapValWrapped);
7123
7124 if (!LinearOffset->isZero())
7125 Result = Builder.CreateAdd(LHS: Result, RHS: LinearOffset, Name: "switch.offset",
7126 /*HasNUW = */ false,
7127 /*HasNSW = */ !LinearMapValWrapped);
7128 return Result;
7129 }
7130 case BitMapKind: {
7131 ++NumBitMaps;
7132 // Type of the bitmap (e.g. i59).
7133 IntegerType *MapTy = BitMap->getIntegerType();
7134
7135 // Cast Index to the same type as the bitmap.
7136 // Note: The Index is <= the number of elements in the table, so
7137 // truncating it to the width of the bitmask is safe.
7138 Value *ShiftAmt = Builder.CreateZExtOrTrunc(V: Index, DestTy: MapTy, Name: "switch.cast");
7139
7140 // Multiply the shift amount by the element width. NUW/NSW can always be
7141 // set, because wouldFitInRegister guarantees Index * ShiftAmt is in
7142 // BitMap's bit width.
7143 ShiftAmt = Builder.CreateMul(
7144 LHS: ShiftAmt, RHS: ConstantInt::get(Ty: MapTy, V: BitMapElementTy->getBitWidth()),
7145 Name: "switch.shiftamt",/*HasNUW =*/true,/*HasNSW =*/true);
7146
7147 // Shift down.
7148 Value *DownShifted =
7149 Builder.CreateLShr(LHS: BitMap, RHS: ShiftAmt, Name: "switch.downshift");
7150 // Mask off.
7151 return Builder.CreateTrunc(V: DownShifted, DestTy: BitMapElementTy, Name: "switch.masked");
7152 }
7153 case LookupTableKind: {
7154 ++NumLookupTables;
7155 auto *Table =
7156 new GlobalVariable(*Func->getParent(), Initializer->getType(),
7157 /*isConstant=*/true, GlobalVariable::PrivateLinkage,
7158 Initializer, "switch.table." + Func->getName());
7159 Table->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
7160 // Set the alignment to that of an array items. We will be only loading one
7161 // value out of it.
7162 Table->setAlignment(DL.getPrefTypeAlign(Ty: ValueType));
7163 Type *IndexTy = DL.getIndexType(PtrTy: Table->getType());
7164 auto *ArrayTy = cast<ArrayType>(Val: Table->getValueType());
7165
7166 if (Index->getType() != IndexTy) {
7167 unsigned OldBitWidth = Index->getType()->getIntegerBitWidth();
7168 Index = Builder.CreateZExtOrTrunc(V: Index, DestTy: IndexTy);
7169 if (auto *Zext = dyn_cast<ZExtInst>(Val: Index))
7170 Zext->setNonNeg(
7171 isUIntN(N: OldBitWidth - 1, x: ArrayTy->getNumElements() - 1));
7172 }
7173
7174 Value *GEPIndices[] = {ConstantInt::get(Ty: IndexTy, V: 0), Index};
7175 Value *GEP =
7176 Builder.CreateInBoundsGEP(Ty: ArrayTy, Ptr: Table, IdxList: GEPIndices, Name: "switch.gep");
7177 Value *Load =
7178 Builder.CreateLoad(Ty: ArrayTy->getElementType(), Ptr: GEP, Name: "switch.load");
7179 if (Load->getType() == ValueType)
7180 return Load;
7181 return Builder.CreateZExt(V: Load, DestTy: ValueType, Name: "switch.ext");
7182 }
7183 }
7184 llvm_unreachable("Unknown helper kind!");
7185}
7186
7187bool SwitchReplacement::wouldFitInRegister(const DataLayout &DL,
7188 uint64_t TableSize,
7189 Type *ElementType) {
7190 auto *IT = dyn_cast<IntegerType>(Val: ElementType);
7191 if (!IT)
7192 return false;
7193 // FIXME: If the type is wider than it needs to be, e.g. i8 but all values
7194 // are <= 15, we could try to narrow the type.
7195
7196 // Avoid overflow, fitsInLegalInteger uses unsigned int for the width.
7197 if (TableSize >= UINT_MAX / IT->getBitWidth())
7198 return false;
7199 return DL.fitsInLegalInteger(Width: TableSize * IT->getBitWidth());
7200}
7201
7202static bool isTypeLegalForLookupTable(Type *Ty, const TargetTransformInfo &TTI,
7203 const DataLayout &DL) {
7204 // Allow any legal type.
7205 if (TTI.isTypeLegal(Ty))
7206 return true;
7207
7208 auto *IT = dyn_cast<IntegerType>(Val: Ty);
7209 if (!IT)
7210 return false;
7211
7212 // Also allow power of 2 integer types that have at least 8 bits and fit in
7213 // a register. These types are common in frontend languages and targets
7214 // usually support loads of these types.
7215 // TODO: We could relax this to any integer that fits in a register and rely
7216 // on ABI alignment and padding in the table to allow the load to be widened.
7217 // Or we could widen the constants and truncate the load.
7218 unsigned BitWidth = IT->getBitWidth();
7219 return BitWidth >= 8 && isPowerOf2_32(Value: BitWidth) &&
7220 DL.fitsInLegalInteger(Width: IT->getBitWidth());
7221}
7222
7223Constant *SwitchReplacement::getDefaultValue() { return DefaultValue; }
7224
7225bool SwitchReplacement::isLookupTable() { return Kind == LookupTableKind; }
7226
7227bool SwitchReplacement::isBitMap() { return Kind == BitMapKind; }
7228
7229static bool isSwitchDense(uint64_t NumCases, uint64_t CaseRange, bool OptSize) {
7230 // 40% is the default density for building a jump table in optsize/minsize
7231 // mode, 10% is the default density for jump tables. See also
7232 // TargetLoweringBase::isSuitableForJumpTable(), which this function was based
7233 // on.
7234 const uint64_t MinDensity = OptSize ? 40 : 10;
7235
7236 if (CaseRange >= UINT64_MAX / 100)
7237 return false; // Avoid multiplication overflows below.
7238
7239 return NumCases * 100 >= CaseRange * MinDensity;
7240}
7241
7242static bool isSwitchDense(ArrayRef<int64_t> Values, bool OptSize) {
7243 uint64_t Diff = (uint64_t)Values.back() - (uint64_t)Values.front();
7244 uint64_t Range = Diff + 1;
7245 if (Range < Diff)
7246 return false; // Overflow.
7247
7248 return isSwitchDense(NumCases: Values.size(), CaseRange: Range, OptSize);
7249}
7250
7251static std::optional<unsigned>
7252getDenseSwitchRangeReductionShift(ArrayRef<int64_t> Values, int64_t Base,
7253 bool OptSize) {
7254 assert(Values.size() > 1 && "expected multiple switch cases");
7255 if (!llvm::all_of(Range&: Values, P: [Base](int64_t V) { return V >= Base; }))
7256 return std::nullopt;
7257
7258 // First, transform the values by subtracting Base.
7259 SmallVector<int64_t, 4> ReducedValues(Values);
7260 uint64_t ReducedValuesOr = 0;
7261 for (auto &V : ReducedValues) {
7262 uint64_t Reduced = (uint64_t)V - (uint64_t)Base;
7263 ReducedValuesOr |= Reduced;
7264 V = (int64_t)Reduced;
7265 }
7266
7267 // Conceptually, the reduced values are non-negative distances from Base.
7268 // Since the rest of the transform is bitwise only, treat them as unsigned
7269 // bit patterns from here.
7270
7271 // countr_zero(0) returns 64. As Values is guaranteed to have more than
7272 // one element and LLVM disallows duplicate cases, ReducedValuesOr will
7273 // have at least one bit set, so Shift will be less than 64.
7274 unsigned Shift = llvm::countr_zero(Val: ReducedValuesOr);
7275 assert(Shift < 64);
7276 if (Shift > 0)
7277 for (auto &V : ReducedValues)
7278 V = (int64_t)((uint64_t)V >> Shift);
7279
7280 if (!isSwitchDense(Values: ReducedValues, OptSize))
7281 return std::nullopt;
7282
7283 return Shift;
7284}
7285
7286/// Determine whether a lookup table should be built for this switch, based on
7287/// the number of cases, size of the table, and the types of the results.
7288// TODO: We could support larger than legal types by limiting based on the
7289// number of loads required and/or table size. If the constants are small we
7290// could use smaller table entries and extend after the load.
7291static bool shouldBuildLookupTable(SwitchInst *SI, uint64_t TableSize,
7292 const TargetTransformInfo &TTI,
7293 const DataLayout &DL,
7294 const SmallVector<Type *> &ResultTypes) {
7295 if (SI->getNumCases() > TableSize)
7296 return false; // TableSize overflowed.
7297
7298 bool AllTablesFitInRegister = true;
7299 bool HasIllegalType = false;
7300 for (const auto &Ty : ResultTypes) {
7301 // Saturate this flag to true.
7302 HasIllegalType = HasIllegalType || !isTypeLegalForLookupTable(Ty, TTI, DL);
7303
7304 // Saturate this flag to false.
7305 AllTablesFitInRegister =
7306 AllTablesFitInRegister &&
7307 SwitchReplacement::wouldFitInRegister(DL, TableSize, ElementType: Ty);
7308
7309 // If both flags saturate, we're done. NOTE: This *only* works with
7310 // saturating flags, and all flags have to saturate first due to the
7311 // non-deterministic behavior of iterating over a dense map.
7312 if (HasIllegalType && !AllTablesFitInRegister)
7313 break;
7314 }
7315
7316 // If each table would fit in a register, we should build it anyway.
7317 if (AllTablesFitInRegister)
7318 return true;
7319
7320 // Don't build a table that doesn't fit in-register if it has illegal types.
7321 if (HasIllegalType)
7322 return false;
7323
7324 return isSwitchDense(NumCases: SI->getNumCases(), CaseRange: TableSize,
7325 OptSize: SI->getFunction()->hasOptSize());
7326}
7327
7328static bool shouldUseSwitchConditionAsTableIndex(
7329 ConstantInt &MinCaseVal, const ConstantInt &MaxCaseVal,
7330 bool HasDefaultResults, const SmallVector<Type *> &ResultTypes,
7331 const DataLayout &DL, const TargetTransformInfo &TTI) {
7332 if (MinCaseVal.isNullValue())
7333 return true;
7334 if (MinCaseVal.isNegative() ||
7335 MaxCaseVal.getLimitedValue() == std::numeric_limits<uint64_t>::max() ||
7336 !HasDefaultResults)
7337 return false;
7338 return all_of(Range: ResultTypes, P: [&](const auto &ResultType) {
7339 return SwitchReplacement::wouldFitInRegister(
7340 DL, TableSize: MaxCaseVal.getLimitedValue() + 1 /* TableSize */, ElementType: ResultType);
7341 });
7342}
7343
7344/// Try to reuse the switch table index compare. Following pattern:
7345/// \code
7346/// if (idx < tablesize)
7347/// r = table[idx]; // table does not contain default_value
7348/// else
7349/// r = default_value;
7350/// if (r != default_value)
7351/// ...
7352/// \endcode
7353/// Is optimized to:
7354/// \code
7355/// cond = idx < tablesize;
7356/// if (cond)
7357/// r = table[idx];
7358/// else
7359/// r = default_value;
7360/// if (cond)
7361/// ...
7362/// \endcode
7363/// Jump threading will then eliminate the second if(cond).
7364static void reuseTableCompare(
7365 User *PhiUser, BasicBlock *PhiBlock, CondBrInst *RangeCheckBranch,
7366 Constant *DefaultValue,
7367 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values) {
7368 ICmpInst *CmpInst = dyn_cast<ICmpInst>(Val: PhiUser);
7369 if (!CmpInst)
7370 return;
7371
7372 // We require that the compare is in the same block as the phi so that jump
7373 // threading can do its work afterwards.
7374 if (CmpInst->getParent() != PhiBlock)
7375 return;
7376
7377 Constant *CmpOp1 = dyn_cast<Constant>(Val: CmpInst->getOperand(i_nocapture: 1));
7378 if (!CmpOp1)
7379 return;
7380
7381 Value *RangeCmp = RangeCheckBranch->getCondition();
7382 Constant *TrueConst = ConstantInt::getTrue(Ty: RangeCmp->getType());
7383 Constant *FalseConst = ConstantInt::getFalse(Ty: RangeCmp->getType());
7384
7385 // Check if the compare with the default value is constant true or false.
7386 const DataLayout &DL = PhiBlock->getDataLayout();
7387 Constant *DefaultConst = ConstantFoldCompareInstOperands(
7388 Predicate: CmpInst->getPredicate(), LHS: DefaultValue, RHS: CmpOp1, DL);
7389 if (DefaultConst != TrueConst && DefaultConst != FalseConst)
7390 return;
7391
7392 // Check if the compare with the case values is distinct from the default
7393 // compare result.
7394 for (auto ValuePair : Values) {
7395 Constant *CaseConst = ConstantFoldCompareInstOperands(
7396 Predicate: CmpInst->getPredicate(), LHS: ValuePair.second, RHS: CmpOp1, DL);
7397 if (!CaseConst || CaseConst == DefaultConst ||
7398 (CaseConst != TrueConst && CaseConst != FalseConst))
7399 return;
7400 }
7401
7402 // Check if the branch instruction dominates the phi node. It's a simple
7403 // dominance check, but sufficient for our needs.
7404 // Although this check is invariant in the calling loops, it's better to do it
7405 // at this late stage. Practically we do it at most once for a switch.
7406 BasicBlock *BranchBlock = RangeCheckBranch->getParent();
7407 for (BasicBlock *Pred : predecessors(BB: PhiBlock)) {
7408 if (Pred != BranchBlock && Pred->getUniquePredecessor() != BranchBlock)
7409 return;
7410 }
7411
7412 if (DefaultConst == FalseConst) {
7413 // The compare yields the same result. We can replace it.
7414 CmpInst->replaceAllUsesWith(V: RangeCmp);
7415 ++NumTableCmpReuses;
7416 } else {
7417 // The compare yields the same result, just inverted. We can replace it.
7418 Value *InvertedTableCmp = BinaryOperator::CreateXor(
7419 V1: RangeCmp, V2: ConstantInt::get(Ty: RangeCmp->getType(), V: 1), Name: "inverted.cmp",
7420 InsertBefore: RangeCheckBranch->getIterator());
7421 CmpInst->replaceAllUsesWith(V: InvertedTableCmp);
7422 ++NumTableCmpReuses;
7423 }
7424}
7425
7426/// If the switch is only used to initialize one or more phi nodes in a common
7427/// successor block with different constant values, replace the switch with
7428/// lookup tables.
7429static bool simplifySwitchLookup(SwitchInst *SI, IRBuilder<> &Builder,
7430 DomTreeUpdater *DTU, const DataLayout &DL,
7431 const TargetTransformInfo &TTI,
7432 bool ConvertSwitchToLookupTable) {
7433 assert(SI->getNumCases() > 1 && "Degenerate switch?");
7434
7435 BasicBlock *BB = SI->getParent();
7436 Function *Fn = BB->getParent();
7437
7438 // FIXME: If the switch is too sparse for a lookup table, perhaps we could
7439 // split off a dense part and build a lookup table for that.
7440
7441 // FIXME: This creates arrays of GEPs to constant strings, which means each
7442 // GEP needs a runtime relocation in PIC code. We should just build one big
7443 // string and lookup indices into that.
7444
7445 // Ignore switches with less than three cases. Lookup tables will not make
7446 // them faster, so we don't analyze them.
7447 if (SI->getNumCases() < 3)
7448 return false;
7449
7450 // Figure out the corresponding result for each case value and phi node in the
7451 // common destination, as well as the min and max case values.
7452 assert(!SI->cases().empty());
7453 SwitchInst::CaseIt CI = SI->case_begin();
7454 ConstantInt *MinCaseVal = CI->getCaseValue();
7455 ConstantInt *MaxCaseVal = CI->getCaseValue();
7456
7457 BasicBlock *CommonDest = nullptr;
7458
7459 using ResultListTy = SmallVector<std::pair<ConstantInt *, Constant *>, 4>;
7460 SmallDenseMap<PHINode *, ResultListTy> ResultLists;
7461
7462 SmallDenseMap<PHINode *, Constant *> DefaultResults;
7463 SmallVector<Type *> ResultTypes;
7464 SmallVector<PHINode *, 4> PHIs;
7465
7466 for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) {
7467 ConstantInt *CaseVal = CI->getCaseValue();
7468 if (CaseVal->getValue().slt(RHS: MinCaseVal->getValue()))
7469 MinCaseVal = CaseVal;
7470 if (CaseVal->getValue().sgt(RHS: MaxCaseVal->getValue()))
7471 MaxCaseVal = CaseVal;
7472
7473 // Resulting value at phi nodes for this case value.
7474 using ResultsTy = SmallVector<std::pair<PHINode *, Constant *>, 4>;
7475 ResultsTy Results;
7476 if (!getCaseResults(SI, CaseVal, CaseDest: CI->getCaseSuccessor(), CommonDest: &CommonDest,
7477 Res&: Results, DL, TTI))
7478 return false;
7479
7480 // Append the result and result types from this case to the list for each
7481 // phi.
7482 for (const auto &I : Results) {
7483 PHINode *PHI = I.first;
7484 Constant *Value = I.second;
7485 auto [It, Inserted] = ResultLists.try_emplace(Key: PHI);
7486 if (Inserted)
7487 PHIs.push_back(Elt: PHI);
7488 It->second.push_back(Elt: std::make_pair(x&: CaseVal, y&: Value));
7489 ResultTypes.push_back(Elt: PHI->getType());
7490 }
7491 }
7492
7493 // If the table has holes, we need a constant result for the default case
7494 // or a bitmask that fits in a register.
7495 SmallVector<std::pair<PHINode *, Constant *>, 4> DefaultResultsList;
7496 bool HasDefaultResults =
7497 getCaseResults(SI, CaseVal: nullptr, CaseDest: SI->getDefaultDest(), CommonDest: &CommonDest,
7498 Res&: DefaultResultsList, DL, TTI);
7499 for (const auto &I : DefaultResultsList) {
7500 PHINode *PHI = I.first;
7501 Constant *Result = I.second;
7502 DefaultResults[PHI] = Result;
7503 }
7504
7505 bool UseSwitchConditionAsTableIndex = shouldUseSwitchConditionAsTableIndex(
7506 MinCaseVal&: *MinCaseVal, MaxCaseVal: *MaxCaseVal, HasDefaultResults, ResultTypes, DL, TTI);
7507 uint64_t TableSize;
7508 ConstantInt *TableIndexOffset;
7509 if (UseSwitchConditionAsTableIndex) {
7510 TableSize = MaxCaseVal->getLimitedValue() + 1;
7511 TableIndexOffset = ConstantInt::get(Ty: MaxCaseVal->getIntegerType(), V: 0);
7512 } else {
7513 TableSize =
7514 (MaxCaseVal->getValue() - MinCaseVal->getValue()).getLimitedValue() + 1;
7515
7516 TableIndexOffset = MinCaseVal;
7517 }
7518
7519 // If the default destination is unreachable, or if the lookup table covers
7520 // all values of the conditional variable, branch directly to the lookup table
7521 // BB. Otherwise, check that the condition is within the case range.
7522 uint64_t NumResults = ResultLists[PHIs[0]].size();
7523 bool DefaultIsReachable = !SI->defaultDestUnreachable();
7524
7525 bool TableHasHoles = (NumResults < TableSize);
7526
7527 // If the table has holes but the default destination doesn't produce any
7528 // constant results, the lookup table entries corresponding to the holes will
7529 // contain poison.
7530 bool AllHolesArePoison = TableHasHoles && !HasDefaultResults;
7531
7532 // If the default destination doesn't produce a constant result but is still
7533 // reachable, and the lookup table has holes, we need to use a mask to
7534 // determine if the current index should load from the lookup table or jump
7535 // to the default case.
7536 // The mask is unnecessary if the table has holes but the default destination
7537 // is unreachable, as in that case the holes must also be unreachable.
7538 bool NeedMask = AllHolesArePoison && DefaultIsReachable;
7539 if (NeedMask) {
7540 // As an extra penalty for the validity test we require more cases.
7541 if (SI->getNumCases() < 4) // FIXME: Find best threshold value (benchmark).
7542 return false;
7543 if (!DL.fitsInLegalInteger(Width: TableSize))
7544 return false;
7545 }
7546
7547 if (!shouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes))
7548 return false;
7549
7550 // Compute the table index value.
7551 Value *TableIndex;
7552 if (UseSwitchConditionAsTableIndex) {
7553 TableIndex = SI->getCondition();
7554 if (HasDefaultResults) {
7555 // Grow the table to cover all possible index values to avoid the range
7556 // check. It will use the default result to fill in the table hole later,
7557 // so make sure it exist.
7558 ConstantRange CR = computeConstantRange(V: TableIndex, /*ForSigned=*/false,
7559 SQ: SimplifyQuery(DL));
7560 // Grow the table shouldn't have any size impact by checking
7561 // wouldFitInRegister.
7562 // TODO: Consider growing the table also when it doesn't fit in a register
7563 // if no optsize is specified.
7564 const uint64_t UpperBound = CR.getUpper().getLimitedValue();
7565 if (!CR.isUpperWrapped() &&
7566 all_of(Range&: ResultTypes, P: [&](const auto &ResultType) {
7567 return SwitchReplacement::wouldFitInRegister(DL, TableSize: UpperBound,
7568 ElementType: ResultType);
7569 })) {
7570 // There may be some case index larger than the UpperBound (unreachable
7571 // case), so make sure the table size does not get smaller.
7572 TableSize = std::max(a: UpperBound, b: TableSize);
7573 // The default branch is unreachable after we enlarge the lookup table.
7574 // Adjust DefaultIsReachable to reuse code path.
7575 DefaultIsReachable = false;
7576 }
7577 }
7578 }
7579
7580 // Keep track of the switch replacement for each phi
7581 SmallDenseMap<PHINode *, SwitchReplacement> PhiToReplacementMap;
7582 for (PHINode *PHI : PHIs) {
7583 const auto &ResultList = ResultLists[PHI];
7584
7585 Type *ResultType = ResultList.begin()->second->getType();
7586 // Use any value to fill the lookup table holes.
7587 Constant *DefaultVal =
7588 AllHolesArePoison ? PoisonValue::get(T: ResultType) : DefaultResults[PHI];
7589 StringRef FuncName = Fn->getName();
7590 SwitchReplacement Replacement(*Fn->getParent(), TableSize, TableIndexOffset,
7591 ResultList, DefaultVal, DL, TTI, FuncName);
7592 PhiToReplacementMap.insert(KV: {PHI, Replacement});
7593 }
7594
7595 bool AnyLookupTables = any_of(
7596 Range&: PhiToReplacementMap, P: [](auto &KV) { return KV.second.isLookupTable(); });
7597 bool AnyBitMaps = any_of(Range&: PhiToReplacementMap,
7598 P: [](auto &KV) { return KV.second.isBitMap(); });
7599
7600 // A few conditions prevent the generation of lookup tables:
7601 // 1. The target does not support lookup tables.
7602 // 2. The "no-jump-tables" function attribute is set.
7603 // However, these objections do not apply to other switch replacements, like
7604 // the bitmap, so we only stop here if any of these conditions are met and we
7605 // want to create a LUT. Otherwise, continue with the switch replacement.
7606 if (AnyLookupTables &&
7607 (!TTI.shouldBuildLookupTables() ||
7608 Fn->getFnAttribute(Kind: "no-jump-tables").getValueAsBool()))
7609 return false;
7610
7611 // In the early optimization pipeline, disable formation of lookup tables,
7612 // bit maps and mask checks, as they may inhibit further optimization.
7613 if (!ConvertSwitchToLookupTable &&
7614 (AnyLookupTables || AnyBitMaps || NeedMask))
7615 return false;
7616
7617 Builder.SetInsertPoint(SI);
7618 // TableIndex is the switch condition - TableIndexOffset if we don't
7619 // use the condition directly
7620 if (!UseSwitchConditionAsTableIndex) {
7621 // If the default is unreachable, all case values are s>= MinCaseVal. Then
7622 // we can try to attach nsw.
7623 bool MayWrap = true;
7624 if (!DefaultIsReachable) {
7625 APInt Res =
7626 MaxCaseVal->getValue().ssub_ov(RHS: MinCaseVal->getValue(), Overflow&: MayWrap);
7627 (void)Res;
7628 }
7629 TableIndex = Builder.CreateSub(LHS: SI->getCondition(), RHS: TableIndexOffset,
7630 Name: "switch.tableidx", /*HasNUW =*/false,
7631 /*HasNSW =*/!MayWrap);
7632 }
7633
7634 std::vector<DominatorTree::UpdateType> Updates;
7635
7636 // Compute the maximum table size representable by the integer type we are
7637 // switching upon.
7638 unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits();
7639 uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize;
7640 assert(MaxTableSize >= TableSize &&
7641 "It is impossible for a switch to have more entries than the max "
7642 "representable value of its input integer type's size.");
7643
7644 // Create the BB that does the lookups.
7645 Module &Mod = *CommonDest->getParent()->getParent();
7646 BasicBlock *LookupBB = BasicBlock::Create(
7647 Context&: Mod.getContext(), Name: "switch.lookup", Parent: CommonDest->getParent(), InsertBefore: CommonDest);
7648
7649 CondBrInst *RangeCheckBranch = nullptr;
7650 CondBrInst *CondBranch = nullptr;
7651
7652 Builder.SetInsertPoint(SI);
7653 const bool GeneratingCoveredLookupTable = (MaxTableSize == TableSize);
7654 if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
7655 Builder.CreateBr(Dest: LookupBB);
7656 if (DTU)
7657 Updates.push_back(x: {DominatorTree::Insert, BB, LookupBB});
7658 // Note: We call removeProdecessor later since we need to be able to get the
7659 // PHI value for the default case in case we're using a bit mask.
7660 } else {
7661 Value *Cmp = Builder.CreateICmpULT(
7662 LHS: TableIndex, RHS: ConstantInt::get(Ty: MinCaseVal->getType(), V: TableSize));
7663 RangeCheckBranch =
7664 Builder.CreateCondBr(Cond: Cmp, True: LookupBB, False: SI->getDefaultDest());
7665 CondBranch = RangeCheckBranch;
7666 if (DTU)
7667 Updates.push_back(x: {DominatorTree::Insert, BB, LookupBB});
7668 }
7669
7670 // Populate the BB that does the lookups.
7671 Builder.SetInsertPoint(LookupBB);
7672
7673 if (NeedMask) {
7674 // Before doing the lookup, we do the hole check. The LookupBB is therefore
7675 // re-purposed to do the hole check, and we create a new LookupBB.
7676 BasicBlock *MaskBB = LookupBB;
7677 MaskBB->setName("switch.hole_check");
7678 LookupBB = BasicBlock::Create(Context&: Mod.getContext(), Name: "switch.lookup",
7679 Parent: CommonDest->getParent(), InsertBefore: CommonDest);
7680
7681 // Make the mask's bitwidth at least 8-bit and a power-of-2 to avoid
7682 // unnecessary illegal types.
7683 uint64_t TableSizePowOf2 = NextPowerOf2(A: std::max(a: 7ULL, b: TableSize - 1ULL));
7684 APInt MaskInt(TableSizePowOf2, 0);
7685 APInt One(TableSizePowOf2, 1);
7686 // Build bitmask; fill in a 1 bit for every case.
7687 const ResultListTy &ResultList = ResultLists[PHIs[0]];
7688 for (const auto &Result : ResultList) {
7689 uint64_t Idx = (Result.first->getValue() - TableIndexOffset->getValue())
7690 .getLimitedValue();
7691 MaskInt |= One << Idx;
7692 }
7693 ConstantInt *TableMask = ConstantInt::get(Context&: Mod.getContext(), V: MaskInt);
7694
7695 // Get the TableIndex'th bit of the bitmask.
7696 // If this bit is 0 (meaning hole) jump to the default destination,
7697 // else continue with table lookup.
7698 IntegerType *MapTy = TableMask->getIntegerType();
7699 Value *MaskIndex =
7700 Builder.CreateZExtOrTrunc(V: TableIndex, DestTy: MapTy, Name: "switch.maskindex");
7701 Value *Shifted = Builder.CreateLShr(LHS: TableMask, RHS: MaskIndex, Name: "switch.shifted");
7702 Value *LoBit = Builder.CreateTrunc(
7703 V: Shifted, DestTy: Type::getInt1Ty(C&: Mod.getContext()), Name: "switch.lobit");
7704 CondBranch = Builder.CreateCondBr(Cond: LoBit, True: LookupBB, False: SI->getDefaultDest());
7705 if (DTU) {
7706 Updates.push_back(x: {DominatorTree::Insert, MaskBB, LookupBB});
7707 Updates.push_back(x: {DominatorTree::Insert, MaskBB, SI->getDefaultDest()});
7708 }
7709 Builder.SetInsertPoint(LookupBB);
7710 addPredecessorToBlock(Succ: SI->getDefaultDest(), NewPred: MaskBB, ExistPred: BB);
7711 }
7712
7713 if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
7714 // We cached PHINodes in PHIs. To avoid accessing deleted PHINodes later,
7715 // do not delete PHINodes here.
7716 SI->getDefaultDest()->removePredecessor(Pred: BB,
7717 /*KeepOneInputPHIs=*/true);
7718 if (DTU)
7719 Updates.push_back(x: {DominatorTree::Delete, BB, SI->getDefaultDest()});
7720 }
7721
7722 for (PHINode *PHI : PHIs) {
7723 const ResultListTy &ResultList = ResultLists[PHI];
7724 auto Replacement = PhiToReplacementMap.at(Val: PHI);
7725 auto *Result = Replacement.replaceSwitch(Index: TableIndex, Builder, DL, Func: Fn);
7726 // Do a small peephole optimization: re-use the switch table compare if
7727 // possible.
7728 if (!TableHasHoles && HasDefaultResults && RangeCheckBranch) {
7729 BasicBlock *PhiBlock = PHI->getParent();
7730 // Search for compare instructions which use the phi.
7731 for (auto *User : PHI->users()) {
7732 reuseTableCompare(PhiUser: User, PhiBlock, RangeCheckBranch,
7733 DefaultValue: Replacement.getDefaultValue(), Values: ResultList);
7734 }
7735 }
7736
7737 PHI->addIncoming(V: Result, BB: LookupBB);
7738 }
7739
7740 Builder.CreateBr(Dest: CommonDest);
7741 if (DTU)
7742 Updates.push_back(x: {DominatorTree::Insert, LookupBB, CommonDest});
7743
7744 SmallVector<uint32_t> BranchWeights;
7745 const bool HasBranchWeights = CondBranch && !ProfcheckDisableMetadataFixes &&
7746 extractBranchWeights(I: *SI, Weights&: BranchWeights);
7747 uint64_t ToLookupWeight = 0;
7748 uint64_t ToDefaultWeight = 0;
7749
7750 // Remove the switch.
7751 SmallPtrSet<BasicBlock *, 8> RemovedSuccessors;
7752 for (unsigned I = 0, E = SI->getNumSuccessors(); I < E; ++I) {
7753 BasicBlock *Succ = SI->getSuccessor(idx: I);
7754
7755 if (Succ == SI->getDefaultDest()) {
7756 if (HasBranchWeights)
7757 ToDefaultWeight += BranchWeights[I];
7758 continue;
7759 }
7760 Succ->removePredecessor(Pred: BB);
7761 if (DTU && RemovedSuccessors.insert(Ptr: Succ).second)
7762 Updates.push_back(x: {DominatorTree::Delete, BB, Succ});
7763 if (HasBranchWeights)
7764 ToLookupWeight += BranchWeights[I];
7765 }
7766 SI->eraseFromParent();
7767 if (HasBranchWeights)
7768 setFittedBranchWeights(I&: *CondBranch, Weights: {ToLookupWeight, ToDefaultWeight},
7769 /*IsExpected=*/false);
7770 if (DTU)
7771 DTU->applyUpdates(Updates);
7772
7773 if (NeedMask)
7774 ++NumLookupTablesHoles;
7775 return true;
7776}
7777
7778/// Try to transform a switch that has "holes" in it to a contiguous sequence
7779/// of cases.
7780///
7781/// A switch such as: switch(i) {case 5: case 9: case 13: case 17:} can be
7782/// range-reduced to: switch ((i-5) / 4) {case 0: case 1: case 2: case 3:}.
7783///
7784/// This converts a sparse switch into a dense switch which allows better
7785/// lowering and could also allow transforming into a lookup table.
7786static bool reduceSwitchRange(SwitchInst *SI, IRBuilder<> &Builder,
7787 const DataLayout &DL,
7788 const TargetTransformInfo &TTI) {
7789 auto *CondTy = cast<IntegerType>(Val: SI->getCondition()->getType());
7790 if (CondTy->getIntegerBitWidth() > 64 ||
7791 !DL.fitsInLegalInteger(Width: CondTy->getIntegerBitWidth()))
7792 return false;
7793 // Only bother with this optimization if there are more than 3 switch cases;
7794 // SDAG will only bother creating jump tables for 4 or more cases.
7795 if (SI->getNumCases() < 4)
7796 return false;
7797
7798 // This transform is agnostic to the signedness of the input or case values. We
7799 // can treat the case values as signed or unsigned. We can optimize more common
7800 // cases such as a sequence crossing zero {-4,0,4,8} if we interpret case values
7801 // as signed.
7802 SmallVector<int64_t,4> Values;
7803 for (const auto &C : SI->cases())
7804 Values.push_back(Elt: C.getCaseValue()->getValue().getSExtValue());
7805 llvm::sort(C&: Values);
7806
7807 // If the switch is already dense, there's nothing useful to do here.
7808 bool OptSize = SI->getFunction()->hasOptSize();
7809 if (isSwitchDense(Values, OptSize))
7810 return false;
7811
7812 // Find a Base and corresponding Shift that results in a dense switch range.
7813 // Values[0] is the local minimum.
7814 int64_t Base = Values[0];
7815 std::optional<unsigned> Shift;
7816 // Prefer Base=0 when shifting out common low zero bits still produces a dense
7817 // range, as this avoids an unnecessary `(condition - local_min)` expression.
7818 // However, avoiding the subtract can leave a wider reduced range than using
7819 // the local minimum, so require Base=0 to satisfy the stricter optsize
7820 // density threshold before falling back to the normal density policy for
7821 // local-min.
7822 if ((Shift = getDenseSwitchRangeReductionShift(Values, /*Base=*/0,
7823 /*OptSize=*/true)))
7824 Base = 0;
7825 else if (Base != 0)
7826 Shift = getDenseSwitchRangeReductionShift(Values, Base, OptSize);
7827
7828 if (!Shift)
7829 return false;
7830
7831 // The obvious transform is to shift the switch condition right and emit a
7832 // check that the condition actually cleanly divided by GCD, i.e.
7833 // C & (1 << Shift - 1) == 0
7834 // inserting a new CFG edge to handle the case where it didn't divide cleanly.
7835 //
7836 // A cheaper way of doing this is a simple ROTR(C, Shift). This performs the
7837 // shift and puts the shifted-off bits in the uppermost bits. If any of these
7838 // are nonzero then the switch condition will be very large and will hit the
7839 // default case.
7840 //
7841 // This transform can be done speculatively because it is so cheap - it
7842 // results in a single rotate operation being inserted.
7843
7844 auto *Ty = cast<IntegerType>(Val: SI->getCondition()->getType());
7845 Builder.SetInsertPoint(SI);
7846 Value *Sub = SI->getCondition();
7847 if (Base != 0)
7848 Sub = Builder.CreateSub(LHS: Sub, RHS: ConstantInt::getSigned(Ty, V: Base));
7849 Value *Rot = Builder.CreateIntrinsic(
7850 RetTy: Ty, ID: Intrinsic::fshl,
7851 Args: {Sub, Sub, ConstantInt::get(Ty, V: Ty->getBitWidth() - *Shift)});
7852 SI->replaceUsesOfWith(From: SI->getCondition(), To: Rot);
7853
7854 for (auto Case : SI->cases()) {
7855 auto *Orig = Case.getCaseValue();
7856 auto Sub = Orig->getValue() - APInt(Ty->getBitWidth(), Base, true);
7857 Case.setValue(cast<ConstantInt>(Val: ConstantInt::get(Ty, V: Sub.lshr(shiftAmt: *Shift))));
7858 }
7859 return true;
7860}
7861
7862/// Tries to transform the switch when the condition is umin with a constant.
7863/// In that case, the default branch can be replaced by the constant's branch.
7864/// This method also removes dead cases when the simplification cannot replace
7865/// the default branch.
7866///
7867/// For example:
7868/// switch(umin(a, 3)) {
7869/// case 0:
7870/// case 1:
7871/// case 2:
7872/// case 3:
7873/// case 4:
7874/// // ...
7875/// default:
7876/// unreachable
7877/// }
7878///
7879/// Transforms into:
7880///
7881/// switch(a) {
7882/// case 0:
7883/// case 1:
7884/// case 2:
7885/// default:
7886/// // This is case 3
7887/// }
7888static bool simplifySwitchWhenUMin(SwitchInst *SI, DomTreeUpdater *DTU) {
7889 Value *A;
7890 ConstantInt *Constant;
7891
7892 if (!match(V: SI->getCondition(), P: m_UMin(Op0: m_Value(V&: A), Op1: m_ConstantInt(CI&: Constant))))
7893 return false;
7894
7895 SmallVector<DominatorTree::UpdateType> Updates;
7896 SwitchInstProfUpdateWrapper SIW(*SI);
7897 BasicBlock *BB = SIW->getParent();
7898
7899 // Dead cases are removed even when the simplification fails.
7900 // A case is dead when its value is higher than the Constant.
7901 for (auto I = SI->case_begin(), E = SI->case_end(); I != E;) {
7902 if (!I->getCaseValue()->getValue().ugt(RHS: Constant->getValue())) {
7903 ++I;
7904 continue;
7905 }
7906 BasicBlock *DeadCaseBB = I->getCaseSuccessor();
7907 DeadCaseBB->removePredecessor(Pred: BB);
7908 I = SIW.removeCase(I);
7909 E = SIW->case_end();
7910 if (!is_contained(Range: successors(BB), Element: DeadCaseBB))
7911 Updates.push_back(Elt: {DominatorTree::Delete, BB, DeadCaseBB});
7912 }
7913
7914 auto Case = SI->findCaseValue(C: Constant);
7915 // If the case value is not found, `findCaseValue` returns the default case.
7916 // In this scenario, since there is no explicit `case 3:`, the simplification
7917 // fails. The simplification also fails when the switch’s default destination
7918 // is reachable.
7919 if (!SI->defaultDestUnreachable() || Case == SI->case_default()) {
7920 if (DTU)
7921 DTU->applyUpdates(Updates);
7922 return !Updates.empty();
7923 }
7924
7925 BasicBlock *Unreachable = SI->getDefaultDest();
7926 SIW.replaceDefaultDest(I: Case);
7927 SIW.removeCase(I: Case);
7928 SIW->setCondition(A);
7929
7930 Updates.push_back(Elt: {DominatorTree::Delete, BB, Unreachable});
7931
7932 if (DTU)
7933 DTU->applyUpdates(Updates);
7934
7935 return true;
7936}
7937
7938static bool simplifySwitchDefaultBranch(SwitchInst *SI, DomTreeUpdater *DTU,
7939 const DataLayout &DL,
7940 AssumptionCache *AC) {
7941 assert(SI);
7942 if (SI->defaultDestUnreachable())
7943 return false;
7944
7945 // If it can be proved that the switch condition takes some concrete value
7946 // in the default block, we can make some nice simplifications to the
7947 // switch.
7948 BasicBlock *Default = SI->getDefaultDest();
7949 const Instruction *CxtI = &*Default->getFirstNonPHIIt();
7950 const KnownBits Known = computeKnownBits(
7951 V: SI->getCondition(),
7952 Q: SimplifyQuery(DL, /*DT=*/nullptr, AC, CxtI).allowEphemerals(AllowEphemerals: true));
7953 if (!Known.isConstant())
7954 return false;
7955
7956 // At this point, we know that only one value can be mapped to the
7957 // default block. So, if a case doesn't exist for it already, we
7958 // can create one pointing to the default block.
7959 ConstantInt *CaseVal =
7960 ConstantInt::get(Context&: SI->getContext(), V: Known.getConstant());
7961 const llvm::SwitchInst::CaseIt CaseIt = SI->findCaseValue(C: CaseVal);
7962 if (CaseIt == SI->case_default()) {
7963 SwitchInstProfUpdateWrapper SIW(*SI);
7964 SIW.addCase(OnVal: CaseVal, Dest: Default, W: SIW.getSuccessorWeight(idx: 0));
7965 SIW.setSuccessorWeight(idx: 0, W: 0);
7966 }
7967 // If there is a pre-existing case for the constant, the default branch
7968 // will be removed rather than being moved. Thus, we are removing an edge
7969 // in the CFG, and need to update any PHIs in the default block.
7970 createUnreachableSwitchDefault(Switch: SI, DTU, /*RemoveOrigDefaultBlock=*/CaseIt !=
7971 SI->case_default());
7972
7973 assert(SI->getNumCases() > 0 && "Switch should have at least one case");
7974 assert(SI->findCaseValue(CaseVal) != SI->case_default() &&
7975 "Proven value should have a dedicated case");
7976 assert(SI->defaultDestUnreachable());
7977 return true;
7978}
7979
7980/// Tries to transform switch of powers of two to reduce switch range.
7981/// For example, switch like:
7982/// switch (C) { case 1: case 2: case 64: case 128: }
7983/// will be transformed to:
7984/// switch (count_trailing_zeros(C)) { case 0: case 1: case 6: case 7: }
7985///
7986/// This transformation allows better lowering and may transform the switch
7987/// instruction into a sequence of bit manipulation and a smaller
7988/// log2(C)-indexed value table (instead of traditionally emitting a load of the
7989/// address of the jump target, and indirectly jump to it).
7990static bool simplifySwitchOfPowersOfTwo(SwitchInst *SI, IRBuilder<> &Builder,
7991 DomTreeUpdater *DTU,
7992 const DataLayout &DL,
7993 const TargetTransformInfo &TTI) {
7994 Value *Condition = SI->getCondition();
7995 LLVMContext &Context = SI->getContext();
7996 auto *CondTy = cast<IntegerType>(Val: Condition->getType());
7997
7998 if (CondTy->getIntegerBitWidth() > 64 ||
7999 !DL.fitsInLegalInteger(Width: CondTy->getIntegerBitWidth()))
8000 return false;
8001
8002 // Ensure trailing zeroes count intrinsic emission is not too expensive.
8003 IntrinsicCostAttributes Attrs(Intrinsic::cttz, CondTy,
8004 {Condition, ConstantInt::getTrue(Context)});
8005 if (TTI.getIntrinsicInstrCost(ICA: Attrs, CostKind: TTI::TCK_SizeAndLatency) >
8006 TTI::TCC_Basic * 2)
8007 return false;
8008
8009 // Only bother with this optimization if there are more than 3 switch cases.
8010 // SDAG will start emitting jump tables for 4 or more cases.
8011 if (SI->getNumCases() < 4)
8012 return false;
8013
8014 // Check that switch cases are powers of two.
8015 SmallVector<uint64_t, 4> Values;
8016 for (const auto &Case : SI->cases()) {
8017 uint64_t CaseValue = Case.getCaseValue()->getValue().getZExtValue();
8018 if (llvm::has_single_bit(Value: CaseValue))
8019 Values.push_back(Elt: CaseValue);
8020 else
8021 return false;
8022 }
8023
8024 // isSwichDense requires case values to be sorted.
8025 llvm::sort(C&: Values);
8026 if (!isSwitchDense(NumCases: Values.size(),
8027 CaseRange: llvm::countr_zero(Val: Values.back()) -
8028 llvm::countr_zero(Val: Values.front()) + 1,
8029 OptSize: SI->getFunction()->hasOptSize()))
8030 // Transform is unable to generate dense switch.
8031 return false;
8032
8033 Builder.SetInsertPoint(SI);
8034
8035 if (!SI->defaultDestUnreachable()) {
8036 // Let non-power-of-two inputs jump to the default case, when the latter is
8037 // reachable.
8038 auto *PopC = Builder.CreateUnaryIntrinsic(ID: Intrinsic::ctpop, Op: Condition);
8039 auto *IsPow2 = Builder.CreateICmpEQ(LHS: PopC, RHS: ConstantInt::get(Ty: CondTy, V: 1));
8040
8041 auto *OrigBB = SI->getParent();
8042 auto *DefaultCaseBB = SI->getDefaultDest();
8043 BasicBlock *SplitBB = SplitBlock(Old: OrigBB, SplitPt: SI, DTU);
8044 auto It = OrigBB->getTerminator()->getIterator();
8045 SmallVector<uint32_t> Weights;
8046 auto HasWeights =
8047 !ProfcheckDisableMetadataFixes && extractBranchWeights(I: *SI, Weights);
8048 auto *BI = CondBrInst::Create(Cond: IsPow2, IfTrue: SplitBB, IfFalse: DefaultCaseBB, InsertBefore: It);
8049 if (HasWeights && any_of(Range&: Weights, P: not_equal_to(Arg: 0))) {
8050 // IsPow2 covers a subset of the cases in which we'd go to the default
8051 // label. The other is those powers of 2 that don't appear in the case
8052 // statement. We don't know the distribution of the values coming in, so
8053 // the safest is to split 50-50 the original probability to `default`.
8054 uint64_t OrigDenominator =
8055 sum_of(Range: map_range(C&: Weights, F: StaticCastTo<uint64_t>));
8056 SmallVector<uint64_t> NewWeights(2);
8057 NewWeights[1] = Weights[0] / 2;
8058 NewWeights[0] = OrigDenominator - NewWeights[1];
8059 setFittedBranchWeights(I&: *BI, Weights: NewWeights, /*IsExpected=*/false);
8060 // The probability of executing the default block stays constant. It was
8061 // p_d = Weights[0] / OrigDenominator
8062 // we rewrite as W/D
8063 // We want to find the probability of the default branch of the switch
8064 // statement. Let's call it X. We have W/D = W/2D + X * (1-W/2D)
8065 // i.e. the original probability is the probability we go to the default
8066 // branch from the BI branch, or we take the default branch on the SI.
8067 // Meaning X = W / (2D - W), or (W/2) / (D - W/2)
8068 // This matches using W/2 for the default branch probability numerator and
8069 // D-W/2 as the denominator.
8070 Weights[0] = NewWeights[1];
8071 uint64_t CasesDenominator = OrigDenominator - Weights[0];
8072 for (auto &W : drop_begin(RangeOrContainer&: Weights))
8073 W = NewWeights[0] * static_cast<double>(W) / CasesDenominator;
8074
8075 setBranchWeights(I&: *SI, Weights, /*IsExpected=*/false);
8076 }
8077 // BI is handling the default case for SI, and so should share its DebugLoc.
8078 BI->setDebugLoc(SI->getDebugLoc());
8079 It->eraseFromParent();
8080
8081 addPredecessorToBlock(Succ: DefaultCaseBB, NewPred: OrigBB, ExistPred: SplitBB);
8082 if (DTU)
8083 DTU->applyUpdates(Updates: {{DominatorTree::Insert, OrigBB, DefaultCaseBB}});
8084 }
8085
8086 // Replace each case with its trailing zeros number.
8087 for (auto &Case : SI->cases()) {
8088 auto *OrigValue = Case.getCaseValue();
8089 Case.setValue(ConstantInt::get(Ty: OrigValue->getIntegerType(),
8090 V: OrigValue->getValue().countr_zero()));
8091 }
8092
8093 // Replace condition with its trailing zeros number.
8094 auto *ConditionTrailingZeros = Builder.CreateIntrinsic(
8095 ID: Intrinsic::cttz, OverloadTypes: {CondTy}, Args: {Condition, ConstantInt::getTrue(Context)});
8096
8097 SI->setCondition(ConditionTrailingZeros);
8098
8099 return true;
8100}
8101
8102/// Fold switch over ucmp/scmp intrinsic to br if two of the switch arms have
8103/// the same destination.
8104static bool simplifySwitchOfCmpIntrinsic(SwitchInst *SI, IRBuilderBase &Builder,
8105 DomTreeUpdater *DTU) {
8106 auto *Cmp = dyn_cast<CmpIntrinsic>(Val: SI->getCondition());
8107 if (!Cmp || !Cmp->hasOneUse())
8108 return false;
8109
8110 SmallVector<uint32_t, 4> Weights;
8111 bool HasWeights = extractBranchWeights(ProfileData: getBranchWeightMDNode(I: *SI), Weights);
8112 if (!HasWeights)
8113 Weights.resize(N: 4); // Avoid checking HasWeights everywhere.
8114
8115 // Normalize to [us]cmp == Res ? Succ : OtherSucc.
8116 int64_t Res;
8117 BasicBlock *Succ, *OtherSucc;
8118 uint32_t SuccWeight = 0, OtherSuccWeight = 0;
8119 BasicBlock *Unreachable = nullptr;
8120
8121 if (SI->getNumCases() == 2) {
8122 // Find which of 1, 0 or -1 is missing (handled by default dest).
8123 SmallSet<int64_t, 3> Missing;
8124 Missing.insert(V: 1);
8125 Missing.insert(V: 0);
8126 Missing.insert(V: -1);
8127
8128 Succ = SI->getDefaultDest();
8129 SuccWeight = Weights[0];
8130 OtherSucc = nullptr;
8131 for (auto &Case : SI->cases()) {
8132 std::optional<int64_t> Val =
8133 Case.getCaseValue()->getValue().trySExtValue();
8134 if (!Val)
8135 return false;
8136 if (!Missing.erase(V: *Val))
8137 return false;
8138 if (OtherSucc && OtherSucc != Case.getCaseSuccessor())
8139 return false;
8140 OtherSucc = Case.getCaseSuccessor();
8141 OtherSuccWeight += Weights[Case.getSuccessorIndex()];
8142 }
8143
8144 assert(Missing.size() == 1 && "Should have one case left");
8145 Res = *Missing.begin();
8146 } else if (SI->getNumCases() == 3 && SI->defaultDestUnreachable()) {
8147 // Normalize so that Succ is taken once and OtherSucc twice.
8148 Unreachable = SI->getDefaultDest();
8149 Succ = OtherSucc = nullptr;
8150 for (auto &Case : SI->cases()) {
8151 BasicBlock *NewSucc = Case.getCaseSuccessor();
8152 uint32_t Weight = Weights[Case.getSuccessorIndex()];
8153 if (!OtherSucc || OtherSucc == NewSucc) {
8154 OtherSucc = NewSucc;
8155 OtherSuccWeight += Weight;
8156 } else if (!Succ) {
8157 Succ = NewSucc;
8158 SuccWeight = Weight;
8159 } else if (Succ == NewSucc) {
8160 std::swap(a&: Succ, b&: OtherSucc);
8161 std::swap(a&: SuccWeight, b&: OtherSuccWeight);
8162 } else
8163 return false;
8164 }
8165 for (auto &Case : SI->cases()) {
8166 std::optional<int64_t> Val =
8167 Case.getCaseValue()->getValue().trySExtValue();
8168 if (!Val || (Val != 1 && Val != 0 && Val != -1))
8169 return false;
8170 if (Case.getCaseSuccessor() == Succ) {
8171 Res = *Val;
8172 break;
8173 }
8174 }
8175 } else {
8176 return false;
8177 }
8178
8179 // Determine predicate for the missing case.
8180 ICmpInst::Predicate Pred;
8181 switch (Res) {
8182 case 1:
8183 Pred = ICmpInst::ICMP_UGT;
8184 break;
8185 case 0:
8186 Pred = ICmpInst::ICMP_EQ;
8187 break;
8188 case -1:
8189 Pred = ICmpInst::ICMP_ULT;
8190 break;
8191 }
8192 if (Cmp->isSigned())
8193 Pred = ICmpInst::getSignedPredicate(Pred);
8194
8195 MDNode *NewWeights = nullptr;
8196 if (HasWeights)
8197 NewWeights = MDBuilder(SI->getContext())
8198 .createBranchWeights(TrueWeight: SuccWeight, FalseWeight: OtherSuccWeight);
8199
8200 BasicBlock *BB = SI->getParent();
8201 Builder.SetInsertPoint(SI->getIterator());
8202 Value *ICmp = Builder.CreateICmp(P: Pred, LHS: Cmp->getLHS(), RHS: Cmp->getRHS());
8203 Builder.CreateCondBr(Cond: ICmp, True: Succ, False: OtherSucc, BranchWeights: NewWeights,
8204 Unpredictable: SI->getMetadata(KindID: LLVMContext::MD_unpredictable));
8205 OtherSucc->removePredecessor(Pred: BB);
8206 if (Unreachable)
8207 Unreachable->removePredecessor(Pred: BB);
8208 SI->eraseFromParent();
8209 Cmp->eraseFromParent();
8210 if (DTU && Unreachable)
8211 DTU->applyUpdates(Updates: {{DominatorTree::Delete, BB, Unreachable}});
8212 return true;
8213}
8214
8215/// Checking whether two BBs are equal depends on the contents of the
8216/// BasicBlock and the incoming values of their successor PHINodes.
8217/// PHINode::getIncomingValueForBlock is O(|Preds|), so we'd like to avoid
8218/// calling this function on each BasicBlock every time isEqual is called,
8219/// especially since the same BasicBlock may be passed as an argument multiple
8220/// times. To do this, we can precompute a map of PHINode -> Pred BasicBlock ->
8221/// IncomingValue and add it in the Wrapper so isEqual can do O(1) checking
8222/// of the incoming values.
8223struct EqualBBWrapper {
8224 BasicBlock *BB;
8225
8226 // One Phi usually has < 8 incoming values.
8227 using BB2ValueMap = SmallDenseMap<BasicBlock *, Value *, 8>;
8228 using Phi2IVsMap = DenseMap<PHINode *, BB2ValueMap>;
8229 Phi2IVsMap *PhiPredIVs;
8230
8231 // We only merge the identical non-entry BBs with
8232 // - terminator unconditional br to Succ (pending relaxation),
8233 // - does not have address taken / weird control.
8234 static bool canBeMerged(const BasicBlock *BB) {
8235 assert(BB && "Expected non-null BB");
8236 // Entry block cannot be eliminated or have predecessors.
8237 if (BB->isEntryBlock())
8238 return false;
8239
8240 // Single successor and must be Succ.
8241 // FIXME: Relax that the terminator is a BranchInst by checking for equality
8242 // on other kinds of terminators. We decide to only support unconditional
8243 // branches for now for compile time reasons.
8244 auto *BI = dyn_cast<UncondBrInst>(Val: BB->getTerminator());
8245 if (!BI)
8246 return false;
8247
8248 // Avoid blocks that are "address-taken" (blockaddress) or have unusual
8249 // uses.
8250 if (BB->hasAddressTaken() || BB->isEHPad())
8251 return false;
8252
8253 // TODO: relax this condition to merge equal blocks with >1 instructions?
8254 // Here, we use a O(1) form of the O(n) comparison of `size() != 1`.
8255 if (&BB->front() != &BB->back())
8256 return false;
8257
8258 // The BB must have at least one predecessor.
8259 if (pred_empty(BB))
8260 return false;
8261
8262 return true;
8263 }
8264};
8265
8266template <> struct llvm::DenseMapInfo<const EqualBBWrapper *> {
8267 static unsigned getHashValue(const EqualBBWrapper *EBW) {
8268 BasicBlock *BB = EBW->BB;
8269 UncondBrInst *BI = cast<UncondBrInst>(Val: BB->getTerminator());
8270 assert(BB->size() == 1 && "Expected just a single branch in the BB");
8271
8272 // Since we assume the BB is just a single UncondBrInst with a single
8273 // successor, we hash as the BB and the incoming Values of its successor
8274 // PHIs. Initially, we tried to just use the successor BB as the hash, but
8275 // including the incoming PHI values leads to better performance.
8276 // We also tried to build a map from BB -> Succs.IncomingValues ahead of
8277 // time and passing it in EqualBBWrapper, but this slowed down the average
8278 // compile time without having any impact on the worst case compile time.
8279 BasicBlock *Succ = BI->getSuccessor();
8280 auto PhiValsForBB = map_range(C: Succ->phis(), F: [&](PHINode &Phi) {
8281 return (*EBW->PhiPredIVs)[&Phi][BB];
8282 });
8283 return hash_combine(args: Succ, args: hash_combine_range(R&: PhiValsForBB));
8284 }
8285 static bool isEqual(const EqualBBWrapper *LHS, const EqualBBWrapper *RHS) {
8286 BasicBlock *A = LHS->BB;
8287 BasicBlock *B = RHS->BB;
8288
8289 // FIXME: we checked that the size of A and B are both 1 in
8290 // mergeIdenticalUncondBBs to make the Case list smaller to
8291 // improve performance. If we decide to support BasicBlocks with more
8292 // than just a single instruction, we need to check that A.size() ==
8293 // B.size() here, and we need to check more than just the BranchInsts
8294 // for equality.
8295
8296 UncondBrInst *ABI = cast<UncondBrInst>(Val: A->getTerminator());
8297 UncondBrInst *BBI = cast<UncondBrInst>(Val: B->getTerminator());
8298 if (ABI->getSuccessor() != BBI->getSuccessor())
8299 return false;
8300
8301 // Need to check that PHIs in successor have matching values.
8302 BasicBlock *Succ = ABI->getSuccessor();
8303 auto IfPhiIVMatch = [&](PHINode &Phi) {
8304 // Replace O(|Pred|) Phi.getIncomingValueForBlock with this O(1) hashmap
8305 // query.
8306 auto &PredIVs = (*LHS->PhiPredIVs)[&Phi];
8307 return PredIVs[A] == PredIVs[B];
8308 };
8309 return all_of(Range: Succ->phis(), P: IfPhiIVMatch);
8310 }
8311};
8312
8313// Merge identical BBs into one of them.
8314static bool mergeIdenticalBBs(ArrayRef<BasicBlock *> Candidates,
8315 DomTreeUpdater *DTU) {
8316 if (Candidates.size() < 2)
8317 return false;
8318
8319 // Build Cases. Skip BBs that are not candidates for simplification. Mark
8320 // PHINodes which need to be processed into PhiPredIVs. We decide to process
8321 // an entire PHI at once after the loop, opposed to calling
8322 // getIncomingValueForBlock inside this loop, since each call to
8323 // getIncomingValueForBlock is O(|Preds|).
8324 EqualBBWrapper::Phi2IVsMap PhiPredIVs;
8325 SmallVector<EqualBBWrapper> BBs2Merge;
8326 BBs2Merge.reserve(N: Candidates.size());
8327 SmallSetVector<PHINode *, 8> Phis;
8328
8329 for (BasicBlock *BB : Candidates) {
8330 BasicBlock *Succ = BB->getSingleSuccessor();
8331 assert(Succ && "Expected unconditional BB");
8332 BBs2Merge.emplace_back(Args: EqualBBWrapper{.BB: BB, .PhiPredIVs: &PhiPredIVs});
8333 Phis.insert_range(R: make_pointer_range(Range: Succ->phis()));
8334 }
8335
8336 // Precompute a data structure to improve performance of isEqual for
8337 // EqualBBWrapper.
8338 PhiPredIVs.reserve(NumEntries: Phis.size());
8339 for (PHINode *Phi : Phis) {
8340 auto &IVs =
8341 PhiPredIVs.try_emplace(Key: Phi, Args: Phi->getNumIncomingValues()).first->second;
8342 // Pre-fill all incoming for O(1) lookup as Phi.getIncomingValueForBlock is
8343 // O(|Pred|).
8344 for (auto &IV : Phi->incoming_values())
8345 IVs.insert(KV: {Phi->getIncomingBlock(U: IV), IV.get()});
8346 }
8347
8348 // Group duplicates using DenseSet with custom equality/hashing.
8349 // Build a set such that if the EqualBBWrapper exists in the set and another
8350 // EqualBBWrapper isEqual, then the equivalent EqualBBWrapper which is not in
8351 // the set should be replaced with the one in the set. If the EqualBBWrapper
8352 // is not in the set, then it should be added to the set so other
8353 // EqualBBWrapper can check against it in the same manner. We use
8354 // EqualBBWrapper instead of just BasicBlock because we'd like to pass around
8355 // information to isEquality, getHashValue, and when doing the replacement
8356 // with better performance.
8357 DenseSet<const EqualBBWrapper *> Keep;
8358 Keep.reserve(Size: BBs2Merge.size());
8359
8360 SmallVector<DominatorTree::UpdateType> Updates;
8361 Updates.reserve(N: BBs2Merge.size() * 2);
8362
8363 bool MadeChange = false;
8364
8365 // Helper: redirect all edges X -> DeadPred to X -> LivePred.
8366 auto RedirectIncomingEdges = [&](BasicBlock *Dead, BasicBlock *Live) {
8367 SmallSetVector<BasicBlock *, 8> DeadPreds(llvm::from_range,
8368 predecessors(BB: Dead));
8369 if (DTU) {
8370 // All predecessors of DeadPred (except the common predecessor) will be
8371 // moved to LivePred.
8372 Updates.reserve(N: Updates.size() + DeadPreds.size() * 2);
8373 SmallPtrSet<BasicBlock *, 16> LivePreds(llvm::from_range,
8374 predecessors(BB: Live));
8375 for (BasicBlock *PredOfDead : DeadPreds) {
8376 // Do not modify those common predecessors of DeadPred and LivePred.
8377 if (!LivePreds.contains(Ptr: PredOfDead))
8378 Updates.push_back(Elt: {DominatorTree::Insert, PredOfDead, Live});
8379 Updates.push_back(Elt: {DominatorTree::Delete, PredOfDead, Dead});
8380 }
8381 }
8382 LLVM_DEBUG(dbgs() << "Replacing duplicate pred BB ";
8383 Dead->printAsOperand(dbgs()); dbgs() << " with pred ";
8384 Live->printAsOperand(dbgs()); dbgs() << " for ";
8385 Live->getSingleSuccessor()->printAsOperand(dbgs());
8386 dbgs() << "\n");
8387 // Replace successors in all predecessors of DeadPred.
8388 for (BasicBlock *PredOfDead : DeadPreds) {
8389 Instruction *T = PredOfDead->getTerminator();
8390 T->replaceSuccessorWith(OldBB: Dead, NewBB: Live);
8391 }
8392 };
8393
8394 // Try to eliminate duplicate predecessors.
8395 for (const auto &EBW : BBs2Merge) {
8396 // EBW is a candidate for simplification. If we find a duplicate BB,
8397 // replace it.
8398 const auto &[It, Inserted] = Keep.insert(V: &EBW);
8399 if (Inserted)
8400 continue;
8401
8402 // Found duplicate: merge P into canonical predecessor It->Pred.
8403 BasicBlock *KeepBB = (*It)->BB;
8404 BasicBlock *DeadBB = EBW.BB;
8405
8406 // Avoid merging a BB with itself.
8407 if (KeepBB == DeadBB)
8408 continue;
8409
8410 // Redirect all edges into DeadPred to KeepPred.
8411 RedirectIncomingEdges(DeadBB, KeepBB);
8412
8413 // Now DeadBB should become unreachable; leave DCE to later,
8414 // but we can try to simplify it if it only branches to Succ.
8415 // (We won't erase here to keep the routine simple and DT-safe.)
8416 assert(pred_empty(DeadBB) && "DeadBB should be unreachable.");
8417 MadeChange = true;
8418 }
8419
8420 if (DTU && !Updates.empty())
8421 DTU->applyUpdates(Updates);
8422
8423 return MadeChange;
8424}
8425
8426bool SimplifyCFGOpt::simplifyDuplicateSwitchArms(SwitchInst *SI,
8427 DomTreeUpdater *DTU) {
8428 // Collect candidate switch-arms top-down.
8429 SmallSetVector<BasicBlock *, 16> FilteredArms(
8430 llvm::from_range,
8431 make_filter_range(Range: successors(I: SI), Pred: EqualBBWrapper::canBeMerged));
8432 return mergeIdenticalBBs(Candidates: FilteredArms.getArrayRef(), DTU);
8433}
8434
8435bool SimplifyCFGOpt::simplifyDuplicatePredecessors(BasicBlock *BB,
8436 DomTreeUpdater *DTU) {
8437 // Need at least 2 predecessors to do anything.
8438 if (!BB || !BB->hasNPredecessorsOrMore(N: 2))
8439 return false;
8440
8441 // Compilation time consideration: retain the canonical loop, otherwise, we
8442 // require more time in the later loop canonicalization.
8443 if (Options.NeedCanonicalLoop && is_contained(Range&: LoopHeaders, Element: BB))
8444 return false;
8445
8446 // Collect candidate predecessors bottom-up.
8447 SmallSetVector<BasicBlock *, 8> FilteredPreds(
8448 llvm::from_range,
8449 make_filter_range(Range: predecessors(BB), Pred: EqualBBWrapper::canBeMerged));
8450 return mergeIdenticalBBs(Candidates: FilteredPreds.getArrayRef(), DTU);
8451}
8452
8453bool SimplifyCFGOpt::simplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) {
8454 BasicBlock *BB = SI->getParent();
8455
8456 if (isValueEqualityComparison(TI: SI)) {
8457 // If we only have one predecessor, and if it is a branch on this value,
8458 // see if that predecessor totally determines the outcome of this switch.
8459 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
8460 if (simplifyEqualityComparisonWithOnlyPredecessor(TI: SI, Pred: OnlyPred, Builder))
8461 return requestResimplify();
8462
8463 Value *Cond = SI->getCondition();
8464 if (SelectInst *Select = dyn_cast<SelectInst>(Val: Cond))
8465 if (simplifySwitchOnSelect(SI, Select))
8466 return requestResimplify();
8467
8468 // If the block only contains the switch, see if we can fold the block
8469 // away into any preds.
8470 if (SI == &*BB->begin())
8471 if (foldValueComparisonIntoPredecessors(TI: SI, Builder))
8472 return requestResimplify();
8473 }
8474
8475 // Try to transform the switch into an icmp and a branch.
8476 // The conversion from switch to comparison may lose information on
8477 // impossible switch values, so disable it early in the pipeline.
8478 if (Options.ConvertSwitchRangeToICmp && turnSwitchRangeIntoICmp(SI, Builder))
8479 return requestResimplify();
8480
8481 // Remove unreachable cases.
8482 if (eliminateDeadSwitchCases(SI, DTU, AC: Options.AC, DL))
8483 return requestResimplify();
8484
8485 if (simplifySwitchOfCmpIntrinsic(SI, Builder, DTU))
8486 return requestResimplify();
8487
8488 if (trySwitchToSelect(SI, Builder, DTU, DL, TTI))
8489 return requestResimplify();
8490
8491 if (Options.ForwardSwitchCondToPhi && forwardSwitchConditionToPHI(SI))
8492 return requestResimplify();
8493
8494 // The conversion of switches to arithmetic or lookup table is disabled in
8495 // the early optimization pipeline, as it may lose information or make the
8496 // resulting code harder to analyze.
8497 if (Options.ConvertSwitchToArithmetic || Options.ConvertSwitchToLookupTable)
8498 if (simplifySwitchLookup(SI, Builder, DTU, DL, TTI,
8499 ConvertSwitchToLookupTable: Options.ConvertSwitchToLookupTable))
8500 return requestResimplify();
8501
8502 if (simplifySwitchOfPowersOfTwo(SI, Builder, DTU, DL, TTI))
8503 return requestResimplify();
8504
8505 if (reduceSwitchRange(SI, Builder, DL, TTI))
8506 return requestResimplify();
8507
8508 if (HoistCommon &&
8509 hoistCommonCodeFromSuccessors(TI: SI, AllInstsEqOnly: !Options.HoistCommonInsts))
8510 return requestResimplify();
8511
8512 // We can merge identical switch arms early to enhance more aggressive
8513 // optimization on switch.
8514 if (simplifyDuplicateSwitchArms(SI, DTU))
8515 return requestResimplify();
8516
8517 if (simplifySwitchWhenUMin(SI, DTU))
8518 return requestResimplify();
8519
8520 if (simplifySwitchDefaultBranch(SI, DTU, DL, AC: Options.AC))
8521 return requestResimplify();
8522
8523 return false;
8524}
8525
8526bool SimplifyCFGOpt::simplifyIndirectBr(IndirectBrInst *IBI) {
8527 BasicBlock *BB = IBI->getParent();
8528 bool Changed = false;
8529 SmallVector<uint32_t> BranchWeights;
8530 const bool HasBranchWeights = !ProfcheckDisableMetadataFixes &&
8531 extractBranchWeights(I: *IBI, Weights&: BranchWeights);
8532
8533 DenseMap<const BasicBlock *, uint64_t> TargetWeight;
8534 if (HasBranchWeights)
8535 for (size_t I = 0, E = IBI->getNumDestinations(); I < E; ++I)
8536 TargetWeight[IBI->getDestination(i: I)] += BranchWeights[I];
8537
8538 // Eliminate redundant destinations.
8539 SmallPtrSet<Value *, 8> Succs;
8540 SmallSetVector<BasicBlock *, 8> RemovedSuccs;
8541 for (unsigned I = 0, E = IBI->getNumDestinations(); I != E; ++I) {
8542 BasicBlock *Dest = IBI->getDestination(i: I);
8543 if (!Dest->hasAddressTaken() || !Succs.insert(Ptr: Dest).second) {
8544 if (!Dest->hasAddressTaken())
8545 RemovedSuccs.insert(X: Dest);
8546 Dest->removePredecessor(Pred: BB);
8547 IBI->removeDestination(i: I);
8548 --I;
8549 --E;
8550 Changed = true;
8551 }
8552 }
8553
8554 if (DTU) {
8555 std::vector<DominatorTree::UpdateType> Updates;
8556 Updates.reserve(n: RemovedSuccs.size());
8557 for (auto *RemovedSucc : RemovedSuccs)
8558 Updates.push_back(x: {DominatorTree::Delete, BB, RemovedSucc});
8559 DTU->applyUpdates(Updates);
8560 }
8561
8562 if (IBI->getNumDestinations() == 0) {
8563 // If the indirectbr has no successors, change it to unreachable.
8564 new UnreachableInst(IBI->getContext(), IBI->getIterator());
8565 eraseTerminatorAndDCECond(TI: IBI);
8566 return true;
8567 }
8568
8569 if (IBI->getNumDestinations() == 1) {
8570 // If the indirectbr has one successor, change it to a direct branch.
8571 UncondBrInst::Create(Target: IBI->getDestination(i: 0), InsertBefore: IBI->getIterator());
8572 eraseTerminatorAndDCECond(TI: IBI);
8573 return true;
8574 }
8575 if (HasBranchWeights) {
8576 SmallVector<uint64_t> NewBranchWeights(IBI->getNumDestinations());
8577 for (size_t I = 0, E = IBI->getNumDestinations(); I < E; ++I)
8578 NewBranchWeights[I] += TargetWeight.find(Val: IBI->getDestination(i: I))->second;
8579 setFittedBranchWeights(I&: *IBI, Weights: NewBranchWeights, /*IsExpected=*/false);
8580 }
8581 if (SelectInst *SI = dyn_cast<SelectInst>(Val: IBI->getAddress())) {
8582 if (simplifyIndirectBrOnSelect(IBI, SI))
8583 return requestResimplify();
8584 }
8585 return Changed;
8586}
8587
8588/// Given an block with only a single landing pad and a unconditional branch
8589/// try to find another basic block which this one can be merged with. This
8590/// handles cases where we have multiple invokes with unique landing pads, but
8591/// a shared handler.
8592///
8593/// We specifically choose to not worry about merging non-empty blocks
8594/// here. That is a PRE/scheduling problem and is best solved elsewhere. In
8595/// practice, the optimizer produces empty landing pad blocks quite frequently
8596/// when dealing with exception dense code. (see: instcombine, gvn, if-else
8597/// sinking in this file)
8598///
8599/// This is primarily a code size optimization. We need to avoid performing
8600/// any transform which might inhibit optimization (such as our ability to
8601/// specialize a particular handler via tail commoning). We do this by not
8602/// merging any blocks which require us to introduce a phi. Since the same
8603/// values are flowing through both blocks, we don't lose any ability to
8604/// specialize. If anything, we make such specialization more likely.
8605///
8606/// TODO - This transformation could remove entries from a phi in the target
8607/// block when the inputs in the phi are the same for the two blocks being
8608/// merged. In some cases, this could result in removal of the PHI entirely.
8609static bool tryToMergeLandingPad(LandingPadInst *LPad, UncondBrInst *BI,
8610 BasicBlock *BB, DomTreeUpdater *DTU) {
8611 auto Succ = BB->getUniqueSuccessor();
8612 assert(Succ);
8613 // If there's a phi in the successor block, we'd likely have to introduce
8614 // a phi into the merged landing pad block.
8615 if (isa<PHINode>(Val: *Succ->begin()))
8616 return false;
8617
8618 for (BasicBlock *OtherPred : predecessors(BB: Succ)) {
8619 if (BB == OtherPred)
8620 continue;
8621 BasicBlock::iterator I = OtherPred->begin();
8622 LandingPadInst *LPad2 = dyn_cast<LandingPadInst>(Val&: I);
8623 if (!LPad2 || !LPad2->isIdenticalTo(I: LPad))
8624 continue;
8625 ++I;
8626 UncondBrInst *BI2 = dyn_cast<UncondBrInst>(Val&: I);
8627 if (!BI2 || !BI2->isIdenticalTo(I: BI))
8628 continue;
8629
8630 std::vector<DominatorTree::UpdateType> Updates;
8631
8632 // We've found an identical block. Update our predecessors to take that
8633 // path instead and make ourselves dead.
8634 SmallSetVector<BasicBlock *, 16> UniquePreds(pred_begin(BB), pred_end(BB));
8635 for (BasicBlock *Pred : UniquePreds) {
8636 InvokeInst *II = cast<InvokeInst>(Val: Pred->getTerminator());
8637 assert(II->getNormalDest() != BB && II->getUnwindDest() == BB &&
8638 "unexpected successor");
8639 II->setUnwindDest(OtherPred);
8640 if (DTU) {
8641 Updates.push_back(x: {DominatorTree::Insert, Pred, OtherPred});
8642 Updates.push_back(x: {DominatorTree::Delete, Pred, BB});
8643 }
8644 }
8645
8646 SmallSetVector<BasicBlock *, 16> UniqueSuccs(succ_begin(BB), succ_end(BB));
8647 for (BasicBlock *Succ : UniqueSuccs) {
8648 Succ->removePredecessor(Pred: BB);
8649 if (DTU)
8650 Updates.push_back(x: {DominatorTree::Delete, BB, Succ});
8651 }
8652
8653 IRBuilder<> Builder(BI);
8654 Builder.CreateUnreachable();
8655 BI->eraseFromParent();
8656 if (DTU)
8657 DTU->applyUpdates(Updates);
8658 return true;
8659 }
8660 return false;
8661}
8662
8663bool SimplifyCFGOpt::simplifyUncondBranch(UncondBrInst *BI,
8664 IRBuilder<> &Builder) {
8665 BasicBlock *BB = BI->getParent();
8666 BasicBlock *Succ = BI->getSuccessor(i: 0);
8667
8668 // If the Terminator is the only non-phi instruction, simplify the block.
8669 // If LoopHeader is provided, check if the block or its successor is a loop
8670 // header. (This is for early invocations before loop simplify and
8671 // vectorization to keep canonical loop forms for nested loops. These blocks
8672 // can be eliminated when the pass is invoked later in the back-end.)
8673 // Note that if BB has only one predecessor then we do not introduce new
8674 // backedge, so we can eliminate BB.
8675 bool NeedCanonicalLoop =
8676 Options.NeedCanonicalLoop &&
8677 (!LoopHeaders.empty() && BB->hasNPredecessorsOrMore(N: 2) &&
8678 (is_contained(Range&: LoopHeaders, Element: BB) || is_contained(Range&: LoopHeaders, Element: Succ)));
8679 BasicBlock::iterator I = BB->getFirstNonPHIOrDbg();
8680 if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
8681 !NeedCanonicalLoop && TryToSimplifyUncondBranchFromEmptyBlock(BB, DTU))
8682 return true;
8683
8684 // If the only instruction in the block is a seteq/setne comparison against a
8685 // constant, try to simplify the block.
8686 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Val&: I)) {
8687 if (ICI->isEquality() && isa<ConstantInt>(Val: ICI->getOperand(i_nocapture: 1))) {
8688 ++I;
8689 if (I->isTerminator() &&
8690 tryToSimplifyUncondBranchWithICmpInIt(ICI, Builder))
8691 return true;
8692 if (isa<SelectInst>(Val: I) && I->getNextNode()->isTerminator() &&
8693 tryToSimplifyUncondBranchWithICmpSelectInIt(ICI, Select: cast<SelectInst>(Val&: I),
8694 Builder))
8695 return true;
8696 }
8697 }
8698
8699 // See if we can merge an empty landing pad block with another which is
8700 // equivalent.
8701 if (LandingPadInst *LPad = dyn_cast<LandingPadInst>(Val&: I)) {
8702 ++I;
8703 if (I->isTerminator() && tryToMergeLandingPad(LPad, BI, BB, DTU))
8704 return true;
8705 }
8706
8707 return false;
8708}
8709
8710static BasicBlock *allPredecessorsComeFromSameSource(BasicBlock *BB) {
8711 BasicBlock *PredPred = nullptr;
8712 for (auto *P : predecessors(BB)) {
8713 BasicBlock *PPred = P->getSinglePredecessor();
8714 if (!PPred || (PredPred && PredPred != PPred))
8715 return nullptr;
8716 PredPred = PPred;
8717 }
8718 return PredPred;
8719}
8720
8721/// Fold the following pattern:
8722/// bb0:
8723/// br i1 %cond1, label %bb1, label %bb2
8724/// bb1:
8725/// br i1 %cond2, label %bb3, label %bb4
8726/// bb2:
8727/// br i1 %cond2, label %bb4, label %bb3
8728/// bb3:
8729/// ...
8730/// bb4:
8731/// ...
8732/// into
8733/// bb0:
8734/// %cond = xor i1 %cond1, %cond2
8735/// br i1 %cond, label %bb4, label %bb3
8736/// bb3:
8737/// ...
8738/// bb4:
8739/// ...
8740/// NOTE: %cond2 always dominates the terminator of bb0.
8741static bool mergeNestedCondBranch(CondBrInst *BI, DomTreeUpdater *DTU) {
8742 BasicBlock *BB = BI->getParent();
8743 BasicBlock *BB1 = BI->getSuccessor(i: 0);
8744 BasicBlock *BB2 = BI->getSuccessor(i: 1);
8745 auto IsSimpleSuccessor = [BB](BasicBlock *Succ, CondBrInst *&SuccBI) {
8746 if (Succ == BB)
8747 return false;
8748 if (&Succ->front() != Succ->getTerminator())
8749 return false;
8750 SuccBI = dyn_cast<CondBrInst>(Val: Succ->getTerminator());
8751 if (!SuccBI)
8752 return false;
8753 BasicBlock *Succ1 = SuccBI->getSuccessor(i: 0);
8754 BasicBlock *Succ2 = SuccBI->getSuccessor(i: 1);
8755 return Succ1 != Succ && Succ2 != Succ && Succ1 != BB && Succ2 != BB &&
8756 !isa<PHINode>(Val: Succ1->front()) && !isa<PHINode>(Val: Succ2->front());
8757 };
8758 CondBrInst *BB1BI, *BB2BI;
8759 if (!IsSimpleSuccessor(BB1, BB1BI) || !IsSimpleSuccessor(BB2, BB2BI))
8760 return false;
8761
8762 if (BB1BI->getCondition() != BB2BI->getCondition() ||
8763 BB1BI->getSuccessor(i: 0) != BB2BI->getSuccessor(i: 1) ||
8764 BB1BI->getSuccessor(i: 1) != BB2BI->getSuccessor(i: 0))
8765 return false;
8766
8767 BasicBlock *BB3 = BB1BI->getSuccessor(i: 0);
8768 BasicBlock *BB4 = BB1BI->getSuccessor(i: 1);
8769 // Bail out on trivial cases to avoid bothering to handle the special case in
8770 // the code below.
8771 if (BB3 == BB4)
8772 return false;
8773 IRBuilder<> Builder(BI);
8774 BI->setCondition(
8775 Builder.CreateXor(LHS: BI->getCondition(), RHS: BB1BI->getCondition()));
8776 BB1->removePredecessor(Pred: BB);
8777 BI->setSuccessor(idx: 0, NewSucc: BB4);
8778 BB2->removePredecessor(Pred: BB);
8779 BI->setSuccessor(idx: 1, NewSucc: BB3);
8780 if (DTU) {
8781 SmallVector<DominatorTree::UpdateType, 4> Updates;
8782 Updates.push_back(Elt: {DominatorTree::Delete, BB, BB1});
8783 Updates.push_back(Elt: {DominatorTree::Insert, BB, BB4});
8784 Updates.push_back(Elt: {DominatorTree::Delete, BB, BB2});
8785 Updates.push_back(Elt: {DominatorTree::Insert, BB, BB3});
8786
8787 DTU->applyUpdates(Updates);
8788 }
8789 bool HasWeight = false;
8790 uint64_t BBTWeight, BBFWeight;
8791 if (extractBranchWeights(I: *BI, TrueVal&: BBTWeight, FalseVal&: BBFWeight))
8792 HasWeight = true;
8793 else
8794 BBTWeight = BBFWeight = 1;
8795 uint64_t BB1TWeight, BB1FWeight;
8796 if (extractBranchWeights(I: *BB1BI, TrueVal&: BB1TWeight, FalseVal&: BB1FWeight))
8797 HasWeight = true;
8798 else
8799 BB1TWeight = BB1FWeight = 1;
8800 uint64_t BB2TWeight, BB2FWeight;
8801 if (extractBranchWeights(I: *BB2BI, TrueVal&: BB2TWeight, FalseVal&: BB2FWeight))
8802 HasWeight = true;
8803 else
8804 BB2TWeight = BB2FWeight = 1;
8805 if (HasWeight) {
8806 uint64_t Weights[2] = {BBTWeight * BB1FWeight + BBFWeight * BB2TWeight,
8807 BBTWeight * BB1TWeight + BBFWeight * BB2FWeight};
8808 setFittedBranchWeights(I&: *BI, Weights, /*IsExpected=*/false,
8809 /*ElideAllZero=*/true);
8810 }
8811 return true;
8812}
8813
8814bool SimplifyCFGOpt::simplifyCondBranch(CondBrInst *BI, IRBuilder<> &Builder) {
8815 assert(
8816 !isa<ConstantInt>(BI->getCondition()) &&
8817 BI->getSuccessor(0) != BI->getSuccessor(1) &&
8818 "Tautological conditional branch should have been eliminated already.");
8819
8820 BasicBlock *BB = BI->getParent();
8821 if (!Options.SimplifyCondBranch ||
8822 BI->getFunction()->hasFnAttribute(Kind: Attribute::OptForFuzzing))
8823 return false;
8824
8825 // Conditional branch
8826 if (isValueEqualityComparison(TI: BI)) {
8827 // If we only have one predecessor, and if it is a branch on this value,
8828 // see if that predecessor totally determines the outcome of this
8829 // switch.
8830 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
8831 if (simplifyEqualityComparisonWithOnlyPredecessor(TI: BI, Pred: OnlyPred, Builder))
8832 return requestResimplify();
8833
8834 // This block must be empty, except for the setcond inst, if it exists.
8835 // Ignore pseudo intrinsics.
8836 for (auto &I : *BB) {
8837 if (isa<PseudoProbeInst>(Val: I) ||
8838 &I == cast<Instruction>(Val: BI->getCondition()))
8839 continue;
8840 if (&I == BI)
8841 if (foldValueComparisonIntoPredecessors(TI: BI, Builder))
8842 return requestResimplify();
8843 break;
8844 }
8845 }
8846
8847 // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction.
8848 if (simplifyBranchOnICmpChain(BI, Builder, DL))
8849 return true;
8850
8851 // If this basic block has dominating predecessor blocks and the dominating
8852 // blocks' conditions imply BI's condition, we know the direction of BI.
8853 std::optional<bool> Imp = isImpliedByDomCondition(Cond: BI->getCondition(), ContextI: BI, DL);
8854 if (Imp) {
8855 // Turn this into a branch on constant.
8856 auto *OldCond = BI->getCondition();
8857 ConstantInt *TorF = *Imp ? ConstantInt::getTrue(Context&: BB->getContext())
8858 : ConstantInt::getFalse(Context&: BB->getContext());
8859 BI->setCondition(TorF);
8860 RecursivelyDeleteTriviallyDeadInstructions(V: OldCond);
8861 return requestResimplify();
8862 }
8863
8864 // If this basic block is ONLY a compare and a branch, and if a predecessor
8865 // branches to us and one of our successors, fold the comparison into the
8866 // predecessor and use logical operations to pick the right destination.
8867 if (Options.SpeculateBlocks &&
8868 foldBranchToCommonDest(BI, DTU, /*MSSAU=*/nullptr, TTI: &TTI, AC: Options.AC,
8869 BonusInstThreshold: Options.BonusInstThreshold))
8870 return requestResimplify();
8871
8872 // We have a conditional branch to two blocks that are only reachable
8873 // from BI. We know that the condbr dominates the two blocks, so see if
8874 // there is any identical code in the "then" and "else" blocks. If so, we
8875 // can hoist it up to the branching block.
8876 if (BI->getSuccessor(i: 0)->getSinglePredecessor()) {
8877 if (BI->getSuccessor(i: 1)->getSinglePredecessor()) {
8878 if (HoistCommon &&
8879 hoistCommonCodeFromSuccessors(TI: BI, AllInstsEqOnly: !Options.HoistCommonInsts))
8880 return requestResimplify();
8881
8882 if (BI && Options.HoistLoadsStoresWithCondFaulting &&
8883 isProfitableToSpeculate(BI, Invert: std::nullopt, TTI)) {
8884 SmallVector<Instruction *, 2> SpeculatedConditionalLoadsStores;
8885 auto CanSpeculateConditionalLoadsStores = [&]() {
8886 for (auto *Succ : successors(BB)) {
8887 for (Instruction &I : *Succ) {
8888 if (I.isTerminator()) {
8889 if (I.getNumSuccessors() > 1)
8890 return false;
8891 continue;
8892 } else if (!isSafeCheapLoadStore(I: &I, TTI) ||
8893 SpeculatedConditionalLoadsStores.size() ==
8894 HoistLoadsStoresWithCondFaultingThreshold) {
8895 return false;
8896 }
8897 SpeculatedConditionalLoadsStores.push_back(Elt: &I);
8898 }
8899 }
8900 return !SpeculatedConditionalLoadsStores.empty();
8901 };
8902
8903 if (CanSpeculateConditionalLoadsStores()) {
8904 hoistConditionalLoadsStores(BI, SpeculatedConditionalLoadsStores,
8905 Invert: std::nullopt, Sel: nullptr);
8906 return requestResimplify();
8907 }
8908 }
8909 } else {
8910 // If Successor #1 has multiple preds, we may be able to conditionally
8911 // execute Successor #0 if it branches to Successor #1.
8912 Instruction *Succ0TI = BI->getSuccessor(i: 0)->getTerminator();
8913 if (Succ0TI->getNumSuccessors() == 1 &&
8914 Succ0TI->getSuccessor(Idx: 0) == BI->getSuccessor(i: 1))
8915 if (speculativelyExecuteBB(BI, ThenBB: BI->getSuccessor(i: 0)))
8916 return requestResimplify();
8917 }
8918 } else if (BI->getSuccessor(i: 1)->getSinglePredecessor()) {
8919 // If Successor #0 has multiple preds, we may be able to conditionally
8920 // execute Successor #1 if it branches to Successor #0.
8921 Instruction *Succ1TI = BI->getSuccessor(i: 1)->getTerminator();
8922 if (Succ1TI->getNumSuccessors() == 1 &&
8923 Succ1TI->getSuccessor(Idx: 0) == BI->getSuccessor(i: 0))
8924 if (speculativelyExecuteBB(BI, ThenBB: BI->getSuccessor(i: 1)))
8925 return requestResimplify();
8926 }
8927
8928 // If this is a branch on something for which we know the constant value in
8929 // predecessors (e.g. a phi node in the current block), thread control
8930 // through this block.
8931 if (foldCondBranchOnValueKnownInPredecessor(BI))
8932 return requestResimplify();
8933
8934 // Scan predecessor blocks for conditional branches.
8935 for (BasicBlock *Pred : predecessors(BB))
8936 if (CondBrInst *PBI = dyn_cast<CondBrInst>(Val: Pred->getTerminator()))
8937 if (PBI != BI)
8938 if (SimplifyCondBranchToCondBranch(PBI, BI, DTU, DL, TTI))
8939 return requestResimplify();
8940
8941 // Look for diamond patterns.
8942 if (MergeCondStores)
8943 if (BasicBlock *PrevBB = allPredecessorsComeFromSameSource(BB))
8944 if (CondBrInst *PBI = dyn_cast<CondBrInst>(Val: PrevBB->getTerminator()))
8945 if (PBI != BI)
8946 if (mergeConditionalStores(PBI, QBI: BI, DTU, DL, TTI))
8947 return requestResimplify();
8948
8949 // Look for nested conditional branches.
8950 if (mergeNestedCondBranch(BI, DTU))
8951 return requestResimplify();
8952
8953 return false;
8954}
8955
8956/// Check if passing a value to an instruction will cause undefined behavior.
8957static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I, bool PtrValueMayBeModified) {
8958 assert(V->getType() == I->getType() && "Mismatched types");
8959 Constant *C = dyn_cast<Constant>(Val: V);
8960 if (!C)
8961 return false;
8962
8963 if (I->use_empty())
8964 return false;
8965
8966 if (C->isNullValue() || isa<UndefValue>(Val: C)) {
8967 // Find the first same-block use with a UB-triggering opcode, skipping
8968 // cross-block or before-I uses.
8969 auto FindUse = llvm::find_if(Range: I->uses(), P: [I](auto &U) {
8970 auto *Use = cast<Instruction>(U.getUser());
8971 // Only same-block uses after I can witness UB at I's program point.
8972 // Self-uses and before-I uses can occur when I is a PHI node.
8973 if (Use->getParent() != I->getParent() || Use == I || Use->comesBefore(I))
8974 return false;
8975 // Change this list when we want to add new instructions.
8976 switch (Use->getOpcode()) {
8977 default:
8978 return false;
8979 case Instruction::GetElementPtr:
8980 case Instruction::Ret:
8981 case Instruction::BitCast:
8982 case Instruction::Load:
8983 case Instruction::Store:
8984 case Instruction::Call:
8985 case Instruction::CallBr:
8986 case Instruction::Invoke:
8987 case Instruction::UDiv:
8988 case Instruction::URem:
8989 // Note: signed div/rem of INT_MIN / -1 is also immediate UB, not
8990 // implemented to avoid code complexity as it is unclear how useful such
8991 // logic is.
8992 case Instruction::SDiv:
8993 case Instruction::SRem:
8994 return true;
8995 }
8996 });
8997 if (FindUse == I->use_end())
8998 return false;
8999 auto &Use = *FindUse;
9000 auto *User = cast<Instruction>(Val: Use.getUser());
9001
9002 // Now make sure that there are no instructions in between that can alter
9003 // control flow (eg. calls)
9004 auto InstrRange =
9005 make_range(x: std::next(x: I->getIterator()), y: User->getIterator());
9006 if (any_of(Range&: InstrRange, P: [](Instruction &I) {
9007 return !isGuaranteedToTransferExecutionToSuccessor(I: &I);
9008 }))
9009 return false;
9010
9011 // Look through GEPs. A load from a GEP derived from NULL is still undefined
9012 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Val: User))
9013 if (GEP->getPointerOperand() == I) {
9014 // The type of GEP may differ from the type of base pointer.
9015 // Bail out on vector GEPs, as they are not handled by other checks.
9016 if (GEP->getType()->isVectorTy())
9017 return false;
9018 // The current base address is null, there are four cases to consider:
9019 // getelementptr (TY, null, 0) -> null
9020 // getelementptr (TY, null, not zero) -> may be modified
9021 // getelementptr inbounds (TY, null, 0) -> null
9022 // getelementptr inbounds (TY, null, not zero) -> poison iff null is
9023 // undefined?
9024 if (!GEP->hasAllZeroIndices() &&
9025 (!GEP->isInBounds() ||
9026 NullPointerIsDefined(F: GEP->getFunction(),
9027 AS: GEP->getPointerAddressSpace())))
9028 PtrValueMayBeModified = true;
9029 return passingValueIsAlwaysUndefined(V, I: GEP, PtrValueMayBeModified);
9030 }
9031
9032 // Look through return.
9033 if (ReturnInst *Ret = dyn_cast<ReturnInst>(Val: User)) {
9034 bool HasNoUndefAttr =
9035 Ret->getFunction()->hasRetAttribute(Kind: Attribute::NoUndef);
9036 // Return undefined to a noundef return value is undefined.
9037 if (isa<UndefValue>(Val: C) && HasNoUndefAttr)
9038 return true;
9039 // Return null to a nonnull+noundef return value is undefined.
9040 if (C->isNullValue() && HasNoUndefAttr &&
9041 Ret->getFunction()->hasRetAttribute(Kind: Attribute::NonNull)) {
9042 return !PtrValueMayBeModified;
9043 }
9044 }
9045
9046 // Load from null is undefined.
9047 if (LoadInst *LI = dyn_cast<LoadInst>(Val: User))
9048 if (!LI->isVolatile())
9049 return !NullPointerIsDefined(F: LI->getFunction(),
9050 AS: LI->getPointerAddressSpace());
9051
9052 // Store to null is undefined.
9053 if (StoreInst *SI = dyn_cast<StoreInst>(Val: User))
9054 if (!SI->isVolatile())
9055 return (!NullPointerIsDefined(F: SI->getFunction(),
9056 AS: SI->getPointerAddressSpace())) &&
9057 SI->getPointerOperand() == I;
9058
9059 // llvm.assume(false/undef) always triggers immediate UB.
9060 if (auto *Assume = dyn_cast<AssumeInst>(Val: User)) {
9061 // Ignore assume operand bundles.
9062 if (I == Assume->getArgOperand(i: 0))
9063 return true;
9064 }
9065
9066 if (auto *CB = dyn_cast<CallBase>(Val: User)) {
9067 if (C->isNullValue() && NullPointerIsDefined(F: CB->getFunction()))
9068 return false;
9069 // A call to null is undefined.
9070 if (CB->getCalledOperand() == I)
9071 return true;
9072
9073 if (CB->isArgOperand(U: &Use)) {
9074 unsigned ArgIdx = CB->getArgOperandNo(U: &Use);
9075 // Passing null to a nonnnull+noundef argument is undefined.
9076 if (isa<ConstantPointerNull>(Val: C) && C->getType()->isPointerTy() &&
9077 CB->paramHasNonNullAttr(ArgNo: ArgIdx, /*AllowUndefOrPoison=*/false))
9078 return !PtrValueMayBeModified;
9079 // Passing undef to a noundef argument is undefined.
9080 if (isa<UndefValue>(Val: C) && CB->isPassingUndefUB(ArgNo: ArgIdx))
9081 return true;
9082 }
9083 }
9084 // Div/Rem by zero is immediate UB
9085 if (match(V: User, P: m_BinOp(L: m_Value(), R: m_Specific(V: I))) && User->isIntDivRem())
9086 return true;
9087 }
9088 return false;
9089}
9090
9091/// If BB has an incoming value that will always trigger undefined behavior
9092/// (eg. null pointer dereference), remove the branch leading here.
9093static bool removeUndefIntroducingPredecessor(BasicBlock *BB,
9094 DomTreeUpdater *DTU,
9095 AssumptionCache *AC) {
9096 for (PHINode &PHI : BB->phis())
9097 for (unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i)
9098 if (passingValueIsAlwaysUndefined(V: PHI.getIncomingValue(i), I: &PHI)) {
9099 BasicBlock *Predecessor = PHI.getIncomingBlock(i);
9100 Instruction *T = Predecessor->getTerminator();
9101 IRBuilder<> Builder(T);
9102 if (isa<UncondBrInst>(Val: T)) {
9103 BB->removePredecessor(Pred: Predecessor);
9104 // Turn unconditional branches into unreachables.
9105 Builder.CreateUnreachable();
9106 T->eraseFromParent();
9107 if (DTU)
9108 DTU->applyUpdates(Updates: {{DominatorTree::Delete, Predecessor, BB}});
9109 return true;
9110 } else if (CondBrInst *BI = dyn_cast<CondBrInst>(Val: T)) {
9111 BB->removePredecessor(Pred: Predecessor);
9112 // Handle degenerate conditional branches.
9113 if (BI->getSuccessor(i: 0) == BI->getSuccessor(i: 1)) {
9114 // The only difference from the UncondBrInst path above is that it
9115 // has two edges in CFG.
9116 BB->removePredecessor(Pred: Predecessor);
9117 // Turn unconditional branches into unreachables.
9118 Builder.CreateUnreachable();
9119 } else {
9120 // Preserve guarding condition in assume, because it might not be
9121 // inferrable from any dominating condition.
9122 Value *Cond = BI->getCondition();
9123 CallInst *Assumption;
9124 if (BI->getSuccessor(i: 0) == BB)
9125 Assumption = Builder.CreateAssumption(Cond: Builder.CreateNot(V: Cond));
9126 else
9127 Assumption = Builder.CreateAssumption(Cond);
9128 if (AC)
9129 AC->registerAssumption(CI: cast<AssumeInst>(Val: Assumption));
9130 Builder.CreateBr(Dest: BI->getSuccessor(i: 0) == BB ? BI->getSuccessor(i: 1)
9131 : BI->getSuccessor(i: 0));
9132 }
9133 BI->eraseFromParent();
9134 if (DTU)
9135 DTU->applyUpdates(Updates: {{DominatorTree::Delete, Predecessor, BB}});
9136 return true;
9137 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(Val: T)) {
9138 // Redirect all branches leading to UB into
9139 // a newly created unreachable block.
9140 BasicBlock *Unreachable = BasicBlock::Create(
9141 Context&: Predecessor->getContext(), Name: "unreachable", Parent: BB->getParent(), InsertBefore: BB);
9142 Builder.SetInsertPoint(Unreachable);
9143 // The new block contains only one instruction: Unreachable
9144 Builder.CreateUnreachable();
9145 for (const auto &Case : SI->cases())
9146 if (Case.getCaseSuccessor() == BB) {
9147 BB->removePredecessor(Pred: Predecessor);
9148 Case.setSuccessor(Unreachable);
9149 }
9150 if (SI->getDefaultDest() == BB) {
9151 BB->removePredecessor(Pred: Predecessor);
9152 SI->setDefaultDest(Unreachable);
9153 }
9154
9155 if (DTU)
9156 DTU->applyUpdates(
9157 Updates: { { DominatorTree::Insert, Predecessor, Unreachable },
9158 { DominatorTree::Delete, Predecessor, BB } });
9159 return true;
9160 }
9161 }
9162
9163 return false;
9164}
9165
9166bool SimplifyCFGOpt::simplifyOnce(BasicBlock *BB) {
9167 bool Changed = false;
9168
9169 assert(BB && BB->getParent() && "Block not embedded in function!");
9170 assert(BB->getTerminator() && "Degenerate basic block encountered!");
9171
9172 // Remove basic blocks that have no predecessors (except the entry block)...
9173 // or that just have themself as a predecessor. These are unreachable.
9174 if ((pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()) ||
9175 BB->getSinglePredecessor() == BB) {
9176 LLVM_DEBUG(dbgs() << "Removing BB: \n" << *BB);
9177 DeleteDeadBlock(BB, DTU);
9178 return true;
9179 }
9180
9181 // Check to see if we can constant propagate this terminator instruction
9182 // away...
9183 Changed |= ConstantFoldTerminator(BB, /*DeleteDeadConditions=*/true,
9184 /*TLI=*/nullptr, DTU);
9185
9186 // Check for and eliminate duplicate PHI nodes in this block.
9187 Changed |= EliminateDuplicatePHINodes(BB);
9188
9189 // Check for and remove branches that will always cause undefined behavior.
9190 if (removeUndefIntroducingPredecessor(BB, DTU, AC: Options.AC))
9191 return requestResimplify();
9192
9193 // Merge basic blocks into their predecessor if there is only one distinct
9194 // pred, and if there is only one distinct successor of the predecessor, and
9195 // if there are no PHI nodes.
9196 if (MergeBlockIntoPredecessor(BB, DTU))
9197 return true;
9198
9199 if (SinkCommon && Options.SinkCommonInsts) {
9200 if (sinkCommonCodeFromPredecessors(BB, DTU) ||
9201 mergeCompatibleInvokes(BB, DTU)) {
9202 // sinkCommonCodeFromPredecessors() does not automatically CSE PHI's,
9203 // so we may now how duplicate PHI's.
9204 // Let's rerun EliminateDuplicatePHINodes() first,
9205 // before foldTwoEntryPHINode() potentially converts them into select's,
9206 // after which we'd need a whole EarlyCSE pass run to cleanup them.
9207 return true;
9208 }
9209 // Merge identical predecessors of this block.
9210 if (simplifyDuplicatePredecessors(BB, DTU))
9211 return true;
9212 }
9213
9214 if (Options.SpeculateBlocks &&
9215 !BB->getParent()->hasFnAttribute(Kind: Attribute::OptForFuzzing)) {
9216 // If there is a trivial two-entry PHI node in this basic block, and we can
9217 // eliminate it, do so now.
9218 if (auto *PN = dyn_cast<PHINode>(Val: BB->begin()))
9219 if (PN->getNumIncomingValues() == 2)
9220 if (foldTwoEntryPHINode(PN, TTI, DTU, AC: Options.AC, DL,
9221 SpeculateUnpredictables: Options.SpeculateUnpredictables))
9222 return true;
9223 }
9224
9225 IRBuilder<> Builder(BB);
9226 Instruction *Terminator = BB->getTerminator();
9227 Builder.SetInsertPoint(Terminator);
9228 switch (Terminator->getOpcode()) {
9229 case Instruction::UncondBr:
9230 Changed |= simplifyUncondBranch(BI: cast<UncondBrInst>(Val: Terminator), Builder);
9231 break;
9232 case Instruction::CondBr:
9233 Changed |= simplifyCondBranch(BI: cast<CondBrInst>(Val: Terminator), Builder);
9234 break;
9235 case Instruction::Resume:
9236 Changed |= simplifyResume(RI: cast<ResumeInst>(Val: Terminator), Builder);
9237 break;
9238 case Instruction::CleanupRet:
9239 Changed |= simplifyCleanupReturn(RI: cast<CleanupReturnInst>(Val: Terminator));
9240 break;
9241 case Instruction::Switch:
9242 Changed |= simplifySwitch(SI: cast<SwitchInst>(Val: Terminator), Builder);
9243 break;
9244 case Instruction::Unreachable:
9245 Changed |= simplifyUnreachable(UI: cast<UnreachableInst>(Val: Terminator));
9246 break;
9247 case Instruction::IndirectBr:
9248 Changed |= simplifyIndirectBr(IBI: cast<IndirectBrInst>(Val: Terminator));
9249 break;
9250 }
9251
9252 return Changed;
9253}
9254
9255bool SimplifyCFGOpt::run(BasicBlock *BB) {
9256 bool Changed = false;
9257
9258 // Repeated simplify BB as long as resimplification is requested.
9259 do {
9260 Resimplify = false;
9261
9262 // Perform one round of simplifcation. Resimplify flag will be set if
9263 // another iteration is requested.
9264 Changed |= simplifyOnce(BB);
9265 } while (Resimplify);
9266
9267 return Changed;
9268}
9269
9270bool llvm::simplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI,
9271 DomTreeUpdater *DTU, const SimplifyCFGOptions &Options,
9272 ArrayRef<WeakVH> LoopHeaders) {
9273 return SimplifyCFGOpt(TTI, DTU, BB->getDataLayout(), LoopHeaders,
9274 Options)
9275 .run(BB);
9276}
9277