blob: 76442ad278ab3f6f46f0f26b9da9395f83b82507 [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"
16#include "llvm/CodeGen/MachineRegisterInfo.h"
Quentin Colombetcfd97b92016-05-20 00:35:26 +000017#include "llvm/Support/BlockFrequency.h"
Quentin Colombete16f5612016-04-07 23:53:55 +000018#include "llvm/Support/Debug.h"
Quentin Colombet40ad5732016-04-07 18:19:27 +000019#include "llvm/Target/TargetSubtargetInfo.h"
Quentin Colombet8e8e85c2016-04-05 19:06:01 +000020
21#define DEBUG_TYPE "regbankselect"
22
23using namespace llvm;
24
25char RegBankSelect::ID = 0;
26INITIALIZE_PASS(RegBankSelect, "regbankselect",
27 "Assign register bank of generic virtual registers",
28 false, false);
29
Quentin Colombet40ad5732016-04-07 18:19:27 +000030RegBankSelect::RegBankSelect()
31 : MachineFunctionPass(ID), RBI(nullptr), MRI(nullptr) {
Quentin Colombet8e8e85c2016-04-05 19:06:01 +000032 initializeRegBankSelectPass(*PassRegistry::getPassRegistry());
33}
34
Quentin Colombet40ad5732016-04-07 18:19:27 +000035void RegBankSelect::init(MachineFunction &MF) {
36 RBI = MF.getSubtarget().getRegBankInfo();
37 assert(RBI && "Cannot work without RegisterBankInfo");
38 MRI = &MF.getRegInfo();
Quentin Colombetaac71a42016-04-07 21:32:23 +000039 TRI = MF.getSubtarget().getRegisterInfo();
Quentin Colombet40ad5732016-04-07 18:19:27 +000040 MIRBuilder.setMF(MF);
41}
42
43bool RegBankSelect::assignmentMatch(
Quentin Colombet0d77da42016-05-20 00:42:57 +000044 unsigned Reg, const RegisterBankInfo::ValueMapping &ValMapping,
45 bool &OnlyAssign) const {
46 // By default we assume we will have to repair something.
47 OnlyAssign = false;
Quentin Colombet40ad5732016-04-07 18:19:27 +000048 // Each part of a break down needs to end up in a different register.
49 // In other word, Reg assignement does not match.
50 if (ValMapping.BreakDown.size() > 1)
51 return false;
52
Quentin Colombet6d6d6af2016-04-08 16:48:16 +000053 const RegisterBank *CurRegBank = RBI->getRegBank(Reg, *MRI, *TRI);
54 const RegisterBank *DesiredRegBrank = ValMapping.BreakDown[0].RegBank;
Quentin Colombet0d77da42016-05-20 00:42:57 +000055 // Reg is free of assignment, a simple assignment will make the
56 // register bank to match.
57 OnlyAssign = CurRegBank == nullptr;
Quentin Colombet6d6d6af2016-04-08 16:48:16 +000058 DEBUG(dbgs() << "Does assignment already match: ";
59 if (CurRegBank) dbgs() << *CurRegBank; else dbgs() << "none";
60 dbgs() << " against ";
61 assert(DesiredRegBrank && "The mapping must be valid");
62 dbgs() << *DesiredRegBrank << '\n';);
63 return CurRegBank == DesiredRegBrank;
Quentin Colombet40ad5732016-04-07 18:19:27 +000064}
65
66unsigned
67RegBankSelect::repairReg(unsigned Reg,
Quentin Colombet904a2c72016-04-12 00:12:59 +000068 const RegisterBankInfo::ValueMapping &ValMapping,
69 MachineInstr &DefUseMI, bool IsDef) {
Quentin Colombet40ad5732016-04-07 18:19:27 +000070 assert(ValMapping.BreakDown.size() == 1 &&
71 "Support for complex break down not supported yet");
72 const RegisterBankInfo::PartialMapping &PartialMap = ValMapping.BreakDown[0];
Quentin Colombet0e5ff582016-04-21 18:09:34 +000073 assert(PartialMap.Length ==
Quentin Colombet777a7712016-04-12 00:38:51 +000074 (TargetRegisterInfo::isPhysicalRegister(Reg)
75 ? TRI->getMinimalPhysRegClass(Reg)->getSize() * 8
76 : MRI->getSize(Reg)) &&
Quentin Colombet40ad5732016-04-07 18:19:27 +000077 "Repairing other than copy not implemented yet");
Quentin Colombet904a2c72016-04-12 00:12:59 +000078 // If the MIRBuilder is configured to insert somewhere else than
79 // DefUseMI, we may not use this function like was it first
80 // internded (local repairing), so make sure we pay attention before
81 // we remove the assert.
82 // In particular, it is likely that we will have to properly save
83 // the insertion point of the MIRBuilder and restore it at the end
84 // of this method.
85 assert(&DefUseMI == &(*MIRBuilder.getInsertPt()) &&
86 "Need to save and restore the insertion point");
87 // For use, we will add a copy just in front of the instruction.
88 // For def, we will add a copy just after the instruction.
89 // In either case, the insertion point must be valid. In particular,
90 // make sure we do not insert in the middle of terminators or phis.
91 bool Before = !IsDef;
92 setSafeInsertionPoint(DefUseMI, Before);
93 if (DefUseMI.isTerminator() && Before) {
94 // Check that the insertion point does not happen
95 // before the definition of Reg.
96 // This can happen if Reg is defined by a terminator
97 // and used by another one.
98 // In that case the repairing code is actually more involved
99 // because we have to split the block.
100
101 // Assert that this is not a physical register.
102 // The target independent code does not insert physical registers
103 // on terminators, so if we end up in this situation, this is
104 // likely a bug in the target.
105 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) &&
106 "Check for physical register not implemented");
107 const MachineInstr *RegDef = MRI->getVRegDef(Reg);
108 assert(RegDef && "Reg has more than one definition?");
109 // Assert to make the code more readable; Reg is used by DefUseMI, i.e.,
110 // (Before == !IsDef == true), so DefUseMI != RegDef otherwise we have
111 // a use (that is not a PHI) that is not dominated by its def.
112 assert(&DefUseMI != RegDef && "Def does not dominate all of its uses");
113 if (RegDef->isTerminator() && RegDef->getParent() == DefUseMI.getParent())
114 // By construction, the repairing should happen between two
115 // terminators: RegDef and DefUseMI.
116 // This is not implemented.
117 report_fatal_error("Repairing between terminators not implemented yet");
118 }
119
120 // Create a new temporary to hold the repaired value.
Quentin Colombet0e5ff582016-04-21 18:09:34 +0000121 unsigned NewReg = MRI->createGenericVirtualRegister(PartialMap.Length);
Quentin Colombet904a2c72016-04-12 00:12:59 +0000122 // Set the registers for the source and destination of the copy.
123 unsigned Src = Reg, Dst = NewReg;
124 // If this is a definition that we repair, the copy will be
125 // inverted.
126 if (IsDef)
127 std::swap(Src, Dst);
128 (void)MIRBuilder.buildInstr(TargetOpcode::COPY, Dst, Src);
129
Quentin Colombete16f5612016-04-07 23:53:55 +0000130 DEBUG(dbgs() << "Repair: " << PrintReg(Reg) << " with: "
131 << PrintReg(NewReg) << '\n');
Quentin Colombet904a2c72016-04-12 00:12:59 +0000132
133 // Restore the insertion point of the MIRBuilder.
134 MIRBuilder.setInstr(DefUseMI, Before);
Quentin Colombet40ad5732016-04-07 18:19:27 +0000135 return NewReg;
136}
137
Quentin Colombet904a2c72016-04-12 00:12:59 +0000138void RegBankSelect::setSafeInsertionPoint(MachineInstr &InsertPt, bool Before) {
139 // Check that we are not looking to insert before a phi.
140 // Indeed, we would need more information on what to do.
141 // By default that should be all the predecessors, but this is
142 // probably not what we want in general.
143 assert((!Before || !InsertPt.isPHI()) &&
144 "Insertion before phis not implemented");
145 // The same kind of observation hold for terminators if we try to
146 // insert after them.
147 assert((Before || !InsertPt.isTerminator()) &&
148 "Insertion after terminatos not implemented");
149 if (InsertPt.isPHI()) {
150 assert(!Before && "Not supported!!");
151 MachineBasicBlock *MBB = InsertPt.getParent();
152 assert(MBB && "Insertion point is not in a basic block");
153 MachineBasicBlock::iterator FirstNonPHIPt = MBB->getFirstNonPHI();
154 if (FirstNonPHIPt == MBB->end()) {
155 // If there is not any non-phi instruction, insert at the end of MBB.
156 MIRBuilder.setMBB(*MBB, /*Beginning*/ false);
157 return;
158 }
159 // The insertion point before the first non-phi instruction.
160 MIRBuilder.setInstr(*FirstNonPHIPt, /*Before*/ true);
161 return;
162 }
163 if (InsertPt.isTerminator()) {
164 MachineBasicBlock *MBB = InsertPt.getParent();
165 assert(MBB && "Insertion point is not in a basic block");
166 MIRBuilder.setInstr(*MBB->getFirstTerminator(), /*Before*/ true);
167 return;
168 }
169 MIRBuilder.setInstr(InsertPt, /*Before*/ Before);
170}
171
Quentin Colombet40ad5732016-04-07 18:19:27 +0000172void RegBankSelect::assignInstr(MachineInstr &MI) {
Quentin Colombete16f5612016-04-07 23:53:55 +0000173 DEBUG(dbgs() << "Assign: " << MI);
Quentin Colombet40ad5732016-04-07 18:19:27 +0000174 const RegisterBankInfo::InstructionMapping DefaultMapping =
175 RBI->getInstrMapping(MI);
176 // Make sure the mapping is valid for MI.
Quentin Colombetc320fb42016-04-21 18:34:43 +0000177 assert(DefaultMapping.verify(MI) && "Invalid instruction mapping");
Quentin Colombete16f5612016-04-07 23:53:55 +0000178
179 DEBUG(dbgs() << "Mapping: " << DefaultMapping << '\n');
180
Quentin Colombet40ad5732016-04-07 18:19:27 +0000181 // Set the insertion point before MI.
182 // This is where we are going to insert the repairing code if any.
183 MIRBuilder.setInstr(MI, /*Before*/ true);
184
185 // For now, do not look for alternative mappings.
186 // Alternative mapping may require to rewrite MI and we do not support
187 // that yet.
188 // Walk the operands and assign then to the chosen mapping, possibly with
189 // the insertion of repair code for uses.
190 for (unsigned OpIdx = 0, EndIdx = MI.getNumOperands(); OpIdx != EndIdx;
191 ++OpIdx) {
192 MachineOperand &MO = MI.getOperand(OpIdx);
193 // Nothing to be done for non-register operands.
194 if (!MO.isReg())
195 continue;
196 unsigned Reg = MO.getReg();
197 if (!Reg)
198 continue;
199
200 const RegisterBankInfo::ValueMapping &ValMapping =
201 DefaultMapping.getOperandMapping(OpIdx);
202 // If Reg is already properly mapped, move on.
Quentin Colombet0d77da42016-05-20 00:42:57 +0000203 bool OnlyAssign;
204 if (assignmentMatch(Reg, ValMapping, OnlyAssign))
Quentin Colombet40ad5732016-04-07 18:19:27 +0000205 continue;
206
207 // For uses, we may need to create a new temporary.
208 // Indeed, if Reg is already assigned a register bank, at this
209 // point, we know it is different from the one defined by the
210 // chosen mapping, we need to adjust for that.
Quentin Colombet904a2c72016-04-12 00:12:59 +0000211 // For definitions, changing the register bank will affect all
212 // its uses, and in particular the ones we already visited.
213 // Although this is correct, since with the RPO traversal of the
214 // basic blocks the only uses that we already visisted for this
215 // definition are PHIs (i.e., copies), this may not be the best
216 // solution according to the cost model.
217 // Therefore, create a new temporary for Reg.
Quentin Colombet40ad5732016-04-07 18:19:27 +0000218 assert(ValMapping.BreakDown.size() == 1 &&
219 "Support for complex break down not supported yet");
Quentin Colombet0d77da42016-05-20 00:42:57 +0000220 if (!OnlyAssign) {
Quentin Colombet904a2c72016-04-12 00:12:59 +0000221 if (!MO.isDef() && MI.isPHI()) {
222 // Phis are already copies, so there is nothing to repair.
223 // Note: This will not hold when we support break downs with
224 // more than one segment.
225 DEBUG(dbgs() << "Skip PHI use\n");
226 continue;
227 }
228 // If MO is a definition, since repairing after a terminator is
229 // painful, do not repair. Indeed, this is probably not worse
230 // saving the move in the PHIs that will get reassigned.
231 if (!MO.isDef() || !MI.isTerminator())
232 Reg = repairReg(Reg, ValMapping, MI, MO.isDef());
Quentin Colombet40ad5732016-04-07 18:19:27 +0000233 }
Quentin Colombet904a2c72016-04-12 00:12:59 +0000234
Quentin Colombet40ad5732016-04-07 18:19:27 +0000235 // If we end up here, MO should be free of encoding constraints,
236 // i.e., we do not have to constrained the RegBank of Reg to
237 // the requirement of the operands.
238 // If that is not the case, this means the code was broken before
239 // hands because we should have found that the assignment match.
240 // This will not hold when we will consider alternative mappings.
Quentin Colombet6d6d6af2016-04-08 16:48:16 +0000241 DEBUG(dbgs() << "Assign: " << *ValMapping.BreakDown[0].RegBank << " to "
242 << PrintReg(Reg) << '\n');
Quentin Colombet904a2c72016-04-12 00:12:59 +0000243
Quentin Colombet40ad5732016-04-07 18:19:27 +0000244 MRI->setRegBank(Reg, *ValMapping.BreakDown[0].RegBank);
245 MO.setReg(Reg);
246 }
Quentin Colombete16f5612016-04-07 23:53:55 +0000247 DEBUG(dbgs() << "Assigned: " << MI);
Quentin Colombet40ad5732016-04-07 18:19:27 +0000248}
249
Quentin Colombet8e8e85c2016-04-05 19:06:01 +0000250bool RegBankSelect::runOnMachineFunction(MachineFunction &MF) {
Quentin Colombete16f5612016-04-07 23:53:55 +0000251 DEBUG(dbgs() << "Assign register banks for: " << MF.getName() << '\n');
Quentin Colombet40ad5732016-04-07 18:19:27 +0000252 init(MF);
253 // Walk the function and assign register banks to all operands.
Quentin Colombetab8c21f2016-04-08 17:19:10 +0000254 // Use a RPOT to make sure all registers are assigned before we choose
255 // the best mapping of the current instruction.
256 ReversePostOrderTraversal<MachineFunction*> RPOT(&MF);
257 for (MachineBasicBlock *MBB : RPOT)
258 for (MachineInstr &MI : *MBB)
Quentin Colombet40ad5732016-04-07 18:19:27 +0000259 assignInstr(MI);
Quentin Colombet8e8e85c2016-04-05 19:06:01 +0000260 return false;
261}
Quentin Colombetcfd97b92016-05-20 00:35:26 +0000262
263//------------------------------------------------------------------------------
264// Helper Class Implementation
265//------------------------------------------------------------------------------
266RegBankSelect::MappingCost::MappingCost(const BlockFrequency &LocalFreq)
267 : LocalCost(0), NonLocalCost(0), LocalFreq(LocalFreq.getFrequency()) {}
268
269bool RegBankSelect::MappingCost::addLocalCost(uint64_t Cost) {
270 // Check if this overflows.
271 if (LocalCost + Cost < LocalCost) {
272 saturate();
273 return true;
274 }
275 LocalCost += Cost;
276 return isSaturated();
277}
278
279bool RegBankSelect::MappingCost::addNonLocalCost(uint64_t Cost) {
280 // Check if this overflows.
281 if (NonLocalCost + Cost < NonLocalCost) {
282 saturate();
283 return true;
284 }
285 NonLocalCost += Cost;
286 return isSaturated();
287}
288
289bool RegBankSelect::MappingCost::isSaturated() const {
290 return LocalCost == UINT64_MAX - 1 && NonLocalCost == UINT64_MAX &&
291 LocalFreq == UINT64_MAX;
292}
293
294void RegBankSelect::MappingCost::saturate() {
295 *this = ImpossibleCost();
296 --LocalCost;
297}
298
299RegBankSelect::MappingCost RegBankSelect::MappingCost::ImpossibleCost() {
300 return MappingCost(UINT64_MAX, UINT64_MAX, UINT64_MAX);
301}
302
303bool RegBankSelect::MappingCost::operator<(const MappingCost &Cost) const {
304 // Sort out the easy cases.
305 if (*this == Cost)
306 return false;
307 // If one is impossible to realize the other is cheaper unless it is
308 // impossible as well.
309 if ((*this == ImpossibleCost()) || (Cost == ImpossibleCost()))
310 return (*this == ImpossibleCost()) < (Cost == ImpossibleCost());
311 // If one is saturated the other is cheaper, unless it is saturated
312 // as well.
313 if (isSaturated() || Cost.isSaturated())
314 return isSaturated() < Cost.isSaturated();
315 // At this point we know both costs hold sensible values.
316
317 // If both values have a different base frequency, there is no much
318 // we can do but to scale everything.
319 // However, if they have the same base frequency we can avoid making
320 // complicated computation.
321 uint64_t ThisLocalAdjust;
322 uint64_t OtherLocalAdjust;
323 if (LLVM_LIKELY(LocalFreq == Cost.LocalFreq)) {
324
325 // At this point, we know the local costs are comparable.
326 // Do the case that do not involve potential overflow first.
327 if (NonLocalCost == Cost.NonLocalCost)
328 // Since the non-local costs do not discriminate on the result,
329 // just compare the local costs.
330 return LocalCost < Cost.LocalCost;
331
332 // The base costs are comparable so we may only keep the relative
333 // value to increase our chances of avoiding overflows.
334 ThisLocalAdjust = 0;
335 OtherLocalAdjust = 0;
336 if (LocalCost < Cost.LocalCost)
337 OtherLocalAdjust = Cost.LocalCost - LocalCost;
338 else
339 ThisLocalAdjust = LocalCost - Cost.LocalCost;
340
341 } else {
342 ThisLocalAdjust = LocalCost;
343 OtherLocalAdjust = Cost.LocalCost;
344 }
345
346 // The non-local costs are comparable, just keep the relative value.
347 uint64_t ThisNonLocalAdjust = 0;
348 uint64_t OtherNonLocalAdjust = 0;
349 if (NonLocalCost < Cost.NonLocalCost)
350 OtherNonLocalAdjust = Cost.NonLocalCost - NonLocalCost;
351 else
352 ThisNonLocalAdjust = NonLocalCost - Cost.NonLocalCost;
353 // Scale everything to make them comparable.
354 uint64_t ThisScaledCost = ThisLocalAdjust * LocalFreq;
355 // Check for overflow on that operation.
356 bool ThisOverflows = ThisLocalAdjust && (ThisScaledCost < ThisLocalAdjust ||
357 ThisScaledCost < LocalFreq);
358 uint64_t OtherScaledCost = OtherLocalAdjust * Cost.LocalFreq;
359 // Check for overflow on the last operation.
360 bool OtherOverflows =
361 OtherLocalAdjust &&
362 (OtherScaledCost < OtherLocalAdjust || OtherScaledCost < Cost.LocalFreq);
363 // Add the non-local costs.
364 ThisOverflows |= ThisNonLocalAdjust &&
365 ThisScaledCost + ThisNonLocalAdjust < ThisNonLocalAdjust;
366 ThisScaledCost += ThisNonLocalAdjust;
367 OtherOverflows |= OtherNonLocalAdjust &&
368 OtherScaledCost + OtherNonLocalAdjust < OtherNonLocalAdjust;
369 OtherScaledCost += OtherNonLocalAdjust;
370 // If both overflows, we cannot compare without additional
371 // precision, e.g., APInt. Just give up on that case.
372 if (ThisOverflows && OtherOverflows)
373 return false;
374 // If one overflows but not the other, we can still compare.
375 if (ThisOverflows || OtherOverflows)
376 return ThisOverflows < OtherOverflows;
377 // Otherwise, just compare the values.
378 return ThisScaledCost < OtherScaledCost;
379}
380
381bool RegBankSelect::MappingCost::operator==(const MappingCost &Cost) const {
382 return LocalCost == Cost.LocalCost && NonLocalCost == Cost.NonLocalCost &&
383 LocalFreq == Cost.LocalFreq;
384}