LLVM 24.0.0git
HexagonGlobalScheduler.cpp
Go to the documentation of this file.
1
2//===----- HexagonGlobalScheduler.cpp - Global Scheduler ------------------===//
3//
4// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
5// See https://llvm.org/LICENSE.txt for license information.
6// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7//
8//===----------------------------------------------------------------------===//
9//
10// Basic infrastructure for the global scheduling + Hexagon pull-up pass.
11// Currently run at the very end of code generation for Hexagon, cleans
12// up lost scheduling opportunities. Currently breaks liveness, so no passes
13// that rely on liveness info should run afterwards. Will be fixed in future
14// versions.
15//
16//===----------------------------------------------------------------------===//
17#include "Hexagon.h"
18#include "HexagonGlobalRegion.h"
19#include "HexagonRegisterInfo.h"
20#include "HexagonSubtarget.h"
22#include "llvm/ADT/DenseMap.h"
23#include "llvm/ADT/SmallSet.h"
24#include "llvm/ADT/Statistic.h"
37#include "llvm/CodeGen/Passes.h"
46#include "llvm/Support/Debug.h"
49
50#include <list>
51#include <map>
52
53#define DEBUG_TYPE "global_sched"
54
55using namespace llvm;
56
57STATISTIC(HexagonNumPullUps, "Number of instructions pull-ups");
58STATISTIC(HexagonNumDualJumps, "Number of dual jumps formed");
59
60static cl::opt<bool> DisablePullUp("disable-pull-up", cl::Hidden,
61 cl::desc("Disable Hexagon pull-up pass"));
62
64 "enable-speculative-pull-up", cl::Hidden,
65 cl::desc("Enable speculation during Hexagon pull-up pass"));
66
68 "enable-local-pull-up", cl::Hidden, cl::init(true),
69 cl::desc("Enable same BB pull during Hexagon pull-up pass"));
70
72 "speculate-loads-on-pull-up", cl::Hidden, cl::init(true),
73 cl::desc("Allow speculative loads during Hexagon pull-up pass"));
74
76 "cmp-branch-loads-pull-up", cl::Hidden, cl::init(true),
77 cl::desc("Allow compare-branch loads during Hexagon pull-up pass"));
78
79static cl::opt<bool> AllowUnlikelyPath("unlikely-path-pull-up", cl::Hidden,
80 cl::init(true),
81 cl::desc("Allow unlikely path pull up"));
82
83static cl::opt<bool>
84 PerformDualJumps("dual-jump-in-pull-up", cl::Hidden, cl::init(true),
85 cl::desc("Perform dual jump formation during pull up"));
86
88 "enable-dependent-pull-up", cl::Hidden, cl::init(true),
89 cl::desc("Perform dual jump formation during pull up"));
90
91static cl::opt<bool>
92 AllowBBPeelPullUp("enable-bb-peel-pull-up", cl::Hidden, cl::init(true),
93 cl::desc("Peel a reg copy out of a BBloop"));
94
96 "prevent-compound-separation", cl::Hidden,
97 cl::desc("Do not destroy existing compounds during pull up"));
98
100 "prevent-duplex-separation", cl::Hidden, cl::init(true),
101 cl::desc("Do not destroy existing duplexes during pull up"));
102
103static cl::opt<unsigned> MainCandidateQueueSize("pull-up-main-queue-size",
104 cl::Hidden, cl::init(8));
105
106static cl::opt<unsigned> SecondaryCandidateQueueSize("pull-up-sec-queue-size",
107 cl::Hidden, cl::init(2));
108
110 "post-pull-up-opt", cl::Hidden, cl::init(true),
111 cl::desc("Enable opt. exposed by pull-up e.g., remove redundant jumps"));
112
114 "speculate-non-pred-insn", cl::Hidden, cl::init(true),
115 cl::desc("Speculate non-predicable instructions in parent BB"));
116
117static cl::opt<bool>
118 DisableCheckBundles("disable-hexagon-check-bundles", cl::Hidden,
119 cl::init(true),
120 cl::desc("Disable Hexagon check bundles pass"));
121
122static cl::opt<bool>
123 WarnOnBundleSize("warn-on-bundle-size", cl::Hidden,
124 cl::desc("Hexagon check bundles and warn on size"));
125
126static cl::opt<bool>
127 ForceNoopHazards("force-noop-hazards", cl::Hidden, cl::init(false),
128 cl::desc("Force noop hazards in scheduler"));
131
132namespace llvm {
135} // namespace llvm
136
137namespace {
138class HexagonGlobalSchedulerImpl;
139
140class HexagonGlobalScheduler : public MachineFunctionPass {
141public:
142 static char ID;
143 HexagonGlobalScheduler() : MachineFunctionPass(ID) {
145 }
146
147 void getAnalysisUsage(AnalysisUsage &AU) const override {
149 AU.addRequired<MachineLoopInfoWrapperPass>();
150 AU.addRequired<AAResultsWrapperPass>();
151 AU.addRequired<MachineBranchProbabilityInfoWrapperPass>();
152 AU.addRequired<MachineBlockFrequencyInfoWrapperPass>();
153 AU.addRequired<MachineDominatorTreeWrapperPass>();
155 }
156
157 StringRef getPassName() const override { return "Hexagon Global Scheduler"; }
158
159 bool runOnMachineFunction(MachineFunction &Fn) override;
160};
161char HexagonGlobalScheduler::ID = 0;
162
163// Describes a single pull-up candidate.
164class PullUpCandidate {
165 MachineBasicBlock::instr_iterator CandidateLocation;
167 bool DependentOp;
168 signed BenefitCost;
169 std::vector<MachineInstr *> Backtrack;
170
171public:
172 PullUpCandidate(MachineBasicBlock::instr_iterator MII) {
173 CandidateLocation = MII;
174 BenefitCost = 0;
175 }
176
177 PullUpCandidate(MachineBasicBlock::instr_iterator MII,
179 std::vector<MachineInstr *> &backtrack, bool DependentOp,
180 signed Cost)
181 : CandidateLocation(MII), HomeBundle(HomeBundle),
182 DependentOp(DependentOp), BenefitCost(Cost) {
183 // Copy of the backtrack.
184 Backtrack = backtrack;
185 }
186
187 void populate(MachineBasicBlock::instr_iterator &MII,
189 std::vector<MachineInstr *> &backtrack, bool &dependentOp) {
190 MII = CandidateLocation;
191 WorkPoint = HomeBundle;
192 backtrack = Backtrack;
193 dependentOp = DependentOp;
194 }
195
196 signed getCost() { return BenefitCost; }
197
198 MachineInstr *getCandidate() { return &*CandidateLocation; }
199
200 void dump() {
201 dbgs() << "Cost(" << BenefitCost;
202 dbgs() << ") Dependent(" << DependentOp;
203 dbgs() << ") backtrack size(" << Backtrack.size() << ")\t";
204 CandidateLocation->dump();
205 }
206};
207
208/// PullUpCandidateSorter - A Sort utility for pull-up candidates.
209struct PullUpCandidateSorter {
210 PullUpCandidateSorter() {}
211 bool operator()(PullUpCandidate *LHS, PullUpCandidate *RHS) {
212 return LHS->getCost() > RHS->getCost();
213 }
214};
215
216// Describes a single pull-up opportunity: location to which
217// pull-up is possible with additional information about it.
218// Also contains a list of pull-up candidates for this location.
219class PullUpState {
220 friend class HexagonGlobalSchedulerImpl;
221 // Available opportunity for pull-up.
222 // FAIAP a bundle with an empty slot.
223 MachineBasicBlock::iterator HomeLocation;
224 // Home bundle copy. This is here for speed of iteration.
226 // Multiple candidates for the Home location.
227 SmallVector<PullUpCandidate *, 8> PullUpCandidates;
228
229 const HexagonInstrInfo *QII;
230
231public:
232 PullUpState(const HexagonInstrInfo *QII) : HomeLocation(NULL), QII(QII) {}
233
234 ~PullUpState() { reset(); }
235
236 void addPullUpCandidate(MachineBasicBlock::instr_iterator MII,
238 std::vector<MachineInstr *> &backtrack,
239 bool DependentOp, signed Cost) {
240 LLVM_DEBUG(dbgs() << "\t[addPullUpCandidate]: "; (*MII).dump());
241 PullUpCandidate *PUI =
242 new PullUpCandidate(MII, HomeBundle, backtrack, DependentOp, Cost);
243 PullUpCandidates.push_back(PUI);
244 }
245
246 void dump() {
247 unsigned element = 0;
248 for (unsigned i = 0; i < HomeBundle.size(); i++) {
249 dbgs() << "[" << element++;
250 dbgs() << "] Home Duplex("
251 << QII->getDuplexCandidateGroup(*HomeBundle[i]);
252 dbgs() << ") Compound (" << QII->getCompoundCandidateGroup(*HomeBundle[i])
253 << ") ";
254 HomeBundle[i]->dump();
255 }
256 dbgs() << "\n";
257 element = 0;
258 for (SmallVector<PullUpCandidate *, 4>::iterator
259 I = PullUpCandidates.begin(),
260 E = PullUpCandidates.end();
261 I != E; ++I) {
262 dbgs() << "[" << element++ << "] Cand: Compound(";
263 dbgs() << QII->getCompoundCandidateGroup(*(*I)->getCandidate()) << ") ";
264 (*I)->dump();
265 }
266 }
267
268 void reset() {
269 HomeLocation = NULL;
270 for (SmallVector<PullUpCandidate *, 4>::iterator
271 I = PullUpCandidates.begin(),
272 E = PullUpCandidates.end();
273 I != E; ++I)
274 delete *I;
275 PullUpCandidates.clear();
276 HomeBundle.clear();
277 }
278
279 void addHomeLocation(MachineBasicBlock::iterator WorkPoint) {
280 reset();
281 HomeLocation = WorkPoint;
282 }
283
284 unsigned haveCandidates() { return PullUpCandidates.size(); }
285};
286
287class HexagonGlobalSchedulerImpl : public HexagonPacketizerList {
288 // List of PullUp regions for this function.
289 std::vector<BasicBlockRegion *> PullUpRegions;
290 // Map of approximate distance for each BB from the
291 // function base.
292 DenseMap<MachineBasicBlock *, unsigned> BlockToInstOffset;
293 // Keep track of multiple pull-up candidates.
294 PullUpState CurrentState;
295 // Empty basic blocks as a result of pull-up.
296 std::vector<MachineBasicBlock *> EmptyBBs;
297 // Save all the Speculated MachineInstr that were moved
298 // FROM MachineBasicBlock because we don't want to have
299 // more than one speculated instructions pulled into one packet.
300 // TODO: This can be removed once we have a use-def dependency chain
301 // for all the instructions in a function.
302 std::map<MachineInstr *, MachineBasicBlock *> SpeculatedIns;
303 // All the regs and their aliases used by an instruction.
304 std::map<MachineInstr *, std::vector<unsigned>> MIUseSet;
305 // All the regs and their aliases defined by an instruction.
306 std::map<MachineInstr *, std::vector<unsigned>> MIDefSet;
307
308 AliasAnalysis *AA;
309 const MachineBranchProbabilityInfo *MBPI;
310 const MachineBlockFrequencyInfo *MBFI;
311 const MachineRegisterInfo *MRI;
312 const MachineFrameInfo &MFI;
313 const HexagonRegisterInfo *QRI;
314 const HexagonInstrInfo *QII;
315 MachineLoopInfo &MLI;
316 MachineDominatorTree &MDT;
317 MachineInstrBuilder Ext;
318 MachineInstrBuilder Nop;
319 const unsigned PacketSize;
320 TargetSchedModel TSchedModel;
321
322public:
323 // Ctor.
324 HexagonGlobalSchedulerImpl(MachineFunction &MF, MachineLoopInfo &MLI,
325 MachineDominatorTree &MDT, AliasAnalysis *AA,
326 const MachineBranchProbabilityInfo *MBPI,
327 const MachineBlockFrequencyInfo *MBFI,
328 const MachineRegisterInfo *MRI,
329 const MachineFrameInfo &MFI,
330 const HexagonRegisterInfo *QRI);
331 HexagonGlobalSchedulerImpl(const HexagonGlobalSchedulerImpl &) = delete;
332 HexagonGlobalSchedulerImpl &
333 operator=(const HexagonGlobalSchedulerImpl &) = delete;
334
335 ~HexagonGlobalSchedulerImpl() {
336 // Free regions.
337 for (std::vector<BasicBlockRegion *>::iterator I = PullUpRegions.begin(),
338 E = PullUpRegions.end();
339 I != E; ++I)
340 delete *I;
341 MF.deleteMachineInstr(Ext);
342 MF.deleteMachineInstr(Nop);
343 }
344
345 // initPacketizerState - initialize some internal flags.
346 void initPacketizerState() override;
347
348 // ignorePseudoInstruction - Ignore bundling of pseudo instructions.
349 bool ignoreInstruction(MachineInstr *MI);
350
351 // isSoloInstruction - return true if instruction MI can not be packetized
352 // with any other instruction, which means that MI itself is a packet.
353 bool isSoloInstruction(const MachineInstr &MI) override;
354
355 // Add MI to packetizer state. Returns false if it cannot fit in the packet.
356 bool incrementalAddToPacket(MachineInstr &MI);
357
358 // formPullUpRegions - Top level call to form regions.
359 bool formPullUpRegions(MachineFunction &Fn);
360
361 // performPullUp - Top level call for pull-up.
362 bool performPullUp();
363
364 // performPullUpCFG - Top level call for pull-up CFG.
365 bool performPullUpCFG(MachineFunction &Fn);
366
367 // performExposedOptimizations -
368 // Look for optimization opportunities after pullup.
369 bool performExposedOptimizations(MachineFunction &Fn);
370
371 // optimizeBranching -
372 // 1. A conditional-jump transfers control to a BB with
373 // jump as the only instruction.
374 // if(p0) jump t1
375 // // ...
376 // t1: jump t2
377 // 2. When a BB with a single conditional jump, jumps to succ-of-succ and
378 // falls-through BB with only jump instruction.
379 // { if(p0) jump t1 }
380 // { jump t2 }
381 // t1: { ... }
382 MachineBasicBlock *optimizeBranches(MachineBasicBlock *MBB,
383 MachineBasicBlock *TBB,
384 MachineInstr *FirstTerm,
385 MachineBasicBlock *FBB);
386
387 // removeRedundantBranches -
388 // 1. Remove jump to the layout successor.
389 // 2. Remove multiple (dual) jump to the same target.
390 bool removeRedundantBranches(MachineBasicBlock *MBB, MachineBasicBlock *TBB,
391 MachineInstr *FirstTerm, MachineBasicBlock *FBB,
392 MachineInstr *SecondTerm);
393
394 // optimizeDualJumps - optimize dual jumps in a packet
395 // For now: Replace dual jump by single jump in case of a fall through.
396 bool optimizeDualJumps(MachineBasicBlock *MBB, MachineBasicBlock *TBB,
397 MachineInstr *FirstTerm, MachineBasicBlock *FBB,
398 MachineInstr *SecondTerm);
399
400 void GenUseDefChain(MachineFunction &Fn);
401
402 // Return region pointer or null if none found.
403 BasicBlockRegion *getRegionForMBB(std::vector<BasicBlockRegion *> &Regions,
404 MachineBasicBlock *MBB);
405
406 // Saves all the used-regs and their aliases in Uses.
407 // Saves all the defined-regs and their aliases in Defs.
408 void MIUseDefSet(MachineInstr *MI, std::vector<unsigned> &Defs,
409 std::vector<unsigned> &Uses);
410
411 // This is a very useful debug utility.
412 unsigned countCompounds(MachineFunction &Fn);
413
414 // Check bundle counts
415 void checkBundleCounts(MachineFunction &Fn);
416
417private:
418 // Get next BB to be included into the region.
419 MachineBasicBlock *getNextPURBB(MachineBasicBlock *MBB, bool SecondBest);
420
421 void setUsedRegs(BitVector &Set, unsigned Reg);
422 bool AliasingRegs(unsigned RegA, unsigned RegB);
423
424 // Test is true if the two MIs cannot be safely reordered.
425 bool ReorderDependencyTest(MachineInstr *MIa, MachineInstr *MIb);
426
427 bool canAddMIToThisPacket(
428 MachineInstr *MI,
430
431 bool pullUpPeelBBLoop(MachineBasicBlock *PredBB, MachineBasicBlock *LoopBB);
432
433 MachineInstr *findBundleAndBranch(MachineBasicBlock *BB,
435
436 // Does this bundle have any slots left?
437 bool ResourcesAvailableInBundle(BasicBlockRegion *CurrentRegion,
438 MachineBasicBlock::iterator &TargetPacket);
439
440 // Perform the actual move.
441 MachineInstr *MoveAndUpdateLiveness(
442 BasicBlockRegion *CurrentRegion, MachineBasicBlock *HomeBB,
443 MachineInstr *InstrToMove, bool NeedToNewify, unsigned DepReg,
444 bool MovingDependentOp, MachineBasicBlock *OriginBB,
445 MachineInstr *OriginalInstruction, SmallVector<MachineOperand, 4> &Cond,
446 MachineBasicBlock::iterator &SourceLocation,
447 MachineBasicBlock::iterator &TargetPacket,
449 std::vector<MachineInstr *> &backtrack);
450
451 // Updates incremental kill patterns along the backtrack.
452 void updateKillAlongThePath(MachineBasicBlock *HomeBB,
453 MachineBasicBlock *OriginBB,
456 MachineBasicBlock::iterator &SourcePacket,
457 MachineBasicBlock::iterator &TargetPacket,
458 std::vector<MachineInstr *> &backtrack);
459
460 // Gather list of pull-up candidates.
461 bool findPullUpCandidates(MachineBasicBlock::iterator &WorkPoint,
463 std::vector<MachineInstr *> &backtrack,
464 unsigned MaxCandidates);
465
466 // See if the instruction could be pulled up.
467 bool tryMultipleInstructions(
468 MachineBasicBlock::iterator &RetVal, /* output parameter */
469 std::vector<BasicBlockRegion *>::iterator &CurrentRegion,
471 MachineBasicBlock::iterator &ToThisBBEnd,
472 MachineBasicBlock::iterator &FromThisBBEnd, bool PathInRegion = true);
473
474 // Try to move MI into existing bundle.
475 bool MoveMItoBundle(BasicBlockRegion *CurrentRegion,
478 MachineBasicBlock::iterator &TargetPacket,
479 MachineBasicBlock::iterator &SourceLocation,
480 std::vector<MachineInstr *> &backtrack,
481 bool MovingDependentOp, bool PathInRegion);
482
483 // Insert temporary MI copy into MBB.
485 insertTempCopy(MachineBasicBlock *MBB,
486 MachineBasicBlock::iterator &TargetPacket, MachineInstr *MI,
487 bool DeleteOldCopy);
488
490 findInsertPositionInBundle(MachineBasicBlock::iterator &Bundle,
491 MachineInstr *MI, bool &LastInBundle);
492
493 bool NeedToNewify(MachineBasicBlock::instr_iterator NewMI, unsigned *DepReg,
494 MachineInstr *TargetPacket);
495
496 bool CanNewifiedBeUsedInBundle(MachineBasicBlock::instr_iterator NewMI,
497 unsigned DepReg, MachineInstr *TargetPacket);
498
499 void addInstructionToExistingBundle(MachineBasicBlock *HomeBB,
503 MachineBasicBlock::iterator &TargetPacket,
505 std::vector<MachineInstr *> &backtrack);
506
507 void removeInstructionFromExistingBundle(
508 MachineBasicBlock *HomeBB, MachineBasicBlock::instr_iterator &Head,
510 MachineBasicBlock::iterator &SourceLocation,
511 MachineBasicBlock::iterator &NextMI, bool MovingDependentOp,
512 std::vector<MachineInstr *> &backtrack);
513
514 // Check for conditional register operaton.
515 bool MIsCondAssign(MachineInstr *BMI, MachineInstr *MI,
516 SmallVector<unsigned, 4> &Defs);
517
518 // Test all the conditions required for instruction to be
519 // speculative. These are just required conditions, cost
520 // or benefit should be computed elsewhere.
521 bool canMIBeSpeculated(MachineInstr *MI, MachineBasicBlock *ToBB,
522 MachineBasicBlock *FromBB,
523 std::vector<MachineInstr *> &backtrack);
524
525 // See if this branch target belongs to the current region.
526 bool isBranchWithinRegion(BasicBlockRegion *CurrentRegion, MachineInstr *MI);
527
528 // A collection of low level utilities.
529 bool MIsAreDependent(MachineInstr *MIa, MachineInstr *MIb);
530 bool MIsHaveTrueDependency(MachineInstr *MIa, MachineInstr *MIb);
531 bool canReorderMIs(MachineInstr *MIa, MachineInstr *MIb);
532 bool canCauseStall(MachineInstr *MI, MachineInstr *MJ);
533 bool canThisMIBeMoved(MachineInstr *MI,
535 bool &MovingDependentOp, int &Cost);
536 bool MIisDualJumpCandidate(MachineInstr *MI,
537 MachineBasicBlock::iterator &WorkPoint);
538 bool DemoteToDotOld(MachineInstr *MI);
539 bool isNewifiable(MachineBasicBlock::instr_iterator MII, unsigned DepReg,
540 MachineInstr *TargetPacket);
541 bool IsNewifyStore(MachineInstr *MI);
542 bool isJumpOutOfRange(MachineInstr *MI);
543 bool IsDualJumpFirstCandidate(MachineInstr *MI);
544 bool IsDualJumpFirstCandidate(MachineBasicBlock *MBB);
545 bool IsDualJumpFirstCandidate(MachineBasicBlock::iterator &TargetPacket);
546 bool IsNotDualJumpFirstCandidate(MachineInstr *MI);
547 bool isJumpOutOfRange(MachineInstr *UnCond, MachineInstr *Cond);
548 bool IsDualJumpSecondCandidate(MachineInstr *MI);
549 bool tryAllocateResourcesForConstExt(MachineInstr *MI, bool UpdateState);
550 bool isCompoundPair(MachineInstr *MIa, MachineInstr *MIb);
551 bool doesMIDefinesPredicate(MachineInstr *MI, SmallVector<unsigned, 4> &Defs);
552 bool AnalyzeBBBranches(MachineBasicBlock *MBB, MachineBasicBlock *&TBB,
553 MachineInstr *&FirstTerm, MachineBasicBlock *&FBB,
554 MachineInstr *&SecondTerm);
555 inline bool multipleBranchesFromToBB(MachineBasicBlock *BB) const;
556};
557} // namespace
558
559INITIALIZE_PASS_BEGIN(HexagonGlobalScheduler, "global-sched",
560 "Hexagon Global Scheduler", false, false)
566INITIALIZE_PASS_END(HexagonGlobalScheduler, "global-sched",
567 "Hexagon Global Scheduler", false, false)
568
569/// HexagonGlobalSchedulerImpl Ctor.
570HexagonGlobalSchedulerImpl::HexagonGlobalSchedulerImpl(
575 : HexagonPacketizerList(MF, MLI, AA, nullptr, false), PullUpRegions(0),
576 CurrentState((const HexagonInstrInfo *)TII), AA(AA), MBPI(MBPI),
577 MBFI(MBFI), MRI(MRI), MFI(MFI), QRI(QRI), MLI(MLI), MDT(MDT),
578 PacketSize(MF.getSubtarget().getSchedModel().IssueWidth) {
579 QII = (const HexagonInstrInfo *)TII;
580 Ext = BuildMI(MF, DebugLoc(), QII->get(Hexagon::A4_ext));
581 Nop = BuildMI(MF, DebugLoc(), QII->get(Hexagon::A2_nop));
582 TSchedModel.init(&MF.getSubtarget());
583}
584
585// Return bundle size without debug instructions.
586static unsigned nonDbgBundleSize(MachineBasicBlock::iterator &TargetPacket) {
588 MachineBasicBlock::instr_iterator End = MII->getParent()->instr_end();
589 unsigned count = 0;
590 for (++MII; MII != End && MII->isInsideBundle(); ++MII) {
591 if (MII->isDebugInstr())
592 continue;
593 count++;
594 }
595 return count;
596}
597
598/// The pass main entry point.
599bool HexagonGlobalScheduler::runOnMachineFunction(MachineFunction &Fn) {
600 auto &HST = Fn.getSubtarget<HexagonSubtarget>();
601 if (DisablePullUp || !HST.usePackets() || skipFunction(Fn.getFunction()))
602 return false;
603
604 const MachineRegisterInfo *MRI = &Fn.getRegInfo();
605 const MachineFrameInfo &MFI = Fn.getFrameInfo();
606 const HexagonRegisterInfo *QRI = HST.getRegisterInfo();
607 MachineLoopInfo &MLI = getAnalysis<MachineLoopInfoWrapperPass>().getLI();
608 MachineDominatorTree &MDT =
609 getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
610 const MachineBranchProbabilityInfo *MBPI =
611 &getAnalysis<MachineBranchProbabilityInfoWrapperPass>().getMBPI();
612 const MachineBlockFrequencyInfo *MBFI =
613 &getAnalysis<MachineBlockFrequencyInfoWrapperPass>().getMBFI();
614 AliasAnalysis *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
615
616 // Preserve comounds if Opt Size.
617 const Function &F = Fn.getFunction();
618 if (F.hasOptSize() && PreventCompoundSeparation.getNumOccurrences() == 0)
620
621 // Instantiate the Scheduler.
622 HexagonGlobalSchedulerImpl GlobalSchedulerState(Fn, MLI, MDT, AA, MBPI, MBFI,
623 MRI, MFI, QRI);
624
625 // DFA state table should not be empty.
626 assert(GlobalSchedulerState.getResourceTracker() && "Empty DFA table!");
627
628 // Loop over all of the basic blocks.
629 // PullUp regions are basically traces with no side entrances.
630 // Might want to traverse BB by frequency.
631 GlobalSchedulerState.checkBundleCounts(Fn);
632
633 // Pullup does not handle hazards yet.
635 return true;
636
637 LLVM_DEBUG(GlobalSchedulerState.countCompounds(Fn));
638 GlobalSchedulerState.GenUseDefChain(Fn);
639 GlobalSchedulerState.formPullUpRegions(Fn);
640 GlobalSchedulerState.performPullUp();
641 GlobalSchedulerState.performPullUpCFG(Fn);
642 if (PostPullUpOpt) {
643 GlobalSchedulerState.formPullUpRegions(Fn);
644 GlobalSchedulerState.performExposedOptimizations(Fn);
645 }
646 LLVM_DEBUG(GlobalSchedulerState.countCompounds(Fn));
647
648 return true;
649}
650
651/// Allocate resources (i.e. 4 bytes) for constant extender. If succeess, return
652/// true, otherwise, return false.
653bool HexagonGlobalSchedulerImpl::tryAllocateResourcesForConstExt(
654 MachineInstr *MI, bool UpdateState = true) {
655 if (ResourceTracker->canReserveResources(*Ext)) {
656 // We do not always want to change the state of ResourceTracker.
657 // When we do not want to change it, we need to test for additional
658 // corner cases.
659 if (UpdateState)
660 ResourceTracker->reserveResources(*Ext);
661 else if (CurrentPacketMIs.size() >= PacketSize - 1)
662 return false;
663 return true;
664 }
665
666 return false;
667}
668
669static bool IsSchedBarrier(const MachineInstr *MI) {
670 return MI->getOpcode() == Hexagon::Y2_barrier;
671}
672
673static bool IsIndirectCall(const MachineInstr *MI) {
674 return MI->getOpcode() == Hexagon::J2_callr;
675}
676
677#ifndef NDEBUG
679 if (MI->isBundledWithPred())
680 dbgs() << "^";
681 else
682 dbgs() << " ";
683 if (MI->isBundledWithSucc())
684 dbgs() << "v";
685 else
686 dbgs() << " ";
687 MI->dump();
688}
689
692 dbgs() << "\tNULL\n";
693 return;
694 }
695 MachineInstr *MI = &*MII;
696 MachineBasicBlock *MBB = MI->getParent();
697 // Uninserted instruction.
698 if (!MBB) {
699 dbgs() << "\tUnattached: ";
700 DumpLinked(MI);
701 return;
702 }
703 dbgs() << "\t";
704 DumpLinked(MI);
705 if (MI->isBundle()) {
706 MachineBasicBlock::instr_iterator MIE = MI->getParent()->instr_end();
707 for (++MII; MII != MIE && MII->isInsideBundle() && !MII->isBundle();
708 ++MII) {
709 dbgs() << "\t\t*";
710 DumpLinked(&*MII);
711 }
712 }
713}
714
717 if (MII == BBEnd) {
718 dbgs() << "\tBBEnd\n";
719 return;
720 }
721
722 DumpPacket(MII);
723}
724#endif
725
726static bool isBranch(MachineInstr *MI) {
727 if (MI->isBundle()) {
728 MachineBasicBlock::instr_iterator MII = MI->getIterator();
729 MachineBasicBlock::instr_iterator MIE = MI->getParent()->instr_end();
730 for (++MII; MII != MIE && MII->isInsideBundle() && !MII->isBundle();
731 ++MII) {
732 if (MII->isBranch())
733 return true;
734 }
735 } else
736 return MI->isBranch();
737 return false;
738}
739
740/// Any of those must not be first dual jump. Everything else is OK.
741bool HexagonGlobalSchedulerImpl::IsNotDualJumpFirstCandidate(MachineInstr *MI) {
742 if (MI->isCall() || (MI->isBranch() && !QII->isPredicated(*MI)) ||
743 MI->isReturn() || QII->isEndLoopN(MI->getOpcode()))
744 return true;
745 return false;
746}
747
748/// These four functions clearly belong in HexagonInstrInfo.cpp.
749/// Is this MI could be first dual jump instruction?
750bool HexagonGlobalSchedulerImpl::IsDualJumpFirstCandidate(MachineInstr *MI) {
751 if (!PerformDualJumps)
752 return false;
753 if (MI->isBranch() && QII->isPredicated(*MI) && !QII->isNewValueJump(*MI) &&
754 !MI->isIndirectBranch() && !QII->isEndLoopN(MI->getOpcode()))
755 return true;
756 // Missing loopN here, but not sure if there will be any benefit from it.
757 return false;
758}
759
760/// This version covers the whole packet.
761bool HexagonGlobalSchedulerImpl::IsDualJumpFirstCandidate(
762 MachineBasicBlock::iterator &TargetPacket) {
763 if (!PerformDualJumps)
764 return false;
765 MachineInstr *MI = &*TargetPacket;
766
767 if (MI->isBundle()) {
768 // If this is a bundle, it must be the last bundle in BB.
769 if (&(*MI->getParent()->rbegin()) != MI)
770 return false;
771
772 MachineBasicBlock::instr_iterator MII = MI->getIterator();
773 MachineBasicBlock::instr_iterator BBEnd = MI->getParent()->instr_end();
774 // If there is a control flow op in this packet, this is the case
775 // we look for, even if they are dependent on other members.
776 for (++MII; MII != BBEnd && MII->isInsideBundle() && !MII->isBundle();
777 ++MII)
778 if (IsNotDualJumpFirstCandidate(&*MII))
779 return false;
780 } else
781 return IsDualJumpFirstCandidate(MI);
782
783 return true;
784}
785
786/// This version cover whole BB. There could be a BB
787/// with no control flow in it. In this case we can still pull-up a jump
788/// into it. Negative proof.
789bool HexagonGlobalSchedulerImpl::IsDualJumpFirstCandidate(
790 MachineBasicBlock *MBB) {
791 if (!PerformDualJumps)
792 return false;
793
795 MBBEnd = MBB->instr_end();
796 MII != MBBEnd; ++MII) {
797 MachineInstr *MI = &*MII;
798 if (MI->isDebugInstr())
799 continue;
800 if (!MI->isBundle() && IsNotDualJumpFirstCandidate(MI))
801 return false;
802 }
803 return true;
804}
805
806/// Is this MI could be second dual jump instruction?
807bool HexagonGlobalSchedulerImpl::IsDualJumpSecondCandidate(MachineInstr *MI) {
808 if (!PerformDualJumps)
809 return false;
810 if ((MI->isBranch() && !QII->isNewValueJump(*MI) && !MI->isIndirectBranch() &&
811 !QII->isEndLoopN(MI->getOpcode())) ||
812 (MI->isCall() && !IsIndirectCall(MI)))
813 return true;
814 return false;
815}
816
817// Since we have no exact knowledge of code layout,
818// allow some safety buffer for jump target.
819// This is measured in bytes.
820static const unsigned SafetyBuffer = 200;
821
824 MachineBasicBlock::instr_iterator MIB = MBB->instr_begin();
825 MachineBasicBlock::instr_iterator MIE = MBB->instr_end();
827 while (MII != MIE) {
828 if (!MII->isBundle() && MII->isTerminator())
829 return MII;
830 ++MII;
831 }
832 return MIE;
833}
834
835/// Check if a given instruction is:
836/// - a jump to a distant target
837/// - that exceeds its immediate range
838/// If both conditions are true, it requires constant extension.
839bool HexagonGlobalSchedulerImpl::isJumpOutOfRange(MachineInstr *MI) {
840 if (!MI || !MI->isBranch())
841 return false;
842 MachineBasicBlock *MBB = MI->getParent();
843 auto FirstTerm = getHexagonFirstInstrTerminator(MBB);
844 if (FirstTerm == MBB->instr_end())
845 return false;
846
847 unsigned InstOffset = BlockToInstOffset[MBB];
848 unsigned Distance = 0;
849 MachineBasicBlock::instr_iterator FTMII = FirstTerm;
850
851 // To save time, estimate exact position of a branch instruction
852 // as one at the end of the MBB.
853 // Number of instructions times typical instruction size.
854 InstOffset += (QII->nonDbgBBSize(MBB) * HEXAGON_INSTR_SIZE);
855
856 MachineBasicBlock *TBB = NULL, *FBB = NULL;
857 SmallVector<MachineOperand, 4> Cond;
858
859 // Try to analyze this branch.
860 if (QII->analyzeBranch(*MBB, TBB, FBB, Cond, false)) {
861 // Could not analyze it. See if this is something we can recognize.
862 // If it is a NVJ, it should always have its target in
863 // a fixed location.
864 if (QII->isNewValueJump(*FirstTerm))
865 TBB = FirstTerm->getOperand(QII->getCExtOpNum(*FirstTerm)).getMBB();
866 }
867 if (TBB && (MI == &*FirstTerm)) {
868 Distance =
869 (unsigned)std::abs((long long)InstOffset - BlockToInstOffset[TBB]) +
871 LLVM_DEBUG(dbgs() << "\tFirst term offset(" << Distance << "): ";
872 FirstTerm->dump());
873 return !QII->isJumpWithinBranchRange(*FirstTerm, Distance);
874 }
875 if (FBB) {
876 // Look for second terminator.
877 FTMII++;
878 MachineInstr *SecondTerm = &*FTMII;
879 assert(FTMII != MBB->instr_end() &&
880 (SecondTerm->isBranch() || SecondTerm->isCall()) &&
881 "Bad second terminator");
882 if (MI != SecondTerm)
883 return false;
884 // Analyze the second branch in the BB.
885 Distance =
886 (unsigned)std::abs((long long)InstOffset - BlockToInstOffset[FBB]) +
888 LLVM_DEBUG(dbgs() << "\tSecond term offset(" << Distance << "): ";
889 FirstTerm->dump());
890 return !QII->isJumpWithinBranchRange(*SecondTerm, Distance);
891 }
892 return false;
893}
894
895/// Returns true if an instruction can be promoted to .new predicate
896/// or new-value store.
897/// Performs implicit version checking.
898bool HexagonGlobalSchedulerImpl::isNewifiable(
899 MachineBasicBlock::instr_iterator MII, unsigned DepReg,
900 MachineInstr *TargetPacket) {
901 MachineInstr *MI = &*MII;
902 if (QII->isDotNewInst(*MI) ||
903 !CanNewifiedBeUsedInBundle(MII, DepReg, TargetPacket))
904 return false;
905 return (QII->isPredicated(*MI) && QII->getDotNewPredOp(*MI, nullptr) > 0) ||
906 QII->mayBeNewStore(*MI);
907}
908
909bool HexagonGlobalSchedulerImpl::DemoteToDotOld(MachineInstr *MI) {
910 int NewOpcode = QII->getDotOldOp(*MI);
911 MI->setDesc(QII->get(NewOpcode));
912 return true;
913}
914
915// initPacketizerState - Initialize packetizer flags
916void HexagonGlobalSchedulerImpl::initPacketizerState(void) {
917 CurrentPacketMIs.clear();
918 return;
919}
920
921// ignorePseudoInstruction - Ignore bundling of pseudo instructions.
922bool HexagonGlobalSchedulerImpl::ignoreInstruction(MachineInstr *MI) {
923 if (MI->isDebugInstr())
924 return true;
925
926 // We must print out inline assembly
927 if (MI->isInlineAsm())
928 return false;
929
930 // We check if MI has any functional units mapped to it.
931 // If it doesn't, we ignore the instruction.
932 const MCInstrDesc &TID = MI->getDesc();
933 unsigned SchedClass = TID.getSchedClass();
934 const InstrStage *IS =
935 ResourceTracker->getInstrItins()->beginStage(SchedClass);
936 unsigned FuncUnits = IS->getUnits();
937 return !FuncUnits;
938}
939
940// isSoloInstruction: - Returns true for instructions that must be
941// scheduled in their own packet.
942bool HexagonGlobalSchedulerImpl::isSoloInstruction(const MachineInstr &MI) {
943 if (MI.isInlineAsm())
944 return true;
945
946 if (MI.isEHLabel())
947 return true;
948
949 // From Hexagon V4 Programmer's Reference Manual 3.4.4 Grouping constraints:
950 // trap, pause, barrier, icinva, isync, and syncht are solo instructions.
951 // They must not be grouped with other instructions in a packet.
952 if (IsSchedBarrier(&MI))
953 return true;
954
955 if (MI.getOpcode() == Hexagon::A2_nop)
956 return true;
957
958 return false;
959}
960
961/// Return region ptr or null if non found.
962BasicBlockRegion *HexagonGlobalSchedulerImpl::getRegionForMBB(
963 std::vector<BasicBlockRegion *> &Regions, MachineBasicBlock *MBB) {
964 for (std::vector<BasicBlockRegion *>::iterator I = Regions.begin(),
965 E = Regions.end();
966 I != E; ++I) {
967 if ((*I)->findMBB(MBB))
968 return *I;
969 }
970 return NULL;
971}
972
973/// Select best candidate to form regions.
974static inline bool selectBestBB(BlockFrequency &BBaFreq, unsigned BBaSize,
975 BlockFrequency &BBbFreq, unsigned BBbSize) {
976 if (BBaFreq.getFrequency() > BBbFreq.getFrequency())
977 return true;
978 // TODO: This needs fine tuning.
979 // if (BBaSize < BBbSize)
980 // return true;
981 if (BBaFreq.getFrequency() == BBbFreq.getFrequency())
982 return true;
983 return false;
984}
985
986/// Returns BB pointer if one of MBB successors should be added to the
987/// current PullUp Region, NULL otherwise.
988/// If SecondBest is defined, get next one after Best match.
989/// Most of the time, since we practically always have only two successors,
990/// this is "the other" BB successor which still matches original
991/// selection criterion.
992MachineBasicBlock *
993HexagonGlobalSchedulerImpl::getNextPURBB(MachineBasicBlock *MBB,
994 bool SecondBest = false) {
995 if (!MBB)
996 return NULL;
997
998 BlockFrequency BestBlockFreq = BlockFrequency(0);
999 unsigned BestBlockSize = 0;
1000 MachineBasicBlock *BestBB = NULL;
1001 MachineBasicBlock *SecondBestBB = NULL;
1002
1003 // Catch single BB loops.
1004 for (MachineBasicBlock *Succ : MBB->successors())
1005 if (Succ == MBB)
1006 return NULL;
1007
1008 // Iterate through successors to MBB.
1009 for (MachineBasicBlock *Succ : MBB->successors()) {
1010 BlockFrequency BlockFreq = MBFI->getBlockFreq(Succ);
1011
1012 LLVM_DEBUG(dbgs() << "\tsucc BB(" << Succ->getNumber() << ") freq("
1013 << BlockFreq.getFrequency() << ")");
1014
1015 if (!SecondBest && getRegionForMBB(PullUpRegions, Succ))
1016 continue;
1017
1018 // If there is more then one predecessor to this block, do not include it.
1019 // It means there is a side entrance to it.
1020 if (Succ->pred_size() > 1)
1021 continue;
1022
1023 // If this block is a target of an indirect branch, it should
1024 // also not be included.
1025 if (Succ->isEHPad() || Succ->hasAddressTaken())
1026 continue;
1027
1028 // Get BB edge frequency.
1029 BlockFrequency EdgeFreq = BlockFreq * MBPI->getEdgeProbability(MBB, Succ);
1030 LLVM_DEBUG(dbgs() << "\tedge with freq(" << EdgeFreq.getFrequency()
1031 << ")\n");
1032
1033 if (selectBestBB(EdgeFreq, QII->nonDbgBBSize(Succ), BestBlockFreq,
1034 BestBlockSize)) {
1035 BestBlockFreq = EdgeFreq;
1036 BestBlockSize = QII->nonDbgBBSize(Succ);
1037 SecondBestBB = BestBB;
1038 BestBB = Succ;
1039 } else if (!SecondBestBB) {
1040 SecondBestBB = Succ;
1041 }
1042 }
1043 if (SecondBest)
1044 return SecondBestBB;
1045 else
1046 return BestBB;
1047}
1048
1049/// Form region to perform pull-up.
1050bool HexagonGlobalSchedulerImpl::formPullUpRegions(MachineFunction &Fn) {
1051 const Function &F = Fn.getFunction();
1052 // Check for single-block functions and skip them.
1053 if (std::next(F.begin()) == F.end())
1054 return false;
1055
1056 // Compute map for BB distances.
1057 // Offset of the current instruction from the start.
1058 unsigned InstOffset = 0;
1059
1060 LLVM_DEBUG(dbgs() << "****** Form PullUpRegions **************\n");
1061 // Loop over all basic blocks.
1062 // PullUp regions are basically traces with no side entrances.
1063 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end(); MBB != MBBe;
1064 ++MBB) {
1065 if (MBB->getAlignment() > llvm::Align(1)) {
1066 // Although we don't know the exact layout of the final code, we need
1067 // to account for alignment padding somehow. This heuristic pads each
1068 // aligned basic block according to the alignment value.
1069 int ByteAlign = MBB->getAlignment().value() - 1;
1070 InstOffset = (InstOffset + ByteAlign) & ~(ByteAlign);
1071 }
1072 // Remember BB layout offset.
1073 BlockToInstOffset[&*MBB] = InstOffset;
1075 MIE = MBB->instr_end();
1076 MII != MIE; ++MII)
1077 if (!MII->isBundle())
1078 InstOffset += QII->getSize(*MII);
1079
1080 // If this BB is already in a region, move on.
1081 if (getRegionForMBB(PullUpRegions, &*MBB))
1082 continue;
1083
1084 LLVM_DEBUG(dbgs() << "\nRoot BB(" << MBB->getNumber() << ") name("
1085 << MBB->getName() << ") size(" << QII->nonDbgBBSize(&*MBB)
1086 << ") freq(" << printBlockFreq(*MBFI, *MBB)
1087 << ") pred_size(" << MBB->pred_size() << ") in_func("
1088 << MBB->getParent()->getFunction().getName() << ")\n");
1089
1090 BasicBlockRegion *PUR = new BasicBlockRegion(TII, QRI, &*MBB);
1091 PullUpRegions.push_back(PUR);
1092
1093 for (MachineBasicBlock *MBBR = getNextPURBB(&*MBB); MBBR;
1094 MBBR = getNextPURBB(MBBR)) {
1095 LLVM_DEBUG(dbgs() << "Add BB(" << MBBR->getNumber() << ") name("
1096 << MBBR->getName() << ") size("
1097 << QII->nonDbgBBSize(MBBR) << ") freq("
1098 << printBlockFreq(*MBFI, *MBBR) << ") in_func("
1099 << MBBR->getParent()->getFunction().getName() << ")\n");
1100 PUR->addBBtoRegion(MBBR);
1101 }
1102 }
1103 return true;
1104}
1105
1106/// Return true if MI is an instruction we are unable to reason about
1107/// (like something with unmodeled memory side effects).
1109 if (MI->hasUnmodeledSideEffects() || MI->hasOrderedMemoryRef() ||
1110 MI->isCall() ||
1111 (MI->getOpcode() == Hexagon::J2_jump && !MI->getOperand(0).isMBB()))
1112 return true;
1113 return false;
1114}
1115
1116/// Gather register def/uses from MI.
1117/// This treats possible (predicated) defs
1118/// as actually happening ones (conservatively).
1119static inline void parseOperands(MachineInstr *MI,
1122 Defs.clear();
1123 Uses.clear();
1124
1125 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1126 const MachineOperand &MO = MI->getOperand(i);
1127
1128 if (MO.isReg()) {
1129 unsigned Reg = MO.getReg();
1130 if (!Reg)
1131 continue;
1133 if (MO.isUse())
1134 Uses.push_back(MO.getReg());
1135 if (MO.isDef())
1136 Defs.push_back(MO.getReg());
1137 } else if (MO.isRegMask()) {
1138 for (unsigned R = 1, NR = Hexagon::NUM_TARGET_REGS; R != NR; ++R)
1139 if (MO.clobbersPhysReg(R))
1140 Defs.push_back(R);
1141 }
1142 }
1143}
1144
1145void HexagonGlobalSchedulerImpl::MIUseDefSet(MachineInstr *MI,
1146 std::vector<unsigned> &Defs,
1147 std::vector<unsigned> &Uses) {
1148 Defs.clear();
1149 Uses.clear();
1150 assert(!MI->isBundle() && "Cannot parse regs of a bundle.");
1151 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1152 const MachineOperand &MO = MI->getOperand(i);
1153
1154 if (MO.isReg()) {
1155 unsigned Reg = MO.getReg();
1156 if (!Reg)
1157 continue;
1158 assert(Register::isPhysicalRegister(Reg));
1159 std::vector<unsigned> &Refs = MO.isUse() ? Uses : Defs;
1160 for (MCRegAliasIterator AI(MO.getReg(), QRI, true); AI.isValid(); ++AI)
1161 Refs.push_back(*AI);
1162 } else if (MO.isRegMask()) {
1163 for (unsigned R = 1, NR = Hexagon::NUM_TARGET_REGS; R != NR; ++R)
1164 if (MO.clobbersPhysReg(R))
1165 Defs.push_back(R);
1166 }
1167 }
1168}
1169
1170/// Some apparent dependencies are not actually restricting us since there
1171/// is a delay between assignment and actual usage, like in case of a call.
1172/// There could be more cases here, but this one seems the most obvious.
1174 if (MIa->isCall() && !MIb->isCall())
1175 return true;
1176 if (!MIa->isCall() && MIb->isCall())
1177 return true;
1178 return false;
1179}
1180
1181/// This is a check for resources availability and dependency
1182/// for an MI being tried for an existing bundle.
1183/// This is needed because we can:
1184/// - save time by filtering out trivial cases
1185/// - we want to reuse infrastructure that does not really knows
1186/// how to deal with parallel semantics of a bundle that already
1187/// exists. For instance, the following case:
1188/// SI %R6<def> = L2_ploadrif_io %P0<kill>, %R7, 4;
1189/// SJ %R6<def> = A2_tfr %R0;
1190/// will be happily allowed by isLegalToPacketizeTogether since in serial
1191/// semantics it never happens, and even if it does, it is legal. Not so
1192/// for when we __speculatively__ trying and MI for a bundle.
1193///
1194/// Note: This is not equivalent to MIsAreDependent().
1195/// MIsAreDependent only understands serial semantics.
1196/// These are OK to packetize together:
1197/// %R0<def> = L2_loadri_io %R18, 76; mem:LD4[%sunkaddr226](tbaa=!"int")
1198/// %R2<def> = ASL %R0<kill>, 3; flags: Inside bundle
1199///
1200bool HexagonGlobalSchedulerImpl::canAddMIToThisPacket(
1201 MachineInstr *MI,
1203 if (!MI)
1204 return false;
1205 LLVM_DEBUG(dbgs() << "\n\t[canAddMIToThisPacket]: "; MI->dump());
1206
1207 // Const extenders need custom resource checking...
1208 // Should be OK if we can update the check everywhere.
1209 if ((QII->isConstExtended(*MI) || QII->isExtended(*MI) ||
1210 isJumpOutOfRange(MI)) &&
1211 !tryAllocateResourcesForConstExt(MI, false))
1212 return false;
1213
1214 // Ask DFA if machine resource is available for MI.
1215 if (!ResourceTracker->canReserveResources(*MI) || !shouldAddToPacket(*MI)) {
1216 LLVM_DEBUG(dbgs() << "\tNo DFA resources.\n");
1217 return false;
1218 }
1219
1220 SmallVector<unsigned, 4> BundleDefs;
1221 SmallVector<unsigned, 8> BundleUses;
1222 SmallVector<unsigned, 4> Defs;
1223 SmallVector<unsigned, 8> Uses;
1224 MachineInstr *FirstCompound = NULL, *SecondCompound = NULL;
1225 MachineInstr *FirstDuplex = NULL, *SecondDuplex = NULL;
1226
1227 parseOperands(MI, Defs, Uses);
1228 for (SmallVector<MachineInstr *, HEXAGON_PACKET_SIZE>::iterator
1229 BI = Bundle.begin(),
1230 BE = Bundle.end();
1231 BI != BE; ++BI) {
1232 BundleDefs.clear();
1233 BundleUses.clear();
1234 parseOperands(*BI, BundleDefs, BundleUses);
1235
1236 MachineInstr *Inst1 = *BI;
1237 MachineInstr *Inst2 = MI;
1238
1239 if (Inst1->getParent() && OneFloatPerPacket && QII->isFloat(*Inst1) &&
1240 QII->isFloat(*Inst2))
1241 return false;
1242
1243 if (Inst1->getParent() && OneComplexPerPacket && QII->isComplex(*Inst1) &&
1244 QII->isComplex(*Inst2))
1245 return false;
1246
1248 if (QII->getCompoundCandidateGroup(**BI)) {
1249 if (!FirstCompound)
1250 FirstCompound = *BI;
1251 else {
1252 SecondCompound = *BI;
1253 if (isCompoundPair(FirstCompound, SecondCompound)) {
1254 if (MI->mayLoad() || MI->mayStore()) {
1255 LLVM_DEBUG(dbgs() << "\tPrevent compound destruction.\n");
1256 return false;
1257 }
1258 }
1259 }
1260 }
1262 if (QII->getDuplexCandidateGroup(**BI)) {
1263 if (!FirstDuplex)
1264 FirstDuplex = *BI;
1265 else {
1266 SecondDuplex = *BI;
1267 if (QII->isDuplexPair(*FirstDuplex, *SecondDuplex)) {
1268 if (MI->mayLoad() || MI->mayStore()) {
1269 LLVM_DEBUG(dbgs() << "\tPrevent duplex destruction.\n");
1270 return false;
1271 }
1272 }
1273 }
1274 }
1275
1276 for (unsigned i = 0; i < Defs.size(); i++) {
1277 // Check for multiple definitions in the same packet.
1278 for (unsigned j = 0; j < BundleDefs.size(); j++)
1279 // Multiple defs in the same packet.
1280 // Calls are OK here.
1281 // Also if we have multiple defs of PC, this simply means we are
1282 // dealing with dual jumps.
1283 if (AliasingRegs(Defs[i], BundleDefs[j]) &&
1284 !isDelayedUseException(MI, *BI) &&
1285 !(IsDualJumpFirstCandidate(*BI) && IsDualJumpSecondCandidate(MI))) {
1286 LLVM_DEBUG(dbgs() << "\tMultiple defs.\n\t"; MI->dump();
1287 dbgs() << "\t"; (*BI)->dump());
1288 return false;
1289 }
1290
1291 // See if we are creating a swap case as we go, and disallow
1292 // it for now.
1293 // Also, this is not OK:
1294 // if (!p0) r7 = r5
1295 // if (!p0) r5 = #0
1296 // But this is fine:
1297 // if (!p0) r7 = r5
1298 // if (p0) r5 = #0
1299 // Aslo - this is not a swap, but an opportunity to newify:
1300 // %P1<def> = C2_cmpeqi %R0, 0; flags:
1301 // %R0<def> = L2_ploadrif_io %P1<kill>, %R29, 8;
1302 // TODO: Handle this.
1303 for (unsigned j = 0; j < BundleUses.size(); j++)
1304 if (AliasingRegs(Defs[i], BundleUses[j])) {
1305 for (unsigned k = 0; k < BundleDefs.size(); k++)
1306 for (unsigned l = 0; l < Uses.size(); l++) {
1307 if (AliasingRegs(BundleDefs[k], Uses[l]) &&
1308 !isDelayedUseException(MI, *BI)) {
1309 LLVM_DEBUG(dbgs() << "\tSwap detected:\n\t"; MI->dump();
1310 dbgs() << "\t"; (*BI)->dump());
1311 return false;
1312 }
1313 }
1314 }
1315 }
1316
1317 for (unsigned i = 0; i < Uses.size(); i++) {
1318 // Check for true data dependency.
1319 for (unsigned j = 0; j < BundleDefs.size(); j++)
1320 if (AliasingRegs(Uses[i], BundleDefs[j]) &&
1321 !isDelayedUseException(MI, *BI)) {
1322 LLVM_DEBUG(dbgs() << "\tImmediate Use detected on reg("
1323 << printReg(Uses[i], QRI) << ")\n\t";
1324 MI->dump(); dbgs() << "\t"; (*BI)->dump());
1325 // TODO: This could be an opportunity for newifying:
1326 // %P0<def> = C2_cmpeqi %R26, 0
1327 // %R26<def> = A2_tfr %R0<kill>
1328 // if (CanPromoteToDotNew(MI, Uses[i]))
1329 // LLVM_DEBUG(dbgs() << "\tCan promoto to .new form.\n");
1330 // else
1331 return false;
1332 }
1333 }
1334
1335 // For calls we also check callee save regs.
1336 if ((*BI)->isCall()) {
1337 for (const uint16_t *I = QRI->getCalleeSavedRegs(&MF); *I; ++I) {
1338 for (unsigned i = 0; i < Defs.size(); i++) {
1339 if (AliasingRegs(Defs[i], *I)) {
1340 LLVM_DEBUG(dbgs() << "\tAlias with call.\n");
1341 return false;
1342 }
1343 }
1344 }
1345 }
1346
1347 // If this is return, we are probably speculating (otherwise
1348 // we could not pull in there) and will not win from pulling
1349 // into this location anyhow.
1350 // Example: a side exit.
1351 // if (!p0) dealloc_return
1352 // TODO: Can check that we do not overwrite return value
1353 // and proceed.
1354 if ((*BI)->isBarrier()) {
1355 LLVM_DEBUG(dbgs() << "\tBarrier interference.\n");
1356 return false;
1357 }
1358
1359 // \ref-manual (7.3.4) A loop setup packet in loopN or spNloop0 cannot
1360 // contain a speculative indirect jump,
1361 // a new-value compare jump or a dealloc_return.
1362 // Speculative indirect jumps (predicate + .new + indirect):
1363 // if ([!]Ps.new) jumpr:t Rs
1364 // if ([!]Ps.new) jumpr:nt Rs
1365 // @note: We don't want to pull across a call to be on the safe side.
1366 if (QII->isLoopN(*MI) &&
1367 ((QII->isPredicated(**BI) && QII->isPredicatedNew(**BI) &&
1368 QII->isJumpR(**BI)) ||
1369 QII->isNewValueJump(**BI) || QII->isDeallocRet(**BI) ||
1370 (*BI)->isCall())) {
1371 LLVM_DEBUG(dbgs() << "\tLoopN pull interference.\n");
1372 return false;
1373 }
1374
1375 // The opposite is also true.
1376 if (QII->isLoopN(**BI) &&
1377 ((QII->isPredicated(*MI) && QII->isPredicatedNew(*MI) &&
1378 QII->isJumpR(*MI)) ||
1379 QII->isNewValueJump(*MI) || QII->isDeallocRet(*MI) || MI->isCall())) {
1380 LLVM_DEBUG(dbgs() << "\tResident LoopN.\n");
1381 return false;
1382 }
1383
1384 // @todo \ref-manual 7.6.1
1385 // Presence of NVJ adds more restrictions.
1386 if (QII->isNewValueJump(**BI) &&
1387 (MI->mayStore() || MI->getOpcode() == Hexagon::S2_allocframe ||
1388 MI->isCall())) {
1389 LLVM_DEBUG(dbgs() << "\tNew val Jump.\n");
1390 return false;
1391 }
1392
1393 // For memory operations, check aliasing.
1394 // First, be conservative on these objects. Might be overly constraining,
1395 // so recheck.
1397 // Currently it catches things like this:
1398 // S2_storerinew_io %R29, 32, %R16
1399 // S2_storeri_io %R29, 68, %R0
1400 // which we can reason about.
1401 // TODO: revisit.
1402 return false;
1403
1404 // If packet has a new-value store, MI can't be a store instruction.
1405 if (QII->isNewValueStore(**BI) && MI->mayStore()) {
1406 LLVM_DEBUG(dbgs() << "\tNew Value Store to store.\n");
1407 return false;
1408 }
1409
1410 if ((QII->isMemOp(**BI) && MI->mayStore()) ||
1411 (QII->isMemOp(*MI) && (*BI)->mayStore())) {
1412 LLVM_DEBUG(
1413 dbgs() << "\tSlot 0 not available for store because of memop.\n");
1414 return false;
1415 }
1416
1417 // If any of these is true, check aliasing.
1418 if ((MI->mayLoad() && (*BI)->mayStore()) ||
1419 (MI->mayStore() && (*BI)->mayLoad()) ||
1420 (MI->mayStore() && (*BI)->mayStore())) {
1421 if (QII->areMemAccessesDependent(AA, MI, *BI)) {
1422 LLVM_DEBUG(dbgs() << "\tAliasing detected:\n\t"; MI->dump();
1423 dbgs() << "\t"; (*BI)->dump());
1424 return false;
1425 }
1426 }
1427 // Do not move an instruction to this packet if this packet
1428 // already contains a speculated instruction.
1429 std::map<MachineInstr *, MachineBasicBlock *>::iterator MIMoved;
1430 MIMoved = SpeculatedIns.find(*BI);
1431 if ((MIMoved != SpeculatedIns.end()) &&
1432 (MIMoved->second != (*BI)->getParent())) {
1433 LLVM_DEBUG(
1434 dbgs() << "This packet already contains a speculated instruction";
1435 (*BI)->dump(););
1436 return false;
1437 }
1438 }
1439
1440 // Do not pull-up vector instructions because these instructions have
1441 // multi-cycle latencies, and the pull-up pass doesn't correctly account
1442 // for instructions that stall for more than one cycle.
1443 if (QII->isHVXVec(*MI))
1444 return false;
1445
1446 return true;
1447}
1448
1449/// Test is true if the two MIs cannot be safely reordered.
1450bool HexagonGlobalSchedulerImpl::ReorderDependencyTest(MachineInstr *MIa,
1451 MachineInstr *MIb) {
1452 SmallVector<unsigned, 4> DefsA;
1453 SmallVector<unsigned, 4> DefsB;
1454 SmallVector<unsigned, 8> UsesA;
1455 SmallVector<unsigned, 8> UsesB;
1456
1457 parseOperands(MIa, DefsA, UsesA);
1458 parseOperands(MIb, DefsB, UsesB);
1459
1460 for (SmallVector<unsigned, 4>::iterator IDA = DefsA.begin(),
1461 IDAE = DefsA.end();
1462 IDA != IDAE; ++IDA) {
1463 for (SmallVector<unsigned, 8>::iterator IUB = UsesB.begin(),
1464 IUBE = UsesB.end();
1465 IUB != IUBE; ++IUB)
1466 // True data dependency.
1467 if (AliasingRegs(*IDA, *IUB))
1468 return true;
1469
1470 for (SmallVector<unsigned, 4>::iterator IDB = DefsB.begin(),
1471 IDBE = DefsB.end();
1472 IDB != IDBE; ++IDB)
1473 // Output dependency.
1474 if (AliasingRegs(*IDA, *IDB))
1475 return true;
1476 }
1477
1478 for (SmallVector<unsigned, 4>::iterator IDB = DefsB.begin(),
1479 IDBE = DefsB.end();
1480 IDB != IDBE; ++IDB) {
1481 for (SmallVector<unsigned, 8>::iterator IUA = UsesA.begin(),
1482 IUAE = UsesA.end();
1483 IUA != IUAE; ++IUA)
1484 // True data dependency.
1485 if (AliasingRegs(*IDB, *IUA))
1486 return true;
1487 }
1488
1489 // Do not reorder two calls...
1490 if (MIa->isCall() && MIb->isCall())
1491 return true;
1492
1493 // For calls we also check callee save regs.
1494 if (MIa->isCall())
1495 for (const uint16_t *I = QRI->getCalleeSavedRegs(&MF); *I; ++I) {
1496 for (unsigned i = 0; i < DefsB.size(); i++) {
1497 if (AliasingRegs(DefsB[i], *I))
1498 return true;
1499 }
1500 }
1501
1502 if (MIb->isCall())
1503 for (const uint16_t *I = QRI->getCalleeSavedRegs(&MF); *I; ++I) {
1504 for (unsigned i = 0; i < DefsA.size(); i++) {
1505 if (AliasingRegs(DefsA[i], *I))
1506 return true;
1507 }
1508 }
1509
1510 // For memory operations, check aliasing.
1511 // First, be conservative on these objects.
1512 // Might be overly constraining, so recheck.
1513 if ((isGlobalMemoryObject(MIa)) || (isGlobalMemoryObject(MIb)))
1514 return true;
1515
1516 // If any of these is true, check aliasing.
1517 if (((MIa->mayLoad() && MIb->mayStore()) ||
1518 (MIa->mayStore() && MIb->mayLoad()) ||
1519 (MIa->mayStore() && MIb->mayStore())) &&
1520 QII->areMemAccessesDependent(AA, MIa, MIb))
1521 return true;
1522
1523 return false;
1524}
1525
1526/// Serial semantics.
1527bool HexagonGlobalSchedulerImpl::MIsAreDependent(MachineInstr *MIa,
1528 MachineInstr *MIb) {
1529 if (MIa == MIb)
1530 return false;
1531
1532 if (ReorderDependencyTest(MIa, MIb)) {
1533 LLVM_DEBUG(dbgs() << "\t\t[MIsAreDependent]:\n\t\t"; MIa->dump();
1534 dbgs() << "\t\t"; MIb->dump());
1535 return true;
1536 }
1537 return false;
1538}
1539
1540/// Serial semantics.
1541bool HexagonGlobalSchedulerImpl::MIsHaveTrueDependency(MachineInstr *MIa,
1542 MachineInstr *MIb) {
1543 if (MIa == MIb)
1544 return false;
1545
1546 SmallVector<unsigned, 4> DefsA;
1547 SmallVector<unsigned, 4> DefsB;
1548 SmallVector<unsigned, 8> UsesA;
1549 SmallVector<unsigned, 8> UsesB;
1550
1551 parseOperands(MIa, DefsA, UsesA);
1552 parseOperands(MIb, DefsB, UsesB);
1553
1554 for (SmallVector<unsigned, 4>::iterator IDA = DefsA.begin(),
1555 IDAE = DefsA.end();
1556 IDA != IDAE; ++IDA) {
1557 for (SmallVector<unsigned, 8>::iterator IUB = UsesB.begin(),
1558 IUBE = UsesB.end();
1559 IUB != IUBE; ++IUB)
1560 // True data dependency.
1561 if (AliasingRegs(*IDA, *IUB))
1562 return true;
1563 }
1564 return false;
1565}
1566
1567/// Sequential semantics. Can these two MIs be reordered?
1568/// Moving MIa from "behind" to "in front" of MIb.
1569bool HexagonGlobalSchedulerImpl::canReorderMIs(MachineInstr *MIa,
1570 MachineInstr *MIb) {
1571 if (!MIa || !MIb)
1572 return false;
1573
1574 // Within bundle semantics are parallel.
1575 if (MIa->isBundle()) {
1578 for (++MII; MII != MIIE && MII->isInsideBundle(); ++MII) {
1579 if (MII->isDebugInstr())
1580 continue;
1581 if (MIsAreDependent(&*MII, MIb))
1582 return false;
1583 }
1584 return true;
1585 }
1586 return !MIsAreDependent(MIa, MIb);
1587}
1588
1590 if (MI->isInlineAsm() || MI->isEHLabel() || IsSchedBarrier(MI))
1591 return true;
1592 return false;
1593}
1594
1596 if (MI->isBranch() || MI->isReturn() || MI->isCall() || MI->isBarrier() ||
1597 MI->isTerminator() || MIMustNotBePulledUp(MI))
1598 return true;
1599 return false;
1600}
1601
1602// Only approve dual jump candidate:
1603// It is a branch, and we move it to last packet of the target location.
1604bool HexagonGlobalSchedulerImpl::MIisDualJumpCandidate(
1605 MachineInstr *MI, MachineBasicBlock::iterator &WorkPoint) {
1606 if (!PerformDualJumps || !IsDualJumpSecondCandidate(MI) ||
1607 MIMustNotBePulledUp(MI) || ignoreInstruction(MI))
1608 return false;
1609
1610 MachineBasicBlock *FromThisBB = MI->getParent();
1611 MachineBasicBlock *ToThisBB = WorkPoint->getParent();
1612
1613 LLVM_DEBUG(dbgs() << "\t\t[MIisDualJumpCandidate] To BB("
1614 << ToThisBB->getNumber() << ") From BB("
1615 << FromThisBB->getNumber() << ")\n");
1616 // If the question is about the same BB, we do not want to get
1617 // dual jump involved - it is a different case.
1618 if (FromThisBB == ToThisBB)
1619 return false;
1620
1621 // Dual jump could only be done on neigboring BBs.
1622 // The FromThisBB must only have one predecessor - the basic
1623 // block we are trying to merge.
1624 if ((*(FromThisBB->pred_begin()) != ToThisBB) ||
1625 (std::next(FromThisBB->pred_begin()) != FromThisBB->pred_end()))
1626 return false;
1627
1628 // If this block is a target of an indirect branch, it should
1629 // also not be included.
1630 if (FromThisBB->isEHPad() || FromThisBB->hasAddressTaken())
1631 return false;
1632
1633 // Now we must preserve original fall through paths. In fact we
1634 // might be dealing with 3way branching.
1635 MachineBasicBlock *ToTBB = NULL, *ToFBB = NULL;
1636
1637 if (ToThisBB->succ_size() == 2) {
1638 // Check the branch from target block.
1639 // If we have two successors, we must understand the branch.
1640 SmallVector<MachineOperand, 4> ToCond;
1641 if (!QII->analyzeBranch(*ToThisBB, ToTBB, ToFBB, ToCond, false)) {
1642 // Have the branch. Check the topology.
1643 LLVM_DEBUG(dbgs() << "\t\tToThisBB has two successors: TBB("
1644 << ToTBB->getNumber() << ") and FBB(";
1645 if (ToFBB) dbgs() << ToFBB->getNumber() << ").\n";
1646 else dbgs() << "None"
1647 << ").\n";);
1648 if (ToTBB == FromThisBB) {
1649 // If the from BB is not the fall through, we can only handle case
1650 // when second branch is unconditional jump.
1651 return false;
1652 } else if (ToFBB == FromThisBB || !ToFBB) {
1653 // If the fall through path of ToBB is our FromBB, we have more freedom
1654 // of operation.
1655 LLVM_DEBUG(dbgs() << "\t\tFall through jump target.\n");
1656 }
1657 } else {
1658 LLVM_DEBUG(dbgs() << "\t\tUnable to analyze first branch.\n");
1659 return false;
1660 }
1661 } else if (ToThisBB->succ_size() == 1) {
1662 ToFBB = *ToThisBB->succ_begin();
1663 assert(ToFBB == FromThisBB && "Bad CFG layout");
1664 } else
1665 return false;
1666
1667 // First unbundled control flow instruction in the BB.
1668 if (!MI->isBundled() && MI == &*FromThisBB->getFirstNonDebugInstr())
1669 return IsDualJumpFirstCandidate(WorkPoint);
1670
1671 return false;
1672}
1673
1674// Check whether moving MI to MJ's packet would cause a stall from a previous
1675// packet.
1676bool HexagonGlobalSchedulerImpl::canCauseStall(MachineInstr *MI,
1677 MachineInstr *MJ) {
1678 SmallVector<unsigned, 4> DefsMJI;
1679 SmallVector<unsigned, 8> UsesMJI;
1680 SmallVector<unsigned, 4> DefsMI;
1681 SmallVector<unsigned, 8> UsesMI;
1682 parseOperands(MI, DefsMI, UsesMI);
1683
1684 for (auto Use : UsesMI) {
1685 int UseIdx = MI->findRegisterUseOperandIdx(Use, /*TRI=*/nullptr);
1686 if (UseIdx == -1)
1687 continue;
1688 bool ShouldBreak = false;
1689 int BundleCount = 0;
1691 Begin = MJ->getParent()->instr_begin(),
1692 MJI = MJ->getIterator();
1693 MJI != Begin; --MJI) {
1694 if (MJI->isBundle()) {
1695 ++BundleCount;
1696 continue;
1697 }
1698 parseOperands(&*MJI, DefsMJI, UsesMJI);
1699 for (auto Def : DefsMJI) {
1700 if (Def == Use || AliasingRegs(Def, Use)) {
1701 int DefIdx = MJI->findRegisterDefOperandIdx(Def, /*TRI=*/nullptr);
1702 if (DefIdx >= 0) {
1703 int Latency =
1704 TSchedModel.computeOperandLatency(&*MJI, DefIdx, MI, UseIdx);
1705 if (Latency > BundleCount)
1706 // There will be a stall if MI is moved to MJ's packet.
1707 return true;
1708 // We found the def for the use and it does not cause a stall.
1709 // Continue checking the next use for a potential stall.
1710 ShouldBreak = true;
1711 break;
1712 }
1713 }
1714 }
1715 if (ShouldBreak)
1716 break;
1717 if (!MJI->isBundled() && !MJI->isDebugInstr())
1718 ++BundleCount;
1719 }
1720 }
1721 return false;
1722}
1723
1724/// Analyze this instruction. If this is an unbundled instruction, see
1725/// if it in theory could be packetized.
1726/// If it is already part of a packet, see if it has internal
1727/// dependencies to this packet.
1728bool HexagonGlobalSchedulerImpl::canThisMIBeMoved(
1729 MachineInstr *MI, MachineBasicBlock::iterator &WorkPoint,
1730 bool &MovingDependentOp, int &Cost) {
1731 if (!MI)
1732 return false;
1733 // By default, it is a normal move.
1734 MovingDependentOp = false;
1735 Cost = 0;
1736 // If MI is a 'formed' compound not potential compound, bail out.
1737 if (QII->isCompoundBranchInstr(*MI))
1738 return false;
1739 // See if we can potentially break potential compound candidates,
1740 // and do not do it.
1741 if (PreventCompoundSeparation && MI->isBundled()) {
1743 if (MICG != HexagonII::HCG_None) {
1744 // Check internal dependencies in the bundle.
1745 // First, find the bundle header.
1746 MachineBasicBlock::instr_iterator MII = MI->getIterator();
1747 for (--MII; MII->isBundled(); --MII)
1748 if (MII->isBundle())
1749 break;
1750
1751 MachineBasicBlock::instr_iterator BBEnd = MI->getParent()->instr_end();
1752 for (++MII; MII != BBEnd && MII->isInsideBundle() && !MII->isBundle();
1753 ++MII) {
1754 if (&(*MII) == MI)
1755 continue;
1756 if (isCompoundPair(&*MII, MI)) {
1757 LLVM_DEBUG(dbgs() << "\tPrevent Compound separation.\n");
1758 return false;
1759 }
1760 }
1761 }
1762 }
1763 // Same thing for duplex candidates.
1764 if (PreventDuplexSeparation && MI->isBundled()) {
1766 // Check internal dependencies in the bundle.
1767 // First, find the bundle header.
1768 MachineBasicBlock::instr_iterator MII = MI->getIterator();
1769 for (--MII; MII->isBundled(); --MII)
1770 if (MII->isBundle())
1771 break;
1772
1773 MachineBasicBlock::instr_iterator BBEnd = MI->getParent()->instr_end();
1774 for (++MII; MII != BBEnd && MII->isInsideBundle() && !MII->isBundle();
1775 ++MII) {
1776 if ((&(*MII) != MI) && QII->isDuplexPair(*MII, *MI)) {
1777 LLVM_DEBUG(dbgs() << "\tPrevent Duplex separation.\n");
1778 return false;
1779 }
1780 }
1781 }
1782 }
1783
1784 // If we perform dual jump formation during the pull-up,
1785 // then we want to consider several additional situations.
1786 // a) Allow moving of dependent instruction from a packet
1787 // b) Allow moving some control flow instructions if they meet
1788 // dual jump criteria.
1789 if (MIisDualJumpCandidate(MI, WorkPoint)) {
1790 LLVM_DEBUG(dbgs() << "\t\tDual jump candidate:\t"; MI->dump());
1791 // Here we are breaking our general assumption about not moving dependent
1792 // instructions. To save us two more expensive checks down the line,
1793 // propagate the information directly.
1794 MovingDependentOp = true;
1795 return true;
1796 }
1797
1798 // Any of these should not even be tried.
1799 if (MIShouldNotBePulledUp(MI) || ignoreInstruction(MI))
1800 return false;
1801 // Pulling up these instructions could put them
1802 // out of jump range/offset size.
1803 if (QII->isLoopN(*MI)) {
1804 unsigned dist_looplabel =
1805 BlockToInstOffset.find(MI->getOperand(0).getMBB())->second;
1806 unsigned dist_newloop0 =
1807 BlockToInstOffset.find(WorkPoint->getParent())->second;
1808 // Check if the jump in the last instruction is within range.
1809 unsigned Distance =
1810 (unsigned)std::abs((long long)dist_looplabel - dist_newloop0) +
1811 QII->nonDbgBBSize(WorkPoint->getParent()) * 4 + SafetyBuffer;
1812 const HexagonInstrInfo *HII = (const HexagonInstrInfo *)TII;
1813 if (!HII->isJumpWithinBranchRange(*MI, Distance)) {
1814 LLVM_DEBUG(dbgs() << "\nloopN cannot be moved since Distance: "
1815 << Distance << " outside branch range.";);
1816 return false;
1817 }
1818 LLVM_DEBUG(dbgs() << "\nloopN can be moved since Distance: " << Distance
1819 << " within branch range.";);
1820 }
1821 // If the def-set of an MI is one of the live-ins then MI should
1822 // kill that reg and no instruction before MI should use it.
1823 // For simplicity, allow only if MI is the first instruction in the MBB.
1824 std::map<MachineInstr *, std::vector<unsigned>>::const_iterator DefIter =
1825 MIDefSet.find(MI);
1826 MachineBasicBlock *MBB = MI->getParent();
1827 for (unsigned i = 0; DefIter != MIDefSet.end() && i < DefIter->second.size();
1828 ++i) {
1829 if (MBB->isLiveIn(DefIter->second[i]) &&
1831 return false;
1832 }
1833 // If it is part of a bundle, analyze it.
1834 if (MI->isBundled()) {
1835 // Cannot move bundle header itself. This function is about
1836 // individual MI move.
1837 if (MI->isBundle())
1838 return false;
1839
1840 // Check internal dependencies in the bundle.
1841 // First, find the bundle header.
1842 MachineBasicBlock::instr_iterator MII = MI->getIterator();
1843 for (--MII; MII->isBundled(); --MII)
1844 if (MII->isBundle())
1845 break;
1846
1847 MachineBasicBlock::instr_iterator BBEnd = MI->getParent()->instr_end();
1848 for (++MII; MII != BBEnd && MII->isInsideBundle() && !MII->isBundle();
1849 ++MII) {
1850 if (MII->isDebugInstr())
1851 continue;
1852 if (MIsAreDependent(&*MII, MI)) {
1853 if (!AllowDependentPullUp) {
1854 LLVM_DEBUG(dbgs() << "\t\tDependent.\n");
1855 return false;
1856 } else {
1857 // There are a few cases that we can safely move a dependent
1858 // instruction away from this packet.
1859 // One example is an instruction setting a call operands.
1860 if ((MII->isCall() && !IsIndirectCall(&*MII)) ||
1861 IsDualJumpSecondCandidate(&*MII) || MI->isBranch()) {
1862 LLVM_DEBUG(dbgs() << "\t\tDependent, but allow to move.\n");
1863 MovingDependentOp = true;
1864 Cost -= 10;
1865 continue;
1866 } else {
1867 LLVM_DEBUG(dbgs() << "\t\tDependent, and do not allow for now.\n");
1868 return false;
1869 }
1870 }
1871 }
1872 }
1873 }
1874 return true;
1875}
1876
1877/// Return true if MI defines a predicate and parse all defs.
1878bool HexagonGlobalSchedulerImpl::doesMIDefinesPredicate(
1879 MachineInstr *MI, SmallVector<unsigned, 4> &Defs) {
1880 bool defsPredicate = false;
1881 Defs.clear();
1882
1883 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1884 const MachineOperand &MO = MI->getOperand(i);
1885
1886 // Regmasks are considered "implicit".
1887 if (!MO.isReg())
1888 continue;
1889 unsigned Reg = MO.getReg();
1890
1891 if (!Reg || QRI->isFakeReg(Reg))
1892 continue;
1893
1894 assert(Register::isPhysicalRegister(Reg));
1895
1896 if (MO.isDef() && !MO.isImplicit()) {
1897 const TargetRegisterClass *RC = QRI->getMinimalPhysRegClass(Reg);
1898 if (RC == &Hexagon::PredRegsRegClass) {
1899 defsPredicate = true;
1900 Defs.push_back(MO.getReg());
1901 }
1902 }
1903 }
1904 return defsPredicate;
1905}
1906
1907/// We have just tentatively added a predicated MI to an existing packet.
1908/// Now we need to determine if it needs to be changed to .new form.
1909/// It only handles compare/predicate right now.
1910/// TODO - clean this logic up.
1911/// TODO - generalize to handle any .new
1912bool HexagonGlobalSchedulerImpl::NeedToNewify(
1913 MachineBasicBlock::instr_iterator NewMI, unsigned *DepReg,
1914 MachineInstr *TargetPacket = NULL) {
1916 SmallVector<unsigned, 4> DefsA;
1917 SmallVector<unsigned, 4> DefsB;
1918 SmallVector<unsigned, 8> UsesB;
1919
1920 // If this is not a normal bundle, we are probably
1921 // trying to size two lonesome instructions together,
1922 // and trying to say if one of them will need to be
1923 // newified. In this is the case we have something like this:
1924 // BB#5:
1925 // %P0<def> = CMPGEri %R4, 2
1926 // S2_pstorerif_io %P0<kill>, %R29, 16, %R21<kill>
1927 // BUNDLE %R7<imp-def>, %R4<imp-def>, %R7<imp-use>
1928 parseOperands(&*NewMI, DefsB, UsesB);
1929 if (TargetPacket && !TargetPacket->isBundled()) {
1930 if (doesMIDefinesPredicate(TargetPacket, DefsA)) {
1931 for (SmallVector<unsigned, 4>::iterator IA = DefsA.begin(),
1932 IAE = DefsA.end();
1933 IA != IAE; ++IA)
1934 for (SmallVector<unsigned, 8>::iterator IB = UsesB.begin(),
1935 IBE = UsesB.end();
1936 IB != IBE; ++IB)
1937 if (*IA == *IB) {
1938 *DepReg = *IA;
1939 return true;
1940 }
1941 }
1942 return false;
1943 }
1944
1945 // Find bundle header.
1946 for (--MII; MII->isBundled(); --MII)
1947 if (MII->isBundle())
1948 break;
1949
1950 // Iterate down, if there is data dependent cmp found, need to .newify.
1951 // Also, we can have the following:
1952 // {
1953 // p0 = r7
1954 // if (!p0.new) jump:t .LBB4_18
1955 // if (p0.new) r8 = zxth(r12)
1956 // }
1957 MachineBasicBlock::instr_iterator BBEnd = MII->getParent()->instr_end();
1958 for (++MII; MII != BBEnd && MII->isBundled() && !MII->isBundle(); ++MII) {
1959 if (MII == NewMI)
1960 continue;
1961 if (doesMIDefinesPredicate(&*MII, DefsA)) {
1962 for (SmallVector<unsigned, 4>::iterator IA = DefsA.begin(),
1963 IAE = DefsA.end();
1964 IA != IAE; ++IA)
1965 for (SmallVector<unsigned, 8>::iterator IB = UsesB.begin(),
1966 IBE = UsesB.end();
1967 IB != IBE; ++IB)
1968 // We do not have multiple predicate regs defined in any instruction,
1969 // if we ever will, this needs to be generalized.
1970 if (*IA == *IB) {
1971 *DepReg = *IA;
1972 return true;
1973 }
1974 DefsA.clear();
1975 }
1976 }
1977 LLVM_DEBUG(dbgs() << "\nNo need to newify:"; NewMI->dump());
1978 return false;
1979}
1980
1981/// We know this instruction needs to be newified to be added to the packet,
1982/// but not all combinations are legal.
1983/// It is a complimentary check to NeedToNewify().
1984/// The packet actually contains the new instruction during the check.
1985bool HexagonGlobalSchedulerImpl::CanNewifiedBeUsedInBundle(
1986 MachineBasicBlock::instr_iterator NewMI, unsigned DepReg,
1987 MachineInstr *TargetPacket) {
1989 if (!TargetPacket || !TargetPacket->isBundled())
1990 return true;
1991
1992 // Find the bundle header.
1993 for (--MII; MII->isBundled(); --MII)
1994 if (MII->isBundle())
1995 break;
1996
1997 MachineBasicBlock::instr_iterator BBEnd = MII->getParent()->instr_end();
1998 for (++MII; MII != BBEnd && MII->isBundled() && !MII->isBundle(); ++MII) {
1999 // Effectively we look for the case of late predicates.
2000 // No additional checks at the time.
2001 if (MII == NewMI || !QII->isPredicateLate(MII->getOpcode()))
2002 continue;
2003 SmallVector<unsigned, 4> DefsA;
2004 if (!doesMIDefinesPredicate(&*MII, DefsA))
2005 continue;
2006 for (auto &IA : DefsA)
2007 if (IA == DepReg)
2008 return false;
2009 }
2010 return true;
2011}
2012
2013/// setUsed - Set the register and its sub-registers as being used.
2014/// Similar to RegScavenger::setUsed().
2015void HexagonGlobalSchedulerImpl::setUsedRegs(BitVector &Set, unsigned Reg) {
2016 Set.reset(Reg);
2017 for (MCSubRegIterator SubRegs(Reg, QRI); SubRegs.isValid(); ++SubRegs)
2018 Set.reset(*SubRegs);
2019}
2020
2021/// Are these two registers overlaping?
2022bool HexagonGlobalSchedulerImpl::AliasingRegs(unsigned RegA, unsigned RegB) {
2023 if (RegA == RegB)
2024 return true;
2025
2026 for (MCSubRegIterator SubRegs(RegA, QRI); SubRegs.isValid(); ++SubRegs)
2027 if (RegB == *SubRegs)
2028 return true;
2029
2030 for (MCSubRegIterator SubRegs(RegB, QRI); SubRegs.isValid(); ++SubRegs)
2031 if (RegA == *SubRegs)
2032 return true;
2033
2034 return false;
2035}
2036
2037/// Find use with this reg, and unmark the kill flag.
2038static inline void unmarkKillReg(MachineInstr *MI, unsigned Reg) {
2039 if (MI->isDebugInstr())
2040 return;
2041
2042 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
2043 MachineOperand &MO = MI->getOperand(i);
2044
2045 if (!MO.isReg())
2046 continue;
2047
2048 if (MO.isKill() && (MO.getReg() == Reg))
2049 MO.setIsKill(false);
2050 }
2051}
2052
2053/// Find use with this reg, and unmark the kill flag.
2054static inline void markKillReg(MachineInstr *MI, unsigned Reg) {
2055 if (MI->isDebugInstr())
2056 return;
2057
2058 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
2059 MachineOperand &MO = MI->getOperand(i);
2060
2061 if (!MO.isReg())
2062 continue;
2063
2064 if (MO.isUse() && (MO.getReg() == Reg))
2065 MO.setIsKill(true);
2066 }
2067}
2068
2069/// We have just moved an instruction that could have changed kill patterns
2070/// along the path it was moved. We need to update it.
2071void HexagonGlobalSchedulerImpl::updateKillAlongThePath(
2072 MachineBasicBlock *HomeBB, MachineBasicBlock *OriginBB,
2075 MachineBasicBlock::iterator &SourcePacket,
2076 MachineBasicBlock::iterator &TargetPacket,
2077 std::vector<MachineInstr *> &backtrack) {
2078 // This is the instruction being moved.
2079 MachineInstr *MI = &*Head;
2080 MachineBasicBlock *CurrentBB = OriginBB;
2081 SmallSet<unsigned, 8> KilledUseSet;
2082
2083 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
2084 const MachineOperand &MO = MI->getOperand(i);
2085 if (!MO.isReg())
2086 continue;
2087 unsigned Reg = MO.getReg();
2088 if (!Reg)
2089 continue;
2090
2091 if (MO.isKill())
2092 KilledUseSet.insert(Reg);
2093 }
2094
2095 // If there are no kills here, we are done.
2096 if (KilledUseSet.empty())
2097 return;
2098
2099 LLVM_DEBUG(dbgs() << "\n[updateKillAlongThePath]\n");
2100 LLVM_DEBUG(dbgs() << "\t\tInstrToMove :\t"; MI->dump());
2101 LLVM_DEBUG(dbgs() << "\t\tSourceLocation:\n";
2102 DumpPacket(SourcePacket.getInstrIterator()));
2103 LLVM_DEBUG(dbgs() << "\t\tTargetPacket :\n";
2104 DumpPacket(TargetPacket.getInstrIterator()));
2105 LLVM_DEBUG(dbgs() << "\tUpdate Kills. Need to update (" << KilledUseSet.size()
2106 << ")kills. From BB (" << OriginBB->getNumber() << ")\n");
2107 LLVM_DEBUG(dbgs() << "\tMove path:\n");
2108 assert(!backtrack.empty() && "Empty back track");
2109
2110 // We have pulled up an instruction, with one of its uses marked as kill.
2111 // If there is any other use of the same register along the move path,
2112 // and there are no side exits with killed register live-in along them,
2113 // we need to mark last use of that reg as kill.
2114 for (signed i = backtrack.size() - 1; i >= 0; --i) {
2115 LLVM_DEBUG(dbgs() << "\t\t[" << i << "]BB("
2116 << backtrack[i]->getParent()->getNumber() << ")\t";
2117 backtrack[i]->dump());
2118 if (CurrentBB != backtrack[i]->getParent()) {
2119 LLVM_DEBUG(dbgs() << "\t\tChange BB from (" << CurrentBB->getNumber()
2120 << ") to(" << backtrack[i]->getParent()->getNumber()
2121 << ")\n");
2123 SI = backtrack[i]->getParent()->succ_begin(),
2124 SE = backtrack[i]->getParent()->succ_end();
2125 SI != SE; ++SI) {
2126 if (*SI == CurrentBB)
2127 continue;
2128
2129 LLVM_DEBUG(dbgs() << "\t\tSide Exit:\n\t"; (*SI)->dump());
2130 // If any reg kill is live along this side exit, it is not
2131 // a kill any more.
2132 for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
2133 E = (*SI)->livein_end();
2134 I != E; ++I) {
2135 if (KilledUseSet.count((*I).PhysReg)) {
2136 LLVM_DEBUG(dbgs() << "\t\tReg (" << printReg((*I).PhysReg, QRI)
2137 << ") is LiveIn along side exit.\n");
2138 KilledUseSet.erase((*I).PhysReg);
2139 unmarkKillReg(MI, (*I).PhysReg);
2140 }
2141 if (KilledUseSet.empty())
2142 return;
2143 }
2144 }
2145 CurrentBB = backtrack[i]->getParent();
2146 }
2147
2148 // Done with the whole path.
2149 if (backtrack[i] == &*TargetPacket)
2150 return;
2151
2152 // Starting the tracking. Do not update source bundle.
2153 // If TargetPacket == SourcePacket we have returned
2154 // in the previous check.
2155 if (backtrack[i] == &*SourcePacket)
2156 continue;
2157
2158 // Ignore DBG_VALUE.
2159 if (backtrack[i]->isDebugInstr())
2160 continue;
2161
2162 // Encountered an intermediary bundle. Process it.
2163 // Beware, sometimes check for backtrack[i] == TargetPacket
2164 // does not work, so this instruction could be one from the target bundle.
2165 SmallVector<unsigned, 4> Defs;
2166 SmallVector<unsigned, 8> Uses;
2167 MachineInstr *MIU = backtrack[i];
2168 parseOperands(MIU, Defs, Uses);
2169
2170 for (SmallVector<unsigned, 8>::iterator IA = Uses.begin(), IAE = Uses.end();
2171 IA != IAE; ++IA) {
2172 if (KilledUseSet.count(*IA)) {
2173 // Now this is new kill point for this Reg.
2174 // Update the bundle, and any local uses.
2175 markKillReg(MIU, *IA);
2176
2177 // Unmark the current MI.
2178 unmarkKillReg(MI, *IA);
2179
2180 if (MIU->isBundle()) {
2181 // TODO: Can do this cleaner and faster.
2184 for (++MII; MII != End && MII->isInsideBundle(); ++MII)
2185 markKillReg(&*MII, *IA);
2186 }
2187
2188 // We have updated this kill reg, if there are more, keep on going.
2189 KilledUseSet.erase(*IA);
2190
2191 // If the set is exhausted, just leave.
2192 if (KilledUseSet.empty())
2193 return;
2194 }
2195 }
2196 }
2197}
2198
2199/// This is houskeeping for bundle with instruction just added to it.
2200void HexagonGlobalSchedulerImpl::addInstructionToExistingBundle(
2201 MachineBasicBlock *HomeBB, MachineBasicBlock::instr_iterator &Head,
2204 MachineBasicBlock::iterator &TargetPacket,
2206 std::vector<MachineInstr *> &backtrack) {
2207 Tail = getBundleEnd(Head);
2208 LLVM_DEBUG(dbgs() << "\t\t\t[Add] Head home: "; DumpPacket(Head));
2209
2210 // Old header to be deleted shortly.
2211 MachineBasicBlock::instr_iterator Outcast = Head;
2212 // Unbundle old header.
2213 if (Outcast->isBundle() && Outcast->isBundledWithSucc())
2214 Outcast->unbundleFromSucc();
2215
2216 bool memShufDisabled = QII->getBundleNoShuf(*Outcast);
2217
2218 // Create new bundle header and update MI flags.
2219 finalizeBundle(*HomeBB, ++Head, Tail);
2220 MachineBasicBlock::instr_iterator BundleMII = std::prev(Head);
2221 if (memShufDisabled)
2222 QII->setBundleNoShuf(BundleMII);
2223 --Head;
2224
2225 LLVM_DEBUG(dbgs() << "\t\t\t[Add] New Head : "; DumpPacket(Head));
2226
2227 // The old header could be listed in the back tracking,
2228 // so if it is, we need to update it.
2229 for (unsigned i = 0; i < backtrack.size(); ++i)
2230 if (backtrack[i] == &*Outcast)
2231 backtrack[i] = &*Head;
2232
2233 // Same for top MI iterator.
2234 if (NextMI == Outcast)
2235 NextMI = Head;
2236
2237 TargetPacket = Head;
2238 HomeBB->erase(Outcast);
2239}
2240
2241/// This handles houskeeping for bundle with instruction just deleted from it.
2242/// We do not see the original moved instruction in here.
2243void HexagonGlobalSchedulerImpl::removeInstructionFromExistingBundle(
2244 MachineBasicBlock *HomeBB, MachineBasicBlock::instr_iterator &Head,
2246 MachineBasicBlock::iterator &SourceLocation,
2247 MachineBasicBlock::iterator &NextMI, bool MovingDependentOp,
2248 std::vector<MachineInstr *> &backtrack) {
2249 // Empty BBs will be deleted shortly.
2250 if (HomeBB->empty()) {
2253 return;
2254 }
2255
2256 if (!SourceLocation->isBundle()) {
2257 LLVM_DEBUG(dbgs() << "\t\t\tOriginal instruction was not bundled.\n\t\t\t";
2258 SourceLocation->dump());
2259 // If original instruction was not bundled, and we have moved it
2260 // and it is in the back track, we probably want to remove it from there.
2261 LLVM_DEBUG(dbgs() << "\t\t\t[Rem] New head: "; backtrack.back()->dump());
2262
2263 for (unsigned i = 0; i < backtrack.size(); ++i) {
2264 if (backtrack[i] == &*SourceLocation) {
2265 // By definition, this should be the last instruction in the backtrack.
2266 assert((backtrack[i] == backtrack.back()) && "Lost back track");
2267 backtrack.pop_back();
2268 }
2269 // Point the main iterator to the next instruction.
2270 if (NextMI == SourceLocation)
2271 NextMI++;
2272 }
2273 SourceLocation = MachineBasicBlock::iterator();
2276 return;
2277 }
2278
2279 // The old header, soon to be deleted.
2280 MachineBasicBlock::instr_iterator Outcast = SourceLocation.getInstrIterator();
2281 LLVM_DEBUG(dbgs() << "\t\t\t[Rem] SourceLocation after bundle update: ";
2282 DumpPacket(Outcast));
2283
2284 // If bundle has been already destroyed. BB->splat seems to do it some times
2285 // but not the other.
2286 // We already know that SourceLocation is bundle header.
2287 if (!SourceLocation->isBundledWithSucc()) {
2288 assert(!Head->isBundledWithSucc() && !Head->isBundledWithPred() &&
2289 "Bad bundle");
2290 } else {
2291 Head = SourceLocation.getInstrIterator();
2292 Tail = getBundleEnd(Head);
2293 unsigned Size = 0;
2294 unsigned BBSizeWithDbg = 0;
2296 MachineBasicBlock::const_instr_iterator E = Head->getParent()->instr_end();
2297
2298 for (++I; I != E && I->isBundledWithPred(); ++I) {
2299 ++BBSizeWithDbg;
2300 if (!I->isDebugInstr())
2301 ++Size;
2302 }
2303
2304 LLVM_DEBUG(dbgs() << "\t\t\t[Rem] Size(" << Size << ") Head orig: ";
2305 DumpPacket(Head));
2306 // The old header, soon to be deleted.
2307 Outcast = Head;
2308
2309 // The old Header is still counted here.
2310 if (Size > 1) {
2311 if (Outcast->isBundle() && Outcast->isBundledWithSucc())
2312 Outcast->unbundleFromSucc();
2313
2314 bool memShufDisabled = QII->getBundleNoShuf(*Outcast);
2315 // The finalizeBundle() assumes that "original" sequence
2316 // it is finalizing is sequentially correct. That basically
2317 // means that swap case might not be handled properly.
2318 // I find insert point for the pull-up instruction myself,
2319 // and I should try to catch that swap case there, and refuse
2320 // to insert if I cannot guarantee correct serial semantics.
2321 // In the future, I need my own incremental "inserToBundle"
2322 // function.
2323 finalizeBundle(*HomeBB, ++Head, Tail);
2324 MachineBasicBlock::instr_iterator BundleMII = std::prev(Head);
2325 if (memShufDisabled)
2326 QII->setBundleNoShuf(BundleMII);
2327
2328 --Head;
2329 } else if (Size == 1) {
2330 // There is only one non-debug instruction in the bundle.
2331 if (BBSizeWithDbg > 1) {
2332 // There are some debug instructions that should be unbundled too.
2334 MachineBasicBlock::instr_iterator E = Head->getParent()->instr_end();
2335 for (++I; I != E && I->isBundledWithPred(); ++I) {
2336 I->unbundleFromPred();
2337 // Set Head to the non-debug instruction.
2338 if (!I->isDebugInstr())
2339 Head = I;
2340 }
2341 } else {
2342 // This means that only one original instruction is
2343 // left in the bundle. We need to "unbundle" it because the
2344 // rest of API will not like it.
2345 ++Head;
2346 if (Head->isBundledWithPred())
2347 Head->unbundleFromPred();
2348 if (Head->isBundledWithSucc())
2349 Head->unbundleFromSucc();
2350 }
2351 // Head is no longer bundled, so none of its reads are internal.
2352 for (MachineOperand &MO : Head->all_uses())
2353 MO.setIsInternalRead(false);
2354 } else
2355 llvm_unreachable("Corrupt bundle");
2356 }
2357
2358 LLVM_DEBUG(dbgs() << "\t\t\t[Rem] New Head : "; DumpPacket(Head));
2359 SourceLocation = Head;
2360
2361 // The old header could be listed in the back tracking,
2362 // so if it is, we need to update it.
2363 for (unsigned i = 0; i < backtrack.size(); ++i)
2364 if (backtrack[i] == &*Outcast)
2365 backtrack[i] = &*Head;
2366
2367 // Same for top MI iterator.
2368 if (NextMI == Outcast)
2369 NextMI = Head;
2370
2371 HomeBB->erase(Outcast);
2372}
2373
2374#ifndef NDEBUG
2376 const TargetRegisterInfo *TRI) {
2377 LLVM_DEBUG(dbgs() << "\tLiveness for BB:\n"; MBB->dump());
2378 for (MachineBasicBlock::const_succ_iterator SI = MBB->succ_begin(),
2379 SE = MBB->succ_end();
2380 SI != SE; ++SI) {
2381 LLVM_DEBUG(dbgs() << "\tSuccessor BB (" << (*SI)->getNumber() << "):");
2382 for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
2383 E = (*SI)->livein_end();
2384 I != E; ++I)
2385 LLVM_DEBUG(dbgs() << "\t" << printReg((*I).PhysReg, TRI));
2386 LLVM_DEBUG(dbgs() << "\n");
2387 }
2388}
2389#endif
2390
2391// Blocks should be considered empty if they contain only debug info;
2392// else the debug info would affect codegen.
2394 if (MBB->empty())
2395 return true;
2396 for (MachineBasicBlock::iterator MBBI = MBB->begin(), MBBE = MBB->end();
2397 MBBI != MBBE; ++MBBI) {
2398 if (!MBBI->isDebugInstr())
2399 return false;
2400 }
2401 return true;
2402}
2403
2404/// Treat given instruction as a branch, go through its operands
2405/// and see if any of them is a BB address. If so, return it.
2406/// Return NULL otherwise.
2408 if (!MI || !MI->isBranch() || MI->isBundle())
2409 return NULL;
2410
2411 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
2412 const MachineOperand &MO = MI->getOperand(i);
2413 if (MO.isMBB())
2414 return MO.getMBB();
2415 }
2416 return NULL;
2417}
2418
2419/// Similar to HexagonInstrInfo::analyzeBranch but handles
2420/// serveral more general cases including parsing empty BBs when possible.
2421bool HexagonGlobalSchedulerImpl::AnalyzeBBBranches(MachineBasicBlock *MBB,
2422 MachineBasicBlock *&TBB,
2423 MachineInstr *&FirstTerm,
2424 MachineBasicBlock *&FBB,
2425 MachineInstr *&SecondTerm) {
2426 // Hexagon allowes up to two jumps in MBB.
2427 FirstTerm = NULL;
2428 SecondTerm = NULL;
2429
2430 LLVM_DEBUG(dbgs() << "\n\t\tAnalyze Branches in BB(" << MBB->getNumber()
2431 << ")\n");
2432 if (MBB->succ_size() == 0) {
2433 LLVM_DEBUG(dbgs() << "\n\t\tBlock has no successors.\n");
2434 return true;
2435 }
2436 // Find both jumps.
2437 // We largely rely on implied assumption that BB branching always
2438 // looks like this:
2439 // J2_jumpf %P0, <BB#60>, %PC<imp-def>;
2440 // J2_jump <BB#49>
2441 // Branches also could be in different packets.
2445
2446 if (QII->nonDbgBBSize(MBB) == 1) {
2448 if (MII->isBranch())
2449 FirstTerm = &*MII;
2450 } else {
2451 // We have already eliminated the case when MIB == MIE.
2452 while (MII != MIE) {
2453 if (!MII->isBundle() && MII->isBranch()) {
2454 if (!FirstTerm)
2455 FirstTerm = &*MII;
2456 else
2457 SecondTerm = &*MII;
2458 }
2459 ++MII;
2460 }
2461 }
2462 if ((FirstTerm && FirstTerm->isIndirectBranch()) ||
2463 (SecondTerm && SecondTerm->isIndirectBranch())) {
2464 LLVM_DEBUG(dbgs() << "\n\t\tCannot analyze BB with indirect branch.");
2465 return true;
2466 }
2467 if ((FirstTerm && FirstTerm->getOpcode() == Hexagon::J2_jump &&
2468 !FirstTerm->getOperand(0).isMBB()) ||
2469 (SecondTerm && SecondTerm->getOpcode() == Hexagon::J2_jump &&
2470 !SecondTerm->getOperand(0).isMBB())) {
2471 LLVM_DEBUG(
2472 dbgs() << "\n\t\tCannot analyze BB with a branch out of function.");
2473 return true;
2474 }
2475
2476 // Now try to analyze this branch.
2477 SmallVector<MachineOperand, 4> Cond;
2478 if (QII->analyzeBranch(*MBB, TBB, FBB, Cond, false)) {
2479 LLVM_DEBUG(dbgs() << "\t\tFail to analyze with analyzeBranch.\n");
2480 LLVM_DEBUG(dbgs() << "\t\tFirst term: "; if (FirstTerm) FirstTerm->dump();
2481 else dbgs() << "None\n";);
2482 // Could not analyze it. See if this is something we can recognize.
2483 TBB = getBranchDestination(FirstTerm);
2484 }
2485 // There are several cases not handled by HexagonInstrInfo::analyzeBranch.
2486 if (!TBB) {
2487 LLVM_DEBUG(dbgs() << "\t\tMissing TBB.\n");
2488 // There is a branch, but TBB is not found.
2489 // The BB could also be empty at this point. See if it is a trivial
2490 // layout case.
2491 if (MBB->succ_size() == 1) {
2492 TBB = *MBB->succ_begin();
2493 LLVM_DEBUG(dbgs() << "\t\tFall through TBB(" << TBB->getNumber()
2494 << ").\n");
2495 return false;
2496 } else if (MBB->succ_size() == 2) {
2497 // This should cover majority of remaining cases.
2498 if (FirstTerm && SecondTerm &&
2499 (QII->isPredicated(*FirstTerm) || QII->isNewValueJump(*FirstTerm)) &&
2500 !QII->isPredicated(*SecondTerm)) {
2501 TBB = getBranchDestination(FirstTerm);
2502 FBB = getBranchDestination(SecondTerm);
2503 LLVM_DEBUG(dbgs() << "\t\tCanonical dual jump layout: TBB("
2504 << TBB->getNumber() << ") FBB(" << FBB->getNumber()
2505 << ").\n");
2506 return false;
2507 } else if (SecondTerm && SecondTerm->getOpcode() == Hexagon::J2_jump &&
2508 SecondTerm->getOperand(0).isMBB()) {
2509 // Look at the second term if I know it, to find out what is the fall
2510 // through for this BB.
2511 FBB = SecondTerm->getOperand(0).getMBB();
2512 assert(MBB->succ_size() == 2 && "Expected exactly 2 successors");
2513 MachineBasicBlock *Succ0 = *MBB->succ_begin();
2514 MachineBasicBlock *Succ1 = *std::next(MBB->succ_begin());
2515 if (FBB == Succ0)
2516 TBB = Succ1;
2517 else
2518 TBB = Succ0;
2519 LLVM_DEBUG(dbgs() << "\t\tSecond br is J2_jump TBB(" << TBB->getNumber()
2520 << ") FBB(" << FBB->getNumber() << ").\n");
2521 return false;
2522 } else {
2523 // This might be an empty BB but still with two
2524 // successors set. Try to use CFG layout to sort it out.
2525 // This could happen when last jump was pulled up from a BB, and
2526 // CFG is being updated. At that point this method is called and
2527 // returns best guess possible for TBB/FBB. Fortunately order of those
2528 // is irrelevant, and rather used a worklist for CFG update.
2530 MachineFunction &MF = *MBB->getParent();
2531 (void)MF; // supress compiler warning
2532 // If there are no other clues, assume next sequential BB
2533 // in CFG as FBB.
2534 ++MBBIter;
2535 assert(MBBIter != MF.end() && "I give up.");
2536 FBB = &(*MBBIter);
2537 assert(MBB->succ_size() == 2 && "Expected exactly 2 successors");
2538 MachineBasicBlock *S0 = *MBB->succ_begin();
2539 MachineBasicBlock *S1 = *std::next(MBB->succ_begin());
2540 if (FBB == S0)
2541 TBB = S1;
2542 else if (FBB == S1) {
2543 TBB = S0;
2544 } else {
2545 // This case can arise when the layout successor basic block (++IMBB)
2546 // got empty during pull-up.
2547 // As a result, ++IMBB is not one of MBB's successors.
2548 MBBIter = MF.begin();
2549 while (!MBB->isSuccessor(&*MBBIter) && (MBBIter != MF.end()))
2550 ++MBBIter;
2551 assert(MBBIter != MF.end() && "Malformed BB with invalid successors");
2552 FBB = &*MBBIter;
2553 if (FBB == S0)
2554 TBB = S1;
2555 else
2556 TBB = S0;
2557 }
2558 LLVM_DEBUG(dbgs() << "\t\tUse layout TBB(" << TBB->getNumber()
2559 << ") FBB(" << FBB->getNumber() << ").\n");
2560 return false;
2561 }
2562 }
2563 assert(!FirstTerm && "Bad BB");
2564 return true;
2565 }
2566 // Ok, we have TBB, but maybe missing FBB.
2567 if (!FBB && SecondTerm) {
2568 LLVM_DEBUG(dbgs() << "\t\tMissing FBB.\n");
2569 // analyzeBranch could lie to us, ignore it in this case.
2570 // For the canonical case simply take known branch targets.
2571 if ((QII->isPredicated(*FirstTerm) || QII->isNewValueJump(*FirstTerm)) &&
2572 !QII->isPredicated(*SecondTerm)) {
2573 FBB = getBranchDestination(SecondTerm);
2574 } else {
2575 // Second term is also predicated.
2576 // Use CFG layout. Assign layout successor as FBB.
2577 for (MachineBasicBlock *Succ : MBB->successors()) {
2578 if (MBB->isLayoutSuccessor(Succ))
2579 FBB = Succ;
2580 }
2581 if (FBB == NULL) {
2582 LLVM_DEBUG(dbgs() << "\nNo layout successor found.");
2583 LLVM_DEBUG(dbgs() << "Possibly the layout successor is an empty BB");
2584 return true;
2585 }
2586 if (TBB == FBB)
2587 LLVM_DEBUG(dbgs() << "Malformed branch with useless branch condition";);
2588 }
2589 LLVM_DEBUG(dbgs() << "\t\tSecond term: "; SecondTerm->dump());
2590 } else if (TBB && !FBB) {
2591 // If BB ends in endloop, and it is a single BB hw loop,
2592 // we will have a single terminator, but we can figure FBB
2593 // easily from CFG.
2594 if (MBB->succ_size() == 2) {
2595 MachineBasicBlock *S0 = *MBB->succ_begin();
2596 MachineBasicBlock *S1 = *std::next(MBB->succ_begin());
2597 if (TBB == S0)
2598 FBB = S1;
2599 else
2600 FBB = S0;
2601 }
2602 }
2603
2604 LLVM_DEBUG(dbgs() << "\t\tFinal TBB(" << TBB->getNumber() << ").\n";
2605 if (FBB) dbgs() << "\t\tFinal FBB(" << FBB->getNumber() << ").\n";
2606 else dbgs() << "\t\tFinal FBB(None)\n";);
2607 return false;
2608}
2609
2610/// updateBranches - Updates all branches to \p From in the basic block \p
2611/// InBlock to branches to \p To.
2613 MachineBasicBlock *To) {
2614 for (MachineBasicBlock::instr_iterator BI = InBlock.instr_begin(),
2615 E = InBlock.instr_end();
2616 BI != E; ++BI) {
2617 MachineInstr *Inst = &*BI;
2618 // Ignore anything that is not a branch.
2619 if (!Inst->isBranch())
2620 continue;
2622 OE = Inst->operands_end();
2623 OI != OE; ++OI) {
2624 MachineOperand &Opd = *OI;
2625 // Look for basic block "From".
2626 if (!Opd.isMBB() || Opd.getMBB() != From)
2627 continue;
2628 // Update it.
2629 Opd.setMBB(To);
2630 }
2631 }
2632}
2633
2634/// Rewrite all predecessors of the old block to go to the fallthrough
2635/// instead.
2636/// NB: Collect predecessors into a snapshot vector before iterating to
2637/// avoid iterator invalidation on MBB's predecessor list. Each call to
2638/// ReplaceUsesOfBlockWith modifies both the successor list of Pred and
2639/// the predecessor list of MBB, which invalidates debug-mode iterators
2640/// (detected by _GLIBCXX_DEBUG).
2642 MachineBasicBlock *MFBB) {
2643 MachineFunction &MF = *MBB.getParent();
2644
2645 if (MFBB->getIterator() == MF.end())
2646 return;
2647
2648 // Snapshot the predecessor list to avoid iterator invalidation.
2649 SmallVector<MachineBasicBlock *, 4> Preds(MBB.pred_begin(), MBB.pred_end());
2650 for (MachineBasicBlock *Pred : Preds) {
2651 if (!Pred->isSuccessor(&MBB))
2652 continue;
2653 Pred->ReplaceUsesOfBlockWith(&MBB, MFBB);
2654 updateBranches(*Pred, &MBB, MFBB);
2655 }
2656}
2657
2658static void UpdateCFG(MachineBasicBlock *HomeBB, MachineBasicBlock *OriginBB,
2659 MachineInstr *MII, MachineBasicBlock *HomeTBB,
2660 MachineBasicBlock *HomeFBB, MachineInstr *FTA,
2661 MachineInstr *STA,
2662 const MachineBranchProbabilityInfo *MBPI) {
2663 MachineBasicBlock *S2Add = NULL, *S2Remove = NULL;
2664 bool RemoveLSIfPresent = false;
2665 if ((&*MII == FTA) && MII->isConditionalBranch()) {
2666 LLVM_DEBUG(dbgs() << "\nNew firstterm conditional jump added to HomeBB";);
2667 S2Add = HomeTBB;
2668 S2Remove = HomeTBB;
2669 } else if ((&*MII == STA) && MII->isConditionalBranch()) {
2670 LLVM_DEBUG(dbgs() << "\nNew secondterm conditional jump added to HomeBB";);
2671 // AnalyzeBBBranches might not give correct information in this case.
2672 // The branch destination may be a symbol, not necessarily a block.
2673 if (MachineBasicBlock *Dest = getBranchDestination(MII)) {
2674 LLVM_DEBUG(dbgs() << "\nBranch destination for pulled instruction is BB#"
2675 << Dest->getNumber(););
2676 S2Add = Dest;
2677 S2Remove = Dest;
2678 }
2679 } else if ((&*MII == FTA) && MII->isUnconditionalBranch()) {
2680 LLVM_DEBUG(dbgs() << "\nNew firstterm unconditional jump added to HomeBB";);
2681 S2Add = HomeTBB;
2682 S2Remove = HomeTBB;
2683 RemoveLSIfPresent = true;
2684 } else if ((&*MII == STA) && MII->isUnconditionalBranch()) {
2685 LLVM_DEBUG(
2686 dbgs() << "\nNew secondterm unconditional jump added to HomeBB";);
2687 S2Add = HomeFBB;
2688 S2Remove = HomeFBB;
2689 RemoveLSIfPresent = true;
2690 }
2691 if (S2Add && !HomeBB->isSuccessor(S2Add)) {
2692 HomeBB->addSuccessor(S2Add, MBPI->getEdgeProbability(OriginBB, S2Add));
2693 }
2694 if (S2Remove)
2695 OriginBB->removeSuccessor(S2Remove);
2696 if (RemoveLSIfPresent) {
2697 MachineFunction::iterator HomeBBLS = HomeBB->getIterator();
2698 ++HomeBBLS;
2699 if (HomeBBLS != HomeBB->getParent()->end() &&
2700 HomeBB->isLayoutSuccessor(&*HomeBBLS)) {
2701 LLVM_DEBUG(dbgs() << "\nRemoving LayoutSucc BB#" << HomeBBLS->getNumber()
2702 << "from list of successors";);
2703 HomeBB->removeSuccessor(&*HomeBBLS);
2704 }
2705 }
2706}
2707
2708/// Move instruction from/to BB, Update liveness info,
2709/// return pointer to the newly inserted and modified
2710/// instruction.
2711MachineInstr *HexagonGlobalSchedulerImpl::MoveAndUpdateLiveness(
2712 BasicBlockRegion *CurrentRegion, MachineBasicBlock *HomeBB,
2713 MachineInstr *InstrToMove, bool NeedToNewify, unsigned DepReg,
2714 bool MovingDependentOp, MachineBasicBlock *OriginBB,
2715 MachineInstr *OriginalInstruction, SmallVector<MachineOperand, 4> &Cond,
2716 MachineBasicBlock::iterator &SourceLocation,
2717 MachineBasicBlock::iterator &TargetPacket,
2719 std::vector<MachineInstr *> &backtrack) {
2720 LLVM_DEBUG(
2721 dbgs() << "\n...............[MoveAndUpdateLiveness]..............\n");
2722 LLVM_DEBUG(dbgs() << "\t\tInstrToMove :\t"; InstrToMove->dump());
2723 LLVM_DEBUG(dbgs() << "\t\tOriginalInstruction:\t";
2724 OriginalInstruction->dump());
2725 LLVM_DEBUG(dbgs() << "\t\tSourceLocation :\t";
2726 DumpPacket(SourceLocation.getInstrIterator()));
2727 LLVM_DEBUG(dbgs() << "\t\tTargetPacket :\t";
2728 DumpPacket(TargetPacket.getInstrIterator()));
2729
2731 SourceLocation.getInstrIterator();
2732 MachineBasicBlock::instr_iterator OriginalTail = getBundleEnd(OriginalHead);
2734 OriginalInstruction->getIterator();
2735
2736 // Remove our temporary instruction.
2737 MachineBasicBlock::instr_iterator kill_it(InstrToMove);
2738 HomeBB->erase(kill_it);
2739
2740 MachineBasicBlock::instr_iterator TargetHead(TargetPacket.getInstrIterator());
2741 MachineBasicBlock::instr_iterator TargetTail = getBundleEnd(TargetHead);
2742
2743 LLVM_DEBUG(dbgs() << "\n\tTo BB before:\n"; debugLivenessForBB(HomeBB, QRI));
2744 LLVM_DEBUG(dbgs() << "\n\tFrom BB before:\n";
2745 debugLivenessForBB(OriginBB, QRI));
2746
2747 // Before we perform the move, we need to collect the worklist
2748 // of BBs for liveness updated.
2749 std::list<MachineBasicBlock *> WorkList;
2750
2751 // Insert into the work list all BBs along the backtrace.
2752 for (std::vector<MachineInstr *>::iterator RI = backtrack.begin(),
2753 RIE = backtrack.end();
2754 RI != RIE; RI++)
2755 WorkList.push_back((*RI)->getParent());
2756
2757 // Only keep unique entries.
2758 // TODO: Use a different container here.
2759 WorkList.unique();
2760
2761 // Move the original instruction.
2762 // If this instruction is inside a bundle, update the bundle.
2764 TargetHead->getParent()->instr_end();
2765 bool LastInstructionInBundle = false;
2766 MachineBasicBlock::instr_iterator MII = findInsertPositionInBundle(
2767 TargetPacket, &*OutcastFrom, LastInstructionInBundle);
2768
2769 (void)BBEnd;
2770 LLVM_DEBUG(dbgs() << "\n\t\t\tHead target : "; DumpPacket(TargetHead));
2771 LLVM_DEBUG(dbgs() << "\t\t\tTail target : ";
2772 DumpPacket(TargetTail, BBEnd));
2773 LLVM_DEBUG(dbgs() << "\t\t\tInsert right before: "; DumpPacket(MII, BBEnd));
2774
2775 MIBundleBuilder Bundle(&*TargetHead);
2776
2777 // Actual move. One day liveness might be updated here.
2778 if (OriginalInstruction->isBundled()) {
2779 Bundle.insert(MII, OriginalInstruction->removeFromBundle());
2780 --MII;
2781 } else {
2782 // This is one case currently unhandled by Bundle.insert
2783 // and needs to be fixed upstream. Meanwhile use old way to handle
2784 // this odd case.
2785 if (OriginalInstruction->getIterator() == TargetTail) {
2786 LLVM_DEBUG(dbgs() << "\t\t\tSpecial case move.\n");
2787 MachineBasicBlock::instr_iterator MIIToPred = MII;
2788 --MIIToPred;
2789 LLVM_DEBUG(dbgs() << "\t\t\tInser after : ";
2790 DumpPacket(MIIToPred, BBEnd));
2791 // Unbundle it in its current location.
2792 if (OutcastFrom->isBundledWithSucc()) {
2793 OutcastFrom->clearFlag(MachineInstr::BundledSucc);
2794 OutcastFrom->clearFlag(MachineInstr::BundledPred);
2795 } else if (OutcastFrom->isBundledWithPred()) {
2796 OutcastFrom->unbundleFromPred();
2797 }
2798 HomeBB->splice(MII, OriginBB, OutcastFrom);
2799 if (!MII->isBundledWithPred())
2800 MII->bundleWithPred();
2801 if (!LastInstructionInBundle && !MII->isBundledWithSucc())
2802 MII->bundleWithSucc();
2803 // This is the instruction after which we have inserted.
2804 if (!MIIToPred->isBundledWithSucc())
2805 MIIToPred->bundleWithSucc();
2806 } else {
2807 Bundle.insert(MII, OriginalInstruction->removeFromParent());
2808 --MII;
2809 }
2810 }
2811 // Source location bundle is updated later in the
2812 // removeInstructionFromExistingBundle().
2813
2814 LLVM_DEBUG(dbgs() << "\t\t\tNew packet head: "; DumpPacket(TargetHead));
2815 LLVM_DEBUG(dbgs() << "\t\t\tInserted op : "; MII->dump());
2816 LLVM_DEBUG(dbgs() << "\n\tTo BB after move:\n";
2817 debugLivenessForBB(HomeBB, QRI));
2818 LLVM_DEBUG(dbgs() << "\n\tFrom BB after:\n";
2819 debugLivenessForBB(OriginBB, QRI));
2820
2821 // Update kill patterns. Do it before we have predicated the moved
2822 // instruction.
2823 updateKillAlongThePath(HomeBB, OriginBB, MII, TargetTail, SourceLocation,
2824 TargetPacket, backtrack);
2825 // I need to know:
2826 // - true/false predication
2827 // - do I need to .new it?
2828 // - do I need to .old it?
2829 // If the original instruction used new value operands,
2830 // it might need to be changed to the generic form
2831 // before further processing.
2832 if (QII->isDotNewInst(*MII)) {
2833 DemoteToDotOld(&*MII);
2834 LLVM_DEBUG(dbgs() << "\t\t\tDemoted to .old\t:"; MII->dump());
2835 }
2836
2837 // We have previously checked whether this instruction could
2838 // be placed in this packet, including all possible transformations
2839 // it might need, so if any request will fail now, something is wrong.
2840 //
2841 // Need for predication and the exact condition is determined by
2842 // the path between original and current instruction location.
2843 if (!Cond.empty()) { // To be predicated
2844 LLVM_DEBUG(dbgs() << "\t\t\tPredicating:"; MII->dump());
2845 assert(TII->isPredicable(*MII) && "MII is not predicable");
2847 if (NeedToNewify) {
2848 assert((DepReg < std::numeric_limits<unsigned>::max()) &&
2849 "Invalid pred reg value");
2850 LLVM_DEBUG(dbgs() << "\t\t\tNeeds to NEWify on Reg("
2851 << printReg(DepReg, QRI) << ").\n");
2852 int NewOpcode = QII->getDotNewPredOp(*MII, MBPI);
2853 MII->setDesc(QII->get(NewOpcode));
2854
2855 // Now we need to mark newly created predicate operand as
2856 // internal read.
2857 // TODO: Better look for predicate operand.
2858 for (unsigned i = 0, e = MII->getNumOperands(); i != e; ++i) {
2859 MachineOperand &MO = MII->getOperand(i);
2860 if (!MO.isReg())
2861 continue;
2862 if (MO.isDef())
2863 continue;
2864 if (DepReg == MO.getReg())
2865 MO.setIsInternalRead();
2866 }
2867 }
2868 LLVM_DEBUG(dbgs() << "\t\t\tNew predicated form:\t"; MII->dump());
2869 // If the predicate has changed kill pattern, now we need to propagate
2870 // that again. This is important for liveness computation.
2871 updateKillAlongThePath(HomeBB, OriginBB, MII, TargetTail, SourceLocation,
2872 TargetPacket, backtrack);
2873 }
2874
2875 // Create new bundle header, remove the old one.
2876 addInstructionToExistingBundle(HomeBB, TargetHead, TargetTail, MII,
2877 TargetPacket, NextMI, backtrack);
2878
2879 // If moved instruction was inside a bundle, update that bundle.
2880 removeInstructionFromExistingBundle(OriginBB, ++OriginalHead, OriginalTail,
2881 SourceLocation, NextMI, MovingDependentOp,
2882 backtrack);
2883
2884 // If removed instruction could have been dependent on any
2885 // of the remaining ops, we need to oldify possible affected ones.
2886 LLVM_DEBUG(dbgs() << "\t\tTargetHead:\t"; DumpPacket(TargetHead, BBEnd));
2887 LLVM_DEBUG(dbgs() << "\t\tOriginalHead:\t"; DumpPacket(OriginalHead, BBEnd));
2888 LLVM_DEBUG(dbgs() << "\t\tOriginalInstruction:\t";
2889 DumpPacket(OriginalInstruction->getIterator(), BBEnd));
2890 LLVM_DEBUG(dbgs() << "\t\tOutcastFrom:\t"; DumpPacket(OutcastFrom, BBEnd));
2891
2892 // Clean up the original source bundle on a global scope.
2893 if (OriginalHead != MachineBasicBlock::instr_iterator() &&
2894 QII->isEndLoopN(OriginalHead->getOpcode())) {
2895 // Single endloop left. Since it is not a real instruction,
2896 // we can simply add it to a non empty previous bundle, if one exist,
2897 // or let assembler to produce a fake bundle for it.
2898 LLVM_DEBUG(dbgs() << "\t\tOnly endloop in packet.\n");
2900 if (OriginBB->begin() != I) {
2901 --I;
2902 if (I->isBundled()) {
2903 if (!I->isBundledWithSucc())
2904 I->bundleWithSucc();
2905 if (!OriginalHead->isBundledWithPred())
2906 OriginalHead->bundleWithPred();
2907 }
2908 // else we probably need to create a new bundle here.
2909 // SourceLocation = NULL;
2910 }
2911 } else if (MovingDependentOp &&
2912 OriginalHead != MachineBasicBlock::instr_iterator()) {
2913 if (OriginalHead->isBundled()) {
2914 for (MachineBasicBlock::instr_iterator J = ++OriginalHead;
2915 J != OriginalTail && J->isInsideBundle() && !J->isBundle(); ++J) {
2916 // Need to oldify it.
2917 if (MIsHaveTrueDependency(OriginalInstruction, &*J) &&
2918 QII->isDotNewInst(*J)) {
2919 LLVM_DEBUG(dbgs() << "\t\tDemoting to .old:\t"; J->dump());
2920 DemoteToDotOld(&*J);
2921 }
2922 }
2923 } else {
2924 // Single instruction left.
2925 if (MIsHaveTrueDependency(OriginalInstruction, &*OriginalHead) &&
2926 QII->isDotNewInst(*OriginalHead)) {
2927 LLVM_DEBUG(dbgs() << "\t\tDemoting to .old op:\t";
2928 OriginalHead->dump());
2929 DemoteToDotOld(&*OriginalHead);
2930 }
2931 }
2932 }
2933
2934 // Now we need to update liveness to all BBs involved
2935 // including those we might have "passed" through on the way here.
2936 LLVM_DEBUG(dbgs() << "\n\tTo BB after bundle update:\n"; HomeBB->dump());
2937 LLVM_DEBUG(dbgs() << "\n\n\tFrom BB after bundle update:\n";
2938 OriginBB->dump());
2939
2940 // Update global liveness.
2941 LLVM_DEBUG(dbgs() << "\n\tWorkList:\t");
2942 for (std::list<MachineBasicBlock *>::iterator BBI = WorkList.begin(),
2943 BBIE = WorkList.end();
2944 BBI != BBIE; BBI++) {
2945 LLVM_DEBUG(dbgs() << "BB#" << (*BBI)->getNumber() << " ");
2946 }
2947 LLVM_DEBUG(dbgs() << "\n");
2948
2949 do {
2950 MachineBasicBlock *BB = WorkList.back();
2951 WorkList.pop_back();
2952 CurrentRegion->getLivenessInfoForBB(BB)->UpdateLiveness(BB);
2953 } while (!WorkList.empty());
2954
2955 // No need to analyze for empty BB or update CFG for same BB pullup.
2956 if (OriginBB == HomeBB)
2957 return &*TargetHead;
2958 // If the instruction moved was a branch we need to update the
2959 // successor/predecessor of OriginBB and HomeBB accordingly.
2960 MachineBasicBlock *HomeTBB, *HomeFBB;
2961 MachineInstr *FTA = NULL, *STA = NULL;
2962 bool HomeBBAnalyzed = !AnalyzeBBBranches(HomeBB, HomeTBB, FTA, HomeFBB, STA);
2963 if (MII->isBranch()) {
2964 if (HomeBBAnalyzed) {
2965 UpdateCFG(HomeBB, OriginBB, &*MII, HomeTBB, HomeFBB, FTA, STA, MBPI);
2966 } else {
2967 llvm_unreachable("Underimplememted AnalyzeBBBranches");
2968 }
2969 }
2970 // If we have exhausted the OriginBB clean it up.
2971 // Beware that we could have created dual conditional jumps, which
2972 // ultimately means we can have three way jumps.
2973 if (IsEmptyBlock(OriginBB) && !OriginBB->isEHPad() &&
2974 !OriginBB->hasAddressTaken() && !OriginBB->succ_empty()) {
2975 // Dead block? Unlikely, but check.
2976 LLVM_DEBUG(dbgs() << "Empty BB(" << OriginBB->getNumber() << ").\n");
2977 // Update region map.
2978 CurrentRegion->RemoveBBFromRegion(OriginBB);
2979 // Keep the list of empty basic blocks to be freed later.
2980 EmptyBBs.push_back(OriginBB);
2981 if (OriginBB->pred_empty() || OriginBB->succ_empty())
2982 return &*TargetHead;
2983
2984 if (OriginBB->succ_size() == 1) {
2985 // Find empty block's successor.
2986 MachineBasicBlock *CommonFBB = *OriginBB->succ_begin();
2987 updatePredecessors(*OriginBB, CommonFBB);
2988 // Remove the only successor entry for empty BB.
2989 OriginBB->removeSuccessor(CommonFBB);
2990 } else {
2991 // Three way branching is not yet fully supported.
2992 assert((OriginBB->succ_size() == 2) && "Underimplemented 3way branch.");
2993 MachineBasicBlock *OriginTBB, *OriginFBB;
2994 MachineInstr *FTB = NULL, *STB = NULL;
2995
2996 LLVM_DEBUG(dbgs() << "\tComplex case.\n");
2997 if (HomeBBAnalyzed &&
2998 !AnalyzeBBBranches(OriginBB, OriginTBB, FTB, OriginFBB, STB)) {
2999 assert(OriginFBB && "Missing Origin FBB");
3000 if (HomeFBB == OriginBB) {
3001 // OriginBB is FBB for HomeBB.
3002 if (HomeTBB == OriginTBB) {
3003 // Shared TBB target, common FBB.
3004 updatePredecessors(*OriginBB, OriginFBB);
3005 } else if (HomeTBB == OriginFBB) {
3006 // Shared TBB target, common FBB.
3007 updatePredecessors(*OriginBB, OriginTBB);
3008 } else {
3009 // Three way branch. Add new successor to HomeBB.
3010 updatePredecessors(*OriginBB, OriginFBB);
3011 // TODO: Update the weight as well.
3012 // Adding the successor to make updatePredecessor happy.
3013 HomeBB->addSuccessor(OriginBB);
3014 updatePredecessors(*OriginBB, OriginTBB);
3015 }
3016 } else if (HomeTBB == OriginBB) {
3017 // OriginBB is TBB for HomeBB.
3018 if (HomeFBB == OriginTBB) {
3019 // Shared TBB target, common FBB.
3020 updatePredecessors(*OriginBB, OriginFBB);
3021 } else if (HomeFBB == OriginFBB) {
3022 // Shared TBB target, common FBB.
3023 updatePredecessors(*OriginBB, OriginTBB);
3024 } else {
3025 // Three way branch. Add new successor to HomeBB.
3026 updatePredecessors(*OriginBB, OriginFBB);
3027 // TODO: Update the weight as well.
3028 // Adding the successor to make updatePredecessor happy.
3029 HomeBB->addSuccessor(OriginBB);
3030 updatePredecessors(*OriginBB, OriginTBB);
3031 }
3032 } else
3033 llvm_unreachable("CFG update failed");
3034 // The empty BB can now be relieved of its successors.
3035 OriginBB->removeSuccessor(OriginFBB);
3036 OriginBB->removeSuccessor(OriginTBB);
3037 } else
3038 llvm_unreachable("Underimplemented analyzeBranch");
3039 }
3040 LLVM_DEBUG(dbgs() << "Updated BB(" << HomeBB->getNumber() << ").\n";
3041 HomeBB->dump());
3042 }
3043 return &*TargetHead;
3044}
3045
3046// Find where inside a given bundle current instruction should be inserted.
3047// Instruction will be inserted _before_ this position.
3049HexagonGlobalSchedulerImpl::findInsertPositionInBundle(
3050 MachineBasicBlock::iterator &Bundle, MachineInstr *MI, bool &LastInBundle) {
3052 MachineBasicBlock *MBB = MII->getParent();
3054 MachineBasicBlock::instr_iterator FirstBranch = BBEnd;
3055 MachineBasicBlock::instr_iterator LastBundledInstruction = BBEnd;
3056 MachineBasicBlock::instr_iterator DualJumpFirstCandidate = BBEnd;
3057
3058 assert(MII->isBundle() && "Missing insert location");
3059 bool isDualJumpSecondCandidate = IsDualJumpSecondCandidate(MI);
3060 LastInBundle = false;
3061
3062 for (++MII; MII != BBEnd && MII->isInsideBundle() && !MII->isBundle();
3063 ++MII) {
3064 if (MII->isBranch() && (FirstBranch == BBEnd))
3065 FirstBranch = MII;
3066 // If what we insert is a dual jump, we need to find
3067 // first jump, and insert new instruction after it.
3068 if (isDualJumpSecondCandidate && IsDualJumpFirstCandidate(&*MII))
3069 DualJumpFirstCandidate = MII;
3070 LastBundledInstruction = MII;
3071 }
3072
3073 if (DualJumpFirstCandidate != BBEnd) {
3074 // First respect dual jumps.
3075 ++DualJumpFirstCandidate;
3076 if (DualJumpFirstCandidate == BBEnd ||
3077 DualJumpFirstCandidate == LastBundledInstruction)
3078 LastInBundle = true;
3079 return DualJumpFirstCandidate;
3080 } else if (FirstBranch != BBEnd) {
3081 // If we have no dual jumps, but do have a single
3082 // branch in the bundle, add our new instruction
3083 // right before it.
3084 return FirstBranch;
3085 } else if (LastBundledInstruction != BBEnd) {
3086 LastInBundle = true;
3087 return ++LastBundledInstruction;
3088 } else
3089 llvm_unreachable("Lost in bundle");
3090 return MBB->instr_begin();
3091}
3092
3093/// This function for now needs to try to insert new instruction
3094/// in correct serial semantics fashion - i.e. find "correct" insert
3095/// point for instruction as if inserting in serial sequence.
3096MachineBasicBlock::instr_iterator HexagonGlobalSchedulerImpl::insertTempCopy(
3097 MachineBasicBlock *MBB, MachineBasicBlock::iterator &TargetPacket,
3098 MachineInstr *MI, bool DeleteOldCopy) {
3100 MachineBasicBlock *CurrentBB = MI->getParent();
3101
3102 assert(CurrentBB && "Corrupt instruction");
3103 // Create a temporary copy of the instruction we are considering.
3104 // LLVM refuses to deal with an instruction which was not inserted
3105 // to any BB. We can visit multiple BBs on the way "up", so we
3106 // create a temp copy of the original instruction and delete it later.
3107 // It is way cheaper than using splice and then
3108 // needing to undo it most of the time.
3109 MachineInstr *NewMI = MI->getParent()->getParent()->CloneMachineInstr(MI);
3110 // Make sure all bundling flags are cleared.
3111 if (NewMI->isBundledWithPred())
3112 NewMI->unbundleFromPred();
3113 if (NewMI->isBundledWithSucc())
3114 NewMI->unbundleFromSucc();
3115
3116 if (DeleteOldCopy) {
3117 // Remove our temporary instruction.
3118 // MachineBasicBlock::erase method calls unbundleSingleMI()
3119 // prior to deletion, so we do not have to do it here.
3121 CurrentBB->erase(kill_it);
3122 }
3123
3124 // If the original instruction used new value operands,
3125 // it might need to be changed to generic form
3126 // before further processing.
3127 if (QII->isDotNewInst(*NewMI))
3128 DemoteToDotOld(NewMI);
3129
3130 // Insert new temporary instruction.
3131 // If this is the destination packet, insert the tmp after
3132 // its header. Otherwise, as second instr in BB.
3133 if (TargetPacket->getParent() == MBB) {
3134 MII = TargetPacket.getInstrIterator();
3135
3136 if (MII->isBundled()) {
3137 bool LastInBundle = false;
3139 findInsertPositionInBundle(TargetPacket, NewMI, LastInBundle);
3140 MIBundleBuilder Bundle(&*TargetPacket);
3141 Bundle.insert(InsertBefore, NewMI);
3142 } else
3143 MBB->insertAfter(MII, NewMI);
3144 } else {
3145 MII = MBB->instr_begin();
3146
3147 // Skip debug instructions.
3148 while (MII->isDebugInstr())
3149 MII++;
3150
3151 if (MII->isBundled()) {
3152 MIBundleBuilder Bundle(&*MII);
3153 Bundle.insert(++MII, NewMI);
3154 } else
3155 MBB->insertAfter(MII, NewMI);
3156 }
3157 return NewMI->getIterator();
3158}
3159
3160// Check for a conditionally assigned register within the block.
3161bool HexagonGlobalSchedulerImpl::MIsCondAssign(MachineInstr *BMI,
3162 MachineInstr *MI,
3163 SmallVector<unsigned, 4> &Defs) {
3164 if (!QII->isPredicated(*BMI))
3165 return false;
3166 // Its a conditional instruction, now is it the same registers as MI?
3167 SmallVector<unsigned, 4> CondDefs;
3168 SmallVector<unsigned, 8> CondUses;
3169 parseOperands(BMI, CondDefs, CondUses);
3170
3171 for (SmallVector<unsigned, 4>::iterator ID = Defs.begin(), IDE = Defs.end();
3172 ID != IDE; ++ID) {
3173 for (SmallVector<unsigned, 4>::iterator CID = CondDefs.begin(),
3174 CIDE = CondDefs.end();
3175 CID != CIDE; ++CID) {
3176 if (AliasingRegs(*CID, *ID)) {
3177 LLVM_DEBUG(dbgs() << "\tFound conditional def, can't move\n";
3178 BMI->dump());
3179 return true;
3180 }
3181 }
3182 }
3183 return false;
3184}
3185
3186// Returns the Union of all the elements in Set1 and
3187// Union of all the elements in Set2 separately.
3188// Constraints:
3189// Set1 and Set2 should contain an entry for each element in Range.
3190template <typename ElemType, typename IndexType>
3191void Unify(std::vector<ElemType> Range,
3192 std::map<ElemType, std::vector<IndexType>> &Set1,
3193 std::map<ElemType, std::vector<IndexType>> &Set2,
3194 std::pair<std::vector<IndexType>, std::vector<IndexType>> &UnionSet,
3195 unsigned union_size = 100) {
3196 typedef
3197 typename std::map<ElemType, std::vector<IndexType>>::iterator PosIter_t;
3198 typedef typename std::vector<IndexType>::iterator IndexIter_t;
3199 std::vector<IndexType> &Union1 = UnionSet.first;
3200 std::vector<IndexType> &Union2 = UnionSet.second;
3201 Union1.resize(union_size, 0);
3202 Union2.resize(union_size, 0);
3203 LLVM_DEBUG(dbgs() << "\n\t\tElements in the range:\n";);
3204 typename std::vector<ElemType>::iterator iter = Range.begin();
3205 while (iter != Range.end()) {
3206 if ((*iter)->isDebugInstr()) {
3207 ++iter;
3208 continue;
3209 }
3210 LLVM_DEBUG((*iter)->dump());
3211 PosIter_t set1_pos = Set1.find(*iter);
3212 assert(set1_pos != Set1.end() &&
3213 "Set1 should contain an entry for each element in Range.");
3214 IndexIter_t set1idx = set1_pos->second.begin();
3215 while (set1idx != set1_pos->second.end()) {
3216 Union1[*set1idx] = 1;
3217 ++set1idx;
3218 }
3219 PosIter_t set2_pos = Set2.find(*iter);
3220 assert(set2_pos != Set2.end() &&
3221 "Set2 should contain an entry for each element in Range.");
3222 IndexIter_t set2idx = set2_pos->second.begin();
3223 while (set2idx != set2_pos->second.end()) {
3224 Union2[*set2idx] = 1;
3225 ++set2idx;
3226 }
3227 ++iter;
3228 }
3229}
3230
3231static void UpdateBundle(MachineInstr *BundleHead) {
3232 assert(BundleHead->isBundle() && "Not a bundle header");
3233 if (!BundleHead)
3234 return;
3235 unsigned Size = BundleHead->getBundleSize();
3236 if (Size >= 2)
3237 return;
3238 if (Size == 1) {
3239 MachineBasicBlock::instr_iterator MIter = BundleHead->getIterator();
3240 MachineInstr *MI = &*(++MIter);
3241 MI->unbundleFromPred();
3242 }
3243 BundleHead->eraseFromParent();
3244}
3245
3246/// Gatekeeper for instruction speculation.
3247/// If all MI defs are dead (not live-in) to any other
3248/// BB but the one we are moving into, and it could not cause
3249/// exception by early execution, allow it to be pulled up.
3250bool HexagonGlobalSchedulerImpl::canMIBeSpeculated(
3251 MachineInstr *MI, MachineBasicBlock *ToBB, MachineBasicBlock *FromBB,
3252 std::vector<MachineInstr *> &backtrack) {
3253 // For now disallow memory accesses from speculation.
3254 // Generally we can check if they potentially may trap/cause an exception.
3255 if (!EnableSpeculativePullUp || !MI || MI->mayStore())
3256 return false;
3257
3258 LLVM_DEBUG(dbgs() << "\t[canMIBeSpeculated] From BB(" << FromBB->getNumber()
3259 << "):\t";
3260 MI->dump());
3261 LLVM_DEBUG(dbgs() << "\tTo this BB:\n"; ToBB->dump());
3262
3263 if (!ToBB->isSuccessor(FromBB))
3264 return false;
3265
3266 // This is a very tricky topic. Speculating arithmetic instructions with
3267 // results dead out of a loop more times then required by number of
3268 // iterations is safe, while speculating loads can cause an exception.
3269 // Simplest of checks is to not cross loop exit edge, or in our case
3270 // do not pull-in to a loop exit BB, but there are implications for
3271 // non-natural loops (not recognized by LLVM as loops) and multi-threaded
3272 // code.
3273 if (AllowSpeculateLoads && MI->mayLoad()) {
3274 // Invariant loads should always be safe.
3275 if (!MI->isDereferenceableInvariantLoad())
3276 return false;
3277 LLVM_DEBUG(dbgs() << "\tSpeculating a Load.\n");
3278 }
3279
3280 SmallVector<unsigned, 4> Defs;
3281 SmallVector<unsigned, 8> Uses;
3282 parseOperands(MI, Defs, Uses);
3283
3284 // Do not speculate instructions that modify reserved global registers.
3285 for (unsigned R : Defs)
3286 if (MRI->isReserved(R) && QRI->isGlobalReg(R))
3287 return false;
3288
3290 SE = ToBB->succ_end();
3291 SI != SE; ++SI) {
3292 // TODO: Allow an instruction (I) which 'defines' the live-in reg (R)
3293 // along the path when I is the first instruction to use the R.
3294 // i.e., I kills R before any other instruction in the BB uses it.
3295 // TODO: We have already parsed live sets - reuse them.
3296 if (*SI == FromBB)
3297 continue;
3298 LLVM_DEBUG(dbgs() << "\tTarget succesor BB to check:\n"; (*SI)->dump());
3299 LLVM_DEBUG(
3300 for (MachineBasicBlock::const_succ_iterator SII = (*SI)->succ_begin(),
3301 SIE = (*SI)->succ_end();
3302 SII != SIE; ++SII)(*SII)
3303 ->dump());
3304 for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
3305 E = (*SI)->livein_end();
3306 I != E; ++I)
3307 for (SmallVector<unsigned, 4>::iterator ID = Defs.begin(),
3308 IDE = Defs.end();
3309 ID != IDE; ++ID) {
3310 if (AliasingRegs((*I).PhysReg, *ID))
3311 return false;
3312 }
3313
3314 // Check the successor blocks for conditional define.
3315 // TODO: We should really test the whole path here.
3316 for (MachineBasicBlock::instr_iterator BI = (*SI)->instr_begin(),
3317 E = (*SI)->instr_end();
3318 BI != E; ++BI) {
3319 if (BI->isBundle() || BI->isDebugInstr())
3320 continue;
3321 LLVM_DEBUG(dbgs() << "\t\tcheck against:\t"; BI->dump());
3322 if (MIsCondAssign(&*BI, MI, Defs))
3323 return false;
3324 }
3325 }
3326 // Taking a very conservative approach during speculation.
3327 // Traverse the path (FromBB, ToBB] and make sure
3328 // that the def-use set of the instruction to be moved
3329 // are not modified.
3330 std::vector<MachineBasicBlock *> PathBB;
3331 for (unsigned i = 0; i < backtrack.size(); ++i) {
3332 // Insert unique BB along the path but skip FromBB
3333 MachineBasicBlock *MBB = backtrack[i]->getParent();
3334 if ((MBB != FromBB) &&
3335 (std::find(PathBB.begin(), PathBB.end(), MBB) == PathBB.end()))
3336 PathBB.push_back(MBB);
3337 }
3338 bool WaitingForTargetPacket = true;
3340 std::vector<MachineInstr *> TraversalRange;
3341 LLVM_DEBUG(dbgs() << "\n\tElements in the range:");
3342 // TODO: Use just the backtrack to get TraversalRange because it
3343 // contains the path (only when speculated from a path in region).
3344 // Note: We check the dependency of instruction-to-move with
3345 // all the instructions (starting from backtrack[0]) in the parent BBs
3346 // because a BB might have a branching from in between due to packetization
3347 // and just checking packets in the backtrack won't be comprehensive.
3348 for (unsigned i = 0; i < PathBB.size(); ++i) {
3349 for (MII = PathBB[i]->instr_begin(); MII != PathBB[i]->instr_end(); ++MII) {
3350 // Skip instructions until the target packet is found.
3351 // although target packet is already checked for correctness,
3352 // it is good to check here to validate intermediate pullups.
3353 if (backtrack[0] == &*MII)
3354 WaitingForTargetPacket = false;
3355 if (WaitingForTargetPacket)
3356 continue;
3357 if (MII->isBundle())
3358 continue;
3359 // TODO: Ideally we should check that there is a `linear' control flow
3360 // in the TraversalRange in all possible manner. For e.g.,
3361 // BB0 { packet1: if(p0) indirect_jump BB1;
3362 // packet2: jump BB2 }
3363 // BB1 { i1 }. In this case we should not pull `i1' into packet2.
3364 if (MII->isCall() || MII->isReturn() ||
3365 (MII->getOpcode() == Hexagon::J2_jump && !MII->getOperand(0).isMBB()))
3366 return false;
3367 if (MI != &*MII) {
3368 TraversalRange.push_back(&*MII);
3369 LLVM_DEBUG(MII->dump(););
3370 }
3371 }
3372 }
3373 // Get the union of def/use set of all the instructions along TraversalRange.
3374 std::pair<std::vector<unsigned>, std::vector<unsigned>> RangeDefUse;
3375 Unify(TraversalRange, MIDefSet, MIUseSet, RangeDefUse, QRI->getNumRegs());
3376 // No instruction (along TraversalRange) should 'define' the use set of MI
3377 for (unsigned j = 0; j < Uses.size(); ++j)
3378 if (RangeDefUse.first[Uses[j]]) {
3379 LLVM_DEBUG(dbgs() << "\n\t\tUnresolved dependency along path to HOME for "
3380 << printReg(Uses[j], QRI););
3381 return false;
3382 }
3383 // No instruction (along TraversalRange) should 'define' or 'use'
3384 // the def set of MI
3385 for (unsigned j = 0; j < Defs.size(); ++j)
3386 if (RangeDefUse.first[Defs[j]] || RangeDefUse.second[Defs[j]]) {
3387 LLVM_DEBUG(dbgs() << "\n\t\tUnresolved dependency along path to HOME for "
3388 << printReg(Defs[j], QRI););
3389 return false;
3390 }
3391 return true;
3392}
3393
3394/// Try to move InstrToMove to TargetPacket using path stored in backtrack.
3395/// SourceLocation is current iterator point. It must be updated to the new
3396/// iteration location after all updates.
3397/// Alogrithm:
3398/// To move an instruction (I) from OriginBB through HomeBB via backtrack.
3399/// for each packet (i) in backtrack, analyzeBranch
3400/// case 1 (success)
3401/// case Pulling from conditional branch:
3402/// if I is predicable
3403/// Try to predicate on the branch condition
3404/// else
3405/// Try to speculate I to backtrack[i].
3406/// case Pulling from unconditional branch:
3407/// Just pullup. (TODO: Speculate here as well)
3408/// case 2 (fails)
3409/// Try to speculate I backtrack[i].
3410bool HexagonGlobalSchedulerImpl::MoveMItoBundle(
3411 BasicBlockRegion *CurrentRegion,
3414 MachineBasicBlock::iterator &TargetPacket,
3415 MachineBasicBlock::iterator &SourceLocation,
3416 std::vector<MachineInstr *> &backtrack, bool MovingDependentOp,
3417 bool PathInRegion) {
3418 MachineBasicBlock *HomeBB = TargetPacket->getParent();
3419 MachineBasicBlock *OriginBB = InstrToMove->getParent();
3420 MachineBasicBlock *CurrentBB = OriginBB;
3421 MachineBasicBlock *CleanupBB = OriginBB;
3422 MachineBasicBlock *PreviousBB = OriginBB;
3423 MachineInstr *OriginalInstructionToMove = &*InstrToMove;
3424
3425 assert(HomeBB && "Missing HomeBB");
3426 assert(OriginBB && "Missing OriginBB");
3427
3428 LLVM_DEBUG(dbgs() << "\n.........[MoveMItoBundle]..............\n");
3429 LLVM_DEBUG(dbgs() << "\t\tInstrToMove :\t"; InstrToMove->dump());
3430 LLVM_DEBUG(dbgs() << "\t\tTargetPacket :\t";
3431 DumpPacket(TargetPacket.getInstrIterator()));
3432 LLVM_DEBUG(dbgs() << "\t\tSourceLocation:\t";
3433 DumpPacket(SourceLocation.getInstrIterator()));
3434
3435 // We do not allow to move instructions in the same BB.
3436 if (HomeBB == OriginBB) {
3437 LLVM_DEBUG(dbgs() << "\t\tSame BB pull-up.\n");
3438 if (!EnableLocalPullUp)
3439 return false;
3440 }
3441
3442 if (OneFloatPerPacket && QII->isFloat(*TargetPacket) &&
3443 QII->isFloat(*InstrToMove))
3444 return false;
3445
3446 if (OneComplexPerPacket && QII->isComplex(*TargetPacket) &&
3447 QII->isComplex(*InstrToMove))
3448 return false;
3449
3450 LLVM_DEBUG(dbgs() << "\t\tWay home:\n");
3451 // Test integrity of the back track.
3452 for (unsigned i = 0; i < backtrack.size(); ++i) {
3453 assert(backtrack[i]->getParent() && "Messed back track.");
3454 LLVM_DEBUG(dbgs() << "\t\t[" << i << "] BB("
3455 << backtrack[i]->getParent()->getNumber() << ")\t";
3456 backtrack[i]->dump());
3457 }
3458 LLVM_DEBUG(dbgs() << "\n");
3459
3460 bool NeedCleanup = false;
3461 bool NeedToPredicate = false;
3462 bool MINeedToNewify = false;
3463 unsigned DepReg = std::numeric_limits<unsigned>::max();
3464 bool isDualJump = false;
3465 SmallVector<MachineOperand, 4> Cond;
3466 SmallVector<MachineOperand, 4> PredCond;
3467 std::vector<MachineInstr *> PullUpPath;
3468 if (PathInRegion)
3469 PullUpPath = backtrack;
3470 else {
3471 PullUpPath.push_back(&*TargetPacket);
3472 PullUpPath.push_back(&*InstrToMove);
3473 }
3474
3475 // Now start iterating over all instructions
3476 // preceeding the one we are trying to move,
3477 // and see if they could be reodered/bypassed.
3478 for (std::vector<MachineInstr *>::reverse_iterator RI = backtrack.rbegin(),
3479 RIE = backtrack.rend();
3480 RI < RIE; ++RI) {
3481 // Once most of debug will be gone, this will be a real assert.
3482 // assert((backtrack.front() == ToThisBundle) && "Lost my way home.");
3483 MachineInstr *MIWH = *RI;
3484 if (QII->isDotNewInst(*InstrToMove)) {
3485 LLVM_DEBUG(dbgs() << "Cannot move a dot new instruction:";
3486 InstrToMove->dump());
3487 if (NeedCleanup)
3488 CleanupBB->erase(InstrToMove);
3489 return false;
3490 }
3491 if (canCauseStall(&*InstrToMove, MIWH)) {
3492 if (NeedCleanup)
3493 CleanupBB->erase(InstrToMove);
3494 return false;
3495 }
3496 LLVM_DEBUG(dbgs() << "\t> Step home BB(" << MIWH->getParent()->getNumber()
3497 << "):\t";
3498 DumpPacket(MIWH->getIterator()));
3499
3500 // See if we cross a jump, and possibly change the form of instruction.
3501 // Passing through BBs with dual jumps in different packets
3502 // takes extra care.
3503 bool isBranchMIWH = isBranch(MIWH);
3504 if (((&*SourceLocation != MIWH) && isBranchMIWH) ||
3505 (CurrentBB != MIWH->getParent())) {
3506 LLVM_DEBUG(dbgs() << "\tChange BB from(" << CurrentBB->getNumber()
3507 << ") to (" << MIWH->getParent()->getNumber() << ")\n");
3508 PreviousBB = CurrentBB;
3509 CurrentBB = MIWH->getParent();
3510
3511 // See what kind of branch we are dealing with.
3512 MachineBasicBlock *PredTBB = NULL;
3513 MachineBasicBlock *PredFBB = NULL;
3514
3515 if (QII->analyzeBranch(*CurrentBB, PredTBB, PredFBB, Cond, false)) {
3516 // We currently do not handle NV jumps of this kind:
3517 // if (cmp.eq(r0.new, #0)) jump:t .LBB12_69
3518 // TODO: Need to handle them.
3519 LLVM_DEBUG(dbgs() << "\tCould not analyze branch.\n");
3520
3521 // This is the main point of lost performance.
3522 // We could try to speculate here, but for that we need accurate
3523 // liveness info, and it is not ready yet.
3524 if (!canMIBeSpeculated(&*InstrToMove, CurrentBB, PreviousBB,
3525 PullUpPath)) {
3526 if (NeedCleanup)
3527 CleanupBB->erase(InstrToMove);
3528 return false;
3529 } else {
3530 // Save speculated instruction moved.
3531 SpeculatedIns.insert(
3532 std::make_pair(OriginalInstructionToMove, OriginBB));
3533 LLVM_DEBUG(dbgs() << "\nSpeculatedInsToMove"; InstrToMove->dump());
3534 }
3535
3536 LLVM_DEBUG(dbgs() << "\tSpeculating.\n");
3537 // If we are speculating, we can come through a predication
3538 // into an unconditional branch...
3539 // For now simply bail out.
3540 // TODO: See if this ever happens.
3541 if (NeedToPredicate) {
3543 << "\tUnderimplemented pred for speculative move.\n");
3544 if (NeedCleanup)
3545 CleanupBB->erase(InstrToMove);
3546 return false;
3547 }
3548 InstrToMove =
3549 insertTempCopy(CurrentBB, TargetPacket, &*InstrToMove, NeedCleanup);
3550 NeedCleanup = true;
3551 NeedToPredicate = false;
3552 assert(!NeedToPredicate && "Need to handle predication for this case");
3553 CleanupBB = CurrentBB;
3554 // No need to recheck for resources - instruction did not change.
3555 LLVM_DEBUG(dbgs() << "\tUpdated BB:\n"; CurrentBB->dump());
3556 } else {
3557 bool LocalNeedPredication = true;
3558 // We were able to analyze the branch.
3559 if (!isBranchMIWH && !PredTBB) {
3560 LLVM_DEBUG(dbgs() << "\tDo not need predicate for this case.\n");
3561 LocalNeedPredication = false;
3562 }
3563 // First see if this is a potential dual jump situation.
3564 if (IsDualJumpSecondCandidate(&*InstrToMove) &&
3565 IsDualJumpFirstCandidate(TargetPacket)) {
3566 LLVM_DEBUG(dbgs() << "\tPerforming unrestricted dual jump.\n");
3567 isDualJump = true;
3568 } else if (LocalNeedPredication && (PredFBB != PreviousBB)) {
3569 // Predicate instruction based on condition feeding it.
3570 // This is generally a statefull pull-up path.
3571 // Can this insn be predicated? If so, try to do it.
3572 if (TII->isPredicable(*InstrToMove)) {
3573 if (PredTBB) {
3574 if (PreviousBB != PredTBB) {
3575 // If we "came" not from TBB, we need to invert condition.
3577 LLVM_DEBUG(dbgs() << "\tUnable to invert condition.\n");
3578 if (NeedCleanup)
3579 CleanupBB->erase(InstrToMove);
3580 return false;
3581 }
3582 }
3583 LLVM_DEBUG(dbgs() << "\tTBB(" << PredTBB->getNumber()
3584 << ")InvertCondition("
3585 << (PreviousBB != PredTBB) << ")\n");
3586 }
3587 // Create a new copy of the instruction we are trying to move.
3588 // It changes enough (new BB, predicated form) and untill we
3589 // reach home, we do not even know if it is going to work.
3590 InstrToMove = insertTempCopy(CurrentBB, TargetPacket, &*InstrToMove,
3591 NeedCleanup);
3592 NeedCleanup = true;
3593 NeedToPredicate = true;
3594 CleanupBB = CurrentBB;
3595
3596 if (PredCond.empty() && // If not already predicated.
3597 TII->PredicateInstruction(*InstrToMove, Cond)) {
3598 LLVM_DEBUG(dbgs() << "\tNew predicated insn:\t";
3599 InstrToMove->dump());
3600 // After predication some instruction could become const extended:
3601 // L2_loadrigp == "$dst=memw(#$global)"
3602 // L4_ploadrit_abs == "if ($src1) $dst=memw(##$global)"
3603 // Resource checking for those is different.
3604 if ((QII->isExtended(*InstrToMove) ||
3605 QII->isConstExtended(*InstrToMove) ||
3606 isJumpOutOfRange(&*InstrToMove)) &&
3607 !tryAllocateResourcesForConstExt(&*InstrToMove, false)) {
3608 // If we cannot, do not modify the state.
3610 << "\tEI Could not be added to the packet.\n");
3611 CleanupBB->erase(InstrToMove);
3612 return false;
3613 }
3614
3615 if (!ResourceTracker->canReserveResources(*InstrToMove) ||
3616 !shouldAddToPacket(*InstrToMove)) {
3617 // It will not fit in its new form...
3618 LLVM_DEBUG(dbgs() << "\tCould not be added in its new form.\n");
3619 CurrentBB->erase(InstrToMove);
3620 return false;
3621 }
3622
3623 // Need also verify that we can newify it if we want to.
3624 if (NeedToNewify(InstrToMove, &DepReg, &*TargetPacket)) {
3625 if (isNewifiable(InstrToMove, DepReg, &*TargetPacket)) {
3626 MINeedToNewify = true;
3627 LLVM_DEBUG(dbgs() << "\t\t\tNeeds to NEWify on Reg("
3628 << printReg(DepReg, QRI) << ").\n");
3629 } else {
3630 LLVM_DEBUG(dbgs() << "\tNon newifiable in this bundle: ";
3631 InstrToMove->dump());
3632 CleanupBB->erase(InstrToMove);
3633 return false;
3634 }
3635 }
3636
3637 LLVM_DEBUG(dbgs() << "\tUpdated BB:\n"; CurrentBB->dump());
3638 PredCond = Cond;
3639 // Now the instruction uses the pred-reg as well.
3640 if (!Cond.empty() && (Cond.size() == 2)) {
3641 MIUseSet[OriginalInstructionToMove].push_back(Cond[1].getReg());
3642 }
3643 assert(((Cond.size() <= 2) &&
3644 !(QII->isNewValueJump(Cond[0].getImm()))) &&
3645 "Update MIUseSet for new-value compare jumps");
3646 } else {
3647 LLVM_DEBUG(dbgs() << "\tCould not predicate it\n");
3648 LLVM_DEBUG(dbgs() << "\tTrying to speculate!\t";
3649 InstrToMove->dump());
3650 bool DistantSpeculation = false;
3651 std::vector<MachineInstr *> NonPredPullUpPath;
3652 unsigned btidx = 0;
3653 // Generate a backtrack path for instruction to be speculated.
3654 // Original backtrack may start from a different (ancestor)
3655 // target packet.
3656 while (btidx < backtrack.size()) {
3657 const MachineBasicBlock *btBB = backtrack[btidx]->getParent();
3658 if ((btBB == PreviousBB) || (btBB == CurrentBB))
3659 NonPredPullUpPath.push_back(backtrack[btidx]);
3660 ++btidx;
3661 }
3662 // Speculate only to immediate predecessor.
3663 if (PreviousBB != CurrentBB) {
3664 if (*(PreviousBB->pred_begin()) != CurrentBB) {
3665 // In a region there are no side entries.
3666 DistantSpeculation = true;
3668 << "\n\tMI not in immediate successor of BB#"
3669 << CurrentBB->getNumber() << ", MI is in BB#"
3670 << PreviousBB->getNumber(););
3671 }
3672 assert((PreviousBB->pred_size() < 2) &&
3673 "Region with a side entry");
3674 }
3675 // TODO: Speculate ins. when pulled from unlikely path.
3676 if (DistantSpeculation || /*!PathInRegion ||*/
3677 InstrToMove->mayLoad() || InstrToMove->mayStore() ||
3678 InstrToMove->hasUnmodeledSideEffects() ||
3679 !canMIBeSpeculated(&*InstrToMove, CurrentBB, PreviousBB,
3680 NonPredPullUpPath)) {
3681 CleanupBB->erase(InstrToMove);
3682 return false;
3683 } else {
3684 // Save speculated instruction moved.
3685 NeedToPredicate = false;
3686 SpeculatedIns.insert(
3687 std::make_pair(OriginalInstructionToMove, OriginBB));
3688 LLVM_DEBUG(dbgs() << "\nPredicable+SpeculatedInsToMove";
3689 InstrToMove->dump());
3690 }
3691 }
3692 } else {
3693 // This is a non-predicable instruction. We still can try to
3694 // speculate it here.
3695 LLVM_DEBUG(dbgs() << "\tNon predicable insn!\t";
3696 InstrToMove->dump());
3697 // TODO: Speculate ins. when pulled from unlikely path.
3698 if (!SpeculateNonPredInsn || !PathInRegion ||
3699 InstrToMove->mayLoad() || InstrToMove->mayStore() ||
3700 InstrToMove->hasUnmodeledSideEffects() ||
3701 !canMIBeSpeculated(&*InstrToMove, CurrentBB, PreviousBB,
3702 PullUpPath)) {
3703 if (NeedCleanup)
3704 CleanupBB->erase(InstrToMove);
3705 return false;
3706 } else {
3707 // Save speculated instruction moved.
3708 SpeculatedIns.insert(
3709 std::make_pair(OriginalInstructionToMove, OriginBB));
3710 LLVM_DEBUG(dbgs() << "\nNonPredicable+SpeculatedInsToMove";
3711 InstrToMove->dump());
3712 }
3713
3714 InstrToMove = insertTempCopy(CurrentBB, TargetPacket, &*InstrToMove,
3715 NeedCleanup);
3716 NeedCleanup = true;
3717 CleanupBB = CurrentBB;
3718 }
3719 } else {
3720 // No branch. Fall through.
3721 LLVM_DEBUG(dbgs() << "\tFall through BB.\n"
3722 << "\tCurrentBB:" << CurrentBB->getNumber()
3723 << "\tPreviousBB:" << PreviousBB->getNumber();
3724 if (PredFBB) dbgs()
3725 << "\tPredFBB:" << PredFBB->getNumber(););
3726 // Even though this is a fall though case, we still can
3727 // have a dual jump situation here with a CALL involved.
3728 // For now simply avoid it.
3729 if (IsDualJumpSecondCandidate(&*InstrToMove)) {
3730 llvm_unreachable("Dual jumps with known?");
3731 LLVM_DEBUG(dbgs() << "\tUnderimplemented dual jump formation.\n");
3732 if (NeedCleanup)
3733 CleanupBB->erase(InstrToMove);
3734 return false;
3735 }
3736
3737 if (!CurrentBB->isSuccessor(PreviousBB)) {
3738 LLVM_DEBUG(dbgs() << "\tNon-successor fall through.\n");
3739 if (NeedCleanup)
3740 CleanupBB->erase(InstrToMove);
3741 return false;
3742 }
3743 SpeculatedIns.insert(
3744 std::make_pair(OriginalInstructionToMove, OriginBB));
3745 LLVM_DEBUG(dbgs() << "\nSpeculatedInsToMove+FallThroughBB";
3746 InstrToMove->dump());
3747 // Create a temp copy.
3748 InstrToMove = insertTempCopy(CurrentBB, TargetPacket, &*InstrToMove,
3749 NeedCleanup);
3750 NeedCleanup = true;
3751 NeedToPredicate = false;
3752 CleanupBB = CurrentBB;
3753 LLVM_DEBUG(dbgs() << "\tUpdated BB:\n"; CurrentBB->dump());
3754 }
3755 }
3756 }
3757 // If we have reached Home, great.
3758 // Original check should have verified that instruction could be added
3759 // to the target packet, so here we do nothing for deps.
3760 if (MIWH == backtrack.front()) {
3761 LLVM_DEBUG(dbgs() << "\tHOME!\n");
3762 break;
3763 }
3764
3765 // Test if we can reorder the two MIs.
3766 // The exception is when we are forming dual jumps - we can pull up
3767 // dependent instruction to the last bundle of an immediate predecesor
3768 // of the current BB if control flow permits it.
3769 // In this special case we also need to update the bundle we are moving
3770 // from.
3771 if (!(MovingDependentOp && (MIWH == &*SourceLocation)) &&
3772 !canReorderMIs(MIWH, &*InstrToMove)) {
3773 if (NeedCleanup)
3774 CleanupBB->erase(InstrToMove);
3775 return false;
3776 }
3777 }
3778 // We have previously tested this instruction, but has not updated the state
3779 // for it. Do it now.
3780 if (QII->isExtended(*InstrToMove) || QII->isConstExtended(*InstrToMove) ||
3781 isJumpOutOfRange(&*InstrToMove)) {
3782 if (!tryAllocateResourcesForConstExt(&*InstrToMove))
3783 llvm_unreachable("Missed dependency test");
3784 }
3785
3786 // Ok. We can safely move this instruction all the way up.
3787 // We also potentially have a slot for it.
3788 // During move original instruction could have changed (becoming predicated).
3789 // Now try to place the final instance of it into the current packet.
3790 LLVM_DEBUG(dbgs() << "\nWant to move ";
3791 if (MovingDependentOp) dbgs() << "dependent op"; dbgs() << ": ";
3792 InstrToMove->dump(); dbgs() << "To BB:\n"; HomeBB->dump();
3793 dbgs() << "From BB:\n"; OriginBB->dump());
3794
3795 // Keep these two statistics separately.
3796 if (!isDualJump)
3797 HexagonNumPullUps++;
3798 else
3799 HexagonNumDualJumps++;
3800
3801 // This means we have not yet inserted the temp copy of InstrToMove
3802 // in the target bundle. We are probably inside the same BB.
3803 if (!NeedCleanup) {
3804 InstrToMove =
3805 insertTempCopy(HomeBB, TargetPacket, &*InstrToMove, NeedCleanup);
3806 NeedCleanup = true;
3807 }
3808
3809 // No problems detected. Add it.
3810 // If we were adding InstrToMove to a single, not yet packetized
3811 // instruction, we need to create bundle header for it before proceeding.
3812 // Be carefull since endPacket also resets the DFA state.
3813 if (!TargetPacket->isBundle()) {
3814 LLVM_DEBUG(dbgs() << "\tForm a new bundle.\n");
3815 finalizeBundle(*HomeBB, TargetPacket.getInstrIterator(),
3816 std::next(InstrToMove));
3817 LLVM_DEBUG(HomeBB->dump());
3818 // Now we need to adjust pointer to the newly created packet header.
3820 MII--;
3821
3822 // Is it also on the way home?
3823 for (unsigned i = 0; i < backtrack.size(); ++i)
3824 if (backtrack[i] == &*TargetPacket)
3825 backtrack[i] = &*MII;
3826
3827 // Is it where our next MI is pointing?
3828 if (NextMI == TargetPacket)
3829 NextMI = MII;
3830 TargetPacket = MII;
3831 }
3832
3833 // Move and Update Liveness info.
3834 MoveAndUpdateLiveness(CurrentRegion, HomeBB, &*InstrToMove, MINeedToNewify,
3835 DepReg, MovingDependentOp, OriginBB,
3836 OriginalInstructionToMove, PredCond, SourceLocation,
3837 TargetPacket, NextMI, backtrack);
3838
3839 LLVM_DEBUG(dbgs() << "\n______Updated______\n"; HomeBB->dump();
3840 OriginBB->dump());
3841
3842 return true;
3843}
3844
3845/// Verify that we respect CFG layout during pull-up.
3846bool HexagonGlobalSchedulerImpl::isBranchWithinRegion(
3847 BasicBlockRegion *CurrentRegion, MachineInstr *MI) {
3848 assert(MI && MI->isBranch() && "Missing call info");
3849
3850 MachineBasicBlock *MBB = MI->getParent();
3851 LLVM_DEBUG(dbgs() << "\t[isBranchWithinRegion] BB(" << MBB->getNumber()
3852 << ") Branch instr:\t";
3853 MI->dump());
3854 // If there is only one successor, it is safe to pull.
3855 if (MBB->succ_size() <= 1)
3856 return true;
3857 // If there are multiple successors (jump table), we should
3858 // not allow pull up over this instruction.
3859 if (MBB->succ_size() > 2)
3860 return false;
3861
3862 MachineBasicBlock *NextRegionBB;
3863 MachineBasicBlock *TBB, *FBB;
3864 MachineInstr *FirstTerm = NULL;
3865 MachineInstr *SecondTerm = NULL;
3866
3867 if (AnalyzeBBBranches(MBB, TBB, FirstTerm, FBB, SecondTerm)) {
3868 LLVM_DEBUG(dbgs() << "\t\tAnalyzeBBBranches failed!\n");
3869 return false;
3870 }
3871
3872 // If there is no jump in this BB, it simply falls through.
3873 if (!FirstTerm) {
3874 LLVM_DEBUG(dbgs() << "\t\tNo FirstTerm\n");
3875 return true;
3876 } else if (QII->isEndLoopN(FirstTerm->getOpcode())) {
3877 // We can easily analyze where endloop would take us
3878 // but here it would be pointless either way since
3879 // the region will not cross it.
3880 LLVM_DEBUG(dbgs() << "\t\tEndloop terminator\n");
3881 return false;
3882 }
3883 // On some occasions we see code like this:
3884 // BB#142: derived from LLVM BB %init, Align 4 (16 bytes)
3885 // Live Ins: %R17 %R18
3886 // Predecessors according to CFG: BB#2
3887 // EH_LABEL <MCSym=.Ltmp35>
3888 // J2_jump <BB#3>, %PC<imp-def>
3889 // Successors according to CFG: BB#3(1048575) BB#138(1)
3890 // It breaks most assumptions about CFG layout, so untill we know
3891 // the source of it, let's have a safeguard.
3892 if (MBB->succ_size() > 1 && !TII->isPredicated(*FirstTerm) &&
3893 !QII->isNewValueJump(*FirstTerm)) {
3894 LLVM_DEBUG(dbgs() << "\t\tBadly formed BB.\n");
3895 return false;
3896 }
3897
3898 LLVM_DEBUG(dbgs() << "\t\tFirstTerm: "; FirstTerm->dump());
3899 LLVM_DEBUG(dbgs() << "\t\tSecondTerm: "; if (SecondTerm) SecondTerm->dump();
3900 else dbgs() << "None\n";);
3901
3902 // All cases where there is only one branch in BB are OK to proceed.
3903 if (!SecondTerm)
3904 return true;
3905
3906 assert(!QII->isEndLoopN(SecondTerm->getOpcode()) && "Found endloop.");
3907
3908 // Find next BB in this region - if there is none, we will likely
3909 // stop pulling in the next check outside of this function.
3910 // This largely is don't care.
3911 NextRegionBB = CurrentRegion->findNextMBB(MBB);
3912 if (!NextRegionBB) {
3913 LLVM_DEBUG(dbgs() << "\t\tNo next BB in the region...\n");
3914 return true;
3915 }
3916 LLVM_DEBUG(dbgs() << "\t\tNextRegionBB(" << NextRegionBB->getNumber()
3917 << ")\n");
3918 assert(TBB && "Corrupt BB layout");
3919 // This means we are trying to pull into a packet _before_ the first
3920 // branch in the MBB.
3921 if (MI == FirstTerm) {
3922 LLVM_DEBUG(dbgs() << "\t\tTBB(" << TBB->getNumber()
3923 << ") NextBB in the region(" << NextRegionBB->getNumber()
3924 << ")\n");
3925 return (TBB == NextRegionBB);
3926 }
3927 assert(FBB && "Corrupt BB layout");
3928 // This means we are trying to pull into the packet _after_ first branch,
3929 // and it is OK if we pull from the second branch target.
3930 // This pull is always speculative.
3931 if ((MI != SecondTerm)) {
3932 LLVM_DEBUG(dbgs() << "\t\tDual terminator not matching SecondTerm.\n");
3933 return false;
3934 }
3935 // Analyze the second branch in the BB.
3936 LLVM_DEBUG(dbgs() << "\t\tFBB(" << FBB->getNumber()
3937 << ") NextBB in the region(" << NextRegionBB->getNumber()
3938 << ")\n");
3939 return (FBB == NextRegionBB);
3940}
3941
3942/// Check if a given instruction is:
3943/// - a jump to a distant target
3944/// - that exceeds its immediate range
3945/// If both conditions are true, it requires constant extension.
3946bool HexagonGlobalSchedulerImpl::isJumpOutOfRange(MachineInstr *UnCond,
3947 MachineInstr *Cond) {
3948 if (!UnCond || !UnCond->isBranch())
3949 return false;
3950
3951 MachineBasicBlock *UnCondBB = UnCond->getParent();
3952 MachineBasicBlock *CondBB = Cond->getParent();
3953 MachineInstr *FirstTerm = &*(CondBB->getFirstInstrTerminator());
3954 // This might be worth an assert.
3955 if (FirstTerm == &*CondBB->instr_end())
3956 return false;
3957
3958 unsigned InstOffset = BlockToInstOffset[UnCondBB];
3959 unsigned Distance = 0;
3960
3961 // To save time, estimate exact position of a branch instruction
3962 // as one at the end of the UnCondBB.
3963 // Number of instructions times typical instruction size.
3964 InstOffset += (QII->nonDbgBBSize(UnCondBB) * HEXAGON_INSTR_SIZE);
3965
3966 MachineBasicBlock *TBB = NULL, *FBB = NULL;
3967 SmallVector<MachineOperand, 4> CondList;
3968
3969 // Find the target of the unconditional branch in UnCondBB, which is returned
3970 // in TBB. Then use the CondBB to extract the FirsTerm. We desire to replace
3971 // the branch target in FirstTerm with the branch location from the UnCondBB,
3972 // provided it is within the distance of the opcode in FirstTerm.
3973 if (QII->analyzeBranch(*UnCondBB, TBB, FBB, CondList, false))
3974 // Could not analyze it. give up.
3975 return false;
3976
3977 if (TBB && (Cond == FirstTerm)) {
3978 Distance =
3979 (unsigned)std::abs((long long)InstOffset - BlockToInstOffset[TBB]) +
3981 return !QII->isJumpWithinBranchRange(*FirstTerm, Distance);
3982 }
3983 return false;
3984}
3985
3986// findBundleAndBranch returns the branch instruction and the
3987// bundle which contains it. Null is returned if not found.
3988MachineInstr *HexagonGlobalSchedulerImpl::findBundleAndBranch(
3989 MachineBasicBlock *BB, MachineBasicBlock::iterator &Bundle) {
3990 // Find the conditional branch out of BB.
3991 if (!BB)
3992 return NULL;
3993 MachineInstr *CondBranch = NULL;
3994 Bundle = BB->end();
3996 MBBEnd = BB->instr_end();
3997 MII != MBBEnd; ++MII) {
3998 MachineInstr *MI = &*MII;
3999 if (MII->isConditionalBranch()) {
4000 CondBranch = MI;
4001 }
4002 }
4003 if (!CondBranch)
4004 return NULL;
4006 if (!MII->isBundled())
4007 return NULL;
4008 // Find bundle header.
4009 for (--MII; MII->isBundled(); --MII)
4010 if (MII->isBundle()) {
4011 Bundle = MII;
4012 break;
4013 }
4014 return CondBranch;
4015}
4016
4017// pullUpPeelBBLoop
4018// A single BB loop with a register copy at the beginning in its
4019// own bundle, benefits from eliminating the extra bundle. We do
4020// this by predicating the register copy in the predecessor BB, and
4021// again in the last bundle of the loop.
4022bool HexagonGlobalSchedulerImpl::pullUpPeelBBLoop(MachineBasicBlock *PredBB,
4023 MachineBasicBlock *LoopBB) {
4024 if (!AllowBBPeelPullUp)
4025 return false;
4026 if (!LoopBB || !PredBB)
4027 return false;
4028
4029 // We consider single BB loops only. Check for it here.
4030 if (LoopBB->isEHPad() || LoopBB->hasAddressTaken())
4031 return false;
4032 if (LoopBB->succ_size() != 2)
4033 return false;
4034 if (LoopBB->pred_size() != 2)
4035 return false;
4036 // Make sure one of the successors and one of the predecssors is to self.
4037 if (!(LoopBB->isSuccessor(LoopBB) && LoopBB->isPredecessor(LoopBB)))
4038 return false;
4039
4040 // Find the none self successor block. We know we only have 2 successors.
4041 MachineBasicBlock *SuccBB = NULL;
4042 for (MachineBasicBlock::succ_iterator SI = LoopBB->succ_begin(),
4043 SE = LoopBB->succ_end();
4044 SI != SE; ++SI)
4045 if (*SI != LoopBB) {
4046 SuccBB = *SI;
4047 break;
4048 }
4049 if (!SuccBB)
4050 return false;
4051
4052 // Find the conditional branch and its bundle inside PredBB.
4053 MachineBasicBlock::iterator PredBundle;
4054 MachineInstr *PredCondBranch = NULL;
4055 PredCondBranch = findBundleAndBranch(PredBB, PredBundle);
4056 if (!PredCondBranch)
4057 return false;
4058 if (PredBundle == PredBB->end())
4059 return false;
4060 LLVM_DEBUG(dbgs() << "PredBB's Branch: ");
4061 LLVM_DEBUG(dbgs() << *PredCondBranch);
4062
4063 // Look for leading reg copy as single bundle and make sure its live in.
4065 // Skip debug instructions.
4066 while (FMI->isDebugInstr())
4067 FMI++;
4068
4069 MachineInstr *RegMI = &*FMI;
4070 if (RegMI->isBundle())
4071 return false;
4072 if (RegMI->getOpcode() != Hexagon::A2_tfr)
4073 return false;
4074 if (!(RegMI->getOperand(0).isReg() && RegMI->getOperand(1).isReg()))
4075 return false;
4076 unsigned InLoopReg = RegMI->getOperand(1).getReg();
4077 if (!LoopBB->isLiveIn(InLoopReg))
4078 return false;
4079
4080 // Create a region to pass to ResourcesAvailableInBundle.
4081 BasicBlockRegion PUR(BasicBlockRegion(TII, QRI, PredBB));
4082 PUR.addBBtoRegion(LoopBB);
4083 PUR.addBBtoRegion(SuccBB);
4084
4085 // Make sure we have space in PredBB's last bundle.
4086 if (!ResourcesAvailableInBundle(&PUR, PredBundle))
4087 return false;
4089 CurrentState.HomeBundle);
4090
4091 // Find condition to use for predicating the reg copy into PredBB.
4092 MachineBasicBlock *TBB = NULL, *FBB = NULL;
4093 SmallVector<MachineOperand, 4> Cond;
4094 if (QII->analyzeBranch(*PredBB, TBB, FBB, Cond, false))
4095 return false;
4096 if (Cond.empty())
4097 return false;
4098
4099 // Find condition to use for predicating the reg copy at the end of LoopBB.
4100 MachineBasicBlock *LTBB = NULL, *LFBB = NULL;
4101 SmallVector<MachineOperand, 4> LCond;
4102 if (QII->analyzeBranch(*LoopBB, LTBB, LFBB, LCond, false))
4103 return false;
4104 if (LCond.empty())
4105 return false;
4106
4107 // Move predicated reg copy to previous BB's last bundle.
4108 if (!TII->isPredicable(*RegMI))
4109 return false;
4110 MachineInstr *InstrToMove =
4111 &*insertTempCopy(PredBB, PredBundle, RegMI, false);
4112 if (!canAddMIToThisPacket(InstrToMove, PredBundlePkt)) {
4113 PredBB->erase_instr(InstrToMove);
4114 return false;
4115 }
4116
4117 if (!TII->PredicateInstruction(*InstrToMove, Cond)) {
4118 // Failed to predicate the copy reg.
4119 PredBB->erase_instr(InstrToMove);
4120 return false;
4121 }
4122
4123 // Can we newify this instruction?
4124 unsigned DepReg = 0;
4125 if (NeedToNewify(InstrToMove->getIterator(), &DepReg, &*PredBundle) &&
4126 !isNewifiable(InstrToMove->getIterator(), DepReg, &*PredBundle)) {
4127 PredBB->erase_instr(InstrToMove);
4128 return false;
4129 }
4130 // Newify it, and then undo it if we determine we are using a .old.
4131 int NewOpcode = QII->getDotNewPredOp(*InstrToMove, MBPI);
4132 // Undo newify if we have a non .new predicated jump we are matching.
4133 if (!QII->isDotNewInst(*PredCondBranch))
4134 NewOpcode = QII->getDotOldOp(*InstrToMove);
4135 NewOpcode = QII->getInvertedPredicatedOpcode(NewOpcode);
4136 // Properly set the opcode on the new hoisted reg copy instruction.
4137 InstrToMove->setDesc(QII->get(NewOpcode));
4138 if (!incrementalAddToPacket(*InstrToMove)) {
4139 PredBB->erase_instr(InstrToMove);
4140 return false;
4141 }
4142
4143 // Find the conditional branch and its bundle for LoopBB.
4144 MachineBasicBlock::iterator LoopBundle;
4145 MachineInstr *LoopCondBranch = NULL;
4146 LoopCondBranch = findBundleAndBranch(LoopBB, LoopBundle);
4147 if (!LoopCondBranch)
4148 return false;
4149 if (LoopBundle == LoopBB->end())
4150 return false;
4151 LLVM_DEBUG(dbgs() << "LoopBB's Branch: ");
4152 LLVM_DEBUG(dbgs() << *LoopCondBranch);
4153
4154 // Make sure we have space in LoopBB's last bundle.
4155 if (!ResourcesAvailableInBundle(&PUR, LoopBundle))
4156 return false;
4158 CurrentState.HomeBundle);
4159
4160 // Move predicated reg copy to last bundle of LoopBB.
4161 MachineInstr *InstrToSink =
4162 &*insertTempCopy(LoopBB, LoopBundle, RegMI, false);
4163 if (!canAddMIToThisPacket(InstrToSink, LoopBundlePkt)) {
4164 // Get rid of previous instruction as well.
4165 PredBB->erase_instr(InstrToMove);
4166 LoopBB->erase_instr(InstrToSink);
4167 return false;
4168 }
4169
4170 if (!TII->PredicateInstruction(*InstrToSink, LCond)) {
4171 // Get rid of previous instruction as well.
4172 PredBB->erase_instr(InstrToMove);
4173 LoopBB->erase_instr(InstrToSink);
4174 return false;
4175 }
4176 // Can we newify this instruction?
4177 if (NeedToNewify(InstrToSink->getIterator(), &DepReg, &*LoopBundle) &&
4178 !isNewifiable(InstrToSink->getIterator(), DepReg, &*LoopBundle)) {
4179 // Get rid of previous instruction as well.
4180 PredBB->erase_instr(InstrToMove);
4181 PredBB->erase_instr(InstrToSink);
4182 return false;
4183 }
4184 NewOpcode = QII->getDotNewPredOp(*InstrToSink, MBPI);
4185 // Undo newify if we have a non .new predicated jump we are matching.
4186 if (!QII->isDotNewInst(*LoopCondBranch))
4187 NewOpcode = QII->getDotOldOp(*InstrToSink);
4188 InstrToSink->setDesc(QII->get(NewOpcode));
4189 if (!incrementalAddToPacket(*InstrToSink)) {
4190 // Get rid of previous instruction as well.
4191 PredBB->erase_instr(InstrToMove);
4192 LoopBB->erase_instr(InstrToSink);
4193 return false;
4194 }
4195
4196 // Remove old instruction.
4197 LoopBB->erase_instr(RegMI);
4198 // Set loop alignment to 32.
4199 LoopBB->setAlignment(llvm::Align(32));
4200
4201 LLVM_DEBUG(dbgs() << "Peeled Single BBLoop copy\n");
4202 LLVM_DEBUG(dbgs() << *InstrToMove);
4203 LLVM_DEBUG(dbgs() << *InstrToSink);
4204 LLVM_DEBUG(dbgs() << *PredBB);
4205 LLVM_DEBUG(dbgs() << *LoopBB);
4206 LLVM_DEBUG(dbgs() << *SuccBB);
4207 LLVM_DEBUG(dbgs() << "--- BBLoop ---\n\n");
4208 return true;
4209}
4210
4211bool HexagonGlobalSchedulerImpl::performPullUpCFG(MachineFunction &Fn) {
4212 const Function &F = Fn.getFunction();
4213 // Check for single-block functions and skip them.
4214 if (std::next(F.begin()) == F.end())
4215 return false;
4216 bool Changed = false;
4217 LLVM_DEBUG(dbgs() << "****** PullUpCFG **************\n");
4218
4219 // Loop over all basic blocks, asking if 3 consecutive blocks are
4220 // the jump opportunity.
4221 MachineBasicBlock *PrevBlock = NULL;
4222 MachineBasicBlock *JumpBlock = NULL;
4223 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end(); MBB != MBBe;
4224 ++MBB) {
4225 MachineBasicBlock *FallBlock = &*MBB;
4226 if (PrevBlock && JumpBlock) {
4227 Changed |= pullUpPeelBBLoop(PrevBlock, JumpBlock);
4228 }
4229 PrevBlock = JumpBlock;
4230 JumpBlock = FallBlock;
4231 }
4232 return Changed;
4233}
4234
4235void HexagonGlobalSchedulerImpl::GenUseDefChain(MachineFunction &Fn) {
4236 std::vector<unsigned> Defs;
4237 std::vector<unsigned> Uses;
4238 for (MachineFunction::iterator MBBIter = Fn.begin(); MBBIter != Fn.end();
4239 ++MBBIter) {
4240 for (MachineBasicBlock::instr_iterator MIter = MBBIter->instr_begin();
4241 MIter != MBBIter->instr_end(); ++MIter) {
4242 if (MIter->isBundle() || MIter->isDebugInstr())
4243 continue;
4244 LLVM_DEBUG(dbgs() << "\n\nInserted Ins:"; MIter->dump());
4245 MIUseDefSet(&*MIter, Defs, Uses);
4246 LLVM_DEBUG(dbgs() << "\n\tDefs:";
4247 for (unsigned i = 0; i < Defs.size(); ++i) dbgs()
4248 << printReg(Defs[i], QRI) << ",");
4249 LLVM_DEBUG(dbgs() << "\n\tUses:";
4250 for (unsigned i = 0; i < Uses.size(); ++i) dbgs()
4251 << printReg(Uses[i], QRI) << ",");
4252 MIDefSet[&*MIter] = Defs;
4253 MIUseSet[&*MIter] = Uses;
4254 }
4255 }
4256}
4257
4258// optimizeBranching -
4259// 1. A conditional-jump transfers control to a BB with
4260// jump as the only instruction.
4261// if(p0) jump t1
4262// // ...
4263// t1: jump t2
4264// 2. When a BB with a single conditional jump, jumps to succ-of-succ and
4265// falls-through BB with only jump instruction.
4266// { if(p0) jump t1 }
4267// { jump t2 }
4268// t1: { ... }
4269MachineBasicBlock *HexagonGlobalSchedulerImpl::optimizeBranches(
4270 MachineBasicBlock *MBB, MachineBasicBlock *TBB, MachineInstr *FirstTerm,
4271 MachineBasicBlock *FBB) {
4272 LLVM_DEBUG(dbgs() << "\n\t\t[optimizeBranching]\n");
4273 if ((TBB == MBB) || (FBB == MBB))
4274 LLVM_DEBUG(dbgs() << "Cannot deal with loops in BB#" << MBB->getNumber(););
4275
4276 // LLVM_DEBUG(dbgs() << "\n\t\tTBBMIb:"; MII->dump(););
4277 // { if(p) jump t1; }
4278 // t1: { jump t2; }
4279 // --> { if(p) jump t2
4280 // remove t1: { jump t2; }, if it's address is not taken/not a landing pad.
4281 if (QII->nonDbgBBSize(TBB) == 1) {
4282 MachineInstr *TBBMIb = &*TBB->getFirstNonDebugInstr();
4283 if (TBBMIb->getOpcode() == Hexagon::J2_jump &&
4284 TBBMIb->getOperand(0).isMBB()) {
4285 MachineBasicBlock *NewTarget = TBBMIb->getOperand(0).getMBB();
4286 if (TBB == NewTarget) // Infinite loop.
4287 return NULL;
4288
4289 LLVM_DEBUG(dbgs() << "\nSuboptimal branching in TBB");
4290 // Check if the jump in the last instruction is within range.
4291 int64_t InstOffset =
4292 BlockToInstOffset.find(MBB)->second + QII->nonDbgBBSize(MBB) * 4;
4293 unsigned Distance = (unsigned)std::abs(
4294 InstOffset - BlockToInstOffset.find(NewTarget)->second);
4295 if (!QII->isJumpWithinBranchRange(*FirstTerm, Distance)) {
4296 LLVM_DEBUG(dbgs() << "\nUnconditional jump target:" << Distance
4297 << " out of range.");
4298 return NULL;
4299 }
4300 // We need to make sure that the TBB is _not_ also a target for another
4301 // branch. This is suboptimal since theoretically we can update both
4302 // branches.
4303 if (!TBB->hasAddressTaken() && !TBB->isEHPad() && TBB->pred_size() == 1) {
4304 updatePredecessors(*TBB, NewTarget);
4305 // TBB has only one successor since only one J2_jump instr.
4306 TBB->removeSuccessor(TBB->succ_begin());
4307 TBBMIb->removeFromParent();
4308 if (!TBB->empty()) {
4309 // There are only debug instructions in TBB now. Move them to
4310 // the beginning of NewTarget.
4311 NewTarget->splice(NewTarget->getFirstNonPHI(), TBB, TBB->begin(),
4312 TBB->end());
4313 }
4314 return TBB;
4315 } else {
4316 MBB->ReplaceUsesOfBlockWith(TBB, NewTarget);
4317 return NULL;
4318 }
4319 }
4320 }
4321 // { if(p) jump t1; } may contain more instructions
4322 // { jump t2; } --only one instruction
4323 // t1: {...}
4324 // TBB is layout successor of FBB, then we can change the branch target
4325 // for conditional jump and invert the predicate to remove jump t2.
4326 // { if(!p) jump t2; }
4327 // t1: {...}
4328 if (QII->nonDbgBBSize(FBB) == 1) {
4329 MachineInstr *FBBMIb = &*FBB->getFirstNonDebugInstr();
4330 if (FBBMIb->getOpcode() == Hexagon::J2_jump &&
4331 FBBMIb->getOperand(0).isMBB()) {
4332 MachineBasicBlock *NewTarget = FBBMIb->getOperand(0).getMBB();
4333 if (FBB->hasAddressTaken() || FBB->isEHPad() ||
4334 !FBB->isLayoutSuccessor(TBB) || (FBB == NewTarget /*Infinite loop*/))
4335 return NULL;
4336
4337 LLVM_DEBUG(dbgs() << "\nSuboptimal branching in FBB");
4338 // Check if the jump in the last instruction is within range.
4339 int64_t InstOffset =
4340 BlockToInstOffset.find(MBB)->second + QII->nonDbgBBSize(MBB) * 4;
4341 unsigned Distance = (unsigned)std::abs(
4342 InstOffset - BlockToInstOffset.find(NewTarget)->second);
4343 if (!QII->isJumpWithinBranchRange(*FirstTerm, Distance)) {
4344 LLVM_DEBUG(dbgs() << "\nUnconditional jump target:" << Distance
4345 << " out of range.");
4346 return NULL;
4347 }
4348 if (!QII->invertAndChangeJumpTarget(*FirstTerm, NewTarget))
4349 return NULL;
4350 LLVM_DEBUG(dbgs() << "\nNew instruction:"; FirstTerm->dump(););
4351 updatePredecessors(*FBB, NewTarget);
4352 // Only one successor remains for FBB
4353 FBB->removeSuccessor(FBB->succ_begin());
4354 FBBMIb->removeFromParent();
4355 return FBB;
4356 }
4357 }
4358 return NULL;
4359}
4360
4361// performExposedOptimizations -
4362// look for optimization opportunities after pullup.
4363// e.g. jump to adjacent targets
4364bool HexagonGlobalSchedulerImpl::performExposedOptimizations(
4365 MachineFunction &Fn) {
4366 // Check for single-block functions and skip them.
4367 if (std::next(Fn.getFunction().begin()) == Fn.getFunction().end())
4368 return true;
4369 LLVM_DEBUG(dbgs() << "\n\t\t[performExposedOptimizations]\n");
4370 // Erasing the empty basic blocks formed during pullup.
4371 std::vector<MachineBasicBlock *>::iterator ebb = EmptyBBs.begin();
4372 while (ebb != EmptyBBs.end()) {
4373 assert(IsEmptyBlock(*ebb) && "Pullup inserted packets into an empty BB");
4374 LLVM_DEBUG(dbgs() << "Removing BB(" << (*ebb)->getNumber()
4375 << ") from parent.\n");
4376 (*ebb)->eraseFromParent();
4377 ++ebb;
4378 }
4379 MachineBasicBlock *TBB = NULL, *FBB = NULL;
4380 MachineInstr *FirstTerm = NULL, *SecondTerm = NULL;
4381
4382 SmallVector<MachineBasicBlock *, 4> Erase;
4383
4384 for (MachineBasicBlock &MBB : Fn) {
4385 if (MBB.succ_size() > 2 ||
4386 AnalyzeBBBranches(&MBB, TBB, FirstTerm, FBB, SecondTerm)) {
4387 LLVM_DEBUG(dbgs() << "\nAnalyzeBBBranches failed in BB#"
4388 << MBB.getNumber() << "\n";);
4389 continue;
4390 }
4391 if (FirstTerm && QII->isCompoundBranchInstr(*FirstTerm))
4392 continue;
4393 if (TBB && FirstTerm &&
4394 removeRedundantBranches(&MBB, TBB, FirstTerm, FBB, SecondTerm)) {
4395 LLVM_DEBUG(dbgs() << "\nRemoved redundant branches in BB#"
4396 << MBB.getNumber(););
4397 continue;
4398 }
4399 if (FirstTerm && SecondTerm &&
4400 optimizeDualJumps(&MBB, TBB, FirstTerm, FBB, SecondTerm)) {
4401 LLVM_DEBUG(dbgs() << "\nRemoved dual jumps in in BB#"
4402 << MBB.getNumber(););
4403 continue;
4404 }
4405 if (TBB && FBB && FirstTerm && !SecondTerm) {
4406 MachineBasicBlock *MBBToErase =
4407 optimizeBranches(&MBB, TBB, FirstTerm, FBB);
4408 if (MBBToErase) {
4409 assert(IsEmptyBlock(MBBToErase) && "Erasing non-empty BB");
4410 Erase.push_back(MBBToErase);
4411 LLVM_DEBUG(dbgs() << "\nOptimized jump from BB#" << MBB.getNumber());
4412 }
4413 }
4414 }
4415 for (MachineBasicBlock *MBB : Erase)
4417
4418 return false;
4419}
4420
4421// 1. Remove jump to the layout successor.
4422// 2. Remove multiple (dual) jump to the same target.
4423bool HexagonGlobalSchedulerImpl::removeRedundantBranches(
4424 MachineBasicBlock *MBB, MachineBasicBlock *TBB, MachineInstr *FirstTerm,
4425 MachineBasicBlock *FBB, MachineInstr *SecondTerm) {
4426 bool Analyzed = false;
4427 LLVM_DEBUG(dbgs() << "\n\t\t[removeRedundantBranches]\n");
4428 MachineInstr *Head = NULL, *ToErase = NULL;
4429 if (!FBB && (FirstTerm->getOpcode() == Hexagon::J2_jump) &&
4431 // Jmp layout_succ_basic_block <-- Remove
4432 LLVM_DEBUG(
4433 dbgs() << "\nRemoving Uncond. jump to the layout successor in BB#"
4434 << MBB->getNumber());
4435 ToErase = FirstTerm;
4436 } else if (SecondTerm && (TBB == FBB) &&
4437 (SecondTerm->getOpcode() == Hexagon::J2_jump)) {
4438 // If both branching instructions in same packet or are consecutive.
4439 // Jmp_c t1 <-- Remove
4440 // Jmp t1
4441 // @Note: If they are in different packets or if they are separated
4442 // by packet(s), this opt. cannot be done.
4443 MachineBasicBlock::instr_iterator FirstTermIter = FirstTerm->getIterator();
4444 MachineBasicBlock::instr_iterator SecondTermIter =
4445 SecondTerm->getIterator();
4446 if (++FirstTermIter == SecondTermIter) {
4447 LLVM_DEBUG(dbgs() << "\nRemoving multiple branching to same target in BB#"
4448 << MBB->getNumber());
4449 // TODO: This might make the `p' register assignment instruction dead.
4450 // and can be removed.
4451 ToErase = FirstTerm;
4452 }
4453 } else if (SecondTerm && (SecondTerm->getOpcode() == Hexagon::J2_jump) &&
4454 FBB && MBB->isLayoutSuccessor(FBB)) {
4455 // Jmp_c t1
4456 // Jmp layout_succ_basic_block <-- Remove
4457 LLVM_DEBUG(dbgs() << "\nRemoving fall through branch in BB#"
4458 << MBB->getNumber());
4459 ToErase = SecondTerm;
4460 } else if (SecondTerm && QII->PredOpcodeHasJMP_c(SecondTerm->getOpcode()) &&
4462 // Jmp_c t1
4463 // Jmp_c layout_succ_basic_block <-- Remove
4464 // In this case AnalyzeBBBranches might assign FBB to some other BB.
4465 // So using the jump target of SecondTerm to check.
4466 LLVM_DEBUG(dbgs() << "\nRemoving Cond. jump to the layout successor in BB#"
4467 << MBB->getNumber());
4468 ToErase = SecondTerm;
4469 }
4470 // Remove the instruction from the BB
4471 if (ToErase) {
4472 if (ToErase->isBundled()) {
4473 Head = &*getBundleStart(ToErase->getIterator());
4474 ToErase->eraseFromBundle();
4475 UpdateBundle(Head);
4476 } else
4477 ToErase->eraseFromParent();
4478 Analyzed = true;
4479 }
4480 return Analyzed;
4481}
4482
4483// ----- convert
4484// p = <expr>
4485// if(p) jump layout_succ_basic_block
4486// jump t
4487// ----- to
4488// p = <expr>
4489// if(!p) jump t
4490// for now only looking at the dual jump
4491bool HexagonGlobalSchedulerImpl::optimizeDualJumps(MachineBasicBlock *MBB,
4492 MachineBasicBlock *TBB,
4493 MachineInstr *FirstTerm,
4494 MachineBasicBlock *FBB,
4495 MachineInstr *SecondTerm) {
4496 LLVM_DEBUG(dbgs() << "\n******* optimizeDualJumps *******");
4497
4498 bool Analyzed = false;
4499
4500 if (QII->PredOpcodeHasJMP_c(FirstTerm->getOpcode()) &&
4501 (SecondTerm->getOpcode() == Hexagon::J2_jump)) {
4502
4503 if (TBB == FBB) {
4504 LLVM_DEBUG(dbgs() << "\nBoth successors are the same.");
4505 return Analyzed;
4506 }
4507
4508 // Do not optimize for dual jumps if this MBB
4509 // contains a speculatively pulled-up instruction.
4510 // A speculated instruction is more likely to be at the end of MBB.
4512 while (SII != MBB->instr_rend()) {
4513 MachineInstr *SI = &*SII;
4514 std::map<MachineInstr *, MachineBasicBlock *>::iterator MIMoved;
4515 MIMoved = SpeculatedIns.find(SI);
4516 if ((MIMoved != SpeculatedIns.end()) &&
4517 (MIMoved->second != SI->getParent())) {
4518 return Analyzed;
4519 }
4520 ++SII;
4521 }
4522
4523 LLVM_DEBUG(dbgs() << "\nCandidate for jump optimization in BB("
4524 << MBB->getNumber() << ").\n";);
4525
4526 // Predicated jump to layout successor followed by an unconditional jump.
4527 if (MBB->isLayoutSuccessor(TBB)) {
4528
4529 // Check if the jump in the last instruction is within range.
4530 int64_t InstOffset =
4531 BlockToInstOffset.find(&*MBB)->second + QII->nonDbgBBSize(MBB) * 4;
4532 unsigned Distance =
4533 (unsigned)std::abs(InstOffset - BlockToInstOffset.find(FBB)->second) +
4535 if (!QII->isJumpWithinBranchRange(*FirstTerm, Distance)) {
4536 LLVM_DEBUG(dbgs() << "\nUnconditional jump target:" << Distance
4537 << " out of range.");
4538 return Analyzed;
4539 }
4540
4541 // modify the second last -predicated- instruction (sense and target)
4542 LLVM_DEBUG(dbgs() << "\nFirst Instr:" << *FirstTerm;);
4543 LLVM_DEBUG(dbgs() << "\nSecond Instr:" << *SecondTerm;);
4544 LLVM_DEBUG(dbgs() << "\nOld Succ BB(" << TBB->getNumber() << ").";);
4545
4546 QII->invertAndChangeJumpTarget(*FirstTerm, FBB);
4547
4548 LLVM_DEBUG(dbgs() << "\nNew First Instruction:" << *FirstTerm;);
4549
4550 // unbundle if there is only one instruction left
4551 MachineInstr *SecondHead, *FirstHead;
4552 FirstHead = FirstTerm->isBundled()
4553 ? &*getBundleStart(FirstTerm->getIterator())
4554 : nullptr;
4555 SecondHead = SecondTerm->isBundled()
4556 ? &*getBundleStart(SecondTerm->getIterator())
4557 : nullptr;
4558
4559 // 1. Both unbundled, 2. FirstTerm inside bundle, second outside.
4560 if (!SecondHead)
4561 SecondTerm->eraseFromParent();
4562 else if (!FirstHead) {
4563 // 3. FirstHead outside, SecondHead inside.
4564 SecondTerm->eraseFromBundle();
4565 UpdateBundle(SecondHead);
4566 } else if (FirstHead == SecondHead) {
4567 // 4. Both are in the same bundle
4568 assert((FirstHead && SecondHead) && "Unbundled Instruction");
4569 SecondTerm->eraseFromBundle();
4570 if (SecondHead->getBundleSize() < 2)
4571 UpdateBundle(SecondHead);
4572 } else {
4573 // 5. Both are in different bundles
4574 SecondTerm->eraseFromBundle();
4575 UpdateBundle(SecondHead);
4576 }
4577 Analyzed = true;
4578 }
4579 }
4580 return Analyzed;
4581}
4582
4583/// Are there any resources left in this bundle?
4584bool HexagonGlobalSchedulerImpl::ResourcesAvailableInBundle(
4585 BasicBlockRegion *CurrentRegion,
4586 MachineBasicBlock::iterator &TargetPacket) {
4588
4589 // If this is a single instruction, form new packet around it.
4590 if (!TargetPacket->isBundle()) {
4591 if (ignoreInstruction(&*MII) || isSoloInstruction(*MII))
4592 return false;
4593
4594 // Before we begin, we need to make sure that we do not
4595 // look at an unconditional jump outside the current region.
4596 if (MII->isBranch() && !isBranchWithinRegion(CurrentRegion, &*MII))
4597 return false;
4598
4599 // Build up state for this new packet.
4600 // Note, we cannot create a bundle header for it,
4601 // so this "bundle" only exist in DFA state, and not in code.
4602 initPacketizerState();
4603 ResourceTracker->clearResources();
4604 CurrentState.addHomeLocation(MII);
4605 return incrementalAddToPacket(*MII);
4606 }
4607
4608 MachineBasicBlock::instr_iterator End = MII->getParent()->instr_end();
4609
4610 // Build up state for this packet.
4611 initPacketizerState();
4612 ResourceTracker->clearResources();
4613 CurrentState.addHomeLocation(MII);
4614
4615 for (++MII; MII != End && MII->isInsideBundle(); ++MII) {
4616 if (MII->getOpcode() == TargetOpcode::DBG_VALUE ||
4617 MII->getOpcode() == TargetOpcode::IMPLICIT_DEF ||
4618 MII->getOpcode() == TargetOpcode::CFI_INSTRUCTION || MII->isEHLabel())
4619 continue;
4620
4621 // Before we begin, we need to make sure that we do not
4622 // look at an unconditional jump outside the current region.
4623 // TODO: See if we can profit from handling this kind of cases:
4624 // B#15: derived from LLVM BB %if.then22
4625 // Predecessors according to CFG: BB#13
4626 // BUNDLE %PC<imp-def>, %P2<imp-use,kill>
4627 // * J2_jumpf %P2<kill,internal>, <BB#17>, %PC<imp-def>; flags:
4628 // * J2_jump <BB#18>, %PC<imp-def>; flags:
4629 // Successors according to CFG: BB#18(62) BB#17(62)
4630 // Curently we do not allow them.
4631 if (MII->isBranch() && !isBranchWithinRegion(CurrentRegion, &*MII))
4632 return false;
4633
4634 if (!incrementalAddToPacket(*MII))
4635 return false;
4636 }
4637 return ResourceTracker->canReserveResources(*Nop);
4638}
4639
4640/// Symmetrical. See if these two instructions are fit for compound pair.
4641bool HexagonGlobalSchedulerImpl::isCompoundPair(MachineInstr *MIa,
4642 MachineInstr *MIb) {
4644 MIbG = QII->getCompoundCandidateGroup(*MIb);
4645 // We have two candidates - check that this is the same register
4646 // we are talking about.
4647 unsigned Opcb = MIb->getOpcode();
4648 if (MIaG == HexagonII::HCG_C && MIbG == HexagonII::HCG_A &&
4649 (Opcb == Hexagon::A2_tfr || Opcb == Hexagon::A2_tfrsi))
4650 return true;
4651 unsigned Opca = MIa->getOpcode();
4652 if (MIbG == HexagonII::HCG_C && MIaG == HexagonII::HCG_A &&
4653 (Opca == Hexagon::A2_tfr || Opca == Hexagon::A2_tfrsi))
4654 return true;
4655 return (((MIaG == HexagonII::HCG_A && MIbG == HexagonII::HCG_B) ||
4656 (MIbG == HexagonII::HCG_A && MIaG == HexagonII::HCG_B)) &&
4657 (MIa->getOperand(0).getReg() == MIb->getOperand(0).getReg()));
4658}
4659
4660// This is a weird situation when BB conditionally branches + falls through
4661// to layout successor. \ref bug17792
4662inline bool HexagonGlobalSchedulerImpl::multipleBranchesFromToBB(
4663 MachineBasicBlock *BB) const {
4664 if (BB->succ_size() != 1)
4665 return false;
4666 SmallVector<MachineInstr *, 2> Jumpers = QII->getBranchingInstrs(*BB);
4667 return ((Jumpers.size() == 1) && !Jumpers[0]->isUnconditionalBranch());
4668}
4669
4670/// Gather a worklist of MaxCandidates pull-up candidates.
4671/// Compute relative cost.
4672bool HexagonGlobalSchedulerImpl::findPullUpCandidates(
4673 MachineBasicBlock::iterator &WorkPoint,
4675 std::vector<MachineInstr *> &backtrack, unsigned MaxCandidates = 1) {
4676
4677 const HexagonInstrInfo *QII = (const HexagonInstrInfo *)TII;
4678 MachineBasicBlock *FromThisBB = FromHere->getParent();
4679 bool MovingDependentOp = false;
4680 signed CostBenefit = 0;
4681
4682 // Do not collect more than that many candidates.
4683 if (CurrentState.haveCandidates() >= MaxCandidates)
4684 return false;
4685
4686 LLVM_DEBUG(dbgs() << "\n\tTry from BB(" << FromThisBB->getNumber() << "):\n";
4687 DumpPacket(FromHere.getInstrIterator()));
4688
4689 if (FromHere->isBundle()) {
4691 for (++MII; MII != FromThisBB->instr_end() && MII->isInsideBundle();
4692 ++MII) {
4693 if (MII->isDebugInstr())
4694 continue;
4695 LLVM_DEBUG(dbgs() << "\tCandidate from BB("
4696 << MII->getParent()->getNumber() << "): ";
4697 MII->dump());
4698
4699 // See if this instruction could be moved.
4700 if (!canThisMIBeMoved(&*MII, WorkPoint, MovingDependentOp, CostBenefit))
4701 continue;
4702
4703 MachineBasicBlock::instr_iterator InstrToMove = MII;
4704 if (canAddMIToThisPacket(&*InstrToMove, CurrentState.HomeBundle)) {
4705 CostBenefit -= (backtrack.size() * 4);
4706 // Prefer instructions in empty packets.
4707 CostBenefit += (PacketSize - nonDbgBundleSize(FromHere)) * 2;
4708 // Prefer Compares.
4709 if (MII->isCompare())
4710 CostBenefit += 10;
4711 // Check duplex conditions;
4712 for (unsigned i = 0; i < CurrentState.HomeBundle.size(); i++) {
4713 if (QII->isDuplexPair(*CurrentState.HomeBundle[i], *MII)) {
4714 LLVM_DEBUG(dbgs() << "\tGot real Duplex (bundle).\n");
4715 CostBenefit += 20;
4716 }
4717 if (isCompoundPair(CurrentState.HomeBundle[i], &*MII)) {
4718 LLVM_DEBUG(dbgs() << "\tGot compound (bundle).\n");
4719 CostBenefit += 40;
4720 }
4721 }
4722 // Create a record for this location.
4723 CurrentState.addPullUpCandidate(InstrToMove, WorkPoint, backtrack,
4724 MovingDependentOp, CostBenefit);
4725 } else
4726 LLVM_DEBUG(dbgs() << "\tNo resources in the target packet.\n");
4727 }
4728 }
4729 // This is a standalone instruction.
4730 // First see if this MI can even be moved. Cost model for a single instruction
4731 // should be rather different from moving something out of a bundle.
4732 else if (canThisMIBeMoved(&*FromHere, WorkPoint, MovingDependentOp,
4733 CostBenefit)) {
4734 MachineBasicBlock::instr_iterator InstrToMove = FromHere.getInstrIterator();
4735 if (canAddMIToThisPacket(&*InstrToMove, CurrentState.HomeBundle)) {
4736 CostBenefit -= (backtrack.size() * 4);
4737 // Prefer Compares.
4738 if (InstrToMove->isCompare())
4739 CostBenefit += 10;
4740 // It is better to pull a single instruction in to a bundle - save
4741 // a cycle immediately.
4742 CostBenefit += 10;
4743 // Search for duplex match.
4744 for (unsigned i = 0; i < CurrentState.HomeBundle.size(); i++) {
4745 if (QII->isDuplexPair(*CurrentState.HomeBundle[i], *InstrToMove)) {
4746 LLVM_DEBUG(dbgs() << "\tGot real Duplex (single).\n");
4747 CostBenefit += 30;
4748 }
4749 if (isCompoundPair(CurrentState.HomeBundle[i], &*InstrToMove)) {
4750 LLVM_DEBUG(dbgs() << "\tGot compound (single).\n");
4751 CostBenefit += 50;
4752 }
4753 }
4754 // Create a record for this location.
4755 CurrentState.addPullUpCandidate(InstrToMove, WorkPoint, backtrack,
4756 MovingDependentOp, CostBenefit);
4757 } else
4758 LLVM_DEBUG(dbgs() << "\tNo resources for single in the target packet.\n");
4759 }
4760 return true;
4761}
4762
4763/// Try to move a candidate MI.
4764/// The move can destroy all iterator system, so we have to drag them
4765/// around to keep them up to date.
4766bool HexagonGlobalSchedulerImpl::tryMultipleInstructions(
4767 MachineBasicBlock::iterator &RetVal, /* output parameter */
4768 std::vector<BasicBlockRegion *>::iterator &CurrentRegion,
4770 MachineBasicBlock::iterator &ToThisBBEnd,
4771 MachineBasicBlock::iterator &FromThisBBEnd, bool PathInRegion) {
4772
4775 bool MovingDependentOp = false;
4776 std::vector<MachineInstr *> backtrack;
4777
4778 LLVM_DEBUG(dbgs() << "\n\tTry Multiple candidates: \n");
4779
4780 std::sort(CurrentState.PullUpCandidates.begin(),
4781 CurrentState.PullUpCandidates.end(), PullUpCandidateSorter());
4782 LLVM_DEBUG(CurrentState.dump());
4783 // Iterate through candidates in sorted order.
4784 for (SmallVector<PullUpCandidate *, 4>::iterator
4785 I = CurrentState.PullUpCandidates.begin(),
4786 E = CurrentState.PullUpCandidates.end();
4787 I != E; ++I) {
4788 (*I)->populate(MII, WorkPoint, backtrack, MovingDependentOp);
4789
4790 MachineBasicBlock *FromThisBB = MII->getParent();
4791 MachineBasicBlock *ToThisBB = WorkPoint->getParent();
4792
4793 LLVM_DEBUG(dbgs() << "\n\tCandidate: "; MII->dump());
4794 LLVM_DEBUG(dbgs() << "\tDependent(" << MovingDependentOp << ") FromBB("
4795 << FromThisBB->getNumber() << ") ToBB("
4796 << ToThisBB->getNumber() << ") to this packet:\n";
4797 DumpPacket(WorkPoint.getInstrIterator()));
4798
4799 MachineBasicBlock::instr_iterator FromHereII = MII;
4800 if (MII->isInsideBundle()) {
4801 while (!FromHereII->isBundle())
4802 --FromHereII;
4803 LLVM_DEBUG(dbgs() << "\tFrom here:\n"; DumpPacket(FromHereII));
4804
4805 MachineBasicBlock::iterator FromHere(FromHereII);
4806 // We have instruction that could be moved from its current position.
4807 if (MoveMItoBundle(*CurrentRegion, MII, NextMI, WorkPoint, FromHere,
4808 backtrack, MovingDependentOp, PathInRegion)) {
4809 // If BB from which we pull is now empty, move on.
4810 if (IsEmptyBlock(FromThisBB)) {
4811 LLVM_DEBUG(dbgs() << "\n\tExhosted BB (bundle).\n");
4812 return false;
4813 }
4814 FromThisBBEnd = FromThisBB->end();
4815 ToThisBBEnd = ToThisBB->end();
4816
4817 LLVM_DEBUG(dbgs() << "\n\tAfter updates(bundle to bundle):\n");
4818 LLVM_DEBUG(dbgs() << "\t\tWorkPoint: ";
4819 DumpPacket(WorkPoint.getInstrIterator()));
4820
4821 // We should not increment current position,
4822 // but rather try one more time to pull from the same bundle.
4823 RetVal = WorkPoint;
4824 return true;
4825 } else
4826 LLVM_DEBUG(dbgs() << "\tCould not move packetized instr.\n");
4827 } else {
4828 MachineBasicBlock::iterator FromHere(FromHereII);
4829 if (MoveMItoBundle(*CurrentRegion, MII, NextMI, WorkPoint, FromHere,
4830 backtrack, MovingDependentOp, PathInRegion)) {
4831
4832 // If BB from which we pull is now empty, move on.
4833 if (IsEmptyBlock(FromThisBB)) {
4834 LLVM_DEBUG(dbgs() << "\n\tExhosted BB (single).\n");
4835 return false;
4836 }
4837 FromThisBBEnd = FromThisBB->end();
4838 ToThisBBEnd = ToThisBB->end();
4839
4840 LLVM_DEBUG(dbgs() << "\tAfter updates (single to bundle):\n");
4841 LLVM_DEBUG(dbgs() << "\t\tWorkPoint: ";
4842 DumpPacket(WorkPoint.getInstrIterator()));
4843 // We should not increment current position,
4844 // but rather try one more time to pull from the same bundle.
4845 RetVal = WorkPoint;
4846 return true;
4847 } else
4848 LLVM_DEBUG(dbgs() << "\tCould not move single.\n");
4849 }
4850 }
4851 LLVM_DEBUG(dbgs() << "\tNot a single candidate fit.\n");
4852 return false;
4853}
4854
4855/// Main function. Iterate all current regions one at a time,
4856/// and look for pull-up opportunities.
4857/// Pseudo sequence:
4858/// - for all bundles and single instructions in region:
4859/// - see if resources are available (in the same cycle) - this is HOME.
4860/// - Starting from next BB in region, find an instruction that could be:
4861/// - removed from its current location
4862/// - added to underutilized bundle (including bundles with only one op)
4863/// - If so, trace path back to HOME and check that candidate could be
4864/// reordered with all the intermediate instructions.
4865bool HexagonGlobalSchedulerImpl::performPullUp() {
4866 std::vector<MachineInstr *> backtrack;
4868 MachineBasicBlock::iterator FromThisBBEnd;
4869
4870 LLVM_DEBUG(dbgs() << "****** PullUpRegions ***********\n");
4871 // For all regions...
4872 for (std::vector<BasicBlockRegion *>::iterator
4873 CurrentRegion = PullUpRegions.begin(),
4874 E = PullUpRegions.end();
4875 CurrentRegion != E; ++CurrentRegion) {
4876
4877 LLVM_DEBUG(dbgs() << "\n\nRegion with(" << (*CurrentRegion)->size()
4878 << ")BBs\n");
4879
4880 if (!EnableLocalPullUp && (*CurrentRegion)->size() < 2)
4881 continue;
4882
4883 // For all MBB in the region... except the last one.
4884 // ...except when we want to allow local pull-up.
4885 for (auto ToThisBB = (*CurrentRegion)->getRootMBB(),
4886 LastBBInRegion = (*CurrentRegion)->getLastMBB();
4887 ToThisBB != LastBBInRegion; ++ToThisBB) {
4888 // If we do not want to allow same BB pull-up, take an early exit.
4889 if (!EnableLocalPullUp && (std::next(ToThisBB) == LastBBInRegion))
4890 break;
4891 if (multipleBranchesFromToBB(*ToThisBB))
4892 break;
4893
4894 auto FromThisBB = ToThisBB;
4895 MachineBasicBlock::iterator ToThisBBEnd = (*ToThisBB)->end();
4896 MachineBasicBlock::iterator MI = (*ToThisBB)->begin();
4897
4898 LLVM_DEBUG(dbgs() << "\n\tHome iterator moved to new BB("
4899 << (*ToThisBB)->getNumber() << ")\n";
4900 (*ToThisBB)->dump());
4901
4902 // For all instructions in the BB.
4903 while (MI != ToThisBBEnd) {
4904 MachineBasicBlock::iterator WorkPoint = MI;
4905 ++MI;
4906
4907 // Trivial check that there are unused resources
4908 // in the current location (cycle).
4909 while (ResourcesAvailableInBundle(*CurrentRegion, WorkPoint)) {
4910 LLVM_DEBUG(dbgs() << "\nxxxx Next Home in BB("
4911 << (*ToThisBB)->getNumber() << "):\n";
4912 DumpPacket(WorkPoint.getInstrIterator()));
4913 // Keep the path to the candidate.
4914 // It is the traveled path between home and work point.
4915 // Reset it for the new iteration.
4916 backtrack.clear();
4917
4918 // The point of pull-up source (WorkPoint) could begin from the
4919 // current BB, but only if we allow pull-up in the same BB.
4920 // At the moment we do not.
4921 // We also do not process last block in the region,
4922 // so it is safe to always begin with the next BB in the region.
4923 // Start from "next" BB in the region.
4924 if (EnableLocalPullUp) {
4925 FromThisBB = ToThisBB;
4926 FromHere = WorkPoint;
4927 ++FromHere;
4928 FromThisBBEnd = (*FromThisBB)->end();
4929
4930 // Initialize backtrack.
4931 // These are instructions between Home location
4932 // and the WorkPoint.
4933 for (MachineBasicBlock::iterator I = WorkPoint, IE = FromHere;
4934 I != IE; ++I)
4935 backtrack.push_back(&*I);
4936 } else {
4937 FromThisBB = ToThisBB;
4938 ++FromThisBB;
4939 FromHere = (*FromThisBB)->begin();
4940 FromThisBBEnd = (*FromThisBB)->end();
4941
4942 // Initialize backtrack.
4943 // These are instructions between Home location
4944 // and the end of the home BB.
4945 for (MachineBasicBlock::iterator I = WorkPoint, IE = ToThisBBEnd;
4946 I != IE; ++I)
4947 backtrack.push_back(&*I);
4948 }
4949
4950 // Search for pull-up candidate.
4951 while (true) {
4952 // If this BB is over, move onto the next one
4953 // in this region.
4954 if (FromHere == FromThisBBEnd) {
4955 ++FromThisBB;
4956 // Refresh LastBBInRegion in case tryMultipleInstructions modified
4957 // the regions Elements vector, invalidating the iterator.
4958 LastBBInRegion = (*CurrentRegion)->getLastMBB();
4959 if (FromThisBB == LastBBInRegion)
4960 break;
4961 else {
4962 LLVM_DEBUG(dbgs() << "\n\tNext BB in this region\n";
4963 (*FromThisBB)->dump());
4964 FromThisBBEnd = (*FromThisBB)->end();
4965 FromHere = (*FromThisBB)->begin();
4966 if (FromThisBBEnd == FromHere)
4967 break;
4968 }
4969 }
4970 if ((*FromHere).isDebugInstr()) {
4971 ++FromHere;
4972 continue;
4973 }
4974 // This is a step Home.
4975 backtrack.push_back(&*FromHere);
4976 if (!findPullUpCandidates(WorkPoint, FromHere, backtrack,
4978 break;
4979 ++FromHere;
4980 }
4981 // Try to pull-up one of the selected candidates.
4982 if (!tryMultipleInstructions(/*output*/ WorkPoint, CurrentRegion, MI,
4983 ToThisBBEnd, FromThisBBEnd))
4984 break;
4985 }
4986 }
4987 // Refresh LastBBInRegion after potential CFG modifications.
4988 LastBBInRegion = (*CurrentRegion)->getLastMBB();
4989 }
4990 // AllowUnlikelyPath is on by default,
4991 // if we wish to disable it, we can do so here.
4992 if (!AllowUnlikelyPath)
4993 continue;
4994
4995 // We have parsed the likely path through the region.
4996 // Now traverse the other (unlikely) path.
4997 //
4998 // Note: BasicBlockRegion uses a vector for MBB storage, so adding BBs to
4999 // the region while iterating could invalidate iterators. Collect the work
5000 // items first, then process them.
5001 std::vector<std::pair<MachineBasicBlock *, MachineBasicBlock *>>
5002 UnlikelyWork;
5003 UnlikelyWork.reserve((*CurrentRegion)->size());
5004 for (auto ToIt = (*CurrentRegion)->getRootMBB(),
5005 End = (*CurrentRegion)->getLastMBB();
5006 ToIt != End; ++ToIt) {
5007 MachineBasicBlock *ToBB = *ToIt;
5008 MachineBasicBlock *SecondBest = getNextPURBB(ToBB, true);
5009 if (SecondBest)
5010 UnlikelyWork.emplace_back(ToBB, SecondBest);
5011 }
5012
5013 for (auto [ToBB, SecondBest] : UnlikelyWork) {
5014 LLVM_DEBUG(dbgs() << "\tFor BB:\n"; ToBB->dump());
5015 LLVM_DEBUG(dbgs() << "\tHave SecondBest:\n"; SecondBest->dump());
5016 // Adding this BB to the region should not be done if we
5017 // plan to reuse it(the region) again. For now it is OK.
5018 (*CurrentRegion)->addBBtoRegion(SecondBest);
5019 LLVM_DEBUG(dbgs() << "\tHome iterator moved to new BB("
5020 << ToBB->getNumber() << ")\n";
5021 ToBB->dump());
5022 MachineBasicBlock::iterator ToThisBBEnd = ToBB->end();
5024
5025 // For all instructions in the BB.
5026 while (MI != ToThisBBEnd) {
5027 MachineBasicBlock::iterator WorkPoint = MI;
5028 ++MI;
5029
5030 // Trivial check that there are unused resources
5031 // in the current location (cycle).
5032 while (ResourcesAvailableInBundle(*CurrentRegion, WorkPoint)) {
5033 LLVM_DEBUG(dbgs() << "\nxxxx Second visit Home in BB("
5034 << ToBB->getNumber() << "):\n";
5035 DumpPacket(WorkPoint.getInstrIterator()));
5036
5037 FromHere = SecondBest->begin();
5038 FromThisBBEnd = SecondBest->end();
5039
5040 // Keep the path to the candidate.
5041 backtrack.clear();
5042
5043 // This is Home location.
5044 for (MachineBasicBlock::iterator I = WorkPoint, IE = ToThisBBEnd;
5045 I != IE; ++I)
5046 backtrack.push_back(&*I);
5047
5048 while (true) {
5049 // If this BB is over, move onto the next one
5050 // in this region.
5051 if (FromHere == FromThisBBEnd) {
5053 << "\tOnly do one successor for the second try\n");
5054 break;
5055 }
5056 if ((*FromHere).isDebugInstr()) {
5057 ++FromHere;
5058 continue;
5059 }
5060 // This is a step Home.
5061 backtrack.push_back(&*FromHere);
5062 if (!findPullUpCandidates(WorkPoint, FromHere, backtrack,
5064 break;
5065 ++FromHere;
5066 }
5067 // Try to pull-up one of selected candidate.
5068 if (!tryMultipleInstructions(/*output*/ WorkPoint, CurrentRegion, MI,
5069 ToThisBBEnd, FromThisBBEnd, false))
5070 break;
5071 }
5072 }
5073 }
5074 }
5075 return true;
5076}
5077
5078bool HexagonGlobalSchedulerImpl::incrementalAddToPacket(MachineInstr &MI) {
5079
5080 LLVM_DEBUG(dbgs() << "\t[AddToPacket] (" << CurrentPacketMIs.size()
5081 << ") adding:\t";
5082 MI.dump());
5083
5084 if (!ResourceTracker->canReserveResources(MI) || !shouldAddToPacket(MI))
5085 return false;
5086
5087 ResourceTracker->reserveResources(MI);
5088 CurrentPacketMIs.push_back(&MI);
5089 CurrentState.HomeBundle.push_back(&MI);
5090
5091 if (QII->isExtended(MI) || QII->isConstExtended(MI) ||
5092 isJumpOutOfRange(&MI)) {
5093 // If at this point of time we cannot reserve resources,
5094 // this might mean that the packet came into the pull-up
5095 // pass already in danger of overflowing.
5096 // Nevertheless, since this is only a possibility of overflow
5097 // no error should be issued here.
5098 if (ResourceTracker->canReserveResources(*Ext)) {
5099 ResourceTracker->reserveResources(*Ext);
5100 LLVM_DEBUG(dbgs() << "\t[AddToPacket] (" << CurrentPacketMIs.size()
5101 << ") adding:\t immext_i\n");
5102 CurrentPacketMIs.push_back(Ext);
5103 CurrentState.HomeBundle.push_back(Ext);
5104 return true;
5105 } else {
5106 LLVM_DEBUG(dbgs() << "\t Previous overflow possible.\n");
5107 return false;
5108 }
5109 }
5110 return true;
5111}
5112
5113void HexagonGlobalSchedulerImpl::checkBundleCounts(MachineFunction &Fn) {
5115 return;
5116
5117 unsigned BundleLimit = 4;
5118
5119 for (MachineFunction::iterator MBBi = Fn.begin(), MBBe = Fn.end();
5120 MBBi != MBBe; ++MBBi) {
5121
5122 for (MachineBasicBlock::iterator MI = MBBi->instr_begin(),
5123 ME = MBBi->instr_end();
5124 MI != ME; ++MI) {
5125 if (MI->isBundle()) {
5126 MachineBasicBlock::instr_iterator MII = MI.getInstrIterator();
5127 MachineBasicBlock::instr_iterator End = MII->getParent()->instr_end();
5128
5129 unsigned InstrCount = 0;
5130
5131 for (++MII; MII != End && MII->isInsideBundle(); ++MII) {
5132 if (MII->getOpcode() == TargetOpcode::DBG_VALUE ||
5133 MII->getOpcode() == TargetOpcode::IMPLICIT_DEF ||
5134 MII->getOpcode() == TargetOpcode::CFI_INSTRUCTION ||
5135 MII->isEHLabel() || QII->isEndLoopN(MII->getOpcode())) {
5136 continue;
5137 } else {
5138 InstrCount++;
5139 }
5140 }
5141 if (InstrCount > BundleLimit) {
5142 if (WarnOnBundleSize) {
5143 LLVM_DEBUG(dbgs() << "Warning bundle size exceeded " << *MI);
5144 } else {
5145 assert(0 && "Bundle size exceeded");
5146 }
5147 }
5148 }
5149 }
5150 }
5151}
5152
5153/// Debugging only. Count compound and duplex opportunities.
5154unsigned HexagonGlobalSchedulerImpl::countCompounds(MachineFunction &Fn) {
5155 unsigned CompoundCount = 0;
5156 [[maybe_unused]] unsigned DuplexCount = 0;
5157 [[maybe_unused]] unsigned InstOffset = 0;
5158
5159 // Loop over all basic blocks.
5160 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end(); MBB != MBBe;
5161 ++MBB) {
5162 LLVM_DEBUG(dbgs() << "\n BB#" << MBB->getNumber() << " " << MBB->getName()
5163 << " in_func "
5164 << MBB->getParent()->getFunction().getName() << " \n");
5166 ME = MBB->instr_end();
5167 MI != ME; ++MI) {
5168 if (MI->isDebugInstr())
5169 continue;
5170 if (MI->isBundle()) {
5171 MachineBasicBlock::instr_iterator MII = MI.getInstrIterator();
5172 MachineBasicBlock::instr_iterator MIE = MI->getParent()->instr_end();
5173 MachineInstr *FirstCompound = NULL, *SecondCompound = NULL;
5174 MachineInstr *FirstDuplex = NULL, *SecondDuplex = NULL;
5175 LLVM_DEBUG(dbgs() << "{\n");
5176
5177 for (++MII; MII != MIE && MII->isInsideBundle() && !MII->isBundle();
5178 ++MII) {
5179 if (MII->isDebugInstr())
5180 continue;
5181 LLVM_DEBUG(dbgs() << "(" << InstOffset << ")\t");
5182 InstOffset += QII->getSize(*MII);
5183 if (QII->getCompoundCandidateGroup(*MII)) {
5184 if (!FirstCompound) {
5185 FirstCompound = &*MII;
5186 LLVM_DEBUG(dbgs() << "XX ");
5187 } else {
5188 SecondCompound = &*MII;
5189 LLVM_DEBUG(dbgs() << "YY ");
5190 }
5191 }
5192 if (QII->getDuplexCandidateGroup(*MII)) {
5193 if (!FirstDuplex) {
5194 FirstDuplex = &*MII;
5195 LLVM_DEBUG(dbgs() << "AA ");
5196 } else {
5197 SecondDuplex = &*MII;
5198 LLVM_DEBUG(dbgs() << "VV ");
5199 }
5200 }
5201 LLVM_DEBUG(MII->dump());
5202 }
5203 LLVM_DEBUG(dbgs() << "}\n");
5204 if (SecondCompound) {
5205 if (isCompoundPair(FirstCompound, SecondCompound)) {
5206 LLVM_DEBUG(dbgs() << "Compound pair (" << CompoundCount << ")\n");
5207 CompoundCount++;
5208 }
5209 }
5210 if (SecondDuplex) {
5211 if (QII->isDuplexPair(*FirstDuplex, *SecondDuplex)) {
5212 LLVM_DEBUG(dbgs() << "Duplex pair (" << DuplexCount << ")\n");
5213 DuplexCount++;
5214 }
5215 }
5216 } else {
5217 LLVM_DEBUG(dbgs() << "(" << InstOffset << ")\t");
5218 if (QII->getCompoundCandidateGroup(*MI))
5219 LLVM_DEBUG(dbgs() << "XX ");
5220 if (QII->getDuplexCandidateGroup(*MI))
5221 LLVM_DEBUG(dbgs() << "AA ");
5222 InstOffset += QII->getSize(*MI);
5223 LLVM_DEBUG(MI->dump());
5224 }
5225 }
5226 }
5227 LLVM_DEBUG(dbgs() << "Total compound(" << CompoundCount << ") duplex("
5228 << DuplexCount << ")\n");
5229 return CompoundCount;
5230}
5231
5232//===----------------------------------------------------------------------===//
5233// Public Constructor Functions
5234//===----------------------------------------------------------------------===//
5235
5237 return new HexagonGlobalScheduler();
5238}
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
constexpr LLT S1
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator MBBI
static const Function * getParent(const Value *V)
bbsections Prepares for basic block by splitting functions into clusters of basic static false void updateBranches(MachineFunction &MF, const SmallVector< MachineBasicBlock * > &PreLayoutFallThroughs)
static bool IsEmptyBlock(MachineBasicBlock *MBB)
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static InstructionCost getCost(const AnalysisOptions &Opts, Instruction &Inst, TTI::TargetCostKind CostKind, TargetTransformInfo &TTI)
Definition CostModel.cpp:33
static unsigned InstrCount
This file defines the DenseMap class.
const HexagonInstrInfo * TII
static void DumpLinked(MachineInstr *MI)
static bool IsSchedBarrier(const MachineInstr *MI)
static cl::opt< bool > EnableSpeculativePullUp("enable-speculative-pull-up", cl::Hidden, cl::desc("Enable speculation during Hexagon pull-up pass"))
static cl::opt< bool > ForceNoopHazards("force-noop-hazards", cl::Hidden, cl::init(false), cl::desc("Force noop hazards in scheduler"))
static MachineBasicBlock::instr_iterator getHexagonFirstInstrTerminator(MachineBasicBlock *MBB)
static void debugLivenessForBB(const MachineBasicBlock *MBB, const TargetRegisterInfo *TRI)
static void markKillReg(MachineInstr *MI, unsigned Reg)
Find use with this reg, and unmark the kill flag.
static MachineBasicBlock * getBranchDestination(MachineInstr *MI)
Treat given instruction as a branch, go through its operands and see if any of them is a BB address.
static cl::opt< bool > AllowBBPeelPullUp("enable-bb-peel-pull-up", cl::Hidden, cl::init(true), cl::desc("Peel a reg copy out of a BBloop"))
cl::opt< bool > OneComplexPerPacket
static void updatePredecessors(MachineBasicBlock &MBB, MachineBasicBlock *MFBB)
Rewrite all predecessors of the old block to go to the fallthrough instead.
static void parseOperands(MachineInstr *MI, SmallVector< unsigned, 4 > &Defs, SmallVector< unsigned, 8 > &Uses)
Gather register def/uses from MI.
static bool selectBestBB(BlockFrequency &BBaFreq, unsigned BBaSize, BlockFrequency &BBbFreq, unsigned BBbSize)
Select best candidate to form regions.
static bool MIMustNotBePulledUp(MachineInstr *MI)
static cl::opt< bool > PreventDuplexSeparation("prevent-duplex-separation", cl::Hidden, cl::init(true), cl::desc("Do not destroy existing duplexes during pull up"))
static cl::opt< bool > AllowCmpBranchLoads("cmp-branch-loads-pull-up", cl::Hidden, cl::init(true), cl::desc("Allow compare-branch loads during Hexagon pull-up pass"))
static void DumpPacket(MachineBasicBlock::instr_iterator MII)
static cl::opt< unsigned > SecondaryCandidateQueueSize("pull-up-sec-queue-size", cl::Hidden, cl::init(2))
static bool isDelayedUseException(MachineInstr *MIa, MachineInstr *MIb)
Some apparent dependencies are not actually restricting us since there is a delay between assignment ...
static cl::opt< bool > AllowUnlikelyPath("unlikely-path-pull-up", cl::Hidden, cl::init(true), cl::desc("Allow unlikely path pull up"))
static const unsigned SafetyBuffer
static cl::opt< bool > EnableLocalPullUp("enable-local-pull-up", cl::Hidden, cl::init(true), cl::desc("Enable same BB pull during Hexagon pull-up pass"))
static cl::opt< bool > SpeculateNonPredInsn("speculate-non-pred-insn", cl::Hidden, cl::init(true), cl::desc("Speculate non-predicable instructions in parent BB"))
static void UpdateCFG(MachineBasicBlock *HomeBB, MachineBasicBlock *OriginBB, MachineInstr *MII, MachineBasicBlock *HomeTBB, MachineBasicBlock *HomeFBB, MachineInstr *FTA, MachineInstr *STA, const MachineBranchProbabilityInfo *MBPI)
static cl::opt< bool > WarnOnBundleSize("warn-on-bundle-size", cl::Hidden, cl::desc("Hexagon check bundles and warn on size"))
static unsigned nonDbgBundleSize(MachineBasicBlock::iterator &TargetPacket)
static bool isGlobalMemoryObject(MachineInstr *MI)
Return true if MI is an instruction we are unable to reason about (like something with unmodeled memo...
void Unify(std::vector< ElemType > Range, std::map< ElemType, std::vector< IndexType > > &Set1, std::map< ElemType, std::vector< IndexType > > &Set2, std::pair< std::vector< IndexType >, std::vector< IndexType > > &UnionSet, unsigned union_size=100)
static cl::opt< bool > PreventCompoundSeparation("prevent-compound-separation", cl::Hidden, cl::desc("Do not destroy existing compounds during pull up"))
static cl::opt< bool > AllowDependentPullUp("enable-dependent-pull-up", cl::Hidden, cl::init(true), cl::desc("Perform dual jump formation during pull up"))
static cl::opt< unsigned > MainCandidateQueueSize("pull-up-main-queue-size", cl::Hidden, cl::init(8))
static cl::opt< bool > DisableCheckBundles("disable-hexagon-check-bundles", cl::Hidden, cl::init(true), cl::desc("Disable Hexagon check bundles pass"))
static cl::opt< bool > PerformDualJumps("dual-jump-in-pull-up", cl::Hidden, cl::init(true), cl::desc("Perform dual jump formation during pull up"))
static void UpdateBundle(MachineInstr *BundleHead)
static bool IsIndirectCall(const MachineInstr *MI)
static cl::opt< bool > DisablePullUp("disable-pull-up", cl::Hidden, cl::desc("Disable Hexagon pull-up pass"))
static cl::opt< bool > AllowSpeculateLoads("speculate-loads-on-pull-up", cl::Hidden, cl::init(true), cl::desc("Allow speculative loads during Hexagon pull-up pass"))
static void unmarkKillReg(MachineInstr *MI, unsigned Reg)
Find use with this reg, and unmark the kill flag.
static bool MIShouldNotBePulledUp(MachineInstr *MI)
static cl::opt< bool > PostPullUpOpt("post-pull-up-opt", cl::Hidden, cl::init(true), cl::desc("Enable opt. exposed by pull-up e.g., remove redundant jumps"))
cl::opt< bool > OneFloatPerPacket
#define HEXAGON_INSTR_SIZE
IRTranslator LLVM IR MI
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
static MCRegister getReg(const MCDisassembler *D, unsigned RC, unsigned RegNo)
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
if(PassOpts->AAPipeline)
#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
static bool isBranch(unsigned Opcode)
SmallVector< MachineOperand, 4 > Cond
MachineRegisterInfo & MRI
const SmallVectorImpl< MachineOperand > MachineBasicBlock * TBB
Remove Loads Into Fake Uses
static bool InBlock(const Value *V, const BasicBlock *BB)
This file defines the SmallSet 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:119
Value * RHS
Value * LHS
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object.
LLVM_ABI AnalysisUsage & addRequiredID(const void *ID)
Definition Pass.cpp:294
AnalysisUsage & addRequired()
void RemoveBBFromRegion(MachineBasicBlock *MBB)
MachineBasicBlock * findNextMBB(MachineBasicBlock *MBB)
LivenessInfo * getLivenessInfoForBB(MachineBasicBlock *MBB)
void addBBtoRegion(MachineBasicBlock *MBB)
uint64_t getFrequency() const
Returns the frequency as a fixpoint number scaled by the entry frequency.
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
iterator begin()
Definition Function.h:847
iterator end()
Definition Function.h:849
bool isPredicated(const MachineInstr &MI) const override
Returns true if the instruction is already predicated.
bool isCompoundBranchInstr(const MachineInstr &MI) const
bool isDuplexPair(const MachineInstr &MIa, const MachineInstr &MIb) const
Symmetrical. See if these two instructions are fit for duplex pair.
bool isJumpR(const MachineInstr &MI) const
bool invertAndChangeJumpTarget(MachineInstr &MI, MachineBasicBlock *NewTarget) const
int getDotNewPredOp(const MachineInstr &MI, const MachineBranchProbabilityInfo *MBPI) const
unsigned getInvertedPredicatedOpcode(const int Opc) const
HexagonII::SubInstructionGroup getDuplexCandidateGroup(const MachineInstr &MI) const
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 isPredicatedNew(const MachineInstr &MI) const
bool isJumpWithinBranchRange(const MachineInstr &MI, unsigned offset) const
bool mayBeNewStore(const MachineInstr &MI) const
bool reverseBranchCondition(SmallVectorImpl< MachineOperand > &Cond) const override
Reverses the branch condition of the specified condition list, returning false on success and true if...
bool isLoopN(const MachineInstr &MI) const
bool isConstExtended(const MachineInstr &MI) const
bool PredOpcodeHasJMP_c(unsigned Opcode) const
bool areMemAccessesDependent(AAResults *AA, const MachineInstr *MIa, const MachineInstr *MIb) const
Return true if the memory accesses of MIa and MIb may depend on each other.
bool isExtended(const MachineInstr &MI) const
bool isPredicateLate(unsigned Opcode) const
bool isComplex(const MachineInstr &MI) const
void setBundleNoShuf(MachineBasicBlock::instr_iterator MIB) const
bool isMemOp(const MachineInstr &MI) const
int getDotOldOp(const MachineInstr &MI) const
bool isDeallocRet(const MachineInstr &MI) const
unsigned getCExtOpNum(const MachineInstr &MI) const
bool isDotNewInst(const MachineInstr &MI) const
unsigned getSize(const MachineInstr &MI) const
bool isHVXVec(const MachineInstr &MI) const
bool getBundleNoShuf(const MachineInstr &MIB) const
bool isNewValueJump(const MachineInstr &MI) const
bool PredicateInstruction(MachineInstr &MI, ArrayRef< MachineOperand > Cond) const override
Convert the instruction into a predicated instruction.
bool isFloat(const MachineInstr &MI) const
unsigned nonDbgBBSize(const MachineBasicBlock *BB) const
getInstrTimingClassLatency - Compute the instruction latency of a given instruction using Timing Clas...
bool isEndLoopN(unsigned Opcode) const
bool isPredicable(const MachineInstr &MI) const override
Return true if the specified instruction can be predicated.
HexagonII::CompoundGroup getCompoundCandidateGroup(const MachineInstr &MI) const
SmallVector< MachineInstr *, 2 > getBranchingInstrs(MachineBasicBlock &MBB) const
bool isNewValueStore(const MachineInstr &MI) const
const MCPhysReg * getCalleeSavedRegs(const MachineFunction *MF) const override
Code Generation virtual methods...
bool isFakeReg(MCPhysReg Reg) const
Returns true if the given reserved physical register Reg is live across function calls/returns.
bool isGlobalReg(MCPhysReg Reg) const
Returns true if the given reserved physical register is live across function calls/returns.
void UpdateLiveness(MachineBasicBlock *MBB)
unsigned getSchedClass() const
Return the scheduling class for this instruction.
bool isEHPad() const
Returns true if the block is a landing pad.
reverse_instr_iterator instr_rbegin()
instr_iterator erase_instr(MachineInstr *I)
Remove an instruction from the instruction list and delete it.
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
SmallVectorImpl< MachineBasicBlock * >::const_iterator const_succ_iterator
LLVM_ABI iterator getFirstNonDebugInstr(bool SkipPseudoOp=true)
Returns an iterator to the first non-debug instruction in the basic block, or end().
LiveInVector::const_iterator livein_iterator
bool hasAddressTaken() const
Test whether this block is used as something other than the target of a terminator,...
void setAlignment(Align A)
Set alignment of the basic block.
LLVM_ABI void dump() const
LLVM_ABI void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
SmallVectorImpl< MachineBasicBlock * >::iterator succ_iterator
LLVM_ABI void removeSuccessor(MachineBasicBlock *Succ, bool NormalizeSuccProbs=false)
Remove successor from the successors list of this MachineBasicBlock.
LLVM_ABI iterator getFirstNonPHI()
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
LLVM_ABI bool isPredecessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB is a predecessor of this block.
reverse_instr_iterator instr_rend()
Instructions::iterator instr_iterator
LLVM_ABI void ReplaceUsesOfBlockWith(MachineBasicBlock *Old, MachineBasicBlock *New)
Given a machine basic block that branched to 'Old', change the code and CFG so that it branches to 'N...
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.
Instructions::const_iterator const_instr_iterator
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
LLVM_ABI instr_iterator erase(instr_iterator I)
Remove an instruction from the instruction list and delete it.
iterator_range< succ_iterator > successors()
LLVM_ABI instr_iterator getFirstInstrTerminator()
Same getFirstTerminator but it ignores bundles and return an instr_iterator instead.
iterator insertAfter(iterator I, MachineInstr *MI)
Insert MI into the instruction list after I.
LLVM_ABI bool isSuccessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB is a successor of this 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 '...
Align getAlignment() const
Return alignment of the basic block.
MachineInstrBundleIterator< MachineInstr > iterator
LLVM_ABI StringRef getName() const
Return the name of the corresponding LLVM basic block, or an empty string.
LLVM_ABI bool isLiveIn(MCRegister Reg, LaneBitmask LaneMask=LaneBitmask::getAll()) const
Return true if the specified register is in the live in set.
Instructions::reverse_iterator reverse_instr_iterator
MachineBlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate machine basic b...
LLVM_ABI BlockFrequency getBlockFreq(const MachineBasicBlock *MBB) const
getblockFreq - Return block frequency.
LLVM_ABI BranchProbability getEdgeProbability(const MachineBasicBlock *Src, const MachineBasicBlock *Dst) const
Analysis pass which computes a MachineDominatorTree.
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
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.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
BasicBlockListType::iterator iterator
Representation of each machine instruction.
mop_iterator operands_begin()
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
LLVM_ABI MachineInstr * removeFromParent()
Unlink 'this' from the containing basic block, and return it without deleting it.
const MachineBasicBlock * getParent() const
bool isCall(QueryType Type=AnyInBundle) const
bool isBundle() const
LLVM_ABI MachineInstr * removeFromBundle()
Unlink this instruction from its basic block and return it without deleting it.
bool isBranch(QueryType Type=AnyInBundle) const
Returns true if this is a conditional, unconditional, or indirect branch.
bool isBundledWithPred() const
Return true if this instruction is part of a bundle, and it is not the first instruction in the bundl...
LLVM_ABI void unbundleFromPred()
Break bundle above this instruction.
bool mayLoad(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read memory.
mop_iterator operands_end()
LLVM_ABI unsigned getBundleSize() const
Return the number of instructions inside the MI bundle, excluding the bundle header.
bool isConditionalBranch(QueryType Type=AnyInBundle) const
Return true if this is a branch which may fall through to the next instruction or may transfer contro...
LLVM_ABI void setDesc(const MCInstrDesc &TID)
Replace the instruction descriptor (thus opcode) of the current instruction with a new one.
bool isUnconditionalBranch(QueryType Type=AnyInBundle) const
Return true if this is a branch which always transfers control flow to some other block.
LLVM_ABI void eraseFromBundle()
Unlink 'this' from its basic block and delete it.
MachineOperand * mop_iterator
iterator/begin/end - Iterate over all operands of a machine instruction.
bool mayStore(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly modify memory.
LLVM_ABI void dump() const
bool isBundledWithSucc() const
Return true if this instruction is part of a bundle, and it is not the last instruction in the bundle...
const MachineOperand & getOperand(unsigned i) const
LLVM_ABI void unbundleFromSucc()
Break bundle below this instruction.
LLVM_ABI MachineInstrBundleIterator< MachineInstr > eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
bool isIndirectBranch(QueryType Type=AnyInBundle) const
Return true if this is an indirect branch, such as a branch through a register.
bool isBundled() const
Return true if this instruction part of a bundle.
MachineOperand class - Representation of each machine instruction operand.
void setIsInternalRead(bool Val=true)
bool isReg() const
isReg - Tests if this is a MO_Register operand.
bool isRegMask() const
isRegMask - Tests if this is a MO_RegisterMask operand.
MachineBasicBlock * getMBB() const
void setIsKill(bool Val=true)
void setMBB(MachineBasicBlock *MBB)
Register getReg() const
getReg - Returns the register number.
static bool clobbersPhysReg(const uint32_t *RegMask, MCRegister PhysReg)
clobbersPhysReg - Returns true if this RegMask clobbers PhysReg.
bool isMBB() const
isMBB - Tests if this is a MO_MachineBasicBlock operand.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
bool isReserved(MCRegister PhysReg) const
isReserved - Returns true when PhysReg is a reserved register.
PassRegistry - This class manages the registration and intitialization of the pass subsystem as appli...
static LLVM_ABI PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
static constexpr bool isPhysicalRegister(unsigned Reg)
Return true if the specified register number is in the physical register namespace.
Definition Register.h:60
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
Definition SmallSet.h:176
bool empty() const
Definition SmallSet.h:169
bool erase(const T &V)
Definition SmallSet.h:200
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:184
size_type size() const
Definition SmallSet.h:171
iterator insert(iterator I, T &&Elt)
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
LLVM_ABI void init(const TargetSubtargetInfo *TSInfo, bool EnableSModel=true, bool EnableSItins=true)
Initialize the machine model for instruction scheduling.
LLVM_ABI unsigned computeOperandLatency(const MachineInstr *DefMI, unsigned DefOperIdx, const MachineInstr *UseMI, unsigned UseOperIdx) const
Compute operand latency based on the available machine model.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
int getNumOccurrences() const
unsigned getPosition() const
self_iterator getIterator()
Definition ilist_node.h:123
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Abstract Attribute helper functions.
Definition Attributor.h:166
@ Tail
Attemps to make calls as fast as possible while guaranteeing that tail call optimization can always b...
Definition CallingConv.h:76
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
LLVM_ABI void finalizeBundle(MachineBasicBlock &MBB, MachineBasicBlock::instr_iterator FirstMI, MachineBasicBlock::instr_iterator LastMI)
finalizeBundle - Finalize a machine instruction bundle which includes a sequence of instructions star...
MachineBasicBlock::instr_iterator getBundleStart(MachineBasicBlock::instr_iterator I)
Returns an iterator to the first instruction in the bundle containing I.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
InstructionCost Cost
LLVM_ABI char & MachineDominatorsID
MachineDominators - This pass is a machine dominators analysis pass.
void initializeHexagonGlobalSchedulerPass(PassRegistry &)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
MachineBasicBlock::instr_iterator getBundleEnd(MachineBasicBlock::instr_iterator I)
Returns an iterator pointing beyond the bundle containing I.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
RNSuccIterator< NodeRef, BlockT, RegionT > succ_begin(NodeRef Node)
RNSuccIterator< NodeRef, BlockT, RegionT > succ_end(NodeRef Node)
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:2028
LLVM_ABI Printable printBlockFreq(const BlockFrequencyInfo &BFI, BlockFrequency Freq)
Print the block frequency Freq relative to the current functions entry frequency.
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
AAResults AliasAnalysis
Temporary typedef for legacy code that uses a generic AliasAnalysis pointer or reference.
LLVM_ABI Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
FunctionPass * createHexagonGlobalScheduler()
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:82