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