LLVM 24.0.0git
HexagonGlobalSchedulerV2.cpp
Go to the documentation of this file.
1//===----- HexagonGlobalSchedulerV2.cpp - Global Scheduler ----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// Basic infrastructure for the global scheduling + Hexagon pull-up pass.
10// Currently run at the very end of code generation for Hexagon, cleans
11// up lost scheduling opportunities. Liveness is preserved after this pass,
12// and we should not run a liveness analysis after this pass because compound
13// instructions might be formed which do not fit into the usual model of
14// use-after-def of regs.
15//
16// @note: Local pullup runs after global scheduling because global pullup
17// leaves room in packets that local instructions can fill.
18//
19// @note: Local push-down moves instructions into the immediate successor
20// packet only.
21//
22// Brief overview of working of this global scheduler.
23// This version of Hexagon Global Scheduler is basically a greedy scheduler.
24// The main purpose of this VLIW global scheduler is to increase the packet
25// density (= #instructions/#packets). Since the VLIW packetizer works on a
26// local scope, it cannot fill up the packets very efficiently.
27// Having a global scheduler post-SSA makes it a complicated infrastructure
28// because it has to deal with liveness+dependencies of physical registers.
29// As a result, many strict measures have been taken to ensure correctness.
30// There are assertions put at places where some assumptions were implicit.
31// This also means that many optimization opportunities are not explored.
32//
33// The global scheduler heavily relies on HexagonLiveVariables.cpp and
34// HexagonVLIWPacketizer.cpp.
35// There is one function isLegalToPacketizeTogetherMI() which copies little
36// bit of code from HexagonPacketizerList::isLegalToPacketizeTogether, because
37// this the packetizer version takes in SchedulingUnits as arguments and
38// it wasn't easy to refactor it completely. Please update both the functions
39// in a coherent way. Or better, instead, add code to one
40// of the following three functions:
41//
42// HexagonPacketizerList::hasDeadDependence
43// HexagonPacketizerList::hasControlDependence
44// HexagonPacketizerList::hasDualStoreDependence
45//
46//
47// Step by step explanation of the process of global scheduling.
48//
49// Step1: Correct the CFG.
50// The packetizer/other-pass may leave MBB in a state where there are
51// non-branching instructions after the branches. This pass corrects the CFG
52// so that branches are the only instructions at the very end. This helps
53// reuse analyzeBranch even after packetizer.
54//
55// Step2: Form Scheduling regions.
56// Scheduling regions are sets of basic blocks which have only one entry point
57// but, possibly, multiple exit points. This is essentially a super-block.
58//
59// Step3: Sort Scheduling regions.
60// Sort scheduling regions based on profile/branch-probability. This gives
61// priority to instructions from branch targets with higher probability. In the
62// case where both branches have same probability, it biases one successor by
63// increasing the weight of TBB (see analyzeBranch).
64// - During this pass, AnalyzeBranchInfo of all the MBBs are
65// calculated and stored to be reused later. Care must be taken to update
66// the branch-info when a branch is modified (mostly post-pullup opts)
67//
68// Step4: Perform global+local scheduling of instructions.
69// Global scheduling is done first followed by local.
70// Global scheduling: globalPullup(SchedulingRegion_t &SR)
71// Speculative scheduling is done first followed by predicated scheduling.
72// for each scheduling region
73// for each MBB in a scheduling region
74// for each MI in leaf MBB
75// find a MI candidate by calling canMIBeSpeculated
76// YES=>speculate.
77// YES means it has to be speculated. There is no coming back.
78// These strict checks are necessary to ensure correctness in this
79// complicated infrastructure.
80// NO=>Try to squeeze the bundle by making a compound instruction
81// and hence, freeing up one slot. Only in special cases where
82// `bool preciousToSpeculate' returns true, the opportunities for
83// compound instructions are explored. If it is possible to create
84// a compound then the compound instruction
85// (generateCompoundIfPossible()) is created and again
86// decomposed into individual instructions. This is done because
87// it is not possible to analyzeBranch a BB with compounds (for now).
88//
89// And then try again by calling canMIBeSpeculated
90// YES=>speculate. The bundle now contains five instructions. Since
91// the bundle contains five instructions, care must be taken to
92// avoid doing too much around that packet, because there is no
93// available infrastructure to support five-instruction bundles.
94// NO=>move on to the next MI.
95//
96// for each MI in leaf MBB
97// find a MI candidate by calling canMIBePredicated
98// YES=>predicate.
99// YES means it has to be predicated. There is no coming back.
100// NO=>Try to squeeze the bundle by making a compound instruction
101// and hence, freeing up one slot. Only in special cases where
102// `bool preciousToPredicate' returns true, the opportunities for
103// compound instructions are explored.
104//
105// And then try again by calling canMIBePredicated.
106// This is identical to the case of speculative scheduling.
107//
108//
109// Local scheduling: localPullup
110// Reuses some functionalities of speculative pullup.
111// The function findInsertPtSpec has been designed to be reused for both
112// local+global `speculative' scheduling. Similarly, srcDependence() and
113// dstDependence() are reused.
114//
115// Step5: Packetize
116// When post-sched-packet is enabled (by default), repacketize the MBBs from
117// where pull up moved instructions.
118//
119// Step6: Post scheduling optimizations
120// These are branch optimizations and they modify the CFG. During this stage
121// MBBs having compounds are skipped because analyzeBranch cannot handle
122// compound branches.
123// During this stage AnalyzeBranchInfo is updated whenever a branch
124// optimization was successful.
125//
126// Step7: Generate compound instructions.
127// The function `generateCompoundsPostSched' re-generates compound instructions
128// at places where 5-instruction packets were formed during scheduling.
129//
130// Important functions which are used at multiple places:
131//
132// MII is already a bundle. This will initialize the packetizer and update
133// the DFA with existing resources so that the DFA can be queried for more
134// information e.g. can we put another MI in the bundle?
135// void getResourcesReadyForBundle(MIInstIterType MII, bool Squeeze = false);
136//
137// Returns true if resources are available for MII in the current packet
138// after getResourcesReadyForBundle has been called to initialize the DFA.
139// Takes into account const-extenders as well.
140// bool canReserveResources(MIInstIterType MII) const;
141//
142// When the resources are available, as checked by canReserveResources(),
143// we need to check for compatibility between MI and the destination bundle.
144// This function returns true if MI is compatible. This also takes care of
145// a special case when a branch and its target are too far, and
146// the branch might be constant extended.
147// bool isLegalToPacketizeWith(MIIterType DestPack, MachineInstr *MI);
148//
149// While global scheduling there are two parts.
150// 1. The instruction should be able to execute as the first instruction
151// within its Home/Src MBB. This is handled in findInsertionPtSpecLocal.
152//
153// 2. The instruction should be able to execute in parent/dominating MBB
154// without causing side-effects. This is handled in findInsertPtSpec()
155// while speculating and findInsertPtPred() while predicating.
156//
157// This function will return MBB->begin() if it is possible to move this
158// instruction to the beginning of MBB.
159// MIIterType findInsertionPtSpecLocal(MachineInstr *MI);
160//
161// The function findInsertionPtSpecLocal calls srcDependence which tells if
162// it is possible to `detach' the MI from its Home/Src BUNDLE. For example
163// when there is a .new/duplex etc. dependency we don't want to detach the MI.
164// Dependence within the same packet [SrcBeg, SrcEnd).
165// int srcDependence(MIInstIterType SrcBeg, MIInstIterType SrcEnd,
166// MIInstIterType RMII,
167// SmallSetVector<MachineInstr *, 4> *DepSet)
168// const;
169//
170// This function checks for dependencies between a range of MIIs
171// in the destination/target MBB (where MII will end up). Obviously, in the
172// case of predication we first create a dummy predicate instruction
173// in canMIBePredicated() which calls findInsertPtPred() which then
174// calls dstDependence() to check for dependencies.
175// int dstDependence(MICInstIterType DestBeg, MICInstIterType DestEnd,
176// MICInstIterType MII, MICInstIterType &DepTrue,
177// MICInstIterType &DepAnti, unsigned HLXUseReg = 0,
178// bool isPullDown = false) const;
179//
180//===----------------------------------------------------------------------===//
181#include "Hexagon.h"
182#include "HexagonGlobalRegion.h"
183#include "HexagonInstrInfo.h"
184#include "HexagonLiveVariables.h"
185#include "HexagonRegisterInfo.h"
186#include "HexagonSubtarget.h"
187#include "HexagonTargetMachine.h"
189#include "llvm/ADT/SetVector.h"
190#include "llvm/ADT/SmallVector.h"
191#include "llvm/ADT/Statistic.h"
202#include "llvm/Support/Debug.h"
203
204#include <map>
205#include <unordered_map>
206
207#define DEBUG_TYPE "global_schedV2"
208
209using namespace llvm;
210
211STATISTIC(HexagonGSLocalPullups, "Number of instructions pull-ups locally");
212STATISTIC(HexagonGSGlobalPullups, "Number of instructions pull-ups globally");
213
214static cl::opt<bool>
215 EnableGlobalSched("enable-global-sched", cl::Hidden, cl::init(false),
216 cl::desc("Enable global scheduler optimizer"));
217
218static cl::opt<bool> EnablePullupPred("enable-pullup-pred", cl::Hidden,
219 cl::init(true),
220 cl::desc("Use pullup predication"));
221
222static cl::opt<bool>
223 EnableLocalPullup("enable-local-pullup", cl::Hidden, cl::init(true),
224 cl::desc("Speculate local MIs in parent BUNDLEs"));
225
227 "enable-local-merge-packets", cl::Hidden, cl::init(true),
228 cl::desc("Push down local MIs into the next packet"));
229
230static cl::opt<bool> PostSchedOpt("post-sched-opt", cl::Hidden, cl::init(true),
231 cl::desc("Optimize after global scheduling"));
232
233static cl::opt<bool>
234 PostSchedPack("post-sched-packet", cl::Hidden, cl::init(true),
235 cl::desc("Packetize unbundled MIs after global scheduling"));
236
237static cl::opt<bool>
238 NoPredInBundle("nopred-sched-bundle", cl::Hidden,
239 cl::desc("Do not put predicated instructions in bundle"));
240
241static cl::opt<bool>
242 NoSpecInBundle("nospec-sched-bundle", cl::Hidden,
243 cl::desc("Do not put speculated instructions in bundle"));
244
245static cl::opt<bool>
246 EnableSqueeze("try-squeeze-bundle", cl::Hidden, cl::init(true),
247 cl::desc("Try putting 5 instructions in bundle"));
248
249// Defaults to true up to -O2 and to false above it.
251 "prevent-duplex-sep-v2", cl::Hidden, cl::init(true),
252 cl::desc(
253 "Prevent separation of duplex while pullup in global scheduler V2"));
254
255static cl::opt<bool>
256 PullUnsafeMemops("pull-unsafe-memops", cl::Hidden, cl::init(true),
257 cl::desc("Pull up loads which have no memoperands"));
258
259// Run the machine verifier at several stages of the pass (assert builds).
261 "verify-global-sched", cl::Hidden, cl::init(false),
262 cl::desc("Run the machine verifier at several stages of global scheduler"));
263
264static cl::opt<bool>
265 PredicateAllInst("predicate-all-inst", cl::Hidden,
266 cl::desc("Try predicating all possible instructions."));
267
268static cl::opt<bool>
269 SpeculateAllInst("speculate-all-inst", cl::Hidden,
270 cl::desc("Try speculating all possible instructions."));
271
273 "hexagon-pullup-distance", cl::Hidden, cl::init(10),
274 cl::desc("Maximum number of bundles to check for local pull-up"));
275
277 "enable-single-loop-superblock", cl::Hidden, cl::init(true),
278 cl::desc("Enable superblocks consisting of single block loops."));
279
281 "enable-hvx-local-pullup-load-bypass", cl::Hidden, cl::init(true),
282 cl::desc("Enable the HVX local pull-up pass (load bypass only)."));
283
285 "enable-lcgp-for-load-bypass-only", cl::Hidden, cl::init(true),
286 cl::desc("Enable the HVX last chance global pull-up for load-bypass-only"));
287
288// Enables tryTwoLoadCurBypass: a .cur load bypass for a consumer with up to
289// two producers in one packet; the producer that is not the load is moved
290// away by lastChanceGlobalPullup to free a slot. Off by default.
292 "enable-hvx-two-load-cur-bypass", cl::Hidden, cl::init(false),
293 cl::desc("Enable the two-load .cur load-bypass case in local pull-up."));
294
295static cl::opt<bool>
296 EnableHVXLocalPullup("enable-hvx-local-pullup", cl::Hidden, cl::init(true),
297 cl::desc("Enable the HVX local pull-up pass."));
298
300 "enable-hvx-local-pullup-innermost", cl::Hidden, cl::init(false),
301 cl::desc("Enable the HVX local pull-up pass on single block innermost "
302 "loops only."));
303
305 "disable-hvx-sched-superblock", cl::Hidden, cl::init(false),
306 cl::desc("Disable single block loops in superblocks and the HVX local "
307 "pull-up pass."));
308
309static cl::opt<bool>
310 EnableHVXLCGP("enable-hvx-lcgp", cl::Hidden, cl::init(true),
311 cl::desc("Enable the HVX last chance global pull-up pass."));
312
314 "enable-hvx-superblock-heuristic", cl::Hidden, cl::init(true),
315 cl::desc("Run HVX scheduling only on blocks whose ratio of HVX "
316 "instructions exceeds -hvx-sched-profit-ratio."));
317
318static cl::opt<float>
319 HVXSchedProfitRatio("hvx-sched-profit-ratio", cl::Hidden, cl::init(0.80),
320 cl::desc("Ratio of HVX instruction/Total instructions "
321 "for the profitability check."));
322
324 "enable-hlx-load-store-pullup", cl::Hidden, cl::init(true),
325 cl::desc("Pull up HLX .tmp load uses and .new HLX stores to remove the "
326 "copies inserted by HLX load/store expansion"));
327
328static cl::opt<bool>
329 EnableSparsePullup("enable-sparse-pullup", cl::Hidden, cl::init(true),
330 cl::desc("Enable pullup to/from sparse packets"));
331
332/// Enable cluster pullup optimization.
333/// Cluster pullup allows pulling up groups of dependent instructions together,
334/// rather than just individual instructions. This is particularly important for
335/// HVX/HLX instructions where .tmp and .cur dependencies create instruction
336/// chains that must be moved atomically to maintain correctness.
338 "enable-cluster-pullup", cl::Hidden, cl::init(true),
339 cl::desc("Enable pullup for dependent instruction groups"));
340
342
345
346namespace {
347
348typedef MachineBasicBlock::iterator MIIterType;
349typedef MachineBasicBlock::const_iterator MICIterType;
350typedef MachineBasicBlock::instr_iterator MIInstIterType;
351typedef MachineBasicBlock::const_instr_iterator MICInstIterType;
352typedef MachineBasicBlock::reverse_iterator MIRIterType;
353
354// The Scheduler Class.
355class GlobalScheduler : public HexagonPacketizerList {
356public:
357 // Data structure to store the analyzeBranch.
358 // ABI => Analyze Branch Info.
359 struct ABI {
360 MachineBasicBlock *TBB, *FBB;
361 MachineInstr *FirstTerm, *SecondTerm;
363 bool AnalysisValid;
364 ABI()
365 : TBB(NULL), FBB(NULL), FirstTerm(NULL), SecondTerm(NULL),
366 AnalysisValid(false) {}
367 bool analyzeBranch(MachineBasicBlock *MBB, const HexagonInstrInfo *QII,
368 bool PostSched);
369 void dump() {
370 LLVM_DEBUG(if (TBB) dbgs() << "\nTBB: " << TBB->getNumber();
371 if (FBB) dbgs() << ", FBB: " << FBB->getNumber();
372 if (FirstTerm) dbgs() << ", FirstTerm: " << *FirstTerm;
373 if (SecondTerm) dbgs() << ", SecondTerm: " << *SecondTerm);
374 }
375 };
376 struct AnalyzeBranchInfo_t {
377 typedef std::map<MachineBasicBlock *, ABI> BranchAnalyses_t;
378 BranchAnalyses_t BranchAnalyses;
379
380 // It always returns an ABI so the caller should check if the
381 // branch analysis was valid or not.
382 ABI &getOrCreate(MachineBasicBlock *MBB, const HexagonInstrInfo *QII,
383 bool PostSched = false) {
384 ABI &abi = BranchAnalyses[MBB];
385 if (!abi.AnalysisValid)
386 abi.analyzeBranch(MBB, QII, PostSched);
387 return abi;
388 }
389 void invalidate(MachineBasicBlock *MBB) {
390 iterator it = BranchAnalyses.find(MBB);
391 assert((it != BranchAnalyses.end()) &&
392 "Cannot invalidate un-analyzed branch.");
393 BranchAnalyses.erase(it);
394 }
395 bool hasABInfo(MachineBasicBlock *MBB) const {
396 return BranchAnalyses.find(MBB) != BranchAnalyses.end();
397 }
398
399 typedef BranchAnalyses_t::iterator iterator;
400 typedef BranchAnalyses_t::const_iterator const_iterator;
401 typedef BranchAnalyses_t::size_type size_type;
402
403 iterator begin() { return BranchAnalyses.begin(); }
404 const_iterator begin() const { return BranchAnalyses.begin(); }
405 iterator end() { return BranchAnalyses.end(); }
406 const_iterator end() const { return BranchAnalyses.end(); }
407 bool empty() const { return BranchAnalyses.empty(); }
408 void clear() { BranchAnalyses.clear(); }
409 size_type size() const { return BranchAnalyses.size(); }
410 };
411
412 // Data structure to store a scheduling region.
413 struct SchedulingRegion_t {
414 typedef SmallVector<MachineBasicBlock *, 2> SRMembers_t;
415 typedef MachineBasicBlock SRAtom_t;
416 BranchProbability EdgeProb;
417 SRMembers_t Members;
418 SchedulingRegion_t() : EdgeProb(BranchProbability::getZero()) {}
419
420 void addSRMember(MachineBasicBlock *MBB) { Members.push_back(MBB); }
421
422 void dump() {
423 SmallVector<MachineBasicBlock *, 2>::iterator MBBI = Members.begin();
424 while (MBBI != Members.end()) {
425 LLVM_DEBUG(dbgs() << "\tBB#" << (*MBBI)->getNumber(););
426 ++MBBI;
427 }
428 }
429 typedef SRMembers_t::iterator iterator;
430 typedef SRMembers_t::reverse_iterator reverse_iterator;
431 typedef SRMembers_t::const_iterator const_iterator;
432 typedef SRMembers_t::const_reverse_iterator const_reverse_iterator;
433 typedef SRMembers_t::size_type size_type;
434
435 iterator begin() { return Members.begin(); }
436 const_iterator begin() const { return Members.begin(); }
437 reverse_iterator rbegin() { return Members.rbegin(); }
438 const_reverse_iterator rbegin() const { return Members.rbegin(); }
439 iterator end() { return Members.end(); }
440 const_iterator end() const { return Members.end(); }
441 reverse_iterator rend() { return Members.rend(); }
442 const_reverse_iterator rend() const { return Members.rend(); }
443 bool empty() const { return Members.empty(); }
444 void clear() { Members.clear(); }
445 size_type size() const { return Members.size(); }
446 bool operator<(const SchedulingRegion_t &RHS) {
447 return EdgeProb < RHS.EdgeProb;
448 }
449 bool operator<=(const SchedulingRegion_t &RHS) const {
450 return EdgeProb <= RHS.EdgeProb;
451 }
452 bool operator>(const SchedulingRegion_t &RHS) const {
453 return EdgeProb > RHS.EdgeProb;
454 }
455 bool operator>=(const SchedulingRegion_t &RHS) const {
456 return EdgeProb >= RHS.EdgeProb;
457 }
458 };
459
460 using Dependency = HexagonInstrInfo::Dependency;
461
462 // Typedefs.
463 typedef SmallVector<SchedulingRegion_t, 2> SchedulingRegions_t;
464 typedef DenseMap<SchedulingRegion_t::SRAtom_t *,
466 PulledUpII;
467
468 // Constructor.
469 GlobalScheduler(const HexagonTargetMachine *tm, const HexagonInstrInfo *qii,
470 const HexagonRegisterInfo *tri, MachineFunction &mf,
471 MachineLoopInfo &mli, AliasAnalysis *aa,
472 const MachineBranchProbabilityInfo *mbpi,
473 HexagonLiveVariables *hlv)
474 : HexagonPacketizerList(mf, mli, aa, mbpi, false), TM(tm), QII(qii),
475 TRI(tri), HLV(hlv), MF(mf), MLI(mli), GlobalSpeculatedIns(0),
476 GlobalPredicatedIns(0), LocalPullups(0), SafetyBuffer(200),
477 SafetyBufferDelta(50) {
478 useHVXOps = mf.getSubtarget<HexagonSubtarget>().useHVXOps();
479 useHLXOps = mf.getSubtarget<HexagonSubtarget>().useHLXOps();
480 // TinyCore has different scheduling constraints and resource limits.
481 // Track this to adjust scheduling heuristics accordingly.
482 IsTinyCore = mf.getSubtarget<HexagonSubtarget>().isTinyCore();
483 }
484
485 // Dummy addtoPacket to emulate packetization.
486 MachineBasicBlock::iterator addToPacketPseudo(MachineInstr *MI);
487 void initPacketizerStateLoc();
488 // Is it legal to packetize \p MI with instructions in DestPack.
489 bool isLegalToPacketizeWith(MIIterType DestPack, MachineInstr *MI);
490 // Mimics Packetizers isLegalToPacketizeTogether, plus some more checks.
491 inline bool isLegalToPacketizeTogetherMI(MachineInstr *BI, MachineInstr *MI);
492 // Instructions for which pulled up is disabled
493 inline bool shouldNotBePulledUp(const MachineInstr *MI) const;
494
495 /// Check if it is legal to pull up ToMove across MI during scheduling.
496 /// This function determines if MI is a "barrier" instruction that ToMove
497 /// cannot be moved past.
498 /// \param MI The instruction that might block the move
499 /// \param ToMove The instruction being considered for pullup (optional)
500 /// \param IsMIInDestBundle True if MI is in the destination bundle where
501 /// ToMove will be inserted
502 /// \return true if ToMove should NOT cross MI (i.e., MI is a barrier)
503 inline bool shouldNotBeCrossed(const MachineInstr *MI,
504 const MachineInstr *ToMove,
505 bool IsMIInDestBundle = false) const;
506 // Reserve the resources for Bundle in the resource tracker.
507 // Make compound/duplex instructions when \p Squeeze=true.
508 void getResourcesReadyForBundle(MIInstIterType MII, bool Squeeze = false,
509 MachineInstr *InstrToSkip = nullptr);
510 MachineInstr *generateCompoundIfPossible(MIInstIterType MII,
511 MIInstIterType &GA,
512 MIInstIterType &GB);
513 // TODO: Once MCShuffler can accept bundles with five instructions remove
514 // this function.
515 void generateCompoundsPostSched();
516
517 // Functions to optimize for auto-and predicates
518 bool failsSpecialConditions(MachineInstr *BundleMI, Register DestReg);
519 bool canNewifyPredReg(unsigned Reg, MICInstIterType Producer,
520 MICInstIterType Sentinel) const;
521 bool getDefinitions(MachineInstr *MI, MachineInstr *&Def1,
522 MachineInstr *&Def2, MachineInstr *&Def3);
523 void generateAutoAndPredicates(MachineFunction &MF);
524
525 void packetize();
526 // Returns true if resources are available for MII in the current packet.
527 // Takes into account const-extenders as well.
528 bool canReserveResources(MIInstIterType MII) const;
529 // The usage of \p Reg is replaced by \p ScratchReg.
530 void replaceUsageOfReg(unsigned Reg, unsigned ScratchReg,
531 MachineBasicBlock *MBB,
532 const MachineInstr *ExceptMI = NULL) const;
533 inline void markLiveInsAsUsed(std::unique_ptr<RegScavenger> &RS,
534 MachineBasicBlock *MBB) const;
535 inline void markLiveOutsAsUsed(std::unique_ptr<RegScavenger> &RS,
536 MachineBasicBlock *MBB) const;
537 void markAllRegsAsUsed(std::unique_ptr<RegScavenger> &RS,
538 const MachineBasicBlock *MBB) const;
539 MachineBasicBlock *splitCriticalEdge(MachineBasicBlock *FromBB,
540 MachineBasicBlock *ToBB,
541 MachineBasicBlock *LP);
542 bool hasOneDef(const MachineInstr *MI, unsigned &DefR) const;
543 bool hasOneUse(const MachineInstr *MI, unsigned &UseR) const;
544 bool hasOneDefAndUse(const MachineInstr *MI, unsigned &Def,
545 unsigned &Use) const;
546 MICInstIterType laterOfTheTwo(MICInstIterType I1, MICInstIterType I2,
547 MICInstIterType Sentinel) const;
548 // Supporting API to figure out if the branching instruction MII,
549 // is followed by non-branching instruction.
550 bool branchesInBetweenMBB(MIInstIterType MII, MachineBasicBlock *MBB);
551
552 bool splitMBBAt(MIInstIterType MII, MachineBasicBlock *MBB);
553
554 // Generates control flow by removing 3 way branching.
555 void generateCFG(MachineFunction &MF);
556
557 virtual void schedule() = 0;
558
559 // Mostly branch related optimizations.
560 void performExposedOptimizations();
561 void removeEmptyMBB(MachineBasicBlock *MBB);
562 bool makeAsLayoutSuccessor(MachineBasicBlock *BB1, MachineBasicBlock *BB2);
563 bool removeRedundantBranches(MachineBasicBlock *MBB, MachineBasicBlock *TBB,
564 MachineInstr *FirstTerm, MachineBasicBlock *FBB,
565 MachineInstr *SecondTerm);
566 bool optimizeDualJumps(MachineBasicBlock *MBB, MachineBasicBlock *TBB,
567 MachineInstr *FirstTerm, MachineBasicBlock *FBB,
568 MachineInstr *SecondTerm);
569 MachineBasicBlock *optimizeBranches(MachineBasicBlock *MBB,
570 MachineBasicBlock *TBB,
571 MachineInstr *FirstTerm,
572 MachineBasicBlock *FBB);
573 // A region could be a set of MBBs (Hyperblocks)
574 // where scheduling algorithms could work. Default scheduling region
575 // consists of MBBs where there is a single entry point i.e., the head
576 // of scheduling region. It has at least one exit point i.e., the tail
577 // of the scheduling region.
578 // Criteria of HEAD of a scheduling region (Superblock).
579 // 1. MF.begin()
580 // 2. MBB with more than one successor:
581 // - Can be part of multiple scheduling regions.
582 // For simplicity we'll make this as HEAD as well. This lets us not
583 // worry about the loop as a special case.
584 // 3. MBB with more than one predecessor:
585 // - Will always be (if at all) the HEAD of the scheduling region.
586 virtual void formSchedulingRegions(MachineFunction &MF);
587
588 void printSchedulingRegions() {
590 SchedulingRegions.begin();
591 SRI != SchedulingRegions.end(); ++SRI) {
592 dbgs() << "\nScheduling Region: ";
593 SRI->dump();
594 } dbgs() << "\nTotal Scheduling Regions: "
595 << SchedulingRegions.size() << "\n";);
596 }
597
598 // PruneCriteria returns true if that scheduling region can be removed.
599 typedef bool (GlobalScheduler::*PruneCriteriaFP)(SchedulingRegion_t &) const;
600
601 // Decides whether a scheduling region is to be kept for scheduling.
602 // Returns true when it is okay to remove that region.
603 bool pruneCriteria(SchedulingRegion_t &SR) const {
604 assert(!SR.Members.empty() && "Empty Scheduling region.");
605 if (SR.Members.size() == 1)
606 return true;
607 // If the members are not in the same loop then remove the SR.
608 // We do not want to speculate from outside of loop into the loop body,
609 // unless in a very special case which we deal with in speculateMI.
610 MachineLoop *HeadLI = MLI.getLoopFor(SR.Members[0]);
611 MachineLoop *LeafLI = MLI.getLoopFor(SR.Members[1]);
612
613 bool speculateInnerToOuter = false;
614 if (EnableSingleLoopSuperblock && useHVXOps &&
616 if (HeadLI != nullptr && LeafLI != nullptr) {
617 if (HeadLI->getLoopDepth() < LeafLI->getLoopDepth())
618 speculateInnerToOuter = true;
619 }
620 }
621
622 if (HeadLI != LeafLI && !speculateInnerToOuter)
623 return true;
624 return false;
625 }
626
627 // Removes scheduling regions which cannot/need-not be scheduled.
628 virtual void pruneSchedulingRegions(PruneCriteriaFP PC);
629
630 // Prefers scheduling regions with high branch probability.
631 virtual void sortSchedulingRegions();
632
633 bool isSuperblockLoop(MachineLoop *L);
634 virtual bool isProfitableToScheduleHVX(MachineLoop *L);
635 virtual bool isProfitableToScheduleHVX(MachineBasicBlock *MBB);
636
637protected:
638 // Member variables.
639 const HexagonTargetMachine *TM;
640 const HexagonInstrInfo *QII;
641 const HexagonRegisterInfo *TRI;
642 HexagonLiveVariables *HLV;
643 MachineFunction &MF;
644 MachineLoopInfo &MLI;
645
646 // Since we need to use analyze branch a lot. It is better to save the
647 // analyzeBranch information. Care, however, must be taken to update
648 // this object whenever a basic block is changed.
649 AnalyzeBranchInfo_t AnalyzeBranchInfo;
650 SchedulingRegions_t SchedulingRegions;
651 // Locations where more opportunities of packetization are possible.
652 SmallVector<MachineInstr *, 4> SpecPacketOpp;
653 // Set of bundles which have compound instructions. We need to generate
654 // compound because MCShuffler rejects bundles with five instructions.
655 SmallSetVector<MachineInstr *, 4> ToBeSqueezed;
656 // Ignore any post-sched opts on these MBBs.
657 SmallVector<MachineBasicBlock *, 1> IgnorePostSchedOpt;
658 // List of Speculated instructions inside each MBB (MBB is the destination)
659 PulledUpII SpeculatedIns;
660 // Global pull up from an MBB creates scope for local push-down.
661 // LocalMergePackCand keeps the list of MBBs from where MI was pulled-up.
662 SetVector<MachineBasicBlock *> LocalMergePackCand;
663 // Single block loops for HVX local pullup pass.
664 std::unordered_map<MachineBasicBlock *, float> ProfitableHVXBlocks;
665 unsigned GlobalSpeculatedIns;
666 unsigned GlobalPredicatedIns;
667 unsigned LocalPullups;
668 const unsigned SafetyBuffer;
669 // In case when MBBs are moved in between Jump and their targets.
670 int SafetyBufferDelta;
671 // Is HVX support enabled?
672 bool useHVXOps = false;
673 // Is HLX support enabled?
674 bool useHLXOps = false;
675 // Is target CPU TinyCore? TinyCore has reduced resources and different
676 // scheduling constraints compared to full Hexagon cores.
677 bool IsTinyCore = false;
678};
679
680class GreedyPullup : public GlobalScheduler {
681public:
682 GreedyPullup(const HexagonTargetMachine *tm, const HexagonInstrInfo *qii,
683 const HexagonRegisterInfo *tri, MachineFunction &mf,
684 MachineLoopInfo &mli, AliasAnalysis *aa,
685 const MachineBranchProbabilityInfo *mbpi,
686 HexagonLiveVariables *hlv)
687 : GlobalScheduler(tm, qii, tri, mf, mli, aa, mbpi, hlv) {}
688
689 void schedule() override {
690 for (SchedulingRegions_t::iterator SRI = SchedulingRegions.begin();
691 SRI != SchedulingRegions.end(); ++SRI) {
692 unsigned currSpec = GlobalSpeculatedIns;
693 unsigned currPred = GlobalPredicatedIns;
694 globalPullup(*SRI);
695 LLVM_DEBUG(SRI->dump(););
696 (void)currSpec;
697 (void)currPred;
699 dbgs() << "\n\nCurrent BB Global Pullup stats: Speculated Ins: "
700 << GlobalSpeculatedIns - currSpec
701 << ", Predicated Ins: " << GlobalPredicatedIns - currPred;);
702 }
703
705
707 while (MBBI != MF.end()) {
708 LocalPullups = 0;
709 if (!MBBI->empty() && // Empty elements in a scheduling region.
710 std::find(IgnorePostSchedOpt.begin(), IgnorePostSchedOpt.end(),
711 &*MBBI) == IgnorePostSchedOpt.end()) { // Ignorable MBB?
712 localPullupHLX(&*MBBI);
713 localPullup(&*MBBI);
714 localPullupHVX(&*MBBI);
715 }
716
717 ++MBBI;
719 dbgs() << "\n\nCurrent BB Local Pullup stats: Speculated Ins: "
720 << LocalPullups;);
721 // TODO: Keep track of MBBs where LocalPullup > 0. Then we can do
722 // global scheduling in the regions having this MBB as more
723 // opportunities might have arisen.
724 HexagonGSLocalPullups += LocalPullups;
725 }
726
727 // Merge an instruction into adjacent packet.
729 mergePackets();
730
731 HexagonGSGlobalPullups = GlobalPredicatedIns + GlobalSpeculatedIns;
732
734 dbgs() << "\n\n**********Total Greedy Pullup stats**********"
735 << "\nGlobal speculated instructions: " << GlobalSpeculatedIns
736 << "\nGlobal predicated instructions: " << GlobalPredicatedIns
737 << "\nLocal speculated instruction: " << HexagonGSLocalPullups
738 << "\n";);
739 }
740
741 // Check if moving SrcMI to DestBundle will cause an interlock stall.
742 bool canCauseInterlockStall(MIInstIterType DestBundle, MachineInstr *SrcMI,
743 const InstrItineraryData *II);
744 // Generate the load-bypass (.cur) after moving InstrToMove after LoadInstr.
745 void genLoadBypass(MachineInstr *LoadInstr, MachineInstr *InstrToMove);
746 // Returns true if a single RAW dependence on \p DepTrue (a .cur-able HVX
747 // load in DestBundle) can be satisfied via a .cur load bypass when pulling
748 // up a consumer. \p PktEnd bounds the destination packet for the
749 // no-other-consumer safety check.
750 bool canGenCurBypass(MIInstIterType DestBundle, MachineInstr *DepTrue,
751 MIInstIterType PktEnd, int DstDep,
752 MachineInstr *Consumer,
753 const MachineInstr *Exempt = nullptr);
754 // Two-load .cur bypass: try to pull \p SrcMI (a single consumer with two
755 // RAW producers sharing a packet, one a .cur-able load) into \p DestBundle,
756 // relocating the other producer via lastChanceGlobalPullup. Returns true if
757 // the candidate was handled (moved); iterators are updated in place.
758 bool tryTwoLoadCurBypass(MIIterType &BI, SchedulingRegion_t::SRAtom_t *SR,
759 MIInstIterType &DestBundle, MIIterType &SrcBundle,
760 MIIterType &NextBI, bool isNextBISrc,
761 MIIterType &Next, MachineInstr *SrcMI,
762 SmallPtrSetImpl<MachineInstr *> &PulledUpSet);
763 void localPullupHVX(SchedulingRegion_t::SRAtom_t *SR);
764 // Shared local pullup engine used by localPullup (HVXMode=false) and
765 // localPullupHVX (HVXMode=true).
766 void localPullupImpl(SchedulingRegion_t::SRAtom_t *SR, bool HVXMode);
767 // Pullup HLX instructions to eliminate copies inserted for
768 // .new HLX store and .tmp HLX load
769 void localPullupHLX(SchedulingRegion_t::SRAtom_t *SR);
770 void localPullupHLXLoadUses(SchedulingRegion_t::SRAtom_t *SR,
771 MachineInstr *HLXLoadMI, MachineInstr *HLXCopyMI);
772 void localPullupHLXStore(SchedulingRegion_t::SRAtom_t *SR,
773 MachineInstr *HLXStoreMI, MachineInstr *HLXCopyMI);
774 // Within an MBB
775 void localPullup(SchedulingRegion_t::SRAtom_t *SR);
776 // Local push-down of MI into adjacent packets.
777 bool mergePacketsAround(const SmallVectorImpl<MachineInstr *> &Candidates);
778 bool mergePackets();
779 // Across MBBs
780 void globalPullup(SchedulingRegion_t &SR);
781 // Returns true if MI can be speculated (without predication)
782 // from \p SrcBB to \p DstBB
783 bool canMIBeSpeculated(MachineInstr *MI, MachineBasicBlock *SrcBB,
784 MachineBasicBlock *DstBB, MIIterType &TargetPacket);
785 // Safety checks for instructions e.g., load, store etc.
786 bool safeToSpeculate(MachineInstr *MI, MachineBasicBlock *DstBB) const;
787
788 bool preciousMICanBeSpeculated(MachineInstr *MI, MachineBasicBlock *SrcBB,
789 MachineBasicBlock *DstBB,
790 MachineBasicBlock *OtherBB,
791 MIIterType &TargetPacket,
792 unsigned ApproachNum);
793 inline bool preciousToSpeculate(const MachineInstr *MI,
794 const MachineBasicBlock *SrcBB,
795 const MachineBasicBlock *DstBB,
796 const MachineBasicBlock *OtherBB) const;
797 inline bool preciousToPredicate(const MachineInstr *MI,
798 const MachineBasicBlock *SrcBB,
799 const MachineBasicBlock *DstBB,
800 const MachineBasicBlock *OtherBB) const;
801
802 // Returns true if MI can be speculatively executed (with predication)
803 // from \p SrcBB to \p DstBB
804 bool canMIBePredicated(MachineInstr *MI, MachineBasicBlock *SrcBB,
805 MachineBasicBlock *DstBB, MIIterType &TargetPacket,
806 MICInstIterType &WithinPacket, bool &NeedToNewify,
807 bool &Precious);
808 // Returns the position *before* which \p MI could be inserted.
809 // In case of BUNDLE the \p MI can be inserted within that BUNDLE.
810 // It will try to take an extra step in accommodating the \p SrcMI when
811 // \p SpecPreciousMI=true.
812 MIIterType findInsertPtSpec(MachineInstr *SrcMI, MachineBasicBlock *DstBB,
813 bool SpecPreciousMI, bool SpecPreciousMIComp,
814 bool GlobalPrecious = false);
815 // Returns the position *before* which \p MI could be inserted.
816 // In case of BUNDLE the \p MI can be inserted within that BUNDLE.
817 // @note: The SrcMI can be modified by this function.
818 MIIterType findInsertPtPred(MachineInstr *SrcMI, MachineBasicBlock *DstBB,
819 bool &NeedToNewify, MICInstIterType &WithinPacket,
820 bool PredPreciousMI = false);
821 // Returns true if MI was successfully speculated.
822 bool speculateMI(MachineInstr *MI, MachineBasicBlock *SrcBB,
823 MachineBasicBlock *DstBB, MIIterType DstPos);
824 // Returns true if MI was successfully speculated.
825 bool predicateMI(MachineInstr *MI, MachineBasicBlock *SrcBB,
826 MachineBasicBlock *DstBB, MIIterType DstPack,
827 MICInstIterType WithinPacket, bool NeedToNewify,
828 bool Precious);
829 // Is it okay to execute MI as the first instruction in the MBB.
830 MIIterType findInsertionPtSpecLocal(MachineInstr *MI);
831
832 /// Check dependencies between MII and instructions in range [DestBeg,
833 /// DestEnd). This is used during pullup to ensure moving MII to the
834 /// destination doesn't violate dependencies. [DestBeg, DestEnd) can
835 /// span multiple bundles.
836 /// \param DestBeg Start of destination range
837 /// \param DestEnd End of destination range
838 /// \param MII Instruction being checked for dependencies
839 /// \param DepTrue Output: iterator to true (RAW) dependency if found
840 /// \param DepAnti Output: iterator to anti (WAR) dependency if found
841 /// \param HLXUseReg Optional: specific register to check for HLX
842 /// dependencies
843 /// \param isPullDown True if checking for pulldown (vs pullup) operation
844 /// \return Dependency flags indicating type of dependencies found
845 int dstDependence(MICInstIterType DestBeg, MICInstIterType DestEnd,
846 MICInstIterType MII, MICInstIterType &DepTrue,
847 MICInstIterType &DepAnti, unsigned HLXUseReg = 0,
848 bool IsPullDown = false) const;
849 // A more exhaustive dependence analysis for load bypass, more aggressive
850 // moves, etc. Used from the HVX local pullup.
851 int dstDependence(MICInstIterType DestBeg, MICInstIterType DestEnd,
852 MICInstIterType MII,
853 std::vector<const MachineInstr *> &DepTrueVec,
854 std::vector<const MachineInstr *> &DepAntiVec,
855 std::vector<const MachineInstr *> &DepOutputVec,
856 std::vector<unsigned> *Regs = nullptr) const;
857 // Dependence within the same packet [SrcBeg, SrcEnd).
858 int srcDependence(MIInstIterType SrcBeg, MIInstIterType SrcEnd,
859 MIInstIterType RMII,
860 SmallSetVector<MachineInstr *, 4> *DepSet = nullptr) const;
861 bool singleTrueDep(MICInstIterType SrcBeg, MICInstIterType SrcEnd,
862 MICInstIterType MII, unsigned &Reg) const;
863 bool lastChanceGlobalPullup(MIInstIterType &BundleHead,
864 MIInstIterType InstrToMove,
865 const MachineInstr *LoadBypassCand = nullptr);
866 bool isLoopInvariant(MachineInstr &MI);
867 MachineInstr *isLastChanceGlobalPullupCand(const MachineInstr *MI);
868};
869
870class HexagonGlobalSchedulerV2 : public MachineFunctionPass {
871public:
872 static char ID;
873
874 HexagonGlobalSchedulerV2() : MachineFunctionPass(ID), GS(nullptr) {
876 }
877
878 StringRef getPassName() const override {
879 return "Hexagon Global Scheduler V2";
880 }
881
882 void getAnalysisUsage(AnalysisUsage &AU) const override {
883 AU.addRequired<AAResultsWrapperPass>();
884 AU.addRequired<HexagonLiveVariables>();
885 AU.addRequired<MachineBranchProbabilityInfoWrapperPass>();
886 AU.addRequired<MachineLoopInfoWrapperPass>();
888 }
889
890 bool runOnMachineFunction(MachineFunction &MF) override;
891
892private:
893 // Generates control flow by removing 3 way branching.
894 inline void generateCFG(MachineFunction &MF);
895
896 // Run the machine verifier when -verify-global-sched is set.
897 bool verifyMachineFunction(MachineFunction &MF, StringRef msg) {
899 MF.verify(this, msg.data());
900 return true;
901 }
902
903 // Member variables.
904 const HexagonTargetMachine *TM;
905 const HexagonInstrInfo *QII;
906 const HexagonRegisterInfo *TRI;
907 std::unique_ptr<GlobalScheduler> GS;
908};
909
910char HexagonGlobalSchedulerV2::ID = 0;
911
912} // namespace
913
914INITIALIZE_PASS(HexagonGlobalSchedulerV2, "global-schedV2",
915 "Hexagon Global Scheduler V2", false, false)
916
917//===----------------------------------------------------------------------===//
918// static/inline Functions
919//===----------------------------------------------------------------------===//
921 return MI->getOpcode() == Hexagon::Y2_barrier;
922}
923
924// Heuristic to determine whether to run the HVX local pull-up pass.
925bool GlobalScheduler::isProfitableToScheduleHVX(MachineBasicBlock *MBB) {
927 return true;
928 auto [It, Inserted] = ProfitableHVXBlocks.try_emplace(MBB);
929 if (!Inserted)
930 return It->second > HVXSchedProfitRatio;
931
932 unsigned NumHVXInst = 0, NumTotalInst = 0;
933 for (MIInstIterType II = MBB->instr_begin(), End = MBB->instr_end();
934 II != End; ++II) {
935 if (II->isBundle())
936 continue;
937 if (QII->isHVXVec(*II))
938 ++NumHVXInst;
939 ++NumTotalInst;
940 }
941 if (NumTotalInst == 0)
942 It->second = 0;
943 else
944 It->second = (float)NumHVXInst / (float)NumTotalInst;
945 return It->second > HVXSchedProfitRatio;
946}
947
948// This heuristic can be tuned to allow/disallow formation of superblocks
949// containing single block innermost loops. Currently, it's a simple ratio
950// of HVX vs non-HVX instructions.
951bool GlobalScheduler::isProfitableToScheduleHVX(MachineLoop *L) {
952 assert(L->getNumBlocks() == 1 && "Expecting a single block loop");
954 return true;
955 auto *BB = L->getBlocks()[0];
956 return isProfitableToScheduleHVX(BB);
957}
958
959// We allow single block innermost loops to be a part of the superblock to
960// attempt to schedule them,
961bool GlobalScheduler::isSuperblockLoop(MachineLoop *L) {
962 if (!EnableSingleLoopSuperblock || !useHVXOps ||
964 return false;
965 if (!L || L->getNumBlocks() != 1 || !L->isInnermost())
966 return false;
967 if (L->getBlocks()[0]->succ_size() < 2)
968 return false;
969 if (L->getBlocks()[0]->pred_size() != 2)
970 return false;
971
972 return isProfitableToScheduleHVX(L);
973}
974
975bool GlobalScheduler::shouldNotBePulledUp(const MachineInstr *MI) const {
976 // Allow .new HLX store to be pulled up
977 if (MI->getOpcode() == Hexagon::LX_S16b_new)
978 return false;
979 if (MI->mayStore() || MI->isCall() || MI->isBarrier() || MI->isInlineAsm() ||
980 MI->hasUnmodeledSideEffects() || MI->isEHLabel() || isSchedBarrier(MI))
981 return true;
982 if (MI->isBundle() || MI->isDebugInstr())
983 return true;
984 // Loads with ordered (volatile) memoperands. Assuming loads with empty
985 // memoperands are safe to pull unlike MachineInstr::hasOrderedMemoryRef.
986 if (PullUnsafeMemops && MI->memoperands_empty())
987 return false;
988 return MI->hasOrderedMemoryRef();
989}
990
991/// Determines if MI is a barrier that prevents ToMove from being pulled up past
992/// it. This function implements the core safety checks for instruction
993/// reordering.
994///
995/// Key rules:
996/// - Returns, calls, inline asm, EH labels, Y2_barrier and instructions with
997/// unmodeled side effects are always barriers.
998/// - A load or store is a barrier when ToMove is unknown.
999/// - MI does not block ToMove when both may load.
1000/// - A .tmp or .cur load in the destination bundle (IsMIInDestBundle) does not
1001/// block a store, because it executes early in the packet.
1002/// - Otherwise, a memory access blocks ToMove when areMemAccessesDependent
1003/// says they may alias.
1004bool GlobalScheduler::shouldNotBeCrossed(const MachineInstr *MI,
1005 const MachineInstr *ToMove,
1006 bool IsMIInDestBundle) const {
1007 if (MI->isBundle() || MI->isDebugInstr())
1008 return false;
1009
1010 if (MI->isReturn() || MI->isCall() || MI->hasUnmodeledSideEffects() ||
1011 MI->isInlineAsm() || MI->isEHLabel() || isSchedBarrier(MI))
1012 return true;
1013
1014 // MI is not a load or store
1015 if (!MI->mayLoadOrStore())
1016 return false;
1017
1018 // MI is load or store, but we do not know what is ToMove
1019 if (!ToMove)
1020 return true;
1021
1022 // MI is load or store, ToMove is not a load or store
1023 if (!ToMove->mayLoadOrStore())
1024 return false;
1025
1026 if (MI->mayLoad()) {
1027 // If MI is a load and ToMove are loads, MI and ToMove can be reordered
1028 if (ToMove->mayLoad())
1029 return false;
1030
1031 // MI is a load and ToMove is a store
1032 // If MI is in DestBundle, ignore dependence if the load is a .tmp or .cur
1033 // .tmp and .cur loads execute early
1034 if (IsMIInDestBundle && (QII->isDotTmpInst(*MI) || QII->isDotCurInst(*MI)))
1035 return false;
1036 }
1037 return QII->areMemAccessesDependent(AA, MI, ToMove);
1038}
1039
1040static std::vector<const MachineOperand *>
1042 std::vector<const MachineOperand *> regmaskMOs;
1043 for (MICInstIterType II = MBB.instr_begin(), End = MBB.instr_end(); II != End;
1044 ++II) {
1045 if (II->isBundle() || II->isDebugInstr())
1046 continue;
1047 for (auto &MO : II->operands())
1048 if (MO.isRegMask())
1049 regmaskMOs.push_back(&MO);
1050 }
1051 return regmaskMOs;
1052}
1053
1054// Check if MI is invariant in a single-block loop.
1055// 1) All its uses are loop invariant
1056// 2) It's not redefined
1057// Call-clobbered registers are found from the regmask operands in the block.
1058bool GreedyPullup::isLoopInvariant(MachineInstr &MI) {
1059 auto *MBB = MI.getParent();
1060 MachineLoop *Loop = MLI.getLoopFor(MBB);
1061 if (!Loop)
1062 return true;
1063 if (!isSuperblockLoop(Loop))
1064 return false;
1065 MICInstIterType DefUseR = MBB->instr_end();
1066
1067 for (const MachineOperand &MO : MI.operands()) {
1068 if (!MO.isReg())
1069 continue;
1070 unsigned Op = MO.getReg();
1071 if (MO.isUse()) {
1072 if (HLV->isDefinedWithin(MBB->instr_begin(), MBB->instr_end(), Op,
1073 DefUseR))
1074 return false;
1075 } else if (MO.isDef()) {
1076 if (!MO.isDead()) {
1077 if (HLV->isDefinedWithin(std::next(MI.getIterator()), MBB->instr_end(),
1078 Op, DefUseR) ||
1079 HLV->isDefinedWithin(MBB->instr_begin(), MI.getIterator(), Op,
1080 DefUseR))
1081 return false;
1082
1083 // Not a candidate if it's live out
1084 for (MCRegAliasIterator AI(Op, TRI, true); AI.isValid(); ++AI)
1085 if (HLV->isLiveOut(MBB, *AI))
1086 return false;
1087 }
1088 }
1089 auto regmaskMOs = collectRegmaskMOs(*MBB);
1090 for (auto *MO : regmaskMOs)
1091 if (MO->clobbersPhysReg(Op))
1092 return false;
1093 }
1094 return true;
1095}
1096
1097// Get the iterators corresponding to the BUNDLE enclosing MI.
1098// If MI is not inside the bundle it returns MI as the first element
1099// and the MI+1, as the second element.
1100static std::pair<MIInstIterType, MIInstIterType>
1102 MIInstIterType BundleStart = getBundleStart(MI->getIterator());
1103 MIInstIterType BundleEnd = getBundleEnd(MI->getIterator());
1104 return std::make_pair(BundleStart, BundleEnd);
1105}
1106
1107// Checks if the bundle has at least 2 instructions.
1108// If not then unbundles the instructions and save in SpecScope (if provided).
1109static MachineInstr *
1111 SmallVectorImpl<MachineInstr *> *SpecScope = nullptr) {
1112 unsigned Size = QII->nonDbgBundleSize(BundleHead);
1113 if (Size >= 2)
1114 return nullptr;
1115 MachineInstr *MI = nullptr;
1116 if (Size == 1) {
1117 // Since bundle may have debug instructions.
1118 MIInstIterType BundleEnd = getBundleEnd(BundleHead->getIterator());
1119 MIInstIterType MIter = BundleHead->getIterator();
1120 ++MIter; // Skip the bundle header.
1121 while (MIter != BundleEnd) {
1122 MI = &*(MIter++);
1123 MI->unbundleFromPred();
1124 if (SpecScope)
1125 SpecScope->push_back(MI);
1126 }
1127 }
1128 // In case a bundle full of debug instructions get here.
1129 assert(BundleHead->getBundleSize() == 0);
1130 BundleHead->eraseFromParent();
1131 return MI; // if non-nullptr, point to the instruction
1132}
1133
1134// When MI is removed from a two-instruction bundle, the other instruction
1135// becomes unbundled. Return it in singleInstr.
1136static MachineInstr *
1138 SmallVectorImpl<MachineInstr *> *SpecPacketOpp = nullptr,
1139 MachineInstr **singleInstr = nullptr) {
1140 MachineInstr *NewSingleInstr = nullptr;
1141 MachineInstr *MIP = nullptr;
1142 if (MI->isBundled()) {
1143 MachineInstr *Bundle = &*getBundleStart(MI->getIterator());
1144 MIP = MI->removeFromBundle();
1145 NewSingleInstr = updateBundle(Bundle, QII, SpecPacketOpp);
1146 } else
1147 MIP = MI->removeFromParent();
1148
1149 if (singleInstr)
1150 *singleInstr = NewSingleInstr;
1151 return MIP;
1152}
1153
1154// TODO: Preprocess the MachineFunction to collect these
1155// information so that we don't have to loop over and over again.
1156// Use analyzebranch data (the cond vector)
1159 while (MII != MBB->instr_end()) {
1160 if ((MII->getOpcode() == Hexagon::ENDLOOP0) ||
1161 (MII->getOpcode() == Hexagon::ENDLOOP1))
1162 return true;
1163 ++MII;
1164 }
1165 return false;
1166}
1167
1168static void transferLiveIns(const MachineBasicBlock *From,
1169 MachineBasicBlock *To) {
1170 // Update liveins all at once.
1172 it != From->livein_end(); ++it) {
1173 if (!To->isLiveIn((*it).PhysReg))
1174 To->addLiveIn(*it);
1175 }
1176}
1177
1178// Returns true if Iter is a barrier and if there are other barriers
1179// 'after' Iter.
1180static bool inBetweenBarriers(MICIterType Iter,
1181 const MachineBasicBlock *DstBB) {
1182 MICIterType TestIt = DstBB->begin();
1183 // If Iter is after a Barrier.
1184 while (TestIt != Iter) {
1185 if (Iter->isBarrier())
1186 return true;
1187 ++TestIt;
1188 }
1189 // No barrier before Iter and Iter is not a barrier => okay.
1190 if (!Iter->isBarrier())
1191 return false;
1192 // Iter is a barrier, there should not be a barrier after Iter.
1193 while (Iter != DstBB->end()) {
1194 if (Iter->isBarrier())
1195 return true;
1196 ++Iter;
1197 }
1198 return false;
1199}
1200
1201// Blocks should be considered empty if they contain only debug info;
1202// else the debug info would affect codegen.
1204 if (MBB->isEHPad() || MBB->hasAddressTaken() || MBB->pred_size() != 1 ||
1205 MBB->succ_empty())
1206 return false;
1207 for (MachineBasicBlock::iterator MBBI = MBB->begin(), MBBE = MBB->end();
1208 MBBI != MBBE; ++MBBI) {
1209 if (!MBBI->isDebugInstr())
1210 return false;
1211 }
1212 return true;
1213}
1214
1215// When the DstBB does not contain SrcMI, start from the end.
1216// Otherwise start from the bundle_iterator just before SrcMI.
1217static MIRIterType getSpeculationBeginPoint(MachineInstr *SrcMI,
1218 MachineBasicBlock *DstBB) {
1219 MIRIterType Rb = DstBB->rbegin();
1220 MIRIterType Re = DstBB->rend();
1221
1222 if (SrcMI->getParent() != DstBB)
1223 return Rb;
1224
1225 std::pair<MICInstIterType, MICInstIterType> B = getParentBundle(SrcMI);
1226 // TODO: Is there an advance function for reverse instr iterators?
1227 while ((&*Rb != &*B.first) && (Rb != Re))
1228 ++Rb;
1229 return ++Rb;
1230}
1231
1232//===----------------------------------------------------------------------===//
1233// GlobalScheduler::ABI Functions
1234//===----------------------------------------------------------------------===//
1235// TODO: Modify this to handle cases where succ_size=1.
1236bool GlobalScheduler::ABI::analyzeBranch(MachineBasicBlock *MBB,
1237 const HexagonInstrInfo *QII,
1238 bool PostSched) {
1239 AnalysisValid = !QII->analyzeBranch(*MBB, TBB, FBB, Cond, false);
1240 if (AnalysisValid) {
1241 // According to the HexagonInstrInfo::getBranchingInstrs
1242 // Only the last element can be a conditional branching instruction.
1243 SmallVector<MachineInstr *, 2> Jumpers = QII->getBranchingInstrs(*MBB);
1244 if (!Jumpers.empty() && ((MBB->succ_size() == 2) || PostSched)) {
1245 unsigned jumpers_size = Jumpers.size();
1246 assert((jumpers_size == 1) || (jumpers_size == 2));
1247 FirstTerm = Jumpers.back();
1248 if (jumpers_size == 2)
1249 SecondTerm = Jumpers[0];
1250 if (MBB->succ_size() == 2) {
1251 FBB = *MBB->succ_begin();
1252 if (FBB == TBB)
1253 FBB = *MBB->succ_rbegin(); // Since only two successors.
1254 }
1255 } else {
1256 AnalysisValid = false;
1257 }
1258 }
1259 return AnalysisValid;
1260}
1261
1262//===----------------------------------------------------------------------===//
1263// GlobalScheduler Functions
1264//===----------------------------------------------------------------------===//
1265bool GlobalScheduler::branchesInBetweenMBB(MIInstIterType MII,
1266 MachineBasicBlock *MBB) {
1267 if (!MII->isBranch())
1268 return false;
1269 // Get the beginning of the bundle containing MII.
1270 while (MII->isInsideBundle())
1271 --MII;
1272 // Now, skip to the next bundle.
1273 MII = std::next(MachineBasicBlock::iterator(MII)).getInstrIterator();
1274 if (MII == MBB->instr_end())
1275 return false;
1276
1277 if (endloopAfterMI(MII, MBB))
1278 return false;
1279 if (MII->isReturn())
1280 return false;
1281 // Anything other than a direct jump => branches in between or, > 2 succs.
1282 // MII may be a bundle => > 2 following instructions.
1283 if (MII->isBranch())
1284 return false;
1285 return true;
1286}
1287
1288bool GlobalScheduler::splitMBBAt(MIInstIterType MII, MachineBasicBlock *MBB) {
1289 MachineBasicBlock *OrigTBB = NULL, *OrigFBB = NULL;
1290 SmallVector<MachineOperand, 4> OrigCond;
1291
1292 // Not storing analyzeBranch info here because this will be stale soon.
1293 if (QII->analyzeBranch(*MBB, OrigTBB, OrigFBB, OrigCond, false) ||
1294 (MBB->succ_size() != 2))
1295 return false;
1296
1297 MachineBasicBlock *Succ1 = *MBB->succ_begin();
1298 MachineBasicBlock *Succ2 = *MBB->succ_rbegin();
1299
1300 if (!OrigFBB) {
1301 if (OrigTBB == Succ1)
1302 OrigFBB = Succ2;
1303 OrigFBB = Succ1;
1304 }
1305
1306 const BasicBlock *IR_Block = MBB->getBasicBlock();
1307 MachineFunction *MF = MBB->getParent();
1308 MachineBasicBlock *NewBlock = MF->CreateMachineBasicBlock(IR_Block);
1310
1311 MF->insert(++MBBI, NewBlock);
1312 NewBlock->splice(NewBlock->end(), MBB, MII, MBB->end());
1313
1314 MachineBasicBlock *FirstTBB = NULL, *FirstFBB = NULL;
1315 SmallVector<MachineOperand, 4> FirstCond;
1316
1317 (void)FirstTBB;
1318 (void)FirstFBB;
1319 (void)FirstCond;
1320 assert(!QII->analyzeBranch(*MBB, FirstTBB, FirstFBB, FirstCond, false));
1321
1322 MBB->removeSuccessor(OrigFBB);
1323 MBB->addSuccessor(NewBlock);
1324 NewBlock->addSuccessor(OrigFBB);
1325 // transfer liveins from MBB to NewBlock, just copy the parent's livein.
1326 transferLiveIns(MBB, NewBlock);
1327 return true;
1328}
1329
1330// Ensures that there are no more than 2 successors of a MBB
1331// with direct branching instructions.
1332// Also, performs a small optimization of removing branches to immediate succ.
1333// TODO: Some useful CFG optimizations can be done here to aid in scheduling.
1334void GlobalScheduler::generateCFG(MachineFunction &MF) {
1336 while (MBBI != MF.end()) {
1337 MachineBasicBlock *MBB = &*MBBI;
1338 MIInstIterType MII = MBBI->instr_begin();
1339 while (MII != MBBI->instr_end()) {
1340 MachineInstr *MI = &*MII;
1341 ++MII; // As MI might be removed.
1342 if (branchesInBetweenMBB(MI->getIterator(), MBB)) {
1343 // Splitting the MBB at MII.
1344 LLVM_DEBUG(dbgs() << "\nSplitting the MBB#" << MBB->getNumber()
1345 << " at: ";
1346 MI->dump());
1347 if (!splitMBBAt(std::next(MI->getIterator()), MBB))
1348 assert(MBB->succ_size() > 2);
1349 LLVM_DEBUG(dbgs() << "\nResulting BB: "; MBB->dump(););
1350 } else if (MI->getOpcode() == Hexagon::J2_jump &&
1351 MI->getOperand(0).isMBB()) {
1352 // If it jumps to the layout successor, remove the J2_jump instruction.
1353 MachineBasicBlock *Target = MI->getOperand(0).getMBB();
1354 if (MBB->isLayoutSuccessor(Target)) {
1355 LLVM_DEBUG(dbgs() << "\nRemoving branch to layout succ." << *MI);
1356 if (MI->isBundled()) {
1357 MachineInstr *Head = &*getBundleStart(MI->getIterator());
1358 MI->eraseFromBundle();
1359 updateBundle(Head, QII);
1360 } else
1361 MI->eraseFromParent();
1362 }
1363 }
1364 }
1365 ++MBBI;
1366 }
1367}
1368
1369// TODO: This needs to be improved. Is there a way to just 'copy'
1370// \p BB2 and emplace just after BB1?
1371// @brief Make BB2 as layout successor of BB1.
1372bool GlobalScheduler::makeAsLayoutSuccessor(MachineBasicBlock *BB1,
1373 MachineBasicBlock *BB2) {
1374 assert(!BB1->isLayoutSuccessor(BB2));
1375 // We can only deal with returning MBBs and MBBs with a direct jump.
1376 if (BB2->pred_size() != 1 || (BB2->succ_size() > 1))
1377 return false;
1378 // We don't want to move in MBBs if they change the CFG too much.
1379 // Passing same BB2 in both params to get the num_instrs*instr_size
1380 int InsSize = HLV->getDistanceBetween(BB2, BB2);
1381 if (SafetyBufferDelta < InsSize)
1382 return false;
1383 SafetyBufferDelta -= InsSize;
1384
1385 SmallVector<MachineInstr *, 2> Jumpers = QII->getBranchingInstrs(*BB2);
1386 if (Jumpers.size() > 1 || Jumpers.empty())
1387 return false;
1388 if (QII->isPredicated(*Jumpers[0]))
1389 return false;
1390 LLVM_DEBUG(dbgs() << "\nMaking MBB#" << BB2->getNumber()
1391 << " as LayoutSuccessor of " << BB1->getNumber(););
1393 ++BB1LS; // Current layout successor of BB1
1394 if (BB1LS != MF.end()) {
1395 MF.splice(BB1LS, BB2);
1396 return true;
1397 }
1398 return false;
1399}
1400
1401void GlobalScheduler::removeEmptyMBB(MachineBasicBlock *MBB) {
1402 assert((MBB->succ_size() == 1) && (MBB->pred_size() == 1));
1403 LLVM_DEBUG(dbgs() << "\nRemoving:" << *MBB);
1404 MachineBasicBlock *Pred = *MBB->pred_begin();
1405 LLVM_DEBUG(dbgs() << "\nPred:" << *Pred);
1406 LLVM_DEBUG(dbgs() << "\nSucc:" << **MBB->succ_begin());
1407 Pred->ReplaceUsesOfBlockWith(MBB, *MBB->succ_begin());
1408 LLVM_DEBUG(dbgs() << "\nPred after update:" << *Pred);
1409 MachineJumpTableInfo *MJTI = MBB->getParent()->getJumpTableInfo();
1410 if (MJTI) {
1412 }
1414 LLVM_DEBUG(dbgs() << "Removing BB(" << MBB->getNumber()
1415 << ") from parent.\n");
1417}
1418
1419// 1. Remove jump to the layout successor.
1420// 2. Remove multiple (dual) jump to the same target.
1421bool GlobalScheduler::removeRedundantBranches(MachineBasicBlock *MBB,
1422 MachineBasicBlock *TBB,
1423 MachineInstr *FirstTerm,
1424 MachineBasicBlock *FBB,
1425 MachineInstr *SecondTerm) {
1426 bool Analyzed = false;
1427 LLVM_DEBUG(dbgs() << "\n[removeRedundantBranches]");
1428 MachineInstr *Head = NULL, *ToErase = NULL;
1429 if (!FBB && (FirstTerm->getOpcode() == Hexagon::J2_jump) &&
1431 // Jmp layout_succ_basic_block <-- Remove
1432 LLVM_DEBUG(
1433 dbgs() << "\nRemoving Uncond. jump to the layout successor in BB#"
1434 << MBB->getNumber());
1435 ToErase = FirstTerm;
1436 } else if (SecondTerm && (TBB == FBB) &&
1437 (SecondTerm->getOpcode() == Hexagon::J2_jump)) {
1438 // If both branching instructions in same packet or are consecutive.
1439 // Jmp_c t1 <-- Remove
1440 // Jmp t1
1441 // @Note: If they are in different packets or if they are separated
1442 // by packet(s), this opt. cannot be done.
1443 MachineBasicBlock::instr_iterator FirstTermIter = FirstTerm->getIterator();
1444 MachineBasicBlock::instr_iterator SecondTermIter =
1445 SecondTerm->getIterator();
1446 if (++FirstTermIter == SecondTermIter &&
1447 !QII->isCompoundBranchInstr(*FirstTerm)) {
1448 LLVM_DEBUG(dbgs() << "\nRemoving multiple branching to same target in BB#"
1449 << MBB->getNumber());
1450 // TODO: This might make the `p' register assignment instruction dead.
1451 // and can be removed.
1452 ToErase = FirstTerm;
1453 }
1454 } else if (SecondTerm && (SecondTerm->getOpcode() == Hexagon::J2_jump) &&
1455 FBB && MBB->isLayoutSuccessor(FBB)) {
1456 // Jmp_c t1
1457 // Jmp layout_succ_basic_block <-- Remove
1458 LLVM_DEBUG(dbgs() << "\nRemoving fall through branch in BB#"
1459 << MBB->getNumber());
1460 ToErase = SecondTerm;
1461 } else if (!SecondTerm && !FirstTerm->isUnconditionalBranch() &&
1463 // Branching+Fallthrough to the layout successor.
1464 // Jmp_c layout_succ_basic_block <-- Remove
1465 assert(MBB->succ_size() == 1 && "Malformed CFG");
1466 ToErase = FirstTerm;
1467 }
1468 // Remove the instruction from the BB
1469 if (ToErase) {
1470 if (ToErase->isBundled()) {
1471 Head = &*getBundleStart(ToErase->getIterator());
1472 ToErase->eraseFromBundle();
1473 updateBundle(Head, QII);
1474 } else
1475 ToErase->eraseFromParent();
1476 Analyzed = true;
1477 }
1478 return Analyzed;
1479}
1480
1481// ----- convert
1482// p = <expr>
1483// if(p) jump layout_succ_basic_block
1484// jump t
1485// ----- to
1486// p = <expr>
1487// if(!p) jump t
1488// for now only looking at the dual jump
1489bool GlobalScheduler::optimizeDualJumps(MachineBasicBlock *MBB,
1490 MachineBasicBlock *TBB,
1491 MachineInstr *FirstTerm,
1492 MachineBasicBlock *FBB,
1493 MachineInstr *SecondTerm) {
1494 LLVM_DEBUG(dbgs() << "\n[optimizeDualJumps]");
1495
1496 bool Analyzed = false;
1497
1498 if (QII->PredOpcodeHasJMP_c(FirstTerm->getOpcode()) &&
1499 (SecondTerm->getOpcode() == Hexagon::J2_jump)) {
1500
1501 if (TBB == FBB) {
1502 LLVM_DEBUG(dbgs() << "\nBoth successors are the same.");
1503 return Analyzed;
1504 }
1505
1506 LLVM_DEBUG(dbgs() << "\nCandidate for jump optimization in BB("
1507 << MBB->getNumber() << ").\n";);
1508
1509 // Predicated jump to layout successor followed by an unconditional jump.
1510 if (MBB->isLayoutSuccessor(TBB)) {
1511 // Check if the jump in the last instruction is within range.
1512 unsigned Distance = HLV->getDistanceBetween(MBB, FBB) + SafetyBuffer;
1513 if (!QII->isJumpWithinBranchRange(*FirstTerm, Distance)) {
1514 LLVM_DEBUG(dbgs() << "\nUnconditional jump target:" << Distance
1515 << " out of range.");
1516 return Analyzed;
1517 }
1518
1519 // modify the second last -predicated- instruction (sense and target)
1520 LLVM_DEBUG(dbgs() << "\nFirst Instr:" << *FirstTerm;);
1521 LLVM_DEBUG(dbgs() << "\nSecond Instr:" << *SecondTerm;);
1522 LLVM_DEBUG(dbgs() << "\nOld Succ BB(" << TBB->getNumber() << ").";);
1523
1524 QII->invertAndChangeJumpTarget(*FirstTerm, FBB);
1525
1526 LLVM_DEBUG(dbgs() << "\nNew First Instruction:" << *FirstTerm;);
1527
1528 // unbundle if there is only one instruction left
1529 MachineInstr *SecondHead, *FirstHead;
1530 FirstHead = FirstTerm->isBundled()
1531 ? &*getBundleStart(FirstTerm->getIterator())
1532 : nullptr;
1533 SecondHead = SecondTerm->isBundled()
1534 ? &*getBundleStart(SecondTerm->getIterator())
1535 : nullptr;
1536
1537 // 1. Both unbundled, 2. FirstTerm inside bundle, second outside.
1538 if (!SecondHead)
1539 SecondTerm->eraseFromParent();
1540 else if (!FirstHead) {
1541 // 3. FirstHead outside, SecondHead inside.
1542 SecondTerm->eraseFromBundle();
1543 updateBundle(SecondHead, QII);
1544 } else if (FirstHead == SecondHead) {
1545 // 4. Both are in the same bundle
1546 assert((FirstHead && SecondHead) && "Unbundled Instruction");
1547 SecondTerm->eraseFromBundle();
1548 updateBundle(SecondHead, QII);
1549 } else {
1550 // 5. Both are in different bundles
1551 SecondTerm->eraseFromBundle();
1552 updateBundle(SecondHead, QII);
1553 }
1554 Analyzed = true;
1555 }
1556 }
1557 return Analyzed;
1558}
1559
1560// optimizeBranching -
1561// 1. A conditional-jump transfers control to a BB with
1562// jump as the only instruction.
1563// if(p0) jump t1
1564// // ...
1565// t1: jump t2
1566// 2. When a BB with a single conditional jump, jumps to succ-of-succ and
1567// falls-through BB with only jump instruction.
1568// { if(p0) jump t1 }
1569// { jump t2 }
1570// t1: { ... }
1571MachineBasicBlock *GlobalScheduler::optimizeBranches(MachineBasicBlock *MBB,
1572 MachineBasicBlock *TBB,
1573 MachineInstr *FirstTerm,
1574 MachineBasicBlock *FBB) {
1575 LLVM_DEBUG(dbgs() << "\n[optimizeBranches]");
1576 if ((TBB == MBB) || (FBB == MBB))
1577 LLVM_DEBUG(dbgs() << "Cannot deal with loops in BB#" << MBB->getNumber(););
1578
1579 // { if(p) jump t1; }
1580 // t1: { jump t2; }
1581 // --> { if(p) jump t2
1582 // remove t1: { jump t2; }, if it's address is not taken/not a landing pad.
1583 if (QII->nonDbgBBSize(TBB) == 1) {
1584 MachineInstr *TBBMIb = &*TBB->getFirstNonDebugInstr();
1585 if (TBBMIb->getOpcode() == Hexagon::J2_jump &&
1586 TBBMIb->getOperand(0).isMBB()) {
1587 MachineBasicBlock *NewTarget = TBBMIb->getOperand(0).getMBB();
1588 if (TBB->hasAddressTaken() || TBB->isEHPad() ||
1589 TBB == NewTarget /*Infinite loop*/ || (TBB->pred_size() != 1))
1590 return NULL;
1591
1592 LLVM_DEBUG(dbgs() << "\nSuboptimal branching in TBB");
1593 // Check if the jump in the last instruction is within range.
1594 unsigned Distance =
1595 HLV->getDistanceBetween(MBB, NewTarget) + SafetyBuffer;
1596 if (!QII->isJumpWithinBranchRange(*FirstTerm, Distance)) {
1597 LLVM_DEBUG(dbgs() << "\nUnconditional jump target:" << Distance
1598 << " out of range.");
1599 return NULL;
1600 }
1601 MBB->ReplaceUsesOfBlockWith(TBB, NewTarget);
1602 // TBB has only one successor since only one J2_jump instr.
1603 TBB->removeSuccessor(TBB->succ_begin());
1604 TBBMIb->eraseFromParent();
1605 return TBB;
1606 }
1607 if (TBBMIb->isReturn() && QII->isPredicable(*TBBMIb)) {
1608 SmallVector<MachineOperand, 4> PredCond;
1609 QII->findInstrPredicate(FirstTerm, PredCond);
1610 if (PredCond.empty())
1611 return NULL;
1612 unsigned Opcode = TBBMIb->getOpcode();
1613 if ((Opcode != Hexagon::PS_jmpret) && (Opcode != Hexagon::L4_return))
1614 return NULL;
1615 MachineInstr *NewMI = FirstTerm;
1616 bool NeedToNewify = QII->isPredicatedNew(*NewMI);
1617 // Since return instructions execute only in slot 0.
1618 // TODO: For bs > 2 we have to do resource tracking etc.
1619 if (NewMI->isBundled()) {
1620 if (!NeedToNewify)
1621 return nullptr;
1623 if (QII->nonDbgBundleSize(*getBundleStart(It)) > 2)
1624 return nullptr;
1625 }
1626 int rem = NewMI->getNumOperands() - 1;
1627 while (rem >= 0) // Removing from back is faster.
1628 NewMI->removeOperand(rem--);
1629 const MachineInstr *MI2Clone = TBBMIb;
1630 NewMI->setDesc(QII->get(MI2Clone->getOpcode()));
1631 unsigned NumOps = MI2Clone->getNumOperands();
1632 unsigned add = 0;
1633 while (add < NumOps)
1634 NewMI->addOperand(MI2Clone->getOperand(add++));
1635 if (!QII->PredicateInstruction(*NewMI, PredCond))
1636 llvm_unreachable("Instruction should have been predicable");
1637 if (NeedToNewify) {
1638 int NewOpcode = QII->getDotNewPredOp(*NewMI, MBPI);
1639 NewMI->setDesc(QII->get(NewOpcode));
1640 }
1642 LLVM_DEBUG(dbgs() << "ModifiedInstr:"; NewMI->dump(););
1643 if ((TBB != &*MBB->getParent()->begin()) && !TBB->isEHPad() &&
1644 !TBB->hasAddressTaken() && TBB->pred_empty() && TBB->succ_empty())
1645 return TBB;
1646 }
1647 return NULL;
1648 }
1649 // { if(p) jump t1; } may contain more instructions
1650 // { jump t2; } --only one instruction
1651 // t1: {...}
1652 // TBB is layout successor of FBB, then we can change the branch target
1653 // for conditional jump and invert the predicate to remove jump t2.
1654 // { if(!p) jump t2; }
1655 // t1: {...}
1656 if (QII->nonDbgBBSize(FBB) == 1) {
1657 MachineInstr *FBBMIb = &*FBB->getFirstNonDebugInstr();
1658 if (FBBMIb->getOpcode() == Hexagon::J2_jump &&
1659 FBBMIb->getOperand(0).isMBB()) {
1660 MachineBasicBlock *NewTarget = FBBMIb->getOperand(0).getMBB();
1661 if (FBB->hasAddressTaken() || FBB->isEHPad() ||
1662 (FBB == NewTarget /*Infinite loop*/) || (FBB->pred_size() != 1))
1663 return NULL;
1664 if (!FBB->isLayoutSuccessor(TBB) && !makeAsLayoutSuccessor(FBB, TBB))
1665 return NULL;
1667 LLVM_DEBUG(dbgs() << "\nSuboptimal branching in FBB");
1668 // Check if the jump in the last instruction is within range.
1669 unsigned Distance =
1670 HLV->getDistanceBetween(MBB, NewTarget) + SafetyBuffer;
1671
1672 if (!QII->isJumpWithinBranchRange(*FirstTerm, Distance)) {
1673 LLVM_DEBUG(dbgs() << "\nUnconditional jump target:" << Distance
1674 << " out of range.");
1675 return NULL;
1676 }
1677 if (!QII->invertAndChangeJumpTarget(*FirstTerm, NewTarget))
1678 return NULL;
1679 LLVM_DEBUG(dbgs() << "\nNew instruction:"; FirstTerm->dump(););
1680 MBB->ReplaceUsesOfBlockWith(FBB, NewTarget);
1681 FBB->removeSuccessor(FBB->succ_begin());
1682 FBBMIb->eraseFromParent();
1683 return FBB;
1684 }
1685 }
1686 return NULL;
1687}
1688
1689void GlobalScheduler::performExposedOptimizations() {
1690 LLVM_DEBUG(dbgs() << "\n[PerformExposedOptimizations]";);
1692 for (; MBBI != MF.end();) {
1693 MachineBasicBlock *MBB = &*MBBI;
1694 ++MBBI; // MBB might be removed so incrementing early.
1695 // Empty BBs.
1696 if (isEmptyBlock(MBB)) {
1698 pe = MBB->pred_end();
1699 pi != pe; ++pi)
1700 if (AnalyzeBranchInfo.hasABInfo(*pi))
1701 AnalyzeBranchInfo.invalidate(*pi);
1702
1703 if (AnalyzeBranchInfo.hasABInfo(MBB))
1704 AnalyzeBranchInfo.invalidate(MBB);
1705 removeEmptyMBB(MBB);
1706 }
1707 }
1708 for (MBBI = MF.begin(); MBBI != MF.end();) {
1709 MachineBasicBlock *MBB = &*MBBI;
1710 ++MBBI; // MBB might be removed so incrementing early.
1711 LLVM_DEBUG(dbgs() << "\nOptimizing Branches in MBB#" << MBB->getNumber(););
1712 // Don't perform optimizations on these MBBs.
1713 if (std::find(IgnorePostSchedOpt.begin(), IgnorePostSchedOpt.end(), MBB) !=
1714 IgnorePostSchedOpt.end())
1715 continue;
1716 // Branch Optimizations.
1717 ABI &abi = AnalyzeBranchInfo.getOrCreate(MBB, QII, true);
1718 if (!abi.AnalysisValid)
1719 continue;
1720 MachineBasicBlock *TBB = abi.TBB, *FBB = abi.FBB;
1721 MachineInstr *FirstTerm = abi.FirstTerm, *SecondTerm = abi.SecondTerm;
1722
1723 // If there are two jump instructions then see if one can be removed.
1724 if (TBB && FirstTerm &&
1725 removeRedundantBranches(MBB, TBB, FirstTerm, FBB, SecondTerm)) {
1726 LLVM_DEBUG(dbgs() << "\nRemoved redundant branches in BB#"
1727 << MBB->getNumber(););
1728 } else if (FirstTerm && SecondTerm &&
1729 optimizeDualJumps(MBB, TBB, FirstTerm, FBB, SecondTerm)) {
1730 LLVM_DEBUG(dbgs() << "\nRemoved dual jumps in BB#" << MBB->getNumber(););
1731 } else if (TBB && FBB && FirstTerm && !SecondTerm) {
1732 MachineBasicBlock *BBToErase = optimizeBranches(MBB, TBB, FirstTerm, FBB);
1733 if (BBToErase) {
1734 if (AnalyzeBranchInfo.hasABInfo(BBToErase))
1735 AnalyzeBranchInfo.invalidate(BBToErase);
1736 assert(BBToErase->succ_empty() && BBToErase->pred_empty());
1737 BBToErase->eraseFromParent();
1738 // Since we don't know from where this MBB got deleted, restart.
1739 // Also, this enables removal of branches which might
1740 // be redundant as a result of removing BBToErase.
1741 MBBI = MF.begin();
1742 LLVM_DEBUG(dbgs() << "\nOptimized jump from BB#" << MBB->getNumber());
1743 }
1744 }
1745 // We know that MBB was analyzed.
1746 AnalyzeBranchInfo.invalidate(MBB);
1747 }
1748}
1749
1750// Criteria of HEAD of a scheduling region (Superblock).
1751// 1. MF.begin()
1752// 2. MBB with more than one successor:
1753// - Can be part of multiple scheduling regions.
1754// For simplicity we'll make this as HEAD as well. This lets us not
1755// worry about the loop as a special case.
1756// 3. MBB with more than one predecessor:
1757// - Will always be (if at all) the HEAD of the scheduling region.
1758// TODO: Use the dominator tree to construct regions.
1759void GlobalScheduler::formSchedulingRegions(MachineFunction &MF) {
1761 // Populate the HEADs of scheduling regions.
1762 // We don't want to handle MBBs with >2 successors. This lets us
1763 // focus on most common cases and simplifies the analysis.
1764 while (MBBI != MF.end()) {
1765 unsigned MBBPredSize = MBBI->pred_size();
1766 unsigned MBBSuccSize = MBBI->succ_size();
1767 if (((MBBPredSize > 1) && ((MBBSuccSize == 1) || (MBBSuccSize == 2))) ||
1768 (MBBSuccSize == 2)) {
1769 SchedulingRegion_t SR;
1770 SR.addSRMember(&*MBBI);
1771 SchedulingRegions.push_back(SR);
1772 // Push two HEADs so that two scheduling regions can be created.
1773 if (MBBI->succ_size() == 2) {
1774 SchedulingRegions.push_back(SR);
1775 }
1776 }
1777 ++MBBI;
1778 }
1779 // For each HEAD, populate corresponding scheduling region.
1780 SchedulingRegions_t::iterator SRI = SchedulingRegions.begin();
1781 SchedulingRegions_t::iterator SRIPrev = SchedulingRegions.end();
1782 LLVM_DEBUG(dbgs() << "\nConstructing Scheduling Region for HEADs at";);
1783 while (SRI != SchedulingRegions.end()) {
1784 MachineBasicBlock *RegHead = SRI->Members[0];
1785 assert(RegHead);
1786 LLVM_DEBUG(dbgs() << " BB#" << RegHead->getNumber(););
1787 MachineBasicBlock::succ_iterator MBBSucc = RegHead->succ_begin();
1788 // In case of multiple entries, the first HEAD will have the first succ.
1789 // in its region.
1790 // Look at the other successor to construct the region, if the first branch
1791 // of Region HEAD is already included in the previous region.
1792 if ((SRIPrev != SchedulingRegions.end()) &&
1793 (SRIPrev->Members[0] == SRI->Members[0]))
1794 ++MBBSucc;
1795 assert(RegHead->succ_size() < 3);
1796 MachineFunction::iterator RegMBB = (*MBBSucc)->getIterator();
1797 while (1) {
1798 auto *L = MLI.getLoopFor(&*RegMBB);
1799 bool SuccIsSingleBlockLoop =
1800 isSuperblockLoop(L) && RegMBB->getNumber() != RegHead->getNumber();
1801 // pred_size > 1 => HEAD, cannot be included in this region.
1802 // Leaf MBBs should have at least one MI.
1803 if ((RegMBB->pred_size() > 1 && !SuccIsSingleBlockLoop) ||
1804 (RegMBB->succ_empty() && RegMBB->empty()))
1805 break;
1806 SRI->addSRMember(&*RegMBB);
1807 // succ_size = 0 => done!, =2 => HEAD
1808 if (RegMBB->succ_size() != 1) {
1809 break;
1810 }
1811 RegMBB = (*RegMBB->succ_begin())->getIterator();
1812 }
1813 SRIPrev = SRI;
1814 ++SRI;
1815 }
1816}
1817
1818void GlobalScheduler::pruneSchedulingRegions(PruneCriteriaFP PC) {
1819 LLVM_DEBUG(dbgs() << "\nErasing Scheduling Region with HEAD at";);
1820 for (SchedulingRegions_t::iterator SRI = SchedulingRegions.begin();
1821 SRI != SchedulingRegions.end();) {
1822 if ((this->*PC)(*SRI)) {
1823 LLVM_DEBUG(dbgs() << "\tBB#" << SRI->Members[0]->getNumber());
1824 SRI = SchedulingRegions.erase(SRI);
1825 } else {
1826 ++SRI;
1827 }
1828 }
1829}
1830
1831void GlobalScheduler::sortSchedulingRegions() {
1832 for (SchedulingRegions_t::iterator SRI = SchedulingRegions.begin();
1833 SRI != SchedulingRegions.end(); ++SRI) {
1834 SchedulingRegion_t &SR = *SRI;
1835 // The EdgeProb of a scheduling region is the same as the edge prob.
1836 // of the first two MBBs.
1837 SR.EdgeProb = MBPI->getEdgeProbability(SR.Members[0], SR.Members[1]);
1838 if (SR.EdgeProb.getCompl() == SR.EdgeProb) { // N = D/2;
1839 ABI &abi = AnalyzeBranchInfo.getOrCreate(SR.Members[0], QII);
1840 if (!abi.AnalysisValid)
1841 continue;
1842 // Increase the probability of TBB.
1843 if (abi.TBB == SR.Members[1])
1844 SR.EdgeProb = BranchProbability(2, 3); // N = 2D/3
1845 else
1846 SR.EdgeProb = BranchProbability(1, 3); // N = D/3
1847 }
1848 LLVM_DEBUG(dbgs() << "Edge Probability of: "; SR.dump(); dbgs() << ":\t";
1849 SR.EdgeProb.dump(););
1850 }
1851 // Sort in the decreasing order of edge probabilities.
1852 llvm::stable_sort(SchedulingRegions,
1853 std::greater<SchedulingRegions_t::value_type>());
1854}
1855
1857GlobalScheduler::addToPacketPseudo(MachineInstr *MI) {
1859 // We don't want to reserve a resource for CFI_INSTRUCTION (it has zero
1860 // cost).
1861 if (!TII->isZeroCost(MI->getOpcode()))
1862 ResourceTracker->reserveResources(*MI);
1863 if (QII->isConstExtended(*MI)) {
1864 assert(canReserveResourcesForConstExt());
1865 reserveResourcesForConstExt();
1866 }
1867 CurrentPacketMIs.push_back(MI);
1868 return MII;
1869}
1870
1871void GlobalScheduler::initPacketizerStateLoc() {
1873 CurrentPacketMIs.clear();
1874}
1875
1876// Uses the packetizer checks to ensure correctness.
1877bool GlobalScheduler::isLegalToPacketizeWith(MIIterType DestPack,
1878 MachineInstr *MI) {
1879 LLVM_DEBUG(dbgs() << "\n[isLegalToPacketizeWith]";);
1880 assert(DestPack->isBundle());
1881 // Never packetize a solo instruction.
1882 if (isSoloInstruction(*MI))
1883 return false;
1884
1885 // The implementation should be inline with isLegalToPacketizeTogether.
1886 // For all MIs in DestPack call isLegalToPacketizeTogetherMI.
1887 MIInstIterType BI = (&*DestPack)->getIterator();
1888 MachineBasicBlock *MBB = BI->getParent();
1889 const MachineInstr *BranchMI = NULL;
1890 // skipping the bundle header.
1891 for (++BI; (BI != MBB->instr_end()) && BI->isInsideBundle(); ++BI) {
1892 // Remember the branch; its target may need a constant extender (below).
1893 if (BI->isBranch())
1894 BranchMI = &*BI;
1895 if (!isLegalToPacketizeTogetherMI(&*BI, MI))
1896 return false;
1897 }
1898
1899 unsigned NumI = QII->nonDbgBundleSize(*DestPack);
1900 // When there is only one slot left we want to check if there's a
1901 // scope for const-extender.
1902 if ((NumI >= (HEXAGON_PACKET_SIZE - 1)) && BranchMI &&
1903 (DisableHVXLocalPullupAndSuperblock || !useHVXOps ||
1904 !QII->isEndLoopN(BranchMI->getOpcode()))) {
1905 for (unsigned i = 0; i < BranchMI->getNumOperands(); ++i) {
1906 const MachineOperand &MO = BranchMI->getOperand(i);
1907 if (MO.isMBB()) {
1908 unsigned dist = HLV->getDistanceBetween(MBB, MO.getMBB());
1909 if (!QII->isJumpWithinBranchRange(*BranchMI, dist + SafetyBuffer)) {
1910 LLVM_DEBUG(dbgs() << "\nBranch might be constant extended later";);
1911 return false;
1912 }
1913 }
1914 }
1915 }
1916 return true;
1917}
1918
1919// BI is the destination packet where MI may be placed.
1920bool GlobalScheduler::isLegalToPacketizeTogetherMI(MachineInstr *BI,
1921 MachineInstr *MI) {
1922 if (cannotCoexist(*BI, *MI))
1923 return false;
1924
1925 if (hasDeadDependence(*BI, *MI))
1926 return false;
1927 if (hasControlDependence(*BI, *MI))
1928 return false;
1929 if (hasDualStoreDependence(*BI, *MI))
1930 return false;
1931
1932 const MachineBasicBlock *MBB = BI->getParent();
1933 // The implementation should be inline with isLegalToPacketizeTogether.
1934 // Hexagon PRM 7.3.4: a loop setup packet in loopN or spNloop0 cannot
1935 // contain a speculative indirect jump,
1936 // a new-value compare jump or a dealloc_return.
1937 // Speculative indirect jumps (predicate + .new + indirect):
1938 // if ([!]Ps.new) jumpr:t Rs
1939 // if ([!]Ps.new) jumpr:nt Rs
1940 // @note: We don't want to pull across a call to be on the safe side.
1941 if (QII->isLoopN(*MI)) {
1942 if ((QII->isPredicated(*BI) && QII->isPredicatedNew(*BI) &&
1943 QII->isJumpR(*BI)) ||
1944 QII->isNewValueJump(*BI) || QII->isDeallocRet(*BI) || BI->isCall()) {
1945 LLVM_DEBUG(dbgs() << "\nLoopN pull interference.");
1946 return false;
1947 }
1948 // loopN cannot be pulled too far.
1949 unsigned dist = HLV->getDistanceBetween(MBB, MI->getOperand(0).getMBB());
1950 if (!QII->isJumpWithinBranchRange(*MI, dist + SafetyBuffer)) {
1951 LLVM_DEBUG(dbgs() << "\nLoopN cannot be pulled too far";);
1952 return false;
1953 }
1954 }
1955
1956 // The opposite is also true.
1957 if (QII->isLoopN(*BI) &&
1958 ((QII->isPredicated(*MI) && QII->isPredicatedNew(*MI) &&
1959 QII->isJumpR(*MI)) ||
1960 QII->isNewValueJump(*MI) || QII->isDeallocRet(*MI) || MI->isCall())) {
1961 LLVM_DEBUG(dbgs() << "\tResident LoopN.");
1962 return false;
1963 }
1964
1965 // @todo Hexagon PRM 7.6.1:
1966 // Presence of NVJ adds more restrictions.
1967 if (QII->isNewValueJump(*BI) &&
1968 (MI->mayStore() || MI->getOpcode() == Hexagon::S2_allocframe ||
1969 MI->isCall())) {
1970 LLVM_DEBUG(dbgs() << "\nNew val Jump.");
1971 return false;
1972 }
1973
1974 // For memory operations, check aliasing.
1975 // Be conservative with ordered (volatile/atomic) or unknown (no memoperands)
1976 // memory references.
1977 if (BI->hasOrderedMemoryRef())
1978 return false;
1979
1980 // If packet has a new-value store, MI can't be a store instruction.
1981 if (QII->isNewValueStore(*BI) && MI->mayStore()) {
1982 LLVM_DEBUG(dbgs() << "\nNew Value Store to store.");
1983 return false;
1984 }
1985
1986 if ((QII->isMemOp(*BI) && MI->mayStore()) ||
1987 (QII->isMemOp(*MI) && BI->mayStore())) {
1988 LLVM_DEBUG(dbgs() << "\nSlot 0 not available for store because of memop.");
1989 return false;
1990 }
1991 return true;
1992}
1993
1994// @note: This function leaves the packet in an invalid state.
1995// GA and GB are left in the packet and it is the responsibility of the caller
1996// to move/delete them to appropriate places.
1997// @warning: Only works for limited set of branches handled
1998// in HexagonInstrInfo::getCompoundOpcode.
1999MachineInstr *GlobalScheduler::generateCompoundIfPossible(MIInstIterType MII,
2000 MIInstIterType &GA,
2001 MIInstIterType &GB) {
2002 assert(MII->isBundle());
2003 MachineInstr *NewMI = NULL;
2004 MachineBasicBlock *MBB = MII->getParent();
2005 GA = MBB->instr_end();
2006 GB = MBB->instr_end();
2007 ++MII; // Skipping Bundle header.
2008 while ((MII != MBB->instr_end()) && MII->isInsideBundle()) {
2009 if (MII->isCompare() &&
2011 if (GA != MBB->instr_end()) {
2012 GA = MBB->instr_end();
2013 break;
2014 }
2015 GA = MII;
2016 }
2017 if (MII->isBranch() &&
2019 if (GB != MBB->instr_end()) {
2020 GB = MBB->instr_end();
2021 break;
2022 }
2023 GB = MII;
2024 }
2025 ++MII;
2026 }
2027 int CmpOpcode = 0;
2028 if ((GA != MBB->instr_end()) && (GB != MBB->instr_end())) {
2029 CmpOpcode = QII->getCompoundOpcode(*GA, *GB);
2030 if (CmpOpcode != -1) {
2031 LLVM_DEBUG(dbgs() << "\nFound Compound pair: " << *GA << *GB;);
2032 assert(GA->getNumOperands() == 3);
2033 DebugLoc dl = GB->getDebugLoc();
2034 NewMI = BuildMI(*MBB, GB, dl, QII->get(CmpOpcode));
2035 Register PredReg = GA->getOperand(0).getReg();
2036 MachineOperand *PredUse =
2037 NewMI->findRegisterUseOperand(PredReg, /*TRI=*/nullptr);
2038 assert(PredUse && PredUse->isImplicit() &&
2039 "Missing compound predicate use");
2040 PredUse->setIsInternalRead();
2041 NewMI->addOperand(GA->getOperand(1)); // LHS of compare
2042 NewMI->addOperand(GA->getOperand(2)); // RHS of compare
2043 // All the MIs in the HexagonII::HCG_B category have MBB as 2nd operand.
2044 NewMI->addOperand(GB->getOperand(1)); // The branch target.
2045 unsigned dist = HLV->getDistanceBetween(MBB, GB->getOperand(1).getMBB());
2046 if (!QII->isJumpWithinBranchRange(*NewMI, dist + SafetyBuffer +
2047 SafetyBufferDelta)) {
2048 NewMI->eraseFromBundle();
2049 LLVM_DEBUG(dbgs() << ".....NO (Branch too far, cannot form)";);
2050 return NULL;
2051 }
2052 LLVM_DEBUG(dbgs() << "\nNew Compound Instruction:" << *NewMI;);
2053 }
2054 }
2055 return NewMI;
2056}
2057
2058void GlobalScheduler::generateCompoundsPostSched() {
2059 auto it = ToBeSqueezed.begin();
2060 while (it != ToBeSqueezed.end()) {
2061 auto MBB = (*it)->getParent();
2062 MIInstIterType GA = MBB->instr_end(), GB = MBB->instr_end();
2063 MachineInstr *NewMI =
2064 generateCompoundIfPossible((*it)->getIterator(), GA, GB);
2065 (void)NewMI;
2066 assert(NewMI && "Wrong Analysis of compound packets.");
2067 GA->eraseFromBundle();
2068 GB->eraseFromBundle();
2069 updateBundle(*it, QII);
2070 ++it;
2071 }
2072}
2073
2074// Check if the machine instructions belong in the same bundle
2076 if (MI1->isInsideBundle() && MI2->isInsideBundle() &&
2078 return true;
2079 return false;
2080}
2081
2082// Returns true if any of the conditions happen:
2083// (1) If a packet contains endloopN, it cannot perform an auto-AND with
2084// predicate register P3
2085// (2) If a packet contains a register transfer from a general register to a
2086// predicate register, no other instruction in the packet can write to the same
2087// predicate register.
2088// (3) Instructions spNloop0, decbin, tlbmatch, memw_locked, memd_locked,
2089// add:carry, sub:carry, sfcmp, and dfcmp cannot be grouped with another
2090// instruction that sets the same predicate register.
2091bool GlobalScheduler::failsSpecialConditions(MachineInstr *BundleMI,
2092 Register DestReg) {
2093
2094 if (!BundleMI || !BundleMI->getParent())
2095 return true;
2097 E = std::next(I);
2098 E != BundleMI->getParent()->instr_end() && E->isInsideBundle(); ++E) {
2099 MachineInstr &MI = *E;
2100 auto OpC = MI.getOpcode();
2101 // Case 1
2102 if (QII->isEndLoopN(OpC) && DestReg == Hexagon::P3)
2103 return true;
2104 // Case 2
2105 if ((OpC == Hexagon::C2_tfrrp) && MI.getNumOperands() > 0 &&
2106 (DestReg == MI.getOperand(0).getReg()))
2107 return true;
2108 // Case 3
2109 if ((OpC == Hexagon::S2_cabacdecbin) ||
2110 ((QII->isSoftwarePipelineLoopInstr(MI) || OpC == Hexagon::A4_tlbmatch ||
2111 QII->isFloatCompare(MI)) &&
2112 MI.getNumOperands() > 0 && MI.getOperand(0).getReg() == DestReg) ||
2113 ((OpC == Hexagon::S2_storew_locked ||
2114 OpC == Hexagon::S4_stored_locked || OpC == Hexagon::A6_vminub_RdP ||
2115 OpC == Hexagon::A5_ACS || OpC == Hexagon::F2_sfinvsqrta ||
2116 OpC == Hexagon::F2_sfrecipa) &&
2117 MI.getNumOperands() > 1 && MI.getOperand(1).getReg() == DestReg) ||
2118 ((OpC == Hexagon::A4_addp_c || OpC == Hexagon::A4_subp_c) &&
2119 MI.getNumOperands() > 2 && MI.getOperand(3).getReg() == DestReg))
2120 return true;
2121 }
2122 return false;
2123}
2124
2125// Returns true if Reg can be used as a .new predicate source in a packet,
2126// i.e. it is a non-fake predicate register whose definition (Producer) is
2127// not a late-predicate instruction (e.g. A4_addp_c, A4_subp_c).
2128// Sentinel marks the end of the valid iterator range for Producer.
2129bool GlobalScheduler::canNewifyPredReg(unsigned Reg, MICInstIterType Producer,
2130 MICInstIterType Sentinel) const {
2131 if (TRI->isFakeReg(Reg))
2132 return false;
2133 if (TRI->getMinimalPhysRegClass(Reg) != &Hexagon::PredRegsRegClass)
2134 return false;
2135 if (Producer != Sentinel && QII->isPredicateLate(Producer->getOpcode()))
2136 return false;
2137 return true;
2138}
2139
2140// Given a machine instruction, get the defs of the uses and return them as
2141// reference. It uses the infrastructure created in this pass, ie. MIUseDefs
2142bool GlobalScheduler::getDefinitions(MachineInstr *MI, MachineInstr *&Def1,
2143 MachineInstr *&Def2, MachineInstr *&Def3) {
2144
2145 auto MBB = MI->getParent();
2146 if (MI->getNumOperands() < 3)
2147 return false;
2148 Register Reg1 = MI->getOperand(1).getReg();
2149 Register Reg2 = MI->getOperand(2).getReg();
2150 auto Reg3 =
2151 (MI->getNumOperands() == 4) ? MI->getOperand(3).getReg() : Register(0);
2152 const MIUseDef_t &MIUseDefs = HLV->getMIUseDefs();
2153 if (&MBB->front() == MI)
2154 return false;
2155 for (auto DefSearch = std::prev(MI->getIterator());
2156 DefSearch != MBB->instr_begin(); --DefSearch) {
2157 if (DefSearch->isBundle())
2158 continue;
2159
2160 MIUseDef_t::const_iterator DefIter = MIUseDefs.find(&*DefSearch);
2161 if (DefIter == MIUseDefs.end())
2162 continue;
2163
2164 const BitVector &Defs = DefIter->second.second;
2165 if (Defs[Reg1])
2166 Def1 = &*DefSearch;
2167 if (Defs[Reg2])
2168 Def2 = &*DefSearch;
2169 if (Reg3 && Defs[Reg3])
2170 Def3 = &*DefSearch;
2171
2172 if (Def1 && Def2 && (!Reg3 || (Reg3 && Def3)))
2173 return true;
2174 }
2175 return false;
2176}
2177
2178// Exploits a feature of the Hexagon hardware that predicate instructions
2179// in a packet are internally auto ANDed, so a later AND is unnecessary.
2180// Updating liveness is not necessary.
2181void GlobalScheduler::generateAutoAndPredicates(MachineFunction &Fn) {
2182
2183 SmallVector<MachineInstr *, 4> ToBeErased;
2184 for (auto &MBB : Fn) {
2185 for (auto MII = MBB.instr_begin(), ME = MBB.instr_end(); MII != ME; ++MII) {
2186 unsigned OpC = MII->getOpcode();
2187 // TODO check for other opcode types too
2188 if (OpC != Hexagon::C2_and && OpC != Hexagon::C2_andn &&
2189 OpC != Hexagon::C4_and_and && OpC != Hexagon::C4_and_andn)
2190 continue;
2191
2192 Register DestPred = MII->getOperand(0).getReg();
2193 Register Reg1 = MII->getOperand(1).getReg();
2194 Register Reg2 = MII->getOperand(2).getReg();
2195 auto Reg3 = MII->getNumOperands() == 4 ? MII->getOperand(3).getReg()
2196 : Register(0);
2197
2198 // Skip if the operands are the same register
2199 if (Reg1 == Reg2)
2200 continue;
2201 if (Reg3 != 0 && Reg3 == Reg2)
2202 continue;
2203
2204 // Skip if any of the regs are not killed in the AND instruction.
2205 // We don't want any uses of the regs after the AND.
2206 if (!MII->getOperand(1).isKill() || !MII->getOperand(2).isKill() ||
2207 (Reg3 != 0 && !MII->getOperand(3).isKill()))
2208 continue;
2209
2210 // Check if the result of the AND instruction (DestPred) is used by a
2211 // .new instruction within the same packet. If so, skip this AND.
2212 // TODO: This could be handled by replacing the .new use with a regular
2213 // use. Another option is to pullup the .new use if possible
2214 bool UsedByDotNew = false;
2215 auto AndBundleStart = getBundleStart(MII);
2216 auto AndBundleEnd = getBundleEnd(MII);
2217 for (auto BundledII = AndBundleStart; BundledII != AndBundleEnd;
2218 ++BundledII) {
2219 if (&*BundledII == &*MII)
2220 continue;
2221 int UseIdx = BundledII->findRegisterUseOperandIdx(DestPred, TRI);
2222 if (UseIdx >= 0 && QII->isDotNewOperand(*BundledII, UseIdx)) {
2223 UsedByDotNew = true;
2224 break;
2225 }
2226 }
2227 if (UsedByDotNew)
2228 continue;
2229
2230 // Find definitions using MIIDefSet in the same MBB.
2231 MachineInstr *Def1 = nullptr;
2232 MachineInstr *Def2 = nullptr;
2233 MachineInstr *Def3 = nullptr;
2234 if (!getDefinitions(&*MII, Def1, Def2, Def3))
2235 continue;
2236
2237 // Check if the defs are compare instructions
2238 if (!QII->definesPredicateReg(*Def1) ||
2239 !QII->definesPredicateReg(*Def2) ||
2240 (Def3 && !QII->definesPredicateReg(*Def3)))
2241 continue;
2242
2243 // Check if both definitions are in the same bundle
2244 if (!checkIfSameBundle(Def1, Def2))
2245 continue;
2246 if (Def3 && !checkIfSameBundle(Def1, Def3))
2247 continue;
2248
2249 // Check if there are any uses of the predicates before the use in the AND
2250 // instruction If there are, we cannot do this transformation.
2251 MICInstIterType Use;
2252 SmallPtrSet<MachineInstr *, 2> Exception;
2253 auto MIStart = getBundleStart(Def1->getIterator());
2254 auto MIEnd = getBundleEnd(MII);
2255 Exception.insert(&*MII);
2256 if (HLV->isUsedWithin(MIStart, MIEnd, Reg1, Use, &Exception) ||
2257 HLV->isUsedWithin(MIStart, MIEnd, Reg2, Use, &Exception) ||
2258 (Def3 && HLV->isUsedWithin(MIStart, MIEnd, Reg3, Use, &Exception)))
2259 continue;
2260
2261 // Check some special conditions which makes auto-and not possible
2262 if (failsSpecialConditions(&*MIStart, DestPred))
2263 continue;
2264
2265 LLVM_DEBUG(dbgs() << "\n[Found predicate auto and candidate]: ";
2266 MII->dump());
2267
2268 std::optional<unsigned> NewOpC;
2269 switch (OpC) {
2270 // For C2_and: Pd = and(Ps, Pt) - both compares write to DestPred
2271 // (1) Change the def registers
2272 case Hexagon::C2_and:
2273 Def1->getOperand(0).setReg(DestPred);
2274 Def2->getOperand(0).setReg(DestPred);
2275 break;
2276
2277 // For C2_andn: Pd = and(Ps, !Pt) - Ps writes to DestPred, Pt writes
2278 // inverted to DestPred The second operand is the one that gets negated.
2279 // (1) Invert the opcode of the second def
2280 // (2) Change the def registers
2281 case Hexagon::C2_andn:
2282 LLVM_DEBUG(dbgs() << "Get inverted opcode for: "; Def2->dump());
2283 NewOpC = QII->getInvertedCompare(Def2->getOpcode());
2284 if (!NewOpC)
2285 continue;
2286 Def2->setDesc(QII->get(NewOpC.value()));
2287 Def1->getOperand(0).setReg(DestPred);
2288 Def2->getOperand(0).setReg(DestPred);
2289 break;
2290
2291 // (1) Change the three def registers
2292 case Hexagon::C4_and_and:
2293 Def1->getOperand(0).setReg(DestPred);
2294 Def2->getOperand(0).setReg(DestPred);
2295 Def3->getOperand(0).setReg(DestPred);
2296 break;
2297
2298 // (1) Change the three def registers
2299 // (2) Invert the last register's def opcode
2300 case Hexagon::C4_and_andn:
2301 LLVM_DEBUG(dbgs() << "Get inverted opcode for: "; Def3->dump());
2302 NewOpC = QII->getInvertedCompare(Def3->getOpcode());
2303 if (!NewOpC)
2304 continue;
2305 Def3->setDesc(QII->get(NewOpC.value()));
2306 Def1->getOperand(0).setReg(DestPred);
2307 Def2->getOperand(0).setReg(DestPred);
2308 Def3->getOperand(0).setReg(DestPred);
2309 break;
2310
2311 default:
2312 continue;
2313 }
2314
2315 ToBeErased.push_back(&*MII);
2316 }
2317 }
2318
2319 // Erase the redundant AND instructions
2320 for (MachineInstr *It : ToBeErased) {
2321 if (It->isBundled()) {
2322 auto Head = &*getBundleStart(It->getIterator());
2323 It->eraseFromBundle();
2324 updateBundle(Head, QII);
2325 } else
2326 It->eraseFromParent();
2327 }
2328}
2329
2330void GlobalScheduler::packetize() {
2331 DenseSet<unsigned> DoneMBBs;
2332 HexagonPacketizerList Packetizer(MF, MLI, AA, MBPI, false);
2333 SmallVectorImpl<MachineInstr *>::iterator PacketOpp = SpecPacketOpp.begin();
2334 // The Entries are the last instruction where a new MI was scheduled.
2335 // For now we only move up into the MBB.
2336 for (; PacketOpp != SpecPacketOpp.end(); ++PacketOpp) {
2337 MachineBasicBlock *MBB = (*PacketOpp)->getParent();
2338 if (!DoneMBBs.insert(MBB->getNumber()).second)
2339 continue;
2340 MachineBasicBlock::iterator RegionBeg = MBB->begin();
2341 MachineBasicBlock::iterator RegionEnd = std::next(RegionBeg);
2342 for (; RegionBeg != MBB->end(); RegionBeg = RegionEnd) {
2343 // Find scheduling regions and schedule / packetize each region.
2344 // TODO: Find all the regions (unpacketized) and make bundles.
2345 while (RegionBeg != MBB->end() && RegionBeg->isBundled())
2346 ++RegionBeg;
2347 if (RegionBeg == MBB->end())
2348 break;
2349 RegionEnd = std::next(RegionBeg);
2350 while (RegionEnd != MBB->end() && !RegionEnd->isBundled())
2351 ++RegionEnd;
2352 // Skip regions with one instruction.
2353 if (RegionBeg == std::prev(RegionEnd))
2354 continue;
2355 Packetizer.PacketizeMIs(MBB, RegionBeg, RegionEnd);
2356 }
2357 }
2358 Packetizer.unpacketizeSoloInstrs(MF);
2359}
2360
2361// @note When generating a compound instruction, we do not want to
2362// update the liveness of the BUNDLE/MBB because we might decompose later.
2363void GlobalScheduler::getResourcesReadyForBundle(MIInstIterType MII,
2364 bool Squeeze,
2365 MachineInstr *InstrToSkip) {
2366 assert(MII->isBundle());
2367
2368 bool GeneratedCompoundInstr = false;
2369 MachineInstr *NewMI = NULL;
2370 MachineBasicBlock *MBB = MII->getParent();
2371 MIInstIterType GA = MBB->instr_end(), GB = MBB->instr_end();
2372 // MIs because they might be pointing to MIs which are removed from Bundle.
2373 MachineInstr *GAPos, *GBPos;
2374 if (Squeeze && EnableSqueeze &&
2375 (QII->nonDbgBundleSize(*MII) == HEXAGON_PACKET_SIZE)) {
2376 // handle compound/duplex stuff.
2377 LLVM_DEBUG(dbgs() << "\nCompound can be made in this bundle.";);
2378 NewMI = generateCompoundIfPossible(MII, GA, GB);
2379 if (NewMI != NULL) {
2380 GeneratedCompoundInstr = true;
2381 MIInstIterType GANext = std::next(GA);
2382 MIInstIterType GBNext = std::next(GB);
2383 GAPos = GANext != MBB->instr_end() ? &*GANext : nullptr;
2384 GBPos = GBNext != MBB->instr_end() ? &*GBNext : nullptr;
2385 GA = GA->removeFromBundle()->getIterator();
2386 GB = GB->removeFromBundle()->getIterator();
2387 }
2388 }
2389
2390 initPacketizerStateLoc();
2391 ResourceTracker->clearResources();
2392 // Add already packetized instructions.
2393 ++MII; // Skipping Bundle header.
2394
2395 // For TinyCore with Duplexes, change the opcodes of MII to Big Core.
2396 MIInstIterType SavedMII = MII;
2397 auto &ST = MII->getParent()->getParent()->getSubtarget<HexagonSubtarget>();
2398 if (ST.isTinyCoreWithDuplex())
2399 QII->translateInstrsForDup(SavedMII, true);
2400
2401 while ((MII != MBB->instr_end()) && MII->isInsideBundle()) {
2402 assert(ResourceTracker->canReserveResources(*MII) ||
2403 TII->isZeroCost(MII->getOpcode()));
2404 if (!(InstrToSkip && InstrToSkip == &*MII)) {
2405 addToPacketPseudo(&*MII);
2406 }
2407 ++MII;
2408 }
2409
2410 // Restore the opcodes for Tiny Core with Duplexes.
2411 if (ST.isTinyCoreWithDuplex())
2412 QII->translateInstrsForDup(SavedMII, false);
2413
2414 if (GeneratedCompoundInstr) {
2415 // Group B MI should occur 'after' group A MI.
2416 MIInstIterType GBPosMII = GBPos ? GBPos->getIterator() : MBB->instr_end();
2417 MBB->insert(GBPosMII, &*GB);
2418 if (!GB->isBundled())
2419 GB->bundleWithPred();
2420 MIInstIterType GAPosMII = GAPos ? GAPos->getIterator() : MBB->instr_end();
2421 MBB->insert(GAPosMII, &*GA);
2422 assert(GA->isBundled());
2423 NewMI->eraseFromBundle();
2424 }
2425}
2426
2427// TODO: Deal with constant extenders later.
2428// For that we have to try allocate resources for two instructions.
2429bool GlobalScheduler::canReserveResources(MIInstIterType MII) const {
2430 if (QII->isExtended(*MII) || QII->isConstExtended(*MII))
2431 return false;
2432 return ResourceTracker->canReserveResources(*MII);
2433}
2434
2435// The usage of \p Reg is replaced by \p ScratchReg.
2436// @note: Does not do anything with the liveness.
2437void GlobalScheduler::replaceUsageOfReg(unsigned Reg, unsigned ScratchReg,
2438 MachineBasicBlock *MBB,
2439 const MachineInstr *ExceptMI) const {
2440 assert(Reg != ScratchReg);
2441 for (MIInstIterType MII = MBB->instr_begin(), MIE = MBB->instr_end();
2442 MII != MIE; ++MII) {
2443 MachineInstr *MI = &*MII;
2444 if (MI == ExceptMI)
2445 continue;
2446 for (unsigned i = 0; i < MI->getNumOperands(); ++i) {
2447 MachineOperand &MO = MI->getOperand(i);
2448 if (MO.isReg() && (MO.getReg() == Reg))
2449 MO.setReg(ScratchReg);
2450 }
2451 }
2452}
2453
2454void GlobalScheduler::markLiveInsAsUsed(std::unique_ptr<RegScavenger> &RS,
2455 MachineBasicBlock *MBB) const {
2457 lit != MBB->livein_end(); ++lit) {
2458 RS->setRegUsed((*lit).PhysReg);
2459 LLVM_DEBUG(dbgs() << printReg((*lit).PhysReg, TRI););
2460 }
2461}
2462
2463void GlobalScheduler::markLiveOutsAsUsed(std::unique_ptr<RegScavenger> &RS,
2464 MachineBasicBlock *MBB) const {
2465 const BitVector &LO = HLV->getLiveOuts(MBB);
2466 int Reg = LO.find_first();
2467 while (Reg >= 0) {
2468 RS->setRegUsed(Reg);
2469 LLVM_DEBUG(dbgs() << printReg(Reg, TRI););
2470 Reg = LO.find_next(Reg);
2471 }
2472}
2473
2474void GlobalScheduler::markAllRegsAsUsed(std::unique_ptr<RegScavenger> &RS,
2475 const MachineBasicBlock *MBB) const {
2476 // We have to insert a A2_tfr just before the TargetPacket.
2477 // Conservative approach: Traverse all the MIs in DstBB and mark all the
2478 // defs and uses as 'used' in the RegScav.
2479 const MIUseDef_t &MIUseDefs = HLV->getMIUseDefs();
2480 BitVector MBBUseDef(TRI->getNumRegs());
2481 for (MICInstIterType I = MBB->instr_begin(); I != MBB->instr_end(); ++I) {
2482 if (I->isBundle() || I->isDebugInstr())
2483 continue;
2484 MIUseDef_t::const_iterator MIUseDef = MIUseDefs.find(&*I);
2485 assert(MIUseDef != MIUseDefs.end());
2486 MBBUseDef |= MIUseDef->second.first;
2487 MBBUseDef |= MIUseDef->second.second;
2488 }
2489 int Reg = MBBUseDef.find_first();
2490 while (Reg >= 0) {
2491 RS->setRegUsed(Reg);
2492 LLVM_DEBUG(dbgs() << printReg(Reg, TRI););
2493 Reg = MBBUseDef.find_next(Reg);
2494 }
2495}
2496
2497// We want to split the critical edge only when there is a predecessor of ToBB
2498// which is also the layout predecessor of ToBB.
2500 MachineBasicBlock *ToBB) {
2501 // Find the layout predecessor of ToBB.
2502 assert(FromBB->isSuccessor(ToBB));
2503 MachineBasicBlock *LP = NULL;
2505 pe = ToBB->pred_end();
2506 pi != pe; ++pi)
2507 if ((*pi)->isLayoutSuccessor(ToBB))
2508 LP = *pi;
2509 return LP;
2510}
2511
2512MachineBasicBlock *GlobalScheduler::splitCriticalEdge(MachineBasicBlock *FromBB,
2513 MachineBasicBlock *ToBB,
2514 MachineBasicBlock *LP) {
2515 assert(LP->isLayoutSuccessor(ToBB));
2516 MachineBasicBlock *NewBB = MF.CreateMachineBasicBlock();
2517 // We want to insert just before the ToBB because then we don't have to worry
2518 // about the branch range of (FromBB->ToBB).
2519 MF.insert(MachineFunction::iterator(ToBB), NewBB);
2520 FromBB->ReplaceUsesOfBlockWith(ToBB, NewBB);
2521 NewBB->addSuccessor(ToBB);
2522
2523 // Inform HLV of NewBB.
2524 HLV->addNewMBB(NewBB);
2525
2526 // According to the HexagonInstrInfo::getBranchingInstrs
2527 // Only the last element can be a conditional branching instruction.
2528 SmallVector<MachineInstr *, 2> Jumpers = QII->getBranchingInstrs(*LP);
2529 // Jumpers.empty || Jumpers[0] is predicated => fall-through
2530 if ((LP != FromBB) &&
2531 (Jumpers.empty() || !Jumpers[0]->isUnconditionalBranch())) {
2532 DebugLoc dl;
2533 MachineInstr *JumpMI =
2534 BuildMI(*LP, LP->instr_end(), dl, QII->get(Hexagon::J2_jump))
2535 .addMBB(ToBB);
2536 // Update liveness.
2537 HLV->addNewMI(JumpMI, LP);
2538 }
2539 LLVM_DEBUG(dbgs() << "\nLayout Pred after update:" << *LP;);
2540
2541 // We add a jump as a safe-measure, if this is redundant it will be removed.
2542 DebugLoc dl;
2543 MachineInstr *JumpMI =
2544 BuildMI(*NewBB, NewBB->instr_end(), dl, QII->get(Hexagon::J2_jump))
2545 .addMBB(ToBB);
2546 HLV->addNewMI(JumpMI, NewBB);
2547 // Update the branches in LP, invalidate the analyzeBranch of LP and of FromBB
2548 if (AnalyzeBranchInfo.hasABInfo(LP))
2549 AnalyzeBranchInfo.invalidate(LP);
2550 if (AnalyzeBranchInfo.hasABInfo(FromBB))
2551 AnalyzeBranchInfo.invalidate(FromBB);
2552 return NewBB;
2553}
2554
2555// The def should not have subregs.
2556bool GlobalScheduler::hasOneDef(const MachineInstr *MI, unsigned &DefR) const {
2557 DefR = 0;
2558 const MIUseDef_t &MIUseDefs = HLV->getMIUseDefs();
2559 MIUseDef_t::const_iterator MIUseDef = MIUseDefs.find(MI);
2560 if (MIUseDef == MIUseDefs.end())
2561 return false;
2562 const BitVector &Defs = MIUseDef->second.second;
2563 unsigned DefsCount = Defs.count();
2564 // An MI which does not defines a reg should not be here.
2565 assert(DefsCount);
2566 // We don't want to process an MI which defines multiple/no regs.
2567 if (DefsCount != 1)
2568 return false;
2569 DefR = Defs.find_first();
2570 // If this register has a sub-reg we do not want to handle that situation.
2571 return !MCSubRegIterator(DefR, TRI, false).isValid();
2572}
2573
2574// The use should not have subregs.
2575bool GlobalScheduler::hasOneUse(const MachineInstr *MI, unsigned &UseR) const {
2576 UseR = 0;
2577 const MIUseDef_t &MIUseDefs = HLV->getMIUseDefs();
2578 MIUseDef_t::const_iterator MIUseDef = MIUseDefs.find(MI);
2579 if (MIUseDef == MIUseDefs.end())
2580 return false;
2581 const BitVector &Uses = MIUseDef->second.first;
2582 unsigned UsesCount = Uses.count();
2583 // We don't want to process an MI which defines multiple/no regs.
2584 if (UsesCount != 1)
2585 return false;
2586 UseR = Uses.find_first();
2587 // If this register has a sub-reg we do not want to handle that situation.
2588 return !MCSubRegIterator(UseR, TRI, false).isValid();
2589}
2590
2591// MI should have just one def and just one usage.
2592// The def and use should not have subregs.
2593bool GlobalScheduler::hasOneDefAndUse(const MachineInstr *MI, unsigned &Def,
2594 unsigned &Use) const {
2595 return hasOneDef(MI, Def) && hasOneUse(MI, Use);
2596}
2597
2598// Returns later of the two in a linear sequence which might be
2599// I1 .. I2 .. Sentinel, or I2 .. I1 .. Sentinel
2600// If I1 == I2, returns I2.
2601MICInstIterType GlobalScheduler::laterOfTheTwo(MICInstIterType I1,
2602 MICInstIterType I2,
2603 MICInstIterType Sentinel) const {
2604 if (I2 == Sentinel)
2605 return I2;
2606 MICInstIterType Temp = I1;
2607 while (Temp != Sentinel) {
2608 if (Temp == I2)
2609 return I2;
2610 ++Temp;
2611 }
2612 return I1;
2613}
2614
2615// A more exhaustive dependence analysis for load bypass, more aggressive
2616// moves, etc. Used from the HVX local pullup.
2617int GreedyPullup::dstDependence(MICInstIterType DestBeg,
2618 MICInstIterType DestEnd, MICInstIterType MII,
2619 std::vector<const MachineInstr *> &DepTrueVec,
2620 std::vector<const MachineInstr *> &DepAntiVec,
2621 std::vector<const MachineInstr *> &DepOutputVec,
2622 std::vector<unsigned> *Regs) const {
2623
2624 if (DestBeg == DestEnd)
2625 return 0;
2626
2627 unsigned dep = Dependency::Independent;
2628
2629 SmallVector<unsigned> UseRegs;
2630 SmallVector<unsigned> DefRegs;
2631 for (const MachineOperand &MO : MII->operands()) {
2632 if (MO.isReg()) {
2633 if (MO.isUse())
2634 UseRegs.push_back(MO.getReg());
2635 else if (MO.isDef())
2636 DefRegs.push_back(MO.getReg());
2637 }
2638 }
2639
2640 bool addedTrueDep = false, addedFalseDep = false;
2641 auto I = DestEnd;
2642 auto &MIUseDefs = HLV->getMIUseDefs();
2643 do {
2644 --I;
2645 if (!I->isBundle()) {
2646 if (shouldNotBeCrossed(&*I, &*MII)) {
2647 dep = Dependency::Unknown;
2648 break;
2649 }
2650 if (I->isDebugInstr())
2651 continue;
2652 for (auto RegI = UseRegs.begin(), RegE = UseRegs.end(); RegI != RegE;
2653 ++RegI) {
2654 for (MCRegAliasIterator AI(*RegI, TRI, true); AI.isValid(); ++AI) {
2655 if (MIUseDefs[&*I].second[*AI]) {
2656 DepTrueVec.push_back(&*I);
2657 if (Regs)
2658 Regs->push_back(*RegI);
2659 addedTrueDep = true;
2660 dep |= Dependency::RAW;
2661 break;
2662 }
2663 }
2664
2665 if (addedTrueDep) {
2666 UseRegs.erase(RegI);
2667 addedTrueDep = false;
2668 break;
2669 }
2670 }
2671
2672 for (auto RegI = DefRegs.begin(), RegE = DefRegs.end(); RegI != RegE;
2673 ++RegI) {
2674 for (MCRegAliasIterator AI(*RegI, TRI, true); AI.isValid(); ++AI) {
2675 if (MIUseDefs[&*I].second[*AI]) { // WAW case is first
2676 addedFalseDep = true; // WAW prevents any movement, so stop
2677 dep |= Dependency::WAW;
2678 DepOutputVec.push_back(&*I);
2679 break;
2680 }
2681 }
2682
2683 for (MCRegAliasIterator AI(*RegI, TRI, true); AI.isValid(); ++AI) {
2684 if (MIUseDefs[&*I].first[*AI]) {
2685 DepAntiVec.push_back(&*I);
2686 dep |= Dependency::WAR;
2687 break;
2688 }
2689 }
2690
2691 if (addedFalseDep) {
2692 DefRegs.erase(RegI);
2693 addedFalseDep = false;
2694 break;
2695 }
2696 }
2697 }
2698
2699 if (I == DestBeg)
2700 break;
2701
2702 } while (I != DestBeg);
2703
2704 return dep;
2705}
2706
2707//===----------------------------------------------------------------------===//
2708// GreedyPullup Functions
2709//===----------------------------------------------------------------------===//
2710// Returns true if Resources (MII) /\ Resources [DestBeg, DestEnd) != NULL
2711// Use(MII) /\ Def[DestBeg, DestEnd) != NULL
2712// Def(MII) /\ Def+Use[DestBeg, DestEnd) != NULL
2713// For .new MII: Use(MII) /\ Def(Bundle(MII)) == NULL
2714// [DestBeg, DestEnd) can span multiple bundles.
2715// \p DepTrue is the instruction which defines the Operand used by MII.
2716// \p DepAnti is the instruction which uses the Operand defined by MII.
2717// @note: Care must be taken because DepTrue and DepAnti will only give
2718// the def/use of the last operand (there might be more Deps).
2719int GreedyPullup::dstDependence(MICInstIterType DestBeg,
2720 MICInstIterType DestEnd, MICInstIterType MII,
2721 MICInstIterType &DepTrue,
2722 MICInstIterType &DepAnti, unsigned HLXUseReg,
2723 bool IsPullDown) const {
2724 LLVM_DEBUG(dbgs() << "\t[DstDependence]";);
2725 const MachineInstr *MI = &*MII;
2726 const MachineBasicBlock *SrcMBB = MII->getParent();
2727 // Initialize iterators to safe defaults
2728 MICInstIterType DepTrueP = SrcMBB->instr_end(),
2729 DepTrueQ = SrcMBB->instr_end(),
2730 DepAntiP = SrcMBB->instr_end();
2731 DepTrue = SrcMBB->instr_end();
2732 DepAnti = SrcMBB->instr_end();
2733
2734 assert(!shouldNotBePulledUp(&*MII));
2735 MICInstIterType DestBundle =
2736 DestBeg->isBundled() ? getBundleStart(DestBeg) : DestBeg;
2737 MICInstIterType MIBegin = DestBeg;
2738 bool IsMIInDestBundle = false;
2739 for (; MIBegin != DestEnd; ++MIBegin) {
2740 // Need to pass isMIInDestBundle to create single packet HLX load-use-store
2741 // Only do this for local pullup
2742 IsMIInDestBundle = false;
2743 if (!IsPullDown && DestBundle->isBundle() && MIBegin->isBundled())
2744 IsMIInDestBundle = (DestBundle == getBundleStart(MIBegin));
2745 if (!shouldNotBeCrossed(&*MIBegin, &*MII, IsMIInDestBundle))
2746 continue;
2747 LLVM_DEBUG(dbgs() << "<<Unknown dependency>>";);
2748 return Dependency::Unknown;
2749 }
2750 // If MII points to a branch, check that there are no instructions
2751 // between dest bundle end and MII
2752 if (MII->isBranch() || MII->isTerminator() || MII->isReturn()) {
2753 // Only allow local pullup for unbundled endloop.
2754 // Do not allow endloop to be pulled down.
2755 // Check that there are no instructions between DestBundle and endloop.
2756 MICInstIterType SrcBundle = getBundleStart(MII);
2757 if (SrcBundle->getBundleSize() != 1 || SrcMBB != DestBeg->getParent() ||
2758 (laterOfTheTwo(MII, DestBeg, SrcMBB->instr_end()) == DestBeg) ||
2759 getBundleEnd(DestBeg) != SrcBundle) {
2760 LLVM_DEBUG(dbgs() << "<<Unknown dependency>>";);
2761 return Dependency::Unknown;
2762 }
2763 }
2764 unsigned dep = Dependency::Independent;
2765
2766 auto CheckDep = [&](const MachineOperand &MO, unsigned Reg) -> void {
2767 bool IsDef = MO.isReg() ? MO.isDef() : true; // regmask clobbers are defs
2768 const MachineInstr *MI = MO.getParent();
2769 unsigned OpIdx = MO.isReg() ? MO.getOperandNo() : 0;
2770 // Use/Def should not be Defined.
2771 bool destIsBundle = (DestBeg->isBundle() || DestBeg->isBundledWithPred());
2772 // However, return Dependency::Independent for:
2773 // Reg is known to be HLX .new use and has def in Dest bundle
2774 // Reg is known to be use of a HLX load and has tmp def in Dest bundle
2775 if (HLV->isDefinedWithin(DestBeg, DestEnd, Reg, DepTrueP)) {
2776 bool depInDestBundle =
2777 destIsBundle && (getBundleStart(DepTrueP) == getBundleStart(DestBeg));
2778
2779 // DestBundle could have a regular def and a .tmp def
2780 // Regular def could also be a redundant copy (such as l0 = l0)
2781 bool tmpDef = QII->isDotTmpInst(*DepTrueP);
2782 bool regularDef = !tmpDef;
2783 if (depInDestBundle &&
2784 HLV->isDefinedWithin(DestBeg, DepTrueP, Reg, DepTrueQ)) {
2785 tmpDef |= QII->isDotTmpInst(*DepTrueQ);
2786 regularDef |= !tmpDef;
2787 }
2788
2789 bool hasHLXDep = depInDestBundle && (HLXUseReg == Reg);
2790 if (!IsDef) {
2791 // Pull up HLX load use or store.
2792 // We know that DestBundle has .tmp load that feeds the load use
2793 // or DestBundle has a def that feeds .new store
2794 if (hasHLXDep)
2795 return;
2796 LLVM_DEBUG(dbgs() << "<<RAW dependency>>";);
2797 dep |= Dependency::RAW;
2798 } else { // is Def.
2799 if (hasHLXDep && !regularDef)
2800 return;
2801 LLVM_DEBUG(dbgs() << "<<WAW dependency>>";);
2802 dep |= Dependency::WAW;
2803 }
2804 assert(DepTrueP != DestEnd);
2805 DepTrue = DepTrueP;
2806 }
2807 // Defs should not be used in the same packet via operand forwarding (.new,
2808 // .tmp or .cur).
2809 if (!IsDef)
2810 return;
2811 MICInstIterType LastII = DestEnd;
2812 while (HLV->isUsedWithin(DestBeg, LastII, Reg, DepAntiP)) {
2813 bool depInDestBundle =
2814 destIsBundle && (getBundleStart(DepAntiP) == getBundleStart(DestBeg));
2815 const MachineInstr *DepMI = &*DepAntiP;
2816 int UseIdx = DepMI->findRegisterUseOperandIdx(Reg, TRI);
2817 assert(UseIdx >= 0);
2818 // TODO: Packet can have both .cur and .new
2819 bool DefViaRegMask = !MO.isReg(); // regmask clobber has no def operand
2820 if (!EnableDefUseSamePacket || !depInDestBundle ||
2821 !QII->isSafeInBundleWAR(*MI, OpIdx, *DepMI, UseIdx, IsPullDown,
2822 DefViaRegMask)) {
2823 dep |= Dependency::WAR;
2824 assert(DepAntiP != DestEnd);
2825 DepAnti = DepAntiP;
2826 LLVM_DEBUG(dbgs() << "<<WAR dependency>>";);
2827 return;
2828 }
2829 // Safe only if inserted into same bundle as use; callers decide.
2830 dep |= Dependency::WAR_SameBundle;
2831 DepAnti = DepAntiP;
2832 LLVM_DEBUG(dbgs() << "<<WAR_SameBundle dependency>>";);
2833 LastII = DepAntiP;
2834 }
2835 };
2836 // TODO: Check if instruction to be pulled up can be newified
2837 for (unsigned i = 0; i < MI->getNumOperands(); ++i) {
2838 const MachineOperand &MO = MI->getOperand(i);
2839 if (MO.isReg() && MO.getReg()) {
2840 // If this reg has subregs, check dependencies for each subreg
2841 if (MCSubRegIterator(MO.getReg(), TRI, false).isValid()) {
2842 for (MCPhysReg R : TRI->subregs(MO.getReg()))
2843 CheckDep(MO, R);
2844 } else
2845 CheckDep(MO, MO.getReg());
2846 } else if (MO.isRegMask()) {
2847 for (unsigned R = 1, NR = TRI->getNumRegs(); R != NR; ++R)
2848 if (MO.clobbersPhysReg(R))
2849 CheckDep(MO, R);
2850 }
2851 }
2852 return dep;
2853}
2854
2855// Dependence of RMII within the same packet.
2856// \p SrcBeg and \p SrcEnd are begin and end of the bundle respectively.
2857// \p DepSet, if non-null, collects the same-packet instructions that must
2858// move with RMII.
2859int GreedyPullup::srcDependence(
2860 MIInstIterType SrcBeg, MIInstIterType SrcEnd, MIInstIterType RMII,
2861 SmallSetVector<MachineInstr *, 4> *DepSet) const {
2862 LLVM_DEBUG(dbgs() << "\t[SrcDependence]";);
2863 bool PreventDuplex = PreventDuplexSep.getNumOccurrences()
2865 : TM->getOptLevel() <= CodeGenOptLevel::Default;
2866 return QII->srcDependence(SrcBeg, SrcEnd, RMII, HLV->getMIUseDefs(), DepSet,
2867 PreventDuplex, /*IsPullDown=*/false);
2868}
2869
2870bool GreedyPullup::singleTrueDep(MICInstIterType SrcBeg, MICInstIterType SrcEnd,
2871 MICInstIterType MII, unsigned &Reg) const {
2872 const MachineInstr *MI = &*MII;
2873 bool TD = false;
2874 MICInstIterType DepTrueP = SrcEnd;
2875 for (unsigned i = 0; i < MI->getNumOperands(); ++i) {
2876 const MachineOperand &MO = MI->getOperand(i);
2877 if (MO.isReg() && MO.isUse() && MO.getReg()) {
2878 if (HLV->isDefinedWithin(SrcBeg, SrcEnd, MO.getReg(), DepTrueP)) {
2879 if (TD)
2880 return false;
2881 Reg = MO.getReg();
2882 TD = true;
2883 }
2884 }
2885 }
2886 return true;
2887}
2888
2889// Is it okay to execute MI as the first instruction in the MBB.
2890MIIterType GreedyPullup::findInsertionPtSpecLocal(MachineInstr *MI) {
2891 LLVM_DEBUG(dbgs() << "\n[findInsertionPtSpecLocal]");
2892 assert(!shouldNotBePulledUp(MI));
2893 MachineBasicBlock *MBB = MI->getParent();
2894 // First instruction in MBB. Bundled MI can never be the first because
2895 // there will be a Bundle header.
2896 if (MI == &*MBB->getFirstNonDebugInstr())
2897 return MBB->begin();
2898 std::pair<MIInstIterType, MIInstIterType> ParentBundle = getParentBundle(MI);
2899
2900 if (MI->isBundled()) {
2901 // Inside the packet, check only for Src Dependency,
2902 // i.e. are there any consumers of MI within the same packet.
2903 unsigned SrcDep = srcDependence(ParentBundle.first, ParentBundle.second,
2904 MI->getIterator());
2905 // True/Unknown dependence => bail out.
2906 if (!Dependency::hasOnly(SrcDep, Dependency::Independent))
2907 return MBB->end();
2908 // MI is in the first bundle and it has no consumer in the same packet.
2909 if (ParentBundle.first == MBB->getFirstNonDebugInstr())
2910 return MBB->begin();
2911 }
2912
2913 // If MI can execute as the first instruction.
2914 MIIterType InsPos = findInsertPtSpec(MI, MBB, false, false);
2915
2916 return InsPos;
2917}
2918
2919// Local pullup pass to schedule HVX instructions, while avoiding interlock
2920// stalls. Schedule the load bypass opportunities in the basic block
2921// first.
2922void GreedyPullup::localPullupHVX(SchedulingRegion_t::SRAtom_t *SR) {
2924 return;
2925
2926 // Only on innermost loops.
2928 auto *L = MLI.getLoopFor(SR);
2929 if (!L)
2930 return;
2931 if (!isSuperblockLoop(L))
2932 return;
2933 }
2934
2935 // Check if the majority of instructions in the block are HVX instructions.
2936 if (EnableHVXSuperblockHeuristic && !isProfitableToScheduleHVX(SR))
2937 return;
2938
2939 // Route HVX vector pullup through the shared local-pullup engine. HVXMode
2940 // admits plain HVX vector ops as candidates, applies the same
2941 // intermediate-packet-aware dependence checks as scalar pullup, and
2942 // generates .cur load bypasses where profitable.
2943 localPullupImpl(SR, /*HVXMode=*/true);
2944}
2945
2946// InstrToMove is the instruction to be moved to the same packet as LoadInstr
2947// to utilize the load bypass (.cur).
2948// LoadInstr is inside DestBundle.
2949void GreedyPullup::genLoadBypass(MachineInstr *LoadInstr,
2950 MachineInstr *InstrToMove) {
2951 assert(LoadInstr->isBundled() && "Load bypass requires a bundle");
2952 MachineInstr *DestBundle = &*getBundleStart(LoadInstr->getIterator());
2953 int CurOpcode = QII->getDotCurOp(*LoadInstr);
2954 LoadInstr->setDesc(QII->get(CurOpcode));
2955 MIBundleBuilder Bundle(DestBundle);
2956 Bundle.insert(std::next(LoadInstr->getIterator()), InstrToMove);
2957 unsigned DestReg = LoadInstr->getOperand(0).getReg();
2958 for (auto &MO : InstrToMove->operands()) {
2959 if (!MO.isReg())
2960 continue;
2961 if (!MO.isUse())
2962 continue;
2963 for (MCRegAliasIterator AI(MO.getReg(), TRI, true); AI.isValid(); ++AI) {
2964 if (*AI == DestReg)
2965 MO.setIsInternalRead();
2966 }
2967 }
2968}
2969
2970// Returns true if a single RAW dependence on \p DepTrue can be resolved via a
2971// .cur load bypass: \p DepTrue must be a .cur-able HVX load that lives in
2972// DestBundle, there must be no WAW on the destination, and no instruction
2973// other than the consumer being pulled up may read the load's def reg within
2974// the destination packet [next(DestBundle), PktEnd). \p Consumer is the
2975// instruction being pulled up; the cur-load must be its only true-dependence
2976// producer in the pulled region (see the intermediate-producer check below).
2977bool GreedyPullup::canGenCurBypass(MIInstIterType DestBundle,
2978 MachineInstr *DepTrue, MIInstIterType PktEnd,
2979 int DstDep, MachineInstr *Consumer,
2980 const MachineInstr *Exempt) {
2981 assert(Consumer && "Consumer is required for .cur bypass correctness checks");
2982 if (!DepTrue || Dependency::has(DstDep, Dependency::WAW))
2983 return false;
2984 // .cur load bypass is keyed on the mayBeCurLoad TSFlag, not on HVX: any load
2985 // with a .cur form (present or future) is eligible.
2986 if (!QII->mayBeCurLoad(*DepTrue))
2987 return false;
2988 if (&*getBundleStart(DepTrue->getIterator()) != &*DestBundle)
2989 return false;
2990 // If DestBundle is a real bundle, the load must be bundled inside it.
2991 if (DestBundle->isBundle() && !DepTrue->isBundled())
2992 return false;
2993 // No other consumer of the load's def reg may exist in the packet.
2994 unsigned DestReg = DepTrue->getOperand(0).getReg();
2995 for (auto &MI :
2996 iterator_range<MIInstIterType>(std::next(DestBundle), PktEnd)) {
2997 if (&MI == DepTrue)
2998 continue;
2999 for (const MachineOperand &MOP : MI.operands()) {
3000 if (MOP.isReg() && MOP.isUse() && !MOP.isDebug() && MOP.getReg() &&
3001 !MOP.isUndef() && TRI->regsOverlap(MOP.getReg(), DestReg))
3002 return false;
3003 }
3004 }
3005 // .cur only forwards the load's primary def; a post-increment
3006 // load's second (tied pointer) def is not forwarded, so masking the whole
3007 // RAW bit is unsound if the consumer reads that other def instead.
3008 if (Consumer) {
3009 for (const MachineOperand &Def : DepTrue->operands()) {
3010 if (!Def.isReg() || !Def.isDef() || !Def.getReg() ||
3011 Def.getReg() == DestReg)
3012 continue;
3013 for (const MachineOperand &Use : Consumer->operands()) {
3014 if (Use.isReg() && Use.isUse() && !Use.isUndef() && Use.getReg() &&
3015 TRI->regsOverlap(Use.getReg(), Def.getReg()))
3016 return false;
3017 }
3018 }
3019 }
3020 // The caller masks the whole RAW bit, which is only sound if the cur-load is
3021 // the consumer's sole producer across the hoisted region. Refuse if any
3022 // instruction between DestBundle and the consumer defines a reg the consumer
3023 // reads (use-before-def); the scalar dependence surfaces only one producer.
3024 for (MIInstIterType MI = std::next(DestBundle);
3025 MI != Consumer->getIterator() &&
3026 MI != Consumer->getParent()->instr_end();
3027 ++MI) {
3028 if (&*MI == DepTrue || &*MI == Exempt || MI->isBundle())
3029 continue;
3030 for (const MachineOperand &Def : MI->operands()) {
3031 if (!Def.isReg() || !Def.isDef() || !Def.getReg())
3032 continue;
3033 bool ConsumerReads =
3034 llvm::any_of(Consumer->operands(), [&](const MachineOperand &Use) {
3035 return Use.isReg() && Use.isUse() && !Use.isUndef() &&
3036 Use.getReg() && TRI->regsOverlap(Use.getReg(), Def.getReg());
3037 });
3038 if (ConsumerReads)
3039 return false;
3040 }
3041 }
3042 return true;
3043}
3044// Check if moving SrcMI to DestBundle will cause an interlock-stall due to
3045// input latency.
3046bool GreedyPullup::canCauseInterlockStall(MIInstIterType DestBundle,
3047 MachineInstr *SrcMI,
3048 const InstrItineraryData *II) {
3049 bool PrevOK = true;
3050 auto PrevEnd = std::prev(DestBundle);
3051 auto *MBB = SrcMI->getParent();
3052 MachineInstr *PrevStart = nullptr;
3053 if (PrevEnd != MBB->end()) {
3054 if (PrevEnd->isBundled())
3055 PrevStart = &*getBundleStart(PrevEnd);
3056 else
3057 PrevStart = &*PrevEnd;
3058 }
3059
3060 if (PrevEnd != MBB->end() && PrevStart != nullptr) {
3061 std::vector<const MachineInstr *> DepTruePrevVec, DepAntiPrevVec,
3062 DepOutputPrevVec;
3063 std::vector<unsigned> TrueRegs;
3064 int dep = dstDependence(PrevStart->getIterator(), DestBundle,
3065 SrcMI->getIterator(), DepTruePrevVec,
3066 DepAntiPrevVec, DepOutputPrevVec, &TrueRegs);
3067 if (Dependency::has(dep, Dependency::RAW)) {
3068 unsigned RegIdx = 0;
3069 for (auto DepTruePrev : DepTruePrevVec) {
3070 int DefIdx = -1, UseIdx = -1;
3071 for (MCRegAliasIterator AI(TrueRegs[RegIdx], TRI, true);
3072 AI.isValid() && DefIdx == -1; ++AI)
3073 DefIdx = DepTruePrev->findRegisterDefOperandIdx(*AI, /*TRI=*/nullptr);
3074 for (MCRegAliasIterator AI(TrueRegs[RegIdx], TRI, true);
3075 AI.isValid() && UseIdx == -1; ++AI)
3076 UseIdx = SrcMI->findRegisterUseOperandIdx(*AI, /*TRI=*/nullptr);
3077 std::optional<unsigned> OpLatency =
3078 QII->getOperandLatency(II, *DepTruePrev, DefIdx, *SrcMI, UseIdx);
3079 if (!OpLatency) {
3080 ++RegIdx;
3081 continue;
3082 }
3083 int Latency = MF.getSubtarget<HexagonSubtarget>().updateLatency(
3084 *SrcMI, const_cast<MachineInstr &>(*DepTruePrev), false,
3085 *OpLatency);
3086 if (Latency > 1) {
3087 PrevOK = false;
3088 break;
3089 }
3090 ++RegIdx;
3091 }
3092 }
3093 }
3094 return !PrevOK;
3095}
3096
3097// Find all uses of .tmp HLX load and attempt to pullup the uses
3098// to the load's bundle
3099void GreedyPullup::localPullupHLXLoadUses(SchedulingRegion_t::SRAtom_t *SR,
3100 MachineInstr *HLXLoadMI,
3101 MachineInstr *HLXCopyMI) {
3102 LLVM_DEBUG(dbgs() << "\n\n\t\t[LocalPullupHLXLoadUses]");
3103 MIIterType BI =
3105 HLXLoadMI->getIterator());
3106 MIInstIterType DestBundle = BI.getInstrIterator();
3107 unsigned HLXLoadDestReg = HLXLoadMI->getOperand(0).getReg();
3108 unsigned NumLoadUsesPullups = 0;
3109 // List of uses of HLX load that can be pulled up
3110 SmallVector<MachineInstr *, 4> LoadUses;
3111
3112 if (!HLXCopyMI || !HLXLoadDestReg ||
3113 (HLXCopyMI->getOperand(0).getReg() != HLXLoadDestReg))
3114 return;
3115 LLVM_DEBUG(dbgs() << "\nFound HLX load pseudo";
3116 dbgs() << "\nFinding uses of HLX load for pullup into: "
3117 << *DestBundle;);
3118 MachineBasicBlock *MBB = HLXCopyMI->getParent();
3119 MIInstIterType LoadBundleEnd = getBundleEnd(DestBundle);
3120 // Early exit if DestBundle is last bundle in MBB
3121 if (LoadBundleEnd == MBB->end())
3122 return;
3123
3124 // Find all uses of the load
3125 MICInstIterType NextLoadRegDef = MBB->instr_end();
3126 MICInstIterType DepTrueP = MBB->instr_end();
3127 while (HLV->isDefinedWithin(LoadBundleEnd, NextLoadRegDef, HLXLoadDestReg,
3128 DepTrueP))
3129 NextLoadRegDef = DepTrueP;
3130 MICInstIterType PrevLoadRegUse = NextLoadRegDef;
3131 // Instruction that defines HLXLoadDestReg may also use the same register
3132 // Allow isUsedWithin to find it
3133 if (PrevLoadRegUse != MBB->instr_end())
3134 ++PrevLoadRegUse;
3135 while (HLV->isUsedWithin(LoadBundleEnd, PrevLoadRegUse, HLXLoadDestReg,
3136 DepTrueP)) {
3137 LLVM_DEBUG(dbgs() << "\nFound use: "; DepTrueP->dump(););
3138 LoadUses.push_back(&*DepTrueP.getNonConst());
3139 PrevLoadRegUse = DepTrueP;
3140 }
3141
3142 // Check if the load reg is live out from MBB
3143 bool LoadRegIsLiveOut = HLV->isLiveOut(MBB, HLXLoadDestReg) &&
3144 (NextLoadRegDef == MBB->instr_end());
3145
3146 // Check if the bundle contains a call that reads the loaded register
3147 MICInstIterType BStart = getBundleStart(DestBundle);
3148 MICInstIterType BEnd = getBundleEnd(DestBundle);
3149
3150 bool BundleHasCallUse =
3151 QII->hasCallUseInBundle(BStart, BEnd, HLXLoadDestReg, *TRI);
3152
3153 // Attempt to pull up each use of the load
3154 // Iteration order: Nearest to farthest
3155 for (MachineInstr *SrcMI : reverse(LoadUses)) {
3156 if (!HLXCopyMI && (DestBundle->getBundleSize() >= HEXAGON_PACKET_SIZE))
3157 continue;
3158 MIInstIterType SrcMII = SrcMI->getIterator();
3159 // If Use is not bundled, create a single instruction bundle for it
3160 if (!SrcMI->isBundled())
3161 finalizeBundle(*(SrcMI->getParent()), SrcMII, std::next(SrcMII));
3162 // Check if resources are available in Bundle.
3163 std::pair<MIInstIterType, MIInstIterType> ParentBundle =
3164 getParentBundle(&*SrcMII);
3165
3166 LLVM_DEBUG(dbgs() << "\nChecking Resources for: " << *SrcMII;);
3167 if (!isLegalToPacketizeWith(BI, SrcMI) || isSoloInstruction(*SrcMI) ||
3168 shouldNotBePulledUp(SrcMI))
3169 continue;
3170 MICInstIterType DepTrue = MBB->instr_end(), DepAnti = MBB->instr_end();
3171 int DstDep = dstDependence(DestBundle, ParentBundle.first, SrcMII, DepTrue,
3172 DepAnti, HLXLoadDestReg);
3173 int SrcDep = srcDependence(ParentBundle.first, ParentBundle.second, SrcMII);
3174 MIInstIterType DestPos = DestBundle;
3175 getResourcesReadyForBundle(DestPos);
3176 // Delete copy and attempt to pull up the last use
3177 if ((!Dependency::hasOnly(DstDep, Dependency::Independent) ||
3178 !canReserveResources(SrcMII)) &&
3179 !LoadRegIsLiveOut && (NumLoadUsesPullups == (LoadUses.size() - 1)) &&
3180 SrcMI == LoadUses.front() && !BundleHasCallUse) {
3181 LLVM_DEBUG(dbgs() << "\nAttempting to pullup last use by erasing copy: ";
3182 HLXCopyMI->dump(););
3183 HLXCopyMI = HLXCopyMI->removeFromBundle();
3184 DstDep = dstDependence(DestBundle, ParentBundle.first, SrcMII, DepTrue,
3185 DepAnti, HLXLoadDestReg);
3186 getResourcesReadyForBundle(DestPos);
3187 }
3188 // Speculate when there are no dependencies across scheduling path.
3189 if (!(Dependency::hasOnly(DstDep, Dependency::Independent)) ||
3190 !(Dependency::hasOnly(SrcDep, Dependency::Independent)))
3191 continue;
3192 LLVM_DEBUG(dbgs() << "[Can add to packet]";);
3193 if (!canReserveResources(SrcMII)) {
3194 LLVM_DEBUG(dbgs() << " .....NO");
3195 continue;
3196 }
3197 LLVM_DEBUG(dbgs() << "..... YES (Resource available)";);
3198 MachineInstr *InstrToMove = removeMI(SrcMI, QII, nullptr);
3199
3200 MachineOperand *Op = nullptr;
3201 for (MCRegAliasIterator AI(HLXLoadDestReg, TRI, true); AI.isValid(); ++AI) {
3202 Op = InstrToMove->findRegisterUseOperand(*AI, /*TRI=*/nullptr);
3203 if (Op)
3204 break;
3205 }
3206 assert(Op && "Could not find use operand!");
3207 Op->setIsInternalRead();
3208
3209 // Load use must be inserted after the HLX load instruction
3210 // in the bundle to avoid confusing finalizeBundle about liveness
3211 // of the use reg
3212 MIBundleBuilder Bundle(&*DestBundle);
3213 Bundle.insert(std::next(HLXLoadMI->getIterator()), InstrToMove);
3214
3215 // Update pullup count. This might be useful in doing another
3216 // iteration of global pullup into these MBBs.
3217 ++LocalPullups;
3218 ++NumLoadUsesPullups;
3219 LLVM_DEBUG(dbgs() << "\nSpeculated Local MI:\t" << *InstrToMove
3220 << "\nMBB: " << *InstrToMove->getParent());
3221
3222 HLV->updateLocalLiveness(SR, true);
3223 }
3224 // Keep the copy if all uses could not be pulled up, if register is live out,
3225 // if there are no in-bundle uses, or if a call in the bundle reads the reg.
3226 if (NumLoadUsesPullups != LoadUses.size() || LoadRegIsLiveOut ||
3227 BundleHasCallUse) {
3228 // Add back copy if last use could not be pulled up
3229 if (!HLXCopyMI->isBundled()) {
3230 LLVM_DEBUG(dbgs() << "\nRestoring copy\n");
3231 MIBundleBuilder Bundle(&*DestBundle);
3232 Bundle.insert(std::next(HLXLoadMI->getIterator()), HLXCopyMI);
3233 HLV->updateLocalLiveness(SR, true);
3234 }
3235 } else {
3236 // Delete the copy if all uses have been pulled up
3237 if (HLXCopyMI->isBundled())
3238 HLXCopyMI->eraseFromBundle();
3239 else
3240 MF.deleteMachineInstr(HLXCopyMI);
3241 HLV->updateLocalLiveness(SR, true);
3242 }
3243}
3244
3245// Find reaching def of .new HLX store and attempt to pullup the store
3246// to the reaching def's bundle
3247void GreedyPullup::localPullupHLXStore(SchedulingRegion_t::SRAtom_t *SR,
3248 MachineInstr *HLXStoreMI,
3249 MachineInstr *HLXCopyMI) {
3250 LLVM_DEBUG(dbgs() << "\n\n\t\t[LocalPullupHLXStore]");
3251 MIIterType BI =
3253 HLXStoreMI->getIterator());
3254 MIInstIterType SrcBundle = BI.getInstrIterator();
3255 unsigned HLXStoreSrcReg = HLXStoreMI->getOperand(1).getReg();
3256
3257 // Bundle with Def instruction is the destination bundle
3258 MachineInstr *DestMI = nullptr;
3259 // Check if .new HLX store has a HLX copy that feeds it
3260 if (!HLXCopyMI || !HLXStoreSrcReg ||
3261 HLXCopyMI->getOperand(0).getReg() != HLXStoreSrcReg)
3262 return;
3263 LLVM_DEBUG(dbgs() << "\nFound HLX store pseudo";
3264 dbgs() << "\nFinding def for HLX store to be pulled up from: "
3265 << *SrcBundle;);
3266 MachineBasicBlock *MBB = HLXCopyMI->getParent();
3267 MIInstIterType StoreBundleStart = getBundleStart(SrcBundle);
3268
3269 MICInstIterType DepTrueP = MBB->instr_end();
3270 if (HLV->isDefinedWithin(MBB->instr_front().getIterator(), StoreBundleStart,
3271 HLXStoreSrcReg, DepTrueP))
3272 DestMI = &*DepTrueP.getNonConst();
3273
3274 if (!DestMI)
3275 return;
3276 MIInstIterType DestMII = DestMI->getIterator();
3277 // If Def is not bundled, create a single instruction bundle for it
3278 if (!DestMI->isBundled())
3279 finalizeBundle(*(DestMI->getParent()), DestMII, std::next(DestMII));
3280 std::pair<MICInstIterType, MICInstIterType> ParentBundle =
3281 getParentBundle(DestMI);
3282
3283 // Check if resources are available in Bundle.
3284 LLVM_DEBUG(dbgs() << "\nChecking Resources for: " << *HLXStoreMI;);
3285 MIInstIterType DestPos = getBundleStart(DestMII);
3286 if (!isLegalToPacketizeWith(&*DestPos, HLXStoreMI))
3287 return;
3288 MICInstIterType DepTrue = MBB->instr_end(), DepAnti = MBB->instr_end();
3289 int DstDep =
3290 dstDependence(ParentBundle.first, SrcBundle, HLXStoreMI->getIterator(),
3291 DepTrue, DepAnti, HLXStoreSrcReg);
3292
3293 // .new HLX store cannot have dependence on any instruction other than
3294 // feeder copy in source packet. Skip srcDependence check.
3295
3296 // Speculate when there are no dependencies across scheduling path.
3297 if (!Dependency::hasOnly(DstDep, Dependency::Independent))
3298 return;
3299 LLVM_DEBUG(dbgs() << "[Can add to packet]";);
3300 getResourcesReadyForBundle(DestPos);
3301 if (!canReserveResources(HLXStoreMI->getIterator())) {
3302 LLVM_DEBUG(dbgs() << " .....NO");
3303 return;
3304 }
3305 LLVM_DEBUG(dbgs() << "..... YES (Resource available)";);
3306
3307 // Remove the MI before creating the bundle builder, so that the
3308 // builder has the correct iterator bundle end.
3309 MachineInstr *InstrToMove = removeMI(HLXStoreMI, QII, nullptr);
3310
3311 // HLX store must be inserted after the def in the bundle to avoid confusing
3312 // finalizeBundle about liveness of the def reg
3313 MIBundleBuilder Bundle(&*(DestPos));
3314 Bundle.insert(std::next(DestMII), InstrToMove);
3315
3316 if (HLXCopyMI->isBundled())
3317 HLXCopyMI->eraseFromBundle();
3318 else
3319 HLXCopyMI->eraseFromParent();
3320
3321 // Update pullup count. This might be useful in doing another
3322 // iteration of global pullup into these MBBs.
3323 ++LocalPullups;
3324 LLVM_DEBUG(dbgs() << "\nSpeculated Local MI:\t" << *InstrToMove
3325 << "\nMBB: " << *InstrToMove->getParent());
3326 HLV->updateLocalLiveness(SR, true);
3327}
3328
3329// Pullup HLX instructions to create more dense bundles for
3330// HLX load/store instructions.
3331// This will help eliminate HLX copy instructions inserted during pseudo
3332// expansion. Find uses of a .tmp HLX load and try to pullup into the load's
3333// bundle Pullup .new HLX store into a bundle containing its def.
3334void GreedyPullup::localPullupHLX(SchedulingRegion_t::SRAtom_t *SR) {
3335 if (!useHLXOps || !EnableHLXLoadStorePullup)
3336 return;
3337
3338 assert(!SR->empty());
3339 LLVM_DEBUG(dbgs() << "\n\n\t\t[LocalPullupHLX]\tBB#" << SR->getNumber(););
3342 for (MIIterType BI = SR->begin(); BI != SR->end(); ++BI) {
3343 // Do not count DBG instructions if they are present.
3344 if (BI->isDebugInstr())
3345 continue;
3346 // Only look for bundles where HLX load or HLX store pseudos
3347 // were expanded
3348 if (!BI->isBundle() || (!BI->mayLoad() && !BI->mayStore()))
3349 continue;
3350 MachineInstr *HLXLoadMI = nullptr;
3351 MachineInstr *HLXStoreMI = nullptr;
3352 SmallVector<MachineInstr *, 2> HLXCopies;
3353 MIInstIterType MII = BI.getInstrIterator();
3354 for (++MII; // Skip the bundle header.
3355 (MII != SR->instr_end()) && MII->isInsideBundle(); ++MII) {
3356 if (!QII->isHLXVec(*MII))
3357 continue;
3358 switch (MII->getOpcode()) {
3359 case Hexagon::LX_L16b_tmp:
3360 HLXLoadMI = &*MII;
3361 break;
3362 case Hexagon::LX_S16b_new:
3363 HLXStoreMI = &*MII;
3364 break;
3365 case Hexagon::LX_assign:
3366 if (MII->getOperand(0).getReg() == MII->getOperand(1).getReg()) {
3367 HLXCopies.push_back(&*MII);
3368 }
3369 break;
3370 default:
3371 break;
3372 }
3373 }
3374
3375 // Collect all copies and match them to HLX loads/stores by checking
3376 // register operands.
3377 MachineInstr *HLXLoadCopyMI = nullptr;
3378 MachineInstr *HLXStoreCopyMI = nullptr;
3379 for (MachineInstr *CopyMI : HLXCopies) {
3380 Register HLXCopyReg = CopyMI->getOperand(0).getReg();
3381 // If source operand of LX_assign is marked internal,
3382 // it corresponds to HLX load
3383 bool IsInternal = CopyMI->getOperand(1).isInternalRead();
3384 // If we have both HLX load and store in same packet, with two identical
3385 // copies, pair one copy with load and one copy with store.
3386 if (HLXStoreMI && !HLXStoreCopyMI && !IsInternal &&
3387 HLXStoreMI->getOperand(1).getReg() == HLXCopyReg)
3388 HLXStoreCopyMI = CopyMI;
3389 else if (HLXLoadMI && !HLXLoadCopyMI &&
3390 HLXLoadMI->getOperand(0).getReg() == HLXCopyReg)
3391 HLXLoadCopyMI = CopyMI;
3392 }
3393 if (HLXLoadCopyMI)
3394 HLXLoadPseudos.push_back(std::make_pair(HLXLoadMI, HLXLoadCopyMI));
3395 if (HLXStoreCopyMI)
3396 HLXStorePseudos.push_back(std::make_pair(HLXStoreMI, HLXStoreCopyMI));
3397 }
3398
3399 for (auto &LoadPseudo : HLXLoadPseudos)
3400 localPullupHLXLoadUses(SR, LoadPseudo.first, LoadPseudo.second);
3401
3402 for (auto &StorePseudo : HLXStorePseudos)
3403 localPullupHLXStore(SR, StorePseudo.first, StorePseudo.second);
3404}
3405
3406// Try the two-load .cur load-bypass pull-up for a single-instruction cluster.
3407//
3408// This handles a consumer with up to two RAW producers that share a packet,
3409// where one producer is a .cur-able load. The load is rewritten to its .cur
3410// form (forwarding its result within the packet, freeing a register-read
3411// slot); the second producer, if any, is relocated to a loop-predecessor
3412// packet via lastChanceGlobalPullup so the consumer fits.
3413//
3414// Uses the cluster pullup dependence check, which also covers the packets in
3415// between, so SrcMI never moves past a packet it depends on.
3416//
3417// Returns true if it moved SrcMI (caller should skip the common cluster
3418// machinery for this candidate).
3419bool GreedyPullup::tryTwoLoadCurBypass(
3420 MIIterType &BI, SchedulingRegion_t::SRAtom_t *SR,
3421 MIInstIterType &DestBundle, MIIterType &SrcBundle, MIIterType &NextBI,
3422 bool isNextBISrc, MIIterType &Next, MachineInstr *SrcMI,
3423 SmallPtrSetImpl<MachineInstr *> &PulledUpSet) {
3424 MIInstIterType SrcMII = SrcMI->getIterator();
3425 std::pair<MIInstIterType, MIInstIterType> ParentBundle =
3426 getParentBundle(&*SrcMII);
3427
3428 // Enumerate producers via the vector dependence overload; only the vector
3429 // form can express two RAW producers of a single consumer.
3430 std::vector<const MachineInstr *> DepTrueVec, DepAntiVec, DepOutputVec;
3431 int VecDstDep = dstDependence(DestBundle, ParentBundle.first, SrcMII,
3432 DepTrueVec, DepAntiVec, DepOutputVec);
3433
3434 LLVM_DEBUG(dbgs() << "\n[TwoLoadCur] Candidate consumer: " << *SrcMI
3435 << "\t\tRAW producers=" << DepTrueVec.size()
3436 << " output deps=" << DepOutputVec.size() << "\n");
3437
3438 if (!Dependency::has(VecDstDep, Dependency::RAW) || DepTrueVec.size() > 2) {
3439 LLVM_DEBUG(dbgs() << "[TwoLoadCur] Reject: no RAW dep or >2 producers.\n");
3440 return false;
3441 }
3442
3443 bool GenCur = false;
3444 bool PotentialGenCur = false;
3445 const MachineInstr *DepTrue = nullptr;
3446 const MachineInstr *Other = nullptr;
3447
3448 auto IsCurLoad = [&](const MachineInstr *MI) {
3449 return QII->isHVXVec(*MI) && QII->mayBeCurLoad(*MI);
3450 };
3451
3452 if (DepTrueVec.size() == 1) {
3453 const MachineInstr *V0 = DepTrueVec[0];
3454 if (!Dependency::has(VecDstDep, Dependency::WAW) && IsCurLoad(V0) &&
3455 getBundleStart(V0->getIterator()) == DestBundle) {
3456 GenCur = true;
3457 DepTrue = V0;
3458 }
3459 } else if (DepTrueVec.size() == 2 && DepOutputVec.size() <= 1) {
3460 const MachineInstr *V0 = DepTrueVec[0];
3461 const MachineInstr *V1 = DepTrueVec[1];
3462 if (getBundleStart(V0->getIterator()) ==
3463 getBundleStart(V1->getIterator())) {
3464 if (IsCurLoad(V0)) {
3465 DepTrue = V0;
3466 Other = V1;
3467 } else if (IsCurLoad(V1)) {
3468 DepTrue = V1;
3469 Other = V0;
3470 }
3471 if (Other && (!Dependency::has(VecDstDep, Dependency::WAW) ||
3472 Other == DepOutputVec[0]))
3473 PotentialGenCur = true;
3474 }
3475 }
3476
3477 if (!GenCur && !PotentialGenCur)
3478 return false;
3479
3480 LLVM_DEBUG(dbgs() << "[TwoLoadCur] Selected "
3481 << (DepTrueVec.size() == 1 ? "single-load" : "two-load")
3482 << " case: GenCur=" << GenCur
3483 << " PotentialGenCur=" << PotentialGenCur << "\n");
3484
3485 // Validate the load actually lives at the head of the destination bundle.
3486 if (GenCur && DestBundle->isBundle()) {
3487 if (!DepTrue->isBundled() ||
3488 getBundleStart(DepTrue->getIterator()) != DestBundle)
3489 GenCur = false;
3490 }
3491
3492 // The load result must not be consumed by any other instruction between the
3493 // destination bundle and the source bundle (otherwise .cur forwarding is
3494 // unsafe). The second producer (Other) is exempt.
3495 if (GenCur) {
3496 Register DestReg = DepTrue->getOperand(0).getReg();
3497 for (MIInstIterType MI = std::next(DestBundle);
3498 MI != NextBI.getInstrIterator(); ++MI) {
3499 if (&*MI == Other)
3500 continue;
3501 bool Reads = llvm::any_of(MI->operands(), [&](const MachineOperand &MO) {
3502 return MO.isReg() && MO.isUse() && !MO.isUndef() && MO.getReg() &&
3503 TRI->regsOverlap(MO.getReg(), DestReg);
3504 });
3505 if (Reads) {
3506 GenCur = false;
3507 PotentialGenCur = false;
3508 break;
3509 }
3510 }
3511 }
3512
3513 if (!GenCur && !PotentialGenCur)
3514 return false;
3515
3516 // Guard against a third, non-forwardable RAW producer the two-element vector
3517 // dependence misses (use-before-def). Other is relocated later, so exempt it.
3518 if (DepTrue &&
3519 !canGenCurBypass(DestBundle, const_cast<MachineInstr *>(DepTrue),
3520 NextBI.getInstrIterator(), VecDstDep, SrcMI, Other)) {
3521 LLVM_DEBUG(dbgs() << "[TwoLoadCur] Reject: unsafe intermediate RAW "
3522 "producer (canGenCurBypass).\n");
3523 return false;
3524 }
3525
3526 // Allow WAR_SameBundle (SrcMI joins that packet) and, for a .cur, RAW (the
3527 // load is forwarded and the other producer is moved away); any other
3528 // dependence blocks the move.
3529 MachineBasicBlock *MBB = SrcMI->getParent();
3530 MICInstIterType ScalarDepTrue = MBB->instr_end();
3531 MICInstIterType ScalarDepAnti = MBB->instr_end();
3532 int ScalarDstDep = dstDependence(DestBundle, ParentBundle.first, SrcMII,
3533 ScalarDepTrue, ScalarDepAnti);
3534 int DstDepMasked = ScalarDstDep & ~Dependency::WAR_SameBundle;
3535 if (GenCur || PotentialGenCur)
3536 DstDepMasked &= ~Dependency::RAW;
3537 if (!Dependency::hasOnly(DstDepMasked, Dependency::Independent)) {
3538 LLVM_DEBUG(dbgs() << "[TwoLoadCur] Reject: scalar dest dependence not "
3539 "independent after masking.\n");
3540 return false;
3541 }
3542
3543 int SrcDep = srcDependence(ParentBundle.first, ParentBundle.second, SrcMII);
3544 if (!Dependency::hasOnly(SrcDep, Dependency::Independent)) {
3545 LLVM_DEBUG(dbgs() << "[TwoLoadCur] Reject: source dependence not "
3546 "independent.\n");
3547 return false;
3548 }
3549
3550 auto &ST = MF.getSubtarget<HexagonSubtarget>();
3551 const InstrItineraryData *II = ST.getInstrItineraryData();
3552 if (canCauseInterlockStall(DestBundle, SrcMI, II)) {
3553 LLVM_DEBUG(dbgs() << "[TwoLoadCur] Reject: would cause an interlock "
3554 "stall.\n");
3555 return false;
3556 }
3557
3558 // Ensure the destination is a real bundle so we can pull into it.
3559 bool UndoDestBundle = false;
3560 if (!DestBundle->isBundle()) {
3561 finalizeBundle(*DestBundle->getParent(), DestBundle, std::next(DestBundle));
3562 DestBundle = std::prev(DestBundle);
3563 UndoDestBundle = true;
3564 }
3565
3566 MIInstIterType DestPos = DestBundle;
3567 getResourcesReadyForBundle(DestPos);
3568
3569 // PotentialGenCur forces the resource reservation to fail so we drop into
3570 // lastChanceGlobalPullup, which relocates the second producer to free a slot.
3571 bool CanReserve = canReserveResources(SrcMII) && !PotentialGenCur;
3572 bool CanBeMoved = false;
3573 if (!CanReserve) {
3574 const MachineInstr *LoadBypassCand = PotentialGenCur ? Other : nullptr;
3575 LLVM_DEBUG(dbgs() << "[TwoLoadCur] Resources tight; trying "
3576 "lastChanceGlobalPullup (LoadBypassCand="
3577 << (LoadBypassCand ? "Other" : "null") << ").\n");
3578 if ((CanBeMoved =
3579 lastChanceGlobalPullup(DestPos, SrcMII, LoadBypassCand))) {
3580 DestBundle = DestPos;
3581 if (LoadBypassCand)
3582 GenCur = true;
3583 }
3584 } else {
3585 // Single-load .cur bypass whose packet already has room: just packetize.
3586 LLVM_DEBUG(dbgs() << "[TwoLoadCur] Packet has room; packetizing "
3587 "directly.\n");
3588 CanBeMoved = isLegalToPacketizeWith(DestBundle, SrcMI);
3589 }
3590
3591 if (CanBeMoved) {
3592 // Keep NextBI/SrcBundle valid across the move.
3593 bool FixNextBI = false;
3594 if (SrcMII->isBundled()) {
3595 SrcBundle = getBundleStart(SrcMII);
3596 if (&*SrcBundle == &*NextBI)
3597 FixNextBI = true;
3598 } else if (&*SrcMII == &*NextBI) {
3599 NextBI = DestBundle;
3600 }
3601
3602 MachineInstr *SingleInstr = nullptr;
3603 MachineInstr *Instr = removeMI(&*SrcMII, QII, nullptr, &SingleInstr);
3604 if (SingleInstr && FixNextBI)
3605 NextBI = SingleInstr->getIterator();
3606
3607 if (GenCur)
3608 genLoadBypass(const_cast<MachineInstr *>(DepTrue), Instr);
3609 else
3610 MBB->insert(std::next(DestBundle), Instr);
3611
3612 LLVM_DEBUG(dbgs() << "[TwoLoadCur] Pulled up (GenCur=" << GenCur
3613 << "): " << *Instr);
3614 ++LocalPullups;
3615 PulledUpSet.insert(Instr);
3616 HLV->updateLocalLiveness(DestBundle->getParent(), true);
3617 return true;
3618 }
3619
3620 LLVM_DEBUG(dbgs() << "[TwoLoadCur] Reject: candidate could not be moved.\n");
3621 if (UndoDestBundle) {
3622 MIInstIterType I = std::next(DestPos);
3623 I->unbundleFromPred();
3624 DestBundle->eraseFromParent();
3625 DestBundle = I;
3626 }
3627 return false;
3628}
3629
3630// TODO: Handle non-packetized instructions.
3631// @note: Only speculated instructions can be done here.
3632void GreedyPullup::localPullup(SchedulingRegion_t::SRAtom_t *SR) {
3633 localPullupImpl(SR, /*HVXMode=*/false);
3634}
3635
3636// Shared local pullup engine. When HVXMode is set, plain HVX vector ops are
3637// admitted as pullup candidates and .cur load-bypass is generated; otherwise
3638// HVX vector ops are rejected (scalar/HLX behavior).
3639void GreedyPullup::localPullupImpl(SchedulingRegion_t::SRAtom_t *SR,
3640 bool HVXMode) {
3641 assert(!SR->empty());
3642 LLVM_DEBUG(dbgs() << "\n\n\t\t[LocalPullup]\tBB#" << SR->getNumber(););
3643
3644 // Sparse pullup and cluster pullup:
3645 // Enabled by default
3646 // Disabled for TinyCore.
3647
3648 // Allow pullup to/from unbundled instructions or from packets that have <= 2
3649 // instructions.
3650 bool AllowSparsePullup = EnableSparsePullup && !IsTinyCore;
3651
3652 // Allow pullup of cluster of dependent instructions.
3653 bool AllowClusterPullup = EnableClusterPullup && !IsTinyCore;
3654
3655 MIIterType NextBI = SR->begin();
3656 for (MIIterType BI = NextBI; BI != std::prev(SR->end()) && BI != SR->end();
3657 BI = NextBI) {
3658 NextBI = std::next(BI);
3659 if (BI->isDebugInstr())
3660 continue;
3661 MIInstIterType DestBundle = BI.getInstrIterator();
3662 if (!DestBundle->isBundle() && AllowSparsePullup) {
3663 if (isSoloInstruction(*DestBundle))
3664 continue;
3665 finalizeBundle(*(DestBundle->getParent()), DestBundle,
3666 std::next(DestBundle));
3667 DestBundle = std::prev(DestBundle);
3668 BI = DestBundle;
3669 }
3670 if (!DestBundle->isBundle())
3671 continue;
3672 LLVM_DEBUG(dbgs() << "\nDestBundle: " << *DestBundle;);
3673 MIIterType SrcBundle = BI;
3674
3675 // Move to the next bundle to find candidates for local pullup.
3676 // Check dependencies from DestBundle through the SrcBundle.
3677 unsigned NumBundles = 0;
3678 MIIterType Next = std::next(SrcBundle);
3679 for (SrcBundle = Next; SrcBundle != SR->end(); SrcBundle = Next) {
3680 Next = std::next(SrcBundle);
3681 // Do not count DBG instructions if they are present.
3682 if (SrcBundle->isDebugInstr())
3683 continue;
3684 // Verify max pull-up distance based on non-debug values,
3685 // otherwise we can quit earlier in case of -g code.
3686 if (++NumBundles > MaxPUBundles)
3687 break;
3688 if (DestBundle->getBundleSize() >= HEXAGON_PACKET_SIZE)
3689 break;
3690 LLVM_DEBUG(dbgs() << "\nSrcBundle: " << *SrcBundle;);
3691
3692 bool isNextBISrc = false;
3693 if (SrcBundle == std::next(BI))
3694 isNextBISrc = true;
3695
3696 // Pull an unbundled call into the previous packet when the call does
3697 // not depend on that packet, e.g.:
3698 // BUNDLE 4 {
3699 // S4_storeiri_io renamable $r16, 12
3700 // renamable $r0 = L2_loadrub_io killed renamable $r17, 8
3701 // renamable $r17 = A2_addi renamable $r16, 12
3702 // }
3703 // J2_call @Foo
3704 // The generic local pullup does not handle this: the call is not in a
3705 // bundle, and shouldNotBePulledUp rejects calls.
3706 // TODO: Handle this in sparse pullup if shouldNotBePulledUp is relaxed.
3707 if (!SrcBundle->isBundle() && isNextBISrc) {
3708 MIInstIterType MII = SrcBundle.getInstrIterator();
3709 MachineInstr &MI = *MII;
3710 if (MI.getOpcode() == Hexagon::J2_call) {
3711 if (isLegalToPacketizeWith(BI, &MI)) {
3712 MIInstIterType DestPos = DestBundle;
3713 getResourcesReadyForBundle(DestPos);
3714 ++DestPos; // Skip the bundle header.
3715 while (DestPos->isInsideBundle())
3716 ++DestPos;
3717 --DestPos;
3718 if (canReserveResources(MII)) {
3719 NextBI = std::next(SrcBundle);
3720 Next = std::next(SrcBundle);
3721 MachineInstr *InstrToMove = removeMI(&MI, QII, nullptr);
3722 MIBundleBuilder Bundle(&*DestBundle);
3723
3724 Bundle.insert(std::next(DestPos), InstrToMove);
3725
3726 // Update pullup count. This might be useful in doing another
3727 // iteration of global pullup into these MBBs.
3728 ++LocalPullups;
3729 LLVM_DEBUG(dbgs() << "\nSpeculated Local MI:\t" << *InstrToMove
3730 << "\nMBB: " << *InstrToMove->getParent());
3731 HLV->updateLocalLiveness(SR, true);
3732 continue;
3733 }
3734 }
3735 }
3736 }
3737
3738 // When the source bundle has <= 2 instructions, and pullup from sparse
3739 // bundles is disabled, skip the bundle
3740 if (SrcBundle->getBundleSize() <= 2 && !AllowSparsePullup)
3741 continue;
3742
3743 MIInstIterType SrcMII = SrcBundle.getInstrIterator();
3744 if (!SrcMII->isBundled() && AllowSparsePullup) {
3745 if (isSoloInstruction(*SrcMII) || shouldNotBePulledUp(&*SrcMII))
3746 continue;
3747 finalizeBundle(*(SrcMII->getParent()), SrcMII, std::next(SrcMII));
3748 MIInstIterType BundleHead = std::prev(SrcMII);
3749 SrcBundle = BundleHead;
3750 if (isNextBISrc)
3751 NextBI = BundleHead;
3752 SrcMII = BundleHead;
3753 }
3754 MIInstIterType SrcBundleEnd = getBundleEnd(SrcBundle.getInstrIterator());
3755
3757 SmallPtrSet<MachineInstr *, 4> SrcVisitedSet;
3758 // Find a suitable candidate for speculation to DestBundle and speculate.
3759 for (++SrcMII; // Skip the bundle header.
3760 (SrcMII != SR->instr_end()) && SrcMII->isInsideBundle(); ++SrcMII) {
3761 MachineInstr *SrcMI = &*SrcMII;
3762 if (isSoloInstruction(*SrcMI) || SrcMI->isDebugInstr() ||
3763 !SrcVisitedSet.insert(SrcMI).second)
3764 continue;
3765
3766 // Cluster pullup: collect dependent instructions in DepSet.
3767 // A cluster is a set of instructions with same-packet dependencies
3768 // (e.g., .tmp producer and .new consumer) that must be moved together.
3769 // DepSet will contain all instructions in SrcBundle that SrcMI depends
3770 // on.
3771 SmallSetVector<MachineInstr *, 4> DepSet;
3772 int SrcDep =
3773 srcDependence(SrcBundle.getInstrIterator(), SrcBundleEnd, SrcMII,
3774 AllowClusterPullup ? &DepSet : nullptr);
3775 SmallSetVector<MachineInstr *, 4> SrcClusterSet;
3776 if (Dependency::hasOnly(SrcDep, Dependency::Independent)) {
3777 SrcClusterSet.insert(SrcMI);
3778 SrcClusterMIs.push_back(SrcClusterSet);
3779 continue;
3780 }
3781 // If cluster pullup is enabled and we found same-packet dependencies,
3782 // create a cluster containing all dependent instructions.
3783 if (AllowClusterPullup) {
3784 set_union(SrcVisitedSet, DepSet);
3785 if (Dependency::hasOnly(SrcDep, Dependency::SamePacketRAW) ||
3786 Dependency::hasOnly(SrcDep, Dependency::SamePacketWAR) ||
3787 Dependency::hasOnly(SrcDep, Dependency::SamePacket)) {
3788 LLVM_DEBUG(dbgs() << "\nFound cluster of dependent instructions in "
3789 "same packet\n");
3790 for (auto *DepMI : DepSet) {
3791 LLVM_DEBUG(dbgs() << "Cluster MI: "; DepMI->dump());
3792 SrcClusterSet.insert(DepMI);
3793 }
3794 SrcClusterMIs.push_back(SrcClusterSet);
3795 }
3796 }
3797 }
3798
3799 // Sort the clusters by size in descending order
3800 if (AllowClusterPullup) {
3801 llvm::stable_sort(SrcClusterMIs,
3802 [](const auto &ClusterA, const auto &ClusterB) {
3803 return ClusterA.size() > ClusterB.size();
3804 });
3805 }
3806
3807 // Track which instructions have been successfully pulled up to avoid
3808 // pulling the same instruction multiple times (clusters may overlap).
3809 // Pull up clusters from largest to smallest.
3810 // Example candidate:
3811 // {
3812 // renamable $r7, renamable $r2 = L2_loadri_pi killed renamable $r2, 4
3813 // }
3814 // {
3815 // $l4 = LX_L16b_tmp killed renamable $r3
3816 // renamable $ll2 = LX_conv_h_b_lo internal killed renamable $l4
3817 // }
3818 // After cluster pullup:
3819 // {
3820 // $l4 = LX_L16b_tmp killed renamable $r3
3821 // renamable $ll2 = LX_conv_h_b_lo internal killed renamable $l4
3822 // renamable $r7, renamable $r2 = L2_loadri_pi killed renamable $r2, 4
3823 // }
3824 SmallPtrSet<MachineInstr *, 4> PulledUpSet;
3825 SmallPtrSet<MachineInstr *, 4> InsertAtEndSet;
3826 for (auto ClusterSet : SrcClusterMIs) {
3827 bool RejectCluster = false;
3828 // .cur load bypass state for this cluster (HVX mode, single consumer).
3829 MachineInstr *GenCurLoad = nullptr;
3830 MachineInstr *GenCurConsumer = nullptr;
3831 LLVM_DEBUG(dbgs() << "\nChecking pullup legality for cluster: \n";
3832 for (auto *SrcMI : ClusterSet) SrcMI->dump(););
3833
3834 // Two-load .cur bypass (off by default); see tryTwoLoadCurBypass.
3835 if (EnableHVXTwoLoadCurBypass && ClusterSet.size() == 1) {
3836 MachineInstr *SrcMI = *ClusterSet.begin();
3837 if (tryTwoLoadCurBypass(BI, SR, DestBundle, SrcBundle, NextBI,
3838 isNextBISrc, Next, SrcMI, PulledUpSet)) {
3839 continue;
3840 }
3841 }
3842
3843 // Skip this cluster if any instruction was already pulled up.
3844 for (auto *SrcMI : ClusterSet) {
3845 if (PulledUpSet.contains(SrcMI)) {
3846 LLVM_DEBUG(dbgs() << " .....NO, SrcMI has been pulled up: ";
3847 SrcMI->dump(););
3848 RejectCluster = true;
3849 break;
3850 }
3851 }
3852
3853 if (RejectCluster)
3854 continue;
3855
3856 for (auto *SrcMI : ClusterSet) {
3857 LLVM_DEBUG(dbgs() << "\nChecking legality for SrcMI: ";
3858 SrcMI->dump(););
3859
3860 // Do not pull up instructions with multi-cycle latencies, because
3861 // the pull-up pass doesn't correctly
3862 // account for instructions that stall for more than one cycle.
3863 // Exceptions for this: branches, instructions that utilize operand
3864 // forwarding, and HVX vector ops when invoked in HVX mode (their
3865 // latency is checked below via canCauseInterlockStall).
3866 if ((!QII->isTC1(*SrcMI) && !(HVXMode && QII->isHVXVec(*SrcMI)) &&
3867 (!QII->isDotTmpInst(*SrcMI) && !QII->isDotNewInst(*SrcMI) &&
3868 !QII->isDotCurInst(*SrcMI)) &&
3869 (!SrcMI->isBranch() && !SrcMI->isTerminator() &&
3870 !SrcMI->isReturn()))) {
3871 LLVM_DEBUG(dbgs() << " .....NO");
3872 RejectCluster = true;
3873 break;
3874 }
3875
3876 if (!isLegalToPacketizeWith(BI, SrcMI) || isSoloInstruction(*SrcMI) ||
3877 shouldNotBePulledUp(SrcMI)) {
3878 LLVM_DEBUG(dbgs() << " .....NO");
3879 RejectCluster = true;
3880 break;
3881 }
3882 MICInstIterType DepTrue = SR->instr_end(), DepAnti = SR->instr_end();
3883 int DstDep = dstDependence(DestBundle, SrcBundle.getInstrIterator(),
3884 SrcMI->getIterator(), DepTrue, DepAnti);
3885
3886 // A single RAW dependence on a .cur-able load in the destination
3887 // packet can be resolved with a .cur load bypass instead of blocking
3888 // the pullup. Keyed on mayBeCurLoad, not HVX, so any current-value
3889 // load benefits. Only the single-consumer cluster is handled; when
3890 // eligible the RAW bit is masked below so the check is satisfiable.
3891 bool ClusterGenCur =
3892 EnableHVXLocalPullupLB && ClusterSet.size() == 1 &&
3893 Dependency::has(DstDep, Dependency::RAW) &&
3894 DepTrue != SR->instr_end() &&
3895 canGenCurBypass(DestBundle, const_cast<MachineInstr *>(&*DepTrue),
3896 NextBI.getInstrIterator(), DstDep, SrcMI);
3897
3898 // Reject the cluster on any dependence except WAR_SameBundle (the
3899 // cluster joins the bundle) and a RAW resolved by a .cur bypass.
3900 int DstDepMasked = DstDep & ~Dependency::WAR_SameBundle;
3901 if (ClusterGenCur)
3902 DstDepMasked &= ~Dependency::RAW;
3903 if (!(Dependency::hasOnly(DstDepMasked, Dependency::Independent))) {
3904 LLVM_DEBUG(dbgs() << " .....NO");
3905 RejectCluster = true;
3906 break;
3907 }
3908 if (DstDep & Dependency::WAR_SameBundle)
3909 InsertAtEndSet.insert(SrcMI);
3910
3911 if (ClusterGenCur) {
3912 GenCurLoad = const_cast<MachineInstr *>(&*DepTrue);
3913 GenCurConsumer = SrcMI;
3914 }
3915
3916 // Reject if pulling SrcMI into DestBundle violates latency from the
3917 // previous packet (e.g., a multiply result with 2-cycle latency).
3918 // Skip for HLX instructions which have different timing semantics.
3919 if (!QII->isHLXVec(*SrcMI)) {
3920 auto &ST = MF.getSubtarget<HexagonSubtarget>();
3921 const InstrItineraryData *II = ST.getInstrItineraryData();
3922 if (canCauseInterlockStall(DestBundle, SrcMI, II)) {
3923 LLVM_DEBUG(dbgs() << " .....NO (latency violation)");
3924 RejectCluster = true;
3925 break;
3926 }
3927 }
3928
3929 LLVM_DEBUG(dbgs() << " .....YES");
3930 }
3931
3932 // Move to the next cluster if this cluster cannot be pulled up
3933 if (RejectCluster)
3934 continue;
3935
3936 // Check if all instructions in the cluster can fit in the destination
3937 // bundle given current resource constraints.
3938 LLVM_DEBUG(dbgs() << "Checking resources for cluster\n");
3939 MIInstIterType DestPos = DestBundle;
3940 getResourcesReadyForBundle(DestPos);
3941 for (auto *SrcMI : ClusterSet) {
3942 MIInstIterType SrcMII = SrcMI->getIterator();
3943 // Check if resources are available in Bundle.
3944 if (canReserveResources(SrcMII))
3945 addToPacketPseudo(SrcMI);
3946 else {
3947 RejectCluster = true;
3948 break;
3949 }
3950 }
3951
3952 if (RejectCluster)
3953 continue;
3954
3955 // All legality checks passed. Now physically move the cluster.
3956 LLVM_DEBUG(dbgs() << "[Can add to packet]";);
3957 for (auto *SrcMI : ClusterSet) {
3958 // If we have a single instruction bundle here, it means sparse
3959 // pullup is enabled
3960 if (!SrcBundle->isBundled() || SrcBundle->getBundleSize() == 1) {
3961 if (isNextBISrc)
3962 NextBI = std::next(SrcBundle);
3963 Next = std::next(SrcBundle);
3964 }
3965
3966 SmallVector<MachineInstr *, 4> UnbundledMIs;
3967 MachineInstr *InstrToMove = removeMI(SrcMI, QII, &UnbundledMIs);
3968 MIBundleBuilder Bundle(&*DestBundle);
3969
3970 // .cur load bypass: rewrite the load to .cur and let genLoadBypass
3971 // insert the consumer right after it (it performs its own insert and
3972 // marks the internal read), so skip the normal insertion below.
3973 if (GenCurLoad && SrcMI == GenCurConsumer) {
3974 genLoadBypass(GenCurLoad, InstrToMove);
3975 }
3976 // Insert at the end of the bundle: .new MIs, branches and
3977 // terminators go after their producers, and WAR_SameBundle defs go
3978 // after their reader so finalizeBundle does not mark the read
3979 // internal.
3980 else if (QII->isDotNewInst(*InstrToMove) || InstrToMove->isBranch() ||
3981 InstrToMove->isTerminator() ||
3982 InsertAtEndSet.contains(SrcMI))
3983 Bundle.insert(getBundleEnd(DestPos), InstrToMove);
3984 else {
3985 // Insert after any .tmp or .cur instructions at the beginning.
3986 // This maintains correct liveness: .tmp/.cur must be defined before
3987 // other instructions in the packet can use them.
3988 MIInstIterType InsertPos = std::next(DestPos);
3989 while (QII->isDotTmpInst(*InsertPos) ||
3990 QII->isDotCurInst(*InsertPos))
3991 ++InsertPos;
3992 Bundle.insert(InsertPos, InstrToMove);
3993 }
3994
3995 // Update pullup count. This might be useful in doing another
3996 // iteration of global pullup into these MBBs.
3997 ++LocalPullups;
3998 PulledUpSet.insert(InstrToMove);
3999 LLVM_DEBUG(dbgs() << "\nSpeculated Local MI:\t" << *InstrToMove);
4000
4001 // Handle unbundled instructions left behind after removing SrcMI.
4002 // If sparse pullup is enabled, rebundle them; otherwise track them
4003 // for iteration control.
4004 if (UnbundledMIs.empty())
4005 continue;
4006 MIInstIterType UnbundledII = UnbundledMIs.front()->getIterator();
4007 if (AllowSparsePullup) {
4008 MIInstIterType LastUnbundledII = UnbundledMIs.back()->getIterator();
4009 finalizeBundle(*(UnbundledII->getParent()), UnbundledII,
4010 std::next(LastUnbundledII));
4011 --UnbundledII;
4012 }
4013 if (isNextBISrc)
4014 NextBI = UnbundledII;
4015 SrcBundle = UnbundledII;
4016 Next = UnbundledII;
4017 } // end for
4018 LLVM_DEBUG(dbgs() << "\nMBB: "; DestBundle->getParent()->dump());
4019 HLV->updateLocalLiveness(SR, true);
4020 } // end for
4021 } // end for
4022 // If DestBundle is a single instruction bundle at this point,
4023 // unbundle the single instruction to retain compatibility with other APIs
4024 if (AllowSparsePullup && DestBundle->isBundle())
4025 updateBundle(&*DestBundle, QII);
4026 } // end for
4027 // If the last bundle in the scheduling region is a single instruction bundle,
4028 // unbundle the single instruction
4029 MIIterType LastBundle = std::prev(SR->end());
4030 if (AllowSparsePullup && LastBundle->isBundle())
4031 updateBundle(&*LastBundle, QII);
4032}
4033
4034bool GreedyPullup::mergePacketsAround(
4035 const SmallVectorImpl<MachineInstr *> &Candidates) {
4036 bool Changed = false;
4037 for (auto CMII : Candidates) {
4038 MachineInstr *MI = CMII;
4039 MIIterType DestBundle = MI;
4040 MachineBasicBlock *MBB = MI->getParent();
4041 // Since local-pull-up pulls up into preceding bundles,
4042 // we only want to push down into local bundles (immediate next for now).
4043 ++DestBundle;
4044
4045 while (DestBundle != MBB->end() && DestBundle->isDebugInstr())
4046 ++DestBundle;
4047
4048 if (DestBundle == MBB->end() || !DestBundle->isBundle() ||
4049 // Ignore these instructions for simplicity.
4050 shouldNotBePulledUp(MI))
4051 continue;
4052
4053 MICInstIterType DepTrue = MBB->instr_end(), DepAnti = MBB->instr_end();
4054 MIInstIterType DestEnd = getBundleEnd(DestBundle.getInstrIterator());
4055 int DstDep = dstDependence(DestBundle.getInstrIterator(), DestEnd,
4056 MI->getIterator(), DepTrue, DepAnti,
4057 /*HLXUseReg=*/0,
4058 /*isPullDown=*/true);
4059 int DstDepMasked = DstDep & ~Dependency::WAR_SameBundle;
4060 if (!Dependency::hasOnly(DstDepMasked, Dependency::Independent))
4061 continue;
4062
4063 // TODO: Only does a push-down in simple cases without any
4064 // analysis for .new/.cur.
4065 getResourcesReadyForBundle(DestBundle.getInstrIterator());
4066 if (canReserveResources(MI->getIterator()) &&
4067 isLegalToPacketizeWith(DestBundle, MI)) {
4068 LLVM_DEBUG(dbgs() << "\nCan push-down" << *MI);
4069 MachineInstr *MIToInsert = MI->removeFromParent();
4070 MIInstIterType InsertPos = DestBundle.getInstrIterator();
4071 // Insert as the first instruction in bundle (push-down).
4072 MBB->insert(++InsertPos, MIToInsert);
4073 HLV->updateLocalLiveness(MBB, false);
4074 Changed = true;
4075 }
4076 }
4077 return Changed;
4078}
4079
4080// Merge adjacent packets in a BB when possible.
4081// Currently pushing down the individual MIs into next packet.
4082// TODO: push down into later packets as well.
4083bool GreedyPullup::mergePackets() {
4084 bool Changed = false;
4085 for (auto MBB : LocalMergePackCand) {
4086 if (!MBB)
4087 continue;
4088 LLVM_DEBUG(dbgs() << "\nMerging packets within MBB#" << MBB->getNumber(););
4089 SmallVector<MachineInstr *, 2> Candidates;
4090 for (MIIterType MII = MBB->begin(); MII != MBB->end(); ++MII) {
4091 if (!MII->isBundle())
4092 Candidates.push_back(&*MII);
4093 }
4094 Changed |= mergePacketsAround(Candidates);
4095 }
4096 return Changed;
4097}
4098
4099// TODO: Form bigger scheduling regions more than 2 MBBs.
4100void GreedyPullup::globalPullup(SchedulingRegion_t &SR) {
4101 LLVM_DEBUG(dbgs() << "\n[GlobalPullup]";);
4102 // Start from the bottom of the scheduling region (Bottom-up scheduling)
4103 SchedulingRegion_t::reverse_iterator BlockI = SR.rbegin();
4104 assert(!SR.empty() && "Empty scheduling region!");
4105 DenseSet<const MachineBasicBlock *> IgnoreBlocks;
4106 for (++BlockI; BlockI != SR.rend(); ++BlockI) {
4107 if (IgnoreBlocks.find(*BlockI) != IgnoreBlocks.end())
4108 continue;
4109 SchedulingRegion_t::reverse_iterator SrcBlock = BlockI - 1;
4110 LLVM_DEBUG(dbgs() << "\n\t\t*****Speculating MIs from MBB#"
4111 << (*SrcBlock)->getNumber() << " to MBB#"
4112 << (*BlockI)->getNumber() << "*****");
4113 // Do not speculate into a SrcBlock from multiple Blocks.
4114 // Except: When PreciousMICanBeSpeculated.
4115 PulledUpII::iterator hasSpeculatedIns = SpeculatedIns.find(*BlockI);
4116 if (hasSpeculatedIns != SpeculatedIns.end()) {
4117 LLVM_DEBUG(
4118 dbgs() << "\nSrcMBB Already contains speculated ins. Skipping!";);
4119 continue;
4120 }
4121 for (MIInstIterType MII = (*SrcBlock)->instr_begin();
4122 MII != (*SrcBlock)->instr_end();) {
4123 MachineInstr *MIToMove = &*MII;
4124 // The MI might be moved so skip.
4125 ++MII;
4126 if (MIToMove->isDebugInstr())
4127 continue;
4128 LLVM_DEBUG(dbgs() << "\nChecking pullup for MI: "; MIToMove->dump());
4129 MIIterType TargetPacket = (*BlockI)->end();
4130 if (canMIBeSpeculated(MIToMove, *SrcBlock, *BlockI, TargetPacket)) {
4131 // TODO: If MI can be speculated that does not mean
4132 // we 'should' speculate it. Store in ScheduledMI and
4133 // then 'sort/prune' the list before speculating.
4134 LLVM_DEBUG(dbgs() << " .....YES (MICanBeSpeculated)";);
4135 bool done = speculateMI(MIToMove, *SrcBlock, *BlockI, TargetPacket);
4136 SpeculatedIns[*BlockI].push_back(MIToMove);
4137 ++GlobalSpeculatedIns;
4138 // Populate candidates for local push-down.
4139 LocalMergePackCand.insert(*SrcBlock);
4140 (void)done;
4141 assert(done && "Wrong Analysis");
4142 } else
4143 LLVM_DEBUG(dbgs() << " .....NO (MICanBeSpeculated)";);
4144 }
4145 }
4146 BlockI = SR.rbegin();
4147 for (++BlockI; BlockI != SR.rend(); ++BlockI) {
4148 if (IgnoreBlocks.find(*BlockI) != IgnoreBlocks.end())
4149 continue;
4150 SchedulingRegion_t::reverse_iterator SrcBlock = BlockI - 1;
4151 LLVM_DEBUG(dbgs() << "\n\t\t*****Predicating MIs from MBB#"
4152 << (*SrcBlock)->getNumber() << " to MBB#"
4153 << (*BlockI)->getNumber() << "*****");
4154 // Unlike speculation predication can be done from both successors.
4155 for (MIInstIterType MII = (*SrcBlock)->instr_begin();
4156 MII != (*SrcBlock)->instr_end();) {
4157 MachineInstr *MIToMove = &*MII;
4158 // The MI might be moved so skip.
4159 ++MII;
4160 if (MIToMove->isDebugInstr())
4161 continue;
4162 LLVM_DEBUG(dbgs() << "\nChecking pullup for MI: "; MIToMove->dump());
4163 MIIterType TargetPacket = (*BlockI)->end();
4164 MICInstIterType WithinPacket = (*BlockI)->instr_end();
4165 bool NeedToNewify = false, PreciousMIToInsert = false;
4166 if (canMIBePredicated(MIToMove, *SrcBlock, *BlockI, TargetPacket,
4167 WithinPacket, NeedToNewify, PreciousMIToInsert)) {
4168 // TODO: If MI can be predicated that does not mean
4169 // we 'should' predicate it. Store in ScheduledMI and
4170 // then 'sort/prune' the list before predicating.
4171 LLVM_DEBUG(dbgs() << " .....YES (MICanBePredicated)";);
4172 bool done = predicateMI(MIToMove, *SrcBlock, *BlockI, TargetPacket,
4173 WithinPacket, NeedToNewify, PreciousMIToInsert);
4174 (void)done;
4175 assert(done && "Wrong Analysis");
4176 ++GlobalPredicatedIns;
4177 // Populate candidates for local push-down.
4178 LocalMergePackCand.insert(*SrcBlock);
4179 if (PreciousMIToInsert) {
4180 // Once the destination bundle has 5 MIs we want to avoid subsequent
4181 // scheduling into this MBB, so that we skip different sanity checks
4182 // added to ensure consistency in resources available in bundle which
4183 // uses packetizer to track resources and the packetizer does not
4184 // validate more than four instructions in a bundle.
4185 IgnoreBlocks.insert(*BlockI);
4186 ToBeSqueezed.insert(&*TargetPacket);
4187 // Prevent any subsequent e.g. optimizations as well.
4188 IgnorePostSchedOpt.push_back(*BlockI);
4189 LLVM_DEBUG(dbgs() << "\nIgnoring MBB#" << (*BlockI)->getNumber()
4190 << " from further speculation";);
4191 break;
4192 }
4193 } else
4194 LLVM_DEBUG(dbgs() << " .....NO (MICanBePredicated)";);
4195 }
4196 }
4197 // TODO: Look for packetization opportunities or
4198 // or leave this task for MergePackets.
4199 // TODO: Perform branch/post-pullup optimizations.
4200}
4201
4202// Analyze a bundle/independent-instruction at a time.
4203// Perform a bottom up traversal on the def-use set of DstBB MIs.
4204// Resource available in BUNDLE && Dependency constraints are met => done!
4205// Returns the position *before* which \p SrcMI could be inserted.
4206// In case of BUNDLE the \p SrcMI can be inserted within that BUNDLE.
4207// TODO: Insert into a BUNDLE even if there are WAR dependencies
4208// See also findInsertPtPred().
4209// \p SpecPreciousMIComp = true, when speculating PreciousMI comp. code.
4210// \p SpecPreciousMI = true, when speculating PreciousMI.
4211// \p GlobalPrecious = true, when hoisting SrcMI from the innermost single block
4212// loop. Stop searching after the first available bundle with resources.
4213MIIterType GreedyPullup::findInsertPtSpec(MachineInstr *SrcMI,
4214 MachineBasicBlock *DstBB,
4215 bool SpecPreciousMI,
4216 bool SpecPreciousMIComp,
4217 bool GlobalPrecious) {
4218 LLVM_DEBUG(dbgs() << "\n[FindInsertPtSpec]";);
4219 MIIterType DstEnd = DstBB->end();
4220 MIInstIterType InsPos = DstBB->instr_end();
4221 MICInstIterType DepTrue = DstBB->instr_end(), DepAnti = DstBB->instr_end();
4222 if (shouldNotBePulledUp(SrcMI) ||
4223 (QII->isPredicated(*SrcMI) && QII->isPredicatedNew(*SrcMI)) ||
4224 isSoloInstruction(*SrcMI))
4225 return DstEnd;
4226 LLVM_DEBUG(dbgs() << "\nChecking Resource conflict\n";);
4227
4228 // Perform a bottom up traversal on the def-use set of DstBB MIs.
4229 MIRIterType MII = getSpeculationBeginPoint(SrcMI, DstBB);
4230 for (; MII != DstBB->rend(); ++MII) {
4231 MachineInstr *MI = &*MII;
4232 if (MI->isDebugInstr())
4233 continue;
4234 LLVM_DEBUG(dbgs() << "\n\tAgainst:\t* " << *MI;);
4235 // Check for dependencies [RangeBeg, MII) <- in reverse order.
4236 if (MI->isBundle()) {
4237 int DstDep = dstDependence(MI->getIterator(), InsPos,
4238 SrcMI->getIterator(), DepTrue, DepAnti);
4239 if (!Dependency::hasOnly(DstDep, Dependency::Independent))
4240 break;
4241 // A precious MI takes this bundle as the insertion point before the
4242 // resource check; speculateMI() inserts it just before the bundle if it
4243 // does not fit. Other MIs only move into bundles with free resources.
4244 if (SpecPreciousMI)
4245 InsPos = MI->getIterator();
4246 // Continue searching higher up.
4247 LLVM_DEBUG(
4248 dbgs() << "\n\tNo conflict (BUNDLE)! Checking resources.....\n";);
4249 // Check if resources are available in BUNDLE or not.
4250 getResourcesReadyForBundle(MI->getIterator(), SpecPreciousMI);
4251 if (canReserveResources(SrcMI->getIterator())) {
4252 if (!isLegalToPacketizeWith(MI, SrcMI) || NoSpecInBundle)
4253 break;
4254 InsPos = MI->getIterator();
4255 LLVM_DEBUG(dbgs() << ".....(Resources available. Checking higher up)";);
4256 if (GlobalPrecious && InsPos->isBundle())
4257 break;
4258 // Check for dst dep from insertion point until the end of DstBB.
4259 } else {
4260 LLVM_DEBUG(
4261 dbgs() << ".....(No Resources (BUNDLE) Checking further up)";);
4262 // Keep searching higher up; SrcMI is not placed in this bundle.
4263 }
4264 } else {
4265 // Check for dst dep from insertion point until the end of DstBB.
4266 int DstDep = dstDependence(MI->getIterator(), InsPos,
4267 SrcMI->getIterator(), DepTrue, DepAnti);
4268 if (!Dependency::hasOnly(DstDep, Dependency::Independent))
4269 break;
4270 // TODO: Move this somewhere else and abstract it together with
4271 // the code in isLegalToPacketize.
4272 if (QII->isLoopN(*SrcMI)) {
4273 // loopN cannot be pulled too far.
4274 unsigned dist = HLV->getDistanceBetween(MI->getParent(),
4275 SrcMI->getOperand(0).getMBB());
4276 if (!QII->isJumpWithinBranchRange(*SrcMI, dist + SafetyBuffer)) {
4277 LLVM_DEBUG(dbgs() << "\nLoopN cannot be pulled too far into MBB";);
4278 break;
4279 }
4280 }
4281 // Continue searching higher up.
4282 InsPos = MI->getIterator();
4283 LLVM_DEBUG(dbgs() << "No conflict! Checking further up .....\n";);
4284 }
4285 }
4286
4287 if (InsPos == DstBB->instr_end())
4288 return DstEnd;
4289
4290 assert(!InsPos->isInsideBundle());
4291
4292 if (inBetweenBarriers(&*InsPos, DstBB))
4293 return DstEnd;
4294
4295 // Don't speculate outside a bundle when there are multiple execution
4296 // paths from the DstBB. When SpecPreciousMI = true, then in that case if
4297 // InsPos is a bundle then SpeculateMI will insert SrcMI 'just' before
4298 // the BUNDLE when the resources are not available.
4299 // For details see speculateMI().
4300 // TODO: What if resources were available in BUNDLE then higher up
4301 // InsPos was not in a BUNDLE, that time speculation will not happen.
4302 if (!InsPos->isBundle() && !SpecPreciousMIComp && (DstBB->succ_size() > 1))
4303 return DstEnd;
4304
4305 return InsPos;
4306}
4307
4308// @note: The SrcMI can be modified by this function.
4309MIIterType GreedyPullup::findInsertPtPred(MachineInstr *SrcMI,
4310 MachineBasicBlock *DstBB,
4311 bool &NeedToNewify,
4312 MICInstIterType &WithinPacket,
4313 bool PredPreciousMI) {
4314 LLVM_DEBUG(dbgs() << "\n[FindInsertPtPred]";);
4315 MIIterType DstEnd = DstBB->end();
4316 MIInstIterType InsPos = DstBB->instr_end();
4317 MICInstIterType DepTrue = DstBB->instr_end(), DepAnti = DstBB->instr_end();
4318 if (shouldNotBePulledUp(SrcMI) || !QII->isPredicated(*SrcMI) ||
4319 QII->isPredicatedNew(*SrcMI) || isSoloInstruction(*SrcMI))
4320 return DstEnd;
4321 NeedToNewify = false;
4322 WithinPacket = DstBB->instr_end();
4323 LLVM_DEBUG(dbgs() << "\n[FindInsertionPointPredicatedIns]" << *SrcMI;);
4324 LLVM_DEBUG(dbgs() << "\nChecking Resource conflict\n";);
4325 // Perform a bottom up traversal on the def-use set of DstBB MIs.
4326 for (MIRIterType MII = DstBB->rbegin(); MII != DstBB->rend(); ++MII) {
4327 MachineInstr *MI = &*MII;
4328 if (MI->isDebugInstr())
4329 continue;
4330 LLVM_DEBUG(dbgs() << "Against:\t* " << *MI;);
4331 // Check for dependencies [RangeBeg, MII) <- in reverse order.
4332 if (MI->isBundle()) {
4333 // Check if resources are available in BUNDLE or not.
4334 getResourcesReadyForBundle(MI->getIterator(), PredPreciousMI);
4335 if (canReserveResources(SrcMI->getIterator())) {
4336 if (!isLegalToPacketizeWith(MI, SrcMI) || NoPredInBundle)
4337 break;
4338 // Check for dst dep from insertion point until the end of DstBB.
4339 int DstDep = dstDependence(MI->getIterator(), InsPos,
4340 SrcMI->getIterator(), DepTrue, DepAnti);
4341 // check for .new and look no further.
4342 if (Dependency::hasOnly(DstDep, Dependency::RAW)) {
4343 // The dstMI should define a predicate which SrcMI should use.
4344 // And SrcMI should be newifiable.
4345 // Set NeedToNewify = true;
4346 // For RAW in the packet this is perfectly fine and
4347 // no need for further analysis.
4349 << "Read after write dependency with: " << *DepTrue;);
4350 unsigned DefP = 0;
4351 if ((InsPos != DepTrue) && hasOneDef(&*DepTrue, DefP)) {
4352 if (canNewifyPredReg(DefP, DepTrue, DstBB->instr_end()) &&
4353 SrcMI->readsRegister(DefP, /*TRI=*/nullptr) &&
4354 isNewifiable(*SrcMI, &Hexagon::PredRegsRegClass)) {
4355 InsPos = MI->getIterator();
4356 WithinPacket = DepTrue;
4357 NeedToNewify = true;
4358 LLVM_DEBUG(dbgs() << "\tokay (BUNDLE)!";);
4359 }
4360 } else {
4361 LLVM_DEBUG(dbgs() << "\tNot okay (BUNDLE)!";);
4362 }
4363 break;
4364 }
4365 // WAR is fine in the same packet, but look no further.
4366 int DstDepMasked = DstDep & ~Dependency::WAR_SameBundle;
4367 if (Dependency::hasOnly(DstDepMasked, Dependency::RAW)) {
4368 unsigned DepReg = 0;
4369 LLVM_DEBUG(dbgs() << "WAR_SameBundle dependency with: " << *DepAnti;);
4370 if (singleTrueDep(MI->getIterator(), InsPos, SrcMI->getIterator(),
4371 DepReg)) {
4372 MICIterType MIBundle = &*MII;
4373 MICInstIterType Sentinel =
4374 MIBundle == DstBB->end()
4375 ? DstBB->instr_end()
4376 : std::next(MIBundle).getInstrIterator();
4377 if (canNewifyPredReg(DepReg, DepTrue, Sentinel)) {
4378 // WAR for one and RAW for the predicate ins.
4379 InsPos = MI->getIterator();
4380 WithinPacket = laterOfTheTwo(DepTrue, DepAnti, Sentinel);
4381 assert(WithinPacket != Sentinel);
4382 NeedToNewify = true;
4383 LLVM_DEBUG(dbgs() << "Single RAW dependency with: " << *DepTrue;);
4384 }
4385 }
4386 // TODO: Enable this case of only WAR. WithinPacket = DepAnti;
4387 LLVM_DEBUG(dbgs() << "Write after read, okay (BUNDLE)!";);
4388 }
4389 // can look further up.
4390 if (Dependency::hasOnly(DstDep, Dependency::Independent)) {
4391 InsPos = MI->getIterator();
4392 LLVM_DEBUG(dbgs() << "No conflict (BUNDLE)! Checking further up!\n";);
4393 continue;
4394 }
4395 break;
4396 } else {
4397 LLVM_DEBUG(dbgs() << "No Resources";);
4398 // We don't want to move further up because we haven't analyzed the
4399 // dependencies for this packet. We might, but that will make things
4400 // more complicated.
4401 break;
4402 }
4403 } else {
4404 // Check for dst dep from insertion point until the end of DstBB.
4405 int DstDep = dstDependence(MI->getIterator(), InsPos,
4406 SrcMI->getIterator(), DepTrue, DepAnti);
4407 if (!Dependency::hasOnly(DstDep, Dependency::Independent))
4408 break;
4409 // Continue searching higher up.
4410 InsPos = MI->getIterator();
4411 LLVM_DEBUG(dbgs() << "No conflict! Checking further up .....\n";);
4412 }
4413 }
4414 if (InsPos == DstBB->instr_end())
4415 return DstEnd;
4416
4417 assert(!InsPos->isInsideBundle());
4418 if (inBetweenBarriers(&*InsPos, DstBB))
4419 return DstEnd;
4420 return InsPos;
4421}
4422
4423// Is the instruction a candidate for the "last chance global pullup"?
4424// That is, these are the instructions from single block innermost loops that
4425// could be hoisted to the loop entry AND copied to a downstream packet to
4426// free up a resource.
4427// Here, y is a candidate for the "last chance global pullup".
4428// {
4429// x = ...
4430// y = y1, y2 <--- where y1, y2 are loop invariant
4431// }
4432// z = ...
4433// {
4434// ...
4435// ... = y<killed>
4436// }
4437// br Loop
4438//
4439// Only V6_vcombine is handled.
4440// See GreedyPullup::lastChanceGlobalPullup for more details.
4441MachineInstr *
4442GreedyPullup::isLastChanceGlobalPullupCand(const MachineInstr *MI) {
4443 if (MI->getOpcode() != Hexagon::V6_vcombine)
4444 return nullptr;
4445 auto *MBB = MI->getParent();
4446
4447 unsigned Op0 = MI->getOperand(0).getReg();
4448 unsigned Op1 = MI->getOperand(1).getReg();
4449 unsigned Op2 = MI->getOperand(2).getReg();
4450 MICInstIterType DefUseR = MBB->instr_end();
4451
4452 if (MBB->isLiveIn(Op1) && MBB->isLiveIn(Op2) && // y1, y2 live in
4453 !HLV->isDefinedWithin(MBB->instr_begin(), MBB->instr_end(), Op1,
4454 DefUseR) && // and y1, y2 are loop invariant
4455 !HLV->isDefinedWithin(MBB->instr_begin(), MBB->instr_end(), Op2,
4456 DefUseR)) {
4457 if (HLV->isDefinedWithin(std::next(MI->getIterator()), MBB->instr_end(),
4458 Op0, DefUseR)) {
4459 // Cannot be live out.
4460 for (MCRegAliasIterator AI(Op0, TRI, true); AI.isValid(); ++AI)
4461 if (HLV->isLiveOut(MBB, *AI))
4462 return nullptr;
4463
4464 // Find the point where it's killed.
4465 MICInstIterType Use = MBB->instr_end();
4466 if (!HLV->isUsedWithin(std::next(DefUseR), MBB->instr_end(), Op0, Use))
4467 return nullptr;
4468
4469 auto regmaskMOs = collectRegmaskMOs(*MBB);
4470 for (auto *MO : regmaskMOs)
4471 if (MO->clobbersPhysReg(Op0) || MO->clobbersPhysReg(Op1) ||
4472 MO->clobbersPhysReg(Op2))
4473 return nullptr;
4474
4475 MachineInstr *InsertBundle = (MachineInstr *)(const_cast<MachineInstr *>(
4476 &*getBundleStart(Use->getIterator())));
4477
4478 if (!InsertBundle->isBundle())
4479 return nullptr;
4480
4481 return InsertBundle;
4482 }
4483 }
4484 return nullptr;
4485}
4486
4487// Attempt to hoist/copy an instruction from BundleHead to make room for
4488// InstrToMove, if beneficial.
4489// Here, y is a candidate for the "last chance global pullup"
4490// Loop:
4491// {
4492// x = ...
4493// y = y1, y2 <--- where y1, y2 are loop invariant
4494// }
4495// z = ... <--- z could be moved to the packet above if not for y
4496// {
4497// ...
4498// ... = y<killed>
4499// }
4500// br Loop
4501//
4502// If the last chance global pullup is successful, we will end up with:
4503// {
4504// y = y1, y2 <--- global pull up to make it live into the loop
4505// }
4506// Loop:
4507// {
4508// x = ...
4509// z = ... <---- z will get moved to the packet
4510// }
4511// {
4512// y = y1,y2 <--- make it live into the loop
4513// ... = y<killed> <-- uses old value (3.3.1 packet execution semantics)
4514// }
4515// br Loop
4516//
4517bool GreedyPullup::lastChanceGlobalPullup(MIInstIterType &BundleHead,
4518 MIInstIterType InstrToMove,
4519 const MachineInstr *LoadBypassCand) {
4520 if (!EnableHVXLCGP)
4521 return false;
4522 if (EnableLCGPForLoadBypassOnly && LoadBypassCand == nullptr)
4523 return false;
4524 MachineLoop *Loop = MLI.getLoopFor(BundleHead->getParent());
4525 if (!isSuperblockLoop(Loop))
4526 return false;
4527 if (InstrToMove->getOpcode() == Hexagon::V6_vcombine)
4528 return false;
4529 auto MII = BundleHead->getIterator();
4530 MachineInstr *SingleInstr = nullptr;
4531 std::vector<std::pair<MachineInstr *, MachineInstr *>> candidatesForHoist;
4532 auto MBB = MII->getParent();
4533
4534 for (++MII; MII->isInsideBundle(); ++MII)
4535 if (auto *InsertBundle = isLastChanceGlobalPullupCand(&*MII))
4536 candidatesForHoist.emplace_back(&*MII, InsertBundle);
4537
4538 // Find a place to insert
4539 for (auto Cand : candidatesForHoist) {
4540 // Check if it's worth kicking it out
4541 getResourcesReadyForBundle(BundleHead->getIterator(), false,
4542 Cand.first); // kick out
4543 if (!canReserveResources(InstrToMove))
4544 continue;
4545
4546 // We have our candidate; Check if we can place it in the outer scope.
4547 auto *Pred = Loop->getLoopPredecessor();
4548
4549 if (Pred) {
4550 auto TargetPacket = findInsertPtSpec(Cand.first, Pred, false, true);
4551 if (TargetPacket != Pred->end()) {
4552 // We have the packet to which to copy.
4553 for (MIIterType BI = Cand.second; BI != MBB->end(); ++BI) {
4554 if (LoadBypassCand && LoadBypassCand != &*Cand.first)
4555 continue;
4556 if (!BI->isBundle())
4557 continue;
4558 getResourcesReadyForBundle(BI->getIterator());
4559 if (canReserveResources(Cand.first->getIterator())) {
4560 if (isLegalToPacketizeWith(BI, Cand.first)) {
4561 // Now find a spot to copy to make it live in
4562 // Cand.second is the place where it's killed
4563 // Copy the instruction to make it live out of the loop;
4564 MachineInstr *ClonedInstr = MF.CloneMachineInstr(Cand.first);
4565 MIBundleBuilder Bundle(&*BI);
4566 MICInstIterType Use = MBB->instr_end();
4567 if (HLV->isUsedWithin(std::next(BI.getInstrIterator()),
4568 getBundleEnd(BI.getInstrIterator()),
4569 Cand.first->getOperand(0).getReg(), Use)) {
4570 ++Use;
4571 MachineInstr *UseMI = const_cast<MachineInstr *>(&*Use);
4572 Bundle.insert(UseMI->getIterator(), ClonedInstr);
4573 BI->addRegisterDefined(Cand.first->getOperand(0).getReg());
4574 } else {
4575 MIInstIterType DestPos = BI->getIterator();
4576 Bundle.insert(std::next(DestPos), ClonedInstr);
4577 }
4578
4579 assert(!MBB->isLiveIn(Cand.first->getOperand(0).getReg()) &&
4580 "Already live-in");
4581 MBB->addLiveIn(
4582 Cand.first->getOperand(0).getReg()); // Make sure it's live in
4583
4584 auto *Instr =
4585 removeMI(Cand.first, QII, nullptr,
4586 &SingleInstr); // may invalidate the bundle, DestPos
4587 // invalidated
4588
4589 // Not a bundle any longer; turn into a single instruction bundle,
4590 // as the local pullup pass expects a bundle into which to move
4591 // the instruction.
4592 if (SingleInstr) {
4593 BundleHead = SingleInstr->getIterator();
4594 finalizeBundle(*BundleHead->getParent(), BundleHead,
4595 std::next(BundleHead));
4596 BundleHead = std::prev(BundleHead);
4597 }
4598
4599 // Now hoist to the predecessor (i.e. global move)
4600 MIInstIterType DestPos = TargetPacket.getInstrIterator();
4601 // Already a bundle
4602 if (DestPos->isBundle()) {
4603 MIBundleBuilder HoistBundle(&*TargetPacket);
4604 HoistBundle.insert(std::next(DestPos), Instr);
4605 } else {
4606 // Check if it's safe to form a bundle
4607 finalizeBundle(*Pred, DestPos, std::next(DestPos));
4608 auto CheckBundle = std::prev(DestPos);
4609 getResourcesReadyForBundle(CheckBundle);
4610 if (canReserveResources(Instr->getIterator()) &&
4611 isLegalToPacketizeWith(CheckBundle, Instr)) {
4612 MIBundleBuilder HoistBundle(&*CheckBundle);
4613 HoistBundle.insert(std::next(CheckBundle), Instr);
4614 } else {
4615 DestPos->unbundleFromPred();
4616 CheckBundle->eraseFromParent();
4617 Pred->insertAfter(&*DestPos, Instr);
4618 }
4619 }
4620 HLV->updateLocalLiveness(Pred, true);
4621 return true;
4622 }
4623 }
4624 }
4625 }
4626 }
4627 }
4628 return false;
4629}
4630
4631// Currently we are only interested in speculating to
4632// immediate (dominating) predecessor.
4633bool GreedyPullup::canMIBeSpeculated(MachineInstr *MI, MachineBasicBlock *SrcBB,
4634 MachineBasicBlock *DstBB,
4635 MIIterType &TargetPacket) {
4636 LLVM_DEBUG(dbgs() << "\n[canMIBeSpeculated]");
4637 TargetPacket = DstBB->end();
4638
4639 MachineLoop *L = MLI.getLoopFor(SrcBB);
4640 bool isSuperBlockL = isSuperblockLoop(L);
4641 if (isSuperBlockL) {
4642 if (!isLoopInvariant(*MI))
4643 return false;
4644 }
4645
4646 // No dependency in the current SrcBB
4647 if (shouldNotBePulledUp(MI) || findInsertionPtSpecLocal(MI) != SrcBB->begin())
4648 return false;
4649 LLVM_DEBUG(dbgs() << " .....YES";);
4650 ABI &abi = AnalyzeBranchInfo.getOrCreate(DstBB, QII);
4651 // TODO: Handle SchedulingRegions with more than 2 blocks.
4652 if (!abi.AnalysisValid)
4653 return false;
4654 assert(abi.TBB && abi.FBB);
4655 if (!DstBB->isSuccessor(SrcBB))
4656 return false;
4657 bool SrcIsTBB = (abi.TBB == SrcBB);
4658 MachineBasicBlock *OtherBB = abi.FBB;
4659 if (!SrcIsTBB) {
4660 assert(abi.FBB == SrcBB);
4661 OtherBB = abi.TBB;
4662 }
4663
4664 assert(isSuperBlockL || SrcBB->pred_size() == 1);
4665
4666 if (!safeToSpeculate(MI, DstBB))
4667 return false;
4668 LLVM_DEBUG(dbgs() << " .....YES (SafeToSpeculate)";);
4669 // The def(s) of MI should not be live-in in the 'Other' branch.
4670 // TODO: If it is live-in in the 'Other' branch, even then we can speculate
4671 // provided we assign the live-in value to a new register
4672 // and replace the usage with the new register in the 'Other' branch.
4673 bool DefLiveInOtherBB = HLV->isDefLiveIn(MI, OtherBB);
4674 MIIterType TargetPacketIntMI = DstBB->end();
4675 bool PreciousMIShouldBeSpeculated = false;
4676 if (DefLiveInOtherBB) {
4677 LLVM_DEBUG(dbgs() << " ..... (DefLiveInOtherBB)";);
4678 if (!preciousToSpeculate(MI, SrcBB, DstBB, OtherBB))
4679 return false;
4680 LLVM_DEBUG(dbgs() << " .....YES (PreciousToSpeculate)";);
4681 if (!preciousMICanBeSpeculated(MI, SrcBB, DstBB, OtherBB, TargetPacketIntMI,
4682 1))
4683 return false;
4684 PreciousMIShouldBeSpeculated = true;
4685 LLVM_DEBUG(dbgs() << " .....YES (PreciousMICanBeSpeculated)";);
4686 } else
4687 LLVM_DEBUG(dbgs() << " ..... (DefNotLiveInOtherBB)";);
4688
4689 // If MI is loop invariant in the innermost single-block loop, try hard
4690 // to hoist during global pull-up. This is indicated with GlobalPrecious;
4691 bool GlobalPrecious = false;
4692 if ((EnableSingleLoopSuperblock && useHVXOps && isSuperBlockL &&
4694 isLoopInvariant(*MI))
4695 GlobalPrecious = true;
4696
4697 TargetPacket = findInsertPtSpec(MI, DstBB, PreciousMIShouldBeSpeculated,
4698 false, GlobalPrecious);
4699
4700 // Verify what we did was correct.
4701 if (DefLiveInOtherBB) {
4702 MICInstIterType TestIt = DstBB->instr_begin();
4703 // MI cannot be at or before the position of the inserted A2_tfr.
4704 while (TestIt != TargetPacketIntMI.getInstrIterator()) {
4705 assert(TestIt != TargetPacket.getInstrIterator());
4706 ++TestIt;
4707 }
4708 }
4709
4710 if (TargetPacket != DstBB->end()) {
4711 LLVM_DEBUG(dbgs() << "<<Resource available for speculation>>";);
4712 LLVM_DEBUG(if (TargetPacket->isBundle()) dbgs()
4713 << "\nInsert MI inside: " << *TargetPacket;
4714 else dbgs() << "\nInsert MI just before: " << *TargetPacket;);
4715 return true;
4716 }
4717 assert(!PreciousMIShouldBeSpeculated);
4718 return false;
4719}
4720
4721bool GreedyPullup::safeToSpeculate(MachineInstr *MI,
4722 MachineBasicBlock *DstBB) const {
4723 const MachineFunction &MF = *MI->getParent()->getParent();
4724 LLVM_DEBUG(dbgs() << "\n[SafeToSpeculate]";);
4725 if (QII->isPredicated(*MI) || QII->isMemOp(*MI) ||
4726 MI->hasUnmodeledSideEffects()) // To simplify.
4727 return false;
4728 if (MI->mayStore())
4729 return false;
4730 // Do not speculate instructions that modify reserved global registers.
4731 const MachineRegisterInfo &MRI = MF.getRegInfo();
4732 for (const MachineOperand &Op : MI->operands()) {
4733 if (!Op.isReg() || !Op.isDef())
4734 continue;
4735 unsigned R = Op.getReg();
4736 if (MRI.isReserved(R) && TRI->isGlobalReg(R))
4737 return false;
4738 }
4739 if (!MI->mayLoad())
4740 return true;
4741 // For simplification we want to analyze safety of simplest load.
4742 // TODO: Load from absolute address can be added as well.
4743 unsigned DefR = 0, UseR = 0, BaseR = 0, OffR = 0;
4744 if (!MI->hasOneMemOperand() || (*MI->memoperands_begin())->isVolatile() ||
4745 !(*MI->memoperands_begin())->getValue() ||
4746 !hasOneDefAndUse(MI, DefR, UseR))
4747 return false;
4748 // This check is for safety if getUnderlyingObject is messed up.
4749 MICInstIterType DefUseR = DstBB->instr_end();
4750 if (!MI->getParent()->isLiveIn(UseR) ||
4751 HLV->isDefinedWithin(MI->getParent()->instr_begin(), MI->getIterator(),
4752 UseR, DefUseR))
4753 return false;
4754 if (!QII->getBaseAndOffsetPosition(*MI, BaseR, OffR))
4755 return false;
4756 const Value *MIVal =
4757 getUnderlyingObject((*MI->memoperands_begin())->getValue());
4758 if (!MIVal)
4759 return false;
4760 bool LoadFromSameObject = false;
4761 assert(DefR && UseR);
4762 LLVM_DEBUG(dbgs() << "\nChecking if any loads as same as: " << *MI
4763 << "\tValue: ";
4764 MIVal->dump(););
4765 for (MICInstIterType MIIt = DstBB->instr_begin(); MIIt != DstBB->instr_end();
4766 ++MIIt) {
4767 const MachineInstr *MII = &*MIIt;
4768 if (MII->isDebugInstr())
4769 continue;
4770 unsigned DefP = 0, UseP = 0, BaseP = 0, OffP = 0;
4771 if (MII->mayLoad() &&
4772 !(QII->isPredicated(*MII) || QII->isMemOp(*MII) ||
4773 shouldNotBeCrossed(MII, MI)) &&
4774 MII->hasOneMemOperand() && hasOneDefAndUse(MII, DefP, UseP)) {
4775 LLVM_DEBUG(dbgs() << "\nAgainst: " << *MII;);
4776 MachineMemOperand *mmo = *MII->memoperands_begin();
4777 // There is already a load from same address => safe.
4778 if (UseP == UseR) {
4779 MICInstIterType DefUseP = DstBB->instr_end();
4780 if (HLV->isDefinedWithin(MII->getIterator(), DstBB->instr_end(), UseP,
4781 DefUseP))
4782 return false;
4783 // We have to check the immediate part also!
4784 if (mmo->isVolatile() || !mmo->getValue() ||
4785 !QII->getBaseAndOffsetPosition(*MII, BaseP, OffP))
4786 continue;
4787 // Cannot safely speculate a load with a stricter alignment
4788 // requirement.
4789 if ((*MI->memoperands_begin())->getAlign() > mmo->getAlign())
4790 continue;
4791 assert(MII->getOperand(BaseP).getReg() ==
4792 MI->getOperand(BaseR).getReg());
4793 const Value *MIIVal = getUnderlyingObject(mmo->getValue());
4794 if (MIVal == MIIVal) {
4795 LoadFromSameObject = true;
4796 LLVM_DEBUG(dbgs() << "\n\tLoad from same object:"
4797 << "\n\tValue: ";
4798 MIIVal->dump(););
4799 }
4800 }
4801 }
4802 if (MII->modifiesRegister(UseR, TRI))
4803 LoadFromSameObject = false;
4804 }
4805 return LoadFromSameObject;
4806}
4807
4808// Approach1: Check if there is a spare register available such that
4809// the def(MI) can be assigned to that spare register to preserve
4810// liveness in the OtherBB and change the usage of def(MI) in otherBB
4811// to the spare reg. The spare register should not be livein in otherBB.
4812// TODO: Implement Approach2 as well.
4813// Approach2: Check if there is just one MI in the OtherBB which uses
4814// def(MI) (account for aliasing etc.) and if that can be speculated first.
4815// In this approach we won't have to insert compensation code.
4816// Approach3: Split critical edge and insert a copy into the critical BB.
4817// This is a costly operation so it should be done very selectively.
4818bool GreedyPullup::preciousMICanBeSpeculated(MachineInstr *MI,
4819 MachineBasicBlock *SrcBB,
4820 MachineBasicBlock *DstBB,
4821 MachineBasicBlock *OtherBB,
4822 MIIterType &TargetPacket,
4823 unsigned ApproachNum) {
4824 LLVM_DEBUG(dbgs() << "\n[PreciousMICanBeSpeculated]";);
4825 assert(preciousToSpeculate(MI, SrcBB, DstBB, OtherBB));
4826 if (ApproachNum != 1)
4827 return false;
4828
4829 unsigned DefR, UseR;
4830 if (!hasOneDefAndUse(MI, DefR, UseR))
4831 return false;
4832 // TODO: We can remove this, then we have to replace all the usage
4833 // of DefR recursively for OtherBB and all its successors. That is not
4834 // worth it for speculating a single instruction.
4835 bool splitEdge = false;
4836 if (HLV->isLiveOut(OtherBB, DefR))
4837 splitEdge = true;
4838 MachineBasicBlock *LP = nullptr;
4839 if (OtherBB->pred_size() > 1) {
4840 LP = ShouldSplitCriticalEdge(DstBB, OtherBB);
4841 if (!LP)
4842 return false;
4843 LLVM_DEBUG(dbgs() << "\nCritical edge will be split during speculation.";);
4844 }
4845 if (splitEdge ^ (LP != nullptr)) // Both true or both false (for now).
4846 return false;
4847
4848 // TODO: Reconsider the design of this and the MICanBeSpeculated
4849 // because FindInsertionPoint is called twice for MI.
4850 // We need to find the insertion point of MI because we should know
4851 // that MI can be inserted at some position. This function inserts
4852 // an extra instruction so we better be sure in the first place.
4853 TargetPacket = findInsertPtSpec(MI, DstBB, true, false);
4854 if (TargetPacket == DstBB->end()) {
4855 LLVM_DEBUG(dbgs() << "\nPrecious MI cannot be speculated: " << *MI);
4856 return false;
4857 } else {
4858 LLVM_DEBUG(dbgs() << "<<Resource available for speculating PreciousMI>>";);
4859 LLVM_DEBUG(if (TargetPacket->isBundle()) dbgs()
4860 << "\nInsert MI inside: " << *TargetPacket;
4861 else dbgs() << "\nInsert MI just before: " << *TargetPacket;);
4862 }
4863
4864 std::unique_ptr<RegScavenger> RS(new RegScavenger());
4865 RS->enterBasicBlock(*DstBB);
4866 // Mark all the live-ins and their aliases of MBBs involved as used.
4867 LLVM_DEBUG(dbgs() << "\nMarking Liveins:";);
4868 markLiveInsAsUsed(RS, DstBB);
4869 markLiveInsAsUsed(RS, SrcBB);
4870 markLiveInsAsUsed(RS, OtherBB);
4871 markLiveOutsAsUsed(RS, DstBB);
4872 markLiveOutsAsUsed(RS, SrcBB);
4873 // Instead of advancing the scavenger with RS->forward(), conservatively mark
4874 // every register used in DstBB as used.
4875 // TODO: Only the instructions up to TargetPacket need to be considered.
4876 markAllRegsAsUsed(RS, DstBB);
4877 if (!Hexagon::IntRegsRegClass.contains(DefR))
4878 return false;
4879 // Use IntRegs: getMinimalPhysRegClass often returns IntRegsLow8 (R0-R7),
4880 // which would needlessly restrict the scavenged register.
4881 const TargetRegisterClass *RC = &Hexagon::IntRegsRegClass;
4882 unsigned ScratchReg = RS->FindUnusedReg(RC);
4883 if (ScratchReg == 0 || SrcBB->isLiveIn(ScratchReg))
4884 return false;
4885 LLVM_DEBUG(dbgs() << "\nRegister " << printReg(ScratchReg, TRI)
4886 << " available for speculating PreciousMI\n\t" << *MI;);
4887
4888 // Give up if ScratchReg is defined in OtherBB. This keeps the later register
4889 // replacement simple; scavenging another register is not worth it for a
4890 // single instruction.
4891 for (MIInstIterType OMBBI = OtherBB->instr_begin();
4892 OMBBI != OtherBB->instr_end(); ++OMBBI) {
4893 if (OMBBI->modifiesRegister(ScratchReg, TRI))
4894 return false;
4895 // We cannot replace implicit register uses.
4896 if (OMBBI->hasRegisterImplicitUseOperand(DefR))
4897 return false;
4898 }
4899
4900 // Compensation code is created in OtherBB and then moved to DstBB.
4901 DebugLoc dl;
4902 MachineInstr *NewMI = BuildMI(*OtherBB, OtherBB->instr_begin(), dl,
4903 QII->get(Hexagon::A2_tfr), ScratchReg)
4904 .addReg(DefR);
4905 LLVM_DEBUG(dbgs() << "\nCompensation code:" << *NewMI;);
4906 MIIterType NewMIPos = findInsertPtSpec(NewMI, DstBB, false, true);
4907
4908 // TODO: If TargetPacket==NewMIPos we bail out in this case,
4909 // which is sub-optimal. We should modify speculateMI just like
4910 // predicateMI so that it can be clearly specified that NewMI
4911 // can be inserted 'just' before the BUNDLE or inside.
4912 bool invalidSpeculation = (NewMIPos == DstBB->end());
4913 // Returns NewMIPos when TargetPacket = NewMIPos.
4914 MICInstIterType laterOne =
4915 laterOfTheTwo(TargetPacket.getInstrIterator(),
4916 NewMIPos.getInstrIterator(), DstBB->instr_end());
4917 // Requirements on linear ordering of NewMIPos and TargetPacket:
4918 // When TargetPacket is BUNDLE then NewMIPos < TargetPacket
4919 // When TargetPacket is not BUNDLE then NewMIPos <= TargetPacket
4920 // Otherwise the Speculation has to be reverted.
4921 if (laterOne == NewMIPos.getInstrIterator()) {
4922 if (TargetPacket->isBundle() || (NewMIPos != TargetPacket))
4923 invalidSpeculation = true;
4924 }
4925
4926 if (invalidSpeculation) {
4927 LLVM_DEBUG(
4928 dbgs() << "\nSupporting MI for precious MI cannot be speculated: "
4929 << *NewMI);
4930 NewMI->eraseFromParent();
4931 return false;
4932 } else {
4933 LLVM_DEBUG(dbgs() << "<<Resource available for speculating Comp code>>";);
4934 LLVM_DEBUG(if (NewMIPos->isBundle()) dbgs()
4935 << "\nInsert MI inside: " << *NewMIPos;
4936 else dbgs() << "\nInsert MI just before: " << *NewMIPos;);
4937 }
4938
4939 // The position (P) of compensation code should be before the
4940 // position (P') MI that needs to be speculated when P is a bundle.
4941 // When P is not bundle then P may be before or same as P'.
4942 assert(laterOfTheTwo(TargetPacket.getInstrIterator(),
4943 NewMIPos.getInstrIterator(),
4944 DstBB->instr_end()) == TargetPacket.getInstrIterator());
4945
4946 // Replace usage of Reg with ScratchReg in OtherBB.
4947 // Speculate after substitution so that liveness update is correct.
4948 if (!splitEdge && !LP)
4949 replaceUsageOfReg(DefR, ScratchReg, OtherBB, NewMI);
4950
4951 // Since we know that ScratchReg is not live-in in the SrcBB,
4952 // we can safely speculate NewMI into DstBB
4953 bool done = speculateMI(NewMI, OtherBB, DstBB, NewMIPos);
4954 (void)done;
4955 assert(done && "Wrong Analysis of speculation of precious MI");
4956 TargetPacket = NewMIPos;
4957 SpeculatedIns[DstBB].push_back(NewMI);
4958 if (splitEdge && LP) {
4959 MachineBasicBlock *NewCritBB = NULL;
4960 NewCritBB = splitCriticalEdge(DstBB, OtherBB, LP);
4961 assert(NewCritBB);
4962 LLVM_DEBUG(dbgs() << "\nNew critical MBB:" << *NewCritBB;);
4963 LLVM_DEBUG(dbgs() << *DstBB << *OtherBB;);
4964 DebugLoc dl;
4965 MachineInstr *NewMI = BuildMI(*NewCritBB, NewCritBB->instr_begin(), dl,
4966 QII->get(Hexagon::A2_tfr), DefR)
4967 .addReg(ScratchReg);
4968 SpecPacketOpp.push_back(NewMI);
4969 NewCritBB->removeLiveIn(DefR);
4970 // Update liveness.
4971 HLV->addNewMI(NewMI, NewCritBB);
4972 LLVM_DEBUG(dbgs() << "\nAdding MI to New critical MBB:" << *NewCritBB;);
4973 }
4974 return true;
4975}
4976
4977bool GreedyPullup::preciousToSpeculate(const MachineInstr *MI,
4978 const MachineBasicBlock *SrcBB,
4979 const MachineBasicBlock *DstBB,
4980 const MachineBasicBlock *OtherBB) const {
4981 if (SpeculateAllInst)
4982 return true;
4983
4984 LLVM_DEBUG(dbgs() << "\n[PreciousToSpeculate]";);
4985 // When we want to speculate within a loop and the otherBB is outside loop.
4986 MachineLoop *SrcLoop = MLI.getLoopFor(SrcBB);
4987 MachineLoop *DstLoop = MLI.getLoopFor(DstBB);
4988 MachineLoop *OtherBBLoop = MLI.getLoopFor(OtherBB);
4989 return (SrcLoop && MI->mayLoad() && (SrcLoop != OtherBBLoop) &&
4990 (SrcLoop == DstLoop));
4991}
4992
4993bool GreedyPullup::preciousToPredicate(const MachineInstr *MI,
4994 const MachineBasicBlock *SrcBB,
4995 const MachineBasicBlock *DstBB,
4996 const MachineBasicBlock *OtherBB) const {
4997 if (PredicateAllInst)
4998 return true;
4999
5000 MachineLoop *SrcLoop = MLI.getLoopFor(SrcBB);
5001 MachineLoop *DstLoop = MLI.getLoopFor(DstBB);
5002 MachineLoop *OtherBBLoop = MLI.getLoopFor(OtherBB);
5003 // When we want to speculate within a loop and the otherBB is outside loop.
5004 return (MI->mayLoad() && SrcLoop && (SrcLoop == DstLoop) &&
5005 (SrcLoop != OtherBBLoop));
5006}
5007
5008bool GreedyPullup::canMIBePredicated(MachineInstr *MI, MachineBasicBlock *SrcBB,
5009 MachineBasicBlock *DstBB,
5010 MIIterType &TargetPacket,
5011 MICInstIterType &WithinPacket,
5012 bool &NeedToNewify, bool &Precious) {
5013 // Initialize iterators to safe defaults
5014 TargetPacket = DstBB->end();
5015 WithinPacket = DstBB->instr_end();
5016
5017 if (!EnablePullupPred)
5018 return false;
5019 LLVM_DEBUG(dbgs() << "\n[MICanBePredicated]");
5020
5021 MachineLoop *L = MLI.getLoopFor(SrcBB);
5022 if (isSuperblockLoop(L)) {
5023 if (!isLoopInvariant(*MI))
5024 return false;
5025 }
5026
5027 // No dependency in the current SrcBB
5028 if (shouldNotBePulledUp(MI) || findInsertionPtSpecLocal(MI) != SrcBB->begin())
5029 return false;
5030 LLVM_DEBUG(dbgs() << " .....YES";);
5031 ABI &abi = AnalyzeBranchInfo.getOrCreate(DstBB, QII);
5032 if (!abi.AnalysisValid)
5033 return false;
5034 assert(abi.TBB && abi.FBB);
5035 if (!DstBB->isSuccessor(SrcBB))
5036 return false;
5037 bool SrcIsTBB = (abi.TBB == SrcBB);
5038 MachineBasicBlock *OtherBB = abi.FBB;
5039 if (!SrcIsTBB) {
5040 assert(abi.FBB == SrcBB);
5041 OtherBB = abi.TBB;
5042 }
5043 SmallVector<MachineOperand, 4> Cond = abi.Cond;
5044 // Checking the first two is faster than checking isPredicable.
5045 if (QII->isPredicated(*MI) || QII->isMemOp(*MI) || !QII->isPredicable(*MI))
5046 return false;
5047 // Even if def is live-in we should be able to predicate as long
5048 // as we do not cross the existing def in the MBB which we don't anyway.
5049
5050 // Clone the MI for analysis
5051 DebugLoc dl;
5052 // Manage resources properly.
5053 MachineInstr *PredMI =
5054 BuildMI(*SrcBB, SrcBB->instr_begin(), dl, QII->get(MI->getOpcode()));
5055 for (unsigned i = 0; i < MI->getNumOperands(); ++i)
5056 PredMI->addOperand(MI->getOperand(i));
5057 if (!SrcIsTBB) {
5058 // If the branch condition cannot be reversed.
5059 if (QII->reverseBranchCondition(Cond)) {
5060 PredMI->eraseFromParent();
5061 return false;
5062 }
5063 }
5064 if (!QII->PredicateInstruction(*PredMI, Cond)) {
5065 PredMI->eraseFromParent();
5066 return false;
5067 }
5068 LLVM_DEBUG(dbgs() << "\nPredicated MI for analysis:" << *PredMI);
5069 TargetPacket =
5070 findInsertPtPred(PredMI, DstBB, NeedToNewify, WithinPacket, false);
5071 if (TargetPacket == DstBB->end()) {
5072 LLVM_DEBUG(dbgs() << "\nNo resources available for MI; is it precious?";);
5073 Precious = preciousToPredicate(MI, SrcBB, DstBB, OtherBB);
5074 if (Precious) {
5075 LLVM_DEBUG(
5076 dbgs() << "\nMI is Precious, trying the squeeze the dest. BUNDLE");
5077 TargetPacket =
5078 findInsertPtPred(PredMI, DstBB, NeedToNewify, WithinPacket, Precious);
5079 }
5080 }
5081 PredMI->eraseFromParent();
5082 if (TargetPacket != DstBB->end()) {
5083 LLVM_DEBUG(dbgs() << "<<Resource available for predication>>";);
5084 LLVM_DEBUG(if (TargetPacket->isBundle()) dbgs()
5085 << "\nInsert MI inside: " << *TargetPacket;
5086 else dbgs() << "\nInsert MI just before: " << *TargetPacket;);
5087 return true;
5088 }
5089 return false;
5090}
5091
5092// When \p DstPos is a BUNDLE, MI can be moved in that
5093// BUNDLE, otherwise just before the DstPos
5094bool GreedyPullup::speculateMI(MachineInstr *MI, MachineBasicBlock *SrcBB,
5095 MachineBasicBlock *DstBB, MIIterType DstPos) {
5096 LLVM_DEBUG(dbgs() << "\n[SpeculateMI]");
5097 // Remove the MI from SrcBB and put it into DstBB at TargetPacket.
5098 assert(DstPos->getParent() == DstBB);
5099 MachineInstr *InstrToMove;
5100
5101 if (DstPos->isBundle()) {
5102 MIInstIterType DstPack = DstPos.getInstrIterator();
5103 getResourcesReadyForBundle(DstPack);
5104 if (canReserveResources(MI->getIterator()) &&
5105 isLegalToPacketizeWith(DstPos, MI)) {
5106 InstrToMove = removeMI(MI, QII, &SpecPacketOpp);
5107 MIBundleBuilder Bundle(&*DstPos);
5108 Bundle.insert(std::next(DstPack), InstrToMove);
5109 } else {
5110 // If there are no resources then insert just before the BUNDLE.
5111 // TODO: Do this only in special cases.
5112 InstrToMove = removeMI(MI, QII, &SpecPacketOpp);
5113 DstBB->insert(DstPos, InstrToMove);
5114 SpecPacketOpp.push_back(&*DstPos);
5115 }
5116 } else {
5117 // Move the instruction.
5118 InstrToMove = removeMI(MI, QII, &SpecPacketOpp);
5119 DstBB->insert(DstPos, InstrToMove);
5120 // Since an instruction is moved besides another unpacketized insn
5121 // we might be able to packetize them and possibly other nearby insn.
5122 SpecPacketOpp.push_back(&*DstPos);
5123 // TODO: Make the bundle if possible, or leave this task to mergePackets.
5124 }
5125 // Update Liveness
5126 LLVM_DEBUG(dbgs() << "\n[Liveness incrementalUpdate]";);
5127 HLV->incrementalUpdate(InstrToMove->getIterator(), SrcBB, DstBB);
5128 // Mark MI as moved with speculation.
5129 LLVM_DEBUG(dbgs() << "\nSpeculated MI:\t" << *MI;);
5130 LLVM_DEBUG(dbgs() << "\nDstMBB: " << *DstBB << "\nSrcMBB: " << *SrcBB);
5131 return true;
5132}
5133
5134bool GreedyPullup::predicateMI(MachineInstr *MI, MachineBasicBlock *SrcBB,
5135 MachineBasicBlock *DstBB, MIIterType DstPack,
5136 MICInstIterType WithinPacket, bool NeedToNewify,
5137 bool Precious) {
5138 LLVM_DEBUG(dbgs() << "\n[PredicateMI]");
5139 // Remove the MI from SrcBB and put it into DstBB at DstPos.
5140 // Update Liveness
5141 // Mark MI as moved with predication.
5142 assert(DstPack->getParent() == DstBB);
5143 ABI &abi = AnalyzeBranchInfo.getOrCreate(DstBB, QII);
5144 assert(abi.AnalysisValid);
5145 bool SrcIsTBB = (abi.TBB == SrcBB);
5146 SmallVector<MachineOperand, 4> Cond = abi.Cond;
5147 if (!SrcIsTBB) {
5148 // If the branch condition cannot be reversed.
5149 bool Reversed = !QII->reverseBranchCondition(Cond);
5150 (void)Reversed;
5151 assert(Reversed);
5152 }
5153 bool Predicated = QII->PredicateInstruction(*MI, Cond);
5154 (void)Predicated;
5156 // Convert to dot.new as well.
5157 if (NeedToNewify) {
5158 int NewOpcode = QII->getDotNewPredOp(*MI, MBPI);
5159 MI->setDesc(QII->get(NewOpcode));
5160 }
5161
5162 MachineInstr *InstrToMove;
5163 if (DstPack->isBundle()) {
5164 MIInstIterType DstPos = DstPack.getInstrIterator();
5165 getResourcesReadyForBundle(DstPos);
5166 // When the MI is Precious, => it is being inserted into the bundle
5167 // by making compound i.e., five instructions into a BUNDLE.
5168 [[maybe_unused]] bool Reserved = canReserveResources(MI->getIterator());
5169 [[maybe_unused]] bool LegalPacket = isLegalToPacketizeWith(DstPack, MI);
5170 assert(((Reserved && LegalPacket) || Precious) && "Wrong analysis.");
5171
5172 InstrToMove = removeMI(MI, QII, &SpecPacketOpp);
5173 MIBundleBuilder Bundle(&*DstPack);
5174 if (WithinPacket != DstBB->instr_end()) {
5175 assert(WithinPacket->isBundledWithPred());
5176 DstPos = const_cast<MachineInstr *>(&*WithinPacket)->getIterator();
5177 }
5178 Bundle.insert(std::next(DstPos), InstrToMove);
5179 } else {
5180 // Move the instruction.
5181 InstrToMove = removeMI(MI, QII, &SpecPacketOpp);
5182 DstBB->insert(DstPack, InstrToMove);
5183 // Since an instruction is moved besides another unpacketized insn
5184 // we might be able to packetize them and possibly other nearby insn.
5185 SpecPacketOpp.push_back(&*DstPack);
5186 // TODO: Make the bundle if possible, or leave this task to mergePackets.
5187 }
5188
5189 // Update Liveness
5190 LLVM_DEBUG(dbgs() << "\n[Liveness incrementalUpdate]";);
5191 HLV->incrementalUpdate(InstrToMove->getIterator(), SrcBB, DstBB);
5192 // Mark MI as moved with speculation.
5193 LLVM_DEBUG(dbgs() << "\nPredicated MI:\t" << *MI;);
5194 LLVM_DEBUG(dbgs() << "\nDstMBB: " << *DstBB << "\nSrcMBB: " << *SrcBB);
5195 return true;
5196}
5197
5198//===----------------------------------------------------------------------===//
5199// HexagonGlobalScheduler Functions
5200//===----------------------------------------------------------------------===//
5201
5202void HexagonGlobalSchedulerV2::generateCFG(MachineFunction &MF) {
5203 GS->generateCFG(MF);
5204}
5205
5206bool HexagonGlobalSchedulerV2::runOnMachineFunction(MachineFunction &MF) {
5207 auto &ST = MF.getSubtarget<HexagonSubtarget>();
5208 if (!EnableGlobalSched || !ST.usePackets() || skipFunction(MF.getFunction()))
5209 return false;
5210
5211 TM = static_cast<const HexagonTargetMachine *>(&MF.getTarget());
5212 QII = ST.getInstrInfo();
5213 TRI = ST.getRegisterInfo();
5214
5215 AliasAnalysis *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
5216 HexagonLiveVariables *HLV = &getAnalysis<HexagonLiveVariables>();
5217 if (!HLV->HLVComplete) {
5218 LLVM_DEBUG(dbgs() << "\nHexagon Live Variables Analysis unavailable."
5219 << "\nExiting Hexagon Global Scheduler");
5220 return false;
5221 }
5222 const MachineBranchProbabilityInfo *MBPI =
5223 &getAnalysis<MachineBranchProbabilityInfoWrapperPass>().getMBPI();
5224 MachineLoopInfo *MLI = &getAnalysis<MachineLoopInfoWrapperPass>().getLI();
5225
5226 GS.reset(new GreedyPullup(TM, QII, TRI, MF, *MLI, AA, MBPI, HLV));
5227
5228 assert(verifyMachineFunction(MF, "VLIW Packetizer") &&
5229 "Invalid IR after Packetizer");
5230 generateCFG(MF);
5231 LLVM_DEBUG(MF.dump(););
5232 assert(verifyMachineFunction(MF, "After GenerateCFG") &&
5233 "Invalid CFG transformation.");
5234 GS->formSchedulingRegions(MF);
5235 // TODO: Mechanism of sorting the scheduling regions.
5236 GS->printSchedulingRegions();
5237 GS->pruneSchedulingRegions(&GlobalScheduler::pruneCriteria);
5238 LLVM_DEBUG(dbgs() << "\nScheduling regions before sorting";);
5239 GS->printSchedulingRegions();
5240 GS->sortSchedulingRegions();
5241 LLVM_DEBUG(dbgs() << "\nScheduling regions after sorting";);
5242 GS->printSchedulingRegions();
5243 LLVM_DEBUG(MF.dump(););
5244 GS->schedule();
5245 assert(verifyMachineFunction(MF, "After Scheduling") &&
5246 "Invalid Scheduling.");
5247 if (PostSchedPack)
5248 GS->packetize();
5249 assert(verifyMachineFunction(MF, "After post-schedule packetization") &&
5250 "Invalid Opts.");
5251 if (PostSchedOpt) {
5252 // Regenerate distance map because so many instructions have
5253 // been moved.
5254 HLV->regenerateDistanceMap(MF);
5255 GS->performExposedOptimizations();
5256 assert(verifyMachineFunction(MF, "After post-schedule branch opt") &&
5257 "Invalid Opts.");
5258 }
5259 GS->generateCompoundsPostSched();
5260 GS->generateAutoAndPredicates(MF);
5261 return true;
5262}
5263
5264//===----------------------------------------------------------------------===//
5265// Public Constructor Functions
5266//===----------------------------------------------------------------------===//
5267
5269 return new HexagonGlobalSchedulerV2();
5270}
MachineInstrBuilder & UseMI
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
const AArch64InstrInfo & TII
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator MBBI
Function Alias Analysis false
always inline
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static cl::opt< bool > EnableSqueeze("try-squeeze-bundle", cl::Hidden, cl::init(true), cl::desc("Try putting 5 instructions in bundle"))
static cl::opt< bool > PullUnsafeMemops("pull-unsafe-memops", cl::Hidden, cl::init(true), cl::desc("Pull up loads which have no memoperands"))
static cl::opt< bool > DisableHVXLocalPullupAndSuperblock("disable-hvx-sched-superblock", cl::Hidden, cl::init(false), cl::desc("Disable single block loops in superblocks and the HVX local " "pull-up pass."))
static cl::opt< bool > PostSchedOpt("post-sched-opt", cl::Hidden, cl::init(true), cl::desc("Optimize after global scheduling"))
static MachineInstr * updateBundle(MachineInstr *BundleHead, const HexagonInstrInfo *QII, SmallVectorImpl< MachineInstr * > *SpecScope=nullptr)
static bool isEmptyBlock(MachineBasicBlock *MBB)
static std::pair< MIInstIterType, MIInstIterType > getParentBundle(MachineInstr *MI)
static MIRIterType getSpeculationBeginPoint(MachineInstr *SrcMI, MachineBasicBlock *DstBB)
static cl::opt< bool > NoPredInBundle("nopred-sched-bundle", cl::Hidden, cl::desc("Do not put predicated instructions in bundle"))
static cl::opt< bool > EnableLocalMergePackets("enable-local-merge-packets", cl::Hidden, cl::init(true), cl::desc("Push down local MIs into the next packet"))
static cl::opt< bool > PreventDuplexSep("prevent-duplex-sep-v2", cl::Hidden, cl::init(true), cl::desc("Prevent separation of duplex while pullup in global scheduler V2"))
static cl::opt< bool > EnableSparsePullup("enable-sparse-pullup", cl::Hidden, cl::init(true), cl::desc("Enable pullup to/from sparse packets"))
static cl::opt< bool > PostSchedPack("post-sched-packet", cl::Hidden, cl::init(true), cl::desc("Packetize unbundled MIs after global scheduling"))
static cl::opt< bool > EnableHVXLocalPullup("enable-hvx-local-pullup", cl::Hidden, cl::init(true), cl::desc("Enable the HVX local pull-up pass."))
static cl::opt< bool > EnableHVXLocalPullupInnermost("enable-hvx-local-pullup-innermost", cl::Hidden, cl::init(false), cl::desc("Enable the HVX local pull-up pass on single block innermost " "loops only."))
static cl::opt< unsigned > MaxPUBundles("hexagon-pullup-distance", cl::Hidden, cl::init(10), cl::desc("Maximum number of bundles to check for local pull-up"))
static cl::opt< bool > VerifyGlobalSched("verify-global-sched", cl::Hidden, cl::init(false), cl::desc("Run the machine verifier at several stages of global scheduler"))
static void transferLiveIns(const MachineBasicBlock *From, MachineBasicBlock *To)
static MachineBasicBlock * ShouldSplitCriticalEdge(MachineBasicBlock *FromBB, MachineBasicBlock *ToBB)
static cl::opt< bool > NoSpecInBundle("nospec-sched-bundle", cl::Hidden, cl::desc("Do not put speculated instructions in bundle"))
static cl::opt< bool > EnableLocalPullup("enable-local-pullup", cl::Hidden, cl::init(true), cl::desc("Speculate local MIs in parent BUNDLEs"))
static MachineInstr * removeMI(MachineInstr *MI, const HexagonInstrInfo *QII, SmallVectorImpl< MachineInstr * > *SpecPacketOpp=nullptr, MachineInstr **singleInstr=nullptr)
static cl::opt< bool > EnableHVXLCGP("enable-hvx-lcgp", cl::Hidden, cl::init(true), cl::desc("Enable the HVX last chance global pull-up pass."))
static bool checkIfSameBundle(MachineInstr *MI1, MachineInstr *MI2)
static cl::opt< bool > EnableLCGPForLoadBypassOnly("enable-lcgp-for-load-bypass-only", cl::Hidden, cl::init(true), cl::desc("Enable the HVX last chance global pull-up for load-bypass-only"))
static cl::opt< bool > EnableHVXSuperblockHeuristic("enable-hvx-superblock-heuristic", cl::Hidden, cl::init(true), cl::desc("Run HVX scheduling only on blocks whose ratio of HVX " "instructions exceeds -hvx-sched-profit-ratio."))
static cl::opt< bool > EnableSingleLoopSuperblock("enable-single-loop-superblock", cl::Hidden, cl::init(true), cl::desc("Enable superblocks consisting of single block loops."))
static cl::opt< bool > EnableHVXTwoLoadCurBypass("enable-hvx-two-load-cur-bypass", cl::Hidden, cl::init(false), cl::desc("Enable the two-load .cur load-bypass case in local pull-up."))
static std::vector< const MachineOperand * > collectRegmaskMOs(const MachineBasicBlock &MBB)
static cl::opt< bool > EnableHLXLoadStorePullup("enable-hlx-load-store-pullup", cl::Hidden, cl::init(true), cl::desc("Pull up HLX .tmp load uses and .new HLX stores to remove the " "copies inserted by HLX load/store expansion"))
static cl::opt< bool > EnableClusterPullup("enable-cluster-pullup", cl::Hidden, cl::init(true), cl::desc("Enable pullup for dependent instruction groups"))
Enable cluster pullup optimization.
static cl::opt< bool > EnableHVXLocalPullupLB("enable-hvx-local-pullup-load-bypass", cl::Hidden, cl::init(true), cl::desc("Enable the HVX local pull-up pass (load bypass only)."))
static cl::opt< bool > EnablePullupPred("enable-pullup-pred", cl::Hidden, cl::init(true), cl::desc("Use pullup predication"))
static bool inBetweenBarriers(MICIterType Iter, const MachineBasicBlock *DstBB)
static cl::opt< bool > EnableGlobalSched("enable-global-sched", cl::Hidden, cl::init(false), cl::desc("Enable global scheduler optimizer"))
static cl::opt< bool > PredicateAllInst("predicate-all-inst", cl::Hidden, cl::desc("Try predicating all possible instructions."))
bool endloopAfterMI(MachineBasicBlock::instr_iterator MII, MachineBasicBlock *MBB)
static cl::opt< float > HVXSchedProfitRatio("hvx-sched-profit-ratio", cl::Hidden, cl::init(0.80), cl::desc("Ratio of HVX instruction/Total instructions " "for the profitability check."))
static cl::opt< bool > SpeculateAllInst("speculate-all-inst", cl::Hidden, cl::desc("Try speculating all possible instructions."))
cl::opt< bool > OneComplexPerPacket
static const unsigned SafetyBuffer
cl::opt< bool > EnableDefUseSamePacket("enable-def-use-same-packet", cl::Hidden, cl::init(true), cl::desc("Allow moving an instruction out of a packet that redefines one of " "its source registers"))
cl::opt< bool > OneFloatPerPacket
#define HEXAGON_PACKET_SIZE
static bool isSchedBarrier(const MachineInstr &MI)
IRTranslator LLVM IR MI
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
SmallVector< MachineOperand, 4 > Cond
if(!TBB||Cond.size()< 1) return false
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
uint64_t IntrinsicInst * II
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
R600 Packetizer
MachineRegisterInfo & MRI
const SmallVectorImpl< MachineOperand > MachineBasicBlock * TBB
This file declares the machine register scavenger class.
Remove Loads Into Fake Uses
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Definition Value.cpp:479
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:170
#define LLVM_DEBUG(...)
Definition Debug.h:119
Value * RHS
static MachineBasicBlock & splitEdge(MachineBasicBlock &MBB, MachineBasicBlock &Succ, int SuccCount, MachineInstr *Br, MachineInstr *&UncondBr, const X86InstrInfo &TII)
AnalysisUsage & addRequired()
int find_first() const
Returns the index of the first set bit, -1 if none of the bits are set.
Definition BitVector.h:318
size_type count() const
Returns the number of bits which are set.
Definition BitVector.h:182
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
DenseMapIterator< KeyT, ValueT, KeyInfoT, BucketT, true > const_iterator
Definition DenseMap.h:679
iterator end()
Definition DenseMap.h:686
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
bool isHLXVec(const MachineInstr &MI) const
bool isPredicated(const MachineInstr &MI) const override
Returns true if the instruction is already predicated.
bool definesPredicateReg(const MachineInstr &MI) const
bool isCompoundBranchInstr(const MachineInstr &MI) const
bool isJumpR(const MachineInstr &MI) const
bool invertAndChangeJumpTarget(MachineInstr &MI, MachineBasicBlock *NewTarget) const
bool isDotTmpInst(const MachineInstr &MI) const
bool isSoftwarePipelineLoopInstr(const MachineInstr &MI) const
unsigned nonDbgBundleSize(MachineBasicBlock::const_iterator BundleHead) const
int getDotNewPredOp(const MachineInstr &MI, const MachineBranchProbabilityInfo *MBPI) 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
std::optional< unsigned > getOperandLatency(const InstrItineraryData *ItinData, const MachineInstr &DefMI, unsigned DefIdx, const MachineInstr &UseMI, unsigned UseIdx) const override
getOperandLatency - Compute and return the use operand latency of a given pair of def and use.
bool hasCallUseInBundle(MachineBasicBlock::const_instr_iterator MIBegin, MachineBasicBlock::const_instr_iterator MIEnd, unsigned Reg, const TargetRegisterInfo &TRI) const
void findInstrPredicate(MachineInstr *MI, SmallVectorImpl< MachineOperand > &Cond) const
findInstrPredicate - Set the predicate of the instruction in the specified predicate vector First ent...
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 isFloatCompare(const MachineInstr &MI) const
bool isConstExtended(const MachineInstr &MI) const
bool PredOpcodeHasJMP_c(unsigned Opcode) const
bool isDotCurInst(const MachineInstr &MI) 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 isMemOp(const MachineInstr &MI) const
bool isDeallocRet(const MachineInstr &MI) const
bool isDotNewInst(const MachineInstr &MI) const
void translateInstrsForDup(MachineFunction &MF, bool ToBigInstrs=true) const
bool isTC1(const MachineInstr &MI) const
std::optional< unsigned > getInvertedCompare(const int OpC) const
bool isDotNewOperand(const MachineInstr &MI, unsigned OpIndex) const
Should be able to tell if the operand in question is .new.
int getDotCurOp(const MachineInstr &MI) const
bool isSafeInBundleWAR(const MachineInstr &DefMI, unsigned DefOpIdx, const MachineInstr &UseMI, unsigned UseOpIdx, bool IsPullDown=false, bool DefViaRegMask=false) const
A use (UseMI) can share a bundle with an instruction that redefines the same register (DefMI),...
bool isHVXVec(const MachineInstr &MI) const
bool mayBeCurLoad(const MachineInstr &MI) const
bool isNewValueJump(const MachineInstr &MI) const
bool PredicateInstruction(MachineInstr &MI, ArrayRef< MachineOperand > Cond) const override
Convert the instruction into a predicated instruction.
int srcDependence(MachineBasicBlock::instr_iterator SrcBeg, MachineBasicBlock::instr_iterator SrcEnd, MachineBasicBlock::instr_iterator RMII, const MIUseDefMap &MIUseDefs, SmallSetVector< MachineInstr *, 4 > *DepSet=nullptr, bool PreventDuplexSep=true, bool IsPullDown=false) const
Compute the intra-packet dependence of RMII against the rest of the bundle [SrcBeg,...
unsigned nonDbgBBSize(const MachineBasicBlock *BB) const
getInstrTimingClassLatency - Compute the instruction latency of a given instruction using Timing Clas...
bool isEndLoopN(unsigned Opcode) const
bool getBaseAndOffsetPosition(const MachineInstr &MI, unsigned &BasePos, unsigned &OffsetPos) const override
For instructions with a base and offset, return the position of the base register and offset operands...
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
unsigned getCompoundOpcode(const MachineInstr &GA, const MachineInstr &GB) const
unsigned getDistanceBetween(const MachineBasicBlock *From, const MachineBasicBlock *To, unsigned BufferPerMBB=HEXAGON_INSTR_SIZE) const
Returns the linear distance (as per layout) of MI from the Function.
bool isUsedWithin(MICInstIterType MIBegin, MICInstIterType MIEnd, unsigned Reg, MICInstIterType &Use, SmallPtrSet< MachineInstr *, 2 > *ExceptionsList=nullptr) const
bool incrementalUpdate(MICInstIterType MIDelta, MachineBasicBlock *From, MachineBasicBlock *To)
incrementalUpdate - update the liveness when MIDelta is moved from From to To.
bool updateLocalLiveness(MachineFunction &Fn)
updateLocalLiveness - update only kill flags of operands.
const BitVector & getLiveOuts(const MachineBasicBlock *MBB) const
bool isDefLiveIn(const MachineInstr *MI, const MachineBasicBlock *MBB) const
void regenerateDistanceMap(const MachineFunction &Fn)
void addNewMBB(MachineBasicBlock *MBB)
addNewMBB - inform the LiveVariable Analysis that new MBB has been added.
bool isLiveOut(const MachineBasicBlock *MBB, unsigned Reg) const
bool isDefinedWithin(MICInstIterType MIBegin, MICInstIterType MIEnd, unsigned Reg, MICInstIterType &Def) const
void addNewMI(MachineInstr *MI, MachineBasicBlock *MBB)
unsigned getLoopDepth() const
Return the nesting level of this loop.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
livein_iterator livein_end() const
bool isEHPad() const
Returns true if the block is a landing pad.
MachineInstrBundleIterator< const MachineInstr > const_iterator
LLVM_ABI instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
const BasicBlock * getBasicBlock() const
Return the LLVM basic block that this instance corresponded to originally.
LLVM_ABI iterator getFirstNonDebugInstr(bool SkipPseudoOp=true)
Returns an iterator to the first non-debug instruction in the basic block, or end().
LLVM_ABI void removeLiveIn(MCRegister Reg, LaneBitmask LaneMask=LaneBitmask::getAll())
Remove the specified register from the live in set.
LiveInVector::const_iterator livein_iterator
LLVM_ABI livein_iterator livein_begin() const
bool hasAddressTaken() const
Test whether this block is used as something other than the target of a terminator,...
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
SmallVectorImpl< MachineBasicBlock * >::iterator pred_iterator
LLVM_ABI void removeSuccessor(MachineBasicBlock *Succ, bool NormalizeSuccProbs=false)
Remove successor from the successors list of this MachineBasicBlock.
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...
MachineInstrBundleIterator< MachineInstr, true > reverse_iterator
succ_reverse_iterator succ_rbegin()
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
void addLiveIn(MCRegister PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
reverse_iterator rbegin()
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 '...
MachineInstrBundleIterator< MachineInstr > iterator
LLVM_ABI bool isLiveIn(MCRegister Reg, LaneBitmask LaneMask=LaneBitmask::getAll()) const
Return true if the specified register is in the live in set.
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.
void dump() const
dump - Print the current MachineFunction to cerr, useful for debugger use.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
bool verify(Pass *p=nullptr, const char *Banner=nullptr, raw_ostream *OS=nullptr, bool AbortOnError=true) const
Run the current MachineFunction through the machine code verifier, useful for debugger use.
Function & getFunction()
Return the LLVM function that this machine code represents.
BasicBlockListType::iterator iterator
const MachineJumpTableInfo * getJumpTableInfo() const
getJumpTableInfo - Return the jump table info object for the current function.
void splice(iterator InsertPt, iterator MBBI)
MachineBasicBlock * CreateMachineBasicBlock(const BasicBlock *BB=nullptr, std::optional< UniqueBBID > BBID=std::nullopt)
CreateMachineInstr - Allocate a new MachineInstr.
void insert(iterator MBBI, MachineBasicBlock *MBB)
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
static MachineInstrBundleIterator getAtBundleBegin(instr_iterator MI)
Get the bundle iterator for the given instruction's bundle.
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
bool isReturn(QueryType Type=AnyInBundle) const
bool isTerminator(QueryType Type=AnyInBundle) const
Returns true if this instruction part of the terminator for a basic block.
bool mayLoadOrStore(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read or modify memory.
const MachineBasicBlock * getParent() const
bool readsRegister(Register Reg, const TargetRegisterInfo *TRI) const
Return true if the MachineInstr reads the specified register.
bool isCall(QueryType Type=AnyInBundle) const
bool isBundle() const
bool isDebugInstr() const
unsigned getNumOperands() const
Retuns the total number of operands.
LLVM_ABI void addOperand(MachineFunction &MF, const MachineOperand &Op)
Add the specified operand to the instruction.
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 modifiesRegister(Register Reg, const TargetRegisterInfo *TRI) const
Return true if the MachineInstr modifies (fully define or partially define) the specified register.
bool mayLoad(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read memory.
LLVM_ABI int findRegisterUseOperandIdx(Register Reg, const TargetRegisterInfo *TRI, bool isKill=false) const
Returns the operand index that is a use of the specific register or -1 if it is not found.
LLVM_ABI unsigned getBundleSize() const
Return the number of instructions inside the MI bundle, excluding the bundle header.
mop_range operands()
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.
bool hasOneMemOperand() const
Return true if this instruction has exactly one MachineMemOperand.
mmo_iterator memoperands_begin() const
Access to memory operands of the instruction.
bool isInsideBundle() const
Return true if MI is in a bundle (but not the first MI in a bundle).
LLVM_ABI bool hasOrderedMemoryRef() const
Return true if this instruction may have an ordered or volatile memory reference, or if the informati...
MachineOperand * findRegisterUseOperand(Register Reg, const TargetRegisterInfo *TRI, bool isKill=false)
Wrapper for findRegisterUseOperandIdx, it returns a pointer to the MachineOperand rather than an inde...
bool mayStore(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly modify memory.
LLVM_ABI void removeOperand(unsigned OpNo)
Erase an operand from an instruction, leaving it with one fewer operand than it started with.
LLVM_ABI void dump() const
LLVM_ABI void addRegisterDefined(Register Reg, const TargetRegisterInfo *RegInfo=nullptr)
We have determined MI defines a register.
const MachineOperand & getOperand(unsigned i) const
LLVM_ABI MachineInstrBundleIterator< MachineInstr > eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
bool isBundled() const
Return true if this instruction part of a bundle.
LLVM_ABI bool ReplaceMBBInJumpTables(MachineBasicBlock *Old, MachineBasicBlock *New)
ReplaceMBBInJumpTables - If Old is the target of any jump tables, update the jump tables to branch to...
LLVM_ABI unsigned getOperandNo() const
Returns the index of this operand in the instruction that it belongs to.
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
LLVM_ABI void setReg(Register Reg)
Change the register this operand corresponds to.
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
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.
bool isReserved(MCRegister PhysReg) const
isReserved - Returns true when PhysReg is a reserved register.
static LLVM_ABI PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
iterator erase(const_iterator CI)
typename SuperClass::iterator iterator
void push_back(const T &Elt)
std::reverse_iterator< const_iterator > const_reverse_iterator
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
std::reverse_iterator< iterator > reverse_iterator
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
constexpr const char * data() const
Get a pointer to the start of the string (which may not be null terminated).
Definition StringRef.h:138
CodeGenOptLevel getOptLevel() const
Returns the optimization level: None, Less, Default, or Aggressive.
LLVM_ABI void dump() const
Support for debugging, callable in GDB: V->dump()
int getNumOccurrences() const
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:210
iterator find(const_arg_type_t< ValueT > V)
Definition DenseSet.h:175
self_iterator getIterator()
Definition ilist_node.h:123
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
initializer< Ty > init(const Ty &Val)
NodeAddr< DefNode * > Def
Definition RDFGraph.h:384
NodeAddr< InstrNode * > Instr
Definition RDFGraph.h:389
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
bool empty() const
Definition BasicBlock.h:101
std::reverse_iterator< iterator > rbegin() const
Definition BasicBlock.h:93
iterator end() const
Definition BasicBlock.h:89
std::reverse_iterator< iterator > rend() const
Definition BasicBlock.h:96
LLVM_ABI iterator begin() const
This is an optimization pass for GlobalISel generic memory operations.
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
bool operator<(int64_t V1, const APSInt &V2)
Definition APSInt.h:360
void stable_sort(R &&Range)
Definition STLExtras.h:2132
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.
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1685
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
void initializeHexagonGlobalSchedulerV2Pass(PassRegistry &)
bool operator>=(int64_t V1, const APSInt &V2)
Definition APSInt.h:359
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
bool operator>(int64_t V1, const APSInt &V2)
Definition APSInt.h:361
LLVM_ABI void verifyMachineFunction(const std::string &Banner, const MachineFunction &MF)
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
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.
bool set_union(S1Ty &S1, const S2Ty &S2)
set_union(A, B) - Compute A := A u B, return whether A changed.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth, bool MustPreserveProvenance=false)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
iterator_range(Container &&) -> iterator_range< llvm::detail::IterOfRange< Container > >
@ Other
Any other memory.
Definition ModRef.h:68
FunctionPass * createHexagonGlobalSchedulerV2()
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
Definition MCRegister.h:21
DWARFExpression::Operation Op
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
Definition InstrProf.h:147
@ 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.
DenseMap< const MachineInstr *, UseDef_t > MIUseDef_t
bool operator<=(int64_t V1, const APSInt &V2)
Definition APSInt.h:358
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58