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