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