1 //===- llvm/CodeGen/GlobalISel/RegBankSelect.cpp - RegBankSelect -*- C++ -*-==//
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 /// \file
10 /// This file implements the RegBankSelect class.
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/CodeGen/GlobalISel/RegBankSelect.h"
14 #include "llvm/ADT/PostOrderIterator.h"
15 #include "llvm/CodeGen/GlobalISel/LegalizerInfo.h"
16 #include "llvm/CodeGen/GlobalISel/RegisterBank.h"
17 #include "llvm/CodeGen/GlobalISel/Utils.h"
18 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
19 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
20 #include "llvm/CodeGen/MachineRegisterInfo.h"
21 #include "llvm/CodeGen/TargetPassConfig.h"
22 #include "llvm/IR/Function.h"
23 #include "llvm/Support/BlockFrequency.h"
24 #include "llvm/Support/CommandLine.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Target/TargetSubtargetInfo.h"
27 
28 #define DEBUG_TYPE "regbankselect"
29 
30 using namespace llvm;
31 
32 static cl::opt<RegBankSelect::Mode> RegBankSelectMode(
33     cl::desc("Mode of the RegBankSelect pass"), cl::Hidden, cl::Optional,
34     cl::values(clEnumValN(RegBankSelect::Mode::Fast, "regbankselect-fast",
35                           "Run the Fast mode (default mapping)"),
36                clEnumValN(RegBankSelect::Mode::Greedy, "regbankselect-greedy",
37                           "Use the Greedy mode (best local mapping)")));
38 
39 char RegBankSelect::ID = 0;
40 INITIALIZE_PASS_BEGIN(RegBankSelect, DEBUG_TYPE,
41                       "Assign register bank of generic virtual registers",
42                       false, false);
43 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
44 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
45 INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
46 INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,
47                     "Assign register bank of generic virtual registers", false,
48                     false)
49 
50 RegBankSelect::RegBankSelect(Mode RunningMode)
51     : MachineFunctionPass(ID), RBI(nullptr), MRI(nullptr), TRI(nullptr),
52       MBFI(nullptr), MBPI(nullptr), OptMode(RunningMode) {
53   initializeRegBankSelectPass(*PassRegistry::getPassRegistry());
54   if (RegBankSelectMode.getNumOccurrences() != 0) {
55     OptMode = RegBankSelectMode;
56     if (RegBankSelectMode != RunningMode)
57       DEBUG(dbgs() << "RegBankSelect mode overrided by command line\n");
58   }
59 }
60 
61 void RegBankSelect::init(MachineFunction &MF) {
62   RBI = MF.getSubtarget().getRegBankInfo();
63   assert(RBI && "Cannot work without RegisterBankInfo");
64   MRI = &MF.getRegInfo();
65   TRI = MF.getSubtarget().getRegisterInfo();
66   TPC = &getAnalysis<TargetPassConfig>();
67   if (OptMode != Mode::Fast) {
68     MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
69     MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
70   } else {
71     MBFI = nullptr;
72     MBPI = nullptr;
73   }
74   MIRBuilder.setMF(MF);
75   MORE = make_unique<MachineOptimizationRemarkEmitter>(MF, MBFI);
76 }
77 
78 void RegBankSelect::getAnalysisUsage(AnalysisUsage &AU) const {
79   if (OptMode != Mode::Fast) {
80     // We could preserve the information from these two analysis but
81     // the APIs do not allow to do so yet.
82     AU.addRequired<MachineBlockFrequencyInfo>();
83     AU.addRequired<MachineBranchProbabilityInfo>();
84   }
85   AU.addRequired<TargetPassConfig>();
86   MachineFunctionPass::getAnalysisUsage(AU);
87 }
88 
89 bool RegBankSelect::assignmentMatch(
90     unsigned Reg, const RegisterBankInfo::ValueMapping &ValMapping,
91     bool &OnlyAssign) const {
92   // By default we assume we will have to repair something.
93   OnlyAssign = false;
94   // Each part of a break down needs to end up in a different register.
95   // In other word, Reg assignement does not match.
96   if (ValMapping.NumBreakDowns > 1)
97     return false;
98 
99   const RegisterBank *CurRegBank = RBI->getRegBank(Reg, *MRI, *TRI);
100   const RegisterBank *DesiredRegBrank = ValMapping.BreakDown[0].RegBank;
101   // Reg is free of assignment, a simple assignment will make the
102   // register bank to match.
103   OnlyAssign = CurRegBank == nullptr;
104   DEBUG(dbgs() << "Does assignment already match: ";
105         if (CurRegBank) dbgs() << *CurRegBank; else dbgs() << "none";
106         dbgs() << " against ";
107         assert(DesiredRegBrank && "The mapping must be valid");
108         dbgs() << *DesiredRegBrank << '\n';);
109   return CurRegBank == DesiredRegBrank;
110 }
111 
112 bool RegBankSelect::repairReg(
113     MachineOperand &MO, const RegisterBankInfo::ValueMapping &ValMapping,
114     RegBankSelect::RepairingPlacement &RepairPt,
115     const iterator_range<SmallVectorImpl<unsigned>::const_iterator> &NewVRegs) {
116   if (ValMapping.NumBreakDowns != 1 && !TPC->isGlobalISelAbortEnabled())
117     return false;
118   assert(ValMapping.NumBreakDowns == 1 && "Not yet implemented");
119   // An empty range of new register means no repairing.
120   assert(NewVRegs.begin() != NewVRegs.end() && "We should not have to repair");
121 
122   // Assume we are repairing a use and thus, the original reg will be
123   // the source of the repairing.
124   unsigned Src = MO.getReg();
125   unsigned Dst = *NewVRegs.begin();
126 
127   // If we repair a definition, swap the source and destination for
128   // the repairing.
129   if (MO.isDef())
130     std::swap(Src, Dst);
131 
132   assert((RepairPt.getNumInsertPoints() == 1 ||
133           TargetRegisterInfo::isPhysicalRegister(Dst)) &&
134          "We are about to create several defs for Dst");
135 
136   // Build the instruction used to repair, then clone it at the right places.
137   MachineInstr *MI = MIRBuilder.buildCopy(Dst, Src);
138   MI->removeFromParent();
139   DEBUG(dbgs() << "Copy: " << PrintReg(Src) << " to: " << PrintReg(Dst)
140                << '\n');
141   // TODO:
142   // Check if MI is legal. if not, we need to legalize all the
143   // instructions we are going to insert.
144   std::unique_ptr<MachineInstr *[]> NewInstrs(
145       new MachineInstr *[RepairPt.getNumInsertPoints()]);
146   bool IsFirst = true;
147   unsigned Idx = 0;
148   for (const std::unique_ptr<InsertPoint> &InsertPt : RepairPt) {
149     MachineInstr *CurMI;
150     if (IsFirst)
151       CurMI = MI;
152     else
153       CurMI = MIRBuilder.getMF().CloneMachineInstr(MI);
154     InsertPt->insert(*CurMI);
155     NewInstrs[Idx++] = CurMI;
156     IsFirst = false;
157   }
158   // TODO:
159   // Legalize NewInstrs if need be.
160   return true;
161 }
162 
163 uint64_t RegBankSelect::getRepairCost(
164     const MachineOperand &MO,
165     const RegisterBankInfo::ValueMapping &ValMapping) const {
166   assert(MO.isReg() && "We should only repair register operand");
167   assert(ValMapping.NumBreakDowns && "Nothing to map??");
168 
169   bool IsSameNumOfValues = ValMapping.NumBreakDowns == 1;
170   const RegisterBank *CurRegBank = RBI->getRegBank(MO.getReg(), *MRI, *TRI);
171   // If MO does not have a register bank, we should have just been
172   // able to set one unless we have to break the value down.
173   assert((!IsSameNumOfValues || CurRegBank) && "We should not have to repair");
174   // Def: Val <- NewDefs
175   //     Same number of values: copy
176   //     Different number: Val = build_sequence Defs1, Defs2, ...
177   // Use: NewSources <- Val.
178   //     Same number of values: copy.
179   //     Different number: Src1, Src2, ... =
180   //           extract_value Val, Src1Begin, Src1Len, Src2Begin, Src2Len, ...
181   // We should remember that this value is available somewhere else to
182   // coalesce the value.
183 
184   if (IsSameNumOfValues) {
185     const RegisterBank *DesiredRegBrank = ValMapping.BreakDown[0].RegBank;
186     // If we repair a definition, swap the source and destination for
187     // the repairing.
188     if (MO.isDef())
189       std::swap(CurRegBank, DesiredRegBrank);
190     // TODO: It may be possible to actually avoid the copy.
191     // If we repair something where the source is defined by a copy
192     // and the source of that copy is on the right bank, we can reuse
193     // it for free.
194     // E.g.,
195     // RegToRepair<BankA> = copy AlternativeSrc<BankB>
196     // = op RegToRepair<BankA>
197     // We can simply propagate AlternativeSrc instead of copying RegToRepair
198     // into a new virtual register.
199     // We would also need to propagate this information in the
200     // repairing placement.
201     unsigned Cost =
202         RBI->copyCost(*DesiredRegBrank, *CurRegBank,
203                       RegisterBankInfo::getSizeInBits(MO.getReg(), *MRI, *TRI));
204     // TODO: use a dedicated constant for ImpossibleCost.
205     if (Cost != UINT_MAX)
206       return Cost;
207     assert(!TPC->isGlobalISelAbortEnabled() &&
208            "Legalization not available yet");
209     // Return the legalization cost of that repairing.
210   }
211   assert(!TPC->isGlobalISelAbortEnabled() &&
212          "Complex repairing not implemented yet");
213   return UINT_MAX;
214 }
215 
216 RegisterBankInfo::InstructionMapping &RegBankSelect::findBestMapping(
217     MachineInstr &MI, RegisterBankInfo::InstructionMappings &PossibleMappings,
218     SmallVectorImpl<RepairingPlacement> &RepairPts) {
219   assert(!PossibleMappings.empty() &&
220          "Do not know how to map this instruction");
221 
222   RegisterBankInfo::InstructionMapping *BestMapping = nullptr;
223   MappingCost Cost = MappingCost::ImpossibleCost();
224   SmallVector<RepairingPlacement, 4> LocalRepairPts;
225   for (RegisterBankInfo::InstructionMapping &CurMapping : PossibleMappings) {
226     MappingCost CurCost = computeMapping(MI, CurMapping, LocalRepairPts, &Cost);
227     if (CurCost < Cost) {
228       DEBUG(dbgs() << "New best: " << CurCost << '\n');
229       Cost = CurCost;
230       BestMapping = &CurMapping;
231       RepairPts.clear();
232       for (RepairingPlacement &RepairPt : LocalRepairPts)
233         RepairPts.emplace_back(std::move(RepairPt));
234     }
235   }
236   if (!BestMapping && !TPC->isGlobalISelAbortEnabled()) {
237     // If none of the mapping worked that means they are all impossible.
238     // Thus, pick the first one and set an impossible repairing point.
239     // It will trigger the failed isel mode.
240     BestMapping = &(*PossibleMappings.begin());
241     RepairPts.emplace_back(
242         RepairingPlacement(MI, 0, *TRI, *this, RepairingPlacement::Impossible));
243   } else
244     assert(BestMapping && "No suitable mapping for instruction");
245   return *BestMapping;
246 }
247 
248 void RegBankSelect::tryAvoidingSplit(
249     RegBankSelect::RepairingPlacement &RepairPt, const MachineOperand &MO,
250     const RegisterBankInfo::ValueMapping &ValMapping) const {
251   const MachineInstr &MI = *MO.getParent();
252   assert(RepairPt.hasSplit() && "We should not have to adjust for split");
253   // Splitting should only occur for PHIs or between terminators,
254   // because we only do local repairing.
255   assert((MI.isPHI() || MI.isTerminator()) && "Why do we split?");
256 
257   assert(&MI.getOperand(RepairPt.getOpIdx()) == &MO &&
258          "Repairing placement does not match operand");
259 
260   // If we need splitting for phis, that means it is because we
261   // could not find an insertion point before the terminators of
262   // the predecessor block for this argument. In other words,
263   // the input value is defined by one of the terminators.
264   assert((!MI.isPHI() || !MO.isDef()) && "Need split for phi def?");
265 
266   // We split to repair the use of a phi or a terminator.
267   if (!MO.isDef()) {
268     if (MI.isTerminator()) {
269       assert(&MI != &(*MI.getParent()->getFirstTerminator()) &&
270              "Need to split for the first terminator?!");
271     } else {
272       // For the PHI case, the split may not be actually required.
273       // In the copy case, a phi is already a copy on the incoming edge,
274       // therefore there is no need to split.
275       if (ValMapping.NumBreakDowns == 1)
276         // This is a already a copy, there is nothing to do.
277         RepairPt.switchTo(RepairingPlacement::RepairingKind::Reassign);
278     }
279     return;
280   }
281 
282   // At this point, we need to repair a defintion of a terminator.
283 
284   // Technically we need to fix the def of MI on all outgoing
285   // edges of MI to keep the repairing local. In other words, we
286   // will create several definitions of the same register. This
287   // does not work for SSA unless that definition is a physical
288   // register.
289   // However, there are other cases where we can get away with
290   // that while still keeping the repairing local.
291   assert(MI.isTerminator() && MO.isDef() &&
292          "This code is for the def of a terminator");
293 
294   // Since we use RPO traversal, if we need to repair a definition
295   // this means this definition could be:
296   // 1. Used by PHIs (i.e., this VReg has been visited as part of the
297   //    uses of a phi.), or
298   // 2. Part of a target specific instruction (i.e., the target applied
299   //    some register class constraints when creating the instruction.)
300   // If the constraints come for #2, the target said that another mapping
301   // is supported so we may just drop them. Indeed, if we do not change
302   // the number of registers holding that value, the uses will get fixed
303   // when we get to them.
304   // Uses in PHIs may have already been proceeded though.
305   // If the constraints come for #1, then, those are weak constraints and
306   // no actual uses may rely on them. However, the problem remains mainly
307   // the same as for #2. If the value stays in one register, we could
308   // just switch the register bank of the definition, but we would need to
309   // account for a repairing cost for each phi we silently change.
310   //
311   // In any case, if the value needs to be broken down into several
312   // registers, the repairing is not local anymore as we need to patch
313   // every uses to rebuild the value in just one register.
314   //
315   // To summarize:
316   // - If the value is in a physical register, we can do the split and
317   //   fix locally.
318   // Otherwise if the value is in a virtual register:
319   // - If the value remains in one register, we do not have to split
320   //   just switching the register bank would do, but we need to account
321   //   in the repairing cost all the phi we changed.
322   // - If the value spans several registers, then we cannot do a local
323   //   repairing.
324 
325   // Check if this is a physical or virtual register.
326   unsigned Reg = MO.getReg();
327   if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
328     // We are going to split every outgoing edges.
329     // Check that this is possible.
330     // FIXME: The machine representation is currently broken
331     // since it also several terminators in one basic block.
332     // Because of that we would technically need a way to get
333     // the targets of just one terminator to know which edges
334     // we have to split.
335     // Assert that we do not hit the ill-formed representation.
336 
337     // If there are other terminators before that one, some of
338     // the outgoing edges may not be dominated by this definition.
339     assert(&MI == &(*MI.getParent()->getFirstTerminator()) &&
340            "Do not know which outgoing edges are relevant");
341     const MachineInstr *Next = MI.getNextNode();
342     assert((!Next || Next->isUnconditionalBranch()) &&
343            "Do not know where each terminator ends up");
344     if (Next)
345       // If the next terminator uses Reg, this means we have
346       // to split right after MI and thus we need a way to ask
347       // which outgoing edges are affected.
348       assert(!Next->readsRegister(Reg) && "Need to split between terminators");
349     // We will split all the edges and repair there.
350   } else {
351     // This is a virtual register defined by a terminator.
352     if (ValMapping.NumBreakDowns == 1) {
353       // There is nothing to repair, but we may actually lie on
354       // the repairing cost because of the PHIs already proceeded
355       // as already stated.
356       // Though the code will be correct.
357       assert(0 && "Repairing cost may not be accurate");
358     } else {
359       // We need to do non-local repairing. Basically, patch all
360       // the uses (i.e., phis) that we already proceeded.
361       // For now, just say this mapping is not possible.
362       RepairPt.switchTo(RepairingPlacement::RepairingKind::Impossible);
363     }
364   }
365 }
366 
367 RegBankSelect::MappingCost RegBankSelect::computeMapping(
368     MachineInstr &MI, const RegisterBankInfo::InstructionMapping &InstrMapping,
369     SmallVectorImpl<RepairingPlacement> &RepairPts,
370     const RegBankSelect::MappingCost *BestCost) {
371   assert((MBFI || !BestCost) && "Costs comparison require MBFI");
372 
373   if (!InstrMapping.isValid())
374     return MappingCost::ImpossibleCost();
375 
376   // If mapped with InstrMapping, MI will have the recorded cost.
377   MappingCost Cost(MBFI ? MBFI->getBlockFreq(MI.getParent()) : 1);
378   bool Saturated = Cost.addLocalCost(InstrMapping.getCost());
379   assert(!Saturated && "Possible mapping saturated the cost");
380   DEBUG(dbgs() << "Evaluating mapping cost for: " << MI);
381   DEBUG(dbgs() << "With: " << InstrMapping << '\n');
382   RepairPts.clear();
383   if (BestCost && Cost > *BestCost) {
384     DEBUG(dbgs() << "Mapping is too expensive from the start\n");
385     return Cost;
386   }
387 
388   // Moreover, to realize this mapping, the register bank of each operand must
389   // match this mapping. In other words, we may need to locally reassign the
390   // register banks. Account for that repairing cost as well.
391   // In this context, local means in the surrounding of MI.
392   for (unsigned OpIdx = 0, EndOpIdx = InstrMapping.getNumOperands();
393        OpIdx != EndOpIdx; ++OpIdx) {
394     const MachineOperand &MO = MI.getOperand(OpIdx);
395     if (!MO.isReg())
396       continue;
397     unsigned Reg = MO.getReg();
398     if (!Reg)
399       continue;
400     DEBUG(dbgs() << "Opd" << OpIdx << '\n');
401     const RegisterBankInfo::ValueMapping &ValMapping =
402         InstrMapping.getOperandMapping(OpIdx);
403     // If Reg is already properly mapped, this is free.
404     bool Assign;
405     if (assignmentMatch(Reg, ValMapping, Assign)) {
406       DEBUG(dbgs() << "=> is free (match).\n");
407       continue;
408     }
409     if (Assign) {
410       DEBUG(dbgs() << "=> is free (simple assignment).\n");
411       RepairPts.emplace_back(RepairingPlacement(MI, OpIdx, *TRI, *this,
412                                                 RepairingPlacement::Reassign));
413       continue;
414     }
415 
416     // Find the insertion point for the repairing code.
417     RepairPts.emplace_back(
418         RepairingPlacement(MI, OpIdx, *TRI, *this, RepairingPlacement::Insert));
419     RepairingPlacement &RepairPt = RepairPts.back();
420 
421     // If we need to split a basic block to materialize this insertion point,
422     // we may give a higher cost to this mapping.
423     // Nevertheless, we may get away with the split, so try that first.
424     if (RepairPt.hasSplit())
425       tryAvoidingSplit(RepairPt, MO, ValMapping);
426 
427     // Check that the materialization of the repairing is possible.
428     if (!RepairPt.canMaterialize()) {
429       DEBUG(dbgs() << "Mapping involves impossible repairing\n");
430       return MappingCost::ImpossibleCost();
431     }
432 
433     // Account for the split cost and repair cost.
434     // Unless the cost is already saturated or we do not care about the cost.
435     if (!BestCost || Saturated)
436       continue;
437 
438     // To get accurate information we need MBFI and MBPI.
439     // Thus, if we end up here this information should be here.
440     assert(MBFI && MBPI && "Cost computation requires MBFI and MBPI");
441 
442     // FIXME: We will have to rework the repairing cost model.
443     // The repairing cost depends on the register bank that MO has.
444     // However, when we break down the value into different values,
445     // MO may not have a register bank while still needing repairing.
446     // For the fast mode, we don't compute the cost so that is fine,
447     // but still for the repairing code, we will have to make a choice.
448     // For the greedy mode, we should choose greedily what is the best
449     // choice based on the next use of MO.
450 
451     // Sums up the repairing cost of MO at each insertion point.
452     uint64_t RepairCost = getRepairCost(MO, ValMapping);
453     // Bias used for splitting: 5%.
454     const uint64_t PercentageForBias = 5;
455     uint64_t Bias = (RepairCost * PercentageForBias + 99) / 100;
456     // We should not need more than a couple of instructions to repair
457     // an assignment. In other words, the computation should not
458     // overflow because the repairing cost is free of basic block
459     // frequency.
460     assert(((RepairCost < RepairCost * PercentageForBias) &&
461             (RepairCost * PercentageForBias <
462              RepairCost * PercentageForBias + 99)) &&
463            "Repairing involves more than a billion of instructions?!");
464     for (const std::unique_ptr<InsertPoint> &InsertPt : RepairPt) {
465       assert(InsertPt->canMaterialize() && "We should not have made it here");
466       // We will applied some basic block frequency and those uses uint64_t.
467       if (!InsertPt->isSplit())
468         Saturated = Cost.addLocalCost(RepairCost);
469       else {
470         uint64_t CostForInsertPt = RepairCost;
471         // Again we shouldn't overflow here givent that
472         // CostForInsertPt is frequency free at this point.
473         assert(CostForInsertPt + Bias > CostForInsertPt &&
474                "Repairing + split bias overflows");
475         CostForInsertPt += Bias;
476         uint64_t PtCost = InsertPt->frequency(*this) * CostForInsertPt;
477         // Check if we just overflowed.
478         if ((Saturated = PtCost < CostForInsertPt))
479           Cost.saturate();
480         else
481           Saturated = Cost.addNonLocalCost(PtCost);
482       }
483 
484       // Stop looking into what it takes to repair, this is already
485       // too expensive.
486       if (BestCost && Cost > *BestCost) {
487         DEBUG(dbgs() << "Mapping is too expensive, stop processing\n");
488         return Cost;
489       }
490 
491       // No need to accumulate more cost information.
492       // We need to still gather the repairing information though.
493       if (Saturated)
494         break;
495     }
496   }
497   DEBUG(dbgs() << "Total cost is: " << Cost << "\n");
498   return Cost;
499 }
500 
501 bool RegBankSelect::applyMapping(
502     MachineInstr &MI, const RegisterBankInfo::InstructionMapping &InstrMapping,
503     SmallVectorImpl<RegBankSelect::RepairingPlacement> &RepairPts) {
504   // OpdMapper will hold all the information needed for the rewritting.
505   RegisterBankInfo::OperandsMapper OpdMapper(MI, InstrMapping, *MRI);
506 
507   // First, place the repairing code.
508   for (RepairingPlacement &RepairPt : RepairPts) {
509     if (!RepairPt.canMaterialize() ||
510         RepairPt.getKind() == RepairingPlacement::Impossible)
511       return false;
512     assert(RepairPt.getKind() != RepairingPlacement::None &&
513            "This should not make its way in the list");
514     unsigned OpIdx = RepairPt.getOpIdx();
515     MachineOperand &MO = MI.getOperand(OpIdx);
516     const RegisterBankInfo::ValueMapping &ValMapping =
517         InstrMapping.getOperandMapping(OpIdx);
518     unsigned Reg = MO.getReg();
519 
520     switch (RepairPt.getKind()) {
521     case RepairingPlacement::Reassign:
522       assert(ValMapping.NumBreakDowns == 1 &&
523              "Reassignment should only be for simple mapping");
524       MRI->setRegBank(Reg, *ValMapping.BreakDown[0].RegBank);
525       break;
526     case RepairingPlacement::Insert:
527       OpdMapper.createVRegs(OpIdx);
528       if (!repairReg(MO, ValMapping, RepairPt, OpdMapper.getVRegs(OpIdx)))
529         return false;
530       break;
531     default:
532       llvm_unreachable("Other kind should not happen");
533     }
534   }
535   // Second, rewrite the instruction.
536   DEBUG(dbgs() << "Actual mapping of the operands: " << OpdMapper << '\n');
537   RBI->applyMapping(OpdMapper);
538   return true;
539 }
540 
541 bool RegBankSelect::assignInstr(MachineInstr &MI) {
542   DEBUG(dbgs() << "Assign: " << MI);
543   // Remember the repairing placement for all the operands.
544   SmallVector<RepairingPlacement, 4> RepairPts;
545 
546   RegisterBankInfo::InstructionMapping BestMapping;
547   if (OptMode == RegBankSelect::Mode::Fast) {
548     BestMapping = RBI->getInstrMapping(MI);
549     MappingCost DefaultCost = computeMapping(MI, BestMapping, RepairPts);
550     (void)DefaultCost;
551     if (DefaultCost == MappingCost::ImpossibleCost())
552       return false;
553   } else {
554     RegisterBankInfo::InstructionMappings PossibleMappings =
555         RBI->getInstrPossibleMappings(MI);
556     if (PossibleMappings.empty())
557       return false;
558     BestMapping = std::move(findBestMapping(MI, PossibleMappings, RepairPts));
559   }
560   // Make sure the mapping is valid for MI.
561   assert(BestMapping.verify(MI) && "Invalid instruction mapping");
562 
563   DEBUG(dbgs() << "Best Mapping: " << BestMapping << '\n');
564 
565   // After this call, MI may not be valid anymore.
566   // Do not use it.
567   return applyMapping(MI, BestMapping, RepairPts);
568 }
569 
570 bool RegBankSelect::runOnMachineFunction(MachineFunction &MF) {
571   // If the ISel pipeline failed, do not bother running that pass.
572   if (MF.getProperties().hasProperty(
573           MachineFunctionProperties::Property::FailedISel))
574     return false;
575 
576   DEBUG(dbgs() << "Assign register banks for: " << MF.getName() << '\n');
577   const Function *F = MF.getFunction();
578   Mode SaveOptMode = OptMode;
579   if (F->hasFnAttribute(Attribute::OptimizeNone))
580     OptMode = Mode::Fast;
581   init(MF);
582 
583 #ifndef NDEBUG
584   // Check that our input is fully legal: we require the function to have the
585   // Legalized property, so it should be.
586   // FIXME: This should be in the MachineVerifier, but it can't use the
587   // LegalizerInfo as it's currently in the separate GlobalISel library.
588   const MachineRegisterInfo &MRI = MF.getRegInfo();
589   if (const LegalizerInfo *MLI = MF.getSubtarget().getLegalizerInfo()) {
590     for (MachineBasicBlock &MBB : MF) {
591       for (MachineInstr &MI : MBB) {
592         if (isPreISelGenericOpcode(MI.getOpcode()) && !MLI->isLegal(MI, MRI)) {
593           reportGISelFailure(MF, *TPC, *MORE, "gisel-regbankselect",
594                              "instruction is not legal", MI);
595           return false;
596         }
597       }
598     }
599   }
600 #endif
601 
602   // Walk the function and assign register banks to all operands.
603   // Use a RPOT to make sure all registers are assigned before we choose
604   // the best mapping of the current instruction.
605   ReversePostOrderTraversal<MachineFunction*> RPOT(&MF);
606   for (MachineBasicBlock *MBB : RPOT) {
607     // Set a sensible insertion point so that subsequent calls to
608     // MIRBuilder.
609     MIRBuilder.setMBB(*MBB);
610     for (MachineBasicBlock::iterator MII = MBB->begin(), End = MBB->end();
611          MII != End;) {
612       // MI might be invalidated by the assignment, so move the
613       // iterator before hand.
614       MachineInstr &MI = *MII++;
615 
616       // Ignore target-specific instructions: they should use proper regclasses.
617       if (isTargetSpecificOpcode(MI.getOpcode()))
618         continue;
619 
620       if (!assignInstr(MI)) {
621         reportGISelFailure(MF, *TPC, *MORE, "gisel-regbankselect",
622                            "unable to map instruction", MI);
623         return false;
624       }
625     }
626   }
627   OptMode = SaveOptMode;
628   return false;
629 }
630 
631 //------------------------------------------------------------------------------
632 //                  Helper Classes Implementation
633 //------------------------------------------------------------------------------
634 RegBankSelect::RepairingPlacement::RepairingPlacement(
635     MachineInstr &MI, unsigned OpIdx, const TargetRegisterInfo &TRI, Pass &P,
636     RepairingPlacement::RepairingKind Kind)
637     // Default is, we are going to insert code to repair OpIdx.
638     : Kind(Kind),
639       OpIdx(OpIdx),
640       CanMaterialize(Kind != RepairingKind::Impossible),
641       HasSplit(false),
642       P(P) {
643   const MachineOperand &MO = MI.getOperand(OpIdx);
644   assert(MO.isReg() && "Trying to repair a non-reg operand");
645 
646   if (Kind != RepairingKind::Insert)
647     return;
648 
649   // Repairings for definitions happen after MI, uses happen before.
650   bool Before = !MO.isDef();
651 
652   // Check if we are done with MI.
653   if (!MI.isPHI() && !MI.isTerminator()) {
654     addInsertPoint(MI, Before);
655     // We are done with the initialization.
656     return;
657   }
658 
659   // Now, look for the special cases.
660   if (MI.isPHI()) {
661     // - PHI must be the first instructions:
662     //   * Before, we have to split the related incoming edge.
663     //   * After, move the insertion point past the last phi.
664     if (!Before) {
665       MachineBasicBlock::iterator It = MI.getParent()->getFirstNonPHI();
666       if (It != MI.getParent()->end())
667         addInsertPoint(*It, /*Before*/ true);
668       else
669         addInsertPoint(*(--It), /*Before*/ false);
670       return;
671     }
672     // We repair a use of a phi, we may need to split the related edge.
673     MachineBasicBlock &Pred = *MI.getOperand(OpIdx + 1).getMBB();
674     // Check if we can move the insertion point prior to the
675     // terminators of the predecessor.
676     unsigned Reg = MO.getReg();
677     MachineBasicBlock::iterator It = Pred.getLastNonDebugInstr();
678     for (auto Begin = Pred.begin(); It != Begin && It->isTerminator(); --It)
679       if (It->modifiesRegister(Reg, &TRI)) {
680         // We cannot hoist the repairing code in the predecessor.
681         // Split the edge.
682         addInsertPoint(Pred, *MI.getParent());
683         return;
684       }
685     // At this point, we can insert in Pred.
686 
687     // - If It is invalid, Pred is empty and we can insert in Pred
688     //   wherever we want.
689     // - If It is valid, It is the first non-terminator, insert after It.
690     if (It == Pred.end())
691       addInsertPoint(Pred, /*Beginning*/ false);
692     else
693       addInsertPoint(*It, /*Before*/ false);
694   } else {
695     // - Terminators must be the last instructions:
696     //   * Before, move the insert point before the first terminator.
697     //   * After, we have to split the outcoming edges.
698     unsigned Reg = MO.getReg();
699     if (Before) {
700       // Check whether Reg is defined by any terminator.
701       MachineBasicBlock::iterator It = MI;
702       for (auto Begin = MI.getParent()->begin();
703            --It != Begin && It->isTerminator();)
704         if (It->modifiesRegister(Reg, &TRI)) {
705           // Insert the repairing code right after the definition.
706           addInsertPoint(*It, /*Before*/ false);
707           return;
708         }
709       addInsertPoint(*It, /*Before*/ true);
710       return;
711     }
712     // Make sure Reg is not redefined by other terminators, otherwise
713     // we do not know how to split.
714     for (MachineBasicBlock::iterator It = MI, End = MI.getParent()->end();
715          ++It != End;)
716       // The machine verifier should reject this kind of code.
717       assert(It->modifiesRegister(Reg, &TRI) && "Do not know where to split");
718     // Split each outcoming edges.
719     MachineBasicBlock &Src = *MI.getParent();
720     for (auto &Succ : Src.successors())
721       addInsertPoint(Src, Succ);
722   }
723 }
724 
725 void RegBankSelect::RepairingPlacement::addInsertPoint(MachineInstr &MI,
726                                                        bool Before) {
727   addInsertPoint(*new InstrInsertPoint(MI, Before));
728 }
729 
730 void RegBankSelect::RepairingPlacement::addInsertPoint(MachineBasicBlock &MBB,
731                                                        bool Beginning) {
732   addInsertPoint(*new MBBInsertPoint(MBB, Beginning));
733 }
734 
735 void RegBankSelect::RepairingPlacement::addInsertPoint(MachineBasicBlock &Src,
736                                                        MachineBasicBlock &Dst) {
737   addInsertPoint(*new EdgeInsertPoint(Src, Dst, P));
738 }
739 
740 void RegBankSelect::RepairingPlacement::addInsertPoint(
741     RegBankSelect::InsertPoint &Point) {
742   CanMaterialize &= Point.canMaterialize();
743   HasSplit |= Point.isSplit();
744   InsertPoints.emplace_back(&Point);
745 }
746 
747 RegBankSelect::InstrInsertPoint::InstrInsertPoint(MachineInstr &Instr,
748                                                   bool Before)
749     : InsertPoint(), Instr(Instr), Before(Before) {
750   // Since we do not support splitting, we do not need to update
751   // liveness and such, so do not do anything with P.
752   assert((!Before || !Instr.isPHI()) &&
753          "Splitting before phis requires more points");
754   assert((!Before || !Instr.getNextNode() || !Instr.getNextNode()->isPHI()) &&
755          "Splitting between phis does not make sense");
756 }
757 
758 void RegBankSelect::InstrInsertPoint::materialize() {
759   if (isSplit()) {
760     // Slice and return the beginning of the new block.
761     // If we need to split between the terminators, we theoritically
762     // need to know where the first and second set of terminators end
763     // to update the successors properly.
764     // Now, in pratice, we should have a maximum of 2 branch
765     // instructions; one conditional and one unconditional. Therefore
766     // we know how to update the successor by looking at the target of
767     // the unconditional branch.
768     // If we end up splitting at some point, then, we should update
769     // the liveness information and such. I.e., we would need to
770     // access P here.
771     // The machine verifier should actually make sure such cases
772     // cannot happen.
773     llvm_unreachable("Not yet implemented");
774   }
775   // Otherwise the insertion point is just the current or next
776   // instruction depending on Before. I.e., there is nothing to do
777   // here.
778 }
779 
780 bool RegBankSelect::InstrInsertPoint::isSplit() const {
781   // If the insertion point is after a terminator, we need to split.
782   if (!Before)
783     return Instr.isTerminator();
784   // If we insert before an instruction that is after a terminator,
785   // we are still after a terminator.
786   return Instr.getPrevNode() && Instr.getPrevNode()->isTerminator();
787 }
788 
789 uint64_t RegBankSelect::InstrInsertPoint::frequency(const Pass &P) const {
790   // Even if we need to split, because we insert between terminators,
791   // this split has actually the same frequency as the instruction.
792   const MachineBlockFrequencyInfo *MBFI =
793       P.getAnalysisIfAvailable<MachineBlockFrequencyInfo>();
794   if (!MBFI)
795     return 1;
796   return MBFI->getBlockFreq(Instr.getParent()).getFrequency();
797 }
798 
799 uint64_t RegBankSelect::MBBInsertPoint::frequency(const Pass &P) const {
800   const MachineBlockFrequencyInfo *MBFI =
801       P.getAnalysisIfAvailable<MachineBlockFrequencyInfo>();
802   if (!MBFI)
803     return 1;
804   return MBFI->getBlockFreq(&MBB).getFrequency();
805 }
806 
807 void RegBankSelect::EdgeInsertPoint::materialize() {
808   // If we end up repairing twice at the same place before materializing the
809   // insertion point, we may think we have to split an edge twice.
810   // We should have a factory for the insert point such that identical points
811   // are the same instance.
812   assert(Src.isSuccessor(DstOrSplit) && DstOrSplit->isPredecessor(&Src) &&
813          "This point has already been split");
814   MachineBasicBlock *NewBB = Src.SplitCriticalEdge(DstOrSplit, P);
815   assert(NewBB && "Invalid call to materialize");
816   // We reuse the destination block to hold the information of the new block.
817   DstOrSplit = NewBB;
818 }
819 
820 uint64_t RegBankSelect::EdgeInsertPoint::frequency(const Pass &P) const {
821   const MachineBlockFrequencyInfo *MBFI =
822       P.getAnalysisIfAvailable<MachineBlockFrequencyInfo>();
823   if (!MBFI)
824     return 1;
825   if (WasMaterialized)
826     return MBFI->getBlockFreq(DstOrSplit).getFrequency();
827 
828   const MachineBranchProbabilityInfo *MBPI =
829       P.getAnalysisIfAvailable<MachineBranchProbabilityInfo>();
830   if (!MBPI)
831     return 1;
832   // The basic block will be on the edge.
833   return (MBFI->getBlockFreq(&Src) * MBPI->getEdgeProbability(&Src, DstOrSplit))
834       .getFrequency();
835 }
836 
837 bool RegBankSelect::EdgeInsertPoint::canMaterialize() const {
838   // If this is not a critical edge, we should not have used this insert
839   // point. Indeed, either the successor or the predecessor should
840   // have do.
841   assert(Src.succ_size() > 1 && DstOrSplit->pred_size() > 1 &&
842          "Edge is not critical");
843   return Src.canSplitCriticalEdge(DstOrSplit);
844 }
845 
846 RegBankSelect::MappingCost::MappingCost(const BlockFrequency &LocalFreq)
847     : LocalCost(0), NonLocalCost(0), LocalFreq(LocalFreq.getFrequency()) {}
848 
849 bool RegBankSelect::MappingCost::addLocalCost(uint64_t Cost) {
850   // Check if this overflows.
851   if (LocalCost + Cost < LocalCost) {
852     saturate();
853     return true;
854   }
855   LocalCost += Cost;
856   return isSaturated();
857 }
858 
859 bool RegBankSelect::MappingCost::addNonLocalCost(uint64_t Cost) {
860   // Check if this overflows.
861   if (NonLocalCost + Cost < NonLocalCost) {
862     saturate();
863     return true;
864   }
865   NonLocalCost += Cost;
866   return isSaturated();
867 }
868 
869 bool RegBankSelect::MappingCost::isSaturated() const {
870   return LocalCost == UINT64_MAX - 1 && NonLocalCost == UINT64_MAX &&
871          LocalFreq == UINT64_MAX;
872 }
873 
874 void RegBankSelect::MappingCost::saturate() {
875   *this = ImpossibleCost();
876   --LocalCost;
877 }
878 
879 RegBankSelect::MappingCost RegBankSelect::MappingCost::ImpossibleCost() {
880   return MappingCost(UINT64_MAX, UINT64_MAX, UINT64_MAX);
881 }
882 
883 bool RegBankSelect::MappingCost::operator<(const MappingCost &Cost) const {
884   // Sort out the easy cases.
885   if (*this == Cost)
886     return false;
887   // If one is impossible to realize the other is cheaper unless it is
888   // impossible as well.
889   if ((*this == ImpossibleCost()) || (Cost == ImpossibleCost()))
890     return (*this == ImpossibleCost()) < (Cost == ImpossibleCost());
891   // If one is saturated the other is cheaper, unless it is saturated
892   // as well.
893   if (isSaturated() || Cost.isSaturated())
894     return isSaturated() < Cost.isSaturated();
895   // At this point we know both costs hold sensible values.
896 
897   // If both values have a different base frequency, there is no much
898   // we can do but to scale everything.
899   // However, if they have the same base frequency we can avoid making
900   // complicated computation.
901   uint64_t ThisLocalAdjust;
902   uint64_t OtherLocalAdjust;
903   if (LLVM_LIKELY(LocalFreq == Cost.LocalFreq)) {
904 
905     // At this point, we know the local costs are comparable.
906     // Do the case that do not involve potential overflow first.
907     if (NonLocalCost == Cost.NonLocalCost)
908       // Since the non-local costs do not discriminate on the result,
909       // just compare the local costs.
910       return LocalCost < Cost.LocalCost;
911 
912     // The base costs are comparable so we may only keep the relative
913     // value to increase our chances of avoiding overflows.
914     ThisLocalAdjust = 0;
915     OtherLocalAdjust = 0;
916     if (LocalCost < Cost.LocalCost)
917       OtherLocalAdjust = Cost.LocalCost - LocalCost;
918     else
919       ThisLocalAdjust = LocalCost - Cost.LocalCost;
920 
921   } else {
922     ThisLocalAdjust = LocalCost;
923     OtherLocalAdjust = Cost.LocalCost;
924   }
925 
926   // The non-local costs are comparable, just keep the relative value.
927   uint64_t ThisNonLocalAdjust = 0;
928   uint64_t OtherNonLocalAdjust = 0;
929   if (NonLocalCost < Cost.NonLocalCost)
930     OtherNonLocalAdjust = Cost.NonLocalCost - NonLocalCost;
931   else
932     ThisNonLocalAdjust = NonLocalCost - Cost.NonLocalCost;
933   // Scale everything to make them comparable.
934   uint64_t ThisScaledCost = ThisLocalAdjust * LocalFreq;
935   // Check for overflow on that operation.
936   bool ThisOverflows = ThisLocalAdjust && (ThisScaledCost < ThisLocalAdjust ||
937                                            ThisScaledCost < LocalFreq);
938   uint64_t OtherScaledCost = OtherLocalAdjust * Cost.LocalFreq;
939   // Check for overflow on the last operation.
940   bool OtherOverflows =
941       OtherLocalAdjust &&
942       (OtherScaledCost < OtherLocalAdjust || OtherScaledCost < Cost.LocalFreq);
943   // Add the non-local costs.
944   ThisOverflows |= ThisNonLocalAdjust &&
945                    ThisScaledCost + ThisNonLocalAdjust < ThisNonLocalAdjust;
946   ThisScaledCost += ThisNonLocalAdjust;
947   OtherOverflows |= OtherNonLocalAdjust &&
948                     OtherScaledCost + OtherNonLocalAdjust < OtherNonLocalAdjust;
949   OtherScaledCost += OtherNonLocalAdjust;
950   // If both overflows, we cannot compare without additional
951   // precision, e.g., APInt. Just give up on that case.
952   if (ThisOverflows && OtherOverflows)
953     return false;
954   // If one overflows but not the other, we can still compare.
955   if (ThisOverflows || OtherOverflows)
956     return ThisOverflows < OtherOverflows;
957   // Otherwise, just compare the values.
958   return ThisScaledCost < OtherScaledCost;
959 }
960 
961 bool RegBankSelect::MappingCost::operator==(const MappingCost &Cost) const {
962   return LocalCost == Cost.LocalCost && NonLocalCost == Cost.NonLocalCost &&
963          LocalFreq == Cost.LocalFreq;
964 }
965 
966 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
967 LLVM_DUMP_METHOD void RegBankSelect::MappingCost::dump() const {
968   print(dbgs());
969   dbgs() << '\n';
970 }
971 #endif
972 
973 void RegBankSelect::MappingCost::print(raw_ostream &OS) const {
974   if (*this == ImpossibleCost()) {
975     OS << "impossible";
976     return;
977   }
978   if (isSaturated()) {
979     OS << "saturated";
980     return;
981   }
982   OS << LocalFreq << " * " << LocalCost << " + " << NonLocalCost;
983 }
984