LLVM  8.0.1
AArch64A57FPLoadBalancing.cpp
Go to the documentation of this file.
1 //===-- AArch64A57FPLoadBalancing.cpp - Balance FP ops statically on A57---===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
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.
13 //
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.
17 //
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).
24 //
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
28 // not affected.
29 //===----------------------------------------------------------------------===//
30 
31 #include "AArch64.h"
32 #include "AArch64InstrInfo.h"
33 #include "AArch64Subtarget.h"
34 #include "llvm/ADT/BitVector.h"
44 #include "llvm/Support/Debug.h"
46 using namespace llvm;
47 
48 #define DEBUG_TYPE "aarch64-a57-fp-load-balancing"
49 
50 // Enforce the algorithm to use the scavenged register even when the original
51 // destination register is the correct color. Used for testing.
52 static cl::opt<bool>
53 TransformAll("aarch64-a57-fp-load-balancing-force-all",
54  cl::desc("Always modify dest registers regardless of color"),
55  cl::init(false), cl::Hidden);
56 
57 // Never use the balance information obtained from chains - return a specific
58 // color always. Used for testing.
59 static cl::opt<unsigned>
60 OverrideBalance("aarch64-a57-fp-load-balancing-override",
61  cl::desc("Ignore balance information, always return "
62  "(1: Even, 2: Odd)."),
63  cl::init(0), cl::Hidden);
64 
65 //===----------------------------------------------------------------------===//
66 // Helper functions
67 
68 // Is the instruction a type of multiply on 64-bit (or 32-bit) FPRs?
69 static bool isMul(MachineInstr *MI) {
70  switch (MI->getOpcode()) {
71  case AArch64::FMULSrr:
72  case AArch64::FNMULSrr:
73  case AArch64::FMULDrr:
74  case AArch64::FNMULDrr:
75  return true;
76  default:
77  return false;
78  }
79 }
80 
81 // Is the instruction a type of FP multiply-accumulate on 64-bit (or 32-bit) FPRs?
82 static bool isMla(MachineInstr *MI) {
83  switch (MI->getOpcode()) {
84  case AArch64::FMSUBSrrr:
85  case AArch64::FMADDSrrr:
86  case AArch64::FNMSUBSrrr:
87  case AArch64::FNMADDSrrr:
88  case AArch64::FMSUBDrrr:
89  case AArch64::FMADDDrrr:
90  case AArch64::FNMSUBDrrr:
91  case AArch64::FNMADDDrrr:
92  return true;
93  default:
94  return false;
95  }
96 }
97 
98 //===----------------------------------------------------------------------===//
99 
100 namespace {
101 /// A "color", which is either even or odd. Yes, these aren't really colors
102 /// but the algorithm is conceptually doing two-color graph coloring.
103 enum class Color { Even, Odd };
104 #ifndef NDEBUG
105 static const char *ColorNames[2] = { "Even", "Odd" };
106 #endif
107 
108 class Chain;
109 
110 class AArch64A57FPLoadBalancing : public MachineFunctionPass {
112  const TargetRegisterInfo *TRI;
113  RegisterClassInfo RCI;
114 
115 public:
116  static char ID;
117  explicit AArch64A57FPLoadBalancing() : MachineFunctionPass(ID) {
119  }
120 
121  bool runOnMachineFunction(MachineFunction &F) override;
122 
123  MachineFunctionProperties getRequiredProperties() const override {
126  }
127 
128  StringRef getPassName() const override {
129  return "A57 FP Anti-dependency breaker";
130  }
131 
132  void getAnalysisUsage(AnalysisUsage &AU) const override {
133  AU.setPreservesCFG();
135  }
136 
137 private:
139  bool colorChainSet(std::vector<Chain*> GV, MachineBasicBlock &MBB,
140  int &Balance);
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::vector<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);
150 };
151 }
152 
154 
155 INITIALIZE_PASS_BEGIN(AArch64A57FPLoadBalancing, DEBUG_TYPE,
156  "AArch64 A57 FP Load-Balancing", false, false)
157 INITIALIZE_PASS_END(AArch64A57FPLoadBalancing, DEBUG_TYPE,
158  "AArch64 A57 FP Load-Balancing", false, false)
159 
160 namespace {
161 /// A Chain is a sequence of instructions that are linked together by
162 /// an accumulation operand. For example:
163 ///
164 /// fmul def d0, ?
165 /// fmla def d1, ?, ?, killed d0
166 /// fmla def d2, ?, ?, killed d1
167 ///
168 /// There may be other instructions interleaved in the sequence that
169 /// do not belong to the chain. These other instructions must not use
170 /// the "chain" register at any point.
171 ///
172 /// We currently only support chains where the "chain" operand is killed
173 /// at each link in the chain for simplicity.
174 /// A chain has three important instructions - Start, Last and Kill.
175 /// * The start instruction is the first instruction in the chain.
176 /// * Last is the final instruction in the chain.
177 /// * Kill may or may not be defined. If defined, Kill is the instruction
178 /// where the outgoing value of the Last instruction is killed.
179 /// This information is important as if we know the outgoing value is
180 /// killed with no intervening uses, we can safely change its register.
181 ///
182 /// Without a kill instruction, we must assume the outgoing value escapes
183 /// beyond our model and either must not change its register or must
184 /// create a fixup FMOV to keep the old register value consistent.
185 ///
186 class Chain {
187 public:
188  /// The important (marker) instructions.
189  MachineInstr *StartInst, *LastInst, *KillInst;
190  /// The index, from the start of the basic block, that each marker
191  /// appears. These are stored so we can do quick interval tests.
192  unsigned StartInstIdx, LastInstIdx, KillInstIdx;
193  /// All instructions in the chain.
194  std::set<MachineInstr*> Insts;
195  /// True if KillInst cannot be modified. If this is true,
196  /// we cannot change LastInst's outgoing register.
197  /// This will be true for tied values and regmasks.
199  /// The "color" of LastInst. This will be the preferred chain color,
200  /// as changing intermediate nodes is easy but changing the last
201  /// instruction can be more tricky.
203 
204  Chain(MachineInstr *MI, unsigned Idx, Color C)
205  : StartInst(MI), LastInst(MI), KillInst(nullptr),
206  StartInstIdx(Idx), LastInstIdx(Idx), KillInstIdx(0),
207  LastColor(C) {
208  Insts.insert(MI);
209  }
210 
211  /// Add a new instruction into the chain. The instruction's dest operand
212  /// has the given color.
213  void add(MachineInstr *MI, unsigned Idx, Color C) {
214  LastInst = MI;
215  LastInstIdx = Idx;
216  LastColor = C;
217  assert((KillInstIdx == 0 || LastInstIdx < KillInstIdx) &&
218  "Chain: broken invariant. A Chain can only be killed after its last "
219  "def");
220 
221  Insts.insert(MI);
222  }
223 
224  /// Return true if MI is a member of the chain.
225  bool contains(MachineInstr &MI) { return Insts.count(&MI) > 0; }
226 
227  /// Return the number of instructions in the chain.
228  unsigned size() const {
229  return Insts.size();
230  }
231 
232  /// Inform the chain that its last active register (the dest register of
233  /// LastInst) is killed by MI with no intervening uses or defs.
234  void setKill(MachineInstr *MI, unsigned Idx, bool Immutable) {
235  KillInst = MI;
236  KillInstIdx = Idx;
237  KillIsImmutable = Immutable;
238  assert((KillInstIdx == 0 || LastInstIdx < KillInstIdx) &&
239  "Chain: broken invariant. A Chain can only be killed after its last "
240  "def");
241  }
242 
243  /// Return the first instruction in the chain.
244  MachineInstr *getStart() const { return StartInst; }
245  /// Return the last instruction in the chain.
246  MachineInstr *getLast() const { return LastInst; }
247  /// Return the "kill" instruction (as set with setKill()) or NULL.
248  MachineInstr *getKill() const { return KillInst; }
249  /// Return an instruction that can be used as an iterator for the end
250  /// of the chain. This is the maximum of KillInst (if set) and LastInst.
252  return ++MachineBasicBlock::iterator(KillInst ? KillInst : LastInst);
253  }
254  MachineBasicBlock::iterator begin() const { return getStart(); }
255 
256  /// Can the Kill instruction (assuming one exists) be modified?
257  bool isKillImmutable() const { return KillIsImmutable; }
258 
259  /// Return the preferred color of this chain.
261  if (OverrideBalance != 0)
262  return OverrideBalance == 1 ? Color::Even : Color::Odd;
263  return LastColor;
264  }
265 
266  /// Return true if this chain (StartInst..KillInst) overlaps with Other.
267  bool rangeOverlapsWith(const Chain &Other) const {
268  unsigned End = KillInst ? KillInstIdx : LastInstIdx;
269  unsigned OtherEnd = Other.KillInst ?
270  Other.KillInstIdx : Other.LastInstIdx;
271 
272  return StartInstIdx <= OtherEnd && Other.StartInstIdx <= End;
273  }
274 
275  /// Return true if this chain starts before Other.
276  bool startsBefore(const Chain *Other) const {
277  return StartInstIdx < Other->StartInstIdx;
278  }
279 
280  /// Return true if the group will require a fixup MOV at the end.
281  bool requiresFixup() const {
282  return (getKill() && isKillImmutable()) || !getKill();
283  }
284 
285  /// Return a simple string representation of the chain.
286  std::string str() const {
287  std::string S;
288  raw_string_ostream OS(S);
289 
290  OS << "{";
291  StartInst->print(OS, /* SkipOpers= */true);
292  OS << " -> ";
293  LastInst->print(OS, /* SkipOpers= */true);
294  if (KillInst) {
295  OS << " (kill @ ";
296  KillInst->print(OS, /* SkipOpers= */true);
297  OS << ")";
298  }
299  OS << "}";
300 
301  return OS.str();
302  }
303 
304 };
305 
306 } // end anonymous namespace
307 
308 //===----------------------------------------------------------------------===//
309 
310 bool AArch64A57FPLoadBalancing::runOnMachineFunction(MachineFunction &F) {
311  if (skipFunction(F.getFunction()))
312  return false;
313 
315  return false;
316 
317  bool Changed = false;
318  LLVM_DEBUG(dbgs() << "***** AArch64A57FPLoadBalancing *****\n");
319 
320  MRI = &F.getRegInfo();
322  RCI.runOnMachineFunction(F);
323 
324  for (auto &MBB : F) {
325  Changed |= runOnBasicBlock(MBB);
326  }
327 
328  return Changed;
329 }
330 
332  bool Changed = false;
333  LLVM_DEBUG(dbgs() << "Running on MBB: " << MBB
334  << " - scanning instructions...\n");
335 
336  // First, scan the basic block producing a set of chains.
337 
338  // The currently "active" chains - chains that can be added to and haven't
339  // been killed yet. This is keyed by register - all chains can only have one
340  // "link" register between each inst in the chain.
341  std::map<unsigned, Chain*> ActiveChains;
342  std::vector<std::unique_ptr<Chain>> AllChains;
343  unsigned Idx = 0;
344  for (auto &MI : MBB)
345  scanInstruction(&MI, Idx++, ActiveChains, AllChains);
346 
347  LLVM_DEBUG(dbgs() << "Scan complete, " << AllChains.size()
348  << " chains created.\n");
349 
350  // Group the chains into disjoint sets based on their liveness range. This is
351  // a poor-man's version of graph coloring. Ideally we'd create an interference
352  // graph and perform full-on graph coloring on that, but;
353  // (a) That's rather heavyweight for only two colors.
354  // (b) We expect multiple disjoint interference regions - in practice the live
355  // range of chains is quite small and they are clustered between loads
356  // and stores.
358  for (auto &I : AllChains)
359  EC.insert(I.get());
360 
361  for (auto &I : AllChains)
362  for (auto &J : AllChains)
363  if (I != J && I->rangeOverlapsWith(*J))
364  EC.unionSets(I.get(), J.get());
365  LLVM_DEBUG(dbgs() << "Created " << EC.getNumClasses() << " disjoint sets.\n");
366 
367  // Now we assume that every member of an equivalence class interferes
368  // with every other member of that class, and with no members of other classes.
369 
370  // Convert the EquivalenceClasses to a simpler set of sets.
371  std::vector<std::vector<Chain*> > V;
372  for (auto I = EC.begin(), E = EC.end(); I != E; ++I) {
373  std::vector<Chain*> Cs(EC.member_begin(I), EC.member_end());
374  if (Cs.empty()) continue;
375  V.push_back(std::move(Cs));
376  }
377 
378  // Now we have a set of sets, order them by start address so
379  // we can iterate over them sequentially.
380  llvm::sort(V,
381  [](const std::vector<Chain *> &A, const std::vector<Chain *> &B) {
382  return A.front()->startsBefore(B.front());
383  });
384 
385  // As we only have two colors, we can track the global (BB-level) balance of
386  // odds versus evens. We aim to keep this near zero to keep both execution
387  // units fed.
388  // Positive means we're even-heavy, negative we're odd-heavy.
389  //
390  // FIXME: If chains have interdependencies, for example:
391  // mul r0, r1, r2
392  // mul r3, r0, r1
393  // We do not model this and may color each one differently, assuming we'll
394  // get ILP when we obviously can't. This hasn't been seen to be a problem
395  // in practice so far, so we simplify the algorithm by ignoring it.
396  int Parity = 0;
397 
398  for (auto &I : V)
399  Changed |= colorChainSet(std::move(I), MBB, Parity);
400 
401  return Changed;
402 }
403 
404 Chain *AArch64A57FPLoadBalancing::getAndEraseNext(Color PreferredColor,
405  std::vector<Chain*> &L) {
406  if (L.empty())
407  return nullptr;
408 
409  // We try and get the best candidate from L to color next, given that our
410  // preferred color is "PreferredColor". L is ordered from larger to smaller
411  // chains. It is beneficial to color the large chains before the small chains,
412  // but if we can't find a chain of the maximum length with the preferred color,
413  // we fuzz the size and look for slightly smaller chains before giving up and
414  // returning a chain that must be recolored.
415 
416  // FIXME: Does this need to be configurable?
417  const unsigned SizeFuzz = 1;
418  unsigned MinSize = L.front()->size() - SizeFuzz;
419  for (auto I = L.begin(), E = L.end(); I != E; ++I) {
420  if ((*I)->size() <= MinSize) {
421  // We've gone past the size limit. Return the previous item.
422  Chain *Ch = *--I;
423  L.erase(I);
424  return Ch;
425  }
426 
427  if ((*I)->getPreferredColor() == PreferredColor) {
428  Chain *Ch = *I;
429  L.erase(I);
430  return Ch;
431  }
432  }
433 
434  // Bailout case - just return the first item.
435  Chain *Ch = L.front();
436  L.erase(L.begin());
437  return Ch;
438 }
439 
440 bool AArch64A57FPLoadBalancing::colorChainSet(std::vector<Chain*> GV,
441  MachineBasicBlock &MBB,
442  int &Parity) {
443  bool Changed = false;
444  LLVM_DEBUG(dbgs() << "colorChainSet(): #sets=" << GV.size() << "\n");
445 
446  // Sort by descending size order so that we allocate the most important
447  // sets first.
448  // Tie-break equivalent sizes by sorting chains requiring fixups before
449  // those without fixups. The logic here is that we should look at the
450  // chains that we cannot change before we look at those we can,
451  // so the parity counter is updated and we know what color we should
452  // change them to!
453  // Final tie-break with instruction order so pass output is stable (i.e. not
454  // dependent on malloc'd pointer values).
455  llvm::sort(GV, [](const Chain *G1, const Chain *G2) {
456  if (G1->size() != G2->size())
457  return G1->size() > G2->size();
458  if (G1->requiresFixup() != G2->requiresFixup())
459  return G1->requiresFixup() > G2->requiresFixup();
460  // Make sure startsBefore() produces a stable final order.
461  assert((G1 == G2 || (G1->startsBefore(G2) ^ G2->startsBefore(G1))) &&
462  "Starts before not total order!");
463  return G1->startsBefore(G2);
464  });
465 
466  Color PreferredColor = Parity < 0 ? Color::Even : Color::Odd;
467  while (Chain *G = getAndEraseNext(PreferredColor, GV)) {
468  // Start off by assuming we'll color to our own preferred color.
469  Color C = PreferredColor;
470  if (Parity == 0)
471  // But if we really don't care, use the chain's preferred color.
472  C = G->getPreferredColor();
473 
474  LLVM_DEBUG(dbgs() << " - Parity=" << Parity
475  << ", Color=" << ColorNames[(int)C] << "\n");
476 
477  // If we'll need a fixup FMOV, don't bother. Testing has shown that this
478  // happens infrequently and when it does it has at least a 50% chance of
479  // slowing code down instead of speeding it up.
480  if (G->requiresFixup() && C != G->getPreferredColor()) {
481  C = G->getPreferredColor();
482  LLVM_DEBUG(dbgs() << " - " << G->str()
483  << " - not worthwhile changing; "
484  "color remains "
485  << ColorNames[(int)C] << "\n");
486  }
487 
488  Changed |= colorChain(G, C, MBB);
489 
490  Parity += (C == Color::Even) ? G->size() : -G->size();
491  PreferredColor = Parity < 0 ? Color::Even : Color::Odd;
492  }
493 
494  return Changed;
495 }
496 
497 int AArch64A57FPLoadBalancing::scavengeRegister(Chain *G, Color C,
498  MachineBasicBlock &MBB) {
499  // Can we find an appropriate register that is available throughout the life
500  // of the chain? Simulate liveness backwards until the end of the chain.
501  LiveRegUnits Units(*TRI);
502  Units.addLiveOuts(MBB);
504  MachineBasicBlock::iterator ChainEnd = G->end();
505  while (I != ChainEnd) {
506  --I;
507  Units.stepBackward(*I);
508  }
509 
510  // Check which register units are alive throughout the chain.
511  MachineBasicBlock::iterator ChainBegin = G->begin();
512  assert(ChainBegin != ChainEnd && "Chain should contain instructions");
513  do {
514  --I;
515  Units.accumulate(*I);
516  } while (I != ChainBegin);
517 
518  // Make sure we allocate in-order, to get the cheapest registers first.
519  unsigned RegClassID = ChainBegin->getDesc().OpInfo[0].RegClass;
520  auto Ord = RCI.getOrder(TRI->getRegClass(RegClassID));
521  for (auto Reg : Ord) {
522  if (!Units.available(Reg))
523  continue;
524  if (C == getColor(Reg))
525  return Reg;
526  }
527 
528  return -1;
529 }
530 
531 bool AArch64A57FPLoadBalancing::colorChain(Chain *G, Color C,
532  MachineBasicBlock &MBB) {
533  bool Changed = false;
534  LLVM_DEBUG(dbgs() << " - colorChain(" << G->str() << ", "
535  << ColorNames[(int)C] << ")\n");
536 
537  // Try and obtain a free register of the right class. Without a register
538  // to play with we cannot continue.
539  int Reg = scavengeRegister(G, C, MBB);
540  if (Reg == -1) {
541  LLVM_DEBUG(dbgs() << "Scavenging (thus coloring) failed!\n");
542  return false;
543  }
544  LLVM_DEBUG(dbgs() << " - Scavenged register: " << printReg(Reg, TRI) << "\n");
545 
546  std::map<unsigned, unsigned> Substs;
547  for (MachineInstr &I : *G) {
548  if (!G->contains(I) && (&I != G->getKill() || G->isKillImmutable()))
549  continue;
550 
551  // I is a member of G, or I is a mutable instruction that kills G.
552 
553  std::vector<unsigned> ToErase;
554  for (auto &U : I.operands()) {
555  if (U.isReg() && U.isUse() && Substs.find(U.getReg()) != Substs.end()) {
556  unsigned OrigReg = U.getReg();
557  U.setReg(Substs[OrigReg]);
558  if (U.isKill())
559  // Don't erase straight away, because there may be other operands
560  // that also reference this substitution!
561  ToErase.push_back(OrigReg);
562  } else if (U.isRegMask()) {
563  for (auto J : Substs) {
564  if (U.clobbersPhysReg(J.first))
565  ToErase.push_back(J.first);
566  }
567  }
568  }
569  // Now it's safe to remove the substs identified earlier.
570  for (auto J : ToErase)
571  Substs.erase(J);
572 
573  // Only change the def if this isn't the last instruction.
574  if (&I != G->getKill()) {
575  MachineOperand &MO = I.getOperand(0);
576 
577  bool Change = TransformAll || getColor(MO.getReg()) != C;
578  if (G->requiresFixup() && &I == G->getLast())
579  Change = false;
580 
581  if (Change) {
582  Substs[MO.getReg()] = Reg;
583  MO.setReg(Reg);
584 
585  Changed = true;
586  }
587  }
588  }
589  assert(Substs.size() == 0 && "No substitutions should be left active!");
590 
591  if (G->getKill()) {
592  LLVM_DEBUG(dbgs() << " - Kill instruction seen.\n");
593  } else {
594  // We didn't have a kill instruction, but we didn't seem to need to change
595  // the destination register anyway.
596  LLVM_DEBUG(dbgs() << " - Destination register not changed.\n");
597  }
598  return Changed;
599 }
600 
601 void AArch64A57FPLoadBalancing::scanInstruction(
602  MachineInstr *MI, unsigned Idx, std::map<unsigned, Chain *> &ActiveChains,
603  std::vector<std::unique_ptr<Chain>> &AllChains) {
604  // Inspect "MI", updating ActiveChains and AllChains.
605 
606  if (isMul(MI)) {
607 
608  for (auto &I : MI->uses())
609  maybeKillChain(I, Idx, ActiveChains);
610  for (auto &I : MI->defs())
611  maybeKillChain(I, Idx, ActiveChains);
612 
613  // Create a new chain. Multiplies don't require forwarding so can go on any
614  // unit.
615  unsigned DestReg = MI->getOperand(0).getReg();
616 
617  LLVM_DEBUG(dbgs() << "New chain started for register "
618  << printReg(DestReg, TRI) << " at " << *MI);
619 
620  auto G = llvm::make_unique<Chain>(MI, Idx, getColor(DestReg));
621  ActiveChains[DestReg] = G.get();
622  AllChains.push_back(std::move(G));
623 
624  } else if (isMla(MI)) {
625 
626  // It is beneficial to keep MLAs on the same functional unit as their
627  // accumulator operand.
628  unsigned DestReg = MI->getOperand(0).getReg();
629  unsigned AccumReg = MI->getOperand(3).getReg();
630 
631  maybeKillChain(MI->getOperand(1), Idx, ActiveChains);
632  maybeKillChain(MI->getOperand(2), Idx, ActiveChains);
633  if (DestReg != AccumReg)
634  maybeKillChain(MI->getOperand(0), Idx, ActiveChains);
635 
636  if (ActiveChains.find(AccumReg) != ActiveChains.end()) {
637  LLVM_DEBUG(dbgs() << "Chain found for accumulator register "
638  << printReg(AccumReg, TRI) << " in MI " << *MI);
639 
640  // For simplicity we only chain together sequences of MULs/MLAs where the
641  // accumulator register is killed on each instruction. This means we don't
642  // need to track other uses of the registers we want to rewrite.
643  //
644  // FIXME: We could extend to handle the non-kill cases for more coverage.
645  if (MI->getOperand(3).isKill()) {
646  // Add to chain.
647  LLVM_DEBUG(dbgs() << "Instruction was successfully added to chain.\n");
648  ActiveChains[AccumReg]->add(MI, Idx, getColor(DestReg));
649  // Handle cases where the destination is not the same as the accumulator.
650  if (DestReg != AccumReg) {
651  ActiveChains[DestReg] = ActiveChains[AccumReg];
652  ActiveChains.erase(AccumReg);
653  }
654  return;
655  }
656 
657  LLVM_DEBUG(
658  dbgs() << "Cannot add to chain because accumulator operand wasn't "
659  << "marked <kill>!\n");
660  maybeKillChain(MI->getOperand(3), Idx, ActiveChains);
661  }
662 
663  LLVM_DEBUG(dbgs() << "Creating new chain for dest register "
664  << printReg(DestReg, TRI) << "\n");
665  auto G = llvm::make_unique<Chain>(MI, Idx, getColor(DestReg));
666  ActiveChains[DestReg] = G.get();
667  AllChains.push_back(std::move(G));
668 
669  } else {
670 
671  // Non-MUL or MLA instruction. Invalidate any chain in the uses or defs
672  // lists.
673  for (auto &I : MI->uses())
674  maybeKillChain(I, Idx, ActiveChains);
675  for (auto &I : MI->defs())
676  maybeKillChain(I, Idx, ActiveChains);
677 
678  }
679 }
680 
681 void AArch64A57FPLoadBalancing::
682 maybeKillChain(MachineOperand &MO, unsigned Idx,
683  std::map<unsigned, Chain*> &ActiveChains) {
684  // Given an operand and the set of active chains (keyed by register),
685  // determine if a chain should be ended and remove from ActiveChains.
686  MachineInstr *MI = MO.getParent();
687 
688  if (MO.isReg()) {
689 
690  // If this is a KILL of a current chain, record it.
691  if (MO.isKill() && ActiveChains.find(MO.getReg()) != ActiveChains.end()) {
692  LLVM_DEBUG(dbgs() << "Kill seen for chain " << printReg(MO.getReg(), TRI)
693  << "\n");
694  ActiveChains[MO.getReg()]->setKill(MI, Idx, /*Immutable=*/MO.isTied());
695  }
696  ActiveChains.erase(MO.getReg());
697 
698  } else if (MO.isRegMask()) {
699 
700  for (auto I = ActiveChains.begin(), E = ActiveChains.end();
701  I != E;) {
702  if (MO.clobbersPhysReg(I->first)) {
703  LLVM_DEBUG(dbgs() << "Kill (regmask) seen for chain "
704  << printReg(I->first, TRI) << "\n");
705  I->second->setKill(MI, Idx, /*Immutable=*/true);
706  ActiveChains.erase(I++);
707  } else
708  ++I;
709  }
710 
711  }
712 }
713 
714 Color AArch64A57FPLoadBalancing::getColor(unsigned Reg) {
715  if ((TRI->getEncodingValue(Reg) % 2) == 0)
716  return Color::Even;
717  else
718  return Color::Odd;
719 }
720 
721 // Factory function used by AArch64TargetMachine to add the pass to the passmanager.
723  return new AArch64A57FPLoadBalancing();
724 }
bool isRegMask() const
isRegMask - Tests if this is a MO_RegisterMask operand.
uint64_t CallInst * C
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
MachineInstr * getKill() const
Return the "kill" instruction (as set with setKill()) or NULL.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
MachineInstr * StartInst
The important (marker) instructions.
This class represents lattice values for constants.
Definition: AllocatorList.h:24
iterator_range< mop_iterator > uses()
Returns a range that includes all operands that are register uses.
Definition: MachineInstr.h:492
bool requiresFixup() const
Return true if the group will require a fixup MOV at the end.
unsigned getReg() const
getReg - Returns the register number.
static cl::opt< unsigned > OverrideBalance("aarch64-a57-fp-load-balancing-override", cl::desc("Ignore balance information, always return " "(1: Even, 2: Odd)."), cl::init(0), cl::Hidden)
unsigned Reg
#define DEBUG_TYPE
unsigned const TargetRegisterInfo * TRI
F(f)
bool rangeOverlapsWith(const Chain &Other) const
Return true if this chain (StartInst..KillInst) overlaps with Other.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void addLiveOuts(const MachineBasicBlock &MBB)
Adds registers living out of block MBB.
Printable printReg(unsigned Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
bool startsBefore(const Chain *Other) const
Return true if this chain starts before Other.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
Definition: MachineInstr.h:409
std::string str() const
Return a simple string representation of the chain.
bool isKillImmutable() const
Can the Kill instruction (assuming one exists) be modified?
FunctionPass * createAArch64A57FPLoadBalancing()
bool available(MCPhysReg Reg) const
Returns true if no part of physical register Reg is live.
Definition: LiveRegUnits.h:118
static cl::opt< bool > TransformAll("aarch64-a57-fp-load-balancing-force-all", cl::desc("Always modify dest registers regardless of color"), cl::init(false), cl::Hidden)
bool contains(MachineInstr &MI)
Return true if MI is a member of the chain.
void initializeAArch64A57FPLoadBalancingPass(PassRegistry &)
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:423
MachineInstrBundleIterator< MachineInstr > iterator
This file declares the machine register scavenger class.
const TargetRegisterInfo * getTargetRegisterInfo() const
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
unsigned const MachineRegisterInfo * MRI
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
EquivalenceClasses - This represents a collection of equivalence classes and supports three efficient...
Represent the analysis usage information of a pass.
void stepBackward(const MachineInstr &MI)
Updates liveness when stepping backwards over the instruction MI.
iterator_range< mop_iterator > defs()
Returns a range over all explicit operands that are register definitions.
Definition: MachineInstr.h:481
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:285
AArch64 A57 FP Load Balancing
void print(raw_ostream &OS, bool IsStandalone=true, bool SkipOpers=false, bool SkipDebugLoc=false, bool AddNewLine=true, const TargetInstrInfo *TII=nullptr) const
Print this MI to OS.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
std::string & str()
Flushes the stream contents to the target string and returns the string&#39;s reference.
Definition: raw_ostream.h:499
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
Color LastColor
The "color" of LastInst.
void add(MachineInstr *MI, unsigned Idx, Color C)
Add a new instruction into the chain.
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:1116
Color
A "color", which is either even or odd.
MachineOperand class - Representation of each machine instruction operand.
const DataFlowGraph & G
Definition: RDFGraph.cpp:211
Promote Memory to Register
Definition: Mem2Reg.cpp:110
static bool isMla(MachineInstr *MI)
MachineBasicBlock::iterator begin() const
void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition: Pass.cpp:286
MachineInstr * getStart() const
Return the first instruction in the chain.
const Function & getFunction() const
Return the LLVM function that this machine code represents.
void accumulate(const MachineInstr &MI)
Adds all register units used, defined or clobbered in MI.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:133
static bool clobbersPhysReg(const uint32_t *RegMask, unsigned PhysReg)
clobbersPhysReg - Returns true if this RegMask clobbers PhysReg.
std::set< MachineInstr * > Insts
All instructions in the chain.
static bool runOnBasicBlock(MachineBasicBlock *MBB, std::vector< StringRef > &bbNames, std::vector< unsigned > &renamedInOtherBB, unsigned &basicBlockNum, unsigned &VRegGapIndex, NamedVRegCursor &NVC)
MachineInstr * getLast() const
Return the last instruction in the chain.
MachineRegisterInfo - Keep track of information for virtual and physical registers, including vreg register classes, use/def chains for registers, etc.
MachineFunctionProperties & set(Property P)
Representation of each machine instruction.
Definition: MachineInstr.h:64
bool KillIsImmutable
True if KillInst cannot be modified.
A Chain is a sequence of instructions that are linked together by an accumulation operand...
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
void setReg(unsigned Reg)
Change the register this operand corresponds to.
#define I(x, y, z)
Definition: MD5.cpp:58
A set of register units used to track register liveness.
Definition: LiveRegUnits.h:31
bool isReg() const
isReg - Tests if this is a MO_Register operand.
unsigned StartInstIdx
The index, from the start of the basic block, that each marker appears.
void setKill(MachineInstr *MI, unsigned Idx, bool Immutable)
Inform the chain that its last active register (the dest register of LastInst) is killed by MI with n...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:483
INITIALIZE_PASS_BEGIN(AArch64A57FPLoadBalancing, DEBUG_TYPE, "AArch64 A57 FP Load-Balancing", false, false) INITIALIZE_PASS_END(AArch64A57FPLoadBalancing
Color getPreferredColor()
Return the preferred color of this chain.
IRTranslator LLVM IR MI
static bool isMul(MachineInstr *MI)
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
#define LLVM_DEBUG(X)
Definition: Debug.h:123
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:414
MachineBasicBlock::iterator end() const
Return an instruction that can be used as an iterator for the end of the chain.
Properties which a MachineFunction may have at a given point in time.
unsigned size() const
Return the number of instructions in the chain.
Chain(MachineInstr *MI, unsigned Idx, Color C)