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