blob: 4890d45a6d3e9c3b5f500db76413b03b1716f1e2 [file] [log] [blame]
Quentin Colombet8e8e85c2016-04-05 19:06:01 +00001//===- 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"
Quentin Colombetcfd97b92016-05-20 00:35:26 +000014#include "llvm/ADT/PostOrderIterator.h"
Quentin Colombet40ad5732016-04-07 18:19:27 +000015#include "llvm/CodeGen/GlobalISel/RegisterBank.h"
Quentin Colombet55650752016-05-20 00:49:10 +000016#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
17#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
Quentin Colombet40ad5732016-04-07 18:19:27 +000018#include "llvm/CodeGen/MachineRegisterInfo.h"
Quentin Colombeta5530122016-05-20 17:36:54 +000019#include "llvm/IR/Function.h"
Quentin Colombetcfd97b92016-05-20 00:35:26 +000020#include "llvm/Support/BlockFrequency.h"
Quentin Colombete16f5612016-04-07 23:53:55 +000021#include "llvm/Support/Debug.h"
Quentin Colombet40ad5732016-04-07 18:19:27 +000022#include "llvm/Target/TargetSubtargetInfo.h"
Quentin Colombet8e8e85c2016-04-05 19:06:01 +000023
24#define DEBUG_TYPE "regbankselect"
25
26using namespace llvm;
27
28char RegBankSelect::ID = 0;
Quentin Colombet25fcef72016-05-20 17:54:09 +000029INITIALIZE_PASS_BEGIN(RegBankSelect, "regbankselect",
30 "Assign register bank of generic virtual registers",
31 false, false);
32INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
33INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
34INITIALIZE_PASS_END(RegBankSelect, "regbankselect",
35 "Assign register bank of generic virtual registers", false,
36 false);
Quentin Colombet8e8e85c2016-04-05 19:06:01 +000037
Quentin Colombet46df7222016-05-20 16:55:35 +000038RegBankSelect::RegBankSelect(Mode RunningMode)
Quentin Colombet25fcef72016-05-20 17:54:09 +000039 : MachineFunctionPass(ID), RBI(nullptr), MRI(nullptr), TRI(nullptr),
40 MBFI(nullptr), MBPI(nullptr), OptMode(RunningMode) {
Quentin Colombet8e8e85c2016-04-05 19:06:01 +000041 initializeRegBankSelectPass(*PassRegistry::getPassRegistry());
42}
43
Quentin Colombet40ad5732016-04-07 18:19:27 +000044void RegBankSelect::init(MachineFunction &MF) {
45 RBI = MF.getSubtarget().getRegBankInfo();
46 assert(RBI && "Cannot work without RegisterBankInfo");
47 MRI = &MF.getRegInfo();
Quentin Colombetaac71a42016-04-07 21:32:23 +000048 TRI = MF.getSubtarget().getRegisterInfo();
Quentin Colombet25fcef72016-05-20 17:54:09 +000049 if (OptMode != Mode::Fast) {
50 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
51 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
52 } else {
53 MBFI = nullptr;
54 MBPI = nullptr;
55 }
Quentin Colombet40ad5732016-04-07 18:19:27 +000056 MIRBuilder.setMF(MF);
57}
58
Quentin Colombet25fcef72016-05-20 17:54:09 +000059void RegBankSelect::getAnalysisUsage(AnalysisUsage &AU) const {
60 if (OptMode != Mode::Fast) {
61 // We could preserve the information from these two analysis but
62 // the APIs do not allow to do so yet.
63 AU.addRequired<MachineBlockFrequencyInfo>();
64 AU.addRequired<MachineBranchProbabilityInfo>();
65 }
66 MachineFunctionPass::getAnalysisUsage(AU);
67}
68
Quentin Colombet40ad5732016-04-07 18:19:27 +000069bool RegBankSelect::assignmentMatch(
Quentin Colombet0d77da42016-05-20 00:42:57 +000070 unsigned Reg, const RegisterBankInfo::ValueMapping &ValMapping,
71 bool &OnlyAssign) const {
72 // By default we assume we will have to repair something.
73 OnlyAssign = false;
Quentin Colombet40ad5732016-04-07 18:19:27 +000074 // Each part of a break down needs to end up in a different register.
75 // In other word, Reg assignement does not match.
76 if (ValMapping.BreakDown.size() > 1)
77 return false;
78
Quentin Colombet6d6d6af2016-04-08 16:48:16 +000079 const RegisterBank *CurRegBank = RBI->getRegBank(Reg, *MRI, *TRI);
80 const RegisterBank *DesiredRegBrank = ValMapping.BreakDown[0].RegBank;
Quentin Colombet0d77da42016-05-20 00:42:57 +000081 // Reg is free of assignment, a simple assignment will make the
82 // register bank to match.
83 OnlyAssign = CurRegBank == nullptr;
Quentin Colombet6d6d6af2016-04-08 16:48:16 +000084 DEBUG(dbgs() << "Does assignment already match: ";
85 if (CurRegBank) dbgs() << *CurRegBank; else dbgs() << "none";
86 dbgs() << " against ";
87 assert(DesiredRegBrank && "The mapping must be valid");
88 dbgs() << *DesiredRegBrank << '\n';);
89 return CurRegBank == DesiredRegBrank;
Quentin Colombet40ad5732016-04-07 18:19:27 +000090}
91
Quentin Colombetd84d00b2016-05-20 00:55:51 +000092void RegBankSelect::repairReg(
93 MachineOperand &MO, const RegisterBankInfo::ValueMapping &ValMapping,
94 RegBankSelect::RepairingPlacement &RepairPt,
95 const iterator_range<SmallVectorImpl<unsigned>::iterator> &NewVRegs) {
96 assert(ValMapping.BreakDown.size() == 1 && "Not yet implemented");
97 // Assume we are repairing a use and thus, the original reg will be
98 // the source of the repairing.
99 unsigned Src = MO.getReg();
100 unsigned Dst = *NewVRegs.begin();
101 if (ValMapping.BreakDown.size() == 1)
102 MO.setReg(Dst);
Quentin Colombet904a2c72016-04-12 00:12:59 +0000103
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000104 // If we repair a definition, swap the source and destination for
105 // the repairing.
106 if (MO.isDef())
Quentin Colombet904a2c72016-04-12 00:12:59 +0000107 std::swap(Src, Dst);
Quentin Colombet904a2c72016-04-12 00:12:59 +0000108
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000109 assert((RepairPt.getNumInsertPoints() == 1 ||
110 TargetRegisterInfo::isPhysicalRegister(Dst)) &&
111 "We are about to create several defs for Dst");
Quentin Colombet904a2c72016-04-12 00:12:59 +0000112
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000113 // Build the instruction used to repair, then clone it at the right places.
114 MachineInstr *MI = MIRBuilder.buildInstr(TargetOpcode::COPY, Dst, Src);
115 MI->removeFromParent();
116 DEBUG(dbgs() << "Copy: " << PrintReg(Src) << " to: " << PrintReg(Dst)
117 << '\n');
118 // TODO:
119 // Check if MI is legal. if not, we need to legalize all the
120 // instructions we are going to insert.
121 std::unique_ptr<MachineInstr *[]> NewInstrs(
122 new MachineInstr *[RepairPt.getNumInsertPoints()]);
123 bool IsFirst = true;
124 unsigned Idx = 0;
125 for (const std::unique_ptr<InsertPoint> &InsertPt : RepairPt) {
126 MachineInstr *CurMI;
127 if (IsFirst)
128 CurMI = MI;
129 else
130 CurMI = MIRBuilder.getMF().CloneMachineInstr(MI);
131 InsertPt->insert(*CurMI);
132 NewInstrs[Idx++] = CurMI;
133 IsFirst = false;
134 }
135 // TODO:
136 // Legalize NewInstrs if need be.
Quentin Colombet40ad5732016-04-07 18:19:27 +0000137}
138
Quentin Colombetf2723a22016-05-21 01:43:25 +0000139uint64_t RegBankSelect::getRepairCost(
140 const MachineOperand &MO,
141 const RegisterBankInfo::ValueMapping &ValMapping) const {
142 assert(MO.isReg() && "We should only repair register operand");
143 assert(!ValMapping.BreakDown.empty() && "Nothing to map??");
144
145 bool IsSameNumOfValues = ValMapping.BreakDown.size() == 1;
146 const RegisterBank *CurRegBank = RBI->getRegBank(MO.getReg(), *MRI, *TRI);
147 // If MO does not have a register bank, we should have just been
148 // able to set one unless we have to break the value down.
149 assert((!IsSameNumOfValues || CurRegBank) && "We should not have to repair");
150 // Def: Val <- NewDefs
151 // Same number of values: copy
152 // Different number: Val = build_sequence Defs1, Defs2, ...
153 // Use: NewSources <- Val.
154 // Same number of values: copy.
155 // Different number: Src1, Src2, ... =
156 // extract_value Val, Src1Begin, Src1Len, Src2Begin, Src2Len, ...
157 // We should remember that this value is available somewhere else to
158 // coalesce the value.
159
160 if (IsSameNumOfValues) {
161 const RegisterBank *DesiredRegBrank = ValMapping.BreakDown[0].RegBank;
162 // If we repair a definition, swap the source and destination for
163 // the repairing.
164 if (MO.isDef())
165 std::swap(CurRegBank, DesiredRegBrank);
Quentin Colombetcfbdee22016-06-08 01:11:03 +0000166 unsigned Cost =
167 RBI->copyCost(*DesiredRegBrank, *CurRegBank,
168 RegisterBankInfo::getSizeInBits(MO.getReg(), *MRI, *TRI));
Quentin Colombetf2723a22016-05-21 01:43:25 +0000169 // TODO: use a dedicated constant for ImpossibleCost.
170 if (Cost != UINT_MAX)
171 return Cost;
172 assert(false && "Legalization not available yet");
173 // Return the legalization cost of that repairing.
174 }
175 assert(false && "Complex repairing not implemented yet");
176 return 1;
177}
178
Quentin Colombet79fe1be2016-05-20 18:37:33 +0000179RegisterBankInfo::InstructionMapping &RegBankSelect::findBestMapping(
180 MachineInstr &MI, RegisterBankInfo::InstructionMappings &PossibleMappings,
181 SmallVectorImpl<RepairingPlacement> &RepairPts) {
182
183 RegisterBankInfo::InstructionMapping *BestMapping = nullptr;
184 MappingCost Cost = MappingCost::ImpossibleCost();
185 SmallVector<RepairingPlacement, 4> LocalRepairPts;
186 for (RegisterBankInfo::InstructionMapping &CurMapping : PossibleMappings) {
187 MappingCost CurCost = computeMapping(MI, CurMapping, LocalRepairPts, &Cost);
188 if (CurCost < Cost) {
189 Cost = CurCost;
190 BestMapping = &CurMapping;
191 RepairPts.clear();
192 for (RepairingPlacement &RepairPt : LocalRepairPts)
193 RepairPts.emplace_back(std::move(RepairPt));
194 }
195 }
196 assert(BestMapping && "No suitable mapping for instruction");
197 return *BestMapping;
198}
199
Quentin Colombetf75c2bf2016-05-20 16:36:12 +0000200void RegBankSelect::tryAvoidingSplit(
201 RegBankSelect::RepairingPlacement &RepairPt, const MachineOperand &MO,
202 const RegisterBankInfo::ValueMapping &ValMapping) const {
203 const MachineInstr &MI = *MO.getParent();
204 assert(RepairPt.hasSplit() && "We should not have to adjust for split");
205 // Splitting should only occur for PHIs or between terminators,
206 // because we only do local repairing.
207 assert((MI.isPHI() || MI.isTerminator()) && "Why do we split?");
208
209 assert(&MI.getOperand(RepairPt.getOpIdx()) == &MO &&
210 "Repairing placement does not match operand");
211
212 // If we need splitting for phis, that means it is because we
213 // could not find an insertion point before the terminators of
214 // the predecessor block for this argument. In other words,
215 // the input value is defined by one of the terminators.
216 assert((!MI.isPHI() || !MO.isDef()) && "Need split for phi def?");
217
218 // We split to repair the use of a phi or a terminator.
219 if (!MO.isDef()) {
220 if (MI.isTerminator()) {
221 assert(&MI != &(*MI.getParent()->getFirstTerminator()) &&
222 "Need to split for the first terminator?!");
223 } else {
224 // For the PHI case, the split may not be actually required.
225 // In the copy case, a phi is already a copy on the incoming edge,
226 // therefore there is no need to split.
227 if (ValMapping.BreakDown.size() == 1)
228 // This is a already a copy, there is nothing to do.
229 RepairPt.switchTo(RepairingPlacement::RepairingKind::Reassign);
230 }
231 return;
232 }
233
234 // At this point, we need to repair a defintion of a terminator.
235
236 // Technically we need to fix the def of MI on all outgoing
237 // edges of MI to keep the repairing local. In other words, we
238 // will create several definitions of the same register. This
239 // does not work for SSA unless that definition is a physical
240 // register.
241 // However, there are other cases where we can get away with
242 // that while still keeping the repairing local.
243 assert(MI.isTerminator() && MO.isDef() &&
244 "This code is for the def of a terminator");
245
246 // Since we use RPO traversal, if we need to repair a definition
247 // this means this definition could be:
248 // 1. Used by PHIs (i.e., this VReg has been visited as part of the
249 // uses of a phi.), or
250 // 2. Part of a target specific instruction (i.e., the target applied
251 // some register class constraints when creating the instruction.)
252 // If the constraints come for #2, the target said that another mapping
253 // is supported so we may just drop them. Indeed, if we do not change
254 // the number of registers holding that value, the uses will get fixed
255 // when we get to them.
256 // Uses in PHIs may have already been proceeded though.
257 // If the constraints come for #1, then, those are weak constraints and
258 // no actual uses may rely on them. However, the problem remains mainly
259 // the same as for #2. If the value stays in one register, we could
260 // just switch the register bank of the definition, but we would need to
261 // account for a repairing cost for each phi we silently change.
262 //
263 // In any case, if the value needs to be broken down into several
264 // registers, the repairing is not local anymore as we need to patch
265 // every uses to rebuild the value in just one register.
266 //
267 // To summarize:
268 // - If the value is in a physical register, we can do the split and
269 // fix locally.
270 // Otherwise if the value is in a virtual register:
271 // - If the value remains in one register, we do not have to split
272 // just switching the register bank would do, but we need to account
273 // in the repairing cost all the phi we changed.
274 // - If the value spans several registers, then we cannot do a local
275 // repairing.
276
277 // Check if this is a physical or virtual register.
278 unsigned Reg = MO.getReg();
279 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
280 // We are going to split every outgoing edges.
281 // Check that this is possible.
282 // FIXME: The machine representation is currently broken
283 // since it also several terminators in one basic block.
284 // Because of that we would technically need a way to get
285 // the targets of just one terminator to know which edges
286 // we have to split.
287 // Assert that we do not hit the ill-formed representation.
288
289 // If there are other terminators before that one, some of
290 // the outgoing edges may not be dominated by this definition.
291 assert(&MI == &(*MI.getParent()->getFirstTerminator()) &&
292 "Do not know which outgoing edges are relevant");
293 const MachineInstr *Next = MI.getNextNode();
294 assert((!Next || Next->isUnconditionalBranch()) &&
295 "Do not know where each terminator ends up");
296 if (Next)
297 // If the next terminator uses Reg, this means we have
298 // to split right after MI and thus we need a way to ask
299 // which outgoing edges are affected.
300 assert(!Next->readsRegister(Reg) && "Need to split between terminators");
301 // We will split all the edges and repair there.
302 } else {
303 // This is a virtual register defined by a terminator.
304 if (ValMapping.BreakDown.size() == 1) {
305 // There is nothing to repair, but we may actually lie on
306 // the repairing cost because of the PHIs already proceeded
307 // as already stated.
308 // Though the code will be correct.
309 assert(0 && "Repairing cost may not be accurate");
310 } else {
311 // We need to do non-local repairing. Basically, patch all
312 // the uses (i.e., phis) that we already proceeded.
313 // For now, just say this mapping is not possible.
314 RepairPt.switchTo(RepairingPlacement::RepairingKind::Impossible);
315 }
316 }
317}
318
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000319RegBankSelect::MappingCost RegBankSelect::computeMapping(
320 MachineInstr &MI, const RegisterBankInfo::InstructionMapping &InstrMapping,
Quentin Colombet6e80dbc2016-05-20 18:00:46 +0000321 SmallVectorImpl<RepairingPlacement> &RepairPts,
322 const RegBankSelect::MappingCost *BestCost) {
323 assert((MBFI || !BestCost) && "Costs comparison require MBFI");
Quentin Colombete16f5612016-04-07 23:53:55 +0000324
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000325 // If mapped with InstrMapping, MI will have the recorded cost.
Quentin Colombet25fcef72016-05-20 17:54:09 +0000326 MappingCost Cost(MBFI ? MBFI->getBlockFreq(MI.getParent()) : 1);
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000327 bool Saturated = Cost.addLocalCost(InstrMapping.getCost());
328 assert(!Saturated && "Possible mapping saturated the cost");
329 DEBUG(dbgs() << "Evaluating mapping cost for: " << MI);
330 DEBUG(dbgs() << "With: " << InstrMapping << '\n');
331 RepairPts.clear();
Quentin Colombet6e80dbc2016-05-20 18:00:46 +0000332 if (BestCost && Cost > *BestCost)
333 return Cost;
334
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000335 // Moreover, to realize this mapping, the register bank of each operand must
336 // match this mapping. In other words, we may need to locally reassign the
337 // register banks. Account for that repairing cost as well.
338 // In this context, local means in the surrounding of MI.
339 for (unsigned OpIdx = 0, EndOpIdx = MI.getNumOperands(); OpIdx != EndOpIdx;
Quentin Colombet40ad5732016-04-07 18:19:27 +0000340 ++OpIdx) {
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000341 const MachineOperand &MO = MI.getOperand(OpIdx);
Quentin Colombet40ad5732016-04-07 18:19:27 +0000342 if (!MO.isReg())
343 continue;
344 unsigned Reg = MO.getReg();
345 if (!Reg)
346 continue;
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000347 DEBUG(dbgs() << "Opd" << OpIdx);
Quentin Colombet40ad5732016-04-07 18:19:27 +0000348 const RegisterBankInfo::ValueMapping &ValMapping =
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000349 InstrMapping.getOperandMapping(OpIdx);
350 // If Reg is already properly mapped, this is free.
351 bool Assign;
352 if (assignmentMatch(Reg, ValMapping, Assign)) {
353 DEBUG(dbgs() << " is free (match).\n");
Quentin Colombet40ad5732016-04-07 18:19:27 +0000354 continue;
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000355 }
356 if (Assign) {
357 DEBUG(dbgs() << " is free (simple assignment).\n");
358 RepairPts.emplace_back(RepairingPlacement(MI, OpIdx, *TRI, *this,
359 RepairingPlacement::Reassign));
360 continue;
Quentin Colombet40ad5732016-04-07 18:19:27 +0000361 }
Quentin Colombet904a2c72016-04-12 00:12:59 +0000362
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000363 // Find the insertion point for the repairing code.
364 RepairPts.emplace_back(
365 RepairingPlacement(MI, OpIdx, *TRI, *this, RepairingPlacement::Insert));
366 RepairingPlacement &RepairPt = RepairPts.back();
367
Quentin Colombetf75c2bf2016-05-20 16:36:12 +0000368 // If we need to split a basic block to materialize this insertion point,
369 // we may give a higher cost to this mapping.
370 // Nevertheless, we may get away with the split, so try that first.
371 if (RepairPt.hasSplit())
372 tryAvoidingSplit(RepairPt, MO, ValMapping);
373
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000374 // Check that the materialization of the repairing is possible.
375 if (!RepairPt.canMaterialize())
376 return MappingCost::ImpossibleCost();
377
378 // Account for the split cost and repair cost.
Quentin Colombet6e80dbc2016-05-20 18:00:46 +0000379 // Unless the cost is already saturated or we do not care about the cost.
380 if (!BestCost || Saturated)
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000381 continue;
382
Quentin Colombet6e80dbc2016-05-20 18:00:46 +0000383 // To get accurate information we need MBFI and MBPI.
384 // Thus, if we end up here this information should be here.
385 assert(MBFI && MBPI && "Cost computation requires MBFI and MBPI");
386
Quentin Colombetf2723a22016-05-21 01:43:25 +0000387 // Sums up the repairing cost of MO at each insertion point.
388 uint64_t RepairCost = getRepairCost(MO, ValMapping);
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000389 // Bias used for splitting: 5%.
390 const uint64_t PercentageForBias = 5;
391 uint64_t Bias = (RepairCost * PercentageForBias + 99) / 100;
392 // We should not need more than a couple of instructions to repair
393 // an assignment. In other words, the computation should not
394 // overflow because the repairing cost is free of basic block
395 // frequency.
396 assert(((RepairCost < RepairCost * PercentageForBias) &&
397 (RepairCost * PercentageForBias <
398 RepairCost * PercentageForBias + 99)) &&
399 "Repairing involves more than a billion of instructions?!");
400 for (const std::unique_ptr<InsertPoint> &InsertPt : RepairPt) {
401 assert(InsertPt->canMaterialize() && "We should not have made it here");
402 // We will applied some basic block frequency and those uses uint64_t.
403 if (!InsertPt->isSplit())
404 Saturated = Cost.addLocalCost(RepairCost);
405 else {
406 uint64_t CostForInsertPt = RepairCost;
407 // Again we shouldn't overflow here givent that
408 // CostForInsertPt is frequency free at this point.
409 assert(CostForInsertPt + Bias > CostForInsertPt &&
410 "Repairing + split bias overflows");
411 CostForInsertPt += Bias;
412 uint64_t PtCost = InsertPt->frequency(*this) * CostForInsertPt;
413 // Check if we just overflowed.
414 if ((Saturated = PtCost < CostForInsertPt))
415 Cost.saturate();
416 else
417 Saturated = Cost.addNonLocalCost(PtCost);
418 }
Quentin Colombet6e80dbc2016-05-20 18:00:46 +0000419
420 // Stop looking into what it takes to repair, this is already
421 // too expensive.
422 if (BestCost && Cost > *BestCost)
423 return Cost;
424
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000425 // No need to accumulate more cost information.
426 // We need to still gather the repairing information though.
427 if (Saturated)
428 break;
429 }
Quentin Colombet40ad5732016-04-07 18:19:27 +0000430 }
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000431 return Cost;
432}
433
434void RegBankSelect::applyMapping(
435 MachineInstr &MI, const RegisterBankInfo::InstructionMapping &InstrMapping,
436 SmallVectorImpl<RegBankSelect::RepairingPlacement> &RepairPts) {
437 assert(InstrMapping.getID() == RegisterBankInfo::DefaultMappingID &&
438 "Rewriting of MI not implemented yet");
439 // First, place the repairing code.
440 bool NeedRewrite = false;
441 SmallVector<unsigned, 8> NewVRegs;
442 for (RepairingPlacement &RepairPt : RepairPts) {
443 assert(RepairPt.canMaterialize() &&
444 RepairPt.getKind() != RepairingPlacement::Impossible &&
445 "This mapping is impossible");
446 assert(RepairPt.getKind() != RepairingPlacement::None &&
447 "This should not make its way in the list");
448 unsigned OpIdx = RepairPt.getOpIdx();
449 MachineOperand &MO = MI.getOperand(OpIdx);
450 const RegisterBankInfo::ValueMapping &ValMapping =
451 InstrMapping.getOperandMapping(OpIdx);
452 unsigned BreakDownSize = ValMapping.BreakDown.size();
453 unsigned Reg = MO.getReg();
454 NeedRewrite = BreakDownSize != 1;
455
456 switch (RepairPt.getKind()) {
457 case RepairingPlacement::Reassign:
458 assert(BreakDownSize == 1 &&
459 "Reassignment should only be for simple mapping");
460 MRI->setRegBank(Reg, *ValMapping.BreakDown[0].RegBank);
461 break;
462 case RepairingPlacement::Insert:
463 // We need as many new virtual registers as the number of partial mapping.
464 for (const RegisterBankInfo::PartialMapping &PartMap :
465 ValMapping.BreakDown) {
466 unsigned Tmp = MRI->createGenericVirtualRegister(PartMap.Length);
467 MRI->setRegBank(Tmp, *PartMap.RegBank);
468 NewVRegs.push_back(Tmp);
469 }
470 repairReg(MO, ValMapping, RepairPt,
471 make_range(NewVRegs.end() - BreakDownSize, NewVRegs.end()));
472 break;
473 default:
474 llvm_unreachable("Other kind should not happen");
475 }
476 }
477 // Second, rewrite the instruction.
478 (void)NeedRewrite;
479 assert(!NeedRewrite && "Not implemented yet");
480}
481
482void RegBankSelect::assignInstr(MachineInstr &MI) {
483 DEBUG(dbgs() << "Assign: " << MI);
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000484 // Remember the repairing placement for all the operands.
485 SmallVector<RepairingPlacement, 4> RepairPts;
486
Quentin Colombet79fe1be2016-05-20 18:37:33 +0000487 RegisterBankInfo::InstructionMapping BestMapping;
488 if (OptMode == RegBankSelect::Mode::Fast) {
489 BestMapping = RBI->getInstrMapping(MI);
490 MappingCost DefaultCost = computeMapping(MI, BestMapping, RepairPts);
491 (void)DefaultCost;
492 assert(DefaultCost != MappingCost::ImpossibleCost() &&
493 "Default mapping is not suited");
494 } else {
495 RegisterBankInfo::InstructionMappings PossibleMappings =
496 RBI->getInstrPossibleMappings(MI);
497 assert(!PossibleMappings.empty() &&
498 "Do not know how to map this instruction");
499 BestMapping = std::move(findBestMapping(MI, PossibleMappings, RepairPts));
500 }
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000501 // Make sure the mapping is valid for MI.
Quentin Colombet79fe1be2016-05-20 18:37:33 +0000502 assert(BestMapping.verify(MI) && "Invalid instruction mapping");
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000503
Quentin Colombet79fe1be2016-05-20 18:37:33 +0000504 DEBUG(dbgs() << "Mapping: " << BestMapping << '\n');
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000505
Quentin Colombet79fe1be2016-05-20 18:37:33 +0000506 applyMapping(MI, BestMapping, RepairPts);
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000507
Quentin Colombete16f5612016-04-07 23:53:55 +0000508 DEBUG(dbgs() << "Assigned: " << MI);
Quentin Colombet40ad5732016-04-07 18:19:27 +0000509}
510
Quentin Colombet8e8e85c2016-04-05 19:06:01 +0000511bool RegBankSelect::runOnMachineFunction(MachineFunction &MF) {
Quentin Colombete16f5612016-04-07 23:53:55 +0000512 DEBUG(dbgs() << "Assign register banks for: " << MF.getName() << '\n');
Quentin Colombeta5530122016-05-20 17:36:54 +0000513 const Function *F = MF.getFunction();
514 Mode SaveOptMode = OptMode;
515 if (F->hasFnAttribute(Attribute::OptimizeNone))
516 OptMode = Mode::Fast;
Quentin Colombet40ad5732016-04-07 18:19:27 +0000517 init(MF);
518 // Walk the function and assign register banks to all operands.
Quentin Colombetab8c21f2016-04-08 17:19:10 +0000519 // Use a RPOT to make sure all registers are assigned before we choose
520 // the best mapping of the current instruction.
521 ReversePostOrderTraversal<MachineFunction*> RPOT(&MF);
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000522 for (MachineBasicBlock *MBB : RPOT) {
523 // Set a sensible insertion point so that subsequent calls to
524 // MIRBuilder.
525 MIRBuilder.setMBB(*MBB);
Quentin Colombetab8c21f2016-04-08 17:19:10 +0000526 for (MachineInstr &MI : *MBB)
Quentin Colombet40ad5732016-04-07 18:19:27 +0000527 assignInstr(MI);
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000528 }
Quentin Colombeta5530122016-05-20 17:36:54 +0000529 OptMode = SaveOptMode;
Quentin Colombet8e8e85c2016-04-05 19:06:01 +0000530 return false;
531}
Quentin Colombetcfd97b92016-05-20 00:35:26 +0000532
533//------------------------------------------------------------------------------
Quentin Colombet55650752016-05-20 00:49:10 +0000534// Helper Classes Implementation
Quentin Colombetcfd97b92016-05-20 00:35:26 +0000535//------------------------------------------------------------------------------
Quentin Colombet55650752016-05-20 00:49:10 +0000536RegBankSelect::RepairingPlacement::RepairingPlacement(
537 MachineInstr &MI, unsigned OpIdx, const TargetRegisterInfo &TRI, Pass &P,
538 RepairingPlacement::RepairingKind Kind)
539 // Default is, we are going to insert code to repair OpIdx.
540 : Kind(Kind),
541 OpIdx(OpIdx),
542 CanMaterialize(Kind != RepairingKind::Impossible),
543 HasSplit(false),
544 P(P) {
545 const MachineOperand &MO = MI.getOperand(OpIdx);
546 assert(MO.isReg() && "Trying to repair a non-reg operand");
547
548 if (Kind != RepairingKind::Insert)
549 return;
550
551 // Repairings for definitions happen after MI, uses happen before.
552 bool Before = !MO.isDef();
553
554 // Check if we are done with MI.
555 if (!MI.isPHI() && !MI.isTerminator()) {
556 addInsertPoint(MI, Before);
557 // We are done with the initialization.
558 return;
559 }
560
561 // Now, look for the special cases.
562 if (MI.isPHI()) {
563 // - PHI must be the first instructions:
564 // * Before, we have to split the related incoming edge.
565 // * After, move the insertion point past the last phi.
566 if (!Before) {
567 MachineBasicBlock::iterator It = MI.getParent()->getFirstNonPHI();
568 if (It != MI.getParent()->end())
569 addInsertPoint(*It, /*Before*/ true);
570 else
571 addInsertPoint(*(--It), /*Before*/ false);
572 return;
573 }
574 // We repair a use of a phi, we may need to split the related edge.
575 MachineBasicBlock &Pred = *MI.getOperand(OpIdx + 1).getMBB();
576 // Check if we can move the insertion point prior to the
577 // terminators of the predecessor.
578 unsigned Reg = MO.getReg();
579 MachineBasicBlock::iterator It = Pred.getLastNonDebugInstr();
580 for (auto Begin = Pred.begin(); It != Begin && It->isTerminator(); --It)
581 if (It->modifiesRegister(Reg, &TRI)) {
582 // We cannot hoist the repairing code in the predecessor.
583 // Split the edge.
584 addInsertPoint(Pred, *MI.getParent());
585 return;
586 }
587 // At this point, we can insert in Pred.
588
589 // - If It is invalid, Pred is empty and we can insert in Pred
590 // wherever we want.
591 // - If It is valid, It is the first non-terminator, insert after It.
592 if (It == Pred.end())
593 addInsertPoint(Pred, /*Beginning*/ false);
594 else
595 addInsertPoint(*It, /*Before*/ false);
596 } else {
597 // - Terminators must be the last instructions:
598 // * Before, move the insert point before the first terminator.
599 // * After, we have to split the outcoming edges.
600 unsigned Reg = MO.getReg();
601 if (Before) {
602 // Check whether Reg is defined by any terminator.
603 MachineBasicBlock::iterator It = MI;
604 for (auto Begin = MI.getParent()->begin();
605 --It != Begin && It->isTerminator();)
606 if (It->modifiesRegister(Reg, &TRI)) {
607 // Insert the repairing code right after the definition.
608 addInsertPoint(*It, /*Before*/ false);
609 return;
610 }
611 addInsertPoint(*It, /*Before*/ true);
612 return;
613 }
614 // Make sure Reg is not redefined by other terminators, otherwise
615 // we do not know how to split.
616 for (MachineBasicBlock::iterator It = MI, End = MI.getParent()->end();
617 ++It != End;)
618 // The machine verifier should reject this kind of code.
619 assert(It->modifiesRegister(Reg, &TRI) && "Do not know where to split");
620 // Split each outcoming edges.
621 MachineBasicBlock &Src = *MI.getParent();
622 for (auto &Succ : Src.successors())
623 addInsertPoint(Src, Succ);
624 }
625}
626
627void RegBankSelect::RepairingPlacement::addInsertPoint(MachineInstr &MI,
628 bool Before) {
629 addInsertPoint(*new InstrInsertPoint(MI, Before));
630}
631
632void RegBankSelect::RepairingPlacement::addInsertPoint(MachineBasicBlock &MBB,
633 bool Beginning) {
634 addInsertPoint(*new MBBInsertPoint(MBB, Beginning));
635}
636
637void RegBankSelect::RepairingPlacement::addInsertPoint(MachineBasicBlock &Src,
638 MachineBasicBlock &Dst) {
639 addInsertPoint(*new EdgeInsertPoint(Src, Dst, P));
640}
641
642void RegBankSelect::RepairingPlacement::addInsertPoint(
643 RegBankSelect::InsertPoint &Point) {
644 CanMaterialize &= Point.canMaterialize();
645 HasSplit |= Point.isSplit();
646 InsertPoints.emplace_back(&Point);
647}
648
649RegBankSelect::InstrInsertPoint::InstrInsertPoint(MachineInstr &Instr,
650 bool Before)
651 : InsertPoint(), Instr(Instr), Before(Before) {
652 // Since we do not support splitting, we do not need to update
653 // liveness and such, so do not do anything with P.
654 assert((!Before || !Instr.isPHI()) &&
655 "Splitting before phis requires more points");
656 assert((!Before || !Instr.getNextNode() || !Instr.getNextNode()->isPHI()) &&
657 "Splitting between phis does not make sense");
658}
659
660void RegBankSelect::InstrInsertPoint::materialize() {
661 if (isSplit()) {
662 // Slice and return the beginning of the new block.
663 // If we need to split between the terminators, we theoritically
664 // need to know where the first and second set of terminators end
665 // to update the successors properly.
666 // Now, in pratice, we should have a maximum of 2 branch
667 // instructions; one conditional and one unconditional. Therefore
668 // we know how to update the successor by looking at the target of
669 // the unconditional branch.
670 // If we end up splitting at some point, then, we should update
671 // the liveness information and such. I.e., we would need to
672 // access P here.
673 // The machine verifier should actually make sure such cases
674 // cannot happen.
675 llvm_unreachable("Not yet implemented");
676 }
677 // Otherwise the insertion point is just the current or next
678 // instruction depending on Before. I.e., there is nothing to do
679 // here.
680}
681
682bool RegBankSelect::InstrInsertPoint::isSplit() const {
683 // If the insertion point is after a terminator, we need to split.
684 if (!Before)
685 return Instr.isTerminator();
686 // If we insert before an instruction that is after a terminator,
687 // we are still after a terminator.
688 return Instr.getPrevNode() && Instr.getPrevNode()->isTerminator();
689}
690
691uint64_t RegBankSelect::InstrInsertPoint::frequency(const Pass &P) const {
692 // Even if we need to split, because we insert between terminators,
693 // this split has actually the same frequency as the instruction.
694 const MachineBlockFrequencyInfo *MBFI =
695 P.getAnalysisIfAvailable<MachineBlockFrequencyInfo>();
696 if (!MBFI)
697 return 1;
698 return MBFI->getBlockFreq(Instr.getParent()).getFrequency();
699}
700
701uint64_t RegBankSelect::MBBInsertPoint::frequency(const Pass &P) const {
702 const MachineBlockFrequencyInfo *MBFI =
703 P.getAnalysisIfAvailable<MachineBlockFrequencyInfo>();
704 if (!MBFI)
705 return 1;
706 return MBFI->getBlockFreq(&MBB).getFrequency();
707}
708
709void RegBankSelect::EdgeInsertPoint::materialize() {
710 // If we end up repairing twice at the same place before materializing the
711 // insertion point, we may think we have to split an edge twice.
712 // We should have a factory for the insert point such that identical points
713 // are the same instance.
714 assert(Src.isSuccessor(DstOrSplit) && DstOrSplit->isPredecessor(&Src) &&
715 "This point has already been split");
716 MachineBasicBlock *NewBB = Src.SplitCriticalEdge(DstOrSplit, P);
717 assert(NewBB && "Invalid call to materialize");
718 // We reuse the destination block to hold the information of the new block.
719 DstOrSplit = NewBB;
720}
721
722uint64_t RegBankSelect::EdgeInsertPoint::frequency(const Pass &P) const {
723 const MachineBlockFrequencyInfo *MBFI =
724 P.getAnalysisIfAvailable<MachineBlockFrequencyInfo>();
725 if (!MBFI)
726 return 1;
727 if (WasMaterialized)
728 return MBFI->getBlockFreq(DstOrSplit).getFrequency();
729
730 const MachineBranchProbabilityInfo *MBPI =
731 P.getAnalysisIfAvailable<MachineBranchProbabilityInfo>();
732 if (!MBPI)
733 return 1;
734 // The basic block will be on the edge.
735 return (MBFI->getBlockFreq(&Src) * MBPI->getEdgeProbability(&Src, DstOrSplit))
736 .getFrequency();
737}
738
739bool RegBankSelect::EdgeInsertPoint::canMaterialize() const {
740 // If this is not a critical edge, we should not have used this insert
741 // point. Indeed, either the successor or the predecessor should
742 // have do.
743 assert(Src.succ_size() > 1 && DstOrSplit->pred_size() > 1 &&
744 "Edge is not critical");
745 return Src.canSplitCriticalEdge(DstOrSplit);
746}
747
Quentin Colombetcfd97b92016-05-20 00:35:26 +0000748RegBankSelect::MappingCost::MappingCost(const BlockFrequency &LocalFreq)
749 : LocalCost(0), NonLocalCost(0), LocalFreq(LocalFreq.getFrequency()) {}
750
751bool RegBankSelect::MappingCost::addLocalCost(uint64_t Cost) {
752 // Check if this overflows.
753 if (LocalCost + Cost < LocalCost) {
754 saturate();
755 return true;
756 }
757 LocalCost += Cost;
758 return isSaturated();
759}
760
761bool RegBankSelect::MappingCost::addNonLocalCost(uint64_t Cost) {
762 // Check if this overflows.
763 if (NonLocalCost + Cost < NonLocalCost) {
764 saturate();
765 return true;
766 }
767 NonLocalCost += Cost;
768 return isSaturated();
769}
770
771bool RegBankSelect::MappingCost::isSaturated() const {
772 return LocalCost == UINT64_MAX - 1 && NonLocalCost == UINT64_MAX &&
773 LocalFreq == UINT64_MAX;
774}
775
776void RegBankSelect::MappingCost::saturate() {
777 *this = ImpossibleCost();
778 --LocalCost;
779}
780
781RegBankSelect::MappingCost RegBankSelect::MappingCost::ImpossibleCost() {
782 return MappingCost(UINT64_MAX, UINT64_MAX, UINT64_MAX);
783}
784
785bool RegBankSelect::MappingCost::operator<(const MappingCost &Cost) const {
786 // Sort out the easy cases.
787 if (*this == Cost)
788 return false;
789 // If one is impossible to realize the other is cheaper unless it is
790 // impossible as well.
791 if ((*this == ImpossibleCost()) || (Cost == ImpossibleCost()))
792 return (*this == ImpossibleCost()) < (Cost == ImpossibleCost());
793 // If one is saturated the other is cheaper, unless it is saturated
794 // as well.
795 if (isSaturated() || Cost.isSaturated())
796 return isSaturated() < Cost.isSaturated();
797 // At this point we know both costs hold sensible values.
798
799 // If both values have a different base frequency, there is no much
800 // we can do but to scale everything.
801 // However, if they have the same base frequency we can avoid making
802 // complicated computation.
803 uint64_t ThisLocalAdjust;
804 uint64_t OtherLocalAdjust;
805 if (LLVM_LIKELY(LocalFreq == Cost.LocalFreq)) {
806
807 // At this point, we know the local costs are comparable.
808 // Do the case that do not involve potential overflow first.
809 if (NonLocalCost == Cost.NonLocalCost)
810 // Since the non-local costs do not discriminate on the result,
811 // just compare the local costs.
812 return LocalCost < Cost.LocalCost;
813
814 // The base costs are comparable so we may only keep the relative
815 // value to increase our chances of avoiding overflows.
816 ThisLocalAdjust = 0;
817 OtherLocalAdjust = 0;
818 if (LocalCost < Cost.LocalCost)
819 OtherLocalAdjust = Cost.LocalCost - LocalCost;
820 else
821 ThisLocalAdjust = LocalCost - Cost.LocalCost;
822
823 } else {
824 ThisLocalAdjust = LocalCost;
825 OtherLocalAdjust = Cost.LocalCost;
826 }
827
828 // The non-local costs are comparable, just keep the relative value.
829 uint64_t ThisNonLocalAdjust = 0;
830 uint64_t OtherNonLocalAdjust = 0;
831 if (NonLocalCost < Cost.NonLocalCost)
832 OtherNonLocalAdjust = Cost.NonLocalCost - NonLocalCost;
833 else
834 ThisNonLocalAdjust = NonLocalCost - Cost.NonLocalCost;
835 // Scale everything to make them comparable.
836 uint64_t ThisScaledCost = ThisLocalAdjust * LocalFreq;
837 // Check for overflow on that operation.
838 bool ThisOverflows = ThisLocalAdjust && (ThisScaledCost < ThisLocalAdjust ||
839 ThisScaledCost < LocalFreq);
840 uint64_t OtherScaledCost = OtherLocalAdjust * Cost.LocalFreq;
841 // Check for overflow on the last operation.
842 bool OtherOverflows =
843 OtherLocalAdjust &&
844 (OtherScaledCost < OtherLocalAdjust || OtherScaledCost < Cost.LocalFreq);
845 // Add the non-local costs.
846 ThisOverflows |= ThisNonLocalAdjust &&
847 ThisScaledCost + ThisNonLocalAdjust < ThisNonLocalAdjust;
848 ThisScaledCost += ThisNonLocalAdjust;
849 OtherOverflows |= OtherNonLocalAdjust &&
850 OtherScaledCost + OtherNonLocalAdjust < OtherNonLocalAdjust;
851 OtherScaledCost += OtherNonLocalAdjust;
852 // If both overflows, we cannot compare without additional
853 // precision, e.g., APInt. Just give up on that case.
854 if (ThisOverflows && OtherOverflows)
855 return false;
856 // If one overflows but not the other, we can still compare.
857 if (ThisOverflows || OtherOverflows)
858 return ThisOverflows < OtherOverflows;
859 // Otherwise, just compare the values.
860 return ThisScaledCost < OtherScaledCost;
861}
862
863bool RegBankSelect::MappingCost::operator==(const MappingCost &Cost) const {
864 return LocalCost == Cost.LocalCost && NonLocalCost == Cost.NonLocalCost &&
865 LocalFreq == Cost.LocalFreq;
866}