LLVM 24.0.0git
EarlyIfConversion.cpp
Go to the documentation of this file.
1//===-- EarlyIfConversion.cpp - If-conversion on SSA form machine code ----===//
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// Early if-conversion is for out-of-order CPUs that don't have a lot of
10// predicable instructions. The goal is to eliminate conditional branches that
11// may mispredict.
12//
13// Instructions from both sides of the branch are executed specutatively, and a
14// cmov instruction selects the result.
15//
16//===----------------------------------------------------------------------===//
17
19#include "llvm/ADT/BitVector.h"
20#include "llvm/ADT/DenseSet.h"
23#include "llvm/ADT/SparseSet.h"
24#include "llvm/ADT/Statistic.h"
44#include "llvm/Support/Debug.h"
46
47using namespace llvm;
48
49#define DEBUG_TYPE "early-ifcvt"
50
51// Absolute maximum number of instructions allowed per speculated block.
52// This bypasses all other heuristics, so it should be set fairly high.
54BlockInstrLimit("early-ifcvt-limit", cl::init(30), cl::Hidden,
55 cl::desc("Maximum number of instructions per speculated block."));
56
57// Stress testing mode - disable heuristics.
58static cl::opt<bool> Stress("stress-early-ifcvt", cl::Hidden,
59 cl::desc("Turn all knobs to 11"));
60
61// Enable analysis of data dependent branches (conditions derived from loads).
63 "enable-early-ifcvt-data-dependent", cl::Hidden, cl::init(false),
64 cl::desc("Enable hard-to-predict branch analysis for if-conversion"));
65
66// Limit the number steps we take when searching conditions that depend on
67// values recently loaded from memory.
69 MaxNumSteps("early-ifcvt-max-steps", cl::Hidden, cl::init(16),
70 cl::desc("Limit the number of steps taken when searching for a "
71 "recently loaded value"));
72
73STATISTIC(NumDiamondsSeen, "Number of diamonds");
74STATISTIC(NumDiamondsConv, "Number of diamonds converted");
75STATISTIC(NumTrianglesSeen, "Number of triangles");
76STATISTIC(NumTrianglesConv, "Number of triangles converted");
77STATISTIC(NumDataDependant,
78 "Number of data dependent conditional branches encountered");
79STATISTIC(NumLikelyBiased, "Number of branches with a hot path encountered");
80
81//===----------------------------------------------------------------------===//
82// SSAIfConv
83//===----------------------------------------------------------------------===//
84//
85// The SSAIfConv class performs if-conversion on SSA form machine code after
86// determining if it is possible. The class contains no heuristics; external
87// code should be used to determine when if-conversion is a good idea.
88//
89// SSAIfConv can convert both triangles and diamonds:
90//
91// Triangle: Head Diamond: Head
92// | \ / \_
93// | \ / |
94// | [TF]BB FBB TBB
95// | / \ /
96// | / \ /
97// Tail Tail
98//
99// Instructions in the conditional blocks TBB and/or FBB are spliced into the
100// Head block, and phis in the Tail block are converted to select instructions.
101//
102namespace {
103class SSAIfConv {
104 const TargetInstrInfo *TII;
105 const TargetRegisterInfo *TRI;
107
108public:
109 /// The block containing the conditional branch.
110 MachineBasicBlock *Head;
111
112 /// The block containing phis after the if-then-else.
114
115 /// The 'true' conditional block as determined by analyzeBranch.
117
118 /// The 'false' conditional block as determined by analyzeBranch.
120
121 /// isTriangle - When there is no 'else' block, either TBB or FBB will be
122 /// equal to Tail.
123 bool isTriangle() const { return TBB == Tail || FBB == Tail; }
124
125 /// Returns the Tail predecessor for the True side.
126 MachineBasicBlock *getTPred() const { return TBB == Tail ? Head : TBB; }
127
128 /// Returns the Tail predecessor for the False side.
129 MachineBasicBlock *getFPred() const { return FBB == Tail ? Head : FBB; }
130
131 /// Information about each phi in the Tail block.
132 struct PHIInfo {
133 MachineInstr *PHI;
134 Register TReg, FReg;
135 // Latencies from Cond+Branch, TReg, and FReg to DstReg.
136 int CondCycles = 0, TCycles = 0, FCycles = 0;
137
138 PHIInfo(MachineInstr *phi) : PHI(phi) {}
139 };
140
142
143 /// The branch condition determined by analyzeBranch.
145
146private:
147 /// Instructions in Head that define values used by the conditional blocks.
148 /// The hoisted instructions must be inserted after these instructions.
149 SmallPtrSet<MachineInstr*, 8> InsertAfter;
150
151 /// Register units clobbered by the conditional blocks.
152 BitVector ClobberedRegUnits;
153
154 // Scratch pad for findInsertionPoint.
155 SparseSet<MCRegUnit, MCRegUnit, MCRegUnitToIndex> LiveRegUnits;
156
157 /// Insertion point in Head for speculatively executed instructions form TBB
158 /// and FBB.
159 MachineBasicBlock::iterator InsertionPoint;
160
161 /// Return true if all non-terminator instructions in MBB can be safely
162 /// speculated.
163 bool canSpeculateInstrs(MachineBasicBlock *MBB);
164
165 /// Return true if all non-terminator instructions in MBB can be safely
166 /// predicated.
167 bool canPredicateInstrs(MachineBasicBlock *MBB);
168
169 /// Scan through instruction dependencies and update InsertAfter array.
170 /// Return false if any dependency is incompatible with if conversion.
171 bool InstrDependenciesAllowIfConv(MachineInstr *I);
172
173 /// Predicate all instructions of the basic block with current condition
174 /// except for terminators. Reverse the condition if ReversePredicate is set.
175 void PredicateBlock(MachineBasicBlock *MBB, bool ReversePredicate);
176
177 /// Find a valid insertion point in Head.
178 bool findInsertionPoint();
179
180 /// Replace PHI instructions in Tail with selects.
181 void replacePHIInstrs();
182
183 /// Insert selects and rewrite PHI operands to use them.
184 void rewritePHIOperands();
185
186 /// If virtual register has "killed" flag in TBB and FBB basic blocks, remove
187 /// the flag in TBB instruction.
188 void clearRepeatedKillFlagsFromTBB(MachineBasicBlock *TBB,
189 MachineBasicBlock *FBB);
190
191public:
192 /// init - Initialize per-function data structures.
193 void init(MachineFunction &MF) {
194 TII = MF.getSubtarget().getInstrInfo();
195 TRI = MF.getSubtarget().getRegisterInfo();
196 MRI = &MF.getRegInfo();
197 LiveRegUnits.clear();
198 LiveRegUnits.setUniverse(TRI->getNumRegUnits());
199 ClobberedRegUnits.clear();
200 ClobberedRegUnits.resize(TRI->getNumRegUnits());
201 }
202
203 /// canConvertIf - If the sub-CFG headed by MBB can be if-converted,
204 /// initialize the internal state, and return true.
205 /// If predicate is set try to predicate the block otherwise try to
206 /// speculatively execute it.
207 bool canConvertIf(MachineBasicBlock *MBB, bool Predicate = false);
208
209 /// convertIf - If-convert the last block passed to canConvertIf(), assuming
210 /// it is possible. Add any blocks that are to be erased to RemoveBlocks.
211 void convertIf(SmallVectorImpl<MachineBasicBlock *> &RemoveBlocks,
212 bool Predicate = false);
213};
214} // end anonymous namespace
215
216/// canSpeculateInstrs - Returns true if all the instructions in MBB can safely
217/// be speculated. The terminators are not considered.
218///
219/// If instructions use any values that are defined in the head basic block,
220/// the defining instructions are added to InsertAfter.
221///
222/// Any clobbered regunits are added to ClobberedRegUnits.
223///
224bool SSAIfConv::canSpeculateInstrs(MachineBasicBlock *MBB) {
225 // Reject any live-in physregs. It's probably CPSR/EFLAGS, and very hard to
226 // get right.
227 if (!MBB->livein_empty()) {
228 LLVM_DEBUG(dbgs() << printMBBReference(*MBB) << " has live-ins.\n");
229 return false;
230 }
231
232 unsigned InstrCount = 0;
233
234 // Check all instructions, except the terminators. It is assumed that
235 // terminators never have side effects or define any used register values.
236 for (MachineInstr &MI :
238 if (MI.isDebugInstr())
239 continue;
240
241 if (++InstrCount > BlockInstrLimit && !Stress) {
242 LLVM_DEBUG(dbgs() << printMBBReference(*MBB) << " has more than "
243 << BlockInstrLimit << " instructions.\n");
244 return false;
245 }
246
247 // There shouldn't normally be any phis in a single-predecessor block.
248 if (MI.isPHI()) {
249 LLVM_DEBUG(dbgs() << "Can't hoist: " << MI);
250 return false;
251 }
252
253 // Don't speculate loads. Note that it may be possible and desirable to
254 // speculate GOT or constant pool loads that are guaranteed not to trap,
255 // but we don't support that for now.
256 if (MI.mayLoad()) {
257 LLVM_DEBUG(dbgs() << "Won't speculate load: " << MI);
258 return false;
259 }
260
261 // We never speculate stores, so an AA pointer isn't necessary.
262 bool DontMoveAcrossStore = true;
263 if (!MI.isSafeToMove(DontMoveAcrossStore)) {
264 LLVM_DEBUG(dbgs() << "Can't speculate: " << MI);
265 return false;
266 }
267
268 // Check for any dependencies on Head instructions.
269 if (!InstrDependenciesAllowIfConv(&MI))
270 return false;
271 }
272 return true;
273}
274
275/// Check that there is no dependencies preventing if conversion.
276///
277/// If instruction uses any values that are defined in the head basic block,
278/// the defining instructions are added to InsertAfter.
279bool SSAIfConv::InstrDependenciesAllowIfConv(MachineInstr *I) {
280 for (const MachineOperand &MO : I->operands()) {
281 if (MO.isRegMask()) {
282 LLVM_DEBUG(dbgs() << "Won't speculate regmask: " << *I);
283 return false;
284 }
285 if (!MO.isReg())
286 continue;
287 Register Reg = MO.getReg();
288
289 // Remember clobbered regunits.
290 if (MO.isDef() && Reg.isPhysical())
291 for (MCRegUnit Unit : TRI->regunits(Reg.asMCReg()))
292 ClobberedRegUnits.set(static_cast<unsigned>(Unit));
293
294 if (!MO.readsReg() || !Reg.isVirtual())
295 continue;
296 MachineInstr *DefMI = MRI->getVRegDef(Reg);
297 if (!DefMI || DefMI->getParent() != Head)
298 continue;
299 if (InsertAfter.insert(DefMI).second)
300 LLVM_DEBUG(dbgs() << printMBBReference(*I->getParent()) << " depends on "
301 << *DefMI);
302 if (DefMI->isTerminator()) {
303 LLVM_DEBUG(dbgs() << "Can't insert instructions below terminator.\n");
304 return false;
305 }
306 }
307 return true;
308}
309
310/// canPredicateInstrs - Returns true if all the instructions in MBB can safely
311/// be predicates. The terminators are not considered.
312///
313/// If instructions use any values that are defined in the head basic block,
314/// the defining instructions are added to InsertAfter.
315///
316/// Any clobbered regunits are added to ClobberedRegUnits.
317///
318bool SSAIfConv::canPredicateInstrs(MachineBasicBlock *MBB) {
319 // Reject any live-in physregs. It's probably CPSR/EFLAGS, and very hard to
320 // get right.
321 if (!MBB->livein_empty()) {
322 LLVM_DEBUG(dbgs() << printMBBReference(*MBB) << " has live-ins.\n");
323 return false;
324 }
325
326 unsigned InstrCount = 0;
327
328 // Check all instructions, except the terminators. It is assumed that
329 // terminators never have side effects or define any used register values.
332 I != E; ++I) {
333 if (I->isDebugInstr())
334 continue;
335
336 if (++InstrCount > BlockInstrLimit && !Stress) {
337 LLVM_DEBUG(dbgs() << printMBBReference(*MBB) << " has more than "
338 << BlockInstrLimit << " instructions.\n");
339 return false;
340 }
341
342 // There shouldn't normally be any phis in a single-predecessor block.
343 if (I->isPHI()) {
344 LLVM_DEBUG(dbgs() << "Can't predicate: " << *I);
345 return false;
346 }
347
348 // Check that instruction is predicable
349 if (!TII->isPredicable(*I)) {
350 LLVM_DEBUG(dbgs() << "Isn't predicable: " << *I);
351 return false;
352 }
353
354 // Check that instruction is not already predicated.
355 if (TII->isPredicated(*I) && !TII->canPredicatePredicatedInstr(*I)) {
356 LLVM_DEBUG(dbgs() << "Is already predicated: " << *I);
357 return false;
358 }
359
360 // Check for any dependencies on Head instructions.
361 if (!InstrDependenciesAllowIfConv(&(*I)))
362 return false;
363 }
364 return true;
365}
366
367// Apply predicate to all instructions in the machine block.
368void SSAIfConv::PredicateBlock(MachineBasicBlock *MBB, bool ReversePredicate) {
369 auto Condition = Cond;
370 if (ReversePredicate) {
371 bool CanRevCond = !TII->reverseBranchCondition(Condition);
372 assert(CanRevCond && "Reversed predicate is not supported");
373 (void)CanRevCond;
374 }
375 // Terminators don't need to be predicated as they will be removed.
378 I != E; ++I) {
379 if (I->isDebugInstr())
380 continue;
381 TII->PredicateInstruction(*I, Condition);
382 }
383}
384
385/// Find an insertion point in Head for the speculated instructions. The
386/// insertion point must be:
387///
388/// 1. Before any terminators.
389/// 2. After any instructions in InsertAfter.
390/// 3. Not have any clobbered regunits live.
391///
392/// This function sets InsertionPoint and returns true when successful, it
393/// returns false if no valid insertion point could be found.
394///
395bool SSAIfConv::findInsertionPoint() {
396 // Keep track of live regunits before the current position.
397 // Only track RegUnits that are also in ClobberedRegUnits.
398 LiveRegUnits.clear();
403 while (I != B) {
404 --I;
405 // Some of the conditional code depends in I.
406 if (InsertAfter.count(&*I)) {
407 LLVM_DEBUG(dbgs() << "Can't insert code after " << *I);
408 return false;
409 }
410
411 // Update live regunits.
412 for (const MachineOperand &MO : I->operands()) {
413 // We're ignoring regmask operands. That is conservatively correct.
414 if (!MO.isReg())
415 continue;
416 Register Reg = MO.getReg();
417 if (!Reg.isPhysical())
418 continue;
419 // I clobbers Reg, so it isn't live before I.
420 if (MO.isDef())
421 for (MCRegUnit Unit : TRI->regunits(Reg.asMCReg()))
422 LiveRegUnits.erase(Unit);
423 // Unless I reads Reg.
424 if (MO.readsReg())
425 Reads.push_back(Reg.asMCReg());
426 }
427 // Anything read by I is live before I.
428 while (!Reads.empty())
429 for (MCRegUnit Unit : TRI->regunits(Reads.pop_back_val()))
430 if (ClobberedRegUnits.test(static_cast<unsigned>(Unit)))
431 LiveRegUnits.insert(Unit);
432
433 // We can't insert before a terminator.
434 if (I != FirstTerm && I->isTerminator())
435 continue;
436
437 // Some of the clobbered registers are live before I, not a valid insertion
438 // point.
439 if (!LiveRegUnits.empty()) {
440 LLVM_DEBUG({
441 dbgs() << "Would clobber";
442 for (MCRegUnit LRU : LiveRegUnits)
443 dbgs() << ' ' << printRegUnit(LRU, TRI);
444 dbgs() << " live before " << *I;
445 });
446 continue;
447 }
448
449 // This is a valid insertion point.
450 InsertionPoint = I;
451 LLVM_DEBUG(dbgs() << "Can insert before " << *I);
452 return true;
453 }
454 LLVM_DEBUG(dbgs() << "No legal insertion point found.\n");
455 return false;
456}
457
458
459
460/// canConvertIf - analyze the sub-cfg rooted in MBB, and return true if it is
461/// a potential candidate for if-conversion. Fill out the internal state.
462///
463bool SSAIfConv::canConvertIf(MachineBasicBlock *MBB, bool Predicate) {
464 Head = MBB;
465 TBB = FBB = Tail = nullptr;
466
467 if (Head->succ_size() != 2)
468 return false;
469 MachineBasicBlock *Succ0 = Head->succ_begin()[0];
470 MachineBasicBlock *Succ1 = Head->succ_begin()[1];
471
472 // Canonicalize so Succ0 has MBB as its single predecessor.
473 if (Succ0->pred_size() != 1)
474 std::swap(Succ0, Succ1);
475
476 if (Succ0->pred_size() != 1 || Succ0->succ_size() != 1)
477 return false;
478
479 Tail = Succ0->succ_begin()[0];
480
481 // This is not a triangle.
482 if (Tail != Succ1) {
483 // Check for a diamond. We won't deal with any critical edges.
484 if (Succ1->pred_size() != 1 || Succ1->succ_size() != 1 ||
485 Succ1->succ_begin()[0] != Tail)
486 return false;
487 LLVM_DEBUG(dbgs() << "\nDiamond: " << printMBBReference(*Head) << " -> "
488 << printMBBReference(*Succ0) << "/"
489 << printMBBReference(*Succ1) << " -> "
490 << printMBBReference(*Tail) << '\n');
491
492 // Live-in physregs are tricky to get right when speculating code.
493 if (!Tail->livein_empty()) {
494 LLVM_DEBUG(dbgs() << "Tail has live-ins.\n");
495 return false;
496 }
497 } else {
498 LLVM_DEBUG(dbgs() << "\nTriangle: " << printMBBReference(*Head) << " -> "
499 << printMBBReference(*Succ0) << " -> "
500 << printMBBReference(*Tail) << '\n');
501 }
502
503 // This is a triangle or a diamond.
504 // Skip if we cannot predicate and there are no phis skip as there must be
505 // side effects that can only be handled with predication.
506 if (!Predicate && (Tail->empty() || !Tail->front().isPHI())) {
507 LLVM_DEBUG(dbgs() << "No phis in tail.\n");
508 return false;
509 }
510
511 // The branch we're looking to eliminate must be analyzable.
512 Cond.clear();
513 if (TII->analyzeBranch(*Head, TBB, FBB, Cond)) {
514 LLVM_DEBUG(dbgs() << "Branch not analyzable.\n");
515 return false;
516 }
517
518 // This is weird, probably some sort of degenerate CFG.
519 if (!TBB) {
520 LLVM_DEBUG(dbgs() << "analyzeBranch didn't find conditional branch.\n");
521 return false;
522 }
523
524 // Make sure the analyzed branch is conditional; one of the successors
525 // could be a landing pad. (Empty landing pads can be generated on Windows.)
526 if (Cond.empty()) {
527 LLVM_DEBUG(dbgs() << "analyzeBranch found an unconditional branch.\n");
528 return false;
529 }
530
531 // analyzeBranch doesn't set FBB on a fall-through branch.
532 // Make sure it is always set.
533 FBB = TBB == Succ0 ? Succ1 : Succ0;
534
535 // Any phis in the tail block must be convertible to selects.
536 PHIs.clear();
537 MachineBasicBlock *TPred = getTPred();
538 MachineBasicBlock *FPred = getFPred();
539 for (MachineBasicBlock::iterator I = Tail->begin(), E = Tail->end();
540 I != E && I->isPHI(); ++I) {
541 PHIs.push_back(&*I);
542 PHIInfo &PI = PHIs.back();
543 // Find PHI operands corresponding to TPred and FPred.
544 for (unsigned i = 1; i != PI.PHI->getNumOperands(); i += 2) {
545 if (PI.PHI->getOperand(i+1).getMBB() == TPred)
546 PI.TReg = PI.PHI->getOperand(i).getReg();
547 if (PI.PHI->getOperand(i+1).getMBB() == FPred)
548 PI.FReg = PI.PHI->getOperand(i).getReg();
549 }
550 assert(PI.TReg.isVirtual() && "Bad PHI");
551 assert(PI.FReg.isVirtual() && "Bad PHI");
552
553 // Get target information.
554 if (!TII->canInsertSelect(*Head, Cond, PI.PHI->getOperand(0).getReg(),
555 PI.TReg, PI.FReg, PI.CondCycles, PI.TCycles,
556 PI.FCycles)) {
557 LLVM_DEBUG(dbgs() << "Can't convert: " << *PI.PHI);
558 return false;
559 }
560 }
561
562 // Check that the conditional instructions can be speculated.
563 InsertAfter.clear();
564 ClobberedRegUnits.reset();
565 if (Predicate) {
566 if (TBB != Tail && !canPredicateInstrs(TBB))
567 return false;
568 if (FBB != Tail && !canPredicateInstrs(FBB))
569 return false;
570 } else {
571 if (TBB != Tail && !canSpeculateInstrs(TBB))
572 return false;
573 if (FBB != Tail && !canSpeculateInstrs(FBB))
574 return false;
575 }
576
577 // Try to find a valid insertion point for the speculated instructions in the
578 // head basic block.
579 if (!findInsertionPoint())
580 return false;
581
582 if (isTriangle())
583 ++NumTrianglesSeen;
584 else
585 ++NumDiamondsSeen;
586 return true;
587}
588
589/// \return true iff the two registers are known to have the same value.
590static bool hasSameValue(const MachineRegisterInfo &MRI,
591 const TargetInstrInfo *TII, Register TReg,
592 Register FReg) {
593 if (TReg == FReg)
594 return true;
595
596 if (!TReg.isVirtual() || !FReg.isVirtual())
597 return false;
598
599 const MachineInstr *TDef = MRI.getUniqueVRegDef(TReg);
600 const MachineInstr *FDef = MRI.getUniqueVRegDef(FReg);
601 if (!TDef || !FDef)
602 return false;
603
604 // If there are side-effects, all bets are off.
605 if (TDef->hasUnmodeledSideEffects())
606 return false;
607
608 // If the instruction could modify memory, or there may be some intervening
609 // store between the two, we can't consider them to be equal.
610 if (TDef->mayLoadOrStore() && !TDef->isDereferenceableInvariantLoad())
611 return false;
612
613 // We also can't guarantee that they are the same if, for example, the
614 // instructions are both a copy from a physical reg, because some other
615 // instruction may have modified the value in that reg between the two
616 // defining insts.
617 if (any_of(TDef->uses(), [](const MachineOperand &MO) {
618 return MO.isReg() && MO.getReg().isPhysical();
619 }))
620 return false;
621
622 // Check whether the two defining instructions produce the same value(s).
623 if (!TII->produceSameValue(*TDef, *FDef, &MRI))
624 return false;
625
626 // Further, check that the two defs come from corresponding operands.
627 int TIdx = TDef->findRegisterDefOperandIdx(TReg, /*TRI=*/nullptr);
628 int FIdx = FDef->findRegisterDefOperandIdx(FReg, /*TRI=*/nullptr);
629 if (TIdx == -1 || FIdx == -1)
630 return false;
631
632 return TIdx == FIdx;
633}
634
635/// replacePHIInstrs - Completely replace PHI instructions with selects.
636/// This is possible when the only Tail predecessors are the if-converted
637/// blocks.
638void SSAIfConv::replacePHIInstrs() {
639 assert(Tail->pred_size() == 2 && "Cannot replace PHIs");
641 assert(FirstTerm != Head->end() && "No terminators");
642 DebugLoc HeadDL = FirstTerm->getDebugLoc();
643
644 // Convert all PHIs to select instructions inserted before FirstTerm.
645 for (PHIInfo &PI : PHIs) {
646 LLVM_DEBUG(dbgs() << "If-converting " << *PI.PHI);
647 Register DstReg = PI.PHI->getOperand(0).getReg();
648 if (hasSameValue(*MRI, TII, PI.TReg, PI.FReg)) {
649 // We do not need the select instruction if both incoming values are
650 // equal, but we do need a COPY.
651 BuildMI(*Head, FirstTerm, HeadDL, TII->get(TargetOpcode::COPY), DstReg)
652 .addReg(PI.TReg);
653 } else {
654 TII->insertSelect(*Head, FirstTerm, HeadDL, DstReg, Cond, PI.TReg,
655 PI.FReg);
656 }
657 LLVM_DEBUG(dbgs() << " --> " << *std::prev(FirstTerm));
658 PI.PHI->eraseFromParent();
659 PI.PHI = nullptr;
660 }
661}
662
663/// rewritePHIOperands - When there are additional Tail predecessors, insert
664/// select instructions in Head and rewrite PHI operands to use the selects.
665/// Keep the PHI instructions in Tail to handle the other predecessors.
666void SSAIfConv::rewritePHIOperands() {
668 assert(FirstTerm != Head->end() && "No terminators");
669 DebugLoc HeadDL = FirstTerm->getDebugLoc();
670
671 // Convert all PHIs to select instructions inserted before FirstTerm.
672 for (PHIInfo &PI : PHIs) {
673 Register DstReg;
674
675 LLVM_DEBUG(dbgs() << "If-converting " << *PI.PHI);
676 if (hasSameValue(*MRI, TII, PI.TReg, PI.FReg)) {
677 // We do not need the select instruction if both incoming values are
678 // equal.
679 DstReg = PI.TReg;
680 } else {
681 Register PHIDst = PI.PHI->getOperand(0).getReg();
682 DstReg = MRI->createVirtualRegister(MRI->getRegClass(PHIDst));
683 TII->insertSelect(*Head, FirstTerm, HeadDL,
684 DstReg, Cond, PI.TReg, PI.FReg);
685 LLVM_DEBUG(dbgs() << " --> " << *std::prev(FirstTerm));
686 }
687
688 // Rewrite PHI operands TPred -> (DstReg, Head), remove FPred.
689 for (unsigned i = PI.PHI->getNumOperands(); i != 1; i -= 2) {
690 MachineBasicBlock *MBB = PI.PHI->getOperand(i-1).getMBB();
691 if (MBB == getTPred()) {
692 PI.PHI->getOperand(i-1).setMBB(Head);
693 PI.PHI->getOperand(i-2).setReg(DstReg);
694 } else if (MBB == getFPred()) {
695 PI.PHI->removeOperand(i-1);
696 PI.PHI->removeOperand(i-2);
697 }
698 }
699 LLVM_DEBUG(dbgs() << " --> " << *PI.PHI);
700 }
701}
702
703void SSAIfConv::clearRepeatedKillFlagsFromTBB(MachineBasicBlock *TBB,
704 MachineBasicBlock *FBB) {
705 assert(TBB != FBB);
706
707 // Collect virtual registers killed in FBB.
708 SmallDenseSet<Register> FBBKilledRegs;
709 for (MachineInstr &MI : FBB->instrs()) {
710 for (MachineOperand &MO : MI.operands()) {
711 if (MO.isReg() && MO.isKill() && MO.getReg().isVirtual())
712 FBBKilledRegs.insert(MO.getReg());
713 }
714 }
715
716 if (FBBKilledRegs.empty())
717 return;
718
719 // Find the same killed registers in TBB and clear kill flags for them.
720 for (MachineInstr &MI : TBB->instrs()) {
721 for (MachineOperand &MO : MI.operands()) {
722 if (MO.isReg() && MO.isKill() && FBBKilledRegs.contains(MO.getReg()))
723 MO.setIsKill(false);
724 }
725 }
726}
727
728/// convertIf - Execute the if conversion after canConvertIf has determined the
729/// feasibility.
730///
731/// Any basic blocks that need to be erased will be added to RemoveBlocks.
732///
733void SSAIfConv::convertIf(SmallVectorImpl<MachineBasicBlock *> &RemoveBlocks,
734 bool Predicate) {
735 assert(Head && Tail && TBB && FBB && "Call canConvertIf first.");
736
737 // Update statistics.
738 if (isTriangle())
739 ++NumTrianglesConv;
740 else
741 ++NumDiamondsConv;
742
743 // If both blocks are going to be merged into Head, remove "killed" flag in
744 // TBB for registers, which are killed in TBB and FBB. Otherwise, register
745 // will be killed twice in Head after splice. Register killed twice is an
746 // incorrect MIR.
747 if (TBB != Tail && FBB != Tail)
748 clearRepeatedKillFlagsFromTBB(TBB, FBB);
749
750 // Move all instructions into Head, except for the terminators.
751 if (TBB != Tail) {
752 if (Predicate)
753 PredicateBlock(TBB, /*ReversePredicate=*/false);
754 Head->splice(InsertionPoint, TBB, TBB->begin(), TBB->getFirstTerminator());
755 }
756 if (FBB != Tail) {
757 if (Predicate)
758 PredicateBlock(FBB, /*ReversePredicate=*/true);
759 Head->splice(InsertionPoint, FBB, FBB->begin(), FBB->getFirstTerminator());
760 }
761 // Are there extra Tail predecessors?
762 bool ExtraPreds = Tail->pred_size() != 2;
763 if (ExtraPreds)
764 rewritePHIOperands();
765 else
766 replacePHIInstrs();
767
768 // Fix up the CFG, temporarily leave Head without any successors.
769 Head->removeSuccessor(TBB);
770 Head->removeSuccessor(FBB, true);
771 if (TBB != Tail)
772 TBB->removeSuccessor(Tail, true);
773 if (FBB != Tail)
774 FBB->removeSuccessor(Tail, true);
775
776 // Fix up Head's terminators.
777 // It should become a single branch or a fallthrough.
778 DebugLoc HeadDL = Head->getFirstTerminator()->getDebugLoc();
779 TII->removeBranch(*Head);
780
781 // Mark the now empty conditional blocks for removal and move them to the end.
782 // It is likely that Head can fall
783 // through to Tail, and we can join the two blocks.
784 if (TBB != Tail) {
785 RemoveBlocks.push_back(TBB);
786 if (TBB != &TBB->getParent()->back())
787 TBB->moveAfter(&TBB->getParent()->back());
788 }
789 if (FBB != Tail) {
790 RemoveBlocks.push_back(FBB);
791 if (FBB != &FBB->getParent()->back())
792 FBB->moveAfter(&FBB->getParent()->back());
793 }
794
795 assert(Head->succ_empty() && "Additional head successors?");
796 if (!ExtraPreds && Head->isLayoutSuccessor(Tail)) {
797 // Splice Tail onto the end of Head.
798 LLVM_DEBUG(dbgs() << "Joining tail " << printMBBReference(*Tail)
799 << " into head " << printMBBReference(*Head) << '\n');
800 Head->splice(Head->end(), Tail,
801 Tail->begin(), Tail->end());
803 RemoveBlocks.push_back(Tail);
804 if (Tail != &Tail->getParent()->back())
805 Tail->moveAfter(&Tail->getParent()->back());
806 } else {
807 // We need a branch to Tail, let code placement work it out later.
808 LLVM_DEBUG(dbgs() << "Converting to unconditional branch.\n");
810 TII->insertBranch(*Head, Tail, nullptr, EmptyCond, HeadDL);
811 Head->addSuccessor(Tail);
812 }
813 LLVM_DEBUG(dbgs() << *Head);
814}
815
816//===----------------------------------------------------------------------===//
817// EarlyIfConverter Pass
818//===----------------------------------------------------------------------===//
819
820namespace {
821class EarlyIfConverter {
822 const TargetInstrInfo *TII = nullptr;
823 const TargetRegisterInfo *TRI = nullptr;
824 const TargetSubtargetInfo *STI = nullptr;
825 MachineRegisterInfo *MRI = nullptr;
826 MachineDominatorTree *DomTree = nullptr;
827 MachineLoopInfo *Loops = nullptr;
828 MachineTraceMetrics *Traces = nullptr;
829 MachineTraceMetrics::Ensemble *MinInstr = nullptr;
830 MachineBranchProbabilityInfo *MBPI = nullptr;
831 SSAIfConv IfConv;
832
833public:
834 EarlyIfConverter(MachineDominatorTree &DT, MachineLoopInfo &LI,
835 MachineTraceMetrics &MTM, MachineBranchProbabilityInfo *MBPI)
836 : DomTree(&DT), Loops(&LI), Traces(&MTM), MBPI(MBPI) {}
837 EarlyIfConverter() = delete;
838
839 bool run(MachineFunction &MF);
840
841private:
842 bool tryConvertIf(MachineBasicBlock *);
843 void invalidateTraces();
844 bool shouldConvertIf();
845 bool isConditionDataDependent();
846 bool doOperandsComeFromMemory(Register Reg);
847};
848
849class EarlyIfConverterLegacy : public MachineFunctionPass {
850public:
851 static char ID;
852 EarlyIfConverterLegacy() : MachineFunctionPass(ID) {}
853 void getAnalysisUsage(AnalysisUsage &AU) const override;
854 bool runOnMachineFunction(MachineFunction &MF) override;
855 StringRef getPassName() const override { return "Early If-Conversion"; }
856};
857} // end anonymous namespace
858
859char EarlyIfConverterLegacy::ID = 0;
860char &llvm::EarlyIfConverterLegacyID = EarlyIfConverterLegacy::ID;
861
862INITIALIZE_PASS_BEGIN(EarlyIfConverterLegacy, DEBUG_TYPE, "Early If Converter",
863 false, false)
867INITIALIZE_PASS_END(EarlyIfConverterLegacy, DEBUG_TYPE, "Early If Converter",
869
870void EarlyIfConverterLegacy::getAnalysisUsage(AnalysisUsage &AU) const {
871 AU.addPreserved<MachineRegisterClassInfoWrapperPass>();
873 AU.addRequired<MachineDominatorTreeWrapperPass>();
874 AU.addPreserved<MachineDominatorTreeWrapperPass>();
875 AU.addRequired<MachineLoopInfoWrapperPass>();
876 AU.addPreserved<MachineLoopInfoWrapperPass>();
877 AU.addRequired<MachineTraceMetricsWrapperPass>();
878 AU.addPreserved<MachineTraceMetricsWrapperPass>();
880}
881
882namespace {
883/// Update the dominator tree after if-conversion erased some blocks.
884void updateDomTree(MachineDominatorTree *DomTree, const SSAIfConv &IfConv,
886 // convertIf can remove TBB, FBB, and Tail can be merged into Head.
887 // TBB and FBB should not dominate any blocks.
888 // Tail children should be transferred to Head.
889 MachineDomTreeNode *HeadNode = DomTree->getNode(IfConv.Head);
890 for (auto *B : Removed) {
891 MachineDomTreeNode *Node = DomTree->getNode(B);
892 assert(Node != HeadNode && "Cannot erase the head node");
893 while (!Node->isLeaf()) {
894 assert(Node->getBlock() == IfConv.Tail && "Unexpected children");
895 DomTree->changeImmediateDominator(*Node->begin(), HeadNode);
896 }
897 DomTree->eraseNode(B);
898 }
899}
900
901/// Update LoopInfo after if-conversion.
902void updateLoops(MachineLoopInfo *Loops,
904 // If-conversion doesn't change loop structure, and it doesn't mess with back
905 // edges, so updating LoopInfo is simply removing the dead blocks.
906 for (auto *B : Removed)
907 Loops->removeBlock(B);
908}
909} // namespace
910
911/// Invalidate MachineTraceMetrics before if-conversion.
912void EarlyIfConverter::invalidateTraces() {
913 Traces->verifyAnalysis();
914 Traces->invalidate(IfConv.Head);
915 Traces->invalidate(IfConv.Tail);
916 Traces->invalidate(IfConv.TBB);
917 Traces->invalidate(IfConv.FBB);
918 Traces->verifyAnalysis();
919}
920
921static bool isConstantPoolLoad(const MachineInstr *MI) {
922 return MI->mayLoad() && any_of(MI->memoperands(), [](MachineMemOperand *MOp) {
923 const PseudoSourceValue *PSV = MOp->getPseudoValue();
924 return PSV && PSV->isConstantPool();
925 });
926}
927
928/// Check if there are any calls in the range (From, To].
929static bool callInRange(const MachineInstr *From, const MachineInstr *To) {
930 constexpr int MaxInstructionsToCheck = 64;
931 int Count = 0;
932 auto InstrRange =
933 make_range(std::next(From->getIterator()), To->getIterator());
934 return any_of(InstrRange, [&](const MachineInstr &MI) {
935 return ++Count > MaxInstructionsToCheck || MI.isCall();
936 });
937}
938
939/// Check if a register's value comes from a memory load by walking the
940/// def-use chain. We want to prioritize converting branches which
941/// depend on values loaded from memory (unless they are loop invariant,
942/// or come from a constant pool). Only consider loads that are in the
943/// same basic block as the branch to ensure the load is "immediately"
944/// before the branch in program time.
945bool EarlyIfConverter::doOperandsComeFromMemory(Register Reg) {
946 if (!Reg.isVirtual())
947 return false;
948
949 // Walk the def-use chain.
950 SmallPtrSet<const MachineInstr *, 8> VisitedInstrs;
951 SmallVector<const MachineInstr *> Worklist;
952 SmallVector<Register, 16> VisitedRegs;
953
954 MachineInstr *DefMI = MRI->getVRegDef(Reg);
955 // The operand is defined outside of the function - it does not
956 // come from memory access.
957 if (!DefMI)
958 return false;
959
960 Worklist.push_back(DefMI);
961 VisitedRegs.push_back(Reg);
962
963 while (!Worklist.empty() && VisitedInstrs.size() < MaxNumSteps) {
964 const MachineInstr *MI = Worklist.pop_back_val();
965 if (!VisitedInstrs.insert(MI).second)
966 continue;
967
968 // Stop walking if we encounter an instruction outside the head block.
969 if (MI->getParent() != IfConv.Head)
970 break;
971
972 // Check if this instruction is a load, and there are no calls between
973 // the load and the branch (which would break the "close in time"
974 // assumption).
975 if (MI->mayLoad() && !isConstantPoolLoad(MI) &&
976 !MI->isDereferenceableInvariantLoad() &&
977 !callInRange(MI, &*IfConv.Head->getFirstTerminator()))
978 return true;
979
980 // Walk through all register use operands and find their definitions.
981 for (const MachineOperand &MO : MI->operands()) {
982 if (!MO.isReg() || !MO.isUse())
983 continue;
984 Register UseReg = MO.getReg();
985 if (!UseReg.isVirtual())
986 continue;
987
988 if (MachineInstr *UseDef = MRI->getVRegDef(UseReg)) {
989 if (!VisitedInstrs.count(UseDef)) {
990 Worklist.push_back(UseDef);
991 VisitedRegs.push_back(UseReg);
992 }
993 }
994 }
995 }
996
997 return false;
998}
999
1000/// Check if the branch condition is data-dependent (comes from memory loads).
1001bool EarlyIfConverter::isConditionDataDependent() {
1002 TargetInstrInfo::MachineBranchPredicate MBP;
1003 if (TII->analyzeBranchPredicate(*IfConv.Head, MBP, /*AllowModify=*/false))
1004 return false;
1005
1006 if (!MBP.ConditionDef)
1007 return false;
1008
1009 // If the branch is biased (not 50/50), don't consider it data dependent.
1010 // This is to prevent converting unprofitable checks such as
1011 // `x[i] != 0;`
1012 auto TBBProb = MBPI->getEdgeProbability(IfConv.Head, IfConv.TBB);
1013 auto FBBProb = MBPI->getEdgeProbability(IfConv.Head, IfConv.FBB);
1014 if (TBBProb != FBBProb) {
1015 ++NumLikelyBiased;
1016 return false;
1017 }
1018
1019 // Check if operands used to compute the branch condition were loaded recently
1020 // from memory, starting by the ConditionDef itself and walking up the use-def
1021 // chain.
1022 if (doOperandsComeFromMemory(MBP.ConditionDef->getOperand(0).getReg())) {
1023 ++NumDataDependant;
1024 return true;
1025 }
1026
1027 return false;
1028}
1029
1030// Adjust cycles with downward saturation.
1031static unsigned adjCycles(unsigned Cyc, int Delta) {
1032 if (Delta < 0 && Cyc + Delta > Cyc)
1033 return 0;
1034 return Cyc + Delta;
1035}
1036
1037namespace {
1038/// Helper class to simplify emission of cycle counts into optimization remarks.
1039struct Cycles {
1040 const char *Key;
1041 unsigned Value;
1042};
1043template <typename Remark> Remark &operator<<(Remark &R, Cycles C) {
1044 return R << ore::NV(C.Key, C.Value) << (C.Value == 1 ? " cycle" : " cycles");
1045}
1046} // anonymous namespace
1047
1048/// Apply cost model and heuristics to the if-conversion in IfConv.
1049/// Return true if the conversion is a good idea.
1050///
1051bool EarlyIfConverter::shouldConvertIf() {
1052 // Stress testing mode disables all cost considerations.
1053 if (Stress)
1054 return true;
1055
1056 // Do not try to if-convert if the condition has a high chance of being
1057 // predictable.
1058 MachineLoop *CurrentLoop = Loops->getLoopFor(IfConv.Head);
1059 // If the condition is in a loop, consider it predictable if the condition
1060 // itself or all its operands are loop-invariant. E.g. this considers a load
1061 // from a loop-invariant address predictable; we were unable to prove that it
1062 // doesn't alias any of the memory-writes in the loop, but it is likely to
1063 // read to same value multiple times.
1064 if (CurrentLoop && any_of(IfConv.Cond, [&](MachineOperand &MO) {
1065 if (!MO.isReg() || !MO.isUse())
1066 return false;
1067 Register Reg = MO.getReg();
1068 if (Reg.isPhysical())
1069 return false;
1070
1071 MachineInstr *Def = MRI->getVRegDef(Reg);
1072 return CurrentLoop->isLoopInvariant(*Def) ||
1073 all_of(Def->operands(), [&](MachineOperand &Op) {
1074 if (Op.isImm())
1075 return true;
1076 if (!Op.isReg() || !Op.isUse())
1077 return true;
1078 Register Reg = Op.getReg();
1079 if (Reg.isPhysical())
1080 return false;
1081
1082 MachineInstr *Def = MRI->getVRegDef(Reg);
1083 return CurrentLoop->isLoopInvariant(*Def);
1084 });
1085 }))
1086 return false;
1087
1088 if (!MinInstr)
1089 MinInstr = Traces->getEnsemble(MachineTraceStrategy::TS_MinInstrCount);
1090
1091 MachineTraceMetrics::Trace TBBTrace = MinInstr->getTrace(IfConv.getTPred());
1092 MachineTraceMetrics::Trace FBBTrace = MinInstr->getTrace(IfConv.getFPred());
1093 LLVM_DEBUG(dbgs() << "TBB: " << TBBTrace << "FBB: " << FBBTrace);
1094 unsigned MinCrit = std::min(TBBTrace.getCriticalPath(),
1095 FBBTrace.getCriticalPath());
1096
1097 // Set a somewhat arbitrary limit on the critical path extension we accept.
1098 // When hard-to-predict analysis is enabled, use full MispredictPenalty for
1099 // hard-to-predict branches, half for others. Otherwise use half for all.
1100 bool DataDependent = false;
1102 DataDependent = isConditionDataDependent();
1103
1104 unsigned CritLimit = DataDependent ? STI->getMispredictionPenalty()
1105 : STI->getMispredictionPenalty() / 2;
1106
1107 MachineBasicBlock &MBB = *IfConv.Head;
1108 MachineOptimizationRemarkEmitter MORE(*MBB.getParent(), nullptr);
1109
1110 // Emit analysis remark about data-dependent condition.
1111 if (DataDependent) {
1112 MORE.emit([&]() {
1113 return MachineOptimizationRemarkAnalysis(DEBUG_TYPE,
1114 "DataDependentCondition",
1115 MBB.back().getDebugLoc(), &MBB)
1116 << "branch condition is data-dependent (from memory load), "
1117 << "using higher CritLimit of " << ore::NV("CritLimit", CritLimit)
1118 << " cycles";
1119 });
1120 }
1121
1122 // If-conversion only makes sense when there is unexploited ILP. Compute the
1123 // maximum-ILP resource length of the trace after if-conversion. Compare it
1124 // to the shortest critical path.
1126 if (IfConv.TBB != IfConv.Tail)
1127 ExtraBlocks.push_back(IfConv.TBB);
1128 unsigned ResLength = FBBTrace.getResourceLength(ExtraBlocks);
1129 LLVM_DEBUG(dbgs() << "Resource length " << ResLength
1130 << ", minimal critical path " << MinCrit << '\n');
1131 if (ResLength > MinCrit + CritLimit) {
1132 LLVM_DEBUG(dbgs() << "Not enough available ILP.\n");
1133 MORE.emit([&]() {
1134 MachineOptimizationRemarkMissed R(DEBUG_TYPE, "IfConversion",
1135 MBB.findDebugLoc(MBB.back()), &MBB);
1136 R << "did not if-convert branch: the resulting critical path ("
1137 << Cycles{"ResLength", ResLength}
1138 << ") would extend the shorter leg's critical path ("
1139 << Cycles{"MinCrit", MinCrit} << ") by more than the threshold of "
1140 << Cycles{"CritLimit", CritLimit}
1141 << ", which cannot be hidden by available ILP.";
1142 return R;
1143 });
1144 return false;
1145 }
1146
1147 // Assume that the depth of the first head terminator will also be the depth
1148 // of the select instruction inserted, as determined by the flag dependency.
1149 // TBB / FBB data dependencies may delay the select even more.
1150 MachineTraceMetrics::Trace HeadTrace = MinInstr->getTrace(IfConv.Head);
1151 unsigned BranchDepth =
1152 HeadTrace.getInstrCycles(*IfConv.Head->getFirstTerminator()).Depth;
1153 LLVM_DEBUG(dbgs() << "Branch depth: " << BranchDepth << '\n');
1154
1155 // Look at all the tail phis, and compute the critical path extension caused
1156 // by inserting select instructions.
1157 MachineTraceMetrics::Trace TailTrace = MinInstr->getTrace(IfConv.Tail);
1158 struct CriticalPathInfo {
1159 unsigned Extra; // Count of extra cycles that the component adds.
1160 unsigned Depth; // Absolute depth of the component in cycles.
1161 };
1162 CriticalPathInfo Cond{};
1163 CriticalPathInfo TBlock{};
1164 CriticalPathInfo FBlock{};
1165 bool ShouldConvert = true;
1166 for (SSAIfConv::PHIInfo &PI : IfConv.PHIs) {
1167 unsigned Slack = TailTrace.getInstrSlack(*PI.PHI);
1168 unsigned MaxDepth = Slack + TailTrace.getInstrCycles(*PI.PHI).Depth;
1169 LLVM_DEBUG(dbgs() << "Slack " << Slack << ":\t" << *PI.PHI);
1170
1171 // The condition is pulled into the critical path.
1172 unsigned CondDepth = adjCycles(BranchDepth, PI.CondCycles);
1173 if (CondDepth > MaxDepth) {
1174 unsigned Extra = CondDepth - MaxDepth;
1175 LLVM_DEBUG(dbgs() << "Condition adds " << Extra << " cycles.\n");
1176 if (Extra > Cond.Extra)
1177 Cond = {Extra, CondDepth};
1178 if (Extra > CritLimit) {
1179 LLVM_DEBUG(dbgs() << "Exceeds limit of " << CritLimit << '\n');
1180 ShouldConvert = false;
1181 }
1182 }
1183
1184 // The TBB value is pulled into the critical path.
1185 unsigned TDepth = adjCycles(TBBTrace.getPHIDepth(*PI.PHI), PI.TCycles);
1186 if (TDepth > MaxDepth) {
1187 unsigned Extra = TDepth - MaxDepth;
1188 LLVM_DEBUG(dbgs() << "TBB data adds " << Extra << " cycles.\n");
1189 if (Extra > TBlock.Extra)
1190 TBlock = {Extra, TDepth};
1191 if (Extra > CritLimit) {
1192 LLVM_DEBUG(dbgs() << "Exceeds limit of " << CritLimit << '\n');
1193 ShouldConvert = false;
1194 }
1195 }
1196
1197 // The FBB value is pulled into the critical path.
1198 unsigned FDepth = adjCycles(FBBTrace.getPHIDepth(*PI.PHI), PI.FCycles);
1199 if (FDepth > MaxDepth) {
1200 unsigned Extra = FDepth - MaxDepth;
1201 LLVM_DEBUG(dbgs() << "FBB data adds " << Extra << " cycles.\n");
1202 if (Extra > FBlock.Extra)
1203 FBlock = {Extra, FDepth};
1204 if (Extra > CritLimit) {
1205 LLVM_DEBUG(dbgs() << "Exceeds limit of " << CritLimit << '\n');
1206 ShouldConvert = false;
1207 }
1208 }
1209 }
1210
1211 // Organize by "short" and "long" legs, since the diagnostics get confusing
1212 // when referring to the "true" and "false" sides of the branch, given that
1213 // those don't always correlate with what the user wrote in source-terms.
1214 const CriticalPathInfo Short = TBlock.Extra > FBlock.Extra ? FBlock : TBlock;
1215 const CriticalPathInfo Long = TBlock.Extra > FBlock.Extra ? TBlock : FBlock;
1216
1217 if (ShouldConvert) {
1218 MORE.emit([&]() {
1219 MachineOptimizationRemark R(DEBUG_TYPE, "IfConversion",
1220 MBB.back().getDebugLoc(), &MBB);
1221 R << "performing if-conversion on branch: the condition adds "
1222 << Cycles{"CondCycles", Cond.Extra} << " to the critical path";
1223 if (Short.Extra > 0)
1224 R << ", and the short leg adds another "
1225 << Cycles{"ShortCycles", Short.Extra};
1226 if (Long.Extra > 0)
1227 R << ", and the long leg adds another "
1228 << Cycles{"LongCycles", Long.Extra};
1229 R << ", each staying under the threshold of "
1230 << Cycles{"CritLimit", CritLimit} << ".";
1231 return R;
1232 });
1233 } else {
1234 MORE.emit([&]() {
1235 MachineOptimizationRemarkMissed R(DEBUG_TYPE, "IfConversion",
1236 MBB.back().getDebugLoc(), &MBB);
1237 R << "did not if-convert branch: the condition would add "
1238 << Cycles{"CondCycles", Cond.Extra} << " to the critical path";
1239 if (Cond.Extra > CritLimit)
1240 R << " exceeding the limit of " << Cycles{"CritLimit", CritLimit};
1241 if (Short.Extra > 0) {
1242 R << ", and the short leg would add another "
1243 << Cycles{"ShortCycles", Short.Extra};
1244 if (Short.Extra > CritLimit)
1245 R << " exceeding the limit of " << Cycles{"CritLimit", CritLimit};
1246 }
1247 if (Long.Extra > 0) {
1248 R << ", and the long leg would add another "
1249 << Cycles{"LongCycles", Long.Extra};
1250 if (Long.Extra > CritLimit)
1251 R << " exceeding the limit of " << Cycles{"CritLimit", CritLimit};
1252 }
1253 R << ".";
1254 return R;
1255 });
1256 }
1257
1258 return ShouldConvert;
1259}
1260
1261/// Attempt repeated if-conversion on MBB, return true if successful.
1262///
1263bool EarlyIfConverter::tryConvertIf(MachineBasicBlock *MBB) {
1264 bool Changed = false;
1265 while (IfConv.canConvertIf(MBB) && shouldConvertIf()) {
1266 // If-convert MBB and update analyses.
1267 invalidateTraces();
1268 SmallVector<MachineBasicBlock *, 4> RemoveBlocks;
1269 IfConv.convertIf(RemoveBlocks);
1270 Changed = true;
1271 updateDomTree(DomTree, IfConv, RemoveBlocks);
1272 updateLoops(Loops, RemoveBlocks);
1273 for (MachineBasicBlock *MBB : RemoveBlocks)
1275 }
1276 return Changed;
1277}
1278
1279bool EarlyIfConverter::run(MachineFunction &MF) {
1280 LLVM_DEBUG(dbgs() << "********** EARLY IF-CONVERSION **********\n"
1281 << "********** Function: " << MF.getName() << '\n');
1282
1283 STI = &MF.getSubtarget();
1284 // Only run if conversion if the target wants it.
1285 if (!STI->enableEarlyIfConversion())
1286 return false;
1287
1288 TII = STI->getInstrInfo();
1289 TRI = STI->getRegisterInfo();
1290 MRI = &MF.getRegInfo();
1291 MinInstr = nullptr;
1292
1293 bool Changed = false;
1294 IfConv.init(MF);
1295
1296 // Visit blocks in dominator tree post-order. The post-order enables nested
1297 // if-conversion in a single pass. The tryConvertIf() function may erase
1298 // blocks, but only blocks dominated by the head block. This makes it safe to
1299 // update the dominator tree while the post-order iterator is still active.
1300 for (auto *DomNode : post_order(DomTree))
1301 if (tryConvertIf(DomNode->getBlock()))
1302 Changed = true;
1303
1304 return Changed;
1305}
1306
1307PreservedAnalyses
1313 MachineBranchProbabilityInfo *MBPI = nullptr;
1316
1317 EarlyIfConverter Impl(MDT, LI, MTM, MBPI);
1318 bool Changed = Impl.run(MF);
1319 if (!Changed)
1320 return PreservedAnalyses::all();
1321
1323 PA.preserve<MachineDominatorTreeAnalysis>();
1324 PA.preserve<MachineLoopAnalysis>();
1325 PA.preserve<MachineTraceMetricsAnalysis>();
1326 return PA;
1327}
1328
1329bool EarlyIfConverterLegacy::runOnMachineFunction(MachineFunction &MF) {
1330 if (skipFunction(MF.getFunction()))
1331 return false;
1332
1334 getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
1335 MachineLoopInfo &LI = getAnalysis<MachineLoopInfoWrapperPass>().getLI();
1336 MachineTraceMetrics &MTM =
1337 getAnalysis<MachineTraceMetricsWrapperPass>().getMTM();
1338 MachineBranchProbabilityInfo *MBPI = nullptr;
1340 MBPI = &getAnalysis<MachineBranchProbabilityInfoWrapperPass>().getMBPI();
1341
1342 return EarlyIfConverter(MDT, LI, MTM, MBPI).run(MF);
1343}
1344
1345//===----------------------------------------------------------------------===//
1346// EarlyIfPredicator Pass
1347//===----------------------------------------------------------------------===//
1348
1349namespace {
1350class EarlyIfPredicator : public MachineFunctionPass {
1351 const TargetInstrInfo *TII = nullptr;
1352 const TargetRegisterInfo *TRI = nullptr;
1353 TargetSchedModel SchedModel;
1354 MachineRegisterInfo *MRI = nullptr;
1355 MachineDominatorTree *DomTree = nullptr;
1356 MachineBranchProbabilityInfo *MBPI = nullptr;
1357 MachineLoopInfo *Loops = nullptr;
1358 SSAIfConv IfConv;
1359
1360public:
1361 static char ID;
1362 EarlyIfPredicator() : MachineFunctionPass(ID) {}
1363 void getAnalysisUsage(AnalysisUsage &AU) const override;
1364 bool runOnMachineFunction(MachineFunction &MF) override;
1365 StringRef getPassName() const override { return "Early If-predicator"; }
1366
1367protected:
1368 bool tryConvertIf(MachineBasicBlock *);
1369 bool shouldConvertIf();
1370};
1371} // end anonymous namespace
1372
1373#undef DEBUG_TYPE
1374#define DEBUG_TYPE "early-if-predicator"
1375
1376char EarlyIfPredicator::ID = 0;
1377char &llvm::EarlyIfPredicatorID = EarlyIfPredicator::ID;
1378
1379INITIALIZE_PASS_BEGIN(EarlyIfPredicator, DEBUG_TYPE, "Early If Predicator",
1380 false, false)
1383INITIALIZE_PASS_END(EarlyIfPredicator, DEBUG_TYPE, "Early If Predicator", false,
1384 false)
1385
1386void EarlyIfPredicator::getAnalysisUsage(AnalysisUsage &AU) const {
1388 AU.addRequired<MachineDominatorTreeWrapperPass>();
1389 AU.addPreserved<MachineDominatorTreeWrapperPass>();
1390 AU.addRequired<MachineLoopInfoWrapperPass>();
1391 AU.addPreserved<MachineLoopInfoWrapperPass>();
1393}
1394
1395/// Apply the target heuristic to decide if the transformation is profitable.
1396bool EarlyIfPredicator::shouldConvertIf() {
1397 auto TrueProbability = MBPI->getEdgeProbability(IfConv.Head, IfConv.TBB);
1398 if (IfConv.isTriangle()) {
1399 MachineBasicBlock &IfBlock =
1400 (IfConv.TBB == IfConv.Tail) ? *IfConv.FBB : *IfConv.TBB;
1401
1402 unsigned ExtraPredCost = 0;
1403 unsigned Cycles = 0;
1404 for (MachineInstr &I : IfBlock) {
1405 unsigned NumCycles = SchedModel.computeInstrLatency(&I, false);
1406 if (NumCycles > 1)
1407 Cycles += NumCycles - 1;
1408 ExtraPredCost += TII->getPredicationCost(I);
1409 }
1410
1411 return TII->isProfitableToIfCvt(IfBlock, Cycles, ExtraPredCost,
1412 TrueProbability);
1413 }
1414 unsigned TExtra = 0;
1415 unsigned FExtra = 0;
1416 unsigned TCycle = 0;
1417 unsigned FCycle = 0;
1418 for (MachineInstr &I : *IfConv.TBB) {
1419 unsigned NumCycles = SchedModel.computeInstrLatency(&I, false);
1420 if (NumCycles > 1)
1421 TCycle += NumCycles - 1;
1422 TExtra += TII->getPredicationCost(I);
1423 }
1424 for (MachineInstr &I : *IfConv.FBB) {
1425 unsigned NumCycles = SchedModel.computeInstrLatency(&I, false);
1426 if (NumCycles > 1)
1427 FCycle += NumCycles - 1;
1428 FExtra += TII->getPredicationCost(I);
1429 }
1430 return TII->isProfitableToIfCvt(*IfConv.TBB, TCycle, TExtra, *IfConv.FBB,
1431 FCycle, FExtra, TrueProbability);
1432}
1433
1434/// Attempt repeated if-conversion on MBB, return true if successful.
1435///
1436bool EarlyIfPredicator::tryConvertIf(MachineBasicBlock *MBB) {
1437 bool Changed = false;
1438 while (IfConv.canConvertIf(MBB, /*Predicate*/ true) && shouldConvertIf()) {
1439 // If-convert MBB and update analyses.
1440 SmallVector<MachineBasicBlock *, 4> RemoveBlocks;
1441 IfConv.convertIf(RemoveBlocks, /*Predicate*/ true);
1442 Changed = true;
1443 updateDomTree(DomTree, IfConv, RemoveBlocks);
1444 updateLoops(Loops, RemoveBlocks);
1445 for (MachineBasicBlock *MBB : RemoveBlocks)
1447 }
1448 return Changed;
1449}
1450
1451bool EarlyIfPredicator::runOnMachineFunction(MachineFunction &MF) {
1452 LLVM_DEBUG(dbgs() << "********** EARLY IF-PREDICATOR **********\n"
1453 << "********** Function: " << MF.getName() << '\n');
1454 if (skipFunction(MF.getFunction()))
1455 return false;
1456
1457 const TargetSubtargetInfo &STI = MF.getSubtarget();
1458 TII = STI.getInstrInfo();
1459 TRI = STI.getRegisterInfo();
1460 MRI = &MF.getRegInfo();
1461 SchedModel.init(&STI);
1462 DomTree = &getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
1463 Loops = &getAnalysis<MachineLoopInfoWrapperPass>().getLI();
1464 MBPI = &getAnalysis<MachineBranchProbabilityInfoWrapperPass>().getMBPI();
1465
1466 bool Changed = false;
1467 IfConv.init(MF);
1468
1469 // Visit blocks in dominator tree post-order. The post-order enables nested
1470 // if-conversion in a single pass. The tryConvertIf() function may erase
1471 // blocks, but only blocks dominated by the head block. This makes it safe to
1472 // update the dominator tree while the post-order iterator is still active.
1473 for (auto *DomNode : post_order(DomTree))
1474 if (tryConvertIf(DomNode->getBlock()))
1475 Changed = true;
1476
1477 return Changed;
1478}
MachineInstrBuilder MachineInstrBuilder & DefMI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
This file implements the BitVector class.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static unsigned InstrCount
This file defines the DenseSet and SmallDenseSet classes.
static cl::opt< unsigned > MaxNumSteps("early-ifcvt-max-steps", cl::Hidden, cl::init(16), cl::desc("Limit the number of steps taken when searching for a " "recently loaded value"))
static bool hasSameValue(const MachineRegisterInfo &MRI, const TargetInstrInfo *TII, Register TReg, Register FReg)
static unsigned adjCycles(unsigned Cyc, int Delta)
static cl::opt< bool > Stress("stress-early-ifcvt", cl::Hidden, cl::desc("Turn all knobs to 11"))
static cl::opt< unsigned > BlockInstrLimit("early-ifcvt-limit", cl::init(30), cl::Hidden, cl::desc("Maximum number of instructions per speculated block."))
static bool isConstantPoolLoad(const MachineInstr *MI)
static cl::opt< bool > EnableDataDependentBranchAnalysis("enable-early-ifcvt-data-dependent", cl::Hidden, cl::init(false), cl::desc("Enable hard-to-predict branch analysis for if-conversion"))
static bool callInRange(const MachineInstr *From, const MachineInstr *To)
Check if there are any calls in the range (From, To].
#define DEBUG_TYPE
static Register UseReg(const MachineOperand &MO)
const HexagonInstrInfo * TII
Hexagon Hardware Loops
IRTranslator LLVM IR MI
#define I(x, y, z)
Definition MD5.cpp:57
===- MachineOptimizationRemarkEmitter.h - Opt Diagnostics -*- C++ -*-—===//
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
This file builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
const SmallVectorImpl< MachineOperand > MachineBasicBlock * TBB
const SmallVectorImpl< MachineOperand > & Cond
This file defines the SmallPtrSet class.
This file defines the SparseSet class derived from the version described in Briggs,...
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:119
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
bool test(unsigned Idx) const
Returns true if bit Idx is set.
Definition BitVector.h:482
BitVector & reset()
Reset all bits in the bitvector.
Definition BitVector.h:409
BitVector & set()
Set all bits in the bitvector.
Definition BitVector.h:366
void changeImmediateDominator(DomTreeNodeBase< NodeT > *N, DomTreeNodeBase< NodeT > *NewIDom)
changeImmediateDominator - This method is used to update the dominator tree information when a node's...
void eraseNode(NodeT *BB)
eraseNode - Removes a node from the dominator tree.
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
unsigned removeBranch(MachineBasicBlock &MBB, int *BytesRemoved=nullptr) const override
Remove the branching code at the end of the specific MBB.
bool isPredicated(const MachineInstr &MI) const override
Returns true if the instruction is already predicated.
bool analyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB, MachineBasicBlock *&FBB, SmallVectorImpl< MachineOperand > &Cond, bool AllowModify) const override
Analyze the branching code at the end of MBB, returning true if it cannot be understood (e....
bool reverseBranchCondition(SmallVectorImpl< MachineOperand > &Cond) const override
Reverses the branch condition of the specified condition list, returning false on success and true if...
unsigned insertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB, MachineBasicBlock *FBB, ArrayRef< MachineOperand > Cond, const DebugLoc &DL, int *BytesAdded=nullptr) const override
Insert branch code into the end of the specified MachineBasicBlock.
bool isProfitableToIfCvt(MachineBasicBlock &MBB, unsigned NumCycles, unsigned ExtraPredCycles, BranchProbability Probability) const override
Return true if it's profitable to predicate instructions with accumulated instruction latency of "Num...
bool PredicateInstruction(MachineInstr &MI, ArrayRef< MachineOperand > Cond) const override
Convert the instruction into a predicated instruction.
bool isPredicable(const MachineInstr &MI) const override
Return true if the specified instruction can be predicated.
LLVM_ABI void transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB)
Transfers all the successors, as in transferSuccessors, and update PHI operands in the successor bloc...
LLVM_ABI iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
LLVM_ABI void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
LLVM_ABI void removeSuccessor(MachineBasicBlock *Succ, bool NormalizeSuccProbs=false)
Remove successor from the successors list of this MachineBasicBlock.
LLVM_ABI DebugLoc findDebugLoc(instr_iterator MBBI)
Find the next valid DebugLoc starting at MBBI, skipping any debug instructions.
LLVM_ABI bool isLayoutSuccessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB will be emitted immediately after this block, such that if this bloc...
LLVM_ABI void eraseFromParent()
This method unlinks 'this' from the containing function and deletes it.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
MachineInstrBundleIterator< MachineInstr > iterator
LLVM_ABI void moveAfter(MachineBasicBlock *NewBefore)
LLVM_ABI BranchProbability getEdgeProbability(const MachineBasicBlock *Src, const MachineBasicBlock *Dst) const
Analysis pass which computes a MachineDominatorTree.
Analysis pass which computes a MachineDominatorTree.
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
const MachineBasicBlock & back() const
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
Representation of each machine instruction.
bool isTerminator(QueryType Type=AnyInBundle) const
Returns true if this instruction part of the terminator for a basic block.
bool mayLoadOrStore(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read or modify memory.
const MachineBasicBlock * getParent() const
LLVM_ABI bool isDereferenceableInvariantLoad() const
Return true if this load instruction never traps and points to a memory location whose value doesn't ...
LLVM_ABI bool hasUnmodeledSideEffects() const
Return true if this instruction has side effects that are not modeled by mayLoad / mayStore,...
mop_range uses()
Returns all operands which may be register uses.
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
const MachineOperand & getOperand(unsigned i) const
LLVM_ABI int findRegisterDefOperandIdx(Register Reg, const TargetRegisterInfo *TRI, bool isDead=false, bool Overlap=false) const
Returns the operand index that is a def of the specified register or -1 if it is not found.
Analysis pass that exposes the MachineLoopInfo for a machine function.
A description of a memory reference used in the backend.
MachineOperand class - Representation of each machine instruction operand.
Register getReg() const
getReg - Returns the register number.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
LLVM_ABI MachineInstr * getVRegDef(Register Reg) const
getVRegDef - Return the machine instr that defines the specified virtual register or null if none is ...
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
LLVM_ABI MachineInstr * getUniqueVRegDef(Register Reg) const
getUniqueVRegDef - Return the unique machine instr that defines the specified virtual register or nul...
LLVM_ABI unsigned getResourceLength(ArrayRef< const MachineBasicBlock * > Extrablocks={}, ArrayRef< const MCSchedClassDesc * > ExtraInstrs={}, ArrayRef< const MCSchedClassDesc * > RemoveInstrs={}) const
Return the resource length of the trace.
InstrCycles getInstrCycles(const MachineInstr &MI) const
Return the depth and height of MI.
LLVM_ABI unsigned getInstrSlack(const MachineInstr &MI) const
Return the slack of MI.
unsigned getCriticalPath() const
Return the length of the (data dependency) critical path through the trace.
LLVM_ABI unsigned getPHIDepth(const MachineInstr &PHI) const
Return the Depth of a PHI instruction in a trace center block successor.
LLVM_ABI void verifyAnalysis() const
LLVM_ABI void invalidate(const MachineBasicBlock *MBB)
Invalidate cached information about MBB.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
Wrapper class representing virtual and physical registers.
Definition Register.h:20
MCRegister asMCReg() const
Utility to check-convert this value to a MCRegister.
Definition Register.h:107
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Definition Register.h:83
size_type size() const
Definition SmallPtrSet.h:99
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
void push_back(const T &Elt)
iterator erase(iterator I)
erase - Erases an existing element identified by a valid iterator.
Definition SparseSet.h:287
void clear()
clear - Clears the set.
Definition SparseSet.h:190
std::pair< iterator, bool > insert(const ValueT &Val)
insert - Attempts to insert a new element.
Definition SparseSet.h:253
bool empty() const
empty - Returns true if the set is empty.
Definition SparseSet.h:179
TargetInstrInfo - Interface to description of machine instruction set.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
Provide an instruction scheduling machine model to CodeGen passes.
LLVM_ABI void init(const TargetSubtargetInfo *TSInfo, bool EnableSModel=true, bool EnableSItins=true)
Initialize the machine model for instruction scheduling.
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
virtual bool enableEarlyIfConversion() const
Enable the use of the early if conversion pass.
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:209
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition DenseSet.h:182
self_iterator getIterator()
Definition ilist_node.h:123
Changed
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ Tail
Attemps to make calls as fast as possible while guaranteeing that tail call optimization can always b...
Definition CallingConv.h:76
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
initializer< Ty > init(const Ty &Val)
DXILDebugInfoMap run(Module &M)
constexpr double phi
DiagnosticInfoOptimizationBase::Argument NV
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
This is an optimization pass for GlobalISel generic memory operations.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
LLVM_ABI Printable printRegUnit(MCRegUnit Unit, const TargetRegisterInfo *TRI)
Create Printable object to print register units on a raw_ostream.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
LLVM_ABI char & EarlyIfConverterLegacyID
EarlyIfConverter - This pass performs if-conversion on SSA form by inserting cmov instructions.
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
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:1746
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
auto post_order(const T &G)
Post-order traversal of a graph.
LLVM_ABI char & EarlyIfPredicatorID
EarlyIfPredicator - This pass performs if-conversion on SSA form by predicating if/else block and ins...
DomTreeNodeBase< MachineBasicBlock > MachineDomTreeNode
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
#define MORE()
Definition regcomp.c:246
unsigned Depth
Earliest issue cycle as determined by data dependencies and instruction latencies from the beginning ...