1 //===-- AArch64A57FPLoadBalancing.cpp - Balance FP ops statically on A57---===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
9 // For best-case performance on Cortex-A57, we should try to use a balanced
10 // mix of odd and even D-registers when performing a critical sequence of
11 // independent, non-quadword FP/ASIMD floating-point multiply or
12 // multiply-accumulate operations.
14 // This pass attempts to detect situations where the register allocation may
15 // adversely affect this load balancing and to change the registers used so as
16 // to better utilize the CPU.
18 // Ideally we'd just take each multiply or multiply-accumulate in turn and
19 // allocate it alternating even or odd registers. However, multiply-accumulates
20 // are most efficiently performed in the same functional unit as their
21 // accumulation operand. Therefore this pass tries to find maximal sequences
22 // ("Chains") of multiply-accumulates linked via their accumulation operand,
23 // and assign them all the same "color" (oddness/evenness).
25 // This optimization affects S-register and D-register floating point
26 // multiplies and FMADD/FMAs, as well as vector (floating point only) muls and
27 // FMADD/FMA. Q register instructions (and 128-bit vector instructions) are
29 //===----------------------------------------------------------------------===//
32 #include "AArch64InstrInfo.h"
33 #include "AArch64Subtarget.h"
34 #include "llvm/ADT/BitVector.h"
35 #include "llvm/ADT/EquivalenceClasses.h"
36 #include "llvm/CodeGen/MachineFunction.h"
37 #include "llvm/CodeGen/MachineFunctionPass.h"
38 #include "llvm/CodeGen/MachineInstr.h"
39 #include "llvm/CodeGen/MachineInstrBuilder.h"
40 #include "llvm/CodeGen/MachineRegisterInfo.h"
41 #include "llvm/CodeGen/RegisterScavenging.h"
42 #include "llvm/CodeGen/RegisterClassInfo.h"
43 #include "llvm/Support/CommandLine.h"
44 #include "llvm/Support/Debug.h"
45 #include "llvm/Support/raw_ostream.h"
49 #define DEBUG_TYPE "aarch64-a57-fp-load-balancing"
51 // Enforce the algorithm to use the scavenged register even when the original
52 // destination register is the correct color. Used for testing.
54 TransformAll("aarch64-a57-fp-load-balancing-force-all",
55 cl::desc("Always modify dest registers regardless of color"),
56 cl::init(false), cl::Hidden);
58 // Never use the balance information obtained from chains - return a specific
59 // color always. Used for testing.
60 static cl::opt<unsigned>
61 OverrideBalance("aarch64-a57-fp-load-balancing-override",
62 cl::desc("Ignore balance information, always return "
63 "(1: Even, 2: Odd)."),
64 cl::init(0), cl::Hidden);
66 //===----------------------------------------------------------------------===//
69 // Is the instruction a type of multiply on 64-bit (or 32-bit) FPRs?
70 static bool isMul(MachineInstr *MI) {
71 switch (MI->getOpcode()) {
72 case AArch64::FMULSrr:
73 case AArch64::FNMULSrr:
74 case AArch64::FMULDrr:
75 case AArch64::FNMULDrr:
77 case AArch64::FMULv2f32:
84 // Is the instruction a type of FP multiply-accumulate on 64-bit (or 32-bit) FPRs?
85 static bool isMla(MachineInstr *MI) {
86 switch (MI->getOpcode()) {
87 case AArch64::FMSUBSrrr:
88 case AArch64::FMADDSrrr:
89 case AArch64::FNMSUBSrrr:
90 case AArch64::FNMADDSrrr:
91 case AArch64::FMSUBDrrr:
92 case AArch64::FMADDDrrr:
93 case AArch64::FNMSUBDrrr:
94 case AArch64::FNMADDDrrr:
96 case AArch64::FMLAv2f32:
97 case AArch64::FMLSv2f32:
104 //===----------------------------------------------------------------------===//
107 /// A "color", which is either even or odd. Yes, these aren't really colors
108 /// but the algorithm is conceptually doing two-color graph coloring.
109 enum class Color { Even, Odd };
111 static const char *ColorNames[2] = { "Even", "Odd" };
116 class AArch64A57FPLoadBalancing : public MachineFunctionPass {
117 const AArch64InstrInfo *TII;
118 MachineRegisterInfo *MRI;
119 const TargetRegisterInfo *TRI;
120 RegisterClassInfo RCI;
124 explicit AArch64A57FPLoadBalancing() : MachineFunctionPass(ID) {}
126 bool runOnMachineFunction(MachineFunction &F) override;
128 const char *getPassName() const override {
129 return "A57 FP Anti-dependency breaker";
132 void getAnalysisUsage(AnalysisUsage &AU) const override {
133 AU.setPreservesCFG();
134 MachineFunctionPass::getAnalysisUsage(AU);
138 bool runOnBasicBlock(MachineBasicBlock &MBB);
139 bool colorChainSet(std::vector<Chain*> GV, MachineBasicBlock &MBB,
141 bool colorChain(Chain *G, Color C, MachineBasicBlock &MBB);
142 int scavengeRegister(Chain *G, Color C, MachineBasicBlock &MBB);
143 void scanInstruction(MachineInstr *MI, unsigned Idx,
144 std::map<unsigned, Chain*> &Active,
145 std::set<std::unique_ptr<Chain>> &AllChains);
146 void maybeKillChain(MachineOperand &MO, unsigned Idx,
147 std::map<unsigned, Chain*> &RegChains);
148 Color getColor(unsigned Register);
149 Chain *getAndEraseNext(Color PreferredColor, std::vector<Chain*> &L);
151 char AArch64A57FPLoadBalancing::ID = 0;
153 /// A Chain is a sequence of instructions that are linked together by
154 /// an accumulation operand. For example:
157 /// fmla d1<def>, ?, ?, d0<kill>
158 /// fmla d2<def>, ?, ?, d1<kill>
160 /// There may be other instructions interleaved in the sequence that
161 /// do not belong to the chain. These other instructions must not use
162 /// the "chain" register at any point.
164 /// We currently only support chains where the "chain" operand is killed
165 /// at each link in the chain for simplicity.
166 /// A chain has three important instructions - Start, Last and Kill.
167 /// * The start instruction is the first instruction in the chain.
168 /// * Last is the final instruction in the chain.
169 /// * Kill may or may not be defined. If defined, Kill is the instruction
170 /// where the outgoing value of the Last instruction is killed.
171 /// This information is important as if we know the outgoing value is
172 /// killed with no intervening uses, we can safely change its register.
174 /// Without a kill instruction, we must assume the outgoing value escapes
175 /// beyond our model and either must not change its register or must
176 /// create a fixup FMOV to keep the old register value consistent.
180 /// The important (marker) instructions.
181 MachineInstr *StartInst, *LastInst, *KillInst;
182 /// The index, from the start of the basic block, that each marker
183 /// appears. These are stored so we can do quick interval tests.
184 unsigned StartInstIdx, LastInstIdx, KillInstIdx;
185 /// All instructions in the chain.
186 std::set<MachineInstr*> Insts;
187 /// True if KillInst cannot be modified. If this is true,
188 /// we cannot change LastInst's outgoing register.
189 /// This will be true for tied values and regmasks.
190 bool KillIsImmutable;
191 /// The "color" of LastInst. This will be the preferred chain color,
192 /// as changing intermediate nodes is easy but changing the last
193 /// instruction can be more tricky.
196 Chain(MachineInstr *MI, unsigned Idx, Color C)
197 : StartInst(MI), LastInst(MI), KillInst(nullptr),
198 StartInstIdx(Idx), LastInstIdx(Idx), KillInstIdx(0),
203 /// Add a new instruction into the chain. The instruction's dest operand
204 /// has the given color.
205 void add(MachineInstr *MI, unsigned Idx, Color C) {
209 assert((KillInstIdx == 0 || LastInstIdx < KillInstIdx) &&
210 "Chain: broken invariant. A Chain can only be killed after its last "
216 /// Return true if MI is a member of the chain.
217 bool contains(MachineInstr *MI) { return Insts.count(MI) > 0; }
219 /// Return the number of instructions in the chain.
220 unsigned size() const {
224 /// Inform the chain that its last active register (the dest register of
225 /// LastInst) is killed by MI with no intervening uses or defs.
226 void setKill(MachineInstr *MI, unsigned Idx, bool Immutable) {
229 KillIsImmutable = Immutable;
230 assert((KillInstIdx == 0 || LastInstIdx < KillInstIdx) &&
231 "Chain: broken invariant. A Chain can only be killed after its last "
235 /// Return the first instruction in the chain.
236 MachineInstr *getStart() const { return StartInst; }
237 /// Return the last instruction in the chain.
238 MachineInstr *getLast() const { return LastInst; }
239 /// Return the "kill" instruction (as set with setKill()) or NULL.
240 MachineInstr *getKill() const { return KillInst; }
241 /// Return an instruction that can be used as an iterator for the end
242 /// of the chain. This is the maximum of KillInst (if set) and LastInst.
243 MachineBasicBlock::iterator getEnd() const {
244 return ++MachineBasicBlock::iterator(KillInst ? KillInst : LastInst);
247 /// Can the Kill instruction (assuming one exists) be modified?
248 bool isKillImmutable() const { return KillIsImmutable; }
250 /// Return the preferred color of this chain.
251 Color getPreferredColor() {
252 if (OverrideBalance != 0)
253 return OverrideBalance == 1 ? Color::Even : Color::Odd;
257 /// Return true if this chain (StartInst..KillInst) overlaps with Other.
258 bool rangeOverlapsWith(const Chain &Other) const {
259 unsigned End = KillInst ? KillInstIdx : LastInstIdx;
260 unsigned OtherEnd = Other.KillInst ?
261 Other.KillInstIdx : Other.LastInstIdx;
263 return StartInstIdx <= OtherEnd && Other.StartInstIdx <= End;
266 /// Return true if this chain starts before Other.
267 bool startsBefore(Chain *Other) {
268 return StartInstIdx < Other->StartInstIdx;
271 /// Return true if the group will require a fixup MOV at the end.
272 bool requiresFixup() const {
273 return (getKill() && isKillImmutable()) || !getKill();
276 /// Return a simple string representation of the chain.
277 std::string str() const {
279 raw_string_ostream OS(S);
282 StartInst->print(OS, NULL, true);
284 LastInst->print(OS, NULL, true);
287 KillInst->print(OS, NULL, true);
297 } // end anonymous namespace
299 //===----------------------------------------------------------------------===//
301 bool AArch64A57FPLoadBalancing::runOnMachineFunction(MachineFunction &F) {
302 bool Changed = false;
303 DEBUG(dbgs() << "***** AArch64A57FPLoadBalancing *****\n");
305 const TargetMachine &TM = F.getTarget();
306 MRI = &F.getRegInfo();
307 TRI = F.getRegInfo().getTargetRegisterInfo();
308 TII = TM.getSubtarget<AArch64Subtarget>().getInstrInfo();
309 RCI.runOnMachineFunction(F);
311 for (auto &MBB : F) {
312 Changed |= runOnBasicBlock(MBB);
318 bool AArch64A57FPLoadBalancing::runOnBasicBlock(MachineBasicBlock &MBB) {
319 bool Changed = false;
320 DEBUG(dbgs() << "Running on MBB: " << MBB << " - scanning instructions...\n");
322 // First, scan the basic block producing a set of chains.
324 // The currently "active" chains - chains that can be added to and haven't
325 // been killed yet. This is keyed by register - all chains can only have one
326 // "link" register between each inst in the chain.
327 std::map<unsigned, Chain*> ActiveChains;
328 std::set<std::unique_ptr<Chain>> AllChains;
331 scanInstruction(&MI, Idx++, ActiveChains, AllChains);
333 DEBUG(dbgs() << "Scan complete, "<< AllChains.size() << " chains created.\n");
335 // Group the chains into disjoint sets based on their liveness range. This is
336 // a poor-man's version of graph coloring. Ideally we'd create an interference
337 // graph and perform full-on graph coloring on that, but;
338 // (a) That's rather heavyweight for only two colors.
339 // (b) We expect multiple disjoint interference regions - in practice the live
340 // range of chains is quite small and they are clustered between loads
342 EquivalenceClasses<Chain*> EC;
343 for (auto &I : AllChains)
346 for (auto &I : AllChains)
347 for (auto &J : AllChains)
348 if (I != J && I->rangeOverlapsWith(*J))
349 EC.unionSets(I.get(), J.get());
350 DEBUG(dbgs() << "Created " << EC.getNumClasses() << " disjoint sets.\n");
352 // Now we assume that every member of an equivalence class interferes
353 // with every other member of that class, and with no members of other classes.
355 // Convert the EquivalenceClasses to a simpler set of sets.
356 std::vector<std::vector<Chain*> > V;
357 for (auto I = EC.begin(), E = EC.end(); I != E; ++I) {
358 std::vector<Chain*> Cs(EC.member_begin(I), EC.member_end());
359 if (Cs.empty()) continue;
363 // Now we have a set of sets, order them by start address so
364 // we can iterate over them sequentially.
365 std::sort(V.begin(), V.end(),
366 [](const std::vector<Chain*> &A,
367 const std::vector<Chain*> &B) {
368 return A.front()->startsBefore(B.front());
371 // As we only have two colors, we can track the global (BB-level) balance of
372 // odds versus evens. We aim to keep this near zero to keep both execution
374 // Positive means we're even-heavy, negative we're odd-heavy.
376 // FIXME: If chains have interdependencies, for example:
379 // We do not model this and may color each one differently, assuming we'll
380 // get ILP when we obviously can't. This hasn't been seen to be a problem
381 // in practice so far, so we simplify the algorithm by ignoring it.
385 Changed |= colorChainSet(I, MBB, Parity);
390 Chain *AArch64A57FPLoadBalancing::getAndEraseNext(Color PreferredColor,
391 std::vector<Chain*> &L) {
395 // We try and get the best candidate from L to color next, given that our
396 // preferred color is "PreferredColor". L is ordered from larger to smaller
397 // chains. It is beneficial to color the large chains before the small chains,
398 // but if we can't find a chain of the maximum length with the preferred color,
399 // we fuzz the size and look for slightly smaller chains before giving up and
400 // returning a chain that must be recolored.
402 // FIXME: Does this need to be configurable?
403 const unsigned SizeFuzz = 1;
404 unsigned MinSize = L.front()->size() - SizeFuzz;
405 for (auto I = L.begin(), E = L.end(); I != E; ++I) {
406 if ((*I)->size() <= MinSize) {
407 // We've gone past the size limit. Return the previous item.
413 if ((*I)->getPreferredColor() == PreferredColor) {
420 // Bailout case - just return the first item.
421 Chain *Ch = L.front();
426 bool AArch64A57FPLoadBalancing::colorChainSet(std::vector<Chain*> GV,
427 MachineBasicBlock &MBB,
429 bool Changed = false;
430 DEBUG(dbgs() << "colorChainSet(): #sets=" << GV.size() << "\n");
432 // Sort by descending size order so that we allocate the most important
434 // Tie-break equivalent sizes by sorting chains requiring fixups before
435 // those without fixups. The logic here is that we should look at the
436 // chains that we cannot change before we look at those we can,
437 // so the parity counter is updated and we know what color we should
439 std::sort(GV.begin(), GV.end(), [](const Chain *G1, const Chain *G2) {
440 if (G1->size() != G2->size())
441 return G1->size() > G2->size();
442 return G1->requiresFixup() > G2->requiresFixup();
445 Color PreferredColor = Parity < 0 ? Color::Even : Color::Odd;
446 while (Chain *G = getAndEraseNext(PreferredColor, GV)) {
447 // Start off by assuming we'll color to our own preferred color.
448 Color C = PreferredColor;
450 // But if we really don't care, use the chain's preferred color.
451 C = G->getPreferredColor();
453 DEBUG(dbgs() << " - Parity=" << Parity << ", Color="
454 << ColorNames[(int)C] << "\n");
456 // If we'll need a fixup FMOV, don't bother. Testing has shown that this
457 // happens infrequently and when it does it has at least a 50% chance of
458 // slowing code down instead of speeding it up.
459 if (G->requiresFixup() && C != G->getPreferredColor()) {
460 C = G->getPreferredColor();
461 DEBUG(dbgs() << " - " << G->str() << " - not worthwhile changing; "
462 "color remains " << ColorNames[(int)C] << "\n");
465 Changed |= colorChain(G, C, MBB);
467 Parity += (C == Color::Even) ? G->size() : -G->size();
468 PreferredColor = Parity < 0 ? Color::Even : Color::Odd;
474 int AArch64A57FPLoadBalancing::scavengeRegister(Chain *G, Color C,
475 MachineBasicBlock &MBB) {
477 RS.enterBasicBlock(&MBB);
478 RS.forward(MachineBasicBlock::iterator(G->getStart()));
480 // Can we find an appropriate register that is available throughout the life
482 unsigned RegClassID = G->getStart()->getDesc().OpInfo[0].RegClass;
483 BitVector AvailableRegs = RS.getRegsAvailable(TRI->getRegClass(RegClassID));
484 for (MachineBasicBlock::iterator I = G->getStart(), E = G->getEnd();
487 AvailableRegs &= RS.getRegsAvailable(TRI->getRegClass(RegClassID));
489 // Remove any registers clobbered by a regmask.
490 for (auto J : I->operands()) {
492 AvailableRegs.clearBitsNotInMask(J.getRegMask());
496 // Make sure we allocate in-order, to get the cheapest registers first.
497 auto Ord = RCI.getOrder(TRI->getRegClass(RegClassID));
498 for (auto Reg : Ord) {
499 if (!AvailableRegs[Reg])
501 if ((C == Color::Even && (Reg % 2) == 0) ||
502 (C == Color::Odd && (Reg % 2) == 1))
509 bool AArch64A57FPLoadBalancing::colorChain(Chain *G, Color C,
510 MachineBasicBlock &MBB) {
511 bool Changed = false;
512 DEBUG(dbgs() << " - colorChain(" << G->str() << ", "
513 << ColorNames[(int)C] << ")\n");
515 // Try and obtain a free register of the right class. Without a register
516 // to play with we cannot continue.
517 int Reg = scavengeRegister(G, C, MBB);
519 DEBUG(dbgs() << "Scavenging (thus coloring) failed!\n");
522 DEBUG(dbgs() << " - Scavenged register: " << TRI->getName(Reg) << "\n");
524 std::map<unsigned, unsigned> Substs;
525 for (MachineBasicBlock::iterator I = G->getStart(), E = G->getEnd();
527 if (!G->contains(I) &&
528 (&*I != G->getKill() || G->isKillImmutable()))
531 // I is a member of G, or I is a mutable instruction that kills G.
533 std::vector<unsigned> ToErase;
534 for (auto &U : I->operands()) {
535 if (U.isReg() && U.isUse() && Substs.find(U.getReg()) != Substs.end()) {
536 unsigned OrigReg = U.getReg();
537 U.setReg(Substs[OrigReg]);
539 // Don't erase straight away, because there may be other operands
540 // that also reference this substitution!
541 ToErase.push_back(OrigReg);
542 } else if (U.isRegMask()) {
543 for (auto J : Substs) {
544 if (U.clobbersPhysReg(J.first))
545 ToErase.push_back(J.first);
549 // Now it's safe to remove the substs identified earlier.
550 for (auto J : ToErase)
553 // Only change the def if this isn't the last instruction.
554 if (&*I != G->getKill()) {
555 MachineOperand &MO = I->getOperand(0);
557 bool Change = TransformAll || getColor(MO.getReg()) != C;
558 if (G->requiresFixup() && &*I == G->getLast())
562 Substs[MO.getReg()] = Reg;
564 MRI->setPhysRegUsed(Reg);
570 assert(Substs.size() == 0 && "No substitutions should be left active!");
573 DEBUG(dbgs() << " - Kill instruction seen.\n");
575 // We didn't have a kill instruction, but we didn't seem to need to change
576 // the destination register anyway.
577 DEBUG(dbgs() << " - Destination register not changed.\n");
582 void AArch64A57FPLoadBalancing::
583 scanInstruction(MachineInstr *MI, unsigned Idx,
584 std::map<unsigned, Chain*> &ActiveChains,
585 std::set<std::unique_ptr<Chain>> &AllChains) {
586 // Inspect "MI", updating ActiveChains and AllChains.
590 for (auto &I : MI->operands())
591 maybeKillChain(I, Idx, ActiveChains);
593 // Create a new chain. Multiplies don't require forwarding so can go on any
595 unsigned DestReg = MI->getOperand(0).getReg();
597 DEBUG(dbgs() << "New chain started for register "
598 << TRI->getName(DestReg) << " at " << *MI);
600 auto G = llvm::make_unique<Chain>(MI, Idx, getColor(DestReg));
601 ActiveChains[DestReg] = G.get();
602 AllChains.insert(std::move(G));
604 } else if (isMla(MI)) {
606 // It is beneficial to keep MLAs on the same functional unit as their
607 // accumulator operand.
608 unsigned DestReg = MI->getOperand(0).getReg();
609 unsigned AccumReg = MI->getOperand(3).getReg();
611 maybeKillChain(MI->getOperand(1), Idx, ActiveChains);
612 maybeKillChain(MI->getOperand(2), Idx, ActiveChains);
613 if (DestReg != AccumReg)
614 maybeKillChain(MI->getOperand(0), Idx, ActiveChains);
616 if (ActiveChains.find(AccumReg) != ActiveChains.end()) {
617 DEBUG(dbgs() << "Chain found for accumulator register "
618 << TRI->getName(AccumReg) << " in MI " << *MI);
620 // For simplicity we only chain together sequences of MULs/MLAs where the
621 // accumulator register is killed on each instruction. This means we don't
622 // need to track other uses of the registers we want to rewrite.
624 // FIXME: We could extend to handle the non-kill cases for more coverage.
625 if (MI->getOperand(3).isKill()) {
627 DEBUG(dbgs() << "Instruction was successfully added to chain.\n");
628 ActiveChains[AccumReg]->add(MI, Idx, getColor(DestReg));
629 // Handle cases where the destination is not the same as the accumulator.
630 if (DestReg != AccumReg) {
631 ActiveChains[DestReg] = ActiveChains[AccumReg];
632 ActiveChains.erase(AccumReg);
637 DEBUG(dbgs() << "Cannot add to chain because accumulator operand wasn't "
638 << "marked <kill>!\n");
639 maybeKillChain(MI->getOperand(3), Idx, ActiveChains);
642 DEBUG(dbgs() << "Creating new chain for dest register "
643 << TRI->getName(DestReg) << "\n");
644 auto G = llvm::make_unique<Chain>(MI, Idx, getColor(DestReg));
645 ActiveChains[DestReg] = G.get();
646 AllChains.insert(std::move(G));
650 // Non-MUL or MLA instruction. Invalidate any chain in the uses or defs
652 for (auto &I : MI->operands())
653 maybeKillChain(I, Idx, ActiveChains);
658 void AArch64A57FPLoadBalancing::
659 maybeKillChain(MachineOperand &MO, unsigned Idx,
660 std::map<unsigned, Chain*> &ActiveChains) {
661 // Given an operand and the set of active chains (keyed by register),
662 // determine if a chain should be ended and remove from ActiveChains.
663 MachineInstr *MI = MO.getParent();
667 // If this is a KILL of a current chain, record it.
668 if (MO.isKill() && ActiveChains.find(MO.getReg()) != ActiveChains.end()) {
669 DEBUG(dbgs() << "Kill seen for chain " << TRI->getName(MO.getReg())
671 ActiveChains[MO.getReg()]->setKill(MI, Idx, /*Immutable=*/MO.isTied());
673 ActiveChains.erase(MO.getReg());
675 } else if (MO.isRegMask()) {
677 for (auto I = ActiveChains.begin(), E = ActiveChains.end();
679 if (MO.clobbersPhysReg(I->first)) {
680 DEBUG(dbgs() << "Kill (regmask) seen for chain "
681 << TRI->getName(I->first) << "\n");
682 I->second->setKill(MI, Idx, /*Immutable=*/true);
683 ActiveChains.erase(I++);
691 Color AArch64A57FPLoadBalancing::getColor(unsigned Reg) {
692 if ((TRI->getEncodingValue(Reg) % 2) == 0)
698 // Factory function used by AArch64TargetMachine to add the pass to the passmanager.
699 FunctionPass *llvm::createAArch64A57FPLoadBalancing() {
700 return new AArch64A57FPLoadBalancing();